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