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