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