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