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