Add isInsertSubreg property.
[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/DFAPacketizer.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineCombinerPattern.h"
22 #include "llvm/MC/MCInstrInfo.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 class MCSchedModel;
35 class MCSymbolRefExpr;
36 class SDNode;
37 class ScheduleHazardRecognizer;
38 class SelectionDAG;
39 class ScheduleDAG;
40 class TargetRegisterClass;
41 class TargetRegisterInfo;
42 class BranchProbability;
43 class TargetSubtargetInfo;
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(void) 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   /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
851   virtual void getNoopForMachoTarget(MCInst &NopInst) const {
852     // Default to just using 'nop' string.
853   }
854
855
856   /// isPredicated - Returns true if the instruction is already predicated.
857   ///
858   virtual bool isPredicated(const MachineInstr *MI) const {
859     return false;
860   }
861
862   /// isUnpredicatedTerminator - Returns true if the instruction is a
863   /// terminator instruction that has not been predicated.
864   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
865
866   /// PredicateInstruction - Convert the instruction into a predicated
867   /// instruction. It returns true if the operation was successful.
868   virtual
869   bool PredicateInstruction(MachineInstr *MI,
870                         const SmallVectorImpl<MachineOperand> &Pred) const;
871
872   /// SubsumesPredicate - Returns true if the first specified predicate
873   /// subsumes the second, e.g. GE subsumes GT.
874   virtual
875   bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
876                          const SmallVectorImpl<MachineOperand> &Pred2) const {
877     return false;
878   }
879
880   /// DefinesPredicate - If the specified instruction defines any predicate
881   /// or condition code register(s) used for predication, returns true as well
882   /// as the definition predicate(s) by reference.
883   virtual bool DefinesPredicate(MachineInstr *MI,
884                                 std::vector<MachineOperand> &Pred) const {
885     return false;
886   }
887
888   /// isPredicable - Return true if the specified instruction can be predicated.
889   /// By default, this returns true for every instruction with a
890   /// PredicateOperand.
891   virtual bool isPredicable(MachineInstr *MI) const {
892     return MI->getDesc().isPredicable();
893   }
894
895   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
896   /// instruction that defines the specified register class.
897   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
898     return true;
899   }
900
901   /// isSchedulingBoundary - Test if the given instruction should be
902   /// considered a scheduling boundary. This primarily includes labels and
903   /// terminators.
904   virtual bool isSchedulingBoundary(const MachineInstr *MI,
905                                     const MachineBasicBlock *MBB,
906                                     const MachineFunction &MF) const;
907
908   /// Measure the specified inline asm to determine an approximation of its
909   /// length.
910   virtual unsigned getInlineAsmLength(const char *Str,
911                                       const MCAsmInfo &MAI) const;
912
913   /// CreateTargetHazardRecognizer - Allocate and return a hazard recognizer to
914   /// use for this target when scheduling the machine instructions before
915   /// register allocation.
916   virtual ScheduleHazardRecognizer*
917   CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
918                                const ScheduleDAG *DAG) const;
919
920   /// CreateTargetMIHazardRecognizer - Allocate and return a hazard recognizer
921   /// to use for this target when scheduling the machine instructions before
922   /// register allocation.
923   virtual ScheduleHazardRecognizer*
924   CreateTargetMIHazardRecognizer(const InstrItineraryData*,
925                                  const ScheduleDAG *DAG) const;
926
927   /// CreateTargetPostRAHazardRecognizer - Allocate and return a hazard
928   /// recognizer to use for this target when scheduling the machine instructions
929   /// after register allocation.
930   virtual ScheduleHazardRecognizer*
931   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
932                                      const ScheduleDAG *DAG) const;
933
934   /// Provide a global flag for disabling the PreRA hazard recognizer that
935   /// targets may choose to honor.
936   bool usePreRAHazardRecognizer() const;
937
938   /// analyzeCompare - For a comparison instruction, return the source registers
939   /// in SrcReg and SrcReg2 if having two register operands, and the value it
940   /// compares against in CmpValue. Return true if the comparison instruction
941   /// can be analyzed.
942   virtual bool analyzeCompare(const MachineInstr *MI,
943                               unsigned &SrcReg, unsigned &SrcReg2,
944                               int &Mask, int &Value) const {
945     return false;
946   }
947
948   /// optimizeCompareInstr - See if the comparison instruction can be converted
949   /// into something more efficient. E.g., on ARM most instructions can set the
950   /// flags register, obviating the need for a separate CMP.
951   virtual bool optimizeCompareInstr(MachineInstr *CmpInstr,
952                                     unsigned SrcReg, unsigned SrcReg2,
953                                     int Mask, int Value,
954                                     const MachineRegisterInfo *MRI) const {
955     return false;
956   }
957
958   /// optimizeLoadInstr - Try to remove the load by folding it to a register
959   /// operand at the use. We fold the load instructions if and only if the
960   /// def and use are in the same BB. We only look at one load and see
961   /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
962   /// defined by the load we are trying to fold. DefMI returns the machine
963   /// instruction that defines FoldAsLoadDefReg, and the function returns
964   /// the machine instruction generated due to folding.
965   virtual MachineInstr* optimizeLoadInstr(MachineInstr *MI,
966                         const MachineRegisterInfo *MRI,
967                         unsigned &FoldAsLoadDefReg,
968                         MachineInstr *&DefMI) const {
969     return nullptr;
970   }
971
972   /// FoldImmediate - 'Reg' is known to be defined by a move immediate
973   /// instruction, try to fold the immediate into the use instruction.
974   /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
975   /// then the caller may assume that DefMI has been erased from its parent
976   /// block. The caller may assume that it will not be erased by this
977   /// function otherwise.
978   virtual bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
979                              unsigned Reg, MachineRegisterInfo *MRI) const {
980     return false;
981   }
982
983   /// getNumMicroOps - Return the number of u-operations the given machine
984   /// instruction will be decoded to on the target cpu. The itinerary's
985   /// IssueWidth is the number of microops that can be dispatched each
986   /// cycle. An instruction with zero microops takes no dispatch resources.
987   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
988                                   const MachineInstr *MI) const;
989
990   /// isZeroCost - Return true for pseudo instructions that don't consume any
991   /// machine resources in their current form. These are common cases that the
992   /// scheduler should consider free, rather than conservatively handling them
993   /// as instructions with no itinerary.
994   bool isZeroCost(unsigned Opcode) const {
995     return Opcode <= TargetOpcode::COPY;
996   }
997
998   virtual int getOperandLatency(const InstrItineraryData *ItinData,
999                                 SDNode *DefNode, unsigned DefIdx,
1000                                 SDNode *UseNode, unsigned UseIdx) const;
1001
1002   /// getOperandLatency - Compute and return the use operand latency of a given
1003   /// pair of def and use.
1004   /// In most cases, the static scheduling itinerary was enough to determine the
1005   /// operand latency. But it may not be possible for instructions with variable
1006   /// number of defs / uses.
1007   ///
1008   /// This is a raw interface to the itinerary that may be directly overriden by
1009   /// a target. Use computeOperandLatency to get the best estimate of latency.
1010   virtual int getOperandLatency(const InstrItineraryData *ItinData,
1011                                 const MachineInstr *DefMI, unsigned DefIdx,
1012                                 const MachineInstr *UseMI,
1013                                 unsigned UseIdx) const;
1014
1015   /// computeOperandLatency - Compute and return the latency of the given data
1016   /// dependent def and use when the operand indices are already known.
1017   unsigned computeOperandLatency(const InstrItineraryData *ItinData,
1018                                  const MachineInstr *DefMI, unsigned DefIdx,
1019                                  const MachineInstr *UseMI, unsigned UseIdx)
1020     const;
1021
1022   /// getInstrLatency - Compute the instruction latency of a given instruction.
1023   /// If the instruction has higher cost when predicated, it's returned via
1024   /// PredCost.
1025   virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1026                                    const MachineInstr *MI,
1027                                    unsigned *PredCost = nullptr) const;
1028
1029   virtual unsigned getPredicationCost(const MachineInstr *MI) const;
1030
1031   virtual int getInstrLatency(const InstrItineraryData *ItinData,
1032                               SDNode *Node) const;
1033
1034   /// Return the default expected latency for a def based on it's opcode.
1035   unsigned defaultDefLatency(const MCSchedModel *SchedModel,
1036                              const MachineInstr *DefMI) const;
1037
1038   int computeDefOperandLatency(const InstrItineraryData *ItinData,
1039                                const MachineInstr *DefMI) const;
1040
1041   /// isHighLatencyDef - Return true if this opcode has high latency to its
1042   /// result.
1043   virtual bool isHighLatencyDef(int opc) const { return false; }
1044
1045   /// hasHighOperandLatency - Compute operand latency between a def of 'Reg'
1046   /// and an use in the current loop, return true if the target considered
1047   /// it 'high'. This is used by optimization passes such as machine LICM to
1048   /// determine whether it makes sense to hoist an instruction out even in
1049   /// high register pressure situation.
1050   virtual
1051   bool hasHighOperandLatency(const InstrItineraryData *ItinData,
1052                              const MachineRegisterInfo *MRI,
1053                              const MachineInstr *DefMI, unsigned DefIdx,
1054                              const MachineInstr *UseMI, unsigned UseIdx) const {
1055     return false;
1056   }
1057
1058   /// hasLowDefLatency - Compute operand latency of a def of 'Reg', return true
1059   /// if the target considered it 'low'.
1060   virtual
1061   bool hasLowDefLatency(const InstrItineraryData *ItinData,
1062                         const MachineInstr *DefMI, unsigned DefIdx) const;
1063
1064   /// verifyInstruction - Perform target specific instruction verification.
1065   virtual
1066   bool verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const {
1067     return true;
1068   }
1069
1070   /// getExecutionDomain - Return the current execution domain and bit mask of
1071   /// possible domains for instruction.
1072   ///
1073   /// Some micro-architectures have multiple execution domains, and multiple
1074   /// opcodes that perform the same operation in different domains.  For
1075   /// example, the x86 architecture provides the por, orps, and orpd
1076   /// instructions that all do the same thing.  There is a latency penalty if a
1077   /// register is written in one domain and read in another.
1078   ///
1079   /// This function returns a pair (domain, mask) containing the execution
1080   /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
1081   /// function can be used to change the opcode to one of the domains in the
1082   /// bit mask.  Instructions whose execution domain can't be changed should
1083   /// return a 0 mask.
1084   ///
1085   /// The execution domain numbers don't have any special meaning except domain
1086   /// 0 is used for instructions that are not associated with any interesting
1087   /// execution domain.
1088   ///
1089   virtual std::pair<uint16_t, uint16_t>
1090   getExecutionDomain(const MachineInstr *MI) const {
1091     return std::make_pair(0, 0);
1092   }
1093
1094   /// setExecutionDomain - Change the opcode of MI to execute in Domain.
1095   ///
1096   /// The bit (1 << Domain) must be set in the mask returned from
1097   /// getExecutionDomain(MI).
1098   ///
1099   virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const {}
1100
1101
1102   /// getPartialRegUpdateClearance - Returns the preferred minimum clearance
1103   /// before an instruction with an unwanted partial register update.
1104   ///
1105   /// Some instructions only write part of a register, and implicitly need to
1106   /// read the other parts of the register.  This may cause unwanted stalls
1107   /// preventing otherwise unrelated instructions from executing in parallel in
1108   /// an out-of-order CPU.
1109   ///
1110   /// For example, the x86 instruction cvtsi2ss writes its result to bits
1111   /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1112   /// the instruction needs to wait for the old value of the register to become
1113   /// available:
1114   ///
1115   ///   addps %xmm1, %xmm0
1116   ///   movaps %xmm0, (%rax)
1117   ///   cvtsi2ss %rbx, %xmm0
1118   ///
1119   /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1120   /// instruction before it can issue, even though the high bits of %xmm0
1121   /// probably aren't needed.
1122   ///
1123   /// This hook returns the preferred clearance before MI, measured in
1124   /// instructions.  Other defs of MI's operand OpNum are avoided in the last N
1125   /// instructions before MI.  It should only return a positive value for
1126   /// unwanted dependencies.  If the old bits of the defined register have
1127   /// useful values, or if MI is determined to otherwise read the dependency,
1128   /// the hook should return 0.
1129   ///
1130   /// The unwanted dependency may be handled by:
1131   ///
1132   /// 1. Allocating the same register for an MI def and use.  That makes the
1133   ///    unwanted dependency identical to a required dependency.
1134   ///
1135   /// 2. Allocating a register for the def that has no defs in the previous N
1136   ///    instructions.
1137   ///
1138   /// 3. Calling breakPartialRegDependency() with the same arguments.  This
1139   ///    allows the target to insert a dependency breaking instruction.
1140   ///
1141   virtual unsigned
1142   getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
1143                                const TargetRegisterInfo *TRI) const {
1144     // The default implementation returns 0 for no partial register dependency.
1145     return 0;
1146   }
1147
1148   /// \brief Return the minimum clearance before an instruction that reads an
1149   /// unused register.
1150   ///
1151   /// For example, AVX instructions may copy part of an register operand into
1152   /// the unused high bits of the destination register.
1153   ///
1154   /// vcvtsi2sdq %rax, %xmm0<undef>, %xmm14
1155   ///
1156   /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
1157   /// false dependence on any previous write to %xmm0.
1158   ///
1159   /// This hook works similarly to getPartialRegUpdateClearance, except that it
1160   /// does not take an operand index. Instead sets \p OpNum to the index of the
1161   /// unused register.
1162   virtual unsigned getUndefRegClearance(const MachineInstr *MI, unsigned &OpNum,
1163                                         const TargetRegisterInfo *TRI) const {
1164     // The default implementation returns 0 for no undef register dependency.
1165     return 0;
1166   }
1167
1168   /// breakPartialRegDependency - Insert a dependency-breaking instruction
1169   /// before MI to eliminate an unwanted dependency on OpNum.
1170   ///
1171   /// If it wasn't possible to avoid a def in the last N instructions before MI
1172   /// (see getPartialRegUpdateClearance), this hook will be called to break the
1173   /// unwanted dependency.
1174   ///
1175   /// On x86, an xorps instruction can be used as a dependency breaker:
1176   ///
1177   ///   addps %xmm1, %xmm0
1178   ///   movaps %xmm0, (%rax)
1179   ///   xorps %xmm0, %xmm0
1180   ///   cvtsi2ss %rbx, %xmm0
1181   ///
1182   /// An <imp-kill> operand should be added to MI if an instruction was
1183   /// inserted.  This ties the instructions together in the post-ra scheduler.
1184   ///
1185   virtual void
1186   breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
1187                             const TargetRegisterInfo *TRI) const {}
1188
1189   /// Create machine specific model for scheduling.
1190   virtual DFAPacketizer*
1191     CreateTargetScheduleState(const TargetMachine*, const ScheduleDAG*) const {
1192     return nullptr;
1193   }
1194
1195 private:
1196   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
1197 };
1198
1199 } // End llvm namespace
1200
1201 #endif