Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:31

0001 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file contains the declaration of the MachineInstr class, which is the
0010 // basic representation for all target dependent machine instructions used by
0011 // the back end.
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
0016 #define LLVM_CODEGEN_MACHINEINSTR_H
0017 
0018 #include "llvm/ADT/DenseMapInfo.h"
0019 #include "llvm/ADT/PointerSumType.h"
0020 #include "llvm/ADT/ilist.h"
0021 #include "llvm/ADT/ilist_node.h"
0022 #include "llvm/ADT/iterator_range.h"
0023 #include "llvm/Analysis/MemoryLocation.h"
0024 #include "llvm/CodeGen/MachineMemOperand.h"
0025 #include "llvm/CodeGen/MachineOperand.h"
0026 #include "llvm/CodeGen/TargetOpcodes.h"
0027 #include "llvm/IR/DebugLoc.h"
0028 #include "llvm/IR/InlineAsm.h"
0029 #include "llvm/MC/MCInstrDesc.h"
0030 #include "llvm/MC/MCSymbol.h"
0031 #include "llvm/Support/ArrayRecycler.h"
0032 #include "llvm/Support/MathExtras.h"
0033 #include "llvm/Support/TrailingObjects.h"
0034 #include <algorithm>
0035 #include <cassert>
0036 #include <cstdint>
0037 #include <utility>
0038 
0039 namespace llvm {
0040 
0041 class DILabel;
0042 class Instruction;
0043 class MDNode;
0044 class AAResults;
0045 class BatchAAResults;
0046 template <typename T> class ArrayRef;
0047 class DIExpression;
0048 class DILocalVariable;
0049 class LiveRegUnits;
0050 class MachineBasicBlock;
0051 class MachineFunction;
0052 class MachineRegisterInfo;
0053 class ModuleSlotTracker;
0054 class raw_ostream;
0055 template <typename T> class SmallVectorImpl;
0056 class SmallBitVector;
0057 class StringRef;
0058 class TargetInstrInfo;
0059 class TargetRegisterClass;
0060 class TargetRegisterInfo;
0061 
0062 //===----------------------------------------------------------------------===//
0063 /// Representation of each machine instruction.
0064 ///
0065 /// This class isn't a POD type, but it must have a trivial destructor. When a
0066 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
0067 /// without having their destructor called.
0068 ///
0069 class MachineInstr
0070     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
0071                                     ilist_sentinel_tracking<true>> {
0072 public:
0073   using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
0074 
0075   /// Flags to specify different kinds of comments to output in
0076   /// assembly code.  These flags carry semantic information not
0077   /// otherwise easily derivable from the IR text.
0078   ///
0079   enum CommentFlag {
0080     ReloadReuse = 0x1,    // higher bits are reserved for target dep comments.
0081     NoSchedComment = 0x2,
0082     TAsmComments = 0x4    // Target Asm comments should start from this value.
0083   };
0084 
0085   enum MIFlag {
0086     NoFlags = 0,
0087     FrameSetup = 1 << 0,     // Instruction is used as a part of
0088                              // function frame setup code.
0089     FrameDestroy = 1 << 1,   // Instruction is used as a part of
0090                              // function frame destruction code.
0091     BundledPred = 1 << 2,    // Instruction has bundled predecessors.
0092     BundledSucc = 1 << 3,    // Instruction has bundled successors.
0093     FmNoNans = 1 << 4,       // Instruction does not support Fast
0094                              // math nan values.
0095     FmNoInfs = 1 << 5,       // Instruction does not support Fast
0096                              // math infinity values.
0097     FmNsz = 1 << 6,          // Instruction is not required to retain
0098                              // signed zero values.
0099     FmArcp = 1 << 7,         // Instruction supports Fast math
0100                              // reciprocal approximations.
0101     FmContract = 1 << 8,     // Instruction supports Fast math
0102                              // contraction operations like fma.
0103     FmAfn = 1 << 9,          // Instruction may map to Fast math
0104                              // intrinsic approximation.
0105     FmReassoc = 1 << 10,     // Instruction supports Fast math
0106                              // reassociation of operand order.
0107     NoUWrap = 1 << 11,       // Instruction supports binary operator
0108                              // no unsigned wrap.
0109     NoSWrap = 1 << 12,       // Instruction supports binary operator
0110                              // no signed wrap.
0111     IsExact = 1 << 13,       // Instruction supports division is
0112                              // known to be exact.
0113     NoFPExcept = 1 << 14,    // Instruction does not raise
0114                              // floatint-point exceptions.
0115     NoMerge = 1 << 15,       // Passes that drop source location info
0116                              // (e.g. branch folding) should skip
0117                              // this instruction.
0118     Unpredictable = 1 << 16, // Instruction with unpredictable condition.
0119     NoConvergent = 1 << 17,  // Call does not require convergence guarantees.
0120     NonNeg = 1 << 18,        // The operand is non-negative.
0121     Disjoint = 1 << 19,      // Each bit is zero in at least one of the inputs.
0122     NoUSWrap = 1 << 20,      // Instruction supports geps
0123                              // no unsigned signed wrap.
0124     SameSign = 1 << 21       // Both operands have the same sign.
0125   };
0126 
0127 private:
0128   const MCInstrDesc *MCID;              // Instruction descriptor.
0129   MachineBasicBlock *Parent = nullptr;  // Pointer to the owning basic block.
0130 
0131   // Operands are allocated by an ArrayRecycler.
0132   MachineOperand *Operands = nullptr;   // Pointer to the first operand.
0133 
0134 #define LLVM_MI_NUMOPERANDS_BITS 24
0135 #define LLVM_MI_FLAGS_BITS 24
0136 #define LLVM_MI_ASMPRINTERFLAGS_BITS 8
0137 
0138   /// Number of operands on instruction.
0139   uint32_t NumOperands : LLVM_MI_NUMOPERANDS_BITS;
0140 
0141   // OperandCapacity has uint8_t size, so it should be next to NumOperands
0142   // to properly pack.
0143   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
0144   OperandCapacity CapOperands;          // Capacity of the Operands array.
0145 
0146   /// Various bits of additional information about the machine instruction.
0147   uint32_t Flags : LLVM_MI_FLAGS_BITS;
0148 
0149   /// Various bits of information used by the AsmPrinter to emit helpful
0150   /// comments.  This is *not* semantic information.  Do not use this for
0151   /// anything other than to convey comment information to AsmPrinter.
0152   uint8_t AsmPrinterFlags : LLVM_MI_ASMPRINTERFLAGS_BITS;
0153 
0154   /// Internal implementation detail class that provides out-of-line storage for
0155   /// extra info used by the machine instruction when this info cannot be stored
0156   /// in-line within the instruction itself.
0157   ///
0158   /// This has to be defined eagerly due to the implementation constraints of
0159   /// `PointerSumType` where it is used.
0160   class ExtraInfo final : TrailingObjects<ExtraInfo, MachineMemOperand *,
0161                                           MCSymbol *, MDNode *, uint32_t> {
0162   public:
0163     static ExtraInfo *create(BumpPtrAllocator &Allocator,
0164                              ArrayRef<MachineMemOperand *> MMOs,
0165                              MCSymbol *PreInstrSymbol = nullptr,
0166                              MCSymbol *PostInstrSymbol = nullptr,
0167                              MDNode *HeapAllocMarker = nullptr,
0168                              MDNode *PCSections = nullptr, uint32_t CFIType = 0,
0169                              MDNode *MMRAs = nullptr) {
0170       bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
0171       bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
0172       bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
0173       bool HasMMRAs = MMRAs != nullptr;
0174       bool HasCFIType = CFIType != 0;
0175       bool HasPCSections = PCSections != nullptr;
0176       auto *Result = new (Allocator.Allocate(
0177           totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *, uint32_t>(
0178               MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
0179               HasHeapAllocMarker + HasPCSections + HasMMRAs, HasCFIType),
0180           alignof(ExtraInfo)))
0181           ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
0182                     HasHeapAllocMarker, HasPCSections, HasCFIType, HasMMRAs);
0183 
0184       // Copy the actual data into the trailing objects.
0185       std::copy(MMOs.begin(), MMOs.end(),
0186                 Result->getTrailingObjects<MachineMemOperand *>());
0187 
0188       unsigned MDNodeIdx = 0;
0189 
0190       if (HasPreInstrSymbol)
0191         Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
0192       if (HasPostInstrSymbol)
0193         Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
0194             PostInstrSymbol;
0195       if (HasHeapAllocMarker)
0196         Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = HeapAllocMarker;
0197       if (HasPCSections)
0198         Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = PCSections;
0199       if (HasCFIType)
0200         Result->getTrailingObjects<uint32_t>()[0] = CFIType;
0201       if (HasMMRAs)
0202         Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = MMRAs;
0203 
0204       return Result;
0205     }
0206 
0207     ArrayRef<MachineMemOperand *> getMMOs() const {
0208       return ArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
0209     }
0210 
0211     MCSymbol *getPreInstrSymbol() const {
0212       return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
0213     }
0214 
0215     MCSymbol *getPostInstrSymbol() const {
0216       return HasPostInstrSymbol
0217                  ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
0218                  : nullptr;
0219     }
0220 
0221     MDNode *getHeapAllocMarker() const {
0222       return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
0223     }
0224 
0225     MDNode *getPCSections() const {
0226       return HasPCSections
0227                  ? getTrailingObjects<MDNode *>()[HasHeapAllocMarker]
0228                  : nullptr;
0229     }
0230 
0231     uint32_t getCFIType() const {
0232       return HasCFIType ? getTrailingObjects<uint32_t>()[0] : 0;
0233     }
0234 
0235     MDNode *getMMRAMetadata() const {
0236       return HasMMRAs ? getTrailingObjects<MDNode *>()[HasHeapAllocMarker +
0237                                                        HasPCSections]
0238                       : nullptr;
0239     }
0240 
0241   private:
0242     friend TrailingObjects;
0243 
0244     // Description of the extra info, used to interpret the actual optional
0245     // data appended.
0246     //
0247     // Note that this is not terribly space optimized. This leaves a great deal
0248     // of flexibility to fit more in here later.
0249     const int NumMMOs;
0250     const bool HasPreInstrSymbol;
0251     const bool HasPostInstrSymbol;
0252     const bool HasHeapAllocMarker;
0253     const bool HasPCSections;
0254     const bool HasCFIType;
0255     const bool HasMMRAs;
0256 
0257     // Implement the `TrailingObjects` internal API.
0258     size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
0259       return NumMMOs;
0260     }
0261     size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
0262       return HasPreInstrSymbol + HasPostInstrSymbol;
0263     }
0264     size_t numTrailingObjects(OverloadToken<MDNode *>) const {
0265       return HasHeapAllocMarker + HasPCSections;
0266     }
0267     size_t numTrailingObjects(OverloadToken<uint32_t>) const {
0268       return HasCFIType;
0269     }
0270 
0271     // Just a boring constructor to allow us to initialize the sizes. Always use
0272     // the `create` routine above.
0273     ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
0274               bool HasHeapAllocMarker, bool HasPCSections, bool HasCFIType,
0275               bool HasMMRAs)
0276         : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
0277           HasPostInstrSymbol(HasPostInstrSymbol),
0278           HasHeapAllocMarker(HasHeapAllocMarker), HasPCSections(HasPCSections),
0279           HasCFIType(HasCFIType), HasMMRAs(HasMMRAs) {}
0280   };
0281 
0282   /// Enumeration of the kinds of inline extra info available. It is important
0283   /// that the `MachineMemOperand` inline kind has a tag value of zero to make
0284   /// it accessible as an `ArrayRef`.
0285   enum ExtraInfoInlineKinds {
0286     EIIK_MMO = 0,
0287     EIIK_PreInstrSymbol,
0288     EIIK_PostInstrSymbol,
0289     EIIK_OutOfLine
0290   };
0291 
0292   // We store extra information about the instruction here. The common case is
0293   // expected to be nothing or a single pointer (typically a MMO or a symbol).
0294   // We work to optimize this common case by storing it inline here rather than
0295   // requiring a separate allocation, but we fall back to an allocation when
0296   // multiple pointers are needed.
0297   PointerSumType<ExtraInfoInlineKinds,
0298                  PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
0299                  PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
0300                  PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
0301                  PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
0302       Info;
0303 
0304   DebugLoc DbgLoc; // Source line information.
0305 
0306   /// Unique instruction number. Used by DBG_INSTR_REFs to refer to the values
0307   /// defined by this instruction.
0308   unsigned DebugInstrNum;
0309 
0310   /// Cached opcode from MCID.
0311   uint16_t Opcode;
0312 
0313   // Intrusive list support
0314   friend struct ilist_traits<MachineInstr>;
0315   friend struct ilist_callback_traits<MachineBasicBlock>;
0316   void setParent(MachineBasicBlock *P) { Parent = P; }
0317 
0318   /// This constructor creates a copy of the given
0319   /// MachineInstr in the given MachineFunction.
0320   MachineInstr(MachineFunction &, const MachineInstr &);
0321 
0322   /// This constructor create a MachineInstr and add the implicit operands.
0323   /// It reserves space for number of operands specified by
0324   /// MCInstrDesc.  An explicit DebugLoc is supplied.
0325   MachineInstr(MachineFunction &, const MCInstrDesc &TID, DebugLoc DL,
0326                bool NoImp = false);
0327 
0328   // MachineInstrs are pool-allocated and owned by MachineFunction.
0329   friend class MachineFunction;
0330 
0331   void
0332   dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
0333             SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const;
0334 
0335   static bool opIsRegDef(const MachineOperand &Op) {
0336     return Op.isReg() && Op.isDef();
0337   }
0338 
0339   static bool opIsRegUse(const MachineOperand &Op) {
0340     return Op.isReg() && Op.isUse();
0341   }
0342 
0343 public:
0344   MachineInstr(const MachineInstr &) = delete;
0345   MachineInstr &operator=(const MachineInstr &) = delete;
0346   // Use MachineFunction::DeleteMachineInstr() instead.
0347   ~MachineInstr() = delete;
0348 
0349   const MachineBasicBlock* getParent() const { return Parent; }
0350   MachineBasicBlock* getParent() { return Parent; }
0351 
0352   /// Move the instruction before \p MovePos.
0353   void moveBefore(MachineInstr *MovePos);
0354 
0355   /// Return the function that contains the basic block that this instruction
0356   /// belongs to.
0357   ///
0358   /// Note: this is undefined behaviour if the instruction does not have a
0359   /// parent.
0360   const MachineFunction *getMF() const;
0361   MachineFunction *getMF() {
0362     return const_cast<MachineFunction *>(
0363         static_cast<const MachineInstr *>(this)->getMF());
0364   }
0365 
0366   /// Return the asm printer flags bitvector.
0367   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
0368 
0369   /// Clear the AsmPrinter bitvector.
0370   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
0371 
0372   /// Return whether an AsmPrinter flag is set.
0373   bool getAsmPrinterFlag(CommentFlag Flag) const {
0374     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
0375            "Flag is out of range for the AsmPrinterFlags field");
0376     return AsmPrinterFlags & Flag;
0377   }
0378 
0379   /// Set a flag for the AsmPrinter.
0380   void setAsmPrinterFlag(uint8_t Flag) {
0381     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
0382            "Flag is out of range for the AsmPrinterFlags field");
0383     AsmPrinterFlags |= Flag;
0384   }
0385 
0386   /// Clear specific AsmPrinter flags.
0387   void clearAsmPrinterFlag(CommentFlag Flag) {
0388     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
0389            "Flag is out of range for the AsmPrinterFlags field");
0390     AsmPrinterFlags &= ~Flag;
0391   }
0392 
0393   /// Return the MI flags bitvector.
0394   uint32_t getFlags() const {
0395     return Flags;
0396   }
0397 
0398   /// Return whether an MI flag is set.
0399   bool getFlag(MIFlag Flag) const {
0400     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
0401            "Flag is out of range for the Flags field");
0402     return Flags & Flag;
0403   }
0404 
0405   /// Set a MI flag.
0406   void setFlag(MIFlag Flag) {
0407     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
0408            "Flag is out of range for the Flags field");
0409     Flags |= (uint32_t)Flag;
0410   }
0411 
0412   void setFlags(unsigned flags) {
0413     assert(isUInt<LLVM_MI_FLAGS_BITS>(flags) &&
0414            "flags to be set are out of range for the Flags field");
0415     // Filter out the automatically maintained flags.
0416     unsigned Mask = BundledPred | BundledSucc;
0417     Flags = (Flags & Mask) | (flags & ~Mask);
0418   }
0419 
0420   /// clearFlag - Clear a MI flag.
0421   void clearFlag(MIFlag Flag) {
0422     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
0423            "Flag to clear is out of range for the Flags field");
0424     Flags &= ~((uint32_t)Flag);
0425   }
0426 
0427   void clearFlags(unsigned flags) {
0428     assert(isUInt<LLVM_MI_FLAGS_BITS>(flags) &&
0429            "flags to be cleared are out of range for the Flags field");
0430     Flags &= ~flags;
0431   }
0432 
0433   /// Return true if MI is in a bundle (but not the first MI in a bundle).
0434   ///
0435   /// A bundle looks like this before it's finalized:
0436   ///   ----------------
0437   ///   |      MI      |
0438   ///   ----------------
0439   ///          |
0440   ///   ----------------
0441   ///   |      MI    * |
0442   ///   ----------------
0443   ///          |
0444   ///   ----------------
0445   ///   |      MI    * |
0446   ///   ----------------
0447   /// In this case, the first MI starts a bundle but is not inside a bundle, the
0448   /// next 2 MIs are considered "inside" the bundle.
0449   ///
0450   /// After a bundle is finalized, it looks like this:
0451   ///   ----------------
0452   ///   |    Bundle    |
0453   ///   ----------------
0454   ///          |
0455   ///   ----------------
0456   ///   |      MI    * |
0457   ///   ----------------
0458   ///          |
0459   ///   ----------------
0460   ///   |      MI    * |
0461   ///   ----------------
0462   ///          |
0463   ///   ----------------
0464   ///   |      MI    * |
0465   ///   ----------------
0466   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
0467   /// a bundle, but the next three MIs are.
0468   bool isInsideBundle() const {
0469     return getFlag(BundledPred);
0470   }
0471 
0472   /// Return true if this instruction part of a bundle. This is true
0473   /// if either itself or its following instruction is marked "InsideBundle".
0474   bool isBundled() const {
0475     return isBundledWithPred() || isBundledWithSucc();
0476   }
0477 
0478   /// Return true if this instruction is part of a bundle, and it is not the
0479   /// first instruction in the bundle.
0480   bool isBundledWithPred() const { return getFlag(BundledPred); }
0481 
0482   /// Return true if this instruction is part of a bundle, and it is not the
0483   /// last instruction in the bundle.
0484   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
0485 
0486   /// Bundle this instruction with its predecessor. This can be an unbundled
0487   /// instruction, or it can be the first instruction in a bundle.
0488   void bundleWithPred();
0489 
0490   /// Bundle this instruction with its successor. This can be an unbundled
0491   /// instruction, or it can be the last instruction in a bundle.
0492   void bundleWithSucc();
0493 
0494   /// Break bundle above this instruction.
0495   void unbundleFromPred();
0496 
0497   /// Break bundle below this instruction.
0498   void unbundleFromSucc();
0499 
0500   /// Returns the debug location id of this MachineInstr.
0501   const DebugLoc &getDebugLoc() const { return DbgLoc; }
0502 
0503   /// Return the operand containing the offset to be used if this DBG_VALUE
0504   /// instruction is indirect; will be an invalid register if this value is
0505   /// not indirect, and an immediate with value 0 otherwise.
0506   const MachineOperand &getDebugOffset() const {
0507     assert(isNonListDebugValue() && "not a DBG_VALUE");
0508     return getOperand(1);
0509   }
0510   MachineOperand &getDebugOffset() {
0511     assert(isNonListDebugValue() && "not a DBG_VALUE");
0512     return getOperand(1);
0513   }
0514 
0515   /// Return the operand for the debug variable referenced by
0516   /// this DBG_VALUE instruction.
0517   const MachineOperand &getDebugVariableOp() const;
0518   MachineOperand &getDebugVariableOp();
0519 
0520   /// Return the debug variable referenced by
0521   /// this DBG_VALUE instruction.
0522   const DILocalVariable *getDebugVariable() const;
0523 
0524   /// Return the operand for the complex address expression referenced by
0525   /// this DBG_VALUE instruction.
0526   const MachineOperand &getDebugExpressionOp() const;
0527   MachineOperand &getDebugExpressionOp();
0528 
0529   /// Return the complex address expression referenced by
0530   /// this DBG_VALUE instruction.
0531   const DIExpression *getDebugExpression() const;
0532 
0533   /// Return the debug label referenced by
0534   /// this DBG_LABEL instruction.
0535   const DILabel *getDebugLabel() const;
0536 
0537   /// Fetch the instruction number of this MachineInstr. If it does not have
0538   /// one already, a new and unique number will be assigned.
0539   unsigned getDebugInstrNum();
0540 
0541   /// Fetch instruction number of this MachineInstr -- but before it's inserted
0542   /// into \p MF. Needed for transformations that create an instruction but
0543   /// don't immediately insert them.
0544   unsigned getDebugInstrNum(MachineFunction &MF);
0545 
0546   /// Examine the instruction number of this MachineInstr. May be zero if
0547   /// it hasn't been assigned a number yet.
0548   unsigned peekDebugInstrNum() const { return DebugInstrNum; }
0549 
0550   /// Set instruction number of this MachineInstr. Avoid using unless you're
0551   /// deserializing this information.
0552   void setDebugInstrNum(unsigned Num) { DebugInstrNum = Num; }
0553 
0554   /// Drop any variable location debugging information associated with this
0555   /// instruction. Use when an instruction is modified in such a way that it no
0556   /// longer defines the value it used to. Variable locations using that value
0557   /// will be dropped.
0558   void dropDebugNumber() { DebugInstrNum = 0; }
0559 
0560   /// For inline asm, get the !srcloc metadata node if we have it, and decode
0561   /// the loc cookie from it.
0562   const MDNode *getLocCookieMD() const;
0563 
0564   /// Emit an error referring to the source location of this instruction. This
0565   /// should only be used for inline assembly that is somehow impossible to
0566   /// compile. Other errors should have been handled much earlier.
0567   void emitInlineAsmError(const Twine &ErrMsg) const;
0568 
0569   // Emit an error in the LLVMContext referring to the source location of this
0570   // instruction, if available.
0571   void emitGenericError(const Twine &ErrMsg) const;
0572 
0573   /// Returns the target instruction descriptor of this MachineInstr.
0574   const MCInstrDesc &getDesc() const { return *MCID; }
0575 
0576   /// Returns the opcode of this MachineInstr.
0577   unsigned getOpcode() const { return Opcode; }
0578 
0579   /// Retuns the total number of operands.
0580   unsigned getNumOperands() const { return NumOperands; }
0581 
0582   /// Returns the total number of operands which are debug locations.
0583   unsigned getNumDebugOperands() const {
0584     return std::distance(debug_operands().begin(), debug_operands().end());
0585   }
0586 
0587   const MachineOperand& getOperand(unsigned i) const {
0588     assert(i < getNumOperands() && "getOperand() out of range!");
0589     return Operands[i];
0590   }
0591   MachineOperand& getOperand(unsigned i) {
0592     assert(i < getNumOperands() && "getOperand() out of range!");
0593     return Operands[i];
0594   }
0595 
0596   MachineOperand &getDebugOperand(unsigned Index) {
0597     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
0598     return *(debug_operands().begin() + Index);
0599   }
0600   const MachineOperand &getDebugOperand(unsigned Index) const {
0601     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
0602     return *(debug_operands().begin() + Index);
0603   }
0604 
0605   /// Returns whether this debug value has at least one debug operand with the
0606   /// register \p Reg.
0607   bool hasDebugOperandForReg(Register Reg) const {
0608     return any_of(debug_operands(), [Reg](const MachineOperand &Op) {
0609       return Op.isReg() && Op.getReg() == Reg;
0610     });
0611   }
0612 
0613   /// Returns a range of all of the operands that correspond to a debug use of
0614   /// \p Reg.
0615   template <typename Operand, typename Instruction>
0616   static iterator_range<
0617       filter_iterator<Operand *, std::function<bool(Operand &Op)>>>
0618   getDebugOperandsForReg(Instruction *MI, Register Reg) {
0619     std::function<bool(Operand & Op)> OpUsesReg(
0620         [Reg](Operand &Op) { return Op.isReg() && Op.getReg() == Reg; });
0621     return make_filter_range(MI->debug_operands(), OpUsesReg);
0622   }
0623   iterator_range<filter_iterator<const MachineOperand *,
0624                                  std::function<bool(const MachineOperand &Op)>>>
0625   getDebugOperandsForReg(Register Reg) const {
0626     return MachineInstr::getDebugOperandsForReg<const MachineOperand,
0627                                                 const MachineInstr>(this, Reg);
0628   }
0629   iterator_range<filter_iterator<MachineOperand *,
0630                                  std::function<bool(MachineOperand &Op)>>>
0631   getDebugOperandsForReg(Register Reg) {
0632     return MachineInstr::getDebugOperandsForReg<MachineOperand, MachineInstr>(
0633         this, Reg);
0634   }
0635 
0636   bool isDebugOperand(const MachineOperand *Op) const {
0637     return Op >= adl_begin(debug_operands()) && Op <= adl_end(debug_operands());
0638   }
0639 
0640   unsigned getDebugOperandIndex(const MachineOperand *Op) const {
0641     assert(isDebugOperand(Op) && "Expected a debug operand.");
0642     return std::distance(adl_begin(debug_operands()), Op);
0643   }
0644 
0645   /// Returns the total number of definitions.
0646   unsigned getNumDefs() const {
0647     return getNumExplicitDefs() + MCID->implicit_defs().size();
0648   }
0649 
0650   /// Returns true if the instruction has implicit definition.
0651   bool hasImplicitDef() const {
0652     for (const MachineOperand &MO : implicit_operands())
0653       if (MO.isDef())
0654         return true;
0655     return false;
0656   }
0657 
0658   /// Returns the implicit operands number.
0659   unsigned getNumImplicitOperands() const {
0660     return getNumOperands() - getNumExplicitOperands();
0661   }
0662 
0663   /// Return true if operand \p OpIdx is a subregister index.
0664   bool isOperandSubregIdx(unsigned OpIdx) const {
0665     assert(getOperand(OpIdx).isImm() && "Expected MO_Immediate operand type.");
0666     if (isExtractSubreg() && OpIdx == 2)
0667       return true;
0668     if (isInsertSubreg() && OpIdx == 3)
0669       return true;
0670     if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
0671       return true;
0672     if (isSubregToReg() && OpIdx == 3)
0673       return true;
0674     return false;
0675   }
0676 
0677   /// Returns the number of non-implicit operands.
0678   unsigned getNumExplicitOperands() const;
0679 
0680   /// Returns the number of non-implicit definitions.
0681   unsigned getNumExplicitDefs() const;
0682 
0683   /// iterator/begin/end - Iterate over all operands of a machine instruction.
0684   using mop_iterator = MachineOperand *;
0685   using const_mop_iterator = const MachineOperand *;
0686 
0687   mop_iterator operands_begin() { return Operands; }
0688   mop_iterator operands_end() { return Operands + NumOperands; }
0689 
0690   const_mop_iterator operands_begin() const { return Operands; }
0691   const_mop_iterator operands_end() const { return Operands + NumOperands; }
0692 
0693   iterator_range<mop_iterator> operands() {
0694     return make_range(operands_begin(), operands_end());
0695   }
0696   iterator_range<const_mop_iterator> operands() const {
0697     return make_range(operands_begin(), operands_end());
0698   }
0699   iterator_range<mop_iterator> explicit_operands() {
0700     return make_range(operands_begin(),
0701                       operands_begin() + getNumExplicitOperands());
0702   }
0703   iterator_range<const_mop_iterator> explicit_operands() const {
0704     return make_range(operands_begin(),
0705                       operands_begin() + getNumExplicitOperands());
0706   }
0707   iterator_range<mop_iterator> implicit_operands() {
0708     return make_range(explicit_operands().end(), operands_end());
0709   }
0710   iterator_range<const_mop_iterator> implicit_operands() const {
0711     return make_range(explicit_operands().end(), operands_end());
0712   }
0713   /// Returns a range over all operands that are used to determine the variable
0714   /// location for this DBG_VALUE instruction.
0715   iterator_range<mop_iterator> debug_operands() {
0716     assert((isDebugValueLike()) && "Must be a debug value instruction.");
0717     return isNonListDebugValue()
0718                ? make_range(operands_begin(), operands_begin() + 1)
0719                : make_range(operands_begin() + 2, operands_end());
0720   }
0721   /// \copydoc debug_operands()
0722   iterator_range<const_mop_iterator> debug_operands() const {
0723     assert((isDebugValueLike()) && "Must be a debug value instruction.");
0724     return isNonListDebugValue()
0725                ? make_range(operands_begin(), operands_begin() + 1)
0726                : make_range(operands_begin() + 2, operands_end());
0727   }
0728   /// Returns a range over all explicit operands that are register definitions.
0729   /// Implicit definition are not included!
0730   iterator_range<mop_iterator> defs() {
0731     return make_range(operands_begin(),
0732                       operands_begin() + getNumExplicitDefs());
0733   }
0734   /// \copydoc defs()
0735   iterator_range<const_mop_iterator> defs() const {
0736     return make_range(operands_begin(),
0737                       operands_begin() + getNumExplicitDefs());
0738   }
0739   /// Returns a range that includes all operands which may be register uses.
0740   /// This may include unrelated operands which are not register uses.
0741   iterator_range<mop_iterator> uses() {
0742     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
0743   }
0744   /// \copydoc uses()
0745   iterator_range<const_mop_iterator> uses() const {
0746     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
0747   }
0748   iterator_range<mop_iterator> explicit_uses() {
0749     return make_range(operands_begin() + getNumExplicitDefs(),
0750                       operands_begin() + getNumExplicitOperands());
0751   }
0752   iterator_range<const_mop_iterator> explicit_uses() const {
0753     return make_range(operands_begin() + getNumExplicitDefs(),
0754                       operands_begin() + getNumExplicitOperands());
0755   }
0756 
0757   using filtered_mop_iterator =
0758       filter_iterator<mop_iterator, bool (*)(const MachineOperand &)>;
0759   using filtered_const_mop_iterator =
0760       filter_iterator<const_mop_iterator, bool (*)(const MachineOperand &)>;
0761 
0762   /// Returns an iterator range over all operands that are (explicit or
0763   /// implicit) register defs.
0764   iterator_range<filtered_mop_iterator> all_defs() {
0765     return make_filter_range(operands(), opIsRegDef);
0766   }
0767   /// \copydoc all_defs()
0768   iterator_range<filtered_const_mop_iterator> all_defs() const {
0769     return make_filter_range(operands(), opIsRegDef);
0770   }
0771 
0772   /// Returns an iterator range over all operands that are (explicit or
0773   /// implicit) register uses.
0774   iterator_range<filtered_mop_iterator> all_uses() {
0775     return make_filter_range(uses(), opIsRegUse);
0776   }
0777   /// \copydoc all_uses()
0778   iterator_range<filtered_const_mop_iterator> all_uses() const {
0779     return make_filter_range(uses(), opIsRegUse);
0780   }
0781 
0782   /// Returns the number of the operand iterator \p I points to.
0783   unsigned getOperandNo(const_mop_iterator I) const {
0784     return I - operands_begin();
0785   }
0786 
0787   /// Access to memory operands of the instruction. If there are none, that does
0788   /// not imply anything about whether the function accesses memory. Instead,
0789   /// the caller must behave conservatively.
0790   ArrayRef<MachineMemOperand *> memoperands() const {
0791     if (!Info)
0792       return {};
0793 
0794     if (Info.is<EIIK_MMO>())
0795       return ArrayRef(Info.getAddrOfZeroTagPointer(), 1);
0796 
0797     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0798       return EI->getMMOs();
0799 
0800     return {};
0801   }
0802 
0803   /// Access to memory operands of the instruction.
0804   ///
0805   /// If `memoperands_begin() == memoperands_end()`, that does not imply
0806   /// anything about whether the function accesses memory. Instead, the caller
0807   /// must behave conservatively.
0808   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
0809 
0810   /// Access to memory operands of the instruction.
0811   ///
0812   /// If `memoperands_begin() == memoperands_end()`, that does not imply
0813   /// anything about whether the function accesses memory. Instead, the caller
0814   /// must behave conservatively.
0815   mmo_iterator memoperands_end() const { return memoperands().end(); }
0816 
0817   /// Return true if we don't have any memory operands which described the
0818   /// memory access done by this instruction.  If this is true, calling code
0819   /// must be conservative.
0820   bool memoperands_empty() const { return memoperands().empty(); }
0821 
0822   /// Return true if this instruction has exactly one MachineMemOperand.
0823   bool hasOneMemOperand() const { return memoperands().size() == 1; }
0824 
0825   /// Return the number of memory operands.
0826   unsigned getNumMemOperands() const { return memoperands().size(); }
0827 
0828   /// Helper to extract a pre-instruction symbol if one has been added.
0829   MCSymbol *getPreInstrSymbol() const {
0830     if (!Info)
0831       return nullptr;
0832     if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
0833       return S;
0834     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0835       return EI->getPreInstrSymbol();
0836 
0837     return nullptr;
0838   }
0839 
0840   /// Helper to extract a post-instruction symbol if one has been added.
0841   MCSymbol *getPostInstrSymbol() const {
0842     if (!Info)
0843       return nullptr;
0844     if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
0845       return S;
0846     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0847       return EI->getPostInstrSymbol();
0848 
0849     return nullptr;
0850   }
0851 
0852   /// Helper to extract a heap alloc marker if one has been added.
0853   MDNode *getHeapAllocMarker() const {
0854     if (!Info)
0855       return nullptr;
0856     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0857       return EI->getHeapAllocMarker();
0858 
0859     return nullptr;
0860   }
0861 
0862   /// Helper to extract PCSections metadata target sections.
0863   MDNode *getPCSections() const {
0864     if (!Info)
0865       return nullptr;
0866     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0867       return EI->getPCSections();
0868 
0869     return nullptr;
0870   }
0871 
0872   /// Helper to extract mmra.op metadata.
0873   MDNode *getMMRAMetadata() const {
0874     if (!Info)
0875       return nullptr;
0876     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0877       return EI->getMMRAMetadata();
0878     return nullptr;
0879   }
0880 
0881   /// Helper to extract a CFI type hash if one has been added.
0882   uint32_t getCFIType() const {
0883     if (!Info)
0884       return 0;
0885     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
0886       return EI->getCFIType();
0887 
0888     return 0;
0889   }
0890 
0891   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
0892   /// queries but they are bundle aware.
0893 
0894   enum QueryType {
0895     IgnoreBundle,    // Ignore bundles
0896     AnyInBundle,     // Return true if any instruction in bundle has property
0897     AllInBundle      // Return true if all instructions in bundle have property
0898   };
0899 
0900   /// Return true if the instruction (or in the case of a bundle,
0901   /// the instructions inside the bundle) has the specified property.
0902   /// The first argument is the property being queried.
0903   /// The second argument indicates whether the query should look inside
0904   /// instruction bundles.
0905   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
0906     assert(MCFlag < 64 &&
0907            "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
0908     // Inline the fast path for unbundled or bundle-internal instructions.
0909     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
0910       return getDesc().getFlags() & (1ULL << MCFlag);
0911 
0912     // If this is the first instruction in a bundle, take the slow path.
0913     return hasPropertyInBundle(1ULL << MCFlag, Type);
0914   }
0915 
0916   /// Return true if this is an instruction that should go through the usual
0917   /// legalization steps.
0918   bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
0919     return hasProperty(MCID::PreISelOpcode, Type);
0920   }
0921 
0922   /// Return true if this instruction can have a variable number of operands.
0923   /// In this case, the variable operands will be after the normal
0924   /// operands but before the implicit definitions and uses (if any are
0925   /// present).
0926   bool isVariadic(QueryType Type = IgnoreBundle) const {
0927     return hasProperty(MCID::Variadic, Type);
0928   }
0929 
0930   /// Set if this instruction has an optional definition, e.g.
0931   /// ARM instructions which can set condition code if 's' bit is set.
0932   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
0933     return hasProperty(MCID::HasOptionalDef, Type);
0934   }
0935 
0936   /// Return true if this is a pseudo instruction that doesn't
0937   /// correspond to a real machine instruction.
0938   bool isPseudo(QueryType Type = IgnoreBundle) const {
0939     return hasProperty(MCID::Pseudo, Type);
0940   }
0941 
0942   /// Return true if this instruction doesn't produce any output in the form of
0943   /// executable instructions.
0944   bool isMetaInstruction(QueryType Type = IgnoreBundle) const {
0945     return hasProperty(MCID::Meta, Type);
0946   }
0947 
0948   bool isReturn(QueryType Type = AnyInBundle) const {
0949     return hasProperty(MCID::Return, Type);
0950   }
0951 
0952   /// Return true if this is an instruction that marks the end of an EH scope,
0953   /// i.e., a catchpad or a cleanuppad instruction.
0954   bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
0955     return hasProperty(MCID::EHScopeReturn, Type);
0956   }
0957 
0958   bool isCall(QueryType Type = AnyInBundle) const {
0959     return hasProperty(MCID::Call, Type);
0960   }
0961 
0962   /// Return true if this is a call instruction that may have an additional
0963   /// information associated with it.
0964   bool isCandidateForAdditionalCallInfo(QueryType Type = IgnoreBundle) const;
0965 
0966   /// Return true if copying, moving, or erasing this instruction requires
0967   /// updating additional call info (see \ref copyCallInfo, \ref moveCallInfo,
0968   /// \ref eraseCallInfo).
0969   bool shouldUpdateAdditionalCallInfo() const;
0970 
0971   /// Returns true if the specified instruction stops control flow
0972   /// from executing the instruction immediately following it.  Examples include
0973   /// unconditional branches and return instructions.
0974   bool isBarrier(QueryType Type = AnyInBundle) const {
0975     return hasProperty(MCID::Barrier, Type);
0976   }
0977 
0978   /// Returns true if this instruction part of the terminator for a basic block.
0979   /// Typically this is things like return and branch instructions.
0980   ///
0981   /// Various passes use this to insert code into the bottom of a basic block,
0982   /// but before control flow occurs.
0983   bool isTerminator(QueryType Type = AnyInBundle) const {
0984     return hasProperty(MCID::Terminator, Type);
0985   }
0986 
0987   /// Returns true if this is a conditional, unconditional, or indirect branch.
0988   /// Predicates below can be used to discriminate between
0989   /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
0990   /// get more information.
0991   bool isBranch(QueryType Type = AnyInBundle) const {
0992     return hasProperty(MCID::Branch, Type);
0993   }
0994 
0995   /// Return true if this is an indirect branch, such as a
0996   /// branch through a register.
0997   bool isIndirectBranch(QueryType Type = AnyInBundle,
0998                         bool IncludeJumpTable = true) const {
0999     return hasProperty(MCID::IndirectBranch, Type) &&
1000            (IncludeJumpTable || !llvm::any_of(operands(), [](const auto &Op) {
1001               return Op.isJTI();
1002             }));
1003   }
1004 
1005   bool isComputedGoto(QueryType Type = AnyInBundle) const {
1006     // Jump tables are not considered computed gotos.
1007     return isIndirectBranch(Type, /*IncludeJumpTable=*/false);
1008   }
1009 
1010   /// Return true if this is a branch which may fall
1011   /// through to the next instruction or may transfer control flow to some other
1012   /// block.  The TargetInstrInfo::analyzeBranch method can be used to get more
1013   /// information about this branch.
1014   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
1015     return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
1016   }
1017 
1018   /// Return true if this is a branch which always
1019   /// transfers control flow to some other block.  The
1020   /// TargetInstrInfo::analyzeBranch method can be used to get more information
1021   /// about this branch.
1022   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
1023     return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
1024   }
1025 
1026   /// Return true if this instruction has a predicate operand that
1027   /// controls execution.  It may be set to 'always', or may be set to other
1028   /// values.   There are various methods in TargetInstrInfo that can be used to
1029   /// control and modify the predicate in this instruction.
1030   bool isPredicable(QueryType Type = AllInBundle) const {
1031     // If it's a bundle than all bundled instructions must be predicable for this
1032     // to return true.
1033     return hasProperty(MCID::Predicable, Type);
1034   }
1035 
1036   /// Return true if this instruction is a comparison.
1037   bool isCompare(QueryType Type = IgnoreBundle) const {
1038     return hasProperty(MCID::Compare, Type);
1039   }
1040 
1041   /// Return true if this instruction is a move immediate
1042   /// (including conditional moves) instruction.
1043   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
1044     return hasProperty(MCID::MoveImm, Type);
1045   }
1046 
1047   /// Return true if this instruction is a register move.
1048   /// (including moving values from subreg to reg)
1049   bool isMoveReg(QueryType Type = IgnoreBundle) const {
1050     return hasProperty(MCID::MoveReg, Type);
1051   }
1052 
1053   /// Return true if this instruction is a bitcast instruction.
1054   bool isBitcast(QueryType Type = IgnoreBundle) const {
1055     return hasProperty(MCID::Bitcast, Type);
1056   }
1057 
1058   /// Return true if this instruction is a select instruction.
1059   bool isSelect(QueryType Type = IgnoreBundle) const {
1060     return hasProperty(MCID::Select, Type);
1061   }
1062 
1063   /// Return true if this instruction cannot be safely duplicated.
1064   /// For example, if the instruction has a unique labels attached
1065   /// to it, duplicating it would cause multiple definition errors.
1066   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
1067     if (getPreInstrSymbol() || getPostInstrSymbol())
1068       return true;
1069     return hasProperty(MCID::NotDuplicable, Type);
1070   }
1071 
1072   /// Return true if this instruction is convergent.
1073   /// Convergent instructions can not be made control-dependent on any
1074   /// additional values.
1075   bool isConvergent(QueryType Type = AnyInBundle) const {
1076     if (isInlineAsm()) {
1077       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1078       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1079         return true;
1080     }
1081     if (getFlag(NoConvergent))
1082       return false;
1083     return hasProperty(MCID::Convergent, Type);
1084   }
1085 
1086   /// Returns true if the specified instruction has a delay slot
1087   /// which must be filled by the code generator.
1088   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
1089     return hasProperty(MCID::DelaySlot, Type);
1090   }
1091 
1092   /// Return true for instructions that can be folded as
1093   /// memory operands in other instructions. The most common use for this
1094   /// is instructions that are simple loads from memory that don't modify
1095   /// the loaded value in any way, but it can also be used for instructions
1096   /// that can be expressed as constant-pool loads, such as V_SETALLONES
1097   /// on x86, to allow them to be folded when it is beneficial.
1098   /// This should only be set on instructions that return a value in their
1099   /// only virtual register definition.
1100   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
1101     return hasProperty(MCID::FoldableAsLoad, Type);
1102   }
1103 
1104   /// Return true if this instruction behaves
1105   /// the same way as the generic REG_SEQUENCE instructions.
1106   /// E.g., on ARM,
1107   /// dX VMOVDRR rY, rZ
1108   /// is equivalent to
1109   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
1110   ///
1111   /// Note that for the optimizers to be able to take advantage of
1112   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
1113   /// override accordingly.
1114   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
1115     return hasProperty(MCID::RegSequence, Type);
1116   }
1117 
1118   /// Return true if this instruction behaves
1119   /// the same way as the generic EXTRACT_SUBREG instructions.
1120   /// E.g., on ARM,
1121   /// rX, rY VMOVRRD dZ
1122   /// is equivalent to two EXTRACT_SUBREG:
1123   /// rX = EXTRACT_SUBREG dZ, ssub_0
1124   /// rY = EXTRACT_SUBREG dZ, ssub_1
1125   ///
1126   /// Note that for the optimizers to be able to take advantage of
1127   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
1128   /// override accordingly.
1129   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
1130     return hasProperty(MCID::ExtractSubreg, Type);
1131   }
1132 
1133   /// Return true if this instruction behaves
1134   /// the same way as the generic INSERT_SUBREG instructions.
1135   /// E.g., on ARM,
1136   /// dX = VSETLNi32 dY, rZ, Imm
1137   /// is equivalent to a INSERT_SUBREG:
1138   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
1139   ///
1140   /// Note that for the optimizers to be able to take advantage of
1141   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
1142   /// override accordingly.
1143   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
1144     return hasProperty(MCID::InsertSubreg, Type);
1145   }
1146 
1147   //===--------------------------------------------------------------------===//
1148   // Side Effect Analysis
1149   //===--------------------------------------------------------------------===//
1150 
1151   /// Return true if this instruction could possibly read memory.
1152   /// Instructions with this flag set are not necessarily simple load
1153   /// instructions, they may load a value and modify it, for example.
1154   bool mayLoad(QueryType Type = AnyInBundle) const {
1155     if (isInlineAsm()) {
1156       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1157       if (ExtraInfo & InlineAsm::Extra_MayLoad)
1158         return true;
1159     }
1160     return hasProperty(MCID::MayLoad, Type);
1161   }
1162 
1163   /// Return true if this instruction could possibly modify memory.
1164   /// Instructions with this flag set are not necessarily simple store
1165   /// instructions, they may store a modified value based on their operands, or
1166   /// may not actually modify anything, for example.
1167   bool mayStore(QueryType Type = AnyInBundle) const {
1168     if (isInlineAsm()) {
1169       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1170       if (ExtraInfo & InlineAsm::Extra_MayStore)
1171         return true;
1172     }
1173     return hasProperty(MCID::MayStore, Type);
1174   }
1175 
1176   /// Return true if this instruction could possibly read or modify memory.
1177   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
1178     return mayLoad(Type) || mayStore(Type);
1179   }
1180 
1181   /// Return true if this instruction could possibly raise a floating-point
1182   /// exception.  This is the case if the instruction is a floating-point
1183   /// instruction that can in principle raise an exception, as indicated
1184   /// by the MCID::MayRaiseFPException property, *and* at the same time,
1185   /// the instruction is used in a context where we expect floating-point
1186   /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
1187   bool mayRaiseFPException() const {
1188     return hasProperty(MCID::MayRaiseFPException) &&
1189            !getFlag(MachineInstr::MIFlag::NoFPExcept);
1190   }
1191 
1192   //===--------------------------------------------------------------------===//
1193   // Flags that indicate whether an instruction can be modified by a method.
1194   //===--------------------------------------------------------------------===//
1195 
1196   /// Return true if this may be a 2- or 3-address
1197   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
1198   /// result if Y and Z are exchanged.  If this flag is set, then the
1199   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
1200   /// instruction.
1201   ///
1202   /// Note that this flag may be set on instructions that are only commutable
1203   /// sometimes.  In these cases, the call to commuteInstruction will fail.
1204   /// Also note that some instructions require non-trivial modification to
1205   /// commute them.
1206   bool isCommutable(QueryType Type = IgnoreBundle) const {
1207     return hasProperty(MCID::Commutable, Type);
1208   }
1209 
1210   /// Return true if this is a 2-address instruction
1211   /// which can be changed into a 3-address instruction if needed.  Doing this
1212   /// transformation can be profitable in the register allocator, because it
1213   /// means that the instruction can use a 2-address form if possible, but
1214   /// degrade into a less efficient form if the source and dest register cannot
1215   /// be assigned to the same register.  For example, this allows the x86
1216   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
1217   /// is the same speed as the shift but has bigger code size.
1218   ///
1219   /// If this returns true, then the target must implement the
1220   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
1221   /// is allowed to fail if the transformation isn't valid for this specific
1222   /// instruction (e.g. shl reg, 4 on x86).
1223   ///
1224   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
1225     return hasProperty(MCID::ConvertibleTo3Addr, Type);
1226   }
1227 
1228   /// Return true if this instruction requires
1229   /// custom insertion support when the DAG scheduler is inserting it into a
1230   /// machine basic block.  If this is true for the instruction, it basically
1231   /// means that it is a pseudo instruction used at SelectionDAG time that is
1232   /// expanded out into magic code by the target when MachineInstrs are formed.
1233   ///
1234   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
1235   /// is used to insert this into the MachineBasicBlock.
1236   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
1237     return hasProperty(MCID::UsesCustomInserter, Type);
1238   }
1239 
1240   /// Return true if this instruction requires *adjustment*
1241   /// after instruction selection by calling a target hook. For example, this
1242   /// can be used to fill in ARM 's' optional operand depending on whether
1243   /// the conditional flag register is used.
1244   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
1245     return hasProperty(MCID::HasPostISelHook, Type);
1246   }
1247 
1248   /// Returns true if this instruction is a candidate for remat.
1249   /// This flag is deprecated, please don't use it anymore.  If this
1250   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
1251   /// verify the instruction is really rematerializable.
1252   bool isRematerializable(QueryType Type = AllInBundle) const {
1253     // It's only possible to re-mat a bundle if all bundled instructions are
1254     // re-materializable.
1255     return hasProperty(MCID::Rematerializable, Type);
1256   }
1257 
1258   /// Returns true if this instruction has the same cost (or less) than a move
1259   /// instruction. This is useful during certain types of optimizations
1260   /// (e.g., remat during two-address conversion or machine licm)
1261   /// where we would like to remat or hoist the instruction, but not if it costs
1262   /// more than moving the instruction into the appropriate register. Note, we
1263   /// are not marking copies from and to the same register class with this flag.
1264   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
1265     // Only returns true for a bundle if all bundled instructions are cheap.
1266     return hasProperty(MCID::CheapAsAMove, Type);
1267   }
1268 
1269   /// Returns true if this instruction source operands
1270   /// have special register allocation requirements that are not captured by the
1271   /// operand register classes. e.g. ARM::STRD's two source registers must be an
1272   /// even / odd pair, ARM::STM registers have to be in ascending order.
1273   /// Post-register allocation passes should not attempt to change allocations
1274   /// for sources of instructions with this flag.
1275   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
1276     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
1277   }
1278 
1279   /// Returns true if this instruction def operands
1280   /// have special register allocation requirements that are not captured by the
1281   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
1282   /// even / odd pair, ARM::LDM registers have to be in ascending order.
1283   /// Post-register allocation passes should not attempt to change allocations
1284   /// for definitions of instructions with this flag.
1285   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1286     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1287   }
1288 
1289   enum MICheckType {
1290     CheckDefs,      // Check all operands for equality
1291     CheckKillDead,  // Check all operands including kill / dead markers
1292     IgnoreDefs,     // Ignore all definitions
1293     IgnoreVRegDefs  // Ignore virtual register definitions
1294   };
1295 
1296   /// Return true if this instruction is identical to \p Other.
1297   /// Two instructions are identical if they have the same opcode and all their
1298   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1299   /// Note that this means liveness related flags (dead, undef, kill) do not
1300   /// affect the notion of identical.
1301   bool isIdenticalTo(const MachineInstr &Other,
1302                      MICheckType Check = CheckDefs) const;
1303 
1304   /// Returns true if this instruction is a debug instruction that represents an
1305   /// identical debug value to \p Other.
1306   /// This function considers these debug instructions equivalent if they have
1307   /// identical variables, debug locations, and debug operands, and if the
1308   /// DIExpressions combined with the directness flags are equivalent.
1309   bool isEquivalentDbgInstr(const MachineInstr &Other) const;
1310 
1311   /// Unlink 'this' from the containing basic block, and return it without
1312   /// deleting it.
1313   ///
1314   /// This function can not be used on bundled instructions, use
1315   /// removeFromBundle() to remove individual instructions from a bundle.
1316   MachineInstr *removeFromParent();
1317 
1318   /// Unlink this instruction from its basic block and return it without
1319   /// deleting it.
1320   ///
1321   /// If the instruction is part of a bundle, the other instructions in the
1322   /// bundle remain bundled.
1323   MachineInstr *removeFromBundle();
1324 
1325   /// Unlink 'this' from the containing basic block and delete it.
1326   ///
1327   /// If this instruction is the header of a bundle, the whole bundle is erased.
1328   /// This function can not be used for instructions inside a bundle, use
1329   /// eraseFromBundle() to erase individual bundled instructions.
1330   void eraseFromParent();
1331 
1332   /// Unlink 'this' from its basic block and delete it.
1333   ///
1334   /// If the instruction is part of a bundle, the other instructions in the
1335   /// bundle remain bundled.
1336   void eraseFromBundle();
1337 
1338   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1339   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1340   bool isAnnotationLabel() const {
1341     return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1342   }
1343 
1344   bool isLifetimeMarker() const {
1345     return getOpcode() == TargetOpcode::LIFETIME_START ||
1346            getOpcode() == TargetOpcode::LIFETIME_END;
1347   }
1348 
1349   /// Returns true if the MachineInstr represents a label.
1350   bool isLabel() const {
1351     return isEHLabel() || isGCLabel() || isAnnotationLabel();
1352   }
1353 
1354   bool isCFIInstruction() const {
1355     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1356   }
1357 
1358   bool isPseudoProbe() const {
1359     return getOpcode() == TargetOpcode::PSEUDO_PROBE;
1360   }
1361 
1362   // True if the instruction represents a position in the function.
1363   bool isPosition() const { return isLabel() || isCFIInstruction(); }
1364 
1365   bool isNonListDebugValue() const {
1366     return getOpcode() == TargetOpcode::DBG_VALUE;
1367   }
1368   bool isDebugValueList() const {
1369     return getOpcode() == TargetOpcode::DBG_VALUE_LIST;
1370   }
1371   bool isDebugValue() const {
1372     return isNonListDebugValue() || isDebugValueList();
1373   }
1374   bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1375   bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; }
1376   bool isDebugValueLike() const { return isDebugValue() || isDebugRef(); }
1377   bool isDebugPHI() const { return getOpcode() == TargetOpcode::DBG_PHI; }
1378   bool isDebugInstr() const {
1379     return isDebugValue() || isDebugLabel() || isDebugRef() || isDebugPHI();
1380   }
1381   bool isDebugOrPseudoInstr() const {
1382     return isDebugInstr() || isPseudoProbe();
1383   }
1384 
1385   bool isDebugOffsetImm() const {
1386     return isNonListDebugValue() && getDebugOffset().isImm();
1387   }
1388 
1389   /// A DBG_VALUE is indirect iff the location operand is a register and
1390   /// the offset operand is an immediate.
1391   bool isIndirectDebugValue() const {
1392     return isDebugOffsetImm() && getDebugOperand(0).isReg();
1393   }
1394 
1395   /// A DBG_VALUE is an entry value iff its debug expression contains the
1396   /// DW_OP_LLVM_entry_value operation.
1397   bool isDebugEntryValue() const;
1398 
1399   /// Return true if the instruction is a debug value which describes a part of
1400   /// a variable as unavailable.
1401   bool isUndefDebugValue() const {
1402     if (!isDebugValue())
1403       return false;
1404     // If any $noreg locations are given, this DV is undef.
1405     for (const MachineOperand &Op : debug_operands())
1406       if (Op.isReg() && !Op.getReg().isValid())
1407         return true;
1408     return false;
1409   }
1410 
1411   bool isJumpTableDebugInfo() const {
1412     return getOpcode() == TargetOpcode::JUMP_TABLE_DEBUG_INFO;
1413   }
1414 
1415   bool isPHI() const {
1416     return getOpcode() == TargetOpcode::PHI ||
1417            getOpcode() == TargetOpcode::G_PHI;
1418   }
1419   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1420   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1421   bool isInlineAsm() const {
1422     return getOpcode() == TargetOpcode::INLINEASM ||
1423            getOpcode() == TargetOpcode::INLINEASM_BR;
1424   }
1425   /// Returns true if the register operand can be folded with a load or store
1426   /// into a frame index. Does so by checking the InlineAsm::Flag immediate
1427   /// operand at OpId - 1.
1428   bool mayFoldInlineAsmRegOp(unsigned OpId) const;
1429 
1430   bool isStackAligningInlineAsm() const;
1431   InlineAsm::AsmDialect getInlineAsmDialect() const;
1432 
1433   bool isInsertSubreg() const {
1434     return getOpcode() == TargetOpcode::INSERT_SUBREG;
1435   }
1436 
1437   bool isSubregToReg() const {
1438     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1439   }
1440 
1441   bool isRegSequence() const {
1442     return getOpcode() == TargetOpcode::REG_SEQUENCE;
1443   }
1444 
1445   bool isBundle() const {
1446     return getOpcode() == TargetOpcode::BUNDLE;
1447   }
1448 
1449   bool isCopy() const {
1450     return getOpcode() == TargetOpcode::COPY;
1451   }
1452 
1453   bool isFullCopy() const {
1454     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1455   }
1456 
1457   bool isExtractSubreg() const {
1458     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1459   }
1460 
1461   bool isFakeUse() const { return getOpcode() == TargetOpcode::FAKE_USE; }
1462 
1463   /// Return true if the instruction behaves like a copy.
1464   /// This does not include native copy instructions.
1465   bool isCopyLike() const {
1466     return isCopy() || isSubregToReg();
1467   }
1468 
1469   /// Return true is the instruction is an identity copy.
1470   bool isIdentityCopy() const {
1471     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1472       getOperand(0).getSubReg() == getOperand(1).getSubReg();
1473   }
1474 
1475   /// Return true if this is a transient instruction that is either very likely
1476   /// to be eliminated during register allocation (such as copy-like
1477   /// instructions), or if this instruction doesn't have an execution-time cost.
1478   bool isTransient() const {
1479     switch (getOpcode()) {
1480     default:
1481       return isMetaInstruction();
1482     // Copy-like instructions are usually eliminated during register allocation.
1483     case TargetOpcode::PHI:
1484     case TargetOpcode::G_PHI:
1485     case TargetOpcode::COPY:
1486     case TargetOpcode::INSERT_SUBREG:
1487     case TargetOpcode::SUBREG_TO_REG:
1488     case TargetOpcode::REG_SEQUENCE:
1489       return true;
1490     }
1491   }
1492 
1493   /// Return the number of instructions inside the MI bundle, excluding the
1494   /// bundle header.
1495   ///
1496   /// This is the number of instructions that MachineBasicBlock::iterator
1497   /// skips, 0 for unbundled instructions.
1498   unsigned getBundleSize() const;
1499 
1500   /// Return true if the MachineInstr reads the specified register.
1501   /// If TargetRegisterInfo is non-null, then it also checks if there
1502   /// is a read of a super-register.
1503   /// This does not count partial redefines of virtual registers as reads:
1504   ///   %reg1024:6 = OP.
1505   bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1506     return findRegisterUseOperandIdx(Reg, TRI, false) != -1;
1507   }
1508 
1509   /// Return true if the MachineInstr reads the specified virtual register.
1510   /// Take into account that a partial define is a
1511   /// read-modify-write operation.
1512   bool readsVirtualRegister(Register Reg) const {
1513     return readsWritesVirtualRegister(Reg).first;
1514   }
1515 
1516   /// Return a pair of bools (reads, writes) indicating if this instruction
1517   /// reads or writes Reg. This also considers partial defines.
1518   /// If Ops is not null, all operand indices for Reg are added.
1519   std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1520                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1521 
1522   /// Return true if the MachineInstr kills the specified register.
1523   /// If TargetRegisterInfo is non-null, then it also checks if there is
1524   /// a kill of a super-register.
1525   bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1526     return findRegisterUseOperandIdx(Reg, TRI, true) != -1;
1527   }
1528 
1529   /// Return true if the MachineInstr fully defines the specified register.
1530   /// If TargetRegisterInfo is non-null, then it also checks
1531   /// if there is a def of a super-register.
1532   /// NOTE: It's ignoring subreg indices on virtual registers.
1533   bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1534     return findRegisterDefOperandIdx(Reg, TRI, false, false) != -1;
1535   }
1536 
1537   /// Return true if the MachineInstr modifies (fully define or partially
1538   /// define) the specified register.
1539   /// NOTE: It's ignoring subreg indices on virtual registers.
1540   bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1541     return findRegisterDefOperandIdx(Reg, TRI, false, true) != -1;
1542   }
1543 
1544   /// Returns true if the register is dead in this machine instruction.
1545   /// If TargetRegisterInfo is non-null, then it also checks
1546   /// if there is a dead def of a super-register.
1547   bool registerDefIsDead(Register Reg, const TargetRegisterInfo *TRI) const {
1548     return findRegisterDefOperandIdx(Reg, TRI, true, false) != -1;
1549   }
1550 
1551   /// Returns true if the MachineInstr has an implicit-use operand of exactly
1552   /// the given register (not considering sub/super-registers).
1553   bool hasRegisterImplicitUseOperand(Register Reg) const;
1554 
1555   /// Returns the operand index that is a use of the specific register or -1
1556   /// if it is not found. It further tightens the search criteria to a use
1557   /// that kills the register if isKill is true.
1558   int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI,
1559                                 bool isKill = false) const;
1560 
1561   /// Wrapper for findRegisterUseOperandIdx, it returns
1562   /// a pointer to the MachineOperand rather than an index.
1563   MachineOperand *findRegisterUseOperand(Register Reg,
1564                                          const TargetRegisterInfo *TRI,
1565                                          bool isKill = false) {
1566     int Idx = findRegisterUseOperandIdx(Reg, TRI, isKill);
1567     return (Idx == -1) ? nullptr : &getOperand(Idx);
1568   }
1569 
1570   const MachineOperand *findRegisterUseOperand(Register Reg,
1571                                                const TargetRegisterInfo *TRI,
1572                                                bool isKill = false) const {
1573     return const_cast<MachineInstr *>(this)->findRegisterUseOperand(Reg, TRI,
1574                                                                     isKill);
1575   }
1576 
1577   /// Returns the operand index that is a def of the specified register or
1578   /// -1 if it is not found. If isDead is true, defs that are not dead are
1579   /// skipped. If Overlap is true, then it also looks for defs that merely
1580   /// overlap the specified register. If TargetRegisterInfo is non-null,
1581   /// then it also checks if there is a def of a super-register.
1582   /// This may also return a register mask operand when Overlap is true.
1583   int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI,
1584                                 bool isDead = false,
1585                                 bool Overlap = false) const;
1586 
1587   /// Wrapper for findRegisterDefOperandIdx, it returns
1588   /// a pointer to the MachineOperand rather than an index.
1589   MachineOperand *findRegisterDefOperand(Register Reg,
1590                                          const TargetRegisterInfo *TRI,
1591                                          bool isDead = false,
1592                                          bool Overlap = false) {
1593     int Idx = findRegisterDefOperandIdx(Reg, TRI, isDead, Overlap);
1594     return (Idx == -1) ? nullptr : &getOperand(Idx);
1595   }
1596 
1597   const MachineOperand *findRegisterDefOperand(Register Reg,
1598                                                const TargetRegisterInfo *TRI,
1599                                                bool isDead = false,
1600                                                bool Overlap = false) const {
1601     return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1602         Reg, TRI, isDead, Overlap);
1603   }
1604 
1605   /// Find the index of the first operand in the
1606   /// operand list that is used to represent the predicate. It returns -1 if
1607   /// none is found.
1608   int findFirstPredOperandIdx() const;
1609 
1610   /// Find the index of the flag word operand that
1611   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
1612   /// getOperand(OpIdx) does not belong to an inline asm operand group.
1613   ///
1614   /// If GroupNo is not NULL, it will receive the number of the operand group
1615   /// containing OpIdx.
1616   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1617 
1618   /// Compute the static register class constraint for operand OpIdx.
1619   /// For normal instructions, this is derived from the MCInstrDesc.
1620   /// For inline assembly it is derived from the flag words.
1621   ///
1622   /// Returns NULL if the static register class constraint cannot be
1623   /// determined.
1624   const TargetRegisterClass*
1625   getRegClassConstraint(unsigned OpIdx,
1626                         const TargetInstrInfo *TII,
1627                         const TargetRegisterInfo *TRI) const;
1628 
1629   /// Applies the constraints (def/use) implied by this MI on \p Reg to
1630   /// the given \p CurRC.
1631   /// If \p ExploreBundle is set and MI is part of a bundle, all the
1632   /// instructions inside the bundle will be taken into account. In other words,
1633   /// this method accumulates all the constraints of the operand of this MI and
1634   /// the related bundle if MI is a bundle or inside a bundle.
1635   ///
1636   /// Returns the register class that satisfies both \p CurRC and the
1637   /// constraints set by MI. Returns NULL if such a register class does not
1638   /// exist.
1639   ///
1640   /// \pre CurRC must not be NULL.
1641   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1642       Register Reg, const TargetRegisterClass *CurRC,
1643       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1644       bool ExploreBundle = false) const;
1645 
1646   /// Applies the constraints (def/use) implied by the \p OpIdx operand
1647   /// to the given \p CurRC.
1648   ///
1649   /// Returns the register class that satisfies both \p CurRC and the
1650   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1651   /// does not exist.
1652   ///
1653   /// \pre CurRC must not be NULL.
1654   /// \pre The operand at \p OpIdx must be a register.
1655   const TargetRegisterClass *
1656   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1657                               const TargetInstrInfo *TII,
1658                               const TargetRegisterInfo *TRI) const;
1659 
1660   /// Add a tie between the register operands at DefIdx and UseIdx.
1661   /// The tie will cause the register allocator to ensure that the two
1662   /// operands are assigned the same physical register.
1663   ///
1664   /// Tied operands are managed automatically for explicit operands in the
1665   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1666   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1667 
1668   /// Given the index of a tied register operand, find the
1669   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1670   /// index of the tied operand which must exist.
1671   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1672 
1673   /// Given the index of a register def operand,
1674   /// check if the register def is tied to a source operand, due to either
1675   /// two-address elimination or inline assembly constraints. Returns the
1676   /// first tied use operand index by reference if UseOpIdx is not null.
1677   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1678                              unsigned *UseOpIdx = nullptr) const {
1679     const MachineOperand &MO = getOperand(DefOpIdx);
1680     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1681       return false;
1682     if (UseOpIdx)
1683       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1684     return true;
1685   }
1686 
1687   /// Return true if the use operand of the specified index is tied to a def
1688   /// operand. It also returns the def operand index by reference if DefOpIdx
1689   /// is not null.
1690   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1691                              unsigned *DefOpIdx = nullptr) const {
1692     const MachineOperand &MO = getOperand(UseOpIdx);
1693     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1694       return false;
1695     if (DefOpIdx)
1696       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1697     return true;
1698   }
1699 
1700   /// Clears kill flags on all operands.
1701   void clearKillInfo();
1702 
1703   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1704   /// properly composing subreg indices where necessary.
1705   void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1706                           const TargetRegisterInfo &RegInfo);
1707 
1708   /// We have determined MI kills a register. Look for the
1709   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1710   /// add a implicit operand if it's not found. Returns true if the operand
1711   /// exists / is added.
1712   bool addRegisterKilled(Register IncomingReg,
1713                          const TargetRegisterInfo *RegInfo,
1714                          bool AddIfNotFound = false);
1715 
1716   /// Clear all kill flags affecting Reg.  If RegInfo is provided, this includes
1717   /// all aliasing registers.
1718   void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1719 
1720   /// We have determined MI defined a register without a use.
1721   /// Look for the operand that defines it and mark it as IsDead. If
1722   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1723   /// true if the operand exists / is added.
1724   bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1725                        bool AddIfNotFound = false);
1726 
1727   /// Clear all dead flags on operands defining register @p Reg.
1728   void clearRegisterDeads(Register Reg);
1729 
1730   /// Mark all subregister defs of register @p Reg with the undef flag.
1731   /// This function is used when we determined to have a subregister def in an
1732   /// otherwise undefined super register.
1733   void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1734 
1735   /// We have determined MI defines a register. Make sure there is an operand
1736   /// defining Reg.
1737   void addRegisterDefined(Register Reg,
1738                           const TargetRegisterInfo *RegInfo = nullptr);
1739 
1740   /// Mark every physreg used by this instruction as
1741   /// dead except those in the UsedRegs list.
1742   ///
1743   /// On instructions with register mask operands, also add implicit-def
1744   /// operands for all registers in UsedRegs.
1745   void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1746                              const TargetRegisterInfo &TRI);
1747 
1748   /// Return true if it is safe to move this instruction. If
1749   /// SawStore is set to true, it means that there is a store (or call) between
1750   /// the instruction's location and its intended destination.
1751   bool isSafeToMove(bool &SawStore) const;
1752 
1753   /// Return true if this instruction would be trivially dead if all of its
1754   /// defined registers were dead.
1755   bool wouldBeTriviallyDead() const;
1756 
1757   /// Check whether an MI is dead. If \p LivePhysRegs is provided, it is assumed
1758   /// to be at the position of MI and will be used to check the Liveness of
1759   /// physical register defs. If \p LivePhysRegs is not provided, this will
1760   /// pessimistically assume any PhysReg def is live.
1761   /// For trivially dead instructions (i.e. those without hard to model effects
1762   /// / wouldBeTriviallyDead), this checks deadness by analyzing defs of the
1763   /// MachineInstr. If the instruction wouldBeTriviallyDead, and  all the defs
1764   /// either have dead flags or have no uses, then the instruction is said to be
1765   /// dead.
1766   bool isDead(const MachineRegisterInfo &MRI,
1767               LiveRegUnits *LivePhysRegs = nullptr) const;
1768 
1769   /// Returns true if this instruction's memory access aliases the memory
1770   /// access of Other.
1771   //
1772   /// Assumes any physical registers used to compute addresses
1773   /// have the same value for both instructions.  Returns false if neither
1774   /// instruction writes to memory.
1775   ///
1776   /// @param AA Optional alias analysis, used to compare memory operands.
1777   /// @param Other MachineInstr to check aliasing against.
1778   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1779   bool mayAlias(BatchAAResults *AA, const MachineInstr &Other,
1780                 bool UseTBAA) const;
1781   bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1782 
1783   /// Return true if this instruction may have an ordered
1784   /// or volatile memory reference, or if the information describing the memory
1785   /// reference is not available. Return false if it is known to have no
1786   /// ordered or volatile memory references.
1787   bool hasOrderedMemoryRef() const;
1788 
1789   /// Return true if this load instruction never traps and points to a memory
1790   /// location whose value doesn't change during the execution of this function.
1791   ///
1792   /// Examples include loading a value from the constant pool or from the
1793   /// argument area of a function (if it does not change).  If the instruction
1794   /// does multiple loads, this returns true only if all of the loads are
1795   /// dereferenceable and invariant.
1796   bool isDereferenceableInvariantLoad() const;
1797 
1798   /// If the specified instruction is a PHI that always merges together the
1799   /// same virtual register, return the register, otherwise return Register().
1800   Register isConstantValuePHI() const;
1801 
1802   /// Return true if this instruction has side effects that are not modeled
1803   /// by mayLoad / mayStore, etc.
1804   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1805   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1806   /// INLINEASM instruction, in which case the side effect property is encoded
1807   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1808   ///
1809   bool hasUnmodeledSideEffects() const;
1810 
1811   /// Returns true if it is illegal to fold a load across this instruction.
1812   bool isLoadFoldBarrier() const;
1813 
1814   /// Return true if all the defs of this instruction are dead.
1815   bool allDefsAreDead() const;
1816 
1817   /// Return true if all the implicit defs of this instruction are dead.
1818   bool allImplicitDefsAreDead() const;
1819 
1820   /// Return a valid size if the instruction is a spill instruction.
1821   std::optional<LocationSize> getSpillSize(const TargetInstrInfo *TII) const;
1822 
1823   /// Return a valid size if the instruction is a folded spill instruction.
1824   std::optional<LocationSize>
1825   getFoldedSpillSize(const TargetInstrInfo *TII) const;
1826 
1827   /// Return a valid size if the instruction is a restore instruction.
1828   std::optional<LocationSize> getRestoreSize(const TargetInstrInfo *TII) const;
1829 
1830   /// Return a valid size if the instruction is a folded restore instruction.
1831   std::optional<LocationSize>
1832   getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1833 
1834   /// Copy implicit register operands from specified
1835   /// instruction to this instruction.
1836   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1837 
1838   /// Debugging support
1839   /// @{
1840   /// Determine the generic type to be printed (if needed) on uses and defs.
1841   LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1842                      const MachineRegisterInfo &MRI) const;
1843 
1844   /// Return true when an instruction has tied register that can't be determined
1845   /// by the instruction's descriptor. This is useful for MIR printing, to
1846   /// determine whether we need to print the ties or not.
1847   bool hasComplexRegisterTies() const;
1848 
1849   /// Print this MI to \p OS.
1850   /// Don't print information that can be inferred from other instructions if
1851   /// \p IsStandalone is false. It is usually true when only a fragment of the
1852   /// function is printed.
1853   /// Only print the defs and the opcode if \p SkipOpers is true.
1854   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1855   /// Otherwise, also print the debug loc, with a terminating newline.
1856   /// \p TII is used to print the opcode name.  If it's not present, but the
1857   /// MI is in a function, the opcode will be printed using the function's TII.
1858   void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1859              bool SkipDebugLoc = false, bool AddNewLine = true,
1860              const TargetInstrInfo *TII = nullptr) const;
1861   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1862              bool SkipOpers = false, bool SkipDebugLoc = false,
1863              bool AddNewLine = true,
1864              const TargetInstrInfo *TII = nullptr) const;
1865   void dump() const;
1866   /// Print on dbgs() the current instruction and the instructions defining its
1867   /// operands and so on until we reach \p MaxDepth.
1868   void dumpr(const MachineRegisterInfo &MRI,
1869              unsigned MaxDepth = UINT_MAX) const;
1870   /// @}
1871 
1872   //===--------------------------------------------------------------------===//
1873   // Accessors used to build up machine instructions.
1874 
1875   /// Add the specified operand to the instruction.  If it is an implicit
1876   /// operand, it is added to the end of the operand list.  If it is an
1877   /// explicit operand it is added at the end of the explicit operand list
1878   /// (before the first implicit operand).
1879   ///
1880   /// MF must be the machine function that was used to allocate this
1881   /// instruction.
1882   ///
1883   /// MachineInstrBuilder provides a more convenient interface for creating
1884   /// instructions and adding operands.
1885   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1886 
1887   /// Add an operand without providing an MF reference. This only works for
1888   /// instructions that are inserted in a basic block.
1889   ///
1890   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1891   /// preferred.
1892   void addOperand(const MachineOperand &Op);
1893 
1894   /// Inserts Ops BEFORE It. Can untie/retie tied operands.
1895   void insert(mop_iterator InsertBefore, ArrayRef<MachineOperand> Ops);
1896 
1897   /// Replace the instruction descriptor (thus opcode) of
1898   /// the current instruction with a new one.
1899   void setDesc(const MCInstrDesc &TID);
1900 
1901   /// Replace current source information with new such.
1902   /// Avoid using this, the constructor argument is preferable.
1903   void setDebugLoc(DebugLoc DL) {
1904     DbgLoc = std::move(DL);
1905     assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
1906   }
1907 
1908   /// Erase an operand from an instruction, leaving it with one
1909   /// fewer operand than it started with.
1910   void removeOperand(unsigned OpNo);
1911 
1912   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1913   /// the memrefs to their most conservative state.  This should be used only
1914   /// as a last resort since it greatly pessimizes our knowledge of the memory
1915   /// access performed by the instruction.
1916   void dropMemRefs(MachineFunction &MF);
1917 
1918   /// Assign this MachineInstr's memory reference descriptor list.
1919   ///
1920   /// Unlike other methods, this *will* allocate them into a new array
1921   /// associated with the provided `MachineFunction`.
1922   void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1923 
1924   /// Add a MachineMemOperand to the machine instruction.
1925   /// This function should be used only occasionally. The setMemRefs function
1926   /// is the primary method for setting up a MachineInstr's MemRefs list.
1927   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1928 
1929   /// Clone another MachineInstr's memory reference descriptor list and replace
1930   /// ours with it.
1931   ///
1932   /// Note that `*this` may be the incoming MI!
1933   ///
1934   /// Prefer this API whenever possible as it can avoid allocations in common
1935   /// cases.
1936   void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1937 
1938   /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1939   /// list and replace ours with it.
1940   ///
1941   /// Note that `*this` may be one of the incoming MIs!
1942   ///
1943   /// Prefer this API whenever possible as it can avoid allocations in common
1944   /// cases.
1945   void cloneMergedMemRefs(MachineFunction &MF,
1946                           ArrayRef<const MachineInstr *> MIs);
1947 
1948   /// Set a symbol that will be emitted just prior to the instruction itself.
1949   ///
1950   /// Setting this to a null pointer will remove any such symbol.
1951   ///
1952   /// FIXME: This is not fully implemented yet.
1953   void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1954 
1955   /// Set a symbol that will be emitted just after the instruction itself.
1956   ///
1957   /// Setting this to a null pointer will remove any such symbol.
1958   ///
1959   /// FIXME: This is not fully implemented yet.
1960   void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1961 
1962   /// Clone another MachineInstr's pre- and post- instruction symbols and
1963   /// replace ours with it.
1964   void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1965 
1966   /// Set a marker on instructions that denotes where we should create and emit
1967   /// heap alloc site labels. This waits until after instruction selection and
1968   /// optimizations to create the label, so it should still work if the
1969   /// instruction is removed or duplicated.
1970   void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1971 
1972   // Set metadata on instructions that say which sections to emit instruction
1973   // addresses into.
1974   void setPCSections(MachineFunction &MF, MDNode *MD);
1975 
1976   void setMMRAMetadata(MachineFunction &MF, MDNode *MMRAs);
1977 
1978   /// Set the CFI type for the instruction.
1979   void setCFIType(MachineFunction &MF, uint32_t Type);
1980 
1981   /// Return the MIFlags which represent both MachineInstrs. This
1982   /// should be used when merging two MachineInstrs into one. This routine does
1983   /// not modify the MIFlags of this MachineInstr.
1984   uint32_t mergeFlagsWith(const MachineInstr& Other) const;
1985 
1986   static uint32_t copyFlagsFromInstruction(const Instruction &I);
1987 
1988   /// Copy all flags to MachineInst MIFlags
1989   void copyIRFlags(const Instruction &I);
1990 
1991   /// Break any tie involving OpIdx.
1992   void untieRegOperand(unsigned OpIdx) {
1993     MachineOperand &MO = getOperand(OpIdx);
1994     if (MO.isReg() && MO.isTied()) {
1995       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1996       MO.TiedTo = 0;
1997     }
1998   }
1999 
2000   /// Add all implicit def and use operands to this instruction.
2001   void addImplicitDefUseOperands(MachineFunction &MF);
2002 
2003   /// Scan instructions immediately following MI and collect any matching
2004   /// DBG_VALUEs.
2005   void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
2006 
2007   /// Find all DBG_VALUEs that point to the register def in this instruction
2008   /// and point them to \p Reg instead.
2009   void changeDebugValuesDefReg(Register Reg);
2010 
2011   /// Sets all register debug operands in this debug value instruction to be
2012   /// undef.
2013   void setDebugValueUndef() {
2014     assert(isDebugValue() && "Must be a debug value instruction.");
2015     for (MachineOperand &MO : debug_operands()) {
2016       if (MO.isReg()) {
2017         MO.setReg(0);
2018         MO.setSubReg(0);
2019       }
2020     }
2021   }
2022 
2023   std::tuple<Register, Register> getFirst2Regs() const {
2024     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg());
2025   }
2026 
2027   std::tuple<Register, Register, Register> getFirst3Regs() const {
2028     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
2029                       getOperand(2).getReg());
2030   }
2031 
2032   std::tuple<Register, Register, Register, Register> getFirst4Regs() const {
2033     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
2034                       getOperand(2).getReg(), getOperand(3).getReg());
2035   }
2036 
2037   std::tuple<Register, Register, Register, Register, Register>
2038   getFirst5Regs() const {
2039     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
2040                       getOperand(2).getReg(), getOperand(3).getReg(),
2041                       getOperand(4).getReg());
2042   }
2043 
2044   std::tuple<LLT, LLT> getFirst2LLTs() const;
2045   std::tuple<LLT, LLT, LLT> getFirst3LLTs() const;
2046   std::tuple<LLT, LLT, LLT, LLT> getFirst4LLTs() const;
2047   std::tuple<LLT, LLT, LLT, LLT, LLT> getFirst5LLTs() const;
2048 
2049   std::tuple<Register, LLT, Register, LLT> getFirst2RegLLTs() const;
2050   std::tuple<Register, LLT, Register, LLT, Register, LLT>
2051   getFirst3RegLLTs() const;
2052   std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT>
2053   getFirst4RegLLTs() const;
2054   std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT,
2055              Register, LLT>
2056   getFirst5RegLLTs() const;
2057 
2058 private:
2059   /// If this instruction is embedded into a MachineFunction, return the
2060   /// MachineRegisterInfo object for the current function, otherwise
2061   /// return null.
2062   MachineRegisterInfo *getRegInfo();
2063   const MachineRegisterInfo *getRegInfo() const;
2064 
2065   /// Unlink all of the register operands in this instruction from their
2066   /// respective use lists.  This requires that the operands already be on their
2067   /// use lists.
2068   void removeRegOperandsFromUseLists(MachineRegisterInfo&);
2069 
2070   /// Add all of the register operands in this instruction from their
2071   /// respective use lists.  This requires that the operands not be on their
2072   /// use lists yet.
2073   void addRegOperandsToUseLists(MachineRegisterInfo&);
2074 
2075   /// Slow path for hasProperty when we're dealing with a bundle.
2076   bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
2077 
2078   /// Implements the logic of getRegClassConstraintEffectForVReg for the
2079   /// this MI and the given operand index \p OpIdx.
2080   /// If the related operand does not constrained Reg, this returns CurRC.
2081   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
2082       unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
2083       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
2084 
2085   /// Stores extra instruction information inline or allocates as ExtraInfo
2086   /// based on the number of pointers.
2087   void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
2088                     MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
2089                     MDNode *HeapAllocMarker, MDNode *PCSections,
2090                     uint32_t CFIType, MDNode *MMRAs);
2091 };
2092 
2093 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
2094 /// instruction rather than by pointer value.
2095 /// The hashing and equality testing functions ignore definitions so this is
2096 /// useful for CSE, etc.
2097 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
2098   static inline MachineInstr *getEmptyKey() {
2099     return nullptr;
2100   }
2101 
2102   static inline MachineInstr *getTombstoneKey() {
2103     return reinterpret_cast<MachineInstr*>(-1);
2104   }
2105 
2106   static unsigned getHashValue(const MachineInstr* const &MI);
2107 
2108   static bool isEqual(const MachineInstr* const &LHS,
2109                       const MachineInstr* const &RHS) {
2110     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
2111         LHS == getEmptyKey() || LHS == getTombstoneKey())
2112       return LHS == RHS;
2113     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
2114   }
2115 };
2116 
2117 //===----------------------------------------------------------------------===//
2118 // Debugging Support
2119 
2120 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
2121   MI.print(OS);
2122   return OS;
2123 }
2124 
2125 } // end namespace llvm
2126 
2127 #endif // LLVM_CODEGEN_MACHINEINSTR_H