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