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 /// \brief LLVM Value Representation
57 /// This is a very important LLVM class. It is the base class of all values
58 /// computed by a program that may be used as operands to other values. Value is
59 /// the super class of other important classes such as Instruction and Function.
60 /// All Values have a Type. Type is not a subclass of Value. Some values can
61 /// have a name and they belong to some Module. Setting the name on the Value
62 /// automatically updates the module's symbol table.
64 /// Every value has a "use list" that keeps track of which other Values are
65 /// using this Value. A Value can also have an arbitrary number of ValueHandle
66 /// objects that watch it and listen to RAUW and Destroy events. See
67 /// llvm/IR/ValueHandle.h for details.
72 friend class ValueAsMetadata; // Allow access to NameAndIsUsedByMD.
73 friend class ValueHandleBase;
74 PointerIntPair<ValueName *, 1> NameAndIsUsedByMD;
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
104 unsigned NumOperands;
107 template <typename UseT> // UseT == 'Use' or 'const Use'
108 class use_iterator_impl
109 : public std::iterator<std::forward_iterator_tag, UseT *> {
111 explicit use_iterator_impl(UseT *u) : U(u) {}
115 use_iterator_impl() : U() {}
117 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
118 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
120 use_iterator_impl &operator++() { // Preincrement
121 assert(U && "Cannot increment end iterator!");
125 use_iterator_impl operator++(int) { // Postincrement
131 UseT &operator*() const {
132 assert(U && "Cannot dereference end iterator!");
136 UseT *operator->() const { return &operator*(); }
138 operator use_iterator_impl<const UseT>() const {
139 return use_iterator_impl<const UseT>(U);
143 template <typename UserTy> // UserTy == 'User' or 'const User'
144 class user_iterator_impl
145 : public std::iterator<std::forward_iterator_tag, UserTy *> {
146 use_iterator_impl<Use> UI;
147 explicit user_iterator_impl(Use *U) : UI(U) {}
151 user_iterator_impl() {}
153 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
154 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
156 /// \brief Returns true if this iterator is equal to user_end() on the value.
157 bool atEnd() const { return *this == user_iterator_impl(); }
159 user_iterator_impl &operator++() { // Preincrement
163 user_iterator_impl operator++(int) { // Postincrement
169 // Retrieve a pointer to the current User.
170 UserTy *operator*() const {
171 return UI->getUser();
174 UserTy *operator->() const { return operator*(); }
176 operator user_iterator_impl<const UserTy>() const {
177 return user_iterator_impl<const UserTy>(*UI);
180 Use &getUse() const { return *UI; }
183 void operator=(const Value &) = delete;
184 Value(const Value &) = delete;
187 Value(Type *Ty, unsigned scid);
191 /// \brief Support for debugging, callable in GDB: V->dump()
194 /// \brief 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.
199 /// This is useful when you just want to print 'int %reg126', not the
200 /// instruction that generated it. If you specify a Module for context, then
201 /// even constanst get pretty-printed; for example, the type of a null
202 /// pointer is printed symbolically.
203 void printAsOperand(raw_ostream &O, bool PrintType = true,
204 const Module *M = nullptr) const;
206 /// \brief All values are typed, get the type of this value.
207 Type *getType() const { return VTy; }
209 /// \brief All values hold a context through their type.
210 LLVMContext &getContext() const;
212 // \brief All values can potentially be named.
213 bool hasName() const { return getValueName() != nullptr; }
214 ValueName *getValueName() const { return NameAndIsUsedByMD.getPointer(); }
215 void setValueName(ValueName *VN) { NameAndIsUsedByMD.setPointer(VN); }
218 void destroyValueName();
221 /// \brief Return a constant reference to the value's name.
223 /// This is cheap and guaranteed to return the same reference as long as the
224 /// value is not modified.
225 StringRef getName() const;
227 /// \brief Change the name of the value.
229 /// Choose a new unique name if the provided name is taken.
231 /// \param Name The new name; or "" if the value's name should be removed.
232 void setName(const Twine &Name);
235 /// \brief Transfer the name from V to this value.
237 /// After taking V's name, sets V's name to empty.
239 /// \note It is an error to call V->takeName(V).
240 void takeName(Value *V);
242 /// \brief Change all uses of this to point to a new Value.
244 /// Go through the uses list for this definition and make each use point to
245 /// "V" instead of "this". After this completes, 'this's use list is
246 /// guaranteed to be empty.
247 void replaceAllUsesWith(Value *V);
249 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
250 /// make each use point to "V" instead of "this" when the use is outside the
251 /// block. 'This's use list is expected to have at least one element.
252 /// Unlike replaceAllUsesWith this function does not support basic block
253 /// values or constant users.
254 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
256 //----------------------------------------------------------------------
257 // Methods for handling the chain of uses of this Value.
259 bool use_empty() const { return UseList == nullptr; }
261 typedef use_iterator_impl<Use> use_iterator;
262 typedef use_iterator_impl<const Use> const_use_iterator;
263 use_iterator use_begin() { return use_iterator(UseList); }
264 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
265 use_iterator use_end() { return use_iterator(); }
266 const_use_iterator use_end() const { return const_use_iterator(); }
267 iterator_range<use_iterator> uses() {
268 return iterator_range<use_iterator>(use_begin(), use_end());
270 iterator_range<const_use_iterator> uses() const {
271 return iterator_range<const_use_iterator>(use_begin(), use_end());
274 bool user_empty() const { return UseList == nullptr; }
276 typedef user_iterator_impl<User> user_iterator;
277 typedef user_iterator_impl<const User> const_user_iterator;
278 user_iterator user_begin() { return user_iterator(UseList); }
279 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
280 user_iterator user_end() { return user_iterator(); }
281 const_user_iterator user_end() const { return const_user_iterator(); }
282 User *user_back() { return *user_begin(); }
283 const User *user_back() const { return *user_begin(); }
284 iterator_range<user_iterator> users() {
285 return iterator_range<user_iterator>(user_begin(), user_end());
287 iterator_range<const_user_iterator> users() const {
288 return iterator_range<const_user_iterator>(user_begin(), user_end());
291 /// \brief Return true if there is exactly one user of this value.
293 /// This is specialized because it is a common request and does not require
294 /// traversing the whole use list.
295 bool hasOneUse() const {
296 const_use_iterator I = use_begin(), E = use_end();
297 if (I == E) return false;
301 /// \brief Return true if this Value has exactly N users.
302 bool hasNUses(unsigned N) const;
304 /// \brief Return true if this value has N users or more.
306 /// This is logically equivalent to getNumUses() >= N.
307 bool hasNUsesOrMore(unsigned N) const;
309 /// \brief Check if this value is used in the specified basic block.
310 bool isUsedInBasicBlock(const BasicBlock *BB) const;
312 /// \brief This method computes the number of uses of this Value.
314 /// This is a linear time operation. Use hasOneUse, hasNUses, or
315 /// hasNUsesOrMore to check for specific values.
316 unsigned getNumUses() const;
318 /// \brief This method should only be used by the Use class.
319 void addUse(Use &U) { U.addToList(&UseList); }
321 /// \brief Concrete subclass of this.
323 /// An enumeration for keeping track of the concrete subclass of Value that
324 /// is actually instantiated. Values of this enumeration are kept in the
325 /// Value classes SubclassID field. They are used for concrete type
328 ArgumentVal, // This is an instance of Argument
329 BasicBlockVal, // This is an instance of BasicBlock
330 FunctionVal, // This is an instance of Function
331 GlobalAliasVal, // This is an instance of GlobalAlias
332 GlobalVariableVal, // This is an instance of GlobalVariable
333 UndefValueVal, // This is an instance of UndefValue
334 BlockAddressVal, // This is an instance of BlockAddress
335 ConstantExprVal, // This is an instance of ConstantExpr
336 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
337 ConstantDataArrayVal, // This is an instance of ConstantDataArray
338 ConstantDataVectorVal, // This is an instance of ConstantDataVector
339 ConstantIntVal, // This is an instance of ConstantInt
340 ConstantFPVal, // This is an instance of ConstantFP
341 ConstantArrayVal, // This is an instance of ConstantArray
342 ConstantStructVal, // This is an instance of ConstantStruct
343 ConstantVectorVal, // This is an instance of ConstantVector
344 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
345 MetadataAsValueVal, // This is an instance of MetadataAsValue
346 InlineAsmVal, // This is an instance of InlineAsm
347 InstructionVal, // This is an instance of Instruction
348 // Enum values starting at InstructionVal are used for Instructions;
349 // don't add new values here!
352 ConstantFirstVal = FunctionVal,
353 ConstantLastVal = ConstantPointerNullVal
356 /// \brief Return an ID for the concrete type of this object.
358 /// This is used to implement the classof checks. This should not be used
359 /// for any other purpose, as the values may change as LLVM evolves. Also,
360 /// note that for instructions, the Instruction's opcode is added to
361 /// InstructionVal. So this means three things:
362 /// # there is no value with code InstructionVal (no opcode==0).
363 /// # there are more possible values for the value type than in ValueTy enum.
364 /// # the InstructionVal enumerator must be the highest valued enumerator in
365 /// the ValueTy enum.
366 unsigned getValueID() const {
370 /// \brief Return the raw optional flags value contained in this value.
372 /// This should only be used when testing two Values for equivalence.
373 unsigned getRawSubclassOptionalData() const {
374 return SubclassOptionalData;
377 /// \brief Clear the optional flags contained in this value.
378 void clearSubclassOptionalData() {
379 SubclassOptionalData = 0;
382 /// \brief Check the optional flags for equality.
383 bool hasSameSubclassOptionalData(const Value *V) const {
384 return SubclassOptionalData == V->SubclassOptionalData;
387 /// \brief Clear any optional flags not set in the given Value.
388 void intersectOptionalDataWith(const Value *V) {
389 SubclassOptionalData &= V->SubclassOptionalData;
392 /// \brief Return true if there is a value handle associated with this value.
393 bool hasValueHandle() const { return HasValueHandle; }
395 /// \brief Return true if there is metadata referencing this value.
396 bool isUsedByMetadata() const { return NameAndIsUsedByMD.getInt(); }
398 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
400 /// Returns the original uncasted value. If this is called on a non-pointer
401 /// value, it returns 'this'.
402 Value *stripPointerCasts();
403 const Value *stripPointerCasts() const {
404 return const_cast<Value*>(this)->stripPointerCasts();
407 /// \brief Strip off pointer casts and all-zero GEPs.
409 /// Returns the original uncasted value. If this is called on a non-pointer
410 /// value, it returns 'this'.
411 Value *stripPointerCastsNoFollowAliases();
412 const Value *stripPointerCastsNoFollowAliases() const {
413 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
416 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
418 /// Returns the original pointer value. If this is called on a non-pointer
419 /// value, it returns 'this'.
420 Value *stripInBoundsConstantOffsets();
421 const Value *stripInBoundsConstantOffsets() const {
422 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
425 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
427 /// Stores the resulting constant offset stripped into the APInt provided.
428 /// The provided APInt will be extended or truncated as needed to be the
429 /// correct bitwidth for an offset of this pointer type.
431 /// If this is called on a non-pointer value, it returns 'this'.
432 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
434 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
435 APInt &Offset) const {
436 return const_cast<Value *>(this)
437 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
440 /// \brief Strip off pointer casts and inbounds GEPs.
442 /// Returns the original pointer value. If this is called on a non-pointer
443 /// value, it returns 'this'.
444 Value *stripInBoundsOffsets();
445 const Value *stripInBoundsOffsets() const {
446 return const_cast<Value*>(this)->stripInBoundsOffsets();
449 /// \brief Check if this is always a dereferenceable pointer.
451 /// Test if this value is always a pointer to allocated and suitably aligned
452 /// memory for a simple load or store.
453 bool isDereferenceablePointer(const DataLayout &DL) const;
455 /// \brief Translate PHI node to its predecessor from the given basic block.
457 /// If this value is a PHI node with CurBB as its parent, return the value in
458 /// the PHI node corresponding to PredBB. If not, return ourself. This is
459 /// useful if you want to know the value something has in a predecessor
461 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
463 const Value *DoPHITranslation(const BasicBlock *CurBB,
464 const BasicBlock *PredBB) const{
465 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
468 /// \brief The maximum alignment for instructions.
470 /// This is the greatest alignment value supported by load, store, and alloca
471 /// instructions, and global values.
472 static const unsigned MaxAlignmentExponent = 29;
473 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
475 /// \brief Mutate the type of this Value to be of the specified type.
477 /// Note that this is an extremely dangerous operation which can create
478 /// completely invalid IR very easily. It is strongly recommended that you
479 /// recreate IR objects with the right types instead of mutating them in
481 void mutateType(Type *Ty) {
485 /// \brief Sort the use-list.
487 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
488 /// expected to compare two \a Use references.
489 template <class Compare> void sortUseList(Compare Cmp);
491 /// \brief Reverse the use-list.
492 void reverseUseList();
495 /// \brief Merge two lists together.
497 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
498 /// "equal" items from L before items from R.
500 /// \return the first element in the list.
502 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
503 template <class Compare>
504 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
506 mergeUseListsImpl(L, R, &Merged, Cmp);
510 /// \brief Tail-recursive helper for \a mergeUseLists().
512 /// \param[out] Next the first element in the list.
513 template <class Compare>
514 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
517 unsigned short getSubclassDataFromValue() const { return SubclassData; }
518 void setValueSubclassData(unsigned short D) { SubclassData = D; }
521 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
526 void Use::set(Value *V) {
527 if (Val) removeFromList();
529 if (V) V->addUse(*this);
532 template <class Compare> void Value::sortUseList(Compare Cmp) {
533 if (!UseList || !UseList->Next)
534 // No need to sort 0 or 1 uses.
537 // Note: this function completely ignores Prev pointers until the end when
538 // they're fixed en masse.
540 // Create a binomial vector of sorted lists, visiting uses one at a time and
541 // merging lists as necessary.
542 const unsigned MaxSlots = 32;
543 Use *Slots[MaxSlots];
545 // Collect the first use, turning it into a single-item list.
546 Use *Next = UseList->Next;
547 UseList->Next = nullptr;
548 unsigned NumSlots = 1;
551 // Collect all but the last use.
554 Next = Current->Next;
556 // Turn Current into a single-item list.
557 Current->Next = nullptr;
559 // Save Current in the first available slot, merging on collisions.
561 for (I = 0; I < NumSlots; ++I) {
565 // Merge two lists, doubling the size of Current and emptying slot I.
567 // Since the uses in Slots[I] originally preceded those in Current, send
568 // Slots[I] in as the left parameter to maintain a stable sort.
569 Current = mergeUseLists(Slots[I], Current, Cmp);
572 // Check if this is a new slot.
575 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
578 // Found an open slot.
582 // Merge all the lists together.
583 assert(Next && "Expected one more Use");
584 assert(!Next->Next && "Expected only one Use");
586 for (unsigned I = 0; I < NumSlots; ++I)
588 // Since the uses in Slots[I] originally preceded those in UseList, send
589 // Slots[I] in as the left parameter to maintain a stable sort.
590 UseList = mergeUseLists(Slots[I], UseList, Cmp);
592 // Fix the Prev pointers.
593 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
599 template <class Compare>
600 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
611 mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
615 mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
618 // isa - Provide some specializations of isa so that we don't have to include
619 // the subtype header files to test to see if the value is a subclass...
621 template <> struct isa_impl<Constant, Value> {
622 static inline bool doit(const Value &Val) {
623 return Val.getValueID() >= Value::ConstantFirstVal &&
624 Val.getValueID() <= Value::ConstantLastVal;
628 template <> struct isa_impl<Argument, Value> {
629 static inline bool doit (const Value &Val) {
630 return Val.getValueID() == Value::ArgumentVal;
634 template <> struct isa_impl<InlineAsm, Value> {
635 static inline bool doit(const Value &Val) {
636 return Val.getValueID() == Value::InlineAsmVal;
640 template <> struct isa_impl<Instruction, Value> {
641 static inline bool doit(const Value &Val) {
642 return Val.getValueID() >= Value::InstructionVal;
646 template <> struct isa_impl<BasicBlock, Value> {
647 static inline bool doit(const Value &Val) {
648 return Val.getValueID() == Value::BasicBlockVal;
652 template <> struct isa_impl<Function, Value> {
653 static inline bool doit(const Value &Val) {
654 return Val.getValueID() == Value::FunctionVal;
658 template <> struct isa_impl<GlobalVariable, Value> {
659 static inline bool doit(const Value &Val) {
660 return Val.getValueID() == Value::GlobalVariableVal;
664 template <> struct isa_impl<GlobalAlias, Value> {
665 static inline bool doit(const Value &Val) {
666 return Val.getValueID() == Value::GlobalAliasVal;
670 template <> struct isa_impl<GlobalValue, Value> {
671 static inline bool doit(const Value &Val) {
672 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
676 template <> struct isa_impl<GlobalObject, Value> {
677 static inline bool doit(const Value &Val) {
678 return isa<GlobalVariable>(Val) || isa<Function>(Val);
682 // Value* is only 4-byte aligned.
684 class PointerLikeTypeTraits<Value*> {
687 static inline void *getAsVoidPointer(PT P) { return P; }
688 static inline PT getFromVoidPointer(void *P) {
689 return static_cast<PT>(P);
691 enum { NumLowBitsAvailable = 2 };
694 // Create wrappers for C Binding types (see CBindingWrapping.h).
695 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
697 /* Specialized opaque value conversions.
699 inline Value **unwrap(LLVMValueRef *Vals) {
700 return reinterpret_cast<Value**>(Vals);
704 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
706 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
710 return reinterpret_cast<T**>(Vals);
713 inline LLVMValueRef *wrap(const Value **Vals) {
714 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
717 } // End llvm namespace