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