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