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