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