1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the MachineInstr class, which is the
11 // basic representation for all target dependent machine instructions used by
12 // the back end.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
17 #define LLVM_CODEGEN_MACHINEINSTR_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/CodeGen/MachineOperand.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/Support/ArrayRecycler.h"
32 #include "llvm/Target/TargetOpcodes.h"
33 
34 namespace llvm {
35 
36 template <typename T> class SmallVectorImpl;
37 class AliasAnalysis;
38 class TargetInstrInfo;
39 class TargetRegisterClass;
40 class TargetRegisterInfo;
41 class MachineFunction;
42 class MachineMemOperand;
43 
44 //===----------------------------------------------------------------------===//
45 /// MachineInstr - Representation of each machine instruction.
46 ///
47 /// This class isn't a POD type, but it must have a trivial destructor. When a
48 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
49 /// without having their destructor called.
50 ///
51 class MachineInstr : public ilist_node<MachineInstr> {
52 public:
53   typedef MachineMemOperand **mmo_iterator;
54 
55   /// Flags to specify different kinds of comments to output in
56   /// assembly code.  These flags carry semantic information not
57   /// otherwise easily derivable from the IR text.
58   ///
59   enum CommentFlag {
60     ReloadReuse = 0x1
61   };
62 
63   enum MIFlag {
64     NoFlags      = 0,
65     FrameSetup   = 1 << 0,              // Instruction is used as a part of
66                                         // function frame setup code.
67     BundledPred  = 1 << 1,              // Instruction has bundled predecessors.
68     BundledSucc  = 1 << 2               // Instruction has bundled successors.
69   };
70 private:
71   const MCInstrDesc *MCID;              // Instruction descriptor.
72   MachineBasicBlock *Parent;            // Pointer to the owning basic block.
73 
74   // Operands are allocated by an ArrayRecycler.
75   MachineOperand *Operands;             // Pointer to the first operand.
76   unsigned NumOperands;                 // Number of operands on instruction.
77   typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
78   OperandCapacity CapOperands;          // Capacity of the Operands array.
79 
80   uint8_t Flags;                        // Various bits of additional
81                                         // information about machine
82                                         // instruction.
83 
84   uint8_t AsmPrinterFlags;              // Various bits of information used by
85                                         // the AsmPrinter to emit helpful
86                                         // comments.  This is *not* semantic
87                                         // information.  Do not use this for
88                                         // anything other than to convey comment
89                                         // information to AsmPrinter.
90 
91   uint8_t NumMemRefs;                   // Information on memory references.
92   mmo_iterator MemRefs;
93 
94   DebugLoc debugLoc;                    // Source line information.
95 
96   MachineInstr(const MachineInstr&) = delete;
97   void operator=(const MachineInstr&) = delete;
98   // Use MachineFunction::DeleteMachineInstr() instead.
99   ~MachineInstr() = delete;
100 
101   // Intrusive list support
102   friend struct ilist_traits<MachineInstr>;
103   friend struct ilist_traits<MachineBasicBlock>;
104   void setParent(MachineBasicBlock *P) { Parent = P; }
105 
106   /// MachineInstr ctor - This constructor creates a copy of the given
107   /// MachineInstr in the given MachineFunction.
108   MachineInstr(MachineFunction &, const MachineInstr &);
109 
110   /// MachineInstr ctor - This constructor create a MachineInstr and add the
111   /// implicit operands.  It reserves space for number of operands specified by
112   /// MCInstrDesc.  An explicit DebugLoc is supplied.
113   MachineInstr(MachineFunction &, const MCInstrDesc &MCID, DebugLoc dl,
114                bool NoImp = false);
115 
116   // MachineInstrs are pool-allocated and owned by MachineFunction.
117   friend class MachineFunction;
118 
119 public:
120   const MachineBasicBlock* getParent() const { return Parent; }
121   MachineBasicBlock* getParent() { return Parent; }
122 
123   /// getAsmPrinterFlags - Return the asm printer flags bitvector.
124   ///
125   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
126 
127   /// clearAsmPrinterFlags - clear the AsmPrinter bitvector
128   ///
129   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
130 
131   /// getAsmPrinterFlag - Return whether an AsmPrinter flag is set.
132   ///
133   bool getAsmPrinterFlag(CommentFlag Flag) const {
134     return AsmPrinterFlags & Flag;
135   }
136 
137   /// setAsmPrinterFlag - Set a flag for the AsmPrinter.
138   ///
139   void setAsmPrinterFlag(CommentFlag Flag) {
140     AsmPrinterFlags |= (uint8_t)Flag;
141   }
142 
143   /// clearAsmPrinterFlag - clear specific AsmPrinter flags
144   ///
145   void clearAsmPrinterFlag(CommentFlag Flag) {
146     AsmPrinterFlags &= ~Flag;
147   }
148 
149   /// getFlags - Return the MI flags bitvector.
150   uint8_t getFlags() const {
151     return Flags;
152   }
153 
154   /// getFlag - Return whether an MI flag is set.
155   bool getFlag(MIFlag Flag) const {
156     return Flags & Flag;
157   }
158 
159   /// setFlag - Set a MI flag.
160   void setFlag(MIFlag Flag) {
161     Flags |= (uint8_t)Flag;
162   }
163 
164   void setFlags(unsigned flags) {
165     // Filter out the automatically maintained flags.
166     unsigned Mask = BundledPred | BundledSucc;
167     Flags = (Flags & Mask) | (flags & ~Mask);
168   }
169 
170   /// clearFlag - Clear a MI flag.
171   void clearFlag(MIFlag Flag) {
172     Flags &= ~((uint8_t)Flag);
173   }
174 
175   /// isInsideBundle - Return true if MI is in a bundle (but not the first MI
176   /// in a bundle).
177   ///
178   /// A bundle looks like this before it's finalized:
179   ///   ----------------
180   ///   |      MI      |
181   ///   ----------------
182   ///          |
183   ///   ----------------
184   ///   |      MI    * |
185   ///   ----------------
186   ///          |
187   ///   ----------------
188   ///   |      MI    * |
189   ///   ----------------
190   /// In this case, the first MI starts a bundle but is not inside a bundle, the
191   /// next 2 MIs are considered "inside" the bundle.
192   ///
193   /// After a bundle is finalized, it looks like this:
194   ///   ----------------
195   ///   |    Bundle    |
196   ///   ----------------
197   ///          |
198   ///   ----------------
199   ///   |      MI    * |
200   ///   ----------------
201   ///          |
202   ///   ----------------
203   ///   |      MI    * |
204   ///   ----------------
205   ///          |
206   ///   ----------------
207   ///   |      MI    * |
208   ///   ----------------
209   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
210   /// a bundle, but the next three MIs are.
211   bool isInsideBundle() const {
212     return getFlag(BundledPred);
213   }
214 
215   /// isBundled - Return true if this instruction part of a bundle. This is true
216   /// if either itself or its following instruction is marked "InsideBundle".
217   bool isBundled() const {
218     return isBundledWithPred() || isBundledWithSucc();
219   }
220 
221   /// Return true if this instruction is part of a bundle, and it is not the
222   /// first instruction in the bundle.
223   bool isBundledWithPred() const { return getFlag(BundledPred); }
224 
225   /// Return true if this instruction is part of a bundle, and it is not the
226   /// last instruction in the bundle.
227   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
228 
229   /// Bundle this instruction with its predecessor. This can be an unbundled
230   /// instruction, or it can be the first instruction in a bundle.
231   void bundleWithPred();
232 
233   /// Bundle this instruction with its successor. This can be an unbundled
234   /// instruction, or it can be the last instruction in a bundle.
235   void bundleWithSucc();
236 
237   /// Break bundle above this instruction.
238   void unbundleFromPred();
239 
240   /// Break bundle below this instruction.
241   void unbundleFromSucc();
242 
243   /// getDebugLoc - Returns the debug location id of this MachineInstr.
244   ///
245   const DebugLoc &getDebugLoc() const { return debugLoc; }
246 
247   /// \brief Return the debug variable referenced by
248   /// this DBG_VALUE instruction.
249   DIVariable getDebugVariable() const {
250     assert(isDebugValue() && "not a DBG_VALUE");
251     return cast<MDLocalVariable>(getOperand(2).getMetadata());
252   }
253 
254   /// \brief Return the complex address expression referenced by
255   /// this DBG_VALUE instruction.
256   DIExpression getDebugExpression() const {
257     assert(isDebugValue() && "not a DBG_VALUE");
258     return cast<MDExpression>(getOperand(3).getMetadata());
259   }
260 
261   /// emitError - Emit an error referring to the source location of this
262   /// instruction. This should only be used for inline assembly that is somehow
263   /// impossible to compile. Other errors should have been handled much
264   /// earlier.
265   ///
266   /// If this method returns, the caller should try to recover from the error.
267   ///
268   void emitError(StringRef Msg) const;
269 
270   /// getDesc - Returns the target instruction descriptor of this
271   /// MachineInstr.
272   const MCInstrDesc &getDesc() const { return *MCID; }
273 
274   /// getOpcode - Returns the opcode of this MachineInstr.
275   ///
276   int getOpcode() const { return MCID->Opcode; }
277 
278   /// Access to explicit operands of the instruction.
279   ///
280   unsigned getNumOperands() const { return NumOperands; }
281 
282   const MachineOperand& getOperand(unsigned i) const {
283     assert(i < getNumOperands() && "getOperand() out of range!");
284     return Operands[i];
285   }
286   MachineOperand& getOperand(unsigned i) {
287     assert(i < getNumOperands() && "getOperand() out of range!");
288     return Operands[i];
289   }
290 
291   /// getNumExplicitOperands - Returns the number of non-implicit operands.
292   ///
293   unsigned getNumExplicitOperands() const;
294 
295   /// iterator/begin/end - Iterate over all operands of a machine instruction.
296   typedef MachineOperand *mop_iterator;
297   typedef const MachineOperand *const_mop_iterator;
298 
299   mop_iterator operands_begin() { return Operands; }
300   mop_iterator operands_end() { return Operands + NumOperands; }
301 
302   const_mop_iterator operands_begin() const { return Operands; }
303   const_mop_iterator operands_end() const { return Operands + NumOperands; }
304 
305   iterator_range<mop_iterator> operands() {
306     return iterator_range<mop_iterator>(operands_begin(), operands_end());
307   }
308   iterator_range<const_mop_iterator> operands() const {
309     return iterator_range<const_mop_iterator>(operands_begin(), operands_end());
310   }
311   iterator_range<mop_iterator> explicit_operands() {
312     return iterator_range<mop_iterator>(
313         operands_begin(), operands_begin() + getNumExplicitOperands());
314   }
315   iterator_range<const_mop_iterator> explicit_operands() const {
316     return iterator_range<const_mop_iterator>(
317         operands_begin(), operands_begin() + getNumExplicitOperands());
318   }
319   iterator_range<mop_iterator> implicit_operands() {
320     return iterator_range<mop_iterator>(explicit_operands().end(),
321                                         operands_end());
322   }
323   iterator_range<const_mop_iterator> implicit_operands() const {
324     return iterator_range<const_mop_iterator>(explicit_operands().end(),
325                                               operands_end());
326   }
327   iterator_range<mop_iterator> defs() {
328     return iterator_range<mop_iterator>(
329         operands_begin(), operands_begin() + getDesc().getNumDefs());
330   }
331   iterator_range<const_mop_iterator> defs() const {
332     return iterator_range<const_mop_iterator>(
333         operands_begin(), operands_begin() + getDesc().getNumDefs());
334   }
335   iterator_range<mop_iterator> uses() {
336     return iterator_range<mop_iterator>(
337         operands_begin() + getDesc().getNumDefs(), operands_end());
338   }
339   iterator_range<const_mop_iterator> uses() const {
340     return iterator_range<const_mop_iterator>(
341         operands_begin() + getDesc().getNumDefs(), operands_end());
342   }
343 
344   /// Access to memory operands of the instruction
345   mmo_iterator memoperands_begin() const { return MemRefs; }
346   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
347   bool memoperands_empty() const { return NumMemRefs == 0; }
348 
349   iterator_range<mmo_iterator>  memoperands() {
350     return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
351   }
352   iterator_range<mmo_iterator> memoperands() const {
353     return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
354   }
355 
356   /// hasOneMemOperand - Return true if this instruction has exactly one
357   /// MachineMemOperand.
358   bool hasOneMemOperand() const {
359     return NumMemRefs == 1;
360   }
361 
362   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
363   /// queries but they are bundle aware.
364 
365   enum QueryType {
366     IgnoreBundle,    // Ignore bundles
367     AnyInBundle,     // Return true if any instruction in bundle has property
368     AllInBundle      // Return true if all instructions in bundle have property
369   };
370 
371   /// hasProperty - Return true if the instruction (or in the case of a bundle,
372   /// the instructions inside the bundle) has the specified property.
373   /// The first argument is the property being queried.
374   /// The second argument indicates whether the query should look inside
375   /// instruction bundles.
376   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
377     // Inline the fast path for unbundled or bundle-internal instructions.
378     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
379       return getDesc().getFlags() & (1 << MCFlag);
380 
381     // If this is the first instruction in a bundle, take the slow path.
382     return hasPropertyInBundle(1 << MCFlag, Type);
383   }
384 
385   /// isVariadic - Return true if this instruction can have a variable number of
386   /// operands.  In this case, the variable operands will be after the normal
387   /// operands but before the implicit definitions and uses (if any are
388   /// present).
389   bool isVariadic(QueryType Type = IgnoreBundle) const {
390     return hasProperty(MCID::Variadic, Type);
391   }
392 
393   /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
394   /// ARM instructions which can set condition code if 's' bit is set.
395   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
396     return hasProperty(MCID::HasOptionalDef, Type);
397   }
398 
399   /// isPseudo - Return true if this is a pseudo instruction that doesn't
400   /// correspond to a real machine instruction.
401   ///
402   bool isPseudo(QueryType Type = IgnoreBundle) const {
403     return hasProperty(MCID::Pseudo, Type);
404   }
405 
406   bool isReturn(QueryType Type = AnyInBundle) const {
407     return hasProperty(MCID::Return, Type);
408   }
409 
410   bool isCall(QueryType Type = AnyInBundle) const {
411     return hasProperty(MCID::Call, Type);
412   }
413 
414   /// isBarrier - Returns true if the specified instruction stops control flow
415   /// from executing the instruction immediately following it.  Examples include
416   /// unconditional branches and return instructions.
417   bool isBarrier(QueryType Type = AnyInBundle) const {
418     return hasProperty(MCID::Barrier, Type);
419   }
420 
421   /// isTerminator - Returns true if this instruction part of the terminator for
422   /// a basic block.  Typically this is things like return and branch
423   /// instructions.
424   ///
425   /// Various passes use this to insert code into the bottom of a basic block,
426   /// but before control flow occurs.
427   bool isTerminator(QueryType Type = AnyInBundle) const {
428     return hasProperty(MCID::Terminator, Type);
429   }
430 
431   /// isBranch - Returns true if this is a conditional, unconditional, or
432   /// indirect branch.  Predicates below can be used to discriminate between
433   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
434   /// get more information.
435   bool isBranch(QueryType Type = AnyInBundle) const {
436     return hasProperty(MCID::Branch, Type);
437   }
438 
439   /// isIndirectBranch - Return true if this is an indirect branch, such as a
440   /// branch through a register.
441   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
442     return hasProperty(MCID::IndirectBranch, Type);
443   }
444 
445   /// isConditionalBranch - Return true if this is a branch which may fall
446   /// through to the next instruction or may transfer control flow to some other
447   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
448   /// information about this branch.
449   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
450     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
451   }
452 
453   /// isUnconditionalBranch - Return true if this is a branch which always
454   /// transfers control flow to some other block.  The
455   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
456   /// about this branch.
457   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
458     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
459   }
460 
461   /// Return true if this instruction has a predicate operand that
462   /// controls execution.  It may be set to 'always', or may be set to other
463   /// values.   There are various methods in TargetInstrInfo that can be used to
464   /// control and modify the predicate in this instruction.
465   bool isPredicable(QueryType Type = AllInBundle) const {
466     // If it's a bundle than all bundled instructions must be predicable for this
467     // to return true.
468     return hasProperty(MCID::Predicable, Type);
469   }
470 
471   /// isCompare - Return true if this instruction is a comparison.
472   bool isCompare(QueryType Type = IgnoreBundle) const {
473     return hasProperty(MCID::Compare, Type);
474   }
475 
476   /// isMoveImmediate - Return true if this instruction is a move immediate
477   /// (including conditional moves) instruction.
478   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
479     return hasProperty(MCID::MoveImm, Type);
480   }
481 
482   /// isBitcast - Return true if this instruction is a bitcast instruction.
483   ///
484   bool isBitcast(QueryType Type = IgnoreBundle) const {
485     return hasProperty(MCID::Bitcast, Type);
486   }
487 
488   /// isSelect - Return true if this instruction is a select instruction.
489   ///
490   bool isSelect(QueryType Type = IgnoreBundle) const {
491     return hasProperty(MCID::Select, Type);
492   }
493 
494   /// isNotDuplicable - Return true if this instruction cannot be safely
495   /// duplicated.  For example, if the instruction has a unique labels attached
496   /// to it, duplicating it would cause multiple definition errors.
497   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
498     return hasProperty(MCID::NotDuplicable, Type);
499   }
500 
501   /// hasDelaySlot - Returns true if the specified instruction has a delay slot
502   /// which must be filled by the code generator.
503   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
504     return hasProperty(MCID::DelaySlot, Type);
505   }
506 
507   /// canFoldAsLoad - Return true for instructions that can be folded as
508   /// memory operands in other instructions. The most common use for this
509   /// is instructions that are simple loads from memory that don't modify
510   /// the loaded value in any way, but it can also be used for instructions
511   /// that can be expressed as constant-pool loads, such as V_SETALLONES
512   /// on x86, to allow them to be folded when it is beneficial.
513   /// This should only be set on instructions that return a value in their
514   /// only virtual register definition.
515   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
516     return hasProperty(MCID::FoldableAsLoad, Type);
517   }
518 
519   /// \brief Return true if this instruction behaves
520   /// the same way as the generic REG_SEQUENCE instructions.
521   /// E.g., on ARM,
522   /// dX VMOVDRR rY, rZ
523   /// is equivalent to
524   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
525   ///
526   /// Note that for the optimizers to be able to take advantage of
527   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
528   /// override accordingly.
529   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
530     return hasProperty(MCID::RegSequence, Type);
531   }
532 
533   /// \brief Return true if this instruction behaves
534   /// the same way as the generic EXTRACT_SUBREG instructions.
535   /// E.g., on ARM,
536   /// rX, rY VMOVRRD dZ
537   /// is equivalent to two EXTRACT_SUBREG:
538   /// rX = EXTRACT_SUBREG dZ, ssub_0
539   /// rY = EXTRACT_SUBREG dZ, ssub_1
540   ///
541   /// Note that for the optimizers to be able to take advantage of
542   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
543   /// override accordingly.
544   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
545     return hasProperty(MCID::ExtractSubreg, Type);
546   }
547 
548   /// \brief Return true if this instruction behaves
549   /// the same way as the generic INSERT_SUBREG instructions.
550   /// E.g., on ARM,
551   /// dX = VSETLNi32 dY, rZ, Imm
552   /// is equivalent to a INSERT_SUBREG:
553   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
554   ///
555   /// Note that for the optimizers to be able to take advantage of
556   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
557   /// override accordingly.
558   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
559     return hasProperty(MCID::InsertSubreg, Type);
560   }
561 
562   //===--------------------------------------------------------------------===//
563   // Side Effect Analysis
564   //===--------------------------------------------------------------------===//
565 
566   /// mayLoad - Return true if this instruction could possibly read memory.
567   /// Instructions with this flag set are not necessarily simple load
568   /// instructions, they may load a value and modify it, for example.
569   bool mayLoad(QueryType Type = AnyInBundle) const {
570     if (isInlineAsm()) {
571       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
572       if (ExtraInfo & InlineAsm::Extra_MayLoad)
573         return true;
574     }
575     return hasProperty(MCID::MayLoad, Type);
576   }
577 
578 
579   /// mayStore - Return true if this instruction could possibly modify memory.
580   /// Instructions with this flag set are not necessarily simple store
581   /// instructions, they may store a modified value based on their operands, or
582   /// may not actually modify anything, for example.
583   bool mayStore(QueryType Type = AnyInBundle) const {
584     if (isInlineAsm()) {
585       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
586       if (ExtraInfo & InlineAsm::Extra_MayStore)
587         return true;
588     }
589     return hasProperty(MCID::MayStore, Type);
590   }
591 
592   //===--------------------------------------------------------------------===//
593   // Flags that indicate whether an instruction can be modified by a method.
594   //===--------------------------------------------------------------------===//
595 
596   /// isCommutable - Return true if this may be a 2- or 3-address
597   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
598   /// result if Y and Z are exchanged.  If this flag is set, then the
599   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
600   /// instruction.
601   ///
602   /// Note that this flag may be set on instructions that are only commutable
603   /// sometimes.  In these cases, the call to commuteInstruction will fail.
604   /// Also note that some instructions require non-trivial modification to
605   /// commute them.
606   bool isCommutable(QueryType Type = IgnoreBundle) const {
607     return hasProperty(MCID::Commutable, Type);
608   }
609 
610   /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
611   /// which can be changed into a 3-address instruction if needed.  Doing this
612   /// transformation can be profitable in the register allocator, because it
613   /// means that the instruction can use a 2-address form if possible, but
614   /// degrade into a less efficient form if the source and dest register cannot
615   /// be assigned to the same register.  For example, this allows the x86
616   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
617   /// is the same speed as the shift but has bigger code size.
618   ///
619   /// If this returns true, then the target must implement the
620   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
621   /// is allowed to fail if the transformation isn't valid for this specific
622   /// instruction (e.g. shl reg, 4 on x86).
623   ///
624   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
625     return hasProperty(MCID::ConvertibleTo3Addr, Type);
626   }
627 
628   /// usesCustomInsertionHook - Return true if this instruction requires
629   /// custom insertion support when the DAG scheduler is inserting it into a
630   /// machine basic block.  If this is true for the instruction, it basically
631   /// means that it is a pseudo instruction used at SelectionDAG time that is
632   /// expanded out into magic code by the target when MachineInstrs are formed.
633   ///
634   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
635   /// is used to insert this into the MachineBasicBlock.
636   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
637     return hasProperty(MCID::UsesCustomInserter, Type);
638   }
639 
640   /// hasPostISelHook - Return true if this instruction requires *adjustment*
641   /// after instruction selection by calling a target hook. For example, this
642   /// can be used to fill in ARM 's' optional operand depending on whether
643   /// the conditional flag register is used.
644   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
645     return hasProperty(MCID::HasPostISelHook, Type);
646   }
647 
648   /// isRematerializable - Returns true if this instruction is a candidate for
649   /// remat.  This flag is deprecated, please don't use it anymore.  If this
650   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
651   /// verify the instruction is really rematable.
652   bool isRematerializable(QueryType Type = AllInBundle) const {
653     // It's only possible to re-mat a bundle if all bundled instructions are
654     // re-materializable.
655     return hasProperty(MCID::Rematerializable, Type);
656   }
657 
658   /// isAsCheapAsAMove - Returns true if this instruction has the same cost (or
659   /// less) than a move instruction. This is useful during certain types of
660   /// optimizations (e.g., remat during two-address conversion or machine licm)
661   /// where we would like to remat or hoist the instruction, but not if it costs
662   /// more than moving the instruction into the appropriate register. Note, we
663   /// are not marking copies from and to the same register class with this flag.
664   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
665     // Only returns true for a bundle if all bundled instructions are cheap.
666     return hasProperty(MCID::CheapAsAMove, Type);
667   }
668 
669   /// hasExtraSrcRegAllocReq - Returns true if this instruction source operands
670   /// have special register allocation requirements that are not captured by the
671   /// operand register classes. e.g. ARM::STRD's two source registers must be an
672   /// even / odd pair, ARM::STM registers have to be in ascending order.
673   /// Post-register allocation passes should not attempt to change allocations
674   /// for sources of instructions with this flag.
675   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
676     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
677   }
678 
679   /// hasExtraDefRegAllocReq - Returns true if this instruction def operands
680   /// have special register allocation requirements that are not captured by the
681   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
682   /// even / odd pair, ARM::LDM registers have to be in ascending order.
683   /// Post-register allocation passes should not attempt to change allocations
684   /// for definitions of instructions with this flag.
685   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
686     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
687   }
688 
689 
690   enum MICheckType {
691     CheckDefs,      // Check all operands for equality
692     CheckKillDead,  // Check all operands including kill / dead markers
693     IgnoreDefs,     // Ignore all definitions
694     IgnoreVRegDefs  // Ignore virtual register definitions
695   };
696 
697   /// isIdenticalTo - Return true if this instruction is identical to (same
698   /// opcode and same operands as) the specified instruction.
699   bool isIdenticalTo(const MachineInstr *Other,
700                      MICheckType Check = CheckDefs) const;
701 
702   /// Unlink 'this' from the containing basic block, and return it without
703   /// deleting it.
704   ///
705   /// This function can not be used on bundled instructions, use
706   /// removeFromBundle() to remove individual instructions from a bundle.
707   MachineInstr *removeFromParent();
708 
709   /// Unlink this instruction from its basic block and return it without
710   /// deleting it.
711   ///
712   /// If the instruction is part of a bundle, the other instructions in the
713   /// bundle remain bundled.
714   MachineInstr *removeFromBundle();
715 
716   /// Unlink 'this' from the containing basic block and delete it.
717   ///
718   /// If this instruction is the header of a bundle, the whole bundle is erased.
719   /// This function can not be used for instructions inside a bundle, use
720   /// eraseFromBundle() to erase individual bundled instructions.
721   void eraseFromParent();
722 
723   /// Unlink 'this' from the containing basic block and delete it.
724   ///
725   /// For all definitions mark their uses in DBG_VALUE nodes
726   /// as undefined. Otherwise like eraseFromParent().
727   void eraseFromParentAndMarkDBGValuesForRemoval();
728 
729   /// Unlink 'this' form its basic block and delete it.
730   ///
731   /// If the instruction is part of a bundle, the other instructions in the
732   /// bundle remain bundled.
733   void eraseFromBundle();
734 
735   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
736   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
737 
738   /// isLabel - Returns true if the MachineInstr represents a label.
739   ///
740   bool isLabel() const { return isEHLabel() || isGCLabel(); }
741   bool isCFIInstruction() const {
742     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
743   }
744 
745   // True if the instruction represents a position in the function.
746   bool isPosition() const { return isLabel() || isCFIInstruction(); }
747 
748   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
749   /// A DBG_VALUE is indirect iff the first operand is a register and
750   /// the second operand is an immediate.
751   bool isIndirectDebugValue() const {
752     return isDebugValue()
753       && getOperand(0).isReg()
754       && getOperand(1).isImm();
755   }
756 
757   bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
758   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
759   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
760   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
761   bool isMSInlineAsm() const {
762     return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
763   }
764   bool isStackAligningInlineAsm() const;
765   InlineAsm::AsmDialect getInlineAsmDialect() const;
766   bool isInsertSubreg() const {
767     return getOpcode() == TargetOpcode::INSERT_SUBREG;
768   }
769   bool isSubregToReg() const {
770     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
771   }
772   bool isRegSequence() const {
773     return getOpcode() == TargetOpcode::REG_SEQUENCE;
774   }
775   bool isBundle() const {
776     return getOpcode() == TargetOpcode::BUNDLE;
777   }
778   bool isCopy() const {
779     return getOpcode() == TargetOpcode::COPY;
780   }
781   bool isFullCopy() const {
782     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
783   }
784   bool isExtractSubreg() const {
785     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
786   }
787 
788   /// isCopyLike - Return true if the instruction behaves like a copy.
789   /// This does not include native copy instructions.
790   bool isCopyLike() const {
791     return isCopy() || isSubregToReg();
792   }
793 
794   /// isIdentityCopy - Return true is the instruction is an identity copy.
795   bool isIdentityCopy() const {
796     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
797       getOperand(0).getSubReg() == getOperand(1).getSubReg();
798   }
799 
800   /// isTransient - Return true if this is a transient instruction that is
801   /// either very likely to be eliminated during register allocation (such as
802   /// copy-like instructions), or if this instruction doesn't have an
803   /// execution-time cost.
804   bool isTransient() const {
805     switch(getOpcode()) {
806     default: return false;
807     // Copy-like instructions are usually eliminated during register allocation.
808     case TargetOpcode::PHI:
809     case TargetOpcode::COPY:
810     case TargetOpcode::INSERT_SUBREG:
811     case TargetOpcode::SUBREG_TO_REG:
812     case TargetOpcode::REG_SEQUENCE:
813     // Pseudo-instructions that don't produce any real output.
814     case TargetOpcode::IMPLICIT_DEF:
815     case TargetOpcode::KILL:
816     case TargetOpcode::CFI_INSTRUCTION:
817     case TargetOpcode::EH_LABEL:
818     case TargetOpcode::GC_LABEL:
819     case TargetOpcode::DBG_VALUE:
820       return true;
821     }
822   }
823 
824   /// Return the number of instructions inside the MI bundle, excluding the
825   /// bundle header.
826   ///
827   /// This is the number of instructions that MachineBasicBlock::iterator
828   /// skips, 0 for unbundled instructions.
829   unsigned getBundleSize() const;
830 
831   /// readsRegister - Return true if the MachineInstr reads the specified
832   /// register. If TargetRegisterInfo is passed, then it also checks if there
833   /// is a read of a super-register.
834   /// This does not count partial redefines of virtual registers as reads:
835   ///   %reg1024:6 = OP.
836   bool readsRegister(unsigned Reg,
837                      const TargetRegisterInfo *TRI = nullptr) const {
838     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
839   }
840 
841   /// readsVirtualRegister - Return true if the MachineInstr reads the specified
842   /// virtual register. Take into account that a partial define is a
843   /// read-modify-write operation.
844   bool readsVirtualRegister(unsigned Reg) const {
845     return readsWritesVirtualRegister(Reg).first;
846   }
847 
848   /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
849   /// indicating if this instruction reads or writes Reg. This also considers
850   /// partial defines.
851   /// If Ops is not null, all operand indices for Reg are added.
852   std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
853                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
854 
855   /// killsRegister - Return true if the MachineInstr kills the specified
856   /// register. If TargetRegisterInfo is passed, then it also checks if there is
857   /// a kill of a super-register.
858   bool killsRegister(unsigned Reg,
859                      const TargetRegisterInfo *TRI = nullptr) const {
860     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
861   }
862 
863   /// definesRegister - Return true if the MachineInstr fully defines the
864   /// specified register. If TargetRegisterInfo is passed, then it also checks
865   /// if there is a def of a super-register.
866   /// NOTE: It's ignoring subreg indices on virtual registers.
867   bool definesRegister(unsigned Reg,
868                        const TargetRegisterInfo *TRI = nullptr) const {
869     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
870   }
871 
872   /// modifiesRegister - Return true if the MachineInstr modifies (fully define
873   /// or partially define) the specified register.
874   /// NOTE: It's ignoring subreg indices on virtual registers.
875   bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
876     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
877   }
878 
879   /// registerDefIsDead - Returns true if the register is dead in this machine
880   /// instruction. If TargetRegisterInfo is passed, then it also checks
881   /// if there is a dead def of a super-register.
882   bool registerDefIsDead(unsigned Reg,
883                          const TargetRegisterInfo *TRI = nullptr) const {
884     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
885   }
886 
887   /// findRegisterUseOperandIdx() - Returns the operand index that is a use of
888   /// the specific register or -1 if it is not found. It further tightens
889   /// the search criteria to a use that kills the register if isKill is true.
890   int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
891                                 const TargetRegisterInfo *TRI = nullptr) const;
892 
893   /// findRegisterUseOperand - Wrapper for findRegisterUseOperandIdx, it returns
894   /// a pointer to the MachineOperand rather than an index.
895   MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
896                                       const TargetRegisterInfo *TRI = nullptr) {
897     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
898     return (Idx == -1) ? nullptr : &getOperand(Idx);
899   }
900 
901   /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
902   /// the specified register or -1 if it is not found. If isDead is true, defs
903   /// that are not dead are skipped. If Overlap is true, then it also looks for
904   /// defs that merely overlap the specified register. If TargetRegisterInfo is
905   /// non-null, then it also checks if there is a def of a super-register.
906   /// This may also return a register mask operand when Overlap is true.
907   int findRegisterDefOperandIdx(unsigned Reg,
908                                 bool isDead = false, bool Overlap = false,
909                                 const TargetRegisterInfo *TRI = nullptr) const;
910 
911   /// findRegisterDefOperand - Wrapper for findRegisterDefOperandIdx, it returns
912   /// a pointer to the MachineOperand rather than an index.
913   MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
914                                       const TargetRegisterInfo *TRI = nullptr) {
915     int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
916     return (Idx == -1) ? nullptr : &getOperand(Idx);
917   }
918 
919   /// findFirstPredOperandIdx() - Find the index of the first operand in the
920   /// operand list that is used to represent the predicate. It returns -1 if
921   /// none is found.
922   int findFirstPredOperandIdx() const;
923 
924   /// findInlineAsmFlagIdx() - Find the index of the flag word operand that
925   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
926   /// getOperand(OpIdx) does not belong to an inline asm operand group.
927   ///
928   /// If GroupNo is not NULL, it will receive the number of the operand group
929   /// containing OpIdx.
930   ///
931   /// The flag operand is an immediate that can be decoded with methods like
932   /// InlineAsm::hasRegClassConstraint().
933   ///
934   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
935 
936   /// getRegClassConstraint - Compute the static register class constraint for
937   /// operand OpIdx.  For normal instructions, this is derived from the
938   /// MCInstrDesc.  For inline assembly it is derived from the flag words.
939   ///
940   /// Returns NULL if the static register classs constraint cannot be
941   /// determined.
942   ///
943   const TargetRegisterClass*
944   getRegClassConstraint(unsigned OpIdx,
945                         const TargetInstrInfo *TII,
946                         const TargetRegisterInfo *TRI) const;
947 
948   /// \brief Applies the constraints (def/use) implied by this MI on \p Reg to
949   /// the given \p CurRC.
950   /// If \p ExploreBundle is set and MI is part of a bundle, all the
951   /// instructions inside the bundle will be taken into account. In other words,
952   /// this method accumulates all the constrains of the operand of this MI and
953   /// the related bundle if MI is a bundle or inside a bundle.
954   ///
955   /// Returns the register class that statisfies both \p CurRC and the
956   /// constraints set by MI. Returns NULL if such a register class does not
957   /// exist.
958   ///
959   /// \pre CurRC must not be NULL.
960   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
961       unsigned Reg, const TargetRegisterClass *CurRC,
962       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
963       bool ExploreBundle = false) const;
964 
965   /// \brief Applies the constraints (def/use) implied by the \p OpIdx operand
966   /// to the given \p CurRC.
967   ///
968   /// Returns the register class that statisfies both \p CurRC and the
969   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
970   /// does not exist.
971   ///
972   /// \pre CurRC must not be NULL.
973   /// \pre The operand at \p OpIdx must be a register.
974   const TargetRegisterClass *
975   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
976                               const TargetInstrInfo *TII,
977                               const TargetRegisterInfo *TRI) const;
978 
979   /// tieOperands - Add a tie between the register operands at DefIdx and
980   /// UseIdx. The tie will cause the register allocator to ensure that the two
981   /// operands are assigned the same physical register.
982   ///
983   /// Tied operands are managed automatically for explicit operands in the
984   /// MCInstrDesc. This method is for exceptional cases like inline asm.
985   void tieOperands(unsigned DefIdx, unsigned UseIdx);
986 
987   /// findTiedOperandIdx - Given the index of a tied register operand, find the
988   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
989   /// index of the tied operand which must exist.
990   unsigned findTiedOperandIdx(unsigned OpIdx) const;
991 
992   /// isRegTiedToUseOperand - Given the index of a register def operand,
993   /// check if the register def is tied to a source operand, due to either
994   /// two-address elimination or inline assembly constraints. Returns the
995   /// first tied use operand index by reference if UseOpIdx is not null.
996   bool isRegTiedToUseOperand(unsigned DefOpIdx,
997                              unsigned *UseOpIdx = nullptr) const {
998     const MachineOperand &MO = getOperand(DefOpIdx);
999     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1000       return false;
1001     if (UseOpIdx)
1002       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1003     return true;
1004   }
1005 
1006   /// isRegTiedToDefOperand - Return true if the use operand of the specified
1007   /// index is tied to a def operand. It also returns the def operand index by
1008   /// reference if DefOpIdx is not null.
1009   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1010                              unsigned *DefOpIdx = nullptr) const {
1011     const MachineOperand &MO = getOperand(UseOpIdx);
1012     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1013       return false;
1014     if (DefOpIdx)
1015       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1016     return true;
1017   }
1018 
1019   /// clearKillInfo - Clears kill flags on all operands.
1020   ///
1021   void clearKillInfo();
1022 
1023   /// substituteRegister - Replace all occurrences of FromReg with ToReg:SubIdx,
1024   /// properly composing subreg indices where necessary.
1025   void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1026                           const TargetRegisterInfo &RegInfo);
1027 
1028   /// addRegisterKilled - We have determined MI kills a register. Look for the
1029   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1030   /// add a implicit operand if it's not found. Returns true if the operand
1031   /// exists / is added.
1032   bool addRegisterKilled(unsigned IncomingReg,
1033                          const TargetRegisterInfo *RegInfo,
1034                          bool AddIfNotFound = false);
1035 
1036   /// clearRegisterKills - Clear all kill flags affecting Reg.  If RegInfo is
1037   /// provided, this includes super-register kills.
1038   void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1039 
1040   /// addRegisterDead - We have determined MI defined a register without a use.
1041   /// Look for the operand that defines it and mark it as IsDead. If
1042   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1043   /// true if the operand exists / is added.
1044   bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1045                        bool AddIfNotFound = false);
1046 
1047   /// Clear all dead flags on operands defining register @p Reg.
1048   void clearRegisterDeads(unsigned Reg);
1049 
1050   /// Mark all subregister defs of register @p Reg with the undef flag.
1051   /// This function is used when we determined to have a subregister def in an
1052   /// otherwise undefined super register.
1053   void addRegisterDefReadUndef(unsigned Reg);
1054 
1055   /// addRegisterDefined - We have determined MI defines a register. Make sure
1056   /// there is an operand defining Reg.
1057   void addRegisterDefined(unsigned Reg,
1058                           const TargetRegisterInfo *RegInfo = nullptr);
1059 
1060   /// setPhysRegsDeadExcept - Mark every physreg used by this instruction as
1061   /// dead except those in the UsedRegs list.
1062   ///
1063   /// On instructions with register mask operands, also add implicit-def
1064   /// operands for all registers in UsedRegs.
1065   void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1066                              const TargetRegisterInfo &TRI);
1067 
1068   /// isSafeToMove - Return true if it is safe to move this instruction. If
1069   /// SawStore is set to true, it means that there is a store (or call) between
1070   /// the instruction's location and its intended destination.
1071   bool isSafeToMove(const TargetInstrInfo *TII, AliasAnalysis *AA,
1072                     bool &SawStore) const;
1073 
1074   /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1075   /// or volatile memory reference, or if the information describing the memory
1076   /// reference is not available. Return false if it is known to have no
1077   /// ordered or volatile memory references.
1078   bool hasOrderedMemoryRef() const;
1079 
1080   /// isInvariantLoad - Return true if this instruction is loading from a
1081   /// location whose value is invariant across the function.  For example,
1082   /// loading a value from the constant pool or from the argument area of
1083   /// a function if it does not change.  This should only return true of *all*
1084   /// loads the instruction does are invariant (if it does multiple loads).
1085   bool isInvariantLoad(AliasAnalysis *AA) const;
1086 
1087   /// isConstantValuePHI - If the specified instruction is a PHI that always
1088   /// merges together the same virtual register, return the register, otherwise
1089   /// return 0.
1090   unsigned isConstantValuePHI() const;
1091 
1092   /// hasUnmodeledSideEffects - Return true if this instruction has side
1093   /// effects that are not modeled by mayLoad / mayStore, etc.
1094   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1095   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1096   /// INLINEASM instruction, in which case the side effect property is encoded
1097   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1098   ///
1099   bool hasUnmodeledSideEffects() const;
1100 
1101   /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1102   ///
1103   bool allDefsAreDead() const;
1104 
1105   /// copyImplicitOps - Copy implicit register operands from specified
1106   /// instruction to this instruction.
1107   void copyImplicitOps(MachineFunction &MF, const MachineInstr *MI);
1108 
1109   //
1110   // Debugging support
1111   //
1112   void print(raw_ostream &OS, bool SkipOpers = false) const;
1113   void dump() const;
1114 
1115   //===--------------------------------------------------------------------===//
1116   // Accessors used to build up machine instructions.
1117 
1118   /// Add the specified operand to the instruction.  If it is an implicit
1119   /// operand, it is added to the end of the operand list.  If it is an
1120   /// explicit operand it is added at the end of the explicit operand list
1121   /// (before the first implicit operand).
1122   ///
1123   /// MF must be the machine function that was used to allocate this
1124   /// instruction.
1125   ///
1126   /// MachineInstrBuilder provides a more convenient interface for creating
1127   /// instructions and adding operands.
1128   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1129 
1130   /// Add an operand without providing an MF reference. This only works for
1131   /// instructions that are inserted in a basic block.
1132   ///
1133   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1134   /// preferred.
1135   void addOperand(const MachineOperand &Op);
1136 
1137   /// setDesc - Replace the instruction descriptor (thus opcode) of
1138   /// the current instruction with a new one.
1139   ///
1140   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1141 
1142   /// setDebugLoc - Replace current source information with new such.
1143   /// Avoid using this, the constructor argument is preferable.
1144   ///
1145   void setDebugLoc(DebugLoc dl) {
1146     debugLoc = std::move(dl);
1147     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1148   }
1149 
1150   /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
1151   /// fewer operand than it started with.
1152   ///
1153   void RemoveOperand(unsigned i);
1154 
1155   /// addMemOperand - Add a MachineMemOperand to the machine instruction.
1156   /// This function should be used only occasionally. The setMemRefs function
1157   /// is the primary method for setting up a MachineInstr's MemRefs list.
1158   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1159 
1160   /// setMemRefs - Assign this MachineInstr's memory reference descriptor
1161   /// list. This does not transfer ownership.
1162   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1163     MemRefs = NewMemRefs;
1164     NumMemRefs = uint8_t(NewMemRefsEnd - NewMemRefs);
1165     assert(NumMemRefs == NewMemRefsEnd - NewMemRefs && "Too many memrefs");
1166   }
1167 
1168   /// clearMemRefs - Clear this MachineInstr's memory reference descriptor list.
1169   void clearMemRefs() {
1170     MemRefs = nullptr;
1171     NumMemRefs = 0;
1172   }
1173 
1174 private:
1175   /// getRegInfo - If this instruction is embedded into a MachineFunction,
1176   /// return the MachineRegisterInfo object for the current function, otherwise
1177   /// return null.
1178   MachineRegisterInfo *getRegInfo();
1179 
1180   /// untieRegOperand - Break any tie involving OpIdx.
1181   void untieRegOperand(unsigned OpIdx) {
1182     MachineOperand &MO = getOperand(OpIdx);
1183     if (MO.isReg() && MO.isTied()) {
1184       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1185       MO.TiedTo = 0;
1186     }
1187   }
1188 
1189   /// addImplicitDefUseOperands - Add all implicit def and use operands to
1190   /// this instruction.
1191   void addImplicitDefUseOperands(MachineFunction &MF);
1192 
1193   /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
1194   /// this instruction from their respective use lists.  This requires that the
1195   /// operands already be on their use lists.
1196   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1197 
1198   /// AddRegOperandsToUseLists - Add all of the register operands in
1199   /// this instruction from their respective use lists.  This requires that the
1200   /// operands not be on their use lists yet.
1201   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1202 
1203   /// hasPropertyInBundle - Slow path for hasProperty when we're dealing with a
1204   /// bundle.
1205   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1206 
1207   /// \brief Implements the logic of getRegClassConstraintEffectForVReg for the
1208   /// this MI and the given operand index \p OpIdx.
1209   /// If the related operand does not constrained Reg, this returns CurRC.
1210   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1211       unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1212       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1213 };
1214 
1215 /// MachineInstrExpressionTrait - Special DenseMapInfo traits to compare
1216 /// MachineInstr* by *value* of the instruction rather than by pointer value.
1217 /// The hashing and equality testing functions ignore definitions so this is
1218 /// useful for CSE, etc.
1219 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1220   static inline MachineInstr *getEmptyKey() {
1221     return nullptr;
1222   }
1223 
1224   static inline MachineInstr *getTombstoneKey() {
1225     return reinterpret_cast<MachineInstr*>(-1);
1226   }
1227 
1228   static unsigned getHashValue(const MachineInstr* const &MI);
1229 
1230   static bool isEqual(const MachineInstr* const &LHS,
1231                       const MachineInstr* const &RHS) {
1232     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1233         LHS == getEmptyKey() || LHS == getTombstoneKey())
1234       return LHS == RHS;
1235     return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
1236   }
1237 };
1238 
1239 //===----------------------------------------------------------------------===//
1240 // Debugging Support
1241 
1242 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1243   MI.print(OS);
1244   return OS;
1245 }
1246 
1247 } // End llvm namespace
1248 
1249 #endif
1250