MachineInstr.cpp revision 466b534a570f574ed485d875bbca8454f68dcb52
1//===-- MachineInstr.cpp --------------------------------------------------===//
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// Methods common to all machine instructions.
11//
12// FIXME: Now that MachineInstrs have parent pointers, they should always
13// print themselves using their MachineFunction's TargetMachine.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/Value.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/MRegisterInfo.h"
23#include "Support/LeakDetector.h"
24using namespace llvm;
25
26// Global variable holding an array of descriptors for machine instructions.
27// The actual object needs to be created separately for each target machine.
28// This variable is initialized and reset by class TargetInstrInfo.
29//
30// FIXME: This should be a property of the target so that more than one target
31// at a time can be active...
32//
33namespace llvm {
34  extern const TargetInstrDescriptor *TargetInstrDescriptors;
35}
36
37// Constructor for instructions with variable #operands
38MachineInstr::MachineInstr(short opcode, unsigned numOperands)
39  : Opcode(opcode),
40    numImplicitRefs(0),
41    operands(numOperands, MachineOperand()),
42    parent(0) {
43  // Make sure that we get added to a machine basicblock
44  LeakDetector::addGarbageObject(this);
45}
46
47/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
48/// not a resize for them.  It is expected that if you use this that you call
49/// add* methods below to fill up the operands, instead of the Set methods.
50/// Eventually, the "resizing" ctors will be phased out.
51///
52MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
53  : Opcode(opcode), numImplicitRefs(0), parent(0) {
54  operands.reserve(numOperands);
55  // Make sure that we get added to a machine basicblock
56  LeakDetector::addGarbageObject(this);
57}
58
59/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
60/// MachineInstr is created and added to the end of the specified basic block.
61///
62MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
63                           unsigned numOperands)
64  : Opcode(opcode), numImplicitRefs(0), parent(0) {
65  assert(MBB && "Cannot use inserting ctor with null basic block!");
66  operands.reserve(numOperands);
67  // Make sure that we get added to a machine basicblock
68  LeakDetector::addGarbageObject(this);
69  MBB->push_back(this);  // Add instruction to end of basic block!
70}
71
72///MachineInstr ctor - Copies MachineInstr arg exactly
73MachineInstr::MachineInstr(const MachineInstr &MI) {
74  Opcode = MI.getOpcode();
75  numImplicitRefs = MI.getNumImplicitRefs();
76
77  //Add operands
78  for(unsigned i=0; i < MI.getNumOperands(); ++i)
79    operands.push_back(MachineOperand(MI.getOperand(i)));
80}
81
82
83MachineInstr::~MachineInstr()
84{
85  LeakDetector::removeGarbageObject(this);
86}
87
88///clone - Create a copy of 'this' instruction that is identical in
89///all ways except the following: The instruction has no parent The
90///instruction has no name
91MachineInstr* MachineInstr::clone() {
92  MachineInstr* newInst = new MachineInstr(*this);
93}
94
95/// OperandComplete - Return true if it's illegal to add a new operand
96///
97bool MachineInstr::OperandsComplete() const {
98  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
99  if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
100    return true;  // Broken: we have all the operands of this instruction!
101  return false;
102}
103
104/// replace - Support for replacing opcode and operands of a MachineInstr in
105/// place. This only resets the size of the operand vector and initializes it.
106/// The new operands must be set explicitly later.
107///
108void MachineInstr::replace(short opcode, unsigned numOperands) {
109  assert(getNumImplicitRefs() == 0 &&
110         "This is probably broken because implicit refs are going to be lost.");
111  Opcode = opcode;
112  operands.clear();
113  operands.resize(numOperands, MachineOperand());
114
115}
116
117void MachineInstr::SetMachineOperandVal(unsigned i,
118                                        MachineOperand::MachineOperandType opTy,
119                                        Value* V) {
120  assert(i < operands.size());          // may be explicit or implicit op
121  operands[i].opType = opTy;
122  operands[i].contents.value = V;
123  operands[i].regNum = -1;
124}
125
126void
127MachineInstr::SetMachineOperandConst(unsigned i,
128                                     MachineOperand::MachineOperandType opTy,
129                                     int intValue) {
130  assert(i < getNumOperands());          // must be explicit op
131  assert(TargetInstrDescriptors[Opcode].resultPos != (int) i &&
132         "immed. constant cannot be defined");
133
134  operands[i].opType = opTy;
135  operands[i].contents.value = NULL;
136  operands[i].contents.immedVal = intValue;
137  operands[i].regNum = -1;
138  operands[i].flags = 0;
139}
140
141void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
142  assert(i < getNumOperands());          // must be explicit op
143
144  operands[i].opType = MachineOperand::MO_MachineRegister;
145  operands[i].contents.value = NULL;
146  operands[i].regNum = regNum;
147}
148
149// Used only by the SPARC back-end.
150void MachineInstr::SetRegForOperand(unsigned i, int regNum) {
151  assert(i < getNumOperands());          // must be explicit op
152  operands[i].setRegForValue(regNum);
153}
154
155// Used only by the SPARC back-end.
156void MachineInstr::SetRegForImplicitRef(unsigned i, int regNum) {
157  getImplicitOp(i).setRegForValue(regNum);
158}
159
160/// substituteValue - Substitute all occurrences of Value* oldVal with newVal
161/// in all operands and all implicit refs. If defsOnly == true, substitute defs
162/// only.
163///
164/// FIXME: Fold this into its single caller, at SparcInstrSelection.cpp:2865,
165/// or make it a static function in that file.
166///
167unsigned
168MachineInstr::substituteValue(const Value* oldVal, Value* newVal,
169                              bool defsOnly, bool notDefsAndUses,
170                              bool& someArgsWereIgnored)
171{
172  assert((!defsOnly || !notDefsAndUses) &&
173         "notDefsAndUses is irrelevant if defsOnly == true.");
174
175  unsigned numSubst = 0;
176
177  // Substitute operands
178  for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
179    if (*O == oldVal)
180      if (!defsOnly ||
181          notDefsAndUses && (O.isDef() && !O.isUse()) ||
182          !notDefsAndUses && O.isDef())
183        {
184          O.getMachineOperand().contents.value = newVal;
185          ++numSubst;
186        }
187      else
188        someArgsWereIgnored = true;
189
190  // Substitute implicit refs
191  for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i)
192    if (getImplicitRef(i) == oldVal)
193      if (!defsOnly ||
194          notDefsAndUses && (getImplicitOp(i).isDef() && !getImplicitOp(i).isUse()) ||
195          !notDefsAndUses && getImplicitOp(i).isDef())
196        {
197          getImplicitOp(i).contents.value = newVal;
198          ++numSubst;
199        }
200      else
201        someArgsWereIgnored = true;
202
203  return numSubst;
204}
205
206void MachineInstr::dump() const {
207  std::cerr << "  " << *this;
208}
209
210static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
211  os << "(val ";
212  os << (void*) val;                    // print address always
213  if (val && val->hasName())
214    os << " " << val->getName(); // print name also, if available
215  os << ")";
216  return os;
217}
218
219static inline void OutputReg(std::ostream &os, unsigned RegNo,
220                             const MRegisterInfo *MRI = 0) {
221  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
222    if (MRI)
223      os << "%" << MRI->get(RegNo).Name;
224    else
225      os << "%mreg(" << RegNo << ")";
226  } else
227    os << "%reg" << RegNo;
228}
229
230static void print(const MachineOperand &MO, std::ostream &OS,
231                  const TargetMachine &TM) {
232  const MRegisterInfo *MRI = TM.getRegisterInfo();
233  bool CloseParen = true;
234  if (MO.isHiBits32())
235    OS << "%lm(";
236  else if (MO.isLoBits32())
237    OS << "%lo(";
238  else if (MO.isHiBits64())
239    OS << "%hh(";
240  else if (MO.isLoBits64())
241    OS << "%hm(";
242  else
243    CloseParen = false;
244
245  switch (MO.getType()) {
246  case MachineOperand::MO_VirtualRegister:
247    if (MO.getVRegValue()) {
248      OS << "%reg";
249      OutputValue(OS, MO.getVRegValue());
250      if (MO.hasAllocatedReg())
251        OS << "==";
252    }
253    if (MO.hasAllocatedReg())
254      OutputReg(OS, MO.getReg(), MRI);
255    break;
256  case MachineOperand::MO_CCRegister:
257    OS << "%ccreg";
258    OutputValue(OS, MO.getVRegValue());
259    if (MO.hasAllocatedReg()) {
260      OS << "==";
261      OutputReg(OS, MO.getReg(), MRI);
262    }
263    break;
264  case MachineOperand::MO_MachineRegister:
265    OutputReg(OS, MO.getMachineRegNum(), MRI);
266    break;
267  case MachineOperand::MO_SignExtendedImmed:
268    OS << (long)MO.getImmedValue();
269    break;
270  case MachineOperand::MO_UnextendedImmed:
271    OS << (long)MO.getImmedValue();
272    break;
273  case MachineOperand::MO_PCRelativeDisp: {
274    const Value* opVal = MO.getVRegValue();
275    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
276    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
277    if (opVal->hasName())
278      OS << opVal->getName();
279    else
280      OS << (const void*) opVal;
281    OS << ")";
282    break;
283  }
284  case MachineOperand::MO_MachineBasicBlock:
285    OS << "bb<"
286       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
287       << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">";
288    break;
289  case MachineOperand::MO_FrameIndex:
290    OS << "<fi#" << MO.getFrameIndex() << ">";
291    break;
292  case MachineOperand::MO_ConstantPoolIndex:
293    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
294    break;
295  case MachineOperand::MO_GlobalAddress:
296    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
297    break;
298  case MachineOperand::MO_ExternalSymbol:
299    OS << "<es:" << MO.getSymbolName() << ">";
300    break;
301  default:
302    assert(0 && "Unrecognized operand type");
303  }
304
305  if (CloseParen)
306    OS << ")";
307}
308
309void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) const {
310  unsigned StartOp = 0;
311
312   // Specialize printing if op#0 is definition
313  if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
314    ::print(getOperand(0), OS, TM);
315    OS << " = ";
316    ++StartOp;   // Don't print this operand again!
317  }
318  OS << TM.getInstrInfo().getName(getOpcode());
319
320  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
321    const MachineOperand& mop = getOperand(i);
322    if (i != StartOp)
323      OS << ",";
324    OS << " ";
325    ::print(mop, OS, TM);
326
327    if (mop.isDef())
328      if (mop.isUse())
329        OS << "<def&use>";
330      else
331        OS << "<def>";
332  }
333
334  // code for printing implicit references
335  if (getNumImplicitRefs()) {
336    OS << "\tImplicitRefs: ";
337    for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) {
338      OS << "\t";
339      OutputValue(OS, getImplicitRef(i));
340      if (getImplicitOp(i).isDef())
341          if (getImplicitOp(i).isUse())
342            OS << "<def&use>";
343          else
344            OS << "<def>";
345    }
346  }
347
348  OS << "\n";
349}
350
351namespace llvm {
352std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
353  // If the instruction is embedded into a basic block, we can find the target
354  // info for the instruction.
355  if (const MachineBasicBlock *MBB = MI.getParent()) {
356    const MachineFunction *MF = MBB->getParent();
357    MI.print(os, MF->getTarget());
358    return os;
359  }
360
361  // Otherwise, print it out in the "raw" format without symbolic register names
362  // and such.
363  os << TargetInstrDescriptors[MI.getOpcode()].Name;
364
365  for (unsigned i=0, N=MI.getNumOperands(); i < N; i++) {
366    os << "\t" << MI.getOperand(i);
367    if (MI.getOperand(i).isDef())
368      if (MI.getOperand(i).isUse())
369        os << "<d&u>";
370      else
371        os << "<d>";
372  }
373
374  // code for printing implicit references
375  unsigned NumOfImpRefs = MI.getNumImplicitRefs();
376  if (NumOfImpRefs > 0) {
377    os << "\tImplicit: ";
378    for (unsigned z=0; z < NumOfImpRefs; z++) {
379      OutputValue(os, MI.getImplicitRef(z));
380      if (MI.getImplicitOp(z).isDef())
381          if (MI.getImplicitOp(z).isUse())
382            os << "<d&u>";
383          else
384            os << "<d>";
385      os << "\t";
386    }
387  }
388
389  return os << "\n";
390}
391
392std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
393  if (MO.isHiBits32())
394    OS << "%lm(";
395  else if (MO.isLoBits32())
396    OS << "%lo(";
397  else if (MO.isHiBits64())
398    OS << "%hh(";
399  else if (MO.isLoBits64())
400    OS << "%hm(";
401
402  switch (MO.getType())
403    {
404    case MachineOperand::MO_VirtualRegister:
405      if (MO.hasAllocatedReg())
406        OutputReg(OS, MO.getReg());
407
408      if (MO.getVRegValue()) {
409	if (MO.hasAllocatedReg()) OS << "==";
410	OS << "%vreg";
411	OutputValue(OS, MO.getVRegValue());
412      }
413      break;
414    case MachineOperand::MO_CCRegister:
415      OS << "%ccreg";
416      OutputValue(OS, MO.getVRegValue());
417      if (MO.hasAllocatedReg()) {
418        OS << "==";
419        OutputReg(OS, MO.getReg());
420      }
421      break;
422    case MachineOperand::MO_MachineRegister:
423      OutputReg(OS, MO.getMachineRegNum());
424      break;
425    case MachineOperand::MO_SignExtendedImmed:
426      OS << (long)MO.getImmedValue();
427      break;
428    case MachineOperand::MO_UnextendedImmed:
429      OS << (long)MO.getImmedValue();
430      break;
431    case MachineOperand::MO_PCRelativeDisp:
432      {
433        const Value* opVal = MO.getVRegValue();
434        bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
435        OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
436        if (opVal->hasName())
437          OS << opVal->getName();
438        else
439          OS << (const void*) opVal;
440        OS << ")";
441        break;
442      }
443    case MachineOperand::MO_MachineBasicBlock:
444      OS << "bb<"
445         << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
446         << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">";
447      break;
448    case MachineOperand::MO_FrameIndex:
449      OS << "<fi#" << MO.getFrameIndex() << ">";
450      break;
451    case MachineOperand::MO_ConstantPoolIndex:
452      OS << "<cp#" << MO.getConstantPoolIndex() << ">";
453      break;
454    case MachineOperand::MO_GlobalAddress:
455      OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
456      break;
457    case MachineOperand::MO_ExternalSymbol:
458      OS << "<es:" << MO.getSymbolName() << ">";
459      break;
460    default:
461      assert(0 && "Unrecognized operand type");
462      break;
463    }
464
465  if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
466    OS << ")";
467
468  return OS;
469}
470
471}
472