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