LLVM  10.0.0svn
PointerUnion.h
Go to the documentation of this file.
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"
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>
42 };
43 
44 template <typename T, typename RET_EQ, typename RET_NE>
45 struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
47 };
48 
49 template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
51  PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52  using 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 assigment 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>
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;
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>
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(
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>
244  return lhs.getOpaqueValue() == rhs.getOpaqueValue();
245 }
246 
247 template <typename ...PTs>
249  return lhs.getOpaqueValue() != rhs.getOpaqueValue();
250 }
251 
252 template <typename ...PTs>
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>
261  static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
262  return P.getOpaqueValue();
263  }
264 
265  static inline PointerUnion<PTs...> getFromVoidPointer(void *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 /// A pointer union of three pointer types. See documentation for PointerUnion
276 /// for usage.
277 template <typename PT1, typename PT2, typename PT3>
279 
280 /// A pointer union of four pointer types. See documentation for PointerUnion
281 /// for usage.
282 template <typename PT1, typename PT2, typename PT3, typename PT4>
284 
285 // Teach DenseMap how to use PointerUnions as keys.
286 template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
287  using Union = PointerUnion<PTs...>;
288  using FirstInfo =
290 
291  static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
292 
293  static inline Union getTombstoneKey() {
294  return Union(FirstInfo::getTombstoneKey());
295  }
296 
297  static unsigned getHashValue(const Union &UnionVal) {
298  intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
300  }
301 
302  static bool isEqual(const Union &LHS, const Union &RHS) {
303  return LHS == RHS;
304  }
305 };
306 
307 } // end namespace llvm
308 
309 #endif // LLVM_ADT_POINTERUNION_H
Type
MessagePack types as defined in the standard, with the exception of Integer being divided into a sign...
Definition: MsgPackReader.h:48
First const * getAddrOfPtr1() const
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:209
This class represents lattice values for constants.
Definition: AllocatorList.h:23
constexpr int bitsRequired(unsigned n)
Determine the number of bits required to store integers with values < n.
Definition: PointerUnion.h:59
constexpr int lowBitsAvailable()
Definition: PointerUnion.h:63
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:201
typename PointerUnionTypeSelectorReturn< RET_EQ >::Return Return
Definition: PointerUnion.h:46
static void * getAsVoidPointer(const PointerUnion< PTs... > &P)
Definition: PointerUnion.h:261
Get a type based on whether two types are the same or not.
Definition: PointerUnion.h:40
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
static unsigned getHashValue(const Union &UnionVal)
Definition: PointerUnion.h:297
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Definition: PointerUnion.h:179
typename PointerUnionTypeSelector< T1, T2, RET_EQ, RET_NE >::Return Return
Definition: PointerUnion.h:53
#define P(N)
PointerUnion(std::nullptr_t)
Definition: PointerUnion.h:174
typename PointerUnionTypeSelectorReturn< RET_NE >::Return Return
Definition: PointerUnion.h:41
const PointerUnion & operator=(std::nullptr_t)
Assignment from nullptr which just clears the union.
Definition: PointerUnion.h:226
First * getAddrOfPtr1()
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:215
Find the index of a type in a list of types.
Definition: PointerUnion.h:70
Provide PointerLikeTypeTraits for void* that is used by PointerUnion for the template arguments...
Definition: PointerUnion.h:89
static bool isEqual(const Union &LHS, const Union &RHS)
Definition: PointerUnion.h:302
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:1975
#define I(x, y, z)
Definition: MD5.cpp:58
int is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:184
static PointerUnion< PTs... > getFromVoidPointer(void *P)
Definition: PointerUnion.h:265
static PointerUnion getFromOpaqueValue(void *VP)
Definition: PointerUnion.h:235
Implement assigment in terms of construction.
Definition: PointerUnion.h:97
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:343
Find the first type in a list of types.
Definition: PointerUnion.h:83
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:1973
void * getOpaqueValue() const
Definition: PointerUnion.h:234
#define T1
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:156