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.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_VALUE_H
14 #define LLVM_IR_VALUE_H
15 
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/IR/Use.h"
21 #include "llvm/Support/Alignment.h"
22 #include "llvm/Support/CBindingWrapping.h"
23 #include "llvm/Support/Casting.h"
24 #include <cassert>
25 #include <iterator>
26 #include <memory>
27 
28 namespace llvm {
29 
30 class APInt;
31 class Argument;
32 class BasicBlock;
33 class Constant;
34 class ConstantData;
35 class ConstantAggregate;
36 class DataLayout;
37 class Function;
38 class GlobalAlias;
39 class GlobalIFunc;
40 class GlobalIndirectSymbol;
41 class GlobalObject;
42 class GlobalValue;
43 class GlobalVariable;
44 class InlineAsm;
45 class Instruction;
46 class LLVMContext;
47 class MDNode;
48 class Module;
49 class ModuleSlotTracker;
50 class raw_ostream;
51 template<typename ValueTy> class StringMapEntry;
52 class Twine;
53 class Type;
54 class User;
55 
56 using ValueName = StringMapEntry<Value *>;
57 
58 //===----------------------------------------------------------------------===//
59 //                                 Value Class
60 //===----------------------------------------------------------------------===//
61 
62 /// LLVM Value Representation
63 ///
64 /// This is a very important LLVM class. It is the base class of all values
65 /// computed by a program that may be used as operands to other values. Value is
66 /// the super class of other important classes such as Instruction and Function.
67 /// All Values have a Type. Type is not a subclass of Value. Some values can
68 /// have a name and they belong to some Module.  Setting the name on the Value
69 /// automatically updates the module's symbol table.
70 ///
71 /// Every value has a "use list" that keeps track of which other Values are
72 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
73 /// objects that watch it and listen to RAUW and Destroy events.  See
74 /// llvm/IR/ValueHandle.h for details.
75 class Value {
76   Type *VTy;
77   Use *UseList;
78 
79   friend class ValueAsMetadata; // Allow access to IsUsedByMD.
80   friend class ValueHandleBase;
81 
82   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
83   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
84 
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;
92 
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;
100 
101 protected:
102   /// The number of operands in the subclass.
103   ///
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.
107   ///
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.
111   ///
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 = 27 };
115   unsigned NumUserOperands : NumUserOperandsBits;
116 
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 HasMetadata : 1; // Has metadata attached to this?
121   unsigned HasHungOffUses : 1;
122   unsigned HasDescriptor : 1;
123 
124 private:
125   template <typename UseT> // UseT == 'Use' or 'const Use'
126   class use_iterator_impl
127       : public std::iterator<std::forward_iterator_tag, UseT *> {
128     friend class Value;
129 
130     UseT *U;
131 
use_iterator_impl(UseT * u)132     explicit use_iterator_impl(UseT *u) : U(u) {}
133 
134   public:
use_iterator_impl()135     use_iterator_impl() : U() {}
136 
137     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
138     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
139 
140     use_iterator_impl &operator++() { // Preincrement
141       assert(U && "Cannot increment end iterator!");
142       U = U->getNext();
143       return *this;
144     }
145 
146     use_iterator_impl operator++(int) { // Postincrement
147       auto tmp = *this;
148       ++*this;
149       return tmp;
150     }
151 
152     UseT &operator*() const {
153       assert(U && "Cannot dereference end iterator!");
154       return *U;
155     }
156 
157     UseT *operator->() const { return &operator*(); }
158 
159     operator use_iterator_impl<const UseT>() const {
160       return use_iterator_impl<const UseT>(U);
161     }
162   };
163 
164   template <typename UserTy> // UserTy == 'User' or 'const User'
165   class user_iterator_impl
166       : public std::iterator<std::forward_iterator_tag, UserTy *> {
167     use_iterator_impl<Use> UI;
user_iterator_impl(Use * U)168     explicit user_iterator_impl(Use *U) : UI(U) {}
169     friend class Value;
170 
171   public:
172     user_iterator_impl() = default;
173 
174     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
175     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
176 
177     /// Returns true if this iterator is equal to user_end() on the value.
atEnd()178     bool atEnd() const { return *this == user_iterator_impl(); }
179 
180     user_iterator_impl &operator++() { // Preincrement
181       ++UI;
182       return *this;
183     }
184 
185     user_iterator_impl operator++(int) { // Postincrement
186       auto tmp = *this;
187       ++*this;
188       return tmp;
189     }
190 
191     // Retrieve a pointer to the current User.
192     UserTy *operator*() const {
193       return UI->getUser();
194     }
195 
196     UserTy *operator->() const { return operator*(); }
197 
198     operator user_iterator_impl<const UserTy>() const {
199       return user_iterator_impl<const UserTy>(*UI);
200     }
201 
getUse()202     Use &getUse() const { return *UI; }
203   };
204 
205 protected:
206   Value(Type *Ty, unsigned scid);
207 
208   /// Value's destructor should be virtual by design, but that would require
209   /// that Value and all of its subclasses have a vtable that effectively
210   /// duplicates the information in the value ID. As a size optimization, the
211   /// destructor has been protected, and the caller should manually call
212   /// deleteValue.
213   ~Value(); // Use deleteValue() to delete a generic Value.
214 
215 public:
216   Value(const Value &) = delete;
217   Value &operator=(const Value &) = delete;
218 
219   /// Delete a pointer to a generic Value.
220   void deleteValue();
221 
222   /// Support for debugging, callable in GDB: V->dump()
223   void dump() const;
224 
225   /// Implement operator<< on Value.
226   /// @{
227   void print(raw_ostream &O, bool IsForDebug = false) const;
228   void print(raw_ostream &O, ModuleSlotTracker &MST,
229              bool IsForDebug = false) const;
230   /// @}
231 
232   /// Print the name of this Value out to the specified raw_ostream.
233   ///
234   /// This is useful when you just want to print 'int %reg126', not the
235   /// instruction that generated it. If you specify a Module for context, then
236   /// even constanst get pretty-printed; for example, the type of a null
237   /// pointer is printed symbolically.
238   /// @{
239   void printAsOperand(raw_ostream &O, bool PrintType = true,
240                       const Module *M = nullptr) const;
241   void printAsOperand(raw_ostream &O, bool PrintType,
242                       ModuleSlotTracker &MST) const;
243   /// @}
244 
245   /// All values are typed, get the type of this value.
getType()246   Type *getType() const { return VTy; }
247 
248   /// All values hold a context through their type.
249   LLVMContext &getContext() const;
250 
251   // All values can potentially be named.
hasName()252   bool hasName() const { return HasName; }
253   ValueName *getValueName() const;
254   void setValueName(ValueName *VN);
255 
256 private:
257   void destroyValueName();
258   enum class ReplaceMetadataUses { No, Yes };
259   void doRAUW(Value *New, ReplaceMetadataUses);
260   void setNameImpl(const Twine &Name);
261 
262 public:
263   /// Return a constant reference to the value's name.
264   ///
265   /// This guaranteed to return the same reference as long as the value is not
266   /// modified.  If the value has a name, this does a hashtable lookup, so it's
267   /// not free.
268   StringRef getName() const;
269 
270   /// Change the name of the value.
271   ///
272   /// Choose a new unique name if the provided name is taken.
273   ///
274   /// \param Name The new name; or "" if the value's name should be removed.
275   void setName(const Twine &Name);
276 
277   /// Transfer the name from V to this value.
278   ///
279   /// After taking V's name, sets V's name to empty.
280   ///
281   /// \note It is an error to call V->takeName(V).
282   void takeName(Value *V);
283 
284 #ifndef NDEBUG
285   std::string getNameOrAsOperand() const;
286 #endif
287 
288   /// Change all uses of this to point to a new Value.
289   ///
290   /// Go through the uses list for this definition and make each use point to
291   /// "V" instead of "this".  After this completes, 'this's use list is
292   /// guaranteed to be empty.
293   void replaceAllUsesWith(Value *V);
294 
295   /// Change non-metadata uses of this to point to a new Value.
296   ///
297   /// Go through the uses list for this definition and make each use point to
298   /// "V" instead of "this". This function skips metadata entries in the list.
299   void replaceNonMetadataUsesWith(Value *V);
300 
301   /// Go through the uses list for this definition and make each use point
302   /// to "V" if the callback ShouldReplace returns true for the given Use.
303   /// Unlike replaceAllUsesWith() this function does not support basic block
304   /// values or constant users.
replaceUsesWithIf(Value * New,llvm::function_ref<bool (Use & U)> ShouldReplace)305   void replaceUsesWithIf(Value *New,
306                          llvm::function_ref<bool(Use &U)> ShouldReplace) {
307     assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
308     assert(New->getType() == getType() &&
309            "replaceUses of value with new value of different type!");
310 
311     for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
312       Use &U = *UI;
313       ++UI;
314       if (!ShouldReplace(U))
315         continue;
316       U.set(New);
317     }
318   }
319 
320   /// replaceUsesOutsideBlock - Go through the uses list for this definition and
321   /// make each use point to "V" instead of "this" when the use is outside the
322   /// block. 'This's use list is expected to have at least one element.
323   /// Unlike replaceAllUsesWith() this function does not support basic block
324   /// values or constant users.
325   void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
326 
327   //----------------------------------------------------------------------
328   // Methods for handling the chain of uses of this Value.
329   //
330   // Materializing a function can introduce new uses, so these methods come in
331   // two variants:
332   // The methods that start with materialized_ check the uses that are
333   // currently known given which functions are materialized. Be very careful
334   // when using them since you might not get all uses.
335   // The methods that don't start with materialized_ assert that modules is
336   // fully materialized.
337   void assertModuleIsMaterializedImpl() const;
338   // This indirection exists so we can keep assertModuleIsMaterializedImpl()
339   // around in release builds of Value.cpp to be linked with other code built
340   // in debug mode. But this avoids calling it in any of the release built code.
assertModuleIsMaterialized()341   void assertModuleIsMaterialized() const {
342 #ifndef NDEBUG
343     assertModuleIsMaterializedImpl();
344 #endif
345   }
346 
use_empty()347   bool use_empty() const {
348     assertModuleIsMaterialized();
349     return UseList == nullptr;
350   }
351 
materialized_use_empty()352   bool materialized_use_empty() const {
353     return UseList == nullptr;
354   }
355 
356   using use_iterator = use_iterator_impl<Use>;
357   using const_use_iterator = use_iterator_impl<const Use>;
358 
materialized_use_begin()359   use_iterator materialized_use_begin() { return use_iterator(UseList); }
materialized_use_begin()360   const_use_iterator materialized_use_begin() const {
361     return const_use_iterator(UseList);
362   }
use_begin()363   use_iterator use_begin() {
364     assertModuleIsMaterialized();
365     return materialized_use_begin();
366   }
use_begin()367   const_use_iterator use_begin() const {
368     assertModuleIsMaterialized();
369     return materialized_use_begin();
370   }
use_end()371   use_iterator use_end() { return use_iterator(); }
use_end()372   const_use_iterator use_end() const { return const_use_iterator(); }
materialized_uses()373   iterator_range<use_iterator> materialized_uses() {
374     return make_range(materialized_use_begin(), use_end());
375   }
materialized_uses()376   iterator_range<const_use_iterator> materialized_uses() const {
377     return make_range(materialized_use_begin(), use_end());
378   }
uses()379   iterator_range<use_iterator> uses() {
380     assertModuleIsMaterialized();
381     return materialized_uses();
382   }
uses()383   iterator_range<const_use_iterator> uses() const {
384     assertModuleIsMaterialized();
385     return materialized_uses();
386   }
387 
user_empty()388   bool user_empty() const {
389     assertModuleIsMaterialized();
390     return UseList == nullptr;
391   }
392 
393   using user_iterator = user_iterator_impl<User>;
394   using const_user_iterator = user_iterator_impl<const User>;
395 
materialized_user_begin()396   user_iterator materialized_user_begin() { return user_iterator(UseList); }
materialized_user_begin()397   const_user_iterator materialized_user_begin() const {
398     return const_user_iterator(UseList);
399   }
user_begin()400   user_iterator user_begin() {
401     assertModuleIsMaterialized();
402     return materialized_user_begin();
403   }
user_begin()404   const_user_iterator user_begin() const {
405     assertModuleIsMaterialized();
406     return materialized_user_begin();
407   }
user_end()408   user_iterator user_end() { return user_iterator(); }
user_end()409   const_user_iterator user_end() const { return const_user_iterator(); }
user_back()410   User *user_back() {
411     assertModuleIsMaterialized();
412     return *materialized_user_begin();
413   }
user_back()414   const User *user_back() const {
415     assertModuleIsMaterialized();
416     return *materialized_user_begin();
417   }
materialized_users()418   iterator_range<user_iterator> materialized_users() {
419     return make_range(materialized_user_begin(), user_end());
420   }
materialized_users()421   iterator_range<const_user_iterator> materialized_users() const {
422     return make_range(materialized_user_begin(), user_end());
423   }
users()424   iterator_range<user_iterator> users() {
425     assertModuleIsMaterialized();
426     return materialized_users();
427   }
users()428   iterator_range<const_user_iterator> users() const {
429     assertModuleIsMaterialized();
430     return materialized_users();
431   }
432 
433   /// Return true if there is exactly one use of this value.
434   ///
435   /// This is specialized because it is a common request and does not require
436   /// traversing the whole use list.
hasOneUse()437   bool hasOneUse() const { return hasSingleElement(uses()); }
438 
439   /// Return true if this Value has exactly N uses.
440   bool hasNUses(unsigned N) const;
441 
442   /// Return true if this value has N uses or more.
443   ///
444   /// This is logically equivalent to getNumUses() >= N.
445   bool hasNUsesOrMore(unsigned N) const;
446 
447   /// Return true if there is exactly one user of this value.
448   ///
449   /// Note that this is not the same as "has one use". If a value has one use,
450   /// then there certainly is a single user. But if value has several uses,
451   /// it is possible that all uses are in a single user, or not.
452   ///
453   /// This check is potentially costly, since it requires traversing,
454   /// in the worst case, the whole use list of a value.
455   bool hasOneUser() const;
456 
457   /// Return true if there is exactly one use of this value that cannot be
458   /// dropped.
459   ///
460   /// This is specialized because it is a common request and does not require
461   /// traversing the whole use list.
462   Use *getSingleUndroppableUse();
463 
464   /// Return true if there this value.
465   ///
466   /// This is specialized because it is a common request and does not require
467   /// traversing the whole use list.
468   bool hasNUndroppableUses(unsigned N) const;
469 
470   /// Return true if this value has N uses or more.
471   ///
472   /// This is logically equivalent to getNumUses() >= N.
473   bool hasNUndroppableUsesOrMore(unsigned N) const;
474 
475   /// Remove every uses that can safely be removed.
476   ///
477   /// This will remove for example uses in llvm.assume.
478   /// This should be used when performing want to perform a tranformation but
479   /// some Droppable uses pervent it.
480   /// This function optionally takes a filter to only remove some droppable
481   /// uses.
482   void dropDroppableUses(llvm::function_ref<bool(const Use *)> ShouldDrop =
483                              [](const Use *) { return true; });
484 
485   /// Remove every use of this value in \p User that can safely be removed.
486   void dropDroppableUsesIn(User &Usr);
487 
488   /// Remove the droppable use \p U.
489   static void dropDroppableUse(Use &U);
490 
491   /// Check if this value is used in the specified basic block.
492   bool isUsedInBasicBlock(const BasicBlock *BB) const;
493 
494   /// This method computes the number of uses of this Value.
495   ///
496   /// This is a linear time operation.  Use hasOneUse, hasNUses, or
497   /// hasNUsesOrMore to check for specific values.
498   unsigned getNumUses() const;
499 
500   /// This method should only be used by the Use class.
addUse(Use & U)501   void addUse(Use &U) { U.addToList(&UseList); }
502 
503   /// Concrete subclass of this.
504   ///
505   /// An enumeration for keeping track of the concrete subclass of Value that
506   /// is actually instantiated. Values of this enumeration are kept in the
507   /// Value classes SubclassID field. They are used for concrete type
508   /// identification.
509   enum ValueTy {
510 #define HANDLE_VALUE(Name) Name##Val,
511 #include "llvm/IR/Value.def"
512 
513     // Markers:
514 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
515 #include "llvm/IR/Value.def"
516   };
517 
518   /// Return an ID for the concrete type of this object.
519   ///
520   /// This is used to implement the classof checks.  This should not be used
521   /// for any other purpose, as the values may change as LLVM evolves.  Also,
522   /// note that for instructions, the Instruction's opcode is added to
523   /// InstructionVal. So this means three things:
524   /// # there is no value with code InstructionVal (no opcode==0).
525   /// # there are more possible values for the value type than in ValueTy enum.
526   /// # the InstructionVal enumerator must be the highest valued enumerator in
527   ///   the ValueTy enum.
getValueID()528   unsigned getValueID() const {
529     return SubclassID;
530   }
531 
532   /// Return the raw optional flags value contained in this value.
533   ///
534   /// This should only be used when testing two Values for equivalence.
getRawSubclassOptionalData()535   unsigned getRawSubclassOptionalData() const {
536     return SubclassOptionalData;
537   }
538 
539   /// Clear the optional flags contained in this value.
clearSubclassOptionalData()540   void clearSubclassOptionalData() {
541     SubclassOptionalData = 0;
542   }
543 
544   /// Check the optional flags for equality.
hasSameSubclassOptionalData(const Value * V)545   bool hasSameSubclassOptionalData(const Value *V) const {
546     return SubclassOptionalData == V->SubclassOptionalData;
547   }
548 
549   /// Return true if there is a value handle associated with this value.
hasValueHandle()550   bool hasValueHandle() const { return HasValueHandle; }
551 
552   /// Return true if there is metadata referencing this value.
isUsedByMetadata()553   bool isUsedByMetadata() const { return IsUsedByMD; }
554 
555 protected:
556   /// Get the current metadata attachments for the given kind, if any.
557   ///
558   /// These functions require that the value have at most a single attachment
559   /// of the given kind, and return \c nullptr if such an attachment is missing.
560   /// @{
561   MDNode *getMetadata(unsigned KindID) const;
562   MDNode *getMetadata(StringRef Kind) const;
563   /// @}
564 
565   /// Appends all attachments with the given ID to \c MDs in insertion order.
566   /// If the Value has no attachments with the given ID, or if ID is invalid,
567   /// leaves MDs unchanged.
568   /// @{
569   void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const;
570   void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const;
571   /// @}
572 
573   /// Appends all metadata attached to this value to \c MDs, sorting by
574   /// KindID. The first element of each pair returned is the KindID, the second
575   /// element is the metadata value. Attachments with the same ID appear in
576   /// insertion order.
577   void
578   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
579 
580   /// Return true if this value has any metadata attached to it.
hasMetadata()581   bool hasMetadata() const { return (bool)HasMetadata; }
582 
583   /// Return true if this value has the given type of metadata attached.
584   /// @{
hasMetadata(unsigned KindID)585   bool hasMetadata(unsigned KindID) const {
586     return getMetadata(KindID) != nullptr;
587   }
hasMetadata(StringRef Kind)588   bool hasMetadata(StringRef Kind) const {
589     return getMetadata(Kind) != nullptr;
590   }
591   /// @}
592 
593   /// Set a particular kind of metadata attachment.
594   ///
595   /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
596   /// replacing it if it already exists.
597   /// @{
598   void setMetadata(unsigned KindID, MDNode *Node);
599   void setMetadata(StringRef Kind, MDNode *Node);
600   /// @}
601 
602   /// Add a metadata attachment.
603   /// @{
604   void addMetadata(unsigned KindID, MDNode &MD);
605   void addMetadata(StringRef Kind, MDNode &MD);
606   /// @}
607 
608   /// Erase all metadata attachments with the given kind.
609   ///
610   /// \returns true if any metadata was removed.
611   bool eraseMetadata(unsigned KindID);
612 
613   /// Erase all metadata attached to this Value.
614   void clearMetadata();
615 
616 public:
617   /// Return true if this value is a swifterror value.
618   ///
619   /// swifterror values can be either a function argument or an alloca with a
620   /// swifterror attribute.
621   bool isSwiftError() const;
622 
623   /// Strip off pointer casts, all-zero GEPs and address space casts.
624   ///
625   /// Returns the original uncasted value.  If this is called on a non-pointer
626   /// value, it returns 'this'.
627   const Value *stripPointerCasts() const;
stripPointerCasts()628   Value *stripPointerCasts() {
629     return const_cast<Value *>(
630         static_cast<const Value *>(this)->stripPointerCasts());
631   }
632 
633   /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
634   ///
635   /// Returns the original uncasted value.  If this is called on a non-pointer
636   /// value, it returns 'this'.
637   const Value *stripPointerCastsAndAliases() const;
stripPointerCastsAndAliases()638   Value *stripPointerCastsAndAliases() {
639     return const_cast<Value *>(
640         static_cast<const Value *>(this)->stripPointerCastsAndAliases());
641   }
642 
643   /// Strip off pointer casts, all-zero GEPs and address space casts
644   /// but ensures the representation of the result stays the same.
645   ///
646   /// Returns the original uncasted value with the same representation. If this
647   /// is called on a non-pointer value, it returns 'this'.
648   const Value *stripPointerCastsSameRepresentation() const;
stripPointerCastsSameRepresentation()649   Value *stripPointerCastsSameRepresentation() {
650     return const_cast<Value *>(static_cast<const Value *>(this)
651                                    ->stripPointerCastsSameRepresentation());
652   }
653 
654   /// Strip off pointer casts, all-zero GEPs and invariant group info.
655   ///
656   /// Returns the original uncasted value.  If this is called on a non-pointer
657   /// value, it returns 'this'. This function should be used only in
658   /// Alias analysis.
659   const Value *stripPointerCastsAndInvariantGroups() const;
stripPointerCastsAndInvariantGroups()660   Value *stripPointerCastsAndInvariantGroups() {
661     return const_cast<Value *>(static_cast<const Value *>(this)
662                                    ->stripPointerCastsAndInvariantGroups());
663   }
664 
665   /// Strip off pointer casts and all-constant inbounds GEPs.
666   ///
667   /// Returns the original pointer value.  If this is called on a non-pointer
668   /// value, it returns 'this'.
669   const Value *stripInBoundsConstantOffsets() const;
stripInBoundsConstantOffsets()670   Value *stripInBoundsConstantOffsets() {
671     return const_cast<Value *>(
672               static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
673   }
674 
675   /// Accumulate the constant offset this value has compared to a base pointer.
676   /// Only 'getelementptr' instructions (GEPs) are accumulated but other
677   /// instructions, e.g., casts, are stripped away as well.
678   /// The accumulated constant offset is added to \p Offset and the base
679   /// pointer is returned.
680   ///
681   /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
682   /// the address space of 'this' pointer value, e.g., use
683   /// DataLayout::getIndexTypeSizeInBits(Ty).
684   ///
685   /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and
686   /// accumulated even if the GEP is not "inbounds".
687   ///
688   /// If \p ExternalAnalysis is provided it will be used to calculate a offset
689   /// when a operand of GEP is not constant.
690   /// For example, for a value \p ExternalAnalysis might try to calculate a
691   /// lower bound. If \p ExternalAnalysis is successful, it should return true.
692   ///
693   /// If this is called on a non-pointer value, it returns 'this' and the
694   /// \p Offset is not modified.
695   ///
696   /// Note that this function will never return a nullptr. It will also never
697   /// manipulate the \p Offset in a way that would not match the difference
698   /// between the underlying value and the returned one. Thus, if no constant
699   /// offset was found, the returned value is the underlying one and \p Offset
700   /// is unchanged.
701   const Value *stripAndAccumulateConstantOffsets(
702       const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
703       function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
704           nullptr) const;
stripAndAccumulateConstantOffsets(const DataLayout & DL,APInt & Offset,bool AllowNonInbounds)705   Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
706                                            bool AllowNonInbounds) {
707     return const_cast<Value *>(
708         static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
709             DL, Offset, AllowNonInbounds));
710   }
711 
712   /// This is a wrapper around stripAndAccumulateConstantOffsets with the
713   /// in-bounds requirement set to false.
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)714   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
715                                                          APInt &Offset) const {
716     return stripAndAccumulateConstantOffsets(DL, Offset,
717                                              /* AllowNonInbounds */ false);
718   }
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)719   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
720                                                    APInt &Offset) {
721     return stripAndAccumulateConstantOffsets(DL, Offset,
722                                              /* AllowNonInbounds */ false);
723   }
724 
725   /// Strip off pointer casts and inbounds GEPs.
726   ///
727   /// Returns the original pointer value.  If this is called on a non-pointer
728   /// value, it returns 'this'.
729   const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
730                                         [](const Value *) {}) const;
731   inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
732                                   [](const Value *) {}) {
733     return const_cast<Value *>(
734         static_cast<const Value *>(this)->stripInBoundsOffsets(Func));
735   }
736 
737   /// Returns the number of bytes known to be dereferenceable for the
738   /// pointer value.
739   ///
740   /// If CanBeNull is set by this function the pointer can either be null or be
741   /// dereferenceable up to the returned number of bytes.
742   uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
743                                           bool &CanBeNull) const;
744 
745   /// Returns an alignment of the pointer value.
746   ///
747   /// Returns an alignment which is either specified explicitly, e.g. via
748   /// align attribute of a function argument, or guaranteed by DataLayout.
749   Align getPointerAlignment(const DataLayout &DL) const;
750 
751   /// Translate PHI node to its predecessor from the given basic block.
752   ///
753   /// If this value is a PHI node with CurBB as its parent, return the value in
754   /// the PHI node corresponding to PredBB.  If not, return ourself.  This is
755   /// useful if you want to know the value something has in a predecessor
756   /// block.
757   const Value *DoPHITranslation(const BasicBlock *CurBB,
758                                 const BasicBlock *PredBB) const;
DoPHITranslation(const BasicBlock * CurBB,const BasicBlock * PredBB)759   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
760     return const_cast<Value *>(
761              static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
762   }
763 
764   /// The maximum alignment for instructions.
765   ///
766   /// This is the greatest alignment value supported by load, store, and alloca
767   /// instructions, and global values.
768   static const unsigned MaxAlignmentExponent = 29;
769   static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
770 
771   /// Mutate the type of this Value to be of the specified type.
772   ///
773   /// Note that this is an extremely dangerous operation which can create
774   /// completely invalid IR very easily.  It is strongly recommended that you
775   /// recreate IR objects with the right types instead of mutating them in
776   /// place.
mutateType(Type * Ty)777   void mutateType(Type *Ty) {
778     VTy = Ty;
779   }
780 
781   /// Sort the use-list.
782   ///
783   /// Sorts the Value's use-list by Cmp using a stable mergesort.  Cmp is
784   /// expected to compare two \a Use references.
785   template <class Compare> void sortUseList(Compare Cmp);
786 
787   /// Reverse the use-list.
788   void reverseUseList();
789 
790 private:
791   /// Merge two lists together.
792   ///
793   /// Merges \c L and \c R using \c Cmp.  To enable stable sorts, always pushes
794   /// "equal" items from L before items from R.
795   ///
796   /// \return the first element in the list.
797   ///
798   /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
799   template <class Compare>
mergeUseLists(Use * L,Use * R,Compare Cmp)800   static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
801     Use *Merged;
802     Use **Next = &Merged;
803 
804     while (true) {
805       if (!L) {
806         *Next = R;
807         break;
808       }
809       if (!R) {
810         *Next = L;
811         break;
812       }
813       if (Cmp(*R, *L)) {
814         *Next = R;
815         Next = &R->Next;
816         R = R->Next;
817       } else {
818         *Next = L;
819         Next = &L->Next;
820         L = L->Next;
821       }
822     }
823 
824     return Merged;
825   }
826 
827 protected:
getSubclassDataFromValue()828   unsigned short getSubclassDataFromValue() const { return SubclassData; }
setValueSubclassData(unsigned short D)829   void setValueSubclassData(unsigned short D) { SubclassData = D; }
830 };
831 
operatorValueDeleter832 struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
833 
834 /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
835 /// Those don't work because Value and Instruction's destructors are protected,
836 /// aren't virtual, and won't destroy the complete object.
837 using unique_value = std::unique_ptr<Value, ValueDeleter>;
838 
839 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
840   V.print(OS);
841   return OS;
842 }
843 
set(Value * V)844 void Use::set(Value *V) {
845   if (Val) removeFromList();
846   Val = V;
847   if (V) V->addUse(*this);
848 }
849 
850 Value *Use::operator=(Value *RHS) {
851   set(RHS);
852   return RHS;
853 }
854 
855 const Use &Use::operator=(const Use &RHS) {
856   set(RHS.Val);
857   return *this;
858 }
859 
sortUseList(Compare Cmp)860 template <class Compare> void Value::sortUseList(Compare Cmp) {
861   if (!UseList || !UseList->Next)
862     // No need to sort 0 or 1 uses.
863     return;
864 
865   // Note: this function completely ignores Prev pointers until the end when
866   // they're fixed en masse.
867 
868   // Create a binomial vector of sorted lists, visiting uses one at a time and
869   // merging lists as necessary.
870   const unsigned MaxSlots = 32;
871   Use *Slots[MaxSlots];
872 
873   // Collect the first use, turning it into a single-item list.
874   Use *Next = UseList->Next;
875   UseList->Next = nullptr;
876   unsigned NumSlots = 1;
877   Slots[0] = UseList;
878 
879   // Collect all but the last use.
880   while (Next->Next) {
881     Use *Current = Next;
882     Next = Current->Next;
883 
884     // Turn Current into a single-item list.
885     Current->Next = nullptr;
886 
887     // Save Current in the first available slot, merging on collisions.
888     unsigned I;
889     for (I = 0; I < NumSlots; ++I) {
890       if (!Slots[I])
891         break;
892 
893       // Merge two lists, doubling the size of Current and emptying slot I.
894       //
895       // Since the uses in Slots[I] originally preceded those in Current, send
896       // Slots[I] in as the left parameter to maintain a stable sort.
897       Current = mergeUseLists(Slots[I], Current, Cmp);
898       Slots[I] = nullptr;
899     }
900     // Check if this is a new slot.
901     if (I == NumSlots) {
902       ++NumSlots;
903       assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
904     }
905 
906     // Found an open slot.
907     Slots[I] = Current;
908   }
909 
910   // Merge all the lists together.
911   assert(Next && "Expected one more Use");
912   assert(!Next->Next && "Expected only one Use");
913   UseList = Next;
914   for (unsigned I = 0; I < NumSlots; ++I)
915     if (Slots[I])
916       // Since the uses in Slots[I] originally preceded those in UseList, send
917       // Slots[I] in as the left parameter to maintain a stable sort.
918       UseList = mergeUseLists(Slots[I], UseList, Cmp);
919 
920   // Fix the Prev pointers.
921   for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
922     I->Prev = Prev;
923     Prev = &I->Next;
924   }
925 }
926 
927 // isa - Provide some specializations of isa so that we don't have to include
928 // the subtype header files to test to see if the value is a subclass...
929 //
930 template <> struct isa_impl<Constant, Value> {
931   static inline bool doit(const Value &Val) {
932     static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
933     return Val.getValueID() <= Value::ConstantLastVal;
934   }
935 };
936 
937 template <> struct isa_impl<ConstantData, Value> {
938   static inline bool doit(const Value &Val) {
939     return Val.getValueID() >= Value::ConstantDataFirstVal &&
940            Val.getValueID() <= Value::ConstantDataLastVal;
941   }
942 };
943 
944 template <> struct isa_impl<ConstantAggregate, Value> {
945   static inline bool doit(const Value &Val) {
946     return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
947            Val.getValueID() <= Value::ConstantAggregateLastVal;
948   }
949 };
950 
951 template <> struct isa_impl<Argument, Value> {
952   static inline bool doit (const Value &Val) {
953     return Val.getValueID() == Value::ArgumentVal;
954   }
955 };
956 
957 template <> struct isa_impl<InlineAsm, Value> {
958   static inline bool doit(const Value &Val) {
959     return Val.getValueID() == Value::InlineAsmVal;
960   }
961 };
962 
963 template <> struct isa_impl<Instruction, Value> {
964   static inline bool doit(const Value &Val) {
965     return Val.getValueID() >= Value::InstructionVal;
966   }
967 };
968 
969 template <> struct isa_impl<BasicBlock, Value> {
970   static inline bool doit(const Value &Val) {
971     return Val.getValueID() == Value::BasicBlockVal;
972   }
973 };
974 
975 template <> struct isa_impl<Function, Value> {
976   static inline bool doit(const Value &Val) {
977     return Val.getValueID() == Value::FunctionVal;
978   }
979 };
980 
981 template <> struct isa_impl<GlobalVariable, Value> {
982   static inline bool doit(const Value &Val) {
983     return Val.getValueID() == Value::GlobalVariableVal;
984   }
985 };
986 
987 template <> struct isa_impl<GlobalAlias, Value> {
988   static inline bool doit(const Value &Val) {
989     return Val.getValueID() == Value::GlobalAliasVal;
990   }
991 };
992 
993 template <> struct isa_impl<GlobalIFunc, Value> {
994   static inline bool doit(const Value &Val) {
995     return Val.getValueID() == Value::GlobalIFuncVal;
996   }
997 };
998 
999 template <> struct isa_impl<GlobalIndirectSymbol, Value> {
1000   static inline bool doit(const Value &Val) {
1001     return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
1002   }
1003 };
1004 
1005 template <> struct isa_impl<GlobalValue, Value> {
1006   static inline bool doit(const Value &Val) {
1007     return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
1008   }
1009 };
1010 
1011 template <> struct isa_impl<GlobalObject, Value> {
1012   static inline bool doit(const Value &Val) {
1013     return isa<GlobalVariable>(Val) || isa<Function>(Val);
1014   }
1015 };
1016 
1017 // Create wrappers for C Binding types (see CBindingWrapping.h).
1018 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
1019 
1020 // Specialized opaque value conversions.
1021 inline Value **unwrap(LLVMValueRef *Vals) {
1022   return reinterpret_cast<Value**>(Vals);
1023 }
1024 
1025 template<typename T>
1026 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
1027 #ifndef NDEBUG
1028   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
1029     unwrap<T>(*I); // For side effect of calling assert on invalid usage.
1030 #endif
1031   (void)Length;
1032   return reinterpret_cast<T**>(Vals);
1033 }
1034 
1035 inline LLVMValueRef *wrap(const Value **Vals) {
1036   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
1037 }
1038 
1039 } // end namespace llvm
1040 
1041 #endif // LLVM_IR_VALUE_H
1042