f787777ae9d4d65fbd32f0f13f6f67b34845e14e
[oota-llvm.git] / include / llvm / 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_VALUE_H
15 #define LLVM_VALUE_H
16
17 #include "llvm/Use.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Casting.h"
20 #include <string>
21
22 namespace llvm {
23
24 class Constant;
25 class Argument;
26 class Instruction;
27 class BasicBlock;
28 class GlobalValue;
29 class Function;
30 class GlobalVariable;
31 class GlobalAlias;
32 class InlineAsm;
33 class ValueSymbolTable;
34 template<typename ValueTy> class StringMapEntry;
35 template <typename ValueTy = Value>
36 class AssertingVH;
37 typedef StringMapEntry<Value*> ValueName;
38 class raw_ostream;
39 class AssemblyAnnotationWriter;
40 class ValueHandleBase;
41 class LLVMContext;
42 class Twine;
43 class MDNode;
44 class Type;
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 &);     // Do not implement
87   Value(const Value &);              // Do not implement
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(const 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; }
115   ValueName *getValueName() const { return Name; }
116   
117   /// getName() - Return a constant reference to the value's name. This is cheap
118   /// and guaranteed to return the same reference as long as the value is not
119   /// modified.
120   ///
121   /// This is currently guaranteed to return a StringRef for which data() points
122   /// to a valid null terminated string. The use of StringRef.data() is 
123   /// deprecated here, however, and clients should not rely on it. If such 
124   /// behavior is needed, clients should use expensive getNameStr(), or switch 
125   /// to an interface that does not depend on null termination.
126   StringRef getName() const;
127
128   /// getNameStr() - Return the name of the specified value, *constructing a
129   /// string* to hold it.  This is guaranteed to construct a string and is very
130   /// expensive, clients should use getName() unless necessary.
131   std::string getNameStr() const;
132
133   /// setName() - Change the name of the value, choosing a new unique name if
134   /// the provided name is taken.
135   ///
136   /// \arg Name - The new name; or "" if the value's name should be removed.
137   void setName(const Twine &Name);
138
139   
140   /// takeName - transfer the name from V to this value, setting V's name to
141   /// empty.  It is an error to call V->takeName(V). 
142   void takeName(Value *V);
143
144   /// replaceAllUsesWith - Go through the uses list for this definition and make
145   /// each use point to "V" instead of "this".  After this completes, 'this's
146   /// use list is guaranteed to be empty.
147   ///
148   void replaceAllUsesWith(Value *V);
149
150   // uncheckedReplaceAllUsesWith - Just like replaceAllUsesWith but dangerous.
151   // Only use when in type resolution situations!
152   void uncheckedReplaceAllUsesWith(Value *V);
153
154   //----------------------------------------------------------------------
155   // Methods for handling the chain of uses of this Value.
156   //
157   typedef value_use_iterator<User>       use_iterator;
158   typedef value_use_iterator<const User> const_use_iterator;
159
160   bool               use_empty() const { return UseList == 0; }
161   use_iterator       use_begin()       { return use_iterator(UseList); }
162   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
163   use_iterator       use_end()         { return use_iterator(0);   }
164   const_use_iterator use_end()   const { return const_use_iterator(0);   }
165   User              *use_back()        { return *use_begin(); }
166   const User        *use_back()  const { return *use_begin(); }
167
168   /// hasOneUse - Return true if there is exactly one user of this value.  This
169   /// is specialized because it is a common request and does not require
170   /// traversing the whole use list.
171   ///
172   bool hasOneUse() const {
173     const_use_iterator I = use_begin(), E = use_end();
174     if (I == E) return false;
175     return ++I == E;
176   }
177
178   /// hasNUses - Return true if this Value has exactly N users.
179   ///
180   bool hasNUses(unsigned N) const;
181
182   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
183   /// logically equivalent to getNumUses() >= N.
184   ///
185   bool hasNUsesOrMore(unsigned N) const;
186
187   bool isUsedInBasicBlock(const BasicBlock *BB) const;
188
189   /// getNumUses - This method computes the number of uses of this Value.  This
190   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasMoreThanNUses
191   /// to check for specific values.
192   unsigned getNumUses() const;
193
194   /// addUse - This method should only be used by the Use class.
195   ///
196   void addUse(Use &U) { U.addToList(&UseList); }
197
198   /// An enumeration for keeping track of the concrete subclass of Value that
199   /// is actually instantiated. Values of this enumeration are kept in the 
200   /// Value classes SubclassID field. They are used for concrete type
201   /// identification.
202   enum ValueTy {
203     ArgumentVal,              // This is an instance of Argument
204     BasicBlockVal,            // This is an instance of BasicBlock
205     FunctionVal,              // This is an instance of Function
206     GlobalAliasVal,           // This is an instance of GlobalAlias
207     GlobalVariableVal,        // This is an instance of GlobalVariable
208     UndefValueVal,            // This is an instance of UndefValue
209     BlockAddressVal,          // This is an instance of BlockAddress
210     ConstantExprVal,          // This is an instance of ConstantExpr
211     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
212     ConstantIntVal,           // This is an instance of ConstantInt
213     ConstantFPVal,            // This is an instance of ConstantFP
214     ConstantArrayVal,         // This is an instance of ConstantArray
215     ConstantStructVal,        // This is an instance of ConstantStruct
216     ConstantVectorVal,        // This is an instance of ConstantVector
217     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
218     MDNodeVal,                // This is an instance of MDNode
219     MDStringVal,              // This is an instance of MDString
220     InlineAsmVal,             // This is an instance of InlineAsm
221     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
222     FixedStackPseudoSourceValueVal, // This is an instance of 
223                                     // FixedStackPseudoSourceValue
224     InstructionVal,           // This is an instance of Instruction
225     // Enum values starting at InstructionVal are used for Instructions;
226     // don't add new values here!
227
228     // Markers:
229     ConstantFirstVal = FunctionVal,
230     ConstantLastVal  = ConstantPointerNullVal
231   };
232
233   /// getValueID - Return an ID for the concrete type of this object.  This is
234   /// used to implement the classof checks.  This should not be used for any
235   /// other purpose, as the values may change as LLVM evolves.  Also, note that
236   /// for instructions, the Instruction's opcode is added to InstructionVal. So
237   /// this means three things:
238   /// # there is no value with code InstructionVal (no opcode==0).
239   /// # there are more possible values for the value type than in ValueTy enum.
240   /// # the InstructionVal enumerator must be the highest valued enumerator in
241   ///   the ValueTy enum.
242   unsigned getValueID() const {
243     return SubclassID;
244   }
245
246   /// getRawSubclassOptionalData - Return the raw optional flags value
247   /// contained in this value. This should only be used when testing two
248   /// Values for equivalence.
249   unsigned getRawSubclassOptionalData() const {
250     return SubclassOptionalData;
251   }
252
253   /// clearSubclassOptionalData - Clear the optional flags contained in
254   /// this value.
255   void clearSubclassOptionalData() {
256     SubclassOptionalData = 0;
257   }
258
259   /// hasSameSubclassOptionalData - Test whether the optional flags contained
260   /// in this value are equal to the optional flags in the given value.
261   bool hasSameSubclassOptionalData(const Value *V) const {
262     return SubclassOptionalData == V->SubclassOptionalData;
263   }
264
265   /// intersectOptionalDataWith - Clear any optional flags in this value
266   /// that are not also set in the given value.
267   void intersectOptionalDataWith(const Value *V) {
268     SubclassOptionalData &= V->SubclassOptionalData;
269   }
270
271   /// hasValueHandle - Return true if there is a value handle associated with
272   /// this value.
273   bool hasValueHandle() const { return HasValueHandle; }
274   
275   // Methods for support type inquiry through isa, cast, and dyn_cast:
276   static inline bool classof(const Value *) {
277     return true; // Values are always values.
278   }
279
280   /// stripPointerCasts - This method strips off any unneeded pointer
281   /// casts from the specified value, returning the original uncasted value.
282   /// Note that the returned value has pointer type if the specified value does.
283   Value *stripPointerCasts();
284   const Value *stripPointerCasts() const {
285     return const_cast<Value*>(this)->stripPointerCasts();
286   }
287
288   /// isDereferenceablePointer - Test if this value is always a pointer to
289   /// allocated and suitably aligned memory for a simple load or store.
290   bool isDereferenceablePointer() const;
291   
292   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
293   /// return the value in the PHI node corresponding to PredBB.  If not, return
294   /// ourself.  This is useful if you want to know the value something has in a
295   /// predecessor block.
296   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
297
298   const Value *DoPHITranslation(const BasicBlock *CurBB,
299                                 const BasicBlock *PredBB) const{
300     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
301   }
302   
303   /// MaximumAlignment - This is the greatest alignment value supported by
304   /// load, store, and alloca instructions, and global values.
305   static const unsigned MaximumAlignment = 1u << 29;
306   
307   /// mutateType - Mutate the type of this Value to be of the specified type.
308   /// Note that this is an extremely dangerous operation which can create
309   /// completely invalid IR very easily.  It is strongly recommended that you
310   /// recreate IR objects with the right types instead of mutating them in
311   /// place.
312   void mutateType(Type *Ty) {
313     VTy = Ty;
314   }
315   
316 protected:
317   unsigned short getSubclassDataFromValue() const { return SubclassData; }
318   void setValueSubclassData(unsigned short D) { SubclassData = D; }
319 };
320
321 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
322   V.print(OS);
323   return OS;
324 }
325   
326 void Use::set(Value *V) {
327   if (Val) removeFromList();
328   Val = V;
329   if (V) V->addUse(*this);
330 }
331
332
333 // isa - Provide some specializations of isa so that we don't have to include
334 // the subtype header files to test to see if the value is a subclass...
335 //
336 template <> struct isa_impl<Constant, Value> {
337   static inline bool doit(const Value &Val) {
338     return Val.getValueID() >= Value::ConstantFirstVal &&
339       Val.getValueID() <= Value::ConstantLastVal;
340   }
341 };
342
343 template <> struct isa_impl<Argument, Value> {
344   static inline bool doit (const Value &Val) {
345     return Val.getValueID() == Value::ArgumentVal;
346   }
347 };
348
349 template <> struct isa_impl<InlineAsm, Value> { 
350   static inline bool doit(const Value &Val) {
351     return Val.getValueID() == Value::InlineAsmVal;
352   }
353 };
354
355 template <> struct isa_impl<Instruction, Value> { 
356   static inline bool doit(const Value &Val) {
357     return Val.getValueID() >= Value::InstructionVal;
358   }
359 };
360
361 template <> struct isa_impl<BasicBlock, Value> { 
362   static inline bool doit(const Value &Val) {
363     return Val.getValueID() == Value::BasicBlockVal;
364   }
365 };
366
367 template <> struct isa_impl<Function, Value> { 
368   static inline bool doit(const Value &Val) {
369     return Val.getValueID() == Value::FunctionVal;
370   }
371 };
372
373 template <> struct isa_impl<GlobalVariable, Value> { 
374   static inline bool doit(const Value &Val) {
375     return Val.getValueID() == Value::GlobalVariableVal;
376   }
377 };
378
379 template <> struct isa_impl<GlobalAlias, Value> { 
380   static inline bool doit(const Value &Val) {
381     return Val.getValueID() == Value::GlobalAliasVal;
382   }
383 };
384
385 template <> struct isa_impl<GlobalValue, Value> { 
386   static inline bool doit(const Value &Val) {
387     return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
388       isa<GlobalAlias>(Val);
389   }
390 };
391
392 template <> struct isa_impl<MDNode, Value> { 
393   static inline bool doit(const Value &Val) {
394     return Val.getValueID() == Value::MDNodeVal;
395   }
396 };
397   
398 // Value* is only 4-byte aligned.
399 template<>
400 class PointerLikeTypeTraits<Value*> {
401   typedef Value* PT;
402 public:
403   static inline void *getAsVoidPointer(PT P) { return P; }
404   static inline PT getFromVoidPointer(void *P) {
405     return static_cast<PT>(P);
406   }
407   enum { NumLowBitsAvailable = 2 };
408 };
409
410 } // End llvm namespace
411
412 #endif