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