c002cea94a7dddab76bb650ebd09a635458f7218
[oota-llvm.git] / include / llvm / IR / 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_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
16
17 #include "llvm-c/Core.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
23
24 namespace llvm {
25
26 class APInt;
27 class Argument;
28 class AssemblyAnnotationWriter;
29 class BasicBlock;
30 class Constant;
31 class DataLayout;
32 class Function;
33 class GlobalAlias;
34 class GlobalValue;
35 class GlobalVariable;
36 class InlineAsm;
37 class Instruction;
38 class LLVMContext;
39 class MDNode;
40 class Module;
41 class StringRef;
42 class Twine;
43 class Type;
44 class ValueHandleBase;
45 class ValueSymbolTable;
46 class raw_ostream;
47
48 template<typename ValueTy> class StringMapEntry;
49 typedef StringMapEntry<Value*> ValueName;
50
51 //===----------------------------------------------------------------------===//
52 //                                 Value Class
53 //===----------------------------------------------------------------------===//
54
55 /// This is a very important LLVM class. It is the base class of all values 
56 /// computed by a program that may be used as operands to other values. Value is
57 /// the super class of other important classes such as Instruction and Function.
58 /// All Values have a Type. Type is not a subclass of Value. Some values can
59 /// have a name and they belong to some Module.  Setting the name on the Value
60 /// automatically updates the module's symbol table.
61 ///
62 /// Every value has a "use list" that keeps track of which other Values are
63 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
64 /// objects that watch it and listen to RAUW and Destroy events.  See
65 /// llvm/IR/ValueHandle.h for details.
66 ///
67 /// @brief LLVM Value Representation
68 class Value {
69   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
70   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
71 protected:
72   /// SubclassOptionalData - This member is similar to SubclassData, however it
73   /// is for holding information which may be used to aid optimization, but
74   /// which may be cleared to zero without affecting conservative
75   /// interpretation.
76   unsigned char SubclassOptionalData : 7;
77
78 private:
79   template <typename UseT> // UseT == 'Use' or 'const Use'
80   class use_iterator_impl
81       : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
82     typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
83
84     UseT *U;
85     explicit use_iterator_impl(UseT *u) : U(u) {}
86     friend class Value;
87
88   public:
89     typedef typename super::reference reference;
90     typedef typename super::pointer pointer;
91
92     use_iterator_impl() : U() {}
93
94     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
95     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
96
97     use_iterator_impl &operator++() { // Preincrement
98       assert(U && "Cannot increment end iterator!");
99       U = U->getNext();
100       return *this;
101     }
102     use_iterator_impl operator++(int) { // Postincrement
103       auto tmp = *this;
104       ++*this;
105       return tmp;
106     }
107
108     UseT &operator*() const {
109       assert(U && "Cannot dereference end iterator!");
110       return *U;
111     }
112
113     UseT *operator->() const { return &operator*(); }
114
115     operator use_iterator_impl<const UseT>() const {
116       return use_iterator_impl<const UseT>(U);
117     }
118   };
119
120   template <typename UserTy> // UserTy == 'User' or 'const User'
121   class user_iterator_impl
122       : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
123     typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
124
125     use_iterator_impl<Use> UI;
126     explicit user_iterator_impl(Use *U) : UI(U) {}
127     friend class Value;
128
129   public:
130     typedef typename super::reference reference;
131     typedef typename super::pointer pointer;
132
133     user_iterator_impl() {}
134
135     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
136     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
137
138     /// \brief Returns true if this iterator is equal to user_end() on the value.
139     bool atEnd() const { return *this == user_iterator_impl(); }
140
141     user_iterator_impl &operator++() { // Preincrement
142       ++UI;
143       return *this;
144     }
145     user_iterator_impl operator++(int) { // Postincrement
146       auto tmp = *this;
147       ++*this;
148       return tmp;
149     }
150
151     // Retrieve a pointer to the current User.
152     UserTy *operator*() const {
153       return UI->getUser();
154     }
155
156     UserTy *operator->() const { return operator*(); }
157
158     operator user_iterator_impl<const UserTy>() const {
159       return user_iterator_impl<const UserTy>(*UI);
160     }
161
162     Use &getUse() const { return *UI; }
163
164     /// \brief Return the operand # of this use in its User.
165     /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
166     unsigned getOperandNo() const { return UI->getOperandNo(); }
167   };
168
169   /// SubclassData - This member is defined by this class, but is not used for
170   /// anything.  Subclasses can use it to hold whatever state they find useful.
171   /// This field is initialized to zero by the ctor.
172   unsigned short SubclassData;
173
174   Type *VTy;
175   Use *UseList;
176
177   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
178   friend class ValueHandleBase;
179   ValueName *Name;
180
181   void operator=(const Value &) LLVM_DELETED_FUNCTION;
182   Value(const Value &) LLVM_DELETED_FUNCTION;
183
184 protected:
185   /// printCustom - Value subclasses can override this to implement custom
186   /// printing behavior.
187   virtual void printCustom(raw_ostream &O) const;
188
189   Value(Type *Ty, unsigned scid);
190 public:
191   virtual ~Value();
192
193   /// dump - Support for debugging, callable in GDB: V->dump()
194   //
195   void dump() const;
196
197   /// print - Implement operator<< on Value.
198   ///
199   void print(raw_ostream &O) const;
200
201   /// \brief Print the name of this Value out to the specified raw_ostream.
202   /// This is useful when you just want to print 'int %reg126', not the
203   /// instruction that generated it. If you specify a Module for context, then
204   /// even constanst get pretty-printed; for example, the type of a null
205   /// pointer is printed symbolically.
206   void printAsOperand(raw_ostream &O, bool PrintType = true, const Module *M = 0) const;
207
208   /// All values are typed, get the type of this value.
209   ///
210   Type *getType() const { return VTy; }
211
212   /// All values hold a context through their type.
213   LLVMContext &getContext() const;
214
215   // All values can potentially be named.
216   bool hasName() const { return Name != 0 && SubclassID != MDStringVal; }
217   ValueName *getValueName() const { return Name; }
218   void setValueName(ValueName *VN) { Name = VN; }
219   
220   /// getName() - Return a constant reference to the value's name. This is cheap
221   /// and guaranteed to return the same reference as long as the value is not
222   /// modified.
223   StringRef getName() const;
224
225   /// setName() - Change the name of the value, choosing a new unique name if
226   /// the provided name is taken.
227   ///
228   /// \param Name The new name; or "" if the value's name should be removed.
229   void setName(const Twine &Name);
230
231   
232   /// takeName - transfer the name from V to this value, setting V's name to
233   /// empty.  It is an error to call V->takeName(V). 
234   void takeName(Value *V);
235
236   /// replaceAllUsesWith - Go through the uses list for this definition and make
237   /// each use point to "V" instead of "this".  After this completes, 'this's
238   /// use list is guaranteed to be empty.
239   ///
240   void replaceAllUsesWith(Value *V);
241
242   //----------------------------------------------------------------------
243   // Methods for handling the chain of uses of this Value.
244   //
245   bool               use_empty() const { return UseList == 0; }
246
247   typedef use_iterator_impl<Use>       use_iterator;
248   typedef use_iterator_impl<const Use> const_use_iterator;
249   use_iterator       use_begin()       { return use_iterator(UseList); }
250   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
251   use_iterator       use_end()         { return use_iterator();   }
252   const_use_iterator use_end()   const { return const_use_iterator();   }
253   iterator_range<use_iterator> uses() {
254     return iterator_range<use_iterator>(use_begin(), use_end());
255   }
256   iterator_range<const_use_iterator> uses() const {
257     return iterator_range<const_use_iterator>(use_begin(), use_end());
258   }
259
260   typedef user_iterator_impl<User>       user_iterator;
261   typedef user_iterator_impl<const User> const_user_iterator;
262   user_iterator       user_begin()       { return user_iterator(UseList); }
263   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
264   user_iterator       user_end()         { return user_iterator();   }
265   const_user_iterator user_end()   const { return const_user_iterator();   }
266   User               *user_back()        { return *user_begin(); }
267   const User         *user_back()  const { return *user_begin(); }
268   iterator_range<user_iterator> users() {
269     return iterator_range<user_iterator>(user_begin(), user_end());
270   }
271   iterator_range<const_user_iterator> users() const {
272     return iterator_range<const_user_iterator>(user_begin(), user_end());
273   }
274
275   /// hasOneUse - Return true if there is exactly one user of this value.  This
276   /// is specialized because it is a common request and does not require
277   /// traversing the whole use list.
278   ///
279   bool hasOneUse() const {
280     const_use_iterator I = use_begin(), E = use_end();
281     if (I == E) return false;
282     return ++I == E;
283   }
284
285   /// hasNUses - Return true if this Value has exactly N users.
286   ///
287   bool hasNUses(unsigned N) const;
288
289   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
290   /// logically equivalent to getNumUses() >= N.
291   ///
292   bool hasNUsesOrMore(unsigned N) const;
293
294   bool isUsedInBasicBlock(const BasicBlock *BB) const;
295
296   /// getNumUses - This method computes the number of uses of this Value.  This
297   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasNUsesOrMore
298   /// to check for specific values.
299   unsigned getNumUses() const;
300
301   /// addUse - This method should only be used by the Use class.
302   ///
303   void addUse(Use &U) { U.addToList(&UseList); }
304
305   /// An enumeration for keeping track of the concrete subclass of Value that
306   /// is actually instantiated. Values of this enumeration are kept in the 
307   /// Value classes SubclassID field. They are used for concrete type
308   /// identification.
309   enum ValueTy {
310     ArgumentVal,              // This is an instance of Argument
311     BasicBlockVal,            // This is an instance of BasicBlock
312     FunctionVal,              // This is an instance of Function
313     GlobalAliasVal,           // This is an instance of GlobalAlias
314     GlobalVariableVal,        // This is an instance of GlobalVariable
315     UndefValueVal,            // This is an instance of UndefValue
316     BlockAddressVal,          // This is an instance of BlockAddress
317     ConstantExprVal,          // This is an instance of ConstantExpr
318     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
319     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
320     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
321     ConstantIntVal,           // This is an instance of ConstantInt
322     ConstantFPVal,            // This is an instance of ConstantFP
323     ConstantArrayVal,         // This is an instance of ConstantArray
324     ConstantStructVal,        // This is an instance of ConstantStruct
325     ConstantVectorVal,        // This is an instance of ConstantVector
326     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
327     MDNodeVal,                // This is an instance of MDNode
328     MDStringVal,              // This is an instance of MDString
329     InlineAsmVal,             // This is an instance of InlineAsm
330     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
331     FixedStackPseudoSourceValueVal, // This is an instance of 
332                                     // FixedStackPseudoSourceValue
333     InstructionVal,           // This is an instance of Instruction
334     // Enum values starting at InstructionVal are used for Instructions;
335     // don't add new values here!
336
337     // Markers:
338     ConstantFirstVal = FunctionVal,
339     ConstantLastVal  = ConstantPointerNullVal
340   };
341
342   /// getValueID - Return an ID for the concrete type of this object.  This is
343   /// used to implement the classof checks.  This should not be used for any
344   /// other purpose, as the values may change as LLVM evolves.  Also, note that
345   /// for instructions, the Instruction's opcode is added to InstructionVal. So
346   /// this means three things:
347   /// # there is no value with code InstructionVal (no opcode==0).
348   /// # there are more possible values for the value type than in ValueTy enum.
349   /// # the InstructionVal enumerator must be the highest valued enumerator in
350   ///   the ValueTy enum.
351   unsigned getValueID() const {
352     return SubclassID;
353   }
354
355   /// getRawSubclassOptionalData - Return the raw optional flags value
356   /// contained in this value. This should only be used when testing two
357   /// Values for equivalence.
358   unsigned getRawSubclassOptionalData() const {
359     return SubclassOptionalData;
360   }
361
362   /// clearSubclassOptionalData - Clear the optional flags contained in
363   /// this value.
364   void clearSubclassOptionalData() {
365     SubclassOptionalData = 0;
366   }
367
368   /// hasSameSubclassOptionalData - Test whether the optional flags contained
369   /// in this value are equal to the optional flags in the given value.
370   bool hasSameSubclassOptionalData(const Value *V) const {
371     return SubclassOptionalData == V->SubclassOptionalData;
372   }
373
374   /// intersectOptionalDataWith - Clear any optional flags in this value
375   /// that are not also set in the given value.
376   void intersectOptionalDataWith(const Value *V) {
377     SubclassOptionalData &= V->SubclassOptionalData;
378   }
379
380   /// hasValueHandle - Return true if there is a value handle associated with
381   /// this value.
382   bool hasValueHandle() const { return HasValueHandle; }
383
384   /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
385   /// from the specified value, returning the original uncasted value.
386   ///
387   /// If this is called on a non-pointer value, it returns 'this'.
388   Value *stripPointerCasts();
389   const Value *stripPointerCasts() const {
390     return const_cast<Value*>(this)->stripPointerCasts();
391   }
392
393   /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
394   /// specified value, returning the original uncasted value.
395   ///
396   /// If this is called on a non-pointer value, it returns 'this'.
397   Value *stripPointerCastsNoFollowAliases();
398   const Value *stripPointerCastsNoFollowAliases() const {
399     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
400   }
401
402   /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
403   /// specified value, returning the original pointer value.
404   ///
405   /// If this is called on a non-pointer value, it returns 'this'.
406   Value *stripInBoundsConstantOffsets();
407   const Value *stripInBoundsConstantOffsets() const {
408     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
409   }
410
411   /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
412   /// the constant offset stripped.
413   ///
414   /// Stores the resulting constant offset stripped into the APInt provided.
415   /// The provided APInt will be extended or truncated as needed to be the
416   /// correct bitwidth for an offset of this pointer type.
417   ///
418   /// If this is called on a non-pointer value, it returns 'this'.
419   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
420                                                    APInt &Offset);
421   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
422                                                          APInt &Offset) const {
423     return const_cast<Value *>(this)
424         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
425   }
426
427   /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
428   /// the specified value, returning the original pointer value.
429   ///
430   /// If this is called on a non-pointer value, it returns 'this'.
431   Value *stripInBoundsOffsets();
432   const Value *stripInBoundsOffsets() const {
433     return const_cast<Value*>(this)->stripInBoundsOffsets();
434   }
435
436   /// isDereferenceablePointer - Test if this value is always a pointer to
437   /// allocated and suitably aligned memory for a simple load or store.
438   bool isDereferenceablePointer() const;
439   
440   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
441   /// return the value in the PHI node corresponding to PredBB.  If not, return
442   /// ourself.  This is useful if you want to know the value something has in a
443   /// predecessor block.
444   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
445
446   const Value *DoPHITranslation(const BasicBlock *CurBB,
447                                 const BasicBlock *PredBB) const{
448     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
449   }
450   
451   /// MaximumAlignment - This is the greatest alignment value supported by
452   /// load, store, and alloca instructions, and global values.
453   static const unsigned MaximumAlignment = 1u << 29;
454   
455   /// mutateType - Mutate the type of this Value to be of the specified type.
456   /// Note that this is an extremely dangerous operation which can create
457   /// completely invalid IR very easily.  It is strongly recommended that you
458   /// recreate IR objects with the right types instead of mutating them in
459   /// place.
460   void mutateType(Type *Ty) {
461     VTy = Ty;
462   }
463   
464 protected:
465   unsigned short getSubclassDataFromValue() const { return SubclassData; }
466   void setValueSubclassData(unsigned short D) { SubclassData = D; }
467 };
468
469 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
470   V.print(OS);
471   return OS;
472 }
473   
474 void Use::set(Value *V) {
475   if (Val) removeFromList();
476   Val = V;
477   if (V) V->addUse(*this);
478 }
479
480
481 // isa - Provide some specializations of isa so that we don't have to include
482 // the subtype header files to test to see if the value is a subclass...
483 //
484 template <> struct isa_impl<Constant, Value> {
485   static inline bool doit(const Value &Val) {
486     return Val.getValueID() >= Value::ConstantFirstVal &&
487       Val.getValueID() <= Value::ConstantLastVal;
488   }
489 };
490
491 template <> struct isa_impl<Argument, Value> {
492   static inline bool doit (const Value &Val) {
493     return Val.getValueID() == Value::ArgumentVal;
494   }
495 };
496
497 template <> struct isa_impl<InlineAsm, Value> { 
498   static inline bool doit(const Value &Val) {
499     return Val.getValueID() == Value::InlineAsmVal;
500   }
501 };
502
503 template <> struct isa_impl<Instruction, Value> { 
504   static inline bool doit(const Value &Val) {
505     return Val.getValueID() >= Value::InstructionVal;
506   }
507 };
508
509 template <> struct isa_impl<BasicBlock, Value> { 
510   static inline bool doit(const Value &Val) {
511     return Val.getValueID() == Value::BasicBlockVal;
512   }
513 };
514
515 template <> struct isa_impl<Function, Value> { 
516   static inline bool doit(const Value &Val) {
517     return Val.getValueID() == Value::FunctionVal;
518   }
519 };
520
521 template <> struct isa_impl<GlobalVariable, Value> { 
522   static inline bool doit(const Value &Val) {
523     return Val.getValueID() == Value::GlobalVariableVal;
524   }
525 };
526
527 template <> struct isa_impl<GlobalAlias, Value> { 
528   static inline bool doit(const Value &Val) {
529     return Val.getValueID() == Value::GlobalAliasVal;
530   }
531 };
532
533 template <> struct isa_impl<GlobalValue, Value> { 
534   static inline bool doit(const Value &Val) {
535     return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
536       isa<GlobalAlias>(Val);
537   }
538 };
539
540 template <> struct isa_impl<MDNode, Value> { 
541   static inline bool doit(const Value &Val) {
542     return Val.getValueID() == Value::MDNodeVal;
543   }
544 };
545   
546 // Value* is only 4-byte aligned.
547 template<>
548 class PointerLikeTypeTraits<Value*> {
549   typedef Value* PT;
550 public:
551   static inline void *getAsVoidPointer(PT P) { return P; }
552   static inline PT getFromVoidPointer(void *P) {
553     return static_cast<PT>(P);
554   }
555   enum { NumLowBitsAvailable = 2 };
556 };
557
558 // Create wrappers for C Binding types (see CBindingWrapping.h).
559 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
560
561 /* Specialized opaque value conversions.
562  */ 
563 inline Value **unwrap(LLVMValueRef *Vals) {
564   return reinterpret_cast<Value**>(Vals);
565 }
566
567 template<typename T>
568 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
569 #ifdef DEBUG
570   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
571     cast<T>(*I);
572 #endif
573   (void)Length;
574   return reinterpret_cast<T**>(Vals);
575 }
576
577 inline LLVMValueRef *wrap(const Value **Vals) {
578   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
579 }
580
581 } // End llvm namespace
582
583 #endif