1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
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 // This file contains the declaration of the MachineInstr class, which is the
10 // basic representation for all target dependent machine instructions used by
11 // the back end.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
16 #define LLVM_CODEGEN_MACHINEINSTR_H
17 
18 #include "llvm/ADT/DenseMapInfo.h"
19 #include "llvm/ADT/PointerSumType.h"
20 #include "llvm/ADT/ilist.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/TargetOpcodes.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Support/ArrayRecycler.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/TrailingObjects.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <utility>
38 
39 namespace llvm {
40 
41 class DILabel;
42 class Instruction;
43 class MDNode;
44 class AAResults;
45 template <typename T> class ArrayRef;
46 class DIExpression;
47 class DILocalVariable;
48 class MachineBasicBlock;
49 class MachineFunction;
50 class MachineRegisterInfo;
51 class ModuleSlotTracker;
52 class raw_ostream;
53 template <typename T> class SmallVectorImpl;
54 class SmallBitVector;
55 class StringRef;
56 class TargetInstrInfo;
57 class TargetRegisterClass;
58 class TargetRegisterInfo;
59 
60 //===----------------------------------------------------------------------===//
61 /// Representation of each machine instruction.
62 ///
63 /// This class isn't a POD type, but it must have a trivial destructor. When a
64 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
65 /// without having their destructor called.
66 ///
67 class MachineInstr
68     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
69                                     ilist_sentinel_tracking<true>> {
70 public:
71   using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
72 
73   /// Flags to specify different kinds of comments to output in
74   /// assembly code.  These flags carry semantic information not
75   /// otherwise easily derivable from the IR text.
76   ///
77   enum CommentFlag {
78     ReloadReuse = 0x1,    // higher bits are reserved for target dep comments.
79     NoSchedComment = 0x2,
80     TAsmComments = 0x4    // Target Asm comments should start from this value.
81   };
82 
83   enum MIFlag {
84     NoFlags = 0,
85     FrameSetup = 1 << 0,     // Instruction is used as a part of
86                              // function frame setup code.
87     FrameDestroy = 1 << 1,   // Instruction is used as a part of
88                              // function frame destruction code.
89     BundledPred = 1 << 2,    // Instruction has bundled predecessors.
90     BundledSucc = 1 << 3,    // Instruction has bundled successors.
91     FmNoNans = 1 << 4,       // Instruction does not support Fast
92                              // math nan values.
93     FmNoInfs = 1 << 5,       // Instruction does not support Fast
94                              // math infinity values.
95     FmNsz = 1 << 6,          // Instruction is not required to retain
96                              // signed zero values.
97     FmArcp = 1 << 7,         // Instruction supports Fast math
98                              // reciprocal approximations.
99     FmContract = 1 << 8,     // Instruction supports Fast math
100                              // contraction operations like fma.
101     FmAfn = 1 << 9,          // Instruction may map to Fast math
102                              // intrinsic approximation.
103     FmReassoc = 1 << 10,     // Instruction supports Fast math
104                              // reassociation of operand order.
105     NoUWrap = 1 << 11,       // Instruction supports binary operator
106                              // no unsigned wrap.
107     NoSWrap = 1 << 12,       // Instruction supports binary operator
108                              // no signed wrap.
109     IsExact = 1 << 13,       // Instruction supports division is
110                              // known to be exact.
111     NoFPExcept = 1 << 14,    // Instruction does not raise
112                              // floatint-point exceptions.
113     NoMerge = 1 << 15,       // Passes that drop source location info
114                              // (e.g. branch folding) should skip
115                              // this instruction.
116     Unpredictable = 1 << 16, // Instruction with unpredictable condition.
117     NoConvergent = 1 << 17,  // Call does not require convergence guarantees.
118   };
119 
120 private:
121   const MCInstrDesc *MCID;              // Instruction descriptor.
122   MachineBasicBlock *Parent = nullptr;  // Pointer to the owning basic block.
123 
124   // Operands are allocated by an ArrayRecycler.
125   MachineOperand *Operands = nullptr;   // Pointer to the first operand.
126 
127 #define LLVM_MI_NUMOPERANDS_BITS 24
128 #define LLVM_MI_FLAGS_BITS 24
129 #define LLVM_MI_ASMPRINTERFLAGS_BITS 8
130 
131   /// Number of operands on instruction.
132   uint32_t NumOperands : LLVM_MI_NUMOPERANDS_BITS;
133 
134   // OperandCapacity has uint8_t size, so it should be next to NumOperands
135   // to properly pack.
136   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
137   OperandCapacity CapOperands;          // Capacity of the Operands array.
138 
139   /// Various bits of additional information about the machine instruction.
140   uint32_t Flags : LLVM_MI_FLAGS_BITS;
141 
142   /// Various bits of information used by the AsmPrinter to emit helpful
143   /// comments.  This is *not* semantic information.  Do not use this for
144   /// anything other than to convey comment information to AsmPrinter.
145   uint8_t AsmPrinterFlags : LLVM_MI_ASMPRINTERFLAGS_BITS;
146 
147   /// Internal implementation detail class that provides out-of-line storage for
148   /// extra info used by the machine instruction when this info cannot be stored
149   /// in-line within the instruction itself.
150   ///
151   /// This has to be defined eagerly due to the implementation constraints of
152   /// `PointerSumType` where it is used.
153   class ExtraInfo final : TrailingObjects<ExtraInfo, MachineMemOperand *,
154                                           MCSymbol *, MDNode *, uint32_t> {
155   public:
156     static ExtraInfo *create(BumpPtrAllocator &Allocator,
157                              ArrayRef<MachineMemOperand *> MMOs,
158                              MCSymbol *PreInstrSymbol = nullptr,
159                              MCSymbol *PostInstrSymbol = nullptr,
160                              MDNode *HeapAllocMarker = nullptr,
161                              MDNode *PCSections = nullptr,
162                              uint32_t CFIType = 0) {
163       bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
164       bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
165       bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
166       bool HasCFIType = CFIType != 0;
167       bool HasPCSections = PCSections != nullptr;
168       auto *Result = new (Allocator.Allocate(
169           totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *, uint32_t>(
170               MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
171               HasHeapAllocMarker + HasPCSections, HasCFIType),
172           alignof(ExtraInfo)))
173           ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
174                     HasHeapAllocMarker, HasPCSections, HasCFIType);
175 
176       // Copy the actual data into the trailing objects.
177       std::copy(MMOs.begin(), MMOs.end(),
178                 Result->getTrailingObjects<MachineMemOperand *>());
179 
180       if (HasPreInstrSymbol)
181         Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
182       if (HasPostInstrSymbol)
183         Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
184             PostInstrSymbol;
185       if (HasHeapAllocMarker)
186         Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
187       if (HasPCSections)
188         Result->getTrailingObjects<MDNode *>()[HasHeapAllocMarker] =
189             PCSections;
190       if (HasCFIType)
191         Result->getTrailingObjects<uint32_t>()[0] = CFIType;
192 
193       return Result;
194     }
195 
getMMOs()196     ArrayRef<MachineMemOperand *> getMMOs() const {
197       return ArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
198     }
199 
getPreInstrSymbol()200     MCSymbol *getPreInstrSymbol() const {
201       return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
202     }
203 
getPostInstrSymbol()204     MCSymbol *getPostInstrSymbol() const {
205       return HasPostInstrSymbol
206                  ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
207                  : nullptr;
208     }
209 
getHeapAllocMarker()210     MDNode *getHeapAllocMarker() const {
211       return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
212     }
213 
getPCSections()214     MDNode *getPCSections() const {
215       return HasPCSections
216                  ? getTrailingObjects<MDNode *>()[HasHeapAllocMarker]
217                  : nullptr;
218     }
219 
getCFIType()220     uint32_t getCFIType() const {
221       return HasCFIType ? getTrailingObjects<uint32_t>()[0] : 0;
222     }
223 
224   private:
225     friend TrailingObjects;
226 
227     // Description of the extra info, used to interpret the actual optional
228     // data appended.
229     //
230     // Note that this is not terribly space optimized. This leaves a great deal
231     // of flexibility to fit more in here later.
232     const int NumMMOs;
233     const bool HasPreInstrSymbol;
234     const bool HasPostInstrSymbol;
235     const bool HasHeapAllocMarker;
236     const bool HasPCSections;
237     const bool HasCFIType;
238 
239     // Implement the `TrailingObjects` internal API.
numTrailingObjects(OverloadToken<MachineMemOperand * >)240     size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
241       return NumMMOs;
242     }
numTrailingObjects(OverloadToken<MCSymbol * >)243     size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
244       return HasPreInstrSymbol + HasPostInstrSymbol;
245     }
numTrailingObjects(OverloadToken<MDNode * >)246     size_t numTrailingObjects(OverloadToken<MDNode *>) const {
247       return HasHeapAllocMarker + HasPCSections;
248     }
numTrailingObjects(OverloadToken<uint32_t>)249     size_t numTrailingObjects(OverloadToken<uint32_t>) const {
250       return HasCFIType;
251     }
252 
253     // Just a boring constructor to allow us to initialize the sizes. Always use
254     // the `create` routine above.
ExtraInfo(int NumMMOs,bool HasPreInstrSymbol,bool HasPostInstrSymbol,bool HasHeapAllocMarker,bool HasPCSections,bool HasCFIType)255     ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
256               bool HasHeapAllocMarker, bool HasPCSections, bool HasCFIType)
257         : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
258           HasPostInstrSymbol(HasPostInstrSymbol),
259           HasHeapAllocMarker(HasHeapAllocMarker), HasPCSections(HasPCSections),
260           HasCFIType(HasCFIType) {}
261   };
262 
263   /// Enumeration of the kinds of inline extra info available. It is important
264   /// that the `MachineMemOperand` inline kind has a tag value of zero to make
265   /// it accessible as an `ArrayRef`.
266   enum ExtraInfoInlineKinds {
267     EIIK_MMO = 0,
268     EIIK_PreInstrSymbol,
269     EIIK_PostInstrSymbol,
270     EIIK_OutOfLine
271   };
272 
273   // We store extra information about the instruction here. The common case is
274   // expected to be nothing or a single pointer (typically a MMO or a symbol).
275   // We work to optimize this common case by storing it inline here rather than
276   // requiring a separate allocation, but we fall back to an allocation when
277   // multiple pointers are needed.
278   PointerSumType<ExtraInfoInlineKinds,
279                  PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
280                  PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
281                  PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
282                  PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
283       Info;
284 
285   DebugLoc DbgLoc; // Source line information.
286 
287   /// Unique instruction number. Used by DBG_INSTR_REFs to refer to the values
288   /// defined by this instruction.
289   unsigned DebugInstrNum;
290 
291   // Intrusive list support
292   friend struct ilist_traits<MachineInstr>;
293   friend struct ilist_callback_traits<MachineBasicBlock>;
294   void setParent(MachineBasicBlock *P) { Parent = P; }
295 
296   /// This constructor creates a copy of the given
297   /// MachineInstr in the given MachineFunction.
298   MachineInstr(MachineFunction &, const MachineInstr &);
299 
300   /// This constructor create a MachineInstr and add the implicit operands.
301   /// It reserves space for number of operands specified by
302   /// MCInstrDesc.  An explicit DebugLoc is supplied.
303   MachineInstr(MachineFunction &, const MCInstrDesc &TID, DebugLoc DL,
304                bool NoImp = false);
305 
306   // MachineInstrs are pool-allocated and owned by MachineFunction.
307   friend class MachineFunction;
308 
309   void
310   dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
311             SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const;
312 
313   static bool opIsRegDef(const MachineOperand &Op) {
314     return Op.isReg() && Op.isDef();
315   }
316 
317   static bool opIsRegUse(const MachineOperand &Op) {
318     return Op.isReg() && Op.isUse();
319   }
320 
321 public:
322   MachineInstr(const MachineInstr &) = delete;
323   MachineInstr &operator=(const MachineInstr &) = delete;
324   // Use MachineFunction::DeleteMachineInstr() instead.
325   ~MachineInstr() = delete;
326 
327   const MachineBasicBlock* getParent() const { return Parent; }
328   MachineBasicBlock* getParent() { return Parent; }
329 
330   /// Move the instruction before \p MovePos.
331   void moveBefore(MachineInstr *MovePos);
332 
333   /// Return the function that contains the basic block that this instruction
334   /// belongs to.
335   ///
336   /// Note: this is undefined behaviour if the instruction does not have a
337   /// parent.
338   const MachineFunction *getMF() const;
339   MachineFunction *getMF() {
340     return const_cast<MachineFunction *>(
341         static_cast<const MachineInstr *>(this)->getMF());
342   }
343 
344   /// Return the asm printer flags bitvector.
345   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
346 
347   /// Clear the AsmPrinter bitvector.
348   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
349 
350   /// Return whether an AsmPrinter flag is set.
351   bool getAsmPrinterFlag(CommentFlag Flag) const {
352     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
353            "Flag is out of range for the AsmPrinterFlags field");
354     return AsmPrinterFlags & Flag;
355   }
356 
357   /// Set a flag for the AsmPrinter.
358   void setAsmPrinterFlag(uint8_t Flag) {
359     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
360            "Flag is out of range for the AsmPrinterFlags field");
361     AsmPrinterFlags |= Flag;
362   }
363 
364   /// Clear specific AsmPrinter flags.
365   void clearAsmPrinterFlag(CommentFlag Flag) {
366     assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) &&
367            "Flag is out of range for the AsmPrinterFlags field");
368     AsmPrinterFlags &= ~Flag;
369   }
370 
371   /// Return the MI flags bitvector.
372   uint32_t getFlags() const {
373     return Flags;
374   }
375 
376   /// Return whether an MI flag is set.
377   bool getFlag(MIFlag Flag) const {
378     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
379            "Flag is out of range for the Flags field");
380     return Flags & Flag;
381   }
382 
383   /// Set a MI flag.
384   void setFlag(MIFlag Flag) {
385     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
386            "Flag is out of range for the Flags field");
387     Flags |= (uint32_t)Flag;
388   }
389 
390   void setFlags(unsigned flags) {
391     assert(isUInt<LLVM_MI_FLAGS_BITS>(flags) &&
392            "flags to be set are out of range for the Flags field");
393     // Filter out the automatically maintained flags.
394     unsigned Mask = BundledPred | BundledSucc;
395     Flags = (Flags & Mask) | (flags & ~Mask);
396   }
397 
398   /// clearFlag - Clear a MI flag.
399   void clearFlag(MIFlag Flag) {
400     assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) &&
401            "Flag to clear is out of range for the Flags field");
402     Flags &= ~((uint32_t)Flag);
403   }
404 
405   /// Return true if MI is in a bundle (but not the first MI in a bundle).
406   ///
407   /// A bundle looks like this before it's finalized:
408   ///   ----------------
409   ///   |      MI      |
410   ///   ----------------
411   ///          |
412   ///   ----------------
413   ///   |      MI    * |
414   ///   ----------------
415   ///          |
416   ///   ----------------
417   ///   |      MI    * |
418   ///   ----------------
419   /// In this case, the first MI starts a bundle but is not inside a bundle, the
420   /// next 2 MIs are considered "inside" the bundle.
421   ///
422   /// After a bundle is finalized, it looks like this:
423   ///   ----------------
424   ///   |    Bundle    |
425   ///   ----------------
426   ///          |
427   ///   ----------------
428   ///   |      MI    * |
429   ///   ----------------
430   ///          |
431   ///   ----------------
432   ///   |      MI    * |
433   ///   ----------------
434   ///          |
435   ///   ----------------
436   ///   |      MI    * |
437   ///   ----------------
438   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
439   /// a bundle, but the next three MIs are.
440   bool isInsideBundle() const {
441     return getFlag(BundledPred);
442   }
443 
444   /// Return true if this instruction part of a bundle. This is true
445   /// if either itself or its following instruction is marked "InsideBundle".
446   bool isBundled() const {
447     return isBundledWithPred() || isBundledWithSucc();
448   }
449 
450   /// Return true if this instruction is part of a bundle, and it is not the
451   /// first instruction in the bundle.
452   bool isBundledWithPred() const { return getFlag(BundledPred); }
453 
454   /// Return true if this instruction is part of a bundle, and it is not the
455   /// last instruction in the bundle.
456   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
457 
458   /// Bundle this instruction with its predecessor. This can be an unbundled
459   /// instruction, or it can be the first instruction in a bundle.
460   void bundleWithPred();
461 
462   /// Bundle this instruction with its successor. This can be an unbundled
463   /// instruction, or it can be the last instruction in a bundle.
464   void bundleWithSucc();
465 
466   /// Break bundle above this instruction.
467   void unbundleFromPred();
468 
469   /// Break bundle below this instruction.
470   void unbundleFromSucc();
471 
472   /// Returns the debug location id of this MachineInstr.
473   const DebugLoc &getDebugLoc() const { return DbgLoc; }
474 
475   /// Return the operand containing the offset to be used if this DBG_VALUE
476   /// instruction is indirect; will be an invalid register if this value is
477   /// not indirect, and an immediate with value 0 otherwise.
478   const MachineOperand &getDebugOffset() const {
479     assert(isNonListDebugValue() && "not a DBG_VALUE");
480     return getOperand(1);
481   }
482   MachineOperand &getDebugOffset() {
483     assert(isNonListDebugValue() && "not a DBG_VALUE");
484     return getOperand(1);
485   }
486 
487   /// Return the operand for the debug variable referenced by
488   /// this DBG_VALUE instruction.
489   const MachineOperand &getDebugVariableOp() const;
490   MachineOperand &getDebugVariableOp();
491 
492   /// Return the debug variable referenced by
493   /// this DBG_VALUE instruction.
494   const DILocalVariable *getDebugVariable() const;
495 
496   /// Return the operand for the complex address expression referenced by
497   /// this DBG_VALUE instruction.
498   const MachineOperand &getDebugExpressionOp() const;
499   MachineOperand &getDebugExpressionOp();
500 
501   /// Return the complex address expression referenced by
502   /// this DBG_VALUE instruction.
503   const DIExpression *getDebugExpression() const;
504 
505   /// Return the debug label referenced by
506   /// this DBG_LABEL instruction.
507   const DILabel *getDebugLabel() const;
508 
509   /// Fetch the instruction number of this MachineInstr. If it does not have
510   /// one already, a new and unique number will be assigned.
511   unsigned getDebugInstrNum();
512 
513   /// Fetch instruction number of this MachineInstr -- but before it's inserted
514   /// into \p MF. Needed for transformations that create an instruction but
515   /// don't immediately insert them.
516   unsigned getDebugInstrNum(MachineFunction &MF);
517 
518   /// Examine the instruction number of this MachineInstr. May be zero if
519   /// it hasn't been assigned a number yet.
520   unsigned peekDebugInstrNum() const { return DebugInstrNum; }
521 
522   /// Set instruction number of this MachineInstr. Avoid using unless you're
523   /// deserializing this information.
524   void setDebugInstrNum(unsigned Num) { DebugInstrNum = Num; }
525 
526   /// Drop any variable location debugging information associated with this
527   /// instruction. Use when an instruction is modified in such a way that it no
528   /// longer defines the value it used to. Variable locations using that value
529   /// will be dropped.
530   void dropDebugNumber() { DebugInstrNum = 0; }
531 
532   /// Emit an error referring to the source location of this instruction.
533   /// This should only be used for inline assembly that is somehow
534   /// impossible to compile. Other errors should have been handled much
535   /// earlier.
536   ///
537   /// If this method returns, the caller should try to recover from the error.
538   void emitError(StringRef Msg) const;
539 
540   /// Returns the target instruction descriptor of this MachineInstr.
541   const MCInstrDesc &getDesc() const { return *MCID; }
542 
543   /// Returns the opcode of this MachineInstr.
544   unsigned getOpcode() const { return MCID->Opcode; }
545 
546   /// Retuns the total number of operands.
547   unsigned getNumOperands() const { return NumOperands; }
548 
549   /// Returns the total number of operands which are debug locations.
550   unsigned getNumDebugOperands() const {
551     return std::distance(debug_operands().begin(), debug_operands().end());
552   }
553 
554   const MachineOperand& getOperand(unsigned i) const {
555     assert(i < getNumOperands() && "getOperand() out of range!");
556     return Operands[i];
557   }
558   MachineOperand& getOperand(unsigned i) {
559     assert(i < getNumOperands() && "getOperand() out of range!");
560     return Operands[i];
561   }
562 
563   MachineOperand &getDebugOperand(unsigned Index) {
564     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
565     return *(debug_operands().begin() + Index);
566   }
567   const MachineOperand &getDebugOperand(unsigned Index) const {
568     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
569     return *(debug_operands().begin() + Index);
570   }
571 
572   /// Returns whether this debug value has at least one debug operand with the
573   /// register \p Reg.
574   bool hasDebugOperandForReg(Register Reg) const {
575     return any_of(debug_operands(), [Reg](const MachineOperand &Op) {
576       return Op.isReg() && Op.getReg() == Reg;
577     });
578   }
579 
580   /// Returns a range of all of the operands that correspond to a debug use of
581   /// \p Reg.
582   template <typename Operand, typename Instruction>
583   static iterator_range<
584       filter_iterator<Operand *, std::function<bool(Operand &Op)>>>
585   getDebugOperandsForReg(Instruction *MI, Register Reg) {
586     std::function<bool(Operand & Op)> OpUsesReg(
587         [Reg](Operand &Op) { return Op.isReg() && Op.getReg() == Reg; });
588     return make_filter_range(MI->debug_operands(), OpUsesReg);
589   }
590   iterator_range<filter_iterator<const MachineOperand *,
591                                  std::function<bool(const MachineOperand &Op)>>>
592   getDebugOperandsForReg(Register Reg) const {
593     return MachineInstr::getDebugOperandsForReg<const MachineOperand,
594                                                 const MachineInstr>(this, Reg);
595   }
596   iterator_range<filter_iterator<MachineOperand *,
597                                  std::function<bool(MachineOperand &Op)>>>
598   getDebugOperandsForReg(Register Reg) {
599     return MachineInstr::getDebugOperandsForReg<MachineOperand, MachineInstr>(
600         this, Reg);
601   }
602 
603   bool isDebugOperand(const MachineOperand *Op) const {
604     return Op >= adl_begin(debug_operands()) && Op <= adl_end(debug_operands());
605   }
606 
607   unsigned getDebugOperandIndex(const MachineOperand *Op) const {
608     assert(isDebugOperand(Op) && "Expected a debug operand.");
609     return std::distance(adl_begin(debug_operands()), Op);
610   }
611 
612   /// Returns the total number of definitions.
613   unsigned getNumDefs() const {
614     return getNumExplicitDefs() + MCID->implicit_defs().size();
615   }
616 
617   /// Returns true if the instruction has implicit definition.
618   bool hasImplicitDef() const {
619     for (const MachineOperand &MO : implicit_operands())
620       if (MO.isDef() && MO.isImplicit())
621         return true;
622     return false;
623   }
624 
625   /// Returns the implicit operands number.
626   unsigned getNumImplicitOperands() const {
627     return getNumOperands() - getNumExplicitOperands();
628   }
629 
630   /// Return true if operand \p OpIdx is a subregister index.
631   bool isOperandSubregIdx(unsigned OpIdx) const {
632     assert(getOperand(OpIdx).isImm() && "Expected MO_Immediate operand type.");
633     if (isExtractSubreg() && OpIdx == 2)
634       return true;
635     if (isInsertSubreg() && OpIdx == 3)
636       return true;
637     if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
638       return true;
639     if (isSubregToReg() && OpIdx == 3)
640       return true;
641     return false;
642   }
643 
644   /// Returns the number of non-implicit operands.
645   unsigned getNumExplicitOperands() const;
646 
647   /// Returns the number of non-implicit definitions.
648   unsigned getNumExplicitDefs() const;
649 
650   /// iterator/begin/end - Iterate over all operands of a machine instruction.
651   using mop_iterator = MachineOperand *;
652   using const_mop_iterator = const MachineOperand *;
653 
654   mop_iterator operands_begin() { return Operands; }
655   mop_iterator operands_end() { return Operands + NumOperands; }
656 
657   const_mop_iterator operands_begin() const { return Operands; }
658   const_mop_iterator operands_end() const { return Operands + NumOperands; }
659 
660   iterator_range<mop_iterator> operands() {
661     return make_range(operands_begin(), operands_end());
662   }
663   iterator_range<const_mop_iterator> operands() const {
664     return make_range(operands_begin(), operands_end());
665   }
666   iterator_range<mop_iterator> explicit_operands() {
667     return make_range(operands_begin(),
668                       operands_begin() + getNumExplicitOperands());
669   }
670   iterator_range<const_mop_iterator> explicit_operands() const {
671     return make_range(operands_begin(),
672                       operands_begin() + getNumExplicitOperands());
673   }
674   iterator_range<mop_iterator> implicit_operands() {
675     return make_range(explicit_operands().end(), operands_end());
676   }
677   iterator_range<const_mop_iterator> implicit_operands() const {
678     return make_range(explicit_operands().end(), operands_end());
679   }
680   /// Returns a range over all operands that are used to determine the variable
681   /// location for this DBG_VALUE instruction.
682   iterator_range<mop_iterator> debug_operands() {
683     assert((isDebugValueLike()) && "Must be a debug value instruction.");
684     return isNonListDebugValue()
685                ? make_range(operands_begin(), operands_begin() + 1)
686                : make_range(operands_begin() + 2, operands_end());
687   }
688   /// \copydoc debug_operands()
689   iterator_range<const_mop_iterator> debug_operands() const {
690     assert((isDebugValueLike()) && "Must be a debug value instruction.");
691     return isNonListDebugValue()
692                ? make_range(operands_begin(), operands_begin() + 1)
693                : make_range(operands_begin() + 2, operands_end());
694   }
695   /// Returns a range over all explicit operands that are register definitions.
696   /// Implicit definition are not included!
697   iterator_range<mop_iterator> defs() {
698     return make_range(operands_begin(),
699                       operands_begin() + getNumExplicitDefs());
700   }
701   /// \copydoc defs()
702   iterator_range<const_mop_iterator> defs() const {
703     return make_range(operands_begin(),
704                       operands_begin() + getNumExplicitDefs());
705   }
706   /// Returns a range that includes all operands that are register uses.
707   /// This may include unrelated operands which are not register uses.
708   iterator_range<mop_iterator> uses() {
709     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
710   }
711   /// \copydoc uses()
712   iterator_range<const_mop_iterator> uses() const {
713     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
714   }
715   iterator_range<mop_iterator> explicit_uses() {
716     return make_range(operands_begin() + getNumExplicitDefs(),
717                       operands_begin() + getNumExplicitOperands());
718   }
719   iterator_range<const_mop_iterator> explicit_uses() const {
720     return make_range(operands_begin() + getNumExplicitDefs(),
721                       operands_begin() + getNumExplicitOperands());
722   }
723 
724   using filtered_mop_iterator =
725       filter_iterator<mop_iterator, bool (*)(const MachineOperand &)>;
726   using filtered_const_mop_iterator =
727       filter_iterator<const_mop_iterator, bool (*)(const MachineOperand &)>;
728 
729   /// Returns an iterator range over all operands that are (explicit or
730   /// implicit) register defs.
731   iterator_range<filtered_mop_iterator> all_defs() {
732     return make_filter_range(operands(), opIsRegDef);
733   }
734   /// \copydoc all_defs()
735   iterator_range<filtered_const_mop_iterator> all_defs() const {
736     return make_filter_range(operands(), opIsRegDef);
737   }
738 
739   /// Returns an iterator range over all operands that are (explicit or
740   /// implicit) register uses.
741   iterator_range<filtered_mop_iterator> all_uses() {
742     return make_filter_range(uses(), opIsRegUse);
743   }
744   /// \copydoc all_uses()
745   iterator_range<filtered_const_mop_iterator> all_uses() const {
746     return make_filter_range(uses(), opIsRegUse);
747   }
748 
749   /// Returns the number of the operand iterator \p I points to.
750   unsigned getOperandNo(const_mop_iterator I) const {
751     return I - operands_begin();
752   }
753 
754   /// Access to memory operands of the instruction. If there are none, that does
755   /// not imply anything about whether the function accesses memory. Instead,
756   /// the caller must behave conservatively.
757   ArrayRef<MachineMemOperand *> memoperands() const {
758     if (!Info)
759       return {};
760 
761     if (Info.is<EIIK_MMO>())
762       return ArrayRef(Info.getAddrOfZeroTagPointer(), 1);
763 
764     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
765       return EI->getMMOs();
766 
767     return {};
768   }
769 
770   /// Access to memory operands of the instruction.
771   ///
772   /// If `memoperands_begin() == memoperands_end()`, that does not imply
773   /// anything about whether the function accesses memory. Instead, the caller
774   /// must behave conservatively.
775   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
776 
777   /// Access to memory operands of the instruction.
778   ///
779   /// If `memoperands_begin() == memoperands_end()`, that does not imply
780   /// anything about whether the function accesses memory. Instead, the caller
781   /// must behave conservatively.
782   mmo_iterator memoperands_end() const { return memoperands().end(); }
783 
784   /// Return true if we don't have any memory operands which described the
785   /// memory access done by this instruction.  If this is true, calling code
786   /// must be conservative.
787   bool memoperands_empty() const { return memoperands().empty(); }
788 
789   /// Return true if this instruction has exactly one MachineMemOperand.
790   bool hasOneMemOperand() const { return memoperands().size() == 1; }
791 
792   /// Return the number of memory operands.
793   unsigned getNumMemOperands() const { return memoperands().size(); }
794 
795   /// Helper to extract a pre-instruction symbol if one has been added.
796   MCSymbol *getPreInstrSymbol() const {
797     if (!Info)
798       return nullptr;
799     if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
800       return S;
801     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
802       return EI->getPreInstrSymbol();
803 
804     return nullptr;
805   }
806 
807   /// Helper to extract a post-instruction symbol if one has been added.
808   MCSymbol *getPostInstrSymbol() const {
809     if (!Info)
810       return nullptr;
811     if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
812       return S;
813     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
814       return EI->getPostInstrSymbol();
815 
816     return nullptr;
817   }
818 
819   /// Helper to extract a heap alloc marker if one has been added.
820   MDNode *getHeapAllocMarker() const {
821     if (!Info)
822       return nullptr;
823     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
824       return EI->getHeapAllocMarker();
825 
826     return nullptr;
827   }
828 
829   /// Helper to extract PCSections metadata target sections.
830   MDNode *getPCSections() const {
831     if (!Info)
832       return nullptr;
833     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
834       return EI->getPCSections();
835 
836     return nullptr;
837   }
838 
839   /// Helper to extract a CFI type hash if one has been added.
840   uint32_t getCFIType() const {
841     if (!Info)
842       return 0;
843     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
844       return EI->getCFIType();
845 
846     return 0;
847   }
848 
849   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
850   /// queries but they are bundle aware.
851 
852   enum QueryType {
853     IgnoreBundle,    // Ignore bundles
854     AnyInBundle,     // Return true if any instruction in bundle has property
855     AllInBundle      // Return true if all instructions in bundle have property
856   };
857 
858   /// Return true if the instruction (or in the case of a bundle,
859   /// the instructions inside the bundle) has the specified property.
860   /// The first argument is the property being queried.
861   /// The second argument indicates whether the query should look inside
862   /// instruction bundles.
863   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
864     assert(MCFlag < 64 &&
865            "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
866     // Inline the fast path for unbundled or bundle-internal instructions.
867     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
868       return getDesc().getFlags() & (1ULL << MCFlag);
869 
870     // If this is the first instruction in a bundle, take the slow path.
871     return hasPropertyInBundle(1ULL << MCFlag, Type);
872   }
873 
874   /// Return true if this is an instruction that should go through the usual
875   /// legalization steps.
876   bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
877     return hasProperty(MCID::PreISelOpcode, Type);
878   }
879 
880   /// Return true if this instruction can have a variable number of operands.
881   /// In this case, the variable operands will be after the normal
882   /// operands but before the implicit definitions and uses (if any are
883   /// present).
884   bool isVariadic(QueryType Type = IgnoreBundle) const {
885     return hasProperty(MCID::Variadic, Type);
886   }
887 
888   /// Set if this instruction has an optional definition, e.g.
889   /// ARM instructions which can set condition code if 's' bit is set.
890   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
891     return hasProperty(MCID::HasOptionalDef, Type);
892   }
893 
894   /// Return true if this is a pseudo instruction that doesn't
895   /// correspond to a real machine instruction.
896   bool isPseudo(QueryType Type = IgnoreBundle) const {
897     return hasProperty(MCID::Pseudo, Type);
898   }
899 
900   /// Return true if this instruction doesn't produce any output in the form of
901   /// executable instructions.
902   bool isMetaInstruction(QueryType Type = IgnoreBundle) const {
903     return hasProperty(MCID::Meta, Type);
904   }
905 
906   bool isReturn(QueryType Type = AnyInBundle) const {
907     return hasProperty(MCID::Return, Type);
908   }
909 
910   /// Return true if this is an instruction that marks the end of an EH scope,
911   /// i.e., a catchpad or a cleanuppad instruction.
912   bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
913     return hasProperty(MCID::EHScopeReturn, Type);
914   }
915 
916   bool isCall(QueryType Type = AnyInBundle) const {
917     return hasProperty(MCID::Call, Type);
918   }
919 
920   /// Return true if this is a call instruction that may have an associated
921   /// call site entry in the debug info.
922   bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
923   /// Return true if copying, moving, or erasing this instruction requires
924   /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
925   /// \ref eraseCallSiteInfo).
926   bool shouldUpdateCallSiteInfo() const;
927 
928   /// Returns true if the specified instruction stops control flow
929   /// from executing the instruction immediately following it.  Examples include
930   /// unconditional branches and return instructions.
931   bool isBarrier(QueryType Type = AnyInBundle) const {
932     return hasProperty(MCID::Barrier, Type);
933   }
934 
935   /// Returns true if this instruction part of the terminator for a basic block.
936   /// Typically this is things like return and branch instructions.
937   ///
938   /// Various passes use this to insert code into the bottom of a basic block,
939   /// but before control flow occurs.
940   bool isTerminator(QueryType Type = AnyInBundle) const {
941     return hasProperty(MCID::Terminator, Type);
942   }
943 
944   /// Returns true if this is a conditional, unconditional, or indirect branch.
945   /// Predicates below can be used to discriminate between
946   /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
947   /// get more information.
948   bool isBranch(QueryType Type = AnyInBundle) const {
949     return hasProperty(MCID::Branch, Type);
950   }
951 
952   /// Return true if this is an indirect branch, such as a
953   /// branch through a register.
954   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
955     return hasProperty(MCID::IndirectBranch, Type);
956   }
957 
958   /// Return true if this is a branch which may fall
959   /// through to the next instruction or may transfer control flow to some other
960   /// block.  The TargetInstrInfo::analyzeBranch method can be used to get more
961   /// information about this branch.
962   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
963     return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
964   }
965 
966   /// Return true if this is a branch which always
967   /// transfers control flow to some other block.  The
968   /// TargetInstrInfo::analyzeBranch method can be used to get more information
969   /// about this branch.
970   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
971     return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
972   }
973 
974   /// Return true if this instruction has a predicate operand that
975   /// controls execution.  It may be set to 'always', or may be set to other
976   /// values.   There are various methods in TargetInstrInfo that can be used to
977   /// control and modify the predicate in this instruction.
978   bool isPredicable(QueryType Type = AllInBundle) const {
979     // If it's a bundle than all bundled instructions must be predicable for this
980     // to return true.
981     return hasProperty(MCID::Predicable, Type);
982   }
983 
984   /// Return true if this instruction is a comparison.
985   bool isCompare(QueryType Type = IgnoreBundle) const {
986     return hasProperty(MCID::Compare, Type);
987   }
988 
989   /// Return true if this instruction is a move immediate
990   /// (including conditional moves) instruction.
991   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
992     return hasProperty(MCID::MoveImm, Type);
993   }
994 
995   /// Return true if this instruction is a register move.
996   /// (including moving values from subreg to reg)
997   bool isMoveReg(QueryType Type = IgnoreBundle) const {
998     return hasProperty(MCID::MoveReg, Type);
999   }
1000 
1001   /// Return true if this instruction is a bitcast instruction.
1002   bool isBitcast(QueryType Type = IgnoreBundle) const {
1003     return hasProperty(MCID::Bitcast, Type);
1004   }
1005 
1006   /// Return true if this instruction is a select instruction.
1007   bool isSelect(QueryType Type = IgnoreBundle) const {
1008     return hasProperty(MCID::Select, Type);
1009   }
1010 
1011   /// Return true if this instruction cannot be safely duplicated.
1012   /// For example, if the instruction has a unique labels attached
1013   /// to it, duplicating it would cause multiple definition errors.
1014   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
1015     if (getPreInstrSymbol() || getPostInstrSymbol())
1016       return true;
1017     return hasProperty(MCID::NotDuplicable, Type);
1018   }
1019 
1020   /// Return true if this instruction is convergent.
1021   /// Convergent instructions can not be made control-dependent on any
1022   /// additional values.
1023   bool isConvergent(QueryType Type = AnyInBundle) const {
1024     if (isInlineAsm()) {
1025       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1026       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1027         return true;
1028     }
1029     if (getFlag(NoConvergent))
1030       return false;
1031     return hasProperty(MCID::Convergent, Type);
1032   }
1033 
1034   /// Returns true if the specified instruction has a delay slot
1035   /// which must be filled by the code generator.
1036   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
1037     return hasProperty(MCID::DelaySlot, Type);
1038   }
1039 
1040   /// Return true for instructions that can be folded as
1041   /// memory operands in other instructions. The most common use for this
1042   /// is instructions that are simple loads from memory that don't modify
1043   /// the loaded value in any way, but it can also be used for instructions
1044   /// that can be expressed as constant-pool loads, such as V_SETALLONES
1045   /// on x86, to allow them to be folded when it is beneficial.
1046   /// This should only be set on instructions that return a value in their
1047   /// only virtual register definition.
1048   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
1049     return hasProperty(MCID::FoldableAsLoad, Type);
1050   }
1051 
1052   /// Return true if this instruction behaves
1053   /// the same way as the generic REG_SEQUENCE instructions.
1054   /// E.g., on ARM,
1055   /// dX VMOVDRR rY, rZ
1056   /// is equivalent to
1057   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
1058   ///
1059   /// Note that for the optimizers to be able to take advantage of
1060   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
1061   /// override accordingly.
1062   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
1063     return hasProperty(MCID::RegSequence, Type);
1064   }
1065 
1066   /// Return true if this instruction behaves
1067   /// the same way as the generic EXTRACT_SUBREG instructions.
1068   /// E.g., on ARM,
1069   /// rX, rY VMOVRRD dZ
1070   /// is equivalent to two EXTRACT_SUBREG:
1071   /// rX = EXTRACT_SUBREG dZ, ssub_0
1072   /// rY = EXTRACT_SUBREG dZ, ssub_1
1073   ///
1074   /// Note that for the optimizers to be able to take advantage of
1075   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
1076   /// override accordingly.
1077   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
1078     return hasProperty(MCID::ExtractSubreg, Type);
1079   }
1080 
1081   /// Return true if this instruction behaves
1082   /// the same way as the generic INSERT_SUBREG instructions.
1083   /// E.g., on ARM,
1084   /// dX = VSETLNi32 dY, rZ, Imm
1085   /// is equivalent to a INSERT_SUBREG:
1086   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
1087   ///
1088   /// Note that for the optimizers to be able to take advantage of
1089   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
1090   /// override accordingly.
1091   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
1092     return hasProperty(MCID::InsertSubreg, Type);
1093   }
1094 
1095   //===--------------------------------------------------------------------===//
1096   // Side Effect Analysis
1097   //===--------------------------------------------------------------------===//
1098 
1099   /// Return true if this instruction could possibly read memory.
1100   /// Instructions with this flag set are not necessarily simple load
1101   /// instructions, they may load a value and modify it, for example.
1102   bool mayLoad(QueryType Type = AnyInBundle) const {
1103     if (isInlineAsm()) {
1104       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1105       if (ExtraInfo & InlineAsm::Extra_MayLoad)
1106         return true;
1107     }
1108     return hasProperty(MCID::MayLoad, Type);
1109   }
1110 
1111   /// Return true if this instruction could possibly modify memory.
1112   /// Instructions with this flag set are not necessarily simple store
1113   /// instructions, they may store a modified value based on their operands, or
1114   /// may not actually modify anything, for example.
1115   bool mayStore(QueryType Type = AnyInBundle) const {
1116     if (isInlineAsm()) {
1117       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1118       if (ExtraInfo & InlineAsm::Extra_MayStore)
1119         return true;
1120     }
1121     return hasProperty(MCID::MayStore, Type);
1122   }
1123 
1124   /// Return true if this instruction could possibly read or modify memory.
1125   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
1126     return mayLoad(Type) || mayStore(Type);
1127   }
1128 
1129   /// Return true if this instruction could possibly raise a floating-point
1130   /// exception.  This is the case if the instruction is a floating-point
1131   /// instruction that can in principle raise an exception, as indicated
1132   /// by the MCID::MayRaiseFPException property, *and* at the same time,
1133   /// the instruction is used in a context where we expect floating-point
1134   /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
1135   bool mayRaiseFPException() const {
1136     return hasProperty(MCID::MayRaiseFPException) &&
1137            !getFlag(MachineInstr::MIFlag::NoFPExcept);
1138   }
1139 
1140   //===--------------------------------------------------------------------===//
1141   // Flags that indicate whether an instruction can be modified by a method.
1142   //===--------------------------------------------------------------------===//
1143 
1144   /// Return true if this may be a 2- or 3-address
1145   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
1146   /// result if Y and Z are exchanged.  If this flag is set, then the
1147   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
1148   /// instruction.
1149   ///
1150   /// Note that this flag may be set on instructions that are only commutable
1151   /// sometimes.  In these cases, the call to commuteInstruction will fail.
1152   /// Also note that some instructions require non-trivial modification to
1153   /// commute them.
1154   bool isCommutable(QueryType Type = IgnoreBundle) const {
1155     return hasProperty(MCID::Commutable, Type);
1156   }
1157 
1158   /// Return true if this is a 2-address instruction
1159   /// which can be changed into a 3-address instruction if needed.  Doing this
1160   /// transformation can be profitable in the register allocator, because it
1161   /// means that the instruction can use a 2-address form if possible, but
1162   /// degrade into a less efficient form if the source and dest register cannot
1163   /// be assigned to the same register.  For example, this allows the x86
1164   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
1165   /// is the same speed as the shift but has bigger code size.
1166   ///
1167   /// If this returns true, then the target must implement the
1168   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
1169   /// is allowed to fail if the transformation isn't valid for this specific
1170   /// instruction (e.g. shl reg, 4 on x86).
1171   ///
1172   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
1173     return hasProperty(MCID::ConvertibleTo3Addr, Type);
1174   }
1175 
1176   /// Return true if this instruction requires
1177   /// custom insertion support when the DAG scheduler is inserting it into a
1178   /// machine basic block.  If this is true for the instruction, it basically
1179   /// means that it is a pseudo instruction used at SelectionDAG time that is
1180   /// expanded out into magic code by the target when MachineInstrs are formed.
1181   ///
1182   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
1183   /// is used to insert this into the MachineBasicBlock.
1184   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
1185     return hasProperty(MCID::UsesCustomInserter, Type);
1186   }
1187 
1188   /// Return true if this instruction requires *adjustment*
1189   /// after instruction selection by calling a target hook. For example, this
1190   /// can be used to fill in ARM 's' optional operand depending on whether
1191   /// the conditional flag register is used.
1192   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
1193     return hasProperty(MCID::HasPostISelHook, Type);
1194   }
1195 
1196   /// Returns true if this instruction is a candidate for remat.
1197   /// This flag is deprecated, please don't use it anymore.  If this
1198   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
1199   /// verify the instruction is really rematerializable.
1200   bool isRematerializable(QueryType Type = AllInBundle) const {
1201     // It's only possible to re-mat a bundle if all bundled instructions are
1202     // re-materializable.
1203     return hasProperty(MCID::Rematerializable, Type);
1204   }
1205 
1206   /// Returns true if this instruction has the same cost (or less) than a move
1207   /// instruction. This is useful during certain types of optimizations
1208   /// (e.g., remat during two-address conversion or machine licm)
1209   /// where we would like to remat or hoist the instruction, but not if it costs
1210   /// more than moving the instruction into the appropriate register. Note, we
1211   /// are not marking copies from and to the same register class with this flag.
1212   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
1213     // Only returns true for a bundle if all bundled instructions are cheap.
1214     return hasProperty(MCID::CheapAsAMove, Type);
1215   }
1216 
1217   /// Returns true if this instruction source operands
1218   /// have special register allocation requirements that are not captured by the
1219   /// operand register classes. e.g. ARM::STRD's two source registers must be an
1220   /// even / odd pair, ARM::STM registers have to be in ascending order.
1221   /// Post-register allocation passes should not attempt to change allocations
1222   /// for sources of instructions with this flag.
1223   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
1224     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
1225   }
1226 
1227   /// Returns true if this instruction def operands
1228   /// have special register allocation requirements that are not captured by the
1229   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
1230   /// even / odd pair, ARM::LDM registers have to be in ascending order.
1231   /// Post-register allocation passes should not attempt to change allocations
1232   /// for definitions of instructions with this flag.
1233   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1234     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1235   }
1236 
1237   enum MICheckType {
1238     CheckDefs,      // Check all operands for equality
1239     CheckKillDead,  // Check all operands including kill / dead markers
1240     IgnoreDefs,     // Ignore all definitions
1241     IgnoreVRegDefs  // Ignore virtual register definitions
1242   };
1243 
1244   /// Return true if this instruction is identical to \p Other.
1245   /// Two instructions are identical if they have the same opcode and all their
1246   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1247   /// Note that this means liveness related flags (dead, undef, kill) do not
1248   /// affect the notion of identical.
1249   bool isIdenticalTo(const MachineInstr &Other,
1250                      MICheckType Check = CheckDefs) const;
1251 
1252   /// Returns true if this instruction is a debug instruction that represents an
1253   /// identical debug value to \p Other.
1254   /// This function considers these debug instructions equivalent if they have
1255   /// identical variables, debug locations, and debug operands, and if the
1256   /// DIExpressions combined with the directness flags are equivalent.
1257   bool isEquivalentDbgInstr(const MachineInstr &Other) const;
1258 
1259   /// Unlink 'this' from the containing basic block, and return it without
1260   /// deleting it.
1261   ///
1262   /// This function can not be used on bundled instructions, use
1263   /// removeFromBundle() to remove individual instructions from a bundle.
1264   MachineInstr *removeFromParent();
1265 
1266   /// Unlink this instruction from its basic block and return it without
1267   /// deleting it.
1268   ///
1269   /// If the instruction is part of a bundle, the other instructions in the
1270   /// bundle remain bundled.
1271   MachineInstr *removeFromBundle();
1272 
1273   /// Unlink 'this' from the containing basic block and delete it.
1274   ///
1275   /// If this instruction is the header of a bundle, the whole bundle is erased.
1276   /// This function can not be used for instructions inside a bundle, use
1277   /// eraseFromBundle() to erase individual bundled instructions.
1278   void eraseFromParent();
1279 
1280   /// Unlink 'this' from its basic block and delete it.
1281   ///
1282   /// If the instruction is part of a bundle, the other instructions in the
1283   /// bundle remain bundled.
1284   void eraseFromBundle();
1285 
1286   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1287   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1288   bool isAnnotationLabel() const {
1289     return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1290   }
1291 
1292   /// Returns true if the MachineInstr represents a label.
1293   bool isLabel() const {
1294     return isEHLabel() || isGCLabel() || isAnnotationLabel();
1295   }
1296 
1297   bool isCFIInstruction() const {
1298     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1299   }
1300 
1301   bool isPseudoProbe() const {
1302     return getOpcode() == TargetOpcode::PSEUDO_PROBE;
1303   }
1304 
1305   // True if the instruction represents a position in the function.
1306   bool isPosition() const { return isLabel() || isCFIInstruction(); }
1307 
1308   bool isNonListDebugValue() const {
1309     return getOpcode() == TargetOpcode::DBG_VALUE;
1310   }
1311   bool isDebugValueList() const {
1312     return getOpcode() == TargetOpcode::DBG_VALUE_LIST;
1313   }
1314   bool isDebugValue() const {
1315     return isNonListDebugValue() || isDebugValueList();
1316   }
1317   bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1318   bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; }
1319   bool isDebugValueLike() const { return isDebugValue() || isDebugRef(); }
1320   bool isDebugPHI() const { return getOpcode() == TargetOpcode::DBG_PHI; }
1321   bool isDebugInstr() const {
1322     return isDebugValue() || isDebugLabel() || isDebugRef() || isDebugPHI();
1323   }
1324   bool isDebugOrPseudoInstr() const {
1325     return isDebugInstr() || isPseudoProbe();
1326   }
1327 
1328   bool isDebugOffsetImm() const {
1329     return isNonListDebugValue() && getDebugOffset().isImm();
1330   }
1331 
1332   /// A DBG_VALUE is indirect iff the location operand is a register and
1333   /// the offset operand is an immediate.
1334   bool isIndirectDebugValue() const {
1335     return isDebugOffsetImm() && getDebugOperand(0).isReg();
1336   }
1337 
1338   /// A DBG_VALUE is an entry value iff its debug expression contains the
1339   /// DW_OP_LLVM_entry_value operation.
1340   bool isDebugEntryValue() const;
1341 
1342   /// Return true if the instruction is a debug value which describes a part of
1343   /// a variable as unavailable.
1344   bool isUndefDebugValue() const {
1345     if (!isDebugValue())
1346       return false;
1347     // If any $noreg locations are given, this DV is undef.
1348     for (const MachineOperand &Op : debug_operands())
1349       if (Op.isReg() && !Op.getReg().isValid())
1350         return true;
1351     return false;
1352   }
1353 
1354   bool isJumpTableDebugInfo() const {
1355     return getOpcode() == TargetOpcode::JUMP_TABLE_DEBUG_INFO;
1356   }
1357 
1358   bool isPHI() const {
1359     return getOpcode() == TargetOpcode::PHI ||
1360            getOpcode() == TargetOpcode::G_PHI;
1361   }
1362   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1363   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1364   bool isInlineAsm() const {
1365     return getOpcode() == TargetOpcode::INLINEASM ||
1366            getOpcode() == TargetOpcode::INLINEASM_BR;
1367   }
1368   /// Returns true if the register operand can be folded with a load or store
1369   /// into a frame index. Does so by checking the InlineAsm::Flag immediate
1370   /// operand at OpId - 1.
1371   bool mayFoldInlineAsmRegOp(unsigned OpId) const;
1372 
1373   bool isStackAligningInlineAsm() const;
1374   InlineAsm::AsmDialect getInlineAsmDialect() const;
1375 
1376   bool isInsertSubreg() const {
1377     return getOpcode() == TargetOpcode::INSERT_SUBREG;
1378   }
1379 
1380   bool isSubregToReg() const {
1381     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1382   }
1383 
1384   bool isRegSequence() const {
1385     return getOpcode() == TargetOpcode::REG_SEQUENCE;
1386   }
1387 
1388   bool isBundle() const {
1389     return getOpcode() == TargetOpcode::BUNDLE;
1390   }
1391 
1392   bool isCopy() const {
1393     return getOpcode() == TargetOpcode::COPY;
1394   }
1395 
1396   bool isFullCopy() const {
1397     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1398   }
1399 
1400   bool isExtractSubreg() const {
1401     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1402   }
1403 
1404   /// Return true if the instruction behaves like a copy.
1405   /// This does not include native copy instructions.
1406   bool isCopyLike() const {
1407     return isCopy() || isSubregToReg();
1408   }
1409 
1410   /// Return true is the instruction is an identity copy.
1411   bool isIdentityCopy() const {
1412     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1413       getOperand(0).getSubReg() == getOperand(1).getSubReg();
1414   }
1415 
1416   /// Return true if this is a transient instruction that is either very likely
1417   /// to be eliminated during register allocation (such as copy-like
1418   /// instructions), or if this instruction doesn't have an execution-time cost.
1419   bool isTransient() const {
1420     switch (getOpcode()) {
1421     default:
1422       return isMetaInstruction();
1423     // Copy-like instructions are usually eliminated during register allocation.
1424     case TargetOpcode::PHI:
1425     case TargetOpcode::G_PHI:
1426     case TargetOpcode::COPY:
1427     case TargetOpcode::INSERT_SUBREG:
1428     case TargetOpcode::SUBREG_TO_REG:
1429     case TargetOpcode::REG_SEQUENCE:
1430       return true;
1431     }
1432   }
1433 
1434   /// Return the number of instructions inside the MI bundle, excluding the
1435   /// bundle header.
1436   ///
1437   /// This is the number of instructions that MachineBasicBlock::iterator
1438   /// skips, 0 for unbundled instructions.
1439   unsigned getBundleSize() const;
1440 
1441   /// Return true if the MachineInstr reads the specified register.
1442   /// If TargetRegisterInfo is non-null, then it also checks if there
1443   /// is a read of a super-register.
1444   /// This does not count partial redefines of virtual registers as reads:
1445   ///   %reg1024:6 = OP.
1446   bool readsRegister(Register Reg,
1447                      const TargetRegisterInfo *TRI = nullptr) const {
1448     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1449   }
1450 
1451   /// Return true if the MachineInstr reads the specified virtual register.
1452   /// Take into account that a partial define is a
1453   /// read-modify-write operation.
1454   bool readsVirtualRegister(Register Reg) const {
1455     return readsWritesVirtualRegister(Reg).first;
1456   }
1457 
1458   /// Return a pair of bools (reads, writes) indicating if this instruction
1459   /// reads or writes Reg. This also considers partial defines.
1460   /// If Ops is not null, all operand indices for Reg are added.
1461   std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1462                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1463 
1464   /// Return true if the MachineInstr kills the specified register.
1465   /// If TargetRegisterInfo is non-null, then it also checks if there is
1466   /// a kill of a super-register.
1467   bool killsRegister(Register Reg,
1468                      const TargetRegisterInfo *TRI = nullptr) const {
1469     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1470   }
1471 
1472   /// Return true if the MachineInstr fully defines the specified register.
1473   /// If TargetRegisterInfo is non-null, then it also checks
1474   /// if there is a def of a super-register.
1475   /// NOTE: It's ignoring subreg indices on virtual registers.
1476   bool definesRegister(Register Reg,
1477                        const TargetRegisterInfo *TRI = nullptr) const {
1478     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1479   }
1480 
1481   /// Return true if the MachineInstr modifies (fully define or partially
1482   /// define) the specified register.
1483   /// NOTE: It's ignoring subreg indices on virtual registers.
1484   bool modifiesRegister(Register Reg,
1485                         const TargetRegisterInfo *TRI = nullptr) const {
1486     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1487   }
1488 
1489   /// Returns true if the register is dead in this machine instruction.
1490   /// If TargetRegisterInfo is non-null, then it also checks
1491   /// if there is a dead def of a super-register.
1492   bool registerDefIsDead(Register Reg,
1493                          const TargetRegisterInfo *TRI = nullptr) const {
1494     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1495   }
1496 
1497   /// Returns true if the MachineInstr has an implicit-use operand of exactly
1498   /// the given register (not considering sub/super-registers).
1499   bool hasRegisterImplicitUseOperand(Register Reg) const;
1500 
1501   /// Returns the operand index that is a use of the specific register or -1
1502   /// if it is not found. It further tightens the search criteria to a use
1503   /// that kills the register if isKill is true.
1504   int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1505                                 const TargetRegisterInfo *TRI = nullptr) const;
1506 
1507   /// Wrapper for findRegisterUseOperandIdx, it returns
1508   /// a pointer to the MachineOperand rather than an index.
1509   MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1510                                       const TargetRegisterInfo *TRI = nullptr) {
1511     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1512     return (Idx == -1) ? nullptr : &getOperand(Idx);
1513   }
1514 
1515   const MachineOperand *findRegisterUseOperand(
1516     Register Reg, bool isKill = false,
1517     const TargetRegisterInfo *TRI = nullptr) const {
1518     return const_cast<MachineInstr *>(this)->
1519       findRegisterUseOperand(Reg, isKill, TRI);
1520   }
1521 
1522   /// Returns the operand index that is a def of the specified register or
1523   /// -1 if it is not found. If isDead is true, defs that are not dead are
1524   /// skipped. If Overlap is true, then it also looks for defs that merely
1525   /// overlap the specified register. If TargetRegisterInfo is non-null,
1526   /// then it also checks if there is a def of a super-register.
1527   /// This may also return a register mask operand when Overlap is true.
1528   int findRegisterDefOperandIdx(Register Reg,
1529                                 bool isDead = false, bool Overlap = false,
1530                                 const TargetRegisterInfo *TRI = nullptr) const;
1531 
1532   /// Wrapper for findRegisterDefOperandIdx, it returns
1533   /// a pointer to the MachineOperand rather than an index.
1534   MachineOperand *
1535   findRegisterDefOperand(Register Reg, bool isDead = false,
1536                          bool Overlap = false,
1537                          const TargetRegisterInfo *TRI = nullptr) {
1538     int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1539     return (Idx == -1) ? nullptr : &getOperand(Idx);
1540   }
1541 
1542   const MachineOperand *
1543   findRegisterDefOperand(Register Reg, bool isDead = false,
1544                          bool Overlap = false,
1545                          const TargetRegisterInfo *TRI = nullptr) const {
1546     return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1547         Reg, isDead, Overlap, TRI);
1548   }
1549 
1550   /// Find the index of the first operand in the
1551   /// operand list that is used to represent the predicate. It returns -1 if
1552   /// none is found.
1553   int findFirstPredOperandIdx() const;
1554 
1555   /// Find the index of the flag word operand that
1556   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
1557   /// getOperand(OpIdx) does not belong to an inline asm operand group.
1558   ///
1559   /// If GroupNo is not NULL, it will receive the number of the operand group
1560   /// containing OpIdx.
1561   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1562 
1563   /// Compute the static register class constraint for operand OpIdx.
1564   /// For normal instructions, this is derived from the MCInstrDesc.
1565   /// For inline assembly it is derived from the flag words.
1566   ///
1567   /// Returns NULL if the static register class constraint cannot be
1568   /// determined.
1569   const TargetRegisterClass*
1570   getRegClassConstraint(unsigned OpIdx,
1571                         const TargetInstrInfo *TII,
1572                         const TargetRegisterInfo *TRI) const;
1573 
1574   /// Applies the constraints (def/use) implied by this MI on \p Reg to
1575   /// the given \p CurRC.
1576   /// If \p ExploreBundle is set and MI is part of a bundle, all the
1577   /// instructions inside the bundle will be taken into account. In other words,
1578   /// this method accumulates all the constraints of the operand of this MI and
1579   /// the related bundle if MI is a bundle or inside a bundle.
1580   ///
1581   /// Returns the register class that satisfies both \p CurRC and the
1582   /// constraints set by MI. Returns NULL if such a register class does not
1583   /// exist.
1584   ///
1585   /// \pre CurRC must not be NULL.
1586   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1587       Register Reg, const TargetRegisterClass *CurRC,
1588       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1589       bool ExploreBundle = false) const;
1590 
1591   /// Applies the constraints (def/use) implied by the \p OpIdx operand
1592   /// to the given \p CurRC.
1593   ///
1594   /// Returns the register class that satisfies both \p CurRC and the
1595   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1596   /// does not exist.
1597   ///
1598   /// \pre CurRC must not be NULL.
1599   /// \pre The operand at \p OpIdx must be a register.
1600   const TargetRegisterClass *
1601   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1602                               const TargetInstrInfo *TII,
1603                               const TargetRegisterInfo *TRI) const;
1604 
1605   /// Add a tie between the register operands at DefIdx and UseIdx.
1606   /// The tie will cause the register allocator to ensure that the two
1607   /// operands are assigned the same physical register.
1608   ///
1609   /// Tied operands are managed automatically for explicit operands in the
1610   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1611   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1612 
1613   /// Given the index of a tied register operand, find the
1614   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1615   /// index of the tied operand which must exist.
1616   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1617 
1618   /// Given the index of a register def operand,
1619   /// check if the register def is tied to a source operand, due to either
1620   /// two-address elimination or inline assembly constraints. Returns the
1621   /// first tied use operand index by reference if UseOpIdx is not null.
1622   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1623                              unsigned *UseOpIdx = nullptr) const {
1624     const MachineOperand &MO = getOperand(DefOpIdx);
1625     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1626       return false;
1627     if (UseOpIdx)
1628       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1629     return true;
1630   }
1631 
1632   /// Return true if the use operand of the specified index is tied to a def
1633   /// operand. It also returns the def operand index by reference if DefOpIdx
1634   /// is not null.
1635   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1636                              unsigned *DefOpIdx = nullptr) const {
1637     const MachineOperand &MO = getOperand(UseOpIdx);
1638     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1639       return false;
1640     if (DefOpIdx)
1641       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1642     return true;
1643   }
1644 
1645   /// Clears kill flags on all operands.
1646   void clearKillInfo();
1647 
1648   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1649   /// properly composing subreg indices where necessary.
1650   void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1651                           const TargetRegisterInfo &RegInfo);
1652 
1653   /// We have determined MI kills a register. Look for the
1654   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1655   /// add a implicit operand if it's not found. Returns true if the operand
1656   /// exists / is added.
1657   bool addRegisterKilled(Register IncomingReg,
1658                          const TargetRegisterInfo *RegInfo,
1659                          bool AddIfNotFound = false);
1660 
1661   /// Clear all kill flags affecting Reg.  If RegInfo is provided, this includes
1662   /// all aliasing registers.
1663   void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1664 
1665   /// We have determined MI defined a register without a use.
1666   /// Look for the operand that defines it and mark it as IsDead. If
1667   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1668   /// true if the operand exists / is added.
1669   bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1670                        bool AddIfNotFound = false);
1671 
1672   /// Clear all dead flags on operands defining register @p Reg.
1673   void clearRegisterDeads(Register Reg);
1674 
1675   /// Mark all subregister defs of register @p Reg with the undef flag.
1676   /// This function is used when we determined to have a subregister def in an
1677   /// otherwise undefined super register.
1678   void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1679 
1680   /// We have determined MI defines a register. Make sure there is an operand
1681   /// defining Reg.
1682   void addRegisterDefined(Register Reg,
1683                           const TargetRegisterInfo *RegInfo = nullptr);
1684 
1685   /// Mark every physreg used by this instruction as
1686   /// dead except those in the UsedRegs list.
1687   ///
1688   /// On instructions with register mask operands, also add implicit-def
1689   /// operands for all registers in UsedRegs.
1690   void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1691                              const TargetRegisterInfo &TRI);
1692 
1693   /// Return true if it is safe to move this instruction. If
1694   /// SawStore is set to true, it means that there is a store (or call) between
1695   /// the instruction's location and its intended destination.
1696   bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1697 
1698   /// Returns true if this instruction's memory access aliases the memory
1699   /// access of Other.
1700   //
1701   /// Assumes any physical registers used to compute addresses
1702   /// have the same value for both instructions.  Returns false if neither
1703   /// instruction writes to memory.
1704   ///
1705   /// @param AA Optional alias analysis, used to compare memory operands.
1706   /// @param Other MachineInstr to check aliasing against.
1707   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1708   bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1709 
1710   /// Return true if this instruction may have an ordered
1711   /// or volatile memory reference, or if the information describing the memory
1712   /// reference is not available. Return false if it is known to have no
1713   /// ordered or volatile memory references.
1714   bool hasOrderedMemoryRef() const;
1715 
1716   /// Return true if this load instruction never traps and points to a memory
1717   /// location whose value doesn't change during the execution of this function.
1718   ///
1719   /// Examples include loading a value from the constant pool or from the
1720   /// argument area of a function (if it does not change).  If the instruction
1721   /// does multiple loads, this returns true only if all of the loads are
1722   /// dereferenceable and invariant.
1723   bool isDereferenceableInvariantLoad() const;
1724 
1725   /// If the specified instruction is a PHI that always merges together the
1726   /// same virtual register, return the register, otherwise return 0.
1727   unsigned isConstantValuePHI() const;
1728 
1729   /// Return true if this instruction has side effects that are not modeled
1730   /// by mayLoad / mayStore, etc.
1731   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1732   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1733   /// INLINEASM instruction, in which case the side effect property is encoded
1734   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1735   ///
1736   bool hasUnmodeledSideEffects() const;
1737 
1738   /// Returns true if it is illegal to fold a load across this instruction.
1739   bool isLoadFoldBarrier() const;
1740 
1741   /// Return true if all the defs of this instruction are dead.
1742   bool allDefsAreDead() const;
1743 
1744   /// Return true if all the implicit defs of this instruction are dead.
1745   bool allImplicitDefsAreDead() const;
1746 
1747   /// Return a valid size if the instruction is a spill instruction.
1748   std::optional<LocationSize> getSpillSize(const TargetInstrInfo *TII) const;
1749 
1750   /// Return a valid size if the instruction is a folded spill instruction.
1751   std::optional<LocationSize>
1752   getFoldedSpillSize(const TargetInstrInfo *TII) const;
1753 
1754   /// Return a valid size if the instruction is a restore instruction.
1755   std::optional<LocationSize> getRestoreSize(const TargetInstrInfo *TII) const;
1756 
1757   /// Return a valid size if the instruction is a folded restore instruction.
1758   std::optional<LocationSize>
1759   getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1760 
1761   /// Copy implicit register operands from specified
1762   /// instruction to this instruction.
1763   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1764 
1765   /// Debugging support
1766   /// @{
1767   /// Determine the generic type to be printed (if needed) on uses and defs.
1768   LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1769                      const MachineRegisterInfo &MRI) const;
1770 
1771   /// Return true when an instruction has tied register that can't be determined
1772   /// by the instruction's descriptor. This is useful for MIR printing, to
1773   /// determine whether we need to print the ties or not.
1774   bool hasComplexRegisterTies() const;
1775 
1776   /// Print this MI to \p OS.
1777   /// Don't print information that can be inferred from other instructions if
1778   /// \p IsStandalone is false. It is usually true when only a fragment of the
1779   /// function is printed.
1780   /// Only print the defs and the opcode if \p SkipOpers is true.
1781   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1782   /// Otherwise, also print the debug loc, with a terminating newline.
1783   /// \p TII is used to print the opcode name.  If it's not present, but the
1784   /// MI is in a function, the opcode will be printed using the function's TII.
1785   void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1786              bool SkipDebugLoc = false, bool AddNewLine = true,
1787              const TargetInstrInfo *TII = nullptr) const;
1788   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1789              bool SkipOpers = false, bool SkipDebugLoc = false,
1790              bool AddNewLine = true,
1791              const TargetInstrInfo *TII = nullptr) const;
1792   void dump() const;
1793   /// Print on dbgs() the current instruction and the instructions defining its
1794   /// operands and so on until we reach \p MaxDepth.
1795   void dumpr(const MachineRegisterInfo &MRI,
1796              unsigned MaxDepth = UINT_MAX) const;
1797   /// @}
1798 
1799   //===--------------------------------------------------------------------===//
1800   // Accessors used to build up machine instructions.
1801 
1802   /// Add the specified operand to the instruction.  If it is an implicit
1803   /// operand, it is added to the end of the operand list.  If it is an
1804   /// explicit operand it is added at the end of the explicit operand list
1805   /// (before the first implicit operand).
1806   ///
1807   /// MF must be the machine function that was used to allocate this
1808   /// instruction.
1809   ///
1810   /// MachineInstrBuilder provides a more convenient interface for creating
1811   /// instructions and adding operands.
1812   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1813 
1814   /// Add an operand without providing an MF reference. This only works for
1815   /// instructions that are inserted in a basic block.
1816   ///
1817   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1818   /// preferred.
1819   void addOperand(const MachineOperand &Op);
1820 
1821   /// Inserts Ops BEFORE It. Can untie/retie tied operands.
1822   void insert(mop_iterator InsertBefore, ArrayRef<MachineOperand> Ops);
1823 
1824   /// Replace the instruction descriptor (thus opcode) of
1825   /// the current instruction with a new one.
1826   void setDesc(const MCInstrDesc &TID);
1827 
1828   /// Replace current source information with new such.
1829   /// Avoid using this, the constructor argument is preferable.
1830   void setDebugLoc(DebugLoc DL) {
1831     DbgLoc = std::move(DL);
1832     assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
1833   }
1834 
1835   /// Erase an operand from an instruction, leaving it with one
1836   /// fewer operand than it started with.
1837   void removeOperand(unsigned OpNo);
1838 
1839   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1840   /// the memrefs to their most conservative state.  This should be used only
1841   /// as a last resort since it greatly pessimizes our knowledge of the memory
1842   /// access performed by the instruction.
1843   void dropMemRefs(MachineFunction &MF);
1844 
1845   /// Assign this MachineInstr's memory reference descriptor list.
1846   ///
1847   /// Unlike other methods, this *will* allocate them into a new array
1848   /// associated with the provided `MachineFunction`.
1849   void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1850 
1851   /// Add a MachineMemOperand to the machine instruction.
1852   /// This function should be used only occasionally. The setMemRefs function
1853   /// is the primary method for setting up a MachineInstr's MemRefs list.
1854   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1855 
1856   /// Clone another MachineInstr's memory reference descriptor list and replace
1857   /// ours with it.
1858   ///
1859   /// Note that `*this` may be the incoming MI!
1860   ///
1861   /// Prefer this API whenever possible as it can avoid allocations in common
1862   /// cases.
1863   void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1864 
1865   /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1866   /// list and replace ours with it.
1867   ///
1868   /// Note that `*this` may be one of the incoming MIs!
1869   ///
1870   /// Prefer this API whenever possible as it can avoid allocations in common
1871   /// cases.
1872   void cloneMergedMemRefs(MachineFunction &MF,
1873                           ArrayRef<const MachineInstr *> MIs);
1874 
1875   /// Set a symbol that will be emitted just prior to the instruction itself.
1876   ///
1877   /// Setting this to a null pointer will remove any such symbol.
1878   ///
1879   /// FIXME: This is not fully implemented yet.
1880   void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1881 
1882   /// Set a symbol that will be emitted just after the instruction itself.
1883   ///
1884   /// Setting this to a null pointer will remove any such symbol.
1885   ///
1886   /// FIXME: This is not fully implemented yet.
1887   void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1888 
1889   /// Clone another MachineInstr's pre- and post- instruction symbols and
1890   /// replace ours with it.
1891   void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1892 
1893   /// Set a marker on instructions that denotes where we should create and emit
1894   /// heap alloc site labels. This waits until after instruction selection and
1895   /// optimizations to create the label, so it should still work if the
1896   /// instruction is removed or duplicated.
1897   void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1898 
1899   // Set metadata on instructions that say which sections to emit instruction
1900   // addresses into.
1901   void setPCSections(MachineFunction &MF, MDNode *MD);
1902 
1903   /// Set the CFI type for the instruction.
1904   void setCFIType(MachineFunction &MF, uint32_t Type);
1905 
1906   /// Return the MIFlags which represent both MachineInstrs. This
1907   /// should be used when merging two MachineInstrs into one. This routine does
1908   /// not modify the MIFlags of this MachineInstr.
1909   uint32_t mergeFlagsWith(const MachineInstr& Other) const;
1910 
1911   static uint32_t copyFlagsFromInstruction(const Instruction &I);
1912 
1913   /// Copy all flags to MachineInst MIFlags
1914   void copyIRFlags(const Instruction &I);
1915 
1916   /// Break any tie involving OpIdx.
1917   void untieRegOperand(unsigned OpIdx) {
1918     MachineOperand &MO = getOperand(OpIdx);
1919     if (MO.isReg() && MO.isTied()) {
1920       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1921       MO.TiedTo = 0;
1922     }
1923   }
1924 
1925   /// Add all implicit def and use operands to this instruction.
1926   void addImplicitDefUseOperands(MachineFunction &MF);
1927 
1928   /// Scan instructions immediately following MI and collect any matching
1929   /// DBG_VALUEs.
1930   void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1931 
1932   /// Find all DBG_VALUEs that point to the register def in this instruction
1933   /// and point them to \p Reg instead.
1934   void changeDebugValuesDefReg(Register Reg);
1935 
1936   /// Sets all register debug operands in this debug value instruction to be
1937   /// undef.
1938   void setDebugValueUndef() {
1939     assert(isDebugValue() && "Must be a debug value instruction.");
1940     for (MachineOperand &MO : debug_operands()) {
1941       if (MO.isReg()) {
1942         MO.setReg(0);
1943         MO.setSubReg(0);
1944       }
1945     }
1946   }
1947 
1948   std::tuple<Register, Register> getFirst2Regs() const {
1949     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg());
1950   }
1951 
1952   std::tuple<Register, Register, Register> getFirst3Regs() const {
1953     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
1954                       getOperand(2).getReg());
1955   }
1956 
1957   std::tuple<Register, Register, Register, Register> getFirst4Regs() const {
1958     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
1959                       getOperand(2).getReg(), getOperand(3).getReg());
1960   }
1961 
1962   std::tuple<Register, Register, Register, Register, Register>
1963   getFirst5Regs() const {
1964     return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(),
1965                       getOperand(2).getReg(), getOperand(3).getReg(),
1966                       getOperand(4).getReg());
1967   }
1968 
1969   std::tuple<LLT, LLT> getFirst2LLTs() const;
1970   std::tuple<LLT, LLT, LLT> getFirst3LLTs() const;
1971   std::tuple<LLT, LLT, LLT, LLT> getFirst4LLTs() const;
1972   std::tuple<LLT, LLT, LLT, LLT, LLT> getFirst5LLTs() const;
1973 
1974   std::tuple<Register, LLT, Register, LLT> getFirst2RegLLTs() const;
1975   std::tuple<Register, LLT, Register, LLT, Register, LLT>
1976   getFirst3RegLLTs() const;
1977   std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT>
1978   getFirst4RegLLTs() const;
1979   std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT,
1980              Register, LLT>
1981   getFirst5RegLLTs() const;
1982 
1983 private:
1984   /// If this instruction is embedded into a MachineFunction, return the
1985   /// MachineRegisterInfo object for the current function, otherwise
1986   /// return null.
1987   MachineRegisterInfo *getRegInfo();
1988   const MachineRegisterInfo *getRegInfo() const;
1989 
1990   /// Unlink all of the register operands in this instruction from their
1991   /// respective use lists.  This requires that the operands already be on their
1992   /// use lists.
1993   void removeRegOperandsFromUseLists(MachineRegisterInfo&);
1994 
1995   /// Add all of the register operands in this instruction from their
1996   /// respective use lists.  This requires that the operands not be on their
1997   /// use lists yet.
1998   void addRegOperandsToUseLists(MachineRegisterInfo&);
1999 
2000   /// Slow path for hasProperty when we're dealing with a bundle.
2001   bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
2002 
2003   /// Implements the logic of getRegClassConstraintEffectForVReg for the
2004   /// this MI and the given operand index \p OpIdx.
2005   /// If the related operand does not constrained Reg, this returns CurRC.
2006   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
2007       unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
2008       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
2009 
2010   /// Stores extra instruction information inline or allocates as ExtraInfo
2011   /// based on the number of pointers.
2012   void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
2013                     MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
2014                     MDNode *HeapAllocMarker, MDNode *PCSections,
2015                     uint32_t CFIType);
2016 };
2017 
2018 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
2019 /// instruction rather than by pointer value.
2020 /// The hashing and equality testing functions ignore definitions so this is
2021 /// useful for CSE, etc.
2022 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
2023   static inline MachineInstr *getEmptyKey() {
2024     return nullptr;
2025   }
2026 
2027   static inline MachineInstr *getTombstoneKey() {
2028     return reinterpret_cast<MachineInstr*>(-1);
2029   }
2030 
2031   static unsigned getHashValue(const MachineInstr* const &MI);
2032 
2033   static bool isEqual(const MachineInstr* const &LHS,
2034                       const MachineInstr* const &RHS) {
2035     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
2036         LHS == getEmptyKey() || LHS == getTombstoneKey())
2037       return LHS == RHS;
2038     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
2039   }
2040 };
2041 
2042 //===----------------------------------------------------------------------===//
2043 // Debugging Support
2044 
2045 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
2046   MI.print(OS);
2047   return OS;
2048 }
2049 
2050 } // end namespace llvm
2051 
2052 #endif // LLVM_CODEGEN_MACHINEINSTR_H
2053