Debian Codegraph @

js/src/jit/MIR-wasm.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 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "jit/MIR-wasm.h"
8
9 #include "mozilla/ScopeExit.h"
10
11 #include "jit/MIRGraph.h"
12 #include "js/Conversions.h"
13 #include "wasm/WasmCode.h"
14 #include "wasm/WasmFeatures.h" // for wasm::ReportSimdAnalysis
15
16 #include "wasm/WasmInstance-inl.h"
17
18 using namespace js;
19 using namespace js::jit;
20
21 using JS::ToInt32;
22
23 using mozilla::CheckedInt;
24 using mozilla::IsFloat32Representable;
25
26 HashNumber MWasmFloatConstant::valueHash() const {
27 #ifdef ENABLE_WASM_SIMD
28 return ConstantValueHash(type(), u.bits_[0] ^ u.bits_[1]);
29 #else
30 return ConstantValueHash(type(), u.bits_[0]);
31 #endif
32 }
33
34 bool MWasmFloatConstant::congruentTo(const MDefinition* ins) const {
35 return ins->isWasmFloatConstant() && type() == ins->type() &&
36 #ifdef ENABLE_WASM_SIMD
37 u.bits_[1] == ins->toWasmFloatConstant()->u.bits_[1] &&
38 #endif
39 u.bits_[0] == ins->toWasmFloatConstant()->u.bits_[0];
40 }
41
42 HashNumber MWasmNullConstant::valueHash() const {
43 return ConstantValueHash(MIRType::WasmAnyRef, 0);
44 }
45
46 MDefinition* MWasmTruncateToInt32::foldsTo(TempAllocator& alloc) {
47 MDefinition* input = getOperand(0);
48 if (input->type() == MIRType::Int32) {
49 return input;
50 }
51
52 if (input->type() == MIRType::Double && input->isConstant()) {
53 double d = input->toConstant()->toDouble();
54 if (std::isnan(d)) {
55 return this;
56 }
57
58 if (!isUnsigned() && d <= double(INT32_MAX) && d >= double(INT32_MIN)) {
59 return MConstant::New(alloc, Int32Value(ToInt32(d)));
60 }
61
62 if (isUnsigned() && d <= double(UINT32_MAX) && d >= 0) {
63 return MConstant::New(alloc, Int32Value(ToInt32(d)));
64 }
65 }
66
67 if (input->type() == MIRType::Float32 && input->isConstant()) {
68 double f = double(input->toConstant()->toFloat32());
69 if (std::isnan(f)) {
70 return this;
71 }
72
73 if (!isUnsigned() && f <= double(INT32_MAX) && f >= double(INT32_MIN)) {
74 return MConstant::New(alloc, Int32Value(ToInt32(f)));
75 }
76
77 if (isUnsigned() && f <= double(UINT32_MAX) && f >= 0) {
78 return MConstant::New(alloc, Int32Value(ToInt32(f)));
79 }
80 }
81
82 return this;
83 }
84
85 MDefinition* MWasmExtendU32Index::foldsTo(TempAllocator& alloc) {
86 MDefinition* input = this->input();
87 if (input->isConstant()) {
88 return MConstant::NewInt64(
89 alloc, int64_t(uint32_t(input->toConstant()->toInt32())));
90 }
91
92 return this;
93 }
94
95 MDefinition* MWasmWrapU32Index::foldsTo(TempAllocator& alloc) {
96 MDefinition* input = this->input();
97 if (input->isConstant()) {
98 return MConstant::New(
99 alloc, Int32Value(int32_t(uint32_t(input->toConstant()->toInt64()))));
100 }
101
102 return this;
103 }
104
105 // Some helpers for folding wasm and/or/xor on int32/64 values. Rather than
106 // duplicating these for 32 and 64-bit values, all folding is done on 64-bit
107 // values and masked for the 32-bit case.
108
109 const uint64_t Low32Mask = uint64_t(0xFFFFFFFFULL);
110
111 // Routines to check and disassemble values.
112
113 static bool IsIntegralConstant(const MDefinition* def) {
114 return def->isConstant() &&
115 (def->type() == MIRType::Int32 || def->type() == MIRType::Int64);
116 }
117
118 static uint64_t GetIntegralConstant(const MDefinition* def) {
119 if (def->type() == MIRType::Int32) {
120 return uint64_t(def->toConstant()->toInt32()) & Low32Mask;
121 }
122 return uint64_t(def->toConstant()->toInt64());
123 }
124
125 static bool IsIntegralConstantZero(const MDefinition* def) {
126 return IsIntegralConstant(def) && GetIntegralConstant(def) == 0;
127 }
128
129 static bool IsIntegralConstantOnes(const MDefinition* def) {
130 uint64_t ones = def->type() == MIRType::Int32 ? Low32Mask : ~uint64_t(0);
131 return IsIntegralConstant(def) && GetIntegralConstant(def) == ones;
132 }
133
134 // Routines to create values.
135 static MDefinition* ToIntegralConstant(TempAllocator& alloc, MIRType ty,
136 uint64_t val) {
137 switch (ty) {
138 case MIRType::Int32:
139 return MConstant::New(alloc,
140 Int32Value(int32_t(uint32_t(val & Low32Mask))));
141 case MIRType::Int64:
142 return MConstant::NewInt64(alloc, int64_t(val));
143 default:
144 MOZ_CRASH();
145 }
146 }
147
148 static MDefinition* ZeroOfType(TempAllocator& alloc, MIRType ty) {
149 return ToIntegralConstant(alloc, ty, 0);
150 }
151
152 static MDefinition* OnesOfType(TempAllocator& alloc, MIRType ty) {
153 return ToIntegralConstant(alloc, ty, ~uint64_t(0));
154 }
155
156 MDefinition* MWasmBinaryBitwise::foldsTo(TempAllocator& alloc) {
157 MOZ_ASSERT(op() == Opcode::WasmBinaryBitwise);
158 MOZ_ASSERT(type() == MIRType::Int32 || type() == MIRType::Int64);
159
160 MDefinition* argL = getOperand(0);
161 MDefinition* argR = getOperand(1);
162 MOZ_ASSERT(argL->type() == type() && argR->type() == type());
163
164 // The args are the same (SSA name)
165 if (argL == argR) {
166 switch (subOpcode()) {
167 case SubOpcode::And:
168 case SubOpcode::Or:
169 return argL;
170 case SubOpcode::Xor:
171 return ZeroOfType(alloc, type());
172 default:
173 MOZ_CRASH();
174 }
175 }
176
177 // Both args constant
178 if (IsIntegralConstant(argL) && IsIntegralConstant(argR)) {
179 uint64_t valL = GetIntegralConstant(argL);
180 uint64_t valR = GetIntegralConstant(argR);
181 uint64_t val = valL;
182 switch (subOpcode()) {
183 case SubOpcode::And:
184 val &= valR;
185 break;
186 case SubOpcode::Or:
187 val |= valR;
188 break;
189 case SubOpcode::Xor:
190 val ^= valR;
191 break;
192 default:
193 MOZ_CRASH();
194 }
195 return ToIntegralConstant(alloc, type(), val);
196 }
197
198 // Left arg is zero
199 if (IsIntegralConstantZero(argL)) {
200 switch (subOpcode()) {
201 case SubOpcode::And:
202 return ZeroOfType(alloc, type());
203 case SubOpcode::Or:
204 case SubOpcode::Xor:
205 return argR;
206 default:
207 MOZ_CRASH();
208 }
209 }
210
211 // Right arg is zero
212 if (IsIntegralConstantZero(argR)) {
213 switch (subOpcode()) {
214 case SubOpcode::And:
215 return ZeroOfType(alloc, type());
216 case SubOpcode::Or:
217 case SubOpcode::Xor:
218 return argL;
219 default:
220 MOZ_CRASH();
221 }
222 }
223
224 // Left arg is ones
225 if (IsIntegralConstantOnes(argL)) {
226 switch (subOpcode()) {
227 case SubOpcode::And:
228 return argR;
229 case SubOpcode::Or:
230 return OnesOfType(alloc, type());
231 case SubOpcode::Xor:
232 return MBitNot::New(alloc, argR, type());
233 default:
234 MOZ_CRASH();
235 }
236 }
237
238 // Right arg is ones
239 if (IsIntegralConstantOnes(argR)) {
240 switch (subOpcode()) {
241 case SubOpcode::And:
242 return argL;
243 case SubOpcode::Or:
244 return OnesOfType(alloc, type());
245 case SubOpcode::Xor:
246 return MBitNot::New(alloc, argL, type());
247 default:
248 MOZ_CRASH();
249 }
250 }
251
252 return this;
253 }
254
255 MDefinition* MWasmAddOffset::foldsTo(TempAllocator& alloc) {
256 MDefinition* baseArg = base();
257 if (!baseArg->isConstant()) {
258 return this;
259 }
260
261 if (baseArg->type() == MIRType::Int32) {
262 CheckedInt<uint32_t> ptr = baseArg->toConstant()->toInt32();
263 ptr += offset();
264 if (!ptr.isValid()) {
265 return this;
266 }
267 return MConstant::New(alloc, Int32Value(ptr.value()));
268 }
269
270 MOZ_ASSERT(baseArg->type() == MIRType::Int64);
271 CheckedInt<uint64_t> ptr = baseArg->toConstant()->toInt64();
272 ptr += offset();
273 if (!ptr.isValid()) {
274 return this;
275 }
276 return MConstant::NewInt64(alloc, ptr.value());
277 }
278
279 bool MWasmAlignmentCheck::congruentTo(const MDefinition* ins) const {
280 if (!ins->isWasmAlignmentCheck()) {
281 return false;
282 }
283 const MWasmAlignmentCheck* check = ins->toWasmAlignmentCheck();
284 return byteSize_ == check->byteSize() && congruentIfOperandsEqual(check);
285 }
286
287 MDefinition::AliasType MAsmJSLoadHeap::mightAlias(
288 const MDefinition* def) const {
289 if (def->isAsmJSStoreHeap()) {
290 const MAsmJSStoreHeap* store = def->toAsmJSStoreHeap();
291 if (store->accessType() != accessType()) {
292 return AliasType::MayAlias;
293 }
294 if (!base()->isConstant() || !store->base()->isConstant()) {
295 return AliasType::MayAlias;
296 }
297 const MConstant* otherBase = store->base()->toConstant();
298 if (base()->toConstant()->equals(otherBase)) {
299 return AliasType::MayAlias;
300 }
301 return AliasType::NoAlias;
302 }
303 return AliasType::MayAlias;
304 }
305
306 bool MAsmJSLoadHeap::congruentTo(const MDefinition* ins) const {
307 if (!ins->isAsmJSLoadHeap()) {
308 return false;
309 }
310 const MAsmJSLoadHeap* load = ins->toAsmJSLoadHeap();
311 return load->accessType() == accessType() && congruentIfOperandsEqual(load);
312 }
313
314 bool MWasmI31RefGet::congruentTo(const MDefinition* ins) const {
315 if (!ins->isWasmI31RefGet()) {
316 return false;
317 }
318 // Make sure that we have a signed/signed or unsigned/unsigned pair to be
319 // considered congruent.
320 return congruentIfOperandsEqual(ins) &&
321 ins->toWasmI31RefGet()->wideningOp() == wideningOp();
322 }
323
324 MDefinition::AliasType MWasmLoadInstanceDataField::mightAlias(
325 const MDefinition* def) const {
326 if (def->isWasmStoreInstanceDataField()) {
327 const MWasmStoreInstanceDataField* store =
328 def->toWasmStoreInstanceDataField();
329 return store->instanceDataOffset() == instanceDataOffset_
330 ? AliasType::MayAlias
331 : AliasType::NoAlias;
332 }
333
334 return AliasType::MayAlias;
335 }
336
337 MDefinition::AliasType MWasmLoadGlobalCell::mightAlias(
338 const MDefinition* def) const {
339 if (def->isWasmStoreGlobalCell()) {
340 // No globals of different type can alias. See bug 1467415 comment 3.
341 if (type() != def->toWasmStoreGlobalCell()->value()->type()) {
342 return AliasType::NoAlias;
343 }
344
345 // We could do better here. We're dealing with two indirect globals.
346 // If at at least one of them is created in this module, then they
347 // can't alias -- in other words they can only alias if they are both
348 // imported. That would require having a flag on globals to indicate
349 // which are imported. See bug 1467415 comment 3, 4th rule.
350 }
351
352 return AliasType::MayAlias;
353 }
354
355 HashNumber MWasmLoadInstanceDataField::valueHash() const {
356 // Same comment as in MWasmLoadInstanceDataField::congruentTo() applies here.
357 HashNumber hash = MDefinition::valueHash();
358 hash = addU32ToHash(hash, instanceDataOffset_);
359 return hash;
360 }
361
362 bool MWasmLoadInstanceDataField::congruentTo(const MDefinition* ins) const {
363 if (!ins->isWasmLoadInstanceDataField()) {
364 return false;
365 }
366
367 const MWasmLoadInstanceDataField* other = ins->toWasmLoadInstanceDataField();
368
369 // We don't need to consider the isConstant_ markings here, because
370 // equivalence of offsets implies equivalence of constness.
371 bool sameOffsets = instanceDataOffset_ == other->instanceDataOffset_;
372 MOZ_ASSERT_IF(sameOffsets, isConstant_ == other->isConstant_);
373
374 // We omit checking congruence of the operands. There is only one
375 // operand, the instance pointer, and it only ever has one value within the
376 // domain of optimization. If that should ever change then operand
377 // congruence checking should be reinstated.
378 return sameOffsets /* && congruentIfOperandsEqual(other) */;
379 }
380
381 MDefinition* MWasmLoadInstanceDataField::foldsTo(TempAllocator& alloc) {
382 if (!dependency() || !dependency()->isWasmStoreInstanceDataField()) {
383 return this;
384 }
385
386 MWasmStoreInstanceDataField* store =
387 dependency()->toWasmStoreInstanceDataField();
388 if (!store->block()->dominates(block())) {
389 return this;
390 }
391
392 if (store->instanceDataOffset() != instanceDataOffset()) {
393 return this;
394 }
395
396 if (store->value()->type() != type()) {
397 return this;
398 }
399
400 return store->value();
401 }
402
403 MDefinition* MWasmSelect::foldsTo(TempAllocator& alloc) {
404 if (condExpr()->isConstant()) {
405 return condExpr()->toConstant()->toInt32() != 0 ? trueExpr() : falseExpr();
406 }
407 return this;
408 }
409
410 bool MWasmLoadGlobalCell::congruentTo(const MDefinition* ins) const {
411 if (!ins->isWasmLoadGlobalCell()) {
412 return false;
413 }
414 const MWasmLoadGlobalCell* other = ins->toWasmLoadGlobalCell();
415 return congruentIfOperandsEqual(other);
416 }
417
418 #ifdef ENABLE_WASM_SIMD
419 MDefinition* MWasmTernarySimd128::foldsTo(TempAllocator& alloc) {
420 if (simdOp() == wasm::SimdOp::V128Bitselect) {
421 if (v2()->op() == MDefinition::Opcode::WasmFloatConstant) {
422 int8_t shuffle[16];
423 if (specializeBitselectConstantMaskAsShuffle(shuffle)) {
424 return BuildWasmShuffleSimd128(alloc, shuffle, v0(), v1());
425 }
426 } else if (canRelaxBitselect()) {
427 return MWasmTernarySimd128::New(alloc, v0(), v1(), v2(),
428 wasm::SimdOp::I8x16RelaxedLaneSelect);
429 }
430 }
431 return this;
432 }
433
434 inline static bool MatchSpecificShift(MDefinition* instr,
435 wasm::SimdOp simdShiftOp,
436 int shiftValue) {
437 return instr->isWasmShiftSimd128() &&
438 instr->toWasmShiftSimd128()->simdOp() == simdShiftOp &&
439 instr->toWasmShiftSimd128()->rhs()->isConstant() &&
440 instr->toWasmShiftSimd128()->rhs()->toConstant()->toInt32() ==
441 shiftValue;
442 }
443
444 // Matches MIR subtree that represents PMADDUBSW instruction generated by
445 // emscripten. The a and b parameters return subtrees that correspond
446 // operands of the instruction, if match is found.
447 static bool MatchPmaddubswSequence(MWasmBinarySimd128* lhs,
448 MWasmBinarySimd128* rhs, MDefinition** a,
449 MDefinition** b) {
450 MOZ_ASSERT(lhs->simdOp() == wasm::SimdOp::I16x8Mul &&
451 rhs->simdOp() == wasm::SimdOp::I16x8Mul);
452 // The emscripten/LLVM produced the following sequence for _mm_maddubs_epi16:
453 //
454 // return _mm_adds_epi16(
455 // _mm_mullo_epi16(
456 // _mm_and_si128(__a, _mm_set1_epi16(0x00FF)),
457 // _mm_srai_epi16(_mm_slli_epi16(__b, 8), 8)),
458 // _mm_mullo_epi16(_mm_srli_epi16(__a, 8), _mm_srai_epi16(__b, 8)));
459 //
460 // This will roughly correspond the following MIR:
461 // MWasmBinarySimd128[I16x8AddSatS]
462 // |-- lhs: MWasmBinarySimd128[I16x8Mul] (lhs)
463 // | |-- lhs: MWasmBinarySimd128WithConstant[V128And] (op0)
464 // | | |-- lhs: a
465 // | | -- rhs: SimdConstant::SplatX8(0x00FF)
466 // | -- rhs: MWasmShiftSimd128[I16x8ShrS] (op1)
467 // | |-- lhs: MWasmShiftSimd128[I16x8Shl]
468 // | | |-- lhs: b
469 // | | -- rhs: MConstant[8]
470 // | -- rhs: MConstant[8]
471 // -- rhs: MWasmBinarySimd128[I16x8Mul] (rhs)
472 // |-- lhs: MWasmShiftSimd128[I16x8ShrU] (op2)
473 // | |-- lhs: a
474 // | |-- rhs: MConstant[8]
475 // -- rhs: MWasmShiftSimd128[I16x8ShrS] (op3)
476 // |-- lhs: b
477 // -- rhs: MConstant[8]
478
479 // The I16x8AddSatS and I16x8Mul are commutative, so their operands
480 // may be swapped. Rearrange op0, op1, op2, op3 to be in the order
481 // noted above.
482 MDefinition *op0 = lhs->lhs(), *op1 = lhs->rhs(), *op2 = rhs->lhs(),
483 *op3 = rhs->rhs();
484 if (op1->isWasmBinarySimd128WithConstant()) {
485 // Move MWasmBinarySimd128WithConstant[V128And] as first operand in lhs.
486 std::swap(op0, op1);
487 } else if (op3->isWasmBinarySimd128WithConstant()) {
488 // Move MWasmBinarySimd128WithConstant[V128And] as first operand in rhs.
489 std::swap(op2, op3);
490 }
491 if (op2->isWasmBinarySimd128WithConstant()) {
492 // The lhs and rhs are swapped.
493 // Make MWasmBinarySimd128WithConstant[V128And] to be op0.
494 std::swap(op0, op2);
495 std::swap(op1, op3);
496 }
497 if (op2->isWasmShiftSimd128() &&
498 op2->toWasmShiftSimd128()->simdOp() == wasm::SimdOp::I16x8ShrS) {
499 // The op2 and op3 appears to be in wrong order, swap.
500 std::swap(op2, op3);
501 }
502
503 // Check all instructions SIMD code and constant values for assigned
504 // names op0, op1, op2, op3 (see diagram above).
505 const uint16_t const00FF[8] = {255, 255, 255, 255, 255, 255, 255, 255};
506 if (!op0->isWasmBinarySimd128WithConstant() ||
507 op0->toWasmBinarySimd128WithConstant()->simdOp() !=
508 wasm::SimdOp::V128And ||
509 memcmp(op0->toWasmBinarySimd128WithConstant()->rhs().bytes(), const00FF,
510 16) != 0 ||
511 !MatchSpecificShift(op1, wasm::SimdOp::I16x8ShrS, 8) ||
512 !MatchSpecificShift(op2, wasm::SimdOp::I16x8ShrU, 8) ||
513 !MatchSpecificShift(op3, wasm::SimdOp::I16x8ShrS, 8) ||
514 !MatchSpecificShift(op1->toWasmShiftSimd128()->lhs(),
515 wasm::SimdOp::I16x8Shl, 8)) {
516 return false;
517 }
518
519 // Check if the instructions arguments that are subtrees match the
520 // a and b assignments. May depend on GVN behavior.
521 MDefinition* maybeA = op0->toWasmBinarySimd128WithConstant()->lhs();
522 MDefinition* maybeB = op3->toWasmShiftSimd128()->lhs();
523 if (maybeA != op2->toWasmShiftSimd128()->lhs() ||
524 maybeB != op1->toWasmShiftSimd128()->lhs()->toWasmShiftSimd128()->lhs()) {
525 return false;
526 }
527
528 *a = maybeA;
529 *b = maybeB;
530 return true;
531 }
532
533 MDefinition* MWasmBinarySimd128::foldsTo(TempAllocator& alloc) {
534 if (simdOp() == wasm::SimdOp::I8x16Swizzle && rhs()->isWasmFloatConstant()) {
535 // Specialize swizzle(v, constant) as shuffle(mask, v, zero) to trigger all
536 // our shuffle optimizations. We don't report this rewriting as the report
537 // will be overwritten by the subsequent shuffle analysis.
538 int8_t shuffleMask[16];
539 memcpy(shuffleMask, rhs()->toWasmFloatConstant()->toSimd128().bytes(), 16);
540 for (int i = 0; i < 16; i++) {
541 // Out-of-bounds lanes reference the zero vector; in many cases, the zero
542 // vector is removed by subsequent optimizations.
543 if (shuffleMask[i] < 0 || shuffleMask[i] > 15) {
544 shuffleMask[i] = 16;
545 }
546 }
547 MWasmFloatConstant* zero =
548 MWasmFloatConstant::NewSimd128(alloc, SimdConstant::SplatX4(0));
549 if (!zero) {
550 return nullptr;
551 }
552 block()->insertBefore(this, zero);
553 return BuildWasmShuffleSimd128(alloc, shuffleMask, lhs(), zero);
554 }
555
556 // Specialize var OP const / const OP var when possible.
557 //
558 // As the LIR layer can't directly handle v128 constants as part of its normal
559 // machinery we specialize some nodes here if they have single-use v128
560 // constant arguments. The purpose is to generate code that inlines the
561 // constant in the instruction stream, using either a rip-relative load+op or
562 // quickly-synthesized constant in a scratch on x64. There is a general
563 // assumption here that that is better than generating the constant into an
564 // allocatable register, since that register value could not be reused. (This
565 // ignores the possibility that the constant load could be hoisted).
566
567 if (lhs()->isWasmFloatConstant() != rhs()->isWasmFloatConstant() &&
568 specializeForConstantRhs()) {
569 if (isCommutative() && lhs()->isWasmFloatConstant() && lhs()->hasOneUse()) {
570 return MWasmBinarySimd128WithConstant::New(
571 alloc, rhs(), lhs()->toWasmFloatConstant()->toSimd128(), simdOp());
572 }
573
574 if (rhs()->isWasmFloatConstant() && rhs()->hasOneUse()) {
575 return MWasmBinarySimd128WithConstant::New(
576 alloc, lhs(), rhs()->toWasmFloatConstant()->toSimd128(), simdOp());
577 }
578 }
579
580 // Check special encoding for PMADDUBSW.
581 if (canPmaddubsw() && simdOp() == wasm::SimdOp::I16x8AddSatS &&
582 lhs()->isWasmBinarySimd128() && rhs()->isWasmBinarySimd128() &&
583 lhs()->toWasmBinarySimd128()->simdOp() == wasm::SimdOp::I16x8Mul &&
584 rhs()->toWasmBinarySimd128()->simdOp() == wasm::SimdOp::I16x8Mul) {
585 MDefinition *a, *b;
586 if (MatchPmaddubswSequence(lhs()->toWasmBinarySimd128(),
587 rhs()->toWasmBinarySimd128(), &a, &b)) {
588 return MWasmBinarySimd128::New(alloc, a, b, /* commutative = */ false,
589 wasm::SimdOp::MozPMADDUBSW);
590 }
591 }
592
593 return this;
594 }
595
596 MDefinition* MWasmScalarToSimd128::foldsTo(TempAllocator& alloc) {
597 # ifdef DEBUG
598 auto logging = mozilla::MakeScopeExit([&] {
599 js::wasm::ReportSimdAnalysis("scalar-to-simd128 -> constant folded");
600 });
601 # endif
602 if (input()->isConstant()) {
603 MConstant* c = input()->toConstant();
604 switch (simdOp()) {
605 case wasm::SimdOp::I8x16Splat:
606 return MWasmFloatConstant::NewSimd128(
607 alloc, SimdConstant::SplatX16(c->toInt32()));
608 case wasm::SimdOp::I16x8Splat:
609 return MWasmFloatConstant::NewSimd128(
610 alloc, SimdConstant::SplatX8(c->toInt32()));
611 case wasm::SimdOp::I32x4Splat:
612 return MWasmFloatConstant::NewSimd128(
613 alloc, SimdConstant::SplatX4(c->toInt32()));
614 case wasm::SimdOp::I64x2Splat:
615 return MWasmFloatConstant::NewSimd128(
616 alloc, SimdConstant::SplatX2(c->toInt64()));
617 default:
618 # ifdef DEBUG
619 logging.release();
620 # endif
621 return this;
622 }
623 }
624 if (input()->isWasmFloatConstant()) {
625 MWasmFloatConstant* c = input()->toWasmFloatConstant();
626 switch (simdOp()) {
627 case wasm::SimdOp::F32x4Splat:
628 return MWasmFloatConstant::NewSimd128(
629 alloc, SimdConstant::SplatX4(c->toFloat32()));
630 case wasm::SimdOp::F64x2Splat:
631 return MWasmFloatConstant::NewSimd128(
632 alloc, SimdConstant::SplatX2(c->toDouble()));
633 default:
634 # ifdef DEBUG
635 logging.release();
636 # endif
637 return this;
638 }
639 }
640 # ifdef DEBUG
641 logging.release();
642 # endif
643 return this;
644 }
645
646 template <typename T>
647 static bool AllTrue(const T& v) {
648 constexpr size_t count = sizeof(T) / sizeof(*v);
649 static_assert(count == 16 || count == 8 || count == 4 || count == 2);
650 bool result = true;
651 for (unsigned i = 0; i < count; i++) {
652 result = result && v[i] != 0;
653 }
654 return result;
655 }
656
657 template <typename T>
658 static int32_t Bitmask(const T& v) {
659 constexpr size_t count = sizeof(T) / sizeof(*v);
660 constexpr size_t shift = 8 * sizeof(*v) - 1;
661 static_assert(shift == 7 || shift == 15 || shift == 31 || shift == 63);
662 int32_t result = 0;
663 for (unsigned i = 0; i < count; i++) {
664 result = result | int32_t(((v[i] >> shift) & 1) << i);
665 }
666 return result;
667 }
668
669 MDefinition* MWasmReduceSimd128::foldsTo(TempAllocator& alloc) {
670 # ifdef DEBUG
671 auto logging = mozilla::MakeScopeExit([&] {
672 js::wasm::ReportSimdAnalysis("simd128-to-scalar -> constant folded");
673 });
674 # endif
675 if (input()->isWasmFloatConstant()) {
676 SimdConstant c = input()->toWasmFloatConstant()->toSimd128();
677 int32_t i32Result = 0;
678 switch (simdOp()) {
679 case wasm::SimdOp::V128AnyTrue:
680 i32Result = !c.isZeroBits();
681 break;
682 case wasm::SimdOp::I8x16AllTrue:
683 i32Result = AllTrue(
684 SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16());
685 break;
686 case wasm::SimdOp::I8x16Bitmask:
687 i32Result = Bitmask(
688 SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16());
689 break;
690 case wasm::SimdOp::I16x8AllTrue:
691 i32Result = AllTrue(
692 SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8());
693 break;
694 case wasm::SimdOp::I16x8Bitmask:
695 i32Result = Bitmask(
696 SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8());
697 break;
698 case wasm::SimdOp::I32x4AllTrue:
699 i32Result = AllTrue(
700 SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4());
701 break;
702 case wasm::SimdOp::I32x4Bitmask:
703 i32Result = Bitmask(
704 SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4());
705 break;
706 case wasm::SimdOp::I64x2AllTrue:
707 i32Result = AllTrue(
708 SimdConstant::CreateSimd128((int64_t*)c.bytes()).asInt64x2());
709 break;
710 case wasm::SimdOp::I64x2Bitmask:
711 i32Result = Bitmask(
712 SimdConstant::CreateSimd128((int64_t*)c.bytes()).asInt64x2());
713 break;
714 case wasm::SimdOp::I8x16ExtractLaneS:
715 i32Result =
716 SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16()[imm()];
717 break;
718 case wasm::SimdOp::I8x16ExtractLaneU:
719 i32Result = int32_t(SimdConstant::CreateSimd128((int8_t*)c.bytes())
720 .asInt8x16()[imm()]) &
721 0xFF;
722 break;
723 case wasm::SimdOp::I16x8ExtractLaneS:
724 i32Result =
725 SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8()[imm()];
726 break;
727 case wasm::SimdOp::I16x8ExtractLaneU:
728 i32Result = int32_t(SimdConstant::CreateSimd128((int16_t*)c.bytes())
729 .asInt16x8()[imm()]) &
730 0xFFFF;
731 break;
732 case wasm::SimdOp::I32x4ExtractLane:
733 i32Result =
734 SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4()[imm()];
735 break;
736 case wasm::SimdOp::I64x2ExtractLane:
737 return MConstant::NewInt64(
738 alloc, SimdConstant::CreateSimd128((int64_t*)c.bytes())
739 .asInt64x2()[imm()]);
740 case wasm::SimdOp::F32x4ExtractLane:
741 return MWasmFloatConstant::NewFloat32(
742 alloc, SimdConstant::CreateSimd128((float*)c.bytes())
743 .asFloat32x4()[imm()]);
744 case wasm::SimdOp::F64x2ExtractLane:
745 return MWasmFloatConstant::NewDouble(
746 alloc, SimdConstant::CreateSimd128((double*)c.bytes())
747 .asFloat64x2()[imm()]);
748 default:
749 # ifdef DEBUG
750 logging.release();
751 # endif
752 return this;
753 }
754 return MConstant::New(alloc, Int32Value(i32Result), MIRType::Int32);
755 }
756 # ifdef DEBUG
757 logging.release();
758 # endif
759 return this;
760 }
761 #endif // ENABLE_WASM_SIMD
762
763 MDefinition* MWasmUnsignedToDouble::foldsTo(TempAllocator& alloc) {
764 if (input()->isConstant()) {
765 return MConstant::New(
766 alloc, DoubleValue(uint32_t(input()->toConstant()->toInt32())));
767 }
768
769 return this;
770 }
771
772 MDefinition* MWasmUnsignedToFloat32::foldsTo(TempAllocator& alloc) {
773 if (input()->isConstant()) {
774 double dval = double(uint32_t(input()->toConstant()->toInt32()));
775 if (IsFloat32Representable(dval)) {
776 return MConstant::NewFloat32(alloc, float(dval));
777 }
778 }
779
780 return this;
781 }
782
783 MWasmCallCatchable* MWasmCallCatchable::New(
784 TempAllocator& alloc, const wasm::CallSiteDesc& desc,
785 const wasm::CalleeDesc& callee, const Args& args,
786 uint32_t stackArgAreaSizeUnaligned, uint32_t tryNoteIndex,
787 MBasicBlock* fallthroughBlock, MBasicBlock* prePadBlock,
788 MDefinition* tableAddressOrRef) {
789 MWasmCallCatchable* call = new (alloc)
790 MWasmCallCatchable(desc, callee, stackArgAreaSizeUnaligned, tryNoteIndex);
791
792 call->setSuccessor(FallthroughBranchIndex, fallthroughBlock);
793 call->setSuccessor(PrePadBranchIndex, prePadBlock);
794
795 MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableAddressOrRef);
796 if (!call->initWithArgs(alloc, call, args, tableAddressOrRef)) {
797 return nullptr;
798 }
799
800 return call;
801 }
802
803 MWasmCallCatchable* MWasmCallCatchable::NewBuiltinInstanceMethodCall(
804 TempAllocator& alloc, const wasm::CallSiteDesc& desc,
805 const wasm::SymbolicAddress builtin, wasm::FailureMode failureMode,
806 const ABIArg& instanceArg, const Args& args,
807 uint32_t stackArgAreaSizeUnaligned, uint32_t tryNoteIndex,
808 MBasicBlock* fallthroughBlock, MBasicBlock* prePadBlock) {
809 auto callee = wasm::CalleeDesc::builtinInstanceMethod(builtin);
810 MWasmCallCatchable* call = MWasmCallCatchable::New(
811 alloc, desc, callee, args, stackArgAreaSizeUnaligned, tryNoteIndex,
812 fallthroughBlock, prePadBlock, nullptr);
813 if (!call) {
814 return nullptr;
815 }
816
817 MOZ_ASSERT(instanceArg != ABIArg());
818 call->instanceArg_ = instanceArg;
819 call->builtinMethodFailureMode_ = failureMode;
820 return call;
821 }
822
823 MWasmCallUncatchable* MWasmCallUncatchable::New(
824 TempAllocator& alloc, const wasm::CallSiteDesc& desc,
825 const wasm::CalleeDesc& callee, const Args& args,
826 uint32_t stackArgAreaSizeUnaligned, MDefinition* tableAddressOrRef) {
827 MWasmCallUncatchable* call =
828 new (alloc) MWasmCallUncatchable(desc, callee, stackArgAreaSizeUnaligned);
829
830 MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableAddressOrRef);
831 if (!call->initWithArgs(alloc, call, args, tableAddressOrRef)) {
832 return nullptr;
833 }
834
835 return call;
836 }
837
838 MWasmCallUncatchable* MWasmCallUncatchable::NewBuiltinInstanceMethodCall(
839 TempAllocator& alloc, const wasm::CallSiteDesc& desc,
840 const wasm::SymbolicAddress builtin, wasm::FailureMode failureMode,
841 const ABIArg& instanceArg, const Args& args,
842 uint32_t stackArgAreaSizeUnaligned) {
843 auto callee = wasm::CalleeDesc::builtinInstanceMethod(builtin);
844 MWasmCallUncatchable* call = MWasmCallUncatchable::New(
845 alloc, desc, callee, args, stackArgAreaSizeUnaligned, nullptr);
846 if (!call) {
847 return nullptr;
848 }
849
850 MOZ_ASSERT(instanceArg != ABIArg());
851 call->instanceArg_ = instanceArg;
852 call->builtinMethodFailureMode_ = failureMode;
853 return call;
854 }
855
856 MWasmReturnCall* MWasmReturnCall::New(TempAllocator& alloc,
857 const wasm::CallSiteDesc& desc,
858 const wasm::CalleeDesc& callee,
859 const Args& args,
860 uint32_t stackArgAreaSizeUnaligned,
861 MDefinition* tableAddressOrRef) {
862 MWasmReturnCall* call =
863 new (alloc) MWasmReturnCall(desc, callee, stackArgAreaSizeUnaligned);
864
865 MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableAddressOrRef);
866 if (!call->initWithArgs(alloc, call, args, tableAddressOrRef)) {
867 return nullptr;
868 }
869
870 return call;
871 }
872
873 MIonToWasmCall* MIonToWasmCall::New(TempAllocator& alloc,
874 WasmInstanceObject* instanceObj,
875 const wasm::FuncExport& funcExport) {
876 const wasm::FuncType& funcType =
877 instanceObj->instance().codeMeta().getFuncType(funcExport.funcIndex());
878 const wasm::ValTypeVector& results = funcType.results();
879 MIRType resultType = MIRType::Value;
880 // At the JS boundary some wasm types must be represented as a Value, and in
881 // addition a void return requires an Undefined value.
882 if (results.length() > 0 && !results[0].isEncodedAsJSValueOnEscape()) {
883 MOZ_ASSERT(results.length() == 1,
884 "multiple returns not implemented for inlined Wasm calls");
885 resultType = results[0].toMIRType();
886 }
887
888 auto* ins = new (alloc) MIonToWasmCall(instanceObj, resultType, funcExport);
889 if (!ins->init(alloc, funcType.args().length())) {
890 return nullptr;
891 }
892 return ins;
893 }
894
895 #ifdef DEBUG
896 bool MIonToWasmCall::isConsistentFloat32Use(MUse* use) const {
897 const wasm::FuncType& funcType =
898 instance()->codeMeta().getFuncType(funcExport_.funcIndex());
899 return funcType.args()[use->index()].kind() == wasm::ValType::F32;
900 }
901 #endif
902
903 bool MWasmShiftSimd128::congruentTo(const MDefinition* ins) const {
904 if (!ins->isWasmShiftSimd128()) {
905 return false;
906 }
907 return ins->toWasmShiftSimd128()->simdOp() == simdOp_ &&
908 congruentIfOperandsEqual(ins);
909 }
910
911 bool MWasmShuffleSimd128::congruentTo(const MDefinition* ins) const {
912 if (!ins->isWasmShuffleSimd128()) {
913 return false;
914 }
915 return ins->toWasmShuffleSimd128()->shuffle().equals(&shuffle_) &&
916 congruentIfOperandsEqual(ins);
917 }
918
919 bool MWasmUnarySimd128::congruentTo(const MDefinition* ins) const {
920 if (!ins->isWasmUnarySimd128()) {
921 return false;
922 }
923 return ins->toWasmUnarySimd128()->simdOp() == simdOp_ &&
924 congruentIfOperandsEqual(ins);
925 }
926
927 #ifdef ENABLE_WASM_SIMD
928 MWasmShuffleSimd128* jit::BuildWasmShuffleSimd128(TempAllocator& alloc,
929 const int8_t* control,
930 MDefinition* lhs,
931 MDefinition* rhs) {
932 SimdShuffle s =
933 AnalyzeSimdShuffle(SimdConstant::CreateX16(control), lhs, rhs);
934 switch (s.opd) {
935 case SimdShuffle::Operand::LEFT:
936 // When SimdShuffle::Operand is LEFT the right operand is not used,
937 // lose reference to rhs.
938 rhs = lhs;
939 break;
940 case SimdShuffle::Operand::RIGHT:
941 // When SimdShuffle::Operand is RIGHT the left operand is not used,
942 // lose reference to lhs.
943 lhs = rhs;
944 break;
945 default:
946 break;
947 }
948 return MWasmShuffleSimd128::New(alloc, lhs, rhs, s);
949 }
950 #endif // ENABLE_WASM_SIMD
951
952 static MDefinition* FoldTrivialWasmTests(TempAllocator& alloc,
953 wasm::RefType sourceType,
954 wasm::RefType destType) {
955 // Upcasts are trivially valid.
956 if (wasm::RefType::isSubTypeOf(sourceType, destType)) {
957 return MConstant::New(alloc, Int32Value(1), MIRType::Int32);
958 }
959
960 // If two types are completely disjoint, then all casts between them are
961 // impossible.
962 if (!wasm::RefType::castPossible(destType, sourceType)) {
963 return MConstant::New(alloc, Int32Value(0), MIRType::Int32);
964 }
965
966 return nullptr;
967 }
968
969 static MDefinition* FoldTrivialWasmCasts(MDefinition* ref,
970 wasm::RefType sourceType,
971 wasm::RefType destType) {
972 // Upcasts are trivially valid.
973 if (wasm::RefType::isSubTypeOf(sourceType, destType)) {
974 return ref;
975 }
976
977 // We can't fold invalid casts to a trap instruction, because that will
978 // confuse GVN which assumes the folded to instruction has the same type
979 // as the original instruction.
980
981 return nullptr;
982 }
983
984 MDefinition* MWasmRefTestAbstract::foldsTo(TempAllocator& alloc) {
985 if (ref()->wasmRefType().isNothing()) {
986 return this;
987 }
988
989 MDefinition* folded =
990 FoldTrivialWasmTests(alloc, ref()->wasmRefType().value(), destType());
991 if (folded) {
992 return folded;
993 }
994 return this;
995 }
996
997 MDefinition* MWasmRefTestConcrete::foldsTo(TempAllocator& alloc) {
998 if (ref()->wasmRefType().isNothing()) {
999 return this;
1000 }
1001
1002 MDefinition* folded =
1003 FoldTrivialWasmTests(alloc, ref()->wasmRefType().value(), destType());
1004 if (folded) {
1005 return folded;
1006 }
1007 return this;
1008 }
1009
1010 MDefinition* MWasmRefCastAbstract::foldsTo(TempAllocator& alloc) {
1011 if (ref()->wasmRefType().isNothing()) {
1012 return this;
1013 }
1014
1015 MDefinition* folded =
1016 FoldTrivialWasmCasts(ref(), ref()->wasmRefType().value(), destType());
1017 if (folded) {
1018 return folded;
1019 }
1020 return this;
1021 }
1022
1023 MDefinition* MWasmRefCastConcrete::foldsTo(TempAllocator& alloc) {
1024 if (ref()->wasmRefType().isNothing()) {
1025 return this;
1026 }
1027
1028 MDefinition* folded =
1029 FoldTrivialWasmCasts(ref(), ref()->wasmRefType().value(), destType());
1030 if (folded) {
1031 return folded;
1032 }
1033 return this;
1034 }
1035
1036 MDefinition* MWasmRefAsNonNull::foldsTo(TempAllocator& alloc) {
1037 wasm::MaybeRefType inputType = ref()->wasmRefType();
1038 if (inputType.isSome() && !inputType.value().isNullable()) {
1039 return ref();
1040 }
1041 return this;
1042 }
1043
1044 bool MWasmStructState::init() {
1045 // Reserve the size for the number of fields.
1046 return fields_.resize(
1047 wasmStruct_->toWasmNewStructObject()->structType().fields_.length());
1048 }
1049
1050 MWasmStructState* MWasmStructState::New(TempAllocator& alloc,
1051 MDefinition* structObject) {
1052 MWasmStructState* state = new (alloc) MWasmStructState(alloc, structObject);
1053 if (!state->init()) {
1054 return nullptr;
1055 }
1056 return state;
1057 }
1058
1059 MWasmStructState* MWasmStructState::Copy(TempAllocator& alloc,
1060 MWasmStructState* state) {
1061 MDefinition* newWasmStruct = state->wasmStruct();
1062 MWasmStructState* res = new (alloc) MWasmStructState(alloc, newWasmStruct);
1063 if (!res || !res->init()) {
1064 return nullptr;
1065 }
1066 for (size_t i = 0; i < state->numFields(); i++) {
1067 res->setField(i, state->getField(i));
1068 }
1069 return res;
1070 }