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