1 //===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the Value class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
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"
28 class AssemblyAnnotationWriter;
44 class ValueHandleBase;
45 class ValueSymbolTable;
48 template<typename ValueTy> class StringMapEntry;
49 typedef StringMapEntry<Value*> ValueName;
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
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.
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.
67 /// @brief LLVM Value Representation
69 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
70 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
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
76 unsigned char SubclassOptionalData : 7;
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;
85 explicit use_iterator_impl(UseT *u) : U(u) {}
89 typedef typename super::reference reference;
90 typedef typename super::pointer pointer;
92 use_iterator_impl() : U() {}
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); }
97 use_iterator_impl &operator++() { // Preincrement
98 assert(U && "Cannot increment end iterator!");
102 use_iterator_impl operator++(int) { // Postincrement
108 UseT &operator*() const {
109 assert(U && "Cannot dereference end iterator!");
113 UseT *operator->() const { return &operator*(); }
115 operator use_iterator_impl<const UseT>() const {
116 return use_iterator_impl<const UseT>(U);
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;
125 use_iterator_impl<Use> UI;
126 explicit user_iterator_impl(Use *U) : UI(U) {}
130 typedef typename super::reference reference;
131 typedef typename super::pointer pointer;
133 user_iterator_impl() {}
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); }
138 /// \brief Returns true if this iterator is equal to user_end() on the value.
139 bool atEnd() const { return *this == user_iterator_impl(); }
141 user_iterator_impl &operator++() { // Preincrement
145 user_iterator_impl operator++(int) { // Postincrement
151 // Retrieve a pointer to the current User.
152 UserTy *operator*() const {
153 return UI->getUser();
156 UserTy *operator->() const { return operator*(); }
158 operator user_iterator_impl<const UserTy>() const {
159 return user_iterator_impl<const UserTy>(*UI);
162 Use &getUse() const { return *UI; }
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(); }
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;
177 friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
178 friend class ValueHandleBase;
181 void operator=(const Value &) LLVM_DELETED_FUNCTION;
182 Value(const Value &) LLVM_DELETED_FUNCTION;
185 Value(Type *Ty, unsigned scid);
189 /// dump - Support for debugging, callable in GDB: V->dump()
193 /// print - Implement operator<< on Value.
195 void print(raw_ostream &O) const;
197 /// \brief Print the name of this Value out to the specified raw_ostream.
198 /// This is useful when you just want to print 'int %reg126', not the
199 /// instruction that generated it. If you specify a Module for context, then
200 /// even constanst get pretty-printed; for example, the type of a null
201 /// pointer is printed symbolically.
202 void printAsOperand(raw_ostream &O, bool PrintType = true,
203 const Module *M = nullptr) const;
205 /// All values are typed, get the type of this value.
207 Type *getType() const { return VTy; }
209 /// All values hold a context through their type.
210 LLVMContext &getContext() const;
212 // All values can potentially be named.
213 bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
214 ValueName *getValueName() const { return Name; }
215 void setValueName(ValueName *VN) { Name = VN; }
217 /// getName() - Return a constant reference to the value's name. This is cheap
218 /// and guaranteed to return the same reference as long as the value is not
220 StringRef getName() const;
222 /// setName() - Change the name of the value, choosing a new unique name if
223 /// the provided name is taken.
225 /// \param Name The new name; or "" if the value's name should be removed.
226 void setName(const Twine &Name);
229 /// takeName - transfer the name from V to this value, setting V's name to
230 /// empty. It is an error to call V->takeName(V).
231 void takeName(Value *V);
233 /// replaceAllUsesWith - Go through the uses list for this definition and make
234 /// each use point to "V" instead of "this". After this completes, 'this's
235 /// use list is guaranteed to be empty.
237 void replaceAllUsesWith(Value *V);
239 //----------------------------------------------------------------------
240 // Methods for handling the chain of uses of this Value.
242 bool use_empty() const { return UseList == nullptr; }
244 typedef use_iterator_impl<Use> use_iterator;
245 typedef use_iterator_impl<const Use> const_use_iterator;
246 use_iterator use_begin() { return use_iterator(UseList); }
247 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
248 use_iterator use_end() { return use_iterator(); }
249 const_use_iterator use_end() const { return const_use_iterator(); }
250 iterator_range<use_iterator> uses() {
251 return iterator_range<use_iterator>(use_begin(), use_end());
253 iterator_range<const_use_iterator> uses() const {
254 return iterator_range<const_use_iterator>(use_begin(), use_end());
257 typedef user_iterator_impl<User> user_iterator;
258 typedef user_iterator_impl<const User> const_user_iterator;
259 user_iterator user_begin() { return user_iterator(UseList); }
260 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
261 user_iterator user_end() { return user_iterator(); }
262 const_user_iterator user_end() const { return const_user_iterator(); }
263 User *user_back() { return *user_begin(); }
264 const User *user_back() const { return *user_begin(); }
265 iterator_range<user_iterator> users() {
266 return iterator_range<user_iterator>(user_begin(), user_end());
268 iterator_range<const_user_iterator> users() const {
269 return iterator_range<const_user_iterator>(user_begin(), user_end());
272 /// hasOneUse - Return true if there is exactly one user of this value. This
273 /// is specialized because it is a common request and does not require
274 /// traversing the whole use list.
276 bool hasOneUse() const {
277 const_use_iterator I = use_begin(), E = use_end();
278 if (I == E) return false;
282 /// hasNUses - Return true if this Value has exactly N users.
284 bool hasNUses(unsigned N) const;
286 /// hasNUsesOrMore - Return true if this value has N users or more. This is
287 /// logically equivalent to getNumUses() >= N.
289 bool hasNUsesOrMore(unsigned N) const;
291 bool isUsedInBasicBlock(const BasicBlock *BB) const;
293 /// getNumUses - This method computes the number of uses of this Value. This
294 /// is a linear time operation. Use hasOneUse, hasNUses, or hasNUsesOrMore
295 /// to check for specific values.
296 unsigned getNumUses() const;
298 /// addUse - This method should only be used by the Use class.
300 void addUse(Use &U) { U.addToList(&UseList); }
302 /// An enumeration for keeping track of the concrete subclass of Value that
303 /// is actually instantiated. Values of this enumeration are kept in the
304 /// Value classes SubclassID field. They are used for concrete type
307 ArgumentVal, // This is an instance of Argument
308 BasicBlockVal, // This is an instance of BasicBlock
309 FunctionVal, // This is an instance of Function
310 GlobalAliasVal, // This is an instance of GlobalAlias
311 GlobalVariableVal, // This is an instance of GlobalVariable
312 UndefValueVal, // This is an instance of UndefValue
313 BlockAddressVal, // This is an instance of BlockAddress
314 ConstantExprVal, // This is an instance of ConstantExpr
315 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
316 ConstantDataArrayVal, // This is an instance of ConstantDataArray
317 ConstantDataVectorVal, // This is an instance of ConstantDataVector
318 ConstantIntVal, // This is an instance of ConstantInt
319 ConstantFPVal, // This is an instance of ConstantFP
320 ConstantArrayVal, // This is an instance of ConstantArray
321 ConstantStructVal, // This is an instance of ConstantStruct
322 ConstantVectorVal, // This is an instance of ConstantVector
323 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
324 MDNodeVal, // This is an instance of MDNode
325 MDStringVal, // This is an instance of MDString
326 InlineAsmVal, // This is an instance of InlineAsm
327 InstructionVal, // This is an instance of Instruction
328 // Enum values starting at InstructionVal are used for Instructions;
329 // don't add new values here!
332 ConstantFirstVal = FunctionVal,
333 ConstantLastVal = ConstantPointerNullVal
336 /// getValueID - Return an ID for the concrete type of this object. This is
337 /// used to implement the classof checks. This should not be used for any
338 /// other purpose, as the values may change as LLVM evolves. Also, note that
339 /// for instructions, the Instruction's opcode is added to InstructionVal. So
340 /// this means three things:
341 /// # there is no value with code InstructionVal (no opcode==0).
342 /// # there are more possible values for the value type than in ValueTy enum.
343 /// # the InstructionVal enumerator must be the highest valued enumerator in
344 /// the ValueTy enum.
345 unsigned getValueID() const {
349 /// getRawSubclassOptionalData - Return the raw optional flags value
350 /// contained in this value. This should only be used when testing two
351 /// Values for equivalence.
352 unsigned getRawSubclassOptionalData() const {
353 return SubclassOptionalData;
356 /// clearSubclassOptionalData - Clear the optional flags contained in
358 void clearSubclassOptionalData() {
359 SubclassOptionalData = 0;
362 /// hasSameSubclassOptionalData - Test whether the optional flags contained
363 /// in this value are equal to the optional flags in the given value.
364 bool hasSameSubclassOptionalData(const Value *V) const {
365 return SubclassOptionalData == V->SubclassOptionalData;
368 /// intersectOptionalDataWith - Clear any optional flags in this value
369 /// that are not also set in the given value.
370 void intersectOptionalDataWith(const Value *V) {
371 SubclassOptionalData &= V->SubclassOptionalData;
374 /// hasValueHandle - Return true if there is a value handle associated with
376 bool hasValueHandle() const { return HasValueHandle; }
378 /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
379 /// from the specified value, returning the original uncasted value.
381 /// If this is called on a non-pointer value, it returns 'this'.
382 Value *stripPointerCasts();
383 const Value *stripPointerCasts() const {
384 return const_cast<Value*>(this)->stripPointerCasts();
387 /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
388 /// specified value, returning the original uncasted value.
390 /// If this is called on a non-pointer value, it returns 'this'.
391 Value *stripPointerCastsNoFollowAliases();
392 const Value *stripPointerCastsNoFollowAliases() const {
393 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
396 /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
397 /// specified value, returning the original pointer value.
399 /// If this is called on a non-pointer value, it returns 'this'.
400 Value *stripInBoundsConstantOffsets();
401 const Value *stripInBoundsConstantOffsets() const {
402 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
405 /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
406 /// the constant offset stripped.
408 /// Stores the resulting constant offset stripped into the APInt provided.
409 /// The provided APInt will be extended or truncated as needed to be the
410 /// correct bitwidth for an offset of this pointer type.
412 /// If this is called on a non-pointer value, it returns 'this'.
413 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
415 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
416 APInt &Offset) const {
417 return const_cast<Value *>(this)
418 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
421 /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
422 /// the specified value, returning the original pointer value.
424 /// If this is called on a non-pointer value, it returns 'this'.
425 Value *stripInBoundsOffsets();
426 const Value *stripInBoundsOffsets() const {
427 return const_cast<Value*>(this)->stripInBoundsOffsets();
430 /// isDereferenceablePointer - Test if this value is always a pointer to
431 /// allocated and suitably aligned memory for a simple load or store.
432 bool isDereferenceablePointer() const;
434 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
435 /// return the value in the PHI node corresponding to PredBB. If not, return
436 /// ourself. This is useful if you want to know the value something has in a
437 /// predecessor block.
438 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
440 const Value *DoPHITranslation(const BasicBlock *CurBB,
441 const BasicBlock *PredBB) const{
442 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
445 /// MaximumAlignment - This is the greatest alignment value supported by
446 /// load, store, and alloca instructions, and global values.
447 static const unsigned MaximumAlignment = 1u << 29;
449 /// mutateType - Mutate the type of this Value to be of the specified type.
450 /// Note that this is an extremely dangerous operation which can create
451 /// completely invalid IR very easily. It is strongly recommended that you
452 /// recreate IR objects with the right types instead of mutating them in
454 void mutateType(Type *Ty) {
459 unsigned short getSubclassDataFromValue() const { return SubclassData; }
460 void setValueSubclassData(unsigned short D) { SubclassData = D; }
463 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
468 void Use::set(Value *V) {
469 if (Val) removeFromList();
471 if (V) V->addUse(*this);
475 // isa - Provide some specializations of isa so that we don't have to include
476 // the subtype header files to test to see if the value is a subclass...
478 template <> struct isa_impl<Constant, Value> {
479 static inline bool doit(const Value &Val) {
480 return Val.getValueID() >= Value::ConstantFirstVal &&
481 Val.getValueID() <= Value::ConstantLastVal;
485 template <> struct isa_impl<Argument, Value> {
486 static inline bool doit (const Value &Val) {
487 return Val.getValueID() == Value::ArgumentVal;
491 template <> struct isa_impl<InlineAsm, Value> {
492 static inline bool doit(const Value &Val) {
493 return Val.getValueID() == Value::InlineAsmVal;
497 template <> struct isa_impl<Instruction, Value> {
498 static inline bool doit(const Value &Val) {
499 return Val.getValueID() >= Value::InstructionVal;
503 template <> struct isa_impl<BasicBlock, Value> {
504 static inline bool doit(const Value &Val) {
505 return Val.getValueID() == Value::BasicBlockVal;
509 template <> struct isa_impl<Function, Value> {
510 static inline bool doit(const Value &Val) {
511 return Val.getValueID() == Value::FunctionVal;
515 template <> struct isa_impl<GlobalVariable, Value> {
516 static inline bool doit(const Value &Val) {
517 return Val.getValueID() == Value::GlobalVariableVal;
521 template <> struct isa_impl<GlobalAlias, Value> {
522 static inline bool doit(const Value &Val) {
523 return Val.getValueID() == Value::GlobalAliasVal;
527 template <> struct isa_impl<GlobalValue, Value> {
528 static inline bool doit(const Value &Val) {
529 return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
530 isa<GlobalAlias>(Val);
534 template <> struct isa_impl<MDNode, Value> {
535 static inline bool doit(const Value &Val) {
536 return Val.getValueID() == Value::MDNodeVal;
540 // Value* is only 4-byte aligned.
542 class PointerLikeTypeTraits<Value*> {
545 static inline void *getAsVoidPointer(PT P) { return P; }
546 static inline PT getFromVoidPointer(void *P) {
547 return static_cast<PT>(P);
549 enum { NumLowBitsAvailable = 2 };
552 // Create wrappers for C Binding types (see CBindingWrapping.h).
553 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
555 /* Specialized opaque value conversions.
557 inline Value **unwrap(LLVMValueRef *Vals) {
558 return reinterpret_cast<Value**>(Vals);
562 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
564 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
568 return reinterpret_cast<T**>(Vals);
571 inline LLVMValueRef *wrap(const Value **Vals) {
572 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
575 } // End llvm namespace