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