This patch breaks up Wrap.h so that it does not have to include all of
[oota-llvm.git] / include / llvm / IR / Value.h
1 //===-- llvm/Value.h - Definition of the Value 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 declares the Value class. 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
16
17 #include "llvm/IR/Use.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/CBindingWrapping.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm-c/Core.h"
22
23 namespace llvm {
24
25 class Constant;
26 class Argument;
27 class Instruction;
28 class BasicBlock;
29 class GlobalValue;
30 class Function;
31 class GlobalVariable;
32 class GlobalAlias;
33 class InlineAsm;
34 class ValueSymbolTable;
35 template<typename ValueTy> class StringMapEntry;
36 typedef StringMapEntry<Value*> ValueName;
37 class raw_ostream;
38 class AssemblyAnnotationWriter;
39 class ValueHandleBase;
40 class LLVMContext;
41 class Twine;
42 class MDNode;
43 class Type;
44 class StringRef;
45
46 //===----------------------------------------------------------------------===//
47 //                                 Value Class
48 //===----------------------------------------------------------------------===//
49
50 /// This is a very important LLVM class. It is the base class of all values 
51 /// computed by a program that may be used as operands to other values. Value is
52 /// the super class of other important classes such as Instruction and Function.
53 /// All Values have a Type. Type is not a subclass of Value. Some values can
54 /// have a name and they belong to some Module.  Setting the name on the Value
55 /// automatically updates the module's symbol table.
56 ///
57 /// Every value has a "use list" that keeps track of which other Values are
58 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
59 /// objects that watch it and listen to RAUW and Destroy events.  See
60 /// llvm/Support/ValueHandle.h for details.
61 ///
62 /// @brief LLVM Value Representation
63 class Value {
64   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
65   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
66 protected:
67   /// SubclassOptionalData - This member is similar to SubclassData, however it
68   /// is for holding information which may be used to aid optimization, but
69   /// which may be cleared to zero without affecting conservative
70   /// interpretation.
71   unsigned char SubclassOptionalData : 7;
72
73 private:
74   /// SubclassData - This member is defined by this class, but is not used for
75   /// anything.  Subclasses can use it to hold whatever state they find useful.
76   /// This field is initialized to zero by the ctor.
77   unsigned short SubclassData;
78
79   Type *VTy;
80   Use *UseList;
81
82   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
83   friend class ValueHandleBase;
84   ValueName *Name;
85
86   void operator=(const Value &) LLVM_DELETED_FUNCTION;
87   Value(const Value &) LLVM_DELETED_FUNCTION;
88
89 protected:
90   /// printCustom - Value subclasses can override this to implement custom
91   /// printing behavior.
92   virtual void printCustom(raw_ostream &O) const;
93
94   Value(Type *Ty, unsigned scid);
95 public:
96   virtual ~Value();
97
98   /// dump - Support for debugging, callable in GDB: V->dump()
99   //
100   void dump() const;
101
102   /// print - Implement operator<< on Value.
103   ///
104   void print(raw_ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
105
106   /// All values are typed, get the type of this value.
107   ///
108   Type *getType() const { return VTy; }
109
110   /// All values hold a context through their type.
111   LLVMContext &getContext() const;
112
113   // All values can potentially be named.
114   bool hasName() const { return Name != 0 && SubclassID != MDStringVal; }
115   ValueName *getValueName() const { return Name; }
116   void setValueName(ValueName *VN) { Name = VN; }
117   
118   /// getName() - Return a constant reference to the value's name. This is cheap
119   /// and guaranteed to return the same reference as long as the value is not
120   /// modified.
121   StringRef getName() const;
122
123   /// setName() - Change the name of the value, choosing a new unique name if
124   /// the provided name is taken.
125   ///
126   /// \param Name The new name; or "" if the value's name should be removed.
127   void setName(const Twine &Name);
128
129   
130   /// takeName - transfer the name from V to this value, setting V's name to
131   /// empty.  It is an error to call V->takeName(V). 
132   void takeName(Value *V);
133
134   /// replaceAllUsesWith - Go through the uses list for this definition and make
135   /// each use point to "V" instead of "this".  After this completes, 'this's
136   /// use list is guaranteed to be empty.
137   ///
138   void replaceAllUsesWith(Value *V);
139
140   //----------------------------------------------------------------------
141   // Methods for handling the chain of uses of this Value.
142   //
143   typedef value_use_iterator<User>       use_iterator;
144   typedef value_use_iterator<const User> const_use_iterator;
145
146   bool               use_empty() const { return UseList == 0; }
147   use_iterator       use_begin()       { return use_iterator(UseList); }
148   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
149   use_iterator       use_end()         { return use_iterator(0);   }
150   const_use_iterator use_end()   const { return const_use_iterator(0);   }
151   User              *use_back()        { return *use_begin(); }
152   const User        *use_back()  const { return *use_begin(); }
153
154   /// hasOneUse - Return true if there is exactly one user of this value.  This
155   /// is specialized because it is a common request and does not require
156   /// traversing the whole use list.
157   ///
158   bool hasOneUse() const {
159     const_use_iterator I = use_begin(), E = use_end();
160     if (I == E) return false;
161     return ++I == E;
162   }
163
164   /// hasNUses - Return true if this Value has exactly N users.
165   ///
166   bool hasNUses(unsigned N) const;
167
168   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
169   /// logically equivalent to getNumUses() >= N.
170   ///
171   bool hasNUsesOrMore(unsigned N) const;
172
173   bool isUsedInBasicBlock(const BasicBlock *BB) const;
174
175   /// getNumUses - This method computes the number of uses of this Value.  This
176   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasNUsesOrMore
177   /// to check for specific values.
178   unsigned getNumUses() const;
179
180   /// addUse - This method should only be used by the Use class.
181   ///
182   void addUse(Use &U) { U.addToList(&UseList); }
183
184   /// An enumeration for keeping track of the concrete subclass of Value that
185   /// is actually instantiated. Values of this enumeration are kept in the 
186   /// Value classes SubclassID field. They are used for concrete type
187   /// identification.
188   enum ValueTy {
189     ArgumentVal,              // This is an instance of Argument
190     BasicBlockVal,            // This is an instance of BasicBlock
191     FunctionVal,              // This is an instance of Function
192     GlobalAliasVal,           // This is an instance of GlobalAlias
193     GlobalVariableVal,        // This is an instance of GlobalVariable
194     UndefValueVal,            // This is an instance of UndefValue
195     BlockAddressVal,          // This is an instance of BlockAddress
196     ConstantExprVal,          // This is an instance of ConstantExpr
197     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
198     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
199     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
200     ConstantIntVal,           // This is an instance of ConstantInt
201     ConstantFPVal,            // This is an instance of ConstantFP
202     ConstantArrayVal,         // This is an instance of ConstantArray
203     ConstantStructVal,        // This is an instance of ConstantStruct
204     ConstantVectorVal,        // This is an instance of ConstantVector
205     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
206     MDNodeVal,                // This is an instance of MDNode
207     MDStringVal,              // This is an instance of MDString
208     InlineAsmVal,             // This is an instance of InlineAsm
209     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
210     FixedStackPseudoSourceValueVal, // This is an instance of 
211                                     // FixedStackPseudoSourceValue
212     InstructionVal,           // This is an instance of Instruction
213     // Enum values starting at InstructionVal are used for Instructions;
214     // don't add new values here!
215
216     // Markers:
217     ConstantFirstVal = FunctionVal,
218     ConstantLastVal  = ConstantPointerNullVal
219   };
220
221   /// getValueID - Return an ID for the concrete type of this object.  This is
222   /// used to implement the classof checks.  This should not be used for any
223   /// other purpose, as the values may change as LLVM evolves.  Also, note that
224   /// for instructions, the Instruction's opcode is added to InstructionVal. So
225   /// this means three things:
226   /// # there is no value with code InstructionVal (no opcode==0).
227   /// # there are more possible values for the value type than in ValueTy enum.
228   /// # the InstructionVal enumerator must be the highest valued enumerator in
229   ///   the ValueTy enum.
230   unsigned getValueID() const {
231     return SubclassID;
232   }
233
234   /// getRawSubclassOptionalData - Return the raw optional flags value
235   /// contained in this value. This should only be used when testing two
236   /// Values for equivalence.
237   unsigned getRawSubclassOptionalData() const {
238     return SubclassOptionalData;
239   }
240
241   /// clearSubclassOptionalData - Clear the optional flags contained in
242   /// this value.
243   void clearSubclassOptionalData() {
244     SubclassOptionalData = 0;
245   }
246
247   /// hasSameSubclassOptionalData - Test whether the optional flags contained
248   /// in this value are equal to the optional flags in the given value.
249   bool hasSameSubclassOptionalData(const Value *V) const {
250     return SubclassOptionalData == V->SubclassOptionalData;
251   }
252
253   /// intersectOptionalDataWith - Clear any optional flags in this value
254   /// that are not also set in the given value.
255   void intersectOptionalDataWith(const Value *V) {
256     SubclassOptionalData &= V->SubclassOptionalData;
257   }
258
259   /// hasValueHandle - Return true if there is a value handle associated with
260   /// this value.
261   bool hasValueHandle() const { return HasValueHandle; }
262
263   /// stripPointerCasts - This method strips off any unneeded pointer casts and
264   /// all-zero GEPs from the specified value, returning the original uncasted
265   /// value. If this is called on a non-pointer value, it returns 'this'.
266   Value *stripPointerCasts();
267   const Value *stripPointerCasts() const {
268     return const_cast<Value*>(this)->stripPointerCasts();
269   }
270
271   /// stripInBoundsConstantOffsets - This method strips off unneeded pointer casts and
272   /// all-constant GEPs from the specified value, returning the original
273   /// pointer value. If this is called on a non-pointer value, it returns
274   /// 'this'.
275   Value *stripInBoundsConstantOffsets();
276   const Value *stripInBoundsConstantOffsets() const {
277     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
278   }
279
280   /// stripInBoundsOffsets - This method strips off unneeded pointer casts and
281   /// any in-bounds Offsets from the specified value, returning the original
282   /// pointer value. If this is called on a non-pointer value, it returns
283   /// 'this'.
284   Value *stripInBoundsOffsets();
285   const Value *stripInBoundsOffsets() const {
286     return const_cast<Value*>(this)->stripInBoundsOffsets();
287   }
288
289   /// isDereferenceablePointer - Test if this value is always a pointer to
290   /// allocated and suitably aligned memory for a simple load or store.
291   bool isDereferenceablePointer() const;
292   
293   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
294   /// return the value in the PHI node corresponding to PredBB.  If not, return
295   /// ourself.  This is useful if you want to know the value something has in a
296   /// predecessor block.
297   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
298
299   const Value *DoPHITranslation(const BasicBlock *CurBB,
300                                 const BasicBlock *PredBB) const{
301     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
302   }
303   
304   /// MaximumAlignment - This is the greatest alignment value supported by
305   /// load, store, and alloca instructions, and global values.
306   static const unsigned MaximumAlignment = 1u << 29;
307   
308   /// mutateType - Mutate the type of this Value to be of the specified type.
309   /// Note that this is an extremely dangerous operation which can create
310   /// completely invalid IR very easily.  It is strongly recommended that you
311   /// recreate IR objects with the right types instead of mutating them in
312   /// place.
313   void mutateType(Type *Ty) {
314     VTy = Ty;
315   }
316   
317 protected:
318   unsigned short getSubclassDataFromValue() const { return SubclassData; }
319   void setValueSubclassData(unsigned short D) { SubclassData = D; }
320 };
321
322 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
323   V.print(OS);
324   return OS;
325 }
326   
327 void Use::set(Value *V) {
328   if (Val) removeFromList();
329   Val = V;
330   if (V) V->addUse(*this);
331 }
332
333
334 // isa - Provide some specializations of isa so that we don't have to include
335 // the subtype header files to test to see if the value is a subclass...
336 //
337 template <> struct isa_impl<Constant, Value> {
338   static inline bool doit(const Value &Val) {
339     return Val.getValueID() >= Value::ConstantFirstVal &&
340       Val.getValueID() <= Value::ConstantLastVal;
341   }
342 };
343
344 template <> struct isa_impl<Argument, Value> {
345   static inline bool doit (const Value &Val) {
346     return Val.getValueID() == Value::ArgumentVal;
347   }
348 };
349
350 template <> struct isa_impl<InlineAsm, Value> { 
351   static inline bool doit(const Value &Val) {
352     return Val.getValueID() == Value::InlineAsmVal;
353   }
354 };
355
356 template <> struct isa_impl<Instruction, Value> { 
357   static inline bool doit(const Value &Val) {
358     return Val.getValueID() >= Value::InstructionVal;
359   }
360 };
361
362 template <> struct isa_impl<BasicBlock, Value> { 
363   static inline bool doit(const Value &Val) {
364     return Val.getValueID() == Value::BasicBlockVal;
365   }
366 };
367
368 template <> struct isa_impl<Function, Value> { 
369   static inline bool doit(const Value &Val) {
370     return Val.getValueID() == Value::FunctionVal;
371   }
372 };
373
374 template <> struct isa_impl<GlobalVariable, Value> { 
375   static inline bool doit(const Value &Val) {
376     return Val.getValueID() == Value::GlobalVariableVal;
377   }
378 };
379
380 template <> struct isa_impl<GlobalAlias, Value> { 
381   static inline bool doit(const Value &Val) {
382     return Val.getValueID() == Value::GlobalAliasVal;
383   }
384 };
385
386 template <> struct isa_impl<GlobalValue, Value> { 
387   static inline bool doit(const Value &Val) {
388     return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
389       isa<GlobalAlias>(Val);
390   }
391 };
392
393 template <> struct isa_impl<MDNode, Value> { 
394   static inline bool doit(const Value &Val) {
395     return Val.getValueID() == Value::MDNodeVal;
396   }
397 };
398   
399 // Value* is only 4-byte aligned.
400 template<>
401 class PointerLikeTypeTraits<Value*> {
402   typedef Value* PT;
403 public:
404   static inline void *getAsVoidPointer(PT P) { return P; }
405   static inline PT getFromVoidPointer(void *P) {
406     return static_cast<PT>(P);
407   }
408   enum { NumLowBitsAvailable = 2 };
409 };
410
411 // Create wrappers for C Binding types (see CBindingWrapping.h).
412 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
413
414 /* Specialized opaque value conversions.
415  */ 
416 inline Value **unwrap(LLVMValueRef *Vals) {
417   return reinterpret_cast<Value**>(Vals);
418 }
419
420 template<typename T>
421 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
422 #ifdef DEBUG
423   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
424     cast<T>(*I);
425 #endif
426   (void)Length;
427   return reinterpret_cast<T**>(Vals);
428 }
429
430 inline LLVMValueRef *wrap(const Value **Vals) {
431   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
432 }
433
434 } // End llvm namespace
435
436 #endif