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