start pushing MachinePointerInfo out through the MachineMemOperand interface
[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(MachinePointerInfo ptrinfo, unsigned f,
339                                      uint64_t s, unsigned int a)
340   : PtrInfo(ptrinfo), Size(s),
341     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)) {
342   assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
343          "invalid pointer value");
344   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
345   assert((isLoad() || isStore()) && "Not a load/store!");
346 }
347
348 /// Profile - Gather unique data for the object.
349 ///
350 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
351   ID.AddInteger(getOffset());
352   ID.AddInteger(Size);
353   ID.AddPointer(getValue());
354   ID.AddInteger(Flags);
355 }
356
357 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
358   // The Value and Offset may differ due to CSE. But the flags and size
359   // should be the same.
360   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
361   assert(MMO->getSize() == getSize() && "Size mismatch!");
362
363   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
364     // Update the alignment value.
365     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
366       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
367     // Also update the base and offset, because the new alignment may
368     // not be applicable with the old ones.
369     PtrInfo = MMO->PtrInfo;
370   }
371 }
372
373 /// getAlignment - Return the minimum known alignment in bytes of the
374 /// actual memory reference.
375 uint64_t MachineMemOperand::getAlignment() const {
376   return MinAlign(getBaseAlignment(), getOffset());
377 }
378
379 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
380   assert((MMO.isLoad() || MMO.isStore()) &&
381          "SV has to be a load, store or both.");
382   
383   if (MMO.isVolatile())
384     OS << "Volatile ";
385
386   if (MMO.isLoad())
387     OS << "LD";
388   if (MMO.isStore())
389     OS << "ST";
390   OS << MMO.getSize();
391   
392   // Print the address information.
393   OS << "[";
394   if (!MMO.getValue())
395     OS << "<unknown>";
396   else
397     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
398
399   // If the alignment of the memory reference itself differs from the alignment
400   // of the base pointer, print the base alignment explicitly, next to the base
401   // pointer.
402   if (MMO.getBaseAlignment() != MMO.getAlignment())
403     OS << "(align=" << MMO.getBaseAlignment() << ")";
404
405   if (MMO.getOffset() != 0)
406     OS << "+" << MMO.getOffset();
407   OS << "]";
408
409   // Print the alignment of the reference.
410   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
411       MMO.getBaseAlignment() != MMO.getSize())
412     OS << "(align=" << MMO.getAlignment() << ")";
413
414   return OS;
415 }
416
417 //===----------------------------------------------------------------------===//
418 // MachineInstr Implementation
419 //===----------------------------------------------------------------------===//
420
421 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
422 /// TID NULL and no operands.
423 MachineInstr::MachineInstr()
424   : TID(0), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
425     Parent(0) {
426   // Make sure that we get added to a machine basicblock
427   LeakDetector::addGarbageObject(this);
428 }
429
430 void MachineInstr::addImplicitDefUseOperands() {
431   if (TID->ImplicitDefs)
432     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
433       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
434   if (TID->ImplicitUses)
435     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
436       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
437 }
438
439 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
440 /// implicit operands. It reserves space for the number of operands specified by
441 /// the TargetInstrDesc.
442 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
443   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
444     MemRefs(0), MemRefsEnd(0), Parent(0) {
445   if (!NoImp)
446     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
447   Operands.reserve(NumImplicitOps + TID->getNumOperands());
448   if (!NoImp)
449     addImplicitDefUseOperands();
450   // Make sure that we get added to a machine basicblock
451   LeakDetector::addGarbageObject(this);
452 }
453
454 /// MachineInstr ctor - As above, but with a DebugLoc.
455 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
456                            bool NoImp)
457   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
458     Parent(0), debugLoc(dl) {
459   if (!NoImp)
460     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
461   Operands.reserve(NumImplicitOps + TID->getNumOperands());
462   if (!NoImp)
463     addImplicitDefUseOperands();
464   // Make sure that we get added to a machine basicblock
465   LeakDetector::addGarbageObject(this);
466 }
467
468 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
469 /// that the MachineInstr is created and added to the end of the specified 
470 /// basic block.
471 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
472   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
473     MemRefs(0), MemRefsEnd(0), Parent(0) {
474   assert(MBB && "Cannot use inserting ctor with null basic block!");
475   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
476   Operands.reserve(NumImplicitOps + TID->getNumOperands());
477   addImplicitDefUseOperands();
478   // Make sure that we get added to a machine basicblock
479   LeakDetector::addGarbageObject(this);
480   MBB->push_back(this);  // Add instruction to end of basic block!
481 }
482
483 /// MachineInstr ctor - As above, but with a DebugLoc.
484 ///
485 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
486                            const TargetInstrDesc &tid)
487   : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
488     Parent(0), debugLoc(dl) {
489   assert(MBB && "Cannot use inserting ctor with null basic block!");
490   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
491   Operands.reserve(NumImplicitOps + TID->getNumOperands());
492   addImplicitDefUseOperands();
493   // Make sure that we get added to a machine basicblock
494   LeakDetector::addGarbageObject(this);
495   MBB->push_back(this);  // Add instruction to end of basic block!
496 }
497
498 /// MachineInstr ctor - Copies MachineInstr arg exactly
499 ///
500 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
501   : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
502     MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
503     Parent(0), debugLoc(MI.getDebugLoc()) {
504   Operands.reserve(MI.getNumOperands());
505
506   // Add operands
507   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
508     addOperand(MI.getOperand(i));
509   NumImplicitOps = MI.NumImplicitOps;
510
511   // Set parent to null.
512   Parent = 0;
513
514   LeakDetector::addGarbageObject(this);
515 }
516
517 MachineInstr::~MachineInstr() {
518   LeakDetector::removeGarbageObject(this);
519 #ifndef NDEBUG
520   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
521     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
522     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
523            "Reg operand def/use list corrupted");
524   }
525 #endif
526 }
527
528 /// getRegInfo - If this instruction is embedded into a MachineFunction,
529 /// return the MachineRegisterInfo object for the current function, otherwise
530 /// return null.
531 MachineRegisterInfo *MachineInstr::getRegInfo() {
532   if (MachineBasicBlock *MBB = getParent())
533     return &MBB->getParent()->getRegInfo();
534   return 0;
535 }
536
537 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
538 /// this instruction from their respective use lists.  This requires that the
539 /// operands already be on their use lists.
540 void MachineInstr::RemoveRegOperandsFromUseLists() {
541   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
542     if (Operands[i].isReg())
543       Operands[i].RemoveRegOperandFromRegInfo();
544   }
545 }
546
547 /// AddRegOperandsToUseLists - Add all of the register operands in
548 /// this instruction from their respective use lists.  This requires that the
549 /// operands not be on their use lists yet.
550 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
551   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
552     if (Operands[i].isReg())
553       Operands[i].AddRegOperandToRegInfo(&RegInfo);
554   }
555 }
556
557
558 /// addOperand - Add the specified operand to the instruction.  If it is an
559 /// implicit operand, it is added to the end of the operand list.  If it is
560 /// an explicit operand it is added at the end of the explicit operand list
561 /// (before the first implicit operand). 
562 void MachineInstr::addOperand(const MachineOperand &Op) {
563   bool isImpReg = Op.isReg() && Op.isImplicit();
564   assert((isImpReg || !OperandsComplete()) &&
565          "Trying to add an operand to a machine instr that is already done!");
566
567   MachineRegisterInfo *RegInfo = getRegInfo();
568
569   // If we are adding the operand to the end of the list, our job is simpler.
570   // This is true most of the time, so this is a reasonable optimization.
571   if (isImpReg || NumImplicitOps == 0) {
572     // We can only do this optimization if we know that the operand list won't
573     // reallocate.
574     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
575       Operands.push_back(Op);
576     
577       // Set the parent of the operand.
578       Operands.back().ParentMI = this;
579   
580       // If the operand is a register, update the operand's use list.
581       if (Op.isReg()) {
582         Operands.back().AddRegOperandToRegInfo(RegInfo);
583         // If the register operand is flagged as early, mark the operand as such
584         unsigned OpNo = Operands.size() - 1;
585         if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
586           Operands[OpNo].setIsEarlyClobber(true);
587       }
588       return;
589     }
590   }
591   
592   // Otherwise, we have to insert a real operand before any implicit ones.
593   unsigned OpNo = Operands.size()-NumImplicitOps;
594
595   // If this instruction isn't embedded into a function, then we don't need to
596   // update any operand lists.
597   if (RegInfo == 0) {
598     // Simple insertion, no reginfo update needed for other register operands.
599     Operands.insert(Operands.begin()+OpNo, Op);
600     Operands[OpNo].ParentMI = this;
601
602     // Do explicitly set the reginfo for this operand though, to ensure the
603     // next/prev fields are properly nulled out.
604     if (Operands[OpNo].isReg()) {
605       Operands[OpNo].AddRegOperandToRegInfo(0);
606       // If the register operand is flagged as early, mark the operand as such
607       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
608         Operands[OpNo].setIsEarlyClobber(true);
609     }
610
611   } else if (Operands.size()+1 <= Operands.capacity()) {
612     // Otherwise, we have to remove register operands from their register use
613     // list, add the operand, then add the register operands back to their use
614     // list.  This also must handle the case when the operand list reallocates
615     // to somewhere else.
616   
617     // If insertion of this operand won't cause reallocation of the operand
618     // list, just remove the implicit operands, add the operand, then re-add all
619     // the rest of the operands.
620     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
621       assert(Operands[i].isReg() && "Should only be an implicit reg!");
622       Operands[i].RemoveRegOperandFromRegInfo();
623     }
624     
625     // Add the operand.  If it is a register, add it to the reg list.
626     Operands.insert(Operands.begin()+OpNo, Op);
627     Operands[OpNo].ParentMI = this;
628
629     if (Operands[OpNo].isReg()) {
630       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
631       // If the register operand is flagged as early, mark the operand as such
632       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
633         Operands[OpNo].setIsEarlyClobber(true);
634     }
635     
636     // Re-add all the implicit ops.
637     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
638       assert(Operands[i].isReg() && "Should only be an implicit reg!");
639       Operands[i].AddRegOperandToRegInfo(RegInfo);
640     }
641   } else {
642     // Otherwise, we will be reallocating the operand list.  Remove all reg
643     // operands from their list, then readd them after the operand list is
644     // reallocated.
645     RemoveRegOperandsFromUseLists();
646     
647     Operands.insert(Operands.begin()+OpNo, Op);
648     Operands[OpNo].ParentMI = this;
649   
650     // Re-add all the operands.
651     AddRegOperandsToUseLists(*RegInfo);
652
653       // If the register operand is flagged as early, mark the operand as such
654     if (Operands[OpNo].isReg()
655         && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
656       Operands[OpNo].setIsEarlyClobber(true);
657   }
658 }
659
660 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
661 /// fewer operand than it started with.
662 ///
663 void MachineInstr::RemoveOperand(unsigned OpNo) {
664   assert(OpNo < Operands.size() && "Invalid operand number");
665   
666   // Special case removing the last one.
667   if (OpNo == Operands.size()-1) {
668     // If needed, remove from the reg def/use list.
669     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
670       Operands.back().RemoveRegOperandFromRegInfo();
671     
672     Operands.pop_back();
673     return;
674   }
675
676   // Otherwise, we are removing an interior operand.  If we have reginfo to
677   // update, remove all operands that will be shifted down from their reg lists,
678   // move everything down, then re-add them.
679   MachineRegisterInfo *RegInfo = getRegInfo();
680   if (RegInfo) {
681     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
682       if (Operands[i].isReg())
683         Operands[i].RemoveRegOperandFromRegInfo();
684     }
685   }
686   
687   Operands.erase(Operands.begin()+OpNo);
688
689   if (RegInfo) {
690     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
691       if (Operands[i].isReg())
692         Operands[i].AddRegOperandToRegInfo(RegInfo);
693     }
694   }
695 }
696
697 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
698 /// This function should be used only occasionally. The setMemRefs function
699 /// is the primary method for setting up a MachineInstr's MemRefs list.
700 void MachineInstr::addMemOperand(MachineFunction &MF,
701                                  MachineMemOperand *MO) {
702   mmo_iterator OldMemRefs = MemRefs;
703   mmo_iterator OldMemRefsEnd = MemRefsEnd;
704
705   size_t NewNum = (MemRefsEnd - MemRefs) + 1;
706   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
707   mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
708
709   std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
710   NewMemRefs[NewNum - 1] = MO;
711
712   MemRefs = NewMemRefs;
713   MemRefsEnd = NewMemRefsEnd;
714 }
715
716 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
717                                  MICheckType Check) const {
718   // If opcodes or number of operands are not the same then the two
719   // instructions are obviously not identical.
720   if (Other->getOpcode() != getOpcode() ||
721       Other->getNumOperands() != getNumOperands())
722     return false;
723
724   // Check operands to make sure they match.
725   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
726     const MachineOperand &MO = getOperand(i);
727     const MachineOperand &OMO = Other->getOperand(i);
728     // Clients may or may not want to ignore defs when testing for equality.
729     // For example, machine CSE pass only cares about finding common
730     // subexpressions, so it's safe to ignore virtual register defs.
731     if (Check != CheckDefs && MO.isReg() && MO.isDef()) {
732       if (Check == IgnoreDefs)
733         continue;
734       // Check == IgnoreVRegDefs
735       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
736           TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
737         if (MO.getReg() != OMO.getReg())
738           return false;
739     } else if (!MO.isIdenticalTo(OMO))
740       return false;
741   }
742   return true;
743 }
744
745 /// removeFromParent - This method unlinks 'this' from the containing basic
746 /// block, and returns it, but does not delete it.
747 MachineInstr *MachineInstr::removeFromParent() {
748   assert(getParent() && "Not embedded in a basic block!");
749   getParent()->remove(this);
750   return this;
751 }
752
753
754 /// eraseFromParent - This method unlinks 'this' from the containing basic
755 /// block, and deletes it.
756 void MachineInstr::eraseFromParent() {
757   assert(getParent() && "Not embedded in a basic block!");
758   getParent()->erase(this);
759 }
760
761
762 /// OperandComplete - Return true if it's illegal to add a new operand
763 ///
764 bool MachineInstr::OperandsComplete() const {
765   unsigned short NumOperands = TID->getNumOperands();
766   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
767     return true;  // Broken: we have all the operands of this instruction!
768   return false;
769 }
770
771 /// getNumExplicitOperands - Returns the number of non-implicit operands.
772 ///
773 unsigned MachineInstr::getNumExplicitOperands() const {
774   unsigned NumOperands = TID->getNumOperands();
775   if (!TID->isVariadic())
776     return NumOperands;
777
778   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
779     const MachineOperand &MO = getOperand(i);
780     if (!MO.isReg() || !MO.isImplicit())
781       NumOperands++;
782   }
783   return NumOperands;
784 }
785
786
787 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
788 /// the specific register or -1 if it is not found. It further tightens
789 /// the search criteria to a use that kills the register if isKill is true.
790 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
791                                           const TargetRegisterInfo *TRI) const {
792   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
793     const MachineOperand &MO = getOperand(i);
794     if (!MO.isReg() || !MO.isUse())
795       continue;
796     unsigned MOReg = MO.getReg();
797     if (!MOReg)
798       continue;
799     if (MOReg == Reg ||
800         (TRI &&
801          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
802          TargetRegisterInfo::isPhysicalRegister(Reg) &&
803          TRI->isSubRegister(MOReg, Reg)))
804       if (!isKill || MO.isKill())
805         return i;
806   }
807   return -1;
808 }
809
810 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
811 /// indicating if this instruction reads or writes Reg. This also considers
812 /// partial defines.
813 std::pair<bool,bool>
814 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
815                                          SmallVectorImpl<unsigned> *Ops) const {
816   bool PartDef = false; // Partial redefine.
817   bool FullDef = false; // Full define.
818   bool Use = false;
819
820   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
821     const MachineOperand &MO = getOperand(i);
822     if (!MO.isReg() || MO.getReg() != Reg)
823       continue;
824     if (Ops)
825       Ops->push_back(i);
826     if (MO.isUse())
827       Use |= !MO.isUndef();
828     else if (MO.getSubReg())
829       PartDef = true;
830     else
831       FullDef = true;
832   }
833   // A partial redefine uses Reg unless there is also a full define.
834   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
835 }
836
837 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
838 /// the specified register or -1 if it is not found. If isDead is true, defs
839 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
840 /// also checks if there is a def of a super-register.
841 int
842 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
843                                         const TargetRegisterInfo *TRI) const {
844   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
845   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
846     const MachineOperand &MO = getOperand(i);
847     if (!MO.isReg() || !MO.isDef())
848       continue;
849     unsigned MOReg = MO.getReg();
850     bool Found = (MOReg == Reg);
851     if (!Found && TRI && isPhys &&
852         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
853       if (Overlap)
854         Found = TRI->regsOverlap(MOReg, Reg);
855       else
856         Found = TRI->isSubRegister(MOReg, Reg);
857     }
858     if (Found && (!isDead || MO.isDead()))
859       return i;
860   }
861   return -1;
862 }
863
864 /// findFirstPredOperandIdx() - Find the index of the first operand in the
865 /// operand list that is used to represent the predicate. It returns -1 if
866 /// none is found.
867 int MachineInstr::findFirstPredOperandIdx() const {
868   const TargetInstrDesc &TID = getDesc();
869   if (TID.isPredicable()) {
870     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
871       if (TID.OpInfo[i].isPredicate())
872         return i;
873   }
874
875   return -1;
876 }
877   
878 /// isRegTiedToUseOperand - Given the index of a register def operand,
879 /// check if the register def is tied to a source operand, due to either
880 /// two-address elimination or inline assembly constraints. Returns the
881 /// first tied use operand index by reference is UseOpIdx is not null.
882 bool MachineInstr::
883 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
884   if (isInlineAsm()) {
885     assert(DefOpIdx >= 3);
886     const MachineOperand &MO = getOperand(DefOpIdx);
887     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
888       return false;
889     // Determine the actual operand index that corresponds to this index.
890     unsigned DefNo = 0;
891     unsigned DefPart = 0;
892     for (unsigned i = 2, e = getNumOperands(); i < e; ) {
893       const MachineOperand &FMO = getOperand(i);
894       // After the normal asm operands there may be additional imp-def regs.
895       if (!FMO.isImm())
896         return false;
897       // Skip over this def.
898       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
899       unsigned PrevDef = i + 1;
900       i = PrevDef + NumOps;
901       if (i > DefOpIdx) {
902         DefPart = DefOpIdx - PrevDef;
903         break;
904       }
905       ++DefNo;
906     }
907     for (unsigned i = 2, e = getNumOperands(); i != e; ++i) {
908       const MachineOperand &FMO = getOperand(i);
909       if (!FMO.isImm())
910         continue;
911       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
912         continue;
913       unsigned Idx;
914       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
915           Idx == DefNo) {
916         if (UseOpIdx)
917           *UseOpIdx = (unsigned)i + 1 + DefPart;
918         return true;
919       }
920     }
921     return false;
922   }
923
924   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
925   const TargetInstrDesc &TID = getDesc();
926   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
927     const MachineOperand &MO = getOperand(i);
928     if (MO.isReg() && MO.isUse() &&
929         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
930       if (UseOpIdx)
931         *UseOpIdx = (unsigned)i;
932       return true;
933     }
934   }
935   return false;
936 }
937
938 /// isRegTiedToDefOperand - Return true if the operand of the specified index
939 /// is a register use and it is tied to an def operand. It also returns the def
940 /// operand index by reference.
941 bool MachineInstr::
942 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
943   if (isInlineAsm()) {
944     const MachineOperand &MO = getOperand(UseOpIdx);
945     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
946       return false;
947
948     // Find the flag operand corresponding to UseOpIdx
949     unsigned FlagIdx, NumOps=0;
950     for (FlagIdx = 2; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
951       const MachineOperand &UFMO = getOperand(FlagIdx);
952       // After the normal asm operands there may be additional imp-def regs.
953       if (!UFMO.isImm())
954         return false;
955       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
956       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
957       if (UseOpIdx < FlagIdx+NumOps+1)
958         break;
959     }
960     if (FlagIdx >= UseOpIdx)
961       return false;
962     const MachineOperand &UFMO = getOperand(FlagIdx);
963     unsigned DefNo;
964     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
965       if (!DefOpIdx)
966         return true;
967
968       unsigned DefIdx = 2;
969       // Remember to adjust the index. First operand is asm string, second is
970       // the AlignStack bit, then there is a flag for each.
971       while (DefNo) {
972         const MachineOperand &FMO = getOperand(DefIdx);
973         assert(FMO.isImm());
974         // Skip over this def.
975         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
976         --DefNo;
977       }
978       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
979       return true;
980     }
981     return false;
982   }
983
984   const TargetInstrDesc &TID = getDesc();
985   if (UseOpIdx >= TID.getNumOperands())
986     return false;
987   const MachineOperand &MO = getOperand(UseOpIdx);
988   if (!MO.isReg() || !MO.isUse())
989     return false;
990   int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
991   if (DefIdx == -1)
992     return false;
993   if (DefOpIdx)
994     *DefOpIdx = (unsigned)DefIdx;
995   return true;
996 }
997
998 /// clearKillInfo - Clears kill flags on all operands.
999 ///
1000 void MachineInstr::clearKillInfo() {
1001   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1002     MachineOperand &MO = getOperand(i);
1003     if (MO.isReg() && MO.isUse())
1004       MO.setIsKill(false);
1005   }
1006 }
1007
1008 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1009 ///
1010 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1011   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1012     const MachineOperand &MO = MI->getOperand(i);
1013     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1014       continue;
1015     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1016       MachineOperand &MOp = getOperand(j);
1017       if (!MOp.isIdenticalTo(MO))
1018         continue;
1019       if (MO.isKill())
1020         MOp.setIsKill();
1021       else
1022         MOp.setIsDead();
1023       break;
1024     }
1025   }
1026 }
1027
1028 /// copyPredicates - Copies predicate operand(s) from MI.
1029 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1030   const TargetInstrDesc &TID = MI->getDesc();
1031   if (!TID.isPredicable())
1032     return;
1033   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1034     if (TID.OpInfo[i].isPredicate()) {
1035       // Predicated operands must be last operands.
1036       addOperand(MI->getOperand(i));
1037     }
1038   }
1039 }
1040
1041 void MachineInstr::substituteRegister(unsigned FromReg,
1042                                       unsigned ToReg,
1043                                       unsigned SubIdx,
1044                                       const TargetRegisterInfo &RegInfo) {
1045   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1046     if (SubIdx)
1047       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1048     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1049       MachineOperand &MO = getOperand(i);
1050       if (!MO.isReg() || MO.getReg() != FromReg)
1051         continue;
1052       MO.substPhysReg(ToReg, RegInfo);
1053     }
1054   } else {
1055     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1056       MachineOperand &MO = getOperand(i);
1057       if (!MO.isReg() || MO.getReg() != FromReg)
1058         continue;
1059       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1060     }
1061   }
1062 }
1063
1064 /// isSafeToMove - Return true if it is safe to move this instruction. If
1065 /// SawStore is set to true, it means that there is a store (or call) between
1066 /// the instruction's location and its intended destination.
1067 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1068                                 AliasAnalysis *AA,
1069                                 bool &SawStore) const {
1070   // Ignore stuff that we obviously can't move.
1071   if (TID->mayStore() || TID->isCall()) {
1072     SawStore = true;
1073     return false;
1074   }
1075   if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
1076     return false;
1077
1078   // See if this instruction does a load.  If so, we have to guarantee that the
1079   // loaded value doesn't change between the load and the its intended
1080   // destination. The check for isInvariantLoad gives the targe the chance to
1081   // classify the load as always returning a constant, e.g. a constant pool
1082   // load.
1083   if (TID->mayLoad() && !isInvariantLoad(AA))
1084     // Otherwise, this is a real load.  If there is a store between the load and
1085     // end of block, or if the load is volatile, we can't move it.
1086     return !SawStore && !hasVolatileMemoryRef();
1087
1088   return true;
1089 }
1090
1091 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1092 /// instruction which defined the specified register instead of copying it.
1093 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1094                                  AliasAnalysis *AA,
1095                                  unsigned DstReg) const {
1096   bool SawStore = false;
1097   if (!TII->isTriviallyReMaterializable(this, AA) ||
1098       !isSafeToMove(TII, AA, SawStore))
1099     return false;
1100   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1101     const MachineOperand &MO = getOperand(i);
1102     if (!MO.isReg())
1103       continue;
1104     // FIXME: For now, do not remat any instruction with register operands.
1105     // Later on, we can loosen the restriction is the register operands have
1106     // not been modified between the def and use. Note, this is different from
1107     // MachineSink because the code is no longer in two-address form (at least
1108     // partially).
1109     if (MO.isUse())
1110       return false;
1111     else if (!MO.isDead() && MO.getReg() != DstReg)
1112       return false;
1113   }
1114   return true;
1115 }
1116
1117 /// hasVolatileMemoryRef - Return true if this instruction may have a
1118 /// volatile memory reference, or if the information describing the
1119 /// memory reference is not available. Return false if it is known to
1120 /// have no volatile memory references.
1121 bool MachineInstr::hasVolatileMemoryRef() const {
1122   // An instruction known never to access memory won't have a volatile access.
1123   if (!TID->mayStore() &&
1124       !TID->mayLoad() &&
1125       !TID->isCall() &&
1126       !TID->hasUnmodeledSideEffects())
1127     return false;
1128
1129   // Otherwise, if the instruction has no memory reference information,
1130   // conservatively assume it wasn't preserved.
1131   if (memoperands_empty())
1132     return true;
1133   
1134   // Check the memory reference information for volatile references.
1135   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1136     if ((*I)->isVolatile())
1137       return true;
1138
1139   return false;
1140 }
1141
1142 /// isInvariantLoad - Return true if this instruction is loading from a
1143 /// location whose value is invariant across the function.  For example,
1144 /// loading a value from the constant pool or from the argument area
1145 /// of a function if it does not change.  This should only return true of
1146 /// *all* loads the instruction does are invariant (if it does multiple loads).
1147 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1148   // If the instruction doesn't load at all, it isn't an invariant load.
1149   if (!TID->mayLoad())
1150     return false;
1151
1152   // If the instruction has lost its memoperands, conservatively assume that
1153   // it may not be an invariant load.
1154   if (memoperands_empty())
1155     return false;
1156
1157   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1158
1159   for (mmo_iterator I = memoperands_begin(),
1160        E = memoperands_end(); I != E; ++I) {
1161     if ((*I)->isVolatile()) return false;
1162     if ((*I)->isStore()) return false;
1163
1164     if (const Value *V = (*I)->getValue()) {
1165       // A load from a constant PseudoSourceValue is invariant.
1166       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1167         if (PSV->isConstant(MFI))
1168           continue;
1169       // If we have an AliasAnalysis, ask it whether the memory is constant.
1170       if (AA && AA->pointsToConstantMemory(V))
1171         continue;
1172     }
1173
1174     // Otherwise assume conservatively.
1175     return false;
1176   }
1177
1178   // Everything checks out.
1179   return true;
1180 }
1181
1182 /// isConstantValuePHI - If the specified instruction is a PHI that always
1183 /// merges together the same virtual register, return the register, otherwise
1184 /// return 0.
1185 unsigned MachineInstr::isConstantValuePHI() const {
1186   if (!isPHI())
1187     return 0;
1188   assert(getNumOperands() >= 3 &&
1189          "It's illegal to have a PHI without source operands");
1190
1191   unsigned Reg = getOperand(1).getReg();
1192   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1193     if (getOperand(i).getReg() != Reg)
1194       return 0;
1195   return Reg;
1196 }
1197
1198 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1199 ///
1200 bool MachineInstr::allDefsAreDead() const {
1201   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1202     const MachineOperand &MO = getOperand(i);
1203     if (!MO.isReg() || MO.isUse())
1204       continue;
1205     if (!MO.isDead())
1206       return false;
1207   }
1208   return true;
1209 }
1210
1211 void MachineInstr::dump() const {
1212   dbgs() << "  " << *this;
1213 }
1214
1215 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF, 
1216                          raw_ostream &CommentOS) {
1217   const LLVMContext &Ctx = MF->getFunction()->getContext();
1218   if (!DL.isUnknown()) {          // Print source line info.
1219     DIScope Scope(DL.getScope(Ctx));
1220     // Omit the directory, because it's likely to be long and uninteresting.
1221     if (Scope.Verify())
1222       CommentOS << Scope.getFilename();
1223     else
1224       CommentOS << "<unknown>";
1225     CommentOS << ':' << DL.getLine();
1226     if (DL.getCol() != 0)
1227       CommentOS << ':' << DL.getCol();
1228     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1229     if (!InlinedAtDL.isUnknown()) {
1230       CommentOS << " @[ ";
1231       printDebugLoc(InlinedAtDL, MF, CommentOS);
1232       CommentOS << " ]";
1233     }
1234   }
1235 }
1236
1237 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1238   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1239   const MachineFunction *MF = 0;
1240   const MachineRegisterInfo *MRI = 0;
1241   if (const MachineBasicBlock *MBB = getParent()) {
1242     MF = MBB->getParent();
1243     if (!TM && MF)
1244       TM = &MF->getTarget();
1245     if (MF)
1246       MRI = &MF->getRegInfo();
1247   }
1248
1249   // Save a list of virtual registers.
1250   SmallVector<unsigned, 8> VirtRegs;
1251
1252   // Print explicitly defined operands on the left of an assignment syntax.
1253   unsigned StartOp = 0, e = getNumOperands();
1254   for (; StartOp < e && getOperand(StartOp).isReg() &&
1255          getOperand(StartOp).isDef() &&
1256          !getOperand(StartOp).isImplicit();
1257        ++StartOp) {
1258     if (StartOp != 0) OS << ", ";
1259     getOperand(StartOp).print(OS, TM);
1260     unsigned Reg = getOperand(StartOp).getReg();
1261     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
1262       VirtRegs.push_back(Reg);
1263   }
1264
1265   if (StartOp != 0)
1266     OS << " = ";
1267
1268   // Print the opcode name.
1269   OS << getDesc().getName();
1270
1271   // Print the rest of the operands.
1272   bool OmittedAnyCallClobbers = false;
1273   bool FirstOp = true;
1274   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1275     const MachineOperand &MO = getOperand(i);
1276
1277     if (MO.isReg() && MO.getReg() &&
1278         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1279       VirtRegs.push_back(MO.getReg());
1280
1281     // Omit call-clobbered registers which aren't used anywhere. This makes
1282     // call instructions much less noisy on targets where calls clobber lots
1283     // of registers. Don't rely on MO.isDead() because we may be called before
1284     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1285     if (MF && getDesc().isCall() &&
1286         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1287       unsigned Reg = MO.getReg();
1288       if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1289         const MachineRegisterInfo &MRI = MF->getRegInfo();
1290         if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1291           bool HasAliasLive = false;
1292           for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1293                unsigned AliasReg = *Alias; ++Alias)
1294             if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1295               HasAliasLive = true;
1296               break;
1297             }
1298           if (!HasAliasLive) {
1299             OmittedAnyCallClobbers = true;
1300             continue;
1301           }
1302         }
1303       }
1304     }
1305
1306     if (FirstOp) FirstOp = false; else OS << ",";
1307     OS << " ";
1308     if (i < getDesc().NumOperands) {
1309       const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1310       if (TOI.isPredicate())
1311         OS << "pred:";
1312       if (TOI.isOptionalDef())
1313         OS << "opt:";
1314     }
1315     if (isDebugValue() && MO.isMetadata()) {
1316       // Pretty print DBG_VALUE instructions.
1317       const MDNode *MD = MO.getMetadata();
1318       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1319         OS << "!\"" << MDS->getString() << '\"';
1320       else
1321         MO.print(OS, TM);
1322     } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1323       OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1324     } else
1325       MO.print(OS, TM);
1326   }
1327
1328   // Briefly indicate whether any call clobbers were omitted.
1329   if (OmittedAnyCallClobbers) {
1330     if (!FirstOp) OS << ",";
1331     OS << " ...";
1332   }
1333
1334   bool HaveSemi = false;
1335   if (!memoperands_empty()) {
1336     if (!HaveSemi) OS << ";"; HaveSemi = true;
1337
1338     OS << " mem:";
1339     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1340          i != e; ++i) {
1341       OS << **i;
1342       if (llvm::next(i) != e)
1343         OS << " ";
1344     }
1345   }
1346
1347   // Print the regclass of any virtual registers encountered.
1348   if (MRI && !VirtRegs.empty()) {
1349     if (!HaveSemi) OS << ";"; HaveSemi = true;
1350     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1351       const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1352       OS << " " << RC->getName() << ":%reg" << VirtRegs[i];
1353       for (unsigned j = i+1; j != VirtRegs.size();) {
1354         if (MRI->getRegClass(VirtRegs[j]) != RC) {
1355           ++j;
1356           continue;
1357         }
1358         if (VirtRegs[i] != VirtRegs[j])
1359           OS << "," << VirtRegs[j];
1360         VirtRegs.erase(VirtRegs.begin()+j);
1361       }
1362     }
1363   }
1364
1365   if (!debugLoc.isUnknown() && MF) {
1366     if (!HaveSemi) OS << ";";
1367     OS << " dbg:";
1368     printDebugLoc(debugLoc, MF, OS);
1369   }
1370
1371   OS << "\n";
1372 }
1373
1374 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1375                                      const TargetRegisterInfo *RegInfo,
1376                                      bool AddIfNotFound) {
1377   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1378   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1379   bool Found = false;
1380   SmallVector<unsigned,4> DeadOps;
1381   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1382     MachineOperand &MO = getOperand(i);
1383     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1384       continue;
1385     unsigned Reg = MO.getReg();
1386     if (!Reg)
1387       continue;
1388
1389     if (Reg == IncomingReg) {
1390       if (!Found) {
1391         if (MO.isKill())
1392           // The register is already marked kill.
1393           return true;
1394         if (isPhysReg && isRegTiedToDefOperand(i))
1395           // Two-address uses of physregs must not be marked kill.
1396           return true;
1397         MO.setIsKill();
1398         Found = true;
1399       }
1400     } else if (hasAliases && MO.isKill() &&
1401                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1402       // A super-register kill already exists.
1403       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1404         return true;
1405       if (RegInfo->isSubRegister(IncomingReg, Reg))
1406         DeadOps.push_back(i);
1407     }
1408   }
1409
1410   // Trim unneeded kill operands.
1411   while (!DeadOps.empty()) {
1412     unsigned OpIdx = DeadOps.back();
1413     if (getOperand(OpIdx).isImplicit())
1414       RemoveOperand(OpIdx);
1415     else
1416       getOperand(OpIdx).setIsKill(false);
1417     DeadOps.pop_back();
1418   }
1419
1420   // If not found, this means an alias of one of the operands is killed. Add a
1421   // new implicit operand if required.
1422   if (!Found && AddIfNotFound) {
1423     addOperand(MachineOperand::CreateReg(IncomingReg,
1424                                          false /*IsDef*/,
1425                                          true  /*IsImp*/,
1426                                          true  /*IsKill*/));
1427     return true;
1428   }
1429   return Found;
1430 }
1431
1432 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1433                                    const TargetRegisterInfo *RegInfo,
1434                                    bool AddIfNotFound) {
1435   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1436   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1437   bool Found = false;
1438   SmallVector<unsigned,4> DeadOps;
1439   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1440     MachineOperand &MO = getOperand(i);
1441     if (!MO.isReg() || !MO.isDef())
1442       continue;
1443     unsigned Reg = MO.getReg();
1444     if (!Reg)
1445       continue;
1446
1447     if (Reg == IncomingReg) {
1448       if (!Found) {
1449         if (MO.isDead())
1450           // The register is already marked dead.
1451           return true;
1452         MO.setIsDead();
1453         Found = true;
1454       }
1455     } else if (hasAliases && MO.isDead() &&
1456                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1457       // There exists a super-register that's marked dead.
1458       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1459         return true;
1460       if (RegInfo->getSubRegisters(IncomingReg) &&
1461           RegInfo->getSuperRegisters(Reg) &&
1462           RegInfo->isSubRegister(IncomingReg, Reg))
1463         DeadOps.push_back(i);
1464     }
1465   }
1466
1467   // Trim unneeded dead operands.
1468   while (!DeadOps.empty()) {
1469     unsigned OpIdx = DeadOps.back();
1470     if (getOperand(OpIdx).isImplicit())
1471       RemoveOperand(OpIdx);
1472     else
1473       getOperand(OpIdx).setIsDead(false);
1474     DeadOps.pop_back();
1475   }
1476
1477   // If not found, this means an alias of one of the operands is dead. Add a
1478   // new implicit operand if required.
1479   if (Found || !AddIfNotFound)
1480     return Found;
1481     
1482   addOperand(MachineOperand::CreateReg(IncomingReg,
1483                                        true  /*IsDef*/,
1484                                        true  /*IsImp*/,
1485                                        false /*IsKill*/,
1486                                        true  /*IsDead*/));
1487   return true;
1488 }
1489
1490 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1491                                       const TargetRegisterInfo *RegInfo) {
1492   if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1493     MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1494     if (MO)
1495       return;
1496   } else {
1497     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1498       const MachineOperand &MO = getOperand(i);
1499       if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1500           MO.getSubReg() == 0)
1501         return;
1502     }
1503   }
1504   addOperand(MachineOperand::CreateReg(IncomingReg,
1505                                        true  /*IsDef*/,
1506                                        true  /*IsImp*/));
1507 }
1508
1509 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1510                                          const TargetRegisterInfo &TRI) {
1511   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1512     MachineOperand &MO = getOperand(i);
1513     if (!MO.isReg() || !MO.isDef()) continue;
1514     unsigned Reg = MO.getReg();
1515     if (Reg == 0) continue;
1516     bool Dead = true;
1517     for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1518          E = UsedRegs.end(); I != E; ++I)
1519       if (TRI.regsOverlap(*I, Reg)) {
1520         Dead = false;
1521         break;
1522       }
1523     // If there are no uses, including partial uses, the def is dead.
1524     if (Dead) MO.setIsDead();
1525   }
1526 }
1527
1528 unsigned
1529 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1530   unsigned Hash = MI->getOpcode() * 37;
1531   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1532     const MachineOperand &MO = MI->getOperand(i);
1533     uint64_t Key = (uint64_t)MO.getType() << 32;
1534     switch (MO.getType()) {
1535     default: break;
1536     case MachineOperand::MO_Register:
1537       if (MO.isDef() && MO.getReg() &&
1538           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1539         continue;  // Skip virtual register defs.
1540       Key |= MO.getReg();
1541       break;
1542     case MachineOperand::MO_Immediate:
1543       Key |= MO.getImm();
1544       break;
1545     case MachineOperand::MO_FrameIndex:
1546     case MachineOperand::MO_ConstantPoolIndex:
1547     case MachineOperand::MO_JumpTableIndex:
1548       Key |= MO.getIndex();
1549       break;
1550     case MachineOperand::MO_MachineBasicBlock:
1551       Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1552       break;
1553     case MachineOperand::MO_GlobalAddress:
1554       Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1555       break;
1556     case MachineOperand::MO_BlockAddress:
1557       Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1558       break;
1559     case MachineOperand::MO_MCSymbol:
1560       Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1561       break;
1562     }
1563     Key += ~(Key << 32);
1564     Key ^= (Key >> 22);
1565     Key += ~(Key << 13);
1566     Key ^= (Key >> 8);
1567     Key += (Key << 3);
1568     Key ^= (Key >> 15);
1569     Key += ~(Key << 27);
1570     Key ^= (Key >> 31);
1571     Hash = (unsigned)Key + Hash * 37;
1572   }
1573   return Hash;
1574 }