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