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