1 //===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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 defines the PointerUnion class, which is a discriminated union of
10 // pointer types.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ADT_POINTERUNION_H
15 #define LLVM_ADT_POINTERUNION_H
16 
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/Support/PointerLikeTypeTraits.h"
20 #include <cassert>
21 #include <cstddef>
22 #include <cstdint>
23 
24 namespace llvm {
25 
26 template <typename T> struct PointerUnionTypeSelectorReturn {
27   using Return = T;
28 };
29 
30 /// Get a type based on whether two types are the same or not.
31 ///
32 /// For:
33 ///
34 /// \code
35 ///   using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36 /// \endcode
37 ///
38 /// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39 template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40 struct PointerUnionTypeSelector {
41   using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42 };
43 
44 template <typename T, typename RET_EQ, typename RET_NE>
45 struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46   using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47 };
48 
49 template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50 struct PointerUnionTypeSelectorReturn<
51     PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52   using Return =
53       typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54 };
55 
56 namespace pointer_union_detail {
57   /// Determine the number of bits required to store integers with values < n.
58   /// This is ceil(log2(n)).
59   constexpr int bitsRequired(unsigned n) {
60     return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61   }
62 
63   template <typename... Ts> constexpr int lowBitsAvailable() {
64     return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65   }
66 
67   /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68   /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69   /// list.
70   template <typename T, typename ...Us> struct TypeIndex;
71   template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72     static constexpr int Index = 0;
73   };
74   template <typename T, typename U, typename... Us>
75   struct TypeIndex<T, U, Us...> {
76     static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77   };
78   template <typename T> struct TypeIndex<T> {
79     static constexpr int Index = 0;
80   };
81 
82   /// Find the first type in a list of types.
83   template <typename T, typename...> struct GetFirstType {
84     using type = T;
85   };
86 
87   /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88   /// for the template arguments.
89   template <typename ...PTs> class PointerUnionUIntTraits {
90   public:
91     static inline void *getAsVoidPointer(void *P) { return P; }
92     static inline void *getFromVoidPointer(void *P) { return P; }
93     static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94   };
95 
96   /// Implement assignment in terms of construction.
97   template <typename Derived, typename T> struct AssignableFrom {
98     Derived &operator=(T t) {
99       return static_cast<Derived &>(*this) = Derived(t);
100     }
101   };
102 
103   template <typename Derived, typename ValTy, int I, typename ...Types>
104   class PointerUnionMembers;
105 
106   template <typename Derived, typename ValTy, int I>
107   class PointerUnionMembers<Derived, ValTy, I> {
108   protected:
109     ValTy Val;
110     PointerUnionMembers() = default;
111     PointerUnionMembers(ValTy Val) : Val(Val) {}
112 
113     friend struct PointerLikeTypeTraits<Derived>;
114   };
115 
116   template <typename Derived, typename ValTy, int I, typename Type,
117             typename ...Types>
118   class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
119       : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
120     using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
121   public:
122     using Base::Base;
123     PointerUnionMembers() = default;
124     PointerUnionMembers(Type V)
125         : Base(ValTy(const_cast<void *>(
126                          PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
127                      I)) {}
128 
129     using Base::operator=;
130     Derived &operator=(Type V) {
131       this->Val = ValTy(
132           const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
133           I);
134       return static_cast<Derived &>(*this);
135     };
136   };
137 }
138 
139 /// A discriminated union of two or more pointer types, with the discriminator
140 /// in the low bit of the pointer.
141 ///
142 /// This implementation is extremely efficient in space due to leveraging the
143 /// low bits of the pointer, while exposing a natural and type-safe API.
144 ///
145 /// Common use patterns would be something like this:
146 ///    PointerUnion<int*, float*> P;
147 ///    P = (int*)0;
148 ///    printf("%d %d", P.is<int*>(), P.is<float*>());  // prints "1 0"
149 ///    X = P.get<int*>();     // ok.
150 ///    Y = P.get<float*>();   // runtime assertion failure.
151 ///    Z = P.get<double*>();  // compile time failure.
152 ///    P = (float*)0;
153 ///    Y = P.get<float*>();   // ok.
154 ///    X = P.get<int*>();     // runtime assertion failure.
155 template <typename... PTs>
156 class PointerUnion
157     : public pointer_union_detail::PointerUnionMembers<
158           PointerUnion<PTs...>,
159           PointerIntPair<
160               void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
161               pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
162           0, PTs...> {
163   // The first type is special because we want to directly cast a pointer to a
164   // default-initialized union to a pointer to the first type. But we don't
165   // want PointerUnion to be a 'template <typename First, typename ...Rest>'
166   // because it's much more convenient to have a name for the whole pack. So
167   // split off the first type here.
168   using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
169   using Base = typename PointerUnion::PointerUnionMembers;
170 
171 public:
172   PointerUnion() = default;
173 
174   PointerUnion(std::nullptr_t) : PointerUnion() {}
175   using Base::Base;
176 
177   /// Test if the pointer held in the union is null, regardless of
178   /// which type it is.
179   bool isNull() const { return !this->Val.getPointer(); }
180 
181   explicit operator bool() const { return !isNull(); }
182 
183   /// Test if the Union currently holds the type matching T.
184   template <typename T> int is() const {
185     constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
186     static_assert(Index < sizeof...(PTs),
187                   "PointerUnion::is<T> given type not in the union");
188     return this->Val.getInt() == Index;
189   }
190 
191   /// Returns the value of the specified pointer type.
192   ///
193   /// If the specified pointer type is incorrect, assert.
194   template <typename T> T get() const {
195     assert(is<T>() && "Invalid accessor called");
196     return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
197   }
198 
199   /// Returns the current pointer if it is of the specified pointer type,
200   /// otherwises returns null.
201   template <typename T> T dyn_cast() const {
202     if (is<T>())
203       return get<T>();
204     return T();
205   }
206 
207   /// If the union is set to the first pointer type get an address pointing to
208   /// it.
209   First const *getAddrOfPtr1() const {
210     return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
211   }
212 
213   /// If the union is set to the first pointer type get an address pointing to
214   /// it.
215   First *getAddrOfPtr1() {
216     assert(is<First>() && "Val is not the first pointer");
217     assert(
218         PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==
219             this->Val.getPointer() &&
220         "Can't get the address because PointerLikeTypeTraits changes the ptr");
221     return const_cast<First *>(
222         reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
223   }
224 
225   /// Assignment from nullptr which just clears the union.
226   const PointerUnion &operator=(std::nullptr_t) {
227     this->Val.initWithPointer(nullptr);
228     return *this;
229   }
230 
231   /// Assignment from elements of the union.
232   using Base::operator=;
233 
234   void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
235   static inline PointerUnion getFromOpaqueValue(void *VP) {
236     PointerUnion V;
237     V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
238     return V;
239   }
240 };
241 
242 template <typename ...PTs>
243 bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
244   return lhs.getOpaqueValue() == rhs.getOpaqueValue();
245 }
246 
247 template <typename ...PTs>
248 bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
249   return lhs.getOpaqueValue() != rhs.getOpaqueValue();
250 }
251 
252 template <typename ...PTs>
253 bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
254   return lhs.getOpaqueValue() < rhs.getOpaqueValue();
255 }
256 
257 // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
258 // # low bits available = min(PT1bits,PT2bits)-1.
259 template <typename ...PTs>
260 struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
261   static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
262     return P.getOpaqueValue();
263   }
264 
265   static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
266     return PointerUnion<PTs...>::getFromOpaqueValue(P);
267   }
268 
269   // The number of bits available are the min of the pointer types minus the
270   // bits needed for the discriminator.
271   static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
272       PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
273 };
274 
275 // Teach DenseMap how to use PointerUnions as keys.
276 template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
277   using Union = PointerUnion<PTs...>;
278   using FirstInfo =
279       DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
280 
281   static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
282 
283   static inline Union getTombstoneKey() {
284     return Union(FirstInfo::getTombstoneKey());
285   }
286 
287   static unsigned getHashValue(const Union &UnionVal) {
288     intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
289     return DenseMapInfo<intptr_t>::getHashValue(key);
290   }
291 
292   static bool isEqual(const Union &LHS, const Union &RHS) {
293     return LHS == RHS;
294   }
295 };
296 
297 } // end namespace llvm
298 
299 #endif // LLVM_ADT_POINTERUNION_H
300