[Alignment][NFC] Support compile time constants
[llvm-core.git] / include / llvm / IR / Value.h
blob58502907f0e352b2cde8123e32d8d3299eb9b1e0
1 //===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the Value class.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_IR_VALUE_H
14 #define LLVM_IR_VALUE_H
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/STLExtras.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 <cassert>
23 #include <iterator>
24 #include <memory>
26 namespace llvm {
28 class APInt;
29 class Argument;
30 class BasicBlock;
31 class Constant;
32 class ConstantData;
33 class ConstantAggregate;
34 class DataLayout;
35 class Function;
36 class GlobalAlias;
37 class GlobalIFunc;
38 class GlobalIndirectSymbol;
39 class GlobalObject;
40 class GlobalValue;
41 class GlobalVariable;
42 class InlineAsm;
43 class Instruction;
44 class LLVMContext;
45 class Module;
46 class ModuleSlotTracker;
47 class raw_ostream;
48 template<typename ValueTy> class StringMapEntry;
49 class StringRef;
50 class Twine;
51 class Type;
52 class User;
54 using ValueName = StringMapEntry<Value *>;
56 //===----------------------------------------------------------------------===//
57 // Value Class
58 //===----------------------------------------------------------------------===//
60 /// LLVM Value Representation
61 ///
62 /// This is a very important LLVM class. It is the base class of all values
63 /// computed by a program that may be used as operands to other values. Value is
64 /// the super class of other important classes such as Instruction and Function.
65 /// All Values have a Type. Type is not a subclass of Value. Some values can
66 /// have a name and they belong to some Module. Setting the name on the Value
67 /// automatically updates the module's symbol table.
68 ///
69 /// Every value has a "use list" that keeps track of which other Values are
70 /// using this Value. A Value can also have an arbitrary number of ValueHandle
71 /// objects that watch it and listen to RAUW and Destroy events. See
72 /// llvm/IR/ValueHandle.h for details.
73 class Value {
74 // The least-significant bit of the first word of Value *must* be zero:
75 // http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
76 Type *VTy;
77 Use *UseList;
79 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
80 friend class ValueHandleBase;
82 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
83 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
85 protected:
86 /// Hold subclass data that can be dropped.
87 ///
88 /// This member is similar to SubclassData, however it is for holding
89 /// information which may be used to aid optimization, but which may be
90 /// cleared to zero without affecting conservative interpretation.
91 unsigned char SubclassOptionalData : 7;
93 private:
94 /// Hold arbitrary subclass data.
95 ///
96 /// This member is defined by this class, but is not used for anything.
97 /// Subclasses can use it to hold whatever state they find useful. This
98 /// field is initialized to zero by the ctor.
99 unsigned short SubclassData;
101 protected:
102 /// The number of operands in the subclass.
104 /// This member is defined by this class, but not used for anything.
105 /// Subclasses can use it to store their number of operands, if they have
106 /// any.
108 /// This is stored here to save space in User on 64-bit hosts. Since most
109 /// instances of Value have operands, 32-bit hosts aren't significantly
110 /// affected.
112 /// Note, this should *NOT* be used directly by any class other than User.
113 /// User uses this value to find the Use list.
114 enum : unsigned { NumUserOperandsBits = 28 };
115 unsigned NumUserOperands : NumUserOperandsBits;
117 // Use the same type as the bitfield above so that MSVC will pack them.
118 unsigned IsUsedByMD : 1;
119 unsigned HasName : 1;
120 unsigned HasHungOffUses : 1;
121 unsigned HasDescriptor : 1;
123 private:
124 template <typename UseT> // UseT == 'Use' or 'const Use'
125 class use_iterator_impl
126 : public std::iterator<std::forward_iterator_tag, UseT *> {
127 friend class Value;
129 UseT *U;
131 explicit use_iterator_impl(UseT *u) : U(u) {}
133 public:
134 use_iterator_impl() : U() {}
136 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
137 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
139 use_iterator_impl &operator++() { // Preincrement
140 assert(U && "Cannot increment end iterator!");
141 U = U->getNext();
142 return *this;
145 use_iterator_impl operator++(int) { // Postincrement
146 auto tmp = *this;
147 ++*this;
148 return tmp;
151 UseT &operator*() const {
152 assert(U && "Cannot dereference end iterator!");
153 return *U;
156 UseT *operator->() const { return &operator*(); }
158 operator use_iterator_impl<const UseT>() const {
159 return use_iterator_impl<const UseT>(U);
163 template <typename UserTy> // UserTy == 'User' or 'const User'
164 class user_iterator_impl
165 : public std::iterator<std::forward_iterator_tag, UserTy *> {
166 use_iterator_impl<Use> UI;
167 explicit user_iterator_impl(Use *U) : UI(U) {}
168 friend class Value;
170 public:
171 user_iterator_impl() = default;
173 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
174 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
176 /// Returns true if this iterator is equal to user_end() on the value.
177 bool atEnd() const { return *this == user_iterator_impl(); }
179 user_iterator_impl &operator++() { // Preincrement
180 ++UI;
181 return *this;
184 user_iterator_impl operator++(int) { // Postincrement
185 auto tmp = *this;
186 ++*this;
187 return tmp;
190 // Retrieve a pointer to the current User.
191 UserTy *operator*() const {
192 return UI->getUser();
195 UserTy *operator->() const { return operator*(); }
197 operator user_iterator_impl<const UserTy>() const {
198 return user_iterator_impl<const UserTy>(*UI);
201 Use &getUse() const { return *UI; }
204 protected:
205 Value(Type *Ty, unsigned scid);
207 /// Value's destructor should be virtual by design, but that would require
208 /// that Value and all of its subclasses have a vtable that effectively
209 /// duplicates the information in the value ID. As a size optimization, the
210 /// destructor has been protected, and the caller should manually call
211 /// deleteValue.
212 ~Value(); // Use deleteValue() to delete a generic Value.
214 public:
215 Value(const Value &) = delete;
216 Value &operator=(const Value &) = delete;
218 /// Delete a pointer to a generic Value.
219 void deleteValue();
221 /// Support for debugging, callable in GDB: V->dump()
222 void dump() const;
224 /// Implement operator<< on Value.
225 /// @{
226 void print(raw_ostream &O, bool IsForDebug = false) const;
227 void print(raw_ostream &O, ModuleSlotTracker &MST,
228 bool IsForDebug = false) const;
229 /// @}
231 /// Print the name of this Value out to the specified raw_ostream.
233 /// This is useful when you just want to print 'int %reg126', not the
234 /// instruction that generated it. If you specify a Module for context, then
235 /// even constanst get pretty-printed; for example, the type of a null
236 /// pointer is printed symbolically.
237 /// @{
238 void printAsOperand(raw_ostream &O, bool PrintType = true,
239 const Module *M = nullptr) const;
240 void printAsOperand(raw_ostream &O, bool PrintType,
241 ModuleSlotTracker &MST) const;
242 /// @}
244 /// All values are typed, get the type of this value.
245 Type *getType() const { return VTy; }
247 /// All values hold a context through their type.
248 LLVMContext &getContext() const;
250 // All values can potentially be named.
251 bool hasName() const { return HasName; }
252 ValueName *getValueName() const;
253 void setValueName(ValueName *VN);
255 private:
256 void destroyValueName();
257 enum class ReplaceMetadataUses { No, Yes };
258 void doRAUW(Value *New, ReplaceMetadataUses);
259 void setNameImpl(const Twine &Name);
261 public:
262 /// Return a constant reference to the value's name.
264 /// This guaranteed to return the same reference as long as the value is not
265 /// modified. If the value has a name, this does a hashtable lookup, so it's
266 /// not free.
267 StringRef getName() const;
269 /// Change the name of the value.
271 /// Choose a new unique name if the provided name is taken.
273 /// \param Name The new name; or "" if the value's name should be removed.
274 void setName(const Twine &Name);
276 /// Transfer the name from V to this value.
278 /// After taking V's name, sets V's name to empty.
280 /// \note It is an error to call V->takeName(V).
281 void takeName(Value *V);
283 /// Change all uses of this to point to a new Value.
285 /// Go through the uses list for this definition and make each use point to
286 /// "V" instead of "this". After this completes, 'this's use list is
287 /// guaranteed to be empty.
288 void replaceAllUsesWith(Value *V);
290 /// Change non-metadata uses of this to point to a new Value.
292 /// Go through the uses list for this definition and make each use point to
293 /// "V" instead of "this". This function skips metadata entries in the list.
294 void replaceNonMetadataUsesWith(Value *V);
296 /// Go through the uses list for this definition and make each use point
297 /// to "V" if the callback ShouldReplace returns true for the given Use.
298 /// Unlike replaceAllUsesWith() this function does not support basic block
299 /// values or constant users.
300 void replaceUsesWithIf(Value *New,
301 llvm::function_ref<bool(Use &U)> ShouldReplace) {
302 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
303 assert(New->getType() == getType() &&
304 "replaceUses of value with new value of different type!");
306 for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
307 Use &U = *UI;
308 ++UI;
309 if (!ShouldReplace(U))
310 continue;
311 U.set(New);
315 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
316 /// make each use point to "V" instead of "this" when the use is outside the
317 /// block. 'This's use list is expected to have at least one element.
318 /// Unlike replaceAllUsesWith() this function does not support basic block
319 /// values or constant users.
320 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
322 //----------------------------------------------------------------------
323 // Methods for handling the chain of uses of this Value.
325 // Materializing a function can introduce new uses, so these methods come in
326 // two variants:
327 // The methods that start with materialized_ check the uses that are
328 // currently known given which functions are materialized. Be very careful
329 // when using them since you might not get all uses.
330 // The methods that don't start with materialized_ assert that modules is
331 // fully materialized.
332 void assertModuleIsMaterializedImpl() const;
333 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
334 // around in release builds of Value.cpp to be linked with other code built
335 // in debug mode. But this avoids calling it in any of the release built code.
336 void assertModuleIsMaterialized() const {
337 #ifndef NDEBUG
338 assertModuleIsMaterializedImpl();
339 #endif
342 bool use_empty() const {
343 assertModuleIsMaterialized();
344 return UseList == nullptr;
347 bool materialized_use_empty() const {
348 return UseList == nullptr;
351 using use_iterator = use_iterator_impl<Use>;
352 using const_use_iterator = use_iterator_impl<const Use>;
354 use_iterator materialized_use_begin() { return use_iterator(UseList); }
355 const_use_iterator materialized_use_begin() const {
356 return const_use_iterator(UseList);
358 use_iterator use_begin() {
359 assertModuleIsMaterialized();
360 return materialized_use_begin();
362 const_use_iterator use_begin() const {
363 assertModuleIsMaterialized();
364 return materialized_use_begin();
366 use_iterator use_end() { return use_iterator(); }
367 const_use_iterator use_end() const { return const_use_iterator(); }
368 iterator_range<use_iterator> materialized_uses() {
369 return make_range(materialized_use_begin(), use_end());
371 iterator_range<const_use_iterator> materialized_uses() const {
372 return make_range(materialized_use_begin(), use_end());
374 iterator_range<use_iterator> uses() {
375 assertModuleIsMaterialized();
376 return materialized_uses();
378 iterator_range<const_use_iterator> uses() const {
379 assertModuleIsMaterialized();
380 return materialized_uses();
383 bool user_empty() const {
384 assertModuleIsMaterialized();
385 return UseList == nullptr;
388 using user_iterator = user_iterator_impl<User>;
389 using const_user_iterator = user_iterator_impl<const User>;
391 user_iterator materialized_user_begin() { return user_iterator(UseList); }
392 const_user_iterator materialized_user_begin() const {
393 return const_user_iterator(UseList);
395 user_iterator user_begin() {
396 assertModuleIsMaterialized();
397 return materialized_user_begin();
399 const_user_iterator user_begin() const {
400 assertModuleIsMaterialized();
401 return materialized_user_begin();
403 user_iterator user_end() { return user_iterator(); }
404 const_user_iterator user_end() const { return const_user_iterator(); }
405 User *user_back() {
406 assertModuleIsMaterialized();
407 return *materialized_user_begin();
409 const User *user_back() const {
410 assertModuleIsMaterialized();
411 return *materialized_user_begin();
413 iterator_range<user_iterator> materialized_users() {
414 return make_range(materialized_user_begin(), user_end());
416 iterator_range<const_user_iterator> materialized_users() const {
417 return make_range(materialized_user_begin(), user_end());
419 iterator_range<user_iterator> users() {
420 assertModuleIsMaterialized();
421 return materialized_users();
423 iterator_range<const_user_iterator> users() const {
424 assertModuleIsMaterialized();
425 return materialized_users();
428 /// Return true if there is exactly one user of this value.
430 /// This is specialized because it is a common request and does not require
431 /// traversing the whole use list.
432 bool hasOneUse() const {
433 const_use_iterator I = use_begin(), E = use_end();
434 if (I == E) return false;
435 return ++I == E;
438 /// Return true if this Value has exactly N users.
439 bool hasNUses(unsigned N) const;
441 /// Return true if this value has N users or more.
443 /// This is logically equivalent to getNumUses() >= N.
444 bool hasNUsesOrMore(unsigned N) const;
446 /// Check if this value is used in the specified basic block.
447 bool isUsedInBasicBlock(const BasicBlock *BB) const;
449 /// This method computes the number of uses of this Value.
451 /// This is a linear time operation. Use hasOneUse, hasNUses, or
452 /// hasNUsesOrMore to check for specific values.
453 unsigned getNumUses() const;
455 /// This method should only be used by the Use class.
456 void addUse(Use &U) { U.addToList(&UseList); }
458 /// Concrete subclass of this.
460 /// An enumeration for keeping track of the concrete subclass of Value that
461 /// is actually instantiated. Values of this enumeration are kept in the
462 /// Value classes SubclassID field. They are used for concrete type
463 /// identification.
464 enum ValueTy {
465 #define HANDLE_VALUE(Name) Name##Val,
466 #include "llvm/IR/Value.def"
468 // Markers:
469 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
470 #include "llvm/IR/Value.def"
473 /// Return an ID for the concrete type of this object.
475 /// This is used to implement the classof checks. This should not be used
476 /// for any other purpose, as the values may change as LLVM evolves. Also,
477 /// note that for instructions, the Instruction's opcode is added to
478 /// InstructionVal. So this means three things:
479 /// # there is no value with code InstructionVal (no opcode==0).
480 /// # there are more possible values for the value type than in ValueTy enum.
481 /// # the InstructionVal enumerator must be the highest valued enumerator in
482 /// the ValueTy enum.
483 unsigned getValueID() const {
484 return SubclassID;
487 /// Return the raw optional flags value contained in this value.
489 /// This should only be used when testing two Values for equivalence.
490 unsigned getRawSubclassOptionalData() const {
491 return SubclassOptionalData;
494 /// Clear the optional flags contained in this value.
495 void clearSubclassOptionalData() {
496 SubclassOptionalData = 0;
499 /// Check the optional flags for equality.
500 bool hasSameSubclassOptionalData(const Value *V) const {
501 return SubclassOptionalData == V->SubclassOptionalData;
504 /// Return true if there is a value handle associated with this value.
505 bool hasValueHandle() const { return HasValueHandle; }
507 /// Return true if there is metadata referencing this value.
508 bool isUsedByMetadata() const { return IsUsedByMD; }
510 /// Return true if this value is a swifterror value.
512 /// swifterror values can be either a function argument or an alloca with a
513 /// swifterror attribute.
514 bool isSwiftError() const;
516 /// Strip off pointer casts, all-zero GEPs and address space casts.
518 /// Returns the original uncasted value. If this is called on a non-pointer
519 /// value, it returns 'this'.
520 const Value *stripPointerCasts() const;
521 Value *stripPointerCasts() {
522 return const_cast<Value *>(
523 static_cast<const Value *>(this)->stripPointerCasts());
526 /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
528 /// Returns the original uncasted value. If this is called on a non-pointer
529 /// value, it returns 'this'.
530 const Value *stripPointerCastsAndAliases() const;
531 Value *stripPointerCastsAndAliases() {
532 return const_cast<Value *>(
533 static_cast<const Value *>(this)->stripPointerCastsAndAliases());
536 /// Strip off pointer casts, all-zero GEPs and address space casts
537 /// but ensures the representation of the result stays the same.
539 /// Returns the original uncasted value with the same representation. If this
540 /// is called on a non-pointer value, it returns 'this'.
541 const Value *stripPointerCastsSameRepresentation() const;
542 Value *stripPointerCastsSameRepresentation() {
543 return const_cast<Value *>(static_cast<const Value *>(this)
544 ->stripPointerCastsSameRepresentation());
547 /// Strip off pointer casts, all-zero GEPs and invariant group info.
549 /// Returns the original uncasted value. If this is called on a non-pointer
550 /// value, it returns 'this'. This function should be used only in
551 /// Alias analysis.
552 const Value *stripPointerCastsAndInvariantGroups() const;
553 Value *stripPointerCastsAndInvariantGroups() {
554 return const_cast<Value *>(static_cast<const Value *>(this)
555 ->stripPointerCastsAndInvariantGroups());
558 /// Strip off pointer casts and all-constant inbounds GEPs.
560 /// Returns the original pointer value. If this is called on a non-pointer
561 /// value, it returns 'this'.
562 const Value *stripInBoundsConstantOffsets() const;
563 Value *stripInBoundsConstantOffsets() {
564 return const_cast<Value *>(
565 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
568 /// Accumulate the constant offset this value has compared to a base pointer.
569 /// Only 'getelementptr' instructions (GEPs) with constant indices are
570 /// accumulated but other instructions, e.g., casts, are stripped away as
571 /// well. The accumulated constant offset is added to \p Offset and the base
572 /// pointer is returned.
574 /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
575 /// the address space of 'this' pointer value, e.g., use
576 /// DataLayout::getIndexTypeSizeInBits(Ty).
578 /// If \p AllowNonInbounds is true, constant offsets in GEPs are stripped and
579 /// accumulated even if the GEP is not "inbounds".
581 /// If this is called on a non-pointer value, it returns 'this' and the
582 /// \p Offset is not modified.
584 /// Note that this function will never return a nullptr. It will also never
585 /// manipulate the \p Offset in a way that would not match the difference
586 /// between the underlying value and the returned one. Thus, if no constant
587 /// offset was found, the returned value is the underlying one and \p Offset
588 /// is unchanged.
589 const Value *stripAndAccumulateConstantOffsets(const DataLayout &DL,
590 APInt &Offset,
591 bool AllowNonInbounds) const;
592 Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
593 bool AllowNonInbounds) {
594 return const_cast<Value *>(
595 static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
596 DL, Offset, AllowNonInbounds));
599 /// This is a wrapper around stripAndAccumulateConstantOffsets with the
600 /// in-bounds requirement set to false.
601 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
602 APInt &Offset) const {
603 return stripAndAccumulateConstantOffsets(DL, Offset,
604 /* AllowNonInbounds */ false);
606 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
607 APInt &Offset) {
608 return stripAndAccumulateConstantOffsets(DL, Offset,
609 /* AllowNonInbounds */ false);
612 /// Strip off pointer casts and inbounds GEPs.
614 /// Returns the original pointer value. If this is called on a non-pointer
615 /// value, it returns 'this'.
616 const Value *stripInBoundsOffsets() const;
617 Value *stripInBoundsOffsets() {
618 return const_cast<Value *>(
619 static_cast<const Value *>(this)->stripInBoundsOffsets());
622 /// Returns the number of bytes known to be dereferenceable for the
623 /// pointer value.
625 /// If CanBeNull is set by this function the pointer can either be null or be
626 /// dereferenceable up to the returned number of bytes.
627 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
628 bool &CanBeNull) const;
630 /// Returns an alignment of the pointer value.
632 /// Returns an alignment which is either specified explicitly, e.g. via
633 /// align attribute of a function argument, or guaranteed by DataLayout.
634 unsigned getPointerAlignment(const DataLayout &DL) const;
636 /// Translate PHI node to its predecessor from the given basic block.
638 /// If this value is a PHI node with CurBB as its parent, return the value in
639 /// the PHI node corresponding to PredBB. If not, return ourself. This is
640 /// useful if you want to know the value something has in a predecessor
641 /// block.
642 const Value *DoPHITranslation(const BasicBlock *CurBB,
643 const BasicBlock *PredBB) const;
644 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
645 return const_cast<Value *>(
646 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
649 /// The maximum alignment for instructions.
651 /// This is the greatest alignment value supported by load, store, and alloca
652 /// instructions, and global values.
653 static const unsigned MaxAlignmentExponent = 29;
654 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
656 /// Mutate the type of this Value to be of the specified type.
658 /// Note that this is an extremely dangerous operation which can create
659 /// completely invalid IR very easily. It is strongly recommended that you
660 /// recreate IR objects with the right types instead of mutating them in
661 /// place.
662 void mutateType(Type *Ty) {
663 VTy = Ty;
666 /// Sort the use-list.
668 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
669 /// expected to compare two \a Use references.
670 template <class Compare> void sortUseList(Compare Cmp);
672 /// Reverse the use-list.
673 void reverseUseList();
675 private:
676 /// Merge two lists together.
678 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
679 /// "equal" items from L before items from R.
681 /// \return the first element in the list.
683 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
684 template <class Compare>
685 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
686 Use *Merged;
687 Use **Next = &Merged;
689 while (true) {
690 if (!L) {
691 *Next = R;
692 break;
694 if (!R) {
695 *Next = L;
696 break;
698 if (Cmp(*R, *L)) {
699 *Next = R;
700 Next = &R->Next;
701 R = R->Next;
702 } else {
703 *Next = L;
704 Next = &L->Next;
705 L = L->Next;
709 return Merged;
712 protected:
713 unsigned short getSubclassDataFromValue() const { return SubclassData; }
714 void setValueSubclassData(unsigned short D) { SubclassData = D; }
717 struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
719 /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
720 /// Those don't work because Value and Instruction's destructors are protected,
721 /// aren't virtual, and won't destroy the complete object.
722 using unique_value = std::unique_ptr<Value, ValueDeleter>;
724 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
725 V.print(OS);
726 return OS;
729 void Use::set(Value *V) {
730 if (Val) removeFromList();
731 Val = V;
732 if (V) V->addUse(*this);
735 Value *Use::operator=(Value *RHS) {
736 set(RHS);
737 return RHS;
740 const Use &Use::operator=(const Use &RHS) {
741 set(RHS.Val);
742 return *this;
745 template <class Compare> void Value::sortUseList(Compare Cmp) {
746 if (!UseList || !UseList->Next)
747 // No need to sort 0 or 1 uses.
748 return;
750 // Note: this function completely ignores Prev pointers until the end when
751 // they're fixed en masse.
753 // Create a binomial vector of sorted lists, visiting uses one at a time and
754 // merging lists as necessary.
755 const unsigned MaxSlots = 32;
756 Use *Slots[MaxSlots];
758 // Collect the first use, turning it into a single-item list.
759 Use *Next = UseList->Next;
760 UseList->Next = nullptr;
761 unsigned NumSlots = 1;
762 Slots[0] = UseList;
764 // Collect all but the last use.
765 while (Next->Next) {
766 Use *Current = Next;
767 Next = Current->Next;
769 // Turn Current into a single-item list.
770 Current->Next = nullptr;
772 // Save Current in the first available slot, merging on collisions.
773 unsigned I;
774 for (I = 0; I < NumSlots; ++I) {
775 if (!Slots[I])
776 break;
778 // Merge two lists, doubling the size of Current and emptying slot I.
780 // Since the uses in Slots[I] originally preceded those in Current, send
781 // Slots[I] in as the left parameter to maintain a stable sort.
782 Current = mergeUseLists(Slots[I], Current, Cmp);
783 Slots[I] = nullptr;
785 // Check if this is a new slot.
786 if (I == NumSlots) {
787 ++NumSlots;
788 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
791 // Found an open slot.
792 Slots[I] = Current;
795 // Merge all the lists together.
796 assert(Next && "Expected one more Use");
797 assert(!Next->Next && "Expected only one Use");
798 UseList = Next;
799 for (unsigned I = 0; I < NumSlots; ++I)
800 if (Slots[I])
801 // Since the uses in Slots[I] originally preceded those in UseList, send
802 // Slots[I] in as the left parameter to maintain a stable sort.
803 UseList = mergeUseLists(Slots[I], UseList, Cmp);
805 // Fix the Prev pointers.
806 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
807 I->setPrev(Prev);
808 Prev = &I->Next;
812 // isa - Provide some specializations of isa so that we don't have to include
813 // the subtype header files to test to see if the value is a subclass...
815 template <> struct isa_impl<Constant, Value> {
816 static inline bool doit(const Value &Val) {
817 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
818 return Val.getValueID() <= Value::ConstantLastVal;
822 template <> struct isa_impl<ConstantData, Value> {
823 static inline bool doit(const Value &Val) {
824 return Val.getValueID() >= Value::ConstantDataFirstVal &&
825 Val.getValueID() <= Value::ConstantDataLastVal;
829 template <> struct isa_impl<ConstantAggregate, Value> {
830 static inline bool doit(const Value &Val) {
831 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
832 Val.getValueID() <= Value::ConstantAggregateLastVal;
836 template <> struct isa_impl<Argument, Value> {
837 static inline bool doit (const Value &Val) {
838 return Val.getValueID() == Value::ArgumentVal;
842 template <> struct isa_impl<InlineAsm, Value> {
843 static inline bool doit(const Value &Val) {
844 return Val.getValueID() == Value::InlineAsmVal;
848 template <> struct isa_impl<Instruction, Value> {
849 static inline bool doit(const Value &Val) {
850 return Val.getValueID() >= Value::InstructionVal;
854 template <> struct isa_impl<BasicBlock, Value> {
855 static inline bool doit(const Value &Val) {
856 return Val.getValueID() == Value::BasicBlockVal;
860 template <> struct isa_impl<Function, Value> {
861 static inline bool doit(const Value &Val) {
862 return Val.getValueID() == Value::FunctionVal;
866 template <> struct isa_impl<GlobalVariable, Value> {
867 static inline bool doit(const Value &Val) {
868 return Val.getValueID() == Value::GlobalVariableVal;
872 template <> struct isa_impl<GlobalAlias, Value> {
873 static inline bool doit(const Value &Val) {
874 return Val.getValueID() == Value::GlobalAliasVal;
878 template <> struct isa_impl<GlobalIFunc, Value> {
879 static inline bool doit(const Value &Val) {
880 return Val.getValueID() == Value::GlobalIFuncVal;
884 template <> struct isa_impl<GlobalIndirectSymbol, Value> {
885 static inline bool doit(const Value &Val) {
886 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
890 template <> struct isa_impl<GlobalValue, Value> {
891 static inline bool doit(const Value &Val) {
892 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
896 template <> struct isa_impl<GlobalObject, Value> {
897 static inline bool doit(const Value &Val) {
898 return isa<GlobalVariable>(Val) || isa<Function>(Val);
902 // Create wrappers for C Binding types (see CBindingWrapping.h).
903 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
905 // Specialized opaque value conversions.
906 inline Value **unwrap(LLVMValueRef *Vals) {
907 return reinterpret_cast<Value**>(Vals);
910 template<typename T>
911 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
912 #ifndef NDEBUG
913 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
914 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
915 #endif
916 (void)Length;
917 return reinterpret_cast<T**>(Vals);
920 inline LLVMValueRef *wrap(const Value **Vals) {
921 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
924 } // end namespace llvm
926 #endif // LLVM_IR_VALUE_H