Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Everything needed to build actual MIR instructions: the actual opcodes and
* instructions, the instruction interface, and use chains.
*/
#ifndef jit_MIR_h
#define jit_MIR_h
#include "mozilla/Array.h"
#include "mozilla/EnumSet.h"
#include "mozilla/HashFunctions.h"
#ifdef JS_JITSPEW
# include "mozilla/Attributes.h" // MOZ_STACK_CLASS
#endif
#include "mozilla/MacroForEach.h"
#ifdef JS_JITSPEW
# include "mozilla/Sprintf.h"
# include "mozilla/Vector.h"
#endif
#include <algorithm>
#include <initializer_list>
#include "NamespaceImports.h"
#include "jit/AtomicOp.h"
#include "jit/FixedList.h"
#include "jit/InlineList.h"
#include "jit/JitAllocPolicy.h"
#include "jit/MacroAssembler.h"
#include "jit/MIROpsGenerated.h"
#include "jit/ShuffleAnalysis.h"
#include "jit/TypeData.h"
#include "jit/TypePolicy.h"
#include "js/experimental/JitInfo.h" // JSJit{Getter,Setter}Op, JSJitInfo
#include "js/HeapAPI.h"
#include "js/ScalarType.h" // js::Scalar::Type
#include "js/Value.h"
#include "js/Vector.h"
#include "vm/BigIntType.h"
#include "vm/EnvironmentObject.h"
#include "vm/FunctionFlags.h" // js::FunctionFlags
#include "vm/JSContext.h"
#include "vm/RegExpObject.h"
#include "vm/TypedArrayObject.h"
#include "wasm/WasmJS.h" // for WasmInstanceObject
#include "wasm/WasmValType.h"
namespace JS {
struct ExpandoAndGeneration;
}
namespace js {
namespace wasm {
class FuncExport;
extern uint32_t MIRTypeToABIResultSize(jit::MIRType);
} // namespace wasm
class JS_PUBLIC_API GenericPrinter;
class NativeIteratorListHead;
class StringObject;
enum class UnaryMathFunction : uint8_t;
bool CurrentThreadIsIonCompiling();
namespace jit {
class CallInfo;
#ifdef JS_JITSPEW
// Helper for debug printing. Avoids creating a MIR.h <--> MIRGraph.h cycle.
// Implementation of this needs to see inside `MBasicBlock`; that is possible
// in MIR.cpp since it also includes MIRGraph.h, whereas this file does not.
class MBasicBlock;
uint32_t GetMBasicBlockId(const MBasicBlock* block);
// Helper class for debug printing. This class allows `::getExtras` methods
// to add strings to be printed, on a per-MIR-node basis. The strings are
// copied into storage owned by this class when `::add` is called, so the
// `::getExtras` methods do not need to be concerned about storage management.
class MOZ_STACK_CLASS ExtrasCollector {
mozilla::Vector<UniqueChars, 4> strings_;
public:
// Add `str` to the collection. A copy, owned by this object, is made. In
// case of OOM the call has no effect.
void add(const char* str) {
UniqueChars dup = DuplicateString(str);
if (dup) {
(void)strings_.append(std::move(dup));
}
}
size_t count() const { return strings_.length(); }
UniqueChars get(size_t ix) { return std::move(strings_[ix]); }
};
#endif
// Forward declarations of MIR types.
#define FORWARD_DECLARE(op) class M##op;
MIR_OPCODE_LIST(FORWARD_DECLARE)
#undef FORWARD_DECLARE
// MDefinition visitor which ignores non-overloaded visit functions.
class MDefinitionVisitorDefaultNoop {
public:
#define VISIT_INS(op) \
void visit##op(M##op*) {}
MIR_OPCODE_LIST(VISIT_INS)
#undef VISIT_INS
};
class BytecodeSite;
class CompactBufferWriter;
class Range;
#define MIR_FLAG_LIST(_) \
_(InWorklist) \
_(EmittedAtUses) \
_(Commutative) \
_(Movable) /* Allow passes like LICM to move this instruction */ \
_(Lowered) /* (Debug only) has a virtual register */ \
_(Guard) /* Not removable if uses == 0 */ \
\
/* Flag an instruction to be considered as a Guard if the instructions \
* bails out on some inputs. \
* \
* Some optimizations can replace an instruction, and leave its operands \
* unused. When the type information of the operand got used as a \
* predicate of the transformation, then we have to flag the operands as \
* GuardRangeBailouts. \
* \
* This flag prevents further optimization of instructions, which \
* might remove the run-time checks (bailout conditions) used as a \
* predicate of the previous transformation. \
*/ \
_(GuardRangeBailouts) \
\
/* Some instructions have uses that aren't directly represented in the \
* graph, and need to be handled specially. As an example, this is used to \
* keep the flagged instruction in resume points, not substituting with an \
* UndefinedValue. This can be used by call inlining when a function \
* argument is not used by the inlined instructions. It is also used \
* to annotate instructions which were used in removed branches. \
*/ \
_(ImplicitlyUsed) \
\
/* The instruction has been marked dead for lazy removal from resume \
* points. \
*/ \
_(Unused) \
\
/* Marks if the current instruction should go to the bailout paths instead \
* of producing code as part of the control flow. This flag can only be set \
* on instructions which are only used by ResumePoint or by other flagged \
* instructions. \
*/ \
_(RecoveredOnBailout) \
\
/* Some instructions might represent an object, but the memory of these \
* objects might be incomplete if we have not recovered all the stores which \
* were supposed to happen before. This flag is used to annotate \
* instructions which might return a pointer to a memory area which is not \
* yet fully initialized. This flag is used to ensure that stores are \
* executed before returning the value. \
*/ \
_(IncompleteObject) \
\
/* For WebAssembly, there are functions with multiple results. Instead of \
* having the results defined by one call instruction, they are instead \
* captured in subsequent result capture instructions, because modelling \
* multi-value results in Ion is too complicated. However since they \
* capture ambient live registers, it would be an error to move an unrelated \
* instruction between the call and the result capture. This flag is used \
* to prevent code motion from moving instructions in invalid ways. \
*/ \
_(CallResultCapture) \
\
/* The current instruction got discarded from the MIR Graph. This is useful \
* when we want to iterate over resume points and instructions, while \
* handling instructions which are discarded without reporting to the \
* iterator. \
*/ \
_(Discarded)
class MDefinition;
class MInstruction;
class MBasicBlock;
class MNode;
class MUse;
class MPhi;
class MIRGraph;
class MResumePoint;
class MControlInstruction;
// Represents a use of a node.
class MUse : public TempObject, public InlineListNode<MUse> {
// Grant access to setProducerUnchecked.
friend class MDefinition;
friend class MPhi;
MDefinition* producer_; // MDefinition that is being used.
MNode* consumer_; // The node that is using this operand.
// Low-level unchecked edit method for replaceAllUsesWith and
// MPhi::removeOperand. This doesn't update use lists!
// replaceAllUsesWith and MPhi::removeOperand do that manually.
void setProducerUnchecked(MDefinition* producer) {
MOZ_ASSERT(consumer_);
MOZ_ASSERT(producer_);
MOZ_ASSERT(producer);
producer_ = producer;
}
public:
// Default constructor for use in vectors.
MUse() : producer_(nullptr), consumer_(nullptr) {}
// Move constructor for use in vectors. When an MUse is moved, it stays
// in its containing use list.
MUse(MUse&& other)
: InlineListNode<MUse>(std::move(other)),
producer_(other.producer_),
consumer_(other.consumer_) {}
// Construct an MUse initialized with |producer| and |consumer|.
MUse(MDefinition* producer, MNode* consumer) {
initUnchecked(producer, consumer);
}
// Set this use, which was previously clear.
inline void init(MDefinition* producer, MNode* consumer);
// Like init, but works even when the use contains uninitialized data.
inline void initUnchecked(MDefinition* producer, MNode* consumer);
// Like initUnchecked, but set the producer to nullptr.
inline void initUncheckedWithoutProducer(MNode* consumer);
// Set this use, which was not previously clear.
inline void replaceProducer(MDefinition* producer);
// Clear this use.
inline void releaseProducer();
MDefinition* producer() const {
MOZ_ASSERT(producer_ != nullptr);
return producer_;
}
bool hasProducer() const { return producer_ != nullptr; }
MNode* consumer() const {
MOZ_ASSERT(consumer_ != nullptr);
return consumer_;
}
#ifdef DEBUG
// Return the operand index of this MUse in its consumer. This is DEBUG-only
// as normal code should instead call indexOf on the cast consumer directly,
// to allow it to be devirtualized and inlined.
size_t index() const;
#endif
};
using MUseIterator = InlineList<MUse>::iterator;
// A node is an entry in the MIR graph. It has two kinds:
// MInstruction: an instruction which appears in the IR stream.
// MResumePoint: a list of instructions that correspond to the state of the
// interpreter/Baseline stack.
//
// Nodes can hold references to MDefinitions. Each MDefinition has a list of
// nodes holding such a reference (its use chain).
class MNode : public TempObject {
protected:
enum class Kind { Definition = 0, ResumePoint };
private:
static const uintptr_t KindMask = 0x1;
uintptr_t blockAndKind_;
Kind kind() const { return Kind(blockAndKind_ & KindMask); }
protected:
explicit MNode(const MNode& other) : blockAndKind_(other.blockAndKind_) {}
MNode(MBasicBlock* block, Kind kind) { setBlockAndKind(block, kind); }
void setBlockAndKind(MBasicBlock* block, Kind kind) {
blockAndKind_ = uintptr_t(block) | uintptr_t(kind);
MOZ_ASSERT(this->block() == block);
}
MBasicBlock* definitionBlock() const {
MOZ_ASSERT(isDefinition());
static_assert(unsigned(Kind::Definition) == 0,
"Code below relies on low bit being 0");
return reinterpret_cast<MBasicBlock*>(blockAndKind_);
}
MBasicBlock* resumePointBlock() const {
MOZ_ASSERT(isResumePoint());
static_assert(unsigned(Kind::ResumePoint) == 1,
"Code below relies on low bit being 1");
// Use a subtraction: if the caller does block()->foo, the compiler
// will be able to fold it with the load.
return reinterpret_cast<MBasicBlock*>(blockAndKind_ - 1);
}
public:
// Returns the definition at a given operand.
virtual MDefinition* getOperand(size_t index) const = 0;
virtual size_t numOperands() const = 0;
virtual size_t indexOf(const MUse* u) const = 0;
bool isDefinition() const { return kind() == Kind::Definition; }
bool isResumePoint() const { return kind() == Kind::ResumePoint; }
MBasicBlock* block() const {
return reinterpret_cast<MBasicBlock*>(blockAndKind_ & ~KindMask);
}
MBasicBlock* caller() const;
// Sets an already set operand, updating use information. If you're looking
// for setOperand, this is probably what you want.
virtual void replaceOperand(size_t index, MDefinition* operand) = 0;
// Resets the operand to an uninitialized state, breaking the link
// with the previous operand's producer.
void releaseOperand(size_t index) { getUseFor(index)->releaseProducer(); }
bool hasOperand(size_t index) const {
return getUseFor(index)->hasProducer();
}
inline MDefinition* toDefinition();
inline MResumePoint* toResumePoint();
[[nodiscard]] virtual bool writeRecoverData(
CompactBufferWriter& writer) const;
#ifdef JS_JITSPEW
virtual void dump(GenericPrinter& out) const = 0;
virtual void dump() const = 0;
#endif
protected:
// Need visibility on getUseFor to avoid O(n^2) complexity.
friend void AssertBasicGraphCoherency(MIRGraph& graph, bool force);
// Gets the MUse corresponding to given operand.
virtual MUse* getUseFor(size_t index) = 0;
virtual const MUse* getUseFor(size_t index) const = 0;
};
class AliasSet {
private:
uint32_t flags_;
public:
enum Flag {
None_ = 0,
ObjectFields = 1 << 0, // shape, class, slots, length etc.
Element = 1 << 1, // A Value member of obj->elements or
// a typed object.
UnboxedElement = 1 << 2, // An unboxed scalar or reference member of
// typed object.
DynamicSlot = 1 << 3, // A Value member of obj->slots.
FixedSlot = 1 << 4, // A Value member of obj->fixedSlots().
DOMProperty = 1 << 5, // A DOM property
WasmInstanceData = 1 << 6, // An asm.js/wasm private global var
WasmHeap = 1 << 7, // An asm.js/wasm heap load
WasmHeapMeta = 1 << 8, // The asm.js/wasm heap base pointer and
// bounds check limit, in Instance.
ArrayBufferViewLengthOrOffset =
1 << 9, // An array buffer view's length or byteOffset
WasmGlobalCell = 1 << 10, // A wasm global cell
WasmTableElement = 1 << 11, // An element of a wasm table
WasmTableMeta = 1 << 12, // A wasm table elements pointer and
// length field, in instance data.
WasmStackResult = 1 << 13, // A stack result from the current function
// JSContext's exception state. This is used on instructions like MThrow
// or MNewArrayDynamicLength that throw exceptions (other than OOM) but have
// no other side effect, to ensure that they get their own up-to-date resume
// point. (This resume point will be used when constructing the Baseline
// frame during exception bailouts.)
ExceptionState = 1 << 14,
// Used for instructions that load the privateSlot of DOM proxies and
// the ExpandoAndGeneration.
DOMProxyExpando = 1 << 15,
// Hash table of a Map or Set object.
MapOrSetHashTable = 1 << 16,
// Internal state of the random number generator
RNG = 1 << 17,
// The pendingException slot on the wasm instance object.
WasmPendingException = 1 << 18,
// The fuzzilliHash slot
FuzzilliHash = 1 << 19,
// The WasmStructObject::inlineData_[..] storage area
WasmStructInlineDataArea = 1 << 20,
// The WasmStructObject::outlineData_ pointer only
WasmStructOutlineDataPointer = 1 << 21,
// The malloc'd block that WasmStructObject::outlineData_ points at
WasmStructOutlineDataArea = 1 << 22,
// The WasmArrayObject::numElements_ field
WasmArrayNumElements = 1 << 23,
// The WasmArrayObject::data_ pointer only
WasmArrayDataPointer = 1 << 24,
// The malloc'd block that WasmArrayObject::data_ points at
WasmArrayDataArea = 1 << 25,
// The generation counter associated with the global object
GlobalGenerationCounter = 1 << 26,
// The SharedArrayRawBuffer::length field.
SharedArrayRawBufferLength = 1 << 27,
Last = SharedArrayRawBufferLength,
Any = Last | (Last - 1),
NumCategories = 28,
// Indicates load or store.
Store_ = 1 << 31
};
static_assert((1 << NumCategories) - 1 == Any,
"NumCategories must include all flags present in Any");
explicit AliasSet(uint32_t flags) : flags_(flags) {}
public:
inline bool isNone() const { return flags_ == None_; }
uint32_t flags() const { return flags_ & Any; }
inline bool isStore() const { return !!(flags_ & Store_); }
inline bool isLoad() const { return !isStore() && !isNone(); }
inline AliasSet operator|(const AliasSet& other) const {
return AliasSet(flags_ | other.flags_);
}
inline AliasSet operator&(const AliasSet& other) const {
return AliasSet(flags_ & other.flags_);
}
inline AliasSet operator~() const { return AliasSet(~flags_); }
static AliasSet None() { return AliasSet(None_); }
static AliasSet Load(uint32_t flags) {
MOZ_ASSERT(flags && !(flags & Store_));
return AliasSet(flags);
}
static AliasSet Store(uint32_t flags) {
MOZ_ASSERT(flags && !(flags & Store_));
return AliasSet(flags | Store_);
}
};
using MDefinitionVector = Vector<MDefinition*, 6, JitAllocPolicy>;
using MInstructionVector = Vector<MInstruction*, 6, JitAllocPolicy>;
// When a floating-point value is used by nodes which would prefer to
// receive integer inputs, we may be able to help by computing our result
// into an integer directly.
//
// A value can be truncated in 4 differents ways:
// 1. Ignore Infinities (x / 0 --> 0).
// 2. Ignore overflow (INT_MIN / -1 == (INT_MAX + 1) --> INT_MIN)
// 3. Ignore negative zeros. (-0 --> 0)
// 4. Ignore remainder. (3 / 4 --> 0)
//
// Indirect truncation is used to represent that we are interested in the
// truncated result, but only if it can safely flow into operations which
// are computed modulo 2^32, such as (2) and (3). Infinities are not safe,
// as they would have absorbed other math operations. Remainders are not
// safe, as fractions can be scaled up by multiplication.
//
// Division is a particularly interesting node here because it covers all 4
// cases even when its own operands are integers.
//
// Note that these enum values are ordered from least value-modifying to
// most value-modifying, and code relies on this ordering.
enum class TruncateKind {
// No correction.
NoTruncate = 0,
// An integer is desired, but we can't skip bailout checks.
TruncateAfterBailouts = 1,
// The value will be truncated after some arithmetic (see above).
IndirectTruncate = 2,
// Direct and infallible truncation to int32.
Truncate = 3
};
// An MDefinition is an SSA name.
class MDefinition : public MNode {
friend class MBasicBlock;
public:
enum class Opcode : uint16_t {
#define DEFINE_OPCODES(op) op,
MIR_OPCODE_LIST(DEFINE_OPCODES)
#undef DEFINE_OPCODES
};
private:
InlineList<MUse> uses_; // Use chain.
uint32_t id_; // Instruction ID, which after block re-ordering
// is sorted within a basic block.
Opcode op_; // Opcode.
uint16_t flags_; // Bit flags.
Range* range_; // Any computed range for this def.
union {
MDefinition*
loadDependency_; // Implicit dependency (store, call, etc.) of this
// instruction. Used by alias analysis, GVN and LICM.
uint32_t virtualRegister_; // Used by lowering to map definitions to
// virtual registers.
};
// Track bailouts by storing the current pc in MIR instruction. Also used
// for profiling and keeping track of what the last known pc was.
const BytecodeSite* trackedSite_;
// For nodes of MIRType::WasmAnyRef, a type precisely describing the value of
// the node. It is set by the "Track wasm ref types" pass in Ion, and enables
// GVN and LICM to perform more advanced optimizations (such as allowing
// instructions to move if the source values are non-null, or omitting casts
// that are statically known to succeed or fail).
wasm::MaybeRefType wasmRefType_;
// If we generate a bailout path for this instruction, this is the
// bailout kind that will be encoded in the snapshot. When we bail out,
// FinishBailoutToBaseline may take action based on the bailout kind to
// prevent bailout loops. (For example, if an instruction bails out after
// being hoisted by LICM, we will disable LICM when recompiling the script.)
BailoutKind bailoutKind_;
MIRType resultType_; // Representation of result type.
private:
enum Flag {
None = 0,
#define DEFINE_FLAG(flag) flag,
MIR_FLAG_LIST(DEFINE_FLAG)
#undef DEFINE_FLAG
Total
};
bool hasFlags(uint32_t flags) const { return (flags_ & flags) == flags; }
void removeFlags(uint32_t flags) { flags_ &= ~flags; }
void setFlags(uint32_t flags) { flags_ |= flags; }
// Calling isDefinition or isResumePoint on MDefinition is unnecessary.
bool isDefinition() const = delete;
bool isResumePoint() const = delete;
protected:
void setInstructionBlock(MBasicBlock* block, const BytecodeSite* site) {
MOZ_ASSERT(isInstruction());
setBlockAndKind(block, Kind::Definition);
setTrackedSite(site);
}
void setPhiBlock(MBasicBlock* block) {
MOZ_ASSERT(isPhi());
setBlockAndKind(block, Kind::Definition);
}
static HashNumber addU32ToHash(HashNumber hash, uint32_t data) {
return data + (hash << 6) + (hash << 16) - hash;
}
static HashNumber addU64ToHash(HashNumber hash, uint64_t data) {
hash = addU32ToHash(hash, uint32_t(data));
hash = addU32ToHash(hash, uint32_t(data >> 32));
return hash;
}
public:
explicit MDefinition(Opcode op)
: MNode(nullptr, Kind::Definition),
id_(0),
op_(op),
flags_(0),
range_(nullptr),
loadDependency_(nullptr),
trackedSite_(nullptr),
bailoutKind_(BailoutKind::Unknown),
resultType_(MIRType::None) {}
// Copying a definition leaves the list of uses empty.
explicit MDefinition(const MDefinition& other)
: MNode(other),
id_(0),
op_(other.op_),
flags_(other.flags_),
range_(other.range_),
loadDependency_(other.loadDependency_),
trackedSite_(other.trackedSite_),
bailoutKind_(other.bailoutKind_),
resultType_(other.resultType_) {}
Opcode op() const { return op_; }
#ifdef JS_JITSPEW
const char* opName() const;
void printName(GenericPrinter& out) const;
static void PrintOpcodeName(GenericPrinter& out, Opcode op);
virtual void printOpcode(GenericPrinter& out) const;
void dump(GenericPrinter& out) const override;
void dump() const override;
void dumpLocation(GenericPrinter& out) const;
void dumpLocation() const;
// Dump any other stuff the node wants to have printed in `extras`. The
// added strings are copied, with the `ExtrasCollector` taking ownership of
// the copies.
virtual void getExtras(ExtrasCollector* extras) const {}
#endif
// Also for LICM. Test whether this definition is likely to be a call, which
// would clobber all or many of the floating-point registers, such that
// hoisting floating-point constants out of containing loops isn't likely to
// be worthwhile.
virtual bool possiblyCalls() const { return false; }
MBasicBlock* block() const { return definitionBlock(); }
private:
void setTrackedSite(const BytecodeSite* site) {
MOZ_ASSERT(site);
trackedSite_ = site;
}
public:
const BytecodeSite* trackedSite() const {
MOZ_ASSERT(trackedSite_,
"missing tracked bytecode site; node not assigned to a block?");
return trackedSite_;
}
BailoutKind bailoutKind() const { return bailoutKind_; }
void setBailoutKind(BailoutKind kind) { bailoutKind_ = kind; }
// Return the range of this value, *before* any bailout checks. Contrast
// this with the type() method, and the Range constructor which takes an
// MDefinition*, which describe the value *after* any bailout checks.
//
// Warning: Range analysis is removing the bit-operations such as '| 0' at
// the end of the transformations. Using this function to analyse any
// operands after the truncate phase of the range analysis will lead to
// errors. Instead, one should define the collectRangeInfoPreTrunc() to set
// the right set of flags which are dependent on the range of the inputs.
Range* range() const {
MOZ_ASSERT(type() != MIRType::None);
return range_;
}
void setRange(Range* range) {
MOZ_ASSERT(type() != MIRType::None);
range_ = range;
}
virtual HashNumber valueHash() const;
virtual bool congruentTo(const MDefinition* ins) const { return false; }
const MDefinition* skipObjectGuards() const;
// Note that, for a call `congruentIfOperandsEqual(ins)` inside some class
// MFoo, if `true` is returned then we are ensured that `ins` is also an
// MFoo, so it is safe to do `ins->toMFoo()` without first checking whether
// `ins->isMFoo()`.
bool congruentIfOperandsEqual(const MDefinition* ins) const;
virtual MDefinition* foldsTo(TempAllocator& alloc);
virtual void analyzeEdgeCasesForward();
virtual void analyzeEdgeCasesBackward();
// |canTruncate| reports if this instruction supports truncation. If
// |canTruncate| function returns true, then the |truncate| function is
// called on the same instruction to mutate the instruction, such as updating
// the return type, the range and the specialization of the instruction.
virtual bool canTruncate() const;
virtual void truncate(TruncateKind kind);
// Determine what kind of truncate this node prefers for the operand at the
// given index.
virtual TruncateKind operandTruncateKind(size_t index) const;
// Compute an absolute or symbolic range for the value of this node.
virtual void computeRange(TempAllocator& alloc) {}
// Collect information from the pre-truncated ranges.
virtual void collectRangeInfoPreTrunc() {}
uint32_t id() const {
MOZ_ASSERT(block());
return id_;
}
void setId(uint32_t id) { id_ = id; }
#define FLAG_ACCESSOR(flag) \
bool is##flag() const { \
static_assert(Flag::Total <= sizeof(flags_) * 8, \
"Flags should fit in flags_ field"); \
return hasFlags(1 << flag); \
} \
void set##flag() { \
MOZ_ASSERT(!hasFlags(1 << flag)); \
setFlags(1 << flag); \
} \
void setNot##flag() { \
MOZ_ASSERT(hasFlags(1 << flag)); \
removeFlags(1 << flag); \
} \
void set##flag##Unchecked() { setFlags(1 << flag); } \
void setNot##flag##Unchecked() { removeFlags(1 << flag); }
MIR_FLAG_LIST(FLAG_ACCESSOR)
#undef FLAG_ACCESSOR
// Return the type of this value. This may be speculative, and enforced
// dynamically with the use of bailout checks. If all the bailout checks
// pass, the value will have this type.
//
// Unless this is an MUrsh that has bailouts disabled, which, as a special
// case, may return a value in (INT32_MAX,UINT32_MAX] even when its type()
// is MIRType::Int32.
MIRType type() const { return resultType_; }
// Default EnumSet serialization is based on the enum's underlying type, which
// means uint8_t for MIRType. To store all possible MIRType values we need at
// least uint32_t.
using MIRTypeEnumSet = mozilla::EnumSet<MIRType, uint32_t>;
static_assert(static_cast<size_t>(MIRType::Last) <
sizeof(MIRTypeEnumSet::serializedType) * CHAR_BIT);
// Get the wasm reference type stored on the node. Do NOT use in congruentTo,
// as this value can change throughout the optimization process. See
// ReplaceAllUsesWith in ValueNumbering.cpp.
wasm::MaybeRefType wasmRefType() const { return wasmRefType_; }
// Sets the wasm reference type stored on the node. Does not check if there
// was already a type on the node, which may lead to bugs; consider using
// `initWasmRefType` instead if it applies.
void setWasmRefType(wasm::MaybeRefType refType) { wasmRefType_ = refType; }
// Sets the wasm reference type stored on the node. To be used for nodes that
// have a fixed ref type that is set up front, which is a common case. Must be
// called only during the node constructor and never again afterward.
void initWasmRefType(wasm::MaybeRefType refType) {
MOZ_ASSERT(!wasmRefType_);
setWasmRefType(refType);
}
// Compute the wasm reference type for this node. This method is called by
// updateWasmRefType. By default it returns the ref type stored on the node,
// which means it will return either Nothing or a value set by
// initWasmRefType.
virtual wasm::MaybeRefType computeWasmRefType() const { return wasmRefType_; }
// Return true if the result type is a member of the given types.
bool typeIsOneOf(MIRTypeEnumSet types) const {
MOZ_ASSERT(!types.isEmpty());
return types.contains(type());
}
// Float32 specialization operations (see big comment in IonAnalysis before
// the Float32 specialization algorithm).
virtual bool isFloat32Commutative() const { return false; }
virtual bool canProduceFloat32() const { return false; }
virtual bool canConsumeFloat32(MUse* use) const { return false; }
virtual void trySpecializeFloat32(TempAllocator& alloc) {}
#ifdef DEBUG
// Used during the pass that checks that Float32 flow into valid MDefinitions
virtual bool isConsistentFloat32Use(MUse* use) const {
return type() == MIRType::Float32 || canConsumeFloat32(use);
}
#endif
// Returns the beginning of this definition's use chain.
MUseIterator usesBegin() const { return uses_.begin(); }
// Returns the end of this definition's use chain.
MUseIterator usesEnd() const { return uses_.end(); }
bool canEmitAtUses() const { return !isEmittedAtUses(); }
// Removes a use at the given position
void removeUse(MUse* use) { uses_.remove(use); }
#if defined(DEBUG) || defined(JS_JITSPEW)
// Number of uses of this instruction. This function is only available
// in DEBUG mode since it requires traversing the list. Most users should
// use hasUses() or hasOneUse() instead.
size_t useCount() const;
// Number of uses of this instruction (only counting MDefinitions, ignoring
// MResumePoints). This function is only available in DEBUG mode since it
// requires traversing the list. Most users should use hasUses() or
// hasOneUse() instead.
size_t defUseCount() const;
#endif
// Test whether this MDefinition has exactly one use.
bool hasOneUse() const;
// Test whether this MDefinition has exactly one use.
// (only counting MDefinitions, ignoring MResumePoints)
bool hasOneDefUse() const;
// Test whether this MDefinition has exactly one live use. (only counting
// MDefinitions which are not recovered on bailout and ignoring MResumePoints)
bool hasOneLiveDefUse() const;
// Test whether this MDefinition has at least one use.
// (only counting MDefinitions, ignoring MResumePoints)
bool hasDefUses() const;
// Test whether this MDefinition has at least one non-recovered use.
// (only counting MDefinitions, ignoring MResumePoints)
bool hasLiveDefUses() const;
bool hasUses() const { return !uses_.empty(); }
// If this MDefinition has a single use (ignoring MResumePoints), returns that
// use's definition. Else returns nullptr.
MDefinition* maybeSingleDefUse() const;
// Returns the most recently added use (ignoring MResumePoints) for this
// MDefinition. Returns nullptr if there are no uses. Note that this relies on
// addUse adding new uses to the front of the list, and should only be called
// during MIR building (before optimization passes make changes to the uses).
MDefinition* maybeMostRecentlyAddedDefUse() const;
void addUse(MUse* use) {
MOZ_ASSERT(use->producer() == this);
uses_.pushFront(use);
}
void addUseUnchecked(MUse* use) {
MOZ_ASSERT(use->producer() == this);
uses_.pushFrontUnchecked(use);
}
void replaceUse(MUse* old, MUse* now) {
MOZ_ASSERT(now->producer() == this);
uses_.replace(old, now);
}
// Replace the current instruction by a dominating instruction |dom| in all
// uses of the current instruction.
void replaceAllUsesWith(MDefinition* dom);
// Like replaceAllUsesWith, but doesn't set ImplicitlyUsed on |this|'s
// operands.
void justReplaceAllUsesWith(MDefinition* dom);
// Replace the current instruction by an optimized-out constant in all uses
// of the current instruction. Note, that optimized-out constant should not
// be observed, and thus they should not flow in any computation.
[[nodiscard]] bool optimizeOutAllUses(TempAllocator& alloc);
// Replace the current instruction by a dominating instruction |dom| in all
// instruction, but keep the current instruction for resume point and
// instruction which are recovered on bailouts.
void replaceAllLiveUsesWith(MDefinition* dom);
void setVirtualRegister(uint32_t vreg) {
virtualRegister_ = vreg;
setLoweredUnchecked();
}
uint32_t virtualRegister() const {
MOZ_ASSERT(isLowered());
return virtualRegister_;
}
public:
// Opcode testing and casts.
template <typename MIRType>
bool is() const {
return op() == MIRType::classOpcode;
}
template <typename MIRType>
MIRType* to() {
MOZ_ASSERT(this->is<MIRType>());
return static_cast<MIRType*>(this);
}
template <typename MIRType>
const MIRType* to() const {
MOZ_ASSERT(this->is<MIRType>());
return static_cast<const MIRType*>(this);
}
#define OPCODE_CASTS(opcode) \
bool is##opcode() const { return this->is<M##opcode>(); } \
M##opcode* to##opcode() { return this->to<M##opcode>(); } \
const M##opcode* to##opcode() const { return this->to<M##opcode>(); }