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