LLVM 22.0.0git
TrailingObjects.h
Go to the documentation of this file.
1//===--- TrailingObjects.h - Variable-length classes ------------*- 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 header defines support for implementing classes that have
11/// some trailing object (or arrays of objects) appended to them. The
12/// main purpose is to make it obvious where this idiom is being used,
13/// and to make the usage more idiomatic and more difficult to get
14/// wrong.
15///
16/// The TrailingObject template abstracts away the reinterpret_cast,
17/// pointer arithmetic, and size calculations used for the allocation
18/// and access of appended arrays of objects, and takes care that they
19/// are all allocated at their required alignment. Additionally, it
20/// ensures that the base type is final -- deriving from a class that
21/// expects data appended immediately after it is typically not safe.
22///
23/// Users are expected to derive from this template, and provide
24/// numTrailingObjects implementations for each trailing type except
25/// the last, e.g. like this sample:
26///
27/// \code
28/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
29/// friend TrailingObjects;
30///
31/// unsigned NumInts, NumDoubles;
32/// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
33/// };
34/// \endcode
35///
36/// You can access the appended arrays via 'getTrailingObjects', and
37/// determine the size needed for allocation via
38/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
39///
40/// All the methods implemented by this class are intended for use
41/// by the implementation of the class, not as part of its interface
42/// (thus, private inheritance is suggested).
43///
44//===----------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
47#define LLVM_SUPPORT_TRAILINGOBJECTS_H
48
49#include "llvm/ADT/ArrayRef.h"
54#include <new>
55#include <type_traits>
56
57namespace llvm {
58
60
61template <typename... T>
62inline constexpr size_t MaxAlignment = std::max({alignof(T)...});
63
64/// The base class for TrailingObjects* classes.
66protected:
67 /// OverloadToken's purpose is to allow specifying function overloads
68 /// for different types, without actually taking the types as
69 /// parameters. (Necessary because member function templates cannot
70 /// be specialized, so overloads must be used instead of
71 /// specialization.)
72 template <typename T> struct OverloadToken {};
73};
74
75// Just a little helper for transforming a type pack into the same
76// number of a different type. e.g.:
77// ExtractSecondType<Foo..., int>::type
78template <typename Ty1, typename Ty2> struct ExtractSecondType {
79 typedef Ty2 type;
80};
81
82// TrailingObjectsImpl is somewhat complicated, because it is a
83// recursively inheriting template, in order to handle the template
84// varargs. Each level of inheritance picks off a single trailing type
85// then recurses on the rest. The "Align", "BaseTy", and
86// "TopTrailingObj" arguments are passed through unchanged through the
87// recursion. "PrevTy" is, at each level, the type handled by the
88// level right above it.
89
90template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
91 typename... MoreTys>
93 // The main template definition is never used -- the two
94 // specializations cover all possibilities.
95};
96
97template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
98 typename NextTy, typename... MoreTys>
99class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
100 MoreTys...>
101 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
102 MoreTys...> {
103
104 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
105 ParentType;
106
107 struct RequiresRealignment {
108 static const bool value = alignof(PrevTy) < alignof(NextTy);
109 };
110
111 static constexpr bool requiresRealignment() {
112 return RequiresRealignment::value;
113 }
114
115protected:
116 // Ensure the inherited getTrailingObjectsImpl is not hidden.
117 using ParentType::getTrailingObjectsImpl;
118
119 // These two functions are helper functions for
120 // TrailingObjects::getTrailingObjects. They recurse to the left --
121 // the result for each type in the list of trailing types depends on
122 // the result of calling the function on the type to the
123 // left. However, the function for the type to the left is
124 // implemented by a *subclass* of this class, so we invoke it via
125 // the TopTrailingObj, which is, via the
126 // curiously-recurring-template-pattern, the most-derived type in
127 // this recursion, and thus, contains all the overloads.
128 static const NextTy *
129 getTrailingObjectsImpl(const BaseTy *Obj,
131 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
133 TopTrailingObj::callNumTrailingObjects(
135
136 if (requiresRealignment())
137 return reinterpret_cast<const NextTy *>(
139 else
140 return reinterpret_cast<const NextTy *>(Ptr);
141 }
142
143 static NextTy *
146 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
148 TopTrailingObj::callNumTrailingObjects(
150
151 if (requiresRealignment())
152 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
153 else
154 return reinterpret_cast<NextTy *>(Ptr);
155 }
156
157 // Helper function for TrailingObjects::additionalSizeToAlloc: this
158 // function recurses to superclasses, each of which requires one
159 // fewer size_t argument, and adds its own size.
160 static constexpr size_t additionalSizeToAllocImpl(
161 size_t SizeSoFar, size_t Count1,
162 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
163 return ParentType::additionalSizeToAllocImpl(
164 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
165 : SizeSoFar) +
166 sizeof(NextTy) * Count1,
167 MoreCounts...);
168 }
169};
170
171// The base case of the TrailingObjectsImpl inheritance recursion,
172// when there's no more trailing types.
173template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
174class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
175 : public TrailingObjectsBase {
176protected:
177 // This is a dummy method, only here so the "using" doesn't fail --
178 // it will never be called, because this function recurses backwards
179 // up the inheritance chain to subclasses.
181
182 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
183 return SizeSoFar;
184 }
185};
186
187} // end namespace trailing_objects_internal
188
189// Finally, the main type defined in this file, the one intended for users...
190
191/// See the file comment for details on the usage of the
192/// TrailingObjects type.
193template <typename BaseTy, typename... TrailingTys>
196 trailing_objects_internal::MaxAlignment<TrailingTys...>, BaseTy,
197 TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...> {
198
199 template <int A, typename B, typename T, typename P, typename... M>
201
202 template <typename... Tys> class Foo {};
203
204 using ParentType = typename TrailingObjects::TrailingObjectsImpl;
205 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
206
207 using ParentType::getTrailingObjectsImpl;
208
209 template <bool Strict> static void verifyTrailingObjectsAssertions() {
210 // The static_assert for BaseTy must be in a function, and not at
211 // class-level because BaseTy isn't complete at class instantiation time,
212 // but will be by the time this function is instantiated.
213 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
214
215 // Verify that templated getTrailingObjects() is used only with multiple
216 // trailing types. Use getTrailingObjectsNonStrict() which does not check
217 // this.
218 static_assert(!Strict || sizeof...(TrailingTys) > 1,
219 "Use templated getTrailingObjects() only when there are "
220 "multiple trailing types");
221 }
222
223 // These two methods are the base of the recursion for this method.
224 static const BaseTy *
225 getTrailingObjectsImpl(const BaseTy *Obj,
226 TrailingObjectsBase::OverloadToken<BaseTy>) {
227 return Obj;
228 }
229
230 static BaseTy *
231 getTrailingObjectsImpl(BaseTy *Obj,
232 TrailingObjectsBase::OverloadToken<BaseTy>) {
233 return Obj;
234 }
235
236 // callNumTrailingObjects simply calls numTrailingObjects on the
237 // provided Obj -- except when the type being queried is BaseTy
238 // itself. There is always only one of the base object, so that case
239 // is handled here. (An additional benefit of indirecting through
240 // this function is that consumers only say "friend
241 // TrailingObjects", and thus, only this class itself can call the
242 // numTrailingObjects function.)
243 static size_t
244 callNumTrailingObjects(const BaseTy *Obj,
245 TrailingObjectsBase::OverloadToken<BaseTy>) {
246 return 1;
247 }
248
249 template <typename T>
250 static size_t callNumTrailingObjects(const BaseTy *Obj,
251 TrailingObjectsBase::OverloadToken<T>) {
252 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
253 }
254
255public:
256 // Make this (privately inherited) member public.
257#ifndef _MSC_VER
258 using ParentType::OverloadToken;
259#else
260 // An MSVC bug prevents the above from working, (last tested at CL version
261 // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
262 template <typename T>
263 using OverloadToken = typename ParentType::template OverloadToken<T>;
264#endif
265
266 /// Returns a pointer to the trailing object array of the given type
267 /// (which must be one of those specified in the class template). The
268 /// array may have zero or more elements in it.
269 template <typename T> const T *getTrailingObjects() const {
270 verifyTrailingObjectsAssertions<true>();
271 // Forwards to an impl function with overloads, since member
272 // function templates can't be specialized.
273 return this->getTrailingObjectsImpl(
274 static_cast<const BaseTy *>(this),
276 }
277
278 /// Returns a pointer to the trailing object array of the given type
279 /// (which must be one of those specified in the class template). The
280 /// array may have zero or more elements in it.
281 template <typename T> T *getTrailingObjects() {
282 return const_cast<T *>(
283 static_cast<const TrailingObjects *>(this)->getTrailingObjects<T>());
284 }
285
286 // getTrailingObjects() specialization for a single trailing type.
288 typename std::tuple_element_t<0, std::tuple<TrailingTys...>>;
289
291 static_assert(sizeof...(TrailingTys) == 1,
292 "Can use non-templated getTrailingObjects() only when there "
293 "is a single trailing type");
294 verifyTrailingObjectsAssertions<false>();
295 return this->getTrailingObjectsImpl(
296 static_cast<const BaseTy *>(this),
298 }
299
301 return const_cast<FirstTrailingType *>(
302 static_cast<const TrailingObjects *>(this)->getTrailingObjects());
303 }
304
305 // Functions that return the trailing objects as ArrayRefs.
306 template <typename T> MutableArrayRef<T> getTrailingObjects(size_t N) {
308 }
309
310 template <typename T> ArrayRef<T> getTrailingObjects(size_t N) const {
312 }
313
317
321
322 // Non-strict forms of templated `getTrailingObjects` that work with single
323 // trailing type.
324 template <typename T> const T *getTrailingObjectsNonStrict() const {
325 verifyTrailingObjectsAssertions<false>();
326 return this->getTrailingObjectsImpl(
327 static_cast<const BaseTy *>(this),
329 }
330
331 template <typename T> T *getTrailingObjectsNonStrict() {
332 return const_cast<T *>(static_cast<const TrailingObjects *>(this)
333 ->getTrailingObjectsNonStrict<T>());
334 }
335
336 template <typename T>
340
341 template <typename T>
345
346 /// Returns the size of the trailing data, if an object were
347 /// allocated with the given counts (The counts are in the same order
348 /// as the template arguments). This does not include the size of the
349 /// base object. The template arguments must be the same as those
350 /// used in the class; they are supplied here redundantly only so
351 /// that it's clear what the counts are counting in callers.
352 template <typename... Tys>
353 static constexpr std::enable_if_t<
354 std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
356 TrailingTys, size_t>::type... Counts) {
357 return ParentType::additionalSizeToAllocImpl(0, Counts...);
358 }
359
360 /// Returns the total size of an object if it were allocated with the
361 /// given trailing object counts. This is the same as
362 /// additionalSizeToAlloc, except it *does* include the size of the base
363 /// object.
364 template <typename... Tys>
365 static constexpr std::enable_if_t<
366 std::is_same_v<Foo<TrailingTys...>, Foo<Tys...>>, size_t>
368 TrailingTys, size_t>::type... Counts) {
369 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
370 }
371
372 TrailingObjects() = default;
377
378 /// A type where its ::with_counts template member has a ::type member
379 /// suitable for use as uninitialized storage for an object with the given
380 /// trailing object counts. The template arguments are similar to those
381 /// of additionalSizeToAlloc.
382 ///
383 /// Use with FixedSizeStorageOwner, e.g.:
384 ///
385 /// \code{.cpp}
386 ///
387 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
388 /// MyObj::FixedSizeStorageOwner
389 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
390 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
391 ///
392 /// \endcode
393 template <typename... Tys> struct FixedSizeStorage {
394 template <size_t... Counts> struct with_counts {
395 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
396 struct type {
397 alignas(BaseTy) char buffer[Size];
398 };
399 };
400 };
401
402 /// A type that acts as the owner for an object placed into fixed storage.
404 public:
405 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
407 assert(p && "FixedSizeStorageOwner owns null?");
408 p->~BaseTy();
409 }
410
411 BaseTy *get() { return p; }
412 const BaseTy *get() const { return p; }
413
414 private:
419
420 BaseTy *const p;
421 };
422};
423
424} // end namespace llvm
425
426#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define T
#define P(N)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:303
A type that acts as the owner for an object placed into fixed storage.
TrailingObjects & operator=(TrailingObjects &&)=delete
friend class trailing_objects_internal::TrailingObjectsImpl
const FirstTrailingType * getTrailingObjects() const
MutableArrayRef< T > getTrailingObjects(size_t N)
const T * getTrailingObjectsNonStrict() const
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Returns the total size of an object if it were allocated with the given trailing object counts.
TrailingObjects & operator=(const TrailingObjects &)=delete
FirstTrailingType * getTrailingObjects()
ArrayRef< FirstTrailingType > getTrailingObjects(size_t N) const
ArrayRef< T > getTrailingObjectsNonStrict(size_t N) const
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Returns the size of the trailing data, if an object were allocated with the given counts (The counts ...
TrailingObjects(TrailingObjects &&)=delete
MutableArrayRef< T > getTrailingObjectsNonStrict(size_t N)
T * getTrailingObjects()
Returns a pointer to the trailing object array of the given type (which must be one of those specifie...
MutableArrayRef< FirstTrailingType > getTrailingObjects(size_t N)
const T * getTrailingObjects() const
Returns a pointer to the trailing object array of the given type (which must be one of those specifie...
ArrayRef< T > getTrailingObjects(size_t N) const
typename std::tuple_element_t< 0, std::tuple< TrailingTys... > > FirstTrailingType
TrailingObjects(const TrailingObjects &)=delete
The base class for TrailingObjects* classes.
static const NextTy * getTrailingObjectsImpl(const BaseTy *Obj, TrailingObjectsBase::OverloadToken< NextTy >)
static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar, size_t Count1, typename ExtractSecondType< MoreTys, size_t >::type... MoreCounts)
static NextTy * getTrailingObjectsImpl(BaseTy *Obj, TrailingObjectsBase::OverloadToken< NextTy >)
This is an optimization pass for GlobalISel generic memory operations.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
uintptr_t alignAddr(const void *Addr, Align Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition Alignment.h:176
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr Align Of()
Allow constructions of constexpr Align from types.
Definition Alignment.h:94
A type where its with_counts template member has a type member suitable for use as uninitialized stor...
OverloadToken's purpose is to allow specifying function overloads for different types,...