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