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 = 28 };
108 unsigned NumUserOperands : NumUserOperandsBits;
112 bool HasHungOffUses : 1;
113 bool HasDescriptor : 1;
116 template <typename UseT> // UseT == 'Use' or 'const Use'
117 class use_iterator_impl
118 : public std::iterator<std::forward_iterator_tag, UseT *> {
120 explicit use_iterator_impl(UseT *u) : U(u) {}
124 use_iterator_impl() : U() {}
126 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
127 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
129 use_iterator_impl &operator++() { // Preincrement
130 assert(U && "Cannot increment end iterator!");
134 use_iterator_impl operator++(int) { // Postincrement
140 UseT &operator*() const {
141 assert(U && "Cannot dereference end iterator!");
145 UseT *operator->() const { return &operator*(); }
147 operator use_iterator_impl<const UseT>() const {
148 return use_iterator_impl<const UseT>(U);
152 template <typename UserTy> // UserTy == 'User' or 'const User'
153 class user_iterator_impl
154 : public std::iterator<std::forward_iterator_tag, UserTy *> {
155 use_iterator_impl<Use> UI;
156 explicit user_iterator_impl(Use *U) : UI(U) {}
160 user_iterator_impl() {}
162 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
163 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
165 /// \brief Returns true if this iterator is equal to user_end() on the value.
166 bool atEnd() const { return *this == user_iterator_impl(); }
168 user_iterator_impl &operator++() { // Preincrement
172 user_iterator_impl operator++(int) { // Postincrement
178 // Retrieve a pointer to the current User.
179 UserTy *operator*() const {
180 return UI->getUser();
183 UserTy *operator->() const { return operator*(); }
185 operator user_iterator_impl<const UserTy>() const {
186 return user_iterator_impl<const UserTy>(*UI);
189 Use &getUse() const { return *UI; }
192 void operator=(const Value &) = delete;
193 Value(const Value &) = delete;
196 Value(Type *Ty, unsigned scid);
200 /// \brief Support for debugging, callable in GDB: V->dump()
203 /// \brief Implement operator<< on Value.
205 void print(raw_ostream &O, bool IsForDebug = false) const;
206 void print(raw_ostream &O, ModuleSlotTracker &MST,
207 bool IsForDebug = false) const;
210 /// \brief Print the name of this Value out to the specified raw_ostream.
212 /// This is useful when you just want to print 'int %reg126', not the
213 /// instruction that generated it. If you specify a Module for context, then
214 /// even constanst get pretty-printed; for example, the type of a null
215 /// pointer is printed symbolically.
217 void printAsOperand(raw_ostream &O, bool PrintType = true,
218 const Module *M = nullptr) const;
219 void printAsOperand(raw_ostream &O, bool PrintType,
220 ModuleSlotTracker &MST) const;
223 /// \brief All values are typed, get the type of this value.
224 Type *getType() const { return VTy; }
226 /// \brief All values hold a context through their type.
227 LLVMContext &getContext() const;
229 // \brief All values can potentially be named.
230 bool hasName() const { return HasName; }
231 ValueName *getValueName() const;
232 void setValueName(ValueName *VN);
235 void destroyValueName();
236 void setNameImpl(const Twine &Name);
239 /// \brief Return a constant reference to the value's name.
241 /// This is cheap and guaranteed to return the same reference as long as the
242 /// value is not modified.
243 StringRef getName() const;
245 /// \brief Change the name of the value.
247 /// Choose a new unique name if the provided name is taken.
249 /// \param Name The new name; or "" if the value's name should be removed.
250 void setName(const Twine &Name);
253 /// \brief Transfer the name from V to this value.
255 /// After taking V's name, sets V's name to empty.
257 /// \note It is an error to call V->takeName(V).
258 void takeName(Value *V);
260 /// \brief Change all uses of this to point to a new Value.
262 /// Go through the uses list for this definition and make each use point to
263 /// "V" instead of "this". After this completes, 'this's use list is
264 /// guaranteed to be empty.
265 void replaceAllUsesWith(Value *V);
267 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
268 /// make each use point to "V" instead of "this" when the use is outside the
269 /// block. 'This's use list is expected to have at least one element.
270 /// Unlike replaceAllUsesWith this function does not support basic block
271 /// values or constant users.
272 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
274 //----------------------------------------------------------------------
275 // Methods for handling the chain of uses of this Value.
277 bool use_empty() const { return UseList == nullptr; }
279 typedef use_iterator_impl<Use> use_iterator;
280 typedef use_iterator_impl<const Use> const_use_iterator;
281 use_iterator use_begin() { return use_iterator(UseList); }
282 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
283 use_iterator use_end() { return use_iterator(); }
284 const_use_iterator use_end() const { return const_use_iterator(); }
285 iterator_range<use_iterator> uses() {
286 return make_range(use_begin(), use_end());
288 iterator_range<const_use_iterator> uses() const {
289 return make_range(use_begin(), use_end());
292 bool user_empty() const { return UseList == nullptr; }
294 typedef user_iterator_impl<User> user_iterator;
295 typedef user_iterator_impl<const User> const_user_iterator;
296 user_iterator user_begin() { return user_iterator(UseList); }
297 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
298 user_iterator user_end() { return user_iterator(); }
299 const_user_iterator user_end() const { return const_user_iterator(); }
300 User *user_back() { return *user_begin(); }
301 const User *user_back() const { return *user_begin(); }
302 iterator_range<user_iterator> users() {
303 return make_range(user_begin(), user_end());
305 iterator_range<const_user_iterator> users() const {
306 return make_range(user_begin(), user_end());
309 /// \brief Return true if there is exactly one user of this value.
311 /// This is specialized because it is a common request and does not require
312 /// traversing the whole use list.
313 bool hasOneUse() const {
314 const_use_iterator I = use_begin(), E = use_end();
315 if (I == E) return false;
319 /// \brief Return true if this Value has exactly N users.
320 bool hasNUses(unsigned N) const;
322 /// \brief Return true if this value has N users or more.
324 /// This is logically equivalent to getNumUses() >= N.
325 bool hasNUsesOrMore(unsigned N) const;
327 /// \brief Check if this value is used in the specified basic block.
328 bool isUsedInBasicBlock(const BasicBlock *BB) const;
330 /// \brief This method computes the number of uses of this Value.
332 /// This is a linear time operation. Use hasOneUse, hasNUses, or
333 /// hasNUsesOrMore to check for specific values.
334 unsigned getNumUses() const;
336 /// \brief This method should only be used by the Use class.
337 void addUse(Use &U) { U.addToList(&UseList); }
339 /// \brief Concrete subclass of this.
341 /// An enumeration for keeping track of the concrete subclass of Value that
342 /// is actually instantiated. Values of this enumeration are kept in the
343 /// Value classes SubclassID field. They are used for concrete type
346 #define HANDLE_VALUE(Name) Name##Val,
347 #include "llvm/IR/Value.def"
350 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
351 #include "llvm/IR/Value.def"
354 /// \brief Return an ID for the concrete type of this object.
356 /// This is used to implement the classof checks. This should not be used
357 /// for any other purpose, as the values may change as LLVM evolves. Also,
358 /// note that for instructions, the Instruction's opcode is added to
359 /// InstructionVal. So this means three things:
360 /// # there is no value with code InstructionVal (no opcode==0).
361 /// # there are more possible values for the value type than in ValueTy enum.
362 /// # the InstructionVal enumerator must be the highest valued enumerator in
363 /// the ValueTy enum.
364 unsigned getValueID() const {
368 /// \brief Return the raw optional flags value contained in this value.
370 /// This should only be used when testing two Values for equivalence.
371 unsigned getRawSubclassOptionalData() const {
372 return SubclassOptionalData;
375 /// \brief Clear the optional flags contained in this value.
376 void clearSubclassOptionalData() {
377 SubclassOptionalData = 0;
380 /// \brief Check the optional flags for equality.
381 bool hasSameSubclassOptionalData(const Value *V) const {
382 return SubclassOptionalData == V->SubclassOptionalData;
385 /// \brief Clear any optional flags not set in the given Value.
386 void intersectOptionalDataWith(const Value *V) {
387 SubclassOptionalData &= V->SubclassOptionalData;
390 /// \brief Return true if there is a value handle associated with this value.
391 bool hasValueHandle() const { return HasValueHandle; }
393 /// \brief Return true if there is metadata referencing this value.
394 bool isUsedByMetadata() const { return IsUsedByMD; }
396 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
398 /// Returns the original uncasted value. If this is called on a non-pointer
399 /// value, it returns 'this'.
400 Value *stripPointerCasts();
401 const Value *stripPointerCasts() const {
402 return const_cast<Value*>(this)->stripPointerCasts();
405 /// \brief Strip off pointer casts and all-zero GEPs.
407 /// Returns the original uncasted value. If this is called on a non-pointer
408 /// value, it returns 'this'.
409 Value *stripPointerCastsNoFollowAliases();
410 const Value *stripPointerCastsNoFollowAliases() const {
411 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
414 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
416 /// Returns the original pointer value. If this is called on a non-pointer
417 /// value, it returns 'this'.
418 Value *stripInBoundsConstantOffsets();
419 const Value *stripInBoundsConstantOffsets() const {
420 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
423 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
425 /// Stores the resulting constant offset stripped into the APInt provided.
426 /// The provided APInt will be extended or truncated as needed to be the
427 /// correct bitwidth for an offset of this pointer type.
429 /// If this is called on a non-pointer value, it returns 'this'.
430 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
432 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
433 APInt &Offset) const {
434 return const_cast<Value *>(this)
435 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
438 /// \brief Strip off pointer casts and inbounds GEPs.
440 /// Returns the original pointer value. If this is called on a non-pointer
441 /// value, it returns 'this'.
442 Value *stripInBoundsOffsets();
443 const Value *stripInBoundsOffsets() const {
444 return const_cast<Value*>(this)->stripInBoundsOffsets();
447 /// \brief Translate PHI node to its predecessor from the given basic block.
449 /// If this value is a PHI node with CurBB as its parent, return the value in
450 /// the PHI node corresponding to PredBB. If not, return ourself. This is
451 /// useful if you want to know the value something has in a predecessor
453 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
455 const Value *DoPHITranslation(const BasicBlock *CurBB,
456 const BasicBlock *PredBB) const{
457 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
460 /// \brief The maximum alignment for instructions.
462 /// This is the greatest alignment value supported by load, store, and alloca
463 /// instructions, and global values.
464 static const unsigned MaxAlignmentExponent = 29;
465 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
467 /// \brief Mutate the type of this Value to be of the specified type.
469 /// Note that this is an extremely dangerous operation which can create
470 /// completely invalid IR very easily. It is strongly recommended that you
471 /// recreate IR objects with the right types instead of mutating them in
473 void mutateType(Type *Ty) {
477 /// \brief Sort the use-list.
479 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
480 /// expected to compare two \a Use references.
481 template <class Compare> void sortUseList(Compare Cmp);
483 /// \brief Reverse the use-list.
484 void reverseUseList();
487 /// \brief Merge two lists together.
489 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
490 /// "equal" items from L before items from R.
492 /// \return the first element in the list.
494 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
495 template <class Compare>
496 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
498 Use **Next = &Merged;
523 /// \brief Tail-recursive helper for \a mergeUseLists().
525 /// \param[out] Next the first element in the list.
526 template <class Compare>
527 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
530 unsigned short getSubclassDataFromValue() const { return SubclassData; }
531 void setValueSubclassData(unsigned short D) { SubclassData = D; }
534 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
539 void Use::set(Value *V) {
540 if (Val) removeFromList();
542 if (V) V->addUse(*this);
545 template <class Compare> void Value::sortUseList(Compare Cmp) {
546 if (!UseList || !UseList->Next)
547 // No need to sort 0 or 1 uses.
550 // Note: this function completely ignores Prev pointers until the end when
551 // they're fixed en masse.
553 // Create a binomial vector of sorted lists, visiting uses one at a time and
554 // merging lists as necessary.
555 const unsigned MaxSlots = 32;
556 Use *Slots[MaxSlots];
558 // Collect the first use, turning it into a single-item list.
559 Use *Next = UseList->Next;
560 UseList->Next = nullptr;
561 unsigned NumSlots = 1;
564 // Collect all but the last use.
567 Next = Current->Next;
569 // Turn Current into a single-item list.
570 Current->Next = nullptr;
572 // Save Current in the first available slot, merging on collisions.
574 for (I = 0; I < NumSlots; ++I) {
578 // Merge two lists, doubling the size of Current and emptying slot I.
580 // Since the uses in Slots[I] originally preceded those in Current, send
581 // Slots[I] in as the left parameter to maintain a stable sort.
582 Current = mergeUseLists(Slots[I], Current, Cmp);
585 // Check if this is a new slot.
588 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
591 // Found an open slot.
595 // Merge all the lists together.
596 assert(Next && "Expected one more Use");
597 assert(!Next->Next && "Expected only one Use");
599 for (unsigned I = 0; I < NumSlots; ++I)
601 // Since the uses in Slots[I] originally preceded those in UseList, send
602 // Slots[I] in as the left parameter to maintain a stable sort.
603 UseList = mergeUseLists(Slots[I], UseList, Cmp);
605 // Fix the Prev pointers.
606 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
612 // isa - Provide some specializations of isa so that we don't have to include
613 // the subtype header files to test to see if the value is a subclass...
615 template <> struct isa_impl<Constant, Value> {
616 static inline bool doit(const Value &Val) {
617 return Val.getValueID() >= Value::ConstantFirstVal &&
618 Val.getValueID() <= Value::ConstantLastVal;
622 template <> struct isa_impl<Argument, Value> {
623 static inline bool doit (const Value &Val) {
624 return Val.getValueID() == Value::ArgumentVal;
628 template <> struct isa_impl<InlineAsm, Value> {
629 static inline bool doit(const Value &Val) {
630 return Val.getValueID() == Value::InlineAsmVal;
634 template <> struct isa_impl<Instruction, Value> {
635 static inline bool doit(const Value &Val) {
636 return Val.getValueID() >= Value::InstructionVal;
640 template <> struct isa_impl<BasicBlock, Value> {
641 static inline bool doit(const Value &Val) {
642 return Val.getValueID() == Value::BasicBlockVal;
646 template <> struct isa_impl<Function, Value> {
647 static inline bool doit(const Value &Val) {
648 return Val.getValueID() == Value::FunctionVal;
652 template <> struct isa_impl<GlobalVariable, Value> {
653 static inline bool doit(const Value &Val) {
654 return Val.getValueID() == Value::GlobalVariableVal;
658 template <> struct isa_impl<GlobalAlias, Value> {
659 static inline bool doit(const Value &Val) {
660 return Val.getValueID() == Value::GlobalAliasVal;
664 template <> struct isa_impl<GlobalValue, Value> {
665 static inline bool doit(const Value &Val) {
666 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
670 template <> struct isa_impl<GlobalObject, Value> {
671 static inline bool doit(const Value &Val) {
672 return isa<GlobalVariable>(Val) || isa<Function>(Val);
676 // Value* is only 4-byte aligned.
678 class PointerLikeTypeTraits<Value*> {
681 static inline void *getAsVoidPointer(PT P) { return P; }
682 static inline PT getFromVoidPointer(void *P) {
683 return static_cast<PT>(P);
685 enum { NumLowBitsAvailable = 2 };
688 // Create wrappers for C Binding types (see CBindingWrapping.h).
689 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
691 /* Specialized opaque value conversions.
693 inline Value **unwrap(LLVMValueRef *Vals) {
694 return reinterpret_cast<Value**>(Vals);
698 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
700 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
704 return reinterpret_cast<T**>(Vals);
707 inline LLVMValueRef *wrap(const Value **Vals) {
708 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
711 } // End llvm namespace