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