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;
41 class ModuleSlotTracker;
45 class ValueHandleBase;
46 class ValueSymbolTable;
49 template<typename ValueTy> class StringMapEntry;
50 typedef StringMapEntry<Value*> ValueName;
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 /// \brief LLVM Value Representation
58 /// This is a very important LLVM class. It is the base class of all values
59 /// computed by a program that may be used as operands to other values. Value is
60 /// the super class of other important classes such as Instruction and Function.
61 /// All Values have a Type. Type is not a subclass of Value. Some values can
62 /// have a name and they belong to some Module. Setting the name on the Value
63 /// automatically updates the module's symbol table.
65 /// Every value has a "use list" that keeps track of which other Values are
66 /// using this Value. A Value can also have an arbitrary number of ValueHandle
67 /// objects that watch it and listen to RAUW and Destroy events. See
68 /// llvm/IR/ValueHandle.h for details.
73 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
74 friend class ValueHandleBase;
76 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
77 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
79 /// \brief Hold subclass data that can be dropped.
81 /// This member is similar to SubclassData, however it is for holding
82 /// information which may be used to aid optimization, but which may be
83 /// cleared to zero without affecting conservative interpretation.
84 unsigned char SubclassOptionalData : 7;
87 /// \brief Hold arbitrary subclass data.
89 /// This member is defined by this class, but is not used for anything.
90 /// Subclasses can use it to hold whatever state they find useful. This
91 /// field is initialized to zero by the ctor.
92 unsigned short SubclassData;
95 /// \brief The number of operands in the subclass.
97 /// This member is defined by this class, but not used for anything.
98 /// Subclasses can use it to store their number of operands, if they have
101 /// This is stored here to save space in User on 64-bit hosts. Since most
102 /// instances of Value have operands, 32-bit hosts aren't significantly
105 /// Note, this should *NOT* be used directly by any class other than User.
106 /// User uses this value to find the Use list.
107 enum : unsigned { NumUserOperandsBits = 29 };
108 unsigned NumUserOperands : NumUserOperandsBits;
112 bool HasHungOffUses : 1;
115 template <typename UseT> // UseT == 'Use' or 'const Use'
116 class use_iterator_impl
117 : public std::iterator<std::forward_iterator_tag, UseT *> {
119 explicit use_iterator_impl(UseT *u) : U(u) {}
123 use_iterator_impl() : U() {}
125 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
126 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
128 use_iterator_impl &operator++() { // Preincrement
129 assert(U && "Cannot increment end iterator!");
133 use_iterator_impl operator++(int) { // Postincrement
139 UseT &operator*() const {
140 assert(U && "Cannot dereference end iterator!");
144 UseT *operator->() const { return &operator*(); }
146 operator use_iterator_impl<const UseT>() const {
147 return use_iterator_impl<const UseT>(U);
151 template <typename UserTy> // UserTy == 'User' or 'const User'
152 class user_iterator_impl
153 : public std::iterator<std::forward_iterator_tag, UserTy *> {
154 use_iterator_impl<Use> UI;
155 explicit user_iterator_impl(Use *U) : UI(U) {}
159 user_iterator_impl() {}
161 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
162 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
164 /// \brief Returns true if this iterator is equal to user_end() on the value.
165 bool atEnd() const { return *this == user_iterator_impl(); }
167 user_iterator_impl &operator++() { // Preincrement
171 user_iterator_impl operator++(int) { // Postincrement
177 // Retrieve a pointer to the current User.
178 UserTy *operator*() const {
179 return UI->getUser();
182 UserTy *operator->() const { return operator*(); }
184 operator user_iterator_impl<const UserTy>() const {
185 return user_iterator_impl<const UserTy>(*UI);
188 Use &getUse() const { return *UI; }
191 void operator=(const Value &) = delete;
192 Value(const Value &) = delete;
195 Value(Type *Ty, unsigned scid);
199 /// \brief Support for debugging, callable in GDB: V->dump()
202 /// \brief Implement operator<< on Value.
204 void print(raw_ostream &O) const;
205 void print(raw_ostream &O, ModuleSlotTracker &MST) const;
208 /// \brief Print the name of this Value out to the specified raw_ostream.
210 /// This is useful when you just want to print 'int %reg126', not the
211 /// instruction that generated it. If you specify a Module for context, then
212 /// even constanst get pretty-printed; for example, the type of a null
213 /// pointer is printed symbolically.
215 void printAsOperand(raw_ostream &O, bool PrintType = true,
216 const Module *M = nullptr) const;
217 void printAsOperand(raw_ostream &O, bool PrintType,
218 ModuleSlotTracker &MST) const;
221 /// \brief All values are typed, get the type of this value.
222 Type *getType() const { return VTy; }
224 /// \brief All values hold a context through their type.
225 LLVMContext &getContext() const;
227 // \brief All values can potentially be named.
228 bool hasName() const { return HasName; }
229 ValueName *getValueName() const;
230 void setValueName(ValueName *VN);
233 void destroyValueName();
234 void setNameImpl(const Twine &Name);
237 /// \brief Return a constant reference to the value's name.
239 /// This is cheap and guaranteed to return the same reference as long as the
240 /// value is not modified.
241 StringRef getName() const;
243 /// \brief Change the name of the value.
245 /// Choose a new unique name if the provided name is taken.
247 /// \param Name The new name; or "" if the value's name should be removed.
248 void setName(const Twine &Name);
251 /// \brief Transfer the name from V to this value.
253 /// After taking V's name, sets V's name to empty.
255 /// \note It is an error to call V->takeName(V).
256 void takeName(Value *V);
258 /// \brief Change all uses of this to point to a new Value.
260 /// Go through the uses list for this definition and make each use point to
261 /// "V" instead of "this". After this completes, 'this's use list is
262 /// guaranteed to be empty.
263 void replaceAllUsesWith(Value *V);
265 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
266 /// make each use point to "V" instead of "this" when the use is outside the
267 /// block. 'This's use list is expected to have at least one element.
268 /// Unlike replaceAllUsesWith this function does not support basic block
269 /// values or constant users.
270 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
272 //----------------------------------------------------------------------
273 // Methods for handling the chain of uses of this Value.
275 bool use_empty() const { return UseList == nullptr; }
277 typedef use_iterator_impl<Use> use_iterator;
278 typedef use_iterator_impl<const Use> const_use_iterator;
279 use_iterator use_begin() { return use_iterator(UseList); }
280 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
281 use_iterator use_end() { return use_iterator(); }
282 const_use_iterator use_end() const { return const_use_iterator(); }
283 iterator_range<use_iterator> uses() {
284 return iterator_range<use_iterator>(use_begin(), use_end());
286 iterator_range<const_use_iterator> uses() const {
287 return iterator_range<const_use_iterator>(use_begin(), use_end());
290 bool user_empty() const { return UseList == nullptr; }
292 typedef user_iterator_impl<User> user_iterator;
293 typedef user_iterator_impl<const User> const_user_iterator;
294 user_iterator user_begin() { return user_iterator(UseList); }
295 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
296 user_iterator user_end() { return user_iterator(); }
297 const_user_iterator user_end() const { return const_user_iterator(); }
298 User *user_back() { return *user_begin(); }
299 const User *user_back() const { return *user_begin(); }
300 iterator_range<user_iterator> users() {
301 return iterator_range<user_iterator>(user_begin(), user_end());
303 iterator_range<const_user_iterator> users() const {
304 return iterator_range<const_user_iterator>(user_begin(), user_end());
307 /// \brief Return true if there is exactly one user of this value.
309 /// This is specialized because it is a common request and does not require
310 /// traversing the whole use list.
311 bool hasOneUse() const {
312 const_use_iterator I = use_begin(), E = use_end();
313 if (I == E) return false;
317 /// \brief Return true if this Value has exactly N users.
318 bool hasNUses(unsigned N) const;
320 /// \brief Return true if this value has N users or more.
322 /// This is logically equivalent to getNumUses() >= N.
323 bool hasNUsesOrMore(unsigned N) const;
325 /// \brief Check if this value is used in the specified basic block.
326 bool isUsedInBasicBlock(const BasicBlock *BB) const;
328 /// \brief This method computes the number of uses of this Value.
330 /// This is a linear time operation. Use hasOneUse, hasNUses, or
331 /// hasNUsesOrMore to check for specific values.
332 unsigned getNumUses() const;
334 /// \brief This method should only be used by the Use class.
335 void addUse(Use &U) { U.addToList(&UseList); }
337 /// \brief Concrete subclass of this.
339 /// An enumeration for keeping track of the concrete subclass of Value that
340 /// is actually instantiated. Values of this enumeration are kept in the
341 /// Value classes SubclassID field. They are used for concrete type
344 #define HANDLE_VALUE(Name) Name##Val,
345 #include "llvm/IR/Value.def"
348 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
349 #include "llvm/IR/Value.def"
352 /// \brief Return an ID for the concrete type of this object.
354 /// This is used to implement the classof checks. This should not be used
355 /// for any other purpose, as the values may change as LLVM evolves. Also,
356 /// note that for instructions, the Instruction's opcode is added to
357 /// InstructionVal. So this means three things:
358 /// # there is no value with code InstructionVal (no opcode==0).
359 /// # there are more possible values for the value type than in ValueTy enum.
360 /// # the InstructionVal enumerator must be the highest valued enumerator in
361 /// the ValueTy enum.
362 unsigned getValueID() const {
366 /// \brief Return the raw optional flags value contained in this value.
368 /// This should only be used when testing two Values for equivalence.
369 unsigned getRawSubclassOptionalData() const {
370 return SubclassOptionalData;
373 /// \brief Clear the optional flags contained in this value.
374 void clearSubclassOptionalData() {
375 SubclassOptionalData = 0;
378 /// \brief Check the optional flags for equality.
379 bool hasSameSubclassOptionalData(const Value *V) const {
380 return SubclassOptionalData == V->SubclassOptionalData;
383 /// \brief Clear any optional flags not set in the given Value.
384 void intersectOptionalDataWith(const Value *V) {
385 SubclassOptionalData &= V->SubclassOptionalData;
388 /// \brief Return true if there is a value handle associated with this value.
389 bool hasValueHandle() const { return HasValueHandle; }
391 /// \brief Return true if there is metadata referencing this value.
392 bool isUsedByMetadata() const { return IsUsedByMD; }
394 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
396 /// Returns the original uncasted value. If this is called on a non-pointer
397 /// value, it returns 'this'.
398 Value *stripPointerCasts();
399 const Value *stripPointerCasts() const {
400 return const_cast<Value*>(this)->stripPointerCasts();
403 /// \brief Strip off pointer casts and all-zero GEPs.
405 /// Returns the original uncasted value. If this is called on a non-pointer
406 /// value, it returns 'this'.
407 Value *stripPointerCastsNoFollowAliases();
408 const Value *stripPointerCastsNoFollowAliases() const {
409 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
412 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
414 /// Returns the original pointer value. If this is called on a non-pointer
415 /// value, it returns 'this'.
416 Value *stripInBoundsConstantOffsets();
417 const Value *stripInBoundsConstantOffsets() const {
418 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
421 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
423 /// Stores the resulting constant offset stripped into the APInt provided.
424 /// The provided APInt will be extended or truncated as needed to be the
425 /// correct bitwidth for an offset of this pointer type.
427 /// If this is called on a non-pointer value, it returns 'this'.
428 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
430 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
431 APInt &Offset) const {
432 return const_cast<Value *>(this)
433 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
436 /// \brief Strip off pointer casts and inbounds GEPs.
438 /// Returns the original pointer value. If this is called on a non-pointer
439 /// value, it returns 'this'.
440 Value *stripInBoundsOffsets();
441 const Value *stripInBoundsOffsets() const {
442 return const_cast<Value*>(this)->stripInBoundsOffsets();
445 /// \brief Translate PHI node to its predecessor from the given basic block.
447 /// If this value is a PHI node with CurBB as its parent, return the value in
448 /// the PHI node corresponding to PredBB. If not, return ourself. This is
449 /// useful if you want to know the value something has in a predecessor
451 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
453 const Value *DoPHITranslation(const BasicBlock *CurBB,
454 const BasicBlock *PredBB) const{
455 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
458 /// \brief The maximum alignment for instructions.
460 /// This is the greatest alignment value supported by load, store, and alloca
461 /// instructions, and global values.
462 static const unsigned MaxAlignmentExponent = 29;
463 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
465 /// \brief Mutate the type of this Value to be of the specified type.
467 /// Note that this is an extremely dangerous operation which can create
468 /// completely invalid IR very easily. It is strongly recommended that you
469 /// recreate IR objects with the right types instead of mutating them in
471 void mutateType(Type *Ty) {
475 /// \brief Sort the use-list.
477 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
478 /// expected to compare two \a Use references.
479 template <class Compare> void sortUseList(Compare Cmp);
481 /// \brief Reverse the use-list.
482 void reverseUseList();
485 /// \brief Merge two lists together.
487 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
488 /// "equal" items from L before items from R.
490 /// \return the first element in the list.
492 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
493 template <class Compare>
494 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
496 Use **Next = &Merged;
521 /// \brief Tail-recursive helper for \a mergeUseLists().
523 /// \param[out] Next the first element in the list.
524 template <class Compare>
525 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
528 unsigned short getSubclassDataFromValue() const { return SubclassData; }
529 void setValueSubclassData(unsigned short D) { SubclassData = D; }
532 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
537 void Use::set(Value *V) {
538 if (Val) removeFromList();
540 if (V) V->addUse(*this);
543 template <class Compare> void Value::sortUseList(Compare Cmp) {
544 if (!UseList || !UseList->Next)
545 // No need to sort 0 or 1 uses.
548 // Note: this function completely ignores Prev pointers until the end when
549 // they're fixed en masse.
551 // Create a binomial vector of sorted lists, visiting uses one at a time and
552 // merging lists as necessary.
553 const unsigned MaxSlots = 32;
554 Use *Slots[MaxSlots];
556 // Collect the first use, turning it into a single-item list.
557 Use *Next = UseList->Next;
558 UseList->Next = nullptr;
559 unsigned NumSlots = 1;
562 // Collect all but the last use.
565 Next = Current->Next;
567 // Turn Current into a single-item list.
568 Current->Next = nullptr;
570 // Save Current in the first available slot, merging on collisions.
572 for (I = 0; I < NumSlots; ++I) {
576 // Merge two lists, doubling the size of Current and emptying slot I.
578 // Since the uses in Slots[I] originally preceded those in Current, send
579 // Slots[I] in as the left parameter to maintain a stable sort.
580 Current = mergeUseLists(Slots[I], Current, Cmp);
583 // Check if this is a new slot.
586 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
589 // Found an open slot.
593 // Merge all the lists together.
594 assert(Next && "Expected one more Use");
595 assert(!Next->Next && "Expected only one Use");
597 for (unsigned I = 0; I < NumSlots; ++I)
599 // Since the uses in Slots[I] originally preceded those in UseList, send
600 // Slots[I] in as the left parameter to maintain a stable sort.
601 UseList = mergeUseLists(Slots[I], UseList, Cmp);
603 // Fix the Prev pointers.
604 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
610 // isa - Provide some specializations of isa so that we don't have to include
611 // the subtype header files to test to see if the value is a subclass...
613 template <> struct isa_impl<Constant, Value> {
614 static inline bool doit(const Value &Val) {
615 return Val.getValueID() >= Value::ConstantFirstVal &&
616 Val.getValueID() <= Value::ConstantLastVal;
620 template <> struct isa_impl<Argument, Value> {
621 static inline bool doit (const Value &Val) {
622 return Val.getValueID() == Value::ArgumentVal;
626 template <> struct isa_impl<InlineAsm, Value> {
627 static inline bool doit(const Value &Val) {
628 return Val.getValueID() == Value::InlineAsmVal;
632 template <> struct isa_impl<Instruction, Value> {
633 static inline bool doit(const Value &Val) {
634 return Val.getValueID() >= Value::InstructionVal;
638 template <> struct isa_impl<BasicBlock, Value> {
639 static inline bool doit(const Value &Val) {
640 return Val.getValueID() == Value::BasicBlockVal;
644 template <> struct isa_impl<Function, Value> {
645 static inline bool doit(const Value &Val) {
646 return Val.getValueID() == Value::FunctionVal;
650 template <> struct isa_impl<GlobalVariable, Value> {
651 static inline bool doit(const Value &Val) {
652 return Val.getValueID() == Value::GlobalVariableVal;
656 template <> struct isa_impl<GlobalAlias, Value> {
657 static inline bool doit(const Value &Val) {
658 return Val.getValueID() == Value::GlobalAliasVal;
662 template <> struct isa_impl<GlobalValue, Value> {
663 static inline bool doit(const Value &Val) {
664 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
668 template <> struct isa_impl<GlobalObject, Value> {
669 static inline bool doit(const Value &Val) {
670 return isa<GlobalVariable>(Val) || isa<Function>(Val);
674 // Value* is only 4-byte aligned.
676 class PointerLikeTypeTraits<Value*> {
679 static inline void *getAsVoidPointer(PT P) { return P; }
680 static inline PT getFromVoidPointer(void *P) {
681 return static_cast<PT>(P);
683 enum { NumLowBitsAvailable = 2 };
686 // Create wrappers for C Binding types (see CBindingWrapping.h).
687 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
689 /* Specialized opaque value conversions.
691 inline Value **unwrap(LLVMValueRef *Vals) {
692 return reinterpret_cast<Value**>(Vals);
696 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
698 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
702 return reinterpret_cast<T**>(Vals);
705 inline LLVMValueRef *wrap(const Value **Vals) {
706 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
709 } // End llvm namespace