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