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