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