Home | History | Annotate | Download | only in Target
      1 //===-- llvm/Target/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_TARGET_TARGETINSTRINFO_H
     15 #define LLVM_TARGET_TARGETINSTRINFO_H
     16 
     17 #include "llvm/ADT/DenseMap.h"
     18 #include "llvm/ADT/SmallSet.h"
     19 #include "llvm/CodeGen/MachineCombinerPattern.h"
     20 #include "llvm/CodeGen/MachineFunction.h"
     21 #include "llvm/CodeGen/MachineLoopInfo.h"
     22 #include "llvm/MC/MCInstrInfo.h"
     23 #include "llvm/Support/BranchProbability.h"
     24 #include "llvm/Target/TargetRegisterInfo.h"
     25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
     26 
     27 namespace llvm {
     28 
     29 class InstrItineraryData;
     30 class LiveVariables;
     31 class MCAsmInfo;
     32 class MachineMemOperand;
     33 class MachineRegisterInfo;
     34 class MDNode;
     35 class MCInst;
     36 struct MCSchedModel;
     37 class MCSymbolRefExpr;
     38 class SDNode;
     39 class ScheduleHazardRecognizer;
     40 class SelectionDAG;
     41 class ScheduleDAG;
     42 class TargetRegisterClass;
     43 class TargetRegisterInfo;
     44 class TargetSubtargetInfo;
     45 class TargetSchedModel;
     46 class DFAPacketizer;
     47 
     48 template<class T> class SmallVectorImpl;
     49 
     50 //---------------------------------------------------------------------------
     51 ///
     52 /// TargetInstrInfo - Interface to description of machine instruction set
     53 ///
     54 class TargetInstrInfo : public MCInstrInfo {
     55   TargetInstrInfo(const TargetInstrInfo &) = delete;
     56   void operator=(const TargetInstrInfo &) = delete;
     57 public:
     58   TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
     59                   unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
     60       : CallFrameSetupOpcode(CFSetupOpcode),
     61         CallFrameDestroyOpcode(CFDestroyOpcode),
     62         CatchRetOpcode(CatchRetOpcode),
     63         ReturnOpcode(ReturnOpcode) {}
     64 
     65   virtual ~TargetInstrInfo();
     66 
     67   static bool isGenericOpcode(unsigned Opc) {
     68     return Opc <= TargetOpcode::GENERIC_OP_END;
     69   }
     70 
     71   /// Given a machine instruction descriptor, returns the register
     72   /// class constraint for OpNum, or NULL.
     73   const TargetRegisterClass *getRegClass(const MCInstrDesc &TID,
     74                                          unsigned OpNum,
     75                                          const TargetRegisterInfo *TRI,
     76                                          const MachineFunction &MF) const;
     77 
     78   /// Return true if the instruction is trivially rematerializable, meaning it
     79   /// has no side effects and requires no operands that aren't always available.
     80   /// This means the only allowed uses are constants and unallocatable physical
     81   /// registers so that the instructions result is independent of the place
     82   /// in the function.
     83   bool isTriviallyReMaterializable(const MachineInstr &MI,
     84                                    AliasAnalysis *AA = nullptr) const {
     85     return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
     86            (MI.getDesc().isRematerializable() &&
     87             (isReallyTriviallyReMaterializable(MI, AA) ||
     88              isReallyTriviallyReMaterializableGeneric(MI, AA)));
     89   }
     90 
     91 protected:
     92   /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
     93   /// set, this hook lets the target specify whether the instruction is actually
     94   /// trivially rematerializable, taking into consideration its operands. This
     95   /// predicate must return false if the instruction has any side effects other
     96   /// than producing a value, or if it requres any address registers that are
     97   /// not always available.
     98   /// Requirements must be check as stated in isTriviallyReMaterializable() .
     99   virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
    100                                                  AliasAnalysis *AA) const {
    101     return false;
    102   }
    103 
    104   /// This method commutes the operands of the given machine instruction MI.
    105   /// The operands to be commuted are specified by their indices OpIdx1 and
    106   /// OpIdx2.
    107   ///
    108   /// If a target has any instructions that are commutable but require
    109   /// converting to different instructions or making non-trivial changes
    110   /// to commute them, this method can be overloaded to do that.
    111   /// The default implementation simply swaps the commutable operands.
    112   ///
    113   /// If NewMI is false, MI is modified in place and returned; otherwise, a
    114   /// new machine instruction is created and returned.
    115   ///
    116   /// Do not call this method for a non-commutable instruction.
    117   /// Even though the instruction is commutable, the method may still
    118   /// fail to commute the operands, null pointer is returned in such cases.
    119   virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
    120                                                unsigned OpIdx1,
    121                                                unsigned OpIdx2) const;
    122 
    123   /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
    124   /// operand indices to (ResultIdx1, ResultIdx2).
    125   /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
    126   /// predefined to some indices or be undefined (designated by the special
    127   /// value 'CommuteAnyOperandIndex').
    128   /// The predefined result indices cannot be re-defined.
    129   /// The function returns true iff after the result pair redefinition
    130   /// the fixed result pair is equal to or equivalent to the source pair of
    131   /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
    132   /// the pairs (x,y) and (y,x) are equivalent.
    133   static bool fixCommutedOpIndices(unsigned &ResultIdx1,
    134                                    unsigned &ResultIdx2,
    135                                    unsigned CommutableOpIdx1,
    136                                    unsigned CommutableOpIdx2);
    137 
    138 private:
    139   /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
    140   /// set and the target hook isReallyTriviallyReMaterializable returns false,
    141   /// this function does target-independent tests to determine if the
    142   /// instruction is really trivially rematerializable.
    143   bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
    144                                                 AliasAnalysis *AA) const;
    145 
    146 public:
    147   /// These methods return the opcode of the frame setup/destroy instructions
    148   /// if they exist (-1 otherwise).  Some targets use pseudo instructions in
    149   /// order to abstract away the difference between operating with a frame
    150   /// pointer and operating without, through the use of these two instructions.
    151   ///
    152   unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
    153   unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
    154 
    155   unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
    156   unsigned getReturnOpcode() const { return ReturnOpcode; }
    157 
    158   /// Returns the actual stack pointer adjustment made by an instruction
    159   /// as part of a call sequence. By default, only call frame setup/destroy
    160   /// instructions adjust the stack, but targets may want to override this
    161   /// to enable more fine-grained adjustment, or adjust by a different value.
    162   virtual int getSPAdjust(const MachineInstr &MI) const;
    163 
    164   /// Return true if the instruction is a "coalescable" extension instruction.
    165   /// That is, it's like a copy where it's legal for the source to overlap the
    166   /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
    167   /// expected the pre-extension value is available as a subreg of the result
    168   /// register. This also returns the sub-register index in SubIdx.
    169   virtual bool isCoalescableExtInstr(const MachineInstr &MI,
    170                                      unsigned &SrcReg, unsigned &DstReg,
    171                                      unsigned &SubIdx) const {
    172     return false;
    173   }
    174 
    175   /// If the specified machine instruction is a direct
    176   /// load from a stack slot, return the virtual or physical register number of
    177   /// the destination along with the FrameIndex of the loaded stack slot.  If
    178   /// not, return 0.  This predicate must return 0 if the instruction has
    179   /// any side effects other than loading from the stack slot.
    180   virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
    181                                        int &FrameIndex) const {
    182     return 0;
    183   }
    184 
    185   /// Check for post-frame ptr elimination stack locations as well.
    186   /// This uses a heuristic so it isn't reliable for correctness.
    187   virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
    188                                              int &FrameIndex) const {
    189     return 0;
    190   }
    191 
    192   /// If the specified machine instruction has a load from a stack slot,
    193   /// return true along with the FrameIndex of the loaded stack slot and the
    194   /// machine mem operand containing the reference.
    195   /// If not, return false.  Unlike isLoadFromStackSlot, this returns true for
    196   /// any instructions that loads from the stack.  This is just a hint, as some
    197   /// cases may be missed.
    198   virtual bool hasLoadFromStackSlot(const MachineInstr &MI,
    199                                     const MachineMemOperand *&MMO,
    200                                     int &FrameIndex) const;
    201 
    202   /// If the specified machine instruction is a direct
    203   /// store to a stack slot, return the virtual or physical register number of
    204   /// the source reg along with the FrameIndex of the loaded stack slot.  If
    205   /// not, return 0.  This predicate must return 0 if the instruction has
    206   /// any side effects other than storing to the stack slot.
    207   virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
    208                                       int &FrameIndex) const {
    209     return 0;
    210   }
    211 
    212   /// Check for post-frame ptr elimination stack locations as well.
    213   /// This uses a heuristic, so it isn't reliable for correctness.
    214   virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
    215                                             int &FrameIndex) const {
    216     return 0;
    217   }
    218 
    219   /// If the specified machine instruction has a store to a stack slot,
    220   /// return true along with the FrameIndex of the loaded stack slot and the
    221   /// machine mem operand containing the reference.
    222   /// If not, return false.  Unlike isStoreToStackSlot,
    223   /// this returns true for any instructions that stores to the
    224   /// stack.  This is just a hint, as some cases may be missed.
    225   virtual bool hasStoreToStackSlot(const MachineInstr &MI,
    226                                    const MachineMemOperand *&MMO,
    227                                    int &FrameIndex) const;
    228 
    229   /// Return true if the specified machine instruction
    230   /// is a copy of one stack slot to another and has no other effect.
    231   /// Provide the identity of the two frame indices.
    232   virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
    233                                int &SrcFrameIndex) const {
    234     return false;
    235   }
    236 
    237   /// Compute the size in bytes and offset within a stack slot of a spilled
    238   /// register or subregister.
    239   ///
    240   /// \param [out] Size in bytes of the spilled value.
    241   /// \param [out] Offset in bytes within the stack slot.
    242   /// \returns true if both Size and Offset are successfully computed.
    243   ///
    244   /// Not all subregisters have computable spill slots. For example,
    245   /// subregisters registers may not be byte-sized, and a pair of discontiguous
    246   /// subregisters has no single offset.
    247   ///
    248   /// Targets with nontrivial bigendian implementations may need to override
    249   /// this, particularly to support spilled vector registers.
    250   virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
    251                                  unsigned &Size, unsigned &Offset,
    252                                  const MachineFunction &MF) const;
    253 
    254   /// Return true if the instruction is as cheap as a move instruction.
    255   ///
    256   /// Targets for different archs need to override this, and different
    257   /// micro-architectures can also be finely tuned inside.
    258   virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
    259     return MI.isAsCheapAsAMove();
    260   }
    261 
    262   /// Return true if the instruction should be sunk by MachineSink.
    263   ///
    264   /// MachineSink determines on its own whether the instruction is safe to sink;
    265   /// this gives the target a hook to override the default behavior with regards
    266   /// to which instructions should be sunk.
    267   /// The default behavior is to not sink insert_subreg, subreg_to_reg, and
    268   /// reg_sequence. These are meant to be close to the source to make it easier
    269   /// to coalesce.
    270   virtual bool shouldSink(const MachineInstr &MI) const {
    271     return !MI.isInsertSubreg() && !MI.isSubregToReg() && !MI.isRegSequence();
    272   }
    273 
    274   /// Re-issue the specified 'original' instruction at the
    275   /// specific location targeting a new destination register.
    276   /// The register in Orig->getOperand(0).getReg() will be substituted by
    277   /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
    278   /// SubIdx.
    279   virtual void reMaterialize(MachineBasicBlock &MBB,
    280                              MachineBasicBlock::iterator MI, unsigned DestReg,
    281                              unsigned SubIdx, const MachineInstr &Orig,
    282                              const TargetRegisterInfo &TRI) const;
    283 
    284   /// Create a duplicate of the Orig instruction in MF. This is like
    285   /// MachineFunction::CloneMachineInstr(), but the target may update operands
    286   /// that are required to be unique.
    287   ///
    288   /// The instruction must be duplicable as indicated by isNotDuplicable().
    289   virtual MachineInstr *duplicate(MachineInstr &Orig,
    290                                   MachineFunction &MF) const;
    291 
    292   /// This method must be implemented by targets that
    293   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
    294   /// may be able to convert a two-address instruction into one or more true
    295   /// three-address instructions on demand.  This allows the X86 target (for
    296   /// example) to convert ADD and SHL instructions into LEA instructions if they
    297   /// would require register copies due to two-addressness.
    298   ///
    299   /// This method returns a null pointer if the transformation cannot be
    300   /// performed, otherwise it returns the last new instruction.
    301   ///
    302   virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
    303                                               MachineInstr &MI,
    304                                               LiveVariables *LV) const {
    305     return nullptr;
    306   }
    307 
    308   // This constant can be used as an input value of operand index passed to
    309   // the method findCommutedOpIndices() to tell the method that the
    310   // corresponding operand index is not pre-defined and that the method
    311   // can pick any commutable operand.
    312   static const unsigned CommuteAnyOperandIndex = ~0U;
    313 
    314   /// This method commutes the operands of the given machine instruction MI.
    315   ///
    316   /// The operands to be commuted are specified by their indices OpIdx1 and
    317   /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
    318   /// 'CommuteAnyOperandIndex', which means that the method is free to choose
    319   /// any arbitrarily chosen commutable operand. If both arguments are set to
    320   /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
    321   /// operands; then commutes them if such operands could be found.
    322   ///
    323   /// If NewMI is false, MI is modified in place and returned; otherwise, a
    324   /// new machine instruction is created and returned.
    325   ///
    326   /// Do not call this method for a non-commutable instruction or
    327   /// for non-commuable operands.
    328   /// Even though the instruction is commutable, the method may still
    329   /// fail to commute the operands, null pointer is returned in such cases.
    330   MachineInstr *
    331   commuteInstruction(MachineInstr &MI, bool NewMI = false,
    332                      unsigned OpIdx1 = CommuteAnyOperandIndex,
    333                      unsigned OpIdx2 = CommuteAnyOperandIndex) const;
    334 
    335   /// Returns true iff the routine could find two commutable operands in the
    336   /// given machine instruction.
    337   /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
    338   /// If any of the INPUT values is set to the special value
    339   /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
    340   /// operand, then returns its index in the corresponding argument.
    341   /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
    342   /// looks for 2 commutable operands.
    343   /// If INPUT values refer to some operands of MI, then the method simply
    344   /// returns true if the corresponding operands are commutable and returns
    345   /// false otherwise.
    346   ///
    347   /// For example, calling this method this way:
    348   ///     unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
    349   ///     findCommutedOpIndices(MI, Op1, Op2);
    350   /// can be interpreted as a query asking to find an operand that would be
    351   /// commutable with the operand#1.
    352   virtual bool findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1,
    353                                      unsigned &SrcOpIdx2) const;
    354 
    355   /// A pair composed of a register and a sub-register index.
    356   /// Used to give some type checking when modeling Reg:SubReg.
    357   struct RegSubRegPair {
    358     unsigned Reg;
    359     unsigned SubReg;
    360     RegSubRegPair(unsigned Reg = 0, unsigned SubReg = 0)
    361         : Reg(Reg), SubReg(SubReg) {}
    362   };
    363   /// A pair composed of a pair of a register and a sub-register index,
    364   /// and another sub-register index.
    365   /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
    366   struct RegSubRegPairAndIdx : RegSubRegPair {
    367     unsigned SubIdx;
    368     RegSubRegPairAndIdx(unsigned Reg = 0, unsigned SubReg = 0,
    369                         unsigned SubIdx = 0)
    370         : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
    371   };
    372 
    373   /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
    374   /// and \p DefIdx.
    375   /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
    376   /// the list is modeled as <Reg:SubReg, SubIdx>.
    377   /// E.g., REG_SEQUENCE vreg1:sub1, sub0, vreg2, sub1 would produce
    378   /// two elements:
    379   /// - vreg1:sub1, sub0
    380   /// - vreg2<:0>, sub1
    381   ///
    382   /// \returns true if it is possible to build such an input sequence
    383   /// with the pair \p MI, \p DefIdx. False otherwise.
    384   ///
    385   /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
    386   ///
    387   /// \note The generic implementation does not provide any support for
    388   /// MI.isRegSequenceLike(). In other words, one has to override
    389   /// getRegSequenceLikeInputs for target specific instructions.
    390   bool
    391   getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
    392                        SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
    393 
    394   /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
    395   /// and \p DefIdx.
    396   /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
    397   /// E.g., EXTRACT_SUBREG vreg1:sub1, sub0, sub1 would produce:
    398   /// - vreg1:sub1, sub0
    399   ///
    400   /// \returns true if it is possible to build such an input sequence
    401   /// with the pair \p MI, \p DefIdx. False otherwise.
    402   ///
    403   /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
    404   ///
    405   /// \note The generic implementation does not provide any support for
    406   /// MI.isExtractSubregLike(). In other words, one has to override
    407   /// getExtractSubregLikeInputs for target specific instructions.
    408   bool
    409   getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
    410                          RegSubRegPairAndIdx &InputReg) const;
    411 
    412   /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
    413   /// and \p DefIdx.
    414   /// \p [out] BaseReg and \p [out] InsertedReg contain
    415   /// the equivalent inputs of INSERT_SUBREG.
    416   /// E.g., INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
    417   /// - BaseReg: vreg0:sub0
    418   /// - InsertedReg: vreg1:sub1, sub3
    419   ///
    420   /// \returns true if it is possible to build such an input sequence
    421   /// with the pair \p MI, \p DefIdx. False otherwise.
    422   ///
    423   /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
    424   ///
    425   /// \note The generic implementation does not provide any support for
    426   /// MI.isInsertSubregLike(). In other words, one has to override
    427   /// getInsertSubregLikeInputs for target specific instructions.
    428   bool
    429   getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
    430                         RegSubRegPair &BaseReg,
    431                         RegSubRegPairAndIdx &InsertedReg) const;
    432 
    433 
    434   /// Return true if two machine instructions would produce identical values.
    435   /// By default, this is only true when the two instructions
    436   /// are deemed identical except for defs. If this function is called when the
    437   /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
    438   /// aggressive checks.
    439   virtual bool produceSameValue(const MachineInstr &MI0,
    440                                 const MachineInstr &MI1,
    441                                 const MachineRegisterInfo *MRI = nullptr) const;
    442 
    443   /// Analyze the branching code at the end of MBB, returning
    444   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
    445   /// implemented for a target).  Upon success, this returns false and returns
    446   /// with the following information in various cases:
    447   ///
    448   /// 1. If this block ends with no branches (it just falls through to its succ)
    449   ///    just return false, leaving TBB/FBB null.
    450   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
    451   ///    the destination block.
    452   /// 3. If this block ends with a conditional branch and it falls through to a
    453   ///    successor block, it sets TBB to be the branch destination block and a
    454   ///    list of operands that evaluate the condition. These operands can be
    455   ///    passed to other TargetInstrInfo methods to create new branches.
    456   /// 4. If this block ends with a conditional branch followed by an
    457   ///    unconditional branch, it returns the 'true' destination in TBB, the
    458   ///    'false' destination in FBB, and a list of operands that evaluate the
    459   ///    condition.  These operands can be passed to other TargetInstrInfo
    460   ///    methods to create new branches.
    461   ///
    462   /// Note that RemoveBranch and InsertBranch must be implemented to support
    463   /// cases where this method returns success.
    464   ///
    465   /// If AllowModify is true, then this routine is allowed to modify the basic
    466   /// block (e.g. delete instructions after the unconditional branch).
    467   ///
    468   /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
    469   /// before calling this function.
    470   virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
    471                              MachineBasicBlock *&FBB,
    472                              SmallVectorImpl<MachineOperand> &Cond,
    473                              bool AllowModify = false) const {
    474     return true;
    475   }
    476 
    477   /// Represents a predicate at the MachineFunction level.  The control flow a
    478   /// MachineBranchPredicate represents is:
    479   ///
    480   ///  Reg <def>= LHS `Predicate` RHS         == ConditionDef
    481   ///  if Reg then goto TrueDest else goto FalseDest
    482   ///
    483   struct MachineBranchPredicate {
    484     enum ComparePredicate {
    485       PRED_EQ,     // True if two values are equal
    486       PRED_NE,     // True if two values are not equal
    487       PRED_INVALID // Sentinel value
    488     };
    489 
    490     ComparePredicate Predicate;
    491     MachineOperand LHS;
    492     MachineOperand RHS;
    493     MachineBasicBlock *TrueDest;
    494     MachineBasicBlock *FalseDest;
    495     MachineInstr *ConditionDef;
    496 
    497     /// SingleUseCondition is true if ConditionDef is dead except for the
    498     /// branch(es) at the end of the basic block.
    499     ///
    500     bool SingleUseCondition;
    501 
    502     explicit MachineBranchPredicate()
    503         : Predicate(PRED_INVALID), LHS(MachineOperand::CreateImm(0)),
    504           RHS(MachineOperand::CreateImm(0)), TrueDest(nullptr),
    505           FalseDest(nullptr), ConditionDef(nullptr), SingleUseCondition(false) {
    506     }
    507   };
    508 
    509   /// Analyze the branching code at the end of MBB and parse it into the
    510   /// MachineBranchPredicate structure if possible.  Returns false on success
    511   /// and true on failure.
    512   ///
    513   /// If AllowModify is true, then this routine is allowed to modify the basic
    514   /// block (e.g. delete instructions after the unconditional branch).
    515   ///
    516   virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
    517                                       MachineBranchPredicate &MBP,
    518                                       bool AllowModify = false) const {
    519     return true;
    520   }
    521 
    522   /// Remove the branching code at the end of the specific MBB.
    523   /// This is only invoked in cases where AnalyzeBranch returns success. It
    524   /// returns the number of instructions that were removed.
    525   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
    526     llvm_unreachable("Target didn't implement TargetInstrInfo::RemoveBranch!");
    527   }
    528 
    529   /// Insert branch code into the end of the specified MachineBasicBlock.
    530   /// The operands to this method are the same as those
    531   /// returned by AnalyzeBranch.  This is only invoked in cases where
    532   /// AnalyzeBranch returns success. It returns the number of instructions
    533   /// inserted.
    534   ///
    535   /// It is also invoked by tail merging to add unconditional branches in
    536   /// cases where AnalyzeBranch doesn't apply because there was no original
    537   /// branch to analyze.  At least this much must be implemented, else tail
    538   /// merging needs to be disabled.
    539   ///
    540   /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
    541   /// before calling this function.
    542   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
    543                                 MachineBasicBlock *FBB,
    544                                 ArrayRef<MachineOperand> Cond,
    545                                 const DebugLoc &DL) const {
    546     llvm_unreachable("Target didn't implement TargetInstrInfo::InsertBranch!");
    547   }
    548 
    549   /// Analyze the loop code, return true if it cannot be understoo. Upon
    550   /// success, this function returns false and returns information about the
    551   /// induction variable and compare instruction used at the end.
    552   virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
    553                            MachineInstr *&CmpInst) const {
    554     return true;
    555   }
    556 
    557   /// Generate code to reduce the loop iteration by one and check if the loop is
    558   /// finished.  Return the value/register of the the new loop count.  We need
    559   /// this function when peeling off one or more iterations of a loop. This
    560   /// function assumes the nth iteration is peeled first.
    561   virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
    562                                    MachineInstr *IndVar, MachineInstr *Cmp,
    563                                    SmallVectorImpl<MachineOperand> &Cond,
    564                                    SmallVectorImpl<MachineInstr *> &PrevInsts,
    565                                    unsigned Iter, unsigned MaxIter) const {
    566     llvm_unreachable("Target didn't implement ReduceLoopCount");
    567   }
    568 
    569   /// Delete the instruction OldInst and everything after it, replacing it with
    570   /// an unconditional branch to NewDest. This is used by the tail merging pass.
    571   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
    572                                        MachineBasicBlock *NewDest) const;
    573 
    574   /// Get an instruction that performs an unconditional branch to the given
    575   /// symbol.
    576   virtual void
    577   getUnconditionalBranch(MCInst &MI,
    578                          const MCSymbolRefExpr *BranchTarget) const {
    579     llvm_unreachable("Target didn't implement "
    580                      "TargetInstrInfo::getUnconditionalBranch!");
    581   }
    582 
    583   /// Get a machine trap instruction.
    584   virtual void getTrap(MCInst &MI) const {
    585     llvm_unreachable("Target didn't implement TargetInstrInfo::getTrap!");
    586   }
    587 
    588   /// Get a number of bytes that suffices to hold
    589   /// either the instruction returned by getUnconditionalBranch or the
    590   /// instruction returned by getTrap. This only makes sense because
    591   /// getUnconditionalBranch returns a single, specific instruction. This
    592   /// information is needed by the jumptable construction code, since it must
    593   /// decide how many bytes to use for a jumptable entry so it can generate the
    594   /// right mask.
    595   ///
    596   /// Note that if the jumptable instruction requires alignment, then that
    597   /// alignment should be factored into this required bound so that the
    598   /// resulting bound gives the right alignment for the instruction.
    599   virtual unsigned getJumpInstrTableEntryBound() const {
    600     // This method gets called by LLVMTargetMachine always, so it can't fail
    601     // just because there happens to be no implementation for this target.
    602     // Any code that tries to use a jumptable annotation without defining
    603     // getUnconditionalBranch on the appropriate Target will fail anyway, and
    604     // the value returned here won't matter in that case.
    605     return 0;
    606   }
    607 
    608   /// Return true if it's legal to split the given basic
    609   /// block at the specified instruction (i.e. instruction would be the start
    610   /// of a new basic block).
    611   virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
    612                                    MachineBasicBlock::iterator MBBI) const {
    613     return true;
    614   }
    615 
    616   /// Return true if it's profitable to predicate
    617   /// instructions with accumulated instruction latency of "NumCycles"
    618   /// of the specified basic block, where the probability of the instructions
    619   /// being executed is given by Probability, and Confidence is a measure
    620   /// of our confidence that it will be properly predicted.
    621   virtual
    622   bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
    623                            unsigned ExtraPredCycles,
    624                            BranchProbability Probability) const {
    625     return false;
    626   }
    627 
    628   /// Second variant of isProfitableToIfCvt. This one
    629   /// checks for the case where two basic blocks from true and false path
    630   /// of a if-then-else (diamond) are predicated on mutally exclusive
    631   /// predicates, where the probability of the true path being taken is given
    632   /// by Probability, and Confidence is a measure of our confidence that it
    633   /// will be properly predicted.
    634   virtual bool
    635   isProfitableToIfCvt(MachineBasicBlock &TMBB,
    636                       unsigned NumTCycles, unsigned ExtraTCycles,
    637                       MachineBasicBlock &FMBB,
    638                       unsigned NumFCycles, unsigned ExtraFCycles,
    639                       BranchProbability Probability) const {
    640     return false;
    641   }
    642 
    643   /// Return true if it's profitable for if-converter to duplicate instructions
    644   /// of specified accumulated instruction latencies in the specified MBB to
    645   /// enable if-conversion.
    646   /// The probability of the instructions being executed is given by
    647   /// Probability, and Confidence is a measure of our confidence that it
    648   /// will be properly predicted.
    649   virtual bool
    650   isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
    651                             BranchProbability Probability) const {
    652     return false;
    653   }
    654 
    655   /// Return true if it's profitable to unpredicate
    656   /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
    657   /// exclusive predicates.
    658   /// e.g.
    659   ///   subeq  r0, r1, #1
    660   ///   addne  r0, r1, #1
    661   /// =>
    662   ///   sub    r0, r1, #1
    663   ///   addne  r0, r1, #1
    664   ///
    665   /// This may be profitable is conditional instructions are always executed.
    666   virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
    667                                          MachineBasicBlock &FMBB) const {
    668     return false;
    669   }
    670 
    671   /// Return true if it is possible to insert a select
    672   /// instruction that chooses between TrueReg and FalseReg based on the
    673   /// condition code in Cond.
    674   ///
    675   /// When successful, also return the latency in cycles from TrueReg,
    676   /// FalseReg, and Cond to the destination register. In most cases, a select
    677   /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
    678   ///
    679   /// Some x86 implementations have 2-cycle cmov instructions.
    680   ///
    681   /// @param MBB         Block where select instruction would be inserted.
    682   /// @param Cond        Condition returned by AnalyzeBranch.
    683   /// @param TrueReg     Virtual register to select when Cond is true.
    684   /// @param FalseReg    Virtual register to select when Cond is false.
    685   /// @param CondCycles  Latency from Cond+Branch to select output.
    686   /// @param TrueCycles  Latency from TrueReg to select output.
    687   /// @param FalseCycles Latency from FalseReg to select output.
    688   virtual bool canInsertSelect(const MachineBasicBlock &MBB,
    689                                ArrayRef<MachineOperand> Cond,
    690                                unsigned TrueReg, unsigned FalseReg,
    691                                int &CondCycles,
    692                                int &TrueCycles, int &FalseCycles) const {
    693     return false;
    694   }
    695 
    696   /// Insert a select instruction into MBB before I that will copy TrueReg to
    697   /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
    698   ///
    699   /// This function can only be called after canInsertSelect() returned true.
    700   /// The condition in Cond comes from AnalyzeBranch, and it can be assumed
    701   /// that the same flags or registers required by Cond are available at the
    702   /// insertion point.
    703   ///
    704   /// @param MBB      Block where select instruction should be inserted.
    705   /// @param I        Insertion point.
    706   /// @param DL       Source location for debugging.
    707   /// @param DstReg   Virtual register to be defined by select instruction.
    708   /// @param Cond     Condition as computed by AnalyzeBranch.
    709   /// @param TrueReg  Virtual register to copy when Cond is true.
    710   /// @param FalseReg Virtual register to copy when Cons is false.
    711   virtual void insertSelect(MachineBasicBlock &MBB,
    712                             MachineBasicBlock::iterator I, const DebugLoc &DL,
    713                             unsigned DstReg, ArrayRef<MachineOperand> Cond,
    714                             unsigned TrueReg, unsigned FalseReg) const {
    715     llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
    716   }
    717 
    718   /// Analyze the given select instruction, returning true if
    719   /// it cannot be understood. It is assumed that MI->isSelect() is true.
    720   ///
    721   /// When successful, return the controlling condition and the operands that
    722   /// determine the true and false result values.
    723   ///
    724   ///   Result = SELECT Cond, TrueOp, FalseOp
    725   ///
    726   /// Some targets can optimize select instructions, for example by predicating
    727   /// the instruction defining one of the operands. Such targets should set
    728   /// Optimizable.
    729   ///
    730   /// @param         MI Select instruction to analyze.
    731   /// @param Cond    Condition controlling the select.
    732   /// @param TrueOp  Operand number of the value selected when Cond is true.
    733   /// @param FalseOp Operand number of the value selected when Cond is false.
    734   /// @param Optimizable Returned as true if MI is optimizable.
    735   /// @returns False on success.
    736   virtual bool analyzeSelect(const MachineInstr &MI,
    737                              SmallVectorImpl<MachineOperand> &Cond,
    738                              unsigned &TrueOp, unsigned &FalseOp,
    739                              bool &Optimizable) const {
    740     assert(MI.getDesc().isSelect() && "MI must be a select instruction");
    741     return true;
    742   }
    743 
    744   /// Given a select instruction that was understood by
    745   /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
    746   /// merging it with one of its operands. Returns NULL on failure.
    747   ///
    748   /// When successful, returns the new select instruction. The client is
    749   /// responsible for deleting MI.
    750   ///
    751   /// If both sides of the select can be optimized, PreferFalse is used to pick
    752   /// a side.
    753   ///
    754   /// @param MI          Optimizable select instruction.
    755   /// @param NewMIs     Set that record all MIs in the basic block up to \p
    756   /// MI. Has to be updated with any newly created MI or deleted ones.
    757   /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
    758   /// @returns Optimized instruction or NULL.
    759   virtual MachineInstr *optimizeSelect(MachineInstr &MI,
    760                                        SmallPtrSetImpl<MachineInstr *> &NewMIs,
    761                                        bool PreferFalse = false) const {
    762     // This function must be implemented if Optimizable is ever set.
    763     llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
    764   }
    765 
    766   /// Emit instructions to copy a pair of physical registers.
    767   ///
    768   /// This function should support copies within any legal register class as
    769   /// well as any cross-class copies created during instruction selection.
    770   ///
    771   /// The source and destination registers may overlap, which may require a
    772   /// careful implementation when multiple copy instructions are required for
    773   /// large registers. See for example the ARM target.
    774   virtual void copyPhysReg(MachineBasicBlock &MBB,
    775                            MachineBasicBlock::iterator MI, const DebugLoc &DL,
    776                            unsigned DestReg, unsigned SrcReg,
    777                            bool KillSrc) const {
    778     llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
    779   }
    780 
    781   /// Store the specified register of the given register class to the specified
    782   /// stack frame index. The store instruction is to be added to the given
    783   /// machine basic block before the specified machine instruction. If isKill
    784   /// is true, the register operand is the last use and must be marked kill.
    785   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
    786                                    MachineBasicBlock::iterator MI,
    787                                    unsigned SrcReg, bool isKill, int FrameIndex,
    788                                    const TargetRegisterClass *RC,
    789                                    const TargetRegisterInfo *TRI) const {
    790     llvm_unreachable("Target didn't implement "
    791                      "TargetInstrInfo::storeRegToStackSlot!");
    792   }
    793 
    794   /// Load the specified register of the given register class from the specified
    795   /// stack frame index. The load instruction is to be added to the given
    796   /// machine basic block before the specified machine instruction.
    797   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
    798                                     MachineBasicBlock::iterator MI,
    799                                     unsigned DestReg, int FrameIndex,
    800                                     const TargetRegisterClass *RC,
    801                                     const TargetRegisterInfo *TRI) const {
    802     llvm_unreachable("Target didn't implement "
    803                      "TargetInstrInfo::loadRegFromStackSlot!");
    804   }
    805 
    806   /// This function is called for all pseudo instructions
    807   /// that remain after register allocation. Many pseudo instructions are
    808   /// created to help register allocation. This is the place to convert them
    809   /// into real instructions. The target can edit MI in place, or it can insert
    810   /// new instructions and erase MI. The function should return true if
    811   /// anything was changed.
    812   virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
    813 
    814   /// Attempt to fold a load or store of the specified stack
    815   /// slot into the specified machine instruction for the specified operand(s).
    816   /// If this is possible, a new instruction is returned with the specified
    817   /// operand folded, otherwise NULL is returned.
    818   /// The new instruction is inserted before MI, and the client is responsible
    819   /// for removing the old instruction.
    820   MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
    821                                   int FrameIndex,
    822                                   LiveIntervals *LIS = nullptr) const;
    823 
    824   /// Same as the previous version except it allows folding of any load and
    825   /// store from / to any address, not just from a specific stack slot.
    826   MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
    827                                   MachineInstr &LoadMI,
    828                                   LiveIntervals *LIS = nullptr) const;
    829 
    830   /// Return true when there is potentially a faster code sequence
    831   /// for an instruction chain ending in \p Root. All potential patterns are
    832   /// returned in the \p Pattern vector. Pattern should be sorted in priority
    833   /// order since the pattern evaluator stops checking as soon as it finds a
    834   /// faster sequence.
    835   /// \param Root - Instruction that could be combined with one of its operands
    836   /// \param Patterns - Vector of possible combination patterns
    837   virtual bool getMachineCombinerPatterns(
    838       MachineInstr &Root,
    839       SmallVectorImpl<MachineCombinerPattern> &Patterns) const;
    840 
    841   /// Return true when a code sequence can improve throughput. It
    842   /// should be called only for instructions in loops.
    843   /// \param Pattern - combiner pattern
    844   virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
    845 
    846   /// Return true if the input \P Inst is part of a chain of dependent ops
    847   /// that are suitable for reassociation, otherwise return false.
    848   /// If the instruction's operands must be commuted to have a previous
    849   /// instruction of the same type define the first source operand, \P Commuted
    850   /// will be set to true.
    851   bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
    852 
    853   /// Return true when \P Inst is both associative and commutative.
    854   virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
    855     return false;
    856   }
    857 
    858   /// Return true when \P Inst has reassociable operands in the same \P MBB.
    859   virtual bool hasReassociableOperands(const MachineInstr &Inst,
    860                                        const MachineBasicBlock *MBB) const;
    861 
    862   /// Return true when \P Inst has reassociable sibling.
    863   bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
    864 
    865   /// When getMachineCombinerPatterns() finds patterns, this function generates
    866   /// the instructions that could replace the original code sequence. The client
    867   /// has to decide whether the actual replacement is beneficial or not.
    868   /// \param Root - Instruction that could be combined with one of its operands
    869   /// \param Pattern - Combination pattern for Root
    870   /// \param InsInstrs - Vector of new instructions that implement P
    871   /// \param DelInstrs - Old instructions, including Root, that could be
    872   /// replaced by InsInstr
    873   /// \param InstrIdxForVirtReg - map of virtual register to instruction in
    874   /// InsInstr that defines it
    875   virtual void genAlternativeCodeSequence(
    876       MachineInstr &Root, MachineCombinerPattern Pattern,
    877       SmallVectorImpl<MachineInstr *> &InsInstrs,
    878       SmallVectorImpl<MachineInstr *> &DelInstrs,
    879       DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
    880 
    881   /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
    882   /// reduce critical path length.
    883   void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
    884                       MachineCombinerPattern Pattern,
    885                       SmallVectorImpl<MachineInstr *> &InsInstrs,
    886                       SmallVectorImpl<MachineInstr *> &DelInstrs,
    887                       DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
    888 
    889   /// This is an architecture-specific helper function of reassociateOps.
    890   /// Set special operand attributes for new instructions after reassociation.
    891   virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
    892                                      MachineInstr &NewMI1,
    893                                      MachineInstr &NewMI2) const {
    894   }
    895 
    896   /// Return true when a target supports MachineCombiner.
    897   virtual bool useMachineCombiner() const { return false; }
    898 
    899 protected:
    900   /// Target-dependent implementation for foldMemoryOperand.
    901   /// Target-independent code in foldMemoryOperand will
    902   /// take care of adding a MachineMemOperand to the newly created instruction.
    903   /// The instruction and any auxiliary instructions necessary will be inserted
    904   /// at InsertPt.
    905   virtual MachineInstr *
    906   foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
    907                         ArrayRef<unsigned> Ops,
    908                         MachineBasicBlock::iterator InsertPt, int FrameIndex,
    909                         LiveIntervals *LIS = nullptr) const {
    910     return nullptr;
    911   }
    912 
    913   /// Target-dependent implementation for foldMemoryOperand.
    914   /// Target-independent code in foldMemoryOperand will
    915   /// take care of adding a MachineMemOperand to the newly created instruction.
    916   /// The instruction and any auxiliary instructions necessary will be inserted
    917   /// at InsertPt.
    918   virtual MachineInstr *foldMemoryOperandImpl(
    919       MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
    920       MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
    921       LiveIntervals *LIS = nullptr) const {
    922     return nullptr;
    923   }
    924 
    925   /// \brief Target-dependent implementation of getRegSequenceInputs.
    926   ///
    927   /// \returns true if it is possible to build the equivalent
    928   /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
    929   ///
    930   /// \pre MI.isRegSequenceLike().
    931   ///
    932   /// \see TargetInstrInfo::getRegSequenceInputs.
    933   virtual bool getRegSequenceLikeInputs(
    934       const MachineInstr &MI, unsigned DefIdx,
    935       SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
    936     return false;
    937   }
    938 
    939   /// \brief Target-dependent implementation of getExtractSubregInputs.
    940   ///
    941   /// \returns true if it is possible to build the equivalent
    942   /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
    943   ///
    944   /// \pre MI.isExtractSubregLike().
    945   ///
    946   /// \see TargetInstrInfo::getExtractSubregInputs.
    947   virtual bool getExtractSubregLikeInputs(
    948       const MachineInstr &MI, unsigned DefIdx,
    949       RegSubRegPairAndIdx &InputReg) const {
    950     return false;
    951   }
    952 
    953   /// \brief Target-dependent implementation of getInsertSubregInputs.
    954   ///
    955   /// \returns true if it is possible to build the equivalent
    956   /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
    957   ///
    958   /// \pre MI.isInsertSubregLike().
    959   ///
    960   /// \see TargetInstrInfo::getInsertSubregInputs.
    961   virtual bool
    962   getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
    963                             RegSubRegPair &BaseReg,
    964                             RegSubRegPairAndIdx &InsertedReg) const {
    965     return false;
    966   }
    967 
    968 public:
    969   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
    970   /// a store or a load and a store into two or more instruction. If this is
    971   /// possible, returns true as well as the new instructions by reference.
    972   virtual bool
    973   unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
    974                       bool UnfoldLoad, bool UnfoldStore,
    975                       SmallVectorImpl<MachineInstr *> &NewMIs) const {
    976     return false;
    977   }
    978 
    979   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
    980                                    SmallVectorImpl<SDNode*> &NewNodes) const {
    981     return false;
    982   }
    983 
    984   /// Returns the opcode of the would be new
    985   /// instruction after load / store are unfolded from an instruction of the
    986   /// specified opcode. It returns zero if the specified unfolding is not
    987   /// possible. If LoadRegIndex is non-null, it is filled in with the operand
    988   /// index of the operand which will hold the register holding the loaded
    989   /// value.
    990   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
    991                                       bool UnfoldLoad, bool UnfoldStore,
    992                                       unsigned *LoadRegIndex = nullptr) const {
    993     return 0;
    994   }
    995 
    996   /// This is used by the pre-regalloc scheduler to determine if two loads are
    997   /// loading from the same base address. It should only return true if the base
    998   /// pointers are the same and the only differences between the two addresses
    999   /// are the offset. It also returns the offsets by reference.
   1000   virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
   1001                                     int64_t &Offset1, int64_t &Offset2) const {
   1002     return false;
   1003   }
   1004 
   1005   /// This is a used by the pre-regalloc scheduler to determine (in conjunction
   1006   /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
   1007   /// On some targets if two loads are loading from
   1008   /// addresses in the same cache line, it's better if they are scheduled
   1009   /// together. This function takes two integers that represent the load offsets
   1010   /// from the common base address. It returns true if it decides it's desirable
   1011   /// to schedule the two loads together. "NumLoads" is the number of loads that
   1012   /// have already been scheduled after Load1.
   1013   virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
   1014                                        int64_t Offset1, int64_t Offset2,
   1015                                        unsigned NumLoads) const {
   1016     return false;
   1017   }
   1018 
   1019   /// Get the base register and byte offset of an instruction that reads/writes
   1020   /// memory.
   1021   virtual bool getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg,
   1022                                      int64_t &Offset,
   1023                                      const TargetRegisterInfo *TRI) const {
   1024     return false;
   1025   }
   1026 
   1027   /// Return true if the instruction contains a base register and offset. If
   1028   /// true, the function also sets the operand position in the instruction
   1029   /// for the base register and offset.
   1030   virtual bool getBaseAndOffsetPosition(const MachineInstr *MI,
   1031                                         unsigned &BasePos,
   1032                                         unsigned &OffsetPos) const {
   1033     return false;
   1034   }
   1035 
   1036   /// If the instruction is an increment of a constant value, return the amount.
   1037   virtual bool getIncrementValue(const MachineInstr *MI, int &Value) const {
   1038     return false;
   1039   }
   1040 
   1041   virtual bool enableClusterLoads() const { return false; }
   1042 
   1043   virtual bool enableClusterStores() const { return false; }
   1044 
   1045   virtual bool shouldClusterMemOps(MachineInstr &FirstLdSt,
   1046                                    MachineInstr &SecondLdSt,
   1047                                    unsigned NumLoads) const {
   1048     return false;
   1049   }
   1050 
   1051   /// Can this target fuse the given instructions if they are scheduled
   1052   /// adjacent.
   1053   virtual bool shouldScheduleAdjacent(MachineInstr &First,
   1054                                       MachineInstr &Second) const {
   1055     return false;
   1056   }
   1057 
   1058   /// Reverses the branch condition of the specified condition list,
   1059   /// returning false on success and true if it cannot be reversed.
   1060   virtual
   1061   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
   1062     return true;
   1063   }
   1064 
   1065   /// Insert a noop into the instruction stream at the specified point.
   1066   virtual void insertNoop(MachineBasicBlock &MBB,
   1067                           MachineBasicBlock::iterator MI) const;
   1068 
   1069 
   1070   /// Return the noop instruction to use for a noop.
   1071   virtual void getNoopForMachoTarget(MCInst &NopInst) const;
   1072 
   1073   /// Return true for post-incremented instructions.
   1074   virtual bool isPostIncrement(const MachineInstr* MI) const {
   1075     return false;
   1076   }
   1077 
   1078   /// Returns true if the instruction is already predicated.
   1079   virtual bool isPredicated(const MachineInstr &MI) const {
   1080     return false;
   1081   }
   1082 
   1083   /// Returns true if the instruction is a
   1084   /// terminator instruction that has not been predicated.
   1085   virtual bool isUnpredicatedTerminator(const MachineInstr &MI) const;
   1086 
   1087   /// Convert the instruction into a predicated instruction.
   1088   /// It returns true if the operation was successful.
   1089   virtual bool PredicateInstruction(MachineInstr &MI,
   1090                                     ArrayRef<MachineOperand> Pred) const;
   1091 
   1092   /// Returns true if the first specified predicate
   1093   /// subsumes the second, e.g. GE subsumes GT.
   1094   virtual
   1095   bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
   1096                          ArrayRef<MachineOperand> Pred2) const {
   1097     return false;
   1098   }
   1099 
   1100   /// If the specified instruction defines any predicate
   1101   /// or condition code register(s) used for predication, returns true as well
   1102   /// as the definition predicate(s) by reference.
   1103   virtual bool DefinesPredicate(MachineInstr &MI,
   1104                                 std::vector<MachineOperand> &Pred) const {
   1105     return false;
   1106   }
   1107 
   1108   /// Return true if the specified instruction can be predicated.
   1109   /// By default, this returns true for every instruction with a
   1110   /// PredicateOperand.
   1111   virtual bool isPredicable(MachineInstr &MI) const {
   1112     return MI.getDesc().isPredicable();
   1113   }
   1114 
   1115   /// Return true if it's safe to move a machine
   1116   /// instruction that defines the specified register class.
   1117   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
   1118     return true;
   1119   }
   1120 
   1121   /// Test if the given instruction should be considered a scheduling boundary.
   1122   /// This primarily includes labels and terminators.
   1123   virtual bool isSchedulingBoundary(const MachineInstr &MI,
   1124                                     const MachineBasicBlock *MBB,
   1125                                     const MachineFunction &MF) const;
   1126 
   1127   /// Measure the specified inline asm to determine an approximation of its
   1128   /// length.
   1129   virtual unsigned getInlineAsmLength(const char *Str,
   1130                                       const MCAsmInfo &MAI) const;
   1131 
   1132   /// Allocate and return a hazard recognizer to use for this target when
   1133   /// scheduling the machine instructions before register allocation.
   1134   virtual ScheduleHazardRecognizer*
   1135   CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
   1136                                const ScheduleDAG *DAG) const;
   1137 
   1138   /// Allocate and return a hazard recognizer to use for this target when
   1139   /// scheduling the machine instructions before register allocation.
   1140   virtual ScheduleHazardRecognizer*
   1141   CreateTargetMIHazardRecognizer(const InstrItineraryData*,
   1142                                  const ScheduleDAG *DAG) const;
   1143 
   1144   /// Allocate and return a hazard recognizer to use for this target when
   1145   /// scheduling the machine instructions after register allocation.
   1146   virtual ScheduleHazardRecognizer*
   1147   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
   1148                                      const ScheduleDAG *DAG) const;
   1149 
   1150   /// Allocate and return a hazard recognizer to use for by non-scheduling
   1151   /// passes.
   1152   virtual ScheduleHazardRecognizer*
   1153   CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
   1154     return nullptr;
   1155   }
   1156 
   1157   /// Provide a global flag for disabling the PreRA hazard recognizer that
   1158   /// targets may choose to honor.
   1159   bool usePreRAHazardRecognizer() const;
   1160 
   1161   /// For a comparison instruction, return the source registers
   1162   /// in SrcReg and SrcReg2 if having two register operands, and the value it
   1163   /// compares against in CmpValue. Return true if the comparison instruction
   1164   /// can be analyzed.
   1165   virtual bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
   1166                               unsigned &SrcReg2, int &Mask, int &Value) const {
   1167     return false;
   1168   }
   1169 
   1170   /// See if the comparison instruction can be converted
   1171   /// into something more efficient. E.g., on ARM most instructions can set the
   1172   /// flags register, obviating the need for a separate CMP.
   1173   virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
   1174                                     unsigned SrcReg2, int Mask, int Value,
   1175                                     const MachineRegisterInfo *MRI) const {
   1176     return false;
   1177   }
   1178   virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
   1179 
   1180   /// Try to remove the load by folding it to a register operand at the use.
   1181   /// We fold the load instructions if and only if the
   1182   /// def and use are in the same BB. We only look at one load and see
   1183   /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
   1184   /// defined by the load we are trying to fold. DefMI returns the machine
   1185   /// instruction that defines FoldAsLoadDefReg, and the function returns
   1186   /// the machine instruction generated due to folding.
   1187   virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
   1188                                           const MachineRegisterInfo *MRI,
   1189                                           unsigned &FoldAsLoadDefReg,
   1190                                           MachineInstr *&DefMI) const {
   1191     return nullptr;
   1192   }
   1193 
   1194   /// 'Reg' is known to be defined by a move immediate instruction,
   1195   /// try to fold the immediate into the use instruction.
   1196   /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
   1197   /// then the caller may assume that DefMI has been erased from its parent
   1198   /// block. The caller may assume that it will not be erased by this
   1199   /// function otherwise.
   1200   virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
   1201                              unsigned Reg, MachineRegisterInfo *MRI) const {
   1202     return false;
   1203   }
   1204 
   1205   /// Return the number of u-operations the given machine
   1206   /// instruction will be decoded to on the target cpu. The itinerary's
   1207   /// IssueWidth is the number of microops that can be dispatched each
   1208   /// cycle. An instruction with zero microops takes no dispatch resources.
   1209   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
   1210                                   const MachineInstr &MI) const;
   1211 
   1212   /// Return true for pseudo instructions that don't consume any
   1213   /// machine resources in their current form. These are common cases that the
   1214   /// scheduler should consider free, rather than conservatively handling them
   1215   /// as instructions with no itinerary.
   1216   bool isZeroCost(unsigned Opcode) const {
   1217     return Opcode <= TargetOpcode::COPY;
   1218   }
   1219 
   1220   virtual int getOperandLatency(const InstrItineraryData *ItinData,
   1221                                 SDNode *DefNode, unsigned DefIdx,
   1222                                 SDNode *UseNode, unsigned UseIdx) const;
   1223 
   1224   /// Compute and return the use operand latency of a given pair of def and use.
   1225   /// In most cases, the static scheduling itinerary was enough to determine the
   1226   /// operand latency. But it may not be possible for instructions with variable
   1227   /// number of defs / uses.
   1228   ///
   1229   /// This is a raw interface to the itinerary that may be directly overridden
   1230   /// by a target. Use computeOperandLatency to get the best estimate of
   1231   /// latency.
   1232   virtual int getOperandLatency(const InstrItineraryData *ItinData,
   1233                                 const MachineInstr &DefMI, unsigned DefIdx,
   1234                                 const MachineInstr &UseMI,
   1235                                 unsigned UseIdx) const;
   1236 
   1237   /// Compute and return the latency of the given data dependent def and use
   1238   /// when the operand indices are already known. UseMI may be \c nullptr for
   1239   /// an unknown use.
   1240   ///
   1241   /// FindMin may be set to get the minimum vs. expected latency. Minimum
   1242   /// latency is used for scheduling groups, while expected latency is for
   1243   /// instruction cost and critical path.
   1244   ///
   1245   /// Depending on the subtarget's itinerary properties, this may or may not
   1246   /// need to call getOperandLatency(). For most subtargets, we don't need
   1247   /// DefIdx or UseIdx to compute min latency.
   1248   unsigned computeOperandLatency(const InstrItineraryData *ItinData,
   1249                                  const MachineInstr &DefMI, unsigned DefIdx,
   1250                                  const MachineInstr *UseMI,
   1251                                  unsigned UseIdx) const;
   1252 
   1253   /// Compute the instruction latency of a given instruction.
   1254   /// If the instruction has higher cost when predicated, it's returned via
   1255   /// PredCost.
   1256   virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
   1257                                    const MachineInstr &MI,
   1258                                    unsigned *PredCost = nullptr) const;
   1259 
   1260   virtual unsigned getPredicationCost(const MachineInstr &MI) const;
   1261 
   1262   virtual int getInstrLatency(const InstrItineraryData *ItinData,
   1263                               SDNode *Node) const;
   1264 
   1265   /// Return the default expected latency for a def based on its opcode.
   1266   unsigned defaultDefLatency(const MCSchedModel &SchedModel,
   1267                              const MachineInstr &DefMI) const;
   1268 
   1269   int computeDefOperandLatency(const InstrItineraryData *ItinData,
   1270                                const MachineInstr &DefMI) const;
   1271 
   1272   /// Return true if this opcode has high latency to its result.
   1273   virtual bool isHighLatencyDef(int opc) const { return false; }
   1274 
   1275   /// Compute operand latency between a def of 'Reg'
   1276   /// and a use in the current loop. Return true if the target considered
   1277   /// it 'high'. This is used by optimization passes such as machine LICM to
   1278   /// determine whether it makes sense to hoist an instruction out even in a
   1279   /// high register pressure situation.
   1280   virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
   1281                                      const MachineRegisterInfo *MRI,
   1282                                      const MachineInstr &DefMI, unsigned DefIdx,
   1283                                      const MachineInstr &UseMI,
   1284                                      unsigned UseIdx) const {
   1285     return false;
   1286   }
   1287 
   1288   /// Compute operand latency of a def of 'Reg'. Return true
   1289   /// if the target considered it 'low'.
   1290   virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
   1291                                 const MachineInstr &DefMI,
   1292                                 unsigned DefIdx) const;
   1293 
   1294   /// Perform target-specific instruction verification.
   1295   virtual bool verifyInstruction(const MachineInstr &MI,
   1296                                  StringRef &ErrInfo) const {
   1297     return true;
   1298   }
   1299 
   1300   /// Return the current execution domain and bit mask of
   1301   /// possible domains for instruction.
   1302   ///
   1303   /// Some micro-architectures have multiple execution domains, and multiple
   1304   /// opcodes that perform the same operation in different domains.  For
   1305   /// example, the x86 architecture provides the por, orps, and orpd
   1306   /// instructions that all do the same thing.  There is a latency penalty if a
   1307   /// register is written in one domain and read in another.
   1308   ///
   1309   /// This function returns a pair (domain, mask) containing the execution
   1310   /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
   1311   /// function can be used to change the opcode to one of the domains in the
   1312   /// bit mask.  Instructions whose execution domain can't be changed should
   1313   /// return a 0 mask.
   1314   ///
   1315   /// The execution domain numbers don't have any special meaning except domain
   1316   /// 0 is used for instructions that are not associated with any interesting
   1317   /// execution domain.
   1318   ///
   1319   virtual std::pair<uint16_t, uint16_t>
   1320   getExecutionDomain(const MachineInstr &MI) const {
   1321     return std::make_pair(0, 0);
   1322   }
   1323 
   1324   /// Change the opcode of MI to execute in Domain.
   1325   ///
   1326   /// The bit (1 << Domain) must be set in the mask returned from
   1327   /// getExecutionDomain(MI).
   1328   virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
   1329 
   1330   /// Returns the preferred minimum clearance
   1331   /// before an instruction with an unwanted partial register update.
   1332   ///
   1333   /// Some instructions only write part of a register, and implicitly need to
   1334   /// read the other parts of the register.  This may cause unwanted stalls
   1335   /// preventing otherwise unrelated instructions from executing in parallel in
   1336   /// an out-of-order CPU.
   1337   ///
   1338   /// For example, the x86 instruction cvtsi2ss writes its result to bits
   1339   /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
   1340   /// the instruction needs to wait for the old value of the register to become
   1341   /// available:
   1342   ///
   1343   ///   addps %xmm1, %xmm0
   1344   ///   movaps %xmm0, (%rax)
   1345   ///   cvtsi2ss %rbx, %xmm0
   1346   ///
   1347   /// In the code above, the cvtsi2ss instruction needs to wait for the addps
   1348   /// instruction before it can issue, even though the high bits of %xmm0
   1349   /// probably aren't needed.
   1350   ///
   1351   /// This hook returns the preferred clearance before MI, measured in
   1352   /// instructions.  Other defs of MI's operand OpNum are avoided in the last N
   1353   /// instructions before MI.  It should only return a positive value for
   1354   /// unwanted dependencies.  If the old bits of the defined register have
   1355   /// useful values, or if MI is determined to otherwise read the dependency,
   1356   /// the hook should return 0.
   1357   ///
   1358   /// The unwanted dependency may be handled by:
   1359   ///
   1360   /// 1. Allocating the same register for an MI def and use.  That makes the
   1361   ///    unwanted dependency identical to a required dependency.
   1362   ///
   1363   /// 2. Allocating a register for the def that has no defs in the previous N
   1364   ///    instructions.
   1365   ///
   1366   /// 3. Calling breakPartialRegDependency() with the same arguments.  This
   1367   ///    allows the target to insert a dependency breaking instruction.
   1368   ///
   1369   virtual unsigned
   1370   getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
   1371                                const TargetRegisterInfo *TRI) const {
   1372     // The default implementation returns 0 for no partial register dependency.
   1373     return 0;
   1374   }
   1375 
   1376   /// \brief Return the minimum clearance before an instruction that reads an
   1377   /// unused register.
   1378   ///
   1379   /// For example, AVX instructions may copy part of a register operand into
   1380   /// the unused high bits of the destination register.
   1381   ///
   1382   /// vcvtsi2sdq %rax, %xmm0<undef>, %xmm14
   1383   ///
   1384   /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
   1385   /// false dependence on any previous write to %xmm0.
   1386   ///
   1387   /// This hook works similarly to getPartialRegUpdateClearance, except that it
   1388   /// does not take an operand index. Instead sets \p OpNum to the index of the
   1389   /// unused register.
   1390   virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned &OpNum,
   1391                                         const TargetRegisterInfo *TRI) const {
   1392     // The default implementation returns 0 for no undef register dependency.
   1393     return 0;
   1394   }
   1395 
   1396   /// Insert a dependency-breaking instruction
   1397   /// before MI to eliminate an unwanted dependency on OpNum.
   1398   ///
   1399   /// If it wasn't possible to avoid a def in the last N instructions before MI
   1400   /// (see getPartialRegUpdateClearance), this hook will be called to break the
   1401   /// unwanted dependency.
   1402   ///
   1403   /// On x86, an xorps instruction can be used as a dependency breaker:
   1404   ///
   1405   ///   addps %xmm1, %xmm0
   1406   ///   movaps %xmm0, (%rax)
   1407   ///   xorps %xmm0, %xmm0
   1408   ///   cvtsi2ss %rbx, %xmm0
   1409   ///
   1410   /// An <imp-kill> operand should be added to MI if an instruction was
   1411   /// inserted.  This ties the instructions together in the post-ra scheduler.
   1412   ///
   1413   virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
   1414                                          const TargetRegisterInfo *TRI) const {}
   1415 
   1416   /// Create machine specific model for scheduling.
   1417   virtual DFAPacketizer *
   1418   CreateTargetScheduleState(const TargetSubtargetInfo &) const {
   1419     return nullptr;
   1420   }
   1421 
   1422   // Sometimes, it is possible for the target
   1423   // to tell, even without aliasing information, that two MIs access different
   1424   // memory addresses. This function returns true if two MIs access different
   1425   // memory addresses and false otherwise.
   1426   virtual bool
   1427   areMemAccessesTriviallyDisjoint(MachineInstr &MIa, MachineInstr &MIb,
   1428                                   AliasAnalysis *AA = nullptr) const {
   1429     assert((MIa.mayLoad() || MIa.mayStore()) &&
   1430            "MIa must load from or modify a memory location");
   1431     assert((MIb.mayLoad() || MIb.mayStore()) &&
   1432            "MIb must load from or modify a memory location");
   1433     return false;
   1434   }
   1435 
   1436   /// \brief Return the value to use for the MachineCSE's LookAheadLimit,
   1437   /// which is a heuristic used for CSE'ing phys reg defs.
   1438   virtual unsigned getMachineCSELookAheadLimit () const {
   1439     // The default lookahead is small to prevent unprofitable quadratic
   1440     // behavior.
   1441     return 5;
   1442   }
   1443 
   1444   /// Return an array that contains the ids of the target indices (used for the
   1445   /// TargetIndex machine operand) and their names.
   1446   ///
   1447   /// MIR Serialization is able to serialize only the target indices that are
   1448   /// defined by this method.
   1449   virtual ArrayRef<std::pair<int, const char *>>
   1450   getSerializableTargetIndices() const {
   1451     return None;
   1452   }
   1453 
   1454   /// Decompose the machine operand's target flags into two values - the direct
   1455   /// target flag value and any of bit flags that are applied.
   1456   virtual std::pair<unsigned, unsigned>
   1457   decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
   1458     return std::make_pair(0u, 0u);
   1459   }
   1460 
   1461   /// Return an array that contains the direct target flag values and their
   1462   /// names.
   1463   ///
   1464   /// MIR Serialization is able to serialize only the target flags that are
   1465   /// defined by this method.
   1466   virtual ArrayRef<std::pair<unsigned, const char *>>
   1467   getSerializableDirectMachineOperandTargetFlags() const {
   1468     return None;
   1469   }
   1470 
   1471   /// Return an array that contains the bitmask target flag values and their
   1472   /// names.
   1473   ///
   1474   /// MIR Serialization is able to serialize only the target flags that are
   1475   /// defined by this method.
   1476   virtual ArrayRef<std::pair<unsigned, const char *>>
   1477   getSerializableBitmaskMachineOperandTargetFlags() const {
   1478     return None;
   1479   }
   1480 
   1481 private:
   1482   unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
   1483   unsigned CatchRetOpcode;
   1484   unsigned ReturnOpcode;
   1485 };
   1486 
   1487 /// \brief Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
   1488 template<>
   1489 struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
   1490   typedef DenseMapInfo<unsigned> RegInfo;
   1491 
   1492   static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
   1493     return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
   1494                          RegInfo::getEmptyKey());
   1495   }
   1496   static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
   1497     return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
   1498                          RegInfo::getTombstoneKey());
   1499   }
   1500   /// \brief Reuse getHashValue implementation from
   1501   /// std::pair<unsigned, unsigned>.
   1502   static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
   1503     std::pair<unsigned, unsigned> PairVal =
   1504         std::make_pair(Val.Reg, Val.SubReg);
   1505     return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
   1506   }
   1507   static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
   1508                       const TargetInstrInfo::RegSubRegPair &RHS) {
   1509     return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
   1510            RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
   1511   }
   1512 };
   1513 
   1514 } // end namespace llvm
   1515 
   1516 #endif // LLVM_TARGET_TARGETINSTRINFO_H
   1517