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