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