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