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