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