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