20a1970a198437460a09446e4d48ec18a981fa9c
[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 instructions to the code generator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_TARGET_TARGETINSTRINFO_H
15 #define LLVM_TARGET_TARGETINSTRINFO_H
16
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/Support/DataTypes.h"
20 #include <vector>
21 #include <cassert>
22
23 namespace llvm {
24
25 class TargetRegisterClass;
26 class LiveVariables;
27 class CalleeSavedInfo;
28 class SDNode;
29 class SelectionDAG;
30
31 template<class T> class SmallVectorImpl;
32
33 //===----------------------------------------------------------------------===//
34 // Machine Operand Flags and Description
35 //===----------------------------------------------------------------------===//
36   
37 namespace TOI {
38   // Operand constraints: only "tied_to" for now.
39   enum OperandConstraint {
40     TIED_TO = 0  // Must be allocated the same register as.
41   };
42   
43   /// OperandFlags - These are flags set on operands, but should be considered
44   /// private, all access should go through the TargetOperandInfo accessors.
45   /// See the accessors for a description of what these are.
46   enum OperandFlags {
47     LookupPtrRegClass = 0,
48     Predicate,
49     OptionalDef
50   };
51 }
52
53 /// TargetOperandInfo - This holds information about one operand of a machine
54 /// instruction, indicating the register class for register operands, etc.
55 ///
56 class TargetOperandInfo {
57 public:
58   /// RegClass - This specifies the register class enumeration of the operand 
59   /// if the operand is a register.  If not, this contains 0.
60   unsigned short RegClass;
61   unsigned short Flags;
62   /// Lower 16 bits are used to specify which constraints are set. The higher 16
63   /// bits are used to specify the value of constraints (4 bits each).
64   unsigned int Constraints;
65   /// Currently no other information.
66   
67   /// isLookupPtrRegClass - Set if this operand is a pointer value and it
68   /// requires a callback to look up its register class.
69   bool isLookupPtrRegClass() const { return Flags&(1 <<TOI::LookupPtrRegClass);}
70   
71   /// isPredicate - Set if this is one of the operands that made up of
72   /// the predicate operand that controls an isPredicable() instruction.
73   bool isPredicate() const { return Flags & (1 << TOI::Predicate); }
74   
75   /// isOptionalDef - Set if this operand is a optional def.
76   ///
77   bool isOptionalDef() const { return Flags & (1 << TOI::OptionalDef); }
78 };
79
80   
81 //===----------------------------------------------------------------------===//
82 // Machine Instruction Flags and Description
83 //===----------------------------------------------------------------------===//
84
85 /// TargetInstrDescriptor flags - These should be considered private to the
86 /// implementation of the TargetInstrDescriptor class.  Clients should use the
87 /// predicate methods on TargetInstrDescriptor, not use these directly.  These
88 /// all correspond to bitfields in the TargetInstrDescriptor::Flags field.
89 namespace TID {
90   enum {
91     Variadic = 0,
92     HasOptionalDef,
93     Return,
94     Call,
95     ImplicitDef,
96     Barrier,
97     Terminator,
98     Branch,
99     IndirectBranch,
100     Predicable,
101     NotDuplicable,
102     DelaySlot,
103     SimpleLoad,
104     MayStore,
105     NeverHasSideEffects,
106     MayHaveSideEffects,
107     Commutable,
108     ConvertibleTo3Addr,
109     UsesCustomDAGSchedInserter,
110     Rematerializable
111   };
112 }
113
114 /// TargetInstrDescriptor - Describe properties that are true of each
115 /// instruction in the target description file.  This captures information about
116 /// side effects, register use and many other things.  There is one instance of
117 /// this struct for each target instruction class, and the MachineInstr class
118 /// points to this struct directly to describe itself.
119 class TargetInstrDescriptor {
120 public:
121   unsigned short  Opcode;        // The opcode number.
122   unsigned short  NumOperands;   // Num of args (may be more if variable_ops)
123   unsigned short  NumDefs;       // Num of args that are definitions.
124   unsigned short  SchedClass;    // enum identifying instr sched class
125   const char *    Name;          // Name of the instruction record in td file.
126   unsigned        Flags;         // flags identifying machine instr class
127   unsigned        TSFlags;       // Target Specific Flag values
128   const unsigned *ImplicitUses;  // Registers implicitly read by this instr
129   const unsigned *ImplicitDefs;  // Registers implicitly defined by this instr
130   const TargetOperandInfo *OpInfo; // 'NumOperands' entries about operands.
131
132   /// getOperandConstraint - Returns the value of the specific constraint if
133   /// it is set. Returns -1 if it is not set.
134   int getOperandConstraint(unsigned OpNum,
135                            TOI::OperandConstraint Constraint) const {
136     assert((OpNum < NumOperands || isVariadic()) &&
137            "Invalid operand # of TargetInstrInfo");
138     if (OpNum < NumOperands &&
139         (OpInfo[OpNum].Constraints & (1 << Constraint))) {
140       unsigned Pos = 16 + Constraint * 4;
141       return (int)(OpInfo[OpNum].Constraints >> Pos) & 0xf;
142     }
143     return -1;
144   }
145
146   /// findTiedToSrcOperand - Returns the operand that is tied to the specified
147   /// dest operand. Returns -1 if there isn't one.
148   int findTiedToSrcOperand(unsigned OpNum) const;
149   
150   /// getName - Return the name of the record in the .td file for this
151   /// instruction, for example "ADD8ri".
152   const char *getName() const {
153     return Name;
154   }
155   
156   /// getNumOperands - Return the number of declared MachineOperands for this
157   /// MachineInstruction.  Note that variadic (isVariadic() returns true)
158   /// instructions may have additional operands at the end of the list, and note
159   /// that the machine instruction may include implicit register def/uses as
160   /// well.
161   unsigned getNumOperands() const {
162     return NumOperands;
163   }
164   
165   /// getNumDefs - Return the number of MachineOperands that are register
166   /// definitions.  Register definitions always occur at the start of the 
167   /// machine operand list.  This is the number of "outs" in the .td file.
168   unsigned getNumDefs() const {
169     return NumDefs;
170   }
171   
172   /// isVariadic - Return true if this instruction can have a variable number of
173   /// operands.  In this case, the variable operands will be after the normal
174   /// operands but before the implicit definitions and uses (if any are
175   /// present).
176   bool isVariadic() const {
177     return Flags & (1 << TID::Variadic);
178   }
179   
180   /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
181   /// ARM instructions which can set condition code if 's' bit is set.
182   bool hasOptionalDef() const {
183     return Flags & (1 << TID::HasOptionalDef);
184   }
185   
186   /// getImplicitUses - Return a list of machine operands that are potentially
187   /// read by any instance of this machine instruction.  For example, on X86,
188   /// the "adc" instruction adds two register operands and adds the carry bit in
189   /// from the flags register.  In this case, the instruction is marked as
190   /// implicitly reading the flags.  Likewise, the variable shift instruction on
191   /// X86 is marked as implicitly reading the 'CL' register, which it always
192   /// does.
193   ///
194   /// This method returns null if the instruction has no implicit uses.
195   const unsigned *getImplicitUses() const {
196     return ImplicitUses;
197   }
198   
199   /// getImplicitDefs - Return a list of machine operands that are potentially
200   /// written by any instance of this machine instruction.  For example, on X86,
201   /// many instructions implicitly set the flags register.  In this case, they
202   /// are marked as setting the FLAGS.  Likewise, many instructions always
203   /// deposit their result in a physical register.  For example, the X86 divide
204   /// instruction always deposits the quotient and remainder in the EAX/EDX
205   /// registers.  For that instruction, this will return a list containing the
206   /// EAX/EDX/EFLAGS registers.
207   ///
208   /// This method returns null if the instruction has no implicit uses.
209   const unsigned *getImplicitDefs() const {
210     return ImplicitDefs;
211   }
212
213   /// getSchedClass - Return the scheduling class for this instruction.  The
214   /// scheduling class is an index into the InstrItineraryData table.  This
215   /// returns zero if there is no known scheduling information for the
216   /// instruction.
217   ///
218   unsigned getSchedClass() const {
219     return SchedClass;
220   }
221   
222   bool isReturn() const {
223     return Flags & (1 << TID::Return);
224   }
225   
226   bool isCall() const {
227     return Flags & (1 << TID::Call);
228   }
229   
230   /// isImplicitDef - Return true if this is an "IMPLICIT_DEF" instruction,
231   /// which defines a register to an unspecified value.  These basically
232   /// correspond to x = undef.
233   bool isImplicitDef() const {
234     return Flags & (1 << TID::ImplicitDef);
235   }
236   
237   /// isBarrier - Returns true if the specified instruction stops control flow
238   /// from executing the instruction immediately following it.  Examples include
239   /// unconditional branches and return instructions.
240   bool isBarrier() const {
241     return Flags & (1 << TID::Barrier);
242   }
243   
244   /// isTerminator - Returns true if this instruction part of the terminator for
245   /// a basic block.  Typically this is things like return and branch
246   /// instructions.
247   ///
248   /// Various passes use this to insert code into the bottom of a basic block,
249   /// but before control flow occurs.
250   bool isTerminator() const {
251     return Flags & (1 << TID::Terminator);
252   }
253   
254   /// isBranch - Returns true if this is a conditional, unconditional, or
255   /// indirect branch.  Predicates below can be used to discriminate between
256   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
257   /// get more information.
258   bool isBranch() const {
259     return Flags & (1 << TID::Branch);
260   }
261
262   /// isIndirectBranch - Return true if this is an indirect branch, such as a
263   /// branch through a register.
264   bool isIndirectBranch() const {
265     return Flags & (1 << TID::IndirectBranch);
266   }
267   
268   /// isConditionalBranch - Return true if this is a branch which may fall
269   /// through to the next instruction or may transfer control flow to some other
270   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
271   /// information about this branch.
272   bool isConditionalBranch() const {
273     return isBranch() & !isBarrier() & !isIndirectBranch();
274   }
275   
276   /// isUnconditionalBranch - Return true if this is a branch which always
277   /// transfers control flow to some other block.  The
278   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
279   /// about this branch.
280   bool isUnconditionalBranch() const {
281     return isBranch() & isBarrier() & !isIndirectBranch();
282   }
283   
284   // isPredicable - Return true if this instruction has a predicate operand that
285   // controls execution.  It may be set to 'always', or may be set to other
286   /// values.   There are various methods in TargetInstrInfo that can be used to
287   /// control and modify the predicate in this instruction.
288   bool isPredicable() const {
289     return Flags & (1 << TID::Predicable);
290   }
291   
292   /// isNotDuplicable - Return true if this instruction cannot be safely
293   /// duplicated.  For example, if the instruction has a unique labels attached
294   /// to it, duplicating it would cause multiple definition errors.
295   bool isNotDuplicable() const {
296     return Flags & (1 << TID::NotDuplicable);
297   }
298   
299   /// hasDelaySlot - Returns true if the specified instruction has a delay slot
300   /// which must be filled by the code generator.
301   bool hasDelaySlot() const {
302     return Flags & (1 << TID::DelaySlot);
303   }
304   
305   /// isSimpleLoad - Return true for instructions that are simple loads from
306   /// memory.  This should only be set on instructions that load a value from
307   /// memory and return it in their only virtual register definition.
308   /// Instructions that return a value loaded from memory and then modified in
309   /// some way should not return true for this.
310   bool isSimpleLoad() const {
311     return Flags & (1 << TID::SimpleLoad);
312   }
313   
314   //===--------------------------------------------------------------------===//
315   // Side Effect Analysis
316   //===--------------------------------------------------------------------===//
317   
318   /// mayStore - Return true if this instruction could possibly modify memory.
319   /// Instructions with this flag set are not necessarily simple store
320   /// instructions, they may store a modified value based on their operands, or
321   /// may not actually modify anything, for example.
322   bool mayStore() const {
323     return Flags & (1 << TID::MayStore);
324   }
325   
326   // TODO: mayLoad.
327   
328   /// hasNoSideEffects - Return true if all instances of this instruction are
329   /// guaranteed to have no side effects other than:
330   ///   1. The register operands that are def/used by the MachineInstr.
331   ///   2. Registers that are implicitly def/used by the MachineInstr.
332   ///   3. Memory Accesses captured by mayLoad() or mayStore().
333   ///
334   /// Examples of other side effects would be calling a function, modifying
335   /// 'invisible' machine state like a control register, etc.
336   ///
337   /// If some instances of this instruction are side-effect free but others are
338   /// not, the hasConditionalSideEffects() property should return true, not this
339   /// one.
340   ///
341   /// Note that you should not call this method directly, instead, call the
342   /// TargetInstrInfo::hasUnmodelledSideEffects method, which handles analysis
343   /// of the machine instruction.
344   bool hasNoSideEffects() const {
345     return Flags & (1 << TID::NeverHasSideEffects);
346   }
347   
348   /// hasConditionalSideEffects - Return true if some instances of this
349   /// instruction are guaranteed to have no side effects other than those listed
350   /// for hasNoSideEffects().  To determine whether a specific machineinstr has
351   /// side effects, the TargetInstrInfo::isReallySideEffectFree virtual method
352   /// is invoked to decide.
353   ///
354   /// Note that you should not call this method directly, instead, call the
355   /// TargetInstrInfo::hasUnmodelledSideEffects method, which handles analysis
356   /// of the machine instruction.
357   bool hasConditionalSideEffects() const {
358     return Flags & (1 << TID::MayHaveSideEffects);
359   }
360   
361   //===--------------------------------------------------------------------===//
362   // Flags that indicate whether an instruction can be modified by a method.
363   //===--------------------------------------------------------------------===//
364   
365   /// isCommutable - Return true if this may be a 2- or 3-address
366   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
367   /// result if Y and Z are exchanged.  If this flag is set, then the 
368   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
369   /// instruction.
370   ///
371   /// Note that this flag may be set on instructions that are only commutable
372   /// sometimes.  In these cases, the call to commuteInstruction will fail.
373   /// Also note that some instructions require non-trivial modification to
374   /// commute them.
375   bool isCommutable() const {
376     return Flags & (1 << TID::Commutable);
377   }
378   
379   /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
380   /// which can be changed into a 3-address instruction if needed.  Doing this
381   /// transformation can be profitable in the register allocator, because it
382   /// means that the instruction can use a 2-address form if possible, but
383   /// degrade into a less efficient form if the source and dest register cannot
384   /// be assigned to the same register.  For example, this allows the x86
385   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
386   /// is the same speed as the shift but has bigger code size.
387   ///
388   /// If this returns true, then the target must implement the
389   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
390   /// is allowed to fail if the transformation isn't valid for this specific
391   /// instruction (e.g. shl reg, 4 on x86).
392   ///
393   bool isConvertibleTo3Addr() const {
394     return Flags & (1 << TID::ConvertibleTo3Addr);
395   }
396   
397   /// usesCustomDAGSchedInsertionHook - Return true if this instruction requires
398   /// custom insertion support when the DAG scheduler is inserting it into a
399   /// machine basic block.  If this is true for the instruction, it basically
400   /// means that it is a pseudo instruction used at SelectionDAG time that is 
401   /// expanded out into magic code by the target when MachineInstrs are formed.
402   ///
403   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
404   /// is used to insert this into the MachineBasicBlock.
405   bool usesCustomDAGSchedInsertionHook() const {
406     return Flags & (1 << TID::UsesCustomDAGSchedInserter);
407   }
408   
409   /// isRematerializable - Returns true if this instruction is a candidate for
410   /// remat.  This flag is deprecated, please don't use it anymore.  If this
411   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
412   /// verify the instruction is really rematable.
413   bool isRematerializable() const {
414     return Flags & (1 << TID::Rematerializable);
415   }
416 };
417
418
419 //---------------------------------------------------------------------------
420 ///
421 /// TargetInstrInfo - Interface to description of machine instructions
422 ///
423 class TargetInstrInfo {
424   const TargetInstrDescriptor* desc;    // raw array to allow static init'n
425   unsigned NumOpcodes;                  // number of entries in the desc array
426   unsigned numRealOpCodes;              // number of non-dummy op codes
427
428   TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
429   void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
430 public:
431   TargetInstrInfo(const TargetInstrDescriptor *desc, unsigned NumOpcodes);
432   virtual ~TargetInstrInfo();
433
434   // Invariant opcodes: All instruction sets have these as their low opcodes.
435   enum { 
436     PHI = 0,
437     INLINEASM = 1,
438     LABEL = 2,
439     EXTRACT_SUBREG = 3,
440     INSERT_SUBREG = 4
441   };
442
443   unsigned getNumOpcodes() const { return NumOpcodes; }
444
445   /// get - Return the machine instruction descriptor that corresponds to the
446   /// specified instruction opcode.
447   ///
448   const TargetInstrDescriptor& get(unsigned Opcode) const {
449     assert(Opcode < NumOpcodes);
450     return desc[Opcode];
451   }
452
453   /// isTriviallyReMaterializable - Return true if the instruction is trivially
454   /// rematerializable, meaning it has no side effects and requires no operands
455   /// that aren't always available.
456   bool isTriviallyReMaterializable(MachineInstr *MI) const {
457     return MI->getDesc()->isRematerializable() &&
458            isReallyTriviallyReMaterializable(MI);
459   }
460
461   /// hasUnmodelledSideEffects - Returns true if the instruction has side
462   /// effects that are not captured by any operands of the instruction or other
463   /// flags.
464   bool hasUnmodelledSideEffects(MachineInstr *MI) const {
465     const TargetInstrDescriptor *TID = MI->getDesc();
466     if (TID->hasNoSideEffects()) return false;
467     if (!TID->hasConditionalSideEffects()) return true;
468     return !isReallySideEffectFree(MI); // May have side effects
469   }
470 protected:
471   /// isReallyTriviallyReMaterializable - For instructions with opcodes for
472   /// which the M_REMATERIALIZABLE flag is set, this function tests whether the
473   /// instruction itself is actually trivially rematerializable, considering
474   /// its operands.  This is used for targets that have instructions that are
475   /// only trivially rematerializable for specific uses.  This predicate must
476   /// return false if the instruction has any side effects other than
477   /// producing a value, or if it requres any address registers that are not
478   /// always available.
479   virtual bool isReallyTriviallyReMaterializable(MachineInstr *MI) const {
480     return true;
481   }
482
483   /// isReallySideEffectFree - If the M_MAY_HAVE_SIDE_EFFECTS flag is set, this
484   /// method is called to determine if the specific instance of this
485   /// instruction has side effects. This is useful in cases of instructions,
486   /// like loads, which generally always have side effects. A load from a
487   /// constant pool doesn't have side effects, though. So we need to
488   /// differentiate it from the general case.
489   virtual bool isReallySideEffectFree(MachineInstr *MI) const {
490     return false;
491   }
492 public:
493   /// getOperandConstraint - Returns the value of the specific constraint if
494   /// it is set. Returns -1 if it is not set.
495   int getOperandConstraint(unsigned Opcode, unsigned OpNum,
496                            TOI::OperandConstraint Constraint) const {
497     return get(Opcode).getOperandConstraint(OpNum, Constraint);
498   }
499
500   /// Return true if the instruction is a register to register move
501   /// and leave the source and dest operands in the passed parameters.
502   virtual bool isMoveInstr(const MachineInstr& MI,
503                            unsigned& sourceReg,
504                            unsigned& destReg) const {
505     return false;
506   }
507   
508   /// isLoadFromStackSlot - If the specified machine instruction is a direct
509   /// load from a stack slot, return the virtual or physical register number of
510   /// the destination along with the FrameIndex of the loaded stack slot.  If
511   /// not, return 0.  This predicate must return 0 if the instruction has
512   /// any side effects other than loading from the stack slot.
513   virtual unsigned isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
514     return 0;
515   }
516   
517   /// isStoreToStackSlot - If the specified machine instruction is a direct
518   /// store to a stack slot, return the virtual or physical register number of
519   /// the source reg along with the FrameIndex of the loaded stack slot.  If
520   /// not, return 0.  This predicate must return 0 if the instruction has
521   /// any side effects other than storing to the stack slot.
522   virtual unsigned isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
523     return 0;
524   }
525
526   /// convertToThreeAddress - This method must be implemented by targets that
527   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
528   /// may be able to convert a two-address instruction into one or more true
529   /// three-address instructions on demand.  This allows the X86 target (for
530   /// example) to convert ADD and SHL instructions into LEA instructions if they
531   /// would require register copies due to two-addressness.
532   ///
533   /// This method returns a null pointer if the transformation cannot be
534   /// performed, otherwise it returns the last new instruction.
535   ///
536   virtual MachineInstr *
537   convertToThreeAddress(MachineFunction::iterator &MFI,
538                    MachineBasicBlock::iterator &MBBI, LiveVariables &LV) const {
539     return 0;
540   }
541
542   /// commuteInstruction - If a target has any instructions that are commutable,
543   /// but require converting to a different instruction or making non-trivial
544   /// changes to commute them, this method can overloaded to do this.  The
545   /// default implementation of this method simply swaps the first two operands
546   /// of MI and returns it.
547   ///
548   /// If a target wants to make more aggressive changes, they can construct and
549   /// return a new machine instruction.  If an instruction cannot commute, it
550   /// can also return null.
551   ///
552   virtual MachineInstr *commuteInstruction(MachineInstr *MI) const = 0;
553
554   /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
555   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
556   /// implemented for a target).  Upon success, this returns false and returns
557   /// with the following information in various cases:
558   ///
559   /// 1. If this block ends with no branches (it just falls through to its succ)
560   ///    just return false, leaving TBB/FBB null.
561   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
562   ///    the destination block.
563   /// 3. If this block ends with an conditional branch and it falls through to
564   ///    an successor block, it sets TBB to be the branch destination block and a
565   ///    list of operands that evaluate the condition. These
566   ///    operands can be passed to other TargetInstrInfo methods to create new
567   ///    branches.
568   /// 4. If this block ends with an conditional branch and an unconditional
569   ///    block, it returns the 'true' destination in TBB, the 'false' destination
570   ///    in FBB, and a list of operands that evaluate the condition. These
571   ///    operands can be passed to other TargetInstrInfo methods to create new
572   ///    branches.
573   ///
574   /// Note that RemoveBranch and InsertBranch must be implemented to support
575   /// cases where this method returns success.
576   ///
577   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
578                              MachineBasicBlock *&FBB,
579                              std::vector<MachineOperand> &Cond) const {
580     return true;
581   }
582   
583   /// RemoveBranch - Remove the branching code at the end of the specific MBB.
584   /// this is only invoked in cases where AnalyzeBranch returns success. It
585   /// returns the number of instructions that were removed.
586   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
587     assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!"); 
588     return 0;
589   }
590   
591   /// InsertBranch - Insert a branch into the end of the specified
592   /// MachineBasicBlock.  This operands to this method are the same as those
593   /// returned by AnalyzeBranch.  This is invoked in cases where AnalyzeBranch
594   /// returns success and when an unconditional branch (TBB is non-null, FBB is
595   /// null, Cond is empty) needs to be inserted. It returns the number of
596   /// instructions inserted.
597   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
598                             MachineBasicBlock *FBB,
599                             const std::vector<MachineOperand> &Cond) const {
600     assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!"); 
601     return 0;
602   }
603   
604   /// copyRegToReg - Add a copy between a pair of registers
605   virtual void copyRegToReg(MachineBasicBlock &MBB,
606                             MachineBasicBlock::iterator MI,
607                             unsigned DestReg, unsigned SrcReg,
608                             const TargetRegisterClass *DestRC,
609                             const TargetRegisterClass *SrcRC) const {
610     assert(0 && "Target didn't implement TargetInstrInfo::copyRegToReg!");
611   }
612   
613   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
614                                    MachineBasicBlock::iterator MI,
615                                    unsigned SrcReg, bool isKill, int FrameIndex,
616                                    const TargetRegisterClass *RC) const {
617     assert(0 && "Target didn't implement TargetInstrInfo::storeRegToStackSlot!");
618   }
619
620   virtual void storeRegToAddr(MachineFunction &MF, unsigned SrcReg, bool isKill,
621                               SmallVectorImpl<MachineOperand> &Addr,
622                               const TargetRegisterClass *RC,
623                               SmallVectorImpl<MachineInstr*> &NewMIs) const {
624     assert(0 && "Target didn't implement TargetInstrInfo::storeRegToAddr!");
625   }
626
627   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
628                                     MachineBasicBlock::iterator MI,
629                                     unsigned DestReg, int FrameIndex,
630                                     const TargetRegisterClass *RC) const {
631     assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromStackSlot!");
632   }
633
634   virtual void loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
635                                SmallVectorImpl<MachineOperand> &Addr,
636                                const TargetRegisterClass *RC,
637                                SmallVectorImpl<MachineInstr*> &NewMIs) const {
638     assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromAddr!");
639   }
640   
641   /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
642   /// saved registers and returns true if it isn't possible / profitable to do
643   /// so by issuing a series of store instructions via
644   /// storeRegToStackSlot(). Returns false otherwise.
645   virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
646                                          MachineBasicBlock::iterator MI,
647                                 const std::vector<CalleeSavedInfo> &CSI) const {
648     return false;
649   }
650
651   /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
652   /// saved registers and returns true if it isn't possible / profitable to do
653   /// so by issuing a series of load instructions via loadRegToStackSlot().
654   /// Returns false otherwise.
655   virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
656                                            MachineBasicBlock::iterator MI,
657                                 const std::vector<CalleeSavedInfo> &CSI) const {
658     return false;
659   }
660   
661   /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
662   /// slot into the specified machine instruction for the specified operand(s).
663   /// If this is possible, a new instruction is returned with the specified
664   /// operand folded, otherwise NULL is returned. The client is responsible for
665   /// removing the old instruction and adding the new one in the instruction
666   /// stream.
667   virtual MachineInstr* foldMemoryOperand(MachineInstr* MI,
668                                           SmallVectorImpl<unsigned> &Ops,
669                                           int FrameIndex) const {
670     return 0;
671   }
672
673   /// foldMemoryOperand - Same as the previous version except it allows folding
674   /// of any load and store from / to any address, not just from a specific
675   /// stack slot.
676   virtual MachineInstr* foldMemoryOperand(MachineInstr* MI,
677                                           SmallVectorImpl<unsigned> &Ops,
678                                           MachineInstr* LoadMI) const {
679     return 0;
680   }
681
682   /// canFoldMemoryOperand - Returns true if the specified load / store is
683   /// folding is possible.
684   virtual
685   bool canFoldMemoryOperand(MachineInstr *MI,
686                             SmallVectorImpl<unsigned> &Ops) const{
687     return false;
688   }
689
690   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
691   /// a store or a load and a store into two or more instruction. If this is
692   /// possible, returns true as well as the new instructions by reference.
693   virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
694                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
695                                   SmallVectorImpl<MachineInstr*> &NewMIs) const{
696     return false;
697   }
698
699   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
700                                    SmallVectorImpl<SDNode*> &NewNodes) const {
701     return false;
702   }
703
704   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
705   /// instruction after load / store are unfolded from an instruction of the
706   /// specified opcode. It returns zero if the specified unfolding is not
707   /// possible.
708   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
709                                       bool UnfoldLoad, bool UnfoldStore) const {
710     return 0;
711   }
712   
713   /// BlockHasNoFallThrough - Return true if the specified block does not
714   /// fall-through into its successor block.  This is primarily used when a
715   /// branch is unanalyzable.  It is useful for things like unconditional
716   /// indirect branches (jump tables).
717   virtual bool BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
718     return false;
719   }
720   
721   /// ReverseBranchCondition - Reverses the branch condition of the specified
722   /// condition list, returning false on success and true if it cannot be
723   /// reversed.
724   virtual bool ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
725     return true;
726   }
727   
728   /// insertNoop - Insert a noop into the instruction stream at the specified
729   /// point.
730   virtual void insertNoop(MachineBasicBlock &MBB, 
731                           MachineBasicBlock::iterator MI) const {
732     assert(0 && "Target didn't implement insertNoop!");
733     abort();
734   }
735
736   /// isPredicated - Returns true if the instruction is already predicated.
737   ///
738   virtual bool isPredicated(const MachineInstr *MI) const {
739     return false;
740   }
741
742   /// isUnpredicatedTerminator - Returns true if the instruction is a
743   /// terminator instruction that has not been predicated.
744   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
745
746   /// PredicateInstruction - Convert the instruction into a predicated
747   /// instruction. It returns true if the operation was successful.
748   virtual
749   bool PredicateInstruction(MachineInstr *MI,
750                             const std::vector<MachineOperand> &Pred) const = 0;
751
752   /// SubsumesPredicate - Returns true if the first specified predicate
753   /// subsumes the second, e.g. GE subsumes GT.
754   virtual
755   bool SubsumesPredicate(const std::vector<MachineOperand> &Pred1,
756                          const std::vector<MachineOperand> &Pred2) const {
757     return false;
758   }
759
760   /// DefinesPredicate - If the specified instruction defines any predicate
761   /// or condition code register(s) used for predication, returns true as well
762   /// as the definition predicate(s) by reference.
763   virtual bool DefinesPredicate(MachineInstr *MI,
764                                 std::vector<MachineOperand> &Pred) const {
765     return false;
766   }
767
768   /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
769   /// values.
770   virtual const TargetRegisterClass *getPointerRegClass() const {
771     assert(0 && "Target didn't implement getPointerRegClass!");
772     abort();
773     return 0; // Must return a value in order to compile with VS 2005
774   }
775 };
776
777 /// TargetInstrInfoImpl - This is the default implementation of
778 /// TargetInstrInfo, which just provides a couple of default implementations
779 /// for various methods.  This separated out because it is implemented in
780 /// libcodegen, not in libtarget.
781 class TargetInstrInfoImpl : public TargetInstrInfo {
782 protected:
783   TargetInstrInfoImpl(const TargetInstrDescriptor *desc, unsigned NumOpcodes)
784   : TargetInstrInfo(desc, NumOpcodes) {}
785 public:
786   virtual MachineInstr *commuteInstruction(MachineInstr *MI) const;
787   virtual bool PredicateInstruction(MachineInstr *MI,
788                               const std::vector<MachineOperand> &Pred) const;
789   
790 };
791
792 } // End llvm namespace
793
794 #endif