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;
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 ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
74 friend class ValueHandleBase;
77 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
78 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
80 /// \brief Hold subclass data that can be dropped.
82 /// This member is similar to SubclassData, however it is for holding
83 /// information which may be used to aid optimization, but which may be
84 /// cleared to zero without affecting conservative interpretation.
85 unsigned char SubclassOptionalData : 7;
88 /// \brief Hold arbitrary subclass data.
90 /// This member is defined by this class, but is not used for anything.
91 /// Subclasses can use it to hold whatever state they find useful. This
92 /// field is initialized to zero by the ctor.
93 unsigned short SubclassData;
95 template <typename UseT> // UseT == 'Use' or 'const Use'
96 class use_iterator_impl
97 : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
98 typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
101 explicit use_iterator_impl(UseT *u) : U(u) {}
105 typedef typename super::reference reference;
106 typedef typename super::pointer pointer;
108 use_iterator_impl() : U() {}
110 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
111 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
113 use_iterator_impl &operator++() { // Preincrement
114 assert(U && "Cannot increment end iterator!");
118 use_iterator_impl operator++(int) { // Postincrement
124 UseT &operator*() const {
125 assert(U && "Cannot dereference end iterator!");
129 UseT *operator->() const { return &operator*(); }
131 operator use_iterator_impl<const UseT>() const {
132 return use_iterator_impl<const UseT>(U);
136 template <typename UserTy> // UserTy == 'User' or 'const User'
137 class user_iterator_impl
138 : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
139 typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
141 use_iterator_impl<Use> UI;
142 explicit user_iterator_impl(Use *U) : UI(U) {}
146 typedef typename super::reference reference;
147 typedef typename super::pointer pointer;
149 user_iterator_impl() {}
151 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
152 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
154 /// \brief Returns true if this iterator is equal to user_end() on the value.
155 bool atEnd() const { return *this == user_iterator_impl(); }
157 user_iterator_impl &operator++() { // Preincrement
161 user_iterator_impl operator++(int) { // Postincrement
167 // Retrieve a pointer to the current User.
168 UserTy *operator*() const {
169 return UI->getUser();
172 UserTy *operator->() const { return operator*(); }
174 operator user_iterator_impl<const UserTy>() const {
175 return user_iterator_impl<const UserTy>(*UI);
178 Use &getUse() const { return *UI; }
180 /// \brief Return the operand # of this use in its User.
182 /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
183 unsigned getOperandNo() const { return UI->getOperandNo(); }
186 void operator=(const Value &) LLVM_DELETED_FUNCTION;
187 Value(const Value &) LLVM_DELETED_FUNCTION;
190 Value(Type *Ty, unsigned scid);
194 /// \brief Support for debugging, callable in GDB: V->dump()
197 /// \brief Implement operator<< on Value.
198 void print(raw_ostream &O) const;
200 /// \brief Print the name of this Value out to the specified raw_ostream.
202 /// This is useful when you just want to print 'int %reg126', not the
203 /// instruction that generated it. If you specify a Module for context, then
204 /// even constanst get pretty-printed; for example, the type of a null
205 /// pointer is printed symbolically.
206 void printAsOperand(raw_ostream &O, bool PrintType = true,
207 const Module *M = nullptr) const;
209 /// \brief All values are typed, get the type of this value.
210 Type *getType() const { return VTy; }
212 /// \brief All values hold a context through their type.
213 LLVMContext &getContext() const;
215 // \brief All values can potentially be named.
216 bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
217 ValueName *getValueName() const { return Name; }
218 void setValueName(ValueName *VN) { Name = VN; }
220 /// \brief Return a constant reference to the value's name.
222 /// This is cheap and guaranteed to return the same reference as long as the
223 /// value is not modified.
224 StringRef getName() const;
226 /// \brief Change the name of the value.
228 /// Choose a new unique name if the provided name is taken.
230 /// \param Name The new name; or "" if the value's name should be removed.
231 void setName(const Twine &Name);
234 /// \brief Transfer the name from V to this value.
236 /// After taking V's name, sets V's name to empty.
238 /// \note It is an error to call V->takeName(V).
239 void takeName(Value *V);
241 /// \brief Change all uses of this to point to a new Value.
243 /// Go through the uses list for this definition and make each use point to
244 /// "V" instead of "this". After this completes, 'this's use list is
245 /// guaranteed to be empty.
246 void replaceAllUsesWith(Value *V);
248 //----------------------------------------------------------------------
249 // Methods for handling the chain of uses of this Value.
251 bool use_empty() const { return UseList == nullptr; }
253 typedef use_iterator_impl<Use> use_iterator;
254 typedef use_iterator_impl<const Use> const_use_iterator;
255 use_iterator use_begin() { return use_iterator(UseList); }
256 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
257 use_iterator use_end() { return use_iterator(); }
258 const_use_iterator use_end() const { return const_use_iterator(); }
259 iterator_range<use_iterator> uses() {
260 return iterator_range<use_iterator>(use_begin(), use_end());
262 iterator_range<const_use_iterator> uses() const {
263 return iterator_range<const_use_iterator>(use_begin(), use_end());
266 typedef user_iterator_impl<User> user_iterator;
267 typedef user_iterator_impl<const User> const_user_iterator;
268 user_iterator user_begin() { return user_iterator(UseList); }
269 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
270 user_iterator user_end() { return user_iterator(); }
271 const_user_iterator user_end() const { return const_user_iterator(); }
272 User *user_back() { return *user_begin(); }
273 const User *user_back() const { return *user_begin(); }
274 iterator_range<user_iterator> users() {
275 return iterator_range<user_iterator>(user_begin(), user_end());
277 iterator_range<const_user_iterator> users() const {
278 return iterator_range<const_user_iterator>(user_begin(), user_end());
281 /// \brief Return true if there is exactly one user of this value.
283 /// This is specialized because it is a common request and does not require
284 /// traversing the whole use list.
285 bool hasOneUse() const {
286 const_use_iterator I = use_begin(), E = use_end();
287 if (I == E) return false;
291 /// \brief Return true if this Value has exactly N users.
292 bool hasNUses(unsigned N) const;
294 /// \brief Return true if this value has N users or more.
296 /// This is logically equivalent to getNumUses() >= N.
297 bool hasNUsesOrMore(unsigned N) const;
299 /// \brief Check if this value is used in the specified basic block.
300 bool isUsedInBasicBlock(const BasicBlock *BB) const;
302 /// \brief This method computes the number of uses of this Value.
304 /// This is a linear time operation. Use hasOneUse, hasNUses, or
305 /// hasNUsesOrMore to check for specific values.
306 unsigned getNumUses() const;
308 /// \brief This method should only be used by the Use class.
309 void addUse(Use &U) { U.addToList(&UseList); }
311 /// \brief Concrete subclass of this.
313 /// An enumeration for keeping track of the concrete subclass of Value that
314 /// is actually instantiated. Values of this enumeration are kept in the
315 /// Value classes SubclassID field. They are used for concrete type
318 ArgumentVal, // This is an instance of Argument
319 BasicBlockVal, // This is an instance of BasicBlock
320 FunctionVal, // This is an instance of Function
321 GlobalAliasVal, // This is an instance of GlobalAlias
322 GlobalVariableVal, // This is an instance of GlobalVariable
323 UndefValueVal, // This is an instance of UndefValue
324 BlockAddressVal, // This is an instance of BlockAddress
325 ConstantExprVal, // This is an instance of ConstantExpr
326 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
327 ConstantDataArrayVal, // This is an instance of ConstantDataArray
328 ConstantDataVectorVal, // This is an instance of ConstantDataVector
329 ConstantIntVal, // This is an instance of ConstantInt
330 ConstantFPVal, // This is an instance of ConstantFP
331 ConstantArrayVal, // This is an instance of ConstantArray
332 ConstantStructVal, // This is an instance of ConstantStruct
333 ConstantVectorVal, // This is an instance of ConstantVector
334 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
335 MDNodeVal, // This is an instance of MDNode
336 MDStringVal, // This is an instance of MDString
337 InlineAsmVal, // This is an instance of InlineAsm
338 InstructionVal, // This is an instance of Instruction
339 // Enum values starting at InstructionVal are used for Instructions;
340 // don't add new values here!
343 ConstantFirstVal = FunctionVal,
344 ConstantLastVal = ConstantPointerNullVal
347 /// \brief Return an ID for the concrete type of this object.
349 /// This is used to implement the classof checks. This should not be used
350 /// for any other purpose, as the values may change as LLVM evolves. Also,
351 /// note that for instructions, the Instruction's opcode is added to
352 /// InstructionVal. So this means three things:
353 /// # there is no value with code InstructionVal (no opcode==0).
354 /// # there are more possible values for the value type than in ValueTy enum.
355 /// # the InstructionVal enumerator must be the highest valued enumerator in
356 /// the ValueTy enum.
357 unsigned getValueID() const {
361 /// \brief Return the raw optional flags value contained in this value.
363 /// This should only be used when testing two Values for equivalence.
364 unsigned getRawSubclassOptionalData() const {
365 return SubclassOptionalData;
368 /// \brief Clear the optional flags contained in this value.
369 void clearSubclassOptionalData() {
370 SubclassOptionalData = 0;
373 /// \brief Check the optional flags for equality.
374 bool hasSameSubclassOptionalData(const Value *V) const {
375 return SubclassOptionalData == V->SubclassOptionalData;
378 /// \brief Clear any optional flags not set in the given Value.
379 void intersectOptionalDataWith(const Value *V) {
380 SubclassOptionalData &= V->SubclassOptionalData;
383 /// \brief Return true if there is a value handle associated with this value.
384 bool hasValueHandle() const { return HasValueHandle; }
386 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
388 /// Returns the original uncasted value. If this is called on a non-pointer
389 /// value, it returns 'this'.
390 Value *stripPointerCasts();
391 const Value *stripPointerCasts() const {
392 return const_cast<Value*>(this)->stripPointerCasts();
395 /// \brief Strip off pointer casts and all-zero GEPs.
397 /// Returns the original uncasted value. If this is called on a non-pointer
398 /// value, it returns 'this'.
399 Value *stripPointerCastsNoFollowAliases();
400 const Value *stripPointerCastsNoFollowAliases() const {
401 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
404 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
406 /// Returns the original pointer value. If this is called on a non-pointer
407 /// value, it returns 'this'.
408 Value *stripInBoundsConstantOffsets();
409 const Value *stripInBoundsConstantOffsets() const {
410 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
413 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
415 /// Stores the resulting constant offset stripped into the APInt provided.
416 /// The provided APInt will be extended or truncated as needed to be the
417 /// correct bitwidth for an offset of this pointer type.
419 /// If this is called on a non-pointer value, it returns 'this'.
420 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
422 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
423 APInt &Offset) const {
424 return const_cast<Value *>(this)
425 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
428 /// \brief Strip off pointer casts and inbounds GEPs.
430 /// Returns the original pointer value. If this is called on a non-pointer
431 /// value, it returns 'this'.
432 Value *stripInBoundsOffsets();
433 const Value *stripInBoundsOffsets() const {
434 return const_cast<Value*>(this)->stripInBoundsOffsets();
437 /// \brief Check if this is always a dereferenceable pointer.
439 /// Test if this value is always a pointer to allocated and suitably aligned
440 /// memory for a simple load or store.
441 bool isDereferenceablePointer(const DataLayout *DL = nullptr) const;
443 /// \brief Translate PHI node to its predecessor from the given basic block.
445 /// If this value is a PHI node with CurBB as its parent, return the value in
446 /// the PHI node corresponding to PredBB. If not, return ourself. This is
447 /// useful if you want to know the value something has in a predecessor
449 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
451 const Value *DoPHITranslation(const BasicBlock *CurBB,
452 const BasicBlock *PredBB) const{
453 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
456 /// \brief The maximum alignment for instructions.
458 /// This is the greatest alignment value supported by load, store, and alloca
459 /// instructions, and global values.
460 static const unsigned MaximumAlignment = 1u << 29;
462 /// \brief Mutate the type of this Value to be of the specified type.
464 /// Note that this is an extremely dangerous operation which can create
465 /// completely invalid IR very easily. It is strongly recommended that you
466 /// recreate IR objects with the right types instead of mutating them in
468 void mutateType(Type *Ty) {
472 /// \brief Sort the use-list.
474 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
475 /// expected to compare two \a Use references.
476 template <class Compare> void sortUseList(Compare Cmp);
478 /// \brief Reverse the use-list.
479 void reverseUseList();
482 /// \brief Merge two lists together.
484 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
485 /// "equal" items from L before items from R.
487 /// \return the first element in the list.
489 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
490 template <class Compare>
491 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
493 mergeUseListsImpl(L, R, &Merged, Cmp);
497 /// \brief Tail-recursive helper for \a mergeUseLists().
499 /// \param[out] Next the first element in the list.
500 template <class Compare>
501 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
504 unsigned short getSubclassDataFromValue() const { return SubclassData; }
505 void setValueSubclassData(unsigned short D) { SubclassData = D; }
508 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
513 void Use::set(Value *V) {
514 if (Val) removeFromList();
516 if (V) V->addUse(*this);
519 template <class Compare> void Value::sortUseList(Compare Cmp) {
520 if (!UseList || !UseList->Next)
521 // No need to sort 0 or 1 uses.
524 // Note: this function completely ignores Prev pointers until the end when
525 // they're fixed en masse.
527 // Create a binomial vector of sorted lists, visiting uses one at a time and
528 // merging lists as necessary.
529 const unsigned MaxSlots = 32;
530 Use *Slots[MaxSlots];
532 // Collect the first use, turning it into a single-item list.
533 Use *Next = UseList->Next;
534 UseList->Next = nullptr;
535 unsigned NumSlots = 1;
538 // Collect all but the last use.
541 Next = Current->Next;
543 // Turn Current into a single-item list.
544 Current->Next = nullptr;
546 // Save Current in the first available slot, merging on collisions.
548 for (I = 0; I < NumSlots; ++I) {
552 // Merge two lists, doubling the size of Current and emptying slot I.
554 // Since the uses in Slots[I] originally preceded those in Current, send
555 // Slots[I] in as the left parameter to maintain a stable sort.
556 Current = mergeUseLists(Slots[I], Current, Cmp);
559 // Check if this is a new slot.
562 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
565 // Found an open slot.
569 // Merge all the lists together.
570 assert(Next && "Expected one more Use");
571 assert(!Next->Next && "Expected only one Use");
573 for (unsigned I = 0; I < NumSlots; ++I)
575 // Since the uses in Slots[I] originally preceded those in UseList, send
576 // Slots[I] in as the left parameter to maintain a stable sort.
577 UseList = mergeUseLists(Slots[I], UseList, Cmp);
579 // Fix the Prev pointers.
580 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
586 template <class Compare>
587 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
598 mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
602 mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
605 // isa - Provide some specializations of isa so that we don't have to include
606 // the subtype header files to test to see if the value is a subclass...
608 template <> struct isa_impl<Constant, Value> {
609 static inline bool doit(const Value &Val) {
610 return Val.getValueID() >= Value::ConstantFirstVal &&
611 Val.getValueID() <= Value::ConstantLastVal;
615 template <> struct isa_impl<Argument, Value> {
616 static inline bool doit (const Value &Val) {
617 return Val.getValueID() == Value::ArgumentVal;
621 template <> struct isa_impl<InlineAsm, Value> {
622 static inline bool doit(const Value &Val) {
623 return Val.getValueID() == Value::InlineAsmVal;
627 template <> struct isa_impl<Instruction, Value> {
628 static inline bool doit(const Value &Val) {
629 return Val.getValueID() >= Value::InstructionVal;
633 template <> struct isa_impl<BasicBlock, Value> {
634 static inline bool doit(const Value &Val) {
635 return Val.getValueID() == Value::BasicBlockVal;
639 template <> struct isa_impl<Function, Value> {
640 static inline bool doit(const Value &Val) {
641 return Val.getValueID() == Value::FunctionVal;
645 template <> struct isa_impl<GlobalVariable, Value> {
646 static inline bool doit(const Value &Val) {
647 return Val.getValueID() == Value::GlobalVariableVal;
651 template <> struct isa_impl<GlobalAlias, Value> {
652 static inline bool doit(const Value &Val) {
653 return Val.getValueID() == Value::GlobalAliasVal;
657 template <> struct isa_impl<GlobalValue, Value> {
658 static inline bool doit(const Value &Val) {
659 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
663 template <> struct isa_impl<GlobalObject, Value> {
664 static inline bool doit(const Value &Val) {
665 return isa<GlobalVariable>(Val) || isa<Function>(Val);
669 template <> struct isa_impl<MDNode, Value> {
670 static inline bool doit(const Value &Val) {
671 return Val.getValueID() == Value::MDNodeVal;
675 // Value* is only 4-byte aligned.
677 class PointerLikeTypeTraits<Value*> {
680 static inline void *getAsVoidPointer(PT P) { return P; }
681 static inline PT getFromVoidPointer(void *P) {
682 return static_cast<PT>(P);
684 enum { NumLowBitsAvailable = 2 };
687 // Create wrappers for C Binding types (see CBindingWrapping.h).
688 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
690 /* Specialized opaque value conversions.
692 inline Value **unwrap(LLVMValueRef *Vals) {
693 return reinterpret_cast<Value**>(Vals);
697 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
699 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
703 return reinterpret_cast<T**>(Vals);
706 inline LLVMValueRef *wrap(const Value **Vals) {
707 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
710 } // End llvm namespace