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