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