WPILibC++ 2024.3.2
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/// \file
10/// This file defines the PointerUnion class, which is a discriminated union of
11/// pointer types.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef WPIUTIL_WPI_POINTERUNION_H
16#define WPIUTIL_WPI_POINTERUNION_H
17
18#include "wpi/DenseMapInfo.h"
19#include "wpi/PointerIntPair.h"
20#include "wpi/Casting.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdint>
26#include <type_traits>
27
28namespace wpi {
29
30namespace detail {
31template <typename T, typename... Us> struct TypesAreDistinct;
32template <typename T, typename... Us>
34 : std::integral_constant<bool, !std::disjunction_v<std::is_same<T, Us>...> &&
35 TypesAreDistinct<Us...>::value> {};
36template <typename T> struct TypesAreDistinct<T> : std::true_type {};
37} // namespace detail
38
39/// Determine if all types in Ts are distinct.
40///
41/// Useful to statically assert when Ts is intended to describe a non-multi set
42/// of types.
43///
44/// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
45/// asserted once per instantiation of a type which requires it.
46template <typename... Ts> struct TypesAreDistinct;
47template <> struct TypesAreDistinct<> : std::true_type {};
48template <typename... Ts>
50 : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {};
51
52/// Find the first index where a type appears in a list of types.
53///
54/// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
55///
56/// Typically only meaningful when it is otherwise statically known that the
57/// type pack has no duplicate types. This should be guaranteed explicitly with
58/// static_assert(TypesAreDistinct<Us...>::value).
59///
60/// It is a compile-time error to instantiate when T is not present in Us, i.e.
61/// if is_one_of<T, Us...>::value is false.
62template <typename T, typename... Us> struct FirstIndexOfType;
63template <typename T, typename U, typename... Us>
64struct FirstIndexOfType<T, U, Us...>
65 : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
66template <typename T, typename... Us>
67struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
68
69/// Find the type at a given index in a list of types.
70///
71/// TypeAtIndex<I, Ts...> is the type at index I in Ts.
72template <size_t I, typename... Ts>
73using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
74
75namespace pointer_union_detail {
76 /// Determine the number of bits required to store integers with values < n.
77 /// This is ceil(log2(n)).
78 constexpr int bitsRequired(unsigned n) {
79 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
80 }
81
82 template <typename... Ts> constexpr int lowBitsAvailable() {
83 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
84 }
85
86 /// Find the first type in a list of types.
87 template <typename T, typename...> struct GetFirstType {
88 using type = T;
89 };
90
91 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
92 /// for the template arguments.
93 template <typename ...PTs> class PointerUnionUIntTraits {
94 public:
95 static inline void *getAsVoidPointer(void *P) { return P; }
96 static inline void *getFromVoidPointer(void *P) { return P; }
97 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
98 };
99
100 template <typename Derived, typename ValTy, int I, typename ...Types>
102
103 template <typename Derived, typename ValTy, int I>
104 class PointerUnionMembers<Derived, ValTy, I> {
105 protected:
106 ValTy Val;
108 PointerUnionMembers(ValTy Val) : Val(Val) {}
109
110 friend struct PointerLikeTypeTraits<Derived>;
111 };
112
113 template <typename Derived, typename ValTy, int I, typename Type,
114 typename ...Types>
115 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
116 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
117 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
118 public:
119 using Base::Base;
122 : Base(ValTy(const_cast<void *>(
123 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
124 I)) {}
125
126 using Base::operator=;
127 Derived &operator=(Type V) {
128 this->Val = ValTy(
130 I);
131 return static_cast<Derived &>(*this);
132 };
133 };
134}
135
136// This is a forward declaration of CastInfoPointerUnionImpl
137// Refer to its definition below for further details
138template <typename... PTs> struct CastInfoPointerUnionImpl;
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/// PointerUnion<int*, int*> Q; // compile time failure.
156template <typename... PTs>
159 PointerUnion<PTs...>,
160 PointerIntPair<
161 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
162 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
163 0, PTs...> {
164 static_assert(TypesAreDistinct<PTs...>::value,
165 "PointerUnion alternative types cannot be repeated");
166 // The first type is special because we want to directly cast a pointer to a
167 // default-initialized union to a pointer to the first type. But we don't
168 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
169 // because it's much more convenient to have a name for the whole pack. So
170 // split off the first type here.
171 using First = TypeAtIndex<0, PTs...>;
172 using Base = typename PointerUnion::PointerUnionMembers;
173
174 /// This is needed to give the CastInfo implementation below access
175 /// to protected members.
176 /// Refer to its definition for further details.
177 friend struct CastInfoPointerUnionImpl<PTs...>;
178
179public:
180 PointerUnion() = default;
181
182 PointerUnion(std::nullptr_t) : PointerUnion() {}
183 using Base::Base;
184
185 /// Test if the pointer held in the union is null, regardless of
186 /// which type it is.
187 bool isNull() const { return !this->Val.getPointer(); }
188
189 explicit operator bool() const { return !isNull(); }
190
191 // FIXME: Replace the uses of is(), get() and dyn_cast() with
192 // isa<T>, cast<T> and the wpi::dyn_cast<T>
193
194 /// Test if the Union currently holds the type matching T.
195 template <typename T> inline bool is() const { return isa<T>(*this); }
196
197 /// Returns the value of the specified pointer type.
198 ///
199 /// If the specified pointer type is incorrect, assert.
200 template <typename T> inline T get() const {
201 assert(isa<T>(*this) && "Invalid accessor called");
202 return cast<T>(*this);
203 }
204
205 /// Returns the current pointer if it is of the specified pointer type,
206 /// otherwise returns null.
207 template <typename T> inline T dyn_cast() const {
208 return wpi::dyn_cast_if_present<T>(*this);
209 }
210
211 /// If the union is set to the first pointer type get an address pointing to
212 /// it.
213 First const *getAddrOfPtr1() const {
214 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
215 }
216
217 /// If the union is set to the first pointer type get an address pointing to
218 /// it.
219 First *getAddrOfPtr1() {
220 assert(isa<First>(*this) && "Val is not the first pointer");
221 assert(
223 this->Val.getPointer() &&
224 "Can't get the address because PointerLikeTypeTraits changes the ptr");
225 return const_cast<First *>(
226 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
227 }
228
229 /// Assignment from nullptr which just clears the union.
230 const PointerUnion &operator=(std::nullptr_t) {
231 this->Val.initWithPointer(nullptr);
232 return *this;
233 }
234
235 /// Assignment from elements of the union.
236 using Base::operator=;
237
238 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
239 static inline PointerUnion getFromOpaqueValue(void *VP) {
240 PointerUnion V;
241 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
242 return V;
243 }
244};
245
246template <typename ...PTs>
248 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
249}
250
251template <typename ...PTs>
253 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
254}
255
256template <typename ...PTs>
258 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
259}
260
261/// We can't (at least, at this moment with C++14) declare CastInfo
262/// as a friend of PointerUnion like this:
263/// ```
264/// template<typename To>
265/// friend struct CastInfo<To, PointerUnion<PTs...>>;
266/// ```
267/// The compiler complains 'Partial specialization cannot be declared as a
268/// friend'.
269/// So we define this struct to be a bridge between CastInfo and
270/// PointerUnion.
271template <typename... PTs> struct CastInfoPointerUnionImpl {
272 using From = PointerUnion<PTs...>;
273
274 template <typename To> static inline bool isPossible(From &F) {
275 return F.Val.getInt() == FirstIndexOfType<To, PTs...>::value;
276 }
277
278 template <typename To> static To doCast(From &F) {
279 assert(isPossible<To>(F) && "cast to an incompatible type!");
280 return PointerLikeTypeTraits<To>::getFromVoidPointer(F.Val.getPointer());
281 }
282};
283
284// Specialization of CastInfo for PointerUnion
285template <typename To, typename... PTs>
286struct CastInfo<To, PointerUnion<PTs...>>
287 : public DefaultDoCastIfPossible<To, PointerUnion<PTs...>,
288 CastInfo<To, PointerUnion<PTs...>>> {
289 using From = PointerUnion<PTs...>;
291
292 static inline bool isPossible(From &f) {
293 return Impl::template isPossible<To>(f);
294 }
295
296 static To doCast(From &f) { return Impl::template doCast<To>(f); }
297
298 static inline To castFailed() { return To(); }
299};
300
301template <typename To, typename... PTs>
302struct CastInfo<To, const PointerUnion<PTs...>>
303 : public ConstStrippingForwardingCast<To, const PointerUnion<PTs...>,
304 CastInfo<To, PointerUnion<PTs...>>> {
305};
306
307// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
308// # low bits available = min(PT1bits,PT2bits)-1.
309template <typename ...PTs>
311 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
312 return P.getOpaqueValue();
313 }
314
315 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
317 }
318
319 // The number of bits available are the min of the pointer types minus the
320 // bits needed for the discriminator.
321 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
322 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
323};
324
325// Teach DenseMap how to use PointerUnions as keys.
326template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
327 using Union = PointerUnion<PTs...>;
328 using FirstInfo =
330
331 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
332
333 static inline Union getTombstoneKey() {
334 return Union(FirstInfo::getTombstoneKey());
335 }
336
337 static unsigned getHashValue(const Union &UnionVal) {
338 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
340 }
341
342 static bool isEqual(const Union &LHS, const Union &RHS) {
343 return LHS == RHS;
344 }
345};
346
347} // end namespace wpi
348
349#endif // WPIUTIL_WPI_POINTERUNION_H
This file defines DenseMapInfo traits for DenseMap.
This file defines the PointerIntPair class.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:163
static PointerUnion getFromOpaqueValue(void *VP)
Definition: PointerUnion.h:239
PointerUnion()=default
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwise returns null.
Definition: PointerUnion.h:207
void * getOpaqueValue() const
Definition: PointerUnion.h:238
First * getAddrOfPtr1()
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:219
PointerUnion(std::nullptr_t)
Definition: PointerUnion.h:182
First const * getAddrOfPtr1() const
If the union is set to the first pointer type get an address pointing to it.
Definition: PointerUnion.h:213
const PointerUnion & operator=(std::nullptr_t)
Assignment from nullptr which just clears the union.
Definition: PointerUnion.h:230
T get() const
Returns the value of the specified pointer type.
Definition: PointerUnion.h:200
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Definition: PointerUnion.h:187
bool is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:195
Provide PointerLikeTypeTraits for void* that is used by PointerUnion for the template arguments.
Definition: PointerUnion.h:93
static constexpr int NumLowBitsAvailable
Definition: PointerUnion.h:97
static void * getAsVoidPointer(void *P)
Definition: PointerUnion.h:95
static void * getFromVoidPointer(void *P)
Definition: PointerUnion.h:96
detail namespace with internal helper functions
Definition: xchar.h:20
type
Definition: core.h:556
static constexpr const unit_t< compound_unit< charge::coulomb, inverse< substance::mol > > > F(N_A *e)
Faraday constant.
constexpr int lowBitsAvailable()
Definition: PointerUnion.h:82
constexpr int bitsRequired(unsigned n)
Determine the number of bits required to store integers with values < n.
Definition: PointerUnion.h:78
Definition: ntcore_cpp.h:26
constexpr bool operator<(const unexpected< E > &lhs, const unexpected< E > &rhs)
Definition: expected:184
constexpr bool operator==(const unexpected< E > &lhs, const unexpected< E > &rhs)
Definition: expected:176
constexpr bool operator!=(const unexpected< E > &lhs, const unexpected< E > &rhs)
Definition: expected:180
static To doCast(From &f)
Definition: PointerUnion.h:296
static bool isPossible(From &f)
Definition: PointerUnion.h:292
static To castFailed()
Definition: PointerUnion.h:298
This struct provides a method for customizing the way a cast is performed.
Definition: Casting.h:476
We can't (at least, at this moment with C++14) declare CastInfo as a friend of PointerUnion like this...
Definition: PointerUnion.h:271
static To doCast(From &F)
Definition: PointerUnion.h:278
static bool isPossible(From &F)
Definition: PointerUnion.h:274
Provides a cast trait that strips const from types to make it easier to implement a const-version of ...
Definition: Casting.h:388
This cast trait just provides the default implementation of doCastIfPossible to make CastInfo special...
Definition: Casting.h:309
static Union getTombstoneKey()
Definition: PointerUnion.h:333
static unsigned getHashValue(const Union &UnionVal)
Definition: PointerUnion.h:337
static bool isEqual(const Union &LHS, const Union &RHS)
Definition: PointerUnion.h:342
static Union getEmptyKey()
Definition: PointerUnion.h:331
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:50
Find the first index where a type appears in a list of types.
Definition: PointerUnion.h:62
static PointerUnion< PTs... > getFromVoidPointer(void *P)
Definition: PointerUnion.h:315
static void * getAsVoidPointer(const PointerUnion< PTs... > &P)
Definition: PointerUnion.h:311
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
Definition: PointerLikeTypeTraits.h:25
Determine if all types in Ts are distinct.
Definition: PointerUnion.h:50
Definition: PointerUnion.h:35
Find the first type in a list of types.
Definition: PointerUnion.h:87
T type
Definition: PointerUnion.h:88
std::tuple_element_t< I, std::tuple< Ts... > > TypeAtIndex
Find the type at a given index in a list of types.
Definition: PointerUnion.h:73