Debian Codegraph @

js/src/wasm/WasmIonCompile.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/WasmIonCompile.h"
20
21 #include "mozilla/DebugOnly.h"
22 #include "mozilla/MathAlgorithms.h"
23
24 #include <algorithm>
25
26 #include "jit/ABIArgGenerator.h"
27 #include "jit/CodeGenerator.h"
28 #include "jit/CompileInfo.h"
29 #include "jit/Ion.h"
30 #include "jit/IonOptimizationLevels.h"
31 #include "jit/MIR-wasm.h"
32 #include "jit/MIR.h"
33 #include "jit/ShuffleAnalysis.h"
34 #include "js/GCAPI.h" // JS::AutoSuppressGCAnalysis
35 #include "js/ScalarType.h" // js::Scalar::Type
36 #include "util/DifferentialTesting.h"
37 #include "wasm/WasmBaselineCompile.h"
38 #include "wasm/WasmBuiltinModule.h"
39 #include "wasm/WasmBuiltins.h"
40 #include "wasm/WasmCodegenTypes.h"
41 #include "wasm/WasmGC.h"
42 #include "wasm/WasmGcObject.h"
43 #include "wasm/WasmGenerator.h"
44 #include "wasm/WasmOpIter.h"
45 #include "wasm/WasmSignalHandlers.h"
46 #include "wasm/WasmStubs.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::IsPowerOfTwo;
54 using mozilla::Nothing;
55
56 namespace {
57
58 using UniqueCompileInfo = UniquePtr<CompileInfo>;
59 using UniqueCompileInfoVector = Vector<UniqueCompileInfo, 1, SystemAllocPolicy>;
60
61 using BlockVector = Vector<MBasicBlock*, 8, SystemAllocPolicy>;
62 using DefVector = Vector<MDefinition*, 8, SystemAllocPolicy>;
63 using ControlInstructionVector =
64 Vector<MControlInstruction*, 8, SystemAllocPolicy>;
65
66 // [SMDOC] WebAssembly Exception Handling in Ion
67 // =======================================================
68 //
69 // ## Throwing instructions
70 //
71 // Wasm exceptions can be thrown by either a throw instruction (local throw),
72 // or by a wasm call.
73 //
74 // ## The "catching try control"
75 //
76 // We know we are in try-code if there is a surrounding ControlItem with
77 // LabelKind::Try. The innermost such control is called the
78 // "catching try control".
79 //
80 // ## Throws without a catching try control
81 //
82 // Such throws are implemented with an instance call that triggers the exception
83 // unwinding runtime. The exception unwinding runtime will not return to the
84 // function.
85 //
86 // ## "landing pad" and "pre-pad" blocks
87 //
88 // When an exception is thrown, the unwinder will search for the nearest
89 // enclosing try block and redirect control flow to it. The code that executes
90 // before any catch blocks is called the 'landing pad'. The 'landing pad' is
91 // responsible to:
92 // 1. Consume the pending exception state from
93 // Instance::pendingException(Tag)
94 // 2. Branch to the correct catch block, or else rethrow
95 //
96 // There is one landing pad for each try block. The immediate predecessors of
97 // the landing pad are called 'pre-pad' blocks. There is one pre-pad block per
98 // throwing instruction.
99 //
100 // ## Creating pre-pad blocks
101 //
102 // There are two possible sorts of pre-pad blocks, depending on whether we
103 // are branching after a local throw instruction, or after a wasm call:
104 //
105 // - If we encounter a local throw, we create the exception and tag objects,
106 // store them to Instance::pendingException(Tag), and then jump to the
107 // landing pad.
108 //
109 // - If we encounter a wasm call, we construct a MWasmCallCatchable which is a
110 // control instruction with either a branch to a fallthrough block or
111 // to a pre-pad block.
112 //
113 // The pre-pad block for a wasm call is empty except for a jump to the
114 // landing pad. It only exists to avoid critical edges which when split would
115 // violate the invariants of MWasmCallCatchable. The pending exception state
116 // is taken care of by the unwinder.
117 //
118 // Each pre-pad ends with a pending jump to the landing pad. The pending jumps
119 // to the landing pad are tracked in `tryPadPatches`. These are called
120 // "pad patches".
121 //
122 // ## Creating the landing pad
123 //
124 // When we exit try-code, we check if tryPadPatches has captured any control
125 // instructions (pad patches). If not, we don't compile any catches and we mark
126 // the rest as dead code.
127 //
128 // If there are pre-pad blocks, we join them to create a landing pad (or just
129 // "pad"). The pad's last two slots are the caught exception, and the
130 // exception's tag object.
131 //
132 // There are three different forms of try-catch/catch_all Wasm instructions,
133 // which result in different form of landing pad.
134 //
135 // 1. A catchless try, so a Wasm instruction of the form "try ... end".
136 // - In this case, we end the pad by rethrowing the caught exception.
137 //
138 // 2. A single catch_all after a try.
139 // - If the first catch after a try is a catch_all, then there won't be
140 // any more catches, but we need the exception and its tag object, in
141 // case the code in a catch_all contains "rethrow" instructions.
142 // - The Wasm instruction "rethrow", gets the exception and tag object to
143 // rethrow from the last two slots of the landing pad which, due to
144 // validation, is the l'th surrounding ControlItem.
145 // - We immediately GoTo to a new block after the pad and pop both the
146 // exception and tag object, as we don't need them anymore in this case.
147 //
148 // 3. Otherwise, there is one or more catch code blocks following.
149 // - In this case, we construct the landing pad by creating a sequence
150 // of compare and branch blocks that compare the pending exception tag
151 // object to the tag object of the current tagged catch block. This is
152 // done incrementally as we visit each tagged catch block in the bytecode
153 // stream. At every step, we update the ControlItem's block to point to
154 // the next block to be created in the landing pad sequence. The final
155 // block will either be a rethrow, if there is no catch_all, or else a
156 // jump to a catch_all block.
157
158 struct TryControl {
159 // Branches to bind to the try's landing pad.
160 ControlInstructionVector landingPadPatches;
161 // For `try_table`, the list of tagged catches and labels to branch to.
162 TryTableCatchVector catches;
163 // The pending exception for the try's landing pad.
164 MDefinition* pendingException;
165 // The pending exception's tag for the try's landing pad.
166 MDefinition* pendingExceptionTag;
167 // Whether this try is in the body and should catch any thrown exception.
168 bool inBody;
169
170 TryControl()
171 : pendingException(nullptr),
172 pendingExceptionTag(nullptr),
173 inBody(false) {}
174
175 // Reset the try control for when it is cached in FunctionCompiler.
176 void reset() {
177 landingPadPatches.clearAndFree();
178 catches.clearAndFree();
179 inBody = false;
180 }
181 };
182 using UniqueTryControl = UniquePtr<TryControl>;
183 using VectorUniqueTryControl = Vector<UniqueTryControl, 2, SystemAllocPolicy>;
184
185 struct ControlFlowPatch {
186 MControlInstruction* ins;
187 uint32_t index;
188 ControlFlowPatch(MControlInstruction* ins, uint32_t index)
189 : ins(ins), index(index) {}
190 };
191
192 using ControlFlowPatchVector = Vector<ControlFlowPatch, 0, SystemAllocPolicy>;
193
194 struct PendingBlockTarget {
195 ControlFlowPatchVector patches;
196 BranchHint hint = BranchHint::Invalid;
197 };
198
199 using PendingBlockTargetVector =
200 Vector<PendingBlockTarget, 0, SystemAllocPolicy>;
201
202 // Inlined functions accumulate all returns to be bound to a caller function
203 // after compilation is finished.
204 struct PendingInlineReturn {
205 PendingInlineReturn(MGoto* jump, DefVector&& results)
206 : jump(jump), results(std::move(results)) {}
207
208 MGoto* jump;
209 DefVector results;
210 };
211
212 using PendingInlineReturnVector =
213 Vector<PendingInlineReturn, 1, SystemAllocPolicy>;
214
215 // CallCompileState describes a call that is being compiled.
216 struct CallCompileState {
217 // A generator object that is passed each argument as it is compiled.
218 WasmABIArgGenerator abi;
219
220 // Accumulates the register arguments while compiling arguments.
221 MWasmCallBase::Args regArgs;
222
223 // Reserved argument for passing Instance* to builtin instance method calls.
224 ABIArg instanceArg;
225
226 // The stack area in which the callee will write stack return values, or
227 // nullptr if no stack results.
228 MWasmStackResultArea* stackResultArea = nullptr;
229
230 // Indicates that the call is a return/tail call.
231 bool returnCall = false;
232
233 // The landing pad patches for the nearest enclosing try-catch. This is
234 // non-null iff the call is catchable.
235 ControlInstructionVector* tryLandingPadPatches = nullptr;
236
237 // The index of the try note for a catchable call.
238 uint32_t tryNoteIndex = UINT32_MAX;
239
240 // The block to take for fallthrough execution for a catchable call.
241 MBasicBlock* fallthroughBlock = nullptr;
242
243 // The block to take for exceptional execution for a catchable call.
244 MBasicBlock* prePadBlock = nullptr;
245
246 bool isCatchable() const { return tryLandingPadPatches != nullptr; }
247 };
248
249 struct Control {
250 MBasicBlock* block;
251 UniqueTryControl tryControl;
252
253 Control() : block(nullptr), tryControl(nullptr) {}
254 Control(Control&&) = default;
255 Control(const Control&) = delete;
256 };
257
258 struct IonCompilePolicy {
259 // We store SSA definitions in the value stack.
260 using Value = MDefinition*;
261 using ValueVector = DefVector;
262
263 // We store loop headers and then/else blocks in the control flow stack.
264 // In the case of try-catch control blocks, we collect additional information
265 // regarding the possible paths from throws and calls to a landing pad, as
266 // well as information on the landing pad's handlers (its catches).
267 using ControlItem = Control;
268 };
269
270 using IonOpIter = OpIter<IonCompilePolicy>;
271
272 // Statistics for inlining (at all depths) into the root function.
273 struct InliningStats {
274 size_t inlinedDirectBytecodeSize = 0; // sum of sizes of inlinees
275 size_t inlinedDirectFunctions = 0; // number of inlinees
276 size_t inlinedCallRefBytecodeSize = 0; // sum of sizes of inlinees
277 size_t inlinedCallRefFunctions = 0; // number of inlinees
278 bool largeFunctionBackoff = false; // did large function backoff happen?
279 };
280
281 // Encapsulates the generation of MIR for a wasm function and any functions
282 // that become inlined into it.
283 class RootCompiler {
284 const CompilerEnvironment& compilerEnv_;
285 const CodeMetadata& codeMeta_;
286 const CodeTailMetadata* codeTailMeta_;
287
288 const ValTypeVector& locals_;
289 const FuncCompileInput& func_;
290 Decoder& decoder_;
291 FeatureUsage observedFeatures_;
292
293 CompileInfo compileInfo_;
294 const JitCompileOptions options_;
295 TempAllocator& alloc_;
296 MIRGraph mirGraph_;
297 MIRGenerator mirGen_;
298
299 // The current loop depth we're generating inside of. This includes all
300 // callee functions when we're generating an inlined function, and so it
301 // lives here on the root compiler.
302 uint32_t loopDepth_;
303
304 // The current stack of bytecode offsets of the caller functions of the
305 // function currently being inlined.
306 BytecodeOffsetVector inlinedCallerOffsets_;
307 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex_;
308
309 // Compilation statistics for this function.
310 CompileStats funcStats_;
311
312 // Accumulated inlining statistics for this function.
313 InliningStats inliningStats_;
314 // The remaining inlining budget, in terms of bytecode bytes. This may go
315 // negative and so is signed.
316 int64_t localInliningBudget_;
317
318 // All jit::CompileInfo objects created during this compilation. This must
319 // be kept alive for as long as the MIR graph is alive.
320 UniqueCompileInfoVector compileInfos_;
321
322 // Cache of TryControl to minimize heap allocations.
323 VectorUniqueTryControl tryControlCache_;
324
325 // Reference to masm.tryNotes()
326 wasm::TryNoteVector& tryNotes_;
327
328 // Reference to masm.inliningContext()
329 wasm::InliningContext& inliningContext_;
330
331 public:
332 RootCompiler(const CompilerEnvironment& compilerEnv,
333 const CodeMetadata& codeMeta,
334 const CodeTailMetadata* codeTailMeta, TempAllocator& alloc,
335 const ValTypeVector& locals, const FuncCompileInput& func,
336 Decoder& decoder, wasm::TryNoteVector& tryNotes,
337 wasm::InliningContext& inliningContext)
338 : compilerEnv_(compilerEnv),
339 codeMeta_(codeMeta),
340 codeTailMeta_(codeTailMeta),
341 locals_(locals),
342 func_(func),
343 decoder_(decoder),
344 observedFeatures_(FeatureUsage::None),
345 compileInfo_(locals.length()),
346 alloc_(alloc),
347 mirGraph_(&alloc),
348 mirGen_(nullptr, options_, &alloc_, &mirGraph_, &compileInfo_,
349 IonOptimizations.get(OptimizationLevel::Wasm), &codeMeta),
350 loopDepth_(0),
351 localInliningBudget_(0),
352 tryNotes_(tryNotes),
353 inliningContext_(inliningContext) {}
354
355 const CompilerEnvironment& compilerEnv() const { return compilerEnv_; }
356 const CodeMetadata& codeMeta() const { return codeMeta_; }
357 const CodeTailMetadata* codeTailMeta() const { return codeTailMeta_; }
358 const FuncCompileInput& func() const { return func_; }
359 TempAllocator& alloc() { return alloc_; }
360 MIRGraph& mirGraph() { return mirGraph_; }
361 MIRGenerator& mirGen() { return mirGen_; }
362 int64_t inliningBudget() const { return localInliningBudget_; }
363 FeatureUsage observedFeatures() const { return observedFeatures_; }
364 const CompileStats& funcStats() const { return funcStats_; }
365 void noteLargeFunctionBackoffWasApplied() {
366 inliningStats_.largeFunctionBackoff = true;
367 }
368
369 uint32_t loopDepth() const { return loopDepth_; }
370 void startLoop() { loopDepth_++; }
371 void closeLoop() { loopDepth_--; }
372
373 [[nodiscard]] bool generate();
374
375 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex() const {
376 return inlinedCallerOffsetsIndex_;
377 }
378
379 // Add a compile info for an inlined function. This keeps the inlined
380 // function's compile info alive for the outermost function's
381 // compilation.
382 [[nodiscard]] CompileInfo* startInlineCall(
383 uint32_t callerFuncIndex, BytecodeOffset callerOffset,
384 uint32_t calleeFuncIndex, uint32_t numLocals, size_t inlineeBytecodeSize,
385 InliningHeuristics::CallKind callKind);
386 void finishInlineCall();
387
388 // Add a try note and return the index.
389 [[nodiscard]] bool addTryNote(uint32_t* tryNoteIndex) {
390 if (!tryNotes_.append(wasm::TryNote())) {
391 return false;
392 }
393 *tryNoteIndex = tryNotes_.length() - 1;
394 return true;
395 }
396
397 // Try to get a free TryControl from the cache, or allocate a new one.
398 [[nodiscard]] UniqueTryControl newTryControl() {
399 if (tryControlCache_.empty()) {
400 return UniqueTryControl(js_new<TryControl>());
401 }
402 UniqueTryControl tryControl = std::move(tryControlCache_.back());
403 tryControlCache_.popBack();
404 return tryControl;
405 }
406
407 // Release the TryControl to the cache.
408 void freeTryControl(UniqueTryControl&& tryControl) {
409 // Ensure that it's in a consistent state
410 tryControl->reset();
411 // Ignore any OOM, as we'll fail later
412 (void)tryControlCache_.append(std::move(tryControl));
413 }
414 };
415
416 // Encapsulates the generation of MIR for a single function in a wasm module.
417 class FunctionCompiler {
418 // The root function compiler we are being compiled within.
419 RootCompiler& rootCompiler_;
420
421 // The caller function compiler, if any, that we are being inlined into.
422 // Note that `inliningDepth_` is zero for the first inlinee, one for the
423 // second inlinee, etc.
424 const FunctionCompiler* callerCompiler_;
425 const uint32_t inliningDepth_;
426
427 // Information about this function's bytecode and parsing state
428 IonOpIter iter_;
429 uint32_t functionBodyOffset_;
430 const FuncCompileInput& func_;
431 const ValTypeVector& locals_;
432 size_t lastReadCallSite_;
433 size_t numCallRefs_;
434 size_t numAllocSites_;
435
436 // CompileInfo for compiling the MIR for this function. Allocated inside of
437 // RootCompiler::compileInfos, and kept alive for the duration of the
438 // total compilation.
439 const jit::CompileInfo& info_;
440
441 MBasicBlock* curBlock_;
442 uint32_t maxStackArgBytes_;
443
444 // When generating a forward branch we haven't created the basic block that
445 // the branch needs to target. We handle this by accumulating all the branch
446 // instructions that want to target a block we have not yet created into
447 // `pendingBlocks_` and then patching them in `bindBranches`.
448 //
449 // For performance reasons we only grow `pendingBlocks_` as needed, never
450 // shrink it. So the length of the vector has no relation to the current
451 // nesting depth of wasm blocks. We use `pendingBlockDepth_` to track the
452 // current wasm block depth. We assert that all entries beyond the current
453 // block depth are empty.
454 uint32_t pendingBlockDepth_;
455 PendingBlockTargetVector pendingBlocks_;
456 // Control flow patches for exceptions that are caught without a landing
457 // pad they can directly jump to. This happens when either:
458 // (1) `delegate` targets the function body label.
459 // (2) A `try` ends without any cases, and there is no enclosing `try`.
460 // (3) There is no `try` in this function, but a caller function (when
461 // inlining) has a `try`.
462 //
463 // These exceptions will be rethrown using `emitBodyRethrowPad`.
464 ControlInstructionVector bodyRethrowPadPatches_;
465 // A vector of the returns in this function for use when we're being inlined
466 // into another function.
467 PendingInlineReturnVector pendingInlineReturns_;
468 // A block that all uncaught exceptions in this function will jump to. The
469 // inline caller will link this to the nearest enclosing catch handler.
470 MBasicBlock* pendingInlineCatchBlock_;
471
472 // Instance pointer argument to the current function.
473 MWasmParameter* instancePointer_;
474 MWasmParameter* stackResultPointer_;
475
476 public:
477 // Construct a FunctionCompiler for the root function of a compilation
478 FunctionCompiler(RootCompiler& rootCompiler, Decoder& decoder,
479 const FuncCompileInput& func, const ValTypeVector& locals,
480 const CompileInfo& compileInfo)
481 : rootCompiler_(rootCompiler),
482 callerCompiler_(nullptr),
483 inliningDepth_(0),
484 iter_(rootCompiler.codeMeta(), decoder, locals),
485 functionBodyOffset_(decoder.beginOffset()),
486 func_(func),
487 locals_(locals),
488 lastReadCallSite_(0),
489 numCallRefs_(0),
490 numAllocSites_(0),
491 info_(compileInfo),
492 curBlock_(nullptr),
493 maxStackArgBytes_(0),
494 pendingBlockDepth_(0),
495 pendingInlineCatchBlock_(nullptr),
496 instancePointer_(nullptr),
497 stackResultPointer_(nullptr) {}
498
499 // Construct a FunctionCompiler for an inlined callee of a compilation
500 FunctionCompiler(const FunctionCompiler* callerCompiler, Decoder& decoder,
501 const FuncCompileInput& func, const ValTypeVector& locals,
502 const CompileInfo& compileInfo)
503 : rootCompiler_(callerCompiler->rootCompiler_),
504 callerCompiler_(callerCompiler),
505 inliningDepth_(callerCompiler_->inliningDepth() + 1),
506 iter_(rootCompiler_.codeMeta(), decoder, locals),
507 functionBodyOffset_(decoder.beginOffset()),
508 func_(func),
509 locals_(locals),
510 lastReadCallSite_(0),
511 numCallRefs_(0),
512 numAllocSites_(0),
513 info_(compileInfo),
514 curBlock_(nullptr),
515 maxStackArgBytes_(0),
516 pendingBlockDepth_(0),
517 pendingInlineCatchBlock_(nullptr),
518 instancePointer_(callerCompiler_->instancePointer_),
519 stackResultPointer_(nullptr) {}
520
521 RootCompiler& rootCompiler() { return rootCompiler_; }
522 const CodeMetadata& codeMeta() const { return rootCompiler_.codeMeta(); }
523 const CodeTailMetadata* codeTailMeta() const {
524 return rootCompiler_.codeTailMeta();
525 }
526
527 IonOpIter& iter() { return iter_; }
528 uint32_t relativeBytecodeOffset() {
529 return readBytecodeOffset() - functionBodyOffset_;
530 }
531 TempAllocator& alloc() const { return rootCompiler_.alloc(); }
532 // FIXME(1401675): Replace with BlockType.
533 uint32_t funcIndex() const { return func_.index; }
534 const FuncType& funcType() const {
535 return codeMeta().getFuncType(func_.index);
536 }
537
538 bool isInlined() const { return callerCompiler_ != nullptr; }
539 uint32_t inliningDepth() const { return inliningDepth_; }
540
541 MBasicBlock* getCurBlock() const { return curBlock_; }
542 BytecodeOffset bytecodeOffset() const { return iter_.bytecodeOffset(); }
543 TrapSiteDesc trapSiteDesc() {
544 return TrapSiteDesc(wasm::BytecodeOffset(bytecodeOffset()),
545 rootCompiler_.inlinedCallerOffsetsIndex());
546 }
547 TrapSiteDesc trapSiteDescWithCallSiteLineNumber() {
548 return TrapSiteDesc(wasm::BytecodeOffset(readCallSiteLineOrBytecode()),
549 rootCompiler_.inlinedCallerOffsetsIndex());
550 }
551 FeatureUsage featureUsage() const { return iter_.featureUsage(); }
552
553 [[nodiscard]] bool initRoot() {
554 // We are not being inlined into something
555 MOZ_ASSERT(!callerCompiler_);
556
557 // Prepare the entry block for MIR generation:
558
559 const FuncType& ft = funcType();
560 const ArgTypeVector args(ft);
561
562 if (!mirGen().ensureBallast()) {
563 return false;
564 }
565 if (!newBlock(/* prev */ nullptr, &curBlock_)) {
566 return false;
567 }
568
569 for (WasmABIArgIter i(args); !i.done(); i++) {
570 MaybeRefType argRefType;
571 if (!args.isSyntheticStackResultPointerArg(i.index())) {
572 ValType argType = ft.arg(i.index());
573 argRefType = argType.isRefType() ? MaybeRefType(argType.refType())
574 : MaybeRefType();
575 }
576
577 MWasmParameter* ins =
578 MWasmParameter::New(alloc(), *i, i.mirType(), argRefType);
579 curBlock_->add(ins);
580 if (args.isSyntheticStackResultPointerArg(i.index())) {
581 MOZ_ASSERT(stackResultPointer_ == nullptr);
582 stackResultPointer_ = ins;
583 } else {
584 curBlock_->initSlot(info().localSlot(args.naturalIndex(i.index())),
585 ins);
586 }
587 if (!mirGen().ensureBallast()) {
588 return false;
589 }
590 }
591
592 // Set up a parameter that receives the hidden instance pointer argument.
593 instancePointer_ =
594 MWasmParameter::New(alloc(), ABIArg(InstanceReg), MIRType::Pointer);
595 curBlock_->add(instancePointer_);
596 if (!mirGen().ensureBallast()) {
597 return false;
598 }
599
600 for (size_t i = args.lengthWithoutStackResults(); i < locals_.length();
601 i++) {
602 ValType slotValType = locals_[i];
603 #ifndef ENABLE_WASM_SIMD
604 if (slotValType == ValType::V128) {
605 return iter().fail("Ion has no SIMD support yet");
606 }
607 #endif
608 MDefinition* zero = constantZeroOfValType(slotValType);
609 curBlock_->initSlot(info().localSlot(i), zero);
610 if (!mirGen().ensureBallast()) {
611 return false;
612 }
613 }
614
615 return true;
616 }
617
618 [[nodiscard]] bool initInline(const DefVector& argValues) {
619 // "This is an inlined-callee FunctionCompiler"
620 MOZ_ASSERT(callerCompiler_);
621
622 // Prepare the entry block for MIR generation:
623 if (!mirGen().ensureBallast()) {
624 return false;
625 }
626 if (!newBlock(nullptr, &curBlock_)) {
627 return false;
628 }
629
630 MBasicBlock* pred = callerCompiler_->curBlock_;
631 pred->end(MGoto::New(alloc(), curBlock_));
632 if (!curBlock_->addPredecessorWithoutPhis(pred)) {
633 return false;
634 }
635
636 // Set up args slots to point to passed argument values
637 const FuncType& type = funcType();
638 for (uint32_t argIndex = 0; argIndex < type.args().length(); argIndex++) {
639 curBlock_->initSlot(info().localSlot(argIndex), argValues[argIndex]);
640 }
641
642 // Set up a parameter that receives the hidden instance pointer argument.
643 instancePointer_ = callerCompiler_->instancePointer_;
644
645 // Initialize all local slots to zero value
646 for (size_t i = type.args().length(); i < locals_.length(); i++) {
647 ValType slotValType = locals_[i];
648 #ifndef ENABLE_WASM_SIMD
649 if (slotValType == ValType::V128) {
650 return iter().fail("Ion has no SIMD support yet");
651 }
652 #endif
653 MDefinition* zero = constantZeroOfValType(slotValType);
654 curBlock_->initSlot(info().localSlot(i), zero);
655 if (!mirGen().ensureBallast()) {
656 return false;
657 }
658 }
659
660 return true;
661 }
662
663 void finish() {
664 mirGen().accumulateWasmMaxStackArgBytes(maxStackArgBytes_);
665
666 MOZ_ASSERT(pendingBlockDepth_ == 0);
667 #ifdef DEBUG
668 for (PendingBlockTarget& targets : pendingBlocks_) {
669 MOZ_ASSERT(targets.patches.empty());
670 }
671 #endif
672 MOZ_ASSERT(inDeadCode());
673 MOZ_ASSERT(done());
674 MOZ_ASSERT(func_.callSiteLineNums.length() == lastReadCallSite_);
675 MOZ_ASSERT_IF(
676 compilerEnv().mode() == CompileMode::LazyTiering,
677 codeTailMeta()->getFuncDefCallRefs(funcIndex()).length == numCallRefs_);
678 MOZ_ASSERT_IF(codeTailMeta(),
679 codeTailMeta()->getFuncDefAllocSites(funcIndex()).length ==
680 numAllocSites_);
681 MOZ_ASSERT_IF(!isInlined(),
682 pendingInlineReturns_.empty() && !pendingInlineCatchBlock_);
683 MOZ_ASSERT(bodyRethrowPadPatches_.empty());
684 }
685
686 /************************* Read-only interface (after local scope setup) */
687
688 MIRGenerator& mirGen() const { return rootCompiler_.mirGen(); }
689 MIRGraph& mirGraph() const { return rootCompiler_.mirGraph(); }
690 const CompileInfo& info() const { return info_; }
691 const CompilerEnvironment& compilerEnv() const {
692 return rootCompiler_.compilerEnv();
693 }
694
695 MDefinition* getLocalDef(unsigned slot) {
696 if (inDeadCode()) {
697 return nullptr;
698 }
699 return curBlock_->getSlot(info().localSlot(slot));
700 }
701
702 const ValTypeVector& locals() const { return locals_; }
703
704 /*********************************************************** Constants ***/
705
706 MDefinition* constantF32(float f) {
707 if (inDeadCode()) {
708 return nullptr;
709 }
710 auto* cst = MWasmFloatConstant::NewFloat32(alloc(), f);
711 curBlock_->add(cst);
712 return cst;
713 }
714 // Hide all other overloads, to guarantee no implicit argument conversion.
715 template <typename T>
716 MDefinition* constantF32(T) = delete;
717
718 MDefinition* constantF64(double d) {
719 if (inDeadCode()) {
720 return nullptr;
721 }
722 auto* cst = MWasmFloatConstant::NewDouble(alloc(), d);
723 curBlock_->add(cst);
724 return cst;
725 }
726 template <typename T>
727 MDefinition* constantF64(T) = delete;
728
729 MDefinition* constantI32(int32_t i) {
730 if (inDeadCode()) {
731 return nullptr;
732 }
733 MConstant* constant =
734 MConstant::New(alloc(), Int32Value(i), MIRType::Int32);
735 curBlock_->add(constant);
736 return constant;
737 }
738 template <typename T>
739 MDefinition* constantI32(T) = delete;
740
741 MDefinition* constantI64(int64_t i) {
742 if (inDeadCode()) {
743 return nullptr;
744 }
745 MConstant* constant = MConstant::NewInt64(alloc(), i);
746 curBlock_->add(constant);
747 return constant;
748 }
749 template <typename T>
750 MDefinition* constantI64(T) = delete;
751
752 // Produce an MConstant of the machine's target int type (Int32 or Int64).
753 MDefinition* constantTargetWord(intptr_t n) {
754 return targetIs64Bit() ? constantI64(int64_t(n)) : constantI32(int32_t(n));
755 }
756 template <typename T>
757 MDefinition* constantTargetWord(T) = delete;
758
759 #ifdef ENABLE_WASM_SIMD
760 MDefinition* constantV128(V128 v) {
761 if (inDeadCode()) {
762 return nullptr;
763 }
764 MWasmFloatConstant* constant = MWasmFloatConstant::NewSimd128(
765 alloc(), SimdConstant::CreateSimd128((int8_t*)v.bytes));
766 curBlock_->add(constant);
767 return constant;
768 }
769 template <typename T>
770 MDefinition* constantV128(T) = delete;
771 #endif
772
773 MDefinition* constantNullRef(MaybeRefType type) {
774 if (inDeadCode()) {
775 return nullptr;
776 }
777 // MConstant has a lot of baggage so we don't use that here.
778 MWasmNullConstant* constant = MWasmNullConstant::New(alloc(), type);
779 curBlock_->add(constant);
780 return constant;
781 }
782
783 // Produce a zero constant for the specified ValType.
784 MDefinition* constantZeroOfValType(ValType valType) {
785 switch (valType.kind()) {
786 case ValType::I32:
787 return constantI32(0);
788 case ValType::I64:
789 return constantI64(int64_t(0));
790 #ifdef ENABLE_WASM_SIMD
791 case ValType::V128:
792 return constantV128(V128(0));
793 #endif
794 case ValType::F32:
795 return constantF32(0.0f);
796 case ValType::F64:
797 return constantF64(0.0);
798 case ValType::Ref:
799 return constantNullRef(MaybeRefType(valType.refType()));
800 default:
801 MOZ_CRASH();
802 }
803 }
804
805 /***************************** Code generation (after local scope setup) */
806
807 void fence() {
808 if (inDeadCode()) {
809 return;
810 }
811 MWasmFence* ins = MWasmFence::New(alloc());
812 curBlock_->add(ins);
813 }
814
815 template <class T>
816 MDefinition* unary(MDefinition* op) {
817 if (inDeadCode()) {
818 return nullptr;
819 }
820 T* ins = T::New(alloc(), op);
821 curBlock_->add(ins);
822 return ins;
823 }
824
825 template <class T>
826 MDefinition* unary(MDefinition* op, MIRType type) {
827 if (inDeadCode()) {
828 return nullptr;
829 }
830 T* ins = T::New(alloc(), op, type);
831 curBlock_->add(ins);
832 return ins;
833 }
834
835 template <class T>
836 MDefinition* binary(MDefinition* lhs, MDefinition* rhs) {
837 if (inDeadCode()) {
838 return nullptr;
839 }
840 T* ins = T::New(alloc(), lhs, rhs);
841 curBlock_->add(ins);
842 return ins;
843 }
844
845 template <class T>
846 MDefinition* binary(MDefinition* lhs, MDefinition* rhs, MIRType type) {
847 if (inDeadCode()) {
848 return nullptr;
849 }
850 T* ins = T::New(alloc(), lhs, rhs, type);
851 curBlock_->add(ins);
852 return ins;
853 }
854
855 template <class T>
856 MDefinition* binary(MDefinition* lhs, MDefinition* rhs, MIRType type,
857 MWasmBinaryBitwise::SubOpcode subOpc) {
858 if (inDeadCode()) {
859 return nullptr;
860 }
861 T* ins = T::New(alloc(), lhs, rhs, type, subOpc);
862 curBlock_->add(ins);
863 return ins;
864 }
865
866 MDefinition* ursh(MDefinition* lhs, MDefinition* rhs, MIRType type) {
867 if (inDeadCode()) {
868 return nullptr;
869 }
870 auto* ins = MUrsh::NewWasm(alloc(), lhs, rhs, type);
871 curBlock_->add(ins);
872 return ins;
873 }
874
875 MDefinition* add(MDefinition* lhs, MDefinition* rhs, MIRType type) {
876 if (inDeadCode()) {
877 return nullptr;
878 }
879 auto* ins = MAdd::NewWasm(alloc(), lhs, rhs, type);
880 curBlock_->add(ins);
881 return ins;
882 }
883
884 bool mustPreserveNaN(MIRType type) {
885 return IsFloatingPointType(type) && !codeMeta().isAsmJS();
886 }
887
888 MDefinition* sub(MDefinition* lhs, MDefinition* rhs, MIRType type) {
889 if (inDeadCode()) {
890 return nullptr;
891 }
892
893 // wasm can't fold x - 0.0 because of NaN with custom payloads.
894 MSub* ins = MSub::NewWasm(alloc(), lhs, rhs, type, mustPreserveNaN(type));
895 curBlock_->add(ins);
896 return ins;
897 }
898
899 MDefinition* nearbyInt(MDefinition* input, RoundingMode roundingMode) {
900 if (inDeadCode()) {
901 return nullptr;
902 }
903
904 auto* ins = MNearbyInt::New(alloc(), input, input->type(), roundingMode);
905 curBlock_->add(ins);
906 return ins;
907 }
908
909 MDefinition* minMax(MDefinition* lhs, MDefinition* rhs, MIRType type,
910 bool isMax) {
911 if (inDeadCode()) {
912 return nullptr;
913 }
914
915 if (mustPreserveNaN(type)) {
916 // Convert signaling NaN to quiet NaNs.
917 MDefinition* zero = constantZeroOfValType(ValType::fromMIRType(type));
918 lhs = sub(lhs, zero, type);
919 rhs = sub(rhs, zero, type);
920 }
921
922 MMinMax* ins = MMinMax::NewWasm(alloc(), lhs, rhs, type, isMax);
923 curBlock_->add(ins);
924 return ins;
925 }
926
927 MDefinition* mul(MDefinition* lhs, MDefinition* rhs, MIRType type,
928 MMul::Mode mode) {
929 if (inDeadCode()) {
930 return nullptr;
931 }
932
933 // wasm can't fold x * 1.0 because of NaN with custom payloads.
934 auto* ins =
935 MMul::NewWasm(alloc(), lhs, rhs, type, mode, mustPreserveNaN(type));
936 curBlock_->add(ins);
937 return ins;
938 }
939
940 MDefinition* div(MDefinition* lhs, MDefinition* rhs, MIRType type,
941 bool unsignd) {
942 if (inDeadCode()) {
943 return nullptr;
944 }
945 bool trapOnError = !codeMeta().isAsmJS();
946 if (!unsignd && type == MIRType::Int32) {
947 // Enforce the signedness of the operation by coercing the operands
948 // to signed. Otherwise, operands that "look" unsigned to Ion but
949 // are not unsigned to Baldr (eg, unsigned right shifts) may lead to
950 // the operation being executed unsigned. Applies to mod() as well.
951 //
952 // Do this for Int32 only since Int64 is not subject to the same
953 // issues.
954 //
955 // Note the offsets passed to MWasmBuiltinTruncateToInt32 are wrong here,
956 // but it doesn't matter: they're not codegen'd to calls since inputs
957 // already are int32.
958 auto* lhs2 = createTruncateToInt32(lhs);
959 curBlock_->add(lhs2);
960 lhs = lhs2;
961 auto* rhs2 = createTruncateToInt32(rhs);
962 curBlock_->add(rhs2);
963 rhs = rhs2;
964 }
965
966 // For x86 and arm we implement i64 div via c++ builtin.
967 // A call to c++ builtin requires instance pointer.
968 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_ARM)
969 if (type == MIRType::Int64) {
970 auto* ins = MWasmBuiltinDivI64::New(alloc(), lhs, rhs, instancePointer_,
971 unsignd, trapOnError, trapSiteDesc());
972 curBlock_->add(ins);
973 return ins;
974 }
975 #endif
976
977 auto* ins = MDiv::New(alloc(), lhs, rhs, type, unsignd, trapOnError,
978 trapSiteDesc(), mustPreserveNaN(type));
979 curBlock_->add(ins);
980 return ins;
981 }
982
983 MInstruction* createTruncateToInt32(MDefinition* op) {
984 if (op->type() == MIRType::Double || op->type() == MIRType::Float32) {
985 return MWasmBuiltinTruncateToInt32::New(alloc(), op, instancePointer_);
986 }
987
988 return MTruncateToInt32::New(alloc(), op);
989 }
990
991 MDefinition* mod(MDefinition* lhs, MDefinition* rhs, MIRType type,
992 bool unsignd) {
993 if (inDeadCode()) {
994 return nullptr;
995 }
996 bool trapOnError = !codeMeta().isAsmJS();
997 if (!unsignd && type == MIRType::Int32) {
998 // See block comment in div().
999 auto* lhs2 = createTruncateToInt32(lhs);
1000 curBlock_->add(lhs2);
1001 lhs = lhs2;
1002 auto* rhs2 = createTruncateToInt32(rhs);
1003 curBlock_->add(rhs2);
1004 rhs = rhs2;
1005 }
1006
1007 // For x86 and arm we implement i64 mod via c++ builtin.
1008 // A call to c++ builtin requires instance pointer.
1009 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_ARM)
1010 if (type == MIRType::Int64) {
1011 auto* ins = MWasmBuiltinModI64::New(alloc(), lhs, rhs, instancePointer_,
1012 unsignd, trapOnError, trapSiteDesc());
1013 curBlock_->add(ins);
1014 return ins;
1015 }
1016 #endif
1017
1018 // Should be handled separately because we call BuiltinThunk for this case
1019 // and so, need to add the dependency from instancePointer.
1020 if (type == MIRType::Double) {
1021 auto* ins = MWasmBuiltinModD::New(alloc(), lhs, rhs, instancePointer_,
1022 type, bytecodeOffset());
1023 curBlock_->add(ins);
1024 return ins;
1025 }
1026
1027 auto* ins = MMod::New(alloc(), lhs, rhs, type, unsignd, trapOnError,
1028 trapSiteDesc());
1029 curBlock_->add(ins);
1030 return ins;
1031 }
1032
1033 MDefinition* bitnot(MDefinition* op, MIRType type) {
1034 if (inDeadCode()) {
1035 return nullptr;
1036 }
1037 auto* ins = MBitNot::New(alloc(), op, type);
1038 curBlock_->add(ins);
1039 return ins;
1040 }
1041
1042 MDefinition* select(MDefinition* trueExpr, MDefinition* falseExpr,
1043 MDefinition* condExpr) {
1044 if (inDeadCode()) {
1045 return nullptr;
1046 }
1047 auto* ins = MWasmSelect::New(alloc(), trueExpr, falseExpr, condExpr);
1048 curBlock_->add(ins);
1049 return ins;
1050 }
1051
1052 MDefinition* extendI32(MDefinition* op, bool isUnsigned) {
1053 if (inDeadCode()) {
1054 return nullptr;
1055 }
1056 auto* ins = MExtendInt32ToInt64::New(alloc(), op, isUnsigned);
1057 curBlock_->add(ins);
1058 return ins;
1059 }
1060
1061 MDefinition* signExtend(MDefinition* op, uint32_t srcSize,
1062 uint32_t targetSize) {
1063 if (inDeadCode()) {
1064 return nullptr;
1065 }
1066 MInstruction* ins;
1067 switch (targetSize) {
1068 case 4: {
1069 MSignExtendInt32::Mode mode;
1070 switch (srcSize) {
1071 case 1:
1072 mode = MSignExtendInt32::Byte;
1073 break;
1074 case 2:
1075 mode = MSignExtendInt32::Half;
1076 break;
1077 default:
1078 MOZ_CRASH("Bad sign extension");
1079 }
1080 ins = MSignExtendInt32::New(alloc(), op, mode);
1081 break;
1082 }
1083 case 8: {
1084 MSignExtendInt64::Mode mode;
1085 switch (srcSize) {
1086 case 1:
1087 mode = MSignExtendInt64::Byte;
1088 break;
1089 case 2:
1090 mode = MSignExtendInt64::Half;
1091 break;
1092 case 4:
1093 mode = MSignExtendInt64::Word;
1094 break;
1095 default:
1096 MOZ_CRASH("Bad sign extension");
1097 }
1098 ins = MSignExtendInt64::New(alloc(), op, mode);
1099 break;
1100 }
1101 default: {
1102 MOZ_CRASH("Bad sign extension");
1103 }
1104 }
1105 curBlock_->add(ins);
1106 return ins;
1107 }
1108
1109 MDefinition* convertI64ToFloatingPoint(MDefinition* op, MIRType type,
1110 bool isUnsigned) {
1111 if (inDeadCode()) {
1112 return nullptr;
1113 }
1114 #if defined(JS_CODEGEN_ARM)
1115 auto* ins = MBuiltinInt64ToFloatingPoint::New(
1116 alloc(), op, instancePointer_, type, bytecodeOffset(), isUnsigned);
1117 #else
1118 auto* ins = MInt64ToFloatingPoint::New(alloc(), op, type, bytecodeOffset(),
1119 isUnsigned);
1120 #endif
1121 curBlock_->add(ins);
1122 return ins;
1123 }
1124
1125 MDefinition* rotate(MDefinition* input, MDefinition* count, MIRType type,
1126 bool left) {
1127 if (inDeadCode()) {
1128 return nullptr;
1129 }
1130 auto* ins = MRotate::New(alloc(), input, count, type, left);
1131 curBlock_->add(ins);
1132 return ins;
1133 }
1134
1135 template <class T>
1136 MDefinition* truncate(MDefinition* op, TruncFlags flags) {
1137 if (inDeadCode()) {
1138 return nullptr;
1139 }
1140 auto* ins = T::New(alloc(), op, flags, trapSiteDesc());
1141 curBlock_->add(ins);
1142 return ins;
1143 }
1144
1145 #if defined(JS_CODEGEN_ARM)
1146 MDefinition* truncateWithInstance(MDefinition* op, TruncFlags flags) {
1147 if (inDeadCode()) {
1148 return nullptr;
1149 }
1150 auto* ins = MWasmBuiltinTruncateToInt64::New(alloc(), op, instancePointer_,
1151 flags, trapSiteDesc());
1152 curBlock_->add(ins);
1153 return ins;
1154 }
1155 #endif
1156
1157 MDefinition* compare(MDefinition* lhs, MDefinition* rhs, JSOp op,
1158 MCompare::CompareType type) {
1159 if (inDeadCode()) {
1160 return nullptr;
1161 }
1162 auto* ins = MCompare::NewWasm(alloc(), lhs, rhs, op, type);
1163 curBlock_->add(ins);
1164 return ins;
1165 }
1166
1167 void assign(unsigned slot, MDefinition* def) {
1168 if (inDeadCode()) {
1169 return;
1170 }
1171 curBlock_->setSlot(info().localSlot(slot), def);
1172 }
1173
1174 MDefinition* compareIsNull(MDefinition* ref, JSOp compareOp) {
1175 MDefinition* nullVal = constantNullRef(MaybeRefType());
1176 if (!nullVal) {
1177 return nullptr;
1178 }
1179 return compare(ref, nullVal, compareOp, MCompare::Compare_WasmAnyRef);
1180 }
1181
1182 [[nodiscard]] MDefinition* refAsNonNull(MDefinition* ref) {
1183 MOZ_ASSERT(!inDeadCode());
1184 auto* ins = MWasmRefAsNonNull::New(alloc(), ref, trapSiteDesc());
1185 if (!ins) {
1186 return nullptr;
1187 }
1188 curBlock_->add(ins);
1189 return ins;
1190 }
1191
1192 [[nodiscard]] bool brOnNull(uint32_t relativeDepth, const DefVector& values,
1193 const ResultType& type, MDefinition* condition) {
1194 if (inDeadCode()) {
1195 return true;
1196 }
1197
1198 MBasicBlock* fallthroughBlock = nullptr;
1199 if (!newBlock(curBlock_, &fallthroughBlock)) {
1200 return false;
1201 }
1202
1203 MDefinition* check = compareIsNull(condition, JSOp::Eq);
1204 if (!check) {
1205 return false;
1206 }
1207 MTest* test = MTest::New(alloc(), check, nullptr, fallthroughBlock);
1208 if (!test ||
1209 !addControlFlowPatch(test, relativeDepth, MTest::TrueBranchIndex)) {
1210 return false;
1211 }
1212
1213 if (!pushDefs(values)) {
1214 return false;
1215 }
1216
1217 curBlock_->end(test);
1218 curBlock_ = fallthroughBlock;
1219 return true;
1220 }
1221
1222 [[nodiscard]] bool brOnNonNull(uint32_t relativeDepth,
1223 const DefVector& values,
1224 const ResultType& type,
1225 MDefinition* condition) {
1226 if (inDeadCode()) {
1227 return true;
1228 }
1229
1230 MBasicBlock* fallthroughBlock = nullptr;
1231 if (!newBlock(curBlock_, &fallthroughBlock)) {
1232 return false;
1233 }
1234
1235 MDefinition* check = compareIsNull(condition, JSOp::Ne);
1236 if (!check) {
1237 return false;
1238 }
1239 MTest* test = MTest::New(alloc(), check, nullptr, fallthroughBlock);
1240 if (!test ||
1241 !addControlFlowPatch(test, relativeDepth, MTest::TrueBranchIndex)) {
1242 return false;
1243 }
1244
1245 if (!pushDefs(values)) {
1246 return false;
1247 }
1248
1249 curBlock_->end(test);
1250 curBlock_ = fallthroughBlock;
1251 return true;
1252 }
1253
1254 MDefinition* refI31(MDefinition* input) {
1255 auto* ins = MWasmNewI31Ref::New(alloc(), input);
1256 curBlock_->add(ins);
1257 return ins;
1258 }
1259
1260 MDefinition* i31Get(MDefinition* input, FieldWideningOp wideningOp) {
1261 auto* ins = MWasmI31RefGet::New(alloc(), input, wideningOp);
1262 curBlock_->add(ins);
1263 return ins;
1264 }
1265
1266 #ifdef ENABLE_WASM_SIMD
1267 // About Wasm SIMD as supported by Ion:
1268 //
1269 // The expectation is that Ion will only ever support SIMD on x86 and x64,
1270 // since ARMv7 will cease to be a tier-1 platform soon, and MIPS64 will never
1271 // implement SIMD.
1272 //
1273 // The division of the operations into MIR nodes reflects that expectation,
1274 // and is a good fit for x86/x64. Should the expectation change we'll
1275 // possibly want to re-architect the SIMD support to be a little more general.
1276 //
1277 // Most SIMD operations map directly to a single MIR node that ultimately ends
1278 // up being expanded in the macroassembler.
1279 //
1280 // Some SIMD operations that do have a complete macroassembler expansion are
1281 // open-coded into multiple MIR nodes here; in some cases that's just
1282 // convenience, in other cases it may also allow them to benefit from Ion
1283 // optimizations. The reason for the expansions will be documented by a
1284 // comment.
1285
1286 // (v128,v128) -> v128 effect-free binary operations
1287 MDefinition* binarySimd128(MDefinition* lhs, MDefinition* rhs,
1288 bool commutative, SimdOp op) {
1289 if (inDeadCode()) {
1290 return nullptr;
1291 }
1292
1293 MOZ_ASSERT(lhs->type() == MIRType::Simd128 &&
1294 rhs->type() == MIRType::Simd128);
1295
1296 auto* ins = MWasmBinarySimd128::New(alloc(), lhs, rhs, commutative, op);
1297 curBlock_->add(ins);
1298 return ins;
1299 }
1300
1301 // (v128,i32) -> v128 effect-free shift operations
1302 MDefinition* shiftSimd128(MDefinition* lhs, MDefinition* rhs, SimdOp op) {
1303 if (inDeadCode()) {
1304 return nullptr;
1305 }
1306
1307 MOZ_ASSERT(lhs->type() == MIRType::Simd128 &&
1308 rhs->type() == MIRType::Int32);
1309
1310 int32_t maskBits;
1311 if (MacroAssembler::MustMaskShiftCountSimd128(op, &maskBits)) {
1312 MDefinition* mask = constantI32(maskBits);
1313 auto* rhs2 = MBitAnd::New(alloc(), rhs, mask, MIRType::Int32);
1314 curBlock_->add(rhs2);
1315 rhs = rhs2;
1316 }
1317
1318 auto* ins = MWasmShiftSimd128::New(alloc(), lhs, rhs, op);
1319 curBlock_->add(ins);
1320 return ins;
1321 }
1322
1323 // (v128,scalar,imm) -> v128
1324 MDefinition* replaceLaneSimd128(MDefinition* lhs, MDefinition* rhs,
1325 uint32_t laneIndex, SimdOp op) {
1326 if (inDeadCode()) {
1327 return nullptr;
1328 }
1329
1330 MOZ_ASSERT(lhs->type() == MIRType::Simd128);
1331
1332 auto* ins = MWasmReplaceLaneSimd128::New(alloc(), lhs, rhs, laneIndex, op);
1333 curBlock_->add(ins);
1334 return ins;
1335 }
1336
1337 // (scalar) -> v128 effect-free unary operations
1338 MDefinition* scalarToSimd128(MDefinition* src, SimdOp op) {
1339 if (inDeadCode()) {
1340 return nullptr;
1341 }
1342
1343 auto* ins = MWasmScalarToSimd128::New(alloc(), src, op);
1344 curBlock_->add(ins);
1345 return ins;
1346 }
1347
1348 // (v128) -> v128 effect-free unary operations
1349 MDefinition* unarySimd128(MDefinition* src, SimdOp op) {
1350 if (inDeadCode()) {
1351 return nullptr;
1352 }
1353
1354 MOZ_ASSERT(src->type() == MIRType::Simd128);
1355 auto* ins = MWasmUnarySimd128::New(alloc(), src, op);
1356 curBlock_->add(ins);
1357 return ins;
1358 }
1359
1360 // (v128, imm) -> scalar effect-free unary operations
1361 MDefinition* reduceSimd128(MDefinition* src, SimdOp op, ValType outType,
1362 uint32_t imm = 0) {
1363 if (inDeadCode()) {
1364 return nullptr;
1365 }
1366
1367 MOZ_ASSERT(src->type() == MIRType::Simd128);
1368 auto* ins =
1369 MWasmReduceSimd128::New(alloc(), src, op, outType.toMIRType(), imm);
1370 curBlock_->add(ins);
1371 return ins;
1372 }
1373
1374 // (v128, v128, v128) -> v128 effect-free operations
1375 MDefinition* ternarySimd128(MDefinition* v0, MDefinition* v1, MDefinition* v2,
1376 SimdOp op) {
1377 if (inDeadCode()) {
1378 return nullptr;
1379 }
1380
1381 MOZ_ASSERT(v0->type() == MIRType::Simd128 &&
1382 v1->type() == MIRType::Simd128 &&
1383 v2->type() == MIRType::Simd128);
1384
1385 auto* ins = MWasmTernarySimd128::New(alloc(), v0, v1, v2, op);
1386 curBlock_->add(ins);
1387 return ins;
1388 }
1389
1390 // (v128, v128, imm_v128) -> v128 effect-free operations
1391 MDefinition* shuffleSimd128(MDefinition* v1, MDefinition* v2, V128 control) {
1392 if (inDeadCode()) {
1393 return nullptr;
1394 }
1395
1396 MOZ_ASSERT(v1->type() == MIRType::Simd128);
1397 MOZ_ASSERT(v2->type() == MIRType::Simd128);
1398 auto* ins = BuildWasmShuffleSimd128(
1399 alloc(), reinterpret_cast<int8_t*>(control.bytes), v1, v2);
1400 curBlock_->add(ins);
1401 return ins;
1402 }
1403
1404 // Also see below for SIMD memory references
1405
1406 #endif // ENABLE_WASM_SIMD
1407
1408 /************************************************ Linear memory accesses */
1409
1410 // For detailed information about memory accesses, see "Linear memory
1411 // addresses and bounds checking" in WasmMemory.cpp.
1412
1413 private:
1414 // If the platform does not have a HeapReg, load the memory base from
1415 // instance.
1416 MDefinition* maybeLoadMemoryBase(uint32_t memoryIndex) {
1417 #ifdef WASM_HAS_HEAPREG
1418 if (memoryIndex == 0) {
1419 return nullptr;
1420 }
1421 #endif
1422 return memoryBase(memoryIndex);
1423 }
1424
1425 public:
1426 // A value holding the memory base, whether that's HeapReg or some other
1427 // register.
1428 MDefinition* memoryBase(uint32_t memoryIndex) {
1429 AliasSet aliases = !codeMeta().memories[memoryIndex].canMovingGrow()
1430 ? AliasSet::None()
1431 : AliasSet::Load(AliasSet::WasmHeapMeta);
1432 #ifdef WASM_HAS_HEAPREG
1433 if (memoryIndex == 0) {
1434 MWasmHeapReg* base = MWasmHeapReg::New(alloc(), aliases);
1435 curBlock_->add(base);
1436 return base;
1437 }
1438 #endif
1439 uint32_t offset =
1440 memoryIndex == 0
1441 ? Instance::offsetOfMemory0Base()
1442 : (Instance::offsetInData(
1443 codeMeta().offsetOfMemoryInstanceData(memoryIndex) +
1444 offsetof(MemoryInstanceData, base)));
1445 MWasmLoadInstance* base = MWasmLoadInstance::New(
1446 alloc(), instancePointer_, offset, MIRType::Pointer, aliases);
1447 curBlock_->add(base);
1448 return base;
1449 }
1450
1451 private:
1452 // If the bounds checking strategy requires it, load the bounds check limit
1453 // from the instance.
1454 MWasmLoadInstance* maybeLoadBoundsCheckLimit(uint32_t memoryIndex,
1455 MIRType type) {
1456 MOZ_ASSERT(type == MIRType::Int32 || type == MIRType::Int64);
1457 if (codeMeta().hugeMemoryEnabled(memoryIndex)) {
1458 return nullptr;
1459 }
1460 uint32_t offset =
1461 memoryIndex == 0
1462 ? Instance::offsetOfMemory0BoundsCheckLimit()
1463 : (Instance::offsetInData(
1464 codeMeta().offsetOfMemoryInstanceData(memoryIndex) +
1465 offsetof(MemoryInstanceData, boundsCheckLimit)));
1466 AliasSet aliases = !codeMeta().memories[memoryIndex].canMovingGrow()
1467 ? AliasSet::None()
1468 : AliasSet::Load(AliasSet::WasmHeapMeta);
1469 auto* load = MWasmLoadInstance::New(alloc(), instancePointer_, offset, type,
1470 aliases);
1471 curBlock_->add(load);
1472 return load;
1473 }
1474
1475 MDefinition* maybeCanonicalizeNaN(Scalar::Type accessType,
1476 MDefinition* value) {
1477 MOZ_ASSERT(codeMeta().isAsmJS());
1478
1479 // Canonicalize floating point values for differential testing.
1480 if (Scalar::isFloatingType(accessType) &&
1481 js::SupportDifferentialTesting()) {
1482 auto* canonicalize = MCanonicalizeNaN::New(alloc(), value);
1483 curBlock_->add(canonicalize);
1484 return canonicalize;
1485 }
1486 return value;
1487 }
1488
1489 // Return true if the access requires an alignment check. If so, sets
1490 // *mustAdd to true if the offset must be added to the pointer before
1491 // checking.
1492 bool needAlignmentCheck(MemoryAccessDesc* access, MDefinition* base,
1493 bool* mustAdd) {
1494 MOZ_ASSERT(!*mustAdd);
1495
1496 // asm.js accesses are always aligned and need no checks.
1497 if (codeMeta().isAsmJS() || !access->isAtomic()) {
1498 return false;
1499 }
1500
1501 // If the EA is known and aligned it will need no checks.
1502 if (base->isConstant()) {
1503 // We only care about the low bits, so overflow is OK, as is chopping off
1504 // the high bits of an i64 pointer.
1505 uint32_t ptr = 0;
1506 if (isMem64(access->memoryIndex())) {
1507 ptr = uint32_t(base->toConstant()->toInt64());
1508 } else {
1509 ptr = base->toConstant()->toInt32();
1510 }
1511 if (((ptr + access->offset64()) & (access->byteSize() - 1)) == 0) {
1512 return false;
1513 }
1514 }
1515
1516 // If the offset is aligned then the EA is just the pointer, for
1517 // the purposes of this check.
1518 *mustAdd = (access->offset64() & (access->byteSize() - 1)) != 0;
1519 return true;
1520 }
1521
1522 // Fold a constant base into the offset and make the base 0, provided the
1523 // offset stays below the guard limit. The reason for folding the base into
1524 // the offset rather than vice versa is that a small offset can be ignored
1525 // by both explicit bounds checking and bounds check elimination.
1526 void foldConstantPointer(MemoryAccessDesc* access, MDefinition** base) {
1527 uint64_t offsetGuardLimit = GetMaxOffsetGuardLimit(
1528 codeMeta().hugeMemoryEnabled(access->memoryIndex()));
1529
1530 if ((*base)->isConstant()) {
1531 uint64_t basePtr = 0;
1532 if (isMem64(access->memoryIndex())) {
1533 basePtr = uint64_t((*base)->toConstant()->toInt64());
1534 } else {
1535 basePtr = uint64_t(int64_t((*base)->toConstant()->toInt32()));
1536 }
1537
1538 uint64_t offset = access->offset64();
1539 if (offset < offsetGuardLimit && basePtr < offsetGuardLimit - offset) {
1540 offset += basePtr;
1541 access->setOffset32(uint32_t(offset));
1542 *base = isMem64(access->memoryIndex()) ? constantI64(int64_t(0))
1543 : constantI32(0);
1544 }
1545 }
1546 }
1547
1548 // If the offset must be added because it is large or because the true EA must
1549 // be checked, compute the effective address, trapping on overflow.
1550 void maybeComputeEffectiveAddress(MemoryAccessDesc* access,
1551 MDefinition** base, bool mustAddOffset) {
1552 uint64_t offsetGuardLimit = GetMaxOffsetGuardLimit(
1553 codeMeta().hugeMemoryEnabled(access->memoryIndex()));
1554
1555 if (access->offset64() >= offsetGuardLimit ||
1556 access->offset64() > UINT32_MAX || mustAddOffset ||
1557 !JitOptions.wasmFoldOffsets) {
1558 *base = computeEffectiveAddress(*base, access);
1559 }
1560 }
1561
1562 MWasmLoadInstance* needBoundsCheck(uint32_t memoryIndex) {
1563 #ifdef JS_64BIT
1564 // For 32-bit base pointers:
1565 //
1566 // If the bounds check uses the full 64 bits of the bounds check limit, then
1567 // the base pointer must be zero-extended to 64 bits before checking and
1568 // wrapped back to 32-bits after Spectre masking. (And it's important that
1569 // the value we end up with has flowed through the Spectre mask.)
1570 //
1571 // If the memory's max size is known to be smaller than 64K pages exactly,
1572 // we can use a 32-bit check and avoid extension and wrapping.
1573 static_assert(0x100000000 % PageSize == 0);
1574 bool mem32LimitIs64Bits =
1575 isMem32(memoryIndex) &&
1576 !codeMeta().memories[memoryIndex].boundsCheckLimitIs32Bits() &&
1577 MaxMemoryPages(codeMeta().memories[memoryIndex].addressType()) >=
1578 Pages(0x100000000 / PageSize);
1579 #else
1580 // On 32-bit platforms we have no more than 2GB memory and the limit for a
1581 // 32-bit base pointer is never a 64-bit value.
1582 bool mem32LimitIs64Bits = false;
1583 #endif
1584 return maybeLoadBoundsCheckLimit(memoryIndex,
1585 mem32LimitIs64Bits || isMem64(memoryIndex)
1586 ? MIRType::Int64
1587 : MIRType::Int32);
1588 }
1589
1590 void performBoundsCheck(uint32_t memoryIndex, MDefinition** base,
1591 MWasmLoadInstance* boundsCheckLimit) {
1592 // At the outset, actualBase could be the result of pretty much any integer
1593 // operation, or it could be the load of an integer constant. If its type
1594 // is i32, we may assume the value has a canonical representation for the
1595 // platform, see doc block in MacroAssembler.h.
1596 MDefinition* actualBase = *base;
1597
1598 // Extend an i32 index value to perform a 64-bit bounds check if the memory
1599 // can be 4GB or larger.
1600 bool extendAndWrapIndex =
1601 isMem32(memoryIndex) && boundsCheckLimit->type() == MIRType::Int64;
1602 if (extendAndWrapIndex) {
1603 auto* extended = MWasmExtendU32Index::New(alloc(), actualBase);
1604 curBlock_->add(extended);
1605 actualBase = extended;
1606 }
1607
1608 auto target = memoryIndex == 0 ? MWasmBoundsCheck::Memory0
1609 : MWasmBoundsCheck::Unknown;
1610 auto* ins = MWasmBoundsCheck::New(alloc(), actualBase, boundsCheckLimit,
1611 trapSiteDesc(), target);
1612 curBlock_->add(ins);
1613 actualBase = ins;
1614
1615 // If we're masking, then we update *base to create a dependency chain
1616 // through the masked index. But we will first need to wrap the index
1617 // value if it was extended above.
1618 if (JitOptions.spectreIndexMasking) {
1619 if (extendAndWrapIndex) {
1620 auto* wrapped = MWasmWrapU32Index::New(alloc(), actualBase);
1621 curBlock_->add(wrapped);
1622 actualBase = wrapped;
1623 }
1624 *base = actualBase;
1625 }
1626 }
1627
1628 // Perform all necessary checking before a wasm heap access, based on the
1629 // attributes of the access and base pointer.
1630 //
1631 // For 64-bit indices on platforms that are limited to indices that fit into
1632 // 32 bits (all 32-bit platforms and mips64), this returns a bounds-checked
1633 // `base` that has type Int32. Lowering code depends on this and will assert
1634 // that the base has this type. See the end of this function.
1635
1636 void checkOffsetAndAlignmentAndBounds(MemoryAccessDesc* access,
1637 MDefinition** base) {
1638 MOZ_ASSERT(!inDeadCode());
1639 MOZ_ASSERT(!codeMeta().isAsmJS());
1640
1641 // Attempt to fold a constant base pointer into the offset so as to simplify
1642 // the addressing expression. This may update *base.
1643 foldConstantPointer(access, base);
1644
1645 // Determine whether an alignment check is needed and whether the offset
1646 // must be checked too.
1647 bool mustAddOffsetForAlignmentCheck = false;
1648 bool alignmentCheck =
1649 needAlignmentCheck(access, *base, &mustAddOffsetForAlignmentCheck);
1650
1651 // If bounds checking or alignment checking requires it, compute the
1652 // effective address: add the offset into the pointer and trap on overflow.
1653 // This may update *base.
1654 maybeComputeEffectiveAddress(access, base, mustAddOffsetForAlignmentCheck);
1655
1656 // Emit the alignment check if necessary; it traps if it fails.
1657 if (alignmentCheck) {
1658 curBlock_->add(MWasmAlignmentCheck::New(
1659 alloc(), *base, access->byteSize(), trapSiteDesc()));
1660 }
1661
1662 // Emit the bounds check if necessary; it traps if it fails. This may
1663 // update *base.
1664 MWasmLoadInstance* boundsCheckLimit =
1665 needBoundsCheck(access->memoryIndex());
1666 if (boundsCheckLimit) {
1667 performBoundsCheck(access->memoryIndex(), base, boundsCheckLimit);
1668 }
1669
1670 #ifndef JS_64BIT
1671 if (isMem64(access->memoryIndex())) {
1672 // We must have had an explicit bounds check (or one was elided if it was
1673 // proved redundant), and on 32-bit systems the index will for sure fit in
1674 // 32 bits: the max memory is 2GB. So chop the index down to 32-bit to
1675 // simplify the back-end.
1676 MOZ_ASSERT((*base)->type() == MIRType::Int64);
1677 MOZ_ASSERT(!codeMeta().hugeMemoryEnabled(access->memoryIndex()));
1678 auto* chopped = MWasmWrapU32Index::New(alloc(), *base);
1679 MOZ_ASSERT(chopped->type() == MIRType::Int32);
1680 curBlock_->add(chopped);
1681 *base = chopped;
1682 }
1683 #endif
1684 }
1685
1686 bool isSmallerAccessForI64(ValType result, const MemoryAccessDesc* access) {
1687 if (result == ValType::I64 && access->byteSize() <= 4) {
1688 // These smaller accesses should all be zero-extending.
1689 MOZ_ASSERT(!isSignedIntType(access->type()));
1690 return true;
1691 }
1692 return false;
1693 }
1694
1695 public:
1696 bool isMem32(uint32_t memoryIndex) {
1697 return codeMeta().memories[memoryIndex].addressType() == AddressType::I32;
1698 }
1699 bool isMem64(uint32_t memoryIndex) {
1700 return codeMeta().memories[memoryIndex].addressType() == AddressType::I64;
1701 }
1702 bool hugeMemoryEnabled(uint32_t memoryIndex) {
1703 return codeMeta().hugeMemoryEnabled(memoryIndex);
1704 }
1705
1706 // Add the offset into the pointer to yield the EA; trap on overflow. Clears
1707 // the offset on the memory access as a result.
1708 MDefinition* computeEffectiveAddress(MDefinition* base,
1709 MemoryAccessDesc* access) {
1710 if (inDeadCode()) {
1711 return nullptr;
1712 }
1713 uint64_t offset = access->offset64();
1714 if (offset == 0) {
1715 return base;
1716 }
1717 auto* ins = MWasmAddOffset::New(alloc(), base, offset, trapSiteDesc());
1718 curBlock_->add(ins);
1719 access->clearOffset();
1720 return ins;
1721 }
1722
1723 MDefinition* load(MDefinition* base, MemoryAccessDesc* access,
1724 ValType result) {
1725 if (inDeadCode()) {
1726 return nullptr;
1727 }
1728
1729 MDefinition* memoryBase = maybeLoadMemoryBase(access->memoryIndex());
1730 MInstruction* load = nullptr;
1731 if (codeMeta().isAsmJS()) {
1732 MOZ_ASSERT(access->offset64() == 0);
1733 MWasmLoadInstance* boundsCheckLimit =
1734 maybeLoadBoundsCheckLimit(access->memoryIndex(), MIRType::Int32);
1735 load = MAsmJSLoadHeap::New(alloc(), memoryBase, base, boundsCheckLimit,
1736 access->type());
1737 } else {
1738 checkOffsetAndAlignmentAndBounds(access, &base);
1739 #ifndef JS_64BIT
1740 MOZ_ASSERT(base->type() == MIRType::Int32);
1741 #endif
1742 load = MWasmLoad::New(alloc(), memoryBase, base, *access,
1743 result.toMIRType());
1744 }
1745 if (!load) {
1746 return nullptr;
1747 }
1748 curBlock_->add(load);
1749 return load;
1750 }
1751
1752 void store(MDefinition* base, MemoryAccessDesc* access, MDefinition* v) {
1753 if (inDeadCode()) {
1754 return;
1755 }
1756
1757 MDefinition* memoryBase = maybeLoadMemoryBase(access->memoryIndex());
1758 MInstruction* store = nullptr;
1759 if (codeMeta().isAsmJS()) {
1760 MOZ_ASSERT(access->offset64() == 0);
1761 MWasmLoadInstance* boundsCheckLimit =
1762 maybeLoadBoundsCheckLimit(access->memoryIndex(), MIRType::Int32);
1763 v = maybeCanonicalizeNaN(access->type(), v);
1764 store = MAsmJSStoreHeap::New(alloc(), memoryBase, base, boundsCheckLimit,
1765 access->type(), v);
1766 } else {
1767 checkOffsetAndAlignmentAndBounds(access, &base);
1768 #ifndef JS_64BIT
1769 MOZ_ASSERT(base->type() == MIRType::Int32);
1770 #endif
1771 store = MWasmStore::New(alloc(), memoryBase, base, *access, v);
1772 }
1773 if (!store) {
1774 return;
1775 }
1776 curBlock_->add(store);
1777 }
1778
1779 MDefinition* atomicCompareExchangeHeap(MDefinition* base,
1780 MemoryAccessDesc* access,
1781 ValType result, MDefinition* oldv,
1782 MDefinition* newv) {
1783 if (inDeadCode()) {
1784 return nullptr;
1785 }
1786
1787 checkOffsetAndAlignmentAndBounds(access, &base);
1788 #ifndef JS_64BIT
1789 MOZ_ASSERT(base->type() == MIRType::Int32);
1790 #endif
1791
1792 if (isSmallerAccessForI64(result, access)) {
1793 auto* cvtOldv =
1794 MWrapInt64ToInt32::New(alloc(), oldv, /*bottomHalf=*/true);
1795 curBlock_->add(cvtOldv);
1796 oldv = cvtOldv;
1797
1798 auto* cvtNewv =
1799 MWrapInt64ToInt32::New(alloc(), newv, /*bottomHalf=*/true);
1800 curBlock_->add(cvtNewv);
1801 newv = cvtNewv;
1802 }
1803
1804 MDefinition* memoryBase = maybeLoadMemoryBase(access->memoryIndex());
1805 MInstruction* cas = MWasmCompareExchangeHeap::New(
1806 alloc(), bytecodeOffset(), memoryBase, base, *access, oldv, newv,
1807 instancePointer_);
1808 if (!cas) {
1809 return nullptr;
1810 }
1811 curBlock_->add(cas);
1812
1813 if (isSmallerAccessForI64(result, access)) {
1814 cas = MExtendInt32ToInt64::New(alloc(), cas, true);
1815 curBlock_->add(cas);
1816 }
1817
1818 return cas;
1819 }
1820
1821 MDefinition* atomicExchangeHeap(MDefinition* base, MemoryAccessDesc* access,
1822 ValType result, MDefinition* value) {
1823 if (inDeadCode()) {
1824 return nullptr;
1825 }
1826
1827 checkOffsetAndAlignmentAndBounds(access, &base);
1828 #ifndef JS_64BIT
1829 MOZ_ASSERT(base->type() == MIRType::Int32);
1830 #endif
1831
1832 if (isSmallerAccessForI64(result, access)) {
1833 auto* cvtValue =
1834 MWrapInt64ToInt32::New(alloc(), value, /*bottomHalf=*/true);
1835 curBlock_->add(cvtValue);
1836 value = cvtValue;
1837 }
1838
1839 MDefinition* memoryBase = maybeLoadMemoryBase(access->memoryIndex());
1840 MInstruction* xchg =
1841 MWasmAtomicExchangeHeap::New(alloc(), bytecodeOffset(), memoryBase,
1842 base, *access, value, instancePointer_);
1843 if (!xchg) {
1844 return nullptr;
1845 }
1846 curBlock_->add(xchg);
1847
1848 if (isSmallerAccessForI64(result, access)) {
1849 xchg = MExtendInt32ToInt64::New(alloc(), xchg, true);
1850 curBlock_->add(xchg);
1851 }
1852
1853 return xchg;
1854 }
1855
1856 MDefinition* atomicBinopHeap(AtomicOp op, MDefinition* base,
1857 MemoryAccessDesc* access, ValType result,
1858 MDefinition* value) {
1859 if (inDeadCode()) {
1860 return nullptr;
1861 }
1862
1863 checkOffsetAndAlignmentAndBounds(access, &base);
1864 #ifndef JS_64BIT
1865 MOZ_ASSERT(base->type() == MIRType::Int32);
1866 #endif
1867
1868 if (isSmallerAccessForI64(result, access)) {
1869 auto* cvtValue =
1870 MWrapInt64ToInt32::New(alloc(), value, /*bottomHalf=*/true);
1871 curBlock_->add(cvtValue);
1872 value = cvtValue;
1873 }
1874
1875 MDefinition* memoryBase = maybeLoadMemoryBase(access->memoryIndex());
1876 MInstruction* binop =
1877 MWasmAtomicBinopHeap::New(alloc(), bytecodeOffset(), op, memoryBase,
1878 base, *access, value, instancePointer_);
1879 if (!binop) {
1880 return nullptr;
1881 }
1882 curBlock_->add(binop);
1883
1884 if (isSmallerAccessForI64(result, access)) {
1885 binop = MExtendInt32ToInt64::New(alloc(), binop, true);
1886 curBlock_->add(binop);
1887 }
1888
1889 return binop;
1890 }
1891
1892 #ifdef ENABLE_WASM_SIMD
1893 MDefinition* loadSplatSimd128(Scalar::Type viewType,
1894 const LinearMemoryAddress<MDefinition*>& addr,
1895 wasm::SimdOp splatOp) {
1896 if (inDeadCode()) {
1897 return nullptr;
1898 }
1899
1900 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
1901 trapSiteDesc(),
1902 hugeMemoryEnabled(addr.memoryIndex));
1903
1904 // Generate better code (on x86)
1905 // If AVX2 is enabled, more broadcast operators are available.
1906 if (viewType == Scalar::Float64
1907 # if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86)
1908 || (js::jit::CPUInfo::IsAVX2Present() &&
1909 (viewType == Scalar::Uint8 || viewType == Scalar::Uint16 ||
1910 viewType == Scalar::Float32))
1911 # endif
1912 ) {
1913 access.setSplatSimd128Load();
1914 return load(addr.base, &access, ValType::V128);
1915 }
1916
1917 ValType resultType = ValType::I32;
1918 if (viewType == Scalar::Float32) {
1919 resultType = ValType::F32;
1920 splatOp = wasm::SimdOp::F32x4Splat;
1921 }
1922 auto* scalar = load(addr.base, &access, resultType);
1923 if (!inDeadCode() && !scalar) {
1924 return nullptr;
1925 }
1926 return scalarToSimd128(scalar, splatOp);
1927 }
1928
1929 MDefinition* loadExtendSimd128(const LinearMemoryAddress<MDefinition*>& addr,
1930 wasm::SimdOp op) {
1931 if (inDeadCode()) {
1932 return nullptr;
1933 }
1934
1935 // Generate better code (on x86) by loading as a double with an
1936 // operation that sign extends directly.
1937 MemoryAccessDesc access(addr.memoryIndex, Scalar::Float64, addr.align,
1938 addr.offset, trapSiteDesc(),
1939 hugeMemoryEnabled(addr.memoryIndex));
1940 access.setWidenSimd128Load(op);
1941 return load(addr.base, &access, ValType::V128);
1942 }
1943
1944 MDefinition* loadZeroSimd128(Scalar::Type viewType, size_t numBytes,
1945 const LinearMemoryAddress<MDefinition*>& addr) {
1946 if (inDeadCode()) {
1947 return nullptr;
1948 }
1949
1950 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
1951 trapSiteDesc(),
1952 hugeMemoryEnabled(addr.memoryIndex));
1953 access.setZeroExtendSimd128Load();
1954 return load(addr.base, &access, ValType::V128);
1955 }
1956
1957 MDefinition* loadLaneSimd128(uint32_t laneSize,
1958 const LinearMemoryAddress<MDefinition*>& addr,
1959 uint32_t laneIndex, MDefinition* src) {
1960 if (inDeadCode()) {
1961 return nullptr;
1962 }
1963
1964 MemoryAccessDesc access(addr.memoryIndex, Scalar::Simd128, addr.align,
1965 addr.offset, trapSiteDesc(),
1966 hugeMemoryEnabled(addr.memoryIndex));
1967 MDefinition* memoryBase = maybeLoadMemoryBase(access.memoryIndex());
1968 MDefinition* base = addr.base;
1969 MOZ_ASSERT(!codeMeta().isAsmJS());
1970 checkOffsetAndAlignmentAndBounds(&access, &base);
1971 # ifndef JS_64BIT
1972 MOZ_ASSERT(base->type() == MIRType::Int32);
1973 # endif
1974 MInstruction* load = MWasmLoadLaneSimd128::New(
1975 alloc(), memoryBase, base, access, laneSize, laneIndex, src);
1976 if (!load) {
1977 return nullptr;
1978 }
1979 curBlock_->add(load);
1980 return load;
1981 }
1982
1983 void storeLaneSimd128(uint32_t laneSize,
1984 const LinearMemoryAddress<MDefinition*>& addr,
1985 uint32_t laneIndex, MDefinition* src) {
1986 if (inDeadCode()) {
1987 return;
1988 }
1989 MemoryAccessDesc access(addr.memoryIndex, Scalar::Simd128, addr.align,
1990 addr.offset, trapSiteDesc(),
1991 hugeMemoryEnabled(addr.memoryIndex));
1992 MDefinition* memoryBase = maybeLoadMemoryBase(access.memoryIndex());
1993 MDefinition* base = addr.base;
1994 MOZ_ASSERT(!codeMeta().isAsmJS());
1995 checkOffsetAndAlignmentAndBounds(&access, &base);
1996 # ifndef JS_64BIT
1997 MOZ_ASSERT(base->type() == MIRType::Int32);
1998 # endif
1999 MInstruction* store = MWasmStoreLaneSimd128::New(
2000 alloc(), memoryBase, base, access, laneSize, laneIndex, src);
2001 if (!store) {
2002 return;
2003 }
2004 curBlock_->add(store);
2005 }
2006 #endif // ENABLE_WASM_SIMD
2007
2008 /************************************************ Global variable accesses */
2009
2010 MDefinition* loadGlobalVar(const GlobalDesc& global) {
2011 if (inDeadCode()) {
2012 return nullptr;
2013 }
2014
2015 MInstruction* load;
2016 if (global.isIndirect()) {
2017 // Pull a pointer to the value out of Instance::globalArea, then
2018 // load from that pointer. Note that the pointer is immutable
2019 // even though the value it points at may change, hence the use of
2020 // |true| for the first node's |isConst| value, irrespective of
2021 // the |isConst| formal parameter to this method. The latter
2022 // applies to the denoted value as a whole.
2023 auto* cellPtr = MWasmLoadInstanceDataField::New(
2024 alloc(), MIRType::Pointer, global.offset(),
2025 /*isConst=*/true, instancePointer_);
2026 curBlock_->add(cellPtr);
2027 load = MWasmLoadGlobalCell::New(alloc(), global.type().toMIRType(),
2028 cellPtr, global.type());
2029 } else {
2030 // Pull the value directly out of Instance::globalArea.
2031 load = MWasmLoadInstanceDataField::New(
2032 alloc(), global.type().toMIRType(), global.offset(),
2033 !global.isMutable(), instancePointer_,
2034 global.type().toMaybeRefType());
2035 }
2036 curBlock_->add(load);
2037 return load;
2038 }
2039
2040 [[nodiscard]] bool storeGlobalVar(uint32_t lineOrBytecode,
2041 const GlobalDesc& global, MDefinition* v) {
2042 if (inDeadCode()) {
2043 return true;
2044 }
2045
2046 if (global.isIndirect()) {
2047 // Pull a pointer to the value out of Instance::globalArea, then
2048 // store through that pointer.
2049 auto* valueAddr = MWasmLoadInstanceDataField::New(
2050 alloc(), MIRType::Pointer, global.offset(),
2051 /*isConstant=*/true, instancePointer_);
2052 curBlock_->add(valueAddr);
2053
2054 // Handle a store to a ref-typed field specially
2055 if (global.type().toMIRType() == MIRType::WasmAnyRef) {
2056 // Load the previous value for the post-write barrier
2057 MOZ_ASSERT(v->type() == MIRType::WasmAnyRef);
2058 auto* prevValue = MWasmLoadGlobalCell::New(alloc(), MIRType::WasmAnyRef,
2059 valueAddr, global.type());
2060 curBlock_->add(prevValue);
2061
2062 // Store the new value
2063 auto* store =
2064 MWasmStoreRef::New(alloc(), instancePointer_, valueAddr,
2065 /*valueOffset=*/0, v, AliasSet::WasmGlobalCell,
2066 WasmPreBarrierKind::Normal);
2067 curBlock_->add(store);
2068
2069 // Call the post-write barrier
2070 return postBarrierEdgePrecise(lineOrBytecode, valueAddr, prevValue);
2071 }
2072
2073 auto* store = MWasmStoreGlobalCell::New(alloc(), v, valueAddr);
2074 curBlock_->add(store);
2075 return true;
2076 }
2077 // Or else store the value directly in Instance::globalArea.
2078
2079 // Handle a store to a ref-typed field specially
2080 if (global.type().toMIRType() == MIRType::WasmAnyRef) {
2081 // Compute the address of the ref-typed global
2082 auto* valueAddr = MWasmDerivedPointer::New(
2083 alloc(), instancePointer_,
2084 wasm::Instance::offsetInData(global.offset()));
2085 curBlock_->add(valueAddr);
2086
2087 // Load the previous value for the post-write barrier
2088 MOZ_ASSERT(v->type() == MIRType::WasmAnyRef);
2089 auto* prevValue = MWasmLoadGlobalCell::New(alloc(), MIRType::WasmAnyRef,
2090 valueAddr, global.type());
2091 curBlock_->add(prevValue);
2092
2093 // Store the new value
2094 auto* store =
2095 MWasmStoreRef::New(alloc(), instancePointer_, valueAddr,
2096 /*valueOffset=*/0, v, AliasSet::WasmInstanceData,
2097 WasmPreBarrierKind::Normal);
2098 curBlock_->add(store);
2099
2100 // Call the post-write barrier
2101 return postBarrierEdgePrecise(lineOrBytecode, valueAddr, prevValue);
2102 }
2103
2104 auto* store = MWasmStoreInstanceDataField::New(alloc(), global.offset(), v,
2105 instancePointer_);
2106 curBlock_->add(store);
2107 return true;
2108 }
2109
2110 // Load the slot on the instance where the result of `ref.func` is cached.
2111 // This may be null if a function reference for this function has not been
2112 // asked for yet.
2113 MDefinition* loadCachedRefFunc(uint32_t funcIndex) {
2114 uint32_t exportedFuncIndex = codeMeta().findFuncExportIndex(funcIndex);
2115 MWasmLoadInstanceDataField* refFunc = MWasmLoadInstanceDataField::New(
2116 alloc(), MIRType::WasmAnyRef,
2117 codeMeta().offsetOfFuncExportInstanceData(exportedFuncIndex) +
2118 offsetof(FuncExportInstanceData, func),
2119 true, instancePointer_);
2120 curBlock_->add(refFunc);
2121 return refFunc;
2122 }
2123
2124 MDefinition* loadTableField(uint32_t tableIndex, unsigned fieldOffset,
2125 MIRType type) {
2126 uint32_t instanceDataOffset = wasm::Instance::offsetInData(
2127 codeMeta().offsetOfTableInstanceData(tableIndex) + fieldOffset);
2128 auto* load =
2129 MWasmLoadInstance::New(alloc(), instancePointer_, instanceDataOffset,
2130 type, AliasSet::Load(AliasSet::WasmTableMeta));
2131 curBlock_->add(load);
2132 return load;
2133 }
2134
2135 MDefinition* loadTableLength(uint32_t tableIndex) {
2136 return loadTableField(tableIndex, offsetof(TableInstanceData, length),
2137 MIRType::Int32);
2138 }
2139
2140 MDefinition* loadTableElements(uint32_t tableIndex) {
2141 return loadTableField(tableIndex, offsetof(TableInstanceData, elements),
2142 MIRType::Pointer);
2143 }
2144
2145 MDefinition* tableAddressToI32(AddressType addressType,
2146 MDefinition* address) {
2147 switch (addressType) {
2148 case AddressType::I32:
2149 return address;
2150 case AddressType::I64:
2151 auto* clamp = MWasmClampTable64Address::New(alloc(), address);
2152 if (!clamp) {
2153 return nullptr;
2154 }
2155 curBlock_->add(clamp);
2156 return clamp;
2157 }
2158 MOZ_CRASH("unknown address type");
2159 }
2160
2161 MDefinition* tableGetAnyRef(uint32_t tableIndex, MDefinition* address) {
2162 const TableDesc& table = codeMeta().tables[tableIndex];
2163
2164 // Load the table length and perform a bounds check with spectre index
2165 // masking
2166 auto* length = loadTableLength(tableIndex);
2167 auto* check = MWasmBoundsCheck::New(
2168 alloc(), address, length, trapSiteDesc(), MWasmBoundsCheck::Unknown);
2169 curBlock_->add(check);
2170 if (JitOptions.spectreIndexMasking) {
2171 address = check;
2172 }
2173
2174 // Load the table elements and load the element
2175 auto* elements = loadTableElements(tableIndex);
2176 auto* element =
2177 MWasmLoadTableElement::New(alloc(), elements, address, table.elemType);
2178 curBlock_->add(element);
2179 return element;
2180 }
2181
2182 [[nodiscard]] bool tableSetAnyRef(uint32_t tableIndex, MDefinition* address,
2183 MDefinition* value,
2184 uint32_t lineOrBytecode) {
2185 const TableDesc& table = codeMeta().tables[tableIndex];
2186
2187 // Load the table length and perform a bounds check with spectre index
2188 // masking
2189 auto* length = loadTableLength(tableIndex);
2190 auto* check = MWasmBoundsCheck::New(
2191 alloc(), address, length, trapSiteDesc(), MWasmBoundsCheck::Unknown);
2192 curBlock_->add(check);
2193 if (JitOptions.spectreIndexMasking) {
2194 address = check;
2195 }
2196
2197 // Load the table elements
2198 auto* elements = loadTableElements(tableIndex);
2199
2200 // Load the previous value
2201 auto* prevValue =
2202 MWasmLoadTableElement::New(alloc(), elements, address, table.elemType);
2203 curBlock_->add(prevValue);
2204
2205 // Compute the value's location for the post barrier
2206 auto* loc =
2207 MWasmDerivedIndexPointer::New(alloc(), elements, address, ScalePointer);
2208 curBlock_->add(loc);
2209
2210 // Store the new value
2211 auto* store = MWasmStoreRef::New(
2212 alloc(), instancePointer_, loc, /*valueOffset=*/0, value,
2213 AliasSet::WasmTableElement, WasmPreBarrierKind::Normal);
2214 curBlock_->add(store);
2215
2216 // Perform the post barrier
2217 return postBarrierEdgePrecise(lineOrBytecode, loc, prevValue);
2218 }
2219
2220 void addInterruptCheck() {
2221 if (inDeadCode()) {
2222 return;
2223 }
2224 curBlock_->add(
2225 MWasmInterruptCheck::New(alloc(), instancePointer_, trapSiteDesc()));
2226 }
2227
2228 // Perform a post-write barrier to update the generational store buffer. This
2229 // version stores the entire containing object (e.g. a struct) rather than a
2230 // single edge.
2231 [[nodiscard]] bool postBarrierWholeCell(uint32_t lineOrBytecode,
2232 MDefinition* object,
2233 MDefinition* newValue) {
2234 auto* barrier = MWasmPostWriteBarrierWholeCell::New(
2235 alloc(), instancePointer_, object, newValue);
2236 if (!barrier) {
2237 return false;
2238 }
2239 curBlock_->add(barrier);
2240 return true;
2241 }
2242
2243 // Perform a post-write barrier to update the generational store buffer. This
2244 // version tracks a single tenured -> nursery edge, and will remove a previous
2245 // store buffer entry if it is no longer needed.
2246 [[nodiscard]] bool postBarrierEdgePrecise(uint32_t lineOrBytecode,
2247 MDefinition* valueAddr,
2248 MDefinition* value) {
2249 return emitInstanceCall2(lineOrBytecode, SASigPostBarrierEdgePrecise,
2250 valueAddr, value);
2251 }
2252
2253 // Perform a post-write barrier to update the generational store buffer. This
2254 // version does not remove a previous store buffer entry if it is no longer
2255 // needed.
2256 [[nodiscard]] bool postBarrierEdgeAtIndex(uint32_t lineOrBytecode,
2257 MDefinition* object,
2258 MDefinition* valueBase,
2259 MDefinition* index, uint32_t scale,
2260 MDefinition* newValue) {
2261 auto* barrier = MWasmPostWriteBarrierEdgeAtIndex::New(
2262 alloc(), instancePointer_, object, valueBase, index, scale, newValue);
2263 if (!barrier) {
2264 return false;
2265 }
2266 curBlock_->add(barrier);
2267 return true;
2268 }
2269
2270 /***************************************************************** Calls */
2271
2272 // The IonMonkey backend maintains a single stack offset (from the stack
2273 // pointer to the base of the frame) by adding the total amount of spill
2274 // space required plus the maximum stack required for argument passing.
2275 // Since we do not use IonMonkey's MPrepareCall/MPassArg/MCall, we must
2276 // manually accumulate, for the entire function, the maximum required stack
2277 // space for argument passing. (This is passed to the CodeGenerator via
2278 // MIRGenerator::maxWasmStackArgBytes.) This is just be the maximum of the
2279 // stack space required for each individual call (as determined by the call
2280 // ABI).
2281
2282 [[nodiscard]]
2283 bool passInstanceCallArg(MIRType instanceType, CallCompileState* callState) {
2284 if (inDeadCode()) {
2285 return true;
2286 }
2287
2288 // Should only pass an instance once. And it must be a non-GC pointer.
2289 MOZ_ASSERT(callState->instanceArg == ABIArg());
2290 MOZ_ASSERT(instanceType == MIRType::Pointer);
2291 callState->instanceArg = callState->abi.next(MIRType::Pointer);
2292 return true;
2293 }
2294
2295 // Do not call this directly. Call one of the passCallArg() variants instead.
2296 [[nodiscard]]
2297 bool passCallArgWorker(MDefinition* argDef, MIRType type,
2298 CallCompileState* callState) {
2299 MOZ_ASSERT(argDef->type() == type);
2300
2301 ABIArg arg = callState->abi.next(type);
2302 switch (arg.kind()) {
2303 #ifdef JS_CODEGEN_REGISTER_PAIR
2304 case ABIArg::GPR_PAIR: {
2305 auto mirLow =
2306 MWrapInt64ToInt32::New(alloc(), argDef, /* bottomHalf = */ true);
2307 curBlock_->add(mirLow);
2308 auto mirHigh =
2309 MWrapInt64ToInt32::New(alloc(), argDef, /* bottomHalf = */ false);
2310 curBlock_->add(mirHigh);
2311 return callState->regArgs.append(
2312 MWasmCallBase::Arg(AnyRegister(arg.gpr64().low), mirLow)) &&
2313 callState->regArgs.append(
2314 MWasmCallBase::Arg(AnyRegister(arg.gpr64().high), mirHigh));
2315 }
2316 #endif
2317 case ABIArg::GPR:
2318 case ABIArg::FPU:
2319 return callState->regArgs.append(MWasmCallBase::Arg(arg.reg(), argDef));
2320 case ABIArg::Stack: {
2321 auto* mir =
2322 MWasmStackArg::New(alloc(), arg.offsetFromArgBase(), argDef);
2323 curBlock_->add(mir);
2324 return true;
2325 }
2326 case ABIArg::Uninitialized:
2327 MOZ_ASSERT_UNREACHABLE("Uninitialized ABIArg kind");
2328 }
2329 MOZ_CRASH("Unknown ABIArg kind.");
2330 }
2331
2332 template <typename VecT>
2333 [[nodiscard]]
2334 bool passCallArgs(const DefVector& argDefs, const VecT& types,
2335 CallCompileState* callState) {
2336 MOZ_ASSERT(argDefs.length() == types.length());
2337 for (uint32_t i = 0; i < argDefs.length(); i++) {
2338 MDefinition* def = argDefs[i];
2339 ValType type = types[i];
2340 if (!passCallArg(def, type, callState)) {
2341 return false;
2342 }
2343 }
2344 return true;
2345 }
2346
2347 [[nodiscard]]
2348 bool passCallArg(MDefinition* argDef, MIRType type,
2349 CallCompileState* callState) {
2350 if (inDeadCode()) {
2351 return true;
2352 }
2353 return passCallArgWorker(argDef, type, callState);
2354 }
2355
2356 [[nodiscard]]
2357 bool passCallArg(MDefinition* argDef, ValType type,
2358 CallCompileState* callState) {
2359 if (inDeadCode()) {
2360 return true;
2361 }
2362 return passCallArgWorker(argDef, type.toMIRType(), callState);
2363 }
2364
2365 // If the call returns results on the stack, prepare a stack area to receive
2366 // them, and pass the address of the stack area to the callee as an additional
2367 // argument.
2368 [[nodiscard]]
2369 bool passStackResultAreaCallArg(const ResultType& resultType,
2370 CallCompileState* callState) {
2371 if (inDeadCode()) {
2372 return true;
2373 }
2374 ABIResultIter iter(resultType);
2375 while (!iter.done() && iter.cur().inRegister()) {
2376 iter.next();
2377 }
2378 if (iter.done()) {
2379 // No stack results.
2380 return true;
2381 }
2382
2383 auto* stackResultArea = MWasmStackResultArea::New(alloc());
2384 if (!stackResultArea) {
2385 return false;
2386 }
2387 if (!stackResultArea->init(alloc(), iter.remaining())) {
2388 return false;
2389 }
2390 for (uint32_t base = iter.index(); !iter.done(); iter.next()) {
2391 MWasmStackResultArea::StackResult loc(iter.cur().stackOffset(),
2392 iter.cur().type().toMIRType());
2393 stackResultArea->initResult(iter.index() - base, loc);
2394 }
2395 curBlock_->add(stackResultArea);
2396 MDefinition* def = callState->returnCall ? (MDefinition*)stackResultPointer_
2397 : (MDefinition*)stackResultArea;
2398 if (!passCallArg(def, MIRType::StackResults, callState)) {
2399 return false;
2400 }
2401 callState->stackResultArea = stackResultArea;
2402 return true;
2403 }
2404
2405 [[nodiscard]]
2406 bool finishCallArgs(CallCompileState* callState) {
2407 if (inDeadCode()) {
2408 return true;
2409 }
2410
2411 if (!callState->regArgs.append(
2412 MWasmCallBase::Arg(AnyRegister(InstanceReg), instancePointer_))) {
2413 return false;
2414 }
2415
2416 uint32_t stackBytes = callState->abi.stackBytesConsumedSoFar();
2417
2418 maxStackArgBytes_ = std::max(maxStackArgBytes_, stackBytes);
2419 return true;
2420 }
2421
2422 [[nodiscard]]
2423 bool emitCallArgs(const FuncType& funcType, const DefVector& args,
2424 CallCompileState* callState) {
2425 for (size_t i = 0, n = funcType.args().length(); i < n; ++i) {
2426 if (!mirGen().ensureBallast()) {
2427 return false;
2428 }
2429 if (!passCallArg(args[i], funcType.args()[i], callState)) {
2430 return false;
2431 }
2432 }
2433
2434 ResultType resultType = ResultType::Vector(funcType.results());
2435 if (!passStackResultAreaCallArg(resultType, callState)) {
2436 return false;
2437 }
2438
2439 return finishCallArgs(callState);
2440 }
2441
2442 [[nodiscard]]
2443 bool collectUnaryCallResult(MIRType type, MDefinition** result) {
2444 MInstruction* def;
2445 switch (type) {
2446 case MIRType::Int32:
2447 def = MWasmRegisterResult::New(alloc(), MIRType::Int32, ReturnReg);
2448 break;
2449 case MIRType::Int64:
2450 def = MWasmRegister64Result::New(alloc(), ReturnReg64);
2451 break;
2452 case MIRType::Float32:
2453 def = MWasmFloatRegisterResult::New(alloc(), type, ReturnFloat32Reg);
2454 break;
2455 case MIRType::Double:
2456 def = MWasmFloatRegisterResult::New(alloc(), type, ReturnDoubleReg);
2457 break;
2458 #ifdef ENABLE_WASM_SIMD
2459 case MIRType::Simd128:
2460 def = MWasmFloatRegisterResult::New(alloc(), type, ReturnSimd128Reg);
2461 break;
2462 #endif
2463 case MIRType::WasmAnyRef:
2464 def = MWasmRegisterResult::New(alloc(), MIRType::WasmAnyRef, ReturnReg);
2465 break;
2466 case MIRType::None:
2467 MOZ_ASSERT(result == nullptr, "Not expecting any results created");
2468 return true;
2469 default:
2470 MOZ_CRASH("unexpected MIRType result for builtin call");
2471 }
2472
2473 if (!def) {
2474 return false;
2475 }
2476
2477 curBlock_->add(def);
2478 *result = def;
2479
2480 return true;
2481 }
2482
2483 [[nodiscard]]
2484 bool collectCallResults(const ResultType& type,
2485 MWasmStackResultArea* stackResultArea,
2486 DefVector* results) {
2487 if (!results->reserve(type.length())) {
2488 return false;
2489 }
2490
2491 // The result iterator goes in the order in which results would be popped
2492 // off; we want the order in which they would be pushed.
2493 ABIResultIter iter(type);
2494 uint32_t stackResultCount = 0;
2495 while (!iter.done()) {
2496 if (iter.cur().onStack()) {
2497 stackResultCount++;
2498 }
2499 iter.next();
2500 }
2501
2502 for (iter.switchToPrev(); !iter.done(); iter.prev()) {
2503 if (!mirGen().ensureBallast()) {
2504 return false;
2505 }
2506 const ABIResult& result = iter.cur();
2507 MInstruction* def;
2508 if (result.inRegister()) {
2509 switch (result.type().kind()) {
2510 case wasm::ValType::I32:
2511 def =
2512 MWasmRegisterResult::New(alloc(), MIRType::Int32, result.gpr());
2513 break;
2514 case wasm::ValType::I64:
2515 def = MWasmRegister64Result::New(alloc(), result.gpr64());
2516 break;
2517 case wasm::ValType::F32:
2518 def = MWasmFloatRegisterResult::New(alloc(), MIRType::Float32,
2519 result.fpr());
2520 break;
2521 case wasm::ValType::F64:
2522 def = MWasmFloatRegisterResult::New(alloc(), MIRType::Double,
2523 result.fpr());
2524 break;
2525 case wasm::ValType::Ref:
2526 def = MWasmRegisterResult::New(alloc(), MIRType::WasmAnyRef,
2527 result.gpr(),
2528 result.type().toMaybeRefType());
2529 break;
2530 case wasm::ValType::V128:
2531 #ifdef ENABLE_WASM_SIMD
2532 def = MWasmFloatRegisterResult::New(alloc(), MIRType::Simd128,
2533 result.fpr());
2534 #else
2535 return this->iter().fail("Ion has no SIMD support yet");
2536 #endif
2537 }
2538 } else {
2539 MOZ_ASSERT(stackResultArea);
2540 MOZ_ASSERT(stackResultCount);
2541 uint32_t idx = --stackResultCount;
2542 def = MWasmStackResult::New(alloc(), stackResultArea, idx);
2543 }
2544
2545 if (!def) {
2546 return false;
2547 }
2548 curBlock_->add(def);
2549 results->infallibleAppend(def);
2550 }
2551
2552 MOZ_ASSERT(results->length() == type.length());
2553
2554 return true;
2555 }
2556
2557 [[nodiscard]]
2558 bool call(CallCompileState* callState, const CallSiteDesc& desc,
2559 const CalleeDesc& callee, const ArgTypeVector& argTypes,
2560 MDefinition* addressOrRef = nullptr) {
2561 if (!beginCatchableCall(callState)) {
2562 return false;
2563 }
2564
2565 MInstruction* ins;
2566 if (callState->isCatchable()) {
2567 ins = MWasmCallCatchable::New(
2568 alloc(), desc, callee, callState->regArgs,
2569 StackArgAreaSizeUnaligned(argTypes), callState->tryNoteIndex,
2570 callState->fallthroughBlock, callState->prePadBlock, addressOrRef);
2571 } else {
2572 ins = MWasmCallUncatchable::New(alloc(), desc, callee, callState->regArgs,
2573 StackArgAreaSizeUnaligned(argTypes),
2574 addressOrRef);
2575 }
2576 if (!ins) {
2577 return false;
2578 }
2579 curBlock_->add(ins);
2580
2581 return finishCatchableCall(callState);
2582 }
2583
2584 [[nodiscard]]
2585 CallRefHint auditInlineableCallees(InliningHeuristics::CallKind kind,
2586 CallRefHint hints) {
2587 // Takes candidates for inlining as provided in `hints`, and returns a
2588 // subset (or all) of them for which inlining is approved. To indicate
2589 // that they are all disallowed, return an empty CallRefHint.
2590
2591 MOZ_ASSERT_IF(kind == InliningHeuristics::CallKind::Direct,
2592 hints.length() == 1);
2593
2594 // We only support inlining when lazy tiering. This is currently a
2595 // requirement because we need the full module bytecode and function
2596 // definition ranges, which are not available in other modes.
2597 if (compilerEnv().mode() != CompileMode::LazyTiering) {
2598 return CallRefHint();
2599 }
2600
2601 // We don't support asm.js and inlining. asm.js also doesn't support
2602 // baseline, which is required for lazy tiering, so we should never get
2603 // here. The biggest complication for asm.js is getting correct stack
2604 // traces with inlining.
2605 MOZ_ASSERT(!codeMeta().isAsmJS());
2606
2607 // If we were given no candidates, give up now.
2608 if (hints.empty()) {
2609 return CallRefHint();
2610 }
2611
2612 // We can't inline if we've exceeded our per-root-function inlining
2613 // budget.
2614 //
2615 // This logic will cause `availableBudget` to be driven slightly negative
2616 // if a budget overshoot happens, so we will have performed slightly more
2617 // inlining than allowed by the initial setting of `availableBudget`. The
2618 // size of this overshoot is however very limited -- it can't exceed the
2619 // size of three function bodies that are inlined (3 because that's what
2620 // CallRefHint can hold). And the max size of an inlineable function body
2621 // is limited by InliningHeuristics::isSmallEnoughToInline.
2622 if (rootCompiler_.inliningBudget() < 0) {
2623 return CallRefHint();
2624 }
2625
2626 // Check each candidate in turn, and add all acceptable ones to `filtered`.
2627 // It is important that `filtered` retains the same ordering as `hints`.
2628 CallRefHint filtered;
2629 for (uint32_t i = 0; i < hints.length(); i++) {
2630 uint32_t funcIndex = hints.get(i);
2631
2632 // We can't inline an imported function.
2633 if (codeMeta().funcIsImport(funcIndex)) {
2634 continue;
2635 }
2636
2637 // We do not support inlining a callee which uses tail calls
2638 FeatureUsage funcFeatureUsage =
2639 codeTailMeta()->funcDefFeatureUsage(funcIndex);
2640 if (funcFeatureUsage & FeatureUsage::ReturnCall) {
2641 continue;
2642 }
2643
2644 // Ask the heuristics system if we're allowed to inline a function of
2645 // this size and kind at the current inlining depth.
2646 uint32_t inlineeBodySize = codeTailMeta()->funcDefRange(funcIndex).size();
2647 uint32_t rootFunctionBodySize = rootCompiler_.func().bytecodeSize();
2648 bool largeFunctionBackoff;
2649 bool smallEnough = InliningHeuristics::isSmallEnoughToInline(
2650 kind, inliningDepth(), inlineeBodySize, rootFunctionBodySize,
2651 &largeFunctionBackoff);
2652 if (largeFunctionBackoff) {
2653 rootCompiler_.noteLargeFunctionBackoffWasApplied();
2654 }
2655 if (!smallEnough) {
2656 continue;
2657 }
2658
2659 filtered.append(funcIndex);
2660 }
2661
2662 // Whatever ends up in `filtered` is approved for inlining.
2663 return filtered;
2664 }
2665
2666 [[nodiscard]]
2667 bool finishInlinedCallDirect(FunctionCompiler& calleeCompiler,
2668 DefVector* results) {
2669 const PendingInlineReturnVector& calleeReturns =
2670 calleeCompiler.pendingInlineReturns_;
2671 MBasicBlock* calleeCatchBlock = calleeCompiler.pendingInlineCatchBlock_;
2672 const FuncType& calleeFuncType = calleeCompiler.funcType();
2673 MBasicBlock* lastBlockBeforeCall = curBlock_;
2674
2675 // Add the observed features from the inlined function to this function
2676 iter_.addFeatureUsage(calleeCompiler.featureUsage());
2677
2678 // Create a block, if needed, to handle exceptions from the callee function
2679 if (calleeCatchBlock) {
2680 ControlInstructionVector* tryLandingPadPatches;
2681 bool inTryCode = inTryBlock(&tryLandingPadPatches);
2682
2683 // The callee compiler should never create a catch block unless we have
2684 // a landing pad for it
2685 MOZ_RELEASE_ASSERT(inTryCode);
2686
2687 // Create a block in our function to jump to the nearest try block. We
2688 // cannot just use the callee's catch block for this, as the slots on it
2689 // are set up for all the locals from that function. We need to create a
2690 // new block in our function with the slots for this function, that then
2691 // does the jump to the landing pad. Ion should be able to optimize this
2692 // away using jump threading.
2693 MBasicBlock* callerCatchBlock = nullptr;
2694 if (!newBlock(nullptr, &callerCatchBlock)) {
2695 return false;
2696 }
2697
2698 // Our catch block inherits all of the locals state from immediately
2699 // before the inlined call
2700 callerCatchBlock->inheritSlots(lastBlockBeforeCall);
2701
2702 // The callee catch block jumps to our catch block
2703 calleeCatchBlock->end(MGoto::New(alloc(), callerCatchBlock));
2704
2705 // Our catch block has the callee rethrow block as a predecessor, but
2706 // ignores all phi's, because we use our own locals state.
2707 if (!callerCatchBlock->addPredecessorWithoutPhis(calleeCatchBlock)) {
2708 return false;
2709 }
2710
2711 // Our catch block ends with a patch to jump to the enclosing try block.
2712 MBasicBlock* prevBlock = curBlock_;
2713 curBlock_ = callerCatchBlock;
2714 if (!endWithPadPatch(tryLandingPadPatches)) {
2715 return false;
2716 }
2717 curBlock_ = prevBlock;
2718 }
2719
2720 // If there were no returns, then we are now in dead code
2721 if (calleeReturns.empty()) {
2722 curBlock_ = nullptr;
2723 return true;
2724 }
2725
2726 // Create a block to join all of the returns from the inlined function
2727 MBasicBlock* joinAfterCall = nullptr;
2728 if (!newBlock(nullptr, &joinAfterCall)) {
2729 return false;
2730 }
2731
2732 // The join block inherits all of the locals state from immediately before
2733 // the inlined call
2734 joinAfterCall->inheritSlots(lastBlockBeforeCall);
2735
2736 // The join block has a phi node for every result of the inlined function
2737 // type. Each phi node has an operand for each of the returns of the
2738 // inlined function.
2739 for (uint32_t i = 0; i < calleeFuncType.results().length(); i++) {
2740 MPhi* phi = MPhi::New(alloc(), calleeFuncType.results()[i].toMIRType());
2741 if (!phi || !phi->reserveLength(calleeReturns.length())) {
2742 return false;
2743 }
2744 joinAfterCall->addPhi(phi);
2745 if (!results->append(phi)) {
2746 return false;
2747 }
2748 }
2749
2750 // Bind every return from the inlined function to go to the join block, and
2751 // add the results for the return to the phi nodes.
2752 for (size_t i = 0; i < calleeReturns.length(); i++) {
2753 const PendingInlineReturn& calleeReturn = calleeReturns[i];
2754
2755 // Setup the predecessor and successor relationship
2756 MBasicBlock* pred = calleeReturn.jump->block();
2757 if (!joinAfterCall->addPredecessorWithoutPhis(pred)) {
2758 return false;
2759 }
2760 calleeReturn.jump->replaceSuccessor(MGoto::TargetIndex, joinAfterCall);
2761
2762 // For each result in this return, add it to the corresponding phi node
2763 for (uint32_t resultIndex = 0;
2764 resultIndex < calleeFuncType.results().length(); resultIndex++) {
2765 MDefinition* result = (*results)[resultIndex];
2766 ((MPhi*)(result))->addInput(calleeReturn.results[resultIndex]);
2767 }
2768 }
2769
2770 // Continue MIR generation starting in the join block
2771 curBlock_ = joinAfterCall;
2772
2773 return true;
2774 }
2775
2776 [[nodiscard]]
2777 bool callDirect(const FuncType& funcType, uint32_t funcIndex,
2778 uint32_t lineOrBytecode, const DefVector& args,
2779 DefVector* results) {
2780 MOZ_ASSERT(!inDeadCode());
2781
2782 CallCompileState callState;
2783 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
2784 CallSiteKind::Func);
2785 ResultType resultType = ResultType::Vector(funcType.results());
2786 auto callee = CalleeDesc::function(funcIndex);
2787 ArgTypeVector argTypes(funcType);
2788
2789 return emitCallArgs(funcType, args, &callState) &&
2790 call(&callState, desc, callee, argTypes) &&
2791 collectCallResults(resultType, callState.stackResultArea, results);
2792 }
2793
2794 [[nodiscard]]
2795 bool returnCallDirect(const FuncType& funcType, uint32_t funcIndex,
2796 uint32_t lineOrBytecode, const DefVector& args,
2797 DefVector* results) {
2798 MOZ_ASSERT(!inDeadCode());
2799
2800 // We do not support tail calls in inlined functions.
2801 MOZ_RELEASE_ASSERT(!isInlined());
2802
2803 CallCompileState callState;
2804 callState.returnCall = true;
2805 CallSiteDesc desc(lineOrBytecode, CallSiteKind::ReturnFunc);
2806 auto callee = CalleeDesc::function(funcIndex);
2807 ArgTypeVector argTypes(funcType);
2808
2809 if (!emitCallArgs(funcType, args, &callState)) {
2810 return false;
2811 }
2812
2813 auto ins =
2814 MWasmReturnCall::New(alloc(), desc, callee, callState.regArgs,
2815 StackArgAreaSizeUnaligned(argTypes), nullptr);
2816 if (!ins) {
2817 return false;
2818 }
2819 curBlock_->end(ins);
2820 curBlock_ = nullptr;
2821 return true;
2822 }
2823
2824 [[nodiscard]]
2825 bool returnCallImport(unsigned globalDataOffset, uint32_t lineOrBytecode,
2826 const FuncType& funcType, const DefVector& args,
2827 DefVector* results) {
2828 MOZ_ASSERT(!inDeadCode());
2829
2830 // We do not support tail calls in inlined functions.
2831 MOZ_RELEASE_ASSERT(!isInlined());
2832
2833 CallCompileState callState;
2834 callState.returnCall = true;
2835 CallSiteDesc desc(lineOrBytecode, CallSiteKind::Import);
2836 auto callee = CalleeDesc::import(globalDataOffset);
2837 ArgTypeVector argTypes(funcType);
2838
2839 if (!emitCallArgs(funcType, args, &callState)) {
2840 return false;
2841 }
2842
2843 auto* ins =
2844 MWasmReturnCall::New(alloc(), desc, callee, callState.regArgs,
2845 StackArgAreaSizeUnaligned(argTypes), nullptr);
2846 if (!ins) {
2847 return false;
2848 }
2849 curBlock_->end(ins);
2850 curBlock_ = nullptr;
2851 return true;
2852 }
2853
2854 [[nodiscard]]
2855 bool returnCallIndirect(uint32_t funcTypeIndex, uint32_t tableIndex,
2856 MDefinition* address, uint32_t lineOrBytecode,
2857 const DefVector& args, DefVector* results) {
2858 MOZ_ASSERT(!inDeadCode());
2859
2860 // We do not support tail calls in inlined functions.
2861 MOZ_RELEASE_ASSERT(!isInlined());
2862
2863 const FuncType& funcType = (*codeMeta().types)[funcTypeIndex].funcType();
2864 CallIndirectId callIndirectId =
2865 CallIndirectId::forFuncType(codeMeta(), funcTypeIndex);
2866
2867 CallCompileState callState;
2868 callState.returnCall = true;
2869 CalleeDesc callee;
2870 MOZ_ASSERT(callIndirectId.kind() != CallIndirectIdKind::AsmJS);
2871 const TableDesc& table = codeMeta().tables[tableIndex];
2872 callee =
2873 CalleeDesc::wasmTable(codeMeta(), table, tableIndex, callIndirectId);
2874
2875 CallSiteDesc desc(lineOrBytecode, CallSiteKind::Indirect);
2876 ArgTypeVector argTypes(funcType);
2877
2878 if (!emitCallArgs(funcType, args, &callState)) {
2879 return false;
2880 }
2881
2882 MDefinition* address32 = tableAddressToI32(table.addressType(), address);
2883 if (!address32) {
2884 return false;
2885 }
2886
2887 auto* ins =
2888 MWasmReturnCall::New(alloc(), desc, callee, callState.regArgs,
2889 StackArgAreaSizeUnaligned(argTypes), address32);
2890 if (!ins) {
2891 return false;
2892 }
2893 curBlock_->end(ins);
2894 curBlock_ = nullptr;
2895 return true;
2896 }
2897
2898 [[nodiscard]]
2899 bool callIndirect(uint32_t funcTypeIndex, uint32_t tableIndex,
2900 MDefinition* address, uint32_t lineOrBytecode,
2901 const DefVector& args, DefVector* results) {
2902 MOZ_ASSERT(!inDeadCode());
2903
2904 CallCompileState callState;
2905 const FuncType& funcType = (*codeMeta().types)[funcTypeIndex].funcType();
2906 CallIndirectId callIndirectId =
2907 CallIndirectId::forFuncType(codeMeta(), funcTypeIndex);
2908
2909 CalleeDesc callee;
2910 if (codeMeta().isAsmJS()) {
2911 MOZ_ASSERT(tableIndex == 0);
2912 MOZ_ASSERT(callIndirectId.kind() == CallIndirectIdKind::AsmJS);
2913 uint32_t tableIndex = codeMeta().asmJSSigToTableIndex[funcTypeIndex];
2914 const TableDesc& table = codeMeta().tables[tableIndex];
2915 // ensured by asm.js validation
2916 MOZ_ASSERT(table.initialLength() <= UINT32_MAX);
2917 MOZ_ASSERT(IsPowerOfTwo(table.initialLength()));
2918
2919 MDefinition* mask = constantI32(int32_t(table.initialLength() - 1));
2920 MBitAnd* maskedAddress =
2921 MBitAnd::New(alloc(), address, mask, MIRType::Int32);
2922 curBlock_->add(maskedAddress);
2923
2924 address = maskedAddress;
2925 callee = CalleeDesc::asmJSTable(codeMeta(), tableIndex);
2926 } else {
2927 MOZ_ASSERT(callIndirectId.kind() != CallIndirectIdKind::AsmJS);
2928 const TableDesc& table = codeMeta().tables[tableIndex];
2929 callee =
2930 CalleeDesc::wasmTable(codeMeta(), table, tableIndex, callIndirectId);
2931 address = tableAddressToI32(table.addressType(), address);
2932 if (!address) {
2933 return false;
2934 }
2935 }
2936
2937 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
2938 CallSiteKind::Indirect);
2939 ArgTypeVector argTypes(funcType);
2940 ResultType resultType = ResultType::Vector(funcType.results());
2941
2942 return emitCallArgs(funcType, args, &callState) &&
2943 call(&callState, desc, callee, argTypes, address) &&
2944 collectCallResults(resultType, callState.stackResultArea, results);
2945 }
2946
2947 [[nodiscard]]
2948 bool callImport(unsigned instanceDataOffset, uint32_t lineOrBytecode,
2949 const FuncType& funcType, const DefVector& args,
2950 DefVector* results) {
2951 MOZ_ASSERT(!inDeadCode());
2952
2953 CallCompileState callState;
2954 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
2955 CallSiteKind::Import);
2956 auto callee = CalleeDesc::import(instanceDataOffset);
2957 ArgTypeVector argTypes(funcType);
2958 ResultType resultType = ResultType::Vector(funcType.results());
2959
2960 return emitCallArgs(funcType, args, &callState) &&
2961 call(&callState, desc, callee, argTypes) &&
2962 collectCallResults(resultType, callState.stackResultArea, results);
2963 }
2964
2965 [[nodiscard]]
2966 bool builtinCall(CallCompileState* callState,
2967 const SymbolicAddressSignature& builtin,
2968 uint32_t lineOrBytecode, MDefinition** result) {
2969 if (inDeadCode()) {
2970 *result = nullptr;
2971 return true;
2972 }
2973
2974 MOZ_ASSERT(builtin.failureMode == FailureMode::Infallible);
2975
2976 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
2977 CallSiteKind::Symbolic);
2978 auto callee = CalleeDesc::builtin(builtin.identity);
2979
2980 auto* ins =
2981 MWasmCallUncatchable::New(alloc(), desc, callee, callState->regArgs,
2982 StackArgAreaSizeUnaligned(builtin));
2983 if (!ins) {
2984 return false;
2985 }
2986 curBlock_->add(ins);
2987
2988 return collectUnaryCallResult(builtin.retType, result);
2989 }
2990
2991 [[nodiscard]]
2992 bool builtinCall1(const SymbolicAddressSignature& builtin,
2993 uint32_t lineOrBytecode, MDefinition* arg,
2994 MDefinition** result) {
2995 CallCompileState callState;
2996 return passCallArg(arg, builtin.argTypes[0], &callState) &&
2997 finishCallArgs(&callState) &&
2998 builtinCall(&callState, builtin, lineOrBytecode, result);
2999 }
3000
3001 [[nodiscard]]
3002 bool builtinCall2(const SymbolicAddressSignature& builtin,
3003 uint32_t lineOrBytecode, MDefinition* arg1,
3004 MDefinition* arg2, MDefinition** result) {
3005 CallCompileState callState;
3006 return passCallArg(arg1, builtin.argTypes[0], &callState) &&
3007 passCallArg(arg2, builtin.argTypes[1], &callState) &&
3008 finishCallArgs(&callState) &&
3009 builtinCall(&callState, builtin, lineOrBytecode, result);
3010 }
3011
3012 [[nodiscard]]
3013 bool builtinCall5(const SymbolicAddressSignature& builtin,
3014 uint32_t lineOrBytecode, MDefinition* arg1,
3015 MDefinition* arg2, MDefinition* arg3, MDefinition* arg4,
3016 MDefinition* arg5, MDefinition** result) {
3017 CallCompileState callState;
3018 return passCallArg(arg1, builtin.argTypes[0], &callState) &&
3019 passCallArg(arg2, builtin.argTypes[1], &callState) &&
3020 passCallArg(arg3, builtin.argTypes[2], &callState) &&
3021 passCallArg(arg4, builtin.argTypes[3], &callState) &&
3022 passCallArg(arg5, builtin.argTypes[4], &callState) &&
3023 finishCallArgs(&callState) &&
3024 builtinCall(&callState, builtin, lineOrBytecode, result);
3025 }
3026
3027 [[nodiscard]]
3028 bool builtinCall6(const SymbolicAddressSignature& builtin,
3029 uint32_t lineOrBytecode, MDefinition* arg1,
3030 MDefinition* arg2, MDefinition* arg3, MDefinition* arg4,
3031 MDefinition* arg5, MDefinition* arg6,
3032 MDefinition** result) {
3033 CallCompileState callState;
3034 return passCallArg(arg1, builtin.argTypes[0], &callState) &&
3035 passCallArg(arg2, builtin.argTypes[1], &callState) &&
3036 passCallArg(arg3, builtin.argTypes[2], &callState) &&
3037 passCallArg(arg4, builtin.argTypes[3], &callState) &&
3038 passCallArg(arg5, builtin.argTypes[4], &callState) &&
3039 passCallArg(arg6, builtin.argTypes[5], &callState) &&
3040 finishCallArgs(&callState) &&
3041 builtinCall(&callState, builtin, lineOrBytecode, result);
3042 }
3043
3044 [[nodiscard]]
3045 bool instanceCall(CallCompileState* callState,
3046 const SymbolicAddressSignature& builtin,
3047 uint32_t lineOrBytecode, MDefinition** result = nullptr) {
3048 MOZ_ASSERT_IF(!result, builtin.retType == MIRType::None);
3049 if (inDeadCode()) {
3050 if (result) {
3051 *result = nullptr;
3052 }
3053 return true;
3054 }
3055
3056 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
3057 CallSiteKind::Symbolic);
3058 if (builtin.failureMode != FailureMode::Infallible &&
3059 !beginCatchableCall(callState)) {
3060 return false;
3061 }
3062
3063 MInstruction* ins;
3064 if (callState->isCatchable()) {
3065 ins = MWasmCallCatchable::NewBuiltinInstanceMethodCall(
3066 alloc(), desc, builtin.identity, builtin.failureMode,
3067 callState->instanceArg, callState->regArgs,
3068 StackArgAreaSizeUnaligned(builtin), callState->tryNoteIndex,
3069 callState->fallthroughBlock, callState->prePadBlock);
3070 } else {
3071 ins = MWasmCallUncatchable::NewBuiltinInstanceMethodCall(
3072 alloc(), desc, builtin.identity, builtin.failureMode,
3073 callState->instanceArg, callState->regArgs,
3074 StackArgAreaSizeUnaligned(builtin));
3075 }
3076 if (!ins) {
3077 return false;
3078 }
3079 curBlock_->add(ins);
3080
3081 if (!finishCatchableCall(callState)) {
3082 return false;
3083 }
3084
3085 if (!result) {
3086 return true;
3087 }
3088 return collectUnaryCallResult(builtin.retType, result);
3089 }
3090
3091 /*********************************************** Instance call helpers ***/
3092
3093 // Do not call this function directly -- it offers no protection against
3094 // mis-counting of arguments. Instead call one of
3095 // ::emitInstanceCall{0,1,2,3,4,5,6}.
3096 //
3097 // Emits a call to the Instance function indicated by `callee`. This is
3098 // assumed to take an Instance pointer as its first argument. The remaining
3099 // args are taken from `args`, which is assumed to hold `numArgs` entries.
3100 // If `result` is non-null, the MDefinition* holding the return value is
3101 // written to `*result`.
3102 [[nodiscard]]
3103 bool emitInstanceCallN(uint32_t lineOrBytecode,
3104 const SymbolicAddressSignature& callee,
3105 MDefinition** args, size_t numArgs,
3106 MDefinition** result = nullptr) {
3107 // Check that the first formal parameter is plausibly an Instance pointer.
3108 MOZ_ASSERT(callee.numArgs > 0);
3109 MOZ_ASSERT(callee.argTypes[0] == MIRType::Pointer);
3110 // Check we agree on the number of args.
3111 MOZ_ASSERT(numArgs + 1 /* the instance pointer */ == callee.numArgs);
3112 // Check we agree on whether a value is returned.
3113 MOZ_ASSERT((result == nullptr) == (callee.retType == MIRType::None));
3114
3115 // If we are in dead code, it can happen that some of the `args` entries
3116 // are nullptr, which will look like an OOM to the logic below. So exit
3117 // at this point. `passInstanceCallArg`, `passCallArg`, `finishCall` and
3118 // `instanceCall` all do nothing in dead code, so it's valid
3119 // to exit here.
3120 if (inDeadCode()) {
3121 if (result) {
3122 *result = nullptr;
3123 }
3124 return true;
3125 }
3126
3127 // Check all args for signs of OOMness before attempting to allocating any
3128 // more memory.
3129 for (size_t i = 0; i < numArgs; i++) {
3130 if (!args[i]) {
3131 if (result) {
3132 *result = nullptr;
3133 }
3134 return false;
3135 }
3136 }
3137
3138 // Finally, construct the call.
3139 CallCompileState callState;
3140 if (!passInstanceCallArg(callee.argTypes[0], &callState)) {
3141 return false;
3142 }
3143 for (size_t i = 0; i < numArgs; i++) {
3144 if (!passCallArg(args[i], callee.argTypes[i + 1], &callState)) {
3145 return false;
3146 }
3147 }
3148 if (!finishCallArgs(&callState)) {
3149 return false;
3150 }
3151 return instanceCall(&callState, callee, lineOrBytecode, result);
3152 }
3153
3154 [[nodiscard]]
3155 bool emitInstanceCall0(uint32_t lineOrBytecode,
3156 const SymbolicAddressSignature& callee,
3157 MDefinition** result = nullptr) {
3158 MDefinition* args[0] = {};
3159 return emitInstanceCallN(lineOrBytecode, callee, args, 0, result);
3160 }
3161 [[nodiscard]]
3162 bool emitInstanceCall1(uint32_t lineOrBytecode,
3163 const SymbolicAddressSignature& callee,
3164 MDefinition* arg1, MDefinition** result = nullptr) {
3165 MDefinition* args[1] = {arg1};
3166 return emitInstanceCallN(lineOrBytecode, callee, args, 1, result);
3167 }
3168 [[nodiscard]]
3169 bool emitInstanceCall2(uint32_t lineOrBytecode,
3170 const SymbolicAddressSignature& callee,
3171 MDefinition* arg1, MDefinition* arg2,
3172 MDefinition** result = nullptr) {
3173 MDefinition* args[2] = {arg1, arg2};
3174 return emitInstanceCallN(lineOrBytecode, callee, args, 2, result);
3175 }
3176 [[nodiscard]]
3177 bool emitInstanceCall3(uint32_t lineOrBytecode,
3178 const SymbolicAddressSignature& callee,
3179 MDefinition* arg1, MDefinition* arg2,
3180 MDefinition* arg3, MDefinition** result = nullptr) {
3181 MDefinition* args[3] = {arg1, arg2, arg3};
3182 return emitInstanceCallN(lineOrBytecode, callee, args, 3, result);
3183 }
3184 [[nodiscard]]
3185 bool emitInstanceCall4(uint32_t lineOrBytecode,
3186 const SymbolicAddressSignature& callee,
3187 MDefinition* arg1, MDefinition* arg2,
3188 MDefinition* arg3, MDefinition* arg4,
3189 MDefinition** result = nullptr) {
3190 MDefinition* args[4] = {arg1, arg2, arg3, arg4};
3191 return emitInstanceCallN(lineOrBytecode, callee, args, 4, result);
3192 }
3193 [[nodiscard]]
3194 bool emitInstanceCall5(uint32_t lineOrBytecode,
3195 const SymbolicAddressSignature& callee,
3196 MDefinition* arg1, MDefinition* arg2,
3197 MDefinition* arg3, MDefinition* arg4,
3198 MDefinition* arg5, MDefinition** result = nullptr) {
3199 MDefinition* args[5] = {arg1, arg2, arg3, arg4, arg5};
3200 return emitInstanceCallN(lineOrBytecode, callee, args, 5, result);
3201 }
3202 [[nodiscard]]
3203 bool emitInstanceCall6(uint32_t lineOrBytecode,
3204 const SymbolicAddressSignature& callee,
3205 MDefinition* arg1, MDefinition* arg2,
3206 MDefinition* arg3, MDefinition* arg4,
3207 MDefinition* arg5, MDefinition* arg6,
3208 MDefinition** result = nullptr) {
3209 MDefinition* args[6] = {arg1, arg2, arg3, arg4, arg5, arg6};
3210 return emitInstanceCallN(lineOrBytecode, callee, args, 6, result);
3211 }
3212
3213 [[nodiscard]] MDefinition* stackSwitch(MDefinition* suspender,
3214 MDefinition* fn, MDefinition* data,
3215 StackSwitchKind kind) {
3216 MOZ_ASSERT(!inDeadCode());
3217
3218 MInstruction* ins;
3219 switch (kind) {
3220 case StackSwitchKind::SwitchToMain:
3221 ins = MWasmStackSwitchToMain::New(alloc(), suspender, fn, data);
3222 break;
3223 case StackSwitchKind::SwitchToSuspendable:
3224 ins = MWasmStackSwitchToSuspendable::New(alloc(), suspender, fn, data);
3225 break;
3226 case StackSwitchKind::ContinueOnSuspendable:
3227 ins = MWasmStackContinueOnSuspendable::New(alloc(), suspender, data);
3228 break;
3229 }
3230 if (!ins) {
3231 return nullptr;
3232 }
3233
3234 curBlock_->add(ins);
3235
3236 return ins;
3237 }
3238
3239 [[nodiscard]]
3240 bool callRef(const FuncType& funcType, MDefinition* ref,
3241 uint32_t lineOrBytecode, const DefVector& args,
3242 DefVector* results) {
3243 MOZ_ASSERT(!inDeadCode());
3244
3245 CallCompileState callState;
3246 CalleeDesc callee = CalleeDesc::wasmFuncRef();
3247 CallSiteDesc desc(lineOrBytecode, rootCompiler_.inlinedCallerOffsetsIndex(),
3248 CallSiteKind::FuncRef);
3249 ArgTypeVector argTypes(funcType);
3250 ResultType resultType = ResultType::Vector(funcType.results());
3251
3252 return emitCallArgs(funcType, args, &callState) &&
3253 call(&callState, desc, callee, argTypes, ref) &&
3254 collectCallResults(resultType, callState.stackResultArea, results);
3255 }
3256
3257 [[nodiscard]]
3258 bool returnCallRef(const FuncType& funcType, MDefinition* ref,
3259 uint32_t lineOrBytecode, const DefVector& args,
3260 DefVector* results) {
3261 MOZ_ASSERT(!inDeadCode());
3262 MOZ_ASSERT(!isInlined());
3263
3264 CallCompileState callState;
3265 callState.returnCall = true;
3266 CalleeDesc callee = CalleeDesc::wasmFuncRef();
3267 CallSiteDesc desc(lineOrBytecode, CallSiteKind::FuncRef);
3268 ArgTypeVector argTypes(funcType);
3269
3270 if (!emitCallArgs(funcType, args, &callState)) {
3271 return false;
3272 }
3273
3274 auto* ins = MWasmReturnCall::New(alloc(), desc, callee, callState.regArgs,
3275 StackArgAreaSizeUnaligned(argTypes), ref);
3276 if (!ins) {
3277 return false;
3278 }
3279 curBlock_->end(ins);
3280 curBlock_ = nullptr;
3281 return true;
3282 }
3283
3284 [[nodiscard]] MDefinition* stringCast(MDefinition* string) {
3285 auto* ins = MWasmTrapIfAnyRefIsNotJSString::New(
3286 alloc(), string, wasm::Trap::BadCast, trapSiteDesc());
3287 if (!ins) {
3288 return ins;
3289 }
3290 curBlock_->add(ins);
3291 return ins;
3292 }
3293
3294 [[nodiscard]] MDefinition* stringTest(MDefinition* string) {
3295 auto* ins = MWasmAnyRefIsJSString::New(alloc(), string);
3296 if (!ins) {
3297 return nullptr;
3298 }
3299 curBlock_->add(ins);
3300 return ins;
3301 }
3302
3303 [[nodiscard]] MDefinition* stringLength(MDefinition* string) {
3304 auto* ins = MWasmAnyRefJSStringLength::New(
3305 alloc(), string, wasm::Trap::BadCast, trapSiteDesc());
3306 if (!ins) {
3307 return nullptr;
3308 }
3309 curBlock_->add(ins);
3310 return ins;
3311 }
3312
3313 [[nodiscard]] bool dispatchInlineBuiltinModuleFunc(
3314 const BuiltinModuleFunc& builtinModuleFunc, const DefVector& params) {
3315 BuiltinInlineOp inlineOp = builtinModuleFunc.inlineOp();
3316 MOZ_ASSERT(inlineOp != BuiltinInlineOp::None);
3317 switch (inlineOp) {
3318 case BuiltinInlineOp::StringCast: {
3319 MOZ_ASSERT(params.length() == 1);
3320 MDefinition* string = params[0];
3321 MDefinition* cast = stringCast(string);
3322 if (!cast) {
3323 return false;
3324 }
3325 iter().setResult(string);
3326 return true;
3327 }
3328 case BuiltinInlineOp::StringTest: {
3329 MOZ_ASSERT(params.length() == 1);
3330 MDefinition* string = params[0];
3331 MDefinition* test = stringTest(string);
3332 if (!test) {
3333 return false;
3334 }
3335 iter().setResult(test);
3336 return true;
3337 }
3338 case BuiltinInlineOp::StringLength: {
3339 MOZ_ASSERT(params.length() == 1);
3340 MDefinition* string = params[0];
3341 MDefinition* length = stringLength(string);
3342 if (!length) {
3343 return false;
3344 }
3345 iter().setResult(length);
3346 return true;
3347 }
3348 case BuiltinInlineOp::None:
3349 case BuiltinInlineOp::Limit:
3350 break;
3351 }
3352 MOZ_CRASH();
3353 }
3354
3355 [[nodiscard]] bool callBuiltinModuleFunc(
3356 const BuiltinModuleFunc& builtinModuleFunc, const DefVector& params) {
3357 MOZ_ASSERT(!inDeadCode());
3358
3359 BuiltinInlineOp inlineOp = builtinModuleFunc.inlineOp();
3360 if (inlineOp != BuiltinInlineOp::None) {
3361 return dispatchInlineBuiltinModuleFunc(builtinModuleFunc, params);
3362 }
3363
3364 // It's almost possible to use FunctionCompiler::emitInstanceCallN here.
3365 // Unfortunately not currently possible though, since ::emitInstanceCallN
3366 // expects an array of arguments along with a size, and that's not what is
3367 // available here. It would be possible if we were prepared to copy
3368 // `builtinModuleFunc->params` into a fixed-sized (16 element?) array, add
3369 // `memoryBase`, and make the call.
3370 const SymbolicAddressSignature& callee = *builtinModuleFunc.sig();
3371
3372 CallCompileState callState;
3373 if (!passInstanceCallArg(callee.argTypes[0], &callState) ||
3374 !passCallArgs(params, builtinModuleFunc.funcType()->args(),
3375 &callState)) {
3376 return false;
3377 }
3378
3379 if (builtinModuleFunc.usesMemory()) {
3380 if (!passCallArg(memoryBase(0), MIRType::Pointer, &callState)) {
3381 return false;
3382 }
3383 }
3384
3385 if (!finishCallArgs(&callState)) {
3386 return false;
3387 }
3388
3389 bool hasResult = !builtinModuleFunc.funcType()->results().empty();
3390 MDefinition* result = nullptr;
3391 MDefinition** resultOutParam = hasResult ? &result : nullptr;
3392 if (!instanceCall(&callState, callee, readBytecodeOffset(),
3393 resultOutParam)) {
3394 return false;
3395 }
3396
3397 if (hasResult) {
3398 iter().setResult(result);
3399 }
3400 return true;
3401 }
3402
3403 /*********************************************** Control flow generation */
3404
3405 inline bool inDeadCode() const { return curBlock_ == nullptr; }
3406
3407 [[nodiscard]] bool returnValues(DefVector&& values) {
3408 if (inDeadCode()) {
3409 return true;
3410 }
3411
3412 // If we're inlined into another function, we must accumulate the returns
3413 // so that they can be patched into the caller function.
3414 if (isInlined()) {
3415 MGoto* jump = MGoto::New(alloc());
3416 if (!jump) {
3417 return false;
3418 }
3419 curBlock_->end(jump);
3420 curBlock_ = nullptr;
3421 return pendingInlineReturns_.emplaceBack(
3422 PendingInlineReturn(jump, std::move(values)));
3423 }
3424
3425 if (values.empty()) {
3426 curBlock_->end(MWasmReturnVoid::New(alloc(), instancePointer_));
3427 } else {
3428 ResultType resultType = ResultType::Vector(funcType().results());
3429 ABIResultIter iter(resultType);
3430 // Switch to iterate in FIFO order instead of the default LIFO.
3431 while (!iter.done()) {
3432 iter.next();
3433 }
3434 iter.switchToPrev();
3435 for (uint32_t i = 0; !iter.done(); iter.prev(), i++) {
3436 if (!mirGen().ensureBallast()) {
3437 return false;
3438 }
3439 const ABIResult& result = iter.cur();
3440 if (result.onStack()) {
3441 MOZ_ASSERT(iter.remaining() > 1);
3442 auto* store = MWasmStoreStackResult::New(
3443 alloc(), stackResultPointer_, result.stackOffset(), values[i]);
3444 curBlock_->add(store);
3445 } else {
3446 MOZ_ASSERT(iter.remaining() == 1);
3447 MOZ_ASSERT(i + 1 == values.length());
3448 curBlock_->end(
3449 MWasmReturn::New(alloc(), values[i], instancePointer_));
3450 }
3451 }
3452 }
3453 curBlock_ = nullptr;
3454 return true;
3455 }
3456
3457 void unreachableTrap() {
3458 if (inDeadCode()) {
3459 return;
3460 }
3461
3462 auto* ins =
3463 MWasmTrap::New(alloc(), wasm::Trap::Unreachable, trapSiteDesc());
3464 curBlock_->end(ins);
3465 curBlock_ = nullptr;
3466 }
3467
3468 private:
3469 static uint32_t numPushed(MBasicBlock* block) {
3470 return block->stackDepth() - block->info().firstStackSlot();
3471 }
3472
3473 public:
3474 [[nodiscard]] bool pushDefs(const DefVector& defs) {
3475 if (inDeadCode()) {
3476 return true;
3477 }
3478 MOZ_ASSERT(numPushed(curBlock_) == 0);
3479 if (!curBlock_->ensureHasSlots(defs.length())) {
3480 return false;
3481 }
3482 for (MDefinition* def : defs) {
3483 MOZ_ASSERT(def->type() != MIRType::None);
3484 curBlock_->push(def);
3485 }
3486 return true;
3487 }
3488
3489 [[nodiscard]] bool popPushedDefs(DefVector* defs) {
3490 size_t n = numPushed(curBlock_);
3491 if (!defs->resizeUninitialized(n)) {
3492 return false;
3493 }
3494 for (; n > 0; n--) {
3495 MDefinition* def = curBlock_->pop();
3496 MOZ_ASSERT(def->type() != MIRType::Value);
3497 (*defs)[n - 1] = def;
3498 }
3499 return true;
3500 }
3501
3502 private:
3503 [[nodiscard]] bool addJoinPredecessor(const DefVector& defs,
3504 MBasicBlock** joinPred) {
3505 *joinPred = curBlock_;
3506 if (inDeadCode()) {
3507 return true;
3508 }
3509 return pushDefs(defs);
3510 }
3511
3512 public:
3513 [[nodiscard]] bool branchAndStartThen(MDefinition* cond,
3514 MBasicBlock** elseBlock) {
3515 if (inDeadCode()) {
3516 *elseBlock = nullptr;
3517 } else {
3518 MBasicBlock* thenBlock;
3519 if (!newBlock(curBlock_, &thenBlock)) {
3520 return false;
3521 }
3522 if (!newBlock(curBlock_, elseBlock)) {
3523 return false;
3524 }
3525
3526 curBlock_->end(MTest::New(alloc(), cond, thenBlock, *elseBlock));
3527
3528 curBlock_ = thenBlock;
3529 mirGraph().moveBlockToEnd(curBlock_);
3530 }
3531
3532 return startBlock();
3533 }
3534
3535 [[nodiscard]] bool switchToElse(MBasicBlock* elseBlock,
3536 MBasicBlock** thenJoinPred) {
3537 DefVector values;
3538 if (!finishBlock(&values)) {
3539 return false;
3540 }
3541
3542 if (!elseBlock) {
3543 *thenJoinPred = nullptr;
3544 } else {
3545 if (!addJoinPredecessor(values, thenJoinPred)) {
3546 return false;
3547 }
3548
3549 curBlock_ = elseBlock;
3550 mirGraph().moveBlockToEnd(curBlock_);
3551 }
3552
3553 return startBlock();
3554 }
3555
3556 [[nodiscard]] bool joinIfElse(MBasicBlock* thenJoinPred, DefVector* defs) {
3557 DefVector values;
3558 if (!finishBlock(&values)) {
3559 return false;
3560 }
3561
3562 if (!thenJoinPred && inDeadCode()) {
3563 return true;
3564 }
3565
3566 MBasicBlock* elseJoinPred;
3567 if (!addJoinPredecessor(values, &elseJoinPred)) {
3568 return false;
3569 }
3570
3571 mozilla::Array<MBasicBlock*, 2> blocks;
3572 size_t numJoinPreds = 0;
3573 if (thenJoinPred) {
3574 blocks[numJoinPreds++] = thenJoinPred;
3575 }
3576 if (elseJoinPred) {
3577 blocks[numJoinPreds++] = elseJoinPred;
3578 }
3579
3580 if (numJoinPreds == 0) {
3581 return true;
3582 }
3583
3584 MBasicBlock* join;
3585 if (!goToNewBlock(blocks[0], &join)) {
3586 return false;
3587 }
3588 for (size_t i = 1; i < numJoinPreds; ++i) {
3589 if (!goToExistingBlock(blocks[i], join)) {
3590 return false;
3591 }
3592 }
3593
3594 curBlock_ = join;
3595 return popPushedDefs(defs);
3596 }
3597
3598 [[nodiscard]] bool startBlock() {
3599 MOZ_ASSERT_IF(pendingBlockDepth_ < pendingBlocks_.length(),
3600 pendingBlocks_[pendingBlockDepth_].patches.empty());
3601 pendingBlockDepth_++;
3602 return true;
3603 }
3604
3605 [[nodiscard]] bool finishBlock(DefVector* defs) {
3606 MOZ_ASSERT(pendingBlockDepth_);
3607 uint32_t topLabel = --pendingBlockDepth_;
3608 return bindBranches(topLabel, defs);
3609 }
3610
3611 [[nodiscard]] bool startLoop(MBasicBlock** loopHeader, size_t paramCount) {
3612 *loopHeader = nullptr;
3613
3614 pendingBlockDepth_++;
3615 rootCompiler_.startLoop();
3616
3617 if (inDeadCode()) {
3618 return true;
3619 }
3620
3621 // Create the loop header.
3622 MOZ_ASSERT(curBlock_->loopDepth() == rootCompiler_.loopDepth() - 1);
3623 *loopHeader = MBasicBlock::New(mirGraph(), info(), curBlock_,
3624 MBasicBlock::PENDING_LOOP_HEADER);
3625 if (!*loopHeader) {
3626 return false;
3627 }
3628
3629 (*loopHeader)->setLoopDepth(rootCompiler_.loopDepth());
3630 mirGraph().addBlock(*loopHeader);
3631 curBlock_->end(MGoto::New(alloc(), *loopHeader));
3632
3633 DefVector loopParams;
3634 if (!iter().getResults(paramCount, &loopParams)) {
3635 return false;
3636 }
3637
3638 // Eagerly create a phi for all loop params. setLoopBackedge will remove
3639 // any that were not necessary.
3640 for (size_t i = 0; i < paramCount; i++) {
3641 MPhi* phi = MPhi::New(alloc(), loopParams[i]->type());
3642 if (!phi) {
3643 return false;
3644 }
3645 if (!phi->reserveLength(2)) {
3646 return false;
3647 }
3648 (*loopHeader)->addPhi(phi);
3649 phi->addInput(loopParams[i]);
3650 loopParams[i] = phi;
3651 }
3652 iter().setResults(paramCount, loopParams);
3653
3654 MBasicBlock* body;
3655 if (!goToNewBlock(*loopHeader, &body)) {
3656 return false;
3657 }
3658 curBlock_ = body;
3659 return true;
3660 }
3661
3662 private:
3663 void fixupRedundantPhis(MBasicBlock* b) {
3664 for (size_t i = 0, depth = b->stackDepth(); i < depth; i++) {
3665 MDefinition* def = b->getSlot(i);
3666 if (def->isUnused()) {
3667 b->setSlot(i, def->toPhi()->getOperand(0));
3668 }
3669 }
3670 }
3671
3672 [[nodiscard]] bool setLoopBackedge(MBasicBlock* loopEntry,
3673 MBasicBlock* loopBody,
3674 MBasicBlock* backedge, size_t paramCount) {
3675 if (!loopEntry->setBackedgeWasm(backedge, paramCount)) {
3676 return false;
3677 }
3678
3679 // Entering a loop will eagerly create a phi node for all locals and loop
3680 // params. Now that we've closed the loop we can check which phi nodes
3681 // were actually needed by checking if the SSA definition flowing into the
3682 // loop header (operand 0) is different than the SSA definition coming from
3683 // the loop backedge (operand 1). If they are the same definition, the phi
3684 // is redundant and can be removed.
3685 //
3686 // To do this we mark all redundant phis as 'unused', then remove the phi's
3687 // from places in ourself the phis may have flowed into, then replace all
3688 // uses of the phi's in the MIR graph with the original SSA definition.
3689 for (MPhiIterator phi = loopEntry->phisBegin(); phi != loopEntry->phisEnd();
3690 phi++) {
3691 MOZ_ASSERT(phi->numOperands() == 2);
3692 if (phi->getOperand(0) == phi->getOperand(1)) {
3693 phi->setUnused();
3694 }
3695 }
3696
3697 // Fix up phis stored in the slots Vector of pending blocks.
3698 for (PendingBlockTarget& pendingBlockTarget : pendingBlocks_) {
3699 for (ControlFlowPatch& p : pendingBlockTarget.patches) {
3700 MBasicBlock* block = p.ins->block();
3701 if (block->loopDepth() >= loopEntry->loopDepth()) {
3702 fixupRedundantPhis(block);
3703 }
3704 }
3705 }
3706
3707 // The loop body, if any, might be referencing recycled phis too.
3708 if (loopBody) {
3709 fixupRedundantPhis(loopBody);
3710 }
3711
3712 // Pending jumps to an enclosing try-catch may reference the recycled phis.
3713 // We have to search above all enclosing try blocks, as a delegate may move
3714 // patches around.
3715 for (uint32_t depth = 0; depth < iter().controlStackDepth(); depth++) {
3716 LabelKind kind = iter().controlKind(depth);
3717 if (kind != LabelKind::Try && kind != LabelKind::TryTable &&
3718 kind != LabelKind::Body) {
3719 continue;
3720 }
3721 Control& control = iter().controlItem(depth);
3722 if (!control.tryControl) {
3723 continue;
3724 }
3725 for (MControlInstruction* patch : control.tryControl->landingPadPatches) {
3726 MBasicBlock* block = patch->block();
3727 if (block->loopDepth() >= loopEntry->loopDepth()) {
3728 fixupRedundantPhis(block);
3729 }
3730 }
3731 }
3732 for (MControlInstruction* patch : bodyRethrowPadPatches_) {
3733 MBasicBlock* block = patch->block();
3734 if (block->loopDepth() >= loopEntry->loopDepth()) {
3735 fixupRedundantPhis(block);
3736 }
3737 }
3738
3739 // If we're inlined into another function we are accumulating return values
3740 // in a vector, search through the results to see if any refer to a
3741 // redundant phi.
3742 for (PendingInlineReturn& pendingReturn : pendingInlineReturns_) {
3743 for (uint32_t resultIndex = 0;
3744 resultIndex < pendingReturn.results.length(); resultIndex++) {
3745 MDefinition** pendingResult = &pendingReturn.results[resultIndex];
3746 if ((*pendingResult)->isUnused()) {
3747 *pendingResult = (*pendingResult)->toPhi()->getOperand(0);
3748 }
3749 }
3750 }
3751
3752 // Discard redundant phis and add to the free list.
3753 for (MPhiIterator phi = loopEntry->phisBegin();
3754 phi != loopEntry->phisEnd();) {
3755 MPhi* entryDef = *phi++;
3756 if (!entryDef->isUnused()) {
3757 continue;
3758 }
3759
3760 entryDef->justReplaceAllUsesWith(entryDef->getOperand(0));
3761 loopEntry->discardPhi(entryDef);
3762 mirGraph().addPhiToFreeList(entryDef);
3763 }
3764
3765 return true;
3766 }
3767
3768 public:
3769 [[nodiscard]] bool closeLoop(MBasicBlock* loopHeader,
3770 DefVector* loopResults) {
3771 MOZ_ASSERT(pendingBlockDepth_ >= 1);
3772 MOZ_ASSERT(rootCompiler_.loopDepth());
3773
3774 uint32_t headerLabel = pendingBlockDepth_ - 1;
3775
3776 if (!loopHeader) {
3777 MOZ_ASSERT(inDeadCode());
3778 MOZ_ASSERT(headerLabel >= pendingBlocks_.length() ||
3779 pendingBlocks_[headerLabel].patches.empty());
3780 pendingBlockDepth_--;
3781 rootCompiler_.closeLoop();
3782 return true;
3783 }
3784
3785 // Op::Loop doesn't have an implicit backedge so temporarily set
3786 // aside the end of the loop body to bind backedges.
3787 MBasicBlock* loopBody = curBlock_;
3788 curBlock_ = nullptr;
3789
3790 // As explained in bug 1253544, Ion apparently has an invariant that
3791 // there is only one backedge to loop headers. To handle wasm's ability
3792 // to have multiple backedges to the same loop header, we bind all those
3793 // branches as forward jumps to a single backward jump. This is
3794 // unfortunate but the optimizer is able to fold these into single jumps
3795 // to backedges.
3796 DefVector backedgeValues;
3797 if (!bindBranches(headerLabel, &backedgeValues)) {
3798 return false;
3799 }
3800
3801 MOZ_ASSERT(loopHeader->loopDepth() == rootCompiler_.loopDepth());
3802
3803 if (curBlock_) {
3804 // We're on the loop backedge block, created by bindBranches.
3805 for (size_t i = 0, n = numPushed(curBlock_); i != n; i++) {
3806 curBlock_->pop();
3807 }
3808
3809 if (!pushDefs(backedgeValues)) {
3810 return false;
3811 }
3812
3813 MOZ_ASSERT(curBlock_->loopDepth() == rootCompiler_.loopDepth());
3814 curBlock_->end(MGoto::New(alloc(), loopHeader));
3815 if (!setLoopBackedge(loopHeader, loopBody, curBlock_,
3816 backedgeValues.length())) {
3817 return false;
3818 }
3819 }
3820
3821 curBlock_ = loopBody;
3822
3823 rootCompiler_.closeLoop();
3824
3825 // If the loop depth still at the inner loop body, correct it.
3826 if (curBlock_ && curBlock_->loopDepth() != rootCompiler_.loopDepth()) {
3827 MBasicBlock* out;
3828 if (!goToNewBlock(curBlock_, &out)) {
3829 return false;
3830 }
3831 curBlock_ = out;
3832 }
3833
3834 pendingBlockDepth_ -= 1;
3835 return inDeadCode() || popPushedDefs(loopResults);
3836 }
3837
3838 [[nodiscard]] bool addControlFlowPatch(
3839 MControlInstruction* ins, uint32_t relative, uint32_t index,
3840 BranchHint branchHint = BranchHint::Invalid) {
3841 MOZ_ASSERT(relative < pendingBlockDepth_);
3842 uint32_t absolute = pendingBlockDepth_ - 1 - relative;
3843
3844 if (absolute >= pendingBlocks_.length() &&
3845 !pendingBlocks_.resize(absolute + 1)) {
3846 return false;
3847 }
3848
3849 pendingBlocks_[absolute].hint = branchHint;
3850 return pendingBlocks_[absolute].patches.append(
3851 ControlFlowPatch(ins, index));
3852 }
3853
3854 [[nodiscard]] bool br(uint32_t relativeDepth, const DefVector& values) {
3855 if (inDeadCode()) {
3856 return true;
3857 }
3858
3859 MGoto* jump = MGoto::New(alloc());
3860 if (!addControlFlowPatch(jump, relativeDepth, MGoto::TargetIndex)) {
3861 return false;
3862 }
3863
3864 if (!pushDefs(values)) {
3865 return false;
3866 }
3867
3868 curBlock_->end(jump);
3869 curBlock_ = nullptr;
3870 return true;
3871 }
3872
3873 [[nodiscard]] bool brIf(uint32_t relativeDepth, const DefVector& values,
3874 MDefinition* condition, BranchHint branchHint) {
3875 if (inDeadCode()) {
3876 return true;
3877 }
3878
3879 MBasicBlock* joinBlock = nullptr;
3880 if (!newBlock(curBlock_, &joinBlock)) {
3881 return false;
3882 }
3883
3884 MTest* test = MTest::New(alloc(), condition, nullptr, joinBlock);
3885 if (!addControlFlowPatch(test, relativeDepth, MTest::TrueBranchIndex,
3886 branchHint)) {
3887 return false;
3888 }
3889
3890 if (!pushDefs(values)) {
3891 return false;
3892 }
3893
3894 curBlock_->end(test);
3895 curBlock_ = joinBlock;
3896
3897 return true;
3898 }
3899
3900 [[nodiscard]] bool brTable(MDefinition* operand, uint32_t defaultDepth,
3901 const Uint32Vector& depths,
3902 const DefVector& values) {
3903 if (inDeadCode()) {
3904 return true;
3905 }
3906
3907 size_t numCases = depths.length();
3908 MOZ_ASSERT(numCases <= INT32_MAX);
3909 MOZ_ASSERT(numCases);
3910
3911 MTableSwitch* table =
3912 MTableSwitch::New(alloc(), operand, 0, int32_t(numCases - 1));
3913
3914 size_t defaultIndex;
3915 if (!table->addDefault(nullptr, &defaultIndex)) {
3916 return false;
3917 }
3918 if (!addControlFlowPatch(table, defaultDepth, defaultIndex)) {
3919 return false;
3920 }
3921
3922 using IndexToCaseMap =
3923 HashMap<uint32_t, uint32_t, DefaultHasher<uint32_t>, SystemAllocPolicy>;
3924
3925 IndexToCaseMap indexToCase;
3926 if (!indexToCase.put(defaultDepth, defaultIndex)) {
3927 return false;
3928 }
3929
3930 for (size_t i = 0; i < numCases; i++) {
3931 if (!mirGen().ensureBallast()) {
3932 return false;
3933 }
3934
3935 uint32_t depth = depths[i];
3936
3937 size_t caseIndex;
3938 IndexToCaseMap::AddPtr p = indexToCase.lookupForAdd(depth);
3939 if (!p) {
3940 if (!table->addSuccessor(nullptr, &caseIndex)) {
3941 return false;
3942 }
3943 if (!addControlFlowPatch(table, depth, caseIndex)) {
3944 return false;
3945 }
3946 if (!indexToCase.add(p, depth, caseIndex)) {
3947 return false;
3948 }
3949 } else {
3950 caseIndex = p->value();
3951 }
3952
3953 if (!table->addCase(caseIndex)) {
3954 return false;
3955 }
3956 }
3957
3958 if (!pushDefs(values)) {
3959 return false;
3960 }
3961
3962 curBlock_->end(table);
3963 curBlock_ = nullptr;
3964
3965 return true;
3966 }
3967
3968 /********************************************************** Exceptions ***/
3969
3970 bool inTryBlockFrom(uint32_t fromRelativeDepth,
3971 uint32_t* tryRelativeDepth) const {
3972 uint32_t relativeDepth;
3973 if (iter_.controlFindInnermostFrom(
3974 [](LabelKind kind, const Control& control) {
3975 return control.tryControl != nullptr &&
3976 control.tryControl->inBody;
3977 },
3978 fromRelativeDepth, &relativeDepth)) {
3979 *tryRelativeDepth = relativeDepth;
3980 return true;
3981 }
3982
3983 if (callerCompiler_ && callerCompiler_->inTryCode()) {
3984 *tryRelativeDepth = iter_.controlStackDepth() - 1;
3985 return true;
3986 }
3987
3988 return false;
3989 }
3990
3991 bool inTryBlockFrom(uint32_t fromRelativeDepth,
3992 ControlInstructionVector** landingPadPatches) {
3993 uint32_t tryRelativeDepth;
3994 if (!inTryBlockFrom(fromRelativeDepth, &tryRelativeDepth)) {
3995 return false;
3996 }
3997
3998 if (tryRelativeDepth == iter().controlStackDepth() - 1) {
3999 *landingPadPatches = &bodyRethrowPadPatches_;
4000 } else {
4001 *landingPadPatches =
4002 &iter().controlItem(tryRelativeDepth).tryControl->landingPadPatches;
4003 }
4004 return true;
4005 }
4006
4007 bool inTryBlock(ControlInstructionVector** landingPadPatches) {
4008 return inTryBlockFrom(0, landingPadPatches);
4009 }
4010
4011 bool inTryCode() const {
4012 uint32_t tryRelativeDepth;
4013 return inTryBlockFrom(0, &tryRelativeDepth);
4014 }
4015
4016 MDefinition* loadTag(uint32_t tagIndex) {
4017 MWasmLoadInstanceDataField* tag = MWasmLoadInstanceDataField::New(
4018 alloc(), MIRType::WasmAnyRef,
4019 codeMeta().offsetOfTagInstanceData(tagIndex), true, instancePointer_);
4020 curBlock_->add(tag);
4021 return tag;
4022 }
4023
4024 void loadPendingExceptionState(MDefinition** pendingException,
4025 MDefinition** pendingExceptionTag) {
4026 auto* exception = MWasmLoadInstance::New(
4027 alloc(), instancePointer_, wasm::Instance::offsetOfPendingException(),
4028 MIRType::WasmAnyRef, AliasSet::Load(AliasSet::WasmPendingException));
4029 curBlock_->add(exception);
4030 *pendingException = exception;
4031
4032 auto* tag = MWasmLoadInstance::New(
4033 alloc(), instancePointer_,
4034 wasm::Instance::offsetOfPendingExceptionTag(), MIRType::WasmAnyRef,
4035 AliasSet::Load(AliasSet::WasmPendingException));
4036 curBlock_->add(tag);
4037 *pendingExceptionTag = tag;
4038 }
4039
4040 [[nodiscard]] bool setPendingExceptionState(MDefinition* exception,
4041 MDefinition* tag) {
4042 // Set the pending exception object
4043 auto* exceptionAddr = MWasmDerivedPointer::New(
4044 alloc(), instancePointer_, Instance::offsetOfPendingException());
4045 curBlock_->add(exceptionAddr);
4046 auto* setException = MWasmStoreRef::New(
4047 alloc(), instancePointer_, exceptionAddr, /*valueOffset=*/0, exception,
4048 AliasSet::WasmPendingException, WasmPreBarrierKind::Normal);
4049 curBlock_->add(setException);
4050 if (!postBarrierEdgePrecise(/*lineOrBytecode=*/0, exceptionAddr,
4051 exception)) {
4052 return false;
4053 }
4054
4055 // Set the pending exception tag object
4056 auto* exceptionTagAddr = MWasmDerivedPointer::New(
4057 alloc(), instancePointer_, Instance::offsetOfPendingExceptionTag());
4058 curBlock_->add(exceptionTagAddr);
4059 auto* setExceptionTag = MWasmStoreRef::New(
4060 alloc(), instancePointer_, exceptionTagAddr, /*valueOffset=*/0, tag,
4061 AliasSet::WasmPendingException, WasmPreBarrierKind::Normal);
4062 curBlock_->add(setExceptionTag);
4063 return postBarrierEdgePrecise(/*lineOrBytecode=*/0, exceptionTagAddr, tag);
4064 }
4065
4066 [[nodiscard]] bool endWithPadPatch(
4067 ControlInstructionVector* tryLandingPadPatches) {
4068 MGoto* jumpToLandingPad = MGoto::New(alloc());
4069 curBlock_->end(jumpToLandingPad);
4070 return tryLandingPadPatches->emplaceBack(jumpToLandingPad);
4071 }
4072
4073 [[nodiscard]] bool delegatePadPatches(const ControlInstructionVector& patches,
4074 uint32_t relativeDepth) {
4075 if (patches.empty()) {
4076 return true;
4077 }
4078
4079 // Find where we are delegating the pad patches to.
4080 ControlInstructionVector* targetPatches;
4081 if (!inTryBlockFrom(relativeDepth, &targetPatches)) {
4082 MOZ_ASSERT(relativeDepth <= pendingBlockDepth_ - 1);
4083 targetPatches = &bodyRethrowPadPatches_;
4084 }
4085
4086 // Append the delegate's pad patches to the target's.
4087 for (MControlInstruction* ins : patches) {
4088 if (!targetPatches->emplaceBack(ins)) {
4089 return false;
4090 }
4091 }
4092 return true;
4093 }
4094
4095 [[nodiscard]]
4096 bool beginCatchableCall(CallCompileState* callState) {
4097 if (!inTryBlock(&callState->tryLandingPadPatches)) {
4098 MOZ_ASSERT(!callState->isCatchable());
4099 return true;
4100 }
4101 MOZ_ASSERT(callState->isCatchable());
4102
4103 // Allocate a try note
4104 if (!rootCompiler_.addTryNote(&callState->tryNoteIndex)) {
4105 return false;
4106 }
4107
4108 // Allocate blocks for fallthrough and exceptions
4109 return newBlock(curBlock_, &callState->fallthroughBlock) &&
4110 newBlock(curBlock_, &callState->prePadBlock);
4111 }
4112
4113 [[nodiscard]]
4114 bool finishCatchableCall(CallCompileState* callState) {
4115 if (!callState->tryLandingPadPatches) {
4116 return true;
4117 }
4118
4119 // Switch to the prePadBlock
4120 MBasicBlock* callBlock = curBlock_;
4121 curBlock_ = callState->prePadBlock;
4122
4123 // Mark this as the landing pad for the call
4124 curBlock_->add(MWasmCallLandingPrePad::New(alloc(), callBlock,
4125 callState->tryNoteIndex));
4126
4127 // End with a pending jump to the landing pad
4128 if (!endWithPadPatch(callState->tryLandingPadPatches)) {
4129 return false;
4130 }
4131
4132 // Compilation continues in the fallthroughBlock.
4133 curBlock_ = callState->fallthroughBlock;
4134 return true;
4135 }
4136
4137 // Create a landing pad for a try block. This is also used for the implicit
4138 // rethrow landing pad used for delegate instructions that target the
4139 // outermost label.
4140 [[nodiscard]]
4141 bool createTryLandingPad(ControlInstructionVector& landingPadPatches,
4142 MBasicBlock** landingPad) {
4143 MOZ_ASSERT(!landingPadPatches.empty());
4144
4145 // Bind the branches from exception throwing code to a new landing pad
4146 // block. This is done similarly to what is done in bindBranches.
4147 MControlInstruction* ins = landingPadPatches[0];
4148 MBasicBlock* pred = ins->block();
4149 if (!newBlock(pred, landingPad)) {
4150 return false;
4151 }
4152 ins->replaceSuccessor(MGoto::TargetIndex, *landingPad);
4153 for (size_t i = 1; i < landingPadPatches.length(); i++) {
4154 ins = landingPadPatches[i];
4155 pred = ins->block();
4156 if (!(*landingPad)->addPredecessor(alloc(), pred)) {
4157 return false;
4158 }
4159 ins->replaceSuccessor(MGoto::TargetIndex, *landingPad);
4160 }
4161
4162 // Clear the now bound pad patches.
4163 landingPadPatches.clear();
4164 return true;
4165 }
4166
4167 [[nodiscard]]
4168 bool createTryTableLandingPad(TryControl* tryControl) {
4169 // If there were no patches, then there were no throwing instructions and
4170 // we don't need to do anything.
4171 if (tryControl->landingPadPatches.empty()) {
4172 return true;
4173 }
4174
4175 // Create the landing pad block and bind all the throwing instructions
4176 MBasicBlock* landingPad;
4177 if (!createTryLandingPad(tryControl->landingPadPatches, &landingPad)) {
4178 return false;
4179 }
4180
4181 // Get the pending exception from the instance
4182 MDefinition* pendingException;
4183 MDefinition* pendingExceptionTag;
4184 if (!consumePendingException(&landingPad, &pendingException,
4185 &pendingExceptionTag)) {
4186 return false;
4187 }
4188
4189 MBasicBlock* originalBlock = curBlock_;
4190 curBlock_ = landingPad;
4191
4192 bool hadCatchAll = false;
4193 for (const TryTableCatch& tryTableCatch : tryControl->catches) {
4194 // Handle a catch_all by jumping to the target block
4195 if (tryTableCatch.tagIndex == CatchAllIndex) {
4196 // Capture the exnref value if we need to
4197 DefVector values;
4198 if (tryTableCatch.captureExnRef && !values.append(pendingException)) {
4199 return false;
4200 }
4201
4202 // Branch to the catch_all code
4203 if (!br(tryTableCatch.labelRelativeDepth, values)) {
4204 return false;
4205 }
4206
4207 // Break from the loop and skip the implicit rethrow that's needed
4208 // if we didn't have a catch_all
4209 hadCatchAll = true;
4210 break;
4211 }
4212
4213 // Handle a tagged catch by doing a compare and branch on the tag index,
4214 // jumping to a catch block if they match, or else to a fallthrough block
4215 // to continue the landing pad.
4216 MBasicBlock* catchBlock = nullptr;
4217 MBasicBlock* fallthroughBlock = nullptr;
4218 if (!newBlock(curBlock_, &catchBlock) ||
4219 !newBlock(curBlock_, &fallthroughBlock)) {
4220 return false;
4221 }
4222
4223 // Branch to the catch block if the exception's tag matches this catch
4224 // block's tag.
4225 MDefinition* catchTag = loadTag(tryTableCatch.tagIndex);
4226 MDefinition* matchesCatchTag =
4227 compare(pendingExceptionTag, catchTag, JSOp::Eq,
4228 MCompare::Compare_WasmAnyRef);
4229 curBlock_->end(
4230 MTest::New(alloc(), matchesCatchTag, catchBlock, fallthroughBlock));
4231
4232 // Set up the catch block by extracting the values from the exception
4233 // object.
4234 curBlock_ = catchBlock;
4235
4236 // Extract the exception values for the catch block
4237 DefVector values;
4238 if (!loadExceptionValues(pendingException, tryTableCatch.tagIndex,
4239 &values)) {
4240 return false;
4241 }
4242 if (tryTableCatch.captureExnRef && !values.append(pendingException)) {
4243 return false;
4244 }
4245
4246 if (!br(tryTableCatch.labelRelativeDepth, values)) {
4247 return false;
4248 }
4249
4250 curBlock_ = fallthroughBlock;
4251 }
4252
4253 // If there was no catch_all, we must rethrow this exception.
4254 if (!hadCatchAll) {
4255 if (!throwFrom(pendingException, pendingExceptionTag)) {
4256 return false;
4257 }
4258 }
4259
4260 curBlock_ = originalBlock;
4261 return true;
4262 }
4263
4264 // Consume the pending exception state from instance. This will clear out the
4265 // previous value.
4266 [[nodiscard]]
4267 bool consumePendingException(MBasicBlock** landingPad,
4268 MDefinition** pendingException,
4269 MDefinition** pendingExceptionTag) {
4270 MBasicBlock* prevBlock = curBlock_;
4271 curBlock_ = *landingPad;
4272
4273 // Load the pending exception and tag
4274 loadPendingExceptionState(pendingException, pendingExceptionTag);
4275
4276 // Clear the pending exception and tag
4277 auto* null = constantNullRef(MaybeRefType());
4278 if (!setPendingExceptionState(null, null)) {
4279 return false;
4280 }
4281
4282 // The landing pad may have changed from loading and clearing the pending
4283 // exception state.
4284 *landingPad = curBlock_;
4285
4286 curBlock_ = prevBlock;
4287 return true;
4288 }
4289
4290 [[nodiscard]] bool startTry() {
4291 Control& control = iter().controlItem();
4292 control.block = curBlock_;
4293 control.tryControl = rootCompiler_.newTryControl();
4294 if (!control.tryControl) {
4295 return false;
4296 }
4297 control.tryControl->inBody = true;
4298 return startBlock();
4299 }
4300
4301 [[nodiscard]] bool startTryTable(TryTableCatchVector&& catches) {
4302 Control& control = iter().controlItem();
4303 control.block = curBlock_;
4304 control.tryControl = rootCompiler_.newTryControl();
4305 if (!control.tryControl) {
4306 return false;
4307 }
4308 control.tryControl->inBody = true;
4309 control.tryControl->catches = std::move(catches);
4310 return startBlock();
4311 }
4312
4313 [[nodiscard]] bool joinTryOrCatchBlock(Control& control) {
4314 // If the try or catch block ended with dead code, there is no need to
4315 // do any control flow join.
4316 if (inDeadCode()) {
4317 return true;
4318 }
4319
4320 // This is a split path which we'll need to join later, using a control
4321 // flow patch.
4322 MOZ_ASSERT(!curBlock_->hasLastIns());
4323 MGoto* jump = MGoto::New(alloc());
4324 if (!addControlFlowPatch(jump, 0, MGoto::TargetIndex)) {
4325 return false;
4326 }
4327
4328 // Finish the current block with the control flow patch instruction.
4329 curBlock_->end(jump);
4330 return true;
4331 }
4332
4333 // Finish the previous block (either a try or catch block) and then setup a
4334 // new catch block.
4335 [[nodiscard]] bool switchToCatch(Control& control, LabelKind fromKind,
4336 uint32_t tagIndex) {
4337 // Mark this control node as being no longer in the body of the try
4338 control.tryControl->inBody = false;
4339
4340 // If there is no control block, then either:
4341 // - the entry of the try block is dead code, or
4342 // - there is no landing pad for the try-catch.
4343 // In either case, any catch will be dead code.
4344 if (!control.block) {
4345 MOZ_ASSERT(inDeadCode());
4346 return true;
4347 }
4348
4349 // Join the previous try or catch block with a patch to the future join of
4350 // the whole try-catch block.
4351 if (!joinTryOrCatchBlock(control)) {
4352 return false;
4353 }
4354
4355 // If we are switching from the try block, create the landing pad. This is
4356 // guaranteed to happen once and only once before processing catch blocks.
4357 if (fromKind == LabelKind::Try) {
4358 if (!control.tryControl->landingPadPatches.empty()) {
4359 // Create the landing pad block and bind all the throwing instructions
4360 MBasicBlock* padBlock = nullptr;
4361 if (!createTryLandingPad(control.tryControl->landingPadPatches,
4362 &padBlock)) {
4363 return false;
4364 }
4365
4366 // Store the pending exception and tag on the control item for future
4367 // use in catch handlers.
4368 if (!consumePendingException(
4369 &padBlock, &control.tryControl->pendingException,
4370 &control.tryControl->pendingExceptionTag)) {
4371 return false;
4372 }
4373
4374 // Set the control block for this try-catch to the landing pad.
4375 control.block = padBlock;
4376 } else {
4377 control.block = nullptr;
4378 }
4379 }
4380
4381 // If there is no landing pad, then this and following catches are dead
4382 // code.
4383 if (!control.block) {
4384 curBlock_ = nullptr;
4385 return true;
4386 }
4387
4388 // Switch to the landing pad.
4389 curBlock_ = control.block;
4390
4391 // We should have a pending exception and tag if we were able to create a
4392 // landing pad.
4393 MOZ_ASSERT(control.tryControl->pendingException);
4394 MOZ_ASSERT(control.tryControl->pendingExceptionTag);
4395
4396 // Handle a catch_all by immediately jumping to a new block. We require a
4397 // new block (as opposed to just emitting the catch_all code in the current
4398 // block) because rethrow requires the exception/tag to be present in the
4399 // landing pad's slots, while the catch_all block must not have the
4400 // exception/tag in slots.
4401 if (tagIndex == CatchAllIndex) {
4402 MBasicBlock* catchAllBlock = nullptr;
4403 if (!goToNewBlock(curBlock_, &catchAllBlock)) {
4404 return false;
4405 }
4406 // Compilation will continue in the catch_all block.
4407 curBlock_ = catchAllBlock;
4408 return true;
4409 }
4410
4411 // Handle a tagged catch by doing a compare and branch on the tag index,
4412 // jumping to a catch block if they match, or else to a fallthrough block
4413 // to continue the landing pad.
4414 MBasicBlock* catchBlock = nullptr;
4415 MBasicBlock* fallthroughBlock = nullptr;
4416 if (!newBlock(curBlock_, &catchBlock) ||
4417 !newBlock(curBlock_, &fallthroughBlock)) {
4418 return false;
4419 }
4420
4421 // Branch to the catch block if the exception's tag matches this catch
4422 // block's tag.
4423 MDefinition* catchTag = loadTag(tagIndex);
4424 MDefinition* matchesCatchTag =
4425 compare(control.tryControl->pendingExceptionTag, catchTag, JSOp::Eq,
4426 MCompare::Compare_WasmAnyRef);
4427 curBlock_->end(
4428 MTest::New(alloc(), matchesCatchTag, catchBlock, fallthroughBlock));
4429
4430 // The landing pad will continue in the fallthrough block
4431 control.block = fallthroughBlock;
4432
4433 // Set up the catch block by extracting the values from the exception
4434 // object.
4435 curBlock_ = catchBlock;
4436
4437 // Extract the exception values for the catch block
4438 DefVector values;
4439 if (!loadExceptionValues(control.tryControl->pendingException, tagIndex,
4440 &values)) {
4441 return false;
4442 }
4443 iter().setResults(values.length(), values);
4444 return true;
4445 }
4446
4447 [[nodiscard]] bool loadExceptionValues(MDefinition* exception,
4448 uint32_t tagIndex, DefVector* values) {
4449 SharedTagType tagType = codeMeta().tags[tagIndex].type;
4450 const ValTypeVector& params = tagType->argTypes();
4451 const TagOffsetVector& offsets = tagType->argOffsets();
4452
4453 // Get the data pointer from the exception object
4454 auto* data = MWasmLoadField::New(
4455 alloc(), exception, nullptr, WasmExceptionObject::offsetOfData(),
4456 mozilla::Nothing(), MIRType::Pointer, MWideningOp::None,
4457 AliasSet::Load(AliasSet::Any));
4458 if (!data) {
4459 return false;
4460 }
4461 curBlock_->add(data);
4462
4463 // Presize the values vector to the number of params
4464 if (!values->reserve(params.length())) {
4465 return false;
4466 }
4467
4468 // Load each value from the data pointer
4469 for (size_t i = 0; i < params.length(); i++) {
4470 if (!mirGen().ensureBallast()) {
4471 return false;
4472 }
4473 auto* load =
4474 MWasmLoadField::New(alloc(), data, exception, offsets[i],
4475 mozilla::Nothing(), params[i].toMIRType(),
4476 MWideningOp::None, AliasSet::Load(AliasSet::Any),
4477 mozilla::Nothing(), params[i].toMaybeRefType());
4478 if (!load || !values->append(load)) {
4479 return false;
4480 }
4481 curBlock_->add(load);
4482 }
4483 return true;
4484 }
4485
4486 [[nodiscard]] bool finishTryCatch(LabelKind kind, Control& control,
4487 DefVector* defs) {
4488 switch (kind) {
4489 case LabelKind::Try: {
4490 // This is a catchless try, we must delegate all throwing instructions
4491 // to the nearest enclosing try block if one exists, or else to the
4492 // body block which will handle it in emitBodyRethrowPad. We
4493 // specify a relativeDepth of '1' to delegate outside of the still
4494 // active try block.
4495 uint32_t relativeDepth = 1;
4496 if (!delegatePadPatches(control.tryControl->landingPadPatches,
4497 relativeDepth)) {
4498 return false;
4499 }
4500 break;
4501 }
4502 case LabelKind::Catch: {
4503 MOZ_ASSERT(!control.tryControl->inBody);
4504 // This is a try without a catch_all, we must have a rethrow at the end
4505 // of the landing pad (if any).
4506 MBasicBlock* padBlock = control.block;
4507 if (padBlock) {
4508 MBasicBlock* prevBlock = curBlock_;
4509 curBlock_ = padBlock;
4510 if (!throwFrom(control.tryControl->pendingException,
4511 control.tryControl->pendingExceptionTag)) {
4512 return false;
4513 }
4514 curBlock_ = prevBlock;
4515 }
4516 break;
4517 }
4518 case LabelKind::CatchAll: {
4519 MOZ_ASSERT(!control.tryControl->inBody);
4520 // This is a try with a catch_all, and requires no special handling.
4521 break;
4522 }
4523 default:
4524 MOZ_CRASH();
4525 }
4526
4527 // Finish the block, joining the try and catch blocks
4528 return finishBlock(defs);
4529 }
4530
4531 [[nodiscard]] bool finishTryTable(Control& control, DefVector* defs) {
4532 // Mark this control as no longer in the body of the try
4533 control.tryControl->inBody = false;
4534 // Create a landing pad for all of the catches
4535 if (!createTryTableLandingPad(control.tryControl.get())) {
4536 return false;
4537 }
4538 // Finish the block, joining the try and catch blocks
4539 return finishBlock(defs);
4540 }
4541
4542 [[nodiscard]] bool emitBodyRethrowPad(Control& control) {
4543 // If there are no throwing instructions pending, we don't need to do
4544 // anything
4545 if (bodyRethrowPadPatches_.empty()) {
4546 return true;
4547 }
4548
4549 // Create a landing pad for any throwing instructions
4550 MBasicBlock* padBlock;
4551 if (!createTryLandingPad(bodyRethrowPadPatches_, &padBlock)) {
4552 return false;
4553 }
4554
4555 // If we're inlined into another function, we save the landing pad to be
4556 // linked later directly to our caller's landing pad. See
4557 // `finishedInlinedCallDirect`.
4558 if (callerCompiler_ && callerCompiler_->inTryCode()) {
4559 pendingInlineCatchBlock_ = padBlock;
4560 return true;
4561 }
4562
4563 // Otherwise we need to grab the pending exception and rethrow it.
4564 MDefinition* pendingException;
4565 MDefinition* pendingExceptionTag;
4566 if (!consumePendingException(&padBlock, &pendingException,
4567 &pendingExceptionTag)) {
4568 return false;
4569 }
4570
4571 // Switch to the landing pad and rethrow the exception
4572 MBasicBlock* prevBlock = curBlock_;
4573 curBlock_ = padBlock;
4574 if (!throwFrom(pendingException, pendingExceptionTag)) {
4575 return false;
4576 }
4577 curBlock_ = prevBlock;
4578
4579 MOZ_ASSERT(bodyRethrowPadPatches_.empty());
4580 return true;
4581 }
4582
4583 [[nodiscard]] bool emitNewException(MDefinition* tag,
4584 MDefinition** exception) {
4585 return emitInstanceCall1(readBytecodeOffset(), SASigExceptionNew, tag,
4586 exception);
4587 }
4588
4589 [[nodiscard]] bool emitThrow(uint32_t tagIndex, const DefVector& argValues) {
4590 if (inDeadCode()) {
4591 return true;
4592 }
4593 uint32_t bytecodeOffset = readBytecodeOffset();
4594
4595 // Load the tag
4596 MDefinition* tag = loadTag(tagIndex);
4597 if (!tag) {
4598 return false;
4599 }
4600
4601 // Allocate an exception object
4602 MDefinition* exception;
4603 if (!emitNewException(tag, &exception)) {
4604 return false;
4605 }
4606
4607 // Load the data pointer from the object
4608 auto* data = MWasmLoadField::New(
4609 alloc(), exception, nullptr, WasmExceptionObject::offsetOfData(),
4610 mozilla::Nothing(), MIRType::Pointer, MWideningOp::None,
4611 AliasSet::Load(AliasSet::Any));
4612 if (!data) {
4613 return false;
4614 }
4615 curBlock_->add(data);
4616
4617 // Store the params into the data pointer
4618 SharedTagType tagType = codeMeta().tags[tagIndex].type;
4619 for (size_t i = 0; i < tagType->argOffsets().length(); i++) {
4620 if (!mirGen().ensureBallast()) {
4621 return false;
4622 }
4623 ValType type = tagType->argTypes()[i];
4624 uint32_t offset = tagType->argOffsets()[i];
4625
4626 if (!type.isRefRepr()) {
4627 auto* store = MWasmStoreField::New(
4628 alloc(), data, exception, offset, mozilla::Nothing(), argValues[i],
4629 MNarrowingOp::None, AliasSet::Store(AliasSet::Any));
4630 if (!store) {
4631 return false;
4632 }
4633 curBlock_->add(store);
4634 continue;
4635 }
4636
4637 // Store the new value
4638 auto* store = MWasmStoreFieldRef::New(
4639 alloc(), instancePointer_, data, exception, offset,
4640 mozilla::Nothing(), argValues[i], AliasSet::Store(AliasSet::Any),
4641 Nothing(), WasmPreBarrierKind::None);
4642 if (!store) {
4643 return false;
4644 }
4645 curBlock_->add(store);
4646
4647 // Call the post-write barrier
4648 if (!postBarrierWholeCell(bytecodeOffset, exception, argValues[i])) {
4649 return false;
4650 }
4651 }
4652
4653 // Throw the exception
4654 return throwFrom(exception, tag);
4655 }
4656
4657 [[nodiscard]] bool emitThrowRef(MDefinition* exnRef) {
4658 if (inDeadCode()) {
4659 return true;
4660 }
4661
4662 // The exception must be non-null
4663 exnRef = refAsNonNull(exnRef);
4664 if (!exnRef) {
4665 return false;
4666 }
4667
4668 // Call Instance::throwException to perform tag unpacking and throw the
4669 // exception
4670 if (!emitInstanceCall1(readBytecodeOffset(), SASigThrowException, exnRef)) {
4671 return false;
4672 }
4673 unreachableTrap();
4674
4675 curBlock_ = nullptr;
4676 return true;
4677 }
4678
4679 [[nodiscard]] bool throwFrom(MDefinition* exn, MDefinition* tag) {
4680 if (inDeadCode()) {
4681 return true;
4682 }
4683
4684 // Check if there is a local catching try control, and if so, then add a
4685 // pad-patch to its tryPadPatches.
4686 ControlInstructionVector* tryLandingPadPatches;
4687 if (inTryBlock(&tryLandingPadPatches)) {
4688 // Set the pending exception state, the landing pad will read from this
4689 if (!setPendingExceptionState(exn, tag)) {
4690 return false;
4691 }
4692
4693 // End with a pending jump to the landing pad
4694 if (!endWithPadPatch(tryLandingPadPatches)) {
4695 return false;
4696 }
4697 curBlock_ = nullptr;
4698 return true;
4699 }
4700
4701 // If there is no surrounding catching block, call an instance method to
4702 // throw the exception.
4703 if (!emitInstanceCall1(readBytecodeOffset(), SASigThrowException, exn)) {
4704 return false;
4705 }
4706 unreachableTrap();
4707
4708 curBlock_ = nullptr;
4709 return true;
4710 }
4711
4712 [[nodiscard]] bool emitRethrow(uint32_t relativeDepth) {
4713 if (inDeadCode()) {
4714 return true;
4715 }
4716
4717 Control& control = iter().controlItem(relativeDepth);
4718 MOZ_ASSERT(iter().controlKind(relativeDepth) == LabelKind::Catch ||
4719 iter().controlKind(relativeDepth) == LabelKind::CatchAll);
4720 return throwFrom(control.tryControl->pendingException,
4721 control.tryControl->pendingExceptionTag);
4722 }
4723
4724 /******************************** WasmGC: low level load/store helpers ***/
4725
4726 // Given a (StorageType, FieldExtension) pair, produce the (MIRType,
4727 // MWideningOp) pair that will give the correct operation for reading the
4728 // value from memory.
4729 static void fieldLoadInfoToMIR(StorageType type, FieldWideningOp wideningOp,
4730 MIRType* mirType, MWideningOp* mirWideningOp) {
4731 switch (type.kind()) {
4732 case StorageType::I8: {
4733 switch (wideningOp) {
4734 case FieldWideningOp::Signed:
4735 *mirType = MIRType::Int32;
4736 *mirWideningOp = MWideningOp::FromS8;
4737 return;
4738 case FieldWideningOp::Unsigned:
4739 *mirType = MIRType::Int32;
4740 *mirWideningOp = MWideningOp::FromU8;
4741 return;
4742 default:
4743 MOZ_CRASH();
4744 }
4745 }
4746 case StorageType::I16: {
4747 switch (wideningOp) {
4748 case FieldWideningOp::Signed:
4749 *mirType = MIRType::Int32;
4750 *mirWideningOp = MWideningOp::FromS16;
4751 return;
4752 case FieldWideningOp::Unsigned:
4753 *mirType = MIRType::Int32;
4754 *mirWideningOp = MWideningOp::FromU16;
4755 return;
4756 default:
4757 MOZ_CRASH();
4758 }
4759 }
4760 default: {
4761 switch (wideningOp) {
4762 case FieldWideningOp::None:
4763 *mirType = type.toMIRType();
4764 *mirWideningOp = MWideningOp::None;
4765 return;
4766 default:
4767 MOZ_CRASH();
4768 }
4769 }
4770 }
4771 }
4772
4773 // Given a StorageType, return the Scale required when accessing array
4774 // elements of this type.
4775 static Scale scaleFromFieldType(StorageType type) {
4776 if (type.kind() == StorageType::V128) {
4777 // V128 is accessed differently, so this scale will not be used.
4778 return Scale::Invalid;
4779 }
4780 return ShiftToScale(type.indexingShift());
4781 }
4782
4783 // Given a StorageType, produce the MNarrowingOp required for writing the
4784 // value to memory.
4785 static MNarrowingOp fieldStoreInfoToMIR(StorageType type) {
4786 switch (type.kind()) {
4787 case StorageType::I8:
4788 return MNarrowingOp::To8;
4789 case StorageType::I16:
4790 return MNarrowingOp::To16;
4791 default:
4792 return MNarrowingOp::None;
4793 }
4794 }
4795
4796 // Generate a write of `value` at address `base + offset`, where `offset` is
4797 // known at JIT time. If the written value is a reftype, the previous value
4798 // at `base + offset` will be retrieved and handed off to the post-write
4799 // barrier. `keepAlive` will be referenced by the instruction so as to hold
4800 // it live (from the GC's point of view).
4801 [[nodiscard]] bool writeGcValueAtBasePlusOffset(
4802 uint32_t lineOrBytecode, StorageType type, MDefinition* keepAlive,
4803 AliasSet::Flag aliasBitset, MDefinition* value, MDefinition* base,
4804 uint32_t offset, uint32_t fieldIndex, bool needsTrapInfo,
4805 WasmPreBarrierKind preBarrierKind) {
4806 MOZ_ASSERT(aliasBitset != 0);
4807 MOZ_ASSERT(keepAlive->type() == MIRType::WasmAnyRef);
4808 MOZ_ASSERT(type.widenToValType().toMIRType() == value->type());
4809 MNarrowingOp narrowingOp = fieldStoreInfoToMIR(type);
4810
4811 if (!type.isRefRepr()) {
4812 MaybeTrapSiteDesc maybeTrap;
4813 if (needsTrapInfo) {
4814 maybeTrap.emplace(trapSiteDesc());
4815 }
4816
4817 auto* store = MWasmStoreField::New(
4818 alloc(), base, keepAlive, offset, mozilla::Some(fieldIndex), value,
4819 narrowingOp, AliasSet::Store(aliasBitset), maybeTrap);
4820 if (!store) {
4821 return false;
4822 }
4823 curBlock_->add(store);
4824 return true;
4825 }
4826
4827 // Otherwise it's a ref store. Load the previous value so we can show it
4828 // to the post-write barrier.
4829 //
4830 // Optimisation opportunity: for the case where this field write results
4831 // from struct.new, the old value is always zero. So we should synthesise
4832 // a suitable zero constant rather than reading it from the object. See
4833 // also bug 1799999.
4834 MOZ_ASSERT(narrowingOp == MNarrowingOp::None);
4835 MOZ_ASSERT(type.widenToValType() == type.valType());
4836
4837 // Store the new value
4838 auto* store = MWasmStoreFieldRef::New(
4839 alloc(), instancePointer_, base, keepAlive, offset,
4840 mozilla::Some(fieldIndex), value, AliasSet::Store(aliasBitset),
4841 mozilla::Some(trapSiteDesc()), preBarrierKind);
4842 if (!store) {
4843 return false;
4844 }
4845 curBlock_->add(store);
4846
4847 // Call the post-write barrier
4848 return postBarrierWholeCell(lineOrBytecode, keepAlive, value);
4849 }
4850
4851 // Generate a write of `value` at address `base + index * scale`, where
4852 // `scale` is known at JIT-time. If the written value is a reftype, the
4853 // previous value at `base + index * scale` will be retrieved and handed off
4854 // to the post-write barrier. `keepAlive` will be referenced by the
4855 // instruction so as to hold it live (from the GC's point of view).
4856 [[nodiscard]] bool writeGcValueAtBasePlusScaledIndex(
4857 uint32_t lineOrBytecode, StorageType type, MDefinition* keepAlive,
4858 AliasSet::Flag aliasBitset, MDefinition* value, MDefinition* base,
4859 uint32_t scale, MDefinition* index, WasmPreBarrierKind preBarrierKind) {
4860 MOZ_ASSERT(aliasBitset != 0);
4861 MOZ_ASSERT(keepAlive->type() == MIRType::WasmAnyRef);
4862 MOZ_ASSERT(type.widenToValType().toMIRType() == value->type());
4863 MOZ_ASSERT(scale == 1 || scale == 2 || scale == 4 || scale == 8 ||
4864 scale == 16);
4865
4866 MNarrowingOp narrowingOp = fieldStoreInfoToMIR(type);
4867
4868 if (!type.isRefRepr()) {
4869 MaybeTrapSiteDesc maybeTrap;
4870 Scale scale = scaleFromFieldType(type);
4871 auto* store = MWasmStoreElement::New(
4872 alloc(), base, index, value, keepAlive, narrowingOp, scale,
4873 AliasSet::Store(aliasBitset), maybeTrap);
4874 if (!store) {
4875 return false;
4876 }
4877 curBlock_->add(store);
4878 return true;
4879 }
4880
4881 // Otherwise it's a ref store.
4882 MOZ_ASSERT(narrowingOp == MNarrowingOp::None);
4883 MOZ_ASSERT(type.widenToValType() == type.valType());
4884
4885 // Store the new value
4886 auto* store = MWasmStoreElementRef::New(
4887 alloc(), instancePointer_, base, index, value, keepAlive,
4888 AliasSet::Store(aliasBitset), mozilla::Some(trapSiteDesc()),
4889 preBarrierKind);
4890 if (!store) {
4891 return false;
4892 }
4893 curBlock_->add(store);
4894
4895 return postBarrierEdgeAtIndex(lineOrBytecode, keepAlive, base, index,
4896 sizeof(void*), value);
4897 }
4898
4899 // Generate a read from address `base + offset`, where `offset` is known at
4900 // JIT time. The loaded value will be widened as described by `type` and
4901 // `fieldWideningOp`. `keepAlive` will be referenced by the instruction so as
4902 // to hold it live (from the GC's point of view).
4903 [[nodiscard]] MDefinition* readGcValueAtBasePlusOffset(
4904 StorageType type, FieldWideningOp fieldWideningOp, MDefinition* keepAlive,
4905 AliasSet::Flag aliasBitset, MDefinition* base, uint32_t offset,
4906 uint32_t fieldIndex, bool needsTrapInfo) {
4907 MOZ_ASSERT(aliasBitset != 0);
4908 MOZ_ASSERT(keepAlive->type() == MIRType::WasmAnyRef);
4909 MIRType mirType;
4910 MWideningOp mirWideningOp;
4911 fieldLoadInfoToMIR(type, fieldWideningOp, &mirType, &mirWideningOp);
4912 MaybeTrapSiteDesc maybeTrap;
4913 if (needsTrapInfo) {
4914 maybeTrap.emplace(trapSiteDesc());
4915 }
4916
4917 auto* load = MWasmLoadField::New(alloc(), base, keepAlive, offset,
4918 mozilla::Some(fieldIndex), mirType,
4919 mirWideningOp, AliasSet::Load(aliasBitset),
4920 maybeTrap, type.toMaybeRefType());
4921 if (!load) {
4922 return nullptr;
4923 }
4924 curBlock_->add(load);
4925 return load;
4926 }
4927
4928 // Generate a read from address `base + index * scale`, where `scale` is
4929 // known at JIT-time. The loaded value will be widened as described by
4930 // `type` and `fieldWideningOp`. `keepAlive` will be referenced by the
4931 // instruction so as to hold it live (from the GC's point of view).
4932 [[nodiscard]] MDefinition* readGcArrayValueAtIndex(
4933 StorageType type, FieldWideningOp fieldWideningOp, MDefinition* keepAlive,
4934 AliasSet::Flag aliasBitset, MDefinition* base, MDefinition* index) {
4935 MOZ_ASSERT(aliasBitset != 0);
4936 MOZ_ASSERT(keepAlive->type() == MIRType::WasmAnyRef);
4937
4938 MIRType mirType;
4939 MWideningOp mirWideningOp;
4940 fieldLoadInfoToMIR(type, fieldWideningOp, &mirType, &mirWideningOp);
4941 Scale scale = scaleFromFieldType(type);
4942 auto* load = MWasmLoadElement::New(
4943 alloc(), base, keepAlive, index, mirType, mirWideningOp, scale,
4944 AliasSet::Load(aliasBitset), mozilla::Some(trapSiteDesc()),
4945 type.toMaybeRefType());
4946 if (!load) {
4947 return nullptr;
4948 }
4949 curBlock_->add(load);
4950 return load;
4951 }
4952
4953 /************************************************ WasmGC: type helpers ***/
4954
4955 // Returns an MDefinition holding the supertype vector for `typeIndex`.
4956 [[nodiscard]] MDefinition* loadSuperTypeVector(uint32_t typeIndex) {
4957 uint32_t stvOffset = codeMeta().offsetOfSuperTypeVector(typeIndex);
4958
4959 auto* load =
4960 MWasmLoadInstanceDataField::New(alloc(), MIRType::Pointer, stvOffset,
4961 /*isConst=*/true, instancePointer_);
4962 if (!load) {
4963 return nullptr;
4964 }
4965 curBlock_->add(load);
4966 return load;
4967 }
4968
4969 uint32_t readAllocSiteIndex(uint32_t typeIndex) {
4970 if (!codeTailMeta() || !codeTailMeta()->hasFuncDefAllocSites()) {
4971 // For single tier of optimized compilation, there are no assigned alloc
4972 // sites, using type index as alloc site.
4973 return typeIndex;
4974 }
4975 AllocSitesRange rangeInModule =
4976 codeTailMeta()->getFuncDefAllocSites(funcIndex());
4977 uint32_t localIndex = numAllocSites_++;
4978 MOZ_RELEASE_ASSERT(localIndex < rangeInModule.length);
4979 return rangeInModule.begin + localIndex;
4980 }
4981
4982 [[nodiscard]] MDefinition* loadAllocSiteInstanceData(
4983 uint32_t allocSiteIndex) {
4984 auto* allocSites = MWasmLoadInstance::New(
4985 alloc(), instancePointer_, Instance::offsetOfAllocSites(),
4986 MIRType::Pointer, AliasSet::None());
4987 if (!allocSites) {
4988 return nullptr;
4989 }
4990 curBlock_->add(allocSites);
4991
4992 auto* result = MWasmDerivedPointer::New(
4993 alloc(), allocSites, allocSiteIndex * sizeof(gc::AllocSite));
4994 if (!result) {
4995 return nullptr;
4996 }
4997 curBlock_->add(result);
4998 return result;
4999 }
5000
5001 /********************************************** WasmGC: struct helpers ***/
5002
5003 [[nodiscard]] MDefinition* createStructObject(uint32_t typeIndex,
5004 uint32_t allocSiteIndex,
5005 bool zeroFields) {
5006 // Allocate an uninitialized struct.
5007 MDefinition* allocSite = loadAllocSiteInstanceData(allocSiteIndex);
5008 if (!allocSite) {
5009 return nullptr;
5010 }
5011
5012 const TypeDef* typeDef = &(*codeMeta().types)[typeIndex];
5013 auto* structObject =
5014 MWasmNewStructObject::New(alloc(), instancePointer_, allocSite, typeDef,
5015 zeroFields, trapSiteDesc());
5016 if (!structObject) {
5017 return nullptr;
5018 }
5019 curBlock_->add(structObject);
5020
5021 return structObject;
5022 }
5023
5024 // Helper function for EmitStruct{New,Set}: given a MIR pointer to a
5025 // WasmStructObject, a MIR pointer to a value, and a field descriptor,
5026 // generate MIR to write the value to the relevant field in the object.
5027 [[nodiscard]] bool writeValueToStructField(
5028 uint32_t lineOrBytecode, const StructType& structType,
5029 uint32_t fieldIndex, MDefinition* structObject, MDefinition* value,
5030 WasmPreBarrierKind preBarrierKind) {
5031 StorageType fieldType = structType.fields_[fieldIndex].type;
5032 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
5033
5034 bool areaIsOutline;
5035 uint32_t areaOffset;
5036 WasmStructObject::fieldOffsetToAreaAndOffset(fieldType, fieldOffset,
5037 &areaIsOutline, &areaOffset);
5038
5039 // Make `base` point at the first byte of either the struct object as a
5040 // whole or of the out-of-line data area. And adjust `areaOffset`
5041 // accordingly.
5042 MDefinition* base;
5043 bool needsTrapInfo;
5044 if (areaIsOutline) {
5045 auto* loadDataPointer = MWasmLoadField::New(
5046 alloc(), structObject, nullptr,
5047 WasmStructObject::offsetOfOutlineData(), mozilla::Nothing(),
5048 MIRType::Pointer, MWideningOp::None,
5049 AliasSet::Load(AliasSet::WasmStructOutlineDataPointer),
5050 mozilla::Some(trapSiteDesc()));
5051 if (!loadDataPointer) {
5052 return false;
5053 }
5054 curBlock_->add(loadDataPointer);
5055 base = loadDataPointer;
5056 needsTrapInfo = false;
5057 } else {
5058 base = structObject;
5059 needsTrapInfo = true;
5060 areaOffset += WasmStructObject::offsetOfInlineData();
5061 }
5062 // The transaction is to happen at `base + areaOffset`, so to speak.
5063 // After this point we must ignore `fieldOffset`.
5064
5065 // The alias set denoting the field's location, although lacking a
5066 // Load-vs-Store indication at this point.
5067 AliasSet::Flag fieldAliasSet = areaIsOutline
5068 ? AliasSet::WasmStructOutlineDataArea
5069 : AliasSet::WasmStructInlineDataArea;
5070
5071 return writeGcValueAtBasePlusOffset(
5072 lineOrBytecode, fieldType, structObject, fieldAliasSet, value, base,
5073 areaOffset, fieldIndex, needsTrapInfo, preBarrierKind);
5074 }
5075
5076 // Helper function for EmitStructGet: given a MIR pointer to a
5077 // WasmStructObject, a field descriptor and a field widening operation,
5078 // generate MIR to read the value from the relevant field in the object.
5079 [[nodiscard]] MDefinition* readValueFromStructField(
5080 const StructType& structType, uint32_t fieldIndex,
5081 FieldWideningOp wideningOp, MDefinition* structObject) {
5082 StorageType fieldType = structType.fields_[fieldIndex].type;
5083 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
5084
5085 bool areaIsOutline;
5086 uint32_t areaOffset;
5087 WasmStructObject::fieldOffsetToAreaAndOffset(fieldType, fieldOffset,
5088 &areaIsOutline, &areaOffset);
5089
5090 // Make `base` point at the first byte of either the struct object as a
5091 // whole or of the out-of-line data area. And adjust `areaOffset`
5092 // accordingly.
5093 MDefinition* base;
5094 bool needsTrapInfo;
5095 if (areaIsOutline) {
5096 auto* loadDataPointer = MWasmLoadField::New(
5097 alloc(), structObject, nullptr,
5098 WasmStructObject::offsetOfOutlineData(), mozilla::Nothing(),
5099 MIRType::Pointer, MWideningOp::None,
5100 AliasSet::Load(AliasSet::WasmStructOutlineDataPointer),
5101 mozilla::Some(trapSiteDesc()));
5102 if (!loadDataPointer) {
5103 return nullptr;
5104 }
5105 curBlock_->add(loadDataPointer);
5106 base = loadDataPointer;
5107 needsTrapInfo = false;
5108 } else {
5109 base = structObject;
5110 needsTrapInfo = true;
5111 areaOffset += WasmStructObject::offsetOfInlineData();
5112 }
5113 // The transaction is to happen at `base + areaOffset`, so to speak.
5114 // After this point we must ignore `fieldOffset`.
5115
5116 // The alias set denoting the field's location, although lacking a
5117 // Load-vs-Store indication at this point.
5118 AliasSet::Flag fieldAliasSet = areaIsOutline
5119 ? AliasSet::WasmStructOutlineDataArea
5120 : AliasSet::WasmStructInlineDataArea;
5121
5122 return readGcValueAtBasePlusOffset(fieldType, wideningOp, structObject,
5123 fieldAliasSet, base, areaOffset,
5124 fieldIndex, needsTrapInfo);
5125 }
5126
5127 /********************************* WasmGC: address-arithmetic helpers ***/
5128
5129 inline bool targetIs64Bit() const {
5130 #ifdef JS_64BIT
5131 return true;
5132 #else
5133 return false;
5134 #endif
5135 }
5136
5137 // Generate MIR to unsigned widen `val` out to the target word size. If
5138 // `val` is already at the target word size, this is a no-op. The only
5139 // other allowed case is where `val` is Int32 and we're compiling for a
5140 // 64-bit target, in which case a widen is generated.
5141 [[nodiscard]] MDefinition* unsignedWidenToTargetWord(MDefinition* val) {
5142 if (targetIs64Bit()) {
5143 if (val->type() == MIRType::Int32) {
5144 auto* ext = MExtendInt32ToInt64::New(alloc(), val, /*isUnsigned=*/true);
5145 if (!ext) {
5146 return nullptr;
5147 }
5148 curBlock_->add(ext);
5149 return ext;
5150 }
5151 MOZ_ASSERT(val->type() == MIRType::Int64);
5152 return val;
5153 }
5154 MOZ_ASSERT(val->type() == MIRType::Int32);
5155 return val;
5156 }
5157
5158 /********************************************** WasmGC: array helpers ***/
5159
5160 // Given `arrayObject`, the address of a WasmArrayObject, generate MIR to
5161 // return the contents of the WasmArrayObject::numElements_ field.
5162 // Adds trap site info for the null check.
5163 [[nodiscard]] MDefinition* getWasmArrayObjectNumElements(
5164 MDefinition* arrayObject) {
5165 MOZ_ASSERT(arrayObject->type() == MIRType::WasmAnyRef);
5166
5167 auto* numElements = MWasmLoadField::New(
5168 alloc(), arrayObject, nullptr, WasmArrayObject::offsetOfNumElements(),
5169 mozilla::Nothing(), MIRType::Int32, MWideningOp::None,
5170 AliasSet::Load(AliasSet::WasmArrayNumElements),
5171 mozilla::Some(trapSiteDesc()));
5172 if (!numElements) {
5173 return nullptr;
5174 }
5175 curBlock_->add(numElements);
5176
5177 return numElements;
5178 }
5179
5180 // Given `arrayObject`, the address of a WasmArrayObject, generate MIR to
5181 // return the contents of the WasmArrayObject::data_ field.
5182 [[nodiscard]] MDefinition* getWasmArrayObjectData(MDefinition* arrayObject) {
5183 MOZ_ASSERT(arrayObject->type() == MIRType::WasmAnyRef);
5184
5185 auto* data = MWasmLoadField::New(
5186 alloc(), arrayObject, nullptr, WasmArrayObject::offsetOfData(),
5187 mozilla::Nothing(), MIRType::WasmArrayData, MWideningOp::None,
5188 AliasSet::Load(AliasSet::WasmArrayDataPointer),
5189 mozilla::Some(trapSiteDesc()));
5190 if (!data) {
5191 return nullptr;
5192 }
5193 curBlock_->add(data);
5194
5195 return data;
5196 }
5197
5198 // Given a JIT-time-known type index `typeIndex` and a run-time known number
5199 // of elements `numElements`, create MIR to allocate a new wasm array,
5200 // possibly initialized with `typeIndex`s default value.
5201 [[nodiscard]] MDefinition* createArrayObject(uint32_t typeIndex,
5202 uint32_t allocSiteIndex,
5203 MDefinition* numElements,
5204 bool zeroFields) {
5205 MDefinition* allocSite = loadAllocSiteInstanceData(allocSiteIndex);
5206 if (!allocSite) {
5207 return nullptr;
5208 }
5209
5210 const TypeDef* typeDef = &(*codeMeta().types)[typeIndex];
5211 auto* arrayObject = MWasmNewArrayObject::New(
5212 alloc(), instancePointer_, numElements, allocSite, typeDef, zeroFields,
5213 trapSiteDesc());
5214 if (!arrayObject) {
5215 return nullptr;
5216 }
5217 curBlock_->add(arrayObject);
5218
5219 return arrayObject;
5220 }
5221
5222 // This emits MIR to perform several actions common to array loads and
5223 // stores. Given `arrayObject`, that points to a WasmArrayObject, and an
5224 // index value `index`, it:
5225 //
5226 // * Generates a trap if the array pointer is null
5227 // * Gets the size of the array
5228 // * Emits a bounds check of `index` against the array size
5229 // * Retrieves the OOL object pointer from the array
5230 // * Includes check for null via signal handler.
5231 //
5232 // The returned value is for the OOL object pointer.
5233 [[nodiscard]] MDefinition* setupForArrayAccess(MDefinition* arrayObject,
5234 MDefinition* index) {
5235 MOZ_ASSERT(arrayObject->type() == MIRType::WasmAnyRef);
5236 MOZ_ASSERT(index->type() == MIRType::Int32);
5237
5238 // Check for null is done in getWasmArrayObjectNumElements.
5239
5240 // Get the size value for the array.
5241 MDefinition* numElements = getWasmArrayObjectNumElements(arrayObject);
5242 if (!numElements) {
5243 return nullptr;
5244 }
5245
5246 // Create a bounds check.
5247 auto* boundsCheck =
5248 MWasmBoundsCheck::New(alloc(), index, numElements, trapSiteDesc(),
5249 MWasmBoundsCheck::Target::Unknown);
5250 if (!boundsCheck) {
5251 return nullptr;
5252 }
5253 curBlock_->add(boundsCheck);
5254
5255 // Get the address of the first byte of the (OOL) data area.
5256 return getWasmArrayObjectData(arrayObject);
5257 }
5258
5259 [[nodiscard]] bool fillArray(uint32_t lineOrBytecode,
5260 const ArrayType& arrayType,
5261 MDefinition* arrayObject, MDefinition* index,
5262 MDefinition* numElements, MDefinition* val,
5263 WasmPreBarrierKind preBarrierKind) {
5264 mozilla::DebugOnly<MIRType> valMIRType = val->type();
5265 StorageType elemType = arrayType.elementType();
5266 MOZ_ASSERT(elemType.widenToValType().toMIRType() == valMIRType);
5267
5268 uint32_t elemSize = elemType.size();
5269 MOZ_ASSERT(elemSize >= 1 && elemSize <= 16);
5270
5271 // Make `arrayBase` point at the first byte of the (OOL) data area.
5272 MDefinition* arrayBase = getWasmArrayObjectData(arrayObject);
5273 if (!arrayBase) {
5274 return false;
5275 }
5276
5277 // We have:
5278 // arrayBase : TargetWord
5279 // index : Int32
5280 // numElements : Int32
5281 // val : <any StorageType>
5282 // $elemSize = arrayType.elementType_.size(); 1, 2, 4, 8 or 16
5283 //
5284 // Generate MIR:
5285 // <in current block>
5286 // limit : Int32 = index + numElements
5287 // if (limit == index) goto after; // skip loop if trip count == 0
5288 // loop:
5289 // indexPhi = phi(index, indexNext)
5290 // arrayBase[index * $elemSize] = val
5291 // indexNext = indexPhi + 1
5292 // if (indexNext <u limit) goto loop;
5293 // after:
5294 //
5295 // We construct the loop "manually" rather than using
5296 // FunctionCompiler::{startLoop,closeLoop} as the latter have awareness of
5297 // the wasm view of loops, whereas the loop we're building here is not a
5298 // wasm-level loop.
5299 // ==== Create the "loop" and "after" blocks ====
5300 MBasicBlock* loopBlock;
5301 if (!newBlock(curBlock_, &loopBlock, MBasicBlock::LOOP_HEADER)) {
5302 return false;
5303 }
5304 MBasicBlock* afterBlock;
5305 if (!newBlock(loopBlock, &afterBlock)) {
5306 return false;
5307 }
5308
5309 // ==== Fill in the remainder of the block preceding the loop ====
5310 MAdd* limit = MAdd::NewWasm(alloc(), index, numElements, MIRType::Int32);
5311 if (!limit) {
5312 return false;
5313 }
5314 curBlock_->add(limit);
5315
5316 // Note: the comparison (and eventually the entire initialisation loop) will
5317 // be folded out in the case where the number of elements is zero.
5318 // See MCompare::tryFoldEqualOperands.
5319 MDefinition* limitEqualsBase =
5320 compare(limit, index, JSOp::StrictEq, MCompare::Compare_UInt32);
5321 if (!limitEqualsBase) {
5322 return false;
5323 }
5324 MTest* skipIfLimitEqualsBase =
5325 MTest::New(alloc(), limitEqualsBase, afterBlock, loopBlock);
5326 if (!skipIfLimitEqualsBase) {
5327 return false;
5328 }
5329 curBlock_->end(skipIfLimitEqualsBase);
5330 if (!afterBlock->addPredecessor(alloc(), curBlock_)) {
5331 return false;
5332 }
5333
5334 // ==== Fill in the loop block as best we can ====
5335 curBlock_ = loopBlock;
5336 MPhi* indexPhi = MPhi::New(alloc(), MIRType::Int32);
5337 if (!indexPhi) {
5338 return false;
5339 }
5340 if (!indexPhi->reserveLength(2)) {
5341 return false;
5342 }
5343 indexPhi->addInput(index);
5344 curBlock_->addPhi(indexPhi);
5345 curBlock_->setLoopDepth(rootCompiler_.loopDepth() + 1);
5346
5347 if (!writeGcValueAtBasePlusScaledIndex(
5348 lineOrBytecode, elemType, arrayObject, AliasSet::WasmArrayDataArea,
5349 val, arrayBase, elemSize, indexPhi, preBarrierKind)) {
5350 return false;
5351 }
5352
5353 auto* indexNext =
5354 MAdd::NewWasm(alloc(), indexPhi, constantI32(1), MIRType::Int32);
5355 if (!indexNext) {
5356 return false;
5357 }
5358 curBlock_->add(indexNext);
5359 indexPhi->addInput(indexNext);
5360
5361 MDefinition* indexNextLtuLimit =
5362 compare(indexNext, limit, JSOp::Lt, MCompare::Compare_UInt32);
5363 if (!indexNextLtuLimit) {
5364 return false;
5365 }
5366 auto* continueIfIndexNextLtuLimit =
5367 MTest::New(alloc(), indexNextLtuLimit, loopBlock, afterBlock);
5368 if (!continueIfIndexNextLtuLimit) {
5369 return false;
5370 }
5371 curBlock_->end(continueIfIndexNextLtuLimit);
5372 if (!loopBlock->addPredecessor(alloc(), loopBlock)) {
5373 return false;
5374 }
5375 // ==== Loop block completed ====
5376
5377 curBlock_ = afterBlock;
5378 return true;
5379 }
5380
5381 // This routine generates all MIR required for `array.new`. The returned
5382 // value is for the newly created array.
5383 [[nodiscard]] MDefinition* createArrayNewCallAndLoop(uint32_t lineOrBytecode,
5384 uint32_t typeIndex,
5385 uint32_t allocSiteIndex,
5386 MDefinition* numElements,
5387 MDefinition* fillValue) {
5388 // Create the array object, uninitialized.
5389 MDefinition* arrayObject =
5390 createArrayObject(typeIndex, allocSiteIndex, numElements,
5391 /*zeroFields=*/false);
5392 if (!arrayObject) {
5393 return nullptr;
5394 }
5395
5396 // Optimisation opportunity: if the fill value is zero, maybe we should
5397 // likewise skip over the initialisation loop entirely (and, if the zero
5398 // value is visible at JIT time, the loop will be removed). For the
5399 // reftyped case, that would be a big win since each iteration requires a
5400 // call to the post-write barrier routine.
5401
5402 const ArrayType& arrayType = (*codeMeta().types)[typeIndex].arrayType();
5403 if (!fillArray(lineOrBytecode, arrayType, arrayObject, constantI32(0),
5404 numElements, fillValue, WasmPreBarrierKind::None)) {
5405 return nullptr;
5406 }
5407
5408 return arrayObject;
5409 }
5410
5411 [[nodiscard]] bool createArrayCopy(uint32_t lineOrBytecode,
5412 MDefinition* dstArrayObject,
5413 MDefinition* dstArrayIndex,
5414 MDefinition* srcArrayObject,
5415 MDefinition* srcArrayIndex,
5416 MDefinition* numElements, int32_t elemSize,
5417 bool elemsAreRefTyped) {
5418 // Check for null is done in getWasmArrayObjectNumElements.
5419
5420 // Get the arrays' actual sizes.
5421 MDefinition* dstNumElements = getWasmArrayObjectNumElements(dstArrayObject);
5422 if (!dstNumElements) {
5423 return false;
5424 }
5425 MDefinition* srcNumElements = getWasmArrayObjectNumElements(srcArrayObject);
5426 if (!srcNumElements) {
5427 return false;
5428 }
5429
5430 // Create the bounds checks.
5431 MInstruction* dstBoundsCheck = MWasmBoundsCheckRange32::New(
5432 alloc(), dstArrayIndex, numElements, dstNumElements, trapSiteDesc());
5433 if (!dstBoundsCheck) {
5434 return false;
5435 }
5436 curBlock_->add(dstBoundsCheck);
5437
5438 MInstruction* srcBoundsCheck = MWasmBoundsCheckRange32::New(
5439 alloc(), srcArrayIndex, numElements, srcNumElements, trapSiteDesc());
5440 if (!srcBoundsCheck) {
5441 return false;
5442 }
5443 curBlock_->add(srcBoundsCheck);
5444
5445 // Check if numElements != 0 -- optimization to not invoke builtins.
5446 MBasicBlock* copyBlock = nullptr;
5447 if (!newBlock(curBlock_, &copyBlock)) {
5448 return false;
5449 }
5450 MBasicBlock* joinBlock = nullptr;
5451 if (!newBlock(curBlock_, &joinBlock)) {
5452 return false;
5453 }
5454
5455 MInstruction* condition =
5456 MCompare::NewWasm(alloc(), numElements, constantI32(0), JSOp::StrictEq,
5457 MCompare::Compare_UInt32);
5458 curBlock_->add(condition);
5459
5460 MTest* test = MTest::New(alloc(), condition, joinBlock, copyBlock);
5461 if (!test) {
5462 return false;
5463 }
5464 curBlock_->end(test);
5465 curBlock_ = copyBlock;
5466
5467 MInstruction* dstData = MWasmLoadField::New(
5468 alloc(), dstArrayObject, nullptr, WasmArrayObject::offsetOfData(),
5469 mozilla::Nothing(), MIRType::WasmArrayData, MWideningOp::None,
5470 AliasSet::Load(AliasSet::WasmArrayDataPointer));
5471 if (!dstData) {
5472 return false;
5473 }
5474 curBlock_->add(dstData);
5475
5476 MInstruction* srcData = MWasmLoadField::New(
5477 alloc(), srcArrayObject, nullptr, WasmArrayObject::offsetOfData(),
5478 mozilla::Nothing(), MIRType::WasmArrayData, MWideningOp::None,
5479 AliasSet::Load(AliasSet::WasmArrayDataPointer));
5480 if (!srcData) {
5481 return false;
5482 }
5483 curBlock_->add(srcData);
5484
5485 if (elemsAreRefTyped) {
5486 MOZ_RELEASE_ASSERT(elemSize == sizeof(void*));
5487
5488 if (!builtinCall5(SASigArrayRefsMove, lineOrBytecode, dstData,
5489 dstArrayIndex, srcData, srcArrayIndex, numElements,
5490 nullptr)) {
5491 return false;
5492 }
5493 } else {
5494 MDefinition* elemSizeDef = constantI32(elemSize);
5495 if (!elemSizeDef) {
5496 return false;
5497 }
5498
5499 if (!builtinCall6(SASigArrayMemMove, lineOrBytecode, dstData,
5500 dstArrayIndex, srcData, srcArrayIndex, elemSizeDef,
5501 numElements, nullptr)) {
5502 return false;
5503 }
5504 }
5505
5506 MGoto* fallthrough = MGoto::New(alloc(), joinBlock);
5507 if (!fallthrough) {
5508 return false;
5509 }
5510 curBlock_->end(fallthrough);
5511 if (!joinBlock->addPredecessor(alloc(), curBlock_)) {
5512 return false;
5513 }
5514 curBlock_ = joinBlock;
5515 return true;
5516 }
5517
5518 [[nodiscard]] bool createArrayFill(uint32_t lineOrBytecode,
5519 uint32_t typeIndex,
5520 MDefinition* arrayObject,
5521 MDefinition* index, MDefinition* val,
5522 MDefinition* numElements) {
5523 MOZ_ASSERT(arrayObject->type() == MIRType::WasmAnyRef);
5524 MOZ_ASSERT(index->type() == MIRType::Int32);
5525 MOZ_ASSERT(numElements->type() == MIRType::Int32);
5526
5527 const ArrayType& arrayType = (*codeMeta().types)[typeIndex].arrayType();
5528
5529 // Check for null is done in getWasmArrayObjectNumElements.
5530
5531 // Get the array's actual size.
5532 MDefinition* actualNumElements = getWasmArrayObjectNumElements(arrayObject);
5533 if (!actualNumElements) {
5534 return false;
5535 }
5536
5537 // Create a bounds check.
5538 auto* boundsCheck = MWasmBoundsCheckRange32::New(
5539 alloc(), index, numElements, actualNumElements, trapSiteDesc());
5540 if (!boundsCheck) {
5541 return false;
5542 }
5543 curBlock_->add(boundsCheck);
5544
5545 return fillArray(lineOrBytecode, arrayType, arrayObject, index, numElements,
5546 val, WasmPreBarrierKind::Normal);
5547 }
5548
5549 /*********************************************** WasmGC: other helpers ***/
5550
5551 // Generate MIR that causes a trap of kind `trapKind` if `arg` is zero.
5552 // Currently `arg` may only be a MIRType::Int32, but that requirement could
5553 // be relaxed if needed in future.
5554 [[nodiscard]] bool trapIfZero(wasm::Trap trapKind, MDefinition* arg) {
5555 MOZ_ASSERT(arg->type() == MIRType::Int32);
5556
5557 MBasicBlock* trapBlock = nullptr;
5558 if (!newBlock(curBlock_, &trapBlock)) {
5559 return false;
5560 }
5561
5562 auto* trap = MWasmTrap::New(alloc(), trapKind, trapSiteDesc());
5563 if (!trap) {
5564 return false;
5565 }
5566 trapBlock->end(trap);
5567
5568 MBasicBlock* joinBlock = nullptr;
5569 if (!newBlock(curBlock_, &joinBlock)) {
5570 return false;
5571 }
5572
5573 auto* test = MTest::New(alloc(), arg, joinBlock, trapBlock);
5574 if (!test) {
5575 return false;
5576 }
5577 curBlock_->end(test);
5578 curBlock_ = joinBlock;
5579 return true;
5580 }
5581
5582 // Generate MIR that attempts to cast `ref` to `castToTypeDef`. If the
5583 // cast fails, we trap. If it succeeds, then `ref` can be assumed to
5584 // have a type that is a subtype of (or the same as) `castToTypeDef` after
5585 // this point.
5586 [[nodiscard]] MDefinition* refCast(MDefinition* ref, RefType destType) {
5587 MInstruction* cast = nullptr;
5588 if (destType.isTypeRef()) {
5589 uint32_t typeIndex = codeMeta().types->indexOf(*destType.typeDef());
5590 MDefinition* superSTV = loadSuperTypeVector(typeIndex);
5591 if (!superSTV) {
5592 return nullptr;
5593 }
5594 cast = MWasmRefCastConcrete::New(alloc(), ref, superSTV, destType,
5595 trapSiteDesc());
5596 } else {
5597 cast = MWasmRefCastAbstract::New(alloc(), ref, destType, trapSiteDesc());
5598 }
5599
5600 if (!cast) {
5601 return nullptr;
5602 }
5603 curBlock_->add(cast);
5604 return cast;
5605 }
5606
5607 // Generate MIR that computes a boolean value indicating whether or not it
5608 // is possible to cast `ref` to `destType`.
5609 [[nodiscard]] MDefinition* refTest(MDefinition* ref, RefType destType) {
5610 MInstruction* isSubTypeOf = nullptr;
5611 if (destType.isTypeRef()) {
5612 uint32_t typeIndex = codeMeta().types->indexOf(*destType.typeDef());
5613 MDefinition* superSTV = loadSuperTypeVector(typeIndex);
5614 if (!superSTV) {
5615 return nullptr;
5616 }
5617 isSubTypeOf = MWasmRefTestConcrete::New(alloc(), ref, superSTV, destType);
5618 } else {
5619 isSubTypeOf = MWasmRefTestAbstract::New(alloc(), ref, destType);
5620 }
5621 MOZ_ASSERT(isSubTypeOf);
5622
5623 curBlock_->add(isSubTypeOf);
5624 return isSubTypeOf;
5625 }
5626
5627 // Generates MIR for br_on_cast and br_on_cast_fail.
5628 [[nodiscard]] bool brOnCastCommon(bool onSuccess, uint32_t labelRelativeDepth,
5629 RefType sourceType, RefType destType,
5630 const ResultType& labelType,
5631 const DefVector& values) {
5632 if (inDeadCode()) {
5633 return true;
5634 }
5635
5636 MBasicBlock* fallthroughBlock = nullptr;
5637 if (!newBlock(curBlock_, &fallthroughBlock)) {
5638 return false;
5639 }
5640
5641 // `values` are the values in the top block-value on the stack. Since the
5642 // argument to `br_on_cast{_fail}` is at the top of the stack, it is the
5643 // last element in `values`.
5644 //
5645 // For both br_on_cast and br_on_cast_fail, the OpIter validation routines
5646 // ensure that `values` is non-empty (by rejecting the case
5647 // `labelType->length() < 1`) and that the last value in `values` is
5648 // reftyped.
5649 MOZ_RELEASE_ASSERT(values.length() > 0);
5650 MDefinition* ref = values.back();
5651 MOZ_ASSERT(ref->type() == MIRType::WasmAnyRef);
5652
5653 MDefinition* success = refTest(ref, destType);
5654 if (!success) {
5655 return false;
5656 }
5657
5658 MTest* test;
5659 if (onSuccess) {
5660 test = MTest::New(alloc(), success, nullptr, fallthroughBlock);
5661 if (!test || !addControlFlowPatch(test, labelRelativeDepth,
5662 MTest::TrueBranchIndex)) {
5663 return false;
5664 }
5665 } else {
5666 test = MTest::New(alloc(), success, fallthroughBlock, nullptr);
5667 if (!test || !addControlFlowPatch(test, labelRelativeDepth,
5668 MTest::FalseBranchIndex)) {
5669 return false;
5670 }
5671 }
5672
5673 if (!pushDefs(values)) {
5674 return false;
5675 }
5676
5677 curBlock_->end(test);
5678 curBlock_ = fallthroughBlock;
5679 return true;
5680 }
5681
5682 [[nodiscard]] bool brOnNonStruct(const DefVector& values) {
5683 if (inDeadCode()) {
5684 return true;
5685 }
5686
5687 MBasicBlock* fallthroughBlock = nullptr;
5688 if (!newBlock(curBlock_, &fallthroughBlock)) {
5689 return false;
5690 }
5691
5692 MOZ_ASSERT(values.length() > 0);
5693 MOZ_ASSERT(values.back()->type() == MIRType::WasmAnyRef);
5694
5695 MGoto* jump = MGoto::New(alloc(), fallthroughBlock);
5696 if (!jump) {
5697 return false;
5698 }
5699 if (!pushDefs(values)) {
5700 return false;
5701 }
5702
5703 curBlock_->end(jump);
5704 curBlock_ = fallthroughBlock;
5705 return true;
5706 }
5707
5708 [[nodiscard]] MDefinition* convertAnyExtern(MDefinition* ref,
5709 wasm::RefType::Kind kind) {
5710 auto* converted = MWasmRefConvertAnyExtern::New(alloc(), ref, kind);
5711 if (!converted) {
5712 return nullptr;
5713 }
5714 curBlock_->add(converted);
5715 return converted;
5716 }
5717
5718 /************************************************************ DECODING ***/
5719
5720 // AsmJS adds a line number to `callSiteLineNums` for certain operations that
5721 // are represented by a JS call, such as math builtins. We use these line
5722 // numbers when calling builtins. This method will read from
5723 // `callSiteLineNums` when we are using AsmJS, or else return the current
5724 // bytecode offset.
5725 //
5726 // This method MUST be called from opcodes that AsmJS will emit a call site
5727 // line number for, or else the arrays will get out of sync. Other opcodes
5728 // must use `readBytecodeOffset` below.
5729 uint32_t readCallSiteLineOrBytecode() {
5730 if (!func_.callSiteLineNums.empty()) {
5731 return func_.callSiteLineNums[lastReadCallSite_++];
5732 }
5733 return iter_.lastOpcodeOffset();
5734 }
5735
5736 // Return the current bytecode offset.
5737 uint32_t readBytecodeOffset() { return iter_.lastOpcodeOffset(); }
5738
5739 CallRefHint readCallRefHint() {
5740 // We don't track anything if we're not using lazy tiering
5741 if (compilerEnv().mode() != CompileMode::LazyTiering) {
5742 return CallRefHint();
5743 }
5744
5745 CallRefMetricsRange rangeInModule =
5746 codeTailMeta()->getFuncDefCallRefs(funcIndex());
5747 uint32_t localIndex = numCallRefs_++;
5748 MOZ_RELEASE_ASSERT(localIndex < rangeInModule.length);
5749 uint32_t moduleIndex = rangeInModule.begin + localIndex;
5750 return codeTailMeta()->getCallRefHint(moduleIndex);
5751 }
5752
5753 #if DEBUG
5754 bool done() const { return iter_.done(); }
5755 #endif
5756
5757 /*************************************************************************/
5758 private:
5759 [[nodiscard]] bool newBlock(MBasicBlock* pred, MBasicBlock** block,
5760 MBasicBlock::Kind kind = MBasicBlock::NORMAL) {
5761 *block = MBasicBlock::New(mirGraph(), info(), pred, kind);
5762 if (!*block) {
5763 return false;
5764 }
5765 mirGraph().addBlock(*block);
5766 (*block)->setLoopDepth(rootCompiler_.loopDepth());
5767 return true;
5768 }
5769
5770 [[nodiscard]] bool goToNewBlock(MBasicBlock* pred, MBasicBlock** block) {
5771 if (!newBlock(pred, block)) {
5772 return false;
5773 }
5774 pred->end(MGoto::New(alloc(), *block));
5775 return true;
5776 }
5777
5778 [[nodiscard]] bool goToExistingBlock(MBasicBlock* prev, MBasicBlock* next) {
5779 MOZ_ASSERT(prev);
5780 MOZ_ASSERT(next);
5781 prev->end(MGoto::New(alloc(), next));
5782 return next->addPredecessor(alloc(), prev);
5783 }
5784
5785 [[nodiscard]] bool bindBranches(uint32_t absolute, DefVector* defs) {
5786 if (absolute >= pendingBlocks_.length() ||
5787 pendingBlocks_[absolute].patches.empty()) {
5788 return inDeadCode() || popPushedDefs(defs);
5789 }
5790
5791 ControlFlowPatchVector& patches = pendingBlocks_[absolute].patches;
5792 MControlInstruction* ins = patches[0].ins;
5793 MBasicBlock* pred = ins->block();
5794
5795 MBasicBlock* join = nullptr;
5796 if (!newBlock(pred, &join)) {
5797 return false;
5798 }
5799
5800 // Use branch hinting information if any.
5801 if (pendingBlocks_[absolute].hint != BranchHint::Invalid) {
5802 join->setBranchHinting(pendingBlocks_[absolute].hint);
5803 }
5804
5805 pred->mark();
5806 ins->replaceSuccessor(patches[0].index, join);
5807
5808 for (size_t i = 1; i < patches.length(); i++) {
5809 ins = patches[i].ins;
5810
5811 pred = ins->block();
5812 if (!pred->isMarked()) {
5813 if (!join->addPredecessor(alloc(), pred)) {
5814 return false;
5815 }
5816 pred->mark();
5817 }
5818
5819 ins->replaceSuccessor(patches[i].index, join);
5820 }
5821
5822 MOZ_ASSERT_IF(curBlock_, !curBlock_->isMarked());
5823 for (uint32_t i = 0; i < join->numPredecessors(); i++) {
5824 join->getPredecessor(i)->unmark();
5825 }
5826
5827 if (curBlock_ && !goToExistingBlock(curBlock_, join)) {
5828 return false;
5829 }
5830
5831 curBlock_ = join;
5832
5833 if (!popPushedDefs(defs)) {
5834 return false;
5835 }
5836
5837 patches.clear();
5838 return true;
5839 }
5840
5841 bool emitI32Const();
5842 bool emitI64Const();
5843 bool emitF32Const();
5844 bool emitF64Const();
5845 bool emitBlock();
5846 bool emitLoop();
5847 bool emitIf();
5848 bool emitElse();
5849 bool emitEnd();
5850 bool emitBr();
5851 bool emitBrIf();
5852 bool emitBrTable();
5853 bool emitReturn();
5854 bool emitUnreachable();
5855 bool emitTry();
5856 bool emitCatch();
5857 bool emitCatchAll();
5858 bool emitTryTable();
5859 bool emitDelegate();
5860 bool emitThrow();
5861 bool emitThrowRef();
5862 bool emitRethrow();
5863 bool emitInlineCall(const FuncType& funcType, uint32_t funcIndex,
5864 InliningHeuristics::CallKind callKind,
5865 const DefVector& args, DefVector* results);
5866 bool emitCall(bool asmJSFuncDef);
5867 bool emitCallIndirect(bool oldStyle);
5868 bool emitStackSwitch();
5869 bool emitReturnCall();
5870 bool emitReturnCallIndirect();
5871 bool emitReturnCallRef();
5872 bool emitGetLocal();
5873 bool emitSetLocal();
5874 bool emitTeeLocal();
5875 bool emitGetGlobal();
5876 bool emitSetGlobal();
5877 bool emitTeeGlobal();
5878 template <typename MIRClass>
5879 bool emitUnary(ValType operandType);
5880 template <typename MIRClass>
5881 bool emitConversion(ValType operandType, ValType resultType);
5882 template <typename MIRClass>
5883 bool emitUnaryWithType(ValType operandType, MIRType mirType);
5884 template <typename MIRClass>
5885 bool emitConversionWithType(ValType operandType, ValType resultType,
5886 MIRType mirType);
5887 bool emitTruncate(ValType operandType, ValType resultType, bool isUnsigned,
5888 bool isSaturating);
5889 bool emitSignExtend(uint32_t srcSize, uint32_t targetSize);
5890 bool emitExtendI32(bool isUnsigned);
5891 bool emitConvertI64ToFloatingPoint(ValType resultType, MIRType mirType,
5892 bool isUnsigned);
5893 bool emitReinterpret(ValType resultType, ValType operandType,
5894 MIRType mirType);
5895 bool emitAdd(ValType type, MIRType mirType);
5896 bool emitSub(ValType type, MIRType mirType);
5897 bool emitRotate(ValType type, bool isLeftRotation);
5898 bool emitBitNot(ValType operandType, MIRType mirType);
5899 bool emitBitwiseAndOrXor(ValType operandType, MIRType mirType,
5900 MWasmBinaryBitwise::SubOpcode subOpc);
5901 template <typename MIRClass>
5902 bool emitShift(ValType operandType, MIRType mirType);
5903 bool emitUrsh(ValType operandType, MIRType mirType);
5904 bool emitMul(ValType operandType, MIRType mirType);
5905 bool emitDiv(ValType operandType, MIRType mirType, bool isUnsigned);
5906 bool emitRem(ValType operandType, MIRType mirType, bool isUnsigned);
5907 bool emitMinMax(ValType operandType, MIRType mirType, bool isMax);
5908 bool emitCopySign(ValType operandType);
5909 bool emitComparison(ValType operandType, JSOp compareOp,
5910 MCompare::CompareType compareType);
5911 bool emitSelect(bool typed);
5912 bool emitLoad(ValType type, Scalar::Type viewType);
5913 bool emitStore(ValType resultType, Scalar::Type viewType);
5914 bool emitTeeStore(ValType resultType, Scalar::Type viewType);
5915 bool emitTeeStoreWithCoercion(ValType resultType, Scalar::Type viewType);
5916 bool tryInlineUnaryBuiltin(SymbolicAddress callee, MDefinition* input);
5917 bool emitUnaryMathBuiltinCall(const SymbolicAddressSignature& callee);
5918 bool emitBinaryMathBuiltinCall(const SymbolicAddressSignature& callee);
5919 bool emitMemoryGrow();
5920 bool emitMemorySize();
5921 bool emitAtomicCmpXchg(ValType type, Scalar::Type viewType);
5922 bool emitAtomicLoad(ValType type, Scalar::Type viewType);
5923 bool emitAtomicRMW(ValType type, Scalar::Type viewType, jit::AtomicOp op);
5924 bool emitAtomicStore(ValType type, Scalar::Type viewType);
5925 bool emitWait(ValType type, uint32_t byteSize);
5926 bool emitFence();
5927 bool emitNotify();
5928 bool emitAtomicXchg(ValType type, Scalar::Type viewType);
5929 bool emitMemCopyCall(uint32_t dstMemIndex, uint32_t srcMemIndex,
5930 MDefinition* dst, MDefinition* src, MDefinition* len);
5931 bool emitMemCopyInline(uint32_t memoryIndex, MDefinition* dst,
5932 MDefinition* src, uint32_t length);
5933 bool emitMemCopy();
5934 bool emitTableCopy();
5935 bool emitDataOrElemDrop(bool isData);
5936 bool emitMemFillCall(uint32_t memoryIndex, MDefinition* start,
5937 MDefinition* val, MDefinition* len);
5938 bool emitMemFillInline(uint32_t memoryIndex, MDefinition* start,
5939 MDefinition* val, uint32_t length);
5940 bool emitMemFill();
5941 bool emitMemInit();
5942 bool emitTableInit();
5943 bool emitTableFill();
5944 bool emitMemDiscard();
5945 bool emitTableGet();
5946 bool emitTableGrow();
5947 bool emitTableSet();
5948 bool emitTableSize();
5949 bool emitRefFunc();
5950 bool emitRefNull();
5951 bool emitRefIsNull();
5952 bool emitConstSimd128();
5953 bool emitBinarySimd128(bool commutative, SimdOp op);
5954 bool emitTernarySimd128(wasm::SimdOp op);
5955 bool emitShiftSimd128(SimdOp op);
5956 bool emitSplatSimd128(ValType inType, SimdOp op);
5957 bool emitUnarySimd128(SimdOp op);
5958 bool emitReduceSimd128(SimdOp op);
5959 bool emitExtractLaneSimd128(ValType outType, uint32_t laneLimit, SimdOp op);
5960 bool emitReplaceLaneSimd128(ValType laneType, uint32_t laneLimit, SimdOp op);
5961 bool emitShuffleSimd128();
5962 bool emitLoadSplatSimd128(Scalar::Type viewType, wasm::SimdOp splatOp);
5963 bool emitLoadExtendSimd128(wasm::SimdOp op);
5964 bool emitLoadZeroSimd128(Scalar::Type viewType, size_t numBytes);
5965 bool emitLoadLaneSimd128(uint32_t laneSize);
5966 bool emitStoreLaneSimd128(uint32_t laneSize);
5967 bool emitRefAsNonNull();
5968 bool emitBrOnNull();
5969 bool emitBrOnNonNull();
5970 bool emitSpeculativeInlineCallRef(uint32_t bytecodeOffset,
5971 const FuncType& funcType,
5972 CallRefHint expectedFuncIndices,
5973 MDefinition* actualCalleeFunc,
5974 const DefVector& args, DefVector* results);
5975 bool emitCallRef();
5976 bool emitStructNew();
5977 bool emitStructNewDefault();
5978 bool emitStructSet();
5979 bool emitStructGet(FieldWideningOp wideningOp);
5980 bool emitArrayNew();
5981 bool emitArrayNewDefault();
5982 bool emitArrayNewFixed();
5983 bool emitArrayNewData();
5984 bool emitArrayNewElem();
5985 bool emitArrayInitData();
5986 bool emitArrayInitElem();
5987 bool emitArraySet();
5988 bool emitArrayGet(FieldWideningOp wideningOp);
5989 bool emitArrayLen();
5990 bool emitArrayCopy();
5991 bool emitArrayFill();
5992 bool emitRefI31();
5993 bool emitI31Get(FieldWideningOp wideningOp);
5994 bool emitRefTest(bool nullable);
5995 bool emitRefCast(bool nullable);
5996 bool emitBrOnCast(bool onSuccess);
5997 bool emitAnyConvertExtern();
5998 bool emitExternConvertAny();
5999 bool emitCallBuiltinModuleFunc();
6000
6001 public:
6002 bool emitBodyExprs();
6003 };
6004
6005 template <>
6006 MDefinition* FunctionCompiler::unary<MToFloat32>(MDefinition* op) {
6007 if (inDeadCode()) {
6008 return nullptr;
6009 }
6010 auto* ins = MToFloat32::New(alloc(), op, mustPreserveNaN(op->type()));
6011 curBlock_->add(ins);
6012 return ins;
6013 }
6014
6015 template <>
6016 MDefinition* FunctionCompiler::unary<MWasmBuiltinTruncateToInt32>(
6017 MDefinition* op) {
6018 if (inDeadCode()) {
6019 return nullptr;
6020 }
6021 auto* ins = MWasmBuiltinTruncateToInt32::New(
6022 alloc(), op, instancePointer_, trapSiteDescWithCallSiteLineNumber());
6023 curBlock_->add(ins);
6024 return ins;
6025 }
6026
6027 template <>
6028 MDefinition* FunctionCompiler::unary<MNot>(MDefinition* op) {
6029 if (inDeadCode()) {
6030 return nullptr;
6031 }
6032 auto* ins = MNot::NewInt32(alloc(), op);
6033 curBlock_->add(ins);
6034 return ins;
6035 }
6036
6037 template <>
6038 MDefinition* FunctionCompiler::unary<MAbs>(MDefinition* op, MIRType type) {
6039 if (inDeadCode()) {
6040 return nullptr;
6041 }
6042 auto* ins = MAbs::NewWasm(alloc(), op, type);
6043 curBlock_->add(ins);
6044 return ins;
6045 }
6046
6047 bool FunctionCompiler::emitI32Const() {
6048 int32_t i32;
6049 if (!iter().readI32Const(&i32)) {
6050 return false;
6051 }
6052
6053 iter().setResult(constantI32(i32));
6054 return true;
6055 }
6056
6057 bool FunctionCompiler::emitI64Const() {
6058 int64_t i64;
6059 if (!iter().readI64Const(&i64)) {
6060 return false;
6061 }
6062
6063 iter().setResult(constantI64(i64));
6064 return true;
6065 }
6066
6067 bool FunctionCompiler::emitF32Const() {
6068 float f32;
6069 if (!iter().readF32Const(&f32)) {
6070 return false;
6071 }
6072
6073 iter().setResult(constantF32(f32));
6074 return true;
6075 }
6076
6077 bool FunctionCompiler::emitF64Const() {
6078 double f64;
6079 if (!iter().readF64Const(&f64)) {
6080 return false;
6081 }
6082
6083 iter().setResult(constantF64(f64));
6084 return true;
6085 }
6086
6087 bool FunctionCompiler::emitBlock() {
6088 BlockType type;
6089 return iter().readBlock(&type) && startBlock();
6090 }
6091
6092 bool FunctionCompiler::emitLoop() {
6093 BlockType type;
6094 if (!iter().readLoop(&type)) {
6095 return false;
6096 }
6097
6098 MBasicBlock* loopHeader;
6099 if (!startLoop(&loopHeader, type.params().length())) {
6100 return false;
6101 }
6102
6103 addInterruptCheck();
6104
6105 iter().controlItem().block = loopHeader;
6106 return true;
6107 }
6108
6109 bool FunctionCompiler::emitIf() {
6110 BranchHint branchHint =
6111 iter().getBranchHint(funcIndex(), relativeBytecodeOffset());
6112
6113 BlockType type;
6114 MDefinition* condition = nullptr;
6115 if (!iter().readIf(&type, &condition)) {
6116 return false;
6117 }
6118
6119 MBasicBlock* elseBlock;
6120 if (!branchAndStartThen(condition, &elseBlock)) {
6121 return false;
6122 }
6123
6124 // Store the branch hint in the basic block.
6125 if (!inDeadCode() && branchHint != BranchHint::Invalid) {
6126 getCurBlock()->setBranchHinting(branchHint);
6127 }
6128
6129 iter().controlItem().block = elseBlock;
6130 return true;
6131 }
6132
6133 bool FunctionCompiler::emitElse() {
6134 ResultType paramType;
6135 ResultType resultType;
6136 DefVector thenValues;
6137 if (!iter().readElse(&paramType, &resultType, &thenValues)) {
6138 return false;
6139 }
6140
6141 if (!pushDefs(thenValues)) {
6142 return false;
6143 }
6144
6145 Control& control = iter().controlItem();
6146 return switchToElse(control.block, &control.block);
6147 }
6148
6149 bool FunctionCompiler::emitEnd() {
6150 LabelKind kind;
6151 ResultType type;
6152 DefVector preJoinDefs;
6153 DefVector resultsForEmptyElse;
6154 if (!iter().readEnd(&kind, &type, &preJoinDefs, &resultsForEmptyElse)) {
6155 return false;
6156 }
6157
6158 Control& control = iter().controlItem();
6159 MBasicBlock* block = control.block;
6160
6161 if (!pushDefs(preJoinDefs)) {
6162 return false;
6163 }
6164
6165 // Every label case is responsible to pop the control item at the appropriate
6166 // time for the label case
6167 DefVector postJoinDefs;
6168 switch (kind) {
6169 case LabelKind::Body: {
6170 MOZ_ASSERT(!control.tryControl);
6171 if (!emitBodyRethrowPad(control)) {
6172 return false;
6173 }
6174 if (!finishBlock(&postJoinDefs)) {
6175 return false;
6176 }
6177 if (!returnValues(std::move(postJoinDefs))) {
6178 return false;
6179 }
6180 iter().popEnd();
6181 MOZ_ASSERT(iter().controlStackEmpty());
6182 return iter().endFunction(iter().end());
6183 }
6184 case LabelKind::Block:
6185 MOZ_ASSERT(!control.tryControl);
6186 if (!finishBlock(&postJoinDefs)) {
6187 return false;
6188 }
6189 iter().popEnd();
6190 break;
6191 case LabelKind::Loop:
6192 MOZ_ASSERT(!control.tryControl);
6193 if (!closeLoop(block, &postJoinDefs)) {
6194 return false;
6195 }
6196 iter().popEnd();
6197 break;
6198 case LabelKind::Then: {
6199 MOZ_ASSERT(!control.tryControl);
6200 // If we didn't see an Else, create a trivial else block so that we create
6201 // a diamond anyway, to preserve Ion invariants.
6202 if (!switchToElse(block, &block)) {
6203 return false;
6204 }
6205
6206 if (!pushDefs(resultsForEmptyElse)) {
6207 return false;
6208 }
6209
6210 if (!joinIfElse(block, &postJoinDefs)) {
6211 return false;
6212 }
6213 iter().popEnd();
6214 break;
6215 }
6216 case LabelKind::Else:
6217 MOZ_ASSERT(!control.tryControl);
6218 if (!joinIfElse(block, &postJoinDefs)) {
6219 return false;
6220 }
6221 iter().popEnd();
6222 break;
6223 case LabelKind::Try:
6224 case LabelKind::Catch:
6225 case LabelKind::CatchAll:
6226 MOZ_ASSERT(control.tryControl);
6227 if (!finishTryCatch(kind, control, &postJoinDefs)) {
6228 return false;
6229 }
6230 rootCompiler().freeTryControl(std::move(control.tryControl));
6231 iter().popEnd();
6232 break;
6233 case LabelKind::TryTable:
6234 MOZ_ASSERT(control.tryControl);
6235 if (!finishTryTable(control, &postJoinDefs)) {
6236 return false;
6237 }
6238 rootCompiler().freeTryControl(std::move(control.tryControl));
6239 iter().popEnd();
6240 break;
6241 }
6242
6243 MOZ_ASSERT_IF(!inDeadCode(), postJoinDefs.length() == type.length());
6244 iter().setResults(postJoinDefs.length(), postJoinDefs);
6245
6246 return true;
6247 }
6248
6249 bool FunctionCompiler::emitBr() {
6250 uint32_t relativeDepth;
6251 ResultType type;
6252 DefVector values;
6253 if (!iter().readBr(&relativeDepth, &type, &values)) {
6254 return false;
6255 }
6256
6257 return br(relativeDepth, values);
6258 }
6259
6260 bool FunctionCompiler::emitBrIf() {
6261 uint32_t relativeDepth;
6262 ResultType type;
6263 DefVector values;
6264 MDefinition* condition;
6265
6266 BranchHint branchHint =
6267 iter().getBranchHint(funcIndex(), relativeBytecodeOffset());
6268
6269 if (!iter().readBrIf(&relativeDepth, &type, &values, &condition)) {
6270 return false;
6271 }
6272
6273 return brIf(relativeDepth, values, condition, branchHint);
6274 }
6275
6276 bool FunctionCompiler::emitBrTable() {
6277 Uint32Vector depths;
6278 uint32_t defaultDepth;
6279 ResultType branchValueType;
6280 DefVector branchValues;
6281 MDefinition* index;
6282 if (!iter().readBrTable(&depths, &defaultDepth, &branchValueType,
6283 &branchValues, &index)) {
6284 return false;
6285 }
6286
6287 // If all the targets are the same, or there are no targets, we can just
6288 // use a goto. This is not just an optimization: MaybeFoldConditionBlock
6289 // assumes that tables have more than one successor.
6290 bool allSameDepth = true;
6291 for (uint32_t depth : depths) {
6292 if (depth != defaultDepth) {
6293 allSameDepth = false;
6294 break;
6295 }
6296 }
6297
6298 if (allSameDepth) {
6299 return br(defaultDepth, branchValues);
6300 }
6301
6302 return brTable(index, defaultDepth, depths, branchValues);
6303 }
6304
6305 bool FunctionCompiler::emitReturn() {
6306 DefVector values;
6307 if (!iter().readReturn(&values)) {
6308 return false;
6309 }
6310
6311 return returnValues(std::move(values));
6312 }
6313
6314 bool FunctionCompiler::emitUnreachable() {
6315 if (!iter().readUnreachable()) {
6316 return false;
6317 }
6318
6319 unreachableTrap();
6320 return true;
6321 }
6322
6323 bool FunctionCompiler::emitTry() {
6324 BlockType type;
6325 if (!iter().readTry(&type)) {
6326 return false;
6327 }
6328
6329 return startTry();
6330 }
6331
6332 bool FunctionCompiler::emitCatch() {
6333 LabelKind kind;
6334 uint32_t tagIndex;
6335 ResultType paramType, resultType;
6336 DefVector tryValues;
6337 if (!iter().readCatch(&kind, &tagIndex, &paramType, &resultType,
6338 &tryValues)) {
6339 return false;
6340 }
6341
6342 // Pushing the results of the previous block, to properly join control flow
6343 // after the try and after each handler, as well as potential control flow
6344 // patches from other instrunctions. This is similar to what is done for
6345 // if-then-else control flow and for most other control control flow joins.
6346 if (!pushDefs(tryValues)) {
6347 return false;
6348 }
6349
6350 return switchToCatch(iter().controlItem(), kind, tagIndex);
6351 }
6352
6353 bool FunctionCompiler::emitCatchAll() {
6354 LabelKind kind;
6355 ResultType paramType, resultType;
6356 DefVector tryValues;
6357 if (!iter().readCatchAll(&kind, &paramType, &resultType, &tryValues)) {
6358 return false;
6359 }
6360
6361 // Pushing the results of the previous block, to properly join control flow
6362 // after the try and after each handler, as well as potential control flow
6363 // patches from other instrunctions.
6364 if (!pushDefs(tryValues)) {
6365 return false;
6366 }
6367
6368 return switchToCatch(iter().controlItem(), kind, CatchAllIndex);
6369 }
6370
6371 bool FunctionCompiler::emitTryTable() {
6372 BlockType type;
6373 TryTableCatchVector catches;
6374 if (!iter().readTryTable(&type, &catches)) {
6375 return false;
6376 }
6377
6378 return startTryTable(std::move(catches));
6379 }
6380
6381 bool FunctionCompiler::emitDelegate() {
6382 uint32_t relativeDepth;
6383 ResultType resultType;
6384 DefVector tryValues;
6385 if (!iter().readDelegate(&relativeDepth, &resultType, &tryValues)) {
6386 return false;
6387 }
6388
6389 Control& control = iter().controlItem();
6390 MBasicBlock* block = control.block;
6391 MOZ_ASSERT(control.tryControl);
6392
6393 // Unless the entire try-delegate is dead code, delegate any pad-patches from
6394 // this try to the next try-block above relativeDepth.
6395 if (block) {
6396 ControlInstructionVector& padPatches =
6397 control.tryControl->landingPadPatches;
6398 if (!delegatePadPatches(padPatches, relativeDepth)) {
6399 return false;
6400 }
6401 }
6402 rootCompiler().freeTryControl(std::move(control.tryControl));
6403 iter().popDelegate();
6404
6405 // Push the results of the previous block, and join control flow with
6406 // potential control flow patches from other instrunctions in the try code.
6407 // This is similar to what is done for EmitEnd.
6408 if (!pushDefs(tryValues)) {
6409 return false;
6410 }
6411 DefVector postJoinDefs;
6412 if (!finishBlock(&postJoinDefs)) {
6413 return false;
6414 }
6415 MOZ_ASSERT_IF(!inDeadCode(), postJoinDefs.length() == resultType.length());
6416 iter().setResults(postJoinDefs.length(), postJoinDefs);
6417
6418 return true;
6419 }
6420
6421 bool FunctionCompiler::emitThrow() {
6422 uint32_t tagIndex;
6423 DefVector argValues;
6424 if (!iter().readThrow(&tagIndex, &argValues)) {
6425 return false;
6426 }
6427
6428 return emitThrow(tagIndex, argValues);
6429 }
6430
6431 bool FunctionCompiler::emitThrowRef() {
6432 MDefinition* exnRef;
6433 if (!iter().readThrowRef(&exnRef)) {
6434 return false;
6435 }
6436
6437 return emitThrowRef(exnRef);
6438 }
6439
6440 bool FunctionCompiler::emitRethrow() {
6441 uint32_t relativeDepth;
6442 if (!iter().readRethrow(&relativeDepth)) {
6443 return false;
6444 }
6445
6446 return emitRethrow(relativeDepth);
6447 }
6448
6449 bool FunctionCompiler::emitInlineCall(const FuncType& funcType,
6450 uint32_t funcIndex,
6451 InliningHeuristics::CallKind callKind,
6452 const DefVector& args,
6453 DefVector* results) {
6454 UniqueChars error;
6455 const BytecodeRange& funcRange = codeTailMeta()->funcDefRange(funcIndex);
6456 BytecodeSpan funcBytecode = codeTailMeta()->funcDefBody(funcIndex);
6457 FuncCompileInput func(funcIndex, funcRange.start, funcBytecode.data(),
6458 funcBytecode.data() + funcBytecode.size(),
6459 Uint32Vector());
6460 Decoder d(func.begin, func.end, func.lineOrBytecode, &error);
6461
6462 ValTypeVector locals;
6463 if (!DecodeLocalEntriesWithParams(d, codeMeta(), funcIndex, &locals)) {
6464 return false;
6465 }
6466
6467 CompileInfo* compileInfo = rootCompiler().startInlineCall(
6468 this->funcIndex(), bytecodeOffset(), funcIndex, locals.length(),
6469 funcRange.size(), callKind);
6470 if (!compileInfo) {
6471 return false;
6472 }
6473
6474 FunctionCompiler calleeCompiler(this, d, func, locals, *compileInfo);
6475 if (!calleeCompiler.initInline(args)) {
6476 MOZ_ASSERT(!error);
6477 return false;
6478 }
6479
6480 if (!calleeCompiler.startBlock()) {
6481 MOZ_ASSERT(!error);
6482 return false;
6483 }
6484
6485 if (!calleeCompiler.emitBodyExprs()) {
6486 MOZ_ASSERT(!error);
6487 return false;
6488 }
6489
6490 calleeCompiler.finish();
6491 rootCompiler_.finishInlineCall();
6492
6493 return finishInlinedCallDirect(calleeCompiler, results);
6494 }
6495
6496 bool FunctionCompiler::emitCall(bool asmJSFuncDef) {
6497 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
6498
6499 uint32_t funcIndex;
6500 DefVector args;
6501 if (asmJSFuncDef) {
6502 if (!iter().readOldCallDirect(codeMeta().numFuncImports, &funcIndex,
6503 &args)) {
6504 return false;
6505 }
6506 } else {
6507 if (!iter().readCall(&funcIndex, &args)) {
6508 return false;
6509 }
6510 }
6511
6512 if (inDeadCode()) {
6513 return true;
6514 }
6515
6516 const FuncType& funcType = codeMeta().getFuncType(funcIndex);
6517
6518 DefVector results;
6519 if (codeMeta().funcIsImport(funcIndex)) {
6520 BuiltinModuleFuncId knownFuncImport = codeMeta().knownFuncImport(funcIndex);
6521 if (knownFuncImport != BuiltinModuleFuncId::None) {
6522 const BuiltinModuleFunc& builtinModuleFunc =
6523 BuiltinModuleFuncs::getFromId(knownFuncImport);
6524 return callBuiltinModuleFunc(builtinModuleFunc, args);
6525 }
6526
6527 uint32_t instanceDataOffset =
6528 codeMeta().offsetOfFuncImportInstanceData(funcIndex);
6529 if (!callImport(instanceDataOffset, lineOrBytecode, funcType, args,
6530 &results)) {
6531 return false;
6532 }
6533 } else {
6534 const auto callKind = InliningHeuristics::CallKind::Direct;
6535 // Make up a single-entry CallRefHint and enquire about its inlineability.
6536 CallRefHint hints;
6537 hints.append(funcIndex);
6538 hints = auditInlineableCallees(callKind, hints);
6539 if (!hints.empty()) {
6540 // Inlining of `funcIndex` was approved.
6541 if (!emitInlineCall(funcType, funcIndex, callKind, args, &results)) {
6542 return false;
6543 }
6544 } else {
6545 if (!callDirect(funcType, funcIndex, lineOrBytecode, args, &results)) {
6546 return false;
6547 }
6548 }
6549 }
6550
6551 iter().setResults(results.length(), results);
6552 return true;
6553 }
6554
6555 bool FunctionCompiler::emitCallIndirect(bool oldStyle) {
6556 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
6557
6558 uint32_t funcTypeIndex;
6559 uint32_t tableIndex;
6560 MDefinition* callee;
6561 DefVector args;
6562 if (oldStyle) {
6563 tableIndex = 0;
6564 if (!iter().readOldCallIndirect(&funcTypeIndex, &callee, &args)) {
6565 return false;
6566 }
6567 } else {
6568 if (!iter().readCallIndirect(&funcTypeIndex, &tableIndex, &callee, &args)) {
6569 return false;
6570 }
6571 }
6572
6573 if (inDeadCode()) {
6574 return true;
6575 }
6576
6577 DefVector results;
6578 if (!callIndirect(funcTypeIndex, tableIndex, callee, lineOrBytecode, args,
6579 &results)) {
6580 return false;
6581 }
6582
6583 iter().setResults(results.length(), results);
6584 return true;
6585 }
6586
6587 #ifdef ENABLE_WASM_JSPI
6588 bool FunctionCompiler::emitStackSwitch() {
6589 StackSwitchKind kind;
6590 MDefinition* suspender;
6591 MDefinition* fn;
6592 MDefinition* data;
6593 if (!iter().readStackSwitch(&kind, &suspender, &fn, &data)) {
6594 return false;
6595 }
6596 MDefinition* result = stackSwitch(suspender, fn, data, kind);
6597 if (!result) {
6598 return false;
6599 }
6600
6601 if (kind == StackSwitchKind::SwitchToMain) {
6602 iter().setResult(result);
6603 }
6604 return true;
6605 }
6606 #endif
6607
6608 bool FunctionCompiler::emitReturnCall() {
6609 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
6610
6611 uint32_t funcIndex;
6612 DefVector args;
6613 if (!iter().readReturnCall(&funcIndex, &args)) {
6614 return false;
6615 }
6616
6617 if (inDeadCode()) {
6618 return true;
6619 }
6620
6621 const FuncType& funcType = codeMeta().getFuncType(funcIndex);
6622
6623 DefVector results;
6624 if (codeMeta().funcIsImport(funcIndex)) {
6625 uint32_t globalDataOffset =
6626 codeMeta().offsetOfFuncImportInstanceData(funcIndex);
6627 if (!returnCallImport(globalDataOffset, lineOrBytecode, funcType, args,
6628 &results)) {
6629 return false;
6630 }
6631 } else {
6632 if (!returnCallDirect(funcType, funcIndex, lineOrBytecode, args,
6633 &results)) {
6634 return false;
6635 }
6636 }
6637 return true;
6638 }
6639
6640 bool FunctionCompiler::emitReturnCallIndirect() {
6641 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
6642
6643 uint32_t funcTypeIndex;
6644 uint32_t tableIndex;
6645 MDefinition* callee;
6646 DefVector args;
6647 if (!iter().readReturnCallIndirect(&funcTypeIndex, &tableIndex, &callee,
6648 &args)) {
6649 return false;
6650 }
6651
6652 if (inDeadCode()) {
6653 return true;
6654 }
6655
6656 DefVector results;
6657 return returnCallIndirect(funcTypeIndex, tableIndex, callee, lineOrBytecode,
6658 args, &results);
6659 }
6660
6661 bool FunctionCompiler::emitReturnCallRef() {
6662 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
6663
6664 uint32_t funcTypeIndex;
6665 MDefinition* callee;
6666 DefVector args;
6667
6668 if (!iter().readReturnCallRef(&funcTypeIndex, &callee, &args)) {
6669 return false;
6670 }
6671
6672 if (inDeadCode()) {
6673 return true;
6674 }
6675
6676 const FuncType& funcType = codeMeta().types->type(funcTypeIndex).funcType();
6677 DefVector results;
6678 return returnCallRef(funcType, callee, lineOrBytecode, args, &results);
6679 }
6680
6681 bool FunctionCompiler::emitGetLocal() {
6682 uint32_t id;
6683 if (!iter().readGetLocal(&id)) {
6684 return false;
6685 }
6686
6687 iter().setResult(getLocalDef(id));
6688 return true;
6689 }
6690
6691 bool FunctionCompiler::emitSetLocal() {
6692 uint32_t id;
6693 MDefinition* value;
6694 if (!iter().readSetLocal(&id, &value)) {
6695 return false;
6696 }
6697
6698 assign(id, value);
6699 return true;
6700 }
6701
6702 bool FunctionCompiler::emitTeeLocal() {
6703 uint32_t id;
6704 MDefinition* value;
6705 if (!iter().readTeeLocal(&id, &value)) {
6706 return false;
6707 }
6708
6709 assign(id, value);
6710 return true;
6711 }
6712
6713 bool FunctionCompiler::emitGetGlobal() {
6714 uint32_t id;
6715 if (!iter().readGetGlobal(&id)) {
6716 return false;
6717 }
6718
6719 const GlobalDesc& global = codeMeta().globals[id];
6720 if (!global.isConstant()) {
6721 iter().setResult(loadGlobalVar(global));
6722 return true;
6723 }
6724
6725 LitVal value = global.constantValue();
6726
6727 MDefinition* result;
6728 switch (value.type().kind()) {
6729 case ValType::I32:
6730 result = constantI32(int32_t(value.i32()));
6731 break;
6732 case ValType::I64:
6733 result = constantI64(int64_t(value.i64()));
6734 break;
6735 case ValType::F32:
6736 result = constantF32(value.f32());
6737 break;
6738 case ValType::F64:
6739 result = constantF64(value.f64());
6740 break;
6741 case ValType::V128:
6742 #ifdef ENABLE_WASM_SIMD
6743 result = constantV128(value.v128());
6744 break;
6745 #else
6746 return iter().fail("Ion has no SIMD support yet");
6747 #endif
6748 case ValType::Ref:
6749 MOZ_ASSERT(value.ref().isNull());
6750 result = constantNullRef(MaybeRefType(value.type().refType()));
6751 break;
6752 default:
6753 MOZ_CRASH("unexpected type in EmitGetGlobal");
6754 }
6755
6756 iter().setResult(result);
6757 return true;
6758 }
6759
6760 bool FunctionCompiler::emitSetGlobal() {
6761 uint32_t bytecodeOffset = readBytecodeOffset();
6762
6763 uint32_t id;
6764 MDefinition* value;
6765 if (!iter().readSetGlobal(&id, &value)) {
6766 return false;
6767 }
6768
6769 const GlobalDesc& global = codeMeta().globals[id];
6770 MOZ_ASSERT(global.isMutable());
6771 return storeGlobalVar(bytecodeOffset, global, value);
6772 }
6773
6774 bool FunctionCompiler::emitTeeGlobal() {
6775 uint32_t bytecodeOffset = readBytecodeOffset();
6776
6777 uint32_t id;
6778 MDefinition* value;
6779 if (!iter().readTeeGlobal(&id, &value)) {
6780 return false;
6781 }
6782
6783 const GlobalDesc& global = codeMeta().globals[id];
6784 MOZ_ASSERT(global.isMutable());
6785
6786 return storeGlobalVar(bytecodeOffset, global, value);
6787 }
6788
6789 template <typename MIRClass>
6790 bool FunctionCompiler::emitUnary(ValType operandType) {
6791 MDefinition* input;
6792 if (!iter().readUnary(operandType, &input)) {
6793 return false;
6794 }
6795
6796 iter().setResult(unary<MIRClass>(input));
6797 return true;
6798 }
6799
6800 template <typename MIRClass>
6801 bool FunctionCompiler::emitConversion(ValType operandType, ValType resultType) {
6802 MDefinition* input;
6803 if (!iter().readConversion(operandType, resultType, &input)) {
6804 return false;
6805 }
6806
6807 iter().setResult(unary<MIRClass>(input));
6808 return true;
6809 }
6810
6811 template <typename MIRClass>
6812 bool FunctionCompiler::emitUnaryWithType(ValType operandType, MIRType mirType) {
6813 MDefinition* input;
6814 if (!iter().readUnary(operandType, &input)) {
6815 return false;
6816 }
6817
6818 iter().setResult(unary<MIRClass>(input, mirType));
6819 return true;
6820 }
6821
6822 template <typename MIRClass>
6823 bool FunctionCompiler::emitConversionWithType(ValType operandType,
6824 ValType resultType,
6825 MIRType mirType) {
6826 MDefinition* input;
6827 if (!iter().readConversion(operandType, resultType, &input)) {
6828 return false;
6829 }
6830
6831 iter().setResult(unary<MIRClass>(input, mirType));
6832 return true;
6833 }
6834
6835 bool FunctionCompiler::emitTruncate(ValType operandType, ValType resultType,
6836 bool isUnsigned, bool isSaturating) {
6837 MDefinition* input = nullptr;
6838 if (!iter().readConversion(operandType, resultType, &input)) {
6839 return false;
6840 }
6841
6842 TruncFlags flags = 0;
6843 if (isUnsigned) {
6844 flags |= TRUNC_UNSIGNED;
6845 }
6846 if (isSaturating) {
6847 flags |= TRUNC_SATURATING;
6848 }
6849 if (resultType == ValType::I32) {
6850 if (codeMeta().isAsmJS()) {
6851 if (inDeadCode()) {
6852 // The read callsite line, produced by prepareCall, has to be
6853 // consumed -- the MWasmBuiltinTruncateToInt32 and MTruncateToInt32
6854 // will not create MIR node.
6855 (void)readCallSiteLineOrBytecode();
6856 iter().setResult(nullptr);
6857 } else if (input && (input->type() == MIRType::Double ||
6858 input->type() == MIRType::Float32)) {
6859 iter().setResult(unary<MWasmBuiltinTruncateToInt32>(input));
6860 } else {
6861 iter().setResult(unary<MTruncateToInt32>(input));
6862 }
6863 } else {
6864 iter().setResult(truncate<MWasmTruncateToInt32>(input, flags));
6865 }
6866 } else {
6867 MOZ_ASSERT(resultType == ValType::I64);
6868 MOZ_ASSERT(!codeMeta().isAsmJS());
6869 #if defined(JS_CODEGEN_ARM)
6870 iter().setResult(truncateWithInstance(input, flags));
6871 #else
6872 iter().setResult(truncate<MWasmTruncateToInt64>(input, flags));
6873 #endif
6874 }
6875 return true;
6876 }
6877
6878 bool FunctionCompiler::emitSignExtend(uint32_t srcSize, uint32_t targetSize) {
6879 MDefinition* input;
6880 ValType type = targetSize == 4 ? ValType::I32 : ValType::I64;
6881 if (!iter().readConversion(type, type, &input)) {
6882 return false;
6883 }
6884
6885 iter().setResult(signExtend(input, srcSize, targetSize));
6886 return true;
6887 }
6888
6889 bool FunctionCompiler::emitExtendI32(bool isUnsigned) {
6890 MDefinition* input;
6891 if (!iter().readConversion(ValType::I32, ValType::I64, &input)) {
6892 return false;
6893 }
6894
6895 iter().setResult(extendI32(input, isUnsigned));
6896 return true;
6897 }
6898
6899 bool FunctionCompiler::emitConvertI64ToFloatingPoint(ValType resultType,
6900 MIRType mirType,
6901 bool isUnsigned) {
6902 MDefinition* input;
6903 if (!iter().readConversion(ValType::I64, resultType, &input)) {
6904 return false;
6905 }
6906
6907 iter().setResult(convertI64ToFloatingPoint(input, mirType, isUnsigned));
6908 return true;
6909 }
6910
6911 bool FunctionCompiler::emitReinterpret(ValType resultType, ValType operandType,
6912 MIRType mirType) {
6913 MDefinition* input;
6914 if (!iter().readConversion(operandType, resultType, &input)) {
6915 return false;
6916 }
6917
6918 iter().setResult(unary<MReinterpretCast>(input, mirType));
6919 return true;
6920 }
6921
6922 bool FunctionCompiler::emitAdd(ValType type, MIRType mirType) {
6923 MDefinition* lhs;
6924 MDefinition* rhs;
6925 if (!iter().readBinary(type, &lhs, &rhs)) {
6926 return false;
6927 }
6928
6929 iter().setResult(add(lhs, rhs, mirType));
6930 return true;
6931 }
6932
6933 bool FunctionCompiler::emitSub(ValType type, MIRType mirType) {
6934 MDefinition* lhs;
6935 MDefinition* rhs;
6936 if (!iter().readBinary(type, &lhs, &rhs)) {
6937 return false;
6938 }
6939
6940 iter().setResult(sub(lhs, rhs, mirType));
6941 return true;
6942 }
6943
6944 bool FunctionCompiler::emitRotate(ValType type, bool isLeftRotation) {
6945 MDefinition* lhs;
6946 MDefinition* rhs;
6947 if (!iter().readBinary(type, &lhs, &rhs)) {
6948 return false;
6949 }
6950
6951 MDefinition* result = rotate(lhs, rhs, type.toMIRType(), isLeftRotation);
6952 iter().setResult(result);
6953 return true;
6954 }
6955
6956 bool FunctionCompiler::emitBitNot(ValType operandType, MIRType mirType) {
6957 MDefinition* input;
6958 if (!iter().readUnary(operandType, &input)) {
6959 return false;
6960 }
6961
6962 iter().setResult(bitnot(input, mirType));
6963 return true;
6964 }
6965
6966 bool FunctionCompiler::emitBitwiseAndOrXor(
6967 ValType operandType, MIRType mirType,
6968 MWasmBinaryBitwise::SubOpcode subOpc) {
6969 MDefinition* lhs;
6970 MDefinition* rhs;
6971 if (!iter().readBinary(operandType, &lhs, &rhs)) {
6972 return false;
6973 }
6974
6975 iter().setResult(binary<MWasmBinaryBitwise>(lhs, rhs, mirType, subOpc));
6976 return true;
6977 }
6978
6979 template <typename MIRClass>
6980 bool FunctionCompiler::emitShift(ValType operandType, MIRType mirType) {
6981 MDefinition* lhs;
6982 MDefinition* rhs;
6983 if (!iter().readBinary(operandType, &lhs, &rhs)) {
6984 return false;
6985 }
6986
6987 iter().setResult(binary<MIRClass>(lhs, rhs, mirType));
6988 return true;
6989 }
6990
6991 bool FunctionCompiler::emitUrsh(ValType operandType, MIRType mirType) {
6992 MDefinition* lhs;
6993 MDefinition* rhs;
6994 if (!iter().readBinary(operandType, &lhs, &rhs)) {
6995 return false;
6996 }
6997
6998 iter().setResult(ursh(lhs, rhs, mirType));
6999 return true;
7000 }
7001
7002 bool FunctionCompiler::emitMul(ValType operandType, MIRType mirType) {
7003 MDefinition* lhs;
7004 MDefinition* rhs;
7005 if (!iter().readBinary(operandType, &lhs, &rhs)) {
7006 return false;
7007 }
7008
7009 iter().setResult(
7010 mul(lhs, rhs, mirType,
7011 mirType == MIRType::Int32 ? MMul::Integer : MMul::Normal));
7012 return true;
7013 }
7014
7015 bool FunctionCompiler::emitDiv(ValType operandType, MIRType mirType,
7016 bool isUnsigned) {
7017 MDefinition* lhs;
7018 MDefinition* rhs;
7019 if (!iter().readBinary(operandType, &lhs, &rhs)) {
7020 return false;
7021 }
7022
7023 iter().setResult(div(lhs, rhs, mirType, isUnsigned));
7024 return true;
7025 }
7026
7027 bool FunctionCompiler::emitRem(ValType operandType, MIRType mirType,
7028 bool isUnsigned) {
7029 MDefinition* lhs;
7030 MDefinition* rhs;
7031 if (!iter().readBinary(operandType, &lhs, &rhs)) {
7032 return false;
7033 }
7034
7035 iter().setResult(mod(lhs, rhs, mirType, isUnsigned));
7036 return true;
7037 }
7038
7039 bool FunctionCompiler::emitMinMax(ValType operandType, MIRType mirType,
7040 bool isMax) {
7041 MDefinition* lhs;
7042 MDefinition* rhs;
7043 if (!iter().readBinary(operandType, &lhs, &rhs)) {
7044 return false;
7045 }
7046
7047 iter().setResult(minMax(lhs, rhs, mirType, isMax));
7048 return true;
7049 }
7050
7051 bool FunctionCompiler::emitCopySign(ValType operandType) {
7052 MDefinition* lhs;
7053 MDefinition* rhs;
7054 if (!iter().readBinary(operandType, &lhs, &rhs)) {
7055 return false;
7056 }
7057
7058 iter().setResult(binary<MCopySign>(lhs, rhs, operandType.toMIRType()));
7059 return true;
7060 }
7061
7062 bool FunctionCompiler::emitComparison(ValType operandType, JSOp compareOp,
7063 MCompare::CompareType compareType) {
7064 MDefinition* lhs;
7065 MDefinition* rhs;
7066 if (!iter().readComparison(operandType, &lhs, &rhs)) {
7067 return false;
7068 }
7069
7070 iter().setResult(compare(lhs, rhs, compareOp, compareType));
7071 return true;
7072 }
7073
7074 bool FunctionCompiler::emitSelect(bool typed) {
7075 StackType type;
7076 MDefinition* trueValue;
7077 MDefinition* falseValue;
7078 MDefinition* condition;
7079 if (!iter().readSelect(typed, &type, &trueValue, &falseValue, &condition)) {
7080 return false;
7081 }
7082
7083 iter().setResult(select(trueValue, falseValue, condition));
7084 return true;
7085 }
7086
7087 bool FunctionCompiler::emitLoad(ValType type, Scalar::Type viewType) {
7088 LinearMemoryAddress<MDefinition*> addr;
7089 if (!iter().readLoad(type, Scalar::byteSize(viewType), &addr)) {
7090 return false;
7091 }
7092
7093 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7094 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
7095 auto* ins = load(addr.base, &access, type);
7096 if (!inDeadCode() && !ins) {
7097 return false;
7098 }
7099
7100 iter().setResult(ins);
7101 return true;
7102 }
7103
7104 bool FunctionCompiler::emitStore(ValType resultType, Scalar::Type viewType) {
7105 LinearMemoryAddress<MDefinition*> addr;
7106 MDefinition* value;
7107 if (!iter().readStore(resultType, Scalar::byteSize(viewType), &addr,
7108 &value)) {
7109 return false;
7110 }
7111
7112 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7113 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
7114
7115 store(addr.base, &access, value);
7116 return true;
7117 }
7118
7119 bool FunctionCompiler::emitTeeStore(ValType resultType, Scalar::Type viewType) {
7120 LinearMemoryAddress<MDefinition*> addr;
7121 MDefinition* value;
7122 if (!iter().readTeeStore(resultType, Scalar::byteSize(viewType), &addr,
7123 &value)) {
7124 return false;
7125 }
7126
7127 MOZ_ASSERT(isMem32(addr.memoryIndex)); // asm.js opcode
7128 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7129 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
7130
7131 store(addr.base, &access, value);
7132 return true;
7133 }
7134
7135 bool FunctionCompiler::emitTeeStoreWithCoercion(ValType resultType,
7136 Scalar::Type viewType) {
7137 LinearMemoryAddress<MDefinition*> addr;
7138 MDefinition* value;
7139 if (!iter().readTeeStore(resultType, Scalar::byteSize(viewType), &addr,
7140 &value)) {
7141 return false;
7142 }
7143
7144 if (resultType == ValType::F32 && viewType == Scalar::Float64) {
7145 value = unary<MToDouble>(value);
7146 } else if (resultType == ValType::F64 && viewType == Scalar::Float32) {
7147 value = unary<MToFloat32>(value);
7148 } else {
7149 MOZ_CRASH("unexpected coerced store");
7150 }
7151
7152 MOZ_ASSERT(isMem32(addr.memoryIndex)); // asm.js opcode
7153 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7154 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
7155
7156 store(addr.base, &access, value);
7157 return true;
7158 }
7159
7160 bool FunctionCompiler::tryInlineUnaryBuiltin(SymbolicAddress callee,
7161 MDefinition* input) {
7162 if (!input) {
7163 return false;
7164 }
7165
7166 MOZ_ASSERT(IsFloatingPointType(input->type()));
7167
7168 RoundingMode mode;
7169 if (!IsRoundingFunction(callee, &mode)) {
7170 return false;
7171 }
7172
7173 if (!MNearbyInt::HasAssemblerSupport(mode)) {
7174 return false;
7175 }
7176
7177 iter().setResult(nearbyInt(input, mode));
7178 return true;
7179 }
7180
7181 bool FunctionCompiler::emitUnaryMathBuiltinCall(
7182 const SymbolicAddressSignature& callee) {
7183 MOZ_ASSERT(callee.numArgs == 1);
7184
7185 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
7186
7187 MDefinition* input;
7188 if (!iter().readUnary(ValType::fromMIRType(callee.argTypes[0]), &input)) {
7189 return false;
7190 }
7191
7192 if (tryInlineUnaryBuiltin(callee.identity, input)) {
7193 return true;
7194 }
7195
7196 MDefinition* def;
7197 if (!builtinCall1(callee, lineOrBytecode, input, &def)) {
7198 return false;
7199 }
7200
7201 iter().setResult(def);
7202 return true;
7203 }
7204
7205 bool FunctionCompiler::emitBinaryMathBuiltinCall(
7206 const SymbolicAddressSignature& callee) {
7207 MOZ_ASSERT(callee.numArgs == 2);
7208 MOZ_ASSERT(callee.argTypes[0] == callee.argTypes[1]);
7209
7210 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
7211
7212 MDefinition* lhs;
7213 MDefinition* rhs;
7214 // This call to readBinary assumes both operands have the same type.
7215 if (!iter().readBinary(ValType::fromMIRType(callee.argTypes[0]), &lhs,
7216 &rhs)) {
7217 return false;
7218 }
7219
7220 MDefinition* def;
7221 if (!builtinCall2(callee, lineOrBytecode, lhs, rhs, &def)) {
7222 return false;
7223 }
7224
7225 iter().setResult(def);
7226 return true;
7227 }
7228
7229 bool FunctionCompiler::emitMemoryGrow() {
7230 uint32_t bytecodeOffset = readBytecodeOffset();
7231
7232 MDefinition* delta;
7233 uint32_t memoryIndex;
7234 if (!iter().readMemoryGrow(&memoryIndex, &delta)) {
7235 return false;
7236 }
7237
7238 if (inDeadCode()) {
7239 return true;
7240 }
7241
7242 MDefinition* memoryIndexValue = constantI32(int32_t(memoryIndex));
7243 if (!memoryIndexValue) {
7244 return false;
7245 }
7246
7247 const SymbolicAddressSignature& callee =
7248 isMem32(memoryIndex) ? SASigMemoryGrowM32 : SASigMemoryGrowM64;
7249
7250 MDefinition* ret;
7251 if (!emitInstanceCall2(bytecodeOffset, callee, delta, memoryIndexValue,
7252 &ret)) {
7253 return false;
7254 }
7255
7256 iter().setResult(ret);
7257 return true;
7258 }
7259
7260 bool FunctionCompiler::emitMemorySize() {
7261 uint32_t bytecodeOffset = readBytecodeOffset();
7262
7263 uint32_t memoryIndex;
7264 if (!iter().readMemorySize(&memoryIndex)) {
7265 return false;
7266 }
7267
7268 if (inDeadCode()) {
7269 return true;
7270 }
7271
7272 MDefinition* memoryIndexValue = constantI32(int32_t(memoryIndex));
7273 if (!memoryIndexValue) {
7274 return false;
7275 }
7276
7277 const SymbolicAddressSignature& callee =
7278 isMem32(memoryIndex) ? SASigMemorySizeM32 : SASigMemorySizeM64;
7279
7280 MDefinition* ret;
7281 if (!emitInstanceCall1(bytecodeOffset, callee, memoryIndexValue, &ret)) {
7282 return false;
7283 }
7284
7285 iter().setResult(ret);
7286 return true;
7287 }
7288
7289 bool FunctionCompiler::emitAtomicCmpXchg(ValType type, Scalar::Type viewType) {
7290 LinearMemoryAddress<MDefinition*> addr;
7291 MDefinition* oldValue;
7292 MDefinition* newValue;
7293 if (!iter().readAtomicCmpXchg(&addr, type, byteSize(viewType), &oldValue,
7294 &newValue)) {
7295 return false;
7296 }
7297
7298 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7299 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
7300 Synchronization::Full());
7301 auto* ins =
7302 atomicCompareExchangeHeap(addr.base, &access, type, oldValue, newValue);
7303 if (!inDeadCode() && !ins) {
7304 return false;
7305 }
7306
7307 iter().setResult(ins);
7308 return true;
7309 }
7310
7311 bool FunctionCompiler::emitAtomicLoad(ValType type, Scalar::Type viewType) {
7312 LinearMemoryAddress<MDefinition*> addr;
7313 if (!iter().readAtomicLoad(&addr, type, byteSize(viewType))) {
7314 return false;
7315 }
7316
7317 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7318 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
7319 Synchronization::Load());
7320 auto* ins = load(addr.base, &access, type);
7321 if (!inDeadCode() && !ins) {
7322 return false;
7323 }
7324
7325 iter().setResult(ins);
7326 return true;
7327 }
7328
7329 bool FunctionCompiler::emitAtomicRMW(ValType type, Scalar::Type viewType,
7330 jit::AtomicOp op) {
7331 LinearMemoryAddress<MDefinition*> addr;
7332 MDefinition* value;
7333 if (!iter().readAtomicRMW(&addr, type, byteSize(viewType), &value)) {
7334 return false;
7335 }
7336
7337 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7338 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
7339 Synchronization::Full());
7340 auto* ins = atomicBinopHeap(op, addr.base, &access, type, value);
7341 if (!inDeadCode() && !ins) {
7342 return false;
7343 }
7344
7345 iter().setResult(ins);
7346 return true;
7347 }
7348
7349 bool FunctionCompiler::emitAtomicStore(ValType type, Scalar::Type viewType) {
7350 LinearMemoryAddress<MDefinition*> addr;
7351 MDefinition* value;
7352 if (!iter().readAtomicStore(&addr, type, byteSize(viewType), &value)) {
7353 return false;
7354 }
7355
7356 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7357 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
7358 Synchronization::Store());
7359 store(addr.base, &access, value);
7360 return true;
7361 }
7362
7363 bool FunctionCompiler::emitWait(ValType type, uint32_t byteSize) {
7364 MOZ_ASSERT(type == ValType::I32 || type == ValType::I64);
7365 MOZ_ASSERT(type.size() == byteSize);
7366
7367 uint32_t bytecodeOffset = readBytecodeOffset();
7368
7369 LinearMemoryAddress<MDefinition*> addr;
7370 MDefinition* expected;
7371 MDefinition* timeout;
7372 if (!iter().readWait(&addr, type, byteSize, &expected, &timeout)) {
7373 return false;
7374 }
7375
7376 if (inDeadCode()) {
7377 return true;
7378 }
7379
7380 MemoryAccessDesc access(addr.memoryIndex,
7381 type == ValType::I32 ? Scalar::Int32 : Scalar::Int64,
7382 addr.align, addr.offset, trapSiteDesc(),
7383 hugeMemoryEnabled(addr.memoryIndex));
7384 MDefinition* ptr = computeEffectiveAddress(addr.base, &access);
7385 if (!ptr) {
7386 return false;
7387 }
7388
7389 MDefinition* memoryIndex = constantI32(int32_t(addr.memoryIndex));
7390 if (!memoryIndex) {
7391 return false;
7392 }
7393
7394 const SymbolicAddressSignature& callee =
7395 isMem32(addr.memoryIndex)
7396 ? (type == ValType::I32 ? SASigWaitI32M32 : SASigWaitI64M32)
7397 : (type == ValType::I32 ? SASigWaitI32M64 : SASigWaitI64M64);
7398
7399 MDefinition* ret;
7400 if (!emitInstanceCall4(bytecodeOffset, callee, ptr, expected, timeout,
7401 memoryIndex, &ret)) {
7402 return false;
7403 }
7404
7405 iter().setResult(ret);
7406 return true;
7407 }
7408
7409 bool FunctionCompiler::emitFence() {
7410 if (!iter().readFence()) {
7411 return false;
7412 }
7413
7414 fence();
7415 return true;
7416 }
7417
7418 bool FunctionCompiler::emitNotify() {
7419 uint32_t bytecodeOffset = readBytecodeOffset();
7420
7421 LinearMemoryAddress<MDefinition*> addr;
7422 MDefinition* count;
7423 if (!iter().readNotify(&addr, &count)) {
7424 return false;
7425 }
7426
7427 if (inDeadCode()) {
7428 return true;
7429 }
7430
7431 MemoryAccessDesc access(addr.memoryIndex, Scalar::Int32, addr.align,
7432 addr.offset, trapSiteDesc(),
7433 hugeMemoryEnabled(addr.memoryIndex));
7434 MDefinition* ptr = computeEffectiveAddress(addr.base, &access);
7435 if (!ptr) {
7436 return false;
7437 }
7438
7439 MDefinition* memoryIndex = constantI32(int32_t(addr.memoryIndex));
7440 if (!memoryIndex) {
7441 return false;
7442 }
7443
7444 const SymbolicAddressSignature& callee =
7445 isMem32(addr.memoryIndex) ? SASigWakeM32 : SASigWakeM64;
7446
7447 MDefinition* ret;
7448 if (!emitInstanceCall3(bytecodeOffset, callee, ptr, count, memoryIndex,
7449 &ret)) {
7450 return false;
7451 }
7452
7453 iter().setResult(ret);
7454 return true;
7455 }
7456
7457 bool FunctionCompiler::emitAtomicXchg(ValType type, Scalar::Type viewType) {
7458 LinearMemoryAddress<MDefinition*> addr;
7459 MDefinition* value;
7460 if (!iter().readAtomicRMW(&addr, type, byteSize(viewType), &value)) {
7461 return false;
7462 }
7463
7464 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
7465 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
7466 Synchronization::Full());
7467 MDefinition* ins = atomicExchangeHeap(addr.base, &access, type, value);
7468 if (!inDeadCode() && !ins) {
7469 return false;
7470 }
7471
7472 iter().setResult(ins);
7473 return true;
7474 }
7475
7476 bool FunctionCompiler::emitMemCopyCall(uint32_t dstMemIndex,
7477 uint32_t srcMemIndex, MDefinition* dst,
7478 MDefinition* src, MDefinition* len) {
7479 uint32_t bytecodeOffset = readBytecodeOffset();
7480
7481 if (dstMemIndex == srcMemIndex) {
7482 const SymbolicAddressSignature& callee =
7483 (codeMeta().usesSharedMemory(dstMemIndex)
7484 ? (isMem32(dstMemIndex) ? SASigMemCopySharedM32
7485 : SASigMemCopySharedM64)
7486 : (isMem32(dstMemIndex) ? SASigMemCopyM32 : SASigMemCopyM64));
7487 MDefinition* base = memoryBase(dstMemIndex);
7488 if (!base) {
7489 return false;
7490 }
7491 return emitInstanceCall4(bytecodeOffset, callee, dst, src, len, base);
7492 }
7493
7494 AddressType dstIndexType = codeMeta().memories[dstMemIndex].addressType();
7495 AddressType srcIndexType = codeMeta().memories[srcMemIndex].addressType();
7496
7497 if (dstIndexType == AddressType::I32) {
7498 dst = extendI32(dst, /*isUnsigned=*/true);
7499 if (!dst) {
7500 return false;
7501 }
7502 }
7503 if (srcIndexType == AddressType::I32) {
7504 src = extendI32(src, /*isUnsigned=*/true);
7505 if (!src) {
7506 return false;
7507 }
7508 }
7509 if (dstIndexType == AddressType::I32 || srcIndexType == AddressType::I32) {
7510 len = extendI32(len, /*isUnsigned=*/true);
7511 if (!len) {
7512 return false;
7513 }
7514 }
7515
7516 MDefinition* dstMemIndexValue = constantI32(int32_t(dstMemIndex));
7517 if (!dstMemIndexValue) {
7518 return false;
7519 }
7520
7521 MDefinition* srcMemIndexValue = constantI32(int32_t(srcMemIndex));
7522 if (!srcMemIndexValue) {
7523 return false;
7524 }
7525
7526 return emitInstanceCall5(bytecodeOffset, SASigMemCopyAny, dst, src, len,
7527 dstMemIndexValue, srcMemIndexValue);
7528 }
7529
7530 bool FunctionCompiler::emitMemCopyInline(uint32_t memoryIndex, MDefinition* dst,
7531 MDefinition* src, uint32_t length) {
7532 MOZ_ASSERT(length != 0 && length <= MaxInlineMemoryCopyLength);
7533
7534 // Compute the number of copies of each width we will need to do
7535 size_t remainder = length;
7536 #ifdef ENABLE_WASM_SIMD
7537 size_t numCopies16 = 0;
7538 if (MacroAssembler::SupportsFastUnalignedFPAccesses()) {
7539 numCopies16 = remainder / sizeof(V128);
7540 remainder %= sizeof(V128);
7541 }
7542 #endif
7543 #ifdef JS_64BIT
7544 size_t numCopies8 = remainder / sizeof(uint64_t);
7545 remainder %= sizeof(uint64_t);
7546 #endif
7547 size_t numCopies4 = remainder / sizeof(uint32_t);
7548 remainder %= sizeof(uint32_t);
7549 size_t numCopies2 = remainder / sizeof(uint16_t);
7550 remainder %= sizeof(uint16_t);
7551 size_t numCopies1 = remainder;
7552
7553 // Load all source bytes from low to high using the widest transfer width we
7554 // can for the system. We will trap without writing anything if any source
7555 // byte is out-of-bounds.
7556 size_t offset = 0;
7557 DefVector loadedValues;
7558
7559 #ifdef ENABLE_WASM_SIMD
7560 for (uint32_t i = 0; i < numCopies16; i++) {
7561 MemoryAccessDesc access(memoryIndex, Scalar::Simd128, 1, offset,
7562 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7563 auto* loadValue = load(src, &access, ValType::V128);
7564 if (!loadValue || !loadedValues.append(loadValue)) {
7565 return false;
7566 }
7567
7568 offset += sizeof(V128);
7569 }
7570 #endif
7571
7572 #ifdef JS_64BIT
7573 for (uint32_t i = 0; i < numCopies8; i++) {
7574 MemoryAccessDesc access(memoryIndex, Scalar::Int64, 1, offset,
7575 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7576 auto* loadValue = load(src, &access, ValType::I64);
7577 if (!loadValue || !loadedValues.append(loadValue)) {
7578 return false;
7579 }
7580
7581 offset += sizeof(uint64_t);
7582 }
7583 #endif
7584
7585 for (uint32_t i = 0; i < numCopies4; i++) {
7586 MemoryAccessDesc access(memoryIndex, Scalar::Uint32, 1, offset,
7587 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7588 auto* loadValue = load(src, &access, ValType::I32);
7589 if (!loadValue || !loadedValues.append(loadValue)) {
7590 return false;
7591 }
7592
7593 offset += sizeof(uint32_t);
7594 }
7595
7596 if (numCopies2) {
7597 MemoryAccessDesc access(memoryIndex, Scalar::Uint16, 1, offset,
7598 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7599 auto* loadValue = load(src, &access, ValType::I32);
7600 if (!loadValue || !loadedValues.append(loadValue)) {
7601 return false;
7602 }
7603
7604 offset += sizeof(uint16_t);
7605 }
7606
7607 if (numCopies1) {
7608 MemoryAccessDesc access(memoryIndex, Scalar::Uint8, 1, offset,
7609 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7610 auto* loadValue = load(src, &access, ValType::I32);
7611 if (!loadValue || !loadedValues.append(loadValue)) {
7612 return false;
7613 }
7614 }
7615
7616 // Store all source bytes to the destination from high to low. We will trap
7617 // without writing anything on the first store if any dest byte is
7618 // out-of-bounds.
7619 offset = length;
7620
7621 if (numCopies1) {
7622 offset -= sizeof(uint8_t);
7623
7624 MemoryAccessDesc access(memoryIndex, Scalar::Uint8, 1, offset,
7625 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7626 auto* value = loadedValues.popCopy();
7627 store(dst, &access, value);
7628 }
7629
7630 if (numCopies2) {
7631 offset -= sizeof(uint16_t);
7632
7633 MemoryAccessDesc access(memoryIndex, Scalar::Uint16, 1, offset,
7634 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7635 auto* value = loadedValues.popCopy();
7636 store(dst, &access, value);
7637 }
7638
7639 for (uint32_t i = 0; i < numCopies4; i++) {
7640 offset -= sizeof(uint32_t);
7641
7642 MemoryAccessDesc access(memoryIndex, Scalar::Uint32, 1, offset,
7643 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7644 auto* value = loadedValues.popCopy();
7645 store(dst, &access, value);
7646 }
7647
7648 #ifdef JS_64BIT
7649 for (uint32_t i = 0; i < numCopies8; i++) {
7650 offset -= sizeof(uint64_t);
7651
7652 MemoryAccessDesc access(memoryIndex, Scalar::Int64, 1, offset,
7653 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7654 auto* value = loadedValues.popCopy();
7655 store(dst, &access, value);
7656 }
7657 #endif
7658
7659 #ifdef ENABLE_WASM_SIMD
7660 for (uint32_t i = 0; i < numCopies16; i++) {
7661 offset -= sizeof(V128);
7662
7663 MemoryAccessDesc access(memoryIndex, Scalar::Simd128, 1, offset,
7664 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7665 auto* value = loadedValues.popCopy();
7666 store(dst, &access, value);
7667 }
7668 #endif
7669
7670 return true;
7671 }
7672
7673 bool FunctionCompiler::emitMemCopy() {
7674 MDefinition *dst, *src, *len;
7675 uint32_t dstMemIndex;
7676 uint32_t srcMemIndex;
7677 if (!iter().readMemOrTableCopy(true, &dstMemIndex, &dst, &srcMemIndex, &src,
7678 &len)) {
7679 return false;
7680 }
7681
7682 if (inDeadCode()) {
7683 return true;
7684 }
7685
7686 if (dstMemIndex == srcMemIndex && len->isConstant()) {
7687 uint64_t length = isMem32(dstMemIndex) ? len->toConstant()->toInt32()
7688 : len->toConstant()->toInt64();
7689 static_assert(MaxInlineMemoryCopyLength <= UINT32_MAX);
7690 if (length != 0 && length <= MaxInlineMemoryCopyLength) {
7691 return emitMemCopyInline(dstMemIndex, dst, src, uint32_t(length));
7692 }
7693 }
7694
7695 return emitMemCopyCall(dstMemIndex, srcMemIndex, dst, src, len);
7696 }
7697
7698 bool FunctionCompiler::emitTableCopy() {
7699 MDefinition *dst, *src, *len;
7700 uint32_t dstTableIndex;
7701 uint32_t srcTableIndex;
7702 if (!iter().readMemOrTableCopy(false, &dstTableIndex, &dst, &srcTableIndex,
7703 &src, &len)) {
7704 return false;
7705 }
7706
7707 if (inDeadCode()) {
7708 return true;
7709 }
7710
7711 uint32_t bytecodeOffset = readBytecodeOffset();
7712 const TableDesc& dstTable = codeMeta().tables[dstTableIndex];
7713 const TableDesc& srcTable = codeMeta().tables[srcTableIndex];
7714
7715 AddressType dstAddressType = dstTable.addressType();
7716 AddressType srcAddressType = srcTable.addressType();
7717 AddressType lenAddressType =
7718 dstAddressType == AddressType::I64 && srcAddressType == AddressType::I64
7719 ? AddressType::I64
7720 : AddressType::I32;
7721
7722 MDefinition* dst32 = tableAddressToI32(dstAddressType, dst);
7723 if (!dst32) {
7724 return false;
7725 }
7726
7727 MDefinition* src32 = tableAddressToI32(srcAddressType, src);
7728 if (!src32) {
7729 return false;
7730 }
7731
7732 MDefinition* len32 = tableAddressToI32(lenAddressType, len);
7733 if (!len32) {
7734 return false;
7735 }
7736
7737 MDefinition* dti = constantI32(int32_t(dstTableIndex));
7738 MDefinition* sti = constantI32(int32_t(srcTableIndex));
7739
7740 return emitInstanceCall5(bytecodeOffset, SASigTableCopy, dst32, src32, len32,
7741 dti, sti);
7742 }
7743
7744 bool FunctionCompiler::emitDataOrElemDrop(bool isData) {
7745 uint32_t segIndexVal = 0;
7746 if (!iter().readDataOrElemDrop(isData, &segIndexVal)) {
7747 return false;
7748 }
7749
7750 if (inDeadCode()) {
7751 return true;
7752 }
7753
7754 uint32_t bytecodeOffset = readBytecodeOffset();
7755
7756 MDefinition* segIndex = constantI32(int32_t(segIndexVal));
7757
7758 const SymbolicAddressSignature& callee =
7759 isData ? SASigDataDrop : SASigElemDrop;
7760 return emitInstanceCall1(bytecodeOffset, callee, segIndex);
7761 }
7762
7763 bool FunctionCompiler::emitMemFillCall(uint32_t memoryIndex, MDefinition* start,
7764 MDefinition* val, MDefinition* len) {
7765 MDefinition* base = memoryBase(memoryIndex);
7766
7767 uint32_t bytecodeOffset = readBytecodeOffset();
7768 const SymbolicAddressSignature& callee =
7769 (codeMeta().usesSharedMemory(memoryIndex)
7770 ? (isMem32(memoryIndex) ? SASigMemFillSharedM32
7771 : SASigMemFillSharedM64)
7772 : (isMem32(memoryIndex) ? SASigMemFillM32 : SASigMemFillM64));
7773 return emitInstanceCall4(bytecodeOffset, callee, start, val, len, base);
7774 }
7775
7776 bool FunctionCompiler::emitMemFillInline(uint32_t memoryIndex,
7777 MDefinition* start, MDefinition* val,
7778 uint32_t length) {
7779 MOZ_ASSERT(length != 0 && length <= MaxInlineMemoryFillLength);
7780 uint32_t value = val->toConstant()->toInt32();
7781
7782 // Compute the number of copies of each width we will need to do
7783 size_t remainder = length;
7784 #ifdef ENABLE_WASM_SIMD
7785 size_t numCopies16 = 0;
7786 if (MacroAssembler::SupportsFastUnalignedFPAccesses()) {
7787 numCopies16 = remainder / sizeof(V128);
7788 remainder %= sizeof(V128);
7789 }
7790 #endif
7791 #ifdef JS_64BIT
7792 size_t numCopies8 = remainder / sizeof(uint64_t);
7793 remainder %= sizeof(uint64_t);
7794 #endif
7795 size_t numCopies4 = remainder / sizeof(uint32_t);
7796 remainder %= sizeof(uint32_t);
7797 size_t numCopies2 = remainder / sizeof(uint16_t);
7798 remainder %= sizeof(uint16_t);
7799 size_t numCopies1 = remainder;
7800
7801 // Generate splatted definitions for wider fills as needed
7802 #ifdef ENABLE_WASM_SIMD
7803 MDefinition* val16 = numCopies16 ? constantV128(V128(value)) : nullptr;
7804 #endif
7805 #ifdef JS_64BIT
7806 MDefinition* val8 =
7807 numCopies8 ? constantI64(int64_t(SplatByteToUInt<uint64_t>(value, 8)))
7808 : nullptr;
7809 #endif
7810 MDefinition* val4 =
7811 numCopies4 ? constantI32(int32_t(SplatByteToUInt<uint32_t>(value, 4)))
7812 : nullptr;
7813 MDefinition* val2 =
7814 numCopies2 ? constantI32(int32_t(SplatByteToUInt<uint32_t>(value, 2)))
7815 : nullptr;
7816
7817 // Store the fill value to the destination from high to low. We will trap
7818 // without writing anything on the first store if any dest byte is
7819 // out-of-bounds.
7820 size_t offset = length;
7821
7822 if (numCopies1) {
7823 offset -= sizeof(uint8_t);
7824
7825 MemoryAccessDesc access(memoryIndex, Scalar::Uint8, 1, offset,
7826 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7827 store(start, &access, val);
7828 }
7829
7830 if (numCopies2) {
7831 offset -= sizeof(uint16_t);
7832
7833 MemoryAccessDesc access(memoryIndex, Scalar::Uint16, 1, offset,
7834 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7835 store(start, &access, val2);
7836 }
7837
7838 for (uint32_t i = 0; i < numCopies4; i++) {
7839 offset -= sizeof(uint32_t);
7840
7841 MemoryAccessDesc access(memoryIndex, Scalar::Uint32, 1, offset,
7842 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7843 store(start, &access, val4);
7844 }
7845
7846 #ifdef JS_64BIT
7847 for (uint32_t i = 0; i < numCopies8; i++) {
7848 offset -= sizeof(uint64_t);
7849
7850 MemoryAccessDesc access(memoryIndex, Scalar::Int64, 1, offset,
7851 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7852 store(start, &access, val8);
7853 }
7854 #endif
7855
7856 #ifdef ENABLE_WASM_SIMD
7857 for (uint32_t i = 0; i < numCopies16; i++) {
7858 offset -= sizeof(V128);
7859
7860 MemoryAccessDesc access(memoryIndex, Scalar::Simd128, 1, offset,
7861 trapSiteDesc(), hugeMemoryEnabled(memoryIndex));
7862 store(start, &access, val16);
7863 }
7864 #endif
7865
7866 return true;
7867 }
7868
7869 bool FunctionCompiler::emitMemFill() {
7870 uint32_t memoryIndex;
7871 MDefinition *start, *val, *len;
7872 if (!iter().readMemFill(&memoryIndex, &start, &val, &len)) {
7873 return false;
7874 }
7875
7876 if (inDeadCode()) {
7877 return true;
7878 }
7879
7880 if (len->isConstant() && val->isConstant()) {
7881 uint64_t length = isMem32(memoryIndex) ? len->toConstant()->toInt32()
7882 : len->toConstant()->toInt64();
7883 static_assert(MaxInlineMemoryFillLength <= UINT32_MAX);
7884 if (length != 0 && length <= MaxInlineMemoryFillLength) {
7885 return emitMemFillInline(memoryIndex, start, val, uint32_t(length));
7886 }
7887 }
7888
7889 return emitMemFillCall(memoryIndex, start, val, len);
7890 }
7891
7892 bool FunctionCompiler::emitMemInit() {
7893 uint32_t segIndexVal = 0, dstMemIndex = 0;
7894 MDefinition *dstOff, *srcOff, *len;
7895 if (!iter().readMemOrTableInit(true, &segIndexVal, &dstMemIndex, &dstOff,
7896 &srcOff, &len)) {
7897 return false;
7898 }
7899
7900 if (inDeadCode()) {
7901 return true;
7902 }
7903
7904 uint32_t bytecodeOffset = readBytecodeOffset();
7905 const SymbolicAddressSignature& callee =
7906 (isMem32(dstMemIndex) ? SASigMemInitM32 : SASigMemInitM64);
7907
7908 MDefinition* segIndex = constantI32(int32_t(segIndexVal));
7909 if (!segIndex) {
7910 return false;
7911 }
7912
7913 MDefinition* dti = constantI32(int32_t(dstMemIndex));
7914 if (!dti) {
7915 return false;
7916 }
7917
7918 return emitInstanceCall5(bytecodeOffset, callee, dstOff, srcOff, len,
7919 segIndex, dti);
7920 }
7921
7922 bool FunctionCompiler::emitTableInit() {
7923 uint32_t segIndexVal = 0, dstTableIndex = 0;
7924 MDefinition *dstOff, *srcOff, *len;
7925 if (!iter().readMemOrTableInit(false, &segIndexVal, &dstTableIndex, &dstOff,
7926 &srcOff, &len)) {
7927 return false;
7928 }
7929
7930 if (inDeadCode()) {
7931 return true;
7932 }
7933
7934 uint32_t bytecodeOffset = readBytecodeOffset();
7935 const TableDesc& table = codeMeta().tables[dstTableIndex];
7936
7937 MDefinition* dstOff32 = tableAddressToI32(table.addressType(), dstOff);
7938 if (!dstOff32) {
7939 return false;
7940 }
7941
7942 MDefinition* segIndex = constantI32(int32_t(segIndexVal));
7943 if (!segIndex) {
7944 return false;
7945 }
7946
7947 MDefinition* dti = constantI32(int32_t(dstTableIndex));
7948 if (!dti) {
7949 return false;
7950 }
7951
7952 return emitInstanceCall5(bytecodeOffset, SASigTableInit, dstOff32, srcOff,
7953 len, segIndex, dti);
7954 }
7955
7956 bool FunctionCompiler::emitTableFill() {
7957 uint32_t tableIndex;
7958 MDefinition *start, *val, *len;
7959 if (!iter().readTableFill(&tableIndex, &start, &val, &len)) {
7960 return false;
7961 }
7962
7963 if (inDeadCode()) {
7964 return true;
7965 }
7966
7967 uint32_t bytecodeOffset = readBytecodeOffset();
7968 const TableDesc& table = codeMeta().tables[tableIndex];
7969
7970 MDefinition* start32 = tableAddressToI32(table.addressType(), start);
7971 if (!start32) {
7972 return false;
7973 }
7974
7975 MDefinition* len32 = tableAddressToI32(table.addressType(), len);
7976 if (!len32) {
7977 return false;
7978 }
7979
7980 MDefinition* tableIndexArg = constantI32(int32_t(tableIndex));
7981 if (!tableIndexArg) {
7982 return false;
7983 }
7984
7985 return emitInstanceCall4(bytecodeOffset, SASigTableFill, start32, val, len32,
7986 tableIndexArg);
7987 }
7988
7989 #if ENABLE_WASM_MEMORY_CONTROL
7990 bool FunctionCompiler::emitMemDiscard() {
7991 uint32_t memoryIndex;
7992 MDefinition *start, *len;
7993 if (!iter().readMemDiscard(&memoryIndex, &start, &len)) {
7994 return false;
7995 }
7996
7997 if (inDeadCode()) {
7998 return true;
7999 }
8000
8001 uint32_t bytecodeOffset = readBytecodeOffset();
8002
8003 MDefinition* base = memoryBase(memoryIndex);
8004 bool mem32 = isMem32(memoryIndex);
8005
8006 const SymbolicAddressSignature& callee =
8007 (codeMeta().usesSharedMemory(memoryIndex)
8008 ? (mem32 ? SASigMemDiscardSharedM32 : SASigMemDiscardSharedM64)
8009 : (mem32 ? SASigMemDiscardM32 : SASigMemDiscardM64));
8010 return emitInstanceCall3(bytecodeOffset, callee, start, len, base);
8011 }
8012 #endif
8013
8014 bool FunctionCompiler::emitTableGet() {
8015 uint32_t tableIndex;
8016 MDefinition* address;
8017 if (!iter().readTableGet(&tableIndex, &address)) {
8018 return false;
8019 }
8020
8021 if (inDeadCode()) {
8022 return true;
8023 }
8024
8025 const TableDesc& table = codeMeta().tables[tableIndex];
8026
8027 MDefinition* address32 = tableAddressToI32(table.addressType(), address);
8028 if (!address32) {
8029 return false;
8030 }
8031
8032 if (table.elemType.tableRepr() == TableRepr::Ref) {
8033 MDefinition* ret = tableGetAnyRef(tableIndex, address32);
8034 if (!ret) {
8035 return false;
8036 }
8037 iter().setResult(ret);
8038 return true;
8039 }
8040
8041 uint32_t bytecodeOffset = readBytecodeOffset();
8042
8043 MDefinition* tableIndexArg = constantI32(int32_t(tableIndex));
8044 if (!tableIndexArg) {
8045 return false;
8046 }
8047
8048 // The return value here is either null, denoting an error, or a short-lived
8049 // pointer to a location containing a possibly-null ref.
8050 MDefinition* ret;
8051 if (!emitInstanceCall2(bytecodeOffset, SASigTableGet, address32,
8052 tableIndexArg, &ret)) {
8053 return false;
8054 }
8055
8056 iter().setResult(ret);
8057 return true;
8058 }
8059
8060 bool FunctionCompiler::emitTableGrow() {
8061 uint32_t tableIndex;
8062 MDefinition* initValue;
8063 MDefinition* delta;
8064 if (!iter().readTableGrow(&tableIndex, &initValue, &delta)) {
8065 return false;
8066 }
8067
8068 if (inDeadCode()) {
8069 return true;
8070 }
8071
8072 uint32_t bytecodeOffset = readBytecodeOffset();
8073 const TableDesc& table = codeMeta().tables[tableIndex];
8074
8075 MDefinition* delta32 = tableAddressToI32(table.addressType(), delta);
8076 if (!delta32) {
8077 return false;
8078 }
8079
8080 MDefinition* tableIndexArg = constantI32(int32_t(tableIndex));
8081 if (!tableIndexArg) {
8082 return false;
8083 }
8084
8085 MDefinition* ret;
8086 if (!emitInstanceCall3(bytecodeOffset, SASigTableGrow, initValue, delta32,
8087 tableIndexArg, &ret)) {
8088 return false;
8089 }
8090
8091 if (table.addressType() == AddressType::I64) {
8092 ret = extendI32(ret, false);
8093 if (!ret) {
8094 return false;
8095 }
8096 }
8097
8098 iter().setResult(ret);
8099 return true;
8100 }
8101
8102 bool FunctionCompiler::emitTableSet() {
8103 uint32_t tableIndex;
8104 MDefinition* address;
8105 MDefinition* value;
8106 if (!iter().readTableSet(&tableIndex, &address, &value)) {
8107 return false;
8108 }
8109
8110 if (inDeadCode()) {
8111 return true;
8112 }
8113
8114 uint32_t bytecodeOffset = readBytecodeOffset();
8115
8116 const TableDesc& table = codeMeta().tables[tableIndex];
8117
8118 MDefinition* address32 = tableAddressToI32(table.addressType(), address);
8119 if (!address32) {
8120 return false;
8121 }
8122
8123 if (table.elemType.tableRepr() == TableRepr::Ref) {
8124 return tableSetAnyRef(tableIndex, address32, value, bytecodeOffset);
8125 }
8126
8127 MDefinition* tableIndexArg = constantI32(int32_t(tableIndex));
8128 if (!tableIndexArg) {
8129 return false;
8130 }
8131
8132 return emitInstanceCall3(bytecodeOffset, SASigTableSet, address32, value,
8133 tableIndexArg);
8134 }
8135
8136 bool FunctionCompiler::emitTableSize() {
8137 uint32_t tableIndex;
8138 if (!iter().readTableSize(&tableIndex)) {
8139 return false;
8140 }
8141
8142 if (inDeadCode()) {
8143 return true;
8144 }
8145
8146 MDefinition* length = loadTableLength(tableIndex);
8147 if (!length) {
8148 return false;
8149 }
8150
8151 if (codeMeta().tables[tableIndex].addressType() == AddressType::I64) {
8152 length = extendI32(length, true);
8153 if (!length) {
8154 return false;
8155 }
8156 }
8157
8158 iter().setResult(length);
8159 return true;
8160 }
8161
8162 bool FunctionCompiler::emitRefFunc() {
8163 uint32_t funcIndex;
8164 if (!iter().readRefFunc(&funcIndex)) {
8165 return false;
8166 }
8167
8168 if (inDeadCode()) {
8169 return true;
8170 }
8171
8172 uint32_t bytecodeOffset = readBytecodeOffset();
8173
8174 MDefinition* funcIndexArg = constantI32(int32_t(funcIndex));
8175 if (!funcIndexArg) {
8176 return false;
8177 }
8178
8179 // The return value here is either null, denoting an error, or a short-lived
8180 // pointer to a location containing a possibly-null ref.
8181 MDefinition* ret;
8182 if (!emitInstanceCall1(bytecodeOffset, SASigRefFunc, funcIndexArg, &ret)) {
8183 return false;
8184 }
8185
8186 iter().setResult(ret);
8187 return true;
8188 }
8189
8190 bool FunctionCompiler::emitRefNull() {
8191 RefType type;
8192 if (!iter().readRefNull(&type)) {
8193 return false;
8194 }
8195
8196 if (inDeadCode()) {
8197 return true;
8198 }
8199
8200 MDefinition* nullVal = constantNullRef(MaybeRefType(type));
8201 if (!nullVal) {
8202 return false;
8203 }
8204 iter().setResult(nullVal);
8205 return true;
8206 }
8207
8208 bool FunctionCompiler::emitRefIsNull() {
8209 MDefinition* input;
8210 if (!iter().readRefIsNull(&input)) {
8211 return false;
8212 }
8213
8214 if (inDeadCode()) {
8215 return true;
8216 }
8217
8218 MDefinition* nullVal = constantNullRef(MaybeRefType());
8219 if (!nullVal) {
8220 return false;
8221 }
8222 iter().setResult(
8223 compare(input, nullVal, JSOp::Eq, MCompare::Compare_WasmAnyRef));
8224 return true;
8225 }
8226
8227 #ifdef ENABLE_WASM_SIMD
8228 bool FunctionCompiler::emitConstSimd128() {
8229 V128 v128;
8230 if (!iter().readV128Const(&v128)) {
8231 return false;
8232 }
8233
8234 iter().setResult(constantV128(v128));
8235 return true;
8236 }
8237
8238 bool FunctionCompiler::emitBinarySimd128(bool commutative, SimdOp op) {
8239 MDefinition* lhs;
8240 MDefinition* rhs;
8241 if (!iter().readBinary(ValType::V128, &lhs, &rhs)) {
8242 return false;
8243 }
8244
8245 iter().setResult(binarySimd128(lhs, rhs, commutative, op));
8246 return true;
8247 }
8248
8249 bool FunctionCompiler::emitTernarySimd128(wasm::SimdOp op) {
8250 MDefinition* v0;
8251 MDefinition* v1;
8252 MDefinition* v2;
8253 if (!iter().readTernary(ValType::V128, &v0, &v1, &v2)) {
8254 return false;
8255 }
8256
8257 iter().setResult(ternarySimd128(v0, v1, v2, op));
8258 return true;
8259 }
8260
8261 bool FunctionCompiler::emitShiftSimd128(SimdOp op) {
8262 MDefinition* lhs;
8263 MDefinition* rhs;
8264 if (!iter().readVectorShift(&lhs, &rhs)) {
8265 return false;
8266 }
8267
8268 iter().setResult(shiftSimd128(lhs, rhs, op));
8269 return true;
8270 }
8271
8272 bool FunctionCompiler::emitSplatSimd128(ValType inType, SimdOp op) {
8273 MDefinition* src;
8274 if (!iter().readConversion(inType, ValType::V128, &src)) {
8275 return false;
8276 }
8277
8278 iter().setResult(scalarToSimd128(src, op));
8279 return true;
8280 }
8281
8282 bool FunctionCompiler::emitUnarySimd128(SimdOp op) {
8283 MDefinition* src;
8284 if (!iter().readUnary(ValType::V128, &src)) {
8285 return false;
8286 }
8287
8288 iter().setResult(unarySimd128(src, op));
8289 return true;
8290 }
8291
8292 bool FunctionCompiler::emitReduceSimd128(SimdOp op) {
8293 MDefinition* src;
8294 if (!iter().readConversion(ValType::V128, ValType::I32, &src)) {
8295 return false;
8296 }
8297
8298 iter().setResult(reduceSimd128(src, op, ValType::I32));
8299 return true;
8300 }
8301
8302 bool FunctionCompiler::emitExtractLaneSimd128(ValType outType,
8303 uint32_t laneLimit, SimdOp op) {
8304 uint32_t laneIndex;
8305 MDefinition* src;
8306 if (!iter().readExtractLane(outType, laneLimit, &laneIndex, &src)) {
8307 return false;
8308 }
8309
8310 iter().setResult(reduceSimd128(src, op, outType, laneIndex));
8311 return true;
8312 }
8313
8314 bool FunctionCompiler::emitReplaceLaneSimd128(ValType laneType,
8315 uint32_t laneLimit, SimdOp op) {
8316 uint32_t laneIndex;
8317 MDefinition* lhs;
8318 MDefinition* rhs;
8319 if (!iter().readReplaceLane(laneType, laneLimit, &laneIndex, &lhs, &rhs)) {
8320 return false;
8321 }
8322
8323 iter().setResult(replaceLaneSimd128(lhs, rhs, laneIndex, op));
8324 return true;
8325 }
8326
8327 bool FunctionCompiler::emitShuffleSimd128() {
8328 MDefinition* v1;
8329 MDefinition* v2;
8330 V128 control;
8331 if (!iter().readVectorShuffle(&v1, &v2, &control)) {
8332 return false;
8333 }
8334
8335 iter().setResult(shuffleSimd128(v1, v2, control));
8336 return true;
8337 }
8338
8339 bool FunctionCompiler::emitLoadSplatSimd128(Scalar::Type viewType,
8340 wasm::SimdOp splatOp) {
8341 LinearMemoryAddress<MDefinition*> addr;
8342 if (!iter().readLoadSplat(Scalar::byteSize(viewType), &addr)) {
8343 return false;
8344 }
8345
8346 auto* ins = loadSplatSimd128(viewType, addr, splatOp);
8347 if (!inDeadCode() && !ins) {
8348 return false;
8349 }
8350 iter().setResult(ins);
8351 return true;
8352 }
8353
8354 bool FunctionCompiler::emitLoadExtendSimd128(wasm::SimdOp op) {
8355 LinearMemoryAddress<MDefinition*> addr;
8356 if (!iter().readLoadExtend(&addr)) {
8357 return false;
8358 }
8359
8360 auto* ins = loadExtendSimd128(addr, op);
8361 if (!inDeadCode() && !ins) {
8362 return false;
8363 }
8364 iter().setResult(ins);
8365 return true;
8366 }
8367
8368 bool FunctionCompiler::emitLoadZeroSimd128(Scalar::Type viewType,
8369 size_t numBytes) {
8370 LinearMemoryAddress<MDefinition*> addr;
8371 if (!iter().readLoadSplat(numBytes, &addr)) {
8372 return false;
8373 }
8374
8375 auto* ins = loadZeroSimd128(viewType, numBytes, addr);
8376 if (!inDeadCode() && !ins) {
8377 return false;
8378 }
8379 iter().setResult(ins);
8380 return true;
8381 }
8382
8383 bool FunctionCompiler::emitLoadLaneSimd128(uint32_t laneSize) {
8384 uint32_t laneIndex;
8385 MDefinition* src;
8386 LinearMemoryAddress<MDefinition*> addr;
8387 if (!iter().readLoadLane(laneSize, &addr, &laneIndex, &src)) {
8388 return false;
8389 }
8390
8391 auto* ins = loadLaneSimd128(laneSize, addr, laneIndex, src);
8392 if (!inDeadCode() && !ins) {
8393 return false;
8394 }
8395 iter().setResult(ins);
8396 return true;
8397 }
8398
8399 bool FunctionCompiler::emitStoreLaneSimd128(uint32_t laneSize) {
8400 uint32_t laneIndex;
8401 MDefinition* src;
8402 LinearMemoryAddress<MDefinition*> addr;
8403 if (!iter().readStoreLane(laneSize, &addr, &laneIndex, &src)) {
8404 return false;
8405 }
8406
8407 storeLaneSimd128(laneSize, addr, laneIndex, src);
8408 return true;
8409 }
8410
8411 #endif // ENABLE_WASM_SIMD
8412
8413 bool FunctionCompiler::emitRefAsNonNull() {
8414 MDefinition* ref;
8415 if (!iter().readRefAsNonNull(&ref)) {
8416 return false;
8417 }
8418
8419 if (inDeadCode()) {
8420 return true;
8421 }
8422
8423 MDefinition* ins = refAsNonNull(ref);
8424 if (!ins) {
8425 return false;
8426 }
8427
8428 iter().setResult(ins);
8429 return true;
8430 }
8431
8432 bool FunctionCompiler::emitBrOnNull() {
8433 uint32_t relativeDepth;
8434 ResultType type;
8435 DefVector values;
8436 MDefinition* condition;
8437 if (!iter().readBrOnNull(&relativeDepth, &type, &values, &condition)) {
8438 return false;
8439 }
8440
8441 return brOnNull(relativeDepth, values, type, condition);
8442 }
8443
8444 bool FunctionCompiler::emitBrOnNonNull() {
8445 uint32_t relativeDepth;
8446 ResultType type;
8447 DefVector values;
8448 MDefinition* condition;
8449 if (!iter().readBrOnNonNull(&relativeDepth, &type, &values, &condition)) {
8450 return false;
8451 }
8452
8453 return brOnNonNull(relativeDepth, values, type, condition);
8454 }
8455
8456 // Speculatively inline a call_refs that are likely to target the expected
8457 // function index in this module. A fallback for if the actual callee is not
8458 // any of the speculated expected callees is always generated. This leads to a
8459 // control flow chain that is roughly:
8460 //
8461 // if (ref.func $expectedFuncIndex_1) == actualCalleeFunc:
8462 // (call_inline $expectedFuncIndex1)
8463 // else if (ref.func $expectedFuncIndex_2) == actualCalleeFunc:
8464 // (call_inline $expectedFuncIndex2)
8465 // ...
8466 // else:
8467 // (call_ref actualCalleeFunc)
8468 //
8469 bool FunctionCompiler::emitSpeculativeInlineCallRef(
8470 uint32_t bytecodeOffset, const FuncType& funcType,
8471 CallRefHint expectedFuncIndices, MDefinition* actualCalleeFunc,
8472 const DefVector& args, DefVector* results) {
8473 // There must be at least one speculative target.
8474 MOZ_ASSERT(!expectedFuncIndices.empty());
8475
8476 // Perform an up front null check on the callee function reference.
8477 actualCalleeFunc = refAsNonNull(actualCalleeFunc);
8478 if (!actualCalleeFunc) {
8479 return false;
8480 }
8481
8482 constexpr size_t numElseBlocks = CallRefHint::NUM_ENTRIES + 1;
8483 Vector<MBasicBlock*, numElseBlocks, SystemAllocPolicy> elseBlocks;
8484 if (!elseBlocks.reserve(numElseBlocks)) {
8485 return false;
8486 }
8487
8488 for (uint32_t i = 0; i < expectedFuncIndices.length(); i++) {
8489 uint32_t funcIndex = expectedFuncIndices.get(i);
8490
8491 // Load the cached value of `ref.func $expectedFuncIndex` for comparing
8492 // against `actualCalleeFunc`. This cached value may be null if the
8493 // `ref.func` for the expected function has not been executed in this
8494 // runtime session.
8495 //
8496 // This is okay because we have done a null check on the `actualCalleeFunc`
8497 // already and so comparing it against a null expected callee func will
8498 // return false and fall back to the general case. This can only happen if
8499 // we've deserialized a cached module in a different session, and then run
8500 // the code without ever acquiring a reference to the expected function. In
8501 // that case, the expected callee could never be the target of this
8502 // call_ref, so performing the fallback path is the right thing to do
8503 // anyways.
8504 MDefinition* expectedCalleeFunc = loadCachedRefFunc(funcIndex);
8505 if (!expectedCalleeFunc) {
8506 return false;
8507 }
8508
8509 // Check if the callee funcref we have is equals to the expected callee
8510 // funcref we're inlining.
8511 MDefinition* isExpectedCallee =
8512 compare(actualCalleeFunc, expectedCalleeFunc, JSOp::Eq,
8513 MCompare::Compare_WasmAnyRef);
8514 if (!isExpectedCallee) {
8515 return false;
8516 }
8517
8518 // Start a 'then' block, which will have the inlined code
8519 MBasicBlock* elseBlock;
8520 if (!branchAndStartThen(isExpectedCallee, &elseBlock)) {
8521 return false;
8522 }
8523
8524 // Inline the expected callee as we do with direct calls
8525 DefVector inlineResults;
8526 if (!emitInlineCall(funcType, funcIndex,
8527 InliningHeuristics::CallKind::CallRef, args,
8528 &inlineResults)) {
8529 return false;
8530 }
8531
8532 // Push the results for joining with the 'else' block
8533 if (!pushDefs(inlineResults)) {
8534 return false;
8535 }
8536
8537 // Switch to the 'else' block which will have, either the check for the
8538 // next target, or the fallback `call_ref` if we're out of targets.
8539 if (!switchToElse(elseBlock, &elseBlock)) {
8540 return false;
8541 }
8542
8543 elseBlocks.infallibleAppend(elseBlock);
8544 }
8545
8546 DefVector callResults;
8547 if (!callRef(funcType, actualCalleeFunc, bytecodeOffset, args,
8548 &callResults)) {
8549 return false;
8550 }
8551
8552 // Push the results for joining with the 'then' block
8553 if (!pushDefs(callResults)) {
8554 return false;
8555 }
8556
8557 // Join the various branches together
8558 for (uint32_t i = elseBlocks.length() - 1; i != 0; i--) {
8559 DefVector results;
8560 if (!joinIfElse(elseBlocks[i], &results) || !pushDefs(results)) {
8561 return false;
8562 }
8563 }
8564 return joinIfElse(elseBlocks[0], results);
8565 }
8566
8567 bool FunctionCompiler::emitCallRef() {
8568 uint32_t bytecodeOffset = readBytecodeOffset();
8569 uint32_t funcTypeIndex;
8570 MDefinition* callee;
8571 DefVector args;
8572
8573 if (!iter().readCallRef(&funcTypeIndex, &callee, &args)) {
8574 return false;
8575 }
8576
8577 // We must unconditionally read a call_ref hint so that we stay in sync with
8578 // how baseline generates them.
8579 CallRefHint hint = readCallRefHint();
8580
8581 if (inDeadCode()) {
8582 return true;
8583 }
8584
8585 const FuncType& funcType = codeMeta().types->type(funcTypeIndex).funcType();
8586
8587 // Ask the inlining heuristics which entries in `hint` we are allowed to
8588 // inline.
8589 CallRefHint approved =
8590 auditInlineableCallees(InliningHeuristics::CallKind::CallRef, hint);
8591 if (!approved.empty()) {
8592 DefVector results;
8593 if (!emitSpeculativeInlineCallRef(bytecodeOffset, funcType, approved,
8594 callee, args, &results)) {
8595 return false;
8596 }
8597 iter().setResults(results.length(), results);
8598 return true;
8599 }
8600
8601 DefVector results;
8602 if (!callRef(funcType, callee, bytecodeOffset, args, &results)) {
8603 return false;
8604 }
8605
8606 iter().setResults(results.length(), results);
8607 return true;
8608 }
8609
8610 bool FunctionCompiler::emitStructNew() {
8611 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8612
8613 uint32_t typeIndex;
8614 DefVector args;
8615 if (!iter().readStructNew(&typeIndex, &args)) {
8616 return false;
8617 }
8618
8619 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8620
8621 if (inDeadCode()) {
8622 return true;
8623 }
8624
8625 const TypeDef& typeDef = (*codeMeta().types)[typeIndex];
8626 const StructType& structType = typeDef.structType();
8627 MOZ_ASSERT(args.length() == structType.fields_.length());
8628
8629 MDefinition* structObject =
8630 createStructObject(typeIndex, allocSiteIndex, false);
8631 if (!structObject) {
8632 return false;
8633 }
8634
8635 // And fill in the fields.
8636 for (uint32_t fieldIndex = 0; fieldIndex < structType.fields_.length();
8637 fieldIndex++) {
8638 if (!mirGen().ensureBallast()) {
8639 return false;
8640 }
8641 if (!writeValueToStructField(lineOrBytecode, structType, fieldIndex,
8642 structObject, args[fieldIndex],
8643 WasmPreBarrierKind::None)) {
8644 return false;
8645 }
8646 }
8647
8648 iter().setResult(structObject);
8649 return true;
8650 }
8651
8652 bool FunctionCompiler::emitStructNewDefault() {
8653 uint32_t typeIndex;
8654 if (!iter().readStructNewDefault(&typeIndex)) {
8655 return false;
8656 }
8657
8658 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8659
8660 if (inDeadCode()) {
8661 return true;
8662 }
8663
8664 MDefinition* structObject =
8665 createStructObject(typeIndex, allocSiteIndex, true);
8666 if (!structObject) {
8667 return false;
8668 }
8669
8670 iter().setResult(structObject);
8671 return true;
8672 }
8673
8674 bool FunctionCompiler::emitStructSet() {
8675 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8676
8677 uint32_t typeIndex;
8678 uint32_t fieldIndex;
8679 MDefinition* structObject;
8680 MDefinition* value;
8681 if (!iter().readStructSet(&typeIndex, &fieldIndex, &structObject, &value)) {
8682 return false;
8683 }
8684
8685 if (inDeadCode()) {
8686 return true;
8687 }
8688
8689 // Check for null is done at writeValueToStructField.
8690
8691 // And fill in the field.
8692 const StructType& structType = (*codeMeta().types)[typeIndex].structType();
8693 return writeValueToStructField(lineOrBytecode, structType, fieldIndex,
8694 structObject, value,
8695 WasmPreBarrierKind::Normal);
8696 }
8697
8698 bool FunctionCompiler::emitStructGet(FieldWideningOp wideningOp) {
8699 uint32_t typeIndex;
8700 uint32_t fieldIndex;
8701 MDefinition* structObject;
8702 if (!iter().readStructGet(&typeIndex, &fieldIndex, wideningOp,
8703 &structObject)) {
8704 return false;
8705 }
8706
8707 if (inDeadCode()) {
8708 return true;
8709 }
8710
8711 // Check for null is done at readValueFromStructField.
8712
8713 // And fetch the data.
8714 const StructType& structType = (*codeMeta().types)[typeIndex].structType();
8715 MDefinition* load = readValueFromStructField(structType, fieldIndex,
8716 wideningOp, structObject);
8717 if (!load) {
8718 return false;
8719 }
8720
8721 iter().setResult(load);
8722 return true;
8723 }
8724
8725 bool FunctionCompiler::emitArrayNew() {
8726 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8727
8728 uint32_t typeIndex;
8729 MDefinition* numElements;
8730 MDefinition* fillValue;
8731 if (!iter().readArrayNew(&typeIndex, &numElements, &fillValue)) {
8732 return false;
8733 }
8734
8735 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8736
8737 if (inDeadCode()) {
8738 return true;
8739 }
8740
8741 // If the requested size exceeds MaxArrayPayloadBytes, the MIR generated by
8742 // this helper will trap.
8743 MDefinition* arrayObject = createArrayNewCallAndLoop(
8744 lineOrBytecode, typeIndex, allocSiteIndex, numElements, fillValue);
8745 if (!arrayObject) {
8746 return false;
8747 }
8748
8749 iter().setResult(arrayObject);
8750 return true;
8751 }
8752
8753 bool FunctionCompiler::emitArrayNewDefault() {
8754 // This is almost identical to EmitArrayNew, except we skip the
8755 // initialisation loop.
8756 uint32_t typeIndex;
8757 MDefinition* numElements;
8758 if (!iter().readArrayNewDefault(&typeIndex, &numElements)) {
8759 return false;
8760 }
8761
8762 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8763
8764 if (inDeadCode()) {
8765 return true;
8766 }
8767
8768 // Create the array object, default-initialized.
8769 MDefinition* arrayObject =
8770 createArrayObject(typeIndex, allocSiteIndex, numElements,
8771 /*zeroFields=*/true);
8772 if (!arrayObject) {
8773 return false;
8774 }
8775
8776 iter().setResult(arrayObject);
8777 return true;
8778 }
8779
8780 bool FunctionCompiler::emitArrayNewFixed() {
8781 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8782
8783 uint32_t typeIndex, numElements;
8784 DefVector values;
8785
8786 if (!iter().readArrayNewFixed(&typeIndex, &numElements, &values)) {
8787 return false;
8788 }
8789 MOZ_ASSERT(values.length() == numElements);
8790
8791 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8792
8793 if (inDeadCode()) {
8794 return true;
8795 }
8796
8797 MDefinition* numElementsDef = constantI32(int32_t(numElements));
8798 if (!numElementsDef) {
8799 return false;
8800 }
8801
8802 // Create the array object, uninitialized.
8803 const ArrayType& arrayType = (*codeMeta().types)[typeIndex].arrayType();
8804 StorageType elemType = arrayType.elementType();
8805 uint32_t elemSize = elemType.size();
8806 MDefinition* arrayObject =
8807 createArrayObject(typeIndex, allocSiteIndex, numElementsDef,
8808 /*zeroFields=*/false);
8809 if (!arrayObject) {
8810 return false;
8811 }
8812
8813 // Make `base` point at the first byte of the (OOL) data area.
8814 MDefinition* base = getWasmArrayObjectData(arrayObject);
8815 if (!base) {
8816 return false;
8817 }
8818
8819 // Write each element in turn.
8820
8821 // How do we know that the offset expression `i * elemSize` below remains
8822 // within 2^31 (signed-i32) range? In the worst case we will have 16-byte
8823 // values, and there can be at most MaxFunctionBytes expressions, if it were
8824 // theoretically possible to generate one expression per instruction byte.
8825 // Hence the max offset we can be expected to generate is
8826 // `16 * MaxFunctionBytes`.
8827 static_assert(16 /* sizeof v128 */ * MaxFunctionBytes <=
8828 MaxArrayPayloadBytes);
8829 MOZ_RELEASE_ASSERT(numElements <= MaxFunctionBytes);
8830
8831 for (uint32_t i = 0; i < numElements; i++) {
8832 if (!mirGen().ensureBallast()) {
8833 return false;
8834 }
8835 // `i * elemSize` is made safe by the assertions above.
8836 if (!writeGcValueAtBasePlusOffset(
8837 lineOrBytecode, elemType, arrayObject, AliasSet::WasmArrayDataArea,
8838 values[numElements - 1 - i], base, i * elemSize, i, false,
8839 WasmPreBarrierKind::None)) {
8840 return false;
8841 }
8842 }
8843
8844 iter().setResult(arrayObject);
8845 return true;
8846 }
8847
8848 bool FunctionCompiler::emitArrayNewData() {
8849 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8850
8851 uint32_t typeIndex, segIndex;
8852 MDefinition* segByteOffset;
8853 MDefinition* numElements;
8854 if (!iter().readArrayNewData(&typeIndex, &segIndex, &segByteOffset,
8855 &numElements)) {
8856 return false;
8857 }
8858
8859 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8860
8861 if (inDeadCode()) {
8862 return true;
8863 }
8864
8865 MDefinition* typeIndexValue = constantI32(int32_t(typeIndex));
8866 if (!typeIndexValue) {
8867 return false;
8868 }
8869
8870 MDefinition* allocSite = loadAllocSiteInstanceData(allocSiteIndex);
8871 if (!allocSite) {
8872 return false;
8873 }
8874
8875 // Other values we need to pass to the instance call:
8876 MDefinition* segIndexM = constantI32(int32_t(segIndex));
8877 if (!segIndexM) {
8878 return false;
8879 }
8880
8881 // Create call:
8882 // arrayObject = Instance::arrayNewData(segByteOffset:u32, numElements:u32,
8883 // typeDefData:word, segIndex:u32)
8884 // If the requested size exceeds MaxArrayPayloadBytes, the MIR generated by
8885 // this call will trap.
8886 MDefinition* arrayObject;
8887 if (!emitInstanceCall5(lineOrBytecode, SASigArrayNewData, segByteOffset,
8888 numElements, typeIndexValue, allocSite, segIndexM,
8889 &arrayObject)) {
8890 return false;
8891 }
8892
8893 iter().setResult(arrayObject);
8894 return true;
8895 }
8896
8897 bool FunctionCompiler::emitArrayNewElem() {
8898 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8899
8900 uint32_t typeIndex, segIndex;
8901 MDefinition* segElemIndex;
8902 MDefinition* numElements;
8903 if (!iter().readArrayNewElem(&typeIndex, &segIndex, &segElemIndex,
8904 &numElements)) {
8905 return false;
8906 }
8907
8908 uint32_t allocSiteIndex = readAllocSiteIndex(typeIndex);
8909
8910 if (inDeadCode()) {
8911 return true;
8912 }
8913
8914 MDefinition* typeIndexValue = constantI32(int32_t(typeIndex));
8915 if (!typeIndexValue) {
8916 return false;
8917 }
8918
8919 MDefinition* allocSite = loadAllocSiteInstanceData(allocSiteIndex);
8920 if (!allocSite) {
8921 return false;
8922 }
8923
8924 // Other values we need to pass to the instance call:
8925 MDefinition* segIndexM = constantI32(int32_t(segIndex));
8926 if (!segIndexM) {
8927 return false;
8928 }
8929
8930 // Create call:
8931 // arrayObject = Instance::arrayNewElem(segElemIndex:u32, numElements:u32,
8932 // typeDefData:word, segIndex:u32)
8933 // If the requested size exceeds MaxArrayPayloadBytes, the MIR generated by
8934 // this call will trap.
8935 MDefinition* arrayObject;
8936 if (!emitInstanceCall5(lineOrBytecode, SASigArrayNewElem, segElemIndex,
8937 numElements, typeIndexValue, allocSite, segIndexM,
8938 &arrayObject)) {
8939 return false;
8940 }
8941
8942 iter().setResult(arrayObject);
8943 return true;
8944 }
8945
8946 bool FunctionCompiler::emitArrayInitData() {
8947 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8948
8949 uint32_t unusedTypeIndex, segIndex;
8950 MDefinition* array;
8951 MDefinition* arrayIndex;
8952 MDefinition* segOffset;
8953 MDefinition* length;
8954 if (!iter().readArrayInitData(&unusedTypeIndex, &segIndex, &array,
8955 &arrayIndex, &segOffset, &length)) {
8956 return false;
8957 }
8958
8959 if (inDeadCode()) {
8960 return true;
8961 }
8962
8963 // Other values we need to pass to the instance call:
8964 MDefinition* segIndexM = constantI32(int32_t(segIndex));
8965 if (!segIndexM) {
8966 return false;
8967 }
8968
8969 // Create call:
8970 // Instance::arrayInitData(array:word, index:u32, segByteOffset:u32,
8971 // numElements:u32, segIndex:u32) If the requested size exceeds
8972 // MaxArrayPayloadBytes, the MIR generated by this call will trap.
8973 return emitInstanceCall5(lineOrBytecode, SASigArrayInitData, array,
8974 arrayIndex, segOffset, length, segIndexM);
8975 }
8976
8977 bool FunctionCompiler::emitArrayInitElem() {
8978 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
8979
8980 uint32_t typeIndex, segIndex;
8981 MDefinition* array;
8982 MDefinition* arrayIndex;
8983 MDefinition* segOffset;
8984 MDefinition* length;
8985 if (!iter().readArrayInitElem(&typeIndex, &segIndex, &array, &arrayIndex,
8986 &segOffset, &length)) {
8987 return false;
8988 }
8989
8990 if (inDeadCode()) {
8991 return true;
8992 }
8993
8994 MDefinition* typeIndexValue = constantI32(int32_t(typeIndex));
8995 if (!typeIndexValue) {
8996 return false;
8997 }
8998
8999 // Other values we need to pass to the instance call:
9000 MDefinition* segIndexM = constantI32(int32_t(segIndex));
9001 if (!segIndexM) {
9002 return false;
9003 }
9004
9005 // Create call:
9006 // Instance::arrayInitElem(array:word, index:u32, segByteOffset:u32,
9007 // numElements:u32, typeDefData:word, segIndex:u32) If the requested size
9008 // exceeds MaxArrayPayloadBytes, the MIR generated by this call will trap.
9009 return emitInstanceCall6(lineOrBytecode, SASigArrayInitElem, array,
9010 arrayIndex, segOffset, length, typeIndexValue,
9011 segIndexM);
9012 }
9013
9014 bool FunctionCompiler::emitArraySet() {
9015 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
9016
9017 uint32_t typeIndex;
9018 MDefinition* value;
9019 MDefinition* index;
9020 MDefinition* arrayObject;
9021 if (!iter().readArraySet(&typeIndex, &value, &index, &arrayObject)) {
9022 return false;
9023 }
9024
9025 if (inDeadCode()) {
9026 return true;
9027 }
9028
9029 // Check for null is done at setupForArrayAccess.
9030
9031 // Create the object null check and the array bounds check and get the OOL
9032 // data pointer.
9033 MDefinition* base = setupForArrayAccess(arrayObject, index);
9034 if (!base) {
9035 return false;
9036 }
9037
9038 // And do the store.
9039 const ArrayType& arrayType = (*codeMeta().types)[typeIndex].arrayType();
9040 StorageType elemType = arrayType.elementType();
9041 uint32_t elemSize = elemType.size();
9042 MOZ_ASSERT(elemSize >= 1 && elemSize <= 16);
9043
9044 return writeGcValueAtBasePlusScaledIndex(
9045 lineOrBytecode, elemType, arrayObject, AliasSet::WasmArrayDataArea, value,
9046 base, elemSize, index, WasmPreBarrierKind::Normal);
9047 }
9048
9049 bool FunctionCompiler::emitArrayGet(FieldWideningOp wideningOp) {
9050 uint32_t typeIndex;
9051 MDefinition* index;
9052 MDefinition* arrayObject;
9053 if (!iter().readArrayGet(&typeIndex, wideningOp, &index, &arrayObject)) {
9054 return false;
9055 }
9056
9057 if (inDeadCode()) {
9058 return true;
9059 }
9060
9061 // Check for null is done at setupForArrayAccess.
9062
9063 // Create the object null check and the array bounds check and get the data
9064 // pointer.
9065 MDefinition* base = setupForArrayAccess(arrayObject, index);
9066 if (!base) {
9067 return false;
9068 }
9069
9070 // And do the load.
9071 const ArrayType& arrayType = (*codeMeta().types)[typeIndex].arrayType();
9072 StorageType elemType = arrayType.elementType();
9073
9074 MDefinition* load =
9075 readGcArrayValueAtIndex(elemType, wideningOp, arrayObject,
9076 AliasSet::WasmArrayDataArea, base, index);
9077 if (!load) {
9078 return false;
9079 }
9080
9081 iter().setResult(load);
9082 return true;
9083 }
9084
9085 bool FunctionCompiler::emitArrayLen() {
9086 MDefinition* arrayObject;
9087 if (!iter().readArrayLen(&arrayObject)) {
9088 return false;
9089 }
9090
9091 if (inDeadCode()) {
9092 return true;
9093 }
9094
9095 // Check for null is done at getWasmArrayObjectNumElements.
9096
9097 // Get the size value for the array
9098 MDefinition* numElements = getWasmArrayObjectNumElements(arrayObject);
9099 if (!numElements) {
9100 return false;
9101 }
9102
9103 iter().setResult(numElements);
9104 return true;
9105 }
9106
9107 bool FunctionCompiler::emitArrayCopy() {
9108 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
9109
9110 uint32_t dstArrayTypeIndex;
9111 uint32_t srcArrayTypeIndex;
9112 MDefinition* dstArrayObject;
9113 MDefinition* dstArrayIndex;
9114 MDefinition* srcArrayObject;
9115 MDefinition* srcArrayIndex;
9116 MDefinition* numElements;
9117 if (!iter().readArrayCopy(&dstArrayTypeIndex, &srcArrayTypeIndex,
9118 &dstArrayObject, &dstArrayIndex, &srcArrayObject,
9119 &srcArrayIndex, &numElements)) {
9120 return false;
9121 }
9122
9123 if (inDeadCode()) {
9124 return true;
9125 }
9126
9127 const ArrayType& dstArrayType =
9128 codeMeta().types->type(dstArrayTypeIndex).arrayType();
9129 StorageType dstElemType = dstArrayType.elementType();
9130 int32_t elemSize = int32_t(dstElemType.size());
9131 bool elemsAreRefTyped = dstElemType.isRefType();
9132
9133 return createArrayCopy(lineOrBytecode, dstArrayObject, dstArrayIndex,
9134 srcArrayObject, srcArrayIndex, numElements, elemSize,
9135 elemsAreRefTyped);
9136 }
9137
9138 bool FunctionCompiler::emitArrayFill() {
9139 uint32_t lineOrBytecode = readCallSiteLineOrBytecode();
9140
9141 uint32_t typeIndex;
9142 MDefinition* array;
9143 MDefinition* index;
9144 MDefinition* val;
9145 MDefinition* numElements;
9146 if (!iter().readArrayFill(&typeIndex, &array, &index, &val, &numElements)) {
9147 return false;
9148 }
9149
9150 if (inDeadCode()) {
9151 return true;
9152 }
9153
9154 return createArrayFill(lineOrBytecode, typeIndex, array, index, val,
9155 numElements);
9156 }
9157
9158 bool FunctionCompiler::emitRefI31() {
9159 MDefinition* input;
9160 if (!iter().readConversion(ValType::I32,
9161 ValType(RefType::i31().asNonNullable()), &input)) {
9162 return false;
9163 }
9164
9165 if (inDeadCode()) {
9166 return true;
9167 }
9168
9169 MDefinition* output = refI31(input);
9170 if (!output) {
9171 return false;
9172 }
9173 iter().setResult(output);
9174 return true;
9175 }
9176
9177 bool FunctionCompiler::emitI31Get(FieldWideningOp wideningOp) {
9178 MOZ_ASSERT(wideningOp != FieldWideningOp::None);
9179
9180 MDefinition* input;
9181 if (!iter().readConversion(ValType(RefType::i31()), ValType::I32, &input)) {
9182 return false;
9183 }
9184
9185 if (inDeadCode()) {
9186 return true;
9187 }
9188
9189 input = refAsNonNull(input);
9190 if (!input) {
9191 return false;
9192 }
9193 MDefinition* output = i31Get(input, wideningOp);
9194 if (!output) {
9195 return false;
9196 }
9197 iter().setResult(output);
9198 return true;
9199 }
9200
9201 bool FunctionCompiler::emitRefTest(bool nullable) {
9202 MDefinition* ref;
9203 RefType sourceType;
9204 RefType destType;
9205 if (!iter().readRefTest(nullable, &sourceType, &destType, &ref)) {
9206 return false;
9207 }
9208
9209 if (inDeadCode()) {
9210 return true;
9211 }
9212
9213 MDefinition* success = refTest(ref, destType);
9214 if (!success) {
9215 return false;
9216 }
9217
9218 iter().setResult(success);
9219 return true;
9220 }
9221
9222 bool FunctionCompiler::emitRefCast(bool nullable) {
9223 MDefinition* ref;
9224 RefType sourceType;
9225 RefType destType;
9226 if (!iter().readRefCast(nullable, &sourceType, &destType, &ref)) {
9227 return false;
9228 }
9229
9230 if (inDeadCode()) {
9231 return true;
9232 }
9233
9234 MDefinition* castedRef = refCast(ref, destType);
9235 if (!castedRef) {
9236 return false;
9237 }
9238
9239 iter().setResult(castedRef);
9240 return true;
9241 }
9242
9243 bool FunctionCompiler::emitBrOnCast(bool onSuccess) {
9244 uint32_t labelRelativeDepth;
9245 RefType sourceType;
9246 RefType destType;
9247 ResultType labelType;
9248 DefVector values;
9249 if (!iter().readBrOnCast(onSuccess, &labelRelativeDepth, &sourceType,
9250 &destType, &labelType, &values)) {
9251 return false;
9252 }
9253
9254 return brOnCastCommon(onSuccess, labelRelativeDepth, sourceType, destType,
9255 labelType, values);
9256 }
9257
9258 bool FunctionCompiler::emitAnyConvertExtern() {
9259 MDefinition* ref;
9260 if (!iter().readRefConversion(RefType::extern_(), RefType::any(), &ref)) {
9261 return false;
9262 }
9263
9264 if (inDeadCode()) {
9265 return true;
9266 }
9267
9268 MDefinition* conversion = convertAnyExtern(ref, wasm::RefType::Kind::Any);
9269 if (!conversion) {
9270 return false;
9271 }
9272
9273 iter().setResult(conversion);
9274 return true;
9275 }
9276
9277 bool FunctionCompiler::emitExternConvertAny() {
9278 MDefinition* ref;
9279 if (!iter().readRefConversion(RefType::any(), RefType::extern_(), &ref)) {
9280 return false;
9281 }
9282
9283 if (inDeadCode()) {
9284 return true;
9285 }
9286
9287 MDefinition* conversion = convertAnyExtern(ref, wasm::RefType::Kind::Extern);
9288 if (!conversion) {
9289 return false;
9290 }
9291
9292 iter().setResult(conversion);
9293 return true;
9294 }
9295
9296 bool FunctionCompiler::emitCallBuiltinModuleFunc() {
9297 const BuiltinModuleFunc* builtinModuleFunc;
9298
9299 DefVector params;
9300 if (!iter().readCallBuiltinModuleFunc(&builtinModuleFunc, &params)) {
9301 return false;
9302 }
9303
9304 return callBuiltinModuleFunc(*builtinModuleFunc, params);
9305 }
9306
9307 bool FunctionCompiler::emitBodyExprs() {
9308 if (!iter().startFunction(funcIndex())) {
9309 return false;
9310 }
9311
9312 #define CHECK(c) \
9313 if (!(c)) return false; \
9314 break
9315
9316 while (true) {
9317 if (!mirGen().ensureBallast()) {
9318 return false;
9319 }
9320
9321 OpBytes op;
9322 if (!iter().readOp(&op)) {
9323 return false;
9324 }
9325
9326 switch (op.b0) {
9327 case uint16_t(Op::End):
9328 if (!emitEnd()) {
9329 return false;
9330 }
9331 if (iter().controlStackEmpty()) {
9332 return true;
9333 }
9334 break;
9335
9336 // Control opcodes
9337 case uint16_t(Op::Unreachable):
9338 CHECK(emitUnreachable());
9339 case uint16_t(Op::Nop):
9340 CHECK(iter().readNop());
9341 case uint16_t(Op::Block):
9342 CHECK(emitBlock());
9343 case uint16_t(Op::Loop):
9344 CHECK(emitLoop());
9345 case uint16_t(Op::If):
9346 CHECK(emitIf());
9347 case uint16_t(Op::Else):
9348 CHECK(emitElse());
9349 case uint16_t(Op::Try):
9350 CHECK(emitTry());
9351 case uint16_t(Op::Catch):
9352 CHECK(emitCatch());
9353 case uint16_t(Op::CatchAll):
9354 CHECK(emitCatchAll());
9355 case uint16_t(Op::Delegate):
9356 CHECK(emitDelegate());
9357 case uint16_t(Op::Throw):
9358 CHECK(emitThrow());
9359 case uint16_t(Op::Rethrow):
9360 CHECK(emitRethrow());
9361 case uint16_t(Op::ThrowRef):
9362 if (!codeMeta().exnrefEnabled()) {
9363 return iter().unrecognizedOpcode(&op);
9364 }
9365 CHECK(emitThrowRef());
9366 case uint16_t(Op::TryTable):
9367 if (!codeMeta().exnrefEnabled()) {
9368 return iter().unrecognizedOpcode(&op);
9369 }
9370 CHECK(emitTryTable());
9371 case uint16_t(Op::Br):
9372 CHECK(emitBr());
9373 case uint16_t(Op::BrIf):
9374 CHECK(emitBrIf());
9375 case uint16_t(Op::BrTable):
9376 CHECK(emitBrTable());
9377 case uint16_t(Op::Return):
9378 CHECK(emitReturn());
9379
9380 // Calls
9381 case uint16_t(Op::Call):
9382 CHECK(emitCall(/* asmJSFuncDef = */ false));
9383 case uint16_t(Op::CallIndirect):
9384 CHECK(emitCallIndirect(/* oldStyle = */ false));
9385
9386 // Parametric operators
9387 case uint16_t(Op::Drop):
9388 CHECK(iter().readDrop());
9389 case uint16_t(Op::SelectNumeric):
9390 CHECK(emitSelect(/*typed*/ false));
9391 case uint16_t(Op::SelectTyped):
9392 CHECK(emitSelect(/*typed*/ true));
9393
9394 // Locals and globals
9395 case uint16_t(Op::LocalGet):
9396 CHECK(emitGetLocal());
9397 case uint16_t(Op::LocalSet):
9398 CHECK(emitSetLocal());
9399 case uint16_t(Op::LocalTee):
9400 CHECK(emitTeeLocal());
9401 case uint16_t(Op::GlobalGet):
9402 CHECK(emitGetGlobal());
9403 case uint16_t(Op::GlobalSet):
9404 CHECK(emitSetGlobal());
9405 case uint16_t(Op::TableGet):
9406 CHECK(emitTableGet());
9407 case uint16_t(Op::TableSet):
9408 CHECK(emitTableSet());
9409
9410 // Memory-related operators
9411 case uint16_t(Op::I32Load):
9412 CHECK(emitLoad(ValType::I32, Scalar::Int32));
9413 case uint16_t(Op::I64Load):
9414 CHECK(emitLoad(ValType::I64, Scalar::Int64));
9415 case uint16_t(Op::F32Load):
9416 CHECK(emitLoad(ValType::F32, Scalar::Float32));
9417 case uint16_t(Op::F64Load):
9418 CHECK(emitLoad(ValType::F64, Scalar::Float64));
9419 case uint16_t(Op::I32Load8S):
9420 CHECK(emitLoad(ValType::I32, Scalar::Int8));
9421 case uint16_t(Op::I32Load8U):
9422 CHECK(emitLoad(ValType::I32, Scalar::Uint8));
9423 case uint16_t(Op::I32Load16S):
9424 CHECK(emitLoad(ValType::I32, Scalar::Int16));
9425 case uint16_t(Op::I32Load16U):
9426 CHECK(emitLoad(ValType::I32, Scalar::Uint16));
9427 case uint16_t(Op::I64Load8S):
9428 CHECK(emitLoad(ValType::I64, Scalar::Int8));
9429 case uint16_t(Op::I64Load8U):
9430 CHECK(emitLoad(ValType::I64, Scalar::Uint8));
9431 case uint16_t(Op::I64Load16S):
9432 CHECK(emitLoad(ValType::I64, Scalar::Int16));
9433 case uint16_t(Op::I64Load16U):
9434 CHECK(emitLoad(ValType::I64, Scalar::Uint16));
9435 case uint16_t(Op::I64Load32S):
9436 CHECK(emitLoad(ValType::I64, Scalar::Int32));
9437 case uint16_t(Op::I64Load32U):
9438 CHECK(emitLoad(ValType::I64, Scalar::Uint32));
9439 case uint16_t(Op::I32Store):
9440 CHECK(emitStore(ValType::I32, Scalar::Int32));
9441 case uint16_t(Op::I64Store):
9442 CHECK(emitStore(ValType::I64, Scalar::Int64));
9443 case uint16_t(Op::F32Store):
9444 CHECK(emitStore(ValType::F32, Scalar::Float32));
9445 case uint16_t(Op::F64Store):
9446 CHECK(emitStore(ValType::F64, Scalar::Float64));
9447 case uint16_t(Op::I32Store8):
9448 CHECK(emitStore(ValType::I32, Scalar::Int8));
9449 case uint16_t(Op::I32Store16):
9450 CHECK(emitStore(ValType::I32, Scalar::Int16));
9451 case uint16_t(Op::I64Store8):
9452 CHECK(emitStore(ValType::I64, Scalar::Int8));
9453 case uint16_t(Op::I64Store16):
9454 CHECK(emitStore(ValType::I64, Scalar::Int16));
9455 case uint16_t(Op::I64Store32):
9456 CHECK(emitStore(ValType::I64, Scalar::Int32));
9457 case uint16_t(Op::MemorySize):
9458 CHECK(emitMemorySize());
9459 case uint16_t(Op::MemoryGrow):
9460 CHECK(emitMemoryGrow());
9461
9462 // Constants
9463 case uint16_t(Op::I32Const):
9464 CHECK(emitI32Const());
9465 case uint16_t(Op::I64Const):
9466 CHECK(emitI64Const());
9467 case uint16_t(Op::F32Const):
9468 CHECK(emitF32Const());
9469 case uint16_t(Op::F64Const):
9470 CHECK(emitF64Const());
9471
9472 // Comparison operators
9473 case uint16_t(Op::I32Eqz):
9474 CHECK(emitConversion<MNot>(ValType::I32, ValType::I32));
9475 case uint16_t(Op::I32Eq):
9476 CHECK(emitComparison(ValType::I32, JSOp::Eq, MCompare::Compare_Int32));
9477 case uint16_t(Op::I32Ne):
9478 CHECK(emitComparison(ValType::I32, JSOp::Ne, MCompare::Compare_Int32));
9479 case uint16_t(Op::I32LtS):
9480 CHECK(emitComparison(ValType::I32, JSOp::Lt, MCompare::Compare_Int32));
9481 case uint16_t(Op::I32LtU):
9482 CHECK(emitComparison(ValType::I32, JSOp::Lt, MCompare::Compare_UInt32));
9483 case uint16_t(Op::I32GtS):
9484 CHECK(emitComparison(ValType::I32, JSOp::Gt, MCompare::Compare_Int32));
9485 case uint16_t(Op::I32GtU):
9486 CHECK(emitComparison(ValType::I32, JSOp::Gt, MCompare::Compare_UInt32));
9487 case uint16_t(Op::I32LeS):
9488 CHECK(emitComparison(ValType::I32, JSOp::Le, MCompare::Compare_Int32));
9489 case uint16_t(Op::I32LeU):
9490 CHECK(emitComparison(ValType::I32, JSOp::Le, MCompare::Compare_UInt32));
9491 case uint16_t(Op::I32GeS):
9492 CHECK(emitComparison(ValType::I32, JSOp::Ge, MCompare::Compare_Int32));
9493 case uint16_t(Op::I32GeU):
9494 CHECK(emitComparison(ValType::I32, JSOp::Ge, MCompare::Compare_UInt32));
9495 case uint16_t(Op::I64Eqz):
9496 CHECK(emitConversion<MNot>(ValType::I64, ValType::I32));
9497 case uint16_t(Op::I64Eq):
9498 CHECK(emitComparison(ValType::I64, JSOp::Eq, MCompare::Compare_Int64));
9499 case uint16_t(Op::I64Ne):
9500 CHECK(emitComparison(ValType::I64, JSOp::Ne, MCompare::Compare_Int64));
9501 case uint16_t(Op::I64LtS):
9502 CHECK(emitComparison(ValType::I64, JSOp::Lt, MCompare::Compare_Int64));
9503 case uint16_t(Op::I64LtU):
9504 CHECK(emitComparison(ValType::I64, JSOp::Lt, MCompare::Compare_UInt64));
9505 case uint16_t(Op::I64GtS):
9506 CHECK(emitComparison(ValType::I64, JSOp::Gt, MCompare::Compare_Int64));
9507 case uint16_t(Op::I64GtU):
9508 CHECK(emitComparison(ValType::I64, JSOp::Gt, MCompare::Compare_UInt64));
9509 case uint16_t(Op::I64LeS):
9510 CHECK(emitComparison(ValType::I64, JSOp::Le, MCompare::Compare_Int64));
9511 case uint16_t(Op::I64LeU):
9512 CHECK(emitComparison(ValType::I64, JSOp::Le, MCompare::Compare_UInt64));
9513 case uint16_t(Op::I64GeS):
9514 CHECK(emitComparison(ValType::I64, JSOp::Ge, MCompare::Compare_Int64));
9515 case uint16_t(Op::I64GeU):
9516 CHECK(emitComparison(ValType::I64, JSOp::Ge, MCompare::Compare_UInt64));
9517 case uint16_t(Op::F32Eq):
9518 CHECK(
9519 emitComparison(ValType::F32, JSOp::Eq, MCompare::Compare_Float32));
9520 case uint16_t(Op::F32Ne):
9521 CHECK(
9522 emitComparison(ValType::F32, JSOp::Ne, MCompare::Compare_Float32));
9523 case uint16_t(Op::F32Lt):
9524 CHECK(
9525 emitComparison(ValType::F32, JSOp::Lt, MCompare::Compare_Float32));
9526 case uint16_t(Op::F32Gt):
9527 CHECK(
9528 emitComparison(ValType::F32, JSOp::Gt, MCompare::Compare_Float32));
9529 case uint16_t(Op::F32Le):
9530 CHECK(
9531 emitComparison(ValType::F32, JSOp::Le, MCompare::Compare_Float32));
9532 case uint16_t(Op::F32Ge):
9533 CHECK(
9534 emitComparison(ValType::F32, JSOp::Ge, MCompare::Compare_Float32));
9535 case uint16_t(Op::F64Eq):
9536 CHECK(emitComparison(ValType::F64, JSOp::Eq, MCompare::Compare_Double));
9537 case uint16_t(Op::F64Ne):
9538 CHECK(emitComparison(ValType::F64, JSOp::Ne, MCompare::Compare_Double));
9539 case uint16_t(Op::F64Lt):
9540 CHECK(emitComparison(ValType::F64, JSOp::Lt, MCompare::Compare_Double));
9541 case uint16_t(Op::F64Gt):
9542 CHECK(emitComparison(ValType::F64, JSOp::Gt, MCompare::Compare_Double));
9543 case uint16_t(Op::F64Le):
9544 CHECK(emitComparison(ValType::F64, JSOp::Le, MCompare::Compare_Double));
9545 case uint16_t(Op::F64Ge):
9546 CHECK(emitComparison(ValType::F64, JSOp::Ge, MCompare::Compare_Double));
9547
9548 // Numeric operators
9549 case uint16_t(Op::I32Clz):
9550 CHECK(emitUnaryWithType<MClz>(ValType::I32, MIRType::Int32));
9551 case uint16_t(Op::I32Ctz):
9552 CHECK(emitUnaryWithType<MCtz>(ValType::I32, MIRType::Int32));
9553 case uint16_t(Op::I32Popcnt):
9554 CHECK(emitUnaryWithType<MPopcnt>(ValType::I32, MIRType::Int32));
9555 case uint16_t(Op::I32Add):
9556 CHECK(emitAdd(ValType::I32, MIRType::Int32));
9557 case uint16_t(Op::I32Sub):
9558 CHECK(emitSub(ValType::I32, MIRType::Int32));
9559 case uint16_t(Op::I32Mul):
9560 CHECK(emitMul(ValType::I32, MIRType::Int32));
9561 case uint16_t(Op::I32DivS):
9562 case uint16_t(Op::I32DivU):
9563 CHECK(emitDiv(ValType::I32, MIRType::Int32, Op(op.b0) == Op::I32DivU));
9564 case uint16_t(Op::I32RemS):
9565 case uint16_t(Op::I32RemU):
9566 CHECK(emitRem(ValType::I32, MIRType::Int32, Op(op.b0) == Op::I32RemU));
9567 case uint16_t(Op::I32And):
9568 CHECK(emitBitwiseAndOrXor(ValType::I32, MIRType::Int32,
9569 MWasmBinaryBitwise::SubOpcode::And));
9570 case uint16_t(Op::I32Or):
9571 CHECK(emitBitwiseAndOrXor(ValType::I32, MIRType::Int32,
9572 MWasmBinaryBitwise::SubOpcode::Or));
9573 case uint16_t(Op::I32Xor):
9574 CHECK(emitBitwiseAndOrXor(ValType::I32, MIRType::Int32,
9575 MWasmBinaryBitwise::SubOpcode::Xor));
9576 case uint16_t(Op::I32Shl):
9577 CHECK(emitShift<MLsh>(ValType::I32, MIRType::Int32));
9578 case uint16_t(Op::I32ShrS):
9579 CHECK(emitShift<MRsh>(ValType::I32, MIRType::Int32));
9580 case uint16_t(Op::I32ShrU):
9581 CHECK(emitUrsh(ValType::I32, MIRType::Int32));
9582 case uint16_t(Op::I32Rotl):
9583 case uint16_t(Op::I32Rotr):
9584 CHECK(emitRotate(ValType::I32, Op(op.b0) == Op::I32Rotl));
9585 case uint16_t(Op::I64Clz):
9586 CHECK(emitUnaryWithType<MClz>(ValType::I64, MIRType::Int64));
9587 case uint16_t(Op::I64Ctz):
9588 CHECK(emitUnaryWithType<MCtz>(ValType::I64, MIRType::Int64));
9589 case uint16_t(Op::I64Popcnt):
9590 CHECK(emitUnaryWithType<MPopcnt>(ValType::I64, MIRType::Int64));
9591 case uint16_t(Op::I64Add):
9592 CHECK(emitAdd(ValType::I64, MIRType::Int64));
9593 case uint16_t(Op::I64Sub):
9594 CHECK(emitSub(ValType::I64, MIRType::Int64));
9595 case uint16_t(Op::I64Mul):
9596 CHECK(emitMul(ValType::I64, MIRType::Int64));
9597 case uint16_t(Op::I64DivS):
9598 case uint16_t(Op::I64DivU):
9599 CHECK(emitDiv(ValType::I64, MIRType::Int64, Op(op.b0) == Op::I64DivU));
9600 case uint16_t(Op::I64RemS):
9601 case uint16_t(Op::I64RemU):
9602 CHECK(emitRem(ValType::I64, MIRType::Int64, Op(op.b0) == Op::I64RemU));
9603 case uint16_t(Op::I64And):
9604 CHECK(emitBitwiseAndOrXor(ValType::I64, MIRType::Int64,
9605 MWasmBinaryBitwise::SubOpcode::And));
9606 case uint16_t(Op::I64Or):
9607 CHECK(emitBitwiseAndOrXor(ValType::I64, MIRType::Int64,
9608 MWasmBinaryBitwise::SubOpcode::Or));
9609 case uint16_t(Op::I64Xor):
9610 CHECK(emitBitwiseAndOrXor(ValType::I64, MIRType::Int64,
9611 MWasmBinaryBitwise::SubOpcode::Xor));
9612 case uint16_t(Op::I64Shl):
9613 CHECK(emitShift<MLsh>(ValType::I64, MIRType::Int64));
9614 case uint16_t(Op::I64ShrS):
9615 CHECK(emitShift<MRsh>(ValType::I64, MIRType::Int64));
9616 case uint16_t(Op::I64ShrU):
9617 CHECK(emitUrsh(ValType::I64, MIRType::Int64));
9618 case uint16_t(Op::I64Rotl):
9619 case uint16_t(Op::I64Rotr):
9620 CHECK(emitRotate(ValType::I64, Op(op.b0) == Op::I64Rotl));
9621 case uint16_t(Op::F32Abs):
9622 CHECK(emitUnaryWithType<MAbs>(ValType::F32, MIRType::Float32));
9623 case uint16_t(Op::F32Neg):
9624 CHECK(emitUnaryWithType<MWasmNeg>(ValType::F32, MIRType::Float32));
9625 case uint16_t(Op::F32Ceil):
9626 CHECK(emitUnaryMathBuiltinCall(SASigCeilF));
9627 case uint16_t(Op::F32Floor):
9628 CHECK(emitUnaryMathBuiltinCall(SASigFloorF));
9629 case uint16_t(Op::F32Trunc):
9630 CHECK(emitUnaryMathBuiltinCall(SASigTruncF));
9631 case uint16_t(Op::F32Nearest):
9632 CHECK(emitUnaryMathBuiltinCall(SASigNearbyIntF));
9633 case uint16_t(Op::F32Sqrt):
9634 CHECK(emitUnaryWithType<MSqrt>(ValType::F32, MIRType::Float32));
9635 case uint16_t(Op::F32Add):
9636 CHECK(emitAdd(ValType::F32, MIRType::Float32));
9637 case uint16_t(Op::F32Sub):
9638 CHECK(emitSub(ValType::F32, MIRType::Float32));
9639 case uint16_t(Op::F32Mul):
9640 CHECK(emitMul(ValType::F32, MIRType::Float32));
9641 case uint16_t(Op::F32Div):
9642 CHECK(emitDiv(ValType::F32, MIRType::Float32,
9643 /* isUnsigned = */ false));
9644 case uint16_t(Op::F32Min):
9645 case uint16_t(Op::F32Max):
9646 CHECK(emitMinMax(ValType::F32, MIRType::Float32,
9647 Op(op.b0) == Op::F32Max));
9648 case uint16_t(Op::F32CopySign):
9649 CHECK(emitCopySign(ValType::F32));
9650 case uint16_t(Op::F64Abs):
9651 CHECK(emitUnaryWithType<MAbs>(ValType::F64, MIRType::Double));
9652 case uint16_t(Op::F64Neg):
9653 CHECK(emitUnaryWithType<MWasmNeg>(ValType::F64, MIRType::Double));
9654 case uint16_t(Op::F64Ceil):
9655 CHECK(emitUnaryMathBuiltinCall(SASigCeilD));
9656 case uint16_t(Op::F64Floor):
9657 CHECK(emitUnaryMathBuiltinCall(SASigFloorD));
9658 case uint16_t(Op::F64Trunc):
9659 CHECK(emitUnaryMathBuiltinCall(SASigTruncD));
9660 case uint16_t(Op::F64Nearest):
9661 CHECK(emitUnaryMathBuiltinCall(SASigNearbyIntD));
9662 case uint16_t(Op::F64Sqrt):
9663 CHECK(emitUnaryWithType<MSqrt>(ValType::F64, MIRType::Double));
9664 case uint16_t(Op::F64Add):
9665 CHECK(emitAdd(ValType::F64, MIRType::Double));
9666 case uint16_t(Op::F64Sub):
9667 CHECK(emitSub(ValType::F64, MIRType::Double));
9668 case uint16_t(Op::F64Mul):
9669 CHECK(emitMul(ValType::F64, MIRType::Double));
9670 case uint16_t(Op::F64Div):
9671 CHECK(emitDiv(ValType::F64, MIRType::Double,
9672 /* isUnsigned = */ false));
9673 case uint16_t(Op::F64Min):
9674 case uint16_t(Op::F64Max):
9675 CHECK(
9676 emitMinMax(ValType::F64, MIRType::Double, Op(op.b0) == Op::F64Max));
9677 case uint16_t(Op::F64CopySign):
9678 CHECK(emitCopySign(ValType::F64));
9679
9680 // Conversions
9681 case uint16_t(Op::I32WrapI64):
9682 CHECK(emitConversion<MWrapInt64ToInt32>(ValType::I64, ValType::I32));
9683 case uint16_t(Op::I32TruncF32S):
9684 case uint16_t(Op::I32TruncF32U):
9685 CHECK(emitTruncate(ValType::F32, ValType::I32,
9686 Op(op.b0) == Op::I32TruncF32U, false));
9687 case uint16_t(Op::I32TruncF64S):
9688 case uint16_t(Op::I32TruncF64U):
9689 CHECK(emitTruncate(ValType::F64, ValType::I32,
9690 Op(op.b0) == Op::I32TruncF64U, false));
9691 case uint16_t(Op::I64ExtendI32S):
9692 case uint16_t(Op::I64ExtendI32U):
9693 CHECK(emitExtendI32(Op(op.b0) == Op::I64ExtendI32U));
9694 case uint16_t(Op::I64TruncF32S):
9695 case uint16_t(Op::I64TruncF32U):
9696 CHECK(emitTruncate(ValType::F32, ValType::I64,
9697 Op(op.b0) == Op::I64TruncF32U, false));
9698 case uint16_t(Op::I64TruncF64S):
9699 case uint16_t(Op::I64TruncF64U):
9700 CHECK(emitTruncate(ValType::F64, ValType::I64,
9701 Op(op.b0) == Op::I64TruncF64U, false));
9702 case uint16_t(Op::F32ConvertI32S):
9703 CHECK(emitConversion<MToFloat32>(ValType::I32, ValType::F32));
9704 case uint16_t(Op::F32ConvertI32U):
9705 CHECK(
9706 emitConversion<MWasmUnsignedToFloat32>(ValType::I32, ValType::F32));
9707 case uint16_t(Op::F32ConvertI64S):
9708 case uint16_t(Op::F32ConvertI64U):
9709 CHECK(emitConvertI64ToFloatingPoint(ValType::F32, MIRType::Float32,
9710 Op(op.b0) == Op::F32ConvertI64U));
9711 case uint16_t(Op::F32DemoteF64):
9712 CHECK(emitConversion<MToFloat32>(ValType::F64, ValType::F32));
9713 case uint16_t(Op::F64ConvertI32S):
9714 CHECK(emitConversion<MToDouble>(ValType::I32, ValType::F64));
9715 case uint16_t(Op::F64ConvertI32U):
9716 CHECK(
9717 emitConversion<MWasmUnsignedToDouble>(ValType::I32, ValType::F64));
9718 case uint16_t(Op::F64ConvertI64S):
9719 case uint16_t(Op::F64ConvertI64U):
9720 CHECK(emitConvertI64ToFloatingPoint(ValType::F64, MIRType::Double,
9721 Op(op.b0) == Op::F64ConvertI64U));
9722 case uint16_t(Op::F64PromoteF32):
9723 CHECK(emitConversion<MToDouble>(ValType::F32, ValType::F64));
9724
9725 // Reinterpretations
9726 case uint16_t(Op::I32ReinterpretF32):
9727 CHECK(emitReinterpret(ValType::I32, ValType::F32, MIRType::Int32));
9728 case uint16_t(Op::I64ReinterpretF64):
9729 CHECK(emitReinterpret(ValType::I64, ValType::F64, MIRType::Int64));
9730 case uint16_t(Op::F32ReinterpretI32):
9731 CHECK(emitReinterpret(ValType::F32, ValType::I32, MIRType::Float32));
9732 case uint16_t(Op::F64ReinterpretI64):
9733 CHECK(emitReinterpret(ValType::F64, ValType::I64, MIRType::Double));
9734
9735 case uint16_t(Op::RefEq):
9736 CHECK(emitComparison(RefType::eq(), JSOp::Eq,
9737 MCompare::Compare_WasmAnyRef));
9738 case uint16_t(Op::RefFunc):
9739 CHECK(emitRefFunc());
9740 case uint16_t(Op::RefNull):
9741 CHECK(emitRefNull());
9742 case uint16_t(Op::RefIsNull):
9743 CHECK(emitRefIsNull());
9744
9745 // Sign extensions
9746 case uint16_t(Op::I32Extend8S):
9747 CHECK(emitSignExtend(1, 4));
9748 case uint16_t(Op::I32Extend16S):
9749 CHECK(emitSignExtend(2, 4));
9750 case uint16_t(Op::I64Extend8S):
9751 CHECK(emitSignExtend(1, 8));
9752 case uint16_t(Op::I64Extend16S):
9753 CHECK(emitSignExtend(2, 8));
9754 case uint16_t(Op::I64Extend32S):
9755 CHECK(emitSignExtend(4, 8));
9756
9757 case uint16_t(Op::ReturnCall): {
9758 CHECK(emitReturnCall());
9759 }
9760 case uint16_t(Op::ReturnCallIndirect): {
9761 CHECK(emitReturnCallIndirect());
9762 }
9763
9764 case uint16_t(Op::RefAsNonNull):
9765 CHECK(emitRefAsNonNull());
9766 case uint16_t(Op::BrOnNull): {
9767 CHECK(emitBrOnNull());
9768 }
9769 case uint16_t(Op::BrOnNonNull): {
9770 CHECK(emitBrOnNonNull());
9771 }
9772 case uint16_t(Op::CallRef): {
9773 CHECK(emitCallRef());
9774 }
9775
9776 case uint16_t(Op::ReturnCallRef): {
9777 CHECK(emitReturnCallRef());
9778 }
9779
9780 // Gc operations
9781 case uint16_t(Op::GcPrefix): {
9782 switch (op.b1) {
9783 case uint32_t(GcOp::StructNew):
9784 CHECK(emitStructNew());
9785 case uint32_t(GcOp::StructNewDefault):
9786 CHECK(emitStructNewDefault());
9787 case uint32_t(GcOp::StructSet):
9788 CHECK(emitStructSet());
9789 case uint32_t(GcOp::StructGet):
9790 CHECK(emitStructGet(FieldWideningOp::None));
9791 case uint32_t(GcOp::StructGetS):
9792 CHECK(emitStructGet(FieldWideningOp::Signed));
9793 case uint32_t(GcOp::StructGetU):
9794 CHECK(emitStructGet(FieldWideningOp::Unsigned));
9795 case uint32_t(GcOp::ArrayNew):
9796 CHECK(emitArrayNew());
9797 case uint32_t(GcOp::ArrayNewDefault):
9798 CHECK(emitArrayNewDefault());
9799 case uint32_t(GcOp::ArrayNewFixed):
9800 CHECK(emitArrayNewFixed());
9801 case uint32_t(GcOp::ArrayNewData):
9802 CHECK(emitArrayNewData());
9803 case uint32_t(GcOp::ArrayNewElem):
9804 CHECK(emitArrayNewElem());
9805 case uint32_t(GcOp::ArrayInitData):
9806 CHECK(emitArrayInitData());
9807 case uint32_t(GcOp::ArrayInitElem):
9808 CHECK(emitArrayInitElem());
9809 case uint32_t(GcOp::ArraySet):
9810 CHECK(emitArraySet());
9811 case uint32_t(GcOp::ArrayGet):
9812 CHECK(emitArrayGet(FieldWideningOp::None));
9813 case uint32_t(GcOp::ArrayGetS):
9814 CHECK(emitArrayGet(FieldWideningOp::Signed));
9815 case uint32_t(GcOp::ArrayGetU):
9816 CHECK(emitArrayGet(FieldWideningOp::Unsigned));
9817 case uint32_t(GcOp::ArrayLen):
9818 CHECK(emitArrayLen());
9819 case uint32_t(GcOp::ArrayCopy):
9820 CHECK(emitArrayCopy());
9821 case uint32_t(GcOp::ArrayFill):
9822 CHECK(emitArrayFill());
9823 case uint32_t(GcOp::RefI31):
9824 CHECK(emitRefI31());
9825 case uint32_t(GcOp::I31GetS):
9826 CHECK(emitI31Get(FieldWideningOp::Signed));
9827 case uint32_t(GcOp::I31GetU):
9828 CHECK(emitI31Get(FieldWideningOp::Unsigned));
9829 case uint32_t(GcOp::BrOnCast):
9830 CHECK(emitBrOnCast(/*onSuccess=*/true));
9831 case uint32_t(GcOp::BrOnCastFail):
9832 CHECK(emitBrOnCast(/*onSuccess=*/false));
9833 case uint32_t(GcOp::RefTest):
9834 CHECK(emitRefTest(/*nullable=*/false));
9835 case uint32_t(GcOp::RefTestNull):
9836 CHECK(emitRefTest(/*nullable=*/true));
9837 case uint32_t(GcOp::RefCast):
9838 CHECK(emitRefCast(/*nullable=*/false));
9839 case uint32_t(GcOp::RefCastNull):
9840 CHECK(emitRefCast(/*nullable=*/true));
9841 case uint16_t(GcOp::AnyConvertExtern):
9842 CHECK(emitAnyConvertExtern());
9843 case uint16_t(GcOp::ExternConvertAny):
9844 CHECK(emitExternConvertAny());
9845 default:
9846 return iter().unrecognizedOpcode(&op);
9847 } // switch (op.b1)
9848 break;
9849 }
9850
9851 // SIMD operations
9852 #ifdef ENABLE_WASM_SIMD
9853 case uint16_t(Op::SimdPrefix): {
9854 if (!codeMeta().simdAvailable()) {
9855 return iter().unrecognizedOpcode(&op);
9856 }
9857 switch (op.b1) {
9858 case uint32_t(SimdOp::V128Const):
9859 CHECK(emitConstSimd128());
9860 case uint32_t(SimdOp::V128Load):
9861 CHECK(emitLoad(ValType::V128, Scalar::Simd128));
9862 case uint32_t(SimdOp::V128Store):
9863 CHECK(emitStore(ValType::V128, Scalar::Simd128));
9864 case uint32_t(SimdOp::V128And):
9865 case uint32_t(SimdOp::V128Or):
9866 case uint32_t(SimdOp::V128Xor):
9867 case uint32_t(SimdOp::I8x16AvgrU):
9868 case uint32_t(SimdOp::I16x8AvgrU):
9869 case uint32_t(SimdOp::I8x16Add):
9870 case uint32_t(SimdOp::I8x16AddSatS):
9871 case uint32_t(SimdOp::I8x16AddSatU):
9872 case uint32_t(SimdOp::I8x16MinS):
9873 case uint32_t(SimdOp::I8x16MinU):
9874 case uint32_t(SimdOp::I8x16MaxS):
9875 case uint32_t(SimdOp::I8x16MaxU):
9876 case uint32_t(SimdOp::I16x8Add):
9877 case uint32_t(SimdOp::I16x8AddSatS):
9878 case uint32_t(SimdOp::I16x8AddSatU):
9879 case uint32_t(SimdOp::I16x8Mul):
9880 case uint32_t(SimdOp::I16x8MinS):
9881 case uint32_t(SimdOp::I16x8MinU):
9882 case uint32_t(SimdOp::I16x8MaxS):
9883 case uint32_t(SimdOp::I16x8MaxU):
9884 case uint32_t(SimdOp::I32x4Add):
9885 case uint32_t(SimdOp::I32x4Mul):
9886 case uint32_t(SimdOp::I32x4MinS):
9887 case uint32_t(SimdOp::I32x4MinU):
9888 case uint32_t(SimdOp::I32x4MaxS):
9889 case uint32_t(SimdOp::I32x4MaxU):
9890 case uint32_t(SimdOp::I64x2Add):
9891 case uint32_t(SimdOp::I64x2Mul):
9892 case uint32_t(SimdOp::F32x4Add):
9893 case uint32_t(SimdOp::F32x4Mul):
9894 case uint32_t(SimdOp::F32x4Min):
9895 case uint32_t(SimdOp::F32x4Max):
9896 case uint32_t(SimdOp::F64x2Add):
9897 case uint32_t(SimdOp::F64x2Mul):
9898 case uint32_t(SimdOp::F64x2Min):
9899 case uint32_t(SimdOp::F64x2Max):
9900 case uint32_t(SimdOp::I8x16Eq):
9901 case uint32_t(SimdOp::I8x16Ne):
9902 case uint32_t(SimdOp::I16x8Eq):
9903 case uint32_t(SimdOp::I16x8Ne):
9904 case uint32_t(SimdOp::I32x4Eq):
9905 case uint32_t(SimdOp::I32x4Ne):
9906 case uint32_t(SimdOp::I64x2Eq):
9907 case uint32_t(SimdOp::I64x2Ne):
9908 case uint32_t(SimdOp::F32x4Eq):
9909 case uint32_t(SimdOp::F32x4Ne):
9910 case uint32_t(SimdOp::F64x2Eq):
9911 case uint32_t(SimdOp::F64x2Ne):
9912 case uint32_t(SimdOp::I32x4DotI16x8S):
9913 case uint32_t(SimdOp::I16x8ExtmulLowI8x16S):
9914 case uint32_t(SimdOp::I16x8ExtmulHighI8x16S):
9915 case uint32_t(SimdOp::I16x8ExtmulLowI8x16U):
9916 case uint32_t(SimdOp::I16x8ExtmulHighI8x16U):
9917 case uint32_t(SimdOp::I32x4ExtmulLowI16x8S):
9918 case uint32_t(SimdOp::I32x4ExtmulHighI16x8S):
9919 case uint32_t(SimdOp::I32x4ExtmulLowI16x8U):
9920 case uint32_t(SimdOp::I32x4ExtmulHighI16x8U):
9921 case uint32_t(SimdOp::I64x2ExtmulLowI32x4S):
9922 case uint32_t(SimdOp::I64x2ExtmulHighI32x4S):
9923 case uint32_t(SimdOp::I64x2ExtmulLowI32x4U):
9924 case uint32_t(SimdOp::I64x2ExtmulHighI32x4U):
9925 case uint32_t(SimdOp::I16x8Q15MulrSatS):
9926 CHECK(emitBinarySimd128(/* commutative= */ true, SimdOp(op.b1)));
9927 case uint32_t(SimdOp::V128AndNot):
9928 case uint32_t(SimdOp::I8x16Sub):
9929 case uint32_t(SimdOp::I8x16SubSatS):
9930 case uint32_t(SimdOp::I8x16SubSatU):
9931 case uint32_t(SimdOp::I16x8Sub):
9932 case uint32_t(SimdOp::I16x8SubSatS):
9933 case uint32_t(SimdOp::I16x8SubSatU):
9934 case uint32_t(SimdOp::I32x4Sub):
9935 case uint32_t(SimdOp::I64x2Sub):
9936 case uint32_t(SimdOp::F32x4Sub):
9937 case uint32_t(SimdOp::F32x4Div):
9938 case uint32_t(SimdOp::F64x2Sub):
9939 case uint32_t(SimdOp::F64x2Div):
9940 case uint32_t(SimdOp::I8x16NarrowI16x8S):
9941 case uint32_t(SimdOp::I8x16NarrowI16x8U):
9942 case uint32_t(SimdOp::I16x8NarrowI32x4S):
9943 case uint32_t(SimdOp::I16x8NarrowI32x4U):
9944 case uint32_t(SimdOp::I8x16LtS):
9945 case uint32_t(SimdOp::I8x16LtU):
9946 case uint32_t(SimdOp::I8x16GtS):
9947 case uint32_t(SimdOp::I8x16GtU):
9948 case uint32_t(SimdOp::I8x16LeS):
9949 case uint32_t(SimdOp::I8x16LeU):
9950 case uint32_t(SimdOp::I8x16GeS):
9951 case uint32_t(SimdOp::I8x16GeU):
9952 case uint32_t(SimdOp::I16x8LtS):
9953 case uint32_t(SimdOp::I16x8LtU):
9954 case uint32_t(SimdOp::I16x8GtS):
9955 case uint32_t(SimdOp::I16x8GtU):
9956 case uint32_t(SimdOp::I16x8LeS):
9957 case uint32_t(SimdOp::I16x8LeU):
9958 case uint32_t(SimdOp::I16x8GeS):
9959 case uint32_t(SimdOp::I16x8GeU):
9960 case uint32_t(SimdOp::I32x4LtS):
9961 case uint32_t(SimdOp::I32x4LtU):
9962 case uint32_t(SimdOp::I32x4GtS):
9963 case uint32_t(SimdOp::I32x4GtU):
9964 case uint32_t(SimdOp::I32x4LeS):
9965 case uint32_t(SimdOp::I32x4LeU):
9966 case uint32_t(SimdOp::I32x4GeS):
9967 case uint32_t(SimdOp::I32x4GeU):
9968 case uint32_t(SimdOp::I64x2LtS):
9969 case uint32_t(SimdOp::I64x2GtS):
9970 case uint32_t(SimdOp::I64x2LeS):
9971 case uint32_t(SimdOp::I64x2GeS):
9972 case uint32_t(SimdOp::F32x4Lt):
9973 case uint32_t(SimdOp::F32x4Gt):
9974 case uint32_t(SimdOp::F32x4Le):
9975 case uint32_t(SimdOp::F32x4Ge):
9976 case uint32_t(SimdOp::F64x2Lt):
9977 case uint32_t(SimdOp::F64x2Gt):
9978 case uint32_t(SimdOp::F64x2Le):
9979 case uint32_t(SimdOp::F64x2Ge):
9980 case uint32_t(SimdOp::I8x16Swizzle):
9981 case uint32_t(SimdOp::F32x4PMax):
9982 case uint32_t(SimdOp::F32x4PMin):
9983 case uint32_t(SimdOp::F64x2PMax):
9984 case uint32_t(SimdOp::F64x2PMin):
9985 CHECK(emitBinarySimd128(/* commutative= */ false, SimdOp(op.b1)));
9986 case uint32_t(SimdOp::I8x16Splat):
9987 case uint32_t(SimdOp::I16x8Splat):
9988 case uint32_t(SimdOp::I32x4Splat):
9989 CHECK(emitSplatSimd128(ValType::I32, SimdOp(op.b1)));
9990 case uint32_t(SimdOp::I64x2Splat):
9991 CHECK(emitSplatSimd128(ValType::I64, SimdOp(op.b1)));
9992 case uint32_t(SimdOp::F32x4Splat):
9993 CHECK(emitSplatSimd128(ValType::F32, SimdOp(op.b1)));
9994 case uint32_t(SimdOp::F64x2Splat):
9995 CHECK(emitSplatSimd128(ValType::F64, SimdOp(op.b1)));
9996 case uint32_t(SimdOp::I8x16Neg):
9997 case uint32_t(SimdOp::I16x8Neg):
9998 case uint32_t(SimdOp::I16x8ExtendLowI8x16S):
9999 case uint32_t(SimdOp::I16x8ExtendHighI8x16S):
10000 case uint32_t(SimdOp::I16x8ExtendLowI8x16U):
10001 case uint32_t(SimdOp::I16x8ExtendHighI8x16U):
10002 case uint32_t(SimdOp::I32x4Neg):
10003 case uint32_t(SimdOp::I32x4ExtendLowI16x8S):
10004 case uint32_t(SimdOp::I32x4ExtendHighI16x8S):
10005 case uint32_t(SimdOp::I32x4ExtendLowI16x8U):
10006 case uint32_t(SimdOp::I32x4ExtendHighI16x8U):
10007 case uint32_t(SimdOp::I32x4TruncSatF32x4S):
10008 case uint32_t(SimdOp::I32x4TruncSatF32x4U):
10009 case uint32_t(SimdOp::I64x2Neg):
10010 case uint32_t(SimdOp::I64x2ExtendLowI32x4S):
10011 case uint32_t(SimdOp::I64x2ExtendHighI32x4S):
10012 case uint32_t(SimdOp::I64x2ExtendLowI32x4U):
10013 case uint32_t(SimdOp::I64x2ExtendHighI32x4U):
10014 case uint32_t(SimdOp::F32x4Abs):
10015 case uint32_t(SimdOp::F32x4Neg):
10016 case uint32_t(SimdOp::F32x4Sqrt):
10017 case uint32_t(SimdOp::F32x4ConvertI32x4S):
10018 case uint32_t(SimdOp::F32x4ConvertI32x4U):
10019 case uint32_t(SimdOp::F64x2Abs):
10020 case uint32_t(SimdOp::F64x2Neg):
10021 case uint32_t(SimdOp::F64x2Sqrt):
10022 case uint32_t(SimdOp::V128Not):
10023 case uint32_t(SimdOp::I8x16Popcnt):
10024 case uint32_t(SimdOp::I8x16Abs):
10025 case uint32_t(SimdOp::I16x8Abs):
10026 case uint32_t(SimdOp::I32x4Abs):
10027 case uint32_t(SimdOp::I64x2Abs):
10028 case uint32_t(SimdOp::F32x4Ceil):
10029 case uint32_t(SimdOp::F32x4Floor):
10030 case uint32_t(SimdOp::F32x4Trunc):
10031 case uint32_t(SimdOp::F32x4Nearest):
10032 case uint32_t(SimdOp::F64x2Ceil):
10033 case uint32_t(SimdOp::F64x2Floor):
10034 case uint32_t(SimdOp::F64x2Trunc):
10035 case uint32_t(SimdOp::F64x2Nearest):
10036 case uint32_t(SimdOp::F32x4DemoteF64x2Zero):
10037 case uint32_t(SimdOp::F64x2PromoteLowF32x4):
10038 case uint32_t(SimdOp::F64x2ConvertLowI32x4S):
10039 case uint32_t(SimdOp::F64x2ConvertLowI32x4U):
10040 case uint32_t(SimdOp::I32x4TruncSatF64x2SZero):
10041 case uint32_t(SimdOp::I32x4TruncSatF64x2UZero):
10042 case uint32_t(SimdOp::I16x8ExtaddPairwiseI8x16S):
10043 case uint32_t(SimdOp::I16x8ExtaddPairwiseI8x16U):
10044 case uint32_t(SimdOp::I32x4ExtaddPairwiseI16x8S):
10045 case uint32_t(SimdOp::I32x4ExtaddPairwiseI16x8U):
10046 CHECK(emitUnarySimd128(SimdOp(op.b1)));
10047 case uint32_t(SimdOp::V128AnyTrue):
10048 case uint32_t(SimdOp::I8x16AllTrue):
10049 case uint32_t(SimdOp::I16x8AllTrue):
10050 case uint32_t(SimdOp::I32x4AllTrue):
10051 case uint32_t(SimdOp::I64x2AllTrue):
10052 case uint32_t(SimdOp::I8x16Bitmask):
10053 case uint32_t(SimdOp::I16x8Bitmask):
10054 case uint32_t(SimdOp::I32x4Bitmask):
10055 case uint32_t(SimdOp::I64x2Bitmask):
10056 CHECK(emitReduceSimd128(SimdOp(op.b1)));
10057 case uint32_t(SimdOp::I8x16Shl):
10058 case uint32_t(SimdOp::I8x16ShrS):
10059 case uint32_t(SimdOp::I8x16ShrU):
10060 case uint32_t(SimdOp::I16x8Shl):
10061 case uint32_t(SimdOp::I16x8ShrS):
10062 case uint32_t(SimdOp::I16x8ShrU):
10063 case uint32_t(SimdOp::I32x4Shl):
10064 case uint32_t(SimdOp::I32x4ShrS):
10065 case uint32_t(SimdOp::I32x4ShrU):
10066 case uint32_t(SimdOp::I64x2Shl):
10067 case uint32_t(SimdOp::I64x2ShrS):
10068 case uint32_t(SimdOp::I64x2ShrU):
10069 CHECK(emitShiftSimd128(SimdOp(op.b1)));
10070 case uint32_t(SimdOp::I8x16ExtractLaneS):
10071 case uint32_t(SimdOp::I8x16ExtractLaneU):
10072 CHECK(emitExtractLaneSimd128(ValType::I32, 16, SimdOp(op.b1)));
10073 case uint32_t(SimdOp::I16x8ExtractLaneS):
10074 case uint32_t(SimdOp::I16x8ExtractLaneU):
10075 CHECK(emitExtractLaneSimd128(ValType::I32, 8, SimdOp(op.b1)));
10076 case uint32_t(SimdOp::I32x4ExtractLane):
10077 CHECK(emitExtractLaneSimd128(ValType::I32, 4, SimdOp(op.b1)));
10078 case uint32_t(SimdOp::I64x2ExtractLane):
10079 CHECK(emitExtractLaneSimd128(ValType::I64, 2, SimdOp(op.b1)));
10080 case uint32_t(SimdOp::F32x4ExtractLane):
10081 CHECK(emitExtractLaneSimd128(ValType::F32, 4, SimdOp(op.b1)));
10082 case uint32_t(SimdOp::F64x2ExtractLane):
10083 CHECK(emitExtractLaneSimd128(ValType::F64, 2, SimdOp(op.b1)));
10084 case uint32_t(SimdOp::I8x16ReplaceLane):
10085 CHECK(emitReplaceLaneSimd128(ValType::I32, 16, SimdOp(op.b1)));
10086 case uint32_t(SimdOp::I16x8ReplaceLane):
10087 CHECK(emitReplaceLaneSimd128(ValType::I32, 8, SimdOp(op.b1)));
10088 case uint32_t(SimdOp::I32x4ReplaceLane):
10089 CHECK(emitReplaceLaneSimd128(ValType::I32, 4, SimdOp(op.b1)));
10090 case uint32_t(SimdOp::I64x2ReplaceLane):
10091 CHECK(emitReplaceLaneSimd128(ValType::I64, 2, SimdOp(op.b1)));
10092 case uint32_t(SimdOp::F32x4ReplaceLane):
10093 CHECK(emitReplaceLaneSimd128(ValType::F32, 4, SimdOp(op.b1)));
10094 case uint32_t(SimdOp::F64x2ReplaceLane):
10095 CHECK(emitReplaceLaneSimd128(ValType::F64, 2, SimdOp(op.b1)));
10096 case uint32_t(SimdOp::V128Bitselect):
10097 CHECK(emitTernarySimd128(SimdOp(op.b1)));
10098 case uint32_t(SimdOp::I8x16Shuffle):
10099 CHECK(emitShuffleSimd128());
10100 case uint32_t(SimdOp::V128Load8Splat):
10101 CHECK(emitLoadSplatSimd128(Scalar::Uint8, SimdOp::I8x16Splat));
10102 case uint32_t(SimdOp::V128Load16Splat):
10103 CHECK(emitLoadSplatSimd128(Scalar::Uint16, SimdOp::I16x8Splat));
10104 case uint32_t(SimdOp::V128Load32Splat):
10105 CHECK(emitLoadSplatSimd128(Scalar::Float32, SimdOp::I32x4Splat));
10106 case uint32_t(SimdOp::V128Load64Splat):
10107 CHECK(emitLoadSplatSimd128(Scalar::Float64, SimdOp::I64x2Splat));
10108 case uint32_t(SimdOp::V128Load8x8S):
10109 case uint32_t(SimdOp::V128Load8x8U):
10110 case uint32_t(SimdOp::V128Load16x4S):
10111 case uint32_t(SimdOp::V128Load16x4U):
10112 case uint32_t(SimdOp::V128Load32x2S):
10113 case uint32_t(SimdOp::V128Load32x2U):
10114 CHECK(emitLoadExtendSimd128(SimdOp(op.b1)));
10115 case uint32_t(SimdOp::V128Load32Zero):
10116 CHECK(emitLoadZeroSimd128(Scalar::Float32, 4));
10117 case uint32_t(SimdOp::V128Load64Zero):
10118 CHECK(emitLoadZeroSimd128(Scalar::Float64, 8));
10119 case uint32_t(SimdOp::V128Load8Lane):
10120 CHECK(emitLoadLaneSimd128(1));
10121 case uint32_t(SimdOp::V128Load16Lane):
10122 CHECK(emitLoadLaneSimd128(2));
10123 case uint32_t(SimdOp::V128Load32Lane):
10124 CHECK(emitLoadLaneSimd128(4));
10125 case uint32_t(SimdOp::V128Load64Lane):
10126 CHECK(emitLoadLaneSimd128(8));
10127 case uint32_t(SimdOp::V128Store8Lane):
10128 CHECK(emitStoreLaneSimd128(1));
10129 case uint32_t(SimdOp::V128Store16Lane):
10130 CHECK(emitStoreLaneSimd128(2));
10131 case uint32_t(SimdOp::V128Store32Lane):
10132 CHECK(emitStoreLaneSimd128(4));
10133 case uint32_t(SimdOp::V128Store64Lane):
10134 CHECK(emitStoreLaneSimd128(8));
10135 # ifdef ENABLE_WASM_RELAXED_SIMD
10136 case uint32_t(SimdOp::F32x4RelaxedMadd):
10137 case uint32_t(SimdOp::F32x4RelaxedNmadd):
10138 case uint32_t(SimdOp::F64x2RelaxedMadd):
10139 case uint32_t(SimdOp::F64x2RelaxedNmadd):
10140 case uint32_t(SimdOp::I8x16RelaxedLaneSelect):
10141 case uint32_t(SimdOp::I16x8RelaxedLaneSelect):
10142 case uint32_t(SimdOp::I32x4RelaxedLaneSelect):
10143 case uint32_t(SimdOp::I64x2RelaxedLaneSelect):
10144 case uint32_t(SimdOp::I32x4RelaxedDotI8x16I7x16AddS): {
10145 if (!codeMeta().v128RelaxedEnabled()) {
10146 return iter().unrecognizedOpcode(&op);
10147 }
10148 CHECK(emitTernarySimd128(SimdOp(op.b1)));
10149 }
10150 case uint32_t(SimdOp::F32x4RelaxedMin):
10151 case uint32_t(SimdOp::F32x4RelaxedMax):
10152 case uint32_t(SimdOp::F64x2RelaxedMin):
10153 case uint32_t(SimdOp::F64x2RelaxedMax): {
10154 if (!codeMeta().v128RelaxedEnabled()) {
10155 return iter().unrecognizedOpcode(&op);
10156 }
10157 // These aren't really commutative, because at least on Intel, the
10158 // behaviour in the presence of NaNs depends on the order of the
10159 // operands. And we need to have that ordering fixed, so that we
10160 // can produce the same results as baseline. See bug 1946618.
10161 CHECK(emitBinarySimd128(/* commutative= */ false, SimdOp(op.b1)));
10162 }
10163 case uint32_t(SimdOp::I16x8RelaxedQ15MulrS): {
10164 if (!codeMeta().v128RelaxedEnabled()) {
10165 return iter().unrecognizedOpcode(&op);
10166 }
10167 CHECK(emitBinarySimd128(/* commutative= */ true, SimdOp(op.b1)));
10168 }
10169 case uint32_t(SimdOp::I32x4RelaxedTruncF32x4S):
10170 case uint32_t(SimdOp::I32x4RelaxedTruncF32x4U):
10171 case uint32_t(SimdOp::I32x4RelaxedTruncF64x2SZero):
10172 case uint32_t(SimdOp::I32x4RelaxedTruncF64x2UZero): {
10173 if (!codeMeta().v128RelaxedEnabled()) {
10174 return iter().unrecognizedOpcode(&op);
10175 }
10176 CHECK(emitUnarySimd128(SimdOp(op.b1)));
10177 }
10178 case uint32_t(SimdOp::I8x16RelaxedSwizzle):
10179 case uint32_t(SimdOp::I16x8RelaxedDotI8x16I7x16S): {
10180 if (!codeMeta().v128RelaxedEnabled()) {
10181 return iter().unrecognizedOpcode(&op);
10182 }
10183 CHECK(emitBinarySimd128(/* commutative= */ false, SimdOp(op.b1)));
10184 }
10185 # endif
10186
10187 default:
10188 return iter().unrecognizedOpcode(&op);
10189 } // switch (op.b1)
10190 break;
10191 }
10192 #endif
10193
10194 // Miscellaneous operations
10195 case uint16_t(Op::MiscPrefix): {
10196 switch (op.b1) {
10197 case uint32_t(MiscOp::I32TruncSatF32S):
10198 case uint32_t(MiscOp::I32TruncSatF32U):
10199 CHECK(emitTruncate(ValType::F32, ValType::I32,
10200 MiscOp(op.b1) == MiscOp::I32TruncSatF32U, true));
10201 case uint32_t(MiscOp::I32TruncSatF64S):
10202 case uint32_t(MiscOp::I32TruncSatF64U):
10203 CHECK(emitTruncate(ValType::F64, ValType::I32,
10204 MiscOp(op.b1) == MiscOp::I32TruncSatF64U, true));
10205 case uint32_t(MiscOp::I64TruncSatF32S):
10206 case uint32_t(MiscOp::I64TruncSatF32U):
10207 CHECK(emitTruncate(ValType::F32, ValType::I64,
10208 MiscOp(op.b1) == MiscOp::I64TruncSatF32U, true));
10209 case uint32_t(MiscOp::I64TruncSatF64S):
10210 case uint32_t(MiscOp::I64TruncSatF64U):
10211 CHECK(emitTruncate(ValType::F64, ValType::I64,
10212 MiscOp(op.b1) == MiscOp::I64TruncSatF64U, true));
10213 case uint32_t(MiscOp::MemoryCopy):
10214 CHECK(emitMemCopy());
10215 case uint32_t(MiscOp::DataDrop):
10216 CHECK(emitDataOrElemDrop(/*isData=*/true));
10217 case uint32_t(MiscOp::MemoryFill):
10218 CHECK(emitMemFill());
10219 case uint32_t(MiscOp::MemoryInit):
10220 CHECK(emitMemInit());
10221 case uint32_t(MiscOp::TableCopy):
10222 CHECK(emitTableCopy());
10223 case uint32_t(MiscOp::ElemDrop):
10224 CHECK(emitDataOrElemDrop(/*isData=*/false));
10225 case uint32_t(MiscOp::TableInit):
10226 CHECK(emitTableInit());
10227 case uint32_t(MiscOp::TableFill):
10228 CHECK(emitTableFill());
10229 #if ENABLE_WASM_MEMORY_CONTROL
10230 case uint32_t(MiscOp::MemoryDiscard): {
10231 if (!codeMeta().memoryControlEnabled()) {
10232 return iter().unrecognizedOpcode(&op);
10233 }
10234 CHECK(emitMemDiscard());
10235 }
10236 #endif
10237 case uint32_t(MiscOp::TableGrow):
10238 CHECK(emitTableGrow());
10239 case uint32_t(MiscOp::TableSize):
10240 CHECK(emitTableSize());
10241 default:
10242 return iter().unrecognizedOpcode(&op);
10243 }
10244 break;
10245 }
10246
10247 // Thread operations
10248 case uint16_t(Op::ThreadPrefix): {
10249 // Though thread ops can be used on nonshared memories, we make them
10250 // unavailable if shared memory has been disabled in the prefs, for
10251 // maximum predictability and safety and consistency with JS.
10252 if (codeMeta().sharedMemoryEnabled() == Shareable::False) {
10253 return iter().unrecognizedOpcode(&op);
10254 }
10255 switch (op.b1) {
10256 case uint32_t(ThreadOp::Notify):
10257 CHECK(emitNotify());
10258
10259 case uint32_t(ThreadOp::I32Wait):
10260 CHECK(emitWait(ValType::I32, 4));
10261 case uint32_t(ThreadOp::I64Wait):
10262 CHECK(emitWait(ValType::I64, 8));
10263 case uint32_t(ThreadOp::Fence):
10264 CHECK(emitFence());
10265
10266 case uint32_t(ThreadOp::I32AtomicLoad):
10267 CHECK(emitAtomicLoad(ValType::I32, Scalar::Int32));
10268 case uint32_t(ThreadOp::I64AtomicLoad):
10269 CHECK(emitAtomicLoad(ValType::I64, Scalar::Int64));
10270 case uint32_t(ThreadOp::I32AtomicLoad8U):
10271 CHECK(emitAtomicLoad(ValType::I32, Scalar::Uint8));
10272 case uint32_t(ThreadOp::I32AtomicLoad16U):
10273 CHECK(emitAtomicLoad(ValType::I32, Scalar::Uint16));
10274 case uint32_t(ThreadOp::I64AtomicLoad8U):
10275 CHECK(emitAtomicLoad(ValType::I64, Scalar::Uint8));
10276 case uint32_t(ThreadOp::I64AtomicLoad16U):
10277 CHECK(emitAtomicLoad(ValType::I64, Scalar::Uint16));
10278 case uint32_t(ThreadOp::I64AtomicLoad32U):
10279 CHECK(emitAtomicLoad(ValType::I64, Scalar::Uint32));
10280
10281 case uint32_t(ThreadOp::I32AtomicStore):
10282 CHECK(emitAtomicStore(ValType::I32, Scalar::Int32));
10283 case uint32_t(ThreadOp::I64AtomicStore):
10284 CHECK(emitAtomicStore(ValType::I64, Scalar::Int64));
10285 case uint32_t(ThreadOp::I32AtomicStore8U):
10286 CHECK(emitAtomicStore(ValType::I32, Scalar::Uint8));
10287 case uint32_t(ThreadOp::I32AtomicStore16U):
10288 CHECK(emitAtomicStore(ValType::I32, Scalar::Uint16));
10289 case uint32_t(ThreadOp::I64AtomicStore8U):
10290 CHECK(emitAtomicStore(ValType::I64, Scalar::Uint8));
10291 case uint32_t(ThreadOp::I64AtomicStore16U):
10292 CHECK(emitAtomicStore(ValType::I64, Scalar::Uint16));
10293 case uint32_t(ThreadOp::I64AtomicStore32U):
10294 CHECK(emitAtomicStore(ValType::I64, Scalar::Uint32));
10295
10296 case uint32_t(ThreadOp::I32AtomicAdd):
10297 CHECK(emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Add));
10298 case uint32_t(ThreadOp::I64AtomicAdd):
10299 CHECK(emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Add));
10300 case uint32_t(ThreadOp::I32AtomicAdd8U):
10301 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Add));
10302 case uint32_t(ThreadOp::I32AtomicAdd16U):
10303 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Add));
10304 case uint32_t(ThreadOp::I64AtomicAdd8U):
10305 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Add));
10306 case uint32_t(ThreadOp::I64AtomicAdd16U):
10307 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Add));
10308 case uint32_t(ThreadOp::I64AtomicAdd32U):
10309 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Add));
10310
10311 case uint32_t(ThreadOp::I32AtomicSub):
10312 CHECK(emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Sub));
10313 case uint32_t(ThreadOp::I64AtomicSub):
10314 CHECK(emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Sub));
10315 case uint32_t(ThreadOp::I32AtomicSub8U):
10316 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Sub));
10317 case uint32_t(ThreadOp::I32AtomicSub16U):
10318 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Sub));
10319 case uint32_t(ThreadOp::I64AtomicSub8U):
10320 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Sub));
10321 case uint32_t(ThreadOp::I64AtomicSub16U):
10322 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Sub));
10323 case uint32_t(ThreadOp::I64AtomicSub32U):
10324 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Sub));
10325
10326 case uint32_t(ThreadOp::I32AtomicAnd):
10327 CHECK(emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::And));
10328 case uint32_t(ThreadOp::I64AtomicAnd):
10329 CHECK(emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::And));
10330 case uint32_t(ThreadOp::I32AtomicAnd8U):
10331 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::And));
10332 case uint32_t(ThreadOp::I32AtomicAnd16U):
10333 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::And));
10334 case uint32_t(ThreadOp::I64AtomicAnd8U):
10335 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::And));
10336 case uint32_t(ThreadOp::I64AtomicAnd16U):
10337 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::And));
10338 case uint32_t(ThreadOp::I64AtomicAnd32U):
10339 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::And));
10340
10341 case uint32_t(ThreadOp::I32AtomicOr):
10342 CHECK(emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Or));
10343 case uint32_t(ThreadOp::I64AtomicOr):
10344 CHECK(emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Or));
10345 case uint32_t(ThreadOp::I32AtomicOr8U):
10346 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Or));
10347 case uint32_t(ThreadOp::I32AtomicOr16U):
10348 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Or));
10349 case uint32_t(ThreadOp::I64AtomicOr8U):
10350 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Or));
10351 case uint32_t(ThreadOp::I64AtomicOr16U):
10352 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Or));
10353 case uint32_t(ThreadOp::I64AtomicOr32U):
10354 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Or));
10355
10356 case uint32_t(ThreadOp::I32AtomicXor):
10357 CHECK(emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Xor));
10358 case uint32_t(ThreadOp::I64AtomicXor):
10359 CHECK(emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Xor));
10360 case uint32_t(ThreadOp::I32AtomicXor8U):
10361 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Xor));
10362 case uint32_t(ThreadOp::I32AtomicXor16U):
10363 CHECK(emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Xor));
10364 case uint32_t(ThreadOp::I64AtomicXor8U):
10365 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Xor));
10366 case uint32_t(ThreadOp::I64AtomicXor16U):
10367 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Xor));
10368 case uint32_t(ThreadOp::I64AtomicXor32U):
10369 CHECK(emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Xor));
10370
10371 case uint32_t(ThreadOp::I32AtomicXchg):
10372 CHECK(emitAtomicXchg(ValType::I32, Scalar::Int32));
10373 case uint32_t(ThreadOp::I64AtomicXchg):
10374 CHECK(emitAtomicXchg(ValType::I64, Scalar::Int64));
10375 case uint32_t(ThreadOp::I32AtomicXchg8U):
10376 CHECK(emitAtomicXchg(ValType::I32, Scalar::Uint8));
10377 case uint32_t(ThreadOp::I32AtomicXchg16U):
10378 CHECK(emitAtomicXchg(ValType::I32, Scalar::Uint16));
10379 case uint32_t(ThreadOp::I64AtomicXchg8U):
10380 CHECK(emitAtomicXchg(ValType::I64, Scalar::Uint8));
10381 case uint32_t(ThreadOp::I64AtomicXchg16U):
10382 CHECK(emitAtomicXchg(ValType::I64, Scalar::Uint16));
10383 case uint32_t(ThreadOp::I64AtomicXchg32U):
10384 CHECK(emitAtomicXchg(ValType::I64, Scalar::Uint32));
10385
10386 case uint32_t(ThreadOp::I32AtomicCmpXchg):
10387 CHECK(emitAtomicCmpXchg(ValType::I32, Scalar::Int32));
10388 case uint32_t(ThreadOp::I64AtomicCmpXchg):
10389 CHECK(emitAtomicCmpXchg(ValType::I64, Scalar::Int64));
10390 case uint32_t(ThreadOp::I32AtomicCmpXchg8U):
10391 CHECK(emitAtomicCmpXchg(ValType::I32, Scalar::Uint8));
10392 case uint32_t(ThreadOp::I32AtomicCmpXchg16U):
10393 CHECK(emitAtomicCmpXchg(ValType::I32, Scalar::Uint16));
10394 case uint32_t(ThreadOp::I64AtomicCmpXchg8U):
10395 CHECK(emitAtomicCmpXchg(ValType::I64, Scalar::Uint8));
10396 case uint32_t(ThreadOp::I64AtomicCmpXchg16U):
10397 CHECK(emitAtomicCmpXchg(ValType::I64, Scalar::Uint16));
10398 case uint32_t(ThreadOp::I64AtomicCmpXchg32U):
10399 CHECK(emitAtomicCmpXchg(ValType::I64, Scalar::Uint32));
10400
10401 default:
10402 return iter().unrecognizedOpcode(&op);
10403 }
10404 break;
10405 }
10406
10407 // asm.js-specific operators
10408 case uint16_t(Op::MozPrefix): {
10409 if (op.b1 == uint32_t(MozOp::CallBuiltinModuleFunc)) {
10410 if (!codeMeta().isBuiltinModule()) {
10411 return iter().unrecognizedOpcode(&op);
10412 }
10413 CHECK(emitCallBuiltinModuleFunc());
10414 }
10415 #ifdef ENABLE_WASM_JSPI
10416 if (op.b1 == uint32_t(MozOp::StackSwitch)) {
10417 if (!codeMeta().isBuiltinModule() ||
10418 !codeMeta().jsPromiseIntegrationEnabled()) {
10419 return iter().unrecognizedOpcode(&op);
10420 }
10421 CHECK(emitStackSwitch());
10422 }
10423 #endif
10424
10425 if (!codeMeta().isAsmJS()) {
10426 return iter().unrecognizedOpcode(&op);
10427 }
10428 switch (op.b1) {
10429 case uint32_t(MozOp::TeeGlobal):
10430 CHECK(emitTeeGlobal());
10431 case uint32_t(MozOp::I32Min):
10432 case uint32_t(MozOp::I32Max):
10433 CHECK(emitMinMax(ValType::I32, MIRType::Int32,
10434 MozOp(op.b1) == MozOp::I32Max));
10435 case uint32_t(MozOp::I32Neg):
10436 CHECK(emitUnaryWithType<MWasmNeg>(ValType::I32, MIRType::Int32));
10437 case uint32_t(MozOp::I32BitNot):
10438 CHECK(emitBitNot(ValType::I32, MIRType::Int32));
10439 case uint32_t(MozOp::I32Abs):
10440 CHECK(emitUnaryWithType<MAbs>(ValType::I32, MIRType::Int32));
10441 case uint32_t(MozOp::F32TeeStoreF64):
10442 CHECK(emitTeeStoreWithCoercion(ValType::F32, Scalar::Float64));
10443 case uint32_t(MozOp::F64TeeStoreF32):
10444 CHECK(emitTeeStoreWithCoercion(ValType::F64, Scalar::Float32));
10445 case uint32_t(MozOp::I32TeeStore8):
10446 CHECK(emitTeeStore(ValType::I32, Scalar::Int8));
10447 case uint32_t(MozOp::I32TeeStore16):
10448 CHECK(emitTeeStore(ValType::I32, Scalar::Int16));
10449 case uint32_t(MozOp::I64TeeStore8):
10450 CHECK(emitTeeStore(ValType::I64, Scalar::Int8));
10451 case uint32_t(MozOp::I64TeeStore16):
10452 CHECK(emitTeeStore(ValType::I64, Scalar::Int16));
10453 case uint32_t(MozOp::I64TeeStore32):
10454 CHECK(emitTeeStore(ValType::I64, Scalar::Int32));
10455 case uint32_t(MozOp::I32TeeStore):
10456 CHECK(emitTeeStore(ValType::I32, Scalar::Int32));
10457 case uint32_t(MozOp::I64TeeStore):
10458 CHECK(emitTeeStore(ValType::I64, Scalar::Int64));
10459 case uint32_t(MozOp::F32TeeStore):
10460 CHECK(emitTeeStore(ValType::F32, Scalar::Float32));
10461 case uint32_t(MozOp::F64TeeStore):
10462 CHECK(emitTeeStore(ValType::F64, Scalar::Float64));
10463 case uint32_t(MozOp::F64Mod):
10464 CHECK(emitRem(ValType::F64, MIRType::Double,
10465 /* isUnsigned = */ false));
10466 case uint32_t(MozOp::F64SinNative):
10467 CHECK(emitUnaryMathBuiltinCall(SASigSinNativeD));
10468 case uint32_t(MozOp::F64SinFdlibm):
10469 CHECK(emitUnaryMathBuiltinCall(SASigSinFdlibmD));
10470 case uint32_t(MozOp::F64CosNative):
10471 CHECK(emitUnaryMathBuiltinCall(SASigCosNativeD));
10472 case uint32_t(MozOp::F64CosFdlibm):
10473 CHECK(emitUnaryMathBuiltinCall(SASigCosFdlibmD));
10474 case uint32_t(MozOp::F64TanNative):
10475 CHECK(emitUnaryMathBuiltinCall(SASigTanNativeD));
10476 case uint32_t(MozOp::F64TanFdlibm):
10477 CHECK(emitUnaryMathBuiltinCall(SASigTanFdlibmD));
10478 case uint32_t(MozOp::F64Asin):
10479 CHECK(emitUnaryMathBuiltinCall(SASigASinD));
10480 case uint32_t(MozOp::F64Acos):
10481 CHECK(emitUnaryMathBuiltinCall(SASigACosD));
10482 case uint32_t(MozOp::F64Atan):
10483 CHECK(emitUnaryMathBuiltinCall(SASigATanD));
10484 case uint32_t(MozOp::F64Exp):
10485 CHECK(emitUnaryMathBuiltinCall(SASigExpD));
10486 case uint32_t(MozOp::F64Log):
10487 CHECK(emitUnaryMathBuiltinCall(SASigLogD));
10488 case uint32_t(MozOp::F64Pow):
10489 CHECK(emitBinaryMathBuiltinCall(SASigPowD));
10490 case uint32_t(MozOp::F64Atan2):
10491 CHECK(emitBinaryMathBuiltinCall(SASigATan2D));
10492 case uint32_t(MozOp::OldCallDirect):
10493 CHECK(emitCall(/* asmJSFuncDef = */ true));
10494 case uint32_t(MozOp::OldCallIndirect):
10495 CHECK(emitCallIndirect(/* oldStyle = */ true));
10496
10497 default:
10498 return iter().unrecognizedOpcode(&op);
10499 }
10500 break;
10501 }
10502
10503 default:
10504 return iter().unrecognizedOpcode(&op);
10505 }
10506 }
10507
10508 MOZ_CRASH("unreachable");
10509
10510 #undef CHECK
10511 }
10512
10513 } // end anonymous namespace
10514
10515 bool RootCompiler::generate() {
10516 // Initialize global information used for optimization
10517 if (codeMeta_.numMemories() > 0) {
10518 if (codeMeta_.memories[0].addressType() == AddressType::I32) {
10519 mirGen_.initMinWasmMemory0Length(codeMeta_.memories[0].initialLength32());
10520 } else {
10521 mirGen_.initMinWasmMemory0Length(codeMeta_.memories[0].initialLength64());
10522 }
10523 }
10524
10525 // Only activate branch hinting if the option is enabled and some hints were
10526 // parsed.
10527 if (codeMeta_.branchHintingEnabled() && !codeMeta_.branchHints.isEmpty()) {
10528 compileInfo_.setBranchHinting(true);
10529 }
10530
10531 // Figure out what the inlining budget for this function is. If we've
10532 // already exceeded the module-level limit, the budget is zero. See
10533 // "[SMDOC] Per-function and per-module inlining limits" (WasmHeuristics.h)
10534 if (codeTailMeta_) {
10535 auto guard = codeTailMeta_->inliningBudget.lock();
10536
10537 if (guard.get() > 0) {
10538 localInliningBudget_ =
10539 int64_t(codeMeta_.codeSectionSize()) * PerFunctionMaxInliningRatio;
10540 localInliningBudget_ =
10541 std::min<int64_t>(localInliningBudget_, guard.get());
10542 } else {
10543 localInliningBudget_ = 0;
10544 }
10545 MOZ_ASSERT(localInliningBudget_ >= 0);
10546 } else {
10547 localInliningBudget_ = 0;
10548 }
10549
10550 // Build the MIR graph
10551 FunctionCompiler funcCompiler(*this, decoder_, func_, locals_, compileInfo_);
10552 if (!funcCompiler.initRoot() || !funcCompiler.startBlock() ||
10553 !funcCompiler.emitBodyExprs()) {
10554 return false;
10555 }
10556 funcCompiler.finish();
10557 observedFeatures_ = funcCompiler.featureUsage();
10558
10559 MOZ_ASSERT(loopDepth_ == 0);
10560
10561 funcStats_.numFuncs += 1;
10562 funcStats_.bytecodeSize += func_.bytecodeSize();
10563 funcStats_.inlinedDirectCallCount += inliningStats_.inlinedDirectFunctions;
10564 funcStats_.inlinedCallRefCount += inliningStats_.inlinedCallRefFunctions;
10565 funcStats_.inlinedDirectCallBytecodeSize +=
10566 inliningStats_.inlinedDirectBytecodeSize;
10567 funcStats_.inlinedCallRefBytecodeSize +=
10568 inliningStats_.inlinedCallRefBytecodeSize;
10569 funcStats_.numLargeFunctionBackoffs +=
10570 inliningStats_.largeFunctionBackoff ? 1 : 0;
10571
10572 if (codeTailMeta_) {
10573 auto guard = codeTailMeta_->inliningBudget.lock();
10574 // Update the module's inlining budget accordingly. If it is already
10575 // negative, no more inlining for the module can happen, so there's no
10576 // point in updating it further.
10577 if (guard.get() >= 0) {
10578 guard.get() -= int64_t(inliningStats_.inlinedDirectBytecodeSize);
10579 guard.get() -= int64_t(inliningStats_.inlinedCallRefBytecodeSize);
10580 if (guard.get() < 0) {
10581 JS_LOG(wasmPerf, Info,
10582 "CM=..%06lx RC::generate "
10583 "Inlining budget for entire module exceeded",
10584 0xFFFFFF & (unsigned long)uintptr_t(&codeMeta_));
10585 }
10586 }
10587 // If this particular root function overran the function-level
10588 // limit, note that in the module too.
10589 if (localInliningBudget_ < 0) {
10590 funcStats_.numInliningBudgetOverruns += 1;
10591 }
10592 }
10593
10594 return true;
10595 }
10596
10597 CompileInfo* RootCompiler::startInlineCall(
10598 uint32_t callerFuncIndex, BytecodeOffset callerOffset,
10599 uint32_t calleeFuncIndex, uint32_t numLocals, size_t inlineeBytecodeSize,
10600 InliningHeuristics::CallKind callKind) {
10601 if (callKind == InliningHeuristics::CallKind::Direct) {
10602 inliningStats_.inlinedDirectBytecodeSize += inlineeBytecodeSize;
10603 inliningStats_.inlinedDirectFunctions += 1;
10604 } else {
10605 MOZ_ASSERT(callKind == InliningHeuristics::CallKind::CallRef);
10606 inliningStats_.inlinedCallRefBytecodeSize += inlineeBytecodeSize;
10607 inliningStats_.inlinedCallRefFunctions += 1;
10608 }
10609
10610 // Update the inlining budget accordingly. If it is already negative, no
10611 // more inlining within this root function can happen, so there's no
10612 // point in updating it further.
10613 if (localInliningBudget_ >= 0) {
10614 localInliningBudget_ -= int64_t(inlineeBytecodeSize);
10615 #ifdef JS_JITSPEW
10616 if (localInliningBudget_ <= 0) {
10617 JS_LOG(wasmPerf, Info,
10618 "CM=..%06lx RC::startInlineCall "
10619 "Inlining budget for fI=%u exceeded",
10620 0xFFFFFF & (unsigned long)uintptr_t(&codeMeta_), callerFuncIndex);
10621 }
10622 #endif
10623 }
10624
10625 // Add the callers offset to the stack of inlined caller offsets
10626 if (!inlinedCallerOffsets_.append(callerOffset)) {
10627 return nullptr;
10628 }
10629
10630 // Cache a copy of the current stack of inlined caller offsets that can be
10631 // shared across all call sites
10632 InlinedCallerOffsets inlinedCallerOffsets;
10633 if (!inlinedCallerOffsets.appendAll(inlinedCallerOffsets_)) {
10634 return nullptr;
10635 }
10636
10637 if (!inliningContext_.append(std::move(inlinedCallerOffsets),
10638 &inlinedCallerOffsetsIndex_)) {
10639 return nullptr;
10640 }
10641
10642 UniqueCompileInfo compileInfo = MakeUnique<CompileInfo>(numLocals);
10643 if (!compileInfo || !compileInfos_.append(std::move(compileInfo))) {
10644 return nullptr;
10645 }
10646 return compileInfos_[compileInfos_.length() - 1].get();
10647 }
10648
10649 void RootCompiler::finishInlineCall() { inlinedCallerOffsets_.popBack(); }
10650
10651 bool wasm::IonCompileFunctions(const CodeMetadata& codeMeta,
10652 const CodeTailMetadata* codeTailMeta,
10653 const CompilerEnvironment& compilerEnv,
10654 LifoAlloc& lifo,
10655 const FuncCompileInputVector& inputs,
10656 CompiledCode* code, UniqueChars* error) {
10657 MOZ_ASSERT(compilerEnv.tier() == Tier::Optimized);
10658 MOZ_ASSERT(compilerEnv.debug() == DebugEnabled::False);
10659 MOZ_ASSERT_IF(compilerEnv.mode() == CompileMode::LazyTiering, !!codeTailMeta);
10660
10661 // We should not interact with the GC heap, nor allocate from it when we are
10662 // compiling wasm code. Ion data structures have some fields for GC objects
10663 // that we do not use, yet can confuse the static analysis here. Disable it
10664 // for this function.
10665 JS::AutoSuppressGCAnalysis nogc;
10666
10667 TempAllocator alloc(&lifo);
10668 JitContext jitContext;
10669 MOZ_ASSERT(IsCompilingWasm());
10670 WasmMacroAssembler masm(alloc);
10671 #if defined(JS_CODEGEN_ARM64)
10672 masm.SetStackPointer64(PseudoStackPointer64);
10673 #endif
10674
10675 // Swap in already-allocated empty vectors to avoid malloc/free.
10676 MOZ_ASSERT(code->empty());
10677 if (!code->swap(masm)) {
10678 return false;
10679 }
10680
10681 // Create a description of the stack layout created by GenerateTrapExit().
10682 RegisterOffsets trapExitLayout;
10683 size_t trapExitLayoutNumWords;
10684 GenerateTrapExitRegisterOffsets(&trapExitLayout, &trapExitLayoutNumWords);
10685
10686 for (const FuncCompileInput& func : inputs) {
10687 JitSpewCont(JitSpew_Codegen, "\n");
10688 JitSpew(JitSpew_Codegen,
10689 "# ================================"
10690 "==================================");
10691 JitSpew(JitSpew_Codegen, "# ==");
10692 JitSpew(JitSpew_Codegen,
10693 "# wasm::IonCompileFunctions: starting on function index %d",
10694 (int)func.index);
10695
10696 Decoder d(func.begin, func.end, func.lineOrBytecode, error);
10697
10698 // Build the local types vector.
10699 ValTypeVector locals;
10700 if (!DecodeLocalEntriesWithParams(d, codeMeta, func.index, &locals)) {
10701 return false;
10702 }
10703
10704 // Set up for Ion compilation.
10705 RootCompiler rootCompiler(compilerEnv, codeMeta, codeTailMeta, alloc,
10706 locals, func, d, masm.tryNotes(),
10707 masm.inliningContext());
10708 if (!rootCompiler.generate()) {
10709 return false;
10710 }
10711
10712 // Record observed feature usage
10713 FeatureUsage observedFeatures = rootCompiler.observedFeatures();
10714 code->featureUsage |= observedFeatures;
10715
10716 // Compile MIR graph
10717 {
10718 jit::SpewBeginWasmFunction(&rootCompiler.mirGen(), func.index);
10719 jit::AutoSpewEndFunction spewEndFunction(&rootCompiler.mirGen());
10720
10721 if (!OptimizeMIR(&rootCompiler.mirGen())) {
10722 return false;
10723 }
10724
10725 LIRGraph* lir = GenerateLIR(&rootCompiler.mirGen());
10726 if (!lir) {
10727 return false;
10728 }
10729
10730 size_t unwindInfoBefore = masm.codeRangeUnwindInfos().length();
10731
10732 CodeGenerator codegen(&rootCompiler.mirGen(), lir, &masm, &codeMeta);
10733
10734 TrapSiteDesc prologueTrapSiteDesc(
10735 wasm::BytecodeOffset(func.lineOrBytecode));
10736 FuncOffsets offsets;
10737 ArgTypeVector args(codeMeta.getFuncType(func.index));
10738 IonPerfSpewer spewer;
10739 if (!codegen.generateWasm(CallIndirectId::forFunc(codeMeta, func.index),
10740 prologueTrapSiteDesc, args, trapExitLayout,
10741 trapExitLayoutNumWords, &offsets,
10742 &code->stackMaps, &d, &spewer)) {
10743 return false;
10744 }
10745
10746 bool hasUnwindInfo =
10747 unwindInfoBefore != masm.codeRangeUnwindInfos().length();
10748
10749 // Record this function's code range
10750 if (!code->codeRanges.emplaceBack(func.index, offsets, hasUnwindInfo)) {
10751 return false;
10752 }
10753
10754 if (PerfEnabled()) {
10755 if (!code->funcIonSpewers.emplaceBack(func.index, std::move(spewer))) {
10756 return false;
10757 }
10758 }
10759 }
10760
10761 // Record this function's compilation stats
10762 code->compileStats.merge(rootCompiler.funcStats());
10763
10764 // Record this function's specific feature usage
10765 if (!code->funcs.emplaceBack(func.index, observedFeatures)) {
10766 return false;
10767 }
10768
10769 JitSpew(JitSpew_Codegen,
10770 "# wasm::IonCompileFunctions: completed function index %d",
10771 (int)func.index);
10772 JitSpew(JitSpew_Codegen, "# ==");
10773 JitSpew(JitSpew_Codegen,
10774 "# ================================"
10775 "==================================");
10776 JitSpewCont(JitSpew_Codegen, "\n");
10777 }
10778
10779 masm.finish();
10780 if (masm.oom()) {
10781 return false;
10782 }
10783
10784 return code->swap(masm);
10785 }
10786
10787 bool wasm::IonDumpFunction(const CompilerEnvironment& compilerEnv,
10788 const CodeMetadata& codeMeta,
10789 const FuncCompileInput& func,
10790 IonDumpContents contents, GenericPrinter& out,
10791 UniqueChars* error) {
10792 LifoAlloc lifo(TempAllocator::PreferredLifoChunkSize,
10793 js::BackgroundMallocArena);
10794 TempAllocator alloc(&lifo);
10795 JitContext jitContext;
10796 Decoder d(func.begin, func.end, func.lineOrBytecode, error);
10797
10798 // Decode the locals.
10799 ValTypeVector locals;
10800 if (!DecodeLocalEntriesWithParams(d, codeMeta, func.index, &locals)) {
10801 return false;
10802 }
10803
10804 TryNoteVector tryNotes;
10805 InliningContext inliningContext;
10806 RootCompiler rootCompiler(compilerEnv, codeMeta, nullptr, alloc, locals, func,
10807 d, tryNotes, inliningContext);
10808 if (!rootCompiler.generate()) {
10809 return false;
10810 }
10811
10812 if (contents == IonDumpContents::UnoptimizedMIR) {
10813 rootCompiler.mirGraph().dump(out);
10814 return true;
10815 }
10816
10817 // Optimize the MIR graph
10818 if (!OptimizeMIR(&rootCompiler.mirGen())) {
10819 return false;
10820 }
10821
10822 if (contents == IonDumpContents::OptimizedMIR) {
10823 rootCompiler.mirGraph().dump(out);
10824 return true;
10825 }
10826
10827 #ifdef JS_JITSPEW
10828 // Generate the LIR graph
10829 LIRGraph* lir = GenerateLIR(&rootCompiler.mirGen());
10830 if (!lir) {
10831 return false;
10832 }
10833
10834 MOZ_ASSERT(contents == IonDumpContents::LIR);
10835 lir->dump(out);
10836 #else
10837 out.printf("cannot dump LIR without --enable-jitspew");
10838 #endif
10839 return true;
10840 }
10841
10842 bool js::wasm::IonPlatformSupport() {
10843 #if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86) || \
10844 defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_MIPS64) || \
10845 defined(JS_CODEGEN_ARM64) || defined(JS_CODEGEN_LOONG64) || \
10846 defined(JS_CODEGEN_RISCV64)
10847 return true;
10848 #else
10849 return false;
10850 #endif
10851 }