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