0635c23cbea10161e587d2f4348d7a05bf148747
[oota-llvm.git] / include / llvm / Target / TargetInstrInfo.h
1 //===-- llvm/Target/TargetInstrInfo.h - Instruction Info --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file describes the target machine instruction set to the code generator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_TARGET_TARGETINSTRINFO_H
15 #define LLVM_TARGET_TARGETINSTRINFO_H
16
17 #include "llvm/Target/TargetInstrDesc.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19
20 namespace llvm {
21
22 class TargetRegisterClass;
23 class TargetRegisterInfo;
24 class LiveVariables;
25 class CalleeSavedInfo;
26 class SDNode;
27 class SelectionDAG;
28
29 template<class T> class SmallVectorImpl;
30
31
32 //---------------------------------------------------------------------------
33 ///
34 /// TargetInstrInfo - Interface to description of machine instruction set
35 ///
36 class TargetInstrInfo {
37   const TargetInstrDesc *Descriptors; // Raw array to allow static init'n
38   unsigned NumOpcodes;                // Number of entries in the desc array
39
40   TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
41   void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
42 public:
43   TargetInstrInfo(const TargetInstrDesc *desc, unsigned NumOpcodes);
44   virtual ~TargetInstrInfo();
45
46   // Invariant opcodes: All instruction sets have these as their low opcodes.
47   enum { 
48     PHI = 0,
49     INLINEASM = 1,
50     DBG_LABEL = 2,
51     EH_LABEL = 3,
52     GC_LABEL = 4,
53     DECLARE = 5,
54
55     /// EXTRACT_SUBREG - This instruction takes two operands: a register
56     /// that has subregisters, and a subregister index. It returns the
57     /// extracted subregister value. This is commonly used to implement
58     /// truncation operations on target architectures which support it.
59     EXTRACT_SUBREG = 6,
60
61     /// INSERT_SUBREG - This instruction takes three operands: a register
62     /// that has subregisters, a register providing an insert value, and a
63     /// subregister index. It returns the value of the first register with
64     /// the value of the second register inserted. The first register is
65     /// often defined by an IMPLICIT_DEF, as is commonly used to implement
66     /// anyext operations on target architectures which support it.
67     INSERT_SUBREG = 7,
68
69     /// IMPLICIT_DEF - This is the MachineInstr-level equivalent of undef.
70     IMPLICIT_DEF = 8,
71
72     /// SUBREG_TO_REG - This instruction is similar to INSERT_SUBREG except
73     /// that the first operand is an immediate integer constant. This constant
74     /// is often zero, as is commonly used to implement zext operations on
75     /// target architectures which support it, such as with x86-64 (with
76     /// zext from i32 to i64 via implicit zero-extension).
77     SUBREG_TO_REG = 9,
78
79     /// COPY_TO_REGCLASS - This instruction is a placeholder for a plain
80     /// register-to-register copy into a specific register class. This is only
81     /// used between instruction selection and MachineInstr creation, before
82     /// virtual registers have been created for all the instructions, and it's
83     /// only needed in cases where the register classes implied by the
84     /// instructions are insufficient. The actual MachineInstrs to perform
85     /// the copy are emitted with the TargetInstrInfo::copyRegToReg hook.
86     COPY_TO_REGCLASS = 10
87   };
88
89   unsigned getNumOpcodes() const { return NumOpcodes; }
90
91   /// get - Return the machine instruction descriptor that corresponds to the
92   /// specified instruction opcode.
93   ///
94   const TargetInstrDesc &get(unsigned Opcode) const {
95     assert(Opcode < NumOpcodes && "Invalid opcode!");
96     return Descriptors[Opcode];
97   }
98
99   /// isTriviallyReMaterializable - Return true if the instruction is trivially
100   /// rematerializable, meaning it has no side effects and requires no operands
101   /// that aren't always available.
102   bool isTriviallyReMaterializable(const MachineInstr *MI) const {
103     return MI->getDesc().isRematerializable() &&
104            isReallyTriviallyReMaterializable(MI);
105   }
106
107 protected:
108   /// isReallyTriviallyReMaterializable - For instructions with opcodes for
109   /// which the M_REMATERIALIZABLE flag is set, this function tests whether the
110   /// instruction itself is actually trivially rematerializable, considering
111   /// its operands.  This is used for targets that have instructions that are
112   /// only trivially rematerializable for specific uses.  This predicate must
113   /// return false if the instruction has any side effects other than
114   /// producing a value, or if it requres any address registers that are not
115   /// always available.
116   virtual bool isReallyTriviallyReMaterializable(const MachineInstr *MI) const {
117     return true;
118   }
119
120 public:
121   /// Return true if the instruction is a register to register move and return
122   /// the source and dest operands and their sub-register indices by reference.
123   virtual bool isMoveInstr(const MachineInstr& MI,
124                            unsigned& SrcReg, unsigned& DstReg,
125                            unsigned& SrcSubIdx, unsigned& DstSubIdx) const {
126     return false;
127   }
128   
129   /// isLoadFromStackSlot - If the specified machine instruction is a direct
130   /// load from a stack slot, return the virtual or physical register number of
131   /// the destination along with the FrameIndex of the loaded stack slot.  If
132   /// not, return 0.  This predicate must return 0 if the instruction has
133   /// any side effects other than loading from the stack slot.
134   virtual unsigned isLoadFromStackSlot(const MachineInstr *MI,
135                                        int &FrameIndex) const {
136     return 0;
137   }
138   
139   /// isStoreToStackSlot - If the specified machine instruction is a direct
140   /// store to a stack slot, return the virtual or physical register number of
141   /// the source reg along with the FrameIndex of the loaded stack slot.  If
142   /// not, return 0.  This predicate must return 0 if the instruction has
143   /// any side effects other than storing to the stack slot.
144   virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
145                                       int &FrameIndex) const {
146     return 0;
147   }
148
149   /// reMaterialize - Re-issue the specified 'original' instruction at the
150   /// specific location targeting a new destination register.
151   virtual void reMaterialize(MachineBasicBlock &MBB,
152                              MachineBasicBlock::iterator MI,
153                              unsigned DestReg,
154                              const MachineInstr *Orig) const = 0;
155
156   /// isInvariantLoad - Return true if the specified instruction (which is
157   /// marked mayLoad) is loading from a location whose value is invariant across
158   /// the function.  For example, loading a value from the constant pool or from
159   /// from the argument area of a function if it does not change.  This should
160   /// only return true of *all* loads the instruction does are invariant (if it
161   /// does multiple loads).
162   virtual bool isInvariantLoad(const MachineInstr *MI) const {
163     return false;
164   }
165   
166   /// convertToThreeAddress - This method must be implemented by targets that
167   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
168   /// may be able to convert a two-address instruction into one or more true
169   /// three-address instructions on demand.  This allows the X86 target (for
170   /// example) to convert ADD and SHL instructions into LEA instructions if they
171   /// would require register copies due to two-addressness.
172   ///
173   /// This method returns a null pointer if the transformation cannot be
174   /// performed, otherwise it returns the last new instruction.
175   ///
176   virtual MachineInstr *
177   convertToThreeAddress(MachineFunction::iterator &MFI,
178                    MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const {
179     return 0;
180   }
181
182   /// commuteInstruction - If a target has any instructions that are commutable,
183   /// but require converting to a different instruction or making non-trivial
184   /// changes to commute them, this method can overloaded to do this.  The
185   /// default implementation of this method simply swaps the first two operands
186   /// of MI and returns it.
187   ///
188   /// If a target wants to make more aggressive changes, they can construct and
189   /// return a new machine instruction.  If an instruction cannot commute, it
190   /// can also return null.
191   ///
192   /// If NewMI is true, then a new machine instruction must be created.
193   ///
194   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
195                                            bool NewMI = false) const = 0;
196
197   /// findCommutedOpIndices - If specified MI is commutable, return the two
198   /// operand indices that would swap value. Return true if the instruction
199   /// is not in a form which this routine understands.
200   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
201                                      unsigned &SrcOpIdx2) const = 0;
202
203   /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
204   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
205   /// implemented for a target).  Upon success, this returns false and returns
206   /// with the following information in various cases:
207   ///
208   /// 1. If this block ends with no branches (it just falls through to its succ)
209   ///    just return false, leaving TBB/FBB null.
210   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
211   ///    the destination block.
212   /// 3. If this block ends with an conditional branch and it falls through to
213   ///    an successor block, it sets TBB to be the branch destination block and
214   ///    a list of operands that evaluate the condition. These
215   ///    operands can be passed to other TargetInstrInfo methods to create new
216   ///    branches.
217   /// 4. If this block ends with an conditional branch and an unconditional
218   ///    block, it returns the 'true' destination in TBB, the 'false'
219   ///    destination in FBB, and a list of operands that evaluate the condition.
220   ///    These operands can be passed to other TargetInstrInfo methods to create
221   ///    new branches.
222   ///
223   /// Note that RemoveBranch and InsertBranch must be implemented to support
224   /// cases where this method returns success.
225   ///
226   /// If AllowModify is true, then this routine is allowed to modify the basic
227   /// block (e.g. delete instructions after the unconditional branch).
228   ///
229   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
230                              MachineBasicBlock *&FBB,
231                              SmallVectorImpl<MachineOperand> &Cond,
232                              bool AllowModify = false) const {
233     return true;
234   }
235   
236   /// RemoveBranch - Remove the branching code at the end of the specific MBB.
237   /// This is only invoked in cases where AnalyzeBranch returns success. It
238   /// returns the number of instructions that were removed.
239   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
240     assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!"); 
241     return 0;
242   }
243   
244   /// InsertBranch - Insert a branch into the end of the specified
245   /// MachineBasicBlock.  This operands to this method are the same as those
246   /// returned by AnalyzeBranch.  This is invoked in cases where AnalyzeBranch
247   /// returns success and when an unconditional branch (TBB is non-null, FBB is
248   /// null, Cond is empty) needs to be inserted. It returns the number of
249   /// instructions inserted.
250   ///
251   /// It is also invoked by tail merging to add unconditional branches in
252   /// cases where AnalyzeBranch doesn't apply because there was no original
253   /// branch to analyze.  At least this much must be implemented, else tail
254   /// merging needs to be disabled.
255   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
256                             MachineBasicBlock *FBB,
257                             const SmallVectorImpl<MachineOperand> &Cond) const {
258     assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!"); 
259     return 0;
260   }
261   
262   /// copyRegToReg - Emit instructions to copy between a pair of registers. It
263   /// returns false if the target does not how to copy between the specified
264   /// registers.
265   virtual bool copyRegToReg(MachineBasicBlock &MBB,
266                             MachineBasicBlock::iterator MI,
267                             unsigned DestReg, unsigned SrcReg,
268                             const TargetRegisterClass *DestRC,
269                             const TargetRegisterClass *SrcRC) const {
270     assert(0 && "Target didn't implement TargetInstrInfo::copyRegToReg!");
271     return false;
272   }
273   
274   /// storeRegToStackSlot - Store the specified register of the given register
275   /// class to the specified stack frame index. The store instruction is to be
276   /// added to the given machine basic block before the specified machine
277   /// instruction. If isKill is true, the register operand is the last use and
278   /// must be marked kill.
279   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
280                                    MachineBasicBlock::iterator MI,
281                                    unsigned SrcReg, bool isKill, int FrameIndex,
282                                    const TargetRegisterClass *RC) const {
283     assert(0 && "Target didn't implement TargetInstrInfo::storeRegToStackSlot!");
284   }
285
286   /// storeRegToAddr - Store the specified register of the given register class
287   /// to the specified address. The store instruction is to be added to the
288   /// given machine basic block before the specified machine instruction. If
289   /// isKill is true, the register operand is the last use and must be marked
290   /// kill.
291   virtual void storeRegToAddr(MachineFunction &MF, unsigned SrcReg, bool isKill,
292                               SmallVectorImpl<MachineOperand> &Addr,
293                               const TargetRegisterClass *RC,
294                               SmallVectorImpl<MachineInstr*> &NewMIs) const {
295     assert(0 && "Target didn't implement TargetInstrInfo::storeRegToAddr!");
296   }
297
298   /// loadRegFromStackSlot - Load the specified register of the given register
299   /// class from the specified stack frame index. The load instruction is to be
300   /// added to the given machine basic block before the specified machine
301   /// instruction.
302   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
303                                     MachineBasicBlock::iterator MI,
304                                     unsigned DestReg, int FrameIndex,
305                                     const TargetRegisterClass *RC) const {
306     assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromStackSlot!");
307   }
308
309   /// loadRegFromAddr - Load the specified register of the given register class
310   /// class from the specified address. The load instruction is to be added to
311   /// the given machine basic block before the specified machine instruction.
312   virtual void loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
313                                SmallVectorImpl<MachineOperand> &Addr,
314                                const TargetRegisterClass *RC,
315                                SmallVectorImpl<MachineInstr*> &NewMIs) const {
316     assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromAddr!");
317   }
318   
319   /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
320   /// saved registers and returns true if it isn't possible / profitable to do
321   /// so by issuing a series of store instructions via
322   /// storeRegToStackSlot(). Returns false otherwise.
323   virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
324                                          MachineBasicBlock::iterator MI,
325                                 const std::vector<CalleeSavedInfo> &CSI) const {
326     return false;
327   }
328
329   /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
330   /// saved registers and returns true if it isn't possible / profitable to do
331   /// so by issuing a series of load instructions via loadRegToStackSlot().
332   /// Returns false otherwise.
333   virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
334                                            MachineBasicBlock::iterator MI,
335                                 const std::vector<CalleeSavedInfo> &CSI) const {
336     return false;
337   }
338   
339   /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
340   /// slot into the specified machine instruction for the specified operand(s).
341   /// If this is possible, a new instruction is returned with the specified
342   /// operand folded, otherwise NULL is returned. The client is responsible for
343   /// removing the old instruction and adding the new one in the instruction
344   /// stream.
345   MachineInstr* foldMemoryOperand(MachineFunction &MF,
346                                   MachineInstr* MI,
347                                   const SmallVectorImpl<unsigned> &Ops,
348                                   int FrameIndex) const;
349
350   /// foldMemoryOperand - Same as the previous version except it allows folding
351   /// of any load and store from / to any address, not just from a specific
352   /// stack slot.
353   MachineInstr* foldMemoryOperand(MachineFunction &MF,
354                                   MachineInstr* MI,
355                                   const SmallVectorImpl<unsigned> &Ops,
356                                   MachineInstr* LoadMI) const;
357
358 protected:
359   /// foldMemoryOperandImpl - Target-dependent implementation for
360   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
361   /// take care of adding a MachineMemOperand to the newly created instruction.
362   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
363                                           MachineInstr* MI,
364                                           const SmallVectorImpl<unsigned> &Ops,
365                                           int FrameIndex) const {
366     return 0;
367   }
368
369   /// foldMemoryOperandImpl - Target-dependent implementation for
370   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
371   /// take care of adding a MachineMemOperand to the newly created instruction.
372   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
373                                               MachineInstr* MI,
374                                               const SmallVectorImpl<unsigned> &Ops,
375                                               MachineInstr* LoadMI) const {
376     return 0;
377   }
378
379 public:
380   /// canFoldMemoryOperand - Returns true for the specified load / store if
381   /// folding is possible.
382   virtual
383   bool canFoldMemoryOperand(const MachineInstr *MI,
384                             const SmallVectorImpl<unsigned> &Ops) const {
385     return false;
386   }
387
388   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
389   /// a store or a load and a store into two or more instruction. If this is
390   /// possible, returns true as well as the new instructions by reference.
391   virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
392                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
393                                  SmallVectorImpl<MachineInstr*> &NewMIs) const{
394     return false;
395   }
396
397   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
398                                    SmallVectorImpl<SDNode*> &NewNodes) const {
399     return false;
400   }
401
402   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
403   /// instruction after load / store are unfolded from an instruction of the
404   /// specified opcode. It returns zero if the specified unfolding is not
405   /// possible.
406   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
407                                       bool UnfoldLoad, bool UnfoldStore) const {
408     return 0;
409   }
410   
411   /// BlockHasNoFallThrough - Return true if the specified block does not
412   /// fall-through into its successor block.  This is primarily used when a
413   /// branch is unanalyzable.  It is useful for things like unconditional
414   /// indirect branches (jump tables).
415   virtual bool BlockHasNoFallThrough(const MachineBasicBlock &MBB) const {
416     return false;
417   }
418   
419   /// ReverseBranchCondition - Reverses the branch condition of the specified
420   /// condition list, returning false on success and true if it cannot be
421   /// reversed.
422   virtual
423   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
424     return true;
425   }
426   
427   /// insertNoop - Insert a noop into the instruction stream at the specified
428   /// point.
429   virtual void insertNoop(MachineBasicBlock &MBB, 
430                           MachineBasicBlock::iterator MI) const {
431     assert(0 && "Target didn't implement insertNoop!");
432     abort();
433   }
434
435   /// isPredicated - Returns true if the instruction is already predicated.
436   ///
437   virtual bool isPredicated(const MachineInstr *MI) const {
438     return false;
439   }
440
441   /// isUnpredicatedTerminator - Returns true if the instruction is a
442   /// terminator instruction that has not been predicated.
443   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
444
445   /// PredicateInstruction - Convert the instruction into a predicated
446   /// instruction. It returns true if the operation was successful.
447   virtual
448   bool PredicateInstruction(MachineInstr *MI,
449                         const SmallVectorImpl<MachineOperand> &Pred) const = 0;
450
451   /// SubsumesPredicate - Returns true if the first specified predicate
452   /// subsumes the second, e.g. GE subsumes GT.
453   virtual
454   bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
455                          const SmallVectorImpl<MachineOperand> &Pred2) const {
456     return false;
457   }
458
459   /// DefinesPredicate - If the specified instruction defines any predicate
460   /// or condition code register(s) used for predication, returns true as well
461   /// as the definition predicate(s) by reference.
462   virtual bool DefinesPredicate(MachineInstr *MI,
463                                 std::vector<MachineOperand> &Pred) const {
464     return false;
465   }
466
467   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
468   /// instruction that defines the specified register class.
469   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
470     return true;
471   }
472
473   /// GetInstSize - Returns the size of the specified Instruction.
474   /// 
475   virtual unsigned GetInstSizeInBytes(const MachineInstr *MI) const {
476     assert(0 && "Target didn't implement TargetInstrInfo::GetInstSize!");
477     return 0;
478   }
479
480   /// GetFunctionSizeInBytes - Returns the size of the specified MachineFunction.
481   /// 
482   virtual unsigned GetFunctionSizeInBytes(const MachineFunction &MF) const = 0;
483 };
484
485 /// TargetInstrInfoImpl - This is the default implementation of
486 /// TargetInstrInfo, which just provides a couple of default implementations
487 /// for various methods.  This separated out because it is implemented in
488 /// libcodegen, not in libtarget.
489 class TargetInstrInfoImpl : public TargetInstrInfo {
490 protected:
491   TargetInstrInfoImpl(const TargetInstrDesc *desc, unsigned NumOpcodes)
492   : TargetInstrInfo(desc, NumOpcodes) {}
493 public:
494   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
495                                            bool NewMI = false) const;
496   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
497                                      unsigned &SrcOpIdx2) const;
498   virtual bool PredicateInstruction(MachineInstr *MI,
499                             const SmallVectorImpl<MachineOperand> &Pred) const;
500   virtual void reMaterialize(MachineBasicBlock &MBB,
501                              MachineBasicBlock::iterator MI,
502                              unsigned DestReg,
503                              const MachineInstr *Orig) const;
504   virtual unsigned GetFunctionSizeInBytes(const MachineFunction &MF) const;
505 };
506
507 /// getInstrOperandRegClass - Return register class of the operand of an
508 /// instruction of the specified TargetInstrDesc.
509 const TargetRegisterClass*
510 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
511                         const TargetInstrDesc &II, unsigned Op);
512
513 } // End llvm namespace
514
515 #endif