Debian Codegraph @

js/src/jit/LIR.h

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 #ifndef jit_LIR_h
8 #define jit_LIR_h
9
10 // This file declares the core data structures for LIR: storage allocations for
11 // inputs and outputs, as well as the interface instructions must conform to.
12
13 #include "mozilla/Array.h"
14 #include "mozilla/Casting.h"
15
16 #include "jit/Bailouts.h"
17 #include "jit/FixedList.h"
18 #include "jit/InlineList.h"
19 #include "jit/JitAllocPolicy.h"
20 #include "jit/LIROpsGenerated.h"
21 #include "jit/MIR-wasm.h"
22 #include "jit/MIR.h"
23 #include "jit/MIRGraph.h"
24 #include "jit/Registers.h"
25 #include "jit/Safepoints.h"
26 #include "util/Memory.h"
27
28 namespace js {
29 namespace jit {
30
31 class LUse;
32 class LGeneralReg;
33 class LFloatReg;
34 class LStackSlot;
35 class LStackArea;
36 class LArgument;
37 class LConstantIndex;
38 class LInstruction;
39 class LNode;
40 class LDefinition;
41 class MBasicBlock;
42 class MIRGenerator;
43
44 static const uint32_t VREG_INCREMENT = 1;
45
46 static const uint32_t THIS_FRAME_ARGSLOT = 0;
47
48 #if defined(JS_NUNBOX32)
49 static const uint32_t BOX_PIECES = 2;
50 static const uint32_t VREG_TYPE_OFFSET = 0;
51 static const uint32_t VREG_DATA_OFFSET = 1;
52 static const uint32_t TYPE_INDEX = 0;
53 static const uint32_t PAYLOAD_INDEX = 1;
54 static const uint32_t INT64LOW_INDEX = 0;
55 static const uint32_t INT64HIGH_INDEX = 1;
56 #elif defined(JS_PUNBOX64)
57 static const uint32_t BOX_PIECES = 1;
58 #else
59 # error "Unknown!"
60 #endif
61
62 static const uint32_t INT64_PIECES = sizeof(int64_t) / sizeof(uintptr_t);
63
64 // Represents storage for an operand. For constants, the pointer is tagged
65 // with a single bit, and the untagged pointer is a pointer to a Value.
66 class LAllocation {
67 uintptr_t bits_;
68
69 // 3 bits gives us enough for an interesting set of Kinds and also fits
70 // within the alignment bits of pointers to Value, which are always
71 // 8-byte aligned.
72 static const uintptr_t KIND_BITS = 3;
73 static const uintptr_t KIND_SHIFT = 0;
74 static const uintptr_t KIND_MASK = (1 << KIND_BITS) - 1;
75
76 protected:
77 #ifdef JS_64BIT
78 static const uintptr_t DATA_BITS = sizeof(uint32_t) * 8;
79 #else
80 static const uintptr_t DATA_BITS = (sizeof(uint32_t) * 8) - KIND_BITS;
81 #endif
82 static const uintptr_t DATA_SHIFT = KIND_SHIFT + KIND_BITS;
83
84 public:
85 enum Kind {
86 CONSTANT_VALUE, // MConstant*.
87 CONSTANT_INDEX, // Constant arbitrary index.
88 USE, // Use of a virtual register, with physical allocation policy.
89 GPR, // General purpose register.
90 FPU, // Floating-point register.
91 STACK_SLOT, // Stack slot.
92 STACK_AREA, // Stack area.
93 ARGUMENT_SLOT // Argument slot.
94 };
95
96 static const uintptr_t DATA_MASK = (uintptr_t(1) << DATA_BITS) - 1;
97
98 protected:
99 uint32_t data() const {
100 MOZ_ASSERT(!hasIns());
101 return mozilla::AssertedCast<uint32_t>(bits_ >> DATA_SHIFT);
102 }
103 void setData(uintptr_t data) {
104 MOZ_ASSERT(!hasIns());
105 MOZ_ASSERT(data <= DATA_MASK);
106 bits_ &= ~(DATA_MASK << DATA_SHIFT);
107 bits_ |= (data << DATA_SHIFT);
108 }
109 void setKindAndData(Kind kind, uintptr_t data) {
110 MOZ_ASSERT(data <= DATA_MASK);
111 bits_ = (uintptr_t(kind) << KIND_SHIFT) | data << DATA_SHIFT;
112 MOZ_ASSERT(!hasIns());
113 }
114
115 bool hasIns() const { return isStackArea(); }
116 const LInstruction* ins() const {
117 MOZ_ASSERT(hasIns());
118 return reinterpret_cast<const LInstruction*>(bits_ &
119 ~(KIND_MASK << KIND_SHIFT));
120 }
121 LInstruction* ins() {
122 MOZ_ASSERT(hasIns());
123 return reinterpret_cast<LInstruction*>(bits_ & ~(KIND_MASK << KIND_SHIFT));
124 }
125 void setKindAndIns(Kind kind, LInstruction* ins) {
126 uintptr_t data = reinterpret_cast<uintptr_t>(ins);
127 MOZ_ASSERT((data & (KIND_MASK << KIND_SHIFT)) == 0);
128 bits_ = data | (uintptr_t(kind) << KIND_SHIFT);
129 MOZ_ASSERT(hasIns());
130 }
131
132 LAllocation(Kind kind, uintptr_t data) { setKindAndData(kind, data); }
133 LAllocation(Kind kind, LInstruction* ins) { setKindAndIns(kind, ins); }
134 explicit LAllocation(Kind kind) { setKindAndData(kind, 0); }
135
136 public:
137 LAllocation() : bits_(0) { MOZ_ASSERT(isBogus()); }
138
139 // The MConstant pointer must have its low bits cleared.
140 explicit LAllocation(const MConstant* c) {
141 MOZ_ASSERT(c);
142 bits_ = uintptr_t(c);
143 MOZ_ASSERT((bits_ & (KIND_MASK << KIND_SHIFT)) == 0);
144 bits_ |= CONSTANT_VALUE << KIND_SHIFT;
145 }
146 inline explicit LAllocation(AnyRegister reg);
147
148 Kind kind() const { return (Kind)((bits_ >> KIND_SHIFT) & KIND_MASK); }
149
150 bool isBogus() const { return bits_ == 0; }
151 bool isUse() const { return kind() == USE; }
152 bool isConstant() const { return isConstantValue() || isConstantIndex(); }
153 bool isConstantValue() const { return kind() == CONSTANT_VALUE; }
154 bool isConstantIndex() const { return kind() == CONSTANT_INDEX; }
155 bool isGeneralReg() const { return kind() == GPR; }
156 bool isFloatReg() const { return kind() == FPU; }
157 bool isStackSlot() const { return kind() == STACK_SLOT; }
158 bool isStackArea() const { return kind() == STACK_AREA; }
159 bool isArgument() const { return kind() == ARGUMENT_SLOT; }
160 bool isAnyRegister() const { return isGeneralReg() || isFloatReg(); }
161 bool isMemory() const { return isStackSlot() || isArgument(); }
162 inline uint32_t memorySlot() const;
163 inline LUse* toUse();
164 inline const LUse* toUse() const;
165 inline const LGeneralReg* toGeneralReg() const;
166 inline const LFloatReg* toFloatReg() const;
167 inline const LStackSlot* toStackSlot() const;
168 inline LStackArea* toStackArea();
169 inline const LStackArea* toStackArea() const;
170 inline const LArgument* toArgument() const;
171 inline const LConstantIndex* toConstantIndex() const;
172 inline AnyRegister toAnyRegister() const;
173
174 const MConstant* toConstant() const {
175 MOZ_ASSERT(isConstantValue());
176 return reinterpret_cast<const MConstant*>(bits_ &
177 ~(KIND_MASK << KIND_SHIFT));
178 }
179
180 bool operator==(const LAllocation& other) const {
181 return bits_ == other.bits_;
182 }
183
184 bool operator!=(const LAllocation& other) const {
185 return bits_ != other.bits_;
186 }
187
188 HashNumber hash() const { return bits_; }
189
190 uintptr_t asRawBits() const { return bits_; }
191
192 bool aliases(const LAllocation& other) const;
193
194 #ifdef JS_JITSPEW
195 UniqueChars toString() const;
196 void dump() const;
197 #endif
198 };
199
200 class LUse : public LAllocation {
201 static const uint32_t POLICY_BITS = 3;
202 static const uint32_t POLICY_SHIFT = 0;
203 static const uint32_t POLICY_MASK = (1 << POLICY_BITS) - 1;
204 #ifdef JS_CODEGEN_ARM64
205 static const uint32_t REG_BITS = 7;
206 #else
207 static const uint32_t REG_BITS = 6;
208 #endif
209 static const uint32_t REG_SHIFT = POLICY_SHIFT + POLICY_BITS;
210 static const uint32_t REG_MASK = (1 << REG_BITS) - 1;
211
212 // Whether the physical register for this operand may be reused for a def.
213 static const uint32_t USED_AT_START_BITS = 1;
214 static const uint32_t USED_AT_START_SHIFT = REG_SHIFT + REG_BITS;
215 static const uint32_t USED_AT_START_MASK = (1 << USED_AT_START_BITS) - 1;
216
217 // The REG field will hold the register code for any Register or
218 // FloatRegister, though not for an AnyRegister.
219 static_assert(std::max(Registers::Total, FloatRegisters::Total) <=
220 REG_MASK + 1,
221 "The field must be able to represent any register code");
222
223 public:
224 // Virtual registers get the remaining bits.
225 static const uint32_t VREG_BITS =
226 DATA_BITS - (USED_AT_START_SHIFT + USED_AT_START_BITS);
227 static const uint32_t VREG_SHIFT = USED_AT_START_SHIFT + USED_AT_START_BITS;
228 static const uint32_t VREG_MASK = (1 << VREG_BITS) - 1;
229
230 enum Policy {
231 // Input should be in a read-only register or stack slot.
232 ANY,
233
234 // Input must be in a read-only register.
235 REGISTER,
236
237 // Input must be in a specific, read-only register.
238 FIXED,
239
240 // Keep the used virtual register alive, and use whatever allocation is
241 // available. This is similar to ANY but hints to the register allocator
242 // that it is never useful to optimize this site.
243 KEEPALIVE,
244
245 // Input must be allocated on the stack. Only used when extracting stack
246 // results from stack result areas.
247 STACK,
248
249 // For snapshot inputs, indicates that the associated instruction will
250 // write this input to its output register before bailing out.
251 // The register allocator may thus allocate that output register, and
252 // does not need to keep the virtual register alive (alternatively,
253 // this may be treated as KEEPALIVE).
254 RECOVERED_INPUT
255 };
256
257 void set(Policy policy, uint32_t reg, bool usedAtStart) {
258 MOZ_ASSERT(reg <= REG_MASK, "Register code must fit in field");
259 setKindAndData(USE, (policy << POLICY_SHIFT) | (reg << REG_SHIFT) |
260 ((usedAtStart ? 1 : 0) << USED_AT_START_SHIFT));
261 }
262
263 public:
264 LUse(uint32_t vreg, Policy policy, bool usedAtStart = false) {
265 set(policy, 0, usedAtStart);
266 setVirtualRegister(vreg);
267 }
268 explicit LUse(Policy policy, bool usedAtStart = false) {
269 set(policy, 0, usedAtStart);
270 }
271 explicit LUse(Register reg, bool usedAtStart = false) {
272 set(FIXED, reg.code(), usedAtStart);
273 }
274 explicit LUse(FloatRegister reg, bool usedAtStart = false) {
275 set(FIXED, reg.code(), usedAtStart);
276 }
277 LUse(Register reg, uint32_t virtualRegister, bool usedAtStart = false) {
278 set(FIXED, reg.code(), usedAtStart);
279 setVirtualRegister(virtualRegister);
280 }
281 LUse(FloatRegister reg, uint32_t virtualRegister, bool usedAtStart = false) {
282 set(FIXED, reg.code(), usedAtStart);
283 setVirtualRegister(virtualRegister);
284 }
285
286 void setVirtualRegister(uint32_t index) {
287 MOZ_ASSERT(index < VREG_MASK);
288
289 uint32_t old = data() & ~(VREG_MASK << VREG_SHIFT);
290 setData(old | (index << VREG_SHIFT));
291 }
292
293 Policy policy() const {
294 Policy policy = (Policy)((data() >> POLICY_SHIFT) & POLICY_MASK);
295 return policy;
296 }
297 uint32_t virtualRegister() const {
298 uint32_t index = (data() >> VREG_SHIFT) & VREG_MASK;
299 MOZ_ASSERT(index != 0);
300 return index;
301 }
302 uint32_t registerCode() const {
303 MOZ_ASSERT(policy() == FIXED);
304 return (data() >> REG_SHIFT) & REG_MASK;
305 }
306 bool isFixedRegister() const { return policy() == FIXED; }
307 bool usedAtStart() const {
308 return !!((data() >> USED_AT_START_SHIFT) & USED_AT_START_MASK);
309 }
310 };
311
312 static const uint32_t MAX_VIRTUAL_REGISTERS = LUse::VREG_MASK;
313
314 class LBoxAllocation {
315 #ifdef JS_NUNBOX32
316 LAllocation type_;
317 LAllocation payload_;
318 #else
319 LAllocation value_;
320 #endif
321
322 public:
323 #ifdef JS_NUNBOX32
324 LBoxAllocation(LAllocation type, LAllocation payload)
325 : type_(type), payload_(payload) {}
326
327 LAllocation type() const { return type_; }
328 LAllocation payload() const { return payload_; }
329 #else
330 explicit LBoxAllocation(LAllocation value) : value_(value) {}
331
332 LAllocation value() const { return value_; }
333 #endif
334 };
335
336 template <class ValT>
337 class LInt64Value {
338 #if JS_BITS_PER_WORD == 32
339 ValT high_;
340 ValT low_;
341 #else
342 ValT value_;
343 #endif
344
345 public:
346 LInt64Value() = default;
347
348 #if JS_BITS_PER_WORD == 32
349 LInt64Value(ValT high, ValT low) : high_(high), low_(low) {}
350
351 ValT high() const { return high_; }
352 ValT low() const { return low_; }
353
354 const ValT* pointerHigh() const { return &high_; }
355 const ValT* pointerLow() const { return &low_; }
356 #else
357 explicit LInt64Value(ValT value) : value_(value) {}
358
359 ValT value() const { return value_; }
360 const ValT* pointer() const { return &value_; }
361 #endif
362 };
363
364 using LInt64Allocation = LInt64Value<LAllocation>;
365
366 class LGeneralReg : public LAllocation {
367 public:
368 explicit LGeneralReg(Register reg) : LAllocation(GPR, reg.code()) {}
369
370 Register reg() const { return Register::FromCode(data()); }
371 };
372
373 class LFloatReg : public LAllocation {
374 public:
375 explicit LFloatReg(FloatRegister reg) : LAllocation(FPU, reg.code()) {}
376
377 FloatRegister reg() const { return FloatRegister::FromCode(data()); }
378 };
379
380 // Arbitrary constant index.
381 class LConstantIndex : public LAllocation {
382 explicit LConstantIndex(uint32_t index)
383 : LAllocation(CONSTANT_INDEX, index) {}
384
385 public:
386 static LConstantIndex FromIndex(uint32_t index) {
387 return LConstantIndex(index);
388 }
389
390 uint32_t index() const { return data(); }
391 };
392
393 // Stack slots are indices into the stack. The indices are byte indices.
394 class LStackSlot : public LAllocation {
395 // Stack slots are aligned to 32-bit word boundaries.
396 static constexpr uint32_t SLOT_ALIGNMENT = 4;
397
398 // Stack slot width is stored in the two least significant bits.
399 static constexpr uint32_t WIDTH_MASK = SLOT_ALIGNMENT - 1;
400
401 // Remaining bits hold the stack slot offset.
402 static constexpr uint32_t SLOT_MASK = ~WIDTH_MASK;
403
404 public:
405 enum Width {
406 Word,
407 DoubleWord,
408 QuadWord,
409 };
410
411 class SlotAndWidth {
412 uint32_t data_;
413
414 explicit SlotAndWidth(uint32_t data) : data_(data) {}
415
416 public:
417 static SlotAndWidth fromData(uint32_t data) { return SlotAndWidth(data); }
418
419 explicit SlotAndWidth(uint32_t slot, Width width) {
420 MOZ_ASSERT(slot % SLOT_ALIGNMENT == 0);
421 MOZ_ASSERT(uint32_t(width) < SLOT_ALIGNMENT);
422 data_ = slot | uint32_t(width);
423 }
424 uint32_t data() const { return data_; }
425 uint32_t slot() const { return data_ & SLOT_MASK; }
426 Width width() const { return Width(data_ & WIDTH_MASK); }
427 };
428
429 static constexpr uint32_t MAX_SLOT =
430 (uint64_t(1) << LAllocation::DATA_BITS) - 1;
431
432 explicit LStackSlot(SlotAndWidth slotAndWidth)
433 : LAllocation(STACK_SLOT, slotAndWidth.data()) {}
434
435 LStackSlot(uint32_t slot, Width width)
436 : LStackSlot(SlotAndWidth(slot, width)) {}
437
438 uint32_t slot() const { return SlotAndWidth::fromData(data()).slot(); }
439 Width width() const { return SlotAndWidth::fromData(data()).width(); }
440
441 // |Type| is LDefinition::Type, but can't forward declare a nested definition.
442 template <typename Type>
443 static Width width(Type type);
444
445 static uint32_t ByteWidth(Width width) {
446 switch (width) {
447 case Width::Word:
448 return 4;
449 case Width::DoubleWord:
450 return 8;
451 case Width::QuadWord:
452 return 16;
453 }
454 MOZ_CRASH("invalid width");
455 }
456 };
457
458 // Stack area indicates a contiguous stack allocation meant to receive call
459 // results that don't fit in registers.
460 class LStackArea : public LAllocation {
461 public:
462 explicit LStackArea(LInstruction* stackArea)
463 : LAllocation(STACK_AREA, stackArea) {}
464
465 // Byte index of base of stack area, in the same coordinate space as
466 // LStackSlot::slot().
467 inline uint32_t base() const;
468 inline void setBase(uint32_t base);
469
470 // Size in bytes of the stack area.
471 inline uint32_t size() const;
472 inline uint32_t alignment() const { return 8; }
473
474 class ResultIterator {
475 const LStackArea& alloc_;
476 uint32_t idx_;
477
478 public:
479 explicit ResultIterator(const LStackArea& alloc) : alloc_(alloc), idx_(0) {}
480
481 inline bool done() const;
482 inline void next();
483 inline LAllocation alloc() const;
484 inline bool isWasmAnyRef() const;
485
486 explicit operator bool() const { return !done(); }
487 };
488
489 ResultIterator results() const { return ResultIterator(*this); }
490
491 inline LStackSlot resultAlloc(LInstruction* lir, LDefinition* def) const;
492 };
493
494 // Arguments are reverse indices into the stack. The indices are byte indices.
495 class LArgument : public LAllocation {
496 public:
497 explicit LArgument(uint32_t index) : LAllocation(ARGUMENT_SLOT, index) {}
498
499 uint32_t index() const { return data(); }
500 };
501
502 inline uint32_t LAllocation::memorySlot() const {
503 MOZ_ASSERT(isMemory());
504 return isStackSlot() ? toStackSlot()->slot() : toArgument()->index();
505 }
506
507 // Represents storage for a definition.
508 class LDefinition {
509 // Bits containing policy, type, and virtual register.
510 uint32_t bits_;
511
512 // Before register allocation, this optionally contains a fixed policy.
513 // Register allocation assigns this field to a physical policy if none is
514 // fixed.
515 //
516 // Right now, pre-allocated outputs are limited to the following:
517 // * Physical argument stack slots.
518 // * Physical registers.
519 LAllocation output_;
520
521 static const uint32_t TYPE_BITS = 4;
522 static const uint32_t TYPE_SHIFT = 0;
523 static const uint32_t TYPE_MASK = (1 << TYPE_BITS) - 1;
524 static const uint32_t POLICY_BITS = 2;
525 static const uint32_t POLICY_SHIFT = TYPE_SHIFT + TYPE_BITS;
526 static const uint32_t POLICY_MASK = (1 << POLICY_BITS) - 1;
527
528 static const uint32_t VREG_BITS =
529 (sizeof(uint32_t) * 8) - (POLICY_BITS + TYPE_BITS);
530 static const uint32_t VREG_SHIFT = POLICY_SHIFT + POLICY_BITS;
531 static const uint32_t VREG_MASK = (1 << VREG_BITS) - 1;
532
533 public:
534 // Note that definitions, by default, are always allocated a register,
535 // unless the policy specifies that an input can be re-used and that input
536 // is a stack slot.
537 enum Policy {
538 // The policy is predetermined by the LAllocation attached to this
539 // definition. The allocation may be:
540 // * A register, which may not appear as any fixed temporary.
541 // * A stack slot or argument.
542 //
543 // Register allocation will not modify a fixed allocation.
544 FIXED,
545
546 // A random register of an appropriate class will be assigned.
547 REGISTER,
548
549 // An area on the stack must be assigned. Used when defining stack results
550 // and stack result areas.
551 STACK,
552
553 // One definition per instruction must re-use the first input
554 // allocation, which (for now) must be a register.
555 MUST_REUSE_INPUT
556 };
557
558 enum Type {
559 GENERAL, // Generic, integer or pointer-width data (GPR).
560 INT32, // int32 data (GPR).
561 OBJECT, // Pointer that may be collected as garbage (GPR).
562 SLOTS, // Slots/elements/wasm array data pointer that may be moved by minor
563 // GCs (GPR).
564 WASM_ANYREF, // Tagged pointer that may be collected as garbage (GPR).
565 FLOAT32, // 32-bit floating-point value (FPU).
566 DOUBLE, // 64-bit floating-point value (FPU).
567 SIMD128, // 128-bit SIMD vector (FPU).
568 STACKRESULTS, // A variable-size stack allocation that may contain objects.
569 #ifdef JS_NUNBOX32
570 // A type virtual register must be followed by a payload virtual
571 // register, as both will be tracked as a single gcthing.
572 TYPE,
573 PAYLOAD
574 #else
575 BOX // Joined box, for punbox systems. (GPR, gcthing)
576 #endif
577 };
578
579 void set(uint32_t index, Type type, Policy policy) {
580 static_assert(MAX_VIRTUAL_REGISTERS <= VREG_MASK);
581 bits_ =
582 (index << VREG_SHIFT) | (policy << POLICY_SHIFT) | (type << TYPE_SHIFT);
583 #ifndef ENABLE_WASM_SIMD
584 MOZ_ASSERT(this->type() != SIMD128);
585 #endif
586 }
587
588 public:
589 LDefinition(uint32_t index, Type type, Policy policy = REGISTER) {
590 set(index, type, policy);
591 }
592
593 explicit LDefinition(Type type, Policy policy = REGISTER) {
594 set(0, type, policy);
595 }
596
597 LDefinition(Type type, const LAllocation& a) : output_(a) {
598 set(0, type, FIXED);
599 }
600
601 LDefinition(uint32_t index, Type type, const LAllocation& a) : output_(a) {
602 set(index, type, FIXED);
603 }
604
605 LDefinition() : bits_(0) { MOZ_ASSERT(isBogusTemp()); }
606
607 static LDefinition BogusTemp() { return LDefinition(); }
608
609 Policy policy() const {
610 return (Policy)((bits_ >> POLICY_SHIFT) & POLICY_MASK);
611 }
612 Type type() const { return (Type)((bits_ >> TYPE_SHIFT) & TYPE_MASK); }
613
614 static bool isFloatRegCompatible(Type type, FloatRegister reg) {
615 #ifdef JS_CODEGEN_RISCV64
616 if (type == FLOAT32 || type == DOUBLE) {
617 return reg.isSingle() || reg.isDouble();
618 }
619 #else
620 if (type == FLOAT32) {
621 return reg.isSingle();
622 }
623 if (type == DOUBLE) {
624 return reg.isDouble();
625 }
626 #endif
627 MOZ_ASSERT(type == SIMD128);
628 return reg.isSimd128();
629 }
630
631 bool isCompatibleReg(const AnyRegister& r) const {
632 if (isFloatReg() && r.isFloat()) {
633 return isFloatRegCompatible(type(), r.fpu());
634 }
635 return !isFloatReg() && !r.isFloat();
636 }
637 bool isCompatibleDef(const LDefinition& other) const {
638 #if defined(JS_CODEGEN_ARM)
639 if (isFloatReg() && other.isFloatReg()) {
640 return type() == other.type();
641 }
642 return !isFloatReg() && !other.isFloatReg();
643 #else
644 return isFloatReg() == other.isFloatReg();
645 #endif
646 }
647
648 static bool isFloatReg(Type type) {
649 return type == FLOAT32 || type == DOUBLE || type == SIMD128;
650 }
651 bool isFloatReg() const { return isFloatReg(type()); }
652
653 uint32_t virtualRegister() const {
654 uint32_t index = (bits_ >> VREG_SHIFT) & VREG_MASK;
655 // MOZ_ASSERT(index != 0);
656 return index;
657 }
658 LAllocation* output() { return &output_; }
659 const LAllocation* output() const { return &output_; }
660 bool isFixed() const { return policy() == FIXED; }
661 bool isBogusTemp() const { return isFixed() && output()->isBogus(); }
662 void setVirtualRegister(uint32_t index) {
663 MOZ_ASSERT(index < VREG_MASK);
664 bits_ &= ~(VREG_MASK << VREG_SHIFT);
665 bits_ |= index << VREG_SHIFT;
666 }
667 void setOutput(const LAllocation& a) {
668 output_ = a;
669 if (!a.isUse()) {
670 bits_ &= ~(POLICY_MASK << POLICY_SHIFT);
671 bits_ |= FIXED << POLICY_SHIFT;
672 }
673 }
674 void setReusedInput(uint32_t operand) {
675 output_ = LConstantIndex::FromIndex(operand);
676 }
677 uint32_t getReusedInput() const {
678 MOZ_ASSERT(policy() == LDefinition::MUST_REUSE_INPUT);
679 return output_.toConstantIndex()->index();
680 }
681
682 // Returns true if this definition should be added to safepoints for GC
683 // tracing. This includes Value type tags on 32-bit and slots/elements
684 // pointers.
685 inline bool isSafepointGCType(LNode* ins) const;
686
687 static inline Type TypeFrom(MIRType type) {
688 switch (type) {
689 case MIRType::Boolean:
690 case MIRType::Int32:
691 // The stack slot allocator doesn't currently support allocating
692 // 1-byte slots, so for now we lower MIRType::Boolean into INT32.
693 static_assert(sizeof(bool) <= sizeof(int32_t),
694 "bool doesn't fit in an int32 slot");
695 return LDefinition::INT32;
696 case MIRType::String:
697 case MIRType::Symbol:
698 case MIRType::BigInt:
699 case MIRType::Object:
700 return LDefinition::OBJECT;
701 case MIRType::Double:
702 return LDefinition::DOUBLE;
703 case MIRType::Float32:
704 return LDefinition::FLOAT32;
705 #if defined(JS_PUNBOX64)
706 case MIRType::Value:
707 return LDefinition::BOX;
708 #endif
709 case MIRType::Slots:
710 case MIRType::Elements:
711 case MIRType::WasmArrayData:
712 return LDefinition::SLOTS;
713 case MIRType::WasmAnyRef:
714 return LDefinition::WASM_ANYREF;
715 case MIRType::Pointer:
716 case MIRType::IntPtr:
717 return LDefinition::GENERAL;
718 #if defined(JS_PUNBOX64)
719 case MIRType::Int64:
720 return LDefinition::GENERAL;
721 #endif
722 case MIRType::StackResults:
723 return LDefinition::STACKRESULTS;
724 case MIRType::Simd128:
725 return LDefinition::SIMD128;
726 default:
727 MOZ_CRASH("unexpected type");
728 }
729 }
730
731 UniqueChars toString() const;
732
733 #ifdef JS_JITSPEW
734 void dump() const;
735 #endif
736 };
737
738 class LInt64Definition : public LInt64Value<LDefinition> {
739 public:
740 using LInt64Value<LDefinition>::LInt64Value;
741
742 static LInt64Definition BogusTemp() { return LInt64Definition(); }
743
744 bool isBogusTemp() const {
745 #if JS_BITS_PER_WORD == 32
746 MOZ_ASSERT(high().isBogusTemp() == low().isBogusTemp());
747 return high().isBogusTemp();
748 #else
749 return value().isBogusTemp();
750 #endif
751 }
752 };
753
754 template <>
755 inline LStackSlot::Width LStackSlot::width(LDefinition::Type type) {
756 switch (type) {
757 #if JS_BITS_PER_WORD == 32
758 case LDefinition::GENERAL:
759 case LDefinition::OBJECT:
760 case LDefinition::SLOTS:
761 case LDefinition::WASM_ANYREF:
762 #endif
763 #ifdef JS_NUNBOX32
764 case LDefinition::TYPE:
765 case LDefinition::PAYLOAD:
766 #endif
767 case LDefinition::INT32:
768 case LDefinition::FLOAT32:
769 return LStackSlot::Word;
770 #if JS_BITS_PER_WORD == 64
771 case LDefinition::GENERAL:
772 case LDefinition::OBJECT:
773 case LDefinition::SLOTS:
774 case LDefinition::WASM_ANYREF:
775 #endif
776 #ifdef JS_PUNBOX64
777 case LDefinition::BOX:
778 #endif
779 case LDefinition::DOUBLE:
780 return LStackSlot::DoubleWord;
781 case LDefinition::SIMD128:
782 return LStackSlot::QuadWord;
783 case LDefinition::STACKRESULTS:
784 MOZ_CRASH("Stack results area must be allocated manually");
785 }
786 MOZ_CRASH("Unknown slot type");
787 }
788
789 // Forward declarations of LIR types.
790 #define LIROP(op) class L##op;
791 LIR_OPCODE_LIST(LIROP)
792 #undef LIROP
793
794 class LSnapshot;
795 class LSafepoint;
796 class LElementVisitor;
797
798 constexpr size_t MaxNumLInstructionOperands = 63;
799
800 // The common base class for LPhi and LInstruction.
801 class LNode {
802 protected:
803 MDefinition* mir_;
804
805 private:
806 LBlock* block_;
807 uint32_t id_;
808
809 protected:
810 // Bitfields below are all uint32_t to make sure MSVC packs them correctly.
811 uint32_t op_ : 10;
812 uint32_t isCall_ : 1;
813
814 // LPhi::numOperands() may not fit in this bitfield, so we only use this
815 // field for LInstruction.
816 uint32_t nonPhiNumOperands_ : 6;
817 static_assert((1 << 6) - 1 == MaxNumLInstructionOperands,
818 "packing constraints");
819
820 // For LInstruction, the first operand is stored at offset
821 // sizeof(LInstruction) + nonPhiOperandsOffset_ * sizeof(uintptr_t).
822 uint32_t nonPhiOperandsOffset_ : 5;
823 uint32_t numDefs_ : 4;
824 uint32_t numTemps_ : 4;
825
826 public:
827 enum class Opcode {
828 #define LIROP(name) name,
829 LIR_OPCODE_LIST(LIROP)
830 #undef LIROP
831 Invalid
832 };
833
834 LNode(Opcode op, uint32_t nonPhiNumOperands, uint32_t numDefs,
835 uint32_t numTemps)
836 : mir_(nullptr),
837 block_(nullptr),
838 id_(0),
839 op_(uint32_t(op)),
840 isCall_(false),
841 nonPhiNumOperands_(nonPhiNumOperands),
842 nonPhiOperandsOffset_(0),
843 numDefs_(numDefs),
844 numTemps_(numTemps) {
845 MOZ_ASSERT(op < Opcode::Invalid);
846 MOZ_ASSERT(op_ == uint32_t(op), "opcode must fit in bitfield");
847 MOZ_ASSERT(nonPhiNumOperands_ == nonPhiNumOperands,
848 "nonPhiNumOperands must fit in bitfield");
849 MOZ_ASSERT(numDefs_ == numDefs, "numDefs must fit in bitfield");
850 MOZ_ASSERT(numTemps_ == numTemps, "numTemps must fit in bitfield");
851 }
852
853 const char* opName() {
854 switch (op()) {
855 #define LIR_NAME_INS(name) \
856 case Opcode::name: \
857 return #name;
858 LIR_OPCODE_LIST(LIR_NAME_INS)
859 #undef LIR_NAME_INS
860 default:
861 MOZ_CRASH("Invalid op");
862 }
863 }
864
865 // Hook for opcodes to add extra high level detail about what code will be
866 // emitted for the op.
867 private:
868 const char* extraName() const { return nullptr; }
869
870 public:
871 #ifdef JS_JITSPEW
872 const char* getExtraName() const;
873 #endif
874
875 Opcode op() const { return Opcode(op_); }
876
877 bool isInstruction() const { return op() != Opcode::Phi; }
878 inline LInstruction* toInstruction();
879 inline const LInstruction* toInstruction() const;
880
881 // Returns the number of outputs of this instruction. If an output is
882 // unallocated, it is an LDefinition, defining a virtual register.
883 size_t numDefs() const { return numDefs_; }
884
885 bool isCall() const { return isCall_; }
886
887 // Does this call preserve the given register?
888 // By default, it is assumed that all registers are clobbered by a call.
889 inline bool isCallPreserved(AnyRegister reg) const;
890
891 uint32_t id() const { return id_; }
892 void setId(uint32_t id) {
893 MOZ_ASSERT(!id_);
894 MOZ_ASSERT(id);
895 id_ = id;
896 }
897 void setMir(MDefinition* mir) { mir_ = mir; }
898 MDefinition* mirRaw() const {
899 /* Untyped MIR for this op. Prefer mir() methods in subclasses. */
900 return mir_;
901 }
902 LBlock* block() const { return block_; }
903 void setBlock(LBlock* block) { block_ = block; }
904
905 // For an instruction which has a MUST_REUSE_INPUT output, whether that
906 // output register will be restored to its original value when bailing out.
907 inline bool recoversInput() const;
908
909 #ifdef JS_JITSPEW
910 void dump(GenericPrinter& out);
911 void dump();
912 static void printName(GenericPrinter& out, Opcode op);
913 void printName(GenericPrinter& out);
914 void printOperands(GenericPrinter& out);
915 #endif
916
917 public:
918 // Opcode testing and casts.
919 #define LIROP(name) \
920 bool is##name() const { return op() == Opcode::name; } \
921 inline L##name* to##name(); \
922 inline const L##name* to##name() const;
923 LIR_OPCODE_LIST(LIROP)
924 #undef LIROP
925
926 // Note: GenerateOpcodeFiles.py generates LIROpsGenerated.h based on this
927 // macro.
928 #define LIR_HEADER(opcode) \
929 static constexpr LNode::Opcode classOpcode = LNode::Opcode::opcode;
930 };
931
932 extern const char* const LIROpNames[];
933 inline const char* LIRCodeName(LNode::Opcode op) {
934 return LIROpNames[static_cast<size_t>(op)];
935 }
936
937 class LInstruction : public LNode,
938 public TempObject,
939 public InlineListNode<LInstruction> {
940 // This snapshot could be set after a ResumePoint. It is used to restart
941 // from the resume point pc.
942 LSnapshot* snapshot_;
943
944 // Structure capturing the set of stack slots and registers which are known
945 // to hold either gcthings or Values.
946 LSafepoint* safepoint_;
947
948 LMoveGroup* inputMoves_;
949 LMoveGroup* fixReuseMoves_;
950 LMoveGroup* movesAfter_;
951
952 protected:
953 LInstruction(Opcode opcode, uint32_t numOperands, uint32_t numDefs,
954 uint32_t numTemps)
955 : LNode(opcode, numOperands, numDefs, numTemps),
956 snapshot_(nullptr),
957 safepoint_(nullptr),
958 inputMoves_(nullptr),
959 fixReuseMoves_(nullptr),
960 movesAfter_(nullptr) {}
961
962 void setIsCall() { isCall_ = true; }
963
964 public:
965 inline LDefinition* getDef(size_t index);
966
967 void setDef(size_t index, const LDefinition& def) { *getDef(index) = def; }
968
969 LAllocation* getOperand(size_t index) const {
970 MOZ_ASSERT(index < numOperands());
971 MOZ_ASSERT(nonPhiOperandsOffset_ > 0);
972 uintptr_t p = reinterpret_cast<uintptr_t>(this + 1) +
973 nonPhiOperandsOffset_ * sizeof(uintptr_t);
974 return reinterpret_cast<LAllocation*>(p) + index;
975 }
976 void setOperand(size_t index, const LAllocation& a) {
977 *getOperand(index) = a;
978 }
979
980 LBoxAllocation getBoxOperand(size_t index) const {
981 #ifdef JS_NUNBOX32
982 return LBoxAllocation(*getOperand(index + TYPE_INDEX),
983 *getOperand(index + PAYLOAD_INDEX));
984 #else
985 return LBoxAllocation(*getOperand(index));
986 #endif
987 }
988
989 void initOperandsOffset(size_t offset) {
990 MOZ_ASSERT(nonPhiOperandsOffset_ == 0);
991 MOZ_ASSERT(offset >= sizeof(LInstruction));
992 MOZ_ASSERT(((offset - sizeof(LInstruction)) % sizeof(uintptr_t)) == 0);
993 offset = (offset - sizeof(LInstruction)) / sizeof(uintptr_t);
994 nonPhiOperandsOffset_ = offset;
995 MOZ_ASSERT(nonPhiOperandsOffset_ == offset, "offset must fit in bitfield");
996 }
997
998 void changePolicyOfReusedInputToAny(LDefinition* def) {
999 // MUST_REUSE_INPUT is implemented by allocating an output register and
1000 // moving the input to it. Register hints are used to avoid unnecessary
1001 // moves. We give the input an LUse::ANY policy to avoid requiring a
1002 // register for the input.
1003 MOZ_ASSERT(def->policy() == LDefinition::MUST_REUSE_INPUT);
1004 LUse* inputUse = getOperand(def->getReusedInput())->toUse();
1005 MOZ_ASSERT(inputUse->policy() == LUse::REGISTER);
1006 MOZ_ASSERT(inputUse->usedAtStart());
1007 *inputUse = LUse(inputUse->virtualRegister(), LUse::ANY,
1008 /* usedAtStart = */ true);
1009 }
1010
1011 // Returns information about temporary registers needed. Each temporary
1012 // register is an LDefinition with a fixed or virtual register and
1013 // either GENERAL, FLOAT32, or DOUBLE type.
1014 size_t numTemps() const { return numTemps_; }
1015 inline LDefinition* getTemp(size_t index);
1016
1017 LSnapshot* snapshot() const { return snapshot_; }
1018 LSafepoint* safepoint() const { return safepoint_; }
1019 LMoveGroup* inputMoves() const { return inputMoves_; }
1020 void setInputMoves(LMoveGroup* moves) { inputMoves_ = moves; }
1021 LMoveGroup* fixReuseMoves() const { return fixReuseMoves_; }
1022 void setFixReuseMoves(LMoveGroup* moves) { fixReuseMoves_ = moves; }
1023 LMoveGroup* movesAfter() const { return movesAfter_; }
1024 void setMovesAfter(LMoveGroup* moves) { movesAfter_ = moves; }
1025 uint32_t numOperands() const { return nonPhiNumOperands_; }
1026 void assignSnapshot(LSnapshot* snapshot);
1027 void initSafepoint(TempAllocator& alloc);
1028
1029 // InputIter iterates over all operands including snapshot inputs.
1030 // NonSnapshotInputIter does not include snapshot inputs.
1031 //
1032 // There can be many snapshot inputs and these are always KEEPALIVE uses or
1033 // constants. NonSnapshotInputIter can be used in places where we're not
1034 // interested in those.
1035 template <bool WithSnapshotUses>
1036 class InputIterImpl;
1037 using InputIter = InputIterImpl<true>;
1038 using NonSnapshotInputIter = InputIterImpl<false>;
1039
1040 // Iterators for an instruction's outputs and temps. These skip BogusTemp
1041 // definitions.
1042 template <bool Temps>
1043 class DefIterImpl;
1044 using TempIter = DefIterImpl<true>;
1045 using OutputIter = DefIterImpl<false>;
1046 };
1047
1048 LInstruction* LNode::toInstruction() {
1049 MOZ_ASSERT(isInstruction());
1050 return static_cast<LInstruction*>(this);
1051 }
1052
1053 const LInstruction* LNode::toInstruction() const {
1054 MOZ_ASSERT(isInstruction());
1055 return static_cast<const LInstruction*>(this);
1056 }
1057
1058 class LElementVisitor {
1059 #ifdef TRACK_SNAPSHOTS
1060 LInstruction* ins_ = nullptr;
1061 #endif
1062
1063 protected:
1064 #ifdef TRACK_SNAPSHOTS
1065 LInstruction* instruction() { return ins_; }
1066
1067 void setElement(LInstruction* ins) { ins_ = ins; }
1068 #else
1069 void setElement(LInstruction* ins) {}
1070 #endif
1071 };
1072
1073 using LInstructionIterator = InlineList<LInstruction>::iterator;
1074 using LInstructionReverseIterator = InlineList<LInstruction>::reverse_iterator;
1075
1076 class MPhi;
1077
1078 // Phi is a pseudo-instruction that emits no code, and is an annotation for the
1079 // register allocator. Like its equivalent in MIR, phis are collected at the
1080 // top of blocks and are meant to be executed in parallel, choosing the input
1081 // corresponding to the predecessor taken in the control flow graph.
1082 class LPhi final : public LNode {
1083 LAllocation* const inputs_;
1084 LDefinition def_;
1085
1086 public:
1087 LIR_HEADER(Phi)
1088
1089 LPhi(MPhi* ins, LAllocation* inputs)
1090 : LNode(classOpcode,
1091 /* nonPhiNumOperands = */ 0,
1092 /* numDefs = */ 1,
1093 /* numTemps = */ 0),
1094 inputs_(inputs) {
1095 setMir(ins);
1096 }
1097
1098 LDefinition* getDef(size_t index) {
1099 MOZ_ASSERT(index == 0);
1100 return &def_;
1101 }
1102 void setDef(size_t index, const LDefinition& def) {
1103 MOZ_ASSERT(index == 0);
1104 def_ = def;
1105 }
1106 size_t numOperands() const { return mir_->toPhi()->numOperands(); }
1107 LAllocation* getOperand(size_t index) {
1108 MOZ_ASSERT(index < numOperands());
1109 return &inputs_[index];
1110 }
1111 void setOperand(size_t index, const LAllocation& a) {
1112 MOZ_ASSERT(index < numOperands());
1113 inputs_[index] = a;
1114 }
1115
1116 // Phis don't have temps, so calling numTemps/getTemp is pointless.
1117 size_t numTemps() const = delete;
1118 LDefinition* getTemp(size_t index) = delete;
1119 };
1120
1121 class LMoveGroup;
1122 class LBlock {
1123 MBasicBlock* block_;
1124 FixedList<LPhi> phis_;
1125 InlineList<LInstruction> instructions_;
1126 LMoveGroup* entryMoveGroup_;
1127 LMoveGroup* exitMoveGroup_;
1128 Label label_;
1129
1130 public:
1131 explicit LBlock(MBasicBlock* block);
1132 [[nodiscard]] bool init(TempAllocator& alloc);
1133
1134 void add(LInstruction* ins) {
1135 ins->setBlock(this);
1136 instructions_.pushBack(ins);
1137 }
1138 size_t numPhis() const { return phis_.length(); }
1139 LPhi* getPhi(size_t index) { return &phis_[index]; }
1140 const LPhi* getPhi(size_t index) const { return &phis_[index]; }
1141 MBasicBlock* mir() const { return block_; }
1142 LInstructionIterator begin() { return instructions_.begin(); }
1143 LInstructionIterator begin(LInstruction* at) {
1144 return instructions_.begin(at);
1145 }
1146 LInstructionIterator end() { return instructions_.end(); }
1147 LInstructionReverseIterator rbegin() { return instructions_.rbegin(); }
1148 LInstructionReverseIterator rbegin(LInstruction* at) {
1149 return instructions_.rbegin(at);
1150 }
1151 LInstructionReverseIterator rend() { return instructions_.rend(); }
1152 InlineList<LInstruction>& instructions() { return instructions_; }
1153 void insertAfter(LInstruction* at, LInstruction* ins) {
1154 instructions_.insertAfter(at, ins);
1155 }
1156 void insertBefore(LInstruction* at, LInstruction* ins) {
1157 instructions_.insertBefore(at, ins);
1158 }
1159 const LNode* firstElementWithId() const {
1160 return !phis_.empty() ? static_cast<const LNode*>(getPhi(0))
1161 : firstInstructionWithId();
1162 }
1163 uint32_t firstId() const { return firstElementWithId()->id(); }
1164 uint32_t lastId() const { return lastInstructionWithId()->id(); }
1165 const LInstruction* firstInstructionWithId() const;
1166 const LInstruction* lastInstructionWithId() const {
1167 const LInstruction* last = *instructions_.rbegin();
1168 MOZ_ASSERT(last->id());
1169 // The last instruction is a control flow instruction which does not have
1170 // any output.
1171 MOZ_ASSERT(last->numDefs() == 0);
1172 return last;
1173 }
1174
1175 // Return the label to branch to when branching to this block.
1176 Label* label() {
1177 MOZ_ASSERT(!isTrivial());
1178 return &label_;
1179 }
1180
1181 LMoveGroup* getEntryMoveGroup(TempAllocator& alloc);
1182 LMoveGroup* getExitMoveGroup(TempAllocator& alloc);
1183
1184 // Test whether this basic block is empty except for a simple goto, and
1185 // which is not forming a loop. No code will be emitted for such blocks.
1186 bool isTrivial() { return begin()->isGoto() && !mir()->isLoopHeader(); }
1187
1188 #ifdef JS_JITSPEW
1189 void dump(GenericPrinter& out);
1190 void dump();
1191 #endif
1192 };
1193
1194 namespace details {
1195 template <size_t Defs, size_t Temps>
1196 class LInstructionFixedDefsTempsHelper : public LInstruction {
1197 mozilla::Array<LDefinition, Defs + Temps> defsAndTemps_;
1198
1199 protected:
1200 LInstructionFixedDefsTempsHelper(Opcode opcode, uint32_t numOperands)
1201 : LInstruction(opcode, numOperands, Defs, Temps) {}
1202
1203 public:
1204 // Override the methods in LInstruction with more optimized versions
1205 // for when we know the exact instruction type.
1206 LDefinition* getDef(size_t index) {
1207 MOZ_ASSERT(index < Defs);
1208 return &defsAndTemps_[index];
1209 }
1210 LDefinition* getTemp(size_t index) {
1211 MOZ_ASSERT(index < Temps);
1212 return &defsAndTemps_[Defs + index];
1213 }
1214 LInt64Definition getInt64Temp(size_t index) {
1215 MOZ_ASSERT(index + INT64_PIECES <= Temps);
1216 #if JS_BITS_PER_WORD == 32
1217 return LInt64Definition(defsAndTemps_[Defs + index + INT64HIGH_INDEX],
1218 defsAndTemps_[Defs + index + INT64LOW_INDEX]);
1219 #else
1220 return LInt64Definition(defsAndTemps_[Defs + index]);
1221 #endif
1222 }
1223
1224 void setDef(size_t index, const LDefinition& def) {
1225 MOZ_ASSERT(index < Defs);
1226 defsAndTemps_[index] = def;
1227 }
1228 void setTemp(size_t index, const LDefinition& a) {
1229 MOZ_ASSERT(index < Temps);
1230 defsAndTemps_[Defs + index] = a;
1231 }
1232 void setInt64Temp(size_t index, const LInt64Definition& a) {
1233 #if JS_BITS_PER_WORD == 32
1234 setTemp(index, a.low());
1235 setTemp(index + 1, a.high());
1236 #else
1237 setTemp(index, a.value());
1238 #endif
1239 }
1240
1241 // Default accessor, assuming a single output.
1242 const LDefinition* output() {
1243 MOZ_ASSERT(numDefs() == 1);
1244 return getDef(0);
1245 }
1246 static size_t offsetOfDef(size_t index) {
1247 using T = LInstructionFixedDefsTempsHelper<0, 0>;
1248 return offsetof(T, defsAndTemps_) + index * sizeof(LDefinition);
1249 }
1250 static size_t offsetOfTemp(uint32_t numDefs, uint32_t index) {
1251 using T = LInstructionFixedDefsTempsHelper<0, 0>;
1252 return offsetof(T, defsAndTemps_) + (numDefs + index) * sizeof(LDefinition);
1253 }
1254 };
1255 } // namespace details
1256
1257 inline LDefinition* LInstruction::getDef(size_t index) {
1258 MOZ_ASSERT(index < numDefs());
1259 using T = details::LInstructionFixedDefsTempsHelper<0, 0>;
1260 uint8_t* p = reinterpret_cast<uint8_t*>(this) + T::offsetOfDef(index);
1261 return reinterpret_cast<LDefinition*>(p);
1262 }
1263
1264 inline LDefinition* LInstruction::getTemp(size_t index) {
1265 MOZ_ASSERT(index < numTemps());
1266 using T = details::LInstructionFixedDefsTempsHelper<0, 0>;
1267 uint8_t* p =
1268 reinterpret_cast<uint8_t*>(this) + T::offsetOfTemp(numDefs(), index);
1269 return reinterpret_cast<LDefinition*>(p);
1270 }
1271
1272 template <size_t Defs, size_t Operands, size_t Temps>
1273 class LInstructionHelper
1274 : public details::LInstructionFixedDefsTempsHelper<Defs, Temps> {
1275 mozilla::Array<LAllocation, Operands> operands_;
1276
1277 protected:
1278 explicit LInstructionHelper(LNode::Opcode opcode)
1279 : details::LInstructionFixedDefsTempsHelper<Defs, Temps>(opcode,
1280 Operands) {
1281 static_assert(
1282 Operands == 0 || sizeof(operands_) == Operands * sizeof(LAllocation),
1283 "mozilla::Array should not contain other fields");
1284 if (Operands > 0) {
1285 using T = LInstructionHelper<Defs, Operands, Temps>;
1286 this->initOperandsOffset(offsetof(T, operands_));
1287 }
1288 }
1289
1290 public:
1291 // Override the methods in LInstruction with more optimized versions
1292 // for when we know the exact instruction type.
1293 LAllocation* getOperand(size_t index) { return &operands_[index]; }
1294 const LAllocation* getOperand(size_t index) const {
1295 return &operands_[index];
1296 }
1297 void setOperand(size_t index, const LAllocation& a) { operands_[index] = a; }
1298 LBoxAllocation getBoxOperand(size_t index) const {
1299 #ifdef JS_NUNBOX32
1300 return LBoxAllocation(operands_[index + TYPE_INDEX],
1301 operands_[index + PAYLOAD_INDEX]);
1302 #else
1303 return LBoxAllocation(operands_[index]);
1304 #endif
1305 }
1306 void setBoxOperand(size_t index, const LBoxAllocation& alloc) {
1307 #ifdef JS_NUNBOX32
1308 operands_[index + TYPE_INDEX] = alloc.type();
1309 operands_[index + PAYLOAD_INDEX] = alloc.payload();
1310 #else
1311 operands_[index] = alloc.value();
1312 #endif
1313 }
1314 void setInt64Operand(size_t index, const LInt64Allocation& alloc) {
1315 #if JS_BITS_PER_WORD == 32
1316 operands_[index + INT64LOW_INDEX] = alloc.low();
1317 operands_[index + INT64HIGH_INDEX] = alloc.high();
1318 #else
1319 operands_[index] = alloc.value();
1320 #endif
1321 }
1322 LInt64Allocation getInt64Operand(size_t offset) const {
1323 #if JS_BITS_PER_WORD == 32
1324 return LInt64Allocation(operands_[offset + INT64HIGH_INDEX],
1325 operands_[offset + INT64LOW_INDEX]);
1326 #else
1327 return LInt64Allocation(operands_[offset]);
1328 #endif
1329 }
1330 };
1331
1332 template <size_t Defs, size_t Temps>
1333 class LVariadicInstruction
1334 : public details::LInstructionFixedDefsTempsHelper<Defs, Temps> {
1335 protected:
1336 LVariadicInstruction(LNode::Opcode opcode, size_t numOperands)
1337 : details::LInstructionFixedDefsTempsHelper<Defs, Temps>(opcode,
1338 numOperands) {}
1339
1340 public:
1341 void setBoxOperand(size_t index, const LBoxAllocation& a) {
1342 #ifdef JS_NUNBOX32
1343 this->setOperand(index + TYPE_INDEX, a.type());
1344 this->setOperand(index + PAYLOAD_INDEX, a.payload());
1345 #else
1346 this->setOperand(index, a.value());
1347 #endif
1348 }
1349 };
1350
1351 template <size_t Defs, size_t Operands, size_t Temps>
1352 class LCallInstructionHelper
1353 : public LInstructionHelper<Defs, Operands, Temps> {
1354 protected:
1355 explicit LCallInstructionHelper(LNode::Opcode opcode)
1356 : LInstructionHelper<Defs, Operands, Temps>(opcode) {
1357 this->setIsCall();
1358 }
1359 };
1360
1361 // Base class for control instructions (goto, branch, etc.)
1362 template <size_t Succs, size_t Operands, size_t Temps>
1363 class LControlInstructionHelper
1364 : public LInstructionHelper<0, Operands, Temps> {
1365 mozilla::Array<MBasicBlock*, Succs> successors_;
1366
1367 protected:
1368 explicit LControlInstructionHelper(LNode::Opcode opcode)
1369 : LInstructionHelper<0, Operands, Temps>(opcode) {}
1370
1371 public:
1372 size_t numSuccessors() const { return Succs; }
1373 MBasicBlock* getSuccessor(size_t i) const { return successors_[i]; }
1374
1375 void setSuccessor(size_t i, MBasicBlock* successor) {
1376 successors_[i] = successor;
1377 }
1378 };
1379
1380 class LRecoverInfo : public TempObject {
1381 public:
1382 using Instructions = Vector<MNode*, 2, JitAllocPolicy>;
1383
1384 private:
1385 // List of instructions needed to recover the stack frames.
1386 // Outer frames are stored before inner frames.
1387 Instructions instructions_;
1388
1389 // Cached offset where this resume point is encoded.
1390 RecoverOffset recoverOffset_;
1391
1392 // Whether this LRecoverInfo has any side-effect associated with it.
1393 bool hasSideEffects_ = false;
1394
1395 explicit LRecoverInfo(TempAllocator& alloc);
1396 [[nodiscard]] bool init(MResumePoint* mir);
1397
1398 // Fill the instruction vector such as all instructions needed for the
1399 // recovery are pushed before the current instruction.
1400 template <typename Node>
1401 [[nodiscard]] bool appendOperands(Node* ins);
1402 [[nodiscard]] bool appendDefinition(MDefinition* def);
1403 [[nodiscard]] bool appendResumePoint(MResumePoint* rp);
1404
1405 public:
1406 static LRecoverInfo* New(MIRGenerator* gen, MResumePoint* mir);
1407
1408 // Resume point of the inner most function.
1409 MResumePoint* mir() const { return instructions_.back()->toResumePoint(); }
1410 RecoverOffset recoverOffset() const { return recoverOffset_; }
1411 void setRecoverOffset(RecoverOffset offset) {
1412 MOZ_ASSERT(recoverOffset_ == INVALID_RECOVER_OFFSET);
1413 recoverOffset_ = offset;
1414 }
1415
1416 MNode** begin() { return instructions_.begin(); }
1417 MNode** end() { return instructions_.end(); }
1418 size_t numInstructions() const { return instructions_.length(); }
1419 bool hasSideEffects() { return hasSideEffects_; }
1420
1421 class OperandIter {
1422 private:
1423 MNode** it_;
1424 MNode** end_;
1425 size_t op_;
1426 size_t opEnd_;
1427 MResumePoint* rp_;
1428 MNode* node_;
1429
1430 public:
1431 explicit OperandIter(LRecoverInfo* recoverInfo)
1432 : it_(recoverInfo->begin()),
1433 end_(recoverInfo->end()),
1434 op_(0),
1435 opEnd_(0),
1436 rp_(nullptr),
1437 node_(nullptr) {
1438 settle();
1439 }
1440
1441 void settle() {
1442 opEnd_ = (*it_)->numOperands();
1443 while (opEnd_ == 0) {
1444 ++it_;
1445 op_ = 0;
1446 opEnd_ = (*it_)->numOperands();
1447 }
1448 node_ = *it_;
1449 if (node_->isResumePoint()) {
1450 rp_ = node_->toResumePoint();
1451 }
1452 }
1453
1454 MDefinition* operator*() {
1455 if (rp_) { // de-virtualize MResumePoint::getOperand calls.
1456 return rp_->getOperand(op_);
1457 }
1458 return node_->getOperand(op_);
1459 }
1460 MDefinition* operator->() {
1461 if (rp_) { // de-virtualize MResumePoint::getOperand calls.
1462 return rp_->getOperand(op_);
1463 }
1464 return node_->getOperand(op_);
1465 }
1466
1467 OperandIter& operator++() {
1468 ++op_;
1469 if (op_ != opEnd_) {
1470 return *this;
1471 }
1472 op_ = 0;
1473 ++it_;
1474 node_ = rp_ = nullptr;
1475 if (!*this) {
1476 settle();
1477 }
1478 return *this;
1479 }
1480
1481 explicit operator bool() const { return it_ == end_; }
1482
1483 #ifdef DEBUG
1484 bool canOptimizeOutIfUnused();
1485 #endif
1486 };
1487 };
1488
1489 // An LSnapshot is the reflection of an MResumePoint in LIR. Unlike
1490 // MResumePoints, they cannot be shared, as they are filled in by the register
1491 // allocator in order to capture the precise low-level stack state in between an
1492 // instruction's input and output. During code generation, LSnapshots are
1493 // compressed and saved in the compiled script.
1494 class LSnapshot : public TempObject {
1495 private:
1496 LAllocation* slots_;
1497 LRecoverInfo* recoverInfo_;
1498 SnapshotOffset snapshotOffset_;
1499 uint32_t numSlots_;
1500 BailoutKind bailoutKind_;
1501
1502 LSnapshot(LRecoverInfo* recover, BailoutKind kind);
1503 [[nodiscard]] bool init(MIRGenerator* gen);
1504
1505 public:
1506 static LSnapshot* New(MIRGenerator* gen, LRecoverInfo* recover,
1507 BailoutKind kind);
1508
1509 size_t numEntries() const { return numSlots_; }
1510 size_t numSlots() const { return numSlots_ / BOX_PIECES; }
1511 LAllocation* payloadOfSlot(size_t i) {
1512 MOZ_ASSERT(i < numSlots());
1513 size_t entryIndex = (i * BOX_PIECES) + (BOX_PIECES - 1);
1514 return getEntry(entryIndex);
1515 }
1516 #ifdef JS_NUNBOX32
1517 LAllocation* typeOfSlot(size_t i) {
1518 MOZ_ASSERT(i < numSlots());
1519 size_t entryIndex = (i * BOX_PIECES) + (BOX_PIECES - 2);
1520 return getEntry(entryIndex);
1521 }
1522 #endif
1523 LAllocation* getEntry(size_t i) {
1524 MOZ_ASSERT(i < numSlots_);
1525 return &slots_[i];
1526 }
1527 void setEntry(size_t i, const LAllocation& alloc) {
1528 MOZ_ASSERT(i < numSlots_);
1529 slots_[i] = alloc;
1530 }
1531 LRecoverInfo* recoverInfo() const { return recoverInfo_; }
1532 MResumePoint* mir() const { return recoverInfo()->mir(); }
1533 SnapshotOffset snapshotOffset() const { return snapshotOffset_; }
1534 void setSnapshotOffset(SnapshotOffset offset) {
1535 MOZ_ASSERT(snapshotOffset_ == INVALID_SNAPSHOT_OFFSET);
1536 snapshotOffset_ = offset;
1537 }
1538 BailoutKind bailoutKind() const { return bailoutKind_; }
1539 void rewriteRecoveredInput(LUse input);
1540 };
1541
1542 struct SafepointSlotEntry {
1543 // Flag indicating whether this is a slot in the stack or argument space.
1544 uint32_t stack : 1;
1545
1546 // Byte offset of the slot, as in LStackSlot or LArgument.
1547 uint32_t slot : 31;
1548
1549 SafepointSlotEntry() : stack(0), slot(0) {}
1550 SafepointSlotEntry(bool stack, uint32_t slot) : stack(stack), slot(slot) {}
1551 explicit SafepointSlotEntry(const LAllocation* a)
1552 : stack(a->isStackSlot()), slot(a->memorySlot()) {}
1553 };
1554
1555 // Used for the type or payload half of a JS Value on 32-bit platforms.
1556 class SafepointNunboxEntry {
1557 static constexpr size_t VregBits = 31;
1558 uint32_t isType_ : 1;
1559 uint32_t vreg_ : VregBits;
1560 LAllocation alloc_;
1561
1562 static_assert(MAX_VIRTUAL_REGISTERS <= (uint32_t(1) << VregBits) - 1);
1563
1564 public:
1565 SafepointNunboxEntry(bool isType, uint32_t vreg, LAllocation alloc)
1566 : isType_(isType), vreg_(vreg), alloc_(alloc) {
1567 MOZ_ASSERT(alloc.isGeneralReg() || alloc.isMemory());
1568 }
1569 bool isType() const { return isType_; }
1570 uint32_t vreg() const { return vreg_; }
1571 LAllocation alloc() const { return alloc_; }
1572 };
1573
1574 enum class WasmSafepointKind : uint8_t {
1575 // For wasm call instructions (isCall() == true) where registers are spilled
1576 // by register allocation.
1577 LirCall,
1578 // For wasm instructions (isCall() == false) which will spill/restore live
1579 // registers manually in codegen.
1580 CodegenCall,
1581 // For resumable wasm traps where registers will be spilled by the trap
1582 // handler.
1583 Trap,
1584 // For stack switch call.
1585 StackSwitch,
1586 };
1587
1588 class LSafepoint : public TempObject {
1589 using SlotEntry = SafepointSlotEntry;
1590 using NunboxEntry = SafepointNunboxEntry;
1591
1592 public:
1593 using SlotList = Vector<SlotEntry, 0, JitAllocPolicy>;
1594 using NunboxList = Vector<NunboxEntry, 0, JitAllocPolicy>;
1595
1596 private:
1597 // The information in a safepoint describes the registers and gc related
1598 // values that are live at the start of the associated instruction.
1599
1600 // The set of registers which are live at an OOL call made within the
1601 // instruction. This includes any registers for inputs which are not
1602 // use-at-start, any registers for temps, and any registers live after the
1603 // call except outputs of the instruction.
1604 //
1605 // For call instructions, the live regs are empty. Call instructions may
1606 // have register inputs or temporaries, which will *not* be in the live
1607 // registers: if passed to the call, the values passed will be marked via
1608 // TraceJitExitFrame, and no registers can be live after the instruction
1609 // except its outputs.
1610 LiveRegisterSet liveRegs_;
1611
1612 // The subset of liveRegs which contains gcthing pointers.
1613 LiveGeneralRegisterSet gcRegs_;
1614
1615 #ifdef CHECK_OSIPOINT_REGISTERS
1616 // Clobbered regs of the current instruction. This set is never written to
1617 // the safepoint; it's only used by assertions during compilation.
1618 LiveRegisterSet clobberedRegs_;
1619 #endif
1620
1621 // Offset to a position in the safepoint stream, or
1622 // INVALID_SAFEPOINT_OFFSET.
1623 uint32_t safepointOffset_;
1624
1625 // Assembler buffer displacement to OSI point's call location.
1626 uint32_t osiCallPointOffset_;
1627
1628 // List of slots which have gcthing pointers.
1629 SlotList gcSlots_;
1630
1631 #ifdef JS_NUNBOX32
1632 // List of registers (in liveRegs) and slots which contain pieces of Values.
1633 NunboxList nunboxParts_;
1634 #elif JS_PUNBOX64
1635 // List of slots which have Values.
1636 SlotList valueSlots_;
1637
1638 // The subset of liveRegs which have Values.
1639 LiveGeneralRegisterSet valueRegs_;
1640 #endif
1641
1642 // The subset of liveRegs which contains pointers to slots/elements.
1643 LiveGeneralRegisterSet slotsOrElementsRegs_;
1644
1645 // List of slots which have slots/elements pointers.
1646 SlotList slotsOrElementsSlots_;
1647
1648 // The subset of liveRegs which contains wasm::AnyRef's.
1649 LiveGeneralRegisterSet wasmAnyRefRegs_;
1650 // List of slots which have wasm::AnyRef's.
1651 SlotList wasmAnyRefSlots_;
1652
1653 // Wasm only: with what kind of instruction is this LSafepoint associated?
1654 WasmSafepointKind wasmSafepointKind_;
1655
1656 // Wasm only: what is the value of masm.framePushed() that corresponds to
1657 // the lowest-addressed word covered by the StackMap that we will generate
1658 // from this LSafepoint? This depends on the instruction:
1659 //
1660 // WasmSafepointKind::LirCall:
1661 // masm.framePushed() - StackArgAreaSizeUnaligned(arg types for the call),
1662 // because the map does not include the outgoing args themselves, but
1663 // it does cover any and all alignment space above them.
1664 //
1665 // WasmSafepointKind::CodegenCall and WasmSafepointKind::Trap:
1666 // masm.framePushed() unmodified. Note that when constructing the
1667 // StackMap we will add entries below this point to take account of
1668 // registers dumped on the stack.
1669 uint32_t framePushedAtStackMapBase_;
1670
1671 public:
1672 void assertInvariants() {
1673 // Every register in valueRegs and gcRegs should also be in liveRegs.
1674 #ifndef JS_NUNBOX32
1675 MOZ_ASSERT((valueRegs().bits() & ~liveRegs().gprs().bits()) == 0);
1676 #endif
1677 MOZ_ASSERT((gcRegs().bits() & ~liveRegs().gprs().bits()) == 0);
1678 MOZ_ASSERT((wasmAnyRefRegs().bits() & ~liveRegs().gprs().bits()) == 0);
1679 }
1680
1681 explicit LSafepoint(TempAllocator& alloc)
1682 : safepointOffset_(INVALID_SAFEPOINT_OFFSET),
1683 osiCallPointOffset_(0),
1684 gcSlots_(alloc),
1685 #ifdef JS_NUNBOX32
1686 nunboxParts_(alloc),
1687 #else
1688 valueSlots_(alloc),
1689 #endif
1690 slotsOrElementsSlots_(alloc),
1691 wasmAnyRefSlots_(alloc),
1692 wasmSafepointKind_(WasmSafepointKind::LirCall),
1693 framePushedAtStackMapBase_(0) {
1694 assertInvariants();
1695 }
1696 void addLiveRegister(AnyRegister reg) {
1697 liveRegs_.addUnchecked(reg);
1698 assertInvariants();
1699 }
1700 const LiveRegisterSet& liveRegs() const { return liveRegs_; }
1701 #ifdef CHECK_OSIPOINT_REGISTERS
1702 void addClobberedRegister(AnyRegister reg) {
1703 clobberedRegs_.addUnchecked(reg);
1704 assertInvariants();
1705 }
1706 const LiveRegisterSet& clobberedRegs() const { return clobberedRegs_; }
1707 #endif
1708 LiveGeneralRegisterSet gcRegs() const { return gcRegs_; }
1709 [[nodiscard]] bool addGcSlot(bool stack, uint32_t slot) {
1710 bool result = gcSlots_.append(SlotEntry(stack, slot));
1711 if (result) {
1712 assertInvariants();
1713 }
1714 return result;
1715 }
1716 SlotList& gcSlots() { return gcSlots_; }
1717
1718 SlotList& slotsOrElementsSlots() { return slotsOrElementsSlots_; }
1719 LiveGeneralRegisterSet slotsOrElementsRegs() const {
1720 return slotsOrElementsRegs_;
1721 }
1722 [[nodiscard]] bool addSlotsOrElementsSlot(bool stack, uint32_t slot) {
1723 bool result = slotsOrElementsSlots_.append(SlotEntry(stack, slot));
1724 if (result) {
1725 assertInvariants();
1726 }
1727 return result;
1728 }
1729 [[nodiscard]] bool addSlotsOrElementsPointer(LAllocation alloc) {
1730 if (alloc.isMemory()) {
1731 return addSlotsOrElementsSlot(alloc.isStackSlot(), alloc.memorySlot());
1732 }
1733 MOZ_ASSERT(alloc.isGeneralReg());
1734 slotsOrElementsRegs_.addUnchecked(alloc.toGeneralReg()->reg());
1735 assertInvariants();
1736 return true;
1737 }
1738 bool hasSlotsOrElementsPointer(LAllocation alloc) const {
1739 if (alloc.isGeneralReg()) {
1740 return slotsOrElementsRegs().has(alloc.toGeneralReg()->reg());
1741 }
1742 for (size_t i = 0; i < slotsOrElementsSlots_.length(); i++) {
1743 const SlotEntry& entry = slotsOrElementsSlots_[i];
1744 if (entry.stack == alloc.isStackSlot() &&
1745 entry.slot == alloc.memorySlot()) {
1746 return true;
1747 }
1748 }
1749 return false;
1750 }
1751
1752 [[nodiscard]] bool addGcPointer(LAllocation alloc) {
1753 if (alloc.isMemory()) {
1754 return addGcSlot(alloc.isStackSlot(), alloc.memorySlot());
1755 }
1756 MOZ_ASSERT(alloc.isGeneralReg());
1757 gcRegs_.addUnchecked(alloc.toGeneralReg()->reg());
1758 assertInvariants();
1759 return true;
1760 }
1761
1762 bool hasGcPointer(LAllocation alloc) const {
1763 if (alloc.isGeneralReg()) {
1764 return gcRegs().has(alloc.toGeneralReg()->reg());
1765 }
1766 MOZ_ASSERT(alloc.isMemory());
1767 for (size_t i = 0; i < gcSlots_.length(); i++) {
1768 if (gcSlots_[i].stack == alloc.isStackSlot() &&
1769 gcSlots_[i].slot == alloc.memorySlot()) {
1770 return true;
1771 }
1772 }
1773 return false;
1774 }
1775
1776 LiveGeneralRegisterSet wasmAnyRefRegs() const { return wasmAnyRefRegs_; }
1777
1778 [[nodiscard]] bool addWasmAnyRefSlot(bool stack, uint32_t slot) {
1779 bool result = wasmAnyRefSlots_.append(SlotEntry(stack, slot));
1780 if (result) {
1781 assertInvariants();
1782 }
1783 return result;
1784 }
1785 SlotList& wasmAnyRefSlots() { return wasmAnyRefSlots_; }
1786
1787 [[nodiscard]] bool addWasmAnyRef(LAllocation alloc) {
1788 if (alloc.isMemory()) {
1789 return addWasmAnyRefSlot(alloc.isStackSlot(), alloc.memorySlot());
1790 }
1791 MOZ_ASSERT(alloc.isGeneralReg());
1792 wasmAnyRefRegs_.addUnchecked(alloc.toGeneralReg()->reg());
1793 assertInvariants();
1794 return true;
1795 }
1796 bool hasWasmAnyRef(LAllocation alloc) const {
1797 if (alloc.isGeneralReg()) {
1798 return wasmAnyRefRegs().has(alloc.toGeneralReg()->reg());
1799 }
1800 MOZ_ASSERT(alloc.isMemory());
1801 for (size_t i = 0; i < wasmAnyRefSlots_.length(); i++) {
1802 if (wasmAnyRefSlots_[i].stack == alloc.isStackSlot() &&
1803 wasmAnyRefSlots_[i].slot == alloc.memorySlot()) {
1804 return true;
1805 }
1806 }
1807 return false;
1808 }
1809
1810 // Return true if all GC-managed pointers from `alloc` are recorded in this
1811 // safepoint.
1812 bool hasAllWasmAnyRefsFromStackArea(LAllocation alloc) const {
1813 for (LStackArea::ResultIterator iter = alloc.toStackArea()->results(); iter;
1814 iter.next()) {
1815 if (iter.isWasmAnyRef() && !hasWasmAnyRef(iter.alloc())) {
1816 return false;
1817 }
1818 }
1819 return true;
1820 }
1821
1822 #ifdef JS_NUNBOX32
1823 [[nodiscard]] bool addNunboxPart(bool isType, uint32_t vreg,
1824 LAllocation alloc) {
1825 bool result = nunboxParts_.emplaceBack(isType, vreg, alloc);
1826 if (result) {
1827 assertInvariants();
1828 }
1829 return result;
1830 }
1831
1832 # ifdef DEBUG
1833 bool hasNunboxPart(bool isType, LAllocation alloc) const {
1834 for (auto entry : nunboxParts_) {
1835 if (entry.alloc() == alloc && entry.isType() == isType) {
1836 return true;
1837 }
1838 }
1839 return false;
1840 }
1841 # endif
1842
1843 NunboxList& nunboxParts() { return nunboxParts_; }
1844
1845 #elif JS_PUNBOX64
1846 [[nodiscard]] bool addValueSlot(bool stack, uint32_t slot) {
1847 bool result = valueSlots_.append(SlotEntry(stack, slot));
1848 if (result) {
1849 assertInvariants();
1850 }
1851 return result;
1852 }
1853 SlotList& valueSlots() { return valueSlots_; }
1854
1855 bool hasValueSlot(bool stack, uint32_t slot) const {
1856 for (size_t i = 0; i < valueSlots_.length(); i++) {
1857 if (valueSlots_[i].stack == stack && valueSlots_[i].slot == slot) {
1858 return true;
1859 }
1860 }
1861 return false;
1862 }
1863
1864 LiveGeneralRegisterSet valueRegs() const { return valueRegs_; }
1865
1866 [[nodiscard]] bool addBoxedValue(LAllocation alloc) {
1867 if (alloc.isMemory()) {
1868 return addValueSlot(alloc.isStackSlot(), alloc.memorySlot());
1869 }
1870 MOZ_ASSERT(alloc.isGeneralReg());
1871 valueRegs_.addUnchecked(alloc.toGeneralReg()->reg());
1872 assertInvariants();
1873 return true;
1874 }
1875
1876 bool hasBoxedValue(LAllocation alloc) const {
1877 if (alloc.isGeneralReg()) {
1878 return valueRegs().has(alloc.toGeneralReg()->reg());
1879 }
1880 return hasValueSlot(alloc.isStackSlot(), alloc.memorySlot());
1881 }
1882
1883 #endif // JS_PUNBOX64
1884
1885 [[nodiscard]] bool addGCAllocation(uint32_t vregId, LDefinition* def,
1886 LAllocation a);
1887
1888 bool encoded() const { return safepointOffset_ != INVALID_SAFEPOINT_OFFSET; }
1889 uint32_t offset() const {
1890 MOZ_ASSERT(encoded());
1891 return safepointOffset_;
1892 }
1893 void setOffset(uint32_t offset) { safepointOffset_ = offset; }
1894 uint32_t osiReturnPointOffset() const {
1895 // In general, pointer arithmetic on code is bad, but in this case,
1896 // getting the return address from a call instruction, stepping over pools
1897 // would be wrong.
1898 return osiCallPointOffset_ + Assembler::PatchWrite_NearCallSize();
1899 }
1900 uint32_t osiCallPointOffset() const { return osiCallPointOffset_; }
1901 void setOsiCallPointOffset(uint32_t osiCallPointOffset) {
1902 MOZ_ASSERT(!osiCallPointOffset_);
1903 osiCallPointOffset_ = osiCallPointOffset;
1904 }
1905
1906 WasmSafepointKind wasmSafepointKind() const { return wasmSafepointKind_; }
1907 void setWasmSafepointKind(WasmSafepointKind kind) {
1908 wasmSafepointKind_ = kind;
1909 }
1910
1911 // See comment on framePushedAtStackMapBase_.
1912 uint32_t framePushedAtStackMapBase() const {
1913 return framePushedAtStackMapBase_;
1914 }
1915 void setFramePushedAtStackMapBase(uint32_t n) {
1916 MOZ_ASSERT(framePushedAtStackMapBase_ == 0);
1917 framePushedAtStackMapBase_ = n;
1918 }
1919 };
1920
1921 struct WasmRefIsSubtypeDefs {
1922 LAllocation superSTV;
1923 LDefinition scratch1;
1924 LDefinition scratch2;
1925 };
1926
1927 template <bool WithSnapshotUses>
1928 class LInstruction::InputIterImpl {
1929 private:
1930 LInstruction& ins_;
1931 size_t idx_ = 0;
1932 bool snapshot_ = false;
1933
1934 void handleOperandsEnd() {
1935 // Iterate on the snapshot when iteration over all operands is done.
1936 if constexpr (WithSnapshotUses) {
1937 if (!snapshot_ && idx_ == ins_.numOperands() && ins_.snapshot()) {
1938 idx_ = 0;
1939 snapshot_ = true;
1940 }
1941 }
1942 }
1943
1944 public:
1945 explicit InputIterImpl(LInstruction& ins) : ins_(ins) { handleOperandsEnd(); }
1946
1947 bool more() const {
1948 if (WithSnapshotUses && snapshot_) {
1949 return idx_ < ins_.snapshot()->numEntries();
1950 }
1951 if (idx_ < ins_.numOperands()) {
1952 return true;
1953 }
1954 if (WithSnapshotUses && ins_.snapshot() && ins_.snapshot()->numEntries()) {
1955 return true;
1956 }
1957 return false;
1958 }
1959
1960 bool isSnapshotInput() const { return snapshot_; }
1961
1962 void next() {
1963 MOZ_ASSERT(more());
1964 idx_++;
1965 handleOperandsEnd();
1966 }
1967
1968 void replace(const LAllocation& alloc) {
1969 if (WithSnapshotUses && snapshot_) {
1970 ins_.snapshot()->setEntry(idx_, alloc);
1971 } else {
1972 ins_.setOperand(idx_, alloc);
1973 }
1974 }
1975
1976 LAllocation* operator*() const {
1977 if (WithSnapshotUses && snapshot_) {
1978 return ins_.snapshot()->getEntry(idx_);
1979 }
1980 return ins_.getOperand(idx_);
1981 }
1982
1983 LAllocation* operator->() const { return **this; }
1984 };
1985
1986 // Iterator for instruction outputs or temps. Skips BogusTemp definitions.
1987 template <bool Temps>
1988 class LInstruction::DefIterImpl {
1989 private:
1990 LInstruction* ins_;
1991 size_t idx_ = 0;
1992 const size_t len_;
1993
1994 public:
1995 explicit DefIterImpl(LInstruction* ins)
1996 : ins_(ins), len_(Temps ? ins->numTemps() : ins->numDefs()) {
1997 settle();
1998 }
1999 bool done() const {
2000 MOZ_ASSERT(idx_ <= len_);
2001 return idx_ == len_;
2002 }
2003 void operator++(int) {
2004 MOZ_ASSERT(!done());
2005 idx_++;
2006 settle();
2007 }
2008 void settle() {
2009 while (!done() && get()->isBogusTemp()) {
2010 idx_++;
2011 }
2012 }
2013 size_t index() const {
2014 MOZ_ASSERT(!done());
2015 return idx_;
2016 }
2017 LDefinition* get() const {
2018 MOZ_ASSERT(!done());
2019 if constexpr (Temps) {
2020 return ins_->getTemp(idx_);
2021 }
2022 return ins_->getDef(idx_);
2023 }
2024 LDefinition* operator*() const { return get(); }
2025 LDefinition* operator->() const { return **this; }
2026 };
2027
2028 bool LDefinition::isSafepointGCType(LNode* ins) const {
2029 switch (type()) {
2030 case LDefinition::OBJECT:
2031 case LDefinition::SLOTS:
2032 case LDefinition::WASM_ANYREF:
2033 #ifdef JS_NUNBOX32
2034 case LDefinition::TYPE:
2035 case LDefinition::PAYLOAD:
2036 #else
2037 case LDefinition::BOX:
2038 #endif
2039 return true;
2040 case LDefinition::STACKRESULTS: {
2041 LStackArea alloc(ins->toInstruction());
2042 for (auto iter = alloc.results(); iter; iter.next()) {
2043 if (iter.isWasmAnyRef()) {
2044 return true;
2045 }
2046 }
2047 return false;
2048 }
2049 case LDefinition::GENERAL:
2050 case LDefinition::INT32:
2051 case LDefinition::FLOAT32:
2052 case LDefinition::DOUBLE:
2053 case LDefinition::SIMD128:
2054 return false;
2055 }
2056 MOZ_CRASH("invalid type");
2057 }
2058
2059 class LIRGraph {
2060 struct ValueHasher {
2061 using Lookup = Value;
2062 static HashNumber hash(const Value& v) { return HashNumber(v.asRawBits()); }
2063 static bool match(const Value& lhs, const Value& rhs) { return lhs == rhs; }
2064 };
2065
2066 FixedList<LBlock> blocks_;
2067
2068 // constantPool_ is a mozilla::Vector, not a js::Vector, because
2069 // js::Vector<Value> is prohibited as unsafe. This particular Vector of
2070 // Values is safe because it is only used within the scope of an
2071 // AutoSuppressGC (in IonCompile), which inhibits GC.
2072 mozilla::Vector<Value, 0, JitAllocPolicy> constantPool_;
2073 using ConstantPoolMap = HashMap<Value, uint32_t, ValueHasher, JitAllocPolicy>;
2074 ConstantPoolMap constantPoolMap_;
2075 uint32_t numVirtualRegisters_;
2076 uint32_t numInstructions_;
2077
2078 // Number of instructions with a safepoint.
2079 uint32_t numSafepoints_ = 0;
2080 // Number of non-call instructions with a safepoint.
2081 uint32_t numNonCallSafepoints_ = 0;
2082
2083 // Number of call-instructions in this LIR graph.
2084 uint32_t numCallInstructions_ = 0;
2085
2086 // Size of stack slots needed for local spills.
2087 uint32_t localSlotsSize_;
2088 // Number of JS::Value stack slots needed for argument construction for calls.
2089 uint32_t argumentSlotCount_;
2090 // Count the number of extra times a single safepoint would be encoded.
2091 uint32_t extraSafepointUses_;
2092
2093 MIRGraph& mir_;
2094
2095 public:
2096 explicit LIRGraph(MIRGraph* mir);
2097
2098 [[nodiscard]] bool init() {
2099 return blocks_.init(mir_.alloc(), mir_.numBlocks());
2100 }
2101 MIRGraph& mir() const { return mir_; }
2102 size_t numBlocks() const { return blocks_.length(); }
2103 LBlock* getBlock(size_t i) { return &blocks_[i]; }
2104 uint32_t numBlockIds() const { return mir_.numBlockIds(); }
2105 [[nodiscard]] bool initBlock(MBasicBlock* mir) {
2106 auto* block = &blocks_[mir->id()];
2107 auto* lir = new (block) LBlock(mir);
2108 return lir->init(mir_.alloc());
2109 }
2110 uint32_t getVirtualRegister() {
2111 numVirtualRegisters_ += VREG_INCREMENT;
2112 return numVirtualRegisters_;
2113 }
2114 uint32_t numVirtualRegisters() const {
2115 // Virtual registers are 1-based, not 0-based, so add one as a
2116 // convenience for 0-based arrays.
2117 return numVirtualRegisters_ + 1;
2118 }
2119 uint32_t getInstructionId() { return numInstructions_++; }
2120 uint32_t numInstructions() const { return numInstructions_; }
2121
2122 void incNumCallInstructions() { numCallInstructions_++; }
2123 uint32_t numCallInstructions() const { return numCallInstructions_; }
2124
2125 void setLocalSlotsSize(uint32_t localSlotsSize) {
2126 localSlotsSize_ = localSlotsSize;
2127 }
2128 uint32_t localSlotsSize() const { return localSlotsSize_; }
2129 void setArgumentSlotCount(uint32_t argumentSlotCount) {
2130 argumentSlotCount_ = argumentSlotCount;
2131 }
2132 uint32_t argumentSlotCount() const { return argumentSlotCount_; }
2133 void addExtraSafepointUses(uint32_t extra) { extraSafepointUses_ += extra; }
2134 uint32_t extraSafepointUses() const { return extraSafepointUses_; }
2135 [[nodiscard]] bool addConstantToPool(const Value& v, uint32_t* index);
2136 size_t numConstants() const { return constantPool_.length(); }
2137 Value* constantPool() { return &constantPool_[0]; }
2138
2139 void noteNeedsSafepoint(LInstruction* ins) {
2140 numSafepoints_++;
2141 if (!ins->isCall()) {
2142 numNonCallSafepoints_++;
2143 }
2144 }
2145
2146 size_t numNonCallSafepoints() const { return numNonCallSafepoints_; }
2147 size_t numSafepoints() const { return numSafepoints_; }
2148
2149 #ifdef JS_JITSPEW
2150 void dump(GenericPrinter& out);
2151 void dump();
2152 #endif
2153 };
2154
2155 LAllocation::LAllocation(AnyRegister reg) {
2156 if (reg.isFloat()) {
2157 *this = LFloatReg(reg.fpu());
2158 } else {
2159 *this = LGeneralReg(reg.gpr());
2160 }
2161 }
2162
2163 AnyRegister LAllocation::toAnyRegister() const {
2164 MOZ_ASSERT(isAnyRegister());
2165 if (isFloatReg()) {
2166 return AnyRegister(toFloatReg()->reg());
2167 }
2168 return AnyRegister(toGeneralReg()->reg());
2169 }
2170
2171 } // namespace jit
2172 } // namespace js
2173
2174 #include "jit/shared/LIR-shared.h"
2175 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2176 # if defined(JS_CODEGEN_X86)
2177 # include "jit/x86/LIR-x86.h"
2178 # elif defined(JS_CODEGEN_X64)
2179 # include "jit/x64/LIR-x64.h"
2180 # endif
2181 # include "jit/x86-shared/LIR-x86-shared.h"
2182 #elif defined(JS_CODEGEN_ARM)
2183 # include "jit/arm/LIR-arm.h"
2184 #elif defined(JS_CODEGEN_ARM64)
2185 # include "jit/arm64/LIR-arm64.h"
2186 #elif defined(JS_CODEGEN_LOONG64)
2187 # include "jit/loong64/LIR-loong64.h"
2188 #elif defined(JS_CODEGEN_RISCV64)
2189 # include "jit/riscv64/LIR-riscv64.h"
2190 #elif defined(JS_CODEGEN_MIPS64)
2191 # include "jit/mips-shared/LIR-mips-shared.h"
2192 # include "jit/mips64/LIR-mips64.h"
2193 #elif defined(JS_CODEGEN_WASM32)
2194 # include "jit/wasm32/LIR-wasm32.h"
2195 #elif defined(JS_CODEGEN_NONE)
2196 # include "jit/none/LIR-none.h"
2197 #else
2198 # error "Unknown architecture!"
2199 #endif
2200
2201 #undef LIR_HEADER
2202
2203 namespace js {
2204 namespace jit {
2205
2206 #define LIROP(name) \
2207 L##name* LNode::to##name() { \
2208 MOZ_ASSERT(is##name()); \
2209 return static_cast<L##name*>(this); \
2210 } \
2211 const L##name* LNode::to##name() const { \
2212 MOZ_ASSERT(is##name()); \
2213 return static_cast<const L##name*>(this); \
2214 }
2215 LIR_OPCODE_LIST(LIROP)
2216 #undef LIROP
2217
2218 #define LALLOC_CAST(type) \
2219 L##type* LAllocation::to##type() { \
2220 MOZ_ASSERT(is##type()); \
2221 return static_cast<L##type*>(this); \
2222 }
2223 #define LALLOC_CONST_CAST(type) \
2224 const L##type* LAllocation::to##type() const { \
2225 MOZ_ASSERT(is##type()); \
2226 return static_cast<const L##type*>(this); \
2227 }
2228
2229 LALLOC_CAST(Use)
2230 LALLOC_CONST_CAST(Use)
2231 LALLOC_CONST_CAST(GeneralReg)
2232 LALLOC_CONST_CAST(FloatReg)
2233 LALLOC_CONST_CAST(StackSlot)
2234 LALLOC_CAST(StackArea)
2235 LALLOC_CONST_CAST(StackArea)
2236 LALLOC_CONST_CAST(Argument)
2237 LALLOC_CONST_CAST(ConstantIndex)
2238
2239 #undef LALLOC_CAST
2240
2241 } // namespace jit
2242 } // namespace js
2243
2244 #endif /* jit_LIR_h */