[C++11] More 'nullptr' conversion or in some cases just using a boolean check instead...
[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,
207                       const Module *M = nullptr) const;
208
209   /// All values are typed, get the type of this value.
210   ///
211   Type *getType() const { return VTy; }
212
213   /// All values hold a context through their type.
214   LLVMContext &getContext() const;
215
216   // All values can potentially be named.
217   bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
218   ValueName *getValueName() const { return Name; }
219   void setValueName(ValueName *VN) { Name = VN; }
220   
221   /// getName() - Return a constant reference to the value's name. This is cheap
222   /// and guaranteed to return the same reference as long as the value is not
223   /// modified.
224   StringRef getName() const;
225
226   /// setName() - Change the name of the value, choosing a new unique name if
227   /// the provided name is taken.
228   ///
229   /// \param Name The new name; or "" if the value's name should be removed.
230   void setName(const Twine &Name);
231
232   
233   /// takeName - transfer the name from V to this value, setting V's name to
234   /// empty.  It is an error to call V->takeName(V). 
235   void takeName(Value *V);
236
237   /// replaceAllUsesWith - Go through the uses list for this definition and make
238   /// each use point to "V" instead of "this".  After this completes, 'this's
239   /// use list is guaranteed to be empty.
240   ///
241   void replaceAllUsesWith(Value *V);
242
243   //----------------------------------------------------------------------
244   // Methods for handling the chain of uses of this Value.
245   //
246   bool               use_empty() const { return UseList == nullptr; }
247
248   typedef use_iterator_impl<Use>       use_iterator;
249   typedef use_iterator_impl<const Use> const_use_iterator;
250   use_iterator       use_begin()       { return use_iterator(UseList); }
251   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
252   use_iterator       use_end()         { return use_iterator();   }
253   const_use_iterator use_end()   const { return const_use_iterator();   }
254   iterator_range<use_iterator> uses() {
255     return iterator_range<use_iterator>(use_begin(), use_end());
256   }
257   iterator_range<const_use_iterator> uses() const {
258     return iterator_range<const_use_iterator>(use_begin(), use_end());
259   }
260
261   typedef user_iterator_impl<User>       user_iterator;
262   typedef user_iterator_impl<const User> const_user_iterator;
263   user_iterator       user_begin()       { return user_iterator(UseList); }
264   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
265   user_iterator       user_end()         { return user_iterator();   }
266   const_user_iterator user_end()   const { return const_user_iterator();   }
267   User               *user_back()        { return *user_begin(); }
268   const User         *user_back()  const { return *user_begin(); }
269   iterator_range<user_iterator> users() {
270     return iterator_range<user_iterator>(user_begin(), user_end());
271   }
272   iterator_range<const_user_iterator> users() const {
273     return iterator_range<const_user_iterator>(user_begin(), user_end());
274   }
275
276   /// hasOneUse - Return true if there is exactly one user of this value.  This
277   /// is specialized because it is a common request and does not require
278   /// traversing the whole use list.
279   ///
280   bool hasOneUse() const {
281     const_use_iterator I = use_begin(), E = use_end();
282     if (I == E) return false;
283     return ++I == E;
284   }
285
286   /// hasNUses - Return true if this Value has exactly N users.
287   ///
288   bool hasNUses(unsigned N) const;
289
290   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
291   /// logically equivalent to getNumUses() >= N.
292   ///
293   bool hasNUsesOrMore(unsigned N) const;
294
295   bool isUsedInBasicBlock(const BasicBlock *BB) const;
296
297   /// getNumUses - This method computes the number of uses of this Value.  This
298   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasNUsesOrMore
299   /// to check for specific values.
300   unsigned getNumUses() const;
301
302   /// addUse - This method should only be used by the Use class.
303   ///
304   void addUse(Use &U) { U.addToList(&UseList); }
305
306   /// An enumeration for keeping track of the concrete subclass of Value that
307   /// is actually instantiated. Values of this enumeration are kept in the 
308   /// Value classes SubclassID field. They are used for concrete type
309   /// identification.
310   enum ValueTy {
311     ArgumentVal,              // This is an instance of Argument
312     BasicBlockVal,            // This is an instance of BasicBlock
313     FunctionVal,              // This is an instance of Function
314     GlobalAliasVal,           // This is an instance of GlobalAlias
315     GlobalVariableVal,        // This is an instance of GlobalVariable
316     UndefValueVal,            // This is an instance of UndefValue
317     BlockAddressVal,          // This is an instance of BlockAddress
318     ConstantExprVal,          // This is an instance of ConstantExpr
319     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
320     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
321     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
322     ConstantIntVal,           // This is an instance of ConstantInt
323     ConstantFPVal,            // This is an instance of ConstantFP
324     ConstantArrayVal,         // This is an instance of ConstantArray
325     ConstantStructVal,        // This is an instance of ConstantStruct
326     ConstantVectorVal,        // This is an instance of ConstantVector
327     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
328     MDNodeVal,                // This is an instance of MDNode
329     MDStringVal,              // This is an instance of MDString
330     InlineAsmVal,             // This is an instance of InlineAsm
331     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
332     FixedStackPseudoSourceValueVal, // This is an instance of 
333                                     // FixedStackPseudoSourceValue
334     InstructionVal,           // This is an instance of Instruction
335     // Enum values starting at InstructionVal are used for Instructions;
336     // don't add new values here!
337
338     // Markers:
339     ConstantFirstVal = FunctionVal,
340     ConstantLastVal  = ConstantPointerNullVal
341   };
342
343   /// getValueID - Return an ID for the concrete type of this object.  This is
344   /// used to implement the classof checks.  This should not be used for any
345   /// other purpose, as the values may change as LLVM evolves.  Also, note that
346   /// for instructions, the Instruction's opcode is added to InstructionVal. So
347   /// this means three things:
348   /// # there is no value with code InstructionVal (no opcode==0).
349   /// # there are more possible values for the value type than in ValueTy enum.
350   /// # the InstructionVal enumerator must be the highest valued enumerator in
351   ///   the ValueTy enum.
352   unsigned getValueID() const {
353     return SubclassID;
354   }
355
356   /// getRawSubclassOptionalData - Return the raw optional flags value
357   /// contained in this value. This should only be used when testing two
358   /// Values for equivalence.
359   unsigned getRawSubclassOptionalData() const {
360     return SubclassOptionalData;
361   }
362
363   /// clearSubclassOptionalData - Clear the optional flags contained in
364   /// this value.
365   void clearSubclassOptionalData() {
366     SubclassOptionalData = 0;
367   }
368
369   /// hasSameSubclassOptionalData - Test whether the optional flags contained
370   /// in this value are equal to the optional flags in the given value.
371   bool hasSameSubclassOptionalData(const Value *V) const {
372     return SubclassOptionalData == V->SubclassOptionalData;
373   }
374
375   /// intersectOptionalDataWith - Clear any optional flags in this value
376   /// that are not also set in the given value.
377   void intersectOptionalDataWith(const Value *V) {
378     SubclassOptionalData &= V->SubclassOptionalData;
379   }
380
381   /// hasValueHandle - Return true if there is a value handle associated with
382   /// this value.
383   bool hasValueHandle() const { return HasValueHandle; }
384
385   /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
386   /// from the specified value, returning the original uncasted value.
387   ///
388   /// If this is called on a non-pointer value, it returns 'this'.
389   Value *stripPointerCasts();
390   const Value *stripPointerCasts() const {
391     return const_cast<Value*>(this)->stripPointerCasts();
392   }
393
394   /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
395   /// specified value, returning the original uncasted value.
396   ///
397   /// If this is called on a non-pointer value, it returns 'this'.
398   Value *stripPointerCastsNoFollowAliases();
399   const Value *stripPointerCastsNoFollowAliases() const {
400     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
401   }
402
403   /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
404   /// specified value, returning the original pointer value.
405   ///
406   /// If this is called on a non-pointer value, it returns 'this'.
407   Value *stripInBoundsConstantOffsets();
408   const Value *stripInBoundsConstantOffsets() const {
409     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
410   }
411
412   /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
413   /// the constant offset stripped.
414   ///
415   /// Stores the resulting constant offset stripped into the APInt provided.
416   /// The provided APInt will be extended or truncated as needed to be the
417   /// correct bitwidth for an offset of this pointer type.
418   ///
419   /// If this is called on a non-pointer value, it returns 'this'.
420   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
421                                                    APInt &Offset);
422   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
423                                                          APInt &Offset) const {
424     return const_cast<Value *>(this)
425         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
426   }
427
428   /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
429   /// the specified value, returning the original pointer value.
430   ///
431   /// If this is called on a non-pointer value, it returns 'this'.
432   Value *stripInBoundsOffsets();
433   const Value *stripInBoundsOffsets() const {
434     return const_cast<Value*>(this)->stripInBoundsOffsets();
435   }
436
437   /// isDereferenceablePointer - Test if this value is always a pointer to
438   /// allocated and suitably aligned memory for a simple load or store.
439   bool isDereferenceablePointer() const;
440   
441   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
442   /// return the value in the PHI node corresponding to PredBB.  If not, return
443   /// ourself.  This is useful if you want to know the value something has in a
444   /// predecessor block.
445   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
446
447   const Value *DoPHITranslation(const BasicBlock *CurBB,
448                                 const BasicBlock *PredBB) const{
449     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
450   }
451   
452   /// MaximumAlignment - This is the greatest alignment value supported by
453   /// load, store, and alloca instructions, and global values.
454   static const unsigned MaximumAlignment = 1u << 29;
455   
456   /// mutateType - Mutate the type of this Value to be of the specified type.
457   /// Note that this is an extremely dangerous operation which can create
458   /// completely invalid IR very easily.  It is strongly recommended that you
459   /// recreate IR objects with the right types instead of mutating them in
460   /// place.
461   void mutateType(Type *Ty) {
462     VTy = Ty;
463   }
464   
465 protected:
466   unsigned short getSubclassDataFromValue() const { return SubclassData; }
467   void setValueSubclassData(unsigned short D) { SubclassData = D; }
468 };
469
470 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
471   V.print(OS);
472   return OS;
473 }
474   
475 void Use::set(Value *V) {
476   if (Val) removeFromList();
477   Val = V;
478   if (V) V->addUse(*this);
479 }
480
481
482 // isa - Provide some specializations of isa so that we don't have to include
483 // the subtype header files to test to see if the value is a subclass...
484 //
485 template <> struct isa_impl<Constant, Value> {
486   static inline bool doit(const Value &Val) {
487     return Val.getValueID() >= Value::ConstantFirstVal &&
488       Val.getValueID() <= Value::ConstantLastVal;
489   }
490 };
491
492 template <> struct isa_impl<Argument, Value> {
493   static inline bool doit (const Value &Val) {
494     return Val.getValueID() == Value::ArgumentVal;
495   }
496 };
497
498 template <> struct isa_impl<InlineAsm, Value> { 
499   static inline bool doit(const Value &Val) {
500     return Val.getValueID() == Value::InlineAsmVal;
501   }
502 };
503
504 template <> struct isa_impl<Instruction, Value> { 
505   static inline bool doit(const Value &Val) {
506     return Val.getValueID() >= Value::InstructionVal;
507   }
508 };
509
510 template <> struct isa_impl<BasicBlock, Value> { 
511   static inline bool doit(const Value &Val) {
512     return Val.getValueID() == Value::BasicBlockVal;
513   }
514 };
515
516 template <> struct isa_impl<Function, Value> { 
517   static inline bool doit(const Value &Val) {
518     return Val.getValueID() == Value::FunctionVal;
519   }
520 };
521
522 template <> struct isa_impl<GlobalVariable, Value> { 
523   static inline bool doit(const Value &Val) {
524     return Val.getValueID() == Value::GlobalVariableVal;
525   }
526 };
527
528 template <> struct isa_impl<GlobalAlias, Value> { 
529   static inline bool doit(const Value &Val) {
530     return Val.getValueID() == Value::GlobalAliasVal;
531   }
532 };
533
534 template <> struct isa_impl<GlobalValue, Value> { 
535   static inline bool doit(const Value &Val) {
536     return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
537       isa<GlobalAlias>(Val);
538   }
539 };
540
541 template <> struct isa_impl<MDNode, Value> { 
542   static inline bool doit(const Value &Val) {
543     return Val.getValueID() == Value::MDNodeVal;
544   }
545 };
546   
547 // Value* is only 4-byte aligned.
548 template<>
549 class PointerLikeTypeTraits<Value*> {
550   typedef Value* PT;
551 public:
552   static inline void *getAsVoidPointer(PT P) { return P; }
553   static inline PT getFromVoidPointer(void *P) {
554     return static_cast<PT>(P);
555   }
556   enum { NumLowBitsAvailable = 2 };
557 };
558
559 // Create wrappers for C Binding types (see CBindingWrapping.h).
560 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
561
562 /* Specialized opaque value conversions.
563  */ 
564 inline Value **unwrap(LLVMValueRef *Vals) {
565   return reinterpret_cast<Value**>(Vals);
566 }
567
568 template<typename T>
569 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
570 #ifdef DEBUG
571   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
572     cast<T>(*I);
573 #endif
574   (void)Length;
575   return reinterpret_cast<T**>(Vals);
576 }
577
578 inline LLVMValueRef *wrap(const Value **Vals) {
579   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
580 }
581
582 } // End llvm namespace
583
584 #endif