xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/User.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/User.h - User class definition ----------------------*- 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 class defines the interface that one who uses a Value must implement.
10 // Each instance of the Value class keeps track of what User's have handles
11 // to it.
12 //
13 //  * Instructions are the largest class of Users.
14 //  * Constants may be users of other constants (think arrays and stuff)
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_IR_USER_H
19 #define LLVM_IR_USER_H
20 
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Use.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <cassert>
29 #include <cstddef>
30 #include <cstdint>
31 #include <iterator>
32 
33 namespace llvm {
34 
35 template <typename T> class ArrayRef;
36 template <typename T> class MutableArrayRef;
37 
38 /// Compile-time customization of User operands.
39 ///
40 /// Customizes operand-related allocators and accessors.
41 template <class>
42 struct OperandTraits;
43 
44 class User : public Value {
45   friend struct HungoffOperandTraits;
46   template <class ConstantClass> friend struct ConstantAggrKeyType;
47 
48   LLVM_ATTRIBUTE_ALWAYS_INLINE static void *
49   allocateFixedOperandUser(size_t, unsigned, unsigned);
50 
51 protected:
52   // Disable the default operator new, as all subclasses must use one of the
53   // custom operators below depending on how they store their operands.
54   void *operator new(size_t Size) = delete;
55 
56   /// Indicates this User has operands "hung off" in another allocation.
57   struct HungOffOperandsAllocMarker {};
58 
59   /// Indicates this User has operands co-allocated.
60   struct IntrusiveOperandsAllocMarker {
61     /// The number of operands for this User.
62     const unsigned NumOps;
63   };
64 
65   /// Indicates this User has operands and a descriptor co-allocated .
66   struct IntrusiveOperandsAndDescriptorAllocMarker {
67     /// The number of operands for this User.
68     const unsigned NumOps;
69     /// The number of bytes to allocate for the descriptor. Must be divisible by
70     /// `sizeof(void *)`.
71     const unsigned DescBytes;
72   };
73 
74   /// Information about how a User object was allocated, to be passed into the
75   /// User constructor.
76   ///
77   /// DO NOT USE DIRECTLY. Use one of the `AllocMarker` structs instead, they
78   /// call all be implicitly converted to `AllocInfo`.
79   struct AllocInfo {
80   public:
81     const unsigned NumOps : NumUserOperandsBits;
82     LLVM_PREFERRED_TYPE(bool)
83     const unsigned HasHungOffUses : 1;
84     LLVM_PREFERRED_TYPE(bool)
85     const unsigned HasDescriptor : 1;
86 
87     AllocInfo() = delete;
88 
AllocInfoAllocInfo89     constexpr AllocInfo(const HungOffOperandsAllocMarker)
90         : NumOps(0), HasHungOffUses(true), HasDescriptor(false) {}
91 
AllocInfoAllocInfo92     constexpr AllocInfo(const IntrusiveOperandsAllocMarker Alloc)
93         : NumOps(Alloc.NumOps), HasHungOffUses(false), HasDescriptor(false) {}
94 
AllocInfoAllocInfo95     constexpr AllocInfo(const IntrusiveOperandsAndDescriptorAllocMarker Alloc)
96         : NumOps(Alloc.NumOps), HasHungOffUses(false),
97           HasDescriptor(Alloc.DescBytes != 0) {}
98   };
99 
100   /// Allocate a User with an operand pointer co-allocated.
101   ///
102   /// This is used for subclasses which need to allocate a variable number
103   /// of operands, ie, 'hung off uses'.
104   LLVM_ABI void *operator new(size_t Size, HungOffOperandsAllocMarker);
105 
106   /// Allocate a User with the operands co-allocated.
107   ///
108   /// This is used for subclasses which have a fixed number of operands.
109   LLVM_ABI void *operator new(size_t Size,
110                               IntrusiveOperandsAllocMarker allocTrait);
111 
112   /// Allocate a User with the operands co-allocated.  If DescBytes is non-zero
113   /// then allocate an additional DescBytes bytes before the operands. These
114   /// bytes can be accessed by calling getDescriptor.
115   LLVM_ABI void *
116   operator new(size_t Size,
117                IntrusiveOperandsAndDescriptorAllocMarker allocTrait);
118 
User(Type * ty,unsigned vty,AllocInfo AllocInfo)119   User(Type *ty, unsigned vty, AllocInfo AllocInfo) : Value(ty, vty) {
120     assert(AllocInfo.NumOps < (1u << NumUserOperandsBits) &&
121            "Too many operands");
122     NumUserOperands = AllocInfo.NumOps;
123     assert((!AllocInfo.HasDescriptor || !AllocInfo.HasHungOffUses) &&
124            "Cannot have both hung off uses and a descriptor");
125     HasHungOffUses = AllocInfo.HasHungOffUses;
126     HasDescriptor = AllocInfo.HasDescriptor;
127     // If we have hung off uses, then the operand list should initially be
128     // null.
129     assert((!AllocInfo.HasHungOffUses || !getOperandList()) &&
130            "Error in initializing hung off uses for User");
131   }
132 
133   /// Allocate the array of Uses, followed by a pointer
134   /// (with bottom bit set) to the User.
135   /// \param IsPhi identifies callers which are phi nodes and which need
136   /// N BasicBlock* allocated along with N
137   LLVM_ABI void allocHungoffUses(unsigned N, bool IsPhi = false);
138 
139   /// Grow the number of hung off uses.  Note that allocHungoffUses
140   /// should be called if there are no uses.
141   LLVM_ABI void growHungoffUses(unsigned N, bool IsPhi = false);
142 
143 protected:
144   ~User() = default; // Use deleteValue() to delete a generic Instruction.
145 
146 public:
147   User(const User &) = delete;
148 
149   /// Free memory allocated for User and Use objects.
150   LLVM_ABI void operator delete(void *Usr);
151   /// Placement delete - required by std, called if the ctor throws.
delete(void * Usr,HungOffOperandsAllocMarker)152   void operator delete(void *Usr, HungOffOperandsAllocMarker) {
153     // Note: If a subclass manipulates the information which is required to
154     // calculate the Usr memory pointer, e.g. NumUserOperands, the operator
155     // delete of that subclass has to restore the changed information to the
156     // original value, since the dtor of that class is not called if the ctor
157     // fails.
158     User::operator delete(Usr);
159 
160 #ifndef LLVM_ENABLE_EXCEPTIONS
161     llvm_unreachable("Constructor throws?");
162 #endif
163   }
164   /// Placement delete - required by std, called if the ctor throws.
delete(void * Usr,IntrusiveOperandsAllocMarker)165   void operator delete(void *Usr, IntrusiveOperandsAllocMarker) {
166     // Note: If a subclass manipulates the information which is required to calculate the
167     // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has
168     // to restore the changed information to the original value, since the dtor of that class
169     // is not called if the ctor fails.
170     User::operator delete(Usr);
171 
172 #ifndef LLVM_ENABLE_EXCEPTIONS
173     llvm_unreachable("Constructor throws?");
174 #endif
175   }
176   /// Placement delete - required by std, called if the ctor throws.
delete(void * Usr,IntrusiveOperandsAndDescriptorAllocMarker)177   void operator delete(void *Usr, IntrusiveOperandsAndDescriptorAllocMarker) {
178     // Note: If a subclass manipulates the information which is required to calculate the
179     // Usr memory pointer, e.g. NumUserOperands, the operator delete of that subclass has
180     // to restore the changed information to the original value, since the dtor of that class
181     // is not called if the ctor fails.
182     User::operator delete(Usr);
183 
184 #ifndef LLVM_ENABLE_EXCEPTIONS
185     llvm_unreachable("Constructor throws?");
186 #endif
187   }
188 
189 protected:
OpFrom(const U * that)190   template <int Idx, typename U> static Use &OpFrom(const U *that) {
191     return Idx < 0
192       ? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx]
193       : OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx];
194   }
195 
Op()196   template <int Idx> Use &Op() {
197     return OpFrom<Idx>(this);
198   }
Op()199   template <int Idx> const Use &Op() const {
200     return OpFrom<Idx>(this);
201   }
202 
203 private:
getHungOffOperands()204   const Use *getHungOffOperands() const {
205     return *(reinterpret_cast<const Use *const *>(this) - 1);
206   }
207 
getHungOffOperands()208   Use *&getHungOffOperands() { return *(reinterpret_cast<Use **>(this) - 1); }
209 
getIntrusiveOperands()210   const Use *getIntrusiveOperands() const {
211     return reinterpret_cast<const Use *>(this) - NumUserOperands;
212   }
213 
getIntrusiveOperands()214   Use *getIntrusiveOperands() {
215     return reinterpret_cast<Use *>(this) - NumUserOperands;
216   }
217 
setOperandList(Use * NewList)218   void setOperandList(Use *NewList) {
219     assert(HasHungOffUses &&
220            "Setting operand list only required for hung off uses");
221     getHungOffOperands() = NewList;
222   }
223 
224 public:
getOperandList()225   const Use *getOperandList() const {
226     return HasHungOffUses ? getHungOffOperands() : getIntrusiveOperands();
227   }
getOperandList()228   Use *getOperandList() {
229     return const_cast<Use *>(static_cast<const User *>(this)->getOperandList());
230   }
231 
getOperand(unsigned i)232   Value *getOperand(unsigned i) const {
233     assert(i < NumUserOperands && "getOperand() out of range!");
234     return getOperandList()[i];
235   }
236 
setOperand(unsigned i,Value * Val)237   void setOperand(unsigned i, Value *Val) {
238     assert(i < NumUserOperands && "setOperand() out of range!");
239     assert((!isa<Constant>((const Value*)this) ||
240             isa<GlobalValue>((const Value*)this)) &&
241            "Cannot mutate a constant with setOperand!");
242     getOperandList()[i] = Val;
243   }
244 
getOperandUse(unsigned i)245   const Use &getOperandUse(unsigned i) const {
246     assert(i < NumUserOperands && "getOperandUse() out of range!");
247     return getOperandList()[i];
248   }
getOperandUse(unsigned i)249   Use &getOperandUse(unsigned i) {
250     assert(i < NumUserOperands && "getOperandUse() out of range!");
251     return getOperandList()[i];
252   }
253 
getNumOperands()254   unsigned getNumOperands() const { return NumUserOperands; }
255 
256   /// Returns the descriptor co-allocated with this User instance.
257   LLVM_ABI ArrayRef<const uint8_t> getDescriptor() const;
258 
259   /// Returns the descriptor co-allocated with this User instance.
260   LLVM_ABI MutableArrayRef<uint8_t> getDescriptor();
261 
262   /// Subclasses with hung off uses need to manage the operand count
263   /// themselves.  In these instances, the operand count isn't used to find the
264   /// OperandList, so there's no issue in having the operand count change.
setNumHungOffUseOperands(unsigned NumOps)265   void setNumHungOffUseOperands(unsigned NumOps) {
266     assert(HasHungOffUses && "Must have hung off uses to use this method");
267     assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands");
268     NumUserOperands = NumOps;
269   }
270 
271   /// A droppable user is a user for which uses can be dropped without affecting
272   /// correctness and should be dropped rather than preventing a transformation
273   /// from happening.
274   LLVM_ABI bool isDroppable() const;
275 
276   // ---------------------------------------------------------------------------
277   // Operand Iterator interface...
278   //
279   using op_iterator = Use*;
280   using const_op_iterator = const Use*;
281   using op_range = iterator_range<op_iterator>;
282   using const_op_range = iterator_range<const_op_iterator>;
283 
op_begin()284   op_iterator       op_begin()       { return getOperandList(); }
op_begin()285   const_op_iterator op_begin() const { return getOperandList(); }
op_end()286   op_iterator       op_end()         {
287     return getOperandList() + NumUserOperands;
288   }
op_end()289   const_op_iterator op_end()   const {
290     return getOperandList() + NumUserOperands;
291   }
operands()292   op_range operands() {
293     return op_range(op_begin(), op_end());
294   }
operands()295   const_op_range operands() const {
296     return const_op_range(op_begin(), op_end());
297   }
298 
299   /// Iterator for directly iterating over the operand Values.
300   struct value_op_iterator
301       : iterator_adaptor_base<value_op_iterator, op_iterator,
302                               std::random_access_iterator_tag, Value *,
303                               ptrdiff_t, Value *, Value *> {
iterator_adaptor_basevalue_op_iterator304     explicit value_op_iterator(Use *U = nullptr) : iterator_adaptor_base(U) {}
305 
306     Value *operator*() const { return *I; }
307     Value *operator->() const { return operator*(); }
308   };
309 
value_op_begin()310   value_op_iterator value_op_begin() {
311     return value_op_iterator(op_begin());
312   }
value_op_end()313   value_op_iterator value_op_end() {
314     return value_op_iterator(op_end());
315   }
operand_values()316   iterator_range<value_op_iterator> operand_values() {
317     return make_range(value_op_begin(), value_op_end());
318   }
319 
320   struct const_value_op_iterator
321       : iterator_adaptor_base<const_value_op_iterator, const_op_iterator,
322                               std::random_access_iterator_tag, const Value *,
323                               ptrdiff_t, const Value *, const Value *> {
324     explicit const_value_op_iterator(const Use *U = nullptr) :
iterator_adaptor_baseconst_value_op_iterator325       iterator_adaptor_base(U) {}
326 
327     const Value *operator*() const { return *I; }
328     const Value *operator->() const { return operator*(); }
329   };
330 
value_op_begin()331   const_value_op_iterator value_op_begin() const {
332     return const_value_op_iterator(op_begin());
333   }
value_op_end()334   const_value_op_iterator value_op_end() const {
335     return const_value_op_iterator(op_end());
336   }
operand_values()337   iterator_range<const_value_op_iterator> operand_values() const {
338     return make_range(value_op_begin(), value_op_end());
339   }
340 
341   /// Drop all references to operands.
342   ///
343   /// This function is in charge of "letting go" of all objects that this User
344   /// refers to.  This allows one to 'delete' a whole class at a time, even
345   /// though there may be circular references...  First all references are
346   /// dropped, and all use counts go to zero.  Then everything is deleted for
347   /// real.  Note that no operations are valid on an object that has "dropped
348   /// all references", except operator delete.
dropAllReferences()349   void dropAllReferences() {
350     for (Use &U : operands())
351       U.set(nullptr);
352   }
353 
354   /// Replace uses of one Value with another.
355   ///
356   /// Replaces all references to the "From" definition with references to the
357   /// "To" definition. Returns whether any uses were replaced.
358   LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To);
359 
360   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Value * V)361   static bool classof(const Value *V) {
362     return isa<Instruction>(V) || isa<Constant>(V);
363   }
364 };
365 
366 // Either Use objects, or a Use pointer can be prepended to User.
367 static_assert(alignof(Use) >= alignof(User),
368               "Alignment is insufficient after objects prepended to User");
369 static_assert(alignof(Use *) >= alignof(User),
370               "Alignment is insufficient after objects prepended to User");
371 
372 template<> struct simplify_type<User::op_iterator> {
373   using SimpleType = Value*;
374 
375   static SimpleType getSimplifiedValue(User::op_iterator &Val) {
376     return Val->get();
377   }
378 };
379 template<> struct simplify_type<User::const_op_iterator> {
380   using SimpleType = /*const*/ Value*;
381 
382   static SimpleType getSimplifiedValue(User::const_op_iterator &Val) {
383     return Val->get();
384   }
385 };
386 
387 } // end namespace llvm
388 
389 #endif // LLVM_IR_USER_H
390