strength reduce a ton of type equality tests to check the typeid (Through
[oota-llvm.git] / lib / CodeGen / MachineInstr.cpp
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
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 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Constants.h"
16 #include "llvm/InlineAsm.h"
17 #include "llvm/Value.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetInstrDesc.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LeakDetector.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/FoldingSet.h"
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 // MachineOperand Implementation
37 //===----------------------------------------------------------------------===//
38
39 /// AddRegOperandToRegInfo - Add this register operand to the specified
40 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
41 /// explicitly nulled out.
42 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
43   assert(isReg() && "Can only add reg operand to use lists");
44   
45   // If the reginfo pointer is null, just explicitly null out or next/prev
46   // pointers, to ensure they are not garbage.
47   if (RegInfo == 0) {
48     Contents.Reg.Prev = 0;
49     Contents.Reg.Next = 0;
50     return;
51   }
52   
53   // Otherwise, add this operand to the head of the registers use/def list.
54   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
55   
56   // For SSA values, we prefer to keep the definition at the start of the list.
57   // we do this by skipping over the definition if it is at the head of the
58   // list.
59   if (*Head && (*Head)->isDef())
60     Head = &(*Head)->Contents.Reg.Next;
61   
62   Contents.Reg.Next = *Head;
63   if (Contents.Reg.Next) {
64     assert(getReg() == Contents.Reg.Next->getReg() &&
65            "Different regs on the same list!");
66     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
67   }
68   
69   Contents.Reg.Prev = Head;
70   *Head = this;
71 }
72
73 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
74 /// MachineRegisterInfo it is linked with.
75 void MachineOperand::RemoveRegOperandFromRegInfo() {
76   assert(isOnRegUseList() && "Reg operand is not on a use list");
77   // Unlink this from the doubly linked list of operands.
78   MachineOperand *NextOp = Contents.Reg.Next;
79   *Contents.Reg.Prev = NextOp; 
80   if (NextOp) {
81     assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
82     NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
83   }
84   Contents.Reg.Prev = 0;
85   Contents.Reg.Next = 0;
86 }
87
88 void MachineOperand::setReg(unsigned Reg) {
89   if (getReg() == Reg) return; // No change.
90   
91   // Otherwise, we have to change the register.  If this operand is embedded
92   // into a machine function, we need to update the old and new register's
93   // use/def lists.
94   if (MachineInstr *MI = getParent())
95     if (MachineBasicBlock *MBB = MI->getParent())
96       if (MachineFunction *MF = MBB->getParent()) {
97         RemoveRegOperandFromRegInfo();
98         Contents.Reg.RegNo = Reg;
99         AddRegOperandToRegInfo(&MF->getRegInfo());
100         return;
101       }
102         
103   // Otherwise, just change the register, no problem.  :)
104   Contents.Reg.RegNo = Reg;
105 }
106
107 /// ChangeToImmediate - Replace this operand with a new immediate operand of
108 /// the specified value.  If an operand is known to be an immediate already,
109 /// the setImm method should be used.
110 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
111   // If this operand is currently a register operand, and if this is in a
112   // function, deregister the operand from the register's use/def list.
113   if (isReg() && getParent() && getParent()->getParent() &&
114       getParent()->getParent()->getParent())
115     RemoveRegOperandFromRegInfo();
116   
117   OpKind = MO_Immediate;
118   Contents.ImmVal = ImmVal;
119 }
120
121 /// ChangeToRegister - Replace this operand with a new register operand of
122 /// the specified value.  If an operand is known to be an register already,
123 /// the setReg method should be used.
124 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
125                                       bool isKill, bool isDead, bool isUndef) {
126   // If this operand is already a register operand, use setReg to update the 
127   // register's use/def lists.
128   if (isReg()) {
129     assert(!isEarlyClobber());
130     setReg(Reg);
131   } else {
132     // Otherwise, change this to a register and set the reg#.
133     OpKind = MO_Register;
134     Contents.Reg.RegNo = Reg;
135
136     // If this operand is embedded in a function, add the operand to the
137     // register's use/def list.
138     if (MachineInstr *MI = getParent())
139       if (MachineBasicBlock *MBB = MI->getParent())
140         if (MachineFunction *MF = MBB->getParent())
141           AddRegOperandToRegInfo(&MF->getRegInfo());
142   }
143
144   IsDef = isDef;
145   IsImp = isImp;
146   IsKill = isKill;
147   IsDead = isDead;
148   IsUndef = isUndef;
149   IsEarlyClobber = false;
150   SubReg = 0;
151 }
152
153 /// isIdenticalTo - Return true if this operand is identical to the specified
154 /// operand.
155 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
156   if (getType() != Other.getType() ||
157       getTargetFlags() != Other.getTargetFlags())
158     return false;
159   
160   switch (getType()) {
161   default: llvm_unreachable("Unrecognized operand type");
162   case MachineOperand::MO_Register:
163     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
164            getSubReg() == Other.getSubReg();
165   case MachineOperand::MO_Immediate:
166     return getImm() == Other.getImm();
167   case MachineOperand::MO_FPImmediate:
168     return getFPImm() == Other.getFPImm();
169   case MachineOperand::MO_MachineBasicBlock:
170     return getMBB() == Other.getMBB();
171   case MachineOperand::MO_FrameIndex:
172     return getIndex() == Other.getIndex();
173   case MachineOperand::MO_ConstantPoolIndex:
174     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
175   case MachineOperand::MO_JumpTableIndex:
176     return getIndex() == Other.getIndex();
177   case MachineOperand::MO_GlobalAddress:
178     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
179   case MachineOperand::MO_ExternalSymbol:
180     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
181            getOffset() == Other.getOffset();
182   }
183 }
184
185 /// print - Print the specified machine operand.
186 ///
187 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
188   switch (getType()) {
189   case MachineOperand::MO_Register:
190     if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
191       OS << "%reg" << getReg();
192     } else {
193       // If the instruction is embedded into a basic block, we can find the
194       // target info for the instruction.
195       if (TM == 0)
196         if (const MachineInstr *MI = getParent())
197           if (const MachineBasicBlock *MBB = MI->getParent())
198             if (const MachineFunction *MF = MBB->getParent())
199               TM = &MF->getTarget();
200       
201       if (TM)
202         OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
203       else
204         OS << "%mreg" << getReg();
205     }
206
207     if (getSubReg() != 0)
208       OS << ':' << getSubReg();
209
210     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
211         isEarlyClobber()) {
212       OS << '<';
213       bool NeedComma = false;
214       if (isImplicit()) {
215         if (NeedComma) OS << ',';
216         OS << (isDef() ? "imp-def" : "imp-use");
217         NeedComma = true;
218       } else if (isDef()) {
219         if (NeedComma) OS << ',';
220         if (isEarlyClobber())
221           OS << "earlyclobber,";
222         OS << "def";
223         NeedComma = true;
224       }
225       if (isKill() || isDead() || isUndef()) {
226         if (NeedComma) OS << ',';
227         if (isKill())  OS << "kill";
228         if (isDead())  OS << "dead";
229         if (isUndef()) {
230           if (isKill() || isDead())
231             OS << ',';
232           OS << "undef";
233         }
234       }
235       OS << '>';
236     }
237     break;
238   case MachineOperand::MO_Immediate:
239     OS << getImm();
240     break;
241   case MachineOperand::MO_FPImmediate:
242     if (getFPImm()->getType()->isFloatTy())
243       OS << getFPImm()->getValueAPF().convertToFloat();
244     else
245       OS << getFPImm()->getValueAPF().convertToDouble();
246     break;
247   case MachineOperand::MO_MachineBasicBlock:
248     OS << "mbb<"
249        << ((Value*)getMBB()->getBasicBlock())->getName()
250        << "," << (void*)getMBB() << '>';
251     break;
252   case MachineOperand::MO_FrameIndex:
253     OS << "<fi#" << getIndex() << '>';
254     break;
255   case MachineOperand::MO_ConstantPoolIndex:
256     OS << "<cp#" << getIndex();
257     if (getOffset()) OS << "+" << getOffset();
258     OS << '>';
259     break;
260   case MachineOperand::MO_JumpTableIndex:
261     OS << "<jt#" << getIndex() << '>';
262     break;
263   case MachineOperand::MO_GlobalAddress:
264     OS << "<ga:" << ((Value*)getGlobal())->getName();
265     if (getOffset()) OS << "+" << getOffset();
266     OS << '>';
267     break;
268   case MachineOperand::MO_ExternalSymbol:
269     OS << "<es:" << getSymbolName();
270     if (getOffset()) OS << "+" << getOffset();
271     OS << '>';
272     break;
273   default:
274     llvm_unreachable("Unrecognized operand type");
275   }
276   
277   if (unsigned TF = getTargetFlags())
278     OS << "[TF=" << TF << ']';
279 }
280
281 //===----------------------------------------------------------------------===//
282 // MachineMemOperand Implementation
283 //===----------------------------------------------------------------------===//
284
285 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
286                                      int64_t o, uint64_t s, unsigned int a)
287   : Offset(o), Size(s), V(v),
288     Flags((f & 7) | ((Log2_32(a) + 1) << 3)) {
289   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
290   assert((isLoad() || isStore()) && "Not a load/store!");
291 }
292
293 /// Profile - Gather unique data for the object.
294 ///
295 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
296   ID.AddInteger(Offset);
297   ID.AddInteger(Size);
298   ID.AddPointer(V);
299   ID.AddInteger(Flags);
300 }
301
302 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
303   // The Value and Offset may differ due to CSE. But the flags and size
304   // should be the same.
305   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
306   assert(MMO->getSize() == getSize() && "Size mismatch!");
307
308   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
309     // Update the alignment value.
310     Flags = (Flags & 7) | ((Log2_32(MMO->getBaseAlignment()) + 1) << 3);
311     // Also update the base and offset, because the new alignment may
312     // not be applicable with the old ones.
313     V = MMO->getValue();
314     Offset = MMO->getOffset();
315   }
316 }
317
318 /// getAlignment - Return the minimum known alignment in bytes of the
319 /// actual memory reference.
320 uint64_t MachineMemOperand::getAlignment() const {
321   return MinAlign(getBaseAlignment(), getOffset());
322 }
323
324 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
325   assert((MMO.isLoad() || MMO.isStore()) &&
326          "SV has to be a load, store or both.");
327   
328   if (MMO.isVolatile())
329     OS << "Volatile ";
330
331   if (MMO.isLoad())
332     OS << "LD";
333   if (MMO.isStore())
334     OS << "ST";
335   OS << MMO.getSize();
336   
337   // Print the address information.
338   OS << "[";
339   if (!MMO.getValue())
340     OS << "<unknown>";
341   else
342     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
343
344   // If the alignment of the memory reference itself differs from the alignment
345   // of the base pointer, print the base alignment explicitly, next to the base
346   // pointer.
347   if (MMO.getBaseAlignment() != MMO.getAlignment())
348     OS << "(align=" << MMO.getBaseAlignment() << ")";
349
350   if (MMO.getOffset() != 0)
351     OS << "+" << MMO.getOffset();
352   OS << "]";
353
354   // Print the alignment of the reference.
355   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
356       MMO.getBaseAlignment() != MMO.getSize())
357     OS << "(align=" << MMO.getAlignment() << ")";
358
359   return OS;
360 }
361
362 //===----------------------------------------------------------------------===//
363 // MachineInstr Implementation
364 //===----------------------------------------------------------------------===//
365
366 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
367 /// TID NULL and no operands.
368 MachineInstr::MachineInstr()
369   : TID(0), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
370     Parent(0), debugLoc(DebugLoc::getUnknownLoc()) {
371   // Make sure that we get added to a machine basicblock
372   LeakDetector::addGarbageObject(this);
373 }
374
375 void MachineInstr::addImplicitDefUseOperands() {
376   if (TID->ImplicitDefs)
377     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
378       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
379   if (TID->ImplicitUses)
380     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
381       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
382 }
383
384 /// MachineInstr ctor - This constructor create a MachineInstr and add the
385 /// implicit operands. It reserves space for number of operands specified by
386 /// TargetInstrDesc or the numOperands if it is not zero. (for
387 /// instructions with variable number of operands).
388 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
389   : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0), Parent(0),
390     debugLoc(DebugLoc::getUnknownLoc()) {
391   if (!NoImp && TID->getImplicitDefs())
392     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
393       NumImplicitOps++;
394   if (!NoImp && TID->getImplicitUses())
395     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
396       NumImplicitOps++;
397   Operands.reserve(NumImplicitOps + TID->getNumOperands());
398   if (!NoImp)
399     addImplicitDefUseOperands();
400   // Make sure that we get added to a machine basicblock
401   LeakDetector::addGarbageObject(this);
402 }
403
404 /// MachineInstr ctor - As above, but with a DebugLoc.
405 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
406                            bool NoImp)
407   : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
408     Parent(0), debugLoc(dl) {
409   if (!NoImp && TID->getImplicitDefs())
410     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
411       NumImplicitOps++;
412   if (!NoImp && TID->getImplicitUses())
413     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
414       NumImplicitOps++;
415   Operands.reserve(NumImplicitOps + TID->getNumOperands());
416   if (!NoImp)
417     addImplicitDefUseOperands();
418   // Make sure that we get added to a machine basicblock
419   LeakDetector::addGarbageObject(this);
420 }
421
422 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
423 /// that the MachineInstr is created and added to the end of the specified 
424 /// basic block.
425 ///
426 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
427   : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0), Parent(0), 
428     debugLoc(DebugLoc::getUnknownLoc()) {
429   assert(MBB && "Cannot use inserting ctor with null basic block!");
430   if (TID->ImplicitDefs)
431     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
432       NumImplicitOps++;
433   if (TID->ImplicitUses)
434     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
435       NumImplicitOps++;
436   Operands.reserve(NumImplicitOps + TID->getNumOperands());
437   addImplicitDefUseOperands();
438   // Make sure that we get added to a machine basicblock
439   LeakDetector::addGarbageObject(this);
440   MBB->push_back(this);  // Add instruction to end of basic block!
441 }
442
443 /// MachineInstr ctor - As above, but with a DebugLoc.
444 ///
445 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
446                            const TargetInstrDesc &tid)
447   : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
448     Parent(0), debugLoc(dl) {
449   assert(MBB && "Cannot use inserting ctor with null basic block!");
450   if (TID->ImplicitDefs)
451     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
452       NumImplicitOps++;
453   if (TID->ImplicitUses)
454     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
455       NumImplicitOps++;
456   Operands.reserve(NumImplicitOps + TID->getNumOperands());
457   addImplicitDefUseOperands();
458   // Make sure that we get added to a machine basicblock
459   LeakDetector::addGarbageObject(this);
460   MBB->push_back(this);  // Add instruction to end of basic block!
461 }
462
463 /// MachineInstr ctor - Copies MachineInstr arg exactly
464 ///
465 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
466   : TID(&MI.getDesc()), NumImplicitOps(0),
467     MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
468     Parent(0), debugLoc(MI.getDebugLoc()) {
469   Operands.reserve(MI.getNumOperands());
470
471   // Add operands
472   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
473     addOperand(MI.getOperand(i));
474   NumImplicitOps = MI.NumImplicitOps;
475
476   // Set parent to null.
477   Parent = 0;
478
479   LeakDetector::addGarbageObject(this);
480 }
481
482 MachineInstr::~MachineInstr() {
483   LeakDetector::removeGarbageObject(this);
484 #ifndef NDEBUG
485   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
486     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
487     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
488            "Reg operand def/use list corrupted");
489   }
490 #endif
491 }
492
493 /// getRegInfo - If this instruction is embedded into a MachineFunction,
494 /// return the MachineRegisterInfo object for the current function, otherwise
495 /// return null.
496 MachineRegisterInfo *MachineInstr::getRegInfo() {
497   if (MachineBasicBlock *MBB = getParent())
498     return &MBB->getParent()->getRegInfo();
499   return 0;
500 }
501
502 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
503 /// this instruction from their respective use lists.  This requires that the
504 /// operands already be on their use lists.
505 void MachineInstr::RemoveRegOperandsFromUseLists() {
506   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
507     if (Operands[i].isReg())
508       Operands[i].RemoveRegOperandFromRegInfo();
509   }
510 }
511
512 /// AddRegOperandsToUseLists - Add all of the register operands in
513 /// this instruction from their respective use lists.  This requires that the
514 /// operands not be on their use lists yet.
515 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
516   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
517     if (Operands[i].isReg())
518       Operands[i].AddRegOperandToRegInfo(&RegInfo);
519   }
520 }
521
522
523 /// addOperand - Add the specified operand to the instruction.  If it is an
524 /// implicit operand, it is added to the end of the operand list.  If it is
525 /// an explicit operand it is added at the end of the explicit operand list
526 /// (before the first implicit operand). 
527 void MachineInstr::addOperand(const MachineOperand &Op) {
528   bool isImpReg = Op.isReg() && Op.isImplicit();
529   assert((isImpReg || !OperandsComplete()) &&
530          "Trying to add an operand to a machine instr that is already done!");
531
532   MachineRegisterInfo *RegInfo = getRegInfo();
533
534   // If we are adding the operand to the end of the list, our job is simpler.
535   // This is true most of the time, so this is a reasonable optimization.
536   if (isImpReg || NumImplicitOps == 0) {
537     // We can only do this optimization if we know that the operand list won't
538     // reallocate.
539     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
540       Operands.push_back(Op);
541     
542       // Set the parent of the operand.
543       Operands.back().ParentMI = this;
544   
545       // If the operand is a register, update the operand's use list.
546       if (Op.isReg())
547         Operands.back().AddRegOperandToRegInfo(RegInfo);
548       return;
549     }
550   }
551   
552   // Otherwise, we have to insert a real operand before any implicit ones.
553   unsigned OpNo = Operands.size()-NumImplicitOps;
554
555   // If this instruction isn't embedded into a function, then we don't need to
556   // update any operand lists.
557   if (RegInfo == 0) {
558     // Simple insertion, no reginfo update needed for other register operands.
559     Operands.insert(Operands.begin()+OpNo, Op);
560     Operands[OpNo].ParentMI = this;
561
562     // Do explicitly set the reginfo for this operand though, to ensure the
563     // next/prev fields are properly nulled out.
564     if (Operands[OpNo].isReg())
565       Operands[OpNo].AddRegOperandToRegInfo(0);
566
567   } else if (Operands.size()+1 <= Operands.capacity()) {
568     // Otherwise, we have to remove register operands from their register use
569     // list, add the operand, then add the register operands back to their use
570     // list.  This also must handle the case when the operand list reallocates
571     // to somewhere else.
572   
573     // If insertion of this operand won't cause reallocation of the operand
574     // list, just remove the implicit operands, add the operand, then re-add all
575     // the rest of the operands.
576     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
577       assert(Operands[i].isReg() && "Should only be an implicit reg!");
578       Operands[i].RemoveRegOperandFromRegInfo();
579     }
580     
581     // Add the operand.  If it is a register, add it to the reg list.
582     Operands.insert(Operands.begin()+OpNo, Op);
583     Operands[OpNo].ParentMI = this;
584
585     if (Operands[OpNo].isReg())
586       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
587     
588     // Re-add all the implicit ops.
589     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
590       assert(Operands[i].isReg() && "Should only be an implicit reg!");
591       Operands[i].AddRegOperandToRegInfo(RegInfo);
592     }
593   } else {
594     // Otherwise, we will be reallocating the operand list.  Remove all reg
595     // operands from their list, then readd them after the operand list is
596     // reallocated.
597     RemoveRegOperandsFromUseLists();
598     
599     Operands.insert(Operands.begin()+OpNo, Op);
600     Operands[OpNo].ParentMI = this;
601   
602     // Re-add all the operands.
603     AddRegOperandsToUseLists(*RegInfo);
604   }
605 }
606
607 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
608 /// fewer operand than it started with.
609 ///
610 void MachineInstr::RemoveOperand(unsigned OpNo) {
611   assert(OpNo < Operands.size() && "Invalid operand number");
612   
613   // Special case removing the last one.
614   if (OpNo == Operands.size()-1) {
615     // If needed, remove from the reg def/use list.
616     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
617       Operands.back().RemoveRegOperandFromRegInfo();
618     
619     Operands.pop_back();
620     return;
621   }
622
623   // Otherwise, we are removing an interior operand.  If we have reginfo to
624   // update, remove all operands that will be shifted down from their reg lists,
625   // move everything down, then re-add them.
626   MachineRegisterInfo *RegInfo = getRegInfo();
627   if (RegInfo) {
628     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
629       if (Operands[i].isReg())
630         Operands[i].RemoveRegOperandFromRegInfo();
631     }
632   }
633   
634   Operands.erase(Operands.begin()+OpNo);
635
636   if (RegInfo) {
637     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
638       if (Operands[i].isReg())
639         Operands[i].AddRegOperandToRegInfo(RegInfo);
640     }
641   }
642 }
643
644 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
645 /// This function should be used only occasionally. The setMemRefs function
646 /// is the primary method for setting up a MachineInstr's MemRefs list.
647 void MachineInstr::addMemOperand(MachineFunction &MF,
648                                  MachineMemOperand *MO) {
649   mmo_iterator OldMemRefs = MemRefs;
650   mmo_iterator OldMemRefsEnd = MemRefsEnd;
651
652   size_t NewNum = (MemRefsEnd - MemRefs) + 1;
653   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
654   mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
655
656   std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
657   NewMemRefs[NewNum - 1] = MO;
658
659   MemRefs = NewMemRefs;
660   MemRefsEnd = NewMemRefsEnd;
661 }
662
663 /// removeFromParent - This method unlinks 'this' from the containing basic
664 /// block, and returns it, but does not delete it.
665 MachineInstr *MachineInstr::removeFromParent() {
666   assert(getParent() && "Not embedded in a basic block!");
667   getParent()->remove(this);
668   return this;
669 }
670
671
672 /// eraseFromParent - This method unlinks 'this' from the containing basic
673 /// block, and deletes it.
674 void MachineInstr::eraseFromParent() {
675   assert(getParent() && "Not embedded in a basic block!");
676   getParent()->erase(this);
677 }
678
679
680 /// OperandComplete - Return true if it's illegal to add a new operand
681 ///
682 bool MachineInstr::OperandsComplete() const {
683   unsigned short NumOperands = TID->getNumOperands();
684   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
685     return true;  // Broken: we have all the operands of this instruction!
686   return false;
687 }
688
689 /// getNumExplicitOperands - Returns the number of non-implicit operands.
690 ///
691 unsigned MachineInstr::getNumExplicitOperands() const {
692   unsigned NumOperands = TID->getNumOperands();
693   if (!TID->isVariadic())
694     return NumOperands;
695
696   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
697     const MachineOperand &MO = getOperand(i);
698     if (!MO.isReg() || !MO.isImplicit())
699       NumOperands++;
700   }
701   return NumOperands;
702 }
703
704
705 /// isLabel - Returns true if the MachineInstr represents a label.
706 ///
707 bool MachineInstr::isLabel() const {
708   return getOpcode() == TargetInstrInfo::DBG_LABEL ||
709          getOpcode() == TargetInstrInfo::EH_LABEL ||
710          getOpcode() == TargetInstrInfo::GC_LABEL;
711 }
712
713 /// isDebugLabel - Returns true if the MachineInstr represents a debug label.
714 ///
715 bool MachineInstr::isDebugLabel() const {
716   return getOpcode() == TargetInstrInfo::DBG_LABEL;
717 }
718
719 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
720 /// the specific register or -1 if it is not found. It further tightens
721 /// the search criteria to a use that kills the register if isKill is true.
722 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
723                                           const TargetRegisterInfo *TRI) const {
724   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
725     const MachineOperand &MO = getOperand(i);
726     if (!MO.isReg() || !MO.isUse())
727       continue;
728     unsigned MOReg = MO.getReg();
729     if (!MOReg)
730       continue;
731     if (MOReg == Reg ||
732         (TRI &&
733          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
734          TargetRegisterInfo::isPhysicalRegister(Reg) &&
735          TRI->isSubRegister(MOReg, Reg)))
736       if (!isKill || MO.isKill())
737         return i;
738   }
739   return -1;
740 }
741   
742 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
743 /// the specified register or -1 if it is not found. If isDead is true, defs
744 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
745 /// also checks if there is a def of a super-register.
746 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
747                                           const TargetRegisterInfo *TRI) const {
748   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
749     const MachineOperand &MO = getOperand(i);
750     if (!MO.isReg() || !MO.isDef())
751       continue;
752     unsigned MOReg = MO.getReg();
753     if (MOReg == Reg ||
754         (TRI &&
755          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
756          TargetRegisterInfo::isPhysicalRegister(Reg) &&
757          TRI->isSubRegister(MOReg, Reg)))
758       if (!isDead || MO.isDead())
759         return i;
760   }
761   return -1;
762 }
763
764 /// findFirstPredOperandIdx() - Find the index of the first operand in the
765 /// operand list that is used to represent the predicate. It returns -1 if
766 /// none is found.
767 int MachineInstr::findFirstPredOperandIdx() const {
768   const TargetInstrDesc &TID = getDesc();
769   if (TID.isPredicable()) {
770     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
771       if (TID.OpInfo[i].isPredicate())
772         return i;
773   }
774
775   return -1;
776 }
777   
778 /// isRegTiedToUseOperand - Given the index of a register def operand,
779 /// check if the register def is tied to a source operand, due to either
780 /// two-address elimination or inline assembly constraints. Returns the
781 /// first tied use operand index by reference is UseOpIdx is not null.
782 bool MachineInstr::
783 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
784   if (getOpcode() == TargetInstrInfo::INLINEASM) {
785     assert(DefOpIdx >= 2);
786     const MachineOperand &MO = getOperand(DefOpIdx);
787     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
788       return false;
789     // Determine the actual operand index that corresponds to this index.
790     unsigned DefNo = 0;
791     unsigned DefPart = 0;
792     for (unsigned i = 1, e = getNumOperands(); i < e; ) {
793       const MachineOperand &FMO = getOperand(i);
794       // After the normal asm operands there may be additional imp-def regs.
795       if (!FMO.isImm())
796         return false;
797       // Skip over this def.
798       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
799       unsigned PrevDef = i + 1;
800       i = PrevDef + NumOps;
801       if (i > DefOpIdx) {
802         DefPart = DefOpIdx - PrevDef;
803         break;
804       }
805       ++DefNo;
806     }
807     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
808       const MachineOperand &FMO = getOperand(i);
809       if (!FMO.isImm())
810         continue;
811       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
812         continue;
813       unsigned Idx;
814       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
815           Idx == DefNo) {
816         if (UseOpIdx)
817           *UseOpIdx = (unsigned)i + 1 + DefPart;
818         return true;
819       }
820     }
821     return false;
822   }
823
824   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
825   const TargetInstrDesc &TID = getDesc();
826   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
827     const MachineOperand &MO = getOperand(i);
828     if (MO.isReg() && MO.isUse() &&
829         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
830       if (UseOpIdx)
831         *UseOpIdx = (unsigned)i;
832       return true;
833     }
834   }
835   return false;
836 }
837
838 /// isRegTiedToDefOperand - Return true if the operand of the specified index
839 /// is a register use and it is tied to an def operand. It also returns the def
840 /// operand index by reference.
841 bool MachineInstr::
842 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
843   if (getOpcode() == TargetInstrInfo::INLINEASM) {
844     const MachineOperand &MO = getOperand(UseOpIdx);
845     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
846       return false;
847
848     // Find the flag operand corresponding to UseOpIdx
849     unsigned FlagIdx, NumOps=0;
850     for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
851       const MachineOperand &UFMO = getOperand(FlagIdx);
852       // After the normal asm operands there may be additional imp-def regs.
853       if (!UFMO.isImm())
854         return false;
855       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
856       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
857       if (UseOpIdx < FlagIdx+NumOps+1)
858         break;
859     }
860     if (FlagIdx >= UseOpIdx)
861       return false;
862     const MachineOperand &UFMO = getOperand(FlagIdx);
863     unsigned DefNo;
864     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
865       if (!DefOpIdx)
866         return true;
867
868       unsigned DefIdx = 1;
869       // Remember to adjust the index. First operand is asm string, then there
870       // is a flag for each.
871       while (DefNo) {
872         const MachineOperand &FMO = getOperand(DefIdx);
873         assert(FMO.isImm());
874         // Skip over this def.
875         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
876         --DefNo;
877       }
878       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
879       return true;
880     }
881     return false;
882   }
883
884   const TargetInstrDesc &TID = getDesc();
885   if (UseOpIdx >= TID.getNumOperands())
886     return false;
887   const MachineOperand &MO = getOperand(UseOpIdx);
888   if (!MO.isReg() || !MO.isUse())
889     return false;
890   int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
891   if (DefIdx == -1)
892     return false;
893   if (DefOpIdx)
894     *DefOpIdx = (unsigned)DefIdx;
895   return true;
896 }
897
898 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
899 ///
900 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
901   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
902     const MachineOperand &MO = MI->getOperand(i);
903     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
904       continue;
905     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
906       MachineOperand &MOp = getOperand(j);
907       if (!MOp.isIdenticalTo(MO))
908         continue;
909       if (MO.isKill())
910         MOp.setIsKill();
911       else
912         MOp.setIsDead();
913       break;
914     }
915   }
916 }
917
918 /// copyPredicates - Copies predicate operand(s) from MI.
919 void MachineInstr::copyPredicates(const MachineInstr *MI) {
920   const TargetInstrDesc &TID = MI->getDesc();
921   if (!TID.isPredicable())
922     return;
923   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
924     if (TID.OpInfo[i].isPredicate()) {
925       // Predicated operands must be last operands.
926       addOperand(MI->getOperand(i));
927     }
928   }
929 }
930
931 /// isSafeToMove - Return true if it is safe to move this instruction. If
932 /// SawStore is set to true, it means that there is a store (or call) between
933 /// the instruction's location and its intended destination.
934 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
935                                 bool &SawStore) const {
936   // Ignore stuff that we obviously can't move.
937   if (TID->mayStore() || TID->isCall()) {
938     SawStore = true;
939     return false;
940   }
941   if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
942     return false;
943
944   // See if this instruction does a load.  If so, we have to guarantee that the
945   // loaded value doesn't change between the load and the its intended
946   // destination. The check for isInvariantLoad gives the targe the chance to
947   // classify the load as always returning a constant, e.g. a constant pool
948   // load.
949   if (TID->mayLoad() && !TII->isInvariantLoad(this))
950     // Otherwise, this is a real load.  If there is a store between the load and
951     // end of block, or if the load is volatile, we can't move it.
952     return !SawStore && !hasVolatileMemoryRef();
953
954   return true;
955 }
956
957 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
958 /// instruction which defined the specified register instead of copying it.
959 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
960                                  unsigned DstReg) const {
961   bool SawStore = false;
962   if (!getDesc().isRematerializable() ||
963       !TII->isTriviallyReMaterializable(this) ||
964       !isSafeToMove(TII, SawStore))
965     return false;
966   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
967     const MachineOperand &MO = getOperand(i);
968     if (!MO.isReg())
969       continue;
970     // FIXME: For now, do not remat any instruction with register operands.
971     // Later on, we can loosen the restriction is the register operands have
972     // not been modified between the def and use. Note, this is different from
973     // MachineSink because the code is no longer in two-address form (at least
974     // partially).
975     if (MO.isUse())
976       return false;
977     else if (!MO.isDead() && MO.getReg() != DstReg)
978       return false;
979   }
980   return true;
981 }
982
983 /// hasVolatileMemoryRef - Return true if this instruction may have a
984 /// volatile memory reference, or if the information describing the
985 /// memory reference is not available. Return false if it is known to
986 /// have no volatile memory references.
987 bool MachineInstr::hasVolatileMemoryRef() const {
988   // An instruction known never to access memory won't have a volatile access.
989   if (!TID->mayStore() &&
990       !TID->mayLoad() &&
991       !TID->isCall() &&
992       !TID->hasUnmodeledSideEffects())
993     return false;
994
995   // Otherwise, if the instruction has no memory reference information,
996   // conservatively assume it wasn't preserved.
997   if (memoperands_empty())
998     return true;
999   
1000   // Check the memory reference information for volatile references.
1001   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1002     if ((*I)->isVolatile())
1003       return true;
1004
1005   return false;
1006 }
1007
1008 void MachineInstr::dump() const {
1009   errs() << "  " << *this;
1010 }
1011
1012 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1013   // Specialize printing if op#0 is definition
1014   unsigned StartOp = 0;
1015   if (getNumOperands() && getOperand(0).isReg() && getOperand(0).isDef()) {
1016     getOperand(0).print(OS, TM);
1017     OS << " = ";
1018     ++StartOp;   // Don't print this operand again!
1019   }
1020
1021   OS << getDesc().getName();
1022
1023   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1024     if (i != StartOp)
1025       OS << ",";
1026     OS << " ";
1027     getOperand(i).print(OS, TM);
1028   }
1029
1030   if (!memoperands_empty()) {
1031     OS << ", Mem:";
1032     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1033          i != e; ++i) {
1034       OS << **i;
1035       if (next(i) != e)
1036         OS << " ";
1037     }
1038   }
1039
1040   if (!debugLoc.isUnknown()) {
1041     const MachineFunction *MF = getParent()->getParent();
1042     DebugLocTuple DLT = MF->getDebugLocTuple(debugLoc);
1043     DICompileUnit CU(DLT.CompileUnit);
1044     OS << " [dbg: "
1045        << CU.getDirectory() << '/' << CU.getFilename() << ","
1046        << DLT.Line << ","
1047        << DLT.Col  << "]";
1048   }
1049
1050   OS << "\n";
1051 }
1052
1053 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1054                                      const TargetRegisterInfo *RegInfo,
1055                                      bool AddIfNotFound) {
1056   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1057   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1058   bool Found = false;
1059   SmallVector<unsigned,4> DeadOps;
1060   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1061     MachineOperand &MO = getOperand(i);
1062     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1063       continue;
1064     unsigned Reg = MO.getReg();
1065     if (!Reg)
1066       continue;
1067
1068     if (Reg == IncomingReg) {
1069       if (!Found) {
1070         if (MO.isKill())
1071           // The register is already marked kill.
1072           return true;
1073         if (isPhysReg && isRegTiedToDefOperand(i))
1074           // Two-address uses of physregs must not be marked kill.
1075           return true;
1076         MO.setIsKill();
1077         Found = true;
1078       }
1079     } else if (hasAliases && MO.isKill() &&
1080                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1081       // A super-register kill already exists.
1082       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1083         return true;
1084       if (RegInfo->isSubRegister(IncomingReg, Reg))
1085         DeadOps.push_back(i);
1086     }
1087   }
1088
1089   // Trim unneeded kill operands.
1090   while (!DeadOps.empty()) {
1091     unsigned OpIdx = DeadOps.back();
1092     if (getOperand(OpIdx).isImplicit())
1093       RemoveOperand(OpIdx);
1094     else
1095       getOperand(OpIdx).setIsKill(false);
1096     DeadOps.pop_back();
1097   }
1098
1099   // If not found, this means an alias of one of the operands is killed. Add a
1100   // new implicit operand if required.
1101   if (!Found && AddIfNotFound) {
1102     addOperand(MachineOperand::CreateReg(IncomingReg,
1103                                          false /*IsDef*/,
1104                                          true  /*IsImp*/,
1105                                          true  /*IsKill*/));
1106     return true;
1107   }
1108   return Found;
1109 }
1110
1111 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1112                                    const TargetRegisterInfo *RegInfo,
1113                                    bool AddIfNotFound) {
1114   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1115   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1116   bool Found = false;
1117   SmallVector<unsigned,4> DeadOps;
1118   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1119     MachineOperand &MO = getOperand(i);
1120     if (!MO.isReg() || !MO.isDef())
1121       continue;
1122     unsigned Reg = MO.getReg();
1123     if (!Reg)
1124       continue;
1125
1126     if (Reg == IncomingReg) {
1127       if (!Found) {
1128         if (MO.isDead())
1129           // The register is already marked dead.
1130           return true;
1131         MO.setIsDead();
1132         Found = true;
1133       }
1134     } else if (hasAliases && MO.isDead() &&
1135                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1136       // There exists a super-register that's marked dead.
1137       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1138         return true;
1139       if (RegInfo->getSubRegisters(IncomingReg) &&
1140           RegInfo->getSuperRegisters(Reg) &&
1141           RegInfo->isSubRegister(IncomingReg, Reg))
1142         DeadOps.push_back(i);
1143     }
1144   }
1145
1146   // Trim unneeded dead operands.
1147   while (!DeadOps.empty()) {
1148     unsigned OpIdx = DeadOps.back();
1149     if (getOperand(OpIdx).isImplicit())
1150       RemoveOperand(OpIdx);
1151     else
1152       getOperand(OpIdx).setIsDead(false);
1153     DeadOps.pop_back();
1154   }
1155
1156   // If not found, this means an alias of one of the operands is dead. Add a
1157   // new implicit operand if required.
1158   if (Found || !AddIfNotFound)
1159     return Found;
1160     
1161   addOperand(MachineOperand::CreateReg(IncomingReg,
1162                                        true  /*IsDef*/,
1163                                        true  /*IsImp*/,
1164                                        false /*IsKill*/,
1165                                        true  /*IsDead*/));
1166   return true;
1167 }