402178dc6d6708d664e4da144c903c244a34ca36
[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/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Metadata.h"
19 #include "llvm/Type.h"
20 #include "llvm/Value.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetInstrDesc.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/LeakDetector.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/FoldingSet.h"
40 using namespace llvm;
41
42 //===----------------------------------------------------------------------===//
43 // MachineOperand Implementation
44 //===----------------------------------------------------------------------===//
45
46 /// AddRegOperandToRegInfo - Add this register operand to the specified
47 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
48 /// explicitly nulled out.
49 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
50   assert(isReg() && "Can only add reg operand to use lists");
51   
52   // If the reginfo pointer is null, just explicitly null out or next/prev
53   // pointers, to ensure they are not garbage.
54   if (RegInfo == 0) {
55     Contents.Reg.Prev = 0;
56     Contents.Reg.Next = 0;
57     return;
58   }
59   
60   // Otherwise, add this operand to the head of the registers use/def list.
61   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
62   
63   // For SSA values, we prefer to keep the definition at the start of the list.
64   // we do this by skipping over the definition if it is at the head of the
65   // list.
66   if (*Head && (*Head)->isDef())
67     Head = &(*Head)->Contents.Reg.Next;
68   
69   Contents.Reg.Next = *Head;
70   if (Contents.Reg.Next) {
71     assert(getReg() == Contents.Reg.Next->getReg() &&
72            "Different regs on the same list!");
73     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
74   }
75   
76   Contents.Reg.Prev = Head;
77   *Head = this;
78 }
79
80 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
81 /// MachineRegisterInfo it is linked with.
82 void MachineOperand::RemoveRegOperandFromRegInfo() {
83   assert(isOnRegUseList() && "Reg operand is not on a use list");
84   // Unlink this from the doubly linked list of operands.
85   MachineOperand *NextOp = Contents.Reg.Next;
86   *Contents.Reg.Prev = NextOp; 
87   if (NextOp) {
88     assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
89     NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
90   }
91   Contents.Reg.Prev = 0;
92   Contents.Reg.Next = 0;
93 }
94
95 void MachineOperand::setReg(unsigned Reg) {
96   if (getReg() == Reg) return; // No change.
97   
98   // Otherwise, we have to change the register.  If this operand is embedded
99   // into a machine function, we need to update the old and new register's
100   // use/def lists.
101   if (MachineInstr *MI = getParent())
102     if (MachineBasicBlock *MBB = MI->getParent())
103       if (MachineFunction *MF = MBB->getParent()) {
104         RemoveRegOperandFromRegInfo();
105         Contents.Reg.RegNo = Reg;
106         AddRegOperandToRegInfo(&MF->getRegInfo());
107         return;
108       }
109         
110   // Otherwise, just change the register, no problem.  :)
111   Contents.Reg.RegNo = Reg;
112 }
113
114 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
115                                   const TargetRegisterInfo &TRI) {
116   assert(TargetRegisterInfo::isVirtualRegister(Reg));
117   if (SubIdx && getSubReg())
118     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
119   setReg(Reg);
120   if (SubIdx)
121     setSubReg(SubIdx);
122 }
123
124 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
125   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
126   if (getSubReg()) {
127     Reg = TRI.getSubReg(Reg, getSubReg());
128     assert(Reg && "Invalid SubReg for physical register");
129     setSubReg(0);
130   }
131   setReg(Reg);
132 }
133
134 /// ChangeToImmediate - Replace this operand with a new immediate operand of
135 /// the specified value.  If an operand is known to be an immediate already,
136 /// the setImm method should be used.
137 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
138   // If this operand is currently a register operand, and if this is in a
139   // function, deregister the operand from the register's use/def list.
140   if (isReg() && getParent() && getParent()->getParent() &&
141       getParent()->getParent()->getParent())
142     RemoveRegOperandFromRegInfo();
143   
144   OpKind = MO_Immediate;
145   Contents.ImmVal = ImmVal;
146 }
147
148 /// ChangeToRegister - Replace this operand with a new register operand of
149 /// the specified value.  If an operand is known to be an register already,
150 /// the setReg method should be used.
151 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
152                                       bool isKill, bool isDead, bool isUndef,
153                                       bool isDebug) {
154   // If this operand is already a register operand, use setReg to update the 
155   // register's use/def lists.
156   if (isReg()) {
157     assert(!isEarlyClobber());
158     setReg(Reg);
159   } else {
160     // Otherwise, change this to a register and set the reg#.
161     OpKind = MO_Register;
162     Contents.Reg.RegNo = Reg;
163
164     // If this operand is embedded in a function, add the operand to the
165     // register's use/def list.
166     if (MachineInstr *MI = getParent())
167       if (MachineBasicBlock *MBB = MI->getParent())
168         if (MachineFunction *MF = MBB->getParent())
169           AddRegOperandToRegInfo(&MF->getRegInfo());
170   }
171
172   IsDef = isDef;
173   IsImp = isImp;
174   IsKill = isKill;
175   IsDead = isDead;
176   IsUndef = isUndef;
177   IsEarlyClobber = false;
178   IsDebug = isDebug;
179   SubReg = 0;
180 }
181
182 /// isIdenticalTo - Return true if this operand is identical to the specified
183 /// operand.
184 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
185   if (getType() != Other.getType() ||
186       getTargetFlags() != Other.getTargetFlags())
187     return false;
188   
189   switch (getType()) {
190   default: llvm_unreachable("Unrecognized operand type");
191   case MachineOperand::MO_Register:
192     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
193            getSubReg() == Other.getSubReg();
194   case MachineOperand::MO_Immediate:
195     return getImm() == Other.getImm();
196   case MachineOperand::MO_FPImmediate:
197     return getFPImm() == Other.getFPImm();
198   case MachineOperand::MO_MachineBasicBlock:
199     return getMBB() == Other.getMBB();
200   case MachineOperand::MO_FrameIndex:
201     return getIndex() == Other.getIndex();
202   case MachineOperand::MO_ConstantPoolIndex:
203     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
204   case MachineOperand::MO_JumpTableIndex:
205     return getIndex() == Other.getIndex();
206   case MachineOperand::MO_GlobalAddress:
207     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
208   case MachineOperand::MO_ExternalSymbol:
209     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
210            getOffset() == Other.getOffset();
211   case MachineOperand::MO_BlockAddress:
212     return getBlockAddress() == Other.getBlockAddress();
213   case MachineOperand::MO_MCSymbol:
214     return getMCSymbol() == Other.getMCSymbol();
215   case MachineOperand::MO_Metadata:
216     return getMetadata() == Other.getMetadata();
217   }
218 }
219
220 /// print - Print the specified machine operand.
221 ///
222 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
223   // If the instruction is embedded into a basic block, we can find the
224   // target info for the instruction.
225   if (!TM)
226     if (const MachineInstr *MI = getParent())
227       if (const MachineBasicBlock *MBB = MI->getParent())
228         if (const MachineFunction *MF = MBB->getParent())
229           TM = &MF->getTarget();
230
231   switch (getType()) {
232   case MachineOperand::MO_Register:
233     if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
234       OS << "%reg" << getReg();
235     } else {
236       if (TM)
237         OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
238       else
239         OS << "%physreg" << getReg();
240     }
241
242     if (getSubReg() != 0) {
243       if (TM)
244         OS << ':' << TM->getRegisterInfo()->getSubRegIndexName(getSubReg());
245       else
246         OS << ':' << getSubReg();
247     }
248
249     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
250         isEarlyClobber()) {
251       OS << '<';
252       bool NeedComma = false;
253       if (isDef()) {
254         if (NeedComma) OS << ',';
255         if (isEarlyClobber())
256           OS << "earlyclobber,";
257         if (isImplicit())
258           OS << "imp-";
259         OS << "def";
260         NeedComma = true;
261       } else if (isImplicit()) {
262           OS << "imp-use";
263           NeedComma = true;
264       }
265
266       if (isKill() || isDead() || isUndef()) {
267         if (NeedComma) OS << ',';
268         if (isKill())  OS << "kill";
269         if (isDead())  OS << "dead";
270         if (isUndef()) {
271           if (isKill() || isDead())
272             OS << ',';
273           OS << "undef";
274         }
275       }
276       OS << '>';
277     }
278     break;
279   case MachineOperand::MO_Immediate:
280     OS << getImm();
281     break;
282   case MachineOperand::MO_FPImmediate:
283     if (getFPImm()->getType()->isFloatTy())
284       OS << getFPImm()->getValueAPF().convertToFloat();
285     else
286       OS << getFPImm()->getValueAPF().convertToDouble();
287     break;
288   case MachineOperand::MO_MachineBasicBlock:
289     OS << "<BB#" << getMBB()->getNumber() << ">";
290     break;
291   case MachineOperand::MO_FrameIndex:
292     OS << "<fi#" << getIndex() << '>';
293     break;
294   case MachineOperand::MO_ConstantPoolIndex:
295     OS << "<cp#" << getIndex();
296     if (getOffset()) OS << "+" << getOffset();
297     OS << '>';
298     break;
299   case MachineOperand::MO_JumpTableIndex:
300     OS << "<jt#" << getIndex() << '>';
301     break;
302   case MachineOperand::MO_GlobalAddress:
303     OS << "<ga:";
304     WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
305     if (getOffset()) OS << "+" << getOffset();
306     OS << '>';
307     break;
308   case MachineOperand::MO_ExternalSymbol:
309     OS << "<es:" << getSymbolName();
310     if (getOffset()) OS << "+" << getOffset();
311     OS << '>';
312     break;
313   case MachineOperand::MO_BlockAddress:
314     OS << '<';
315     WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
316     OS << '>';
317     break;
318   case MachineOperand::MO_Metadata:
319     OS << '<';
320     WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
321     OS << '>';
322     break;
323   case MachineOperand::MO_MCSymbol:
324     OS << "<MCSym=" << *getMCSymbol() << '>';
325     break;
326   default:
327     llvm_unreachable("Unrecognized operand type");
328   }
329   
330   if (unsigned TF = getTargetFlags())
331     OS << "[TF=" << TF << ']';
332 }
333
334 //===----------------------------------------------------------------------===//
335 // MachineMemOperand Implementation
336 //===----------------------------------------------------------------------===//
337
338 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
339                                      int64_t o, uint64_t s, unsigned int a)
340   : Offset(o), Size(s), V(v),
341     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)) {
342   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
343   assert((isLoad() || isStore()) && "Not a load/store!");
344 }
345
346 /// Profile - Gather unique data for the object.
347 ///
348 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
349   ID.AddInteger(Offset);
350   ID.AddInteger(Size);
351   ID.AddPointer(V);
352   ID.AddInteger(Flags);
353 }
354
355 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
356   // The Value and Offset may differ due to CSE. But the flags and size
357   // should be the same.
358   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
359   assert(MMO->getSize() == getSize() && "Size mismatch!");
360
361   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
362     // Update the alignment value.
363     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
364       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
365     // Also update the base and offset, because the new alignment may
366     // not be applicable with the old ones.
367     V = MMO->getValue();
368     Offset = MMO->getOffset();
369   }
370 }
371
372 /// getAlignment - Return the minimum known alignment in bytes of the
373 /// actual memory reference.
374 uint64_t MachineMemOperand::getAlignment() const {
375   return MinAlign(getBaseAlignment(), getOffset());
376 }
377
378 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
379   assert((MMO.isLoad() || MMO.isStore()) &&
380          "SV has to be a load, store or both.");
381   
382   if (MMO.isVolatile())
383     OS << "Volatile ";
384
385   if (MMO.isLoad())
386     OS << "LD";
387   if (MMO.isStore())
388     OS << "ST";
389   OS << MMO.getSize();
390   
391   // Print the address information.
392   OS << "[";
393   if (!MMO.getValue())
394     OS << "<unknown>";
395   else
396     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
397
398   // If the alignment of the memory reference itself differs from the alignment
399   // of the base pointer, print the base alignment explicitly, next to the base
400   // pointer.
401   if (MMO.getBaseAlignment() != MMO.getAlignment())
402     OS << "(align=" << MMO.getBaseAlignment() << ")";
403
404   if (MMO.getOffset() != 0)
405     OS << "+" << MMO.getOffset();
406   OS << "]";
407
408   // Print the alignment of the reference.
409   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
410       MMO.getBaseAlignment() != MMO.getSize())
411     OS << "(align=" << MMO.getAlignment() << ")";
412
413   return OS;
414 }
415
416 //===----------------------------------------------------------------------===//
417 // MachineInstr Implementation
418 //===----------------------------------------------------------------------===//
419
420 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
421 /// TID NULL and no operands.
422 MachineInstr::MachineInstr()
423   : TID(0), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
424     Parent(0) {
425   // Make sure that we get added to a machine basicblock
426   LeakDetector::addGarbageObject(this);
427 }
428
429 void MachineInstr::addImplicitDefUseOperands() {
430   if (TID->ImplicitDefs)
431     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
432       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
433   if (TID->ImplicitUses)
434     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
435       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
436 }
437
438 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
439 /// implicit operands. It reserves space for the number of operands specified by
440 /// the TargetInstrDesc.
441 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
442   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
443     MemRefs(0), MemRefsEnd(0), Parent(0) {
444   if (!NoImp)
445     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
446   Operands.reserve(NumImplicitOps + TID->getNumOperands());
447   if (!NoImp)
448     addImplicitDefUseOperands();
449   // Make sure that we get added to a machine basicblock
450   LeakDetector::addGarbageObject(this);
451 }
452
453 /// MachineInstr ctor - As above, but with a DebugLoc.
454 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
455                            bool NoImp)
456   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
457     Parent(0), debugLoc(dl) {
458   if (!NoImp)
459     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
460   Operands.reserve(NumImplicitOps + TID->getNumOperands());
461   if (!NoImp)
462     addImplicitDefUseOperands();
463   // Make sure that we get added to a machine basicblock
464   LeakDetector::addGarbageObject(this);
465 }
466
467 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
468 /// that the MachineInstr is created and added to the end of the specified 
469 /// basic block.
470 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
471   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
472     MemRefs(0), MemRefsEnd(0), Parent(0) {
473   assert(MBB && "Cannot use inserting ctor with null basic block!");
474   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
475   Operands.reserve(NumImplicitOps + TID->getNumOperands());
476   addImplicitDefUseOperands();
477   // Make sure that we get added to a machine basicblock
478   LeakDetector::addGarbageObject(this);
479   MBB->push_back(this);  // Add instruction to end of basic block!
480 }
481
482 /// MachineInstr ctor - As above, but with a DebugLoc.
483 ///
484 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
485                            const TargetInstrDesc &tid)
486   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
487     Parent(0), debugLoc(dl) {
488   assert(MBB && "Cannot use inserting ctor with null basic block!");
489   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
490   Operands.reserve(NumImplicitOps + TID->getNumOperands());
491   addImplicitDefUseOperands();
492   // Make sure that we get added to a machine basicblock
493   LeakDetector::addGarbageObject(this);
494   MBB->push_back(this);  // Add instruction to end of basic block!
495 }
496
497 /// MachineInstr ctor - Copies MachineInstr arg exactly
498 ///
499 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
500   : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
501     MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
502     Parent(0), debugLoc(MI.getDebugLoc()) {
503   Operands.reserve(MI.getNumOperands());
504
505   // Add operands
506   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
507     addOperand(MI.getOperand(i));
508   NumImplicitOps = MI.NumImplicitOps;
509
510   // Set parent to null.
511   Parent = 0;
512
513   LeakDetector::addGarbageObject(this);
514 }
515
516 MachineInstr::~MachineInstr() {
517   LeakDetector::removeGarbageObject(this);
518 #ifndef NDEBUG
519   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
520     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
521     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
522            "Reg operand def/use list corrupted");
523   }
524 #endif
525 }
526
527 /// getRegInfo - If this instruction is embedded into a MachineFunction,
528 /// return the MachineRegisterInfo object for the current function, otherwise
529 /// return null.
530 MachineRegisterInfo *MachineInstr::getRegInfo() {
531   if (MachineBasicBlock *MBB = getParent())
532     return &MBB->getParent()->getRegInfo();
533   return 0;
534 }
535
536 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
537 /// this instruction from their respective use lists.  This requires that the
538 /// operands already be on their use lists.
539 void MachineInstr::RemoveRegOperandsFromUseLists() {
540   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
541     if (Operands[i].isReg())
542       Operands[i].RemoveRegOperandFromRegInfo();
543   }
544 }
545
546 /// AddRegOperandsToUseLists - Add all of the register operands in
547 /// this instruction from their respective use lists.  This requires that the
548 /// operands not be on their use lists yet.
549 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
550   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
551     if (Operands[i].isReg())
552       Operands[i].AddRegOperandToRegInfo(&RegInfo);
553   }
554 }
555
556
557 /// addOperand - Add the specified operand to the instruction.  If it is an
558 /// implicit operand, it is added to the end of the operand list.  If it is
559 /// an explicit operand it is added at the end of the explicit operand list
560 /// (before the first implicit operand). 
561 void MachineInstr::addOperand(const MachineOperand &Op) {
562   bool isImpReg = Op.isReg() && Op.isImplicit();
563   assert((isImpReg || !OperandsComplete()) &&
564          "Trying to add an operand to a machine instr that is already done!");
565
566   MachineRegisterInfo *RegInfo = getRegInfo();
567
568   // If we are adding the operand to the end of the list, our job is simpler.
569   // This is true most of the time, so this is a reasonable optimization.
570   if (isImpReg || NumImplicitOps == 0) {
571     // We can only do this optimization if we know that the operand list won't
572     // reallocate.
573     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
574       Operands.push_back(Op);
575     
576       // Set the parent of the operand.
577       Operands.back().ParentMI = this;
578   
579       // If the operand is a register, update the operand's use list.
580       if (Op.isReg()) {
581         Operands.back().AddRegOperandToRegInfo(RegInfo);
582         // If the register operand is flagged as early, mark the operand as such
583         unsigned OpNo = Operands.size() - 1;
584         if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
585           Operands[OpNo].setIsEarlyClobber(true);
586       }
587       return;
588     }
589   }
590   
591   // Otherwise, we have to insert a real operand before any implicit ones.
592   unsigned OpNo = Operands.size()-NumImplicitOps;
593
594   // If this instruction isn't embedded into a function, then we don't need to
595   // update any operand lists.
596   if (RegInfo == 0) {
597     // Simple insertion, no reginfo update needed for other register operands.
598     Operands.insert(Operands.begin()+OpNo, Op);
599     Operands[OpNo].ParentMI = this;
600
601     // Do explicitly set the reginfo for this operand though, to ensure the
602     // next/prev fields are properly nulled out.
603     if (Operands[OpNo].isReg()) {
604       Operands[OpNo].AddRegOperandToRegInfo(0);
605       // If the register operand is flagged as early, mark the operand as such
606       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
607         Operands[OpNo].setIsEarlyClobber(true);
608     }
609
610   } else if (Operands.size()+1 <= Operands.capacity()) {
611     // Otherwise, we have to remove register operands from their register use
612     // list, add the operand, then add the register operands back to their use
613     // list.  This also must handle the case when the operand list reallocates
614     // to somewhere else.
615   
616     // If insertion of this operand won't cause reallocation of the operand
617     // list, just remove the implicit operands, add the operand, then re-add all
618     // the rest of the operands.
619     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
620       assert(Operands[i].isReg() && "Should only be an implicit reg!");
621       Operands[i].RemoveRegOperandFromRegInfo();
622     }
623     
624     // Add the operand.  If it is a register, add it to the reg list.
625     Operands.insert(Operands.begin()+OpNo, Op);
626     Operands[OpNo].ParentMI = this;
627
628     if (Operands[OpNo].isReg()) {
629       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
630       // If the register operand is flagged as early, mark the operand as such
631       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
632         Operands[OpNo].setIsEarlyClobber(true);
633     }
634     
635     // Re-add all the implicit ops.
636     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
637       assert(Operands[i].isReg() && "Should only be an implicit reg!");
638       Operands[i].AddRegOperandToRegInfo(RegInfo);
639     }
640   } else {
641     // Otherwise, we will be reallocating the operand list.  Remove all reg
642     // operands from their list, then readd them after the operand list is
643     // reallocated.
644     RemoveRegOperandsFromUseLists();
645     
646     Operands.insert(Operands.begin()+OpNo, Op);
647     Operands[OpNo].ParentMI = this;
648   
649     // Re-add all the operands.
650     AddRegOperandsToUseLists(*RegInfo);
651
652       // If the register operand is flagged as early, mark the operand as such
653     if (Operands[OpNo].isReg()
654         && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
655       Operands[OpNo].setIsEarlyClobber(true);
656   }
657 }
658
659 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
660 /// fewer operand than it started with.
661 ///
662 void MachineInstr::RemoveOperand(unsigned OpNo) {
663   assert(OpNo < Operands.size() && "Invalid operand number");
664   
665   // Special case removing the last one.
666   if (OpNo == Operands.size()-1) {
667     // If needed, remove from the reg def/use list.
668     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
669       Operands.back().RemoveRegOperandFromRegInfo();
670     
671     Operands.pop_back();
672     return;
673   }
674
675   // Otherwise, we are removing an interior operand.  If we have reginfo to
676   // update, remove all operands that will be shifted down from their reg lists,
677   // move everything down, then re-add them.
678   MachineRegisterInfo *RegInfo = getRegInfo();
679   if (RegInfo) {
680     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
681       if (Operands[i].isReg())
682         Operands[i].RemoveRegOperandFromRegInfo();
683     }
684   }
685   
686   Operands.erase(Operands.begin()+OpNo);
687
688   if (RegInfo) {
689     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
690       if (Operands[i].isReg())
691         Operands[i].AddRegOperandToRegInfo(RegInfo);
692     }
693   }
694 }
695
696 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
697 /// This function should be used only occasionally. The setMemRefs function
698 /// is the primary method for setting up a MachineInstr's MemRefs list.
699 void MachineInstr::addMemOperand(MachineFunction &MF,
700                                  MachineMemOperand *MO) {
701   mmo_iterator OldMemRefs = MemRefs;
702   mmo_iterator OldMemRefsEnd = MemRefsEnd;
703
704   size_t NewNum = (MemRefsEnd - MemRefs) + 1;
705   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
706   mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
707
708   std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
709   NewMemRefs[NewNum - 1] = MO;
710
711   MemRefs = NewMemRefs;
712   MemRefsEnd = NewMemRefsEnd;
713 }
714
715 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
716                                  MICheckType Check) const {
717   // If opcodes or number of operands are not the same then the two
718   // instructions are obviously not identical.
719   if (Other->getOpcode() != getOpcode() ||
720       Other->getNumOperands() != getNumOperands())
721     return false;
722
723   // Check operands to make sure they match.
724   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
725     const MachineOperand &MO = getOperand(i);
726     const MachineOperand &OMO = Other->getOperand(i);
727     // Clients may or may not want to ignore defs when testing for equality.
728     // For example, machine CSE pass only cares about finding common
729     // subexpressions, so it's safe to ignore virtual register defs.
730     if (Check != CheckDefs && MO.isReg() && MO.isDef()) {
731       if (Check == IgnoreDefs)
732         continue;
733       // Check == IgnoreVRegDefs
734       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
735           TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
736         if (MO.getReg() != OMO.getReg())
737           return false;
738     } else if (!MO.isIdenticalTo(OMO))
739       return false;
740   }
741   return true;
742 }
743
744 /// removeFromParent - This method unlinks 'this' from the containing basic
745 /// block, and returns it, but does not delete it.
746 MachineInstr *MachineInstr::removeFromParent() {
747   assert(getParent() && "Not embedded in a basic block!");
748   getParent()->remove(this);
749   return this;
750 }
751
752
753 /// eraseFromParent - This method unlinks 'this' from the containing basic
754 /// block, and deletes it.
755 void MachineInstr::eraseFromParent() {
756   assert(getParent() && "Not embedded in a basic block!");
757   getParent()->erase(this);
758 }
759
760
761 /// OperandComplete - Return true if it's illegal to add a new operand
762 ///
763 bool MachineInstr::OperandsComplete() const {
764   unsigned short NumOperands = TID->getNumOperands();
765   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
766     return true;  // Broken: we have all the operands of this instruction!
767   return false;
768 }
769
770 /// getNumExplicitOperands - Returns the number of non-implicit operands.
771 ///
772 unsigned MachineInstr::getNumExplicitOperands() const {
773   unsigned NumOperands = TID->getNumOperands();
774   if (!TID->isVariadic())
775     return NumOperands;
776
777   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
778     const MachineOperand &MO = getOperand(i);
779     if (!MO.isReg() || !MO.isImplicit())
780       NumOperands++;
781   }
782   return NumOperands;
783 }
784
785
786 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
787 /// the specific register or -1 if it is not found. It further tightens
788 /// the search criteria to a use that kills the register if isKill is true.
789 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
790                                           const TargetRegisterInfo *TRI) const {
791   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
792     const MachineOperand &MO = getOperand(i);
793     if (!MO.isReg() || !MO.isUse())
794       continue;
795     unsigned MOReg = MO.getReg();
796     if (!MOReg)
797       continue;
798     if (MOReg == Reg ||
799         (TRI &&
800          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
801          TargetRegisterInfo::isPhysicalRegister(Reg) &&
802          TRI->isSubRegister(MOReg, Reg)))
803       if (!isKill || MO.isKill())
804         return i;
805   }
806   return -1;
807 }
808
809 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
810 /// indicating if this instruction reads or writes Reg. This also considers
811 /// partial defines.
812 std::pair<bool,bool>
813 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
814                                          SmallVectorImpl<unsigned> *Ops) const {
815   bool PartDef = false; // Partial redefine.
816   bool FullDef = false; // Full define.
817   bool Use = false;
818
819   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
820     const MachineOperand &MO = getOperand(i);
821     if (!MO.isReg() || MO.getReg() != Reg)
822       continue;
823     if (Ops)
824       Ops->push_back(i);
825     if (MO.isUse())
826       Use |= !MO.isUndef();
827     else if (MO.getSubReg())
828       PartDef = true;
829     else
830       FullDef = true;
831   }
832   // A partial redefine uses Reg unless there is also a full define.
833   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
834 }
835
836 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
837 /// the specified register or -1 if it is not found. If isDead is true, defs
838 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
839 /// also checks if there is a def of a super-register.
840 int
841 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
842                                         const TargetRegisterInfo *TRI) const {
843   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
844   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
845     const MachineOperand &MO = getOperand(i);
846     if (!MO.isReg() || !MO.isDef())
847       continue;
848     unsigned MOReg = MO.getReg();
849     bool Found = (MOReg == Reg);
850     if (!Found && TRI && isPhys &&
851         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
852       if (Overlap)
853         Found = TRI->regsOverlap(MOReg, Reg);
854       else
855         Found = TRI->isSubRegister(MOReg, Reg);
856     }
857     if (Found && (!isDead || MO.isDead()))
858       return i;
859   }
860   return -1;
861 }
862
863 /// findFirstPredOperandIdx() - Find the index of the first operand in the
864 /// operand list that is used to represent the predicate. It returns -1 if
865 /// none is found.
866 int MachineInstr::findFirstPredOperandIdx() const {
867   const TargetInstrDesc &TID = getDesc();
868   if (TID.isPredicable()) {
869     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
870       if (TID.OpInfo[i].isPredicate())
871         return i;
872   }
873
874   return -1;
875 }
876   
877 /// isRegTiedToUseOperand - Given the index of a register def operand,
878 /// check if the register def is tied to a source operand, due to either
879 /// two-address elimination or inline assembly constraints. Returns the
880 /// first tied use operand index by reference is UseOpIdx is not null.
881 bool MachineInstr::
882 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
883   if (isInlineAsm()) {
884     assert(DefOpIdx >= 2);
885     const MachineOperand &MO = getOperand(DefOpIdx);
886     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
887       return false;
888     // Determine the actual operand index that corresponds to this index.
889     unsigned DefNo = 0;
890     unsigned DefPart = 0;
891     for (unsigned i = 1, e = getNumOperands(); i < e; ) {
892       const MachineOperand &FMO = getOperand(i);
893       // After the normal asm operands there may be additional imp-def regs.
894       if (!FMO.isImm())
895         return false;
896       // Skip over this def.
897       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
898       unsigned PrevDef = i + 1;
899       i = PrevDef + NumOps;
900       if (i > DefOpIdx) {
901         DefPart = DefOpIdx - PrevDef;
902         break;
903       }
904       ++DefNo;
905     }
906     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
907       const MachineOperand &FMO = getOperand(i);
908       if (!FMO.isImm())
909         continue;
910       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
911         continue;
912       unsigned Idx;
913       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
914           Idx == DefNo) {
915         if (UseOpIdx)
916           *UseOpIdx = (unsigned)i + 1 + DefPart;
917         return true;
918       }
919     }
920     return false;
921   }
922
923   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
924   const TargetInstrDesc &TID = getDesc();
925   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
926     const MachineOperand &MO = getOperand(i);
927     if (MO.isReg() && MO.isUse() &&
928         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
929       if (UseOpIdx)
930         *UseOpIdx = (unsigned)i;
931       return true;
932     }
933   }
934   return false;
935 }
936
937 /// isRegTiedToDefOperand - Return true if the operand of the specified index
938 /// is a register use and it is tied to an def operand. It also returns the def
939 /// operand index by reference.
940 bool MachineInstr::
941 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
942   if (isInlineAsm()) {
943     const MachineOperand &MO = getOperand(UseOpIdx);
944     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
945       return false;
946
947     // Find the flag operand corresponding to UseOpIdx
948     unsigned FlagIdx, NumOps=0;
949     for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
950       const MachineOperand &UFMO = getOperand(FlagIdx);
951       // After the normal asm operands there may be additional imp-def regs.
952       if (!UFMO.isImm())
953         return false;
954       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
955       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
956       if (UseOpIdx < FlagIdx+NumOps+1)
957         break;
958     }
959     if (FlagIdx >= UseOpIdx)
960       return false;
961     const MachineOperand &UFMO = getOperand(FlagIdx);
962     unsigned DefNo;
963     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
964       if (!DefOpIdx)
965         return true;
966
967       unsigned DefIdx = 1;
968       // Remember to adjust the index. First operand is asm string, then there
969       // is a flag for each.
970       while (DefNo) {
971         const MachineOperand &FMO = getOperand(DefIdx);
972         assert(FMO.isImm());
973         // Skip over this def.
974         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
975         --DefNo;
976       }
977       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
978       return true;
979     }
980     return false;
981   }
982
983   const TargetInstrDesc &TID = getDesc();
984   if (UseOpIdx >= TID.getNumOperands())
985     return false;
986   const MachineOperand &MO = getOperand(UseOpIdx);
987   if (!MO.isReg() || !MO.isUse())
988     return false;
989   int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
990   if (DefIdx == -1)
991     return false;
992   if (DefOpIdx)
993     *DefOpIdx = (unsigned)DefIdx;
994   return true;
995 }
996
997 /// clearKillInfo - Clears kill flags on all operands.
998 ///
999 void MachineInstr::clearKillInfo() {
1000   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1001     MachineOperand &MO = getOperand(i);
1002     if (MO.isReg() && MO.isUse())
1003       MO.setIsKill(false);
1004   }
1005 }
1006
1007 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1008 ///
1009 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1010   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1011     const MachineOperand &MO = MI->getOperand(i);
1012     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1013       continue;
1014     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1015       MachineOperand &MOp = getOperand(j);
1016       if (!MOp.isIdenticalTo(MO))
1017         continue;
1018       if (MO.isKill())
1019         MOp.setIsKill();
1020       else
1021         MOp.setIsDead();
1022       break;
1023     }
1024   }
1025 }
1026
1027 /// copyPredicates - Copies predicate operand(s) from MI.
1028 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1029   const TargetInstrDesc &TID = MI->getDesc();
1030   if (!TID.isPredicable())
1031     return;
1032   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1033     if (TID.OpInfo[i].isPredicate()) {
1034       // Predicated operands must be last operands.
1035       addOperand(MI->getOperand(i));
1036     }
1037   }
1038 }
1039
1040 /// isSafeToMove - Return true if it is safe to move this instruction. If
1041 /// SawStore is set to true, it means that there is a store (or call) between
1042 /// the instruction's location and its intended destination.
1043 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1044                                 AliasAnalysis *AA,
1045                                 bool &SawStore) const {
1046   // Ignore stuff that we obviously can't move.
1047   if (TID->mayStore() || TID->isCall()) {
1048     SawStore = true;
1049     return false;
1050   }
1051   if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
1052     return false;
1053
1054   // See if this instruction does a load.  If so, we have to guarantee that the
1055   // loaded value doesn't change between the load and the its intended
1056   // destination. The check for isInvariantLoad gives the targe the chance to
1057   // classify the load as always returning a constant, e.g. a constant pool
1058   // load.
1059   if (TID->mayLoad() && !isInvariantLoad(AA))
1060     // Otherwise, this is a real load.  If there is a store between the load and
1061     // end of block, or if the load is volatile, we can't move it.
1062     return !SawStore && !hasVolatileMemoryRef();
1063
1064   return true;
1065 }
1066
1067 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1068 /// instruction which defined the specified register instead of copying it.
1069 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1070                                  AliasAnalysis *AA,
1071                                  unsigned DstReg) const {
1072   bool SawStore = false;
1073   if (!TII->isTriviallyReMaterializable(this, AA) ||
1074       !isSafeToMove(TII, AA, SawStore))
1075     return false;
1076   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1077     const MachineOperand &MO = getOperand(i);
1078     if (!MO.isReg())
1079       continue;
1080     // FIXME: For now, do not remat any instruction with register operands.
1081     // Later on, we can loosen the restriction is the register operands have
1082     // not been modified between the def and use. Note, this is different from
1083     // MachineSink because the code is no longer in two-address form (at least
1084     // partially).
1085     if (MO.isUse())
1086       return false;
1087     else if (!MO.isDead() && MO.getReg() != DstReg)
1088       return false;
1089   }
1090   return true;
1091 }
1092
1093 /// hasVolatileMemoryRef - Return true if this instruction may have a
1094 /// volatile memory reference, or if the information describing the
1095 /// memory reference is not available. Return false if it is known to
1096 /// have no volatile memory references.
1097 bool MachineInstr::hasVolatileMemoryRef() const {
1098   // An instruction known never to access memory won't have a volatile access.
1099   if (!TID->mayStore() &&
1100       !TID->mayLoad() &&
1101       !TID->isCall() &&
1102       !TID->hasUnmodeledSideEffects())
1103     return false;
1104
1105   // Otherwise, if the instruction has no memory reference information,
1106   // conservatively assume it wasn't preserved.
1107   if (memoperands_empty())
1108     return true;
1109   
1110   // Check the memory reference information for volatile references.
1111   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1112     if ((*I)->isVolatile())
1113       return true;
1114
1115   return false;
1116 }
1117
1118 /// isInvariantLoad - Return true if this instruction is loading from a
1119 /// location whose value is invariant across the function.  For example,
1120 /// loading a value from the constant pool or from the argument area
1121 /// of a function if it does not change.  This should only return true of
1122 /// *all* loads the instruction does are invariant (if it does multiple loads).
1123 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1124   // If the instruction doesn't load at all, it isn't an invariant load.
1125   if (!TID->mayLoad())
1126     return false;
1127
1128   // If the instruction has lost its memoperands, conservatively assume that
1129   // it may not be an invariant load.
1130   if (memoperands_empty())
1131     return false;
1132
1133   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1134
1135   for (mmo_iterator I = memoperands_begin(),
1136        E = memoperands_end(); I != E; ++I) {
1137     if ((*I)->isVolatile()) return false;
1138     if ((*I)->isStore()) return false;
1139
1140     if (const Value *V = (*I)->getValue()) {
1141       // A load from a constant PseudoSourceValue is invariant.
1142       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1143         if (PSV->isConstant(MFI))
1144           continue;
1145       // If we have an AliasAnalysis, ask it whether the memory is constant.
1146       if (AA && AA->pointsToConstantMemory(V))
1147         continue;
1148     }
1149
1150     // Otherwise assume conservatively.
1151     return false;
1152   }
1153
1154   // Everything checks out.
1155   return true;
1156 }
1157
1158 /// isConstantValuePHI - If the specified instruction is a PHI that always
1159 /// merges together the same virtual register, return the register, otherwise
1160 /// return 0.
1161 unsigned MachineInstr::isConstantValuePHI() const {
1162   if (!isPHI())
1163     return 0;
1164   assert(getNumOperands() >= 3 &&
1165          "It's illegal to have a PHI without source operands");
1166
1167   unsigned Reg = getOperand(1).getReg();
1168   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1169     if (getOperand(i).getReg() != Reg)
1170       return 0;
1171   return Reg;
1172 }
1173
1174 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1175 ///
1176 bool MachineInstr::allDefsAreDead() const {
1177   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1178     const MachineOperand &MO = getOperand(i);
1179     if (!MO.isReg() || MO.isUse())
1180       continue;
1181     if (!MO.isDead())
1182       return false;
1183   }
1184   return true;
1185 }
1186
1187 void MachineInstr::dump() const {
1188   dbgs() << "  " << *this;
1189 }
1190
1191 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1192   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1193   const MachineFunction *MF = 0;
1194   if (const MachineBasicBlock *MBB = getParent()) {
1195     MF = MBB->getParent();
1196     if (!TM && MF)
1197       TM = &MF->getTarget();
1198   }
1199
1200   // Print explicitly defined operands on the left of an assignment syntax.
1201   unsigned StartOp = 0, e = getNumOperands();
1202   for (; StartOp < e && getOperand(StartOp).isReg() &&
1203          getOperand(StartOp).isDef() &&
1204          !getOperand(StartOp).isImplicit();
1205        ++StartOp) {
1206     if (StartOp != 0) OS << ", ";
1207     getOperand(StartOp).print(OS, TM);
1208   }
1209
1210   if (StartOp != 0)
1211     OS << " = ";
1212
1213   // Print the opcode name.
1214   OS << getDesc().getName();
1215
1216   // Print the rest of the operands.
1217   bool OmittedAnyCallClobbers = false;
1218   bool FirstOp = true;
1219   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1220     const MachineOperand &MO = getOperand(i);
1221
1222     // Omit call-clobbered registers which aren't used anywhere. This makes
1223     // call instructions much less noisy on targets where calls clobber lots
1224     // of registers. Don't rely on MO.isDead() because we may be called before
1225     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1226     if (MF && getDesc().isCall() &&
1227         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1228       unsigned Reg = MO.getReg();
1229       if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1230         const MachineRegisterInfo &MRI = MF->getRegInfo();
1231         if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1232           bool HasAliasLive = false;
1233           for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1234                unsigned AliasReg = *Alias; ++Alias)
1235             if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1236               HasAliasLive = true;
1237               break;
1238             }
1239           if (!HasAliasLive) {
1240             OmittedAnyCallClobbers = true;
1241             continue;
1242           }
1243         }
1244       }
1245     }
1246
1247     if (FirstOp) FirstOp = false; else OS << ",";
1248     OS << " ";
1249     if (i < getDesc().NumOperands) {
1250       const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1251       if (TOI.isPredicate())
1252         OS << "pred:";
1253       if (TOI.isOptionalDef())
1254         OS << "opt:";
1255     }
1256     if (isDebugValue() && MO.isMetadata()) {
1257       // Pretty print DBG_VALUE instructions.
1258       const MDNode *MD = MO.getMetadata();
1259       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1260         OS << "!\"" << MDS->getString() << '\"';
1261       else
1262         MO.print(OS, TM);
1263     } else
1264       MO.print(OS, TM);
1265   }
1266
1267   // Briefly indicate whether any call clobbers were omitted.
1268   if (OmittedAnyCallClobbers) {
1269     if (!FirstOp) OS << ",";
1270     OS << " ...";
1271   }
1272
1273   bool HaveSemi = false;
1274   if (!memoperands_empty()) {
1275     if (!HaveSemi) OS << ";"; HaveSemi = true;
1276
1277     OS << " mem:";
1278     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1279          i != e; ++i) {
1280       OS << **i;
1281       if (next(i) != e)
1282         OS << " ";
1283     }
1284   }
1285
1286   if (!debugLoc.isUnknown() && MF) {
1287     if (!HaveSemi) OS << ";";
1288
1289     // TODO: print InlinedAtLoc information
1290
1291     DIScope Scope(debugLoc.getScope(MF->getFunction()->getContext()));
1292     OS << " dbg:";
1293     // Omit the directory, since it's usually long and uninteresting.
1294     if (Scope.Verify())
1295       OS << Scope.getFilename();
1296     else
1297       OS << "<unknown>";
1298     OS << ':' << debugLoc.getLine();
1299     if (debugLoc.getCol() != 0)
1300       OS << ':' << debugLoc.getCol();
1301   }
1302
1303   OS << "\n";
1304 }
1305
1306 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1307                                      const TargetRegisterInfo *RegInfo,
1308                                      bool AddIfNotFound) {
1309   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1310   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1311   bool Found = false;
1312   SmallVector<unsigned,4> DeadOps;
1313   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1314     MachineOperand &MO = getOperand(i);
1315     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1316       continue;
1317     unsigned Reg = MO.getReg();
1318     if (!Reg)
1319       continue;
1320
1321     if (Reg == IncomingReg) {
1322       if (!Found) {
1323         if (MO.isKill())
1324           // The register is already marked kill.
1325           return true;
1326         if (isPhysReg && isRegTiedToDefOperand(i))
1327           // Two-address uses of physregs must not be marked kill.
1328           return true;
1329         MO.setIsKill();
1330         Found = true;
1331       }
1332     } else if (hasAliases && MO.isKill() &&
1333                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1334       // A super-register kill already exists.
1335       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1336         return true;
1337       if (RegInfo->isSubRegister(IncomingReg, Reg))
1338         DeadOps.push_back(i);
1339     }
1340   }
1341
1342   // Trim unneeded kill operands.
1343   while (!DeadOps.empty()) {
1344     unsigned OpIdx = DeadOps.back();
1345     if (getOperand(OpIdx).isImplicit())
1346       RemoveOperand(OpIdx);
1347     else
1348       getOperand(OpIdx).setIsKill(false);
1349     DeadOps.pop_back();
1350   }
1351
1352   // If not found, this means an alias of one of the operands is killed. Add a
1353   // new implicit operand if required.
1354   if (!Found && AddIfNotFound) {
1355     addOperand(MachineOperand::CreateReg(IncomingReg,
1356                                          false /*IsDef*/,
1357                                          true  /*IsImp*/,
1358                                          true  /*IsKill*/));
1359     return true;
1360   }
1361   return Found;
1362 }
1363
1364 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1365                                    const TargetRegisterInfo *RegInfo,
1366                                    bool AddIfNotFound) {
1367   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1368   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1369   bool Found = false;
1370   SmallVector<unsigned,4> DeadOps;
1371   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1372     MachineOperand &MO = getOperand(i);
1373     if (!MO.isReg() || !MO.isDef())
1374       continue;
1375     unsigned Reg = MO.getReg();
1376     if (!Reg)
1377       continue;
1378
1379     if (Reg == IncomingReg) {
1380       if (!Found) {
1381         if (MO.isDead())
1382           // The register is already marked dead.
1383           return true;
1384         MO.setIsDead();
1385         Found = true;
1386       }
1387     } else if (hasAliases && MO.isDead() &&
1388                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1389       // There exists a super-register that's marked dead.
1390       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1391         return true;
1392       if (RegInfo->getSubRegisters(IncomingReg) &&
1393           RegInfo->getSuperRegisters(Reg) &&
1394           RegInfo->isSubRegister(IncomingReg, Reg))
1395         DeadOps.push_back(i);
1396     }
1397   }
1398
1399   // Trim unneeded dead operands.
1400   while (!DeadOps.empty()) {
1401     unsigned OpIdx = DeadOps.back();
1402     if (getOperand(OpIdx).isImplicit())
1403       RemoveOperand(OpIdx);
1404     else
1405       getOperand(OpIdx).setIsDead(false);
1406     DeadOps.pop_back();
1407   }
1408
1409   // If not found, this means an alias of one of the operands is dead. Add a
1410   // new implicit operand if required.
1411   if (Found || !AddIfNotFound)
1412     return Found;
1413     
1414   addOperand(MachineOperand::CreateReg(IncomingReg,
1415                                        true  /*IsDef*/,
1416                                        true  /*IsImp*/,
1417                                        false /*IsKill*/,
1418                                        true  /*IsDead*/));
1419   return true;
1420 }
1421
1422 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1423                                       const TargetRegisterInfo *RegInfo) {
1424   if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1425     MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1426     if (MO)
1427       return;
1428   } else {
1429     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1430       const MachineOperand &MO = getOperand(i);
1431       if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1432           MO.getSubReg() == 0)
1433         return;
1434     }
1435   }
1436   addOperand(MachineOperand::CreateReg(IncomingReg,
1437                                        true  /*IsDef*/,
1438                                        true  /*IsImp*/));
1439 }
1440
1441 unsigned
1442 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1443   unsigned Hash = MI->getOpcode() * 37;
1444   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1445     const MachineOperand &MO = MI->getOperand(i);
1446     uint64_t Key = (uint64_t)MO.getType() << 32;
1447     switch (MO.getType()) {
1448     default: break;
1449     case MachineOperand::MO_Register:
1450       if (MO.isDef() && MO.getReg() &&
1451           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1452         continue;  // Skip virtual register defs.
1453       Key |= MO.getReg();
1454       break;
1455     case MachineOperand::MO_Immediate:
1456       Key |= MO.getImm();
1457       break;
1458     case MachineOperand::MO_FrameIndex:
1459     case MachineOperand::MO_ConstantPoolIndex:
1460     case MachineOperand::MO_JumpTableIndex:
1461       Key |= MO.getIndex();
1462       break;
1463     case MachineOperand::MO_MachineBasicBlock:
1464       Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1465       break;
1466     case MachineOperand::MO_GlobalAddress:
1467       Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1468       break;
1469     case MachineOperand::MO_BlockAddress:
1470       Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1471       break;
1472     case MachineOperand::MO_MCSymbol:
1473       Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1474       break;
1475     }
1476     Key += ~(Key << 32);
1477     Key ^= (Key >> 22);
1478     Key += ~(Key << 13);
1479     Key ^= (Key >> 8);
1480     Key += (Key << 3);
1481     Key ^= (Key >> 15);
1482     Key += ~(Key << 27);
1483     Key ^= (Key >> 31);
1484     Hash = (unsigned)Key + Hash * 37;
1485   }
1486   return Hash;
1487 }