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