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