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