b840531ce88b8164587f3ec7b3cfca1ea99af9eb
[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/AbstractTypeUser.h"
18 #include "llvm/Use.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Casting.h"
22 #include <iosfwd>
23 #include <string>
24
25 namespace llvm {
26
27 class Constant;
28 class Argument;
29 class Instruction;
30 class BasicBlock;
31 class GlobalValue;
32 class Function;
33 class GlobalVariable;
34 class GlobalAlias;
35 class InlineAsm;
36 class ValueSymbolTable;
37 class TypeSymbolTable;
38 template<typename ValueTy> class StringMapEntry;
39 template <typename ValueTy = Value>
40 class AssertingVH;
41 typedef StringMapEntry<Value*> ValueName;
42 class raw_ostream;
43 class AssemblyAnnotationWriter;
44 class ValueHandleBase;
45 class LLVMContext;
46
47 //===----------------------------------------------------------------------===//
48 //                                 Value Class
49 //===----------------------------------------------------------------------===//
50
51 /// This is a very important LLVM class. It is the base class of all values 
52 /// computed by a program that may be used as operands to other values. Value is
53 /// the super class of other important classes such as Instruction and Function.
54 /// All Values have a Type. Type is not a subclass of Value. All types can have
55 /// a name and they should belong to some Module. Setting the name on the Value
56 /// automatically updates the module's symbol table.
57 ///
58 /// Every value has a "use list" that keeps track of which other Values are
59 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
60 /// objects that watch it and listen to RAUW and Destroy events see
61 /// llvm/Support/ValueHandle.h for details.
62 ///
63 /// @brief LLVM Value Representation
64 class Value {
65   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
66   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
67 protected:
68   /// SubclassOptionalData - This member is similar to SubclassData, however it
69   /// is for holding information which may be used to aid optimization, but
70   /// which may be cleared to zero without affecting conservative
71   /// interpretation.
72   unsigned char SubclassOptionalData : 7;
73
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 private:
79   PATypeHolder VTy;
80   Use *UseList;
81
82   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
83   friend class SymbolTable;      // Allow SymbolTable to directly poke Name.
84   friend class ValueHandleBase;
85   ValueName *Name;
86
87   void operator=(const Value &);     // Do not implement
88   Value(const Value &);              // Do not implement
89
90 public:
91   Value(const Type *Ty, unsigned scid);
92   virtual ~Value();
93
94   /// dump - Support for debugging, callable in GDB: V->dump()
95   //
96   virtual void dump() const;
97
98   /// print - Implement operator<< on Value.
99   ///
100   void print(std::ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
101   void print(raw_ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
102
103   /// All values are typed, get the type of this value.
104   ///
105   inline const Type *getType() const { return VTy; }
106
107   /// All values hold a context through their type.
108   LLVMContext &getContext() const;
109
110   // All values can potentially be named...
111   inline bool hasName() const { return Name != 0; }
112   ValueName *getValueName() const { return Name; }
113
114   /// getNameStart - Return a pointer to a null terminated string for this name.
115   /// Note that names can have null characters within the string as well as at
116   /// their end.  This always returns a non-null pointer.
117   const char *getNameStart() const { 
118     if (!Name) return "";
119     return getName().begin(); 
120   }
121   /// getNameEnd - Return a pointer to the end of the name.
122   const char *getNameEnd() const { 
123     if (!Name) return "";
124     return getName().end(); 
125   }
126   
127   /// getName() - Return a constant reference to the value's name. This is cheap
128   /// and guaranteed to return the same reference as long as the value is not
129   /// modified.
130   StringRef getName() const;
131
132   /// getNameStr() - Return the name of the specified value, *constructing a
133   /// string* to hold it.  This is guaranteed to construct a string and is very
134   /// expensive, clients should use getName() unless necessary.
135   std::string getNameStr() const;
136
137   /// setName() - Change the name of the value, choosing a new unique name if
138   /// the provided name is taken.
139   ///
140   /// \arg Name - The new name; or "" if the value's name should be removed.
141   void setName(const Twine &Name);
142
143   
144   /// takeName - transfer the name from V to this value, setting V's name to
145   /// empty.  It is an error to call V->takeName(V). 
146   void takeName(Value *V);
147
148   /// replaceAllUsesWith - Go through the uses list for this definition and make
149   /// each use point to "V" instead of "this".  After this completes, 'this's
150   /// use list is guaranteed to be empty.
151   ///
152   void replaceAllUsesWith(Value *V);
153
154   // uncheckedReplaceAllUsesWith - Just like replaceAllUsesWith but dangerous.
155   // Only use when in type resolution situations!
156   void uncheckedReplaceAllUsesWith(Value *V);
157
158   /// clearOptionalData - Clear any optional optimization data from this Value.
159   /// Transformation passes must call this method whenever changing the IR
160   /// in a way that would affect the values produced by this Value, unless
161   /// it takes special care to ensure correctness in some other way.
162   void clearOptionalData() { SubclassOptionalData = 0; }
163
164   //----------------------------------------------------------------------
165   // Methods for handling the chain of uses of this Value.
166   //
167   typedef value_use_iterator<User>       use_iterator;
168   typedef value_use_iterator<const User> use_const_iterator;
169
170   bool               use_empty() const { return UseList == 0; }
171   use_iterator       use_begin()       { return use_iterator(UseList); }
172   use_const_iterator use_begin() const { return use_const_iterator(UseList); }
173   use_iterator       use_end()         { return use_iterator(0);   }
174   use_const_iterator use_end()   const { return use_const_iterator(0);   }
175   User              *use_back()        { return *use_begin(); }
176   const User        *use_back()  const { return *use_begin(); }
177
178   /// hasOneUse - Return true if there is exactly one user of this value.  This
179   /// is specialized because it is a common request and does not require
180   /// traversing the whole use list.
181   ///
182   bool hasOneUse() const {
183     use_const_iterator I = use_begin(), E = use_end();
184     if (I == E) return false;
185     return ++I == E;
186   }
187
188   /// hasNUses - Return true if this Value has exactly N users.
189   ///
190   bool hasNUses(unsigned N) const;
191
192   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
193   /// logically equivalent to getNumUses() >= N.
194   ///
195   bool hasNUsesOrMore(unsigned N) const;
196
197   bool isUsedInBasicBlock(const BasicBlock *BB) const;
198
199   /// getNumUses - This method computes the number of uses of this Value.  This
200   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasMoreThanNUses
201   /// to check for specific values.
202   unsigned getNumUses() const;
203
204   /// addUse - This method should only be used by the Use class.
205   ///
206   void addUse(Use &U) { U.addToList(&UseList); }
207
208   /// An enumeration for keeping track of the concrete subclass of Value that
209   /// is actually instantiated. Values of this enumeration are kept in the 
210   /// Value classes SubclassID field. They are used for concrete type
211   /// identification.
212   enum ValueTy {
213     ArgumentVal,              // This is an instance of Argument
214     BasicBlockVal,            // This is an instance of BasicBlock
215     FunctionVal,              // This is an instance of Function
216     GlobalAliasVal,           // This is an instance of GlobalAlias
217     GlobalVariableVal,        // This is an instance of GlobalVariable
218     UndefValueVal,            // This is an instance of UndefValue
219     ConstantExprVal,          // This is an instance of ConstantExpr
220     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateNull
221     ConstantIntVal,           // This is an instance of ConstantInt
222     ConstantFPVal,            // This is an instance of ConstantFP
223     ConstantArrayVal,         // This is an instance of ConstantArray
224     ConstantStructVal,        // This is an instance of ConstantStruct
225     ConstantVectorVal,        // This is an instance of ConstantVector
226     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
227     MDNodeVal,                // This is an instance of MDNode
228     MDStringVal,              // This is an instance of MDString
229     InlineAsmVal,             // This is an instance of InlineAsm
230     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
231     InstructionVal,           // This is an instance of Instruction
232     
233     // Markers:
234     ConstantFirstVal = FunctionVal,
235     ConstantLastVal  = ConstantPointerNullVal
236   };
237
238   /// getValueID - Return an ID for the concrete type of this object.  This is
239   /// used to implement the classof checks.  This should not be used for any
240   /// other purpose, as the values may change as LLVM evolves.  Also, note that
241   /// for instructions, the Instruction's opcode is added to InstructionVal. So
242   /// this means three things:
243   /// # there is no value with code InstructionVal (no opcode==0).
244   /// # there are more possible values for the value type than in ValueTy enum.
245   /// # the InstructionVal enumerator must be the highest valued enumerator in
246   ///   the ValueTy enum.
247   unsigned getValueID() const {
248     return SubclassID;
249   }
250
251   // Methods for support type inquiry through isa, cast, and dyn_cast:
252   static inline bool classof(const Value *) {
253     return true; // Values are always values.
254   }
255
256   /// getRawType - This should only be used to implement the vmcore library.
257   ///
258   const Type *getRawType() const { return VTy.getRawType(); }
259
260   /// stripPointerCasts - This method strips off any unneeded pointer
261   /// casts from the specified value, returning the original uncasted value.
262   /// Note that the returned value has pointer type if the specified value does.
263   Value *stripPointerCasts();
264   const Value *stripPointerCasts() const {
265     return const_cast<Value*>(this)->stripPointerCasts();
266   }
267
268   /// getUnderlyingObject - This method strips off any GEP address adjustments
269   /// and pointer casts from the specified value, returning the original object
270   /// being addressed.  Note that the returned value has pointer type if the
271   /// specified value does.
272   Value *getUnderlyingObject();
273   const Value *getUnderlyingObject() const {
274     return const_cast<Value*>(this)->getUnderlyingObject();
275   }
276   
277   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
278   /// return the value in the PHI node corresponding to PredBB.  If not, return
279   /// ourself.  This is useful if you want to know the value something has in a
280   /// predecessor block.
281   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
282
283   const Value *DoPHITranslation(const BasicBlock *CurBB,
284                                 const BasicBlock *PredBB) const{
285     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
286   }
287 };
288
289 inline std::ostream &operator<<(std::ostream &OS, const Value &V) {
290   V.print(OS);
291   return OS;
292 }
293 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
294   V.print(OS);
295   return OS;
296 }
297   
298 void Use::set(Value *V) {
299   if (Val) removeFromList();
300   Val = V;
301   if (V) V->addUse(*this);
302 }
303
304
305 // isa - Provide some specializations of isa so that we don't have to include
306 // the subtype header files to test to see if the value is a subclass...
307 //
308 template <> inline bool isa_impl<Constant, Value>(const Value &Val) {
309   return Val.getValueID() >= Value::ConstantFirstVal &&
310          Val.getValueID() <= Value::ConstantLastVal;
311 }
312 template <> inline bool isa_impl<Argument, Value>(const Value &Val) {
313   return Val.getValueID() == Value::ArgumentVal;
314 }
315 template <> inline bool isa_impl<InlineAsm, Value>(const Value &Val) {
316   return Val.getValueID() == Value::InlineAsmVal;
317 }
318 template <> inline bool isa_impl<Instruction, Value>(const Value &Val) {
319   return Val.getValueID() >= Value::InstructionVal;
320 }
321 template <> inline bool isa_impl<BasicBlock, Value>(const Value &Val) {
322   return Val.getValueID() == Value::BasicBlockVal;
323 }
324 template <> inline bool isa_impl<Function, Value>(const Value &Val) {
325   return Val.getValueID() == Value::FunctionVal;
326 }
327 template <> inline bool isa_impl<GlobalVariable, Value>(const Value &Val) {
328   return Val.getValueID() == Value::GlobalVariableVal;
329 }
330 template <> inline bool isa_impl<GlobalAlias, Value>(const Value &Val) {
331   return Val.getValueID() == Value::GlobalAliasVal;
332 }
333 template <> inline bool isa_impl<GlobalValue, Value>(const Value &Val) {
334   return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
335          isa<GlobalAlias>(Val);
336 }
337   
338   
339 // Value* is only 4-byte aligned.
340 template<>
341 class PointerLikeTypeTraits<Value*> {
342   typedef Value* PT;
343 public:
344   static inline void *getAsVoidPointer(PT P) { return P; }
345   static inline PT getFromVoidPointer(void *P) {
346     return static_cast<PT>(P);
347   }
348   enum { NumLowBitsAvailable = 2 };
349 };
350
351 } // End llvm namespace
352
353 #endif