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