TargetInstrInfo.h revision 0eb3edea9cb6819334173a7d288da85943201fe5
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
22namespace llvm {
23
24class InstrItineraryData;
25class LiveVariables;
26class MCAsmInfo;
27class MachineMemOperand;
28class MachineRegisterInfo;
29class MDNode;
30class MCInst;
31class SDNode;
32class ScheduleHazardRecognizer;
33class SelectionDAG;
34class ScheduleDAG;
35class TargetRegisterClass;
36class TargetRegisterInfo;
37class BranchProbability;
38
39template<class T> class SmallVectorImpl;
40
41
42//---------------------------------------------------------------------------
43///
44/// TargetInstrInfo - Interface to description of machine instruction set
45///
46class TargetInstrInfo : public MCInstrInfo {
47  TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
48  void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
49public:
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
75protected:
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
87private:
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
96public:
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
501protected:
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
522public:
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.
700  virtual MachineInstr* optimizeLoadInstr(MachineInstr *MI,
701                        const MachineRegisterInfo *MRI,
702                        SmallSet<unsigned, 4> &FoldAsLoadDefRegs,
703                        MachineInstr *&DefMI) const {
704    return 0;
705  }
706
707  /// FoldImmediate - 'Reg' is known to be defined by a move immediate
708  /// instruction, try to fold the immediate into the use instruction.
709  virtual bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
710                             unsigned Reg, MachineRegisterInfo *MRI) const {
711    return false;
712  }
713
714  /// getNumMicroOps - Return the number of u-operations the given machine
715  /// instruction will be decoded to on the target cpu. The itinerary's
716  /// IssueWidth is the number of microops that can be dispatched each
717  /// cycle. An instruction with zero microops takes no dispatch resources.
718  virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
719                                  const MachineInstr *MI) const = 0;
720
721  /// isZeroCost - Return true for pseudo instructions that don't consume any
722  /// machine resources in their current form. These are common cases that the
723  /// scheduler should consider free, rather than conservatively handling them
724  /// as instructions with no itinerary.
725  bool isZeroCost(unsigned Opcode) const {
726    return Opcode <= TargetOpcode::COPY;
727  }
728
729  virtual int getOperandLatency(const InstrItineraryData *ItinData,
730                                SDNode *DefNode, unsigned DefIdx,
731                                SDNode *UseNode, unsigned UseIdx) const = 0;
732
733  /// getOperandLatency - Compute and return the use operand latency of a given
734  /// pair of def and use.
735  /// In most cases, the static scheduling itinerary was enough to determine the
736  /// operand latency. But it may not be possible for instructions with variable
737  /// number of defs / uses.
738  ///
739  /// This is a raw interface to the itinerary that may be directly overriden by
740  /// a target. Use computeOperandLatency to get the best estimate of latency.
741  virtual int getOperandLatency(const InstrItineraryData *ItinData,
742                                const MachineInstr *DefMI, unsigned DefIdx,
743                                const MachineInstr *UseMI,
744                                unsigned UseIdx) const = 0;
745
746  /// computeOperandLatency - Compute and return the latency of the given data
747  /// dependent def and use when the operand indices are already known.
748  ///
749  /// FindMin may be set to get the minimum vs. expected latency.
750  unsigned computeOperandLatency(const InstrItineraryData *ItinData,
751                                 const MachineInstr *DefMI, unsigned DefIdx,
752                                 const MachineInstr *UseMI, unsigned UseIdx,
753                                 bool FindMin = false) const;
754
755  /// computeOperandLatency - Compute and return the latency of the given data
756  /// dependent def and use. DefMI must be a valid def. UseMI may be NULL for
757  /// an unknown use. If the subtarget allows, this may or may not need to call
758  /// getOperandLatency().
759  ///
760  /// FindMin may be set to get the minimum vs. expected latency. Minimum
761  /// latency is used for scheduling groups, while expected latency is for
762  /// instruction cost and critical path.
763  unsigned computeOperandLatency(const InstrItineraryData *ItinData,
764                                 const TargetRegisterInfo *TRI,
765                                 const MachineInstr *DefMI,
766                                 const MachineInstr *UseMI,
767                                 unsigned Reg, bool FindMin) const;
768
769  /// getOutputLatency - Compute and return the output dependency latency of a
770  /// a given pair of defs which both target the same register. This is usually
771  /// one.
772  virtual unsigned getOutputLatency(const InstrItineraryData *ItinData,
773                                    const MachineInstr *DefMI, unsigned DefIdx,
774                                    const MachineInstr *DepMI) const {
775    return 1;
776  }
777
778  /// getInstrLatency - Compute the instruction latency of a given instruction.
779  /// If the instruction has higher cost when predicated, it's returned via
780  /// PredCost.
781  virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
782                                   const MachineInstr *MI,
783                                   unsigned *PredCost = 0) const = 0;
784
785  virtual int getInstrLatency(const InstrItineraryData *ItinData,
786                              SDNode *Node) const = 0;
787
788  /// Return the default expected latency for a def based on it's opcode.
789  unsigned defaultDefLatency(const InstrItineraryData *ItinData,
790                             const MachineInstr *DefMI) const;
791
792  /// isHighLatencyDef - Return true if this opcode has high latency to its
793  /// result.
794  virtual bool isHighLatencyDef(int opc) const { return false; }
795
796  /// hasHighOperandLatency - Compute operand latency between a def of 'Reg'
797  /// and an use in the current loop, return true if the target considered
798  /// it 'high'. This is used by optimization passes such as machine LICM to
799  /// determine whether it makes sense to hoist an instruction out even in
800  /// high register pressure situation.
801  virtual
802  bool hasHighOperandLatency(const InstrItineraryData *ItinData,
803                             const MachineRegisterInfo *MRI,
804                             const MachineInstr *DefMI, unsigned DefIdx,
805                             const MachineInstr *UseMI, unsigned UseIdx) const {
806    return false;
807  }
808
809  /// hasLowDefLatency - Compute operand latency of a def of 'Reg', return true
810  /// if the target considered it 'low'.
811  virtual
812  bool hasLowDefLatency(const InstrItineraryData *ItinData,
813                        const MachineInstr *DefMI, unsigned DefIdx) const = 0;
814
815  /// verifyInstruction - Perform target specific instruction verification.
816  virtual
817  bool verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const {
818    return true;
819  }
820
821  /// getExecutionDomain - Return the current execution domain and bit mask of
822  /// possible domains for instruction.
823  ///
824  /// Some micro-architectures have multiple execution domains, and multiple
825  /// opcodes that perform the same operation in different domains.  For
826  /// example, the x86 architecture provides the por, orps, and orpd
827  /// instructions that all do the same thing.  There is a latency penalty if a
828  /// register is written in one domain and read in another.
829  ///
830  /// This function returns a pair (domain, mask) containing the execution
831  /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
832  /// function can be used to change the opcode to one of the domains in the
833  /// bit mask.  Instructions whose execution domain can't be changed should
834  /// return a 0 mask.
835  ///
836  /// The execution domain numbers don't have any special meaning except domain
837  /// 0 is used for instructions that are not associated with any interesting
838  /// execution domain.
839  ///
840  virtual std::pair<uint16_t, uint16_t>
841  getExecutionDomain(const MachineInstr *MI) const {
842    return std::make_pair(0, 0);
843  }
844
845  /// setExecutionDomain - Change the opcode of MI to execute in Domain.
846  ///
847  /// The bit (1 << Domain) must be set in the mask returned from
848  /// getExecutionDomain(MI).
849  ///
850  virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const {}
851
852
853  /// getPartialRegUpdateClearance - Returns the preferred minimum clearance
854  /// before an instruction with an unwanted partial register update.
855  ///
856  /// Some instructions only write part of a register, and implicitly need to
857  /// read the other parts of the register.  This may cause unwanted stalls
858  /// preventing otherwise unrelated instructions from executing in parallel in
859  /// an out-of-order CPU.
860  ///
861  /// For example, the x86 instruction cvtsi2ss writes its result to bits
862  /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
863  /// the instruction needs to wait for the old value of the register to become
864  /// available:
865  ///
866  ///   addps %xmm1, %xmm0
867  ///   movaps %xmm0, (%rax)
868  ///   cvtsi2ss %rbx, %xmm0
869  ///
870  /// In the code above, the cvtsi2ss instruction needs to wait for the addps
871  /// instruction before it can issue, even though the high bits of %xmm0
872  /// probably aren't needed.
873  ///
874  /// This hook returns the preferred clearance before MI, measured in
875  /// instructions.  Other defs of MI's operand OpNum are avoided in the last N
876  /// instructions before MI.  It should only return a positive value for
877  /// unwanted dependencies.  If the old bits of the defined register have
878  /// useful values, or if MI is determined to otherwise read the dependency,
879  /// the hook should return 0.
880  ///
881  /// The unwanted dependency may be handled by:
882  ///
883  /// 1. Allocating the same register for an MI def and use.  That makes the
884  ///    unwanted dependency identical to a required dependency.
885  ///
886  /// 2. Allocating a register for the def that has no defs in the previous N
887  ///    instructions.
888  ///
889  /// 3. Calling breakPartialRegDependency() with the same arguments.  This
890  ///    allows the target to insert a dependency breaking instruction.
891  ///
892  virtual unsigned
893  getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
894                               const TargetRegisterInfo *TRI) const {
895    // The default implementation returns 0 for no partial register dependency.
896    return 0;
897  }
898
899  /// breakPartialRegDependency - Insert a dependency-breaking instruction
900  /// before MI to eliminate an unwanted dependency on OpNum.
901  ///
902  /// If it wasn't possible to avoid a def in the last N instructions before MI
903  /// (see getPartialRegUpdateClearance), this hook will be called to break the
904  /// unwanted dependency.
905  ///
906  /// On x86, an xorps instruction can be used as a dependency breaker:
907  ///
908  ///   addps %xmm1, %xmm0
909  ///   movaps %xmm0, (%rax)
910  ///   xorps %xmm0, %xmm0
911  ///   cvtsi2ss %rbx, %xmm0
912  ///
913  /// An <imp-kill> operand should be added to MI if an instruction was
914  /// inserted.  This ties the instructions together in the post-ra scheduler.
915  ///
916  virtual void
917  breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
918                            const TargetRegisterInfo *TRI) const {}
919
920  /// Create machine specific model for scheduling.
921  virtual DFAPacketizer*
922    CreateTargetScheduleState(const TargetMachine*, const ScheduleDAG*) const {
923    return NULL;
924  }
925
926private:
927  int CallFrameSetupOpcode, CallFrameDestroyOpcode;
928};
929
930/// TargetInstrInfoImpl - This is the default implementation of
931/// TargetInstrInfo, which just provides a couple of default implementations
932/// for various methods.  This separated out because it is implemented in
933/// libcodegen, not in libtarget.
934class TargetInstrInfoImpl : public TargetInstrInfo {
935protected:
936  TargetInstrInfoImpl(int CallFrameSetupOpcode = -1,
937                      int CallFrameDestroyOpcode = -1)
938    : TargetInstrInfo(CallFrameSetupOpcode, CallFrameDestroyOpcode) {}
939public:
940  virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
941                                       MachineBasicBlock *NewDest) const;
942  virtual MachineInstr *commuteInstruction(MachineInstr *MI,
943                                           bool NewMI = false) const;
944  virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
945                                     unsigned &SrcOpIdx2) const;
946  virtual bool canFoldMemoryOperand(const MachineInstr *MI,
947                                    const SmallVectorImpl<unsigned> &Ops) const;
948  virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
949                                    const MachineMemOperand *&MMO,
950                                    int &FrameIndex) const;
951  virtual bool hasStoreToStackSlot(const MachineInstr *MI,
952                                   const MachineMemOperand *&MMO,
953                                   int &FrameIndex) const;
954  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
955  virtual bool PredicateInstruction(MachineInstr *MI,
956                            const SmallVectorImpl<MachineOperand> &Pred) const;
957  virtual void reMaterialize(MachineBasicBlock &MBB,
958                             MachineBasicBlock::iterator MI,
959                             unsigned DestReg, unsigned SubReg,
960                             const MachineInstr *Orig,
961                             const TargetRegisterInfo &TRI) const;
962  virtual MachineInstr *duplicate(MachineInstr *Orig,
963                                  MachineFunction &MF) const;
964  virtual bool produceSameValue(const MachineInstr *MI0,
965                                const MachineInstr *MI1,
966                                const MachineRegisterInfo *MRI) const;
967  virtual bool isSchedulingBoundary(const MachineInstr *MI,
968                                    const MachineBasicBlock *MBB,
969                                    const MachineFunction &MF) const;
970
971  virtual int getOperandLatency(const InstrItineraryData *ItinData,
972                                SDNode *DefNode, unsigned DefIdx,
973                                SDNode *UseNode, unsigned UseIdx) const;
974
975  virtual int getInstrLatency(const InstrItineraryData *ItinData,
976                              SDNode *Node) const;
977
978  virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
979                                  const MachineInstr *MI) const;
980
981  virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
982                                   const MachineInstr *MI,
983                                   unsigned *PredCost = 0) const;
984
985  virtual
986  bool hasLowDefLatency(const InstrItineraryData *ItinData,
987                        const MachineInstr *DefMI, unsigned DefIdx) const;
988
989  virtual int getOperandLatency(const InstrItineraryData *ItinData,
990                                const MachineInstr *DefMI, unsigned DefIdx,
991                                const MachineInstr *UseMI,
992                                unsigned UseIdx) const;
993
994  bool usePreRAHazardRecognizer() const;
995
996  virtual ScheduleHazardRecognizer *
997  CreateTargetHazardRecognizer(const TargetMachine*, const ScheduleDAG*) const;
998
999  virtual ScheduleHazardRecognizer *
1000  CreateTargetMIHazardRecognizer(const InstrItineraryData*,
1001                                 const ScheduleDAG*) const;
1002
1003  virtual ScheduleHazardRecognizer *
1004  CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
1005                                     const ScheduleDAG*) const;
1006};
1007
1008} // End llvm namespace
1009
1010#endif
1011