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