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