MachineInstr.h revision 34fb2cad46adb39f3c2cc705fbbf439a383d0f65
1//===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the declaration of the MachineInstr class, which is the
11// basic representation for all target dependent machine instructions used by
12// the back end.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CODEGEN_MACHINEINSTR_H
17#define LLVM_CODEGEN_MACHINEINSTR_H
18
19#include "llvm/ADT/iterator"
20#include "llvm/Support/DataTypes.h"
21#include <vector>
22#include <cassert>
23
24namespace llvm {
25
26class Value;
27class Function;
28class MachineBasicBlock;
29class TargetMachine;
30class GlobalValue;
31
32template <typename T> struct ilist_traits;
33template <typename T> struct ilist;
34
35typedef short MachineOpCode;
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
72struct MachineOperand {
73private:
74  // Bit fields of the flags variable used for different operand properties
75  enum {
76    DEFFLAG     = 0x01,       // this is a def of the operand
77    USEFLAG     = 0x02,       // this is a use of the operand
78    PCRELATIVE  = 0x40        // Operand is relative to PC, not a global address
79  };
80
81public:
82  // UseType - This enum describes how the machine operand is used by
83  // the instruction. Note that the MachineInstr/Operator class
84  // currently uses bool arguments to represent this information
85  // instead of an enum.  Eventually this should change over to use
86  // this _easier to read_ representation instead.
87  //
88  enum UseType {
89    Use = USEFLAG,        /// only read
90    Def = DEFFLAG,        /// only written
91    UseAndDef = Use | Def /// read AND written
92  };
93
94  enum MachineOperandType {
95    MO_VirtualRegister,         // virtual register for *value
96    MO_MachineRegister,         // pre-assigned machine register `regNum'
97    MO_SignExtendedImmed,
98    MO_UnextendedImmed,
99    MO_MachineBasicBlock,       // MachineBasicBlock reference
100    MO_FrameIndex,              // Abstract Stack Frame Index
101    MO_ConstantPoolIndex,       // Address of indexed Constant in Constant Pool
102    MO_JumpTableIndex,          // Address of indexed Jump Table for switch
103    MO_ExternalSymbol,          // Name of external global symbol
104    MO_GlobalAddress            // Address of a global value
105  };
106
107private:
108  union {
109    Value*  value;      // BasicBlockVal for a label operand.
110                        // ConstantVal for a non-address immediate.
111                        // Virtual register for an SSA operand,
112                        //   including hidden operands required for
113                        //   the generated machine code.
114                        // LLVM global for MO_GlobalAddress.
115
116    int64_t immedVal;   // Constant value for an explicit constant
117
118    MachineBasicBlock *MBB;     // For MO_MachineBasicBlock type
119    const char *SymbolName;     // For MO_ExternalSymbol type
120  } contents;
121
122  char flags;                   // see bit field definitions above
123  MachineOperandType opType:8;  // Pack into 8 bits efficiently after flags.
124  union {
125    int regNum;                 // register number for an explicit register
126                                // will be set for a value after reg allocation
127
128    int offset;                 // Offset to address of global or external, only
129                                // valid for MO_GlobalAddress, MO_ExternalSym
130                                // and MO_ConstantPoolIndex
131  } extra;
132
133  void zeroContents () {
134    memset (&contents, 0, sizeof (contents));
135    memset (&extra, 0, sizeof (extra));
136  }
137
138  MachineOperand(int64_t ImmVal = 0,
139        MachineOperandType OpTy = MO_VirtualRegister, int Offset = 0)
140    : flags(0), opType(OpTy) {
141    zeroContents ();
142    contents.immedVal = ImmVal;
143    if (OpTy == MachineOperand::MO_ConstantPoolIndex)
144      extra.offset = Offset;
145    else
146      extra.regNum = -1;
147  }
148
149  MachineOperand(int Reg, MachineOperandType OpTy, UseType UseTy)
150    : flags(UseTy), opType(OpTy) {
151    zeroContents ();
152    extra.regNum = Reg;
153  }
154
155  MachineOperand(Value *V, MachineOperandType OpTy, UseType UseTy,
156                 bool isPCRelative = false)
157    : flags(UseTy | (isPCRelative?PCRELATIVE:0)), opType(OpTy) {
158    assert(OpTy != MachineOperand::MO_GlobalAddress);
159    zeroContents();
160    contents.value = V;
161    extra.regNum = -1;
162  }
163
164  MachineOperand(GlobalValue *V, MachineOperandType OpTy, UseType UseTy,
165                 bool isPCRelative = false, int Offset = 0)
166    : flags(UseTy | (isPCRelative?PCRELATIVE:0)), opType(OpTy) {
167    assert(OpTy == MachineOperand::MO_GlobalAddress);
168    zeroContents ();
169    contents.value = (Value*)V;
170    extra.offset = Offset;
171  }
172
173  MachineOperand(MachineBasicBlock *mbb)
174    : flags(0), opType(MO_MachineBasicBlock) {
175    zeroContents ();
176    contents.MBB = mbb;
177    extra.regNum = -1;
178  }
179
180  MachineOperand(const char *SymName, bool isPCRelative, int Offset)
181    : flags(isPCRelative?PCRELATIVE:0), opType(MO_ExternalSymbol) {
182    zeroContents ();
183    contents.SymbolName = SymName;
184    extra.offset = Offset;
185  }
186
187public:
188  MachineOperand(const MachineOperand &M)
189    : flags(M.flags), opType(M.opType) {
190    zeroContents ();
191    contents = M.contents;
192    extra = M.extra;
193  }
194
195
196  ~MachineOperand() {}
197
198  const MachineOperand &operator=(const MachineOperand &MO) {
199    contents = MO.contents;
200    flags    = MO.flags;
201    opType   = MO.opType;
202    extra    = MO.extra;
203    return *this;
204  }
205
206  /// getType - Returns the MachineOperandType for this operand.
207  ///
208  MachineOperandType getType() const { return opType; }
209
210  /// getUseType - Returns the MachineOperandUseType of this operand.
211  ///
212  UseType getUseType() const { return UseType(flags & (USEFLAG|DEFFLAG)); }
213
214  /// isRegister - Return true if this operand is a register operand.  The X86
215  /// backend currently can't decide whether to use MO_MR or MO_VR to represent
216  /// them, so we accept both.
217  ///
218  /// Note: The sparc backend should not use this method.
219  ///
220  bool isRegister() const {
221    return opType == MO_MachineRegister || opType == MO_VirtualRegister;
222  }
223
224  /// Accessors that tell you what kind of MachineOperand you're looking at.
225  ///
226  bool isMachineBasicBlock() const { return opType == MO_MachineBasicBlock; }
227  bool isImmediate() const {
228    return opType == MO_SignExtendedImmed || opType == MO_UnextendedImmed;
229  }
230  bool isFrameIndex() const { return opType == MO_FrameIndex; }
231  bool isConstantPoolIndex() const { return opType == MO_ConstantPoolIndex; }
232  bool isJumpTableIndex() const { return opType == MO_JumpTableIndex; }
233  bool isGlobalAddress() const { return opType == MO_GlobalAddress; }
234  bool isExternalSymbol() const { return opType == MO_ExternalSymbol; }
235
236  /// getVRegValueOrNull - Get the Value* out of a MachineOperand if it
237  /// has one. This is deprecated and only used by the SPARC v9 backend.
238  ///
239  Value* getVRegValueOrNull() const {
240    return opType == MO_VirtualRegister ? contents.value : NULL;
241  }
242
243  /// MachineOperand accessors that only work on certain types of
244  /// MachineOperand...
245  ///
246  Value* getVRegValue() const {
247    assert(opType == MO_VirtualRegister && "Wrong MachineOperand accessor");
248    return contents.value;
249  }
250  int getMachineRegNum() const {
251    assert(opType == MO_MachineRegister && "Wrong MachineOperand accessor");
252    return extra.regNum;
253  }
254  int64_t getImmedValue() const {
255    assert(isImmediate() && "Wrong MachineOperand accessor");
256    return contents.immedVal;
257  }
258  MachineBasicBlock *getMachineBasicBlock() const {
259    assert(isMachineBasicBlock() && "Wrong MachineOperand accessor");
260    return contents.MBB;
261  }
262  void setMachineBasicBlock(MachineBasicBlock *MBB) {
263    assert(isMachineBasicBlock() && "Wrong MachineOperand accessor");
264    contents.MBB = MBB;
265  }
266  int getFrameIndex() const {
267    assert(isFrameIndex() && "Wrong MachineOperand accessor");
268    return (int)contents.immedVal;
269  }
270  unsigned getConstantPoolIndex() const {
271    assert(isConstantPoolIndex() && "Wrong MachineOperand accessor");
272    return (unsigned)contents.immedVal;
273  }
274  unsigned getJumpTableIndex() const {
275    assert(isJumpTableIndex() && "Wrong MachineOperand accessor");
276    return (unsigned)contents.immedVal;
277  }
278  GlobalValue *getGlobal() const {
279    assert(isGlobalAddress() && "Wrong MachineOperand accessor");
280    return (GlobalValue*)contents.value;
281  }
282  int getOffset() const {
283    assert((isGlobalAddress() || isExternalSymbol() || isConstantPoolIndex()) &&
284        "Wrong MachineOperand accessor");
285    return extra.offset;
286  }
287  const char *getSymbolName() const {
288    assert(isExternalSymbol() && "Wrong MachineOperand accessor");
289    return contents.SymbolName;
290  }
291
292  /// MachineOperand methods for testing that work on any kind of
293  /// MachineOperand...
294  ///
295  bool            isUse           () const { return flags & USEFLAG; }
296  MachineOperand& setUse          ()       { flags |= USEFLAG; return *this; }
297  bool            isDef           () const { return flags & DEFFLAG; }
298  MachineOperand& setDef          ()       { flags |= DEFFLAG; return *this; }
299
300  /// hasAllocatedReg - Returns true iff a machine register has been
301  /// allocated to this operand.
302  ///
303  bool hasAllocatedReg() const {
304    return (extra.regNum >= 0 &&
305            (opType == MO_VirtualRegister || opType == MO_MachineRegister));
306  }
307
308  /// getReg - Returns the register number. It is a runtime error to call this
309  /// if a register is not allocated.
310  ///
311  unsigned getReg() const {
312    assert(hasAllocatedReg());
313    return extra.regNum;
314  }
315
316  /// MachineOperand mutators...
317  ///
318  void setReg(unsigned Reg) {
319    // This method's comment used to say: 'TODO: get rid of this duplicate
320    // code.' It's not clear where the duplication is.
321    assert(hasAllocatedReg() && "This operand cannot have a register number!");
322    extra.regNum = Reg;
323  }
324
325  void setValueReg(Value *val) {
326    assert(getVRegValueOrNull() != 0 && "Original operand must of type Value*");
327    contents.value = val;
328  }
329
330  void setImmedValue(int immVal) {
331    assert(isImmediate() && "Wrong MachineOperand mutator");
332    contents.immedVal = immVal;
333  }
334
335  void setOffset(int Offset) {
336    assert((isGlobalAddress() || isExternalSymbol() || isConstantPoolIndex() ||
337            isJumpTableIndex()) &&
338        "Wrong MachineOperand accessor");
339    extra.offset = Offset;
340  }
341
342  friend std::ostream& operator<<(std::ostream& os, const MachineOperand& mop);
343
344  friend class MachineInstr;
345};
346
347
348//===----------------------------------------------------------------------===//
349// class MachineInstr
350//
351// Purpose:
352//   Representation of each machine instruction.
353//
354//   MachineOpCode must be an enum, defined separately for each target.
355//   E.g., It is defined in SparcInstructionSelection.h for the SPARC.
356//
357//  There are 2 kinds of operands:
358//
359//  (1) Explicit operands of the machine instruction in vector operands[]
360//
361//  (2) "Implicit operands" are values implicitly used or defined by the
362//      machine instruction, such as arguments to a CALL, return value of
363//      a CALL (if any), and return value of a RETURN.
364//===----------------------------------------------------------------------===//
365
366class MachineInstr {
367  short Opcode;                         // the opcode
368  std::vector<MachineOperand> operands; // the operands
369  MachineInstr* prev, *next;            // links for our intrusive list
370  MachineBasicBlock* parent;            // pointer to the owning basic block
371
372  // OperandComplete - Return true if it's illegal to add a new operand
373  bool OperandsComplete() const;
374
375  //Constructor used by clone() method
376  MachineInstr(const MachineInstr&);
377
378  void operator=(const MachineInstr&); // DO NOT IMPLEMENT
379
380  // Intrusive list support
381  //
382  friend struct ilist_traits<MachineInstr>;
383
384public:
385  MachineInstr(short Opcode, unsigned numOperands);
386
387  /// MachineInstr ctor - This constructor only does a _reserve_ of the
388  /// operands, not a resize for them.  It is expected that if you use this that
389  /// you call add* methods below to fill up the operands, instead of the Set
390  /// methods.  Eventually, the "resizing" ctors will be phased out.
391  ///
392  MachineInstr(short Opcode, unsigned numOperands, bool XX, bool YY);
393
394  /// MachineInstr ctor - Work exactly the same as the ctor above, except that
395  /// the MachineInstr is created and added to the end of the specified basic
396  /// block.
397  ///
398  MachineInstr(MachineBasicBlock *MBB, short Opcode, unsigned numOps);
399
400  ~MachineInstr();
401
402  const MachineBasicBlock* getParent() const { return parent; }
403  MachineBasicBlock* getParent() { return parent; }
404
405  /// getOpcode - Returns the opcode of this MachineInstr.
406  ///
407  const int getOpcode() const { return Opcode; }
408
409  /// Access to explicit operands of the instruction.
410  ///
411  unsigned getNumOperands() const { return operands.size(); }
412
413  const MachineOperand& getOperand(unsigned i) const {
414    assert(i < getNumOperands() && "getOperand() out of range!");
415    return operands[i];
416  }
417  MachineOperand& getOperand(unsigned i) {
418    assert(i < getNumOperands() && "getOperand() out of range!");
419    return operands[i];
420  }
421
422
423  /// clone - Create a copy of 'this' instruction that is identical in
424  /// all ways except the the instruction has no parent, prev, or next.
425  MachineInstr* clone() const;
426
427  /// removeFromParent - This method unlinks 'this' from the containing basic
428  /// block, and returns it, but does not delete it.
429  MachineInstr *removeFromParent();
430
431  /// eraseFromParent - This method unlinks 'this' from the containing basic
432  /// block and deletes it.
433  void eraseFromParent() {
434    delete removeFromParent();
435  }
436
437  //
438  // Debugging support
439  //
440  void print(std::ostream &OS, const TargetMachine *TM) const;
441  void dump() const;
442  friend std::ostream& operator<<(std::ostream& os, const MachineInstr& minstr);
443
444  //===--------------------------------------------------------------------===//
445  // Accessors to add operands when building up machine instructions
446  //
447
448  /// addRegOperand - Add a MO_VirtualRegister operand to the end of the
449  /// operands list...
450  ///
451  void addRegOperand(Value *V, bool isDef, bool isDefAndUse=false) {
452    assert(!OperandsComplete() &&
453           "Trying to add an operand to a machine instr that is already done!");
454    operands.push_back(
455      MachineOperand(V, MachineOperand::MO_VirtualRegister,
456                     !isDef ? MachineOperand::Use :
457                     (isDefAndUse ? MachineOperand::UseAndDef :
458                      MachineOperand::Def)));
459  }
460
461  void addRegOperand(Value *V,
462                     MachineOperand::UseType UTy = MachineOperand::Use,
463                     bool isPCRelative = false) {
464    assert(!OperandsComplete() &&
465           "Trying to add an operand to a machine instr that is already done!");
466    operands.push_back(MachineOperand(V, MachineOperand::MO_VirtualRegister,
467                                      UTy, isPCRelative));
468  }
469
470  /// addRegOperand - Add a symbolic virtual register reference...
471  ///
472  void addRegOperand(int reg, bool isDef) {
473    assert(!OperandsComplete() &&
474           "Trying to add an operand to a machine instr that is already done!");
475    operands.push_back(
476      MachineOperand(reg, MachineOperand::MO_VirtualRegister,
477                     isDef ? MachineOperand::Def : MachineOperand::Use));
478  }
479
480  /// addRegOperand - Add a symbolic virtual register reference...
481  ///
482  void addRegOperand(int reg,
483                     MachineOperand::UseType UTy = MachineOperand::Use) {
484    assert(!OperandsComplete() &&
485           "Trying to add an operand to a machine instr that is already done!");
486    operands.push_back(
487      MachineOperand(reg, MachineOperand::MO_VirtualRegister, UTy));
488  }
489
490  /// addMachineRegOperand - Add a virtual register operand to this MachineInstr
491  ///
492  void addMachineRegOperand(int reg, bool isDef) {
493    assert(!OperandsComplete() &&
494           "Trying to add an operand to a machine instr that is already done!");
495    operands.push_back(
496      MachineOperand(reg, MachineOperand::MO_MachineRegister,
497                     isDef ? MachineOperand::Def : MachineOperand::Use));
498  }
499
500  /// addMachineRegOperand - Add a virtual register operand to this MachineInstr
501  ///
502  void addMachineRegOperand(int reg,
503                            MachineOperand::UseType UTy = MachineOperand::Use) {
504    assert(!OperandsComplete() &&
505           "Trying to add an operand to a machine instr that is already done!");
506    operands.push_back(
507      MachineOperand(reg, MachineOperand::MO_MachineRegister, UTy));
508  }
509
510  /// addZeroExtImmOperand - Add a zero extended constant argument to the
511  /// machine instruction.
512  ///
513  void addZeroExtImmOperand(int intValue) {
514    assert(!OperandsComplete() &&
515           "Trying to add an operand to a machine instr that is already done!");
516    operands.push_back(
517      MachineOperand(intValue, MachineOperand::MO_UnextendedImmed));
518  }
519
520  /// addZeroExtImm64Operand - Add a zero extended 64-bit constant argument
521  /// to the machine instruction.
522  ///
523  void addZeroExtImm64Operand(uint64_t intValue) {
524    assert(!OperandsComplete() &&
525           "Trying to add an operand to a machine instr that is already done!");
526    operands.push_back(
527      MachineOperand(intValue, MachineOperand::MO_UnextendedImmed));
528  }
529
530  /// addSignExtImmOperand - Add a zero extended constant argument to the
531  /// machine instruction.
532  ///
533  void addSignExtImmOperand(int intValue) {
534    assert(!OperandsComplete() &&
535           "Trying to add an operand to a machine instr that is already done!");
536    operands.push_back(
537      MachineOperand(intValue, MachineOperand::MO_SignExtendedImmed));
538  }
539
540  void addMachineBasicBlockOperand(MachineBasicBlock *MBB) {
541    assert(!OperandsComplete() &&
542           "Trying to add an operand to a machine instr that is already done!");
543    operands.push_back(MachineOperand(MBB));
544  }
545
546  /// addFrameIndexOperand - Add an abstract frame index to the instruction
547  ///
548  void addFrameIndexOperand(unsigned Idx) {
549    assert(!OperandsComplete() &&
550           "Trying to add an operand to a machine instr that is already done!");
551    operands.push_back(MachineOperand(Idx, MachineOperand::MO_FrameIndex));
552  }
553
554  /// addConstantPoolndexOperand - Add a constant pool object index to the
555  /// instruction.
556  ///
557  void addConstantPoolIndexOperand(unsigned I, int Offset=0) {
558    assert(!OperandsComplete() &&
559           "Trying to add an operand to a machine instr that is already done!");
560    operands.push_back(MachineOperand(I, MachineOperand::MO_ConstantPoolIndex));
561  }
562
563  /// addJumpTableIndexOperand - Add a jump table object index to the
564  /// instruction.
565  ///
566  void addJumpTableIndexOperand(unsigned I) {
567    assert(!OperandsComplete() &&
568           "Trying to add an operand to a machine instr that is already done!");
569    operands.push_back(MachineOperand(I, MachineOperand::MO_JumpTableIndex));
570  }
571
572  void addGlobalAddressOperand(GlobalValue *GV, bool isPCRelative, int Offset) {
573    assert(!OperandsComplete() &&
574           "Trying to add an operand to a machine instr that is already done!");
575    operands.push_back(
576      MachineOperand(GV, MachineOperand::MO_GlobalAddress,
577                     MachineOperand::Use, isPCRelative, Offset));
578  }
579
580  /// addExternalSymbolOperand - Add an external symbol operand to this instr
581  ///
582  void addExternalSymbolOperand(const char *SymName, bool isPCRelative) {
583    operands.push_back(MachineOperand(SymName, isPCRelative, 0));
584  }
585
586  //===--------------------------------------------------------------------===//
587  // Accessors used to modify instructions in place.
588  //
589  // FIXME: Move this stuff to MachineOperand itself!
590
591  /// setOpcode - Replace the opcode of the current instruction with a new one.
592  ///
593  void setOpcode(unsigned Op) { Opcode = Op; }
594
595  /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
596  /// fewer operand than it started with.
597  ///
598  void RemoveOperand(unsigned i) {
599    operands.erase(operands.begin()+i);
600  }
601
602  // Access to set the operands when building the machine instruction
603  //
604  void SetMachineOperandVal(unsigned i,
605                            MachineOperand::MachineOperandType operandType,
606                            Value* V);
607
608  void SetMachineOperandConst(unsigned i,
609                              MachineOperand::MachineOperandType operandType,
610                              int intValue);
611
612  void SetMachineOperandReg(unsigned i, int regNum);
613};
614
615//===----------------------------------------------------------------------===//
616// Debugging Support
617
618std::ostream& operator<<(std::ostream &OS, const MachineInstr &MI);
619std::ostream& operator<<(std::ostream &OS, const MachineOperand &MO);
620
621} // End llvm namespace
622
623#endif
624