Add capability to have a MachineBasicBlock as an operand to a MachineInstr
[oota-llvm.git] / include / llvm / CodeGen / MachineInstr.h
1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*--=//
2 //
3 // This file contains the declaration of the MachineInstr class, which is the
4 // basic representation for all target dependant machine instructions used by
5 // the back end.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
10 #define LLVM_CODEGEN_MACHINEINSTR_H
11
12 #include "llvm/Annotation.h"
13 #include "llvm/Target/MRegisterInfo.h"
14 #include "Support/iterator"
15 #include "Support/NonCopyable.h"
16 #include <vector>
17 class Value;
18 class Function;
19 class MachineBasicBlock;
20 class TargetMachine;
21
22 typedef int MachineOpCode;
23
24 /// MOTy - MachineOperandType - This namespace contains an enum that describes
25 /// how the machine operand is used by the instruction: is it read, defined, or
26 /// both?  Note that the MachineInstr/Operator class currently uses bool
27 /// arguments to represent this information instead of an enum.  Eventually this
28 /// should change over to use this _easier to read_ representation instead.
29 ///
30 namespace MOTy {
31   enum UseType {
32     Use,             /// This machine operand is only read by the instruction
33     Def,             /// This machine operand is only written by the instruction
34     UseAndDef        /// This machine operand is read AND written
35   };
36 }
37
38 //---------------------------------------------------------------------------
39 // class MachineOperand 
40 // 
41 // Purpose:
42 //   Representation of each machine instruction operand.
43 //   This class is designed so that you can allocate a vector of operands
44 //   first and initialize each one later.
45 //
46 //   E.g, for this VM instruction:
47 //              ptr = alloca type, numElements
48 //   we generate 2 machine instructions on the SPARC:
49 // 
50 //              mul Constant, Numelements -> Reg
51 //              add %sp, Reg -> Ptr
52 // 
53 //   Each instruction has 3 operands, listed above.  Of those:
54 //   -  Reg, NumElements, and Ptr are of operand type MO_Register.
55 //   -  Constant is of operand type MO_SignExtendedImmed on the SPARC.
56 //      
57 //   For the register operands, the virtual register type is as follows:
58 //      
59 //   -  Reg will be of virtual register type MO_MInstrVirtualReg.  The field
60 //      MachineInstr* minstr will point to the instruction that computes reg.
61 // 
62 //   -  %sp will be of virtual register type MO_MachineReg.
63 //      The field regNum identifies the machine register.
64 // 
65 //   -  NumElements will be of virtual register type MO_VirtualReg.
66 //      The field Value* value identifies the value.
67 // 
68 //   -  Ptr will also be of virtual register type MO_VirtualReg.
69 //      Again, the field Value* value identifies the value.
70 // 
71 //---------------------------------------------------------------------------
72
73 class MachineOperand {
74 public:
75   enum MachineOperandType {
76     MO_VirtualRegister,         // virtual register for *value
77     MO_MachineRegister,         // pre-assigned machine register `regNum'
78     MO_CCRegister,
79     MO_SignExtendedImmed,
80     MO_UnextendedImmed,
81     MO_PCRelativeDisp,
82     MO_MachineBasicBlock,       // MachineBasicBlock reference
83   };
84   
85 private:
86   // Bit fields of the flags variable used for different operand properties
87   static const char DEFFLAG    = 0x1;  // this is a def of the operand
88   static const char DEFUSEFLAG = 0x2;  // this is both a def and a use
89   static const char HIFLAG32   = 0x4;  // operand is %hi32(value_or_immedVal)
90   static const char LOFLAG32   = 0x8;  // operand is %lo32(value_or_immedVal)
91   static const char HIFLAG64   = 0x10; // operand is %hi64(value_or_immedVal)
92   static const char LOFLAG64   = 0x20; // operand is %lo64(value_or_immedVal)
93   
94 private:
95   union {
96     Value*      value;          // BasicBlockVal for a label operand.
97                                 // ConstantVal for a non-address immediate.
98                                 // Virtual register for an SSA operand,
99                                 // including hidden operands required for
100                                 // the generated machine code.     
101     int64_t immedVal;           // constant value for an explicit constant
102
103     MachineBasicBlock *MBB;     // For MO_MachineBasicBlock type
104   };
105
106   char flags;                   // see bit field definitions above
107   MachineOperandType opType:8;  // Pack into 8 bits efficiently after flags.
108   int regNum;                   // register number for an explicit register
109                                 // will be set for a value after reg allocation
110 private:
111   MachineOperand()
112     : immedVal(0),
113       flags(0),
114       opType(MO_VirtualRegister),
115       regNum(-1) {}
116
117   MachineOperand(int64_t ImmVal, MachineOperandType OpTy)
118     : immedVal(ImmVal),
119       flags(0),
120       opType(OpTy),
121       regNum(-1) {}
122
123   MachineOperand(int Reg, MachineOperandType OpTy, MOTy::UseType UseTy)
124     : immedVal(0),
125       opType(OpTy),
126       regNum(Reg) {
127     switch (UseTy) {
128     case MOTy::Use:       flags = 0; break;
129     case MOTy::Def:       flags = DEFFLAG; break;
130     case MOTy::UseAndDef: flags = DEFUSEFLAG; break;
131     default: assert(0 && "Invalid value for UseTy!");
132     }
133   }
134
135   MachineOperand(Value *V, MachineOperandType OpTy, MOTy::UseType UseTy) 
136     : value(V), opType(OpTy), regNum(-1) {
137     switch (UseTy) {
138     case MOTy::Use:       flags = 0; break;
139     case MOTy::Def:       flags = DEFFLAG; break;
140     case MOTy::UseAndDef: flags = DEFUSEFLAG; break;
141     default: assert(0 && "Invalid value for UseTy!");
142     }
143   }
144
145   MachineOperand(MachineBasicBlock *mbb)
146     : MBB(mbb), flags(0), opType(MO_MachineBasicBlock), regNum(-1) {}
147
148 public:
149   MachineOperand(const MachineOperand &M)
150     : immedVal(M.immedVal),
151       flags(M.flags),
152       opType(M.opType),
153       regNum(M.regNum) {}
154
155   ~MachineOperand() {}
156   
157   // Accessor methods.  Caller is responsible for checking the
158   // operand type before invoking the corresponding accessor.
159   // 
160   MachineOperandType getType() const { return opType; }
161
162
163   // This is to finally stop caring whether we have a virtual or machine
164   // register -- an easier interface is to simply call both virtual and machine
165   // registers essentially the same, yet be able to distinguish when
166   // necessary. Thus the instruction selector can just add registers without
167   // abandon, and the register allocator won't be confused.
168   bool isVirtualRegister() const {
169     return (opType == MO_VirtualRegister || opType == MO_MachineRegister) 
170       && regNum >= MRegisterInfo::FirstVirtualRegister;
171   }
172   bool isPhysicalRegister() const {
173     return (opType == MO_VirtualRegister || opType == MO_MachineRegister) 
174       && regNum < MRegisterInfo::FirstVirtualRegister;
175   }
176   bool isRegister() const { return isVirtualRegister() || isPhysicalRegister();}
177   bool isMachineRegister() const { return !isVirtualRegister(); }
178   bool isMachineBasicBlock() const { return opType == MO_MachineBasicBlock; }
179   bool isPCRelativeDisp() const { return opType == MO_PCRelativeDisp; }
180   bool isImmediate() const {
181     return opType == MO_SignExtendedImmed || opType == MO_UnextendedImmed;
182   }
183
184   inline Value*         getVRegValue    () const {
185     assert(opType == MO_VirtualRegister || opType == MO_CCRegister || 
186            opType == MO_PCRelativeDisp);
187     return value;
188   }
189   inline Value*         getVRegValueOrNull() const {
190     return (opType == MO_VirtualRegister || opType == MO_CCRegister || 
191             opType == MO_PCRelativeDisp)? value : NULL;
192   }
193   inline int            getMachineRegNum() const {
194     assert(opType == MO_MachineRegister);
195     return regNum;
196   }
197   inline int64_t        getImmedValue   () const {
198     assert(isImmediate());
199     return immedVal;
200   }
201   MachineBasicBlock *getMachineBasicBlock() const {
202     assert(isMachineBasicBlock() && "Can't get MBB in non-MBB operand!");
203     return MBB;
204   }
205
206   bool          opIsDef         () const { return flags & DEFFLAG; }
207   bool          opIsDefAndUse   () const { return flags & DEFUSEFLAG; }
208   bool          opHiBits32      () const { return flags & HIFLAG32; }
209   bool          opLoBits32      () const { return flags & LOFLAG32; }
210   bool          opHiBits64      () const { return flags & HIFLAG64; }
211   bool          opLoBits64      () const { return flags & LOFLAG64; }
212
213   // used to check if a machine register has been allocated to this operand
214   inline bool   hasAllocatedReg() const {
215     return (regNum >= 0 &&
216             (opType == MO_VirtualRegister || opType == MO_CCRegister || 
217              opType == MO_MachineRegister));
218   }
219
220   // used to get the reg number if when one is allocated
221   inline int  getAllocatedRegNum() const {
222     assert(opType == MO_VirtualRegister || opType == MO_CCRegister || 
223            opType == MO_MachineRegister);
224     return regNum;
225   }
226
227   inline unsigned getReg() const {
228     assert(hasAllocatedReg() && "Cannot call MachineOperand::getReg()!");
229     return regNum;
230   }    
231   
232   friend std::ostream& operator<<(std::ostream& os, const MachineOperand& mop);
233
234 private:
235
236   // Construction methods needed for fine-grain control.
237   // These must be accessed via coresponding methods in MachineInstr.
238   void markHi32()      { flags |= HIFLAG32; }
239   void markLo32()      { flags |= LOFLAG32; }
240   void markHi64()      { flags |= HIFLAG64; }
241   void markLo64()      { flags |= LOFLAG64; }
242   
243   // Replaces the Value with its corresponding physical register after
244   // register allocation is complete
245   void setRegForValue(int reg) {
246     assert(opType == MO_VirtualRegister || opType == MO_CCRegister || 
247            opType == MO_MachineRegister);
248     regNum = reg;
249   }
250   
251   friend class MachineInstr;
252 };
253
254
255 //---------------------------------------------------------------------------
256 // class MachineInstr 
257 // 
258 // Purpose:
259 //   Representation of each machine instruction.
260 // 
261 //   MachineOpCode must be an enum, defined separately for each target.
262 //   E.g., It is defined in SparcInstructionSelection.h for the SPARC.
263 // 
264 //  There are 2 kinds of operands:
265 // 
266 //  (1) Explicit operands of the machine instruction in vector operands[] 
267 // 
268 //  (2) "Implicit operands" are values implicitly used or defined by the
269 //      machine instruction, such as arguments to a CALL, return value of
270 //      a CALL (if any), and return value of a RETURN.
271 //---------------------------------------------------------------------------
272
273 class MachineInstr: public NonCopyable {      // Disable copy operations
274
275   MachineOpCode    opCode;              // the opcode
276   std::vector<MachineOperand> operands; // the operands
277   unsigned numImplicitRefs;             // number of implicit operands
278
279   MachineOperand& getImplicitOp(unsigned i) {
280     assert(i < numImplicitRefs && "implicit ref# out of range!");
281     return operands[i + operands.size() - numImplicitRefs];
282   }
283   const MachineOperand& getImplicitOp(unsigned i) const {
284     assert(i < numImplicitRefs && "implicit ref# out of range!");
285     return operands[i + operands.size() - numImplicitRefs];
286   }
287
288   // regsUsed - all machine registers used for this instruction, including regs
289   // used to save values across the instruction.  This is a bitset of registers.
290   std::vector<bool> regsUsed;
291
292   // OperandComplete - Return true if it's illegal to add a new operand
293   bool OperandsComplete() const;
294
295 public:
296   MachineInstr(MachineOpCode Opcode);
297   MachineInstr(MachineOpCode Opcode, unsigned numOperands);
298
299   /// MachineInstr ctor - This constructor only does a _reserve_ of the
300   /// operands, not a resize for them.  It is expected that if you use this that
301   /// you call add* methods below to fill up the operands, instead of the Set
302   /// methods.  Eventually, the "resizing" ctors will be phased out.
303   ///
304   MachineInstr(MachineOpCode Opcode, unsigned numOperands, bool XX, bool YY);
305
306   /// MachineInstr ctor - Work exactly the same as the ctor above, except that
307   /// the MachineInstr is created and added to the end of the specified basic
308   /// block.
309   ///
310   MachineInstr(MachineBasicBlock *MBB, MachineOpCode Opcode, unsigned numOps);
311   
312
313   /// replace - Support to rewrite a machine instruction in place: for now,
314   /// simply replace() and then set new operands with Set.*Operand methods
315   /// below.
316   /// 
317   void replace(MachineOpCode Opcode, unsigned numOperands);
318   
319   // The opcode.
320   // 
321   const MachineOpCode getOpcode() const { return opCode; }
322   const MachineOpCode getOpCode() const { return opCode; }
323
324   //
325   // Information about explicit operands of the instruction
326   // 
327   unsigned getNumOperands() const { return operands.size() - numImplicitRefs; }
328   
329   const MachineOperand& getOperand(unsigned i) const {
330     assert(i < getNumOperands() && "getOperand() out of range!");
331     return operands[i];
332   }
333   MachineOperand& getOperand(unsigned i) {
334     assert(i < getNumOperands() && "getOperand() out of range!");
335     return operands[i];
336   }
337
338   MachineOperand::MachineOperandType getOperandType(unsigned i) const {
339     return getOperand(i).getType();
340   }
341
342   bool operandIsDefined(unsigned i) const {
343     return getOperand(i).opIsDef();
344   }
345
346   bool operandIsDefinedAndUsed(unsigned i) const {
347     return getOperand(i).opIsDefAndUse();
348   }
349
350   //
351   // Information about implicit operands of the instruction
352   // 
353   unsigned getNumImplicitRefs() const{ return numImplicitRefs; }
354   
355   const Value* getImplicitRef(unsigned i) const {
356     return getImplicitOp(i).getVRegValue();
357   }
358   Value* getImplicitRef(unsigned i) {
359     return getImplicitOp(i).getVRegValue();
360   }
361
362   bool implicitRefIsDefined(unsigned i) const {
363     return getImplicitOp(i).opIsDef();
364   }
365   bool implicitRefIsDefinedAndUsed(unsigned i) const {
366     return getImplicitOp(i).opIsDefAndUse();
367   }
368   inline void addImplicitRef    (Value* V,
369                                  bool isDef=false,bool isDefAndUse=false);
370   inline void setImplicitRef    (unsigned i, Value* V,
371                                  bool isDef=false, bool isDefAndUse=false);
372
373   //
374   // Information about registers used in this instruction
375   // 
376   const std::vector<bool> &getRegsUsed() const { return regsUsed; }
377   
378   // insertUsedReg - Add a register to the Used registers set...
379   void insertUsedReg(unsigned Reg) {
380     if (Reg >= regsUsed.size())
381       regsUsed.resize(Reg+1);
382     regsUsed[Reg] = true;
383   }
384
385   //
386   // Debugging support
387   //
388   void print(std::ostream &OS, const TargetMachine &TM) const;
389   void dump() const;
390   friend std::ostream& operator<<(std::ostream& os, const MachineInstr& minstr);
391
392   //
393   // Define iterators to access the Value operands of the Machine Instruction.
394   // Note that these iterators only enumerate the explicit operands.
395   // begin() and end() are defined to produce these iterators...
396   //
397   template<class _MI, class _V> class ValOpIterator;
398   typedef ValOpIterator<const MachineInstr*,const Value*> const_val_op_iterator;
399   typedef ValOpIterator<      MachineInstr*,      Value*> val_op_iterator;
400
401   // Access to set the operands when building the machine instruction
402   // 
403   void SetMachineOperandVal     (unsigned i,
404                                  MachineOperand::MachineOperandType operandType,
405                                  Value* V,
406                                  bool isDef=false,
407                                  bool isDefAndUse=false);
408
409   void SetMachineOperandConst   (unsigned i,
410                                  MachineOperand::MachineOperandType operandType,
411                                  int64_t intValue);
412
413   void SetMachineOperandReg     (unsigned i,
414                                  int regNum,
415                                  bool isDef=false);
416
417   //===--------------------------------------------------------------------===//
418   // Accessors to add operands when building up machine instructions
419   //
420
421   /// addRegOperand - Add a MO_VirtualRegister operand to the end of the
422   /// operands list...
423   ///
424   void addRegOperand(Value *V, bool isDef, bool isDefAndUse=false) {
425     assert(!OperandsComplete() &&
426            "Trying to add an operand to a machine instr that is already done!");
427     operands.push_back(MachineOperand(V, MachineOperand::MO_VirtualRegister,
428              !isDef ? MOTy::Use : (isDefAndUse ? MOTy::UseAndDef : MOTy::Def)));
429   }
430
431   void addRegOperand(Value *V, MOTy::UseType UTy = MOTy::Use) {
432     assert(!OperandsComplete() &&
433            "Trying to add an operand to a machine instr that is already done!");
434     operands.push_back(MachineOperand(V, MachineOperand::MO_VirtualRegister,
435                                       UTy));
436   }
437
438   /// addRegOperand - Add a symbolic virtual register reference...
439   ///
440   void addRegOperand(int reg, bool isDef) {
441     assert(!OperandsComplete() &&
442            "Trying to add an operand to a machine instr that is already done!");
443     operands.push_back(MachineOperand(reg, MachineOperand::MO_VirtualRegister,
444                                       isDef ? MOTy::Def : MOTy::Use));
445   }
446
447   /// addRegOperand - Add a symbolic virtual register reference...
448   ///
449   void addRegOperand(int reg, MOTy::UseType UTy = MOTy::Use) {
450     assert(!OperandsComplete() &&
451            "Trying to add an operand to a machine instr that is already done!");
452     operands.push_back(MachineOperand(reg, MachineOperand::MO_VirtualRegister,
453                                       UTy));
454   }
455
456   /// addPCDispOperand - Add a PC relative displacement operand to the MI
457   ///
458   void addPCDispOperand(Value *V) {
459     assert(!OperandsComplete() &&
460            "Trying to add an operand to a machine instr that is already done!");
461     operands.push_back(MachineOperand(V, MachineOperand::MO_PCRelativeDisp,
462                                       MOTy::Use));
463   }
464
465   /// addMachineRegOperand - Add a virtual register operand to this MachineInstr
466   ///
467   void addMachineRegOperand(int reg, bool isDef) {
468     assert(!OperandsComplete() &&
469            "Trying to add an operand to a machine instr that is already done!");
470     operands.push_back(MachineOperand(reg, MachineOperand::MO_MachineRegister,
471                                       isDef ? MOTy::Def : MOTy::Use));
472     insertUsedReg(reg);
473   }
474
475   /// addMachineRegOperand - Add a virtual register operand to this MachineInstr
476   ///
477   void addMachineRegOperand(int reg, MOTy::UseType UTy = MOTy::Use) {
478     assert(!OperandsComplete() &&
479            "Trying to add an operand to a machine instr that is already done!");
480     operands.push_back(MachineOperand(reg, MachineOperand::MO_MachineRegister,
481                                       UTy));
482     insertUsedReg(reg);
483   }
484
485   /// addZeroExtImmOperand - Add a zero extended constant argument to the
486   /// machine instruction.
487   ///
488   void addZeroExtImmOperand(int64_t intValue) {
489     assert(!OperandsComplete() &&
490            "Trying to add an operand to a machine instr that is already done!");
491     operands.push_back(MachineOperand(intValue,
492                                       MachineOperand::MO_UnextendedImmed));
493   }
494
495   /// addSignExtImmOperand - Add a zero extended constant argument to the
496   /// machine instruction.
497   ///
498   void addSignExtImmOperand(int64_t intValue) {
499     assert(!OperandsComplete() &&
500            "Trying to add an operand to a machine instr that is already done!");
501     operands.push_back(MachineOperand(intValue,
502                                       MachineOperand::MO_SignExtendedImmed));
503   }
504
505   void addMachineBasicBlockOperand(MachineBasicBlock *MBB) {
506     assert(!OperandsComplete() &&
507            "Trying to add an operand to a machine instr that is already done!");
508     operands.push_back(MachineOperand(MBB));
509   }
510
511   unsigned substituteValue(const Value* oldVal, Value* newVal,
512                            bool defsOnly = true);
513
514   void setOperandHi32(unsigned i) { operands[i].markHi32(); }
515   void setOperandLo32(unsigned i) { operands[i].markLo32(); }
516   void setOperandHi64(unsigned i) { operands[i].markHi64(); }
517   void setOperandLo64(unsigned i) { operands[i].markLo64(); }
518   
519   
520   // SetRegForOperand - Replaces the Value for the operand with its allocated
521   // physical register after register allocation is complete.
522   // 
523   void SetRegForOperand(unsigned i, int regNum);
524
525   //
526   // Iterator to enumerate machine operands.
527   // 
528   template<class MITy, class VTy>
529   class ValOpIterator : public forward_iterator<VTy, ptrdiff_t> {
530     unsigned i;
531     MITy MI;
532     
533     void skipToNextVal() {
534       while (i < MI->getNumOperands() &&
535              !( (MI->getOperandType(i) == MachineOperand::MO_VirtualRegister ||
536                  MI->getOperandType(i) == MachineOperand::MO_CCRegister)
537                 && MI->getOperand(i).getVRegValue() != 0))
538         ++i;
539     }
540   
541     inline ValOpIterator(MITy mi, unsigned I) : i(I), MI(mi) {
542       skipToNextVal();
543     }
544   
545   public:
546     typedef ValOpIterator<MITy, VTy> _Self;
547     
548     inline VTy operator*() const {
549       return MI->getOperand(i).getVRegValue();
550     }
551
552     const MachineOperand &getMachineOperand() const { return MI->getOperand(i);}
553           MachineOperand &getMachineOperand()       { return MI->getOperand(i);}
554
555     inline VTy operator->() const { return operator*(); }
556
557     inline bool isDef()       const { return MI->getOperand(i).opIsDef(); } 
558     inline bool isDefAndUse() const { return MI->getOperand(i).opIsDefAndUse();}
559
560     inline _Self& operator++() { i++; skipToNextVal(); return *this; }
561     inline _Self  operator++(int) { _Self tmp = *this; ++*this; return tmp; }
562
563     inline bool operator==(const _Self &y) const { 
564       return i == y.i;
565     }
566     inline bool operator!=(const _Self &y) const { 
567       return !operator==(y);
568     }
569
570     static _Self begin(MITy MI) {
571       return _Self(MI, 0);
572     }
573     static _Self end(MITy MI) {
574       return _Self(MI, MI->getNumOperands());
575     }
576   };
577
578   // define begin() and end()
579   val_op_iterator begin() { return val_op_iterator::begin(this); }
580   val_op_iterator end()   { return val_op_iterator::end(this); }
581
582   const_val_op_iterator begin() const {
583     return const_val_op_iterator::begin(this);
584   }
585   const_val_op_iterator end() const {
586     return const_val_op_iterator::end(this);
587   }
588 };
589
590
591 // Define here to enable inlining of the functions used.
592 // 
593 void MachineInstr::addImplicitRef(Value* V,
594                                   bool isDef,
595                                   bool isDefAndUse)
596 {
597   ++numImplicitRefs;
598   addRegOperand(V, isDef, isDefAndUse);
599 }
600
601 void MachineInstr::setImplicitRef(unsigned i,
602                                   Value* V,
603                                   bool isDef,
604                                   bool isDefAndUse)
605 {
606   assert(i < getNumImplicitRefs() && "setImplicitRef() out of range!");
607   SetMachineOperandVal(i + getNumOperands(),
608                        MachineOperand::MO_VirtualRegister,
609                        V, isDef, isDefAndUse);
610 }
611
612
613 //---------------------------------------------------------------------------
614 // Debugging Support
615 //---------------------------------------------------------------------------
616
617 std::ostream& operator<<        (std::ostream& os,
618                                  const MachineInstr& minstr);
619
620 std::ostream& operator<<        (std::ostream& os,
621                                  const MachineOperand& mop);
622                                          
623 void PrintMachineInstructions   (const Function *F);
624
625 #endif