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