[InstCombine] Signed saturation patterns
[llvm-core.git] / include / llvm / ADT / PointerUnion.h
blob98c905775a7769179a46a4fe8100e7c7815893a3
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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_POINTERUNION_H
15 #define LLVM_ADT_POINTERUNION_H
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>
24 namespace llvm {
26 template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
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;
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;
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;
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;
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
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;
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
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...>();
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);
103 template <typename Derived, typename ValTy, int I, typename ...Types>
104 class PointerUnionMembers;
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) {}
113 friend struct PointerLikeTypeTraits<Derived>;
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)) {}
129 using Base::operator=;
130 Derived &operator=(Type V) {
131 this->Val = ValTy(
132 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
134 return static_cast<Derived &>(*this);
139 /// A discriminated union of two or more pointer types, with the discriminator
140 /// in the low bit of the pointer.
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.
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;
171 public:
172 PointerUnion() = default;
174 PointerUnion(std::nullptr_t) : PointerUnion() {}
175 using Base::Base;
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(); }
181 explicit operator bool() const { return !isNull(); }
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;
191 /// Returns the value of the specified pointer type.
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());
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();
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();
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()));
225 /// Assignment from nullptr which just clears the union.
226 const PointerUnion &operator=(std::nullptr_t) {
227 this->Val.initWithPointer(nullptr);
228 return *this;
231 /// Assignment from elements of the union.
232 using Base::operator=;
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;
242 template <typename ...PTs>
243 bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
244 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
247 template <typename ...PTs>
248 bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
249 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
252 template <typename ...PTs>
253 bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
254 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
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();
265 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
266 return PointerUnion<PTs...>::getFromOpaqueValue(P);
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;
275 /// A pointer union of three pointer types. See documentation for PointerUnion
276 /// for usage.
277 template <typename PT1, typename PT2, typename PT3>
278 using PointerUnion3 = PointerUnion<PT1, PT2, PT3>;
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>
283 using PointerUnion4 = PointerUnion<PT1, PT2, PT3, PT4>;
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 =
289 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
291 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
293 static inline Union getTombstoneKey() {
294 return Union(FirstInfo::getTombstoneKey());
297 static unsigned getHashValue(const Union &UnionVal) {
298 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
299 return DenseMapInfo<intptr_t>::getHashValue(key);
302 static bool isEqual(const Union &LHS, const Union &RHS) {
303 return LHS == RHS;
307 } // end namespace llvm
309 #endif // LLVM_ADT_POINTERUNION_H