xref: /llvm-project/llvm/lib/CodeGen/MachineInstr.cpp (revision 03c419628e551983a11c739a001fe0cfbcfa90b1)
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/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ModuleSlotTracker.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/MC/MCInstrDesc.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
45 using namespace llvm;
46 
47 static cl::opt<bool> PrintWholeRegMask(
48     "print-whole-regmask",
49     cl::desc("Print the full contents of regmask operands in IR dumps"),
50     cl::init(true), cl::Hidden);
51 
52 //===----------------------------------------------------------------------===//
53 // MachineOperand Implementation
54 //===----------------------------------------------------------------------===//
55 
56 void MachineOperand::setReg(unsigned Reg) {
57   if (getReg() == Reg) return; // No change.
58 
59   // Otherwise, we have to change the register.  If this operand is embedded
60   // into a machine function, we need to update the old and new register's
61   // use/def lists.
62   if (MachineInstr *MI = getParent())
63     if (MachineBasicBlock *MBB = MI->getParent())
64       if (MachineFunction *MF = MBB->getParent()) {
65         MachineRegisterInfo &MRI = MF->getRegInfo();
66         MRI.removeRegOperandFromUseList(this);
67         SmallContents.RegNo = Reg;
68         MRI.addRegOperandToUseList(this);
69         return;
70       }
71 
72   // Otherwise, just change the register, no problem.  :)
73   SmallContents.RegNo = Reg;
74 }
75 
76 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
77                                   const TargetRegisterInfo &TRI) {
78   assert(TargetRegisterInfo::isVirtualRegister(Reg));
79   if (SubIdx && getSubReg())
80     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
81   setReg(Reg);
82   if (SubIdx)
83     setSubReg(SubIdx);
84 }
85 
86 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
87   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
88   if (getSubReg()) {
89     Reg = TRI.getSubReg(Reg, getSubReg());
90     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
91     // That won't happen in legal code.
92     setSubReg(0);
93   }
94   setReg(Reg);
95 }
96 
97 /// Change a def to a use, or a use to a def.
98 void MachineOperand::setIsDef(bool Val) {
99   assert(isReg() && "Wrong MachineOperand accessor");
100   assert((!Val || !isDebug()) && "Marking a debug operation as def");
101   if (IsDef == Val)
102     return;
103   // MRI may keep uses and defs in different list positions.
104   if (MachineInstr *MI = getParent())
105     if (MachineBasicBlock *MBB = MI->getParent())
106       if (MachineFunction *MF = MBB->getParent()) {
107         MachineRegisterInfo &MRI = MF->getRegInfo();
108         MRI.removeRegOperandFromUseList(this);
109         IsDef = Val;
110         MRI.addRegOperandToUseList(this);
111         return;
112       }
113   IsDef = Val;
114 }
115 
116 // If this operand is currently a register operand, and if this is in a
117 // function, deregister the operand from the register's use/def list.
118 void MachineOperand::removeRegFromUses() {
119   if (!isReg() || !isOnRegUseList())
120     return;
121 
122   if (MachineInstr *MI = getParent()) {
123     if (MachineBasicBlock *MBB = MI->getParent()) {
124       if (MachineFunction *MF = MBB->getParent())
125         MF->getRegInfo().removeRegOperandFromUseList(this);
126     }
127   }
128 }
129 
130 /// ChangeToImmediate - Replace this operand with a new immediate operand of
131 /// the specified value.  If an operand is known to be an immediate already,
132 /// the setImm method should be used.
133 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
134   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
135 
136   removeRegFromUses();
137 
138   OpKind = MO_Immediate;
139   Contents.ImmVal = ImmVal;
140 }
141 
142 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
143   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
144 
145   removeRegFromUses();
146 
147   OpKind = MO_FPImmediate;
148   Contents.CFP = FPImm;
149 }
150 
151 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
152   assert((!isReg() || !isTied()) &&
153          "Cannot change a tied operand into an external symbol");
154 
155   removeRegFromUses();
156 
157   OpKind = MO_ExternalSymbol;
158   Contents.OffsetedInfo.Val.SymbolName = SymName;
159   setOffset(0); // Offset is always 0.
160   setTargetFlags(TargetFlags);
161 }
162 
163 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
164   assert((!isReg() || !isTied()) &&
165          "Cannot change a tied operand into an MCSymbol");
166 
167   removeRegFromUses();
168 
169   OpKind = MO_MCSymbol;
170   Contents.Sym = Sym;
171 }
172 
173 /// ChangeToRegister - Replace this operand with a new register operand of
174 /// the specified value.  If an operand is known to be an register already,
175 /// the setReg method should be used.
176 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
177                                       bool isKill, bool isDead, bool isUndef,
178                                       bool isDebug) {
179   MachineRegisterInfo *RegInfo = nullptr;
180   if (MachineInstr *MI = getParent())
181     if (MachineBasicBlock *MBB = MI->getParent())
182       if (MachineFunction *MF = MBB->getParent())
183         RegInfo = &MF->getRegInfo();
184   // If this operand is already a register operand, remove it from the
185   // register's use/def lists.
186   bool WasReg = isReg();
187   if (RegInfo && WasReg)
188     RegInfo->removeRegOperandFromUseList(this);
189 
190   // Change this to a register and set the reg#.
191   OpKind = MO_Register;
192   SmallContents.RegNo = Reg;
193   SubReg_TargetFlags = 0;
194   IsDef = isDef;
195   IsImp = isImp;
196   IsKill = isKill;
197   IsDead = isDead;
198   IsUndef = isUndef;
199   IsInternalRead = false;
200   IsEarlyClobber = false;
201   IsDebug = isDebug;
202   // Ensure isOnRegUseList() returns false.
203   Contents.Reg.Prev = nullptr;
204   // Preserve the tie when the operand was already a register.
205   if (!WasReg)
206     TiedTo = 0;
207 
208   // If this operand is embedded in a function, add the operand to the
209   // register's use/def list.
210   if (RegInfo)
211     RegInfo->addRegOperandToUseList(this);
212 }
213 
214 /// isIdenticalTo - Return true if this operand is identical to the specified
215 /// operand. Note that this should stay in sync with the hash_value overload
216 /// below.
217 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
218   if (getType() != Other.getType() ||
219       getTargetFlags() != Other.getTargetFlags())
220     return false;
221 
222   switch (getType()) {
223   case MachineOperand::MO_Register:
224     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
225            getSubReg() == Other.getSubReg();
226   case MachineOperand::MO_Immediate:
227     return getImm() == Other.getImm();
228   case MachineOperand::MO_CImmediate:
229     return getCImm() == Other.getCImm();
230   case MachineOperand::MO_FPImmediate:
231     return getFPImm() == Other.getFPImm();
232   case MachineOperand::MO_MachineBasicBlock:
233     return getMBB() == Other.getMBB();
234   case MachineOperand::MO_FrameIndex:
235     return getIndex() == Other.getIndex();
236   case MachineOperand::MO_ConstantPoolIndex:
237   case MachineOperand::MO_TargetIndex:
238     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
239   case MachineOperand::MO_JumpTableIndex:
240     return getIndex() == Other.getIndex();
241   case MachineOperand::MO_GlobalAddress:
242     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
243   case MachineOperand::MO_ExternalSymbol:
244     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
245            getOffset() == Other.getOffset();
246   case MachineOperand::MO_BlockAddress:
247     return getBlockAddress() == Other.getBlockAddress() &&
248            getOffset() == Other.getOffset();
249   case MachineOperand::MO_RegisterMask:
250   case MachineOperand::MO_RegisterLiveOut:
251     return getRegMask() == Other.getRegMask();
252   case MachineOperand::MO_MCSymbol:
253     return getMCSymbol() == Other.getMCSymbol();
254   case MachineOperand::MO_CFIIndex:
255     return getCFIIndex() == Other.getCFIIndex();
256   case MachineOperand::MO_Metadata:
257     return getMetadata() == Other.getMetadata();
258   }
259   llvm_unreachable("Invalid machine operand type");
260 }
261 
262 // Note: this must stay exactly in sync with isIdenticalTo above.
263 hash_code llvm::hash_value(const MachineOperand &MO) {
264   switch (MO.getType()) {
265   case MachineOperand::MO_Register:
266     // Register operands don't have target flags.
267     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
268   case MachineOperand::MO_Immediate:
269     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
270   case MachineOperand::MO_CImmediate:
271     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
272   case MachineOperand::MO_FPImmediate:
273     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
274   case MachineOperand::MO_MachineBasicBlock:
275     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
276   case MachineOperand::MO_FrameIndex:
277     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
278   case MachineOperand::MO_ConstantPoolIndex:
279   case MachineOperand::MO_TargetIndex:
280     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
281                         MO.getOffset());
282   case MachineOperand::MO_JumpTableIndex:
283     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
284   case MachineOperand::MO_ExternalSymbol:
285     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
286                         MO.getSymbolName());
287   case MachineOperand::MO_GlobalAddress:
288     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
289                         MO.getOffset());
290   case MachineOperand::MO_BlockAddress:
291     return hash_combine(MO.getType(), MO.getTargetFlags(),
292                         MO.getBlockAddress(), MO.getOffset());
293   case MachineOperand::MO_RegisterMask:
294   case MachineOperand::MO_RegisterLiveOut:
295     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
296   case MachineOperand::MO_Metadata:
297     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
298   case MachineOperand::MO_MCSymbol:
299     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
300   case MachineOperand::MO_CFIIndex:
301     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
302   }
303   llvm_unreachable("Invalid machine operand type");
304 }
305 
306 void MachineOperand::print(raw_ostream &OS,
307                            const TargetRegisterInfo *TRI) const {
308   ModuleSlotTracker DummyMST(nullptr);
309   print(OS, DummyMST, TRI);
310 }
311 
312 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
313                            const TargetRegisterInfo *TRI) const {
314   switch (getType()) {
315   case MachineOperand::MO_Register:
316     OS << PrintReg(getReg(), TRI, getSubReg());
317 
318     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
319         isInternalRead() || isEarlyClobber() || isTied()) {
320       OS << '<';
321       bool NeedComma = false;
322       if (isDef()) {
323         if (NeedComma) OS << ',';
324         if (isEarlyClobber())
325           OS << "earlyclobber,";
326         if (isImplicit())
327           OS << "imp-";
328         OS << "def";
329         NeedComma = true;
330         // <def,read-undef> only makes sense when getSubReg() is set.
331         // Don't clutter the output otherwise.
332         if (isUndef() && getSubReg())
333           OS << ",read-undef";
334       } else if (isImplicit()) {
335         OS << "imp-use";
336         NeedComma = true;
337       }
338 
339       if (isKill()) {
340         if (NeedComma) OS << ',';
341         OS << "kill";
342         NeedComma = true;
343       }
344       if (isDead()) {
345         if (NeedComma) OS << ',';
346         OS << "dead";
347         NeedComma = true;
348       }
349       if (isUndef() && isUse()) {
350         if (NeedComma) OS << ',';
351         OS << "undef";
352         NeedComma = true;
353       }
354       if (isInternalRead()) {
355         if (NeedComma) OS << ',';
356         OS << "internal";
357         NeedComma = true;
358       }
359       if (isTied()) {
360         if (NeedComma) OS << ',';
361         OS << "tied";
362         if (TiedTo != 15)
363           OS << unsigned(TiedTo - 1);
364       }
365       OS << '>';
366     }
367     break;
368   case MachineOperand::MO_Immediate:
369     OS << getImm();
370     break;
371   case MachineOperand::MO_CImmediate:
372     getCImm()->getValue().print(OS, false);
373     break;
374   case MachineOperand::MO_FPImmediate:
375     if (getFPImm()->getType()->isFloatTy()) {
376       OS << getFPImm()->getValueAPF().convertToFloat();
377     } else if (getFPImm()->getType()->isHalfTy()) {
378       APFloat APF = getFPImm()->getValueAPF();
379       bool Unused;
380       APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &Unused);
381       OS << "half " << APF.convertToFloat();
382     } else {
383       OS << getFPImm()->getValueAPF().convertToDouble();
384     }
385     break;
386   case MachineOperand::MO_MachineBasicBlock:
387     OS << "<BB#" << getMBB()->getNumber() << ">";
388     break;
389   case MachineOperand::MO_FrameIndex:
390     OS << "<fi#" << getIndex() << '>';
391     break;
392   case MachineOperand::MO_ConstantPoolIndex:
393     OS << "<cp#" << getIndex();
394     if (getOffset()) OS << "+" << getOffset();
395     OS << '>';
396     break;
397   case MachineOperand::MO_TargetIndex:
398     OS << "<ti#" << getIndex();
399     if (getOffset()) OS << "+" << getOffset();
400     OS << '>';
401     break;
402   case MachineOperand::MO_JumpTableIndex:
403     OS << "<jt#" << getIndex() << '>';
404     break;
405   case MachineOperand::MO_GlobalAddress:
406     OS << "<ga:";
407     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
408     if (getOffset()) OS << "+" << getOffset();
409     OS << '>';
410     break;
411   case MachineOperand::MO_ExternalSymbol:
412     OS << "<es:" << getSymbolName();
413     if (getOffset()) OS << "+" << getOffset();
414     OS << '>';
415     break;
416   case MachineOperand::MO_BlockAddress:
417     OS << '<';
418     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
419     if (getOffset()) OS << "+" << getOffset();
420     OS << '>';
421     break;
422   case MachineOperand::MO_RegisterMask: {
423     unsigned NumRegsInMask = 0;
424     unsigned NumRegsEmitted = 0;
425     OS << "<regmask";
426     for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
427       unsigned MaskWord = i / 32;
428       unsigned MaskBit = i % 32;
429       if (getRegMask()[MaskWord] & (1 << MaskBit)) {
430         if (PrintWholeRegMask || NumRegsEmitted <= 10) {
431           OS << " " << PrintReg(i, TRI);
432           NumRegsEmitted++;
433         }
434         NumRegsInMask++;
435       }
436     }
437     if (NumRegsEmitted != NumRegsInMask)
438       OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
439     OS << ">";
440     break;
441   }
442   case MachineOperand::MO_RegisterLiveOut:
443     OS << "<regliveout>";
444     break;
445   case MachineOperand::MO_Metadata:
446     OS << '<';
447     getMetadata()->printAsOperand(OS, MST);
448     OS << '>';
449     break;
450   case MachineOperand::MO_MCSymbol:
451     OS << "<MCSym=" << *getMCSymbol() << '>';
452     break;
453   case MachineOperand::MO_CFIIndex:
454     OS << "<call frame instruction>";
455     break;
456   }
457 
458   if (unsigned TF = getTargetFlags())
459     OS << "[TF=" << TF << ']';
460 }
461 
462 //===----------------------------------------------------------------------===//
463 // MachineMemOperand Implementation
464 //===----------------------------------------------------------------------===//
465 
466 /// getAddrSpace - Return the LLVM IR address space number that this pointer
467 /// points into.
468 unsigned MachinePointerInfo::getAddrSpace() const {
469   if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
470   return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
471 }
472 
473 /// getConstantPool - Return a MachinePointerInfo record that refers to the
474 /// constant pool.
475 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
476   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
477 }
478 
479 /// getFixedStack - Return a MachinePointerInfo record that refers to the
480 /// the specified FrameIndex.
481 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
482                                                      int FI, int64_t Offset) {
483   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
484 }
485 
486 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
487   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
488 }
489 
490 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
491   return MachinePointerInfo(MF.getPSVManager().getGOT());
492 }
493 
494 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
495                                                 int64_t Offset) {
496   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
497 }
498 
499 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
500                                      uint64_t s, unsigned int a,
501                                      const AAMDNodes &AAInfo,
502                                      const MDNode *Ranges)
503   : PtrInfo(ptrinfo), Size(s),
504     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
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(Flags);
520 }
521 
522 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
523   // The Value and Offset may differ due to CSE. But the flags and size
524   // should be the same.
525   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
526   assert(MMO->getSize() == getSize() && "Size mismatch!");
527 
528   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
529     // Update the alignment value.
530     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
531       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
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       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 ///
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.
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 void MachineInstr::setType(Type *Ty) {}
714 
715 Type *MachineInstr::getType() const { return nullptr; }
716 
717 #else
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 
724 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.
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.
739 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
740   for (MachineOperand &MO : operands())
741     if (MO.isReg())
742       MRI.addRegOperandToUseList(&MO);
743 }
744 
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.
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).
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 ///
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.
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.
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>
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 
954 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 
970 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 
1033 MachineInstr *MachineInstr::removeFromParent() {
1034   assert(getParent() && "Not embedded in a basic block!");
1035   return getParent()->remove(this);
1036 }
1037 
1038 MachineInstr *MachineInstr::removeFromBundle() {
1039   assert(getParent() && "Not embedded in a basic block!");
1040   return getParent()->remove_instr(this);
1041 }
1042 
1043 void MachineInstr::eraseFromParent() {
1044   assert(getParent() && "Not embedded in a basic block!");
1045   getParent()->erase(this);
1046 }
1047 
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 
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 ///
1075 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 
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 
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 
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 
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 
1124 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 
1133 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 
1139 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 
1167 const TargetRegisterClass*
1168 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1169                                     const TargetInstrInfo *TII,
1170                                     const TargetRegisterInfo *TRI) const {
1171   assert(getParent() && "Can't have an MBB reference here!");
1172   assert(getParent()->getParent() && "Can't have an MF reference here!");
1173   const MachineFunction &MF = *getParent()->getParent();
1174 
1175   // Most opcodes have fixed constraints in their MCInstrDesc.
1176   if (!isInlineAsm())
1177     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1178 
1179   if (!getOperand(OpIdx).isReg())
1180     return nullptr;
1181 
1182   // For tied uses on inline asm, get the constraint from the def.
1183   unsigned DefIdx;
1184   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1185     OpIdx = DefIdx;
1186 
1187   // Inline asm stores register class constraints in the flag word.
1188   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1189   if (FlagIdx < 0)
1190     return nullptr;
1191 
1192   unsigned Flag = getOperand(FlagIdx).getImm();
1193   unsigned RCID;
1194   if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1195     return TRI->getRegClass(RCID);
1196 
1197   // Assume that all registers in a memory operand are pointers.
1198   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1199     return TRI->getPointerRegClass(MF);
1200 
1201   return nullptr;
1202 }
1203 
1204 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1205     unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1206     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1207   // Check every operands inside the bundle if we have
1208   // been asked to.
1209   if (ExploreBundle)
1210     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1211          ++OpndIt)
1212       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1213           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1214   else
1215     // Otherwise, just check the current operands.
1216     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1217       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1218   return CurRC;
1219 }
1220 
1221 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1222     unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1223     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1224   assert(CurRC && "Invalid initial register class");
1225   // Check if Reg is constrained by some of its use/def from MI.
1226   const MachineOperand &MO = getOperand(OpIdx);
1227   if (!MO.isReg() || MO.getReg() != Reg)
1228     return CurRC;
1229   // If yes, accumulate the constraints through the operand.
1230   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1231 }
1232 
1233 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1234     unsigned OpIdx, const TargetRegisterClass *CurRC,
1235     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1236   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1237   const MachineOperand &MO = getOperand(OpIdx);
1238   assert(MO.isReg() &&
1239          "Cannot get register constraints for non-register operand");
1240   assert(CurRC && "Invalid initial register class");
1241   if (unsigned SubIdx = MO.getSubReg()) {
1242     if (OpRC)
1243       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1244     else
1245       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1246   } else if (OpRC)
1247     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1248   return CurRC;
1249 }
1250 
1251 /// Return the number of instructions inside the MI bundle, not counting the
1252 /// header instruction.
1253 unsigned MachineInstr::getBundleSize() const {
1254   MachineBasicBlock::const_instr_iterator I = getIterator();
1255   unsigned Size = 0;
1256   while (I->isBundledWithSucc()) {
1257     ++Size;
1258     ++I;
1259   }
1260   return Size;
1261 }
1262 
1263 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1264 /// the specific register or -1 if it is not found. It further tightens
1265 /// the search criteria to a use that kills the register if isKill is true.
1266 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1267                                           const TargetRegisterInfo *TRI) const {
1268   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1269     const MachineOperand &MO = getOperand(i);
1270     if (!MO.isReg() || !MO.isUse())
1271       continue;
1272     unsigned MOReg = MO.getReg();
1273     if (!MOReg)
1274       continue;
1275     if (MOReg == Reg ||
1276         (TRI &&
1277          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1278          TargetRegisterInfo::isPhysicalRegister(Reg) &&
1279          TRI->isSubRegister(MOReg, Reg)))
1280       if (!isKill || MO.isKill())
1281         return i;
1282   }
1283   return -1;
1284 }
1285 
1286 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1287 /// indicating if this instruction reads or writes Reg. This also considers
1288 /// partial defines.
1289 std::pair<bool,bool>
1290 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1291                                          SmallVectorImpl<unsigned> *Ops) const {
1292   bool PartDef = false; // Partial redefine.
1293   bool FullDef = false; // Full define.
1294   bool Use = false;
1295 
1296   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1297     const MachineOperand &MO = getOperand(i);
1298     if (!MO.isReg() || MO.getReg() != Reg)
1299       continue;
1300     if (Ops)
1301       Ops->push_back(i);
1302     if (MO.isUse())
1303       Use |= !MO.isUndef();
1304     else if (MO.getSubReg() && !MO.isUndef())
1305       // A partial <def,undef> doesn't count as reading the register.
1306       PartDef = true;
1307     else
1308       FullDef = true;
1309   }
1310   // A partial redefine uses Reg unless there is also a full define.
1311   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1312 }
1313 
1314 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1315 /// the specified register or -1 if it is not found. If isDead is true, defs
1316 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1317 /// also checks if there is a def of a super-register.
1318 int
1319 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1320                                         const TargetRegisterInfo *TRI) const {
1321   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1322   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1323     const MachineOperand &MO = getOperand(i);
1324     // Accept regmask operands when Overlap is set.
1325     // Ignore them when looking for a specific def operand (Overlap == false).
1326     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1327       return i;
1328     if (!MO.isReg() || !MO.isDef())
1329       continue;
1330     unsigned MOReg = MO.getReg();
1331     bool Found = (MOReg == Reg);
1332     if (!Found && TRI && isPhys &&
1333         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1334       if (Overlap)
1335         Found = TRI->regsOverlap(MOReg, Reg);
1336       else
1337         Found = TRI->isSubRegister(MOReg, Reg);
1338     }
1339     if (Found && (!isDead || MO.isDead()))
1340       return i;
1341   }
1342   return -1;
1343 }
1344 
1345 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1346 /// operand list that is used to represent the predicate. It returns -1 if
1347 /// none is found.
1348 int MachineInstr::findFirstPredOperandIdx() const {
1349   // Don't call MCID.findFirstPredOperandIdx() because this variant
1350   // is sometimes called on an instruction that's not yet complete, and
1351   // so the number of operands is less than the MCID indicates. In
1352   // particular, the PTX target does this.
1353   const MCInstrDesc &MCID = getDesc();
1354   if (MCID.isPredicable()) {
1355     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1356       if (MCID.OpInfo[i].isPredicate())
1357         return i;
1358   }
1359 
1360   return -1;
1361 }
1362 
1363 // MachineOperand::TiedTo is 4 bits wide.
1364 const unsigned TiedMax = 15;
1365 
1366 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1367 ///
1368 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1369 /// field. TiedTo can have these values:
1370 ///
1371 /// 0:              Operand is not tied to anything.
1372 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1373 /// TiedMax:        Tied to an operand >= TiedMax-1.
1374 ///
1375 /// The tied def must be one of the first TiedMax operands on a normal
1376 /// instruction. INLINEASM instructions allow more tied defs.
1377 ///
1378 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1379   MachineOperand &DefMO = getOperand(DefIdx);
1380   MachineOperand &UseMO = getOperand(UseIdx);
1381   assert(DefMO.isDef() && "DefIdx must be a def operand");
1382   assert(UseMO.isUse() && "UseIdx must be a use operand");
1383   assert(!DefMO.isTied() && "Def is already tied to another use");
1384   assert(!UseMO.isTied() && "Use is already tied to another def");
1385 
1386   if (DefIdx < TiedMax)
1387     UseMO.TiedTo = DefIdx + 1;
1388   else {
1389     // Inline asm can use the group descriptors to find tied operands, but on
1390     // normal instruction, the tied def must be within the first TiedMax
1391     // operands.
1392     assert(isInlineAsm() && "DefIdx out of range");
1393     UseMO.TiedTo = TiedMax;
1394   }
1395 
1396   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1397   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1398 }
1399 
1400 /// Given the index of a tied register operand, find the operand it is tied to.
1401 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1402 /// which must exist.
1403 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1404   const MachineOperand &MO = getOperand(OpIdx);
1405   assert(MO.isTied() && "Operand isn't tied");
1406 
1407   // Normally TiedTo is in range.
1408   if (MO.TiedTo < TiedMax)
1409     return MO.TiedTo - 1;
1410 
1411   // Uses on normal instructions can be out of range.
1412   if (!isInlineAsm()) {
1413     // Normal tied defs must be in the 0..TiedMax-1 range.
1414     if (MO.isUse())
1415       return TiedMax - 1;
1416     // MO is a def. Search for the tied use.
1417     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1418       const MachineOperand &UseMO = getOperand(i);
1419       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1420         return i;
1421     }
1422     llvm_unreachable("Can't find tied use");
1423   }
1424 
1425   // Now deal with inline asm by parsing the operand group descriptor flags.
1426   // Find the beginning of each operand group.
1427   SmallVector<unsigned, 8> GroupIdx;
1428   unsigned OpIdxGroup = ~0u;
1429   unsigned NumOps;
1430   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1431        i += NumOps) {
1432     const MachineOperand &FlagMO = getOperand(i);
1433     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1434     unsigned CurGroup = GroupIdx.size();
1435     GroupIdx.push_back(i);
1436     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1437     // OpIdx belongs to this operand group.
1438     if (OpIdx > i && OpIdx < i + NumOps)
1439       OpIdxGroup = CurGroup;
1440     unsigned TiedGroup;
1441     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1442       continue;
1443     // Operands in this group are tied to operands in TiedGroup which must be
1444     // earlier. Find the number of operands between the two groups.
1445     unsigned Delta = i - GroupIdx[TiedGroup];
1446 
1447     // OpIdx is a use tied to TiedGroup.
1448     if (OpIdxGroup == CurGroup)
1449       return OpIdx - Delta;
1450 
1451     // OpIdx is a def tied to this use group.
1452     if (OpIdxGroup == TiedGroup)
1453       return OpIdx + Delta;
1454   }
1455   llvm_unreachable("Invalid tied operand on inline asm");
1456 }
1457 
1458 /// clearKillInfo - Clears kill flags on all operands.
1459 ///
1460 void MachineInstr::clearKillInfo() {
1461   for (MachineOperand &MO : operands()) {
1462     if (MO.isReg() && MO.isUse())
1463       MO.setIsKill(false);
1464   }
1465 }
1466 
1467 void MachineInstr::substituteRegister(unsigned FromReg,
1468                                       unsigned ToReg,
1469                                       unsigned SubIdx,
1470                                       const TargetRegisterInfo &RegInfo) {
1471   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1472     if (SubIdx)
1473       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1474     for (MachineOperand &MO : operands()) {
1475       if (!MO.isReg() || MO.getReg() != FromReg)
1476         continue;
1477       MO.substPhysReg(ToReg, RegInfo);
1478     }
1479   } else {
1480     for (MachineOperand &MO : operands()) {
1481       if (!MO.isReg() || MO.getReg() != FromReg)
1482         continue;
1483       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1484     }
1485   }
1486 }
1487 
1488 /// isSafeToMove - Return true if it is safe to move this instruction. If
1489 /// SawStore is set to true, it means that there is a store (or call) between
1490 /// the instruction's location and its intended destination.
1491 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1492   // Ignore stuff that we obviously can't move.
1493   //
1494   // Treat volatile loads as stores. This is not strictly necessary for
1495   // volatiles, but it is required for atomic loads. It is not allowed to move
1496   // a load across an atomic load with Ordering > Monotonic.
1497   if (mayStore() || isCall() ||
1498       (mayLoad() && hasOrderedMemoryRef())) {
1499     SawStore = true;
1500     return false;
1501   }
1502 
1503   if (isPosition() || isDebugValue() || isTerminator() ||
1504       hasUnmodeledSideEffects())
1505     return false;
1506 
1507   // See if this instruction does a load.  If so, we have to guarantee that the
1508   // loaded value doesn't change between the load and the its intended
1509   // destination. The check for isInvariantLoad gives the targe the chance to
1510   // classify the load as always returning a constant, e.g. a constant pool
1511   // load.
1512   if (mayLoad() && !isInvariantLoad(AA))
1513     // Otherwise, this is a real load.  If there is a store between the load and
1514     // end of block, we can't move it.
1515     return !SawStore;
1516 
1517   return true;
1518 }
1519 
1520 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1521 /// or volatile memory reference, or if the information describing the memory
1522 /// reference is not available. Return false if it is known to have no ordered
1523 /// memory references.
1524 bool MachineInstr::hasOrderedMemoryRef() const {
1525   // An instruction known never to access memory won't have a volatile access.
1526   if (!mayStore() &&
1527       !mayLoad() &&
1528       !isCall() &&
1529       !hasUnmodeledSideEffects())
1530     return false;
1531 
1532   // Otherwise, if the instruction has no memory reference information,
1533   // conservatively assume it wasn't preserved.
1534   if (memoperands_empty())
1535     return true;
1536 
1537   // Check the memory reference information for ordered references.
1538   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1539     if (!(*I)->isUnordered())
1540       return true;
1541 
1542   return false;
1543 }
1544 
1545 /// isInvariantLoad - Return true if this instruction is loading from a
1546 /// location whose value is invariant across the function.  For example,
1547 /// loading a value from the constant pool or from the argument area
1548 /// of a function if it does not change.  This should only return true of
1549 /// *all* loads the instruction does are invariant (if it does multiple loads).
1550 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1551   // If the instruction doesn't load at all, it isn't an invariant load.
1552   if (!mayLoad())
1553     return false;
1554 
1555   // If the instruction has lost its memoperands, conservatively assume that
1556   // it may not be an invariant load.
1557   if (memoperands_empty())
1558     return false;
1559 
1560   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1561 
1562   for (mmo_iterator I = memoperands_begin(),
1563        E = memoperands_end(); I != E; ++I) {
1564     if ((*I)->isVolatile()) return false;
1565     if ((*I)->isStore()) return false;
1566     if ((*I)->isInvariant()) return true;
1567 
1568 
1569     // A load from a constant PseudoSourceValue is invariant.
1570     if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1571       if (PSV->isConstant(MFI))
1572         continue;
1573 
1574     if (const Value *V = (*I)->getValue()) {
1575       // If we have an AliasAnalysis, ask it whether the memory is constant.
1576       if (AA &&
1577           AA->pointsToConstantMemory(
1578               MemoryLocation(V, (*I)->getSize(), (*I)->getAAInfo())))
1579         continue;
1580     }
1581 
1582     // Otherwise assume conservatively.
1583     return false;
1584   }
1585 
1586   // Everything checks out.
1587   return true;
1588 }
1589 
1590 /// isConstantValuePHI - If the specified instruction is a PHI that always
1591 /// merges together the same virtual register, return the register, otherwise
1592 /// return 0.
1593 unsigned MachineInstr::isConstantValuePHI() const {
1594   if (!isPHI())
1595     return 0;
1596   assert(getNumOperands() >= 3 &&
1597          "It's illegal to have a PHI without source operands");
1598 
1599   unsigned Reg = getOperand(1).getReg();
1600   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1601     if (getOperand(i).getReg() != Reg)
1602       return 0;
1603   return Reg;
1604 }
1605 
1606 bool MachineInstr::hasUnmodeledSideEffects() const {
1607   if (hasProperty(MCID::UnmodeledSideEffects))
1608     return true;
1609   if (isInlineAsm()) {
1610     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1611     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1612       return true;
1613   }
1614 
1615   return false;
1616 }
1617 
1618 bool MachineInstr::isLoadFoldBarrier() const {
1619   return mayStore() || isCall() || hasUnmodeledSideEffects();
1620 }
1621 
1622 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1623 ///
1624 bool MachineInstr::allDefsAreDead() const {
1625   for (const MachineOperand &MO : operands()) {
1626     if (!MO.isReg() || MO.isUse())
1627       continue;
1628     if (!MO.isDead())
1629       return false;
1630   }
1631   return true;
1632 }
1633 
1634 /// copyImplicitOps - Copy implicit register operands from specified
1635 /// instruction to this instruction.
1636 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1637                                    const MachineInstr &MI) {
1638   for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1639        i != e; ++i) {
1640     const MachineOperand &MO = MI.getOperand(i);
1641     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1642       addOperand(MF, MO);
1643   }
1644 }
1645 
1646 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1647 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1648   dbgs() << "  " << *this;
1649 #endif
1650 }
1651 
1652 void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const {
1653   const Module *M = nullptr;
1654   if (const MachineBasicBlock *MBB = getParent())
1655     if (const MachineFunction *MF = MBB->getParent())
1656       M = MF->getFunction()->getParent();
1657 
1658   ModuleSlotTracker MST(M);
1659   print(OS, MST, SkipOpers);
1660 }
1661 
1662 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1663                          bool SkipOpers) const {
1664   // We can be a bit tidier if we know the MachineFunction.
1665   const MachineFunction *MF = nullptr;
1666   const TargetRegisterInfo *TRI = nullptr;
1667   const MachineRegisterInfo *MRI = nullptr;
1668   const TargetInstrInfo *TII = nullptr;
1669   if (const MachineBasicBlock *MBB = getParent()) {
1670     MF = MBB->getParent();
1671     if (MF) {
1672       MRI = &MF->getRegInfo();
1673       TRI = MF->getSubtarget().getRegisterInfo();
1674       TII = MF->getSubtarget().getInstrInfo();
1675     }
1676   }
1677 
1678   // Save a list of virtual registers.
1679   SmallVector<unsigned, 8> VirtRegs;
1680 
1681   // Print explicitly defined operands on the left of an assignment syntax.
1682   unsigned StartOp = 0, e = getNumOperands();
1683   for (; StartOp < e && getOperand(StartOp).isReg() &&
1684          getOperand(StartOp).isDef() &&
1685          !getOperand(StartOp).isImplicit();
1686        ++StartOp) {
1687     if (StartOp != 0) OS << ", ";
1688     getOperand(StartOp).print(OS, MST, TRI);
1689     unsigned Reg = getOperand(StartOp).getReg();
1690     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1691       VirtRegs.push_back(Reg);
1692       unsigned Size;
1693       if (MRI && (Size = MRI->getSize(Reg)))
1694         OS << '(' << Size << ')';
1695     }
1696   }
1697 
1698   if (StartOp != 0)
1699     OS << " = ";
1700 
1701   // Print the opcode name.
1702   if (TII)
1703     OS << TII->getName(getOpcode());
1704   else
1705     OS << "UNKNOWN";
1706 
1707   if (getType()) {
1708     OS << ' ';
1709     getType()->print(OS, /*IsForDebug*/ false, /*NoDetails*/ true);
1710     OS << ' ';
1711   }
1712 
1713   if (SkipOpers)
1714     return;
1715 
1716   // Print the rest of the operands.
1717   bool OmittedAnyCallClobbers = false;
1718   bool FirstOp = true;
1719   unsigned AsmDescOp = ~0u;
1720   unsigned AsmOpCount = 0;
1721 
1722   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1723     // Print asm string.
1724     OS << " ";
1725     getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1726 
1727     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1728     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1729     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1730       OS << " [sideeffect]";
1731     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1732       OS << " [mayload]";
1733     if (ExtraInfo & InlineAsm::Extra_MayStore)
1734       OS << " [maystore]";
1735     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1736       OS << " [alignstack]";
1737     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1738       OS << " [attdialect]";
1739     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1740       OS << " [inteldialect]";
1741 
1742     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1743     FirstOp = false;
1744   }
1745 
1746   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1747     const MachineOperand &MO = getOperand(i);
1748 
1749     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1750       VirtRegs.push_back(MO.getReg());
1751 
1752     // Omit call-clobbered registers which aren't used anywhere. This makes
1753     // call instructions much less noisy on targets where calls clobber lots
1754     // of registers. Don't rely on MO.isDead() because we may be called before
1755     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1756     if (MRI && isCall() &&
1757         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1758       unsigned Reg = MO.getReg();
1759       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1760         if (MRI->use_empty(Reg)) {
1761           bool HasAliasLive = false;
1762           for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1763             unsigned AliasReg = *AI;
1764             if (!MRI->use_empty(AliasReg)) {
1765               HasAliasLive = true;
1766               break;
1767             }
1768           }
1769           if (!HasAliasLive) {
1770             OmittedAnyCallClobbers = true;
1771             continue;
1772           }
1773         }
1774       }
1775     }
1776 
1777     if (FirstOp) FirstOp = false; else OS << ",";
1778     OS << " ";
1779     if (i < getDesc().NumOperands) {
1780       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1781       if (MCOI.isPredicate())
1782         OS << "pred:";
1783       if (MCOI.isOptionalDef())
1784         OS << "opt:";
1785     }
1786     if (isDebugValue() && MO.isMetadata()) {
1787       // Pretty print DBG_VALUE instructions.
1788       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1789       if (DIV && !DIV->getName().empty())
1790         OS << "!\"" << DIV->getName() << '\"';
1791       else
1792         MO.print(OS, MST, TRI);
1793     } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1794       OS << TRI->getSubRegIndexName(MO.getImm());
1795     } else if (i == AsmDescOp && MO.isImm()) {
1796       // Pretty print the inline asm operand descriptor.
1797       OS << '$' << AsmOpCount++;
1798       unsigned Flag = MO.getImm();
1799       switch (InlineAsm::getKind(Flag)) {
1800       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
1801       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
1802       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1803       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
1804       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
1805       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
1806       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1807       }
1808 
1809       unsigned RCID = 0;
1810       if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1811         if (TRI) {
1812           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1813         } else
1814           OS << ":RC" << RCID;
1815       }
1816 
1817       unsigned TiedTo = 0;
1818       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1819         OS << " tiedto:$" << TiedTo;
1820 
1821       OS << ']';
1822 
1823       // Compute the index of the next operand descriptor.
1824       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1825     } else
1826       MO.print(OS, MST, TRI);
1827   }
1828 
1829   // Briefly indicate whether any call clobbers were omitted.
1830   if (OmittedAnyCallClobbers) {
1831     if (!FirstOp) OS << ",";
1832     OS << " ...";
1833   }
1834 
1835   bool HaveSemi = false;
1836   const unsigned PrintableFlags = FrameSetup | FrameDestroy;
1837   if (Flags & PrintableFlags) {
1838     if (!HaveSemi) {
1839       OS << ";";
1840       HaveSemi = true;
1841     }
1842     OS << " flags: ";
1843 
1844     if (Flags & FrameSetup)
1845       OS << "FrameSetup";
1846 
1847     if (Flags & FrameDestroy)
1848       OS << "FrameDestroy";
1849   }
1850 
1851   if (!memoperands_empty()) {
1852     if (!HaveSemi) {
1853       OS << ";";
1854       HaveSemi = true;
1855     }
1856 
1857     OS << " mem:";
1858     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1859          i != e; ++i) {
1860       (*i)->print(OS, MST);
1861       if (std::next(i) != e)
1862         OS << " ";
1863     }
1864   }
1865 
1866   // Print the regclass of any virtual registers encountered.
1867   if (MRI && !VirtRegs.empty()) {
1868     if (!HaveSemi) {
1869       OS << ";";
1870       HaveSemi = true;
1871     }
1872     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1873       const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
1874       if (!RC)
1875         continue;
1876       // Generic virtual registers do not have register classes.
1877       if (RC.is<const RegisterBank *>())
1878         OS << " " << RC.get<const RegisterBank *>()->getName();
1879       else
1880         OS << " "
1881            << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
1882       OS << ':' << PrintReg(VirtRegs[i]);
1883       for (unsigned j = i+1; j != VirtRegs.size();) {
1884         if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
1885           ++j;
1886           continue;
1887         }
1888         if (VirtRegs[i] != VirtRegs[j])
1889           OS << "," << PrintReg(VirtRegs[j]);
1890         VirtRegs.erase(VirtRegs.begin()+j);
1891       }
1892     }
1893   }
1894 
1895   // Print debug location information.
1896   if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1897     if (!HaveSemi)
1898       OS << ";";
1899     auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1900     OS << " line no:" <<  DV->getLine();
1901     if (auto *InlinedAt = debugLoc->getInlinedAt()) {
1902       DebugLoc InlinedAtDL(InlinedAt);
1903       if (InlinedAtDL && MF) {
1904         OS << " inlined @[ ";
1905         InlinedAtDL.print(OS);
1906         OS << " ]";
1907       }
1908     }
1909     if (isIndirectDebugValue())
1910       OS << " indirect";
1911   } else if (debugLoc && MF) {
1912     if (!HaveSemi)
1913       OS << ";";
1914     OS << " dbg:";
1915     debugLoc.print(OS);
1916   }
1917 
1918   OS << '\n';
1919 }
1920 
1921 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1922                                      const TargetRegisterInfo *RegInfo,
1923                                      bool AddIfNotFound) {
1924   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1925   bool hasAliases = isPhysReg &&
1926     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1927   bool Found = false;
1928   SmallVector<unsigned,4> DeadOps;
1929   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1930     MachineOperand &MO = getOperand(i);
1931     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1932       continue;
1933     unsigned Reg = MO.getReg();
1934     if (!Reg)
1935       continue;
1936 
1937     if (Reg == IncomingReg) {
1938       if (!Found) {
1939         if (MO.isKill())
1940           // The register is already marked kill.
1941           return true;
1942         if (isPhysReg && isRegTiedToDefOperand(i))
1943           // Two-address uses of physregs must not be marked kill.
1944           return true;
1945         MO.setIsKill();
1946         Found = true;
1947       }
1948     } else if (hasAliases && MO.isKill() &&
1949                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1950       // A super-register kill already exists.
1951       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1952         return true;
1953       if (RegInfo->isSubRegister(IncomingReg, Reg))
1954         DeadOps.push_back(i);
1955     }
1956   }
1957 
1958   // Trim unneeded kill operands.
1959   while (!DeadOps.empty()) {
1960     unsigned OpIdx = DeadOps.back();
1961     if (getOperand(OpIdx).isImplicit())
1962       RemoveOperand(OpIdx);
1963     else
1964       getOperand(OpIdx).setIsKill(false);
1965     DeadOps.pop_back();
1966   }
1967 
1968   // If not found, this means an alias of one of the operands is killed. Add a
1969   // new implicit operand if required.
1970   if (!Found && AddIfNotFound) {
1971     addOperand(MachineOperand::CreateReg(IncomingReg,
1972                                          false /*IsDef*/,
1973                                          true  /*IsImp*/,
1974                                          true  /*IsKill*/));
1975     return true;
1976   }
1977   return Found;
1978 }
1979 
1980 void MachineInstr::clearRegisterKills(unsigned Reg,
1981                                       const TargetRegisterInfo *RegInfo) {
1982   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1983     RegInfo = nullptr;
1984   for (MachineOperand &MO : operands()) {
1985     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1986       continue;
1987     unsigned OpReg = MO.getReg();
1988     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1989       MO.setIsKill(false);
1990   }
1991 }
1992 
1993 bool MachineInstr::addRegisterDead(unsigned Reg,
1994                                    const TargetRegisterInfo *RegInfo,
1995                                    bool AddIfNotFound) {
1996   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1997   bool hasAliases = isPhysReg &&
1998     MCRegAliasIterator(Reg, RegInfo, false).isValid();
1999   bool Found = false;
2000   SmallVector<unsigned,4> DeadOps;
2001   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2002     MachineOperand &MO = getOperand(i);
2003     if (!MO.isReg() || !MO.isDef())
2004       continue;
2005     unsigned MOReg = MO.getReg();
2006     if (!MOReg)
2007       continue;
2008 
2009     if (MOReg == Reg) {
2010       MO.setIsDead();
2011       Found = true;
2012     } else if (hasAliases && MO.isDead() &&
2013                TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2014       // There exists a super-register that's marked dead.
2015       if (RegInfo->isSuperRegister(Reg, MOReg))
2016         return true;
2017       if (RegInfo->isSubRegister(Reg, MOReg))
2018         DeadOps.push_back(i);
2019     }
2020   }
2021 
2022   // Trim unneeded dead operands.
2023   while (!DeadOps.empty()) {
2024     unsigned OpIdx = DeadOps.back();
2025     if (getOperand(OpIdx).isImplicit())
2026       RemoveOperand(OpIdx);
2027     else
2028       getOperand(OpIdx).setIsDead(false);
2029     DeadOps.pop_back();
2030   }
2031 
2032   // If not found, this means an alias of one of the operands is dead. Add a
2033   // new implicit operand if required.
2034   if (Found || !AddIfNotFound)
2035     return Found;
2036 
2037   addOperand(MachineOperand::CreateReg(Reg,
2038                                        true  /*IsDef*/,
2039                                        true  /*IsImp*/,
2040                                        false /*IsKill*/,
2041                                        true  /*IsDead*/));
2042   return true;
2043 }
2044 
2045 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2046   for (MachineOperand &MO : operands()) {
2047     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2048       continue;
2049     MO.setIsDead(false);
2050   }
2051 }
2052 
2053 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2054   for (MachineOperand &MO : operands()) {
2055     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2056       continue;
2057     MO.setIsUndef(IsUndef);
2058   }
2059 }
2060 
2061 void MachineInstr::addRegisterDefined(unsigned Reg,
2062                                       const TargetRegisterInfo *RegInfo) {
2063   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2064     MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2065     if (MO)
2066       return;
2067   } else {
2068     for (const MachineOperand &MO : operands()) {
2069       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2070           MO.getSubReg() == 0)
2071         return;
2072     }
2073   }
2074   addOperand(MachineOperand::CreateReg(Reg,
2075                                        true  /*IsDef*/,
2076                                        true  /*IsImp*/));
2077 }
2078 
2079 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2080                                          const TargetRegisterInfo &TRI) {
2081   bool HasRegMask = false;
2082   for (MachineOperand &MO : operands()) {
2083     if (MO.isRegMask()) {
2084       HasRegMask = true;
2085       continue;
2086     }
2087     if (!MO.isReg() || !MO.isDef()) continue;
2088     unsigned Reg = MO.getReg();
2089     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2090     // If there are no uses, including partial uses, the def is dead.
2091     if (std::none_of(UsedRegs.begin(), UsedRegs.end(),
2092                      [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2093       MO.setIsDead();
2094   }
2095 
2096   // This is a call with a register mask operand.
2097   // Mask clobbers are always dead, so add defs for the non-dead defines.
2098   if (HasRegMask)
2099     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2100          I != E; ++I)
2101       addRegisterDefined(*I, &TRI);
2102 }
2103 
2104 unsigned
2105 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2106   // Build up a buffer of hash code components.
2107   SmallVector<size_t, 8> HashComponents;
2108   HashComponents.reserve(MI->getNumOperands() + 1);
2109   HashComponents.push_back(MI->getOpcode());
2110   for (const MachineOperand &MO : MI->operands()) {
2111     if (MO.isReg() && MO.isDef() &&
2112         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2113       continue;  // Skip virtual register defs.
2114 
2115     HashComponents.push_back(hash_value(MO));
2116   }
2117   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2118 }
2119 
2120 void MachineInstr::emitError(StringRef Msg) const {
2121   // Find the source location cookie.
2122   unsigned LocCookie = 0;
2123   const MDNode *LocMD = nullptr;
2124   for (unsigned i = getNumOperands(); i != 0; --i) {
2125     if (getOperand(i-1).isMetadata() &&
2126         (LocMD = getOperand(i-1).getMetadata()) &&
2127         LocMD->getNumOperands() != 0) {
2128       if (const ConstantInt *CI =
2129               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2130         LocCookie = CI->getZExtValue();
2131         break;
2132       }
2133     }
2134   }
2135 
2136   if (const MachineBasicBlock *MBB = getParent())
2137     if (const MachineFunction *MF = MBB->getParent())
2138       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2139   report_fatal_error(Msg);
2140 }
2141