add new apis for getting/setting !dbg metadata on
[oota-llvm.git] / include / llvm / Instruction.h
1 //===-- llvm/Instruction.h - Instruction class definition -------*- 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 Instruction class, which is the
11 // base class for all of the LLVM instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_INSTRUCTION_H
16 #define LLVM_INSTRUCTION_H
17
18 #include "llvm/User.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/ValueHandle.h"
21
22 namespace llvm {
23
24 class LLVMContext;
25 class MDNode;
26
27 template<typename ValueSubClass, typename ItemParentClass>
28   class SymbolTableListTraits;
29
30 class Instruction : public User, public ilist_node<Instruction> {
31   void operator=(const Instruction &);     // Do not implement
32   Instruction(const Instruction &);        // Do not implement
33
34   BasicBlock *Parent;
35   TrackingVH<MDNode> DbgInfo;         // 'dbg' Metadata cache.
36   
37   enum {
38     /// HasMetadataBit - This is a bit stored in the SubClassData field which
39     /// indicates whether this instruction has metadata attached to it or not.
40     HasMetadataBit = 1 << 15
41   };
42 public:
43   // Out of line virtual method, so the vtable, etc has a home.
44   ~Instruction();
45   
46   /// use_back - Specialize the methods defined in Value, as we know that an
47   /// instruction can only be used by other instructions.
48   Instruction       *use_back()       { return cast<Instruction>(*use_begin());}
49   const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
50   
51   inline const BasicBlock *getParent() const { return Parent; }
52   inline       BasicBlock *getParent()       { return Parent; }
53
54   /// removeFromParent - This method unlinks 'this' from the containing basic
55   /// block, but does not delete it.
56   ///
57   void removeFromParent();
58
59   /// eraseFromParent - This method unlinks 'this' from the containing basic
60   /// block and deletes it.
61   ///
62   void eraseFromParent();
63
64   /// insertBefore - Insert an unlinked instructions into a basic block
65   /// immediately before the specified instruction.
66   void insertBefore(Instruction *InsertPos);
67
68   /// insertAfter - Insert an unlinked instructions into a basic block
69   /// immediately after the specified instruction.
70   void insertAfter(Instruction *InsertPos);
71
72   /// moveBefore - Unlink this instruction from its current basic block and
73   /// insert it into the basic block that MovePos lives in, right before
74   /// MovePos.
75   void moveBefore(Instruction *MovePos);
76
77   //===--------------------------------------------------------------------===//
78   // Subclass classification.
79   //===--------------------------------------------------------------------===//
80   
81   /// getOpcode() returns a member of one of the enums like Instruction::Add.
82   unsigned getOpcode() const { return getValueID() - InstructionVal; }
83   
84   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
85   bool isTerminator() const { return isTerminator(getOpcode()); }
86   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
87   bool isShift() { return isShift(getOpcode()); }
88   bool isCast() const { return isCast(getOpcode()); }
89   
90   static const char* getOpcodeName(unsigned OpCode);
91
92   static inline bool isTerminator(unsigned OpCode) {
93     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
94   }
95
96   static inline bool isBinaryOp(unsigned Opcode) {
97     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
98   }
99
100   /// @brief Determine if the Opcode is one of the shift instructions.
101   static inline bool isShift(unsigned Opcode) {
102     return Opcode >= Shl && Opcode <= AShr;
103   }
104
105   /// isLogicalShift - Return true if this is a logical shift left or a logical
106   /// shift right.
107   inline bool isLogicalShift() const {
108     return getOpcode() == Shl || getOpcode() == LShr;
109   }
110
111   /// isArithmeticShift - Return true if this is an arithmetic shift right.
112   inline bool isArithmeticShift() const {
113     return getOpcode() == AShr;
114   }
115
116   /// @brief Determine if the OpCode is one of the CastInst instructions.
117   static inline bool isCast(unsigned OpCode) {
118     return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
119   }
120
121   //===--------------------------------------------------------------------===//
122   // Metadata manipulation.
123   //===--------------------------------------------------------------------===//
124   
125   /// hasMetadata() - Return true if this instruction has any metadata attached
126   /// to it.
127   bool hasMetadata() const {
128     return DbgInfo != 0 || hasMetadataHashEntry();
129   }
130   
131   /// getMetadata - Get the metadata of given kind attached to this Instruction.
132   /// If the metadata is not found then return null.
133   MDNode *getMetadata(unsigned KindID) const {
134     if (!hasMetadata()) return 0;
135     return getMetadataImpl(KindID);
136   }
137   
138   /// getMetadata - Get the metadata of given kind attached to this Instruction.
139   /// If the metadata is not found then return null.
140   MDNode *getMetadata(const char *Kind) const {
141     if (!hasMetadata()) return 0;
142     return getMetadataImpl(Kind);
143   }
144   
145   /// getAllMetadata - Get all metadata attached to this Instruction.  The first
146   /// element of each pair returned is the KindID, the second element is the
147   /// metadata value.  This list is returned sorted by the KindID.
148   void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
149     if (hasMetadata())
150       getAllMetadataImpl(MDs);
151   }
152   
153   /// setMetadata - Set the metadata of the specified kind to the specified
154   /// node.  This updates/replaces metadata if already present, or removes it if
155   /// Node is null.
156   void setMetadata(unsigned KindID, MDNode *Node);
157   void setMetadata(const char *Kind, MDNode *Node);
158
159   /// setDbgMetadata - This is just an optimized helper function that is
160   /// equivalent to setMetadata("dbg", Node);
161   void setDbgMetadata(MDNode *Node);
162   
163   /// getDbgMetadata - This is just an optimized helper function that is
164   /// equivalent to calling getMetadata("dbg").
165   MDNode *getDbgMetadata() const {
166     return DbgInfo;
167   }
168   
169 private:
170   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
171   /// metadata hash.
172   bool hasMetadataHashEntry() const {
173     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
174   }
175   
176   // These are all implemented in Metadata.cpp.
177   MDNode *getMetadataImpl(unsigned KindID) const;
178   MDNode *getMetadataImpl(const char *Kind) const;
179   void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
180   void removeAllMetadata();
181 public:
182   //===--------------------------------------------------------------------===//
183   // Predicates and helper methods.
184   //===--------------------------------------------------------------------===//
185   
186   
187   /// isAssociative - Return true if the instruction is associative:
188   ///
189   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
190   ///
191   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative, when
192   /// not applied to floating point types.
193   ///
194   bool isAssociative() const { return isAssociative(getOpcode(), getType()); }
195   static bool isAssociative(unsigned op, const Type *Ty);
196
197   /// isCommutative - Return true if the instruction is commutative:
198   ///
199   ///   Commutative operators satisfy: (x op y) === (y op x)
200   ///
201   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
202   /// applied to any type.
203   ///
204   bool isCommutative() const { return isCommutative(getOpcode()); }
205   static bool isCommutative(unsigned op);
206
207   /// mayWriteToMemory - Return true if this instruction may modify memory.
208   ///
209   bool mayWriteToMemory() const;
210
211   /// mayReadFromMemory - Return true if this instruction may read memory.
212   ///
213   bool mayReadFromMemory() const;
214
215   /// mayThrow - Return true if this instruction may throw an exception.
216   ///
217   bool mayThrow() const;
218
219   /// mayHaveSideEffects - Return true if the instruction may have side effects.
220   ///
221   /// Note that this does not consider malloc and alloca to have side
222   /// effects because the newly allocated memory is completely invisible to
223   /// instructions which don't used the returned value.  For cases where this
224   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
225   bool mayHaveSideEffects() const {
226     return mayWriteToMemory() || mayThrow();
227   }
228
229   /// isSafeToSpeculativelyExecute - Return true if the instruction does not
230   /// have any effects besides calculating the result and does not have
231   /// undefined behavior.
232   ///
233   /// This method never returns true for an instruction that returns true for
234   /// mayHaveSideEffects; however, this method also does some other checks in
235   /// addition. It checks for undefined behavior, like dividing by zero or
236   /// loading from an invalid pointer (but not for undefined results, like a
237   /// shift with a shift amount larger than the width of the result). It checks
238   /// for malloc and alloca because speculatively executing them might cause a
239   /// memory leak. It also returns false for instructions related to control
240   /// flow, specifically terminators and PHI nodes.
241   ///
242   /// This method only looks at the instruction itself and its operands, so if
243   /// this method returns true, it is safe to move the instruction as long as
244   /// the correct dominance relationships for the operands and users hold.
245   /// However, this method can return true for instructions that read memory;
246   /// for such instructions, moving them may change the resulting value.
247   bool isSafeToSpeculativelyExecute() const;
248
249   /// clone() - Create a copy of 'this' instruction that is identical in all
250   /// ways except the following:
251   ///   * The instruction has no parent
252   ///   * The instruction has no name
253   ///
254   Instruction *clone() const;
255   
256   /// isIdenticalTo - Return true if the specified instruction is exactly
257   /// identical to the current one.  This means that all operands match and any
258   /// extra information (e.g. load is volatile) agree.
259   bool isIdenticalTo(const Instruction *I) const;
260   
261   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
262   /// ignores the SubclassOptionalData flags, which specify conditions
263   /// under which the instruction's result is undefined.
264   bool isIdenticalToWhenDefined(const Instruction *I) const;
265   
266   /// This function determines if the specified instruction executes the same
267   /// operation as the current one. This means that the opcodes, type, operand
268   /// types and any other factors affecting the operation must be the same. This
269   /// is similar to isIdenticalTo except the operands themselves don't have to
270   /// be identical.
271   /// @returns true if the specified instruction is the same operation as
272   /// the current one.
273   /// @brief Determine if one instruction is the same operation as another.
274   bool isSameOperationAs(const Instruction *I) const;
275   
276   /// isUsedOutsideOfBlock - Return true if there are any uses of this
277   /// instruction in blocks other than the specified block.  Note that PHI nodes
278   /// are considered to evaluate their operands in the corresponding predecessor
279   /// block.
280   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
281   
282   
283   /// Methods for support type inquiry through isa, cast, and dyn_cast:
284   static inline bool classof(const Instruction *) { return true; }
285   static inline bool classof(const Value *V) {
286     return V->getValueID() >= Value::InstructionVal;
287   }
288
289   //----------------------------------------------------------------------
290   // Exported enumerations.
291   //
292   enum TermOps {       // These terminate basic blocks
293 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
294 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
295 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
296 #include "llvm/Instruction.def"
297   };
298
299   enum BinaryOps {
300 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
301 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
302 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
303 #include "llvm/Instruction.def"
304   };
305
306   enum MemoryOps {
307 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
308 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
309 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
310 #include "llvm/Instruction.def"
311   };
312
313   enum CastOps {
314 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
315 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
316 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
317 #include "llvm/Instruction.def"
318   };
319
320   enum OtherOps {
321 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
322 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
323 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
324 #include "llvm/Instruction.def"
325   };
326 private:
327   // Shadow Value::setValueSubclassData with a private forwarding method so that
328   // subclasses cannot accidentally use it.
329   void setValueSubclassData(unsigned short D) {
330     Value::setValueSubclassData(D);
331   }
332   unsigned short getSubclassDataFromValue() const {
333     return Value::getSubclassDataFromValue();
334   }
335   
336   void setHasMetadataHashEntry(bool V) {
337     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
338                          (V ? HasMetadataBit : 0));
339   }
340   
341   friend class SymbolTableListTraits<Instruction, BasicBlock>;
342   void setParent(BasicBlock *P);
343 protected:
344   // Instruction subclasses can stick up to 15 bits of stuff into the
345   // SubclassData field of instruction with these members.
346   
347   // Verify that only the low 15 bits are used.
348   void setInstructionSubclassData(unsigned short D) {
349     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
350     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
351   }
352   
353   unsigned getSubclassDataFromInstruction() const {
354     return getSubclassDataFromValue() & ~HasMetadataBit;
355   }
356   
357   Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
358               Instruction *InsertBefore = 0);
359   Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
360               BasicBlock *InsertAtEnd);
361   virtual Instruction *clone_impl() const = 0;
362   
363 };
364
365 // Instruction* is only 4-byte aligned.
366 template<>
367 class PointerLikeTypeTraits<Instruction*> {
368   typedef Instruction* PT;
369 public:
370   static inline void *getAsVoidPointer(PT P) { return P; }
371   static inline PT getFromVoidPointer(void *P) {
372     return static_cast<PT>(P);
373   }
374   enum { NumLowBitsAvailable = 2 };
375 };
376   
377 } // End llvm namespace
378
379 #endif