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