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