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/ADT/iterator_range.h"
18 #include "llvm/IR/Use.h"
19 #include "llvm/Support/CBindingWrapping.h"
20 #include "llvm/Support/Casting.h"
26 class AssemblyAnnotationWriter;
30 class ConstantAggregate;
35 class GlobalIndirectSymbol;
43 class ModuleSlotTracker;
47 class ValueHandleBase;
48 class ValueSymbolTable;
51 template<typename ValueTy> class StringMapEntry;
52 typedef StringMapEntry<Value*> ValueName;
54 //===----------------------------------------------------------------------===//
56 //===----------------------------------------------------------------------===//
58 /// \brief LLVM Value Representation
60 /// This is a very important LLVM class. It is the base class of all values
61 /// computed by a program that may be used as operands to other values. Value is
62 /// the super class of other important classes such as Instruction and Function.
63 /// All Values have a Type. Type is not a subclass of Value. Some values can
64 /// have a name and they belong to some Module. Setting the name on the Value
65 /// automatically updates the module's symbol table.
67 /// Every value has a "use list" that keeps track of which other Values are
68 /// using this Value. A Value can also have an arbitrary number of ValueHandle
69 /// objects that watch it and listen to RAUW and Destroy events. See
70 /// llvm/IR/ValueHandle.h for details.
75 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
76 friend class ValueHandleBase;
78 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
79 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
81 /// \brief Hold subclass data that can be dropped.
83 /// This member is similar to SubclassData, however it is for holding
84 /// information which may be used to aid optimization, but which may be
85 /// cleared to zero without affecting conservative interpretation.
86 unsigned char SubclassOptionalData : 7;
89 /// \brief Hold arbitrary subclass data.
91 /// This member is defined by this class, but is not used for anything.
92 /// Subclasses can use it to hold whatever state they find useful. This
93 /// field is initialized to zero by the ctor.
94 unsigned short SubclassData;
97 /// \brief The number of operands in the subclass.
99 /// This member is defined by this class, but not used for anything.
100 /// Subclasses can use it to store their number of operands, if they have
103 /// This is stored here to save space in User on 64-bit hosts. Since most
104 /// instances of Value have operands, 32-bit hosts aren't significantly
107 /// Note, this should *NOT* be used directly by any class other than User.
108 /// User uses this value to find the Use list.
109 enum : unsigned { NumUserOperandsBits = 28 };
110 unsigned NumUserOperands : NumUserOperandsBits;
112 // Use the same type as the bitfield above so that MSVC will pack them.
113 unsigned IsUsedByMD : 1;
114 unsigned HasName : 1;
115 unsigned HasHungOffUses : 1;
116 unsigned HasDescriptor : 1;
119 template <typename UseT> // UseT == 'Use' or 'const Use'
120 class use_iterator_impl
121 : public std::iterator<std::forward_iterator_tag, UseT *> {
123 explicit use_iterator_impl(UseT *u) : U(u) {}
127 use_iterator_impl() : U() {}
129 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
130 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
132 use_iterator_impl &operator++() { // Preincrement
133 assert(U && "Cannot increment end iterator!");
137 use_iterator_impl operator++(int) { // Postincrement
143 UseT &operator*() const {
144 assert(U && "Cannot dereference end iterator!");
148 UseT *operator->() const { return &operator*(); }
150 operator use_iterator_impl<const UseT>() const {
151 return use_iterator_impl<const UseT>(U);
155 template <typename UserTy> // UserTy == 'User' or 'const User'
156 class user_iterator_impl
157 : public std::iterator<std::forward_iterator_tag, UserTy *> {
158 use_iterator_impl<Use> UI;
159 explicit user_iterator_impl(Use *U) : UI(U) {}
163 user_iterator_impl() {}
165 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
166 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
168 /// \brief Returns true if this iterator is equal to user_end() on the value.
169 bool atEnd() const { return *this == user_iterator_impl(); }
171 user_iterator_impl &operator++() { // Preincrement
175 user_iterator_impl operator++(int) { // Postincrement
181 // Retrieve a pointer to the current User.
182 UserTy *operator*() const {
183 return UI->getUser();
186 UserTy *operator->() const { return operator*(); }
188 operator user_iterator_impl<const UserTy>() const {
189 return user_iterator_impl<const UserTy>(*UI);
192 Use &getUse() const { return *UI; }
195 void operator=(const Value &) = delete;
196 Value(const Value &) = delete;
199 Value(Type *Ty, unsigned scid);
203 /// \brief Support for debugging, callable in GDB: V->dump()
206 /// \brief Implement operator<< on Value.
208 void print(raw_ostream &O, bool IsForDebug = false) const;
209 void print(raw_ostream &O, ModuleSlotTracker &MST,
210 bool IsForDebug = false) const;
213 /// \brief Print the name of this Value out to the specified raw_ostream.
215 /// This is useful when you just want to print 'int %reg126', not the
216 /// instruction that generated it. If you specify a Module for context, then
217 /// even constanst get pretty-printed; for example, the type of a null
218 /// pointer is printed symbolically.
220 void printAsOperand(raw_ostream &O, bool PrintType = true,
221 const Module *M = nullptr) const;
222 void printAsOperand(raw_ostream &O, bool PrintType,
223 ModuleSlotTracker &MST) const;
226 /// \brief All values are typed, get the type of this value.
227 Type *getType() const { return VTy; }
229 /// \brief All values hold a context through their type.
230 LLVMContext &getContext() const;
232 // \brief All values can potentially be named.
233 bool hasName() const { return HasName; }
234 ValueName *getValueName() const;
235 void setValueName(ValueName *VN);
238 void destroyValueName();
239 void setNameImpl(const Twine &Name);
242 /// \brief Return a constant reference to the value's name.
244 /// This is cheap and guaranteed to return the same reference as long as the
245 /// value is not modified.
246 StringRef getName() const;
248 /// \brief Change the name of the value.
250 /// Choose a new unique name if the provided name is taken.
252 /// \param Name The new name; or "" if the value's name should be removed.
253 void setName(const Twine &Name);
256 /// \brief Transfer the name from V to this value.
258 /// After taking V's name, sets V's name to empty.
260 /// \note It is an error to call V->takeName(V).
261 void takeName(Value *V);
263 /// \brief Change all uses of this to point to a new Value.
265 /// Go through the uses list for this definition and make each use point to
266 /// "V" instead of "this". After this completes, 'this's use list is
267 /// guaranteed to be empty.
268 void replaceAllUsesWith(Value *V);
270 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
271 /// make each use point to "V" instead of "this" when the use is outside the
272 /// block. 'This's use list is expected to have at least one element.
273 /// Unlike replaceAllUsesWith this function does not support basic block
274 /// values or constant users.
275 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
277 //----------------------------------------------------------------------
278 // Methods for handling the chain of uses of this Value.
280 // Materializing a function can introduce new uses, so these methods come in
282 // The methods that start with materialized_ check the uses that are
283 // currently known given which functions are materialized. Be very careful
284 // when using them since you might not get all uses.
285 // The methods that don't start with materialized_ assert that modules is
286 // fully materialized.
287 void assertModuleIsMaterialized() const;
289 bool use_empty() const {
290 assertModuleIsMaterialized();
291 return UseList == nullptr;
294 typedef use_iterator_impl<Use> use_iterator;
295 typedef use_iterator_impl<const Use> const_use_iterator;
296 use_iterator materialized_use_begin() { return use_iterator(UseList); }
297 const_use_iterator materialized_use_begin() const {
298 return const_use_iterator(UseList);
300 use_iterator use_begin() {
301 assertModuleIsMaterialized();
302 return materialized_use_begin();
304 const_use_iterator use_begin() const {
305 assertModuleIsMaterialized();
306 return materialized_use_begin();
308 use_iterator use_end() { return use_iterator(); }
309 const_use_iterator use_end() const { return const_use_iterator(); }
310 iterator_range<use_iterator> materialized_uses() {
311 return make_range(materialized_use_begin(), use_end());
313 iterator_range<const_use_iterator> materialized_uses() const {
314 return make_range(materialized_use_begin(), use_end());
316 iterator_range<use_iterator> uses() {
317 assertModuleIsMaterialized();
318 return materialized_uses();
320 iterator_range<const_use_iterator> uses() const {
321 assertModuleIsMaterialized();
322 return materialized_uses();
325 bool user_empty() const {
326 assertModuleIsMaterialized();
327 return UseList == nullptr;
330 typedef user_iterator_impl<User> user_iterator;
331 typedef user_iterator_impl<const User> const_user_iterator;
332 user_iterator materialized_user_begin() { return user_iterator(UseList); }
333 const_user_iterator materialized_user_begin() const {
334 return const_user_iterator(UseList);
336 user_iterator user_begin() {
337 assertModuleIsMaterialized();
338 return materialized_user_begin();
340 const_user_iterator user_begin() const {
341 assertModuleIsMaterialized();
342 return materialized_user_begin();
344 user_iterator user_end() { return user_iterator(); }
345 const_user_iterator user_end() const { return const_user_iterator(); }
347 assertModuleIsMaterialized();
348 return *materialized_user_begin();
350 const User *user_back() const {
351 assertModuleIsMaterialized();
352 return *materialized_user_begin();
354 iterator_range<user_iterator> materialized_users() {
355 return make_range(materialized_user_begin(), user_end());
357 iterator_range<const_user_iterator> materialized_users() const {
358 return make_range(materialized_user_begin(), user_end());
360 iterator_range<user_iterator> users() {
361 assertModuleIsMaterialized();
362 return materialized_users();
364 iterator_range<const_user_iterator> users() const {
365 assertModuleIsMaterialized();
366 return materialized_users();
369 /// \brief Return true if there is exactly one user of this value.
371 /// This is specialized because it is a common request and does not require
372 /// traversing the whole use list.
373 bool hasOneUse() const {
374 const_use_iterator I = use_begin(), E = use_end();
375 if (I == E) return false;
379 /// \brief Return true if this Value has exactly N users.
380 bool hasNUses(unsigned N) const;
382 /// \brief Return true if this value has N users or more.
384 /// This is logically equivalent to getNumUses() >= N.
385 bool hasNUsesOrMore(unsigned N) const;
387 /// \brief Check if this value is used in the specified basic block.
388 bool isUsedInBasicBlock(const BasicBlock *BB) const;
390 /// \brief This method computes the number of uses of this Value.
392 /// This is a linear time operation. Use hasOneUse, hasNUses, or
393 /// hasNUsesOrMore to check for specific values.
394 unsigned getNumUses() const;
396 /// \brief This method should only be used by the Use class.
397 void addUse(Use &U) { U.addToList(&UseList); }
399 /// \brief Concrete subclass of this.
401 /// An enumeration for keeping track of the concrete subclass of Value that
402 /// is actually instantiated. Values of this enumeration are kept in the
403 /// Value classes SubclassID field. They are used for concrete type
406 #define HANDLE_VALUE(Name) Name##Val,
407 #include "llvm/IR/Value.def"
410 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
411 #include "llvm/IR/Value.def"
414 /// \brief Return an ID for the concrete type of this object.
416 /// This is used to implement the classof checks. This should not be used
417 /// for any other purpose, as the values may change as LLVM evolves. Also,
418 /// note that for instructions, the Instruction's opcode is added to
419 /// InstructionVal. So this means three things:
420 /// # there is no value with code InstructionVal (no opcode==0).
421 /// # there are more possible values for the value type than in ValueTy enum.
422 /// # the InstructionVal enumerator must be the highest valued enumerator in
423 /// the ValueTy enum.
424 unsigned getValueID() const {
428 /// \brief Return the raw optional flags value contained in this value.
430 /// This should only be used when testing two Values for equivalence.
431 unsigned getRawSubclassOptionalData() const {
432 return SubclassOptionalData;
435 /// \brief Clear the optional flags contained in this value.
436 void clearSubclassOptionalData() {
437 SubclassOptionalData = 0;
440 /// \brief Check the optional flags for equality.
441 bool hasSameSubclassOptionalData(const Value *V) const {
442 return SubclassOptionalData == V->SubclassOptionalData;
445 /// \brief Clear any optional flags not set in the given Value.
446 void intersectOptionalDataWith(const Value *V) {
447 SubclassOptionalData &= V->SubclassOptionalData;
450 /// \brief Return true if there is a value handle associated with this value.
451 bool hasValueHandle() const { return HasValueHandle; }
453 /// \brief Return true if there is metadata referencing this value.
454 bool isUsedByMetadata() const { return IsUsedByMD; }
456 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
458 /// Returns the original uncasted value. If this is called on a non-pointer
459 /// value, it returns 'this'.
460 Value *stripPointerCasts();
461 const Value *stripPointerCasts() const {
462 return const_cast<Value*>(this)->stripPointerCasts();
465 /// \brief Strip off pointer casts and all-zero GEPs.
467 /// Returns the original uncasted value. If this is called on a non-pointer
468 /// value, it returns 'this'.
469 Value *stripPointerCastsNoFollowAliases();
470 const Value *stripPointerCastsNoFollowAliases() const {
471 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
474 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
476 /// Returns the original pointer value. If this is called on a non-pointer
477 /// value, it returns 'this'.
478 Value *stripInBoundsConstantOffsets();
479 const Value *stripInBoundsConstantOffsets() const {
480 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
483 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
485 /// Stores the resulting constant offset stripped into the APInt provided.
486 /// The provided APInt will be extended or truncated as needed to be the
487 /// correct bitwidth for an offset of this pointer type.
489 /// If this is called on a non-pointer value, it returns 'this'.
490 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
492 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
493 APInt &Offset) const {
494 return const_cast<Value *>(this)
495 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
498 /// \brief Strip off pointer casts and inbounds GEPs.
500 /// Returns the original pointer value. If this is called on a non-pointer
501 /// value, it returns 'this'.
502 Value *stripInBoundsOffsets();
503 const Value *stripInBoundsOffsets() const {
504 return const_cast<Value*>(this)->stripInBoundsOffsets();
507 /// \brief Returns the number of bytes known to be dereferenceable for the
510 /// If CanBeNull is set by this function the pointer can either be null or be
511 /// dereferenceable up to the returned number of bytes.
512 unsigned getPointerDereferenceableBytes(const DataLayout &DL,
513 bool &CanBeNull) const;
515 /// \brief Returns an alignment of the pointer value.
517 /// Returns an alignment which is either specified explicitly, e.g. via
518 /// align attribute of a function argument, or guaranteed by DataLayout.
519 unsigned getPointerAlignment(const DataLayout &DL) const;
521 /// \brief Translate PHI node to its predecessor from the given basic block.
523 /// If this value is a PHI node with CurBB as its parent, return the value in
524 /// the PHI node corresponding to PredBB. If not, return ourself. This is
525 /// useful if you want to know the value something has in a predecessor
527 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
529 const Value *DoPHITranslation(const BasicBlock *CurBB,
530 const BasicBlock *PredBB) const{
531 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
534 /// \brief The maximum alignment for instructions.
536 /// This is the greatest alignment value supported by load, store, and alloca
537 /// instructions, and global values.
538 static const unsigned MaxAlignmentExponent = 29;
539 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
541 /// \brief Mutate the type of this Value to be of the specified type.
543 /// Note that this is an extremely dangerous operation which can create
544 /// completely invalid IR very easily. It is strongly recommended that you
545 /// recreate IR objects with the right types instead of mutating them in
547 void mutateType(Type *Ty) {
551 /// \brief Sort the use-list.
553 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
554 /// expected to compare two \a Use references.
555 template <class Compare> void sortUseList(Compare Cmp);
557 /// \brief Reverse the use-list.
558 void reverseUseList();
561 /// \brief Merge two lists together.
563 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
564 /// "equal" items from L before items from R.
566 /// \return the first element in the list.
568 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
569 template <class Compare>
570 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
572 Use **Next = &Merged;
597 /// \brief Tail-recursive helper for \a mergeUseLists().
599 /// \param[out] Next the first element in the list.
600 template <class Compare>
601 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
604 unsigned short getSubclassDataFromValue() const { return SubclassData; }
605 void setValueSubclassData(unsigned short D) { SubclassData = D; }
608 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
613 void Use::set(Value *V) {
614 if (Val) removeFromList();
616 if (V) V->addUse(*this);
619 Value *Use::operator=(Value *RHS) {
624 const Use &Use::operator=(const Use &RHS) {
629 template <class Compare> void Value::sortUseList(Compare Cmp) {
630 if (!UseList || !UseList->Next)
631 // No need to sort 0 or 1 uses.
634 // Note: this function completely ignores Prev pointers until the end when
635 // they're fixed en masse.
637 // Create a binomial vector of sorted lists, visiting uses one at a time and
638 // merging lists as necessary.
639 const unsigned MaxSlots = 32;
640 Use *Slots[MaxSlots];
642 // Collect the first use, turning it into a single-item list.
643 Use *Next = UseList->Next;
644 UseList->Next = nullptr;
645 unsigned NumSlots = 1;
648 // Collect all but the last use.
651 Next = Current->Next;
653 // Turn Current into a single-item list.
654 Current->Next = nullptr;
656 // Save Current in the first available slot, merging on collisions.
658 for (I = 0; I < NumSlots; ++I) {
662 // Merge two lists, doubling the size of Current and emptying slot I.
664 // Since the uses in Slots[I] originally preceded those in Current, send
665 // Slots[I] in as the left parameter to maintain a stable sort.
666 Current = mergeUseLists(Slots[I], Current, Cmp);
669 // Check if this is a new slot.
672 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
675 // Found an open slot.
679 // Merge all the lists together.
680 assert(Next && "Expected one more Use");
681 assert(!Next->Next && "Expected only one Use");
683 for (unsigned I = 0; I < NumSlots; ++I)
685 // Since the uses in Slots[I] originally preceded those in UseList, send
686 // Slots[I] in as the left parameter to maintain a stable sort.
687 UseList = mergeUseLists(Slots[I], UseList, Cmp);
689 // Fix the Prev pointers.
690 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
696 // isa - Provide some specializations of isa so that we don't have to include
697 // the subtype header files to test to see if the value is a subclass...
699 template <> struct isa_impl<Constant, Value> {
700 static inline bool doit(const Value &Val) {
701 return Val.getValueID() >= Value::ConstantFirstVal &&
702 Val.getValueID() <= Value::ConstantLastVal;
706 template <> struct isa_impl<ConstantData, Value> {
707 static inline bool doit(const Value &Val) {
708 return Val.getValueID() >= Value::ConstantDataFirstVal &&
709 Val.getValueID() <= Value::ConstantDataLastVal;
713 template <> struct isa_impl<ConstantAggregate, Value> {
714 static inline bool doit(const Value &Val) {
715 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
716 Val.getValueID() <= Value::ConstantAggregateLastVal;
720 template <> struct isa_impl<Argument, Value> {
721 static inline bool doit (const Value &Val) {
722 return Val.getValueID() == Value::ArgumentVal;
726 template <> struct isa_impl<InlineAsm, Value> {
727 static inline bool doit(const Value &Val) {
728 return Val.getValueID() == Value::InlineAsmVal;
732 template <> struct isa_impl<Instruction, Value> {
733 static inline bool doit(const Value &Val) {
734 return Val.getValueID() >= Value::InstructionVal;
738 template <> struct isa_impl<BasicBlock, Value> {
739 static inline bool doit(const Value &Val) {
740 return Val.getValueID() == Value::BasicBlockVal;
744 template <> struct isa_impl<Function, Value> {
745 static inline bool doit(const Value &Val) {
746 return Val.getValueID() == Value::FunctionVal;
750 template <> struct isa_impl<GlobalVariable, Value> {
751 static inline bool doit(const Value &Val) {
752 return Val.getValueID() == Value::GlobalVariableVal;
756 template <> struct isa_impl<GlobalAlias, Value> {
757 static inline bool doit(const Value &Val) {
758 return Val.getValueID() == Value::GlobalAliasVal;
762 template <> struct isa_impl<GlobalIFunc, Value> {
763 static inline bool doit(const Value &Val) {
764 return Val.getValueID() == Value::GlobalIFuncVal;
768 template <> struct isa_impl<GlobalIndirectSymbol, Value> {
769 static inline bool doit(const Value &Val) {
770 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
774 template <> struct isa_impl<GlobalValue, Value> {
775 static inline bool doit(const Value &Val) {
776 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
780 template <> struct isa_impl<GlobalObject, Value> {
781 static inline bool doit(const Value &Val) {
782 return isa<GlobalVariable>(Val) || isa<Function>(Val);
786 // Value* is only 4-byte aligned.
788 class PointerLikeTypeTraits<Value*> {
791 static inline void *getAsVoidPointer(PT P) { return P; }
792 static inline PT getFromVoidPointer(void *P) {
793 return static_cast<PT>(P);
795 enum { NumLowBitsAvailable = 2 };
798 // Create wrappers for C Binding types (see CBindingWrapping.h).
799 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
801 // Specialized opaque value conversions.
802 inline Value **unwrap(LLVMValueRef *Vals) {
803 return reinterpret_cast<Value**>(Vals);
807 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
809 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
813 return reinterpret_cast<T**>(Vals);
816 inline LLVMValueRef *wrap(const Value **Vals) {
817 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
820 } // End llvm namespace