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