Home | History | Annotate | Download | only in CodeGen
      1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file contains the declaration of the MachineInstr class, which is the
     11 // basic representation for all target dependent machine instructions used by
     12 // the back end.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
     17 #define LLVM_CODEGEN_MACHINEINSTR_H
     18 
     19 #include "llvm/CodeGen/MachineOperand.h"
     20 #include "llvm/MC/MCInstrDesc.h"
     21 #include "llvm/Target/TargetOpcodes.h"
     22 #include "llvm/ADT/ArrayRef.h"
     23 #include "llvm/ADT/ilist.h"
     24 #include "llvm/ADT/ilist_node.h"
     25 #include "llvm/ADT/STLExtras.h"
     26 #include "llvm/ADT/StringRef.h"
     27 #include "llvm/ADT/DenseMapInfo.h"
     28 #include "llvm/InlineAsm.h"
     29 #include "llvm/Support/DebugLoc.h"
     30 #include <vector>
     31 
     32 namespace llvm {
     33 
     34 template <typename T> class SmallVectorImpl;
     35 class AliasAnalysis;
     36 class TargetInstrInfo;
     37 class TargetRegisterClass;
     38 class TargetRegisterInfo;
     39 class MachineFunction;
     40 class MachineMemOperand;
     41 
     42 //===----------------------------------------------------------------------===//
     43 /// MachineInstr - Representation of each machine instruction.
     44 ///
     45 class MachineInstr : public ilist_node<MachineInstr> {
     46 public:
     47   typedef MachineMemOperand **mmo_iterator;
     48 
     49   /// Flags to specify different kinds of comments to output in
     50   /// assembly code.  These flags carry semantic information not
     51   /// otherwise easily derivable from the IR text.
     52   ///
     53   enum CommentFlag {
     54     ReloadReuse = 0x1
     55   };
     56 
     57   enum MIFlag {
     58     NoFlags      = 0,
     59     FrameSetup   = 1 << 0,              // Instruction is used as a part of
     60                                         // function frame setup code.
     61     InsideBundle = 1 << 1               // Instruction is inside a bundle (not
     62                                         // the first MI in a bundle)
     63   };
     64 private:
     65   const MCInstrDesc *MCID;              // Instruction descriptor.
     66 
     67   uint8_t Flags;                        // Various bits of additional
     68                                         // information about machine
     69                                         // instruction.
     70 
     71   uint8_t AsmPrinterFlags;              // Various bits of information used by
     72                                         // the AsmPrinter to emit helpful
     73                                         // comments.  This is *not* semantic
     74                                         // information.  Do not use this for
     75                                         // anything other than to convey comment
     76                                         // information to AsmPrinter.
     77 
     78   uint16_t NumMemRefs;                  // information on memory references
     79   mmo_iterator MemRefs;
     80 
     81   std::vector<MachineOperand> Operands; // the operands
     82   MachineBasicBlock *Parent;            // Pointer to the owning basic block.
     83   DebugLoc debugLoc;                    // Source line information.
     84 
     85   MachineInstr(const MachineInstr&);   // DO NOT IMPLEMENT
     86   void operator=(const MachineInstr&); // DO NOT IMPLEMENT
     87 
     88   // Intrusive list support
     89   friend struct ilist_traits<MachineInstr>;
     90   friend struct ilist_traits<MachineBasicBlock>;
     91   void setParent(MachineBasicBlock *P) { Parent = P; }
     92 
     93   /// MachineInstr ctor - This constructor creates a copy of the given
     94   /// MachineInstr in the given MachineFunction.
     95   MachineInstr(MachineFunction &, const MachineInstr &);
     96 
     97   /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
     98   /// MCID NULL and no operands.
     99   MachineInstr();
    100 
    101   // The next two constructors have DebugLoc and non-DebugLoc versions;
    102   // over time, the non-DebugLoc versions should be phased out and eventually
    103   // removed.
    104 
    105   /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
    106   /// implicit operands.  It reserves space for the number of operands specified
    107   /// by the MCInstrDesc.  The version with a DebugLoc should be preferred.
    108   explicit MachineInstr(const MCInstrDesc &MCID, bool NoImp = false);
    109 
    110   /// MachineInstr ctor - Work exactly the same as the ctor above, except that
    111   /// the MachineInstr is created and added to the end of the specified basic
    112   /// block.  The version with a DebugLoc should be preferred.
    113   MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &MCID);
    114 
    115   /// MachineInstr ctor - This constructor create a MachineInstr and add the
    116   /// implicit operands.  It reserves space for number of operands specified by
    117   /// MCInstrDesc.  An explicit DebugLoc is supplied.
    118   explicit MachineInstr(const MCInstrDesc &MCID, const DebugLoc dl,
    119                         bool NoImp = false);
    120 
    121   /// MachineInstr ctor - Work exactly the same as the ctor above, except that
    122   /// the MachineInstr is created and added to the end of the specified basic
    123   /// block.
    124   MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
    125                const MCInstrDesc &MCID);
    126 
    127   ~MachineInstr();
    128 
    129   // MachineInstrs are pool-allocated and owned by MachineFunction.
    130   friend class MachineFunction;
    131 
    132 public:
    133   const MachineBasicBlock* getParent() const { return Parent; }
    134   MachineBasicBlock* getParent() { return Parent; }
    135 
    136   /// getAsmPrinterFlags - Return the asm printer flags bitvector.
    137   ///
    138   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
    139 
    140   /// clearAsmPrinterFlags - clear the AsmPrinter bitvector
    141   ///
    142   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
    143 
    144   /// getAsmPrinterFlag - Return whether an AsmPrinter flag is set.
    145   ///
    146   bool getAsmPrinterFlag(CommentFlag Flag) const {
    147     return AsmPrinterFlags & Flag;
    148   }
    149 
    150   /// setAsmPrinterFlag - Set a flag for the AsmPrinter.
    151   ///
    152   void setAsmPrinterFlag(CommentFlag Flag) {
    153     AsmPrinterFlags |= (uint8_t)Flag;
    154   }
    155 
    156   /// clearAsmPrinterFlag - clear specific AsmPrinter flags
    157   ///
    158   void clearAsmPrinterFlag(CommentFlag Flag) {
    159     AsmPrinterFlags &= ~Flag;
    160   }
    161 
    162   /// getFlags - Return the MI flags bitvector.
    163   uint8_t getFlags() const {
    164     return Flags;
    165   }
    166 
    167   /// getFlag - Return whether an MI flag is set.
    168   bool getFlag(MIFlag Flag) const {
    169     return Flags & Flag;
    170   }
    171 
    172   /// setFlag - Set a MI flag.
    173   void setFlag(MIFlag Flag) {
    174     Flags |= (uint8_t)Flag;
    175   }
    176 
    177   void setFlags(unsigned flags) {
    178     Flags = flags;
    179   }
    180 
    181   /// clearFlag - Clear a MI flag.
    182   void clearFlag(MIFlag Flag) {
    183     Flags &= ~((uint8_t)Flag);
    184   }
    185 
    186   /// isInsideBundle - Return true if MI is in a bundle (but not the first MI
    187   /// in a bundle).
    188   ///
    189   /// A bundle looks like this before it's finalized:
    190   ///   ----------------
    191   ///   |      MI      |
    192   ///   ----------------
    193   ///          |
    194   ///   ----------------
    195   ///   |      MI    * |
    196   ///   ----------------
    197   ///          |
    198   ///   ----------------
    199   ///   |      MI    * |
    200   ///   ----------------
    201   /// In this case, the first MI starts a bundle but is not inside a bundle, the
    202   /// next 2 MIs are considered "inside" the bundle.
    203   ///
    204   /// After a bundle is finalized, it looks like this:
    205   ///   ----------------
    206   ///   |    Bundle    |
    207   ///   ----------------
    208   ///          |
    209   ///   ----------------
    210   ///   |      MI    * |
    211   ///   ----------------
    212   ///          |
    213   ///   ----------------
    214   ///   |      MI    * |
    215   ///   ----------------
    216   ///          |
    217   ///   ----------------
    218   ///   |      MI    * |
    219   ///   ----------------
    220   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
    221   /// a bundle, but the next three MIs are.
    222   bool isInsideBundle() const {
    223     return getFlag(InsideBundle);
    224   }
    225 
    226   /// setIsInsideBundle - Set InsideBundle bit.
    227   ///
    228   void setIsInsideBundle(bool Val = true) {
    229     if (Val)
    230       setFlag(InsideBundle);
    231     else
    232       clearFlag(InsideBundle);
    233   }
    234 
    235   /// isBundled - Return true if this instruction part of a bundle. This is true
    236   /// if either itself or its following instruction is marked "InsideBundle".
    237   bool isBundled() const;
    238 
    239   /// getDebugLoc - Returns the debug location id of this MachineInstr.
    240   ///
    241   DebugLoc getDebugLoc() const { return debugLoc; }
    242 
    243   /// emitError - Emit an error referring to the source location of this
    244   /// instruction. This should only be used for inline assembly that is somehow
    245   /// impossible to compile. Other errors should have been handled much
    246   /// earlier.
    247   ///
    248   /// If this method returns, the caller should try to recover from the error.
    249   ///
    250   void emitError(StringRef Msg) const;
    251 
    252   /// getDesc - Returns the target instruction descriptor of this
    253   /// MachineInstr.
    254   const MCInstrDesc &getDesc() const { return *MCID; }
    255 
    256   /// getOpcode - Returns the opcode of this MachineInstr.
    257   ///
    258   int getOpcode() const { return MCID->Opcode; }
    259 
    260   /// Access to explicit operands of the instruction.
    261   ///
    262   unsigned getNumOperands() const { return (unsigned)Operands.size(); }
    263 
    264   const MachineOperand& getOperand(unsigned i) const {
    265     assert(i < getNumOperands() && "getOperand() out of range!");
    266     return Operands[i];
    267   }
    268   MachineOperand& getOperand(unsigned i) {
    269     assert(i < getNumOperands() && "getOperand() out of range!");
    270     return Operands[i];
    271   }
    272 
    273   /// getNumExplicitOperands - Returns the number of non-implicit operands.
    274   ///
    275   unsigned getNumExplicitOperands() const;
    276 
    277   /// iterator/begin/end - Iterate over all operands of a machine instruction.
    278   typedef std::vector<MachineOperand>::iterator mop_iterator;
    279   typedef std::vector<MachineOperand>::const_iterator const_mop_iterator;
    280 
    281   mop_iterator operands_begin() { return Operands.begin(); }
    282   mop_iterator operands_end() { return Operands.end(); }
    283 
    284   const_mop_iterator operands_begin() const { return Operands.begin(); }
    285   const_mop_iterator operands_end() const { return Operands.end(); }
    286 
    287   /// Access to memory operands of the instruction
    288   mmo_iterator memoperands_begin() const { return MemRefs; }
    289   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
    290   bool memoperands_empty() const { return NumMemRefs == 0; }
    291 
    292   /// hasOneMemOperand - Return true if this instruction has exactly one
    293   /// MachineMemOperand.
    294   bool hasOneMemOperand() const {
    295     return NumMemRefs == 1;
    296   }
    297 
    298   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
    299   /// queries but they are bundle aware.
    300 
    301   enum QueryType {
    302     IgnoreBundle,    // Ignore bundles
    303     AnyInBundle,     // Return true if any instruction in bundle has property
    304     AllInBundle      // Return true if all instructions in bundle have property
    305   };
    306 
    307   /// hasProperty - Return true if the instruction (or in the case of a bundle,
    308   /// the instructions inside the bundle) has the specified property.
    309   /// The first argument is the property being queried.
    310   /// The second argument indicates whether the query should look inside
    311   /// instruction bundles.
    312   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
    313     // Inline the fast path.
    314     if (Type == IgnoreBundle || !isBundle())
    315       return getDesc().getFlags() & (1 << MCFlag);
    316 
    317     // If we have a bundle, take the slow path.
    318     return hasPropertyInBundle(1 << MCFlag, Type);
    319   }
    320 
    321   /// isVariadic - Return true if this instruction can have a variable number of
    322   /// operands.  In this case, the variable operands will be after the normal
    323   /// operands but before the implicit definitions and uses (if any are
    324   /// present).
    325   bool isVariadic(QueryType Type = IgnoreBundle) const {
    326     return hasProperty(MCID::Variadic, Type);
    327   }
    328 
    329   /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
    330   /// ARM instructions which can set condition code if 's' bit is set.
    331   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
    332     return hasProperty(MCID::HasOptionalDef, Type);
    333   }
    334 
    335   /// isPseudo - Return true if this is a pseudo instruction that doesn't
    336   /// correspond to a real machine instruction.
    337   ///
    338   bool isPseudo(QueryType Type = IgnoreBundle) const {
    339     return hasProperty(MCID::Pseudo, Type);
    340   }
    341 
    342   bool isReturn(QueryType Type = AnyInBundle) const {
    343     return hasProperty(MCID::Return, Type);
    344   }
    345 
    346   bool isCall(QueryType Type = AnyInBundle) const {
    347     return hasProperty(MCID::Call, Type);
    348   }
    349 
    350   /// isBarrier - Returns true if the specified instruction stops control flow
    351   /// from executing the instruction immediately following it.  Examples include
    352   /// unconditional branches and return instructions.
    353   bool isBarrier(QueryType Type = AnyInBundle) const {
    354     return hasProperty(MCID::Barrier, Type);
    355   }
    356 
    357   /// isTerminator - Returns true if this instruction part of the terminator for
    358   /// a basic block.  Typically this is things like return and branch
    359   /// instructions.
    360   ///
    361   /// Various passes use this to insert code into the bottom of a basic block,
    362   /// but before control flow occurs.
    363   bool isTerminator(QueryType Type = AnyInBundle) const {
    364     return hasProperty(MCID::Terminator, Type);
    365   }
    366 
    367   /// isBranch - Returns true if this is a conditional, unconditional, or
    368   /// indirect branch.  Predicates below can be used to discriminate between
    369   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
    370   /// get more information.
    371   bool isBranch(QueryType Type = AnyInBundle) const {
    372     return hasProperty(MCID::Branch, Type);
    373   }
    374 
    375   /// isIndirectBranch - Return true if this is an indirect branch, such as a
    376   /// branch through a register.
    377   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
    378     return hasProperty(MCID::IndirectBranch, Type);
    379   }
    380 
    381   /// isConditionalBranch - Return true if this is a branch which may fall
    382   /// through to the next instruction or may transfer control flow to some other
    383   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
    384   /// information about this branch.
    385   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
    386     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
    387   }
    388 
    389   /// isUnconditionalBranch - Return true if this is a branch which always
    390   /// transfers control flow to some other block.  The
    391   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
    392   /// about this branch.
    393   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
    394     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
    395   }
    396 
    397   // isPredicable - Return true if this instruction has a predicate operand that
    398   // controls execution.  It may be set to 'always', or may be set to other
    399   /// values.   There are various methods in TargetInstrInfo that can be used to
    400   /// control and modify the predicate in this instruction.
    401   bool isPredicable(QueryType Type = AllInBundle) const {
    402     // If it's a bundle than all bundled instructions must be predicable for this
    403     // to return true.
    404     return hasProperty(MCID::Predicable, Type);
    405   }
    406 
    407   /// isCompare - Return true if this instruction is a comparison.
    408   bool isCompare(QueryType Type = IgnoreBundle) const {
    409     return hasProperty(MCID::Compare, Type);
    410   }
    411 
    412   /// isMoveImmediate - Return true if this instruction is a move immediate
    413   /// (including conditional moves) instruction.
    414   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
    415     return hasProperty(MCID::MoveImm, Type);
    416   }
    417 
    418   /// isBitcast - Return true if this instruction is a bitcast instruction.
    419   ///
    420   bool isBitcast(QueryType Type = IgnoreBundle) const {
    421     return hasProperty(MCID::Bitcast, Type);
    422   }
    423 
    424   /// isSelect - Return true if this instruction is a select instruction.
    425   ///
    426   bool isSelect(QueryType Type = IgnoreBundle) const {
    427     return hasProperty(MCID::Select, Type);
    428   }
    429 
    430   /// isNotDuplicable - Return true if this instruction cannot be safely
    431   /// duplicated.  For example, if the instruction has a unique labels attached
    432   /// to it, duplicating it would cause multiple definition errors.
    433   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
    434     return hasProperty(MCID::NotDuplicable, Type);
    435   }
    436 
    437   /// hasDelaySlot - Returns true if the specified instruction has a delay slot
    438   /// which must be filled by the code generator.
    439   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
    440     return hasProperty(MCID::DelaySlot, Type);
    441   }
    442 
    443   /// canFoldAsLoad - Return true for instructions that can be folded as
    444   /// memory operands in other instructions. The most common use for this
    445   /// is instructions that are simple loads from memory that don't modify
    446   /// the loaded value in any way, but it can also be used for instructions
    447   /// that can be expressed as constant-pool loads, such as V_SETALLONES
    448   /// on x86, to allow them to be folded when it is beneficial.
    449   /// This should only be set on instructions that return a value in their
    450   /// only virtual register definition.
    451   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
    452     return hasProperty(MCID::FoldableAsLoad, Type);
    453   }
    454 
    455   //===--------------------------------------------------------------------===//
    456   // Side Effect Analysis
    457   //===--------------------------------------------------------------------===//
    458 
    459   /// mayLoad - Return true if this instruction could possibly read memory.
    460   /// Instructions with this flag set are not necessarily simple load
    461   /// instructions, they may load a value and modify it, for example.
    462   bool mayLoad(QueryType Type = AnyInBundle) const {
    463     return hasProperty(MCID::MayLoad, Type);
    464   }
    465 
    466 
    467   /// mayStore - Return true if this instruction could possibly modify memory.
    468   /// Instructions with this flag set are not necessarily simple store
    469   /// instructions, they may store a modified value based on their operands, or
    470   /// may not actually modify anything, for example.
    471   bool mayStore(QueryType Type = AnyInBundle) const {
    472     return hasProperty(MCID::MayStore, Type);
    473   }
    474 
    475   //===--------------------------------------------------------------------===//
    476   // Flags that indicate whether an instruction can be modified by a method.
    477   //===--------------------------------------------------------------------===//
    478 
    479   /// isCommutable - Return true if this may be a 2- or 3-address
    480   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
    481   /// result if Y and Z are exchanged.  If this flag is set, then the
    482   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
    483   /// instruction.
    484   ///
    485   /// Note that this flag may be set on instructions that are only commutable
    486   /// sometimes.  In these cases, the call to commuteInstruction will fail.
    487   /// Also note that some instructions require non-trivial modification to
    488   /// commute them.
    489   bool isCommutable(QueryType Type = IgnoreBundle) const {
    490     return hasProperty(MCID::Commutable, Type);
    491   }
    492 
    493   /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
    494   /// which can be changed into a 3-address instruction if needed.  Doing this
    495   /// transformation can be profitable in the register allocator, because it
    496   /// means that the instruction can use a 2-address form if possible, but
    497   /// degrade into a less efficient form if the source and dest register cannot
    498   /// be assigned to the same register.  For example, this allows the x86
    499   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
    500   /// is the same speed as the shift but has bigger code size.
    501   ///
    502   /// If this returns true, then the target must implement the
    503   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
    504   /// is allowed to fail if the transformation isn't valid for this specific
    505   /// instruction (e.g. shl reg, 4 on x86).
    506   ///
    507   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
    508     return hasProperty(MCID::ConvertibleTo3Addr, Type);
    509   }
    510 
    511   /// usesCustomInsertionHook - Return true if this instruction requires
    512   /// custom insertion support when the DAG scheduler is inserting it into a
    513   /// machine basic block.  If this is true for the instruction, it basically
    514   /// means that it is a pseudo instruction used at SelectionDAG time that is
    515   /// expanded out into magic code by the target when MachineInstrs are formed.
    516   ///
    517   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
    518   /// is used to insert this into the MachineBasicBlock.
    519   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
    520     return hasProperty(MCID::UsesCustomInserter, Type);
    521   }
    522 
    523   /// hasPostISelHook - Return true if this instruction requires *adjustment*
    524   /// after instruction selection by calling a target hook. For example, this
    525   /// can be used to fill in ARM 's' optional operand depending on whether
    526   /// the conditional flag register is used.
    527   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
    528     return hasProperty(MCID::HasPostISelHook, Type);
    529   }
    530 
    531   /// isRematerializable - Returns true if this instruction is a candidate for
    532   /// remat.  This flag is deprecated, please don't use it anymore.  If this
    533   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
    534   /// verify the instruction is really rematable.
    535   bool isRematerializable(QueryType Type = AllInBundle) const {
    536     // It's only possible to re-mat a bundle if all bundled instructions are
    537     // re-materializable.
    538     return hasProperty(MCID::Rematerializable, Type);
    539   }
    540 
    541   /// isAsCheapAsAMove - Returns true if this instruction has the same cost (or
    542   /// less) than a move instruction. This is useful during certain types of
    543   /// optimizations (e.g., remat during two-address conversion or machine licm)
    544   /// where we would like to remat or hoist the instruction, but not if it costs
    545   /// more than moving the instruction into the appropriate register. Note, we
    546   /// are not marking copies from and to the same register class with this flag.
    547   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
    548     // Only returns true for a bundle if all bundled instructions are cheap.
    549     // FIXME: This probably requires a target hook.
    550     return hasProperty(MCID::CheapAsAMove, Type);
    551   }
    552 
    553   /// hasExtraSrcRegAllocReq - Returns true if this instruction source operands
    554   /// have special register allocation requirements that are not captured by the
    555   /// operand register classes. e.g. ARM::STRD's two source registers must be an
    556   /// even / odd pair, ARM::STM registers have to be in ascending order.
    557   /// Post-register allocation passes should not attempt to change allocations
    558   /// for sources of instructions with this flag.
    559   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
    560     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
    561   }
    562 
    563   /// hasExtraDefRegAllocReq - Returns true if this instruction def operands
    564   /// have special register allocation requirements that are not captured by the
    565   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
    566   /// even / odd pair, ARM::LDM registers have to be in ascending order.
    567   /// Post-register allocation passes should not attempt to change allocations
    568   /// for definitions of instructions with this flag.
    569   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
    570     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
    571   }
    572 
    573 
    574   enum MICheckType {
    575     CheckDefs,      // Check all operands for equality
    576     CheckKillDead,  // Check all operands including kill / dead markers
    577     IgnoreDefs,     // Ignore all definitions
    578     IgnoreVRegDefs  // Ignore virtual register definitions
    579   };
    580 
    581   /// isIdenticalTo - Return true if this instruction is identical to (same
    582   /// opcode and same operands as) the specified instruction.
    583   bool isIdenticalTo(const MachineInstr *Other,
    584                      MICheckType Check = CheckDefs) const;
    585 
    586   /// removeFromParent - This method unlinks 'this' from the containing basic
    587   /// block, and returns it, but does not delete it.
    588   MachineInstr *removeFromParent();
    589 
    590   /// eraseFromParent - This method unlinks 'this' from the containing basic
    591   /// block and deletes it.
    592   void eraseFromParent();
    593 
    594   /// isLabel - Returns true if the MachineInstr represents a label.
    595   ///
    596   bool isLabel() const {
    597     return getOpcode() == TargetOpcode::PROLOG_LABEL ||
    598            getOpcode() == TargetOpcode::EH_LABEL ||
    599            getOpcode() == TargetOpcode::GC_LABEL;
    600   }
    601 
    602   bool isPrologLabel() const {
    603     return getOpcode() == TargetOpcode::PROLOG_LABEL;
    604   }
    605   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
    606   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
    607   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
    608 
    609   bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
    610   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
    611   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
    612   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
    613   bool isStackAligningInlineAsm() const;
    614   InlineAsm::AsmDialect getInlineAsmDialect() const;
    615   bool isInsertSubreg() const {
    616     return getOpcode() == TargetOpcode::INSERT_SUBREG;
    617   }
    618   bool isSubregToReg() const {
    619     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
    620   }
    621   bool isRegSequence() const {
    622     return getOpcode() == TargetOpcode::REG_SEQUENCE;
    623   }
    624   bool isBundle() const {
    625     return getOpcode() == TargetOpcode::BUNDLE;
    626   }
    627   bool isCopy() const {
    628     return getOpcode() == TargetOpcode::COPY;
    629   }
    630   bool isFullCopy() const {
    631     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
    632   }
    633 
    634   /// isCopyLike - Return true if the instruction behaves like a copy.
    635   /// This does not include native copy instructions.
    636   bool isCopyLike() const {
    637     return isCopy() || isSubregToReg();
    638   }
    639 
    640   /// isIdentityCopy - Return true is the instruction is an identity copy.
    641   bool isIdentityCopy() const {
    642     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
    643       getOperand(0).getSubReg() == getOperand(1).getSubReg();
    644   }
    645 
    646   /// isTransient - Return true if this is a transient instruction that is
    647   /// either very likely to be eliminated during register allocation (such as
    648   /// copy-like instructions), or if this instruction doesn't have an
    649   /// execution-time cost.
    650   bool isTransient() const {
    651     switch(getOpcode()) {
    652     default: return false;
    653     // Copy-like instructions are usually eliminated during register allocation.
    654     case TargetOpcode::PHI:
    655     case TargetOpcode::COPY:
    656     case TargetOpcode::INSERT_SUBREG:
    657     case TargetOpcode::SUBREG_TO_REG:
    658     case TargetOpcode::REG_SEQUENCE:
    659     // Pseudo-instructions that don't produce any real output.
    660     case TargetOpcode::IMPLICIT_DEF:
    661     case TargetOpcode::KILL:
    662     case TargetOpcode::PROLOG_LABEL:
    663     case TargetOpcode::EH_LABEL:
    664     case TargetOpcode::GC_LABEL:
    665     case TargetOpcode::DBG_VALUE:
    666       return true;
    667     }
    668   }
    669 
    670   /// getBundleSize - Return the number of instructions inside the MI bundle.
    671   unsigned getBundleSize() const;
    672 
    673   /// readsRegister - Return true if the MachineInstr reads the specified
    674   /// register. If TargetRegisterInfo is passed, then it also checks if there
    675   /// is a read of a super-register.
    676   /// This does not count partial redefines of virtual registers as reads:
    677   ///   %reg1024:6 = OP.
    678   bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
    679     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
    680   }
    681 
    682   /// readsVirtualRegister - Return true if the MachineInstr reads the specified
    683   /// virtual register. Take into account that a partial define is a
    684   /// read-modify-write operation.
    685   bool readsVirtualRegister(unsigned Reg) const {
    686     return readsWritesVirtualRegister(Reg).first;
    687   }
    688 
    689   /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
    690   /// indicating if this instruction reads or writes Reg. This also considers
    691   /// partial defines.
    692   /// If Ops is not null, all operand indices for Reg are added.
    693   std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
    694                                       SmallVectorImpl<unsigned> *Ops = 0) const;
    695 
    696   /// killsRegister - Return true if the MachineInstr kills the specified
    697   /// register. If TargetRegisterInfo is passed, then it also checks if there is
    698   /// a kill of a super-register.
    699   bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
    700     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
    701   }
    702 
    703   /// definesRegister - Return true if the MachineInstr fully defines the
    704   /// specified register. If TargetRegisterInfo is passed, then it also checks
    705   /// if there is a def of a super-register.
    706   /// NOTE: It's ignoring subreg indices on virtual registers.
    707   bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=NULL) const {
    708     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
    709   }
    710 
    711   /// modifiesRegister - Return true if the MachineInstr modifies (fully define
    712   /// or partially define) the specified register.
    713   /// NOTE: It's ignoring subreg indices on virtual registers.
    714   bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
    715     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
    716   }
    717 
    718   /// registerDefIsDead - Returns true if the register is dead in this machine
    719   /// instruction. If TargetRegisterInfo is passed, then it also checks
    720   /// if there is a dead def of a super-register.
    721   bool registerDefIsDead(unsigned Reg,
    722                          const TargetRegisterInfo *TRI = NULL) const {
    723     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
    724   }
    725 
    726   /// findRegisterUseOperandIdx() - Returns the operand index that is a use of
    727   /// the specific register or -1 if it is not found. It further tightens
    728   /// the search criteria to a use that kills the register if isKill is true.
    729   int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
    730                                 const TargetRegisterInfo *TRI = NULL) const;
    731 
    732   /// findRegisterUseOperand - Wrapper for findRegisterUseOperandIdx, it returns
    733   /// a pointer to the MachineOperand rather than an index.
    734   MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
    735                                          const TargetRegisterInfo *TRI = NULL) {
    736     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
    737     return (Idx == -1) ? NULL : &getOperand(Idx);
    738   }
    739 
    740   /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
    741   /// the specified register or -1 if it is not found. If isDead is true, defs
    742   /// that are not dead are skipped. If Overlap is true, then it also looks for
    743   /// defs that merely overlap the specified register. If TargetRegisterInfo is
    744   /// non-null, then it also checks if there is a def of a super-register.
    745   /// This may also return a register mask operand when Overlap is true.
    746   int findRegisterDefOperandIdx(unsigned Reg,
    747                                 bool isDead = false, bool Overlap = false,
    748                                 const TargetRegisterInfo *TRI = NULL) const;
    749 
    750   /// findRegisterDefOperand - Wrapper for findRegisterDefOperandIdx, it returns
    751   /// a pointer to the MachineOperand rather than an index.
    752   MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
    753                                          const TargetRegisterInfo *TRI = NULL) {
    754     int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
    755     return (Idx == -1) ? NULL : &getOperand(Idx);
    756   }
    757 
    758   /// findFirstPredOperandIdx() - Find the index of the first operand in the
    759   /// operand list that is used to represent the predicate. It returns -1 if
    760   /// none is found.
    761   int findFirstPredOperandIdx() const;
    762 
    763   /// findInlineAsmFlagIdx() - Find the index of the flag word operand that
    764   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
    765   /// getOperand(OpIdx) does not belong to an inline asm operand group.
    766   ///
    767   /// If GroupNo is not NULL, it will receive the number of the operand group
    768   /// containing OpIdx.
    769   ///
    770   /// The flag operand is an immediate that can be decoded with methods like
    771   /// InlineAsm::hasRegClassConstraint().
    772   ///
    773   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = 0) const;
    774 
    775   /// getRegClassConstraint - Compute the static register class constraint for
    776   /// operand OpIdx.  For normal instructions, this is derived from the
    777   /// MCInstrDesc.  For inline assembly it is derived from the flag words.
    778   ///
    779   /// Returns NULL if the static register classs constraint cannot be
    780   /// determined.
    781   ///
    782   const TargetRegisterClass*
    783   getRegClassConstraint(unsigned OpIdx,
    784                         const TargetInstrInfo *TII,
    785                         const TargetRegisterInfo *TRI) const;
    786 
    787   /// tieOperands - Add a tie between the register operands at DefIdx and
    788   /// UseIdx. The tie will cause the register allocator to ensure that the two
    789   /// operands are assigned the same physical register.
    790   ///
    791   /// Tied operands are managed automatically for explicit operands in the
    792   /// MCInstrDesc. This method is for exceptional cases like inline asm.
    793   void tieOperands(unsigned DefIdx, unsigned UseIdx);
    794 
    795   /// findTiedOperandIdx - Given the index of a tied register operand, find the
    796   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
    797   /// index of the tied operand which must exist.
    798   unsigned findTiedOperandIdx(unsigned OpIdx) const;
    799 
    800   /// isRegTiedToUseOperand - Given the index of a register def operand,
    801   /// check if the register def is tied to a source operand, due to either
    802   /// two-address elimination or inline assembly constraints. Returns the
    803   /// first tied use operand index by reference if UseOpIdx is not null.
    804   bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx = 0) const {
    805     const MachineOperand &MO = getOperand(DefOpIdx);
    806     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
    807       return false;
    808     if (UseOpIdx)
    809       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
    810     return true;
    811   }
    812 
    813   /// isRegTiedToDefOperand - Return true if the use operand of the specified
    814   /// index is tied to an def operand. It also returns the def operand index by
    815   /// reference if DefOpIdx is not null.
    816   bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx = 0) const {
    817     const MachineOperand &MO = getOperand(UseOpIdx);
    818     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
    819       return false;
    820     if (DefOpIdx)
    821       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
    822     return true;
    823   }
    824 
    825   /// clearKillInfo - Clears kill flags on all operands.
    826   ///
    827   void clearKillInfo();
    828 
    829   /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
    830   ///
    831   void copyKillDeadInfo(const MachineInstr *MI);
    832 
    833   /// copyPredicates - Copies predicate operand(s) from MI.
    834   void copyPredicates(const MachineInstr *MI);
    835 
    836   /// substituteRegister - Replace all occurrences of FromReg with ToReg:SubIdx,
    837   /// properly composing subreg indices where necessary.
    838   void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
    839                           const TargetRegisterInfo &RegInfo);
    840 
    841   /// addRegisterKilled - We have determined MI kills a register. Look for the
    842   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
    843   /// add a implicit operand if it's not found. Returns true if the operand
    844   /// exists / is added.
    845   bool addRegisterKilled(unsigned IncomingReg,
    846                          const TargetRegisterInfo *RegInfo,
    847                          bool AddIfNotFound = false);
    848 
    849   /// clearRegisterKills - Clear all kill flags affecting Reg.  If RegInfo is
    850   /// provided, this includes super-register kills.
    851   void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
    852 
    853   /// addRegisterDead - We have determined MI defined a register without a use.
    854   /// Look for the operand that defines it and mark it as IsDead. If
    855   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
    856   /// true if the operand exists / is added.
    857   bool addRegisterDead(unsigned IncomingReg, const TargetRegisterInfo *RegInfo,
    858                        bool AddIfNotFound = false);
    859 
    860   /// addRegisterDefined - We have determined MI defines a register. Make sure
    861   /// there is an operand defining Reg.
    862   void addRegisterDefined(unsigned IncomingReg,
    863                           const TargetRegisterInfo *RegInfo = 0);
    864 
    865   /// setPhysRegsDeadExcept - Mark every physreg used by this instruction as
    866   /// dead except those in the UsedRegs list.
    867   ///
    868   /// On instructions with register mask operands, also add implicit-def
    869   /// operands for all registers in UsedRegs.
    870   void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
    871                              const TargetRegisterInfo &TRI);
    872 
    873   /// isSafeToMove - Return true if it is safe to move this instruction. If
    874   /// SawStore is set to true, it means that there is a store (or call) between
    875   /// the instruction's location and its intended destination.
    876   bool isSafeToMove(const TargetInstrInfo *TII, AliasAnalysis *AA,
    877                     bool &SawStore) const;
    878 
    879   /// isSafeToReMat - Return true if it's safe to rematerialize the specified
    880   /// instruction which defined the specified register instead of copying it.
    881   bool isSafeToReMat(const TargetInstrInfo *TII, AliasAnalysis *AA,
    882                      unsigned DstReg) const;
    883 
    884   /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
    885   /// or volatile memory reference, or if the information describing the memory
    886   /// reference is not available. Return false if it is known to have no
    887   /// ordered or volatile memory references.
    888   bool hasOrderedMemoryRef() const;
    889 
    890   /// isInvariantLoad - Return true if this instruction is loading from a
    891   /// location whose value is invariant across the function.  For example,
    892   /// loading a value from the constant pool or from the argument area of
    893   /// a function if it does not change.  This should only return true of *all*
    894   /// loads the instruction does are invariant (if it does multiple loads).
    895   bool isInvariantLoad(AliasAnalysis *AA) const;
    896 
    897   /// isConstantValuePHI - If the specified instruction is a PHI that always
    898   /// merges together the same virtual register, return the register, otherwise
    899   /// return 0.
    900   unsigned isConstantValuePHI() const;
    901 
    902   /// hasUnmodeledSideEffects - Return true if this instruction has side
    903   /// effects that are not modeled by mayLoad / mayStore, etc.
    904   /// For all instructions, the property is encoded in MCInstrDesc::Flags
    905   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
    906   /// INLINEASM instruction, in which case the side effect property is encoded
    907   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
    908   ///
    909   bool hasUnmodeledSideEffects() const;
    910 
    911   /// allDefsAreDead - Return true if all the defs of this instruction are dead.
    912   ///
    913   bool allDefsAreDead() const;
    914 
    915   /// copyImplicitOps - Copy implicit register operands from specified
    916   /// instruction to this instruction.
    917   void copyImplicitOps(const MachineInstr *MI);
    918 
    919   //
    920   // Debugging support
    921   //
    922   void print(raw_ostream &OS, const TargetMachine *TM = 0) const;
    923   void dump() const;
    924 
    925   //===--------------------------------------------------------------------===//
    926   // Accessors used to build up machine instructions.
    927 
    928   /// addOperand - Add the specified operand to the instruction.  If it is an
    929   /// implicit operand, it is added to the end of the operand list.  If it is
    930   /// an explicit operand it is added at the end of the explicit operand list
    931   /// (before the first implicit operand).
    932   void addOperand(const MachineOperand &Op);
    933 
    934   /// setDesc - Replace the instruction descriptor (thus opcode) of
    935   /// the current instruction with a new one.
    936   ///
    937   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
    938 
    939   /// setDebugLoc - Replace current source information with new such.
    940   /// Avoid using this, the constructor argument is preferable.
    941   ///
    942   void setDebugLoc(const DebugLoc dl) { debugLoc = dl; }
    943 
    944   /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
    945   /// fewer operand than it started with.
    946   ///
    947   void RemoveOperand(unsigned i);
    948 
    949   /// addMemOperand - Add a MachineMemOperand to the machine instruction.
    950   /// This function should be used only occasionally. The setMemRefs function
    951   /// is the primary method for setting up a MachineInstr's MemRefs list.
    952   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
    953 
    954   /// setMemRefs - Assign this MachineInstr's memory reference descriptor
    955   /// list. This does not transfer ownership.
    956   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
    957     MemRefs = NewMemRefs;
    958     NumMemRefs = NewMemRefsEnd - NewMemRefs;
    959   }
    960 
    961 private:
    962   /// getRegInfo - If this instruction is embedded into a MachineFunction,
    963   /// return the MachineRegisterInfo object for the current function, otherwise
    964   /// return null.
    965   MachineRegisterInfo *getRegInfo();
    966 
    967   /// untieRegOperand - Break any tie involving OpIdx.
    968   void untieRegOperand(unsigned OpIdx) {
    969     MachineOperand &MO = getOperand(OpIdx);
    970     if (MO.isReg() && MO.isTied()) {
    971       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
    972       MO.TiedTo = 0;
    973     }
    974   }
    975 
    976   /// addImplicitDefUseOperands - Add all implicit def and use operands to
    977   /// this instruction.
    978   void addImplicitDefUseOperands();
    979 
    980   /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
    981   /// this instruction from their respective use lists.  This requires that the
    982   /// operands already be on their use lists.
    983   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
    984 
    985   /// AddRegOperandsToUseLists - Add all of the register operands in
    986   /// this instruction from their respective use lists.  This requires that the
    987   /// operands not be on their use lists yet.
    988   void AddRegOperandsToUseLists(MachineRegisterInfo&);
    989 
    990   /// hasPropertyInBundle - Slow path for hasProperty when we're dealing with a
    991   /// bundle.
    992   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
    993 };
    994 
    995 /// MachineInstrExpressionTrait - Special DenseMapInfo traits to compare
    996 /// MachineInstr* by *value* of the instruction rather than by pointer value.
    997 /// The hashing and equality testing functions ignore definitions so this is
    998 /// useful for CSE, etc.
    999 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
   1000   static inline MachineInstr *getEmptyKey() {
   1001     return 0;
   1002   }
   1003 
   1004   static inline MachineInstr *getTombstoneKey() {
   1005     return reinterpret_cast<MachineInstr*>(-1);
   1006   }
   1007 
   1008   static unsigned getHashValue(const MachineInstr* const &MI);
   1009 
   1010   static bool isEqual(const MachineInstr* const &LHS,
   1011                       const MachineInstr* const &RHS) {
   1012     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
   1013         LHS == getEmptyKey() || LHS == getTombstoneKey())
   1014       return LHS == RHS;
   1015     return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
   1016   }
   1017 };
   1018 
   1019 //===----------------------------------------------------------------------===//
   1020 // Debugging Support
   1021 
   1022 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
   1023   MI.print(OS);
   1024   return OS;
   1025 }
   1026 
   1027 } // End llvm namespace
   1028 
   1029 #endif
   1030