LLVM API Documentation

Value.h
Go to the documentation of this file.
00001 //===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file declares the Value class. 
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_IR_VALUE_H
00015 #define LLVM_IR_VALUE_H
00016 
00017 #include "llvm-c/Core.h"
00018 #include "llvm/ADT/iterator_range.h"
00019 #include "llvm/IR/Use.h"
00020 #include "llvm/Support/CBindingWrapping.h"
00021 #include "llvm/Support/Casting.h"
00022 #include "llvm/Support/Compiler.h"
00023 
00024 namespace llvm {
00025 
00026 class APInt;
00027 class Argument;
00028 class AssemblyAnnotationWriter;
00029 class BasicBlock;
00030 class Constant;
00031 class DataLayout;
00032 class Function;
00033 class GlobalAlias;
00034 class GlobalValue;
00035 class GlobalVariable;
00036 class InlineAsm;
00037 class Instruction;
00038 class LLVMContext;
00039 class MDNode;
00040 class Module;
00041 class StringRef;
00042 class Twine;
00043 class Type;
00044 class ValueHandleBase;
00045 class ValueSymbolTable;
00046 class raw_ostream;
00047 
00048 template<typename ValueTy> class StringMapEntry;
00049 typedef StringMapEntry<Value*> ValueName;
00050 
00051 //===----------------------------------------------------------------------===//
00052 //                                 Value Class
00053 //===----------------------------------------------------------------------===//
00054 
00055 /// This is a very important LLVM class. It is the base class of all values 
00056 /// computed by a program that may be used as operands to other values. Value is
00057 /// the super class of other important classes such as Instruction and Function.
00058 /// All Values have a Type. Type is not a subclass of Value. Some values can
00059 /// have a name and they belong to some Module.  Setting the name on the Value
00060 /// automatically updates the module's symbol table.
00061 ///
00062 /// Every value has a "use list" that keeps track of which other Values are
00063 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
00064 /// objects that watch it and listen to RAUW and Destroy events.  See
00065 /// llvm/IR/ValueHandle.h for details.
00066 ///
00067 /// @brief LLVM Value Representation
00068 class Value {
00069   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
00070   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
00071 protected:
00072   /// SubclassOptionalData - This member is similar to SubclassData, however it
00073   /// is for holding information which may be used to aid optimization, but
00074   /// which may be cleared to zero without affecting conservative
00075   /// interpretation.
00076   unsigned char SubclassOptionalData : 7;
00077 
00078 private:
00079   template <typename UseT> // UseT == 'Use' or 'const Use'
00080   class use_iterator_impl
00081       : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
00082     typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
00083 
00084     UseT *U;
00085     explicit use_iterator_impl(UseT *u) : U(u) {}
00086     friend class Value;
00087 
00088   public:
00089     typedef typename super::reference reference;
00090     typedef typename super::pointer pointer;
00091 
00092     use_iterator_impl() : U() {}
00093 
00094     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
00095     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
00096 
00097     use_iterator_impl &operator++() { // Preincrement
00098       assert(U && "Cannot increment end iterator!");
00099       U = U->getNext();
00100       return *this;
00101     }
00102     use_iterator_impl operator++(int) { // Postincrement
00103       auto tmp = *this;
00104       ++*this;
00105       return tmp;
00106     }
00107 
00108     UseT &operator*() const {
00109       assert(U && "Cannot dereference end iterator!");
00110       return *U;
00111     }
00112 
00113     UseT *operator->() const { return &operator*(); }
00114 
00115     operator use_iterator_impl<const UseT>() const {
00116       return use_iterator_impl<const UseT>(U);
00117     }
00118   };
00119 
00120   template <typename UserTy> // UserTy == 'User' or 'const User'
00121   class user_iterator_impl
00122       : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
00123     typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
00124 
00125     use_iterator_impl<Use> UI;
00126     explicit user_iterator_impl(Use *U) : UI(U) {}
00127     friend class Value;
00128 
00129   public:
00130     typedef typename super::reference reference;
00131     typedef typename super::pointer pointer;
00132 
00133     user_iterator_impl() {}
00134 
00135     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
00136     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
00137 
00138     /// \brief Returns true if this iterator is equal to user_end() on the value.
00139     bool atEnd() const { return *this == user_iterator_impl(); }
00140 
00141     user_iterator_impl &operator++() { // Preincrement
00142       ++UI;
00143       return *this;
00144     }
00145     user_iterator_impl operator++(int) { // Postincrement
00146       auto tmp = *this;
00147       ++*this;
00148       return tmp;
00149     }
00150 
00151     // Retrieve a pointer to the current User.
00152     UserTy *operator*() const {
00153       return UI->getUser();
00154     }
00155 
00156     UserTy *operator->() const { return operator*(); }
00157 
00158     operator user_iterator_impl<const UserTy>() const {
00159       return user_iterator_impl<const UserTy>(*UI);
00160     }
00161 
00162     Use &getUse() const { return *UI; }
00163 
00164     /// \brief Return the operand # of this use in its User.
00165     /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
00166     unsigned getOperandNo() const { return UI->getOperandNo(); }
00167   };
00168 
00169   /// SubclassData - This member is defined by this class, but is not used for
00170   /// anything.  Subclasses can use it to hold whatever state they find useful.
00171   /// This field is initialized to zero by the ctor.
00172   unsigned short SubclassData;
00173 
00174   Type *VTy;
00175   Use *UseList;
00176 
00177   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
00178   friend class ValueHandleBase;
00179   ValueName *Name;
00180 
00181   void operator=(const Value &) LLVM_DELETED_FUNCTION;
00182   Value(const Value &) LLVM_DELETED_FUNCTION;
00183 
00184 protected:
00185   /// printCustom - Value subclasses can override this to implement custom
00186   /// printing behavior.
00187   virtual void printCustom(raw_ostream &O) const;
00188 
00189   Value(Type *Ty, unsigned scid);
00190 public:
00191   virtual ~Value();
00192 
00193   /// dump - Support for debugging, callable in GDB: V->dump()
00194   //
00195   void dump() const;
00196 
00197   /// print - Implement operator<< on Value.
00198   ///
00199   void print(raw_ostream &O) const;
00200 
00201   /// \brief Print the name of this Value out to the specified raw_ostream.
00202   /// This is useful when you just want to print 'int %reg126', not the
00203   /// instruction that generated it. If you specify a Module for context, then
00204   /// even constanst get pretty-printed; for example, the type of a null
00205   /// pointer is printed symbolically.
00206   void printAsOperand(raw_ostream &O, bool PrintType = true,
00207                       const Module *M = nullptr) const;
00208 
00209   /// All values are typed, get the type of this value.
00210   ///
00211   Type *getType() const { return VTy; }
00212 
00213   /// All values hold a context through their type.
00214   LLVMContext &getContext() const;
00215 
00216   // All values can potentially be named.
00217   bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
00218   ValueName *getValueName() const { return Name; }
00219   void setValueName(ValueName *VN) { Name = VN; }
00220   
00221   /// getName() - Return a constant reference to the value's name. This is cheap
00222   /// and guaranteed to return the same reference as long as the value is not
00223   /// modified.
00224   StringRef getName() const;
00225 
00226   /// setName() - Change the name of the value, choosing a new unique name if
00227   /// the provided name is taken.
00228   ///
00229   /// \param Name The new name; or "" if the value's name should be removed.
00230   void setName(const Twine &Name);
00231 
00232   
00233   /// takeName - transfer the name from V to this value, setting V's name to
00234   /// empty.  It is an error to call V->takeName(V). 
00235   void takeName(Value *V);
00236 
00237   /// replaceAllUsesWith - Go through the uses list for this definition and make
00238   /// each use point to "V" instead of "this".  After this completes, 'this's
00239   /// use list is guaranteed to be empty.
00240   ///
00241   void replaceAllUsesWith(Value *V);
00242 
00243   //----------------------------------------------------------------------
00244   // Methods for handling the chain of uses of this Value.
00245   //
00246   bool               use_empty() const { return UseList == nullptr; }
00247 
00248   typedef use_iterator_impl<Use>       use_iterator;
00249   typedef use_iterator_impl<const Use> const_use_iterator;
00250   use_iterator       use_begin()       { return use_iterator(UseList); }
00251   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
00252   use_iterator       use_end()         { return use_iterator();   }
00253   const_use_iterator use_end()   const { return const_use_iterator();   }
00254   iterator_range<use_iterator> uses() {
00255     return iterator_range<use_iterator>(use_begin(), use_end());
00256   }
00257   iterator_range<const_use_iterator> uses() const {
00258     return iterator_range<const_use_iterator>(use_begin(), use_end());
00259   }
00260 
00261   typedef user_iterator_impl<User>       user_iterator;
00262   typedef user_iterator_impl<const User> const_user_iterator;
00263   user_iterator       user_begin()       { return user_iterator(UseList); }
00264   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
00265   user_iterator       user_end()         { return user_iterator();   }
00266   const_user_iterator user_end()   const { return const_user_iterator();   }
00267   User               *user_back()        { return *user_begin(); }
00268   const User         *user_back()  const { return *user_begin(); }
00269   iterator_range<user_iterator> users() {
00270     return iterator_range<user_iterator>(user_begin(), user_end());
00271   }
00272   iterator_range<const_user_iterator> users() const {
00273     return iterator_range<const_user_iterator>(user_begin(), user_end());
00274   }
00275 
00276   /// hasOneUse - Return true if there is exactly one user of this value.  This
00277   /// is specialized because it is a common request and does not require
00278   /// traversing the whole use list.
00279   ///
00280   bool hasOneUse() const {
00281     const_use_iterator I = use_begin(), E = use_end();
00282     if (I == E) return false;
00283     return ++I == E;
00284   }
00285 
00286   /// hasNUses - Return true if this Value has exactly N users.
00287   ///
00288   bool hasNUses(unsigned N) const;
00289 
00290   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
00291   /// logically equivalent to getNumUses() >= N.
00292   ///
00293   bool hasNUsesOrMore(unsigned N) const;
00294 
00295   bool isUsedInBasicBlock(const BasicBlock *BB) const;
00296 
00297   /// getNumUses - This method computes the number of uses of this Value.  This
00298   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasNUsesOrMore
00299   /// to check for specific values.
00300   unsigned getNumUses() const;
00301 
00302   /// addUse - This method should only be used by the Use class.
00303   ///
00304   void addUse(Use &U) { U.addToList(&UseList); }
00305 
00306   /// An enumeration for keeping track of the concrete subclass of Value that
00307   /// is actually instantiated. Values of this enumeration are kept in the 
00308   /// Value classes SubclassID field. They are used for concrete type
00309   /// identification.
00310   enum ValueTy {
00311     ArgumentVal,              // This is an instance of Argument
00312     BasicBlockVal,            // This is an instance of BasicBlock
00313     FunctionVal,              // This is an instance of Function
00314     GlobalAliasVal,           // This is an instance of GlobalAlias
00315     GlobalVariableVal,        // This is an instance of GlobalVariable
00316     UndefValueVal,            // This is an instance of UndefValue
00317     BlockAddressVal,          // This is an instance of BlockAddress
00318     ConstantExprVal,          // This is an instance of ConstantExpr
00319     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
00320     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
00321     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
00322     ConstantIntVal,           // This is an instance of ConstantInt
00323     ConstantFPVal,            // This is an instance of ConstantFP
00324     ConstantArrayVal,         // This is an instance of ConstantArray
00325     ConstantStructVal,        // This is an instance of ConstantStruct
00326     ConstantVectorVal,        // This is an instance of ConstantVector
00327     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
00328     MDNodeVal,                // This is an instance of MDNode
00329     MDStringVal,              // This is an instance of MDString
00330     InlineAsmVal,             // This is an instance of InlineAsm
00331     InstructionVal,           // This is an instance of Instruction
00332     // Enum values starting at InstructionVal are used for Instructions;
00333     // don't add new values here!
00334 
00335     // Markers:
00336     ConstantFirstVal = FunctionVal,
00337     ConstantLastVal  = ConstantPointerNullVal
00338   };
00339 
00340   /// getValueID - Return an ID for the concrete type of this object.  This is
00341   /// used to implement the classof checks.  This should not be used for any
00342   /// other purpose, as the values may change as LLVM evolves.  Also, note that
00343   /// for instructions, the Instruction's opcode is added to InstructionVal. So
00344   /// this means three things:
00345   /// # there is no value with code InstructionVal (no opcode==0).
00346   /// # there are more possible values for the value type than in ValueTy enum.
00347   /// # the InstructionVal enumerator must be the highest valued enumerator in
00348   ///   the ValueTy enum.
00349   unsigned getValueID() const {
00350     return SubclassID;
00351   }
00352 
00353   /// getRawSubclassOptionalData - Return the raw optional flags value
00354   /// contained in this value. This should only be used when testing two
00355   /// Values for equivalence.
00356   unsigned getRawSubclassOptionalData() const {
00357     return SubclassOptionalData;
00358   }
00359 
00360   /// clearSubclassOptionalData - Clear the optional flags contained in
00361   /// this value.
00362   void clearSubclassOptionalData() {
00363     SubclassOptionalData = 0;
00364   }
00365 
00366   /// hasSameSubclassOptionalData - Test whether the optional flags contained
00367   /// in this value are equal to the optional flags in the given value.
00368   bool hasSameSubclassOptionalData(const Value *V) const {
00369     return SubclassOptionalData == V->SubclassOptionalData;
00370   }
00371 
00372   /// intersectOptionalDataWith - Clear any optional flags in this value
00373   /// that are not also set in the given value.
00374   void intersectOptionalDataWith(const Value *V) {
00375     SubclassOptionalData &= V->SubclassOptionalData;
00376   }
00377 
00378   /// hasValueHandle - Return true if there is a value handle associated with
00379   /// this value.
00380   bool hasValueHandle() const { return HasValueHandle; }
00381 
00382   /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
00383   /// from the specified value, returning the original uncasted value.
00384   ///
00385   /// If this is called on a non-pointer value, it returns 'this'.
00386   Value *stripPointerCasts();
00387   const Value *stripPointerCasts() const {
00388     return const_cast<Value*>(this)->stripPointerCasts();
00389   }
00390 
00391   /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
00392   /// specified value, returning the original uncasted value.
00393   ///
00394   /// If this is called on a non-pointer value, it returns 'this'.
00395   Value *stripPointerCastsNoFollowAliases();
00396   const Value *stripPointerCastsNoFollowAliases() const {
00397     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
00398   }
00399 
00400   /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
00401   /// specified value, returning the original pointer value.
00402   ///
00403   /// If this is called on a non-pointer value, it returns 'this'.
00404   Value *stripInBoundsConstantOffsets();
00405   const Value *stripInBoundsConstantOffsets() const {
00406     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
00407   }
00408 
00409   /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
00410   /// the constant offset stripped.
00411   ///
00412   /// Stores the resulting constant offset stripped into the APInt provided.
00413   /// The provided APInt will be extended or truncated as needed to be the
00414   /// correct bitwidth for an offset of this pointer type.
00415   ///
00416   /// If this is called on a non-pointer value, it returns 'this'.
00417   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00418                                                    APInt &Offset);
00419   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00420                                                          APInt &Offset) const {
00421     return const_cast<Value *>(this)
00422         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
00423   }
00424 
00425   /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
00426   /// the specified value, returning the original pointer value.
00427   ///
00428   /// If this is called on a non-pointer value, it returns 'this'.
00429   Value *stripInBoundsOffsets();
00430   const Value *stripInBoundsOffsets() const {
00431     return const_cast<Value*>(this)->stripInBoundsOffsets();
00432   }
00433 
00434   /// isDereferenceablePointer - Test if this value is always a pointer to
00435   /// allocated and suitably aligned memory for a simple load or store.
00436   bool isDereferenceablePointer() const;
00437   
00438   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
00439   /// return the value in the PHI node corresponding to PredBB.  If not, return
00440   /// ourself.  This is useful if you want to know the value something has in a
00441   /// predecessor block.
00442   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
00443 
00444   const Value *DoPHITranslation(const BasicBlock *CurBB,
00445                                 const BasicBlock *PredBB) const{
00446     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
00447   }
00448   
00449   /// MaximumAlignment - This is the greatest alignment value supported by
00450   /// load, store, and alloca instructions, and global values.
00451   static const unsigned MaximumAlignment = 1u << 29;
00452   
00453   /// mutateType - Mutate the type of this Value to be of the specified type.
00454   /// Note that this is an extremely dangerous operation which can create
00455   /// completely invalid IR very easily.  It is strongly recommended that you
00456   /// recreate IR objects with the right types instead of mutating them in
00457   /// place.
00458   void mutateType(Type *Ty) {
00459     VTy = Ty;
00460   }
00461   
00462 protected:
00463   unsigned short getSubclassDataFromValue() const { return SubclassData; }
00464   void setValueSubclassData(unsigned short D) { SubclassData = D; }
00465 };
00466 
00467 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
00468   V.print(OS);
00469   return OS;
00470 }
00471   
00472 void Use::set(Value *V) {
00473   if (Val) removeFromList();
00474   Val = V;
00475   if (V) V->addUse(*this);
00476 }
00477 
00478 
00479 // isa - Provide some specializations of isa so that we don't have to include
00480 // the subtype header files to test to see if the value is a subclass...
00481 //
00482 template <> struct isa_impl<Constant, Value> {
00483   static inline bool doit(const Value &Val) {
00484     return Val.getValueID() >= Value::ConstantFirstVal &&
00485       Val.getValueID() <= Value::ConstantLastVal;
00486   }
00487 };
00488 
00489 template <> struct isa_impl<Argument, Value> {
00490   static inline bool doit (const Value &Val) {
00491     return Val.getValueID() == Value::ArgumentVal;
00492   }
00493 };
00494 
00495 template <> struct isa_impl<InlineAsm, Value> { 
00496   static inline bool doit(const Value &Val) {
00497     return Val.getValueID() == Value::InlineAsmVal;
00498   }
00499 };
00500 
00501 template <> struct isa_impl<Instruction, Value> { 
00502   static inline bool doit(const Value &Val) {
00503     return Val.getValueID() >= Value::InstructionVal;
00504   }
00505 };
00506 
00507 template <> struct isa_impl<BasicBlock, Value> { 
00508   static inline bool doit(const Value &Val) {
00509     return Val.getValueID() == Value::BasicBlockVal;
00510   }
00511 };
00512 
00513 template <> struct isa_impl<Function, Value> { 
00514   static inline bool doit(const Value &Val) {
00515     return Val.getValueID() == Value::FunctionVal;
00516   }
00517 };
00518 
00519 template <> struct isa_impl<GlobalVariable, Value> { 
00520   static inline bool doit(const Value &Val) {
00521     return Val.getValueID() == Value::GlobalVariableVal;
00522   }
00523 };
00524 
00525 template <> struct isa_impl<GlobalAlias, Value> { 
00526   static inline bool doit(const Value &Val) {
00527     return Val.getValueID() == Value::GlobalAliasVal;
00528   }
00529 };
00530 
00531 template <> struct isa_impl<GlobalValue, Value> { 
00532   static inline bool doit(const Value &Val) {
00533     return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
00534       isa<GlobalAlias>(Val);
00535   }
00536 };
00537 
00538 template <> struct isa_impl<MDNode, Value> { 
00539   static inline bool doit(const Value &Val) {
00540     return Val.getValueID() == Value::MDNodeVal;
00541   }
00542 };
00543   
00544 // Value* is only 4-byte aligned.
00545 template<>
00546 class PointerLikeTypeTraits<Value*> {
00547   typedef Value* PT;
00548 public:
00549   static inline void *getAsVoidPointer(PT P) { return P; }
00550   static inline PT getFromVoidPointer(void *P) {
00551     return static_cast<PT>(P);
00552   }
00553   enum { NumLowBitsAvailable = 2 };
00554 };
00555 
00556 // Create wrappers for C Binding types (see CBindingWrapping.h).
00557 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
00558 
00559 /* Specialized opaque value conversions.
00560  */ 
00561 inline Value **unwrap(LLVMValueRef *Vals) {
00562   return reinterpret_cast<Value**>(Vals);
00563 }
00564 
00565 template<typename T>
00566 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
00567 #ifdef DEBUG
00568   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
00569     cast<T>(*I);
00570 #endif
00571   (void)Length;
00572   return reinterpret_cast<T**>(Vals);
00573 }
00574 
00575 inline LLVMValueRef *wrap(const Value **Vals) {
00576   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
00577 }
00578 
00579 } // End llvm namespace
00580 
00581 #endif