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