Debian Codegraph @

js/src/wasm/WasmCompile.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2015 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "wasm/WasmCompile.h"
20
21 #include "mozilla/Maybe.h"
22
23 #include <algorithm>
24
25 #include "js/Conversions.h"
26 #include "js/Equality.h"
27 #include "js/ForOfIterator.h"
28 #include "js/PropertyAndElement.h"
29
30 #ifndef __wasi__
31 # include "jit/ProcessExecutableMemory.h"
32 #endif
33
34 #include "jit/FlushICache.h"
35 #include "jit/JitOptions.h"
36 #include "util/Text.h"
37 #include "vm/HelperThreads.h"
38 #include "vm/JSAtomState.h"
39 #include "vm/Realm.h"
40 #include "wasm/WasmBaselineCompile.h"
41 #include "wasm/WasmFeatures.h"
42 #include "wasm/WasmGenerator.h"
43 #include "wasm/WasmIonCompile.h"
44 #include "wasm/WasmOpIter.h"
45 #include "wasm/WasmProcess.h"
46 #include "wasm/WasmSignalHandlers.h"
47 #include "wasm/WasmValidate.h"
48
49 using namespace js;
50 using namespace js::jit;
51 using namespace js::wasm;
52
53 using mozilla::Atomic;
54
55 uint32_t wasm::ObservedCPUFeatures() {
56 enum Arch {
57 X86 = 0x1,
58 X64 = 0x2,
59 ARM = 0x3,
60 MIPS = 0x4,
61 MIPS64 = 0x5,
62 ARM64 = 0x6,
63 LOONG64 = 0x7,
64 RISCV64 = 0x8,
65 ARCH_BITS = 3
66 };
67
68 #if defined(JS_CODEGEN_X86)
69 MOZ_ASSERT(uint32_t(jit::CPUInfo::GetFingerprint()) <=
70 (UINT32_MAX >> ARCH_BITS));
71 return X86 | (uint32_t(jit::CPUInfo::GetFingerprint()) << ARCH_BITS);
72 #elif defined(JS_CODEGEN_X64)
73 MOZ_ASSERT(uint32_t(jit::CPUInfo::GetFingerprint()) <=
74 (UINT32_MAX >> ARCH_BITS));
75 return X64 | (uint32_t(jit::CPUInfo::GetFingerprint()) << ARCH_BITS);
76 #elif defined(JS_CODEGEN_ARM)
77 MOZ_ASSERT(jit::GetARMFlags() <= (UINT32_MAX >> ARCH_BITS));
78 return ARM | (jit::GetARMFlags() << ARCH_BITS);
79 #elif defined(JS_CODEGEN_ARM64)
80 MOZ_ASSERT(jit::GetARM64Flags() <= (UINT32_MAX >> ARCH_BITS));
81 return ARM64 | (jit::GetARM64Flags() << ARCH_BITS);
82 #elif defined(JS_CODEGEN_MIPS64)
83 MOZ_ASSERT(jit::GetMIPSFlags() <= (UINT32_MAX >> ARCH_BITS));
84 return MIPS64 | (jit::GetMIPSFlags() << ARCH_BITS);
85 #elif defined(JS_CODEGEN_LOONG64)
86 MOZ_ASSERT(jit::GetLOONG64Flags() <= (UINT32_MAX >> ARCH_BITS));
87 return LOONG64 | (jit::GetLOONG64Flags() << ARCH_BITS);
88 #elif defined(JS_CODEGEN_RISCV64)
89 MOZ_ASSERT(jit::GetRISCV64Flags() <= (UINT32_MAX >> ARCH_BITS));
90 return RISCV64 | (jit::GetRISCV64Flags() << ARCH_BITS);
91 #elif defined(JS_CODEGEN_NONE) || defined(JS_CODEGEN_WASM32)
92 return 0;
93 #else
94 # error "unknown architecture"
95 #endif
96 }
97
98 bool FeatureOptions::init(JSContext* cx, HandleValue val) {
99 if (val.isNullOrUndefined()) {
100 return true;
101 }
102
103 bool jsStringBuiltinsAvailable = false;
104 #ifdef ENABLE_WASM_JS_STRING_BUILTINS
105 jsStringBuiltinsAvailable = JSStringBuiltinsAvailable(cx);
106 #endif // ENABLE_WASM_JS_STRING_BUILTINS
107 bool isPrivilegedContext = IsPrivilegedContext(cx);
108
109 if (!jsStringBuiltinsAvailable && !isPrivilegedContext) {
110 // Skip checking for a compile options object if we don't have a feature
111 // enabled yet that requires it. Once js-string-builtins is standardized
112 // and shipped we will always need to check for it.
113 MOZ_ASSERT(!this->disableOptimizingCompiler);
114 MOZ_ASSERT(!this->jsStringConstants);
115 MOZ_ASSERT(!this->jsStringBuiltins);
116 return true;
117 }
118
119 if (!val.isObject()) {
120 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
121 JSMSG_WASM_BAD_COMPILE_OPTIONS);
122 return false;
123 }
124 RootedObject obj(cx, &val.toObject());
125
126 if (isPrivilegedContext) {
127 RootedValue disableOptimizingCompiler(cx);
128 if (!JS_GetProperty(cx, obj, "disableOptimizingCompiler",
129 &disableOptimizingCompiler)) {
130 return false;
131 }
132
133 this->disableOptimizingCompiler = JS::ToBoolean(disableOptimizingCompiler);
134 } else {
135 MOZ_ASSERT(!this->disableOptimizingCompiler);
136 }
137
138 #ifdef ENABLE_WASM_JS_STRING_BUILTINS
139 if (jsStringBuiltinsAvailable) {
140 // Check the 'importedStringConstants' option
141 RootedValue importedStringConstants(cx);
142 if (!JS_GetProperty(cx, obj, "importedStringConstants",
143 &importedStringConstants)) {
144 return false;
145 }
146
147 if (importedStringConstants.isNullOrUndefined()) {
148 this->jsStringConstants = false;
149 } else {
150 this->jsStringConstants = true;
151
152 RootedString importedStringConstantsString(
153 cx, JS::ToString(cx, importedStringConstants));
154 if (!importedStringConstantsString) {
155 return false;
156 }
157
158 UniqueChars jsStringConstantsNamespace =
159 StringToNewUTF8CharsZ(cx, *importedStringConstantsString);
160 if (!jsStringConstantsNamespace) {
161 return false;
162 }
163
164 this->jsStringConstantsNamespace =
165 js_new<ShareableChars>(std::move(jsStringConstantsNamespace));
166 if (!this->jsStringConstantsNamespace) {
167 return false;
168 }
169 }
170
171 // Get the `builtins` iterable
172 RootedValue builtins(cx);
173 if (!JS_GetProperty(cx, obj, "builtins", &builtins)) {
174 return false;
175 }
176
177 if (!builtins.isUndefined()) {
178 JS::ForOfIterator iterator(cx);
179
180 if (!iterator.init(builtins, JS::ForOfIterator::ThrowOnNonIterable)) {
181 return false;
182 }
183
184 RootedValue jsStringModule(cx, StringValue(cx->names().jsStringModule));
185 RootedValue nextBuiltin(cx);
186 while (true) {
187 bool done;
188 if (!iterator.next(&nextBuiltin, &done)) {
189 return false;
190 }
191 if (done) {
192 break;
193 }
194
195 bool jsStringBuiltins;
196 if (!JS::LooselyEqual(cx, nextBuiltin, jsStringModule,
197 &jsStringBuiltins)) {
198 return false;
199 }
200
201 // We ignore unknown builtins
202 if (!jsStringBuiltins) {
203 continue;
204 }
205
206 // You cannot request the same builtin twice
207 if (this->jsStringBuiltins && jsStringBuiltins) {
208 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
209 JSMSG_WASM_DUPLICATE_BUILTIN);
210 return false;
211 }
212 this->jsStringBuiltins = jsStringBuiltins;
213 }
214 }
215 }
216 #endif
217
218 return true;
219 }
220
221 FeatureArgs FeatureArgs::build(JSContext* cx, const FeatureOptions& options) {
222 FeatureArgs features;
223
224 #define WASM_FEATURE(NAME, LOWER_NAME, ...) \
225 features.LOWER_NAME = wasm::NAME##Available(cx);
226 JS_FOR_WASM_FEATURES(WASM_FEATURE);
227 #undef WASM_FEATURE
228
229 features.sharedMemory =
230 wasm::ThreadsAvailable(cx) ? Shareable::True : Shareable::False;
231
232 features.simd = jit::JitSupportsWasmSimd();
233 features.isBuiltinModule = options.isBuiltinModule;
234 if (features.jsStringBuiltins) {
235 features.builtinModules.jsString = options.jsStringBuiltins;
236 features.builtinModules.jsStringConstants = options.jsStringConstants;
237 features.builtinModules.jsStringConstantsNamespace =
238 options.jsStringConstantsNamespace;
239 }
240 if (options.requireExnref) {
241 features.exnref = true;
242 }
243
244 return features;
245 }
246
247 SharedCompileArgs CompileArgs::build(JSContext* cx,
248 ScriptedCaller&& scriptedCaller,
249 const FeatureOptions& options,
250 CompileArgsError* error) {
251 bool baseline = BaselineAvailable(cx);
252 bool ion = IonAvailable(cx);
253
254 // If the user requested to disable ion and we're able to, fallback to
255 // baseline.
256 if (baseline && options.disableOptimizingCompiler) {
257 ion = false;
258 }
259
260 // Debug information such as source view or debug traps will require
261 // additional memory and permanently stay in baseline code, so we try to
262 // only enable it when a developer actually cares: when the debugger tab
263 // is open.
264 bool debug = cx->realm() && cx->realm()->debuggerObservesWasm();
265
266 bool forceTiering =
267 cx->options().testWasmAwaitTier2() || JitOptions.wasmDelayTier2;
268
269 // The <Compiler>Available() predicates should ensure no failure here, but
270 // when we're fuzzing we allow inconsistent switches and the check may thus
271 // fail. Let it go to a run-time error instead of crashing.
272 if (debug && ion) {
273 *error = CompileArgsError::NoCompiler;
274 return nullptr;
275 }
276
277 if (forceTiering && !(baseline && ion)) {
278 // This can happen only in testing, and in this case we don't have a
279 // proper way to signal the error, so just silently override the default,
280 // instead of adding a skip-if directive to every test using debug/gc.
281 forceTiering = false;
282 }
283
284 if (!(baseline || ion)) {
285 *error = CompileArgsError::NoCompiler;
286 return nullptr;
287 }
288
289 CompileArgs* target = cx->new_<CompileArgs>();
290 if (!target) {
291 *error = CompileArgsError::OutOfMemory;
292 return nullptr;
293 }
294
295 target->scriptedCaller = std::move(scriptedCaller);
296 target->baselineEnabled = baseline;
297 target->ionEnabled = ion;
298 target->debugEnabled = debug;
299 target->forceTiering = forceTiering;
300 target->features = FeatureArgs::build(cx, options);
301
302 return target;
303 }
304
305 void wasm::SetUseCountersForFeatureUsage(JSContext* cx, JSObject* object,
306 FeatureUsage usage) {
307 if (usage & FeatureUsage::LegacyExceptions) {
308 cx->runtime()->setUseCounter(object, JSUseCounter::WASM_LEGACY_EXCEPTIONS);
309 }
310 }
311
312 SharedCompileArgs CompileArgs::buildForAsmJS(ScriptedCaller&& scriptedCaller) {
313 CompileArgs* target = js_new<CompileArgs>();
314 if (!target) {
315 return nullptr;
316 }
317
318 target->scriptedCaller = std::move(scriptedCaller);
319 // AsmJS is deprecated and doesn't have mechanisms for experimental features,
320 // so we don't need to initialize the FeatureArgs. It also only targets the
321 // Ion backend and does not need WASM debug support since it is de-optimized
322 // to JS in that case.
323 target->ionEnabled = true;
324 target->debugEnabled = false;
325
326 return target;
327 }
328
329 SharedCompileArgs CompileArgs::buildForValidation(const FeatureArgs& args) {
330 CompileArgs* target = js_new<CompileArgs>();
331 if (!target) {
332 return nullptr;
333 }
334
335 // Validation will not need compilers, just mark them disabled
336 target->baselineEnabled = false;
337 target->ionEnabled = false;
338 target->debugEnabled = false;
339 target->forceTiering = false;
340
341 // Set the features
342 target->features = args;
343
344 return target;
345 }
346
347 SharedCompileArgs CompileArgs::buildAndReport(JSContext* cx,
348 ScriptedCaller&& scriptedCaller,
349 const FeatureOptions& options,
350 bool reportOOM) {
351 CompileArgsError error;
352 SharedCompileArgs args =
353 CompileArgs::build(cx, std::move(scriptedCaller), options, &error);
354 if (args) {
355 Log(cx, "available wasm compilers: tier1=%s tier2=%s",
356 args->baselineEnabled ? "baseline" : "none",
357 args->ionEnabled ? "ion" : "none");
358 return args;
359 }
360
361 switch (error) {
362 case CompileArgsError::NoCompiler: {
363 JS_ReportErrorASCII(cx, "no WebAssembly compiler available");
364 break;
365 }
366 case CompileArgsError::OutOfMemory: {
367 // Most callers are required to return 'false' without reporting an OOM,
368 // so we make reporting it optional here.
369 if (reportOOM) {
370 ReportOutOfMemory(cx);
371 }
372 break;
373 }
374 }
375 return nullptr;
376 }
377
378 BytecodeSource::BytecodeSource(const uint8_t* begin, size_t length) {
379 BytecodeRange codeRange;
380 if (!StartsCodeSection(begin, begin + length, &codeRange)) {
381 env_ = BytecodeSpan(begin, length);
382 code_ = BytecodeSpan();
383 tail_ = BytecodeSpan();
384 return;
385 }
386
387 BytecodeRange envRange;
388 BytecodeRange tailRange;
389 if (codeRange.end <= length) {
390 envRange = BytecodeRange(0, codeRange.start);
391 tailRange = BytecodeRange(codeRange.end, length - codeRange.end);
392 } else {
393 MOZ_RELEASE_ASSERT(codeRange.start <= length);
394 // If the specified code range is larger than the buffer, clamp it to the
395 // the buffer size. This buffer will be rejected later.
396 envRange = BytecodeRange(0, codeRange.start);
397 codeRange = BytecodeRange(codeRange.start, length - codeRange.start);
398 MOZ_RELEASE_ASSERT(codeRange.end == length);
399 tailRange = BytecodeRange(length, 0);
400 }
401
402 BytecodeSpan module(begin, length);
403 env_ = envRange.toSpan(module);
404 code_ = codeRange.toSpan(module);
405 tail_ = tailRange.toSpan(module);
406 }
407
408 BytecodeBuffer::BytecodeBuffer(const ShareableBytes* env,
409 const ShareableBytes* code,
410 const ShareableBytes* tail)
411 : env_(env),
412 code_(code),
413 tail_(tail),
414 source_(env_ ? env_->span() : BytecodeSpan(),
415 code_ ? code_->span() : BytecodeSpan(),
416 tail_ ? tail_->span() : BytecodeSpan()) {}
417
418 bool BytecodeBuffer::fromSource(const BytecodeSource& bytecodeSource,
419 BytecodeBuffer* bytecodeBuffer) {
420 SharedBytes env;
421 if (!bytecodeSource.envRange().isEmpty()) {
422 env = ShareableBytes::fromSpan(bytecodeSource.envSpan());
423 if (!env) {
424 return false;
425 }
426 }
427
428 SharedBytes code;
429 if (bytecodeSource.hasCodeSection() &&
430 !bytecodeSource.codeRange().isEmpty()) {
431 code = ShareableBytes::fromSpan(bytecodeSource.codeSpan());
432 if (!code) {
433 return false;
434 }
435 }
436
437 SharedBytes tail;
438 if (bytecodeSource.hasCodeSection() &&
439 !bytecodeSource.tailRange().isEmpty()) {
440 tail = ShareableBytes::fromSpan(bytecodeSource.tailSpan());
441 if (!tail) {
442 return false;
443 }
444 }
445
446 *bytecodeBuffer = BytecodeBuffer(env, code, tail);
447 return true;
448 }
449
450 /*
451 * [SMDOC] Tiered wasm compilation.
452 *
453 * "Tiered compilation" refers to the mechanism where we first compile the code
454 * with a fast non-optimizing compiler so that we can start running the code
455 * quickly, while in the background recompiling the code with the slower
456 * optimizing compiler. Code created by baseline is called "tier-1"; code
457 * created by the optimizing compiler is called "tier-2". When the tier-2 code
458 * is ready, we "tier up" the code by creating paths from tier-1 code into their
459 * tier-2 counterparts; this patching is performed as the program is running.
460 *
461 * ## Selecting the compilation mode
462 *
463 * When wasm bytecode arrives, we choose the compilation strategy based on
464 * switches and on aspects of the code and the hardware. If switches allow
465 * tiered compilation to happen (the normal case), the following logic applies.
466 *
467 * If the code is sufficiently large that tiered compilation would be beneficial
468 * but not so large that it might blow our compiled code budget and make
469 * compilation fail, we choose tiered compilation. Otherwise we go straight to
470 * optimized code.
471 *
472 * The expected benefit of tiering is computed by TieringBeneficial(), below,
473 * based on various estimated parameters of the hardware: ratios of object code
474 * to byte code, speed of the system, number of cores.
475 *
476 * ## Mechanics of tiering up; patching
477 *
478 * Every time control enters a tier-1 function, the function prologue loads its
479 * tiering pointer from the tiering jump table (see JumpTable in WasmCode.h) and
480 * jumps to it.
481 *
482 * Initially, an entry in the tiering table points to the instruction inside the
483 * tier-1 function that follows the jump instruction (hence the jump is an
484 * expensive nop). When the tier-2 compiler is finished, the table is patched
485 * racily to point into the tier-2 function at the correct prologue location
486 * (see loop near the end of Module::finishTier2()). As tier-2 compilation is
487 * performed at most once per Module, there is at most one such racy overwrite
488 * per table element during the lifetime of the Module.
489 *
490 * The effect of the patching is to cause the tier-1 function to jump to its
491 * tier-2 counterpart whenever the tier-1 function is called subsequently. That
492 * is, tier-1 code performs standard frame setup on behalf of whatever code it
493 * jumps to, and the target code (tier-1 or tier-2) allocates its own frame in
494 * whatever way it wants.
495 *
496 * The racy writing means that it is often nondeterministic whether tier-1 or
497 * tier-2 code is reached by any call during the tiering-up process; if F calls
498 * A and B in that order, it may reach tier-2 code for A and tier-1 code for B.
499 * If F is running concurrently on threads T1 and T2, T1 and T2 may see code
500 * from different tiers for either function.
501 *
502 * Note, tiering up also requires upgrading the jit-entry stubs so that they
503 * reference tier-2 code. The mechanics of this upgrading are described at
504 * WasmInstanceObject::getExportedFunction().
505 *
506 * ## Current limitations of tiering
507 *
508 * Tiering is not always seamless. Partly, it is possible for a program to get
509 * stuck in tier-1 code. Partly, a function that has tiered up continues to
510 * force execution to go via tier-1 code to reach tier-2 code, paying for an
511 * additional jump and a slightly less optimized prologue than tier-2 code could
512 * have had on its own.
513 *
514 * Known tiering limitiations:
515 *
516 * - We can tier up only at function boundaries. If a tier-1 function has a
517 * long-running loop it will not tier up until it returns to its caller. If
518 * this loop never exits (a runloop in a worker, for example) then the
519 * function will never tier up.
520 *
521 * To do better, we need OSR.
522 *
523 * - Wasm Table entries are never patched during tier-up. A Table of funcref
524 * holds not a JSFunction pointer, but a (code*,instance*) pair of pointers.
525 * When a table.set operation is performed, the JSFunction value is decomposed
526 * and its code and instance pointers are stored in the table; subsequently,
527 * when a table.get operation is performed, the JSFunction value is
528 * reconstituted from its code pointer using fairly elaborate machinery. (The
529 * mechanics are the same also for the reflected JS operations on a
530 * WebAssembly.Table. For everything, see WasmTable.{cpp,h}.) The code pointer
531 * in the Table will always be the code pointer belonging to the best tier that
532 * was active at the time when that function was stored in that Table slot; in
533 * many cases, it will be tier-1 code. As a consequence, a call through a table
534 * will first enter tier-1 code and then jump to tier-2 code.
535 *
536 * To do better, we must update all the tables in the system when an instance
537 * tiers up. This is expected to be very hard.
538 *
539 * - Imported Wasm functions are never patched during tier-up. Imports are held
540 * in FuncImportInstanceData values in the instance, and for a wasm
541 * callee, what's stored is the raw code pointer into the best tier of the
542 * callee that was active at the time the import was resolved. That could be
543 * baseline code, and if it is, the situation is as for Table entries: a call
544 * to an import will always go via that import's tier-1 code, which will tier
545 * up with an indirect jump.
546 *
547 * To do better, we must update all the import tables in the system that
548 * import functions from instances whose modules have tiered up. This is
549 * expected to be hard.
550 */
551
552 // Classify the current system as one of a set of recognizable classes. This
553 // really needs to get our tier-1 systems right.
554 //
555 // TODO: We don't yet have a good measure of how fast a system is. We
556 // distinguish between mobile and desktop because these are very different kinds
557 // of systems, but we could further distinguish between low / medium / high end
558 // within those major classes. If we do so, then constants below would be
559 // provided for each (class, architecture, system-tier) combination, not just
560 // (class, architecture) as now.
561 //
562 // CPU clock speed is not by itself a good predictor of system performance, as
563 // there are high-performance systems with slow clocks (recent Intel) and
564 // low-performance systems with fast clocks (older AMD). We can also use
565 // physical memory, core configuration, OS details, CPU class and family, and
566 // CPU manufacturer to disambiguate.
567
568 enum class SystemClass {
569 DesktopX86,
570 DesktopX64,
571 DesktopUnknown32,
572 DesktopUnknown64,
573 MobileX86,
574 MobileArm32,
575 MobileArm64,
576 MobileUnknown32,
577 MobileUnknown64
578 };
579
580 static SystemClass ClassifySystem() {
581 bool isDesktop;
582
583 #if defined(ANDROID) || defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64)
584 isDesktop = false;
585 #else
586 isDesktop = true;
587 #endif
588
589 if (isDesktop) {
590 #if defined(JS_CODEGEN_X64)
591 return SystemClass::DesktopX64;
592 #elif defined(JS_CODEGEN_X86)
593 return SystemClass::DesktopX86;
594 #elif defined(JS_64BIT)
595 return SystemClass::DesktopUnknown64;
596 #else
597 return SystemClass::DesktopUnknown32;
598 #endif
599 } else {
600 #if defined(JS_CODEGEN_X86)
601 return SystemClass::MobileX86;
602 #elif defined(JS_CODEGEN_ARM)
603 return SystemClass::MobileArm32;
604 #elif defined(JS_CODEGEN_ARM64)
605 return SystemClass::MobileArm64;
606 #elif defined(JS_64BIT)
607 return SystemClass::MobileUnknown64;
608 #else
609 return SystemClass::MobileUnknown32;
610 #endif
611 }
612 }
613
614 // Code sizes in machine code bytes per bytecode byte, again empirical except
615 // where marked.
616 //
617 // The Ion estimate for ARM64 is the measured Baseline value scaled by a
618 // plausible factor for optimized code.
619
620 static const double x64Tox86Inflation = 1.25;
621
622 static const double x64IonBytesPerBytecode = 2.45;
623 static const double x86IonBytesPerBytecode =
624 x64IonBytesPerBytecode * x64Tox86Inflation;
625 static const double arm32IonBytesPerBytecode = 3.3;
626 static const double arm64IonBytesPerBytecode = 3.0 / 1.4; // Estimate
627
628 static const double x64BaselineBytesPerBytecode = x64IonBytesPerBytecode * 1.43;
629 static const double x86BaselineBytesPerBytecode =
630 x64BaselineBytesPerBytecode * x64Tox86Inflation;
631 static const double arm32BaselineBytesPerBytecode =
632 arm32IonBytesPerBytecode * 1.39;
633 static const double arm64BaselineBytesPerBytecode = 3.0;
634
635 static double OptimizedBytesPerBytecode(SystemClass cls) {
636 switch (cls) {
637 case SystemClass::DesktopX86:
638 case SystemClass::MobileX86:
639 case SystemClass::DesktopUnknown32:
640 return x86IonBytesPerBytecode;
641 case SystemClass::DesktopX64:
642 case SystemClass::DesktopUnknown64:
643 return x64IonBytesPerBytecode;
644 case SystemClass::MobileArm32:
645 case SystemClass::MobileUnknown32:
646 return arm32IonBytesPerBytecode;
647 case SystemClass::MobileArm64:
648 case SystemClass::MobileUnknown64:
649 return arm64IonBytesPerBytecode;
650 default:
651 MOZ_CRASH();
652 }
653 }
654
655 static double BaselineBytesPerBytecode(SystemClass cls) {
656 switch (cls) {
657 case SystemClass::DesktopX86:
658 case SystemClass::MobileX86:
659 case SystemClass::DesktopUnknown32:
660 return x86BaselineBytesPerBytecode;
661 case SystemClass::DesktopX64:
662 case SystemClass::DesktopUnknown64:
663 return x64BaselineBytesPerBytecode;
664 case SystemClass::MobileArm32:
665 case SystemClass::MobileUnknown32:
666 return arm32BaselineBytesPerBytecode;
667 case SystemClass::MobileArm64:
668 case SystemClass::MobileUnknown64:
669 return arm64BaselineBytesPerBytecode;
670 default:
671 MOZ_CRASH();
672 }
673 }
674
675 double wasm::EstimateCompiledCodeSize(Tier tier, size_t bytecodeSize) {
676 SystemClass cls = ClassifySystem();
677 switch (tier) {
678 case Tier::Baseline:
679 return double(bytecodeSize) * BaselineBytesPerBytecode(cls);
680 case Tier::Optimized:
681 return double(bytecodeSize) * OptimizedBytesPerBytecode(cls);
682 }
683 MOZ_CRASH("bad tier");
684 }
685
686 // If parallel Ion compilation is going to take longer than this, we should
687 // tier.
688
689 static const double tierCutoffMs = 10;
690
691 // Compilation rate values are empirical except when noted, the reference
692 // systems are:
693 //
694 // Late-2013 MacBook Pro (2.6GHz 4 x hyperthreaded Haswell, Mac OS X)
695 // Late-2015 Nexus 5X (1.4GHz 4 x Cortex-A53 + 1.8GHz 2 x Cortex-A57, Android)
696 // Ca-2016 SoftIron Overdrive 1000 (1.7GHz 4 x Cortex-A57, Fedora)
697 //
698 // The rates are always per core.
699 //
700 // The estimate for ARM64 is the Baseline compilation rate on the SoftIron
701 // (because we have no Ion yet), divided by 5 to estimate Ion compile rate and
702 // then divided by 2 to make it more reasonable for consumer ARM64 systems.
703
704 static const double x64IonBytecodesPerMs = 2100;
705 static const double x86IonBytecodesPerMs = 1500;
706 static const double arm32IonBytecodesPerMs = 450;
707 static const double arm64IonBytecodesPerMs = 750; // Estimate
708
709 // Tiering cutoff values: if code section sizes are below these values (when
710 // divided by the effective number of cores) we do not tier, because we guess
711 // that parallel Ion compilation will be fast enough.
712
713 static const double x64DesktopTierCutoff = x64IonBytecodesPerMs * tierCutoffMs;
714 static const double x86DesktopTierCutoff = x86IonBytecodesPerMs * tierCutoffMs;
715 static const double x86MobileTierCutoff = x86DesktopTierCutoff / 2; // Guess
716 static const double arm32MobileTierCutoff =
717 arm32IonBytecodesPerMs * tierCutoffMs;
718 static const double arm64MobileTierCutoff =
719 arm64IonBytecodesPerMs * tierCutoffMs;
720
721 static double CodesizeCutoff(SystemClass cls) {
722 switch (cls) {
723 case SystemClass::DesktopX86:
724 case SystemClass::DesktopUnknown32:
725 return x86DesktopTierCutoff;
726 case SystemClass::DesktopX64:
727 case SystemClass::DesktopUnknown64:
728 return x64DesktopTierCutoff;
729 case SystemClass::MobileX86:
730 return x86MobileTierCutoff;
731 case SystemClass::MobileArm32:
732 case SystemClass::MobileUnknown32:
733 return arm32MobileTierCutoff;
734 case SystemClass::MobileArm64:
735 case SystemClass::MobileUnknown64:
736 return arm64MobileTierCutoff;
737 default:
738 MOZ_CRASH();
739 }
740 }
741
742 // As the number of cores grows the effectiveness of each core dwindles (on the
743 // systems we care about for SpiderMonkey).
744 //
745 // The data are empirical, computed from the observed compilation time of the
746 // Tanks demo code on a variable number of cores.
747 //
748 // The heuristic may fail on NUMA systems where the core count is high but the
749 // performance increase is nil or negative once the program moves beyond one
750 // socket. However, few browser users have such systems.
751
752 static double EffectiveCores(uint32_t cores) {
753 if (cores <= 3) {
754 return pow(cores, 0.9);
755 }
756 return pow(cores, 0.75);
757 }
758
759 #ifndef JS_64BIT
760 // Don't tier if tiering will fill code memory to more to more than this
761 // fraction.
762
763 static const double spaceCutoffPct = 0.9;
764 #endif
765
766 // Figure out whether we should use tiered compilation or not.
767 static bool TieringBeneficial(bool lazyTiering, uint32_t codeSize) {
768 // Lazy tiering is assumed to always be beneficial when it is enabled.
769 if (lazyTiering) {
770 return true;
771 }
772
773 uint32_t cpuCount = GetHelperThreadCPUCount();
774 MOZ_ASSERT(cpuCount > 0);
775
776 // It's mostly sensible not to background compile when there's only one
777 // hardware thread as we want foreground computation to have access to that.
778 // However, if wasm background compilation helper threads can be given lower
779 // priority then background compilation on single-core systems still makes
780 // some kind of sense. That said, this is a non-issue: as of September 2017
781 // 1-core was down to 3.5% of our population and falling.
782
783 if (cpuCount == 1) {
784 return false;
785 }
786
787 // Compute the max number of threads available to do actual background
788 // compilation work.
789
790 uint32_t workers = GetMaxWasmCompilationThreads();
791
792 // The number of cores we will use is bounded both by the CPU count and the
793 // worker count, since the worker count already takes this into account.
794
795 uint32_t cores = workers;
796
797 SystemClass cls = ClassifySystem();
798
799 // Ion compilation on available cores must take long enough to be worth the
800 // bother.
801
802 double cutoffSize = CodesizeCutoff(cls);
803 double effectiveCores = EffectiveCores(cores);
804
805 if ((codeSize / effectiveCores) < cutoffSize) {
806 return false;
807 }
808
809 // Do not implement a size cutoff for 64-bit systems since the code size
810 // budget for 64 bit is so large that it will hardly ever be an issue.
811 // (Also the cutoff percentage might be different on 64-bit.)
812
813 #ifndef JS_64BIT
814 // If the amount of executable code for baseline compilation jeopardizes the
815 // availability of executable memory for ion code then do not tier, for now.
816 //
817 // TODO: For now we consider this module in isolation. We should really
818 // worry about what else is going on in this process and might be filling up
819 // the code memory. It's like we need some kind of code memory reservation
820 // system or JIT compilation for large modules.
821
822 double ionRatio = OptimizedBytesPerBytecode(cls);
823 double baselineRatio = BaselineBytesPerBytecode(cls);
824 double needMemory = codeSize * (ionRatio + baselineRatio);
825 double availMemory = LikelyAvailableExecutableMemory();
826 double cutoff = spaceCutoffPct * MaxCodeBytesPerProcess;
827
828 // If the sum of baseline and ion code makes us exceeds some set percentage
829 // of the executable memory then disable tiering.
830
831 if ((MaxCodeBytesPerProcess - availMemory) + needMemory > cutoff) {
832 return false;
833 }
834 #endif
835
836 return true;
837 }
838
839 // Ensure that we have the non-compiler requirements to tier safely.
840 static bool PlatformCanTier(bool lazyTiering) {
841 // Note: ensure this function stays in sync with `WasmLazyTieringEnabled()`.
842 // Tiering needs background threads if we're using eager tiering or we're
843 // using lazy tiering without the synchronous flag.
844 bool synchronousTiering =
845 lazyTiering && JS::Prefs::wasm_lazy_tiering_synchronous();
846
847 return (synchronousTiering || CanUseExtraThreads()) &&
848 jit::CanFlushExecutionContextForAllThreads();
849 }
850
851 CompilerEnvironment::CompilerEnvironment(const CompileArgs& args)
852 : state_(InitialWithArgs), args_(&args) {}
853
854 CompilerEnvironment::CompilerEnvironment(CompileMode mode, Tier tier,
855 DebugEnabled debugEnabled)
856 : state_(InitialWithModeTierDebug),
857 mode_(mode),
858 tier_(tier),
859 debug_(debugEnabled) {}
860
861 void CompilerEnvironment::computeParameters() {
862 MOZ_ASSERT(state_ == InitialWithModeTierDebug);
863
864 state_ = Computed;
865 }
866
867 void CompilerEnvironment::computeParameters(const ModuleMetadata& moduleMeta) {
868 MOZ_ASSERT(!isComputed());
869
870 if (state_ == InitialWithModeTierDebug) {
871 computeParameters();
872 return;
873 }
874
875 bool baselineEnabled = args_->baselineEnabled;
876 bool ionEnabled = args_->ionEnabled;
877 bool debugEnabled = args_->debugEnabled;
878 bool forceTiering = args_->forceTiering;
879
880 bool hasSecondTier = ionEnabled;
881 MOZ_ASSERT_IF(debugEnabled, baselineEnabled);
882 MOZ_ASSERT_IF(forceTiering, baselineEnabled && hasSecondTier);
883
884 // Various constraints in various places should prevent failure here.
885 MOZ_RELEASE_ASSERT(baselineEnabled || ionEnabled);
886
887 bool isGcModule = moduleMeta.codeMeta->types->hasGcType();
888 uint32_t codeSectionSize = moduleMeta.codeMeta->codeSectionSize();
889
890 // We use lazy tiering if the 'for-all' pref is enabled, or the 'gc-only'
891 // pref is enabled and we're compiling a GC module. However, forcing
892 // serialization-testing disables lazy tiering.
893 bool testSerialization = args_->features.testSerialization;
894 bool lazyTiering = (JS::Prefs::wasm_lazy_tiering() ||
895 (JS::Prefs::wasm_lazy_tiering_for_gc() && isGcModule)) &&
896 !testSerialization;
897
898 if (baselineEnabled && hasSecondTier &&
899 (TieringBeneficial(lazyTiering, codeSectionSize) || forceTiering) &&
900 PlatformCanTier(lazyTiering)) {
901 mode_ = lazyTiering ? CompileMode::LazyTiering : CompileMode::EagerTiering;
902 tier_ = Tier::Baseline;
903 } else {
904 mode_ = CompileMode::Once;
905 tier_ = hasSecondTier ? Tier::Optimized : Tier::Baseline;
906 }
907
908 debug_ = debugEnabled ? DebugEnabled::True : DebugEnabled::False;
909
910 state_ = Computed;
911 }
912
913 template <class DecoderT, class ModuleGeneratorT>
914 static bool DecodeFunctionBody(DecoderT& d, ModuleGeneratorT& mg,
915 uint32_t funcIndex) {
916 uint32_t bodySize;
917 if (!d.readVarU32(&bodySize)) {
918 return d.fail("expected number of function body bytes");
919 }
920
921 if (bodySize > MaxFunctionBytes) {
922 return d.fail("function body too big");
923 }
924
925 const size_t offsetInModule = d.currentOffset();
926
927 // Skip over the function body; it will be validated by the compilation
928 // thread.
929 const uint8_t* bodyBegin;
930 if (!d.readBytes(bodySize, &bodyBegin)) {
931 return d.fail("function body length too big");
932 }
933
934 return mg.compileFuncDef(funcIndex, offsetInModule, bodyBegin,
935 bodyBegin + bodySize);
936 }
937
938 template <class DecoderT, class ModuleGeneratorT>
939 static bool DecodeCodeSection(const CodeMetadata& codeMeta, DecoderT& d,
940 ModuleGeneratorT& mg) {
941 if (!codeMeta.codeSectionRange) {
942 if (codeMeta.numFuncDefs() != 0) {
943 return d.fail("expected code section");
944 }
945
946 return mg.finishFuncDefs();
947 }
948
949 uint32_t numFuncDefs;
950 if (!d.readVarU32(&numFuncDefs)) {
951 return d.fail("expected function body count");
952 }
953
954 if (numFuncDefs != codeMeta.numFuncDefs()) {
955 return d.fail(
956 "function body count does not match function signature count");
957 }
958
959 for (uint32_t funcDefIndex = 0; funcDefIndex < numFuncDefs; funcDefIndex++) {
960 if (!DecodeFunctionBody(d, mg, codeMeta.numFuncImports + funcDefIndex)) {
961 return false;
962 }
963 }
964
965 if (!d.finishSection(*codeMeta.codeSectionRange, "code")) {
966 return false;
967 }
968
969 return mg.finishFuncDefs();
970 }
971
972 SharedModule wasm::CompileBuffer(const CompileArgs& args,
973 const BytecodeBufferOrSource& bytecode,
974 UniqueChars* error,
975 UniqueCharsVector* warnings,
976 JS::OptimizedEncodingListener* listener) {
977 MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>();
978 if (!moduleMeta || !moduleMeta->init(args)) {
979 return nullptr;
980 }
981
982 const BytecodeSource& bytecodeSource = bytecode.source();
983 Decoder envDecoder(bytecodeSource.envSpan(), bytecodeSource.envRange().start,
984 error, warnings);
985 if (!DecodeModuleEnvironment(envDecoder, moduleMeta->codeMeta.get(),
986 moduleMeta)) {
987 return nullptr;
988 }
989
990 CompilerEnvironment compilerEnv(args);
991 compilerEnv.computeParameters(*moduleMeta);
992 if (!moduleMeta->prepareForCompile(compilerEnv.mode())) {
993 return nullptr;
994 }
995
996 ModuleGenerator mg(*moduleMeta->codeMeta, compilerEnv,
997 compilerEnv.initialState(), nullptr, error, warnings);
998 if (!mg.initializeCompleteTier()) {
999 return nullptr;
1000 }
1001
1002 // If our bytecode has a code section, then we must switch decoders for
1003 // these section.
1004 if (bytecodeSource.hasCodeSection()) {
1005 // DecodeModuleEnvironment will stop and return true if there is an unknown
1006 // section before the code section. We must check this and return an error.
1007 if (!moduleMeta->codeMeta->codeSectionRange) {
1008 envDecoder.fail("unknown section before code section");
1009 return nullptr;
1010 }
1011
1012 // Our pre-parse that split the module should ensure that after we've
1013 // parsed the environment there are no bytes left.
1014 MOZ_RELEASE_ASSERT(envDecoder.done());
1015
1016 Decoder codeDecoder(bytecodeSource.codeSpan(),
1017 bytecodeSource.codeRange().start, error, warnings);
1018 if (!DecodeCodeSection(*moduleMeta->codeMeta, codeDecoder, mg)) {
1019 return nullptr;
1020 }
1021 // Our pre-parse that split the module should ensure that after we've
1022 // parsed the code section there are no bytes left.
1023 MOZ_RELEASE_ASSERT(codeDecoder.done());
1024
1025 Decoder tailDecoder(bytecodeSource.tailSpan(),
1026 bytecodeSource.tailRange().start, error, warnings);
1027 if (!DecodeModuleTail(tailDecoder, moduleMeta->codeMeta, moduleMeta)) {
1028 return nullptr;
1029 }
1030 // Decoding the module tail should consume all remaining bytes.
1031 MOZ_RELEASE_ASSERT(tailDecoder.done());
1032 } else {
1033 // We still must call this method even without a code section because it
1034 // does validation that ensure we aren't missing function definitions.
1035 if (!DecodeCodeSection(*moduleMeta->codeMeta, envDecoder, mg)) {
1036 return nullptr;
1037 }
1038
1039 if (!DecodeModuleTail(envDecoder, moduleMeta->codeMeta, moduleMeta)) {
1040 return nullptr;
1041 }
1042
1043 // Decoding the module tail should consume all remaining bytes.
1044 MOZ_RELEASE_ASSERT(envDecoder.done());
1045 }
1046
1047 return mg.finishModule(bytecode, *moduleMeta, listener);
1048 }
1049
1050 bool wasm::CompileCompleteTier2(const ShareableBytes* codeSection,
1051 const Module& module, UniqueChars* error,
1052 UniqueCharsVector* warnings,
1053 Atomic<bool>* cancelled) {
1054 CompilerEnvironment compilerEnv(CompileMode::EagerTiering, Tier::Optimized,
1055 DebugEnabled::False);
1056 compilerEnv.computeParameters();
1057
1058 const CodeMetadata& codeMeta = module.codeMeta();
1059 ModuleGenerator mg(codeMeta, compilerEnv, CompileState::EagerTier2, cancelled,
1060 error, warnings);
1061 if (!mg.initializeCompleteTier()) {
1062 return false;
1063 }
1064
1065 if (codeMeta.codeSectionRange) {
1066 BytecodeSpan codeSpan(codeSection->begin(), codeSection->end());
1067 Decoder d(codeSpan, codeMeta.codeSectionRange->start, error);
1068 if (!DecodeCodeSection(module.codeMeta(), d, mg)) {
1069 return false;
1070 }
1071 } else {
1072 MOZ_ASSERT(!codeSection);
1073 MOZ_ASSERT(codeMeta.numFuncDefs() == 0);
1074 if (!mg.finishFuncDefs()) {
1075 return false;
1076 }
1077 }
1078
1079 return mg.finishTier2(module);
1080 }
1081
1082 bool wasm::CompilePartialTier2(const Code& code, uint32_t funcIndex,
1083 UniqueChars* error, UniqueCharsVector* warnings,
1084 mozilla::Atomic<bool>* cancelled) {
1085 CompilerEnvironment compilerEnv(CompileMode::LazyTiering, Tier::Optimized,
1086 DebugEnabled::False);
1087 compilerEnv.computeParameters();
1088
1089 const CodeMetadata& codeMeta = code.codeMeta();
1090 ModuleGenerator mg(codeMeta, compilerEnv, CompileState::LazyTier2, cancelled,
1091 error, warnings);
1092 if (!mg.initializePartialTier(code, funcIndex)) {
1093 // The module is already validated, so this can only be an OOM.
1094 MOZ_ASSERT(!*error);
1095 return false;
1096 }
1097
1098 const BytecodeRange& funcRange = code.codeTailMeta().funcDefRange(funcIndex);
1099 BytecodeSpan funcBytecode = code.codeTailMeta().funcDefBody(funcIndex);
1100
1101 // The following sequence will compile/finish this function, on this thread.
1102 // `error` (as stashed in `mg`) may get set to, for example, "stack frame too
1103 // large", or to "", denoting OOM.
1104 return mg.compileFuncDef(funcIndex, funcRange.start, funcBytecode.data(),
1105 funcBytecode.data() + funcBytecode.size()) &&
1106 mg.finishFuncDefs() && mg.finishPartialTier2();
1107 }
1108
1109 class StreamingDecoder {
1110 Decoder d_;
1111 const ExclusiveBytesPtr& codeBytesEnd_;
1112 const Atomic<bool>& cancelled_;
1113
1114 public:
1115 StreamingDecoder(const CodeMetadata& codeMeta, const Bytes& begin,
1116 const ExclusiveBytesPtr& codeBytesEnd,
1117 const Atomic<bool>& cancelled, UniqueChars* error,
1118 UniqueCharsVector* warnings)
1119 : d_(begin, codeMeta.codeSectionRange->start, error, warnings),
1120 codeBytesEnd_(codeBytesEnd),
1121 cancelled_(cancelled) {}
1122
1123 bool fail(const char* msg) { return d_.fail(msg); }
1124
1125 bool done() const { return d_.done(); }
1126
1127 size_t currentOffset() const { return d_.currentOffset(); }
1128
1129 bool waitForBytes(size_t numBytes) {
1130 numBytes = std::min(numBytes, d_.bytesRemain());
1131 const uint8_t* requiredEnd = d_.currentPosition() + numBytes;
1132 auto codeBytesEnd = codeBytesEnd_.lock();
1133 while (codeBytesEnd < requiredEnd) {
1134 if (cancelled_) {
1135 return false;
1136 }
1137 codeBytesEnd.wait();
1138 }
1139 return true;
1140 }
1141
1142 bool readVarU32(uint32_t* u32) {
1143 return waitForBytes(MaxVarU32DecodedBytes) && d_.readVarU32(u32);
1144 }
1145
1146 bool readBytes(size_t size, const uint8_t** begin) {
1147 return waitForBytes(size) && d_.readBytes(size, begin);
1148 }
1149
1150 bool finishSection(const BytecodeRange& range, const char* name) {
1151 return d_.finishSection(range, name);
1152 }
1153 };
1154
1155 SharedModule wasm::CompileStreaming(
1156 const CompileArgs& args, const ShareableBytes& envBytes,
1157 const ShareableBytes& codeBytes, const ExclusiveBytesPtr& codeBytesEnd,
1158 const ExclusiveStreamEndData& exclusiveStreamEnd,
1159 const Atomic<bool>& cancelled, UniqueChars* error,
1160 UniqueCharsVector* warnings) {
1161 CompilerEnvironment compilerEnv(args);
1162 MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>();
1163 if (!moduleMeta || !moduleMeta->init(args)) {
1164 return nullptr;
1165 }
1166 CodeMetadata& codeMeta = *moduleMeta->codeMeta;
1167
1168 {
1169 Decoder d(envBytes.vector, 0, error, warnings);
1170
1171 if (!DecodeModuleEnvironment(d, &codeMeta, moduleMeta)) {
1172 return nullptr;
1173 }
1174 compilerEnv.computeParameters(*moduleMeta);
1175
1176 if (!codeMeta.codeSectionRange) {
1177 d.fail("unknown section before code section");
1178 return nullptr;
1179 }
1180
1181 MOZ_RELEASE_ASSERT(codeMeta.codeSectionRange->size() == codeBytes.length());
1182 MOZ_RELEASE_ASSERT(d.done());
1183 }
1184
1185 if (!moduleMeta->prepareForCompile(compilerEnv.mode())) {
1186 return nullptr;
1187 }
1188
1189 ModuleGenerator mg(codeMeta, compilerEnv, compilerEnv.initialState(),
1190 &cancelled, error, warnings);
1191 if (!mg.initializeCompleteTier()) {
1192 return nullptr;
1193 }
1194
1195 {
1196 StreamingDecoder d(codeMeta, codeBytes.vector, codeBytesEnd, cancelled,
1197 error, warnings);
1198
1199 if (!DecodeCodeSection(codeMeta, d, mg)) {
1200 return nullptr;
1201 }
1202
1203 MOZ_RELEASE_ASSERT(d.done());
1204 }
1205
1206 {
1207 auto streamEnd = exclusiveStreamEnd.lock();
1208 while (!streamEnd->reached) {
1209 if (cancelled) {
1210 return nullptr;
1211 }
1212 streamEnd.wait();
1213 }
1214 }
1215
1216 const StreamEndData streamEnd = exclusiveStreamEnd.lock();
1217 const ShareableBytes& tailBytes = *streamEnd.tailBytes;
1218
1219 {
1220 Decoder d(tailBytes.vector, codeMeta.codeSectionRange->end, error,
1221 warnings);
1222
1223 if (!DecodeModuleTail(d, &codeMeta, moduleMeta)) {
1224 return nullptr;
1225 }
1226
1227 MOZ_RELEASE_ASSERT(d.done());
1228 }
1229
1230 BytecodeBuffer bytecodeBuffer(&envBytes, &codeBytes, &tailBytes);
1231 return mg.finishModule(BytecodeBufferOrSource(bytecodeBuffer), *moduleMeta,
1232 streamEnd.completeTier2Listener);
1233 }
1234
1235 class DumpIonModuleGenerator {
1236 private:
1237 const CompilerEnvironment& compilerEnv_;
1238 CodeMetadata& codeMeta_;
1239 uint32_t targetFuncIndex_;
1240 IonDumpContents contents_;
1241 GenericPrinter& out_;
1242 UniqueChars* error_;
1243
1244 public:
1245 DumpIonModuleGenerator(const CompilerEnvironment& compilerEnv,
1246 CodeMetadata& codeMeta, uint32_t targetFuncIndex,
1247 IonDumpContents contents, GenericPrinter& out,
1248 UniqueChars* error)
1249 : compilerEnv_(compilerEnv),
1250 codeMeta_(codeMeta),
1251 targetFuncIndex_(targetFuncIndex),
1252 contents_(contents),
1253 out_(out),
1254 error_(error) {}
1255
1256 bool finishFuncDefs() { return true; }
1257 bool compileFuncDef(uint32_t funcIndex, uint32_t lineOrBytecode,
1258 const uint8_t* begin, const uint8_t* end) {
1259 if (funcIndex != targetFuncIndex_) {
1260 return true;
1261 }
1262
1263 FuncCompileInput input(funcIndex, lineOrBytecode, begin, end,
1264 Uint32Vector());
1265 return IonDumpFunction(compilerEnv_, codeMeta_, input, contents_, out_,
1266 error_);
1267 }
1268 };
1269
1270 bool wasm::DumpIonFunctionInModule(const ShareableBytes& bytecode,
1271 uint32_t targetFuncIndex,
1272 IonDumpContents contents,
1273 GenericPrinter& out, UniqueChars* error) {
1274 SharedCompileArgs compileArgs =
1275 CompileArgs::buildForValidation(FeatureArgs::allEnabled());
1276 if (!compileArgs) {
1277 return false;
1278 }
1279 CompilerEnvironment compilerEnv(CompileMode::Once, Tier::Optimized,
1280 DebugEnabled::False);
1281 compilerEnv.computeParameters();
1282
1283 UniqueCharsVector warnings;
1284 Decoder d(bytecode.span(), 0, error, &warnings);
1285 MutableModuleMetadata moduleMeta = js_new<ModuleMetadata>();
1286 if (!moduleMeta || !moduleMeta->init(*compileArgs)) {
1287 return false;
1288 }
1289
1290 if (!DecodeModuleEnvironment(d, moduleMeta->codeMeta, moduleMeta)) {
1291 return false;
1292 }
1293
1294 DumpIonModuleGenerator mg(compilerEnv, *moduleMeta->codeMeta, targetFuncIndex,
1295 contents, out, error);
1296 return moduleMeta->prepareForCompile(CompileMode::Once) &&
1297 DecodeCodeSection(*moduleMeta->codeMeta, d, mg);
1298 }