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