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