e3df010312a0b2ecfe4575da012503cce5bea68d
[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/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/MC/MCInstrDesc.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 using namespace llvm;
44
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
48
49 void MachineOperand::setReg(unsigned Reg) {
50   if (getReg() == Reg) return; // No change.
51
52   // Otherwise, we have to change the register.  If this operand is embedded
53   // into a machine function, we need to update the old and new register's
54   // use/def lists.
55   if (MachineInstr *MI = getParent())
56     if (MachineBasicBlock *MBB = MI->getParent())
57       if (MachineFunction *MF = MBB->getParent()) {
58         MachineRegisterInfo &MRI = MF->getRegInfo();
59         MRI.removeRegOperandFromUseList(this);
60         SmallContents.RegNo = Reg;
61         MRI.addRegOperandToUseList(this);
62         return;
63       }
64
65   // Otherwise, just change the register, no problem.  :)
66   SmallContents.RegNo = Reg;
67 }
68
69 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
70                                   const TargetRegisterInfo &TRI) {
71   assert(TargetRegisterInfo::isVirtualRegister(Reg));
72   if (SubIdx && getSubReg())
73     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
74   setReg(Reg);
75   if (SubIdx)
76     setSubReg(SubIdx);
77 }
78
79 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
80   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
81   if (getSubReg()) {
82     Reg = TRI.getSubReg(Reg, getSubReg());
83     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
84     // That won't happen in legal code.
85     setSubReg(0);
86   }
87   setReg(Reg);
88 }
89
90 /// Change a def to a use, or a use to a def.
91 void MachineOperand::setIsDef(bool Val) {
92   assert(isReg() && "Wrong MachineOperand accessor");
93   assert((!Val || !isDebug()) && "Marking a debug operation as def");
94   if (IsDef == Val)
95     return;
96   // MRI may keep uses and defs in different list positions.
97   if (MachineInstr *MI = getParent())
98     if (MachineBasicBlock *MBB = MI->getParent())
99       if (MachineFunction *MF = MBB->getParent()) {
100         MachineRegisterInfo &MRI = MF->getRegInfo();
101         MRI.removeRegOperandFromUseList(this);
102         IsDef = Val;
103         MRI.addRegOperandToUseList(this);
104         return;
105       }
106   IsDef = Val;
107 }
108
109 /// ChangeToImmediate - Replace this operand with a new immediate operand of
110 /// the specified value.  If an operand is known to be an immediate already,
111 /// the setImm method should be used.
112 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
113   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
114   // If this operand is currently a register operand, and if this is in a
115   // function, deregister the operand from the register's use/def list.
116   if (isReg() && isOnRegUseList())
117     if (MachineInstr *MI = getParent())
118       if (MachineBasicBlock *MBB = MI->getParent())
119         if (MachineFunction *MF = MBB->getParent())
120           MF->getRegInfo().removeRegOperandFromUseList(this);
121
122   OpKind = MO_Immediate;
123   Contents.ImmVal = ImmVal;
124 }
125
126 /// ChangeToRegister - Replace this operand with a new register operand of
127 /// the specified value.  If an operand is known to be an register already,
128 /// the setReg method should be used.
129 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
130                                       bool isKill, bool isDead, bool isUndef,
131                                       bool isDebug) {
132   MachineRegisterInfo *RegInfo = 0;
133   if (MachineInstr *MI = getParent())
134     if (MachineBasicBlock *MBB = MI->getParent())
135       if (MachineFunction *MF = MBB->getParent())
136         RegInfo = &MF->getRegInfo();
137   // If this operand is already a register operand, remove it from the
138   // register's use/def lists.
139   bool WasReg = isReg();
140   if (RegInfo && WasReg)
141     RegInfo->removeRegOperandFromUseList(this);
142
143   // Change this to a register and set the reg#.
144   OpKind = MO_Register;
145   SmallContents.RegNo = Reg;
146   SubReg_TargetFlags = 0;
147   IsDef = isDef;
148   IsImp = isImp;
149   IsKill = isKill;
150   IsDead = isDead;
151   IsUndef = isUndef;
152   IsInternalRead = false;
153   IsEarlyClobber = false;
154   IsDebug = isDebug;
155   // Ensure isOnRegUseList() returns false.
156   Contents.Reg.Prev = 0;
157   // Preserve the tie when the operand was already a register.
158   if (!WasReg)
159     TiedTo = 0;
160
161   // If this operand is embedded in a function, add the operand to the
162   // register's use/def list.
163   if (RegInfo)
164     RegInfo->addRegOperandToUseList(this);
165 }
166
167 /// isIdenticalTo - Return true if this operand is identical to the specified
168 /// operand. Note that this should stay in sync with the hash_value overload
169 /// below.
170 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
171   if (getType() != Other.getType() ||
172       getTargetFlags() != Other.getTargetFlags())
173     return false;
174
175   switch (getType()) {
176   case MachineOperand::MO_Register:
177     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
178            getSubReg() == Other.getSubReg();
179   case MachineOperand::MO_Immediate:
180     return getImm() == Other.getImm();
181   case MachineOperand::MO_CImmediate:
182     return getCImm() == Other.getCImm();
183   case MachineOperand::MO_FPImmediate:
184     return getFPImm() == Other.getFPImm();
185   case MachineOperand::MO_MachineBasicBlock:
186     return getMBB() == Other.getMBB();
187   case MachineOperand::MO_FrameIndex:
188     return getIndex() == Other.getIndex();
189   case MachineOperand::MO_ConstantPoolIndex:
190   case MachineOperand::MO_TargetIndex:
191     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
192   case MachineOperand::MO_JumpTableIndex:
193     return getIndex() == Other.getIndex();
194   case MachineOperand::MO_GlobalAddress:
195     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
196   case MachineOperand::MO_ExternalSymbol:
197     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
198            getOffset() == Other.getOffset();
199   case MachineOperand::MO_BlockAddress:
200     return getBlockAddress() == Other.getBlockAddress() &&
201            getOffset() == Other.getOffset();
202   case MachineOperand::MO_RegisterMask:
203   case MachineOperand::MO_RegisterLiveOut:
204     return getRegMask() == Other.getRegMask();
205   case MachineOperand::MO_MCSymbol:
206     return getMCSymbol() == Other.getMCSymbol();
207   case MachineOperand::MO_Metadata:
208     return getMetadata() == Other.getMetadata();
209   }
210   llvm_unreachable("Invalid machine operand type");
211 }
212
213 // Note: this must stay exactly in sync with isIdenticalTo above.
214 hash_code llvm::hash_value(const MachineOperand &MO) {
215   switch (MO.getType()) {
216   case MachineOperand::MO_Register:
217     // Register operands don't have target flags.
218     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
219   case MachineOperand::MO_Immediate:
220     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
221   case MachineOperand::MO_CImmediate:
222     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
223   case MachineOperand::MO_FPImmediate:
224     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
225   case MachineOperand::MO_MachineBasicBlock:
226     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
227   case MachineOperand::MO_FrameIndex:
228     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
229   case MachineOperand::MO_ConstantPoolIndex:
230   case MachineOperand::MO_TargetIndex:
231     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
232                         MO.getOffset());
233   case MachineOperand::MO_JumpTableIndex:
234     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
235   case MachineOperand::MO_ExternalSymbol:
236     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
237                         MO.getSymbolName());
238   case MachineOperand::MO_GlobalAddress:
239     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
240                         MO.getOffset());
241   case MachineOperand::MO_BlockAddress:
242     return hash_combine(MO.getType(), MO.getTargetFlags(),
243                         MO.getBlockAddress(), MO.getOffset());
244   case MachineOperand::MO_RegisterMask:
245   case MachineOperand::MO_RegisterLiveOut:
246     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
247   case MachineOperand::MO_Metadata:
248     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
249   case MachineOperand::MO_MCSymbol:
250     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
251   }
252   llvm_unreachable("Invalid machine operand type");
253 }
254
255 /// print - Print the specified machine operand.
256 ///
257 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
258   // If the instruction is embedded into a basic block, we can find the
259   // target info for the instruction.
260   if (!TM)
261     if (const MachineInstr *MI = getParent())
262       if (const MachineBasicBlock *MBB = MI->getParent())
263         if (const MachineFunction *MF = MBB->getParent())
264           TM = &MF->getTarget();
265   const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
266
267   switch (getType()) {
268   case MachineOperand::MO_Register:
269     OS << PrintReg(getReg(), TRI, getSubReg());
270
271     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
272         isInternalRead() || isEarlyClobber() || isTied()) {
273       OS << '<';
274       bool NeedComma = false;
275       if (isDef()) {
276         if (NeedComma) OS << ',';
277         if (isEarlyClobber())
278           OS << "earlyclobber,";
279         if (isImplicit())
280           OS << "imp-";
281         OS << "def";
282         NeedComma = true;
283         // <def,read-undef> only makes sense when getSubReg() is set.
284         // Don't clutter the output otherwise.
285         if (isUndef() && getSubReg())
286           OS << ",read-undef";
287       } else if (isImplicit()) {
288           OS << "imp-use";
289           NeedComma = true;
290       }
291
292       if (isKill()) {
293         if (NeedComma) OS << ',';
294         OS << "kill";
295         NeedComma = true;
296       }
297       if (isDead()) {
298         if (NeedComma) OS << ',';
299         OS << "dead";
300         NeedComma = true;
301       }
302       if (isUndef() && isUse()) {
303         if (NeedComma) OS << ',';
304         OS << "undef";
305         NeedComma = true;
306       }
307       if (isInternalRead()) {
308         if (NeedComma) OS << ',';
309         OS << "internal";
310         NeedComma = true;
311       }
312       if (isTied()) {
313         if (NeedComma) OS << ',';
314         OS << "tied";
315         if (TiedTo != 15)
316           OS << unsigned(TiedTo - 1);
317         NeedComma = true;
318       }
319       OS << '>';
320     }
321     break;
322   case MachineOperand::MO_Immediate:
323     OS << getImm();
324     break;
325   case MachineOperand::MO_CImmediate:
326     getCImm()->getValue().print(OS, false);
327     break;
328   case MachineOperand::MO_FPImmediate:
329     if (getFPImm()->getType()->isFloatTy())
330       OS << getFPImm()->getValueAPF().convertToFloat();
331     else
332       OS << getFPImm()->getValueAPF().convertToDouble();
333     break;
334   case MachineOperand::MO_MachineBasicBlock:
335     OS << "<BB#" << getMBB()->getNumber() << ">";
336     break;
337   case MachineOperand::MO_FrameIndex:
338     OS << "<fi#" << getIndex() << '>';
339     break;
340   case MachineOperand::MO_ConstantPoolIndex:
341     OS << "<cp#" << getIndex();
342     if (getOffset()) OS << "+" << getOffset();
343     OS << '>';
344     break;
345   case MachineOperand::MO_TargetIndex:
346     OS << "<ti#" << getIndex();
347     if (getOffset()) OS << "+" << getOffset();
348     OS << '>';
349     break;
350   case MachineOperand::MO_JumpTableIndex:
351     OS << "<jt#" << getIndex() << '>';
352     break;
353   case MachineOperand::MO_GlobalAddress:
354     OS << "<ga:";
355     WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
356     if (getOffset()) OS << "+" << getOffset();
357     OS << '>';
358     break;
359   case MachineOperand::MO_ExternalSymbol:
360     OS << "<es:" << getSymbolName();
361     if (getOffset()) OS << "+" << getOffset();
362     OS << '>';
363     break;
364   case MachineOperand::MO_BlockAddress:
365     OS << '<';
366     WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
367     if (getOffset()) OS << "+" << getOffset();
368     OS << '>';
369     break;
370   case MachineOperand::MO_RegisterMask:
371     OS << "<regmask>";
372     break;
373   case MachineOperand::MO_RegisterLiveOut:
374     OS << "<regliveout>";
375     break;
376   case MachineOperand::MO_Metadata:
377     OS << '<';
378     WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
379     OS << '>';
380     break;
381   case MachineOperand::MO_MCSymbol:
382     OS << "<MCSym=" << *getMCSymbol() << '>';
383     break;
384   }
385
386   if (unsigned TF = getTargetFlags())
387     OS << "[TF=" << TF << ']';
388 }
389
390 //===----------------------------------------------------------------------===//
391 // MachineMemOperand Implementation
392 //===----------------------------------------------------------------------===//
393
394 /// getAddrSpace - Return the LLVM IR address space number that this pointer
395 /// points into.
396 unsigned MachinePointerInfo::getAddrSpace() const {
397   if (V == 0) return 0;
398   return cast<PointerType>(V->getType())->getAddressSpace();
399 }
400
401 /// getConstantPool - Return a MachinePointerInfo record that refers to the
402 /// constant pool.
403 MachinePointerInfo MachinePointerInfo::getConstantPool() {
404   return MachinePointerInfo(PseudoSourceValue::getConstantPool());
405 }
406
407 /// getFixedStack - Return a MachinePointerInfo record that refers to the
408 /// the specified FrameIndex.
409 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
410   return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
411 }
412
413 MachinePointerInfo MachinePointerInfo::getJumpTable() {
414   return MachinePointerInfo(PseudoSourceValue::getJumpTable());
415 }
416
417 MachinePointerInfo MachinePointerInfo::getGOT() {
418   return MachinePointerInfo(PseudoSourceValue::getGOT());
419 }
420
421 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
422   return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
423 }
424
425 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
426                                      uint64_t s, unsigned int a,
427                                      const MDNode *TBAAInfo,
428                                      const MDNode *Ranges)
429   : PtrInfo(ptrinfo), Size(s),
430     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
431     TBAAInfo(TBAAInfo), Ranges(Ranges) {
432   assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
433          "invalid pointer value");
434   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
435   assert((isLoad() || isStore()) && "Not a load/store!");
436 }
437
438 /// Profile - Gather unique data for the object.
439 ///
440 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
441   ID.AddInteger(getOffset());
442   ID.AddInteger(Size);
443   ID.AddPointer(getValue());
444   ID.AddInteger(Flags);
445 }
446
447 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
448   // The Value and Offset may differ due to CSE. But the flags and size
449   // should be the same.
450   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
451   assert(MMO->getSize() == getSize() && "Size mismatch!");
452
453   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
454     // Update the alignment value.
455     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
456       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
457     // Also update the base and offset, because the new alignment may
458     // not be applicable with the old ones.
459     PtrInfo = MMO->PtrInfo;
460   }
461 }
462
463 /// getAlignment - Return the minimum known alignment in bytes of the
464 /// actual memory reference.
465 uint64_t MachineMemOperand::getAlignment() const {
466   return MinAlign(getBaseAlignment(), getOffset());
467 }
468
469 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
470   assert((MMO.isLoad() || MMO.isStore()) &&
471          "SV has to be a load, store or both.");
472
473   if (MMO.isVolatile())
474     OS << "Volatile ";
475
476   if (MMO.isLoad())
477     OS << "LD";
478   if (MMO.isStore())
479     OS << "ST";
480   OS << MMO.getSize();
481
482   // Print the address information.
483   OS << "[";
484   if (!MMO.getValue())
485     OS << "<unknown>";
486   else
487     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
488
489   unsigned AS = MMO.getAddrSpace();
490   if (AS != 0)
491     OS << "(addrspace=" << AS << ')';
492
493   // If the alignment of the memory reference itself differs from the alignment
494   // of the base pointer, print the base alignment explicitly, next to the base
495   // pointer.
496   if (MMO.getBaseAlignment() != MMO.getAlignment())
497     OS << "(align=" << MMO.getBaseAlignment() << ")";
498
499   if (MMO.getOffset() != 0)
500     OS << "+" << MMO.getOffset();
501   OS << "]";
502
503   // Print the alignment of the reference.
504   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
505       MMO.getBaseAlignment() != MMO.getSize())
506     OS << "(align=" << MMO.getAlignment() << ")";
507
508   // Print TBAA info.
509   if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
510     OS << "(tbaa=";
511     if (TBAAInfo->getNumOperands() > 0)
512       WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
513     else
514       OS << "<unknown>";
515     OS << ")";
516   }
517
518   // Print nontemporal info.
519   if (MMO.isNonTemporal())
520     OS << "(nontemporal)";
521
522   return OS;
523 }
524
525 //===----------------------------------------------------------------------===//
526 // MachineInstr Implementation
527 //===----------------------------------------------------------------------===//
528
529 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
530   if (MCID->ImplicitDefs)
531     for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
532       addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
533   if (MCID->ImplicitUses)
534     for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
535       addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
536 }
537
538 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
539 /// implicit operands. It reserves space for the number of operands specified by
540 /// the MCInstrDesc.
541 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
542                            const DebugLoc dl, bool NoImp)
543   : MCID(&tid), Parent(0), Operands(0), NumOperands(0),
544     Flags(0), AsmPrinterFlags(0),
545     NumMemRefs(0), MemRefs(0), debugLoc(dl) {
546   // Reserve space for the expected number of operands.
547   if (unsigned NumOps = MCID->getNumOperands() +
548     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
549     CapOperands = OperandCapacity::get(NumOps);
550     Operands = MF.allocateOperandArray(CapOperands);
551   }
552
553   if (!NoImp)
554     addImplicitDefUseOperands(MF);
555 }
556
557 /// MachineInstr ctor - Copies MachineInstr arg exactly
558 ///
559 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
560   : MCID(&MI.getDesc()), Parent(0), Operands(0), NumOperands(0),
561     Flags(0), AsmPrinterFlags(0),
562     NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
563     debugLoc(MI.getDebugLoc()) {
564   CapOperands = OperandCapacity::get(MI.getNumOperands());
565   Operands = MF.allocateOperandArray(CapOperands);
566
567   // Copy operands.
568   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
569     addOperand(MF, MI.getOperand(i));
570
571   // Copy all the sensible flags.
572   setFlags(MI.Flags);
573 }
574
575 /// getRegInfo - If this instruction is embedded into a MachineFunction,
576 /// return the MachineRegisterInfo object for the current function, otherwise
577 /// return null.
578 MachineRegisterInfo *MachineInstr::getRegInfo() {
579   if (MachineBasicBlock *MBB = getParent())
580     return &MBB->getParent()->getRegInfo();
581   return 0;
582 }
583
584 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
585 /// this instruction from their respective use lists.  This requires that the
586 /// operands already be on their use lists.
587 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
588   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
589     if (Operands[i].isReg())
590       MRI.removeRegOperandFromUseList(&Operands[i]);
591 }
592
593 /// AddRegOperandsToUseLists - Add all of the register operands in
594 /// this instruction from their respective use lists.  This requires that the
595 /// operands not be on their use lists yet.
596 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
597   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
598     if (Operands[i].isReg())
599       MRI.addRegOperandToUseList(&Operands[i]);
600 }
601
602 void MachineInstr::addOperand(const MachineOperand &Op) {
603   MachineBasicBlock *MBB = getParent();
604   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
605   MachineFunction *MF = MBB->getParent();
606   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
607   addOperand(*MF, Op);
608 }
609
610 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
611 /// ranges. If MRI is non-null also update use-def chains.
612 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
613                          unsigned NumOps, MachineRegisterInfo *MRI) {
614   if (MRI)
615     return MRI->moveOperands(Dst, Src, NumOps);
616
617   // Here it would be convenient to call memmove, so that isn't allowed because
618   // MachineOperand has a constructor and so isn't a POD type.
619   if (Dst < Src)
620     for (unsigned i = 0; i != NumOps; ++i)
621       new (Dst + i) MachineOperand(Src[i]);
622   else
623     for (unsigned i = NumOps; i ; --i)
624       new (Dst + i - 1) MachineOperand(Src[i - 1]);
625 }
626
627 /// addOperand - Add the specified operand to the instruction.  If it is an
628 /// implicit operand, it is added to the end of the operand list.  If it is
629 /// an explicit operand it is added at the end of the explicit operand list
630 /// (before the first implicit operand).
631 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
632   assert(MCID && "Cannot add operands before providing an instr descriptor");
633
634   // Check if we're adding one of our existing operands.
635   if (&Op >= Operands && &Op < Operands + NumOperands) {
636     // This is unusual: MI->addOperand(MI->getOperand(i)).
637     // If adding Op requires reallocating or moving existing operands around,
638     // the Op reference could go stale. Support it by copying Op.
639     MachineOperand CopyOp(Op);
640     return addOperand(MF, CopyOp);
641   }
642
643   // Find the insert location for the new operand.  Implicit registers go at
644   // the end, everything else goes before the implicit regs.
645   //
646   // FIXME: Allow mixed explicit and implicit operands on inline asm.
647   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
648   // implicit-defs, but they must not be moved around.  See the FIXME in
649   // InstrEmitter.cpp.
650   unsigned OpNo = getNumOperands();
651   bool isImpReg = Op.isReg() && Op.isImplicit();
652   if (!isImpReg && !isInlineAsm()) {
653     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
654       --OpNo;
655       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
656     }
657   }
658
659 #ifndef NDEBUG
660   bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
661   // OpNo now points as the desired insertion point.  Unless this is a variadic
662   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
663   // RegMask operands go between the explicit and implicit operands.
664   assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
665           OpNo < MCID->getNumOperands() || isMetaDataOp) &&
666          "Trying to add an operand to a machine instr that is already done!");
667 #endif
668
669   MachineRegisterInfo *MRI = getRegInfo();
670
671   // Determine if the Operands array needs to be reallocated.
672   // Save the old capacity and operand array.
673   OperandCapacity OldCap = CapOperands;
674   MachineOperand *OldOperands = Operands;
675   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
676     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
677     Operands = MF.allocateOperandArray(CapOperands);
678     // Move the operands before the insertion point.
679     if (OpNo)
680       moveOperands(Operands, OldOperands, OpNo, MRI);
681   }
682
683   // Move the operands following the insertion point.
684   if (OpNo != NumOperands)
685     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
686                  MRI);
687   ++NumOperands;
688
689   // Deallocate the old operand array.
690   if (OldOperands != Operands && OldOperands)
691     MF.deallocateOperandArray(OldCap, OldOperands);
692
693   // Copy Op into place. It still needs to be inserted into the MRI use lists.
694   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
695   NewMO->ParentMI = this;
696
697   // When adding a register operand, tell MRI about it.
698   if (NewMO->isReg()) {
699     // Ensure isOnRegUseList() returns false, regardless of Op's status.
700     NewMO->Contents.Reg.Prev = 0;
701     // Ignore existing ties. This is not a property that can be copied.
702     NewMO->TiedTo = 0;
703     // Add the new operand to MRI, but only for instructions in an MBB.
704     if (MRI)
705       MRI->addRegOperandToUseList(NewMO);
706     // The MCID operand information isn't accurate until we start adding
707     // explicit operands. The implicit operands are added first, then the
708     // explicits are inserted before them.
709     if (!isImpReg) {
710       // Tie uses to defs as indicated in MCInstrDesc.
711       if (NewMO->isUse()) {
712         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
713         if (DefIdx != -1)
714           tieOperands(DefIdx, OpNo);
715       }
716       // If the register operand is flagged as early, mark the operand as such.
717       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
718         NewMO->setIsEarlyClobber(true);
719     }
720   }
721 }
722
723 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
724 /// fewer operand than it started with.
725 ///
726 void MachineInstr::RemoveOperand(unsigned OpNo) {
727   assert(OpNo < getNumOperands() && "Invalid operand number");
728   untieRegOperand(OpNo);
729
730 #ifndef NDEBUG
731   // Moving tied operands would break the ties.
732   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
733     if (Operands[i].isReg())
734       assert(!Operands[i].isTied() && "Cannot move tied operands");
735 #endif
736
737   MachineRegisterInfo *MRI = getRegInfo();
738   if (MRI && Operands[OpNo].isReg())
739     MRI->removeRegOperandFromUseList(Operands + OpNo);
740
741   // Don't call the MachineOperand destructor. A lot of this code depends on
742   // MachineOperand having a trivial destructor anyway, and adding a call here
743   // wouldn't make it 'destructor-correct'.
744
745   if (unsigned N = NumOperands - 1 - OpNo)
746     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
747   --NumOperands;
748 }
749
750 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
751 /// This function should be used only occasionally. The setMemRefs function
752 /// is the primary method for setting up a MachineInstr's MemRefs list.
753 void MachineInstr::addMemOperand(MachineFunction &MF,
754                                  MachineMemOperand *MO) {
755   mmo_iterator OldMemRefs = MemRefs;
756   unsigned OldNumMemRefs = NumMemRefs;
757
758   unsigned NewNum = NumMemRefs + 1;
759   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
760
761   std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
762   NewMemRefs[NewNum - 1] = MO;
763   setMemRefs(NewMemRefs, NewMemRefs + NewNum);
764 }
765
766 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
767   assert(!isBundledWithPred() && "Must be called on bundle header");
768   for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
769     if (MII->getDesc().getFlags() & Mask) {
770       if (Type == AnyInBundle)
771         return true;
772     } else {
773       if (Type == AllInBundle && !MII->isBundle())
774         return false;
775     }
776     // This was the last instruction in the bundle.
777     if (!MII->isBundledWithSucc())
778       return Type == AllInBundle;
779   }
780 }
781
782 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
783                                  MICheckType Check) const {
784   // If opcodes or number of operands are not the same then the two
785   // instructions are obviously not identical.
786   if (Other->getOpcode() != getOpcode() ||
787       Other->getNumOperands() != getNumOperands())
788     return false;
789
790   if (isBundle()) {
791     // Both instructions are bundles, compare MIs inside the bundle.
792     MachineBasicBlock::const_instr_iterator I1 = *this;
793     MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
794     MachineBasicBlock::const_instr_iterator I2 = *Other;
795     MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
796     while (++I1 != E1 && I1->isInsideBundle()) {
797       ++I2;
798       if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
799         return false;
800     }
801   }
802
803   // Check operands to make sure they match.
804   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
805     const MachineOperand &MO = getOperand(i);
806     const MachineOperand &OMO = Other->getOperand(i);
807     if (!MO.isReg()) {
808       if (!MO.isIdenticalTo(OMO))
809         return false;
810       continue;
811     }
812
813     // Clients may or may not want to ignore defs when testing for equality.
814     // For example, machine CSE pass only cares about finding common
815     // subexpressions, so it's safe to ignore virtual register defs.
816     if (MO.isDef()) {
817       if (Check == IgnoreDefs)
818         continue;
819       else if (Check == IgnoreVRegDefs) {
820         if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
821             TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
822           if (MO.getReg() != OMO.getReg())
823             return false;
824       } else {
825         if (!MO.isIdenticalTo(OMO))
826           return false;
827         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
828           return false;
829       }
830     } else {
831       if (!MO.isIdenticalTo(OMO))
832         return false;
833       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
834         return false;
835     }
836   }
837   // If DebugLoc does not match then two dbg.values are not identical.
838   if (isDebugValue())
839     if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
840         && getDebugLoc() != Other->getDebugLoc())
841       return false;
842   return true;
843 }
844
845 MachineInstr *MachineInstr::removeFromParent() {
846   assert(getParent() && "Not embedded in a basic block!");
847   return getParent()->remove(this);
848 }
849
850 MachineInstr *MachineInstr::removeFromBundle() {
851   assert(getParent() && "Not embedded in a basic block!");
852   return getParent()->remove_instr(this);
853 }
854
855 void MachineInstr::eraseFromParent() {
856   assert(getParent() && "Not embedded in a basic block!");
857   getParent()->erase(this);
858 }
859
860 void MachineInstr::eraseFromBundle() {
861   assert(getParent() && "Not embedded in a basic block!");
862   getParent()->erase_instr(this);
863 }
864
865 /// getNumExplicitOperands - Returns the number of non-implicit operands.
866 ///
867 unsigned MachineInstr::getNumExplicitOperands() const {
868   unsigned NumOperands = MCID->getNumOperands();
869   if (!MCID->isVariadic())
870     return NumOperands;
871
872   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
873     const MachineOperand &MO = getOperand(i);
874     if (!MO.isReg() || !MO.isImplicit())
875       NumOperands++;
876   }
877   return NumOperands;
878 }
879
880 void MachineInstr::bundleWithPred() {
881   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
882   setFlag(BundledPred);
883   MachineBasicBlock::instr_iterator Pred = this;
884   --Pred;
885   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
886   Pred->setFlag(BundledSucc);
887 }
888
889 void MachineInstr::bundleWithSucc() {
890   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
891   setFlag(BundledSucc);
892   MachineBasicBlock::instr_iterator Succ = this;
893   ++Succ;
894   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
895   Succ->setFlag(BundledPred);
896 }
897
898 void MachineInstr::unbundleFromPred() {
899   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
900   clearFlag(BundledPred);
901   MachineBasicBlock::instr_iterator Pred = this;
902   --Pred;
903   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
904   Pred->clearFlag(BundledSucc);
905 }
906
907 void MachineInstr::unbundleFromSucc() {
908   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
909   clearFlag(BundledSucc);
910   MachineBasicBlock::instr_iterator Succ = this;
911   ++Succ;
912   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
913   Succ->clearFlag(BundledPred);
914 }
915
916 bool MachineInstr::isStackAligningInlineAsm() const {
917   if (isInlineAsm()) {
918     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
919     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
920       return true;
921   }
922   return false;
923 }
924
925 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
926   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
927   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
928   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
929 }
930
931 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
932                                        unsigned *GroupNo) const {
933   assert(isInlineAsm() && "Expected an inline asm instruction");
934   assert(OpIdx < getNumOperands() && "OpIdx out of range");
935
936   // Ignore queries about the initial operands.
937   if (OpIdx < InlineAsm::MIOp_FirstOperand)
938     return -1;
939
940   unsigned Group = 0;
941   unsigned NumOps;
942   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
943        i += NumOps) {
944     const MachineOperand &FlagMO = getOperand(i);
945     // If we reach the implicit register operands, stop looking.
946     if (!FlagMO.isImm())
947       return -1;
948     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
949     if (i + NumOps > OpIdx) {
950       if (GroupNo)
951         *GroupNo = Group;
952       return i;
953     }
954     ++Group;
955   }
956   return -1;
957 }
958
959 const TargetRegisterClass*
960 MachineInstr::getRegClassConstraint(unsigned OpIdx,
961                                     const TargetInstrInfo *TII,
962                                     const TargetRegisterInfo *TRI) const {
963   assert(getParent() && "Can't have an MBB reference here!");
964   assert(getParent()->getParent() && "Can't have an MF reference here!");
965   const MachineFunction &MF = *getParent()->getParent();
966
967   // Most opcodes have fixed constraints in their MCInstrDesc.
968   if (!isInlineAsm())
969     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
970
971   if (!getOperand(OpIdx).isReg())
972     return NULL;
973
974   // For tied uses on inline asm, get the constraint from the def.
975   unsigned DefIdx;
976   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
977     OpIdx = DefIdx;
978
979   // Inline asm stores register class constraints in the flag word.
980   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
981   if (FlagIdx < 0)
982     return NULL;
983
984   unsigned Flag = getOperand(FlagIdx).getImm();
985   unsigned RCID;
986   if (InlineAsm::hasRegClassConstraint(Flag, RCID))
987     return TRI->getRegClass(RCID);
988
989   // Assume that all registers in a memory operand are pointers.
990   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
991     return TRI->getPointerRegClass(MF);
992
993   return NULL;
994 }
995
996 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
997     unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
998     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
999   // Check every operands inside the bundle if we have
1000   // been asked to.
1001   if (ExploreBundle)
1002     for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1003          ++OpndIt)
1004       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1005           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1006   else
1007     // Otherwise, just check the current operands.
1008     for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1009       CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1010                                                      CurRC, TII, TRI);
1011   return CurRC;
1012 }
1013
1014 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1015     unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1016     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1017   assert(CurRC && "Invalid initial register class");
1018   // Check if Reg is constrained by some of its use/def from MI.
1019   const MachineOperand &MO = getOperand(OpIdx);
1020   if (!MO.isReg() || MO.getReg() != Reg)
1021     return CurRC;
1022   // If yes, accumulate the constraints through the operand.
1023   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1024 }
1025
1026 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1027     unsigned OpIdx, const TargetRegisterClass *CurRC,
1028     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1029   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1030   const MachineOperand &MO = getOperand(OpIdx);
1031   assert(MO.isReg() &&
1032          "Cannot get register constraints for non-register operand");
1033   assert(CurRC && "Invalid initial register class");
1034   if (unsigned SubIdx = MO.getSubReg()) {
1035     if (OpRC)
1036       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1037     else
1038       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1039   } else if (OpRC)
1040     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1041   return CurRC;
1042 }
1043
1044 /// Return the number of instructions inside the MI bundle, not counting the
1045 /// header instruction.
1046 unsigned MachineInstr::getBundleSize() const {
1047   MachineBasicBlock::const_instr_iterator I = this;
1048   unsigned Size = 0;
1049   while (I->isBundledWithSucc())
1050     ++Size, ++I;
1051   return Size;
1052 }
1053
1054 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1055 /// the specific register or -1 if it is not found. It further tightens
1056 /// the search criteria to a use that kills the register if isKill is true.
1057 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1058                                           const TargetRegisterInfo *TRI) const {
1059   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1060     const MachineOperand &MO = getOperand(i);
1061     if (!MO.isReg() || !MO.isUse())
1062       continue;
1063     unsigned MOReg = MO.getReg();
1064     if (!MOReg)
1065       continue;
1066     if (MOReg == Reg ||
1067         (TRI &&
1068          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1069          TargetRegisterInfo::isPhysicalRegister(Reg) &&
1070          TRI->isSubRegister(MOReg, Reg)))
1071       if (!isKill || MO.isKill())
1072         return i;
1073   }
1074   return -1;
1075 }
1076
1077 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1078 /// indicating if this instruction reads or writes Reg. This also considers
1079 /// partial defines.
1080 std::pair<bool,bool>
1081 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1082                                          SmallVectorImpl<unsigned> *Ops) const {
1083   bool PartDef = false; // Partial redefine.
1084   bool FullDef = false; // Full define.
1085   bool Use = false;
1086
1087   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1088     const MachineOperand &MO = getOperand(i);
1089     if (!MO.isReg() || MO.getReg() != Reg)
1090       continue;
1091     if (Ops)
1092       Ops->push_back(i);
1093     if (MO.isUse())
1094       Use |= !MO.isUndef();
1095     else if (MO.getSubReg() && !MO.isUndef())
1096       // A partial <def,undef> doesn't count as reading the register.
1097       PartDef = true;
1098     else
1099       FullDef = true;
1100   }
1101   // A partial redefine uses Reg unless there is also a full define.
1102   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1103 }
1104
1105 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1106 /// the specified register or -1 if it is not found. If isDead is true, defs
1107 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1108 /// also checks if there is a def of a super-register.
1109 int
1110 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1111                                         const TargetRegisterInfo *TRI) const {
1112   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1113   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1114     const MachineOperand &MO = getOperand(i);
1115     // Accept regmask operands when Overlap is set.
1116     // Ignore them when looking for a specific def operand (Overlap == false).
1117     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1118       return i;
1119     if (!MO.isReg() || !MO.isDef())
1120       continue;
1121     unsigned MOReg = MO.getReg();
1122     bool Found = (MOReg == Reg);
1123     if (!Found && TRI && isPhys &&
1124         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1125       if (Overlap)
1126         Found = TRI->regsOverlap(MOReg, Reg);
1127       else
1128         Found = TRI->isSubRegister(MOReg, Reg);
1129     }
1130     if (Found && (!isDead || MO.isDead()))
1131       return i;
1132   }
1133   return -1;
1134 }
1135
1136 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1137 /// operand list that is used to represent the predicate. It returns -1 if
1138 /// none is found.
1139 int MachineInstr::findFirstPredOperandIdx() const {
1140   // Don't call MCID.findFirstPredOperandIdx() because this variant
1141   // is sometimes called on an instruction that's not yet complete, and
1142   // so the number of operands is less than the MCID indicates. In
1143   // particular, the PTX target does this.
1144   const MCInstrDesc &MCID = getDesc();
1145   if (MCID.isPredicable()) {
1146     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1147       if (MCID.OpInfo[i].isPredicate())
1148         return i;
1149   }
1150
1151   return -1;
1152 }
1153
1154 // MachineOperand::TiedTo is 4 bits wide.
1155 const unsigned TiedMax = 15;
1156
1157 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1158 ///
1159 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1160 /// field. TiedTo can have these values:
1161 ///
1162 /// 0:              Operand is not tied to anything.
1163 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1164 /// TiedMax:        Tied to an operand >= TiedMax-1.
1165 ///
1166 /// The tied def must be one of the first TiedMax operands on a normal
1167 /// instruction. INLINEASM instructions allow more tied defs.
1168 ///
1169 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1170   MachineOperand &DefMO = getOperand(DefIdx);
1171   MachineOperand &UseMO = getOperand(UseIdx);
1172   assert(DefMO.isDef() && "DefIdx must be a def operand");
1173   assert(UseMO.isUse() && "UseIdx must be a use operand");
1174   assert(!DefMO.isTied() && "Def is already tied to another use");
1175   assert(!UseMO.isTied() && "Use is already tied to another def");
1176
1177   if (DefIdx < TiedMax)
1178     UseMO.TiedTo = DefIdx + 1;
1179   else {
1180     // Inline asm can use the group descriptors to find tied operands, but on
1181     // normal instruction, the tied def must be within the first TiedMax
1182     // operands.
1183     assert(isInlineAsm() && "DefIdx out of range");
1184     UseMO.TiedTo = TiedMax;
1185   }
1186
1187   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1188   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1189 }
1190
1191 /// Given the index of a tied register operand, find the operand it is tied to.
1192 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1193 /// which must exist.
1194 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1195   const MachineOperand &MO = getOperand(OpIdx);
1196   assert(MO.isTied() && "Operand isn't tied");
1197
1198   // Normally TiedTo is in range.
1199   if (MO.TiedTo < TiedMax)
1200     return MO.TiedTo - 1;
1201
1202   // Uses on normal instructions can be out of range.
1203   if (!isInlineAsm()) {
1204     // Normal tied defs must be in the 0..TiedMax-1 range.
1205     if (MO.isUse())
1206       return TiedMax - 1;
1207     // MO is a def. Search for the tied use.
1208     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1209       const MachineOperand &UseMO = getOperand(i);
1210       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1211         return i;
1212     }
1213     llvm_unreachable("Can't find tied use");
1214   }
1215
1216   // Now deal with inline asm by parsing the operand group descriptor flags.
1217   // Find the beginning of each operand group.
1218   SmallVector<unsigned, 8> GroupIdx;
1219   unsigned OpIdxGroup = ~0u;
1220   unsigned NumOps;
1221   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1222        i += NumOps) {
1223     const MachineOperand &FlagMO = getOperand(i);
1224     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1225     unsigned CurGroup = GroupIdx.size();
1226     GroupIdx.push_back(i);
1227     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1228     // OpIdx belongs to this operand group.
1229     if (OpIdx > i && OpIdx < i + NumOps)
1230       OpIdxGroup = CurGroup;
1231     unsigned TiedGroup;
1232     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1233       continue;
1234     // Operands in this group are tied to operands in TiedGroup which must be
1235     // earlier. Find the number of operands between the two groups.
1236     unsigned Delta = i - GroupIdx[TiedGroup];
1237
1238     // OpIdx is a use tied to TiedGroup.
1239     if (OpIdxGroup == CurGroup)
1240       return OpIdx - Delta;
1241
1242     // OpIdx is a def tied to this use group.
1243     if (OpIdxGroup == TiedGroup)
1244       return OpIdx + Delta;
1245   }
1246   llvm_unreachable("Invalid tied operand on inline asm");
1247 }
1248
1249 /// clearKillInfo - Clears kill flags on all operands.
1250 ///
1251 void MachineInstr::clearKillInfo() {
1252   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1253     MachineOperand &MO = getOperand(i);
1254     if (MO.isReg() && MO.isUse())
1255       MO.setIsKill(false);
1256   }
1257 }
1258
1259 void MachineInstr::substituteRegister(unsigned FromReg,
1260                                       unsigned ToReg,
1261                                       unsigned SubIdx,
1262                                       const TargetRegisterInfo &RegInfo) {
1263   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1264     if (SubIdx)
1265       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1266     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1267       MachineOperand &MO = getOperand(i);
1268       if (!MO.isReg() || MO.getReg() != FromReg)
1269         continue;
1270       MO.substPhysReg(ToReg, RegInfo);
1271     }
1272   } else {
1273     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1274       MachineOperand &MO = getOperand(i);
1275       if (!MO.isReg() || MO.getReg() != FromReg)
1276         continue;
1277       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1278     }
1279   }
1280 }
1281
1282 /// isSafeToMove - Return true if it is safe to move this instruction. If
1283 /// SawStore is set to true, it means that there is a store (or call) between
1284 /// the instruction's location and its intended destination.
1285 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1286                                 AliasAnalysis *AA,
1287                                 bool &SawStore) const {
1288   // Ignore stuff that we obviously can't move.
1289   //
1290   // Treat volatile loads as stores. This is not strictly necessary for
1291   // volatiles, but it is required for atomic loads. It is not allowed to move
1292   // a load across an atomic load with Ordering > Monotonic.
1293   if (mayStore() || isCall() ||
1294       (mayLoad() && hasOrderedMemoryRef())) {
1295     SawStore = true;
1296     return false;
1297   }
1298
1299   if (isLabel() || isDebugValue() ||
1300       isTerminator() || hasUnmodeledSideEffects())
1301     return false;
1302
1303   // See if this instruction does a load.  If so, we have to guarantee that the
1304   // loaded value doesn't change between the load and the its intended
1305   // destination. The check for isInvariantLoad gives the targe the chance to
1306   // classify the load as always returning a constant, e.g. a constant pool
1307   // load.
1308   if (mayLoad() && !isInvariantLoad(AA))
1309     // Otherwise, this is a real load.  If there is a store between the load and
1310     // end of block, we can't move it.
1311     return !SawStore;
1312
1313   return true;
1314 }
1315
1316 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1317 /// or volatile memory reference, or if the information describing the memory
1318 /// reference is not available. Return false if it is known to have no ordered
1319 /// memory references.
1320 bool MachineInstr::hasOrderedMemoryRef() const {
1321   // An instruction known never to access memory won't have a volatile access.
1322   if (!mayStore() &&
1323       !mayLoad() &&
1324       !isCall() &&
1325       !hasUnmodeledSideEffects())
1326     return false;
1327
1328   // Otherwise, if the instruction has no memory reference information,
1329   // conservatively assume it wasn't preserved.
1330   if (memoperands_empty())
1331     return true;
1332
1333   // Check the memory reference information for ordered references.
1334   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1335     if (!(*I)->isUnordered())
1336       return true;
1337
1338   return false;
1339 }
1340
1341 /// isInvariantLoad - Return true if this instruction is loading from a
1342 /// location whose value is invariant across the function.  For example,
1343 /// loading a value from the constant pool or from the argument area
1344 /// of a function if it does not change.  This should only return true of
1345 /// *all* loads the instruction does are invariant (if it does multiple loads).
1346 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1347   // If the instruction doesn't load at all, it isn't an invariant load.
1348   if (!mayLoad())
1349     return false;
1350
1351   // If the instruction has lost its memoperands, conservatively assume that
1352   // it may not be an invariant load.
1353   if (memoperands_empty())
1354     return false;
1355
1356   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1357
1358   for (mmo_iterator I = memoperands_begin(),
1359        E = memoperands_end(); I != E; ++I) {
1360     if ((*I)->isVolatile()) return false;
1361     if ((*I)->isStore()) return false;
1362     if ((*I)->isInvariant()) return true;
1363
1364     if (const Value *V = (*I)->getValue()) {
1365       // A load from a constant PseudoSourceValue is invariant.
1366       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1367         if (PSV->isConstant(MFI))
1368           continue;
1369       // If we have an AliasAnalysis, ask it whether the memory is constant.
1370       if (AA && AA->pointsToConstantMemory(
1371                       AliasAnalysis::Location(V, (*I)->getSize(),
1372                                               (*I)->getTBAAInfo())))
1373         continue;
1374     }
1375
1376     // Otherwise assume conservatively.
1377     return false;
1378   }
1379
1380   // Everything checks out.
1381   return true;
1382 }
1383
1384 /// isConstantValuePHI - If the specified instruction is a PHI that always
1385 /// merges together the same virtual register, return the register, otherwise
1386 /// return 0.
1387 unsigned MachineInstr::isConstantValuePHI() const {
1388   if (!isPHI())
1389     return 0;
1390   assert(getNumOperands() >= 3 &&
1391          "It's illegal to have a PHI without source operands");
1392
1393   unsigned Reg = getOperand(1).getReg();
1394   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1395     if (getOperand(i).getReg() != Reg)
1396       return 0;
1397   return Reg;
1398 }
1399
1400 bool MachineInstr::hasUnmodeledSideEffects() const {
1401   if (hasProperty(MCID::UnmodeledSideEffects))
1402     return true;
1403   if (isInlineAsm()) {
1404     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1405     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1406       return true;
1407   }
1408
1409   return false;
1410 }
1411
1412 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1413 ///
1414 bool MachineInstr::allDefsAreDead() const {
1415   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1416     const MachineOperand &MO = getOperand(i);
1417     if (!MO.isReg() || MO.isUse())
1418       continue;
1419     if (!MO.isDead())
1420       return false;
1421   }
1422   return true;
1423 }
1424
1425 /// copyImplicitOps - Copy implicit register operands from specified
1426 /// instruction to this instruction.
1427 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1428                                    const MachineInstr *MI) {
1429   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1430        i != e; ++i) {
1431     const MachineOperand &MO = MI->getOperand(i);
1432     if (MO.isReg() && MO.isImplicit())
1433       addOperand(MF, MO);
1434   }
1435 }
1436
1437 void MachineInstr::dump() const {
1438 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1439   dbgs() << "  " << *this;
1440 #endif
1441 }
1442
1443 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1444                          raw_ostream &CommentOS) {
1445   const LLVMContext &Ctx = MF->getFunction()->getContext();
1446   if (!DL.isUnknown()) {          // Print source line info.
1447     DIScope Scope(DL.getScope(Ctx));
1448     assert((!Scope || Scope.isScope()) &&
1449       "Scope of a DebugLoc should be null or a DIScope.");
1450     // Omit the directory, because it's likely to be long and uninteresting.
1451     if (Scope)
1452       CommentOS << Scope.getFilename();
1453     else
1454       CommentOS << "<unknown>";
1455     CommentOS << ':' << DL.getLine();
1456     if (DL.getCol() != 0)
1457       CommentOS << ':' << DL.getCol();
1458     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1459     if (!InlinedAtDL.isUnknown()) {
1460       CommentOS << " @[ ";
1461       printDebugLoc(InlinedAtDL, MF, CommentOS);
1462       CommentOS << " ]";
1463     }
1464   }
1465 }
1466
1467 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1468                          bool SkipOpers) const {
1469   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1470   const MachineFunction *MF = 0;
1471   const MachineRegisterInfo *MRI = 0;
1472   if (const MachineBasicBlock *MBB = getParent()) {
1473     MF = MBB->getParent();
1474     if (!TM && MF)
1475       TM = &MF->getTarget();
1476     if (MF)
1477       MRI = &MF->getRegInfo();
1478   }
1479
1480   // Save a list of virtual registers.
1481   SmallVector<unsigned, 8> VirtRegs;
1482
1483   // Print explicitly defined operands on the left of an assignment syntax.
1484   unsigned StartOp = 0, e = getNumOperands();
1485   for (; StartOp < e && getOperand(StartOp).isReg() &&
1486          getOperand(StartOp).isDef() &&
1487          !getOperand(StartOp).isImplicit();
1488        ++StartOp) {
1489     if (StartOp != 0) OS << ", ";
1490     getOperand(StartOp).print(OS, TM);
1491     unsigned Reg = getOperand(StartOp).getReg();
1492     if (TargetRegisterInfo::isVirtualRegister(Reg))
1493       VirtRegs.push_back(Reg);
1494   }
1495
1496   if (StartOp != 0)
1497     OS << " = ";
1498
1499   // Print the opcode name.
1500   if (TM && TM->getInstrInfo())
1501     OS << TM->getInstrInfo()->getName(getOpcode());
1502   else
1503     OS << "UNKNOWN";
1504
1505   if (SkipOpers)
1506     return;
1507
1508   // Print the rest of the operands.
1509   bool OmittedAnyCallClobbers = false;
1510   bool FirstOp = true;
1511   unsigned AsmDescOp = ~0u;
1512   unsigned AsmOpCount = 0;
1513
1514   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1515     // Print asm string.
1516     OS << " ";
1517     getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1518
1519     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1520     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1521     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1522       OS << " [sideeffect]";
1523     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1524       OS << " [mayload]";
1525     if (ExtraInfo & InlineAsm::Extra_MayStore)
1526       OS << " [maystore]";
1527     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1528       OS << " [alignstack]";
1529     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1530       OS << " [attdialect]";
1531     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1532       OS << " [inteldialect]";
1533
1534     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1535     FirstOp = false;
1536   }
1537
1538
1539   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1540     const MachineOperand &MO = getOperand(i);
1541
1542     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1543       VirtRegs.push_back(MO.getReg());
1544
1545     // Omit call-clobbered registers which aren't used anywhere. This makes
1546     // call instructions much less noisy on targets where calls clobber lots
1547     // of registers. Don't rely on MO.isDead() because we may be called before
1548     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1549     if (MF && isCall() &&
1550         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1551       unsigned Reg = MO.getReg();
1552       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1553         const MachineRegisterInfo &MRI = MF->getRegInfo();
1554         if (MRI.use_empty(Reg)) {
1555           bool HasAliasLive = false;
1556           for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
1557                AI.isValid(); ++AI) {
1558             unsigned AliasReg = *AI;
1559             if (!MRI.use_empty(AliasReg)) {
1560               HasAliasLive = true;
1561               break;
1562             }
1563           }
1564           if (!HasAliasLive) {
1565             OmittedAnyCallClobbers = true;
1566             continue;
1567           }
1568         }
1569       }
1570     }
1571
1572     if (FirstOp) FirstOp = false; else OS << ",";
1573     OS << " ";
1574     if (i < getDesc().NumOperands) {
1575       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1576       if (MCOI.isPredicate())
1577         OS << "pred:";
1578       if (MCOI.isOptionalDef())
1579         OS << "opt:";
1580     }
1581     if (isDebugValue() && MO.isMetadata()) {
1582       // Pretty print DBG_VALUE instructions.
1583       const MDNode *MD = MO.getMetadata();
1584       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1585         OS << "!\"" << MDS->getString() << '\"';
1586       else
1587         MO.print(OS, TM);
1588     } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1589       OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1590     } else if (i == AsmDescOp && MO.isImm()) {
1591       // Pretty print the inline asm operand descriptor.
1592       OS << '$' << AsmOpCount++;
1593       unsigned Flag = MO.getImm();
1594       switch (InlineAsm::getKind(Flag)) {
1595       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
1596       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
1597       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1598       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
1599       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
1600       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
1601       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1602       }
1603
1604       unsigned RCID = 0;
1605       if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1606         if (TM)
1607           OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1608         else
1609           OS << ":RC" << RCID;
1610       }
1611
1612       unsigned TiedTo = 0;
1613       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1614         OS << " tiedto:$" << TiedTo;
1615
1616       OS << ']';
1617
1618       // Compute the index of the next operand descriptor.
1619       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1620     } else
1621       MO.print(OS, TM);
1622   }
1623
1624   // Briefly indicate whether any call clobbers were omitted.
1625   if (OmittedAnyCallClobbers) {
1626     if (!FirstOp) OS << ",";
1627     OS << " ...";
1628   }
1629
1630   bool HaveSemi = false;
1631   const unsigned PrintableFlags = FrameSetup;
1632   if (Flags & PrintableFlags) {
1633     if (!HaveSemi) OS << ";"; HaveSemi = true;
1634     OS << " flags: ";
1635
1636     if (Flags & FrameSetup)
1637       OS << "FrameSetup";
1638   }
1639
1640   if (!memoperands_empty()) {
1641     if (!HaveSemi) OS << ";"; HaveSemi = true;
1642
1643     OS << " mem:";
1644     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1645          i != e; ++i) {
1646       OS << **i;
1647       if (llvm::next(i) != e)
1648         OS << " ";
1649     }
1650   }
1651
1652   // Print the regclass of any virtual registers encountered.
1653   if (MRI && !VirtRegs.empty()) {
1654     if (!HaveSemi) OS << ";"; HaveSemi = true;
1655     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1656       const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1657       OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1658       for (unsigned j = i+1; j != VirtRegs.size();) {
1659         if (MRI->getRegClass(VirtRegs[j]) != RC) {
1660           ++j;
1661           continue;
1662         }
1663         if (VirtRegs[i] != VirtRegs[j])
1664           OS << "," << PrintReg(VirtRegs[j]);
1665         VirtRegs.erase(VirtRegs.begin()+j);
1666       }
1667     }
1668   }
1669
1670   // Print debug location information.
1671   if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1672     if (!HaveSemi) OS << ";"; HaveSemi = true;
1673     DIVariable DV(getOperand(e - 1).getMetadata());
1674     OS << " line no:" <<  DV.getLineNumber();
1675     if (MDNode *InlinedAt = DV.getInlinedAt()) {
1676       DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1677       if (!InlinedAtDL.isUnknown()) {
1678         OS << " inlined @[ ";
1679         printDebugLoc(InlinedAtDL, MF, OS);
1680         OS << " ]";
1681       }
1682     }
1683   } else if (!debugLoc.isUnknown() && MF) {
1684     if (!HaveSemi) OS << ";"; HaveSemi = true;
1685     OS << " dbg:";
1686     printDebugLoc(debugLoc, MF, OS);
1687   }
1688
1689   OS << '\n';
1690 }
1691
1692 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1693                                      const TargetRegisterInfo *RegInfo,
1694                                      bool AddIfNotFound) {
1695   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1696   bool hasAliases = isPhysReg &&
1697     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1698   bool Found = false;
1699   SmallVector<unsigned,4> DeadOps;
1700   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1701     MachineOperand &MO = getOperand(i);
1702     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1703       continue;
1704     unsigned Reg = MO.getReg();
1705     if (!Reg)
1706       continue;
1707
1708     if (Reg == IncomingReg) {
1709       if (!Found) {
1710         if (MO.isKill())
1711           // The register is already marked kill.
1712           return true;
1713         if (isPhysReg && isRegTiedToDefOperand(i))
1714           // Two-address uses of physregs must not be marked kill.
1715           return true;
1716         MO.setIsKill();
1717         Found = true;
1718       }
1719     } else if (hasAliases && MO.isKill() &&
1720                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1721       // A super-register kill already exists.
1722       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1723         return true;
1724       if (RegInfo->isSubRegister(IncomingReg, Reg))
1725         DeadOps.push_back(i);
1726     }
1727   }
1728
1729   // Trim unneeded kill operands.
1730   while (!DeadOps.empty()) {
1731     unsigned OpIdx = DeadOps.back();
1732     if (getOperand(OpIdx).isImplicit())
1733       RemoveOperand(OpIdx);
1734     else
1735       getOperand(OpIdx).setIsKill(false);
1736     DeadOps.pop_back();
1737   }
1738
1739   // If not found, this means an alias of one of the operands is killed. Add a
1740   // new implicit operand if required.
1741   if (!Found && AddIfNotFound) {
1742     addOperand(MachineOperand::CreateReg(IncomingReg,
1743                                          false /*IsDef*/,
1744                                          true  /*IsImp*/,
1745                                          true  /*IsKill*/));
1746     return true;
1747   }
1748   return Found;
1749 }
1750
1751 void MachineInstr::clearRegisterKills(unsigned Reg,
1752                                       const TargetRegisterInfo *RegInfo) {
1753   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1754     RegInfo = 0;
1755   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1756     MachineOperand &MO = getOperand(i);
1757     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1758       continue;
1759     unsigned OpReg = MO.getReg();
1760     if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1761       MO.setIsKill(false);
1762   }
1763 }
1764
1765 bool MachineInstr::addRegisterDead(unsigned Reg,
1766                                    const TargetRegisterInfo *RegInfo,
1767                                    bool AddIfNotFound) {
1768   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1769   bool hasAliases = isPhysReg &&
1770     MCRegAliasIterator(Reg, RegInfo, false).isValid();
1771   bool Found = false;
1772   SmallVector<unsigned,4> DeadOps;
1773   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1774     MachineOperand &MO = getOperand(i);
1775     if (!MO.isReg() || !MO.isDef())
1776       continue;
1777     unsigned MOReg = MO.getReg();
1778     if (!MOReg)
1779       continue;
1780
1781     if (MOReg == Reg) {
1782       MO.setIsDead();
1783       Found = true;
1784     } else if (hasAliases && MO.isDead() &&
1785                TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1786       // There exists a super-register that's marked dead.
1787       if (RegInfo->isSuperRegister(Reg, MOReg))
1788         return true;
1789       if (RegInfo->isSubRegister(Reg, MOReg))
1790         DeadOps.push_back(i);
1791     }
1792   }
1793
1794   // Trim unneeded dead operands.
1795   while (!DeadOps.empty()) {
1796     unsigned OpIdx = DeadOps.back();
1797     if (getOperand(OpIdx).isImplicit())
1798       RemoveOperand(OpIdx);
1799     else
1800       getOperand(OpIdx).setIsDead(false);
1801     DeadOps.pop_back();
1802   }
1803
1804   // If not found, this means an alias of one of the operands is dead. Add a
1805   // new implicit operand if required.
1806   if (Found || !AddIfNotFound)
1807     return Found;
1808
1809   addOperand(MachineOperand::CreateReg(Reg,
1810                                        true  /*IsDef*/,
1811                                        true  /*IsImp*/,
1812                                        false /*IsKill*/,
1813                                        true  /*IsDead*/));
1814   return true;
1815 }
1816
1817 void MachineInstr::addRegisterDefined(unsigned Reg,
1818                                       const TargetRegisterInfo *RegInfo) {
1819   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1820     MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1821     if (MO)
1822       return;
1823   } else {
1824     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1825       const MachineOperand &MO = getOperand(i);
1826       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1827           MO.getSubReg() == 0)
1828         return;
1829     }
1830   }
1831   addOperand(MachineOperand::CreateReg(Reg,
1832                                        true  /*IsDef*/,
1833                                        true  /*IsImp*/));
1834 }
1835
1836 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1837                                          const TargetRegisterInfo &TRI) {
1838   bool HasRegMask = false;
1839   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1840     MachineOperand &MO = getOperand(i);
1841     if (MO.isRegMask()) {
1842       HasRegMask = true;
1843       continue;
1844     }
1845     if (!MO.isReg() || !MO.isDef()) continue;
1846     unsigned Reg = MO.getReg();
1847     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1848     bool Dead = true;
1849     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1850          I != E; ++I)
1851       if (TRI.regsOverlap(*I, Reg)) {
1852         Dead = false;
1853         break;
1854       }
1855     // If there are no uses, including partial uses, the def is dead.
1856     if (Dead) MO.setIsDead();
1857   }
1858
1859   // This is a call with a register mask operand.
1860   // Mask clobbers are always dead, so add defs for the non-dead defines.
1861   if (HasRegMask)
1862     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1863          I != E; ++I)
1864       addRegisterDefined(*I, &TRI);
1865 }
1866
1867 unsigned
1868 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1869   // Build up a buffer of hash code components.
1870   SmallVector<size_t, 8> HashComponents;
1871   HashComponents.reserve(MI->getNumOperands() + 1);
1872   HashComponents.push_back(MI->getOpcode());
1873   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1874     const MachineOperand &MO = MI->getOperand(i);
1875     if (MO.isReg() && MO.isDef() &&
1876         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1877       continue;  // Skip virtual register defs.
1878
1879     HashComponents.push_back(hash_value(MO));
1880   }
1881   return hash_combine_range(HashComponents.begin(), HashComponents.end());
1882 }
1883
1884 void MachineInstr::emitError(StringRef Msg) const {
1885   // Find the source location cookie.
1886   unsigned LocCookie = 0;
1887   const MDNode *LocMD = 0;
1888   for (unsigned i = getNumOperands(); i != 0; --i) {
1889     if (getOperand(i-1).isMetadata() &&
1890         (LocMD = getOperand(i-1).getMetadata()) &&
1891         LocMD->getNumOperands() != 0) {
1892       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1893         LocCookie = CI->getZExtValue();
1894         break;
1895       }
1896     }
1897   }
1898
1899   if (const MachineBasicBlock *MBB = getParent())
1900     if (const MachineFunction *MF = MBB->getParent())
1901       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1902   report_fatal_error(Msg);
1903 }