layout.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // MOTIVATION AND TUTORIAL
  16. //
  17. // If you want to put in a single heap allocation N doubles followed by M ints,
  18. // it's easy if N and M are known at compile time.
  19. //
  20. // struct S {
  21. // double a[N];
  22. // int b[M];
  23. // };
  24. //
  25. // S* p = new S;
  26. //
  27. // But what if N and M are known only in run time? Class template Layout to the
  28. // rescue! It's a portable generalization of the technique known as struct hack.
  29. //
  30. // // This object will tell us everything we need to know about the memory
  31. // // layout of double[N] followed by int[M]. It's structurally identical to
  32. // // size_t[2] that stores N and M. It's very cheap to create.
  33. // const Layout<double, int> layout(N, M);
  34. //
  35. // // Allocate enough memory for both arrays. `AllocSize()` tells us how much
  36. // // memory is needed. We are free to use any allocation function we want as
  37. // // long as it returns aligned memory.
  38. // std::unique_ptr<unsigned char[]> p(new unsigned char[layout.AllocSize()]);
  39. //
  40. // // Obtain the pointer to the array of doubles.
  41. // // Equivalent to `reinterpret_cast<double*>(p.get())`.
  42. // //
  43. // // We could have written layout.Pointer<0>(p) instead. If all the types are
  44. // // unique you can use either form, but if some types are repeated you must
  45. // // use the index form.
  46. // double* a = layout.Pointer<double>(p.get());
  47. //
  48. // // Obtain the pointer to the array of ints.
  49. // // Equivalent to `reinterpret_cast<int*>(p.get() + N * 8)`.
  50. // int* b = layout.Pointer<int>(p);
  51. //
  52. // If we are unable to specify sizes of all fields, we can pass as many sizes as
  53. // we can to `Partial()`. In return, it'll allow us to access the fields whose
  54. // locations and sizes can be computed from the provided information.
  55. // `Partial()` comes in handy when the array sizes are embedded into the
  56. // allocation.
  57. //
  58. // // size_t[1] containing N, size_t[1] containing M, double[N], int[M].
  59. // using L = Layout<size_t, size_t, double, int>;
  60. //
  61. // unsigned char* Allocate(size_t n, size_t m) {
  62. // const L layout(1, 1, n, m);
  63. // unsigned char* p = new unsigned char[layout.AllocSize()];
  64. // *layout.Pointer<0>(p) = n;
  65. // *layout.Pointer<1>(p) = m;
  66. // return p;
  67. // }
  68. //
  69. // void Use(unsigned char* p) {
  70. // // First, extract N and M.
  71. // // Specify that the first array has only one element. Using `prefix` we
  72. // // can access the first two arrays but not more.
  73. // constexpr auto prefix = L::Partial(1);
  74. // size_t n = *prefix.Pointer<0>(p);
  75. // size_t m = *prefix.Pointer<1>(p);
  76. //
  77. // // Now we can get pointers to the payload.
  78. // const L layout(1, 1, n, m);
  79. // double* a = layout.Pointer<double>(p);
  80. // int* b = layout.Pointer<int>(p);
  81. // }
  82. //
  83. // The layout we used above combines fixed-size with dynamically-sized fields.
  84. // This is quite common. Layout is optimized for this use case and generates
  85. // optimal code. All computations that can be performed at compile time are
  86. // indeed performed at compile time.
  87. //
  88. // Efficiency tip: The order of fields matters. In `Layout<T1, ..., TN>` try to
  89. // ensure that `alignof(T1) >= ... >= alignof(TN)`. This way you'll have no
  90. // padding in between arrays.
  91. //
  92. // You can manually override the alignment of an array by wrapping the type in
  93. // `Aligned<T, N>`. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
  94. // and behavior as `Layout<..., T, ...>` except that the first element of the
  95. // array of `T` is aligned to `N` (the rest of the elements follow without
  96. // padding). `N` cannot be less than `alignof(T)`.
  97. //
  98. // `AllocSize()` and `Pointer()` are the most basic methods for dealing with
  99. // memory layouts. Check out the reference or code below to discover more.
  100. //
  101. // EXAMPLE
  102. //
  103. // // Immutable move-only string with sizeof equal to sizeof(void*). The
  104. // // string size and the characters are kept in the same heap allocation.
  105. // class CompactString {
  106. // public:
  107. // CompactString(const char* s = "") {
  108. // const size_t size = strlen(s);
  109. // // size_t[1] followed by char[size + 1].
  110. // const L layout(1, size + 1);
  111. // p_.reset(new unsigned char[layout.AllocSize()]);
  112. // // If running under ASAN, mark the padding bytes, if any, to catch
  113. // // memory errors.
  114. // layout.PoisonPadding(p_.get());
  115. // // Store the size in the allocation.
  116. // *layout.Pointer<size_t>(p_.get()) = size;
  117. // // Store the characters in the allocation.
  118. // memcpy(layout.Pointer<char>(p_.get()), s, size + 1);
  119. // }
  120. //
  121. // size_t size() const {
  122. // // Equivalent to reinterpret_cast<size_t&>(*p).
  123. // return *L::Partial().Pointer<size_t>(p_.get());
  124. // }
  125. //
  126. // const char* c_str() const {
  127. // // Equivalent to reinterpret_cast<char*>(p.get() + sizeof(size_t)).
  128. // // The argument in Partial(1) specifies that we have size_t[1] in front
  129. // // of the characters.
  130. // return L::Partial(1).Pointer<char>(p_.get());
  131. // }
  132. //
  133. // private:
  134. // // Our heap allocation contains a size_t followed by an array of chars.
  135. // using L = Layout<size_t, char>;
  136. // std::unique_ptr<unsigned char[]> p_;
  137. // };
  138. //
  139. // int main() {
  140. // CompactString s = "hello";
  141. // assert(s.size() == 5);
  142. // assert(strcmp(s.c_str(), "hello") == 0);
  143. // }
  144. //
  145. // DOCUMENTATION
  146. //
  147. // The interface exported by this file consists of:
  148. // - class `Layout<>` and its public members.
  149. // - The public members of class `internal_layout::LayoutImpl<>`. That class
  150. // isn't intended to be used directly, and its name and template parameter
  151. // list are internal implementation details, but the class itself provides
  152. // most of the functionality in this file. See comments on its members for
  153. // detailed documentation.
  154. //
  155. // `Layout<T1,... Tn>::Partial(count1,..., countm)` (where `m` <= `n`) returns a
  156. // `LayoutImpl<>` object. `Layout<T1,..., Tn> layout(count1,..., countn)`
  157. // creates a `Layout` object, which exposes the same functionality by inheriting
  158. // from `LayoutImpl<>`.
  159. #ifndef ABSL_CONTAINER_INTERNAL_LAYOUT_H_
  160. #define ABSL_CONTAINER_INTERNAL_LAYOUT_H_
  161. #include <assert.h>
  162. #include <stddef.h>
  163. #include <stdint.h>
  164. #include <ostream>
  165. #include <string>
  166. #include <tuple>
  167. #include <type_traits>
  168. #include <typeinfo>
  169. #include <utility>
  170. #include "absl/base/config.h"
  171. #include "absl/meta/type_traits.h"
  172. #include "absl/strings/str_cat.h"
  173. #include "absl/types/span.h"
  174. #include "absl/utility/utility.h"
  175. #ifdef ABSL_HAVE_ADDRESS_SANITIZER
  176. #include <sanitizer/asan_interface.h>
  177. #endif
  178. #if defined(__GXX_RTTI)
  179. #define ABSL_INTERNAL_HAS_CXA_DEMANGLE
  180. #endif
  181. #ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE
  182. #include <cxxabi.h>
  183. #endif
  184. namespace absl {
  185. ABSL_NAMESPACE_BEGIN
  186. namespace container_internal {
  187. // A type wrapper that instructs `Layout` to use the specific alignment for the
  188. // array. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
  189. // and behavior as `Layout<..., T, ...>` except that the first element of the
  190. // array of `T` is aligned to `N` (the rest of the elements follow without
  191. // padding).
  192. //
  193. // Requires: `N >= alignof(T)` and `N` is a power of 2.
  194. template <class T, size_t N>
  195. struct Aligned;
  196. namespace internal_layout {
  197. template <class T>
  198. struct NotAligned {};
  199. template <class T, size_t N>
  200. struct NotAligned<const Aligned<T, N>> {
  201. static_assert(sizeof(T) == 0, "Aligned<T, N> cannot be const-qualified");
  202. };
  203. template <size_t>
  204. using IntToSize = size_t;
  205. template <class>
  206. using TypeToSize = size_t;
  207. template <class T>
  208. struct Type : NotAligned<T> {
  209. using type = T;
  210. };
  211. template <class T, size_t N>
  212. struct Type<Aligned<T, N>> {
  213. using type = T;
  214. };
  215. template <class T>
  216. struct SizeOf : NotAligned<T>, std::integral_constant<size_t, sizeof(T)> {};
  217. template <class T, size_t N>
  218. struct SizeOf<Aligned<T, N>> : std::integral_constant<size_t, sizeof(T)> {};
  219. // Note: workaround for https://gcc.gnu.org/PR88115
  220. template <class T>
  221. struct AlignOf : NotAligned<T> {
  222. static constexpr size_t value = alignof(T);
  223. };
  224. template <class T, size_t N>
  225. struct AlignOf<Aligned<T, N>> {
  226. static_assert(N % alignof(T) == 0,
  227. "Custom alignment can't be lower than the type's alignment");
  228. static constexpr size_t value = N;
  229. };
  230. // Does `Ts...` contain `T`?
  231. template <class T, class... Ts>
  232. using Contains = absl::disjunction<std::is_same<T, Ts>...>;
  233. template <class From, class To>
  234. using CopyConst =
  235. typename std::conditional<std::is_const<From>::value, const To, To>::type;
  236. // Note: We're not qualifying this with absl:: because it doesn't compile under
  237. // MSVC.
  238. template <class T>
  239. using SliceType = Span<T>;
  240. // This namespace contains no types. It prevents functions defined in it from
  241. // being found by ADL.
  242. namespace adl_barrier {
  243. template <class Needle, class... Ts>
  244. constexpr size_t Find(Needle, Needle, Ts...) {
  245. static_assert(!Contains<Needle, Ts...>(), "Duplicate element type");
  246. return 0;
  247. }
  248. template <class Needle, class T, class... Ts>
  249. constexpr size_t Find(Needle, T, Ts...) {
  250. return adl_barrier::Find(Needle(), Ts()...) + 1;
  251. }
  252. constexpr bool IsPow2(size_t n) { return !(n & (n - 1)); }
  253. // Returns `q * m` for the smallest `q` such that `q * m >= n`.
  254. // Requires: `m` is a power of two. It's enforced by IsLegalElementType below.
  255. constexpr size_t Align(size_t n, size_t m) { return (n + m - 1) & ~(m - 1); }
  256. constexpr size_t Min(size_t a, size_t b) { return b < a ? b : a; }
  257. constexpr size_t Max(size_t a) { return a; }
  258. template <class... Ts>
  259. constexpr size_t Max(size_t a, size_t b, Ts... rest) {
  260. return adl_barrier::Max(b < a ? a : b, rest...);
  261. }
  262. template <class T>
  263. std::string TypeName() {
  264. std::string out;
  265. int status = 0;
  266. char* demangled = nullptr;
  267. #ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE
  268. demangled = abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);
  269. #endif
  270. if (status == 0 && demangled != nullptr) { // Demangling succeeded.
  271. absl::StrAppend(&out, "<", demangled, ">");
  272. free(demangled);
  273. } else {
  274. #if defined(__GXX_RTTI) || defined(_CPPRTTI)
  275. absl::StrAppend(&out, "<", typeid(T).name(), ">");
  276. #endif
  277. }
  278. return out;
  279. }
  280. } // namespace adl_barrier
  281. template <bool C>
  282. using EnableIf = typename std::enable_if<C, int>::type;
  283. // Can `T` be a template argument of `Layout`?
  284. template <class T>
  285. using IsLegalElementType = std::integral_constant<
  286. bool, !std::is_reference<T>::value && !std::is_volatile<T>::value &&
  287. !std::is_reference<typename Type<T>::type>::value &&
  288. !std::is_volatile<typename Type<T>::type>::value &&
  289. adl_barrier::IsPow2(AlignOf<T>::value)>;
  290. template <class Elements, class SizeSeq, class OffsetSeq>
  291. class LayoutImpl;
  292. // Public base class of `Layout` and the result type of `Layout::Partial()`.
  293. //
  294. // `Elements...` contains all template arguments of `Layout` that created this
  295. // instance.
  296. //
  297. // `SizeSeq...` is `[0, NumSizes)` where `NumSizes` is the number of arguments
  298. // passed to `Layout::Partial()` or `Layout::Layout()`.
  299. //
  300. // `OffsetSeq...` is `[0, NumOffsets)` where `NumOffsets` is
  301. // `Min(sizeof...(Elements), NumSizes + 1)` (the number of arrays for which we
  302. // can compute offsets).
  303. template <class... Elements, size_t... SizeSeq, size_t... OffsetSeq>
  304. class LayoutImpl<std::tuple<Elements...>, absl::index_sequence<SizeSeq...>,
  305. absl::index_sequence<OffsetSeq...>> {
  306. private:
  307. static_assert(sizeof...(Elements) > 0, "At least one field is required");
  308. static_assert(absl::conjunction<IsLegalElementType<Elements>...>::value,
  309. "Invalid element type (see IsLegalElementType)");
  310. enum {
  311. NumTypes = sizeof...(Elements),
  312. NumSizes = sizeof...(SizeSeq),
  313. NumOffsets = sizeof...(OffsetSeq),
  314. };
  315. // These are guaranteed by `Layout`.
  316. static_assert(NumOffsets == adl_barrier::Min(NumTypes, NumSizes + 1),
  317. "Internal error");
  318. static_assert(NumTypes > 0, "Internal error");
  319. // Returns the index of `T` in `Elements...`. Results in a compilation error
  320. // if `Elements...` doesn't contain exactly one instance of `T`.
  321. template <class T>
  322. static constexpr size_t ElementIndex() {
  323. static_assert(Contains<Type<T>, Type<typename Type<Elements>::type>...>(),
  324. "Type not found");
  325. return adl_barrier::Find(Type<T>(),
  326. Type<typename Type<Elements>::type>()...);
  327. }
  328. template <size_t N>
  329. using ElementAlignment =
  330. AlignOf<typename std::tuple_element<N, std::tuple<Elements...>>::type>;
  331. public:
  332. // Element types of all arrays packed in a tuple.
  333. using ElementTypes = std::tuple<typename Type<Elements>::type...>;
  334. // Element type of the Nth array.
  335. template <size_t N>
  336. using ElementType = typename std::tuple_element<N, ElementTypes>::type;
  337. constexpr explicit LayoutImpl(IntToSize<SizeSeq>... sizes)
  338. : size_{sizes...} {}
  339. // Alignment of the layout, equal to the strictest alignment of all elements.
  340. // All pointers passed to the methods of layout must be aligned to this value.
  341. static constexpr size_t Alignment() {
  342. return adl_barrier::Max(AlignOf<Elements>::value...);
  343. }
  344. // Offset in bytes of the Nth array.
  345. //
  346. // // int[3], 4 bytes of padding, double[4].
  347. // Layout<int, double> x(3, 4);
  348. // assert(x.Offset<0>() == 0); // The ints starts from 0.
  349. // assert(x.Offset<1>() == 16); // The doubles starts from 16.
  350. //
  351. // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
  352. template <size_t N, EnableIf<N == 0> = 0>
  353. constexpr size_t Offset() const {
  354. return 0;
  355. }
  356. template <size_t N, EnableIf<N != 0> = 0>
  357. constexpr size_t Offset() const {
  358. static_assert(N < NumOffsets, "Index out of bounds");
  359. return adl_barrier::Align(
  360. Offset<N - 1>() + SizeOf<ElementType<N - 1>>() * size_[N - 1],
  361. ElementAlignment<N>::value);
  362. }
  363. // Offset in bytes of the array with the specified element type. There must
  364. // be exactly one such array and its zero-based index must be at most
  365. // `NumSizes`.
  366. //
  367. // // int[3], 4 bytes of padding, double[4].
  368. // Layout<int, double> x(3, 4);
  369. // assert(x.Offset<int>() == 0); // The ints starts from 0.
  370. // assert(x.Offset<double>() == 16); // The doubles starts from 16.
  371. template <class T>
  372. constexpr size_t Offset() const {
  373. return Offset<ElementIndex<T>()>();
  374. }
  375. // Offsets in bytes of all arrays for which the offsets are known.
  376. constexpr std::array<size_t, NumOffsets> Offsets() const {
  377. return {{Offset<OffsetSeq>()...}};
  378. }
  379. // The number of elements in the Nth array. This is the Nth argument of
  380. // `Layout::Partial()` or `Layout::Layout()` (zero-based).
  381. //
  382. // // int[3], 4 bytes of padding, double[4].
  383. // Layout<int, double> x(3, 4);
  384. // assert(x.Size<0>() == 3);
  385. // assert(x.Size<1>() == 4);
  386. //
  387. // Requires: `N < NumSizes`.
  388. template <size_t N>
  389. constexpr size_t Size() const {
  390. static_assert(N < NumSizes, "Index out of bounds");
  391. return size_[N];
  392. }
  393. // The number of elements in the array with the specified element type.
  394. // There must be exactly one such array and its zero-based index must be
  395. // at most `NumSizes`.
  396. //
  397. // // int[3], 4 bytes of padding, double[4].
  398. // Layout<int, double> x(3, 4);
  399. // assert(x.Size<int>() == 3);
  400. // assert(x.Size<double>() == 4);
  401. template <class T>
  402. constexpr size_t Size() const {
  403. return Size<ElementIndex<T>()>();
  404. }
  405. // The number of elements of all arrays for which they are known.
  406. constexpr std::array<size_t, NumSizes> Sizes() const {
  407. return {{Size<SizeSeq>()...}};
  408. }
  409. // Pointer to the beginning of the Nth array.
  410. //
  411. // `Char` must be `[const] [signed|unsigned] char`.
  412. //
  413. // // int[3], 4 bytes of padding, double[4].
  414. // Layout<int, double> x(3, 4);
  415. // unsigned char* p = new unsigned char[x.AllocSize()];
  416. // int* ints = x.Pointer<0>(p);
  417. // double* doubles = x.Pointer<1>(p);
  418. //
  419. // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
  420. // Requires: `p` is aligned to `Alignment()`.
  421. template <size_t N, class Char>
  422. CopyConst<Char, ElementType<N>>* Pointer(Char* p) const {
  423. using C = typename std::remove_const<Char>::type;
  424. static_assert(
  425. std::is_same<C, char>() || std::is_same<C, unsigned char>() ||
  426. std::is_same<C, signed char>(),
  427. "The argument must be a pointer to [const] [signed|unsigned] char");
  428. constexpr size_t alignment = Alignment();
  429. (void)alignment;
  430. assert(reinterpret_cast<uintptr_t>(p) % alignment == 0);
  431. return reinterpret_cast<CopyConst<Char, ElementType<N>>*>(p + Offset<N>());
  432. }
  433. // Pointer to the beginning of the array with the specified element type.
  434. // There must be exactly one such array and its zero-based index must be at
  435. // most `NumSizes`.
  436. //
  437. // `Char` must be `[const] [signed|unsigned] char`.
  438. //
  439. // // int[3], 4 bytes of padding, double[4].
  440. // Layout<int, double> x(3, 4);
  441. // unsigned char* p = new unsigned char[x.AllocSize()];
  442. // int* ints = x.Pointer<int>(p);
  443. // double* doubles = x.Pointer<double>(p);
  444. //
  445. // Requires: `p` is aligned to `Alignment()`.
  446. template <class T, class Char>
  447. CopyConst<Char, T>* Pointer(Char* p) const {
  448. return Pointer<ElementIndex<T>()>(p);
  449. }
  450. // Pointers to all arrays for which pointers are known.
  451. //
  452. // `Char` must be `[const] [signed|unsigned] char`.
  453. //
  454. // // int[3], 4 bytes of padding, double[4].
  455. // Layout<int, double> x(3, 4);
  456. // unsigned char* p = new unsigned char[x.AllocSize()];
  457. //
  458. // int* ints;
  459. // double* doubles;
  460. // std::tie(ints, doubles) = x.Pointers(p);
  461. //
  462. // Requires: `p` is aligned to `Alignment()`.
  463. //
  464. // Note: We're not using ElementType alias here because it does not compile
  465. // under MSVC.
  466. template <class Char>
  467. std::tuple<CopyConst<
  468. Char, typename std::tuple_element<OffsetSeq, ElementTypes>::type>*...>
  469. Pointers(Char* p) const {
  470. return std::tuple<CopyConst<Char, ElementType<OffsetSeq>>*...>(
  471. Pointer<OffsetSeq>(p)...);
  472. }
  473. // The Nth array.
  474. //
  475. // `Char` must be `[const] [signed|unsigned] char`.
  476. //
  477. // // int[3], 4 bytes of padding, double[4].
  478. // Layout<int, double> x(3, 4);
  479. // unsigned char* p = new unsigned char[x.AllocSize()];
  480. // Span<int> ints = x.Slice<0>(p);
  481. // Span<double> doubles = x.Slice<1>(p);
  482. //
  483. // Requires: `N < NumSizes`.
  484. // Requires: `p` is aligned to `Alignment()`.
  485. template <size_t N, class Char>
  486. SliceType<CopyConst<Char, ElementType<N>>> Slice(Char* p) const {
  487. return SliceType<CopyConst<Char, ElementType<N>>>(Pointer<N>(p), Size<N>());
  488. }
  489. // The array with the specified element type. There must be exactly one
  490. // such array and its zero-based index must be less than `NumSizes`.
  491. //
  492. // `Char` must be `[const] [signed|unsigned] char`.
  493. //
  494. // // int[3], 4 bytes of padding, double[4].
  495. // Layout<int, double> x(3, 4);
  496. // unsigned char* p = new unsigned char[x.AllocSize()];
  497. // Span<int> ints = x.Slice<int>(p);
  498. // Span<double> doubles = x.Slice<double>(p);
  499. //
  500. // Requires: `p` is aligned to `Alignment()`.
  501. template <class T, class Char>
  502. SliceType<CopyConst<Char, T>> Slice(Char* p) const {
  503. return Slice<ElementIndex<T>()>(p);
  504. }
  505. // All arrays with known sizes.
  506. //
  507. // `Char` must be `[const] [signed|unsigned] char`.
  508. //
  509. // // int[3], 4 bytes of padding, double[4].
  510. // Layout<int, double> x(3, 4);
  511. // unsigned char* p = new unsigned char[x.AllocSize()];
  512. //
  513. // Span<int> ints;
  514. // Span<double> doubles;
  515. // std::tie(ints, doubles) = x.Slices(p);
  516. //
  517. // Requires: `p` is aligned to `Alignment()`.
  518. //
  519. // Note: We're not using ElementType alias here because it does not compile
  520. // under MSVC.
  521. template <class Char>
  522. std::tuple<SliceType<CopyConst<
  523. Char, typename std::tuple_element<SizeSeq, ElementTypes>::type>>...>
  524. Slices(Char* p) const {
  525. // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63875 (fixed
  526. // in 6.1).
  527. (void)p;
  528. return std::tuple<SliceType<CopyConst<Char, ElementType<SizeSeq>>>...>(
  529. Slice<SizeSeq>(p)...);
  530. }
  531. // The size of the allocation that fits all arrays.
  532. //
  533. // // int[3], 4 bytes of padding, double[4].
  534. // Layout<int, double> x(3, 4);
  535. // unsigned char* p = new unsigned char[x.AllocSize()]; // 48 bytes
  536. //
  537. // Requires: `NumSizes == sizeof...(Ts)`.
  538. constexpr size_t AllocSize() const {
  539. static_assert(NumTypes == NumSizes, "You must specify sizes of all fields");
  540. return Offset<NumTypes - 1>() +
  541. SizeOf<ElementType<NumTypes - 1>>() * size_[NumTypes - 1];
  542. }
  543. // If built with --config=asan, poisons padding bytes (if any) in the
  544. // allocation. The pointer must point to a memory block at least
  545. // `AllocSize()` bytes in length.
  546. //
  547. // `Char` must be `[const] [signed|unsigned] char`.
  548. //
  549. // Requires: `p` is aligned to `Alignment()`.
  550. template <class Char, size_t N = NumOffsets - 1, EnableIf<N == 0> = 0>
  551. void PoisonPadding(const Char* p) const {
  552. Pointer<0>(p); // verify the requirements on `Char` and `p`
  553. }
  554. template <class Char, size_t N = NumOffsets - 1, EnableIf<N != 0> = 0>
  555. void PoisonPadding(const Char* p) const {
  556. static_assert(N < NumOffsets, "Index out of bounds");
  557. (void)p;
  558. #ifdef ABSL_HAVE_ADDRESS_SANITIZER
  559. PoisonPadding<Char, N - 1>(p);
  560. // The `if` is an optimization. It doesn't affect the observable behaviour.
  561. if (ElementAlignment<N - 1>::value % ElementAlignment<N>::value) {
  562. size_t start =
  563. Offset<N - 1>() + SizeOf<ElementType<N - 1>>() * size_[N - 1];
  564. ASAN_POISON_MEMORY_REGION(p + start, Offset<N>() - start);
  565. }
  566. #endif
  567. }
  568. // Human-readable description of the memory layout. Useful for debugging.
  569. // Slow.
  570. //
  571. // // char[5], 3 bytes of padding, int[3], 4 bytes of padding, followed
  572. // // by an unknown number of doubles.
  573. // auto x = Layout<char, int, double>::Partial(5, 3);
  574. // assert(x.DebugString() ==
  575. // "@0<char>(1)[5]; @8<int>(4)[3]; @24<double>(8)");
  576. //
  577. // Each field is in the following format: @offset<type>(sizeof)[size] (<type>
  578. // may be missing depending on the target platform). For example,
  579. // @8<int>(4)[3] means that at offset 8 we have an array of ints, where each
  580. // int is 4 bytes, and we have 3 of those ints. The size of the last field may
  581. // be missing (as in the example above). Only fields with known offsets are
  582. // described. Type names may differ across platforms: one compiler might
  583. // produce "unsigned*" where another produces "unsigned int *".
  584. std::string DebugString() const {
  585. const auto offsets = Offsets();
  586. const size_t sizes[] = {SizeOf<ElementType<OffsetSeq>>()...};
  587. const std::string types[] = {
  588. adl_barrier::TypeName<ElementType<OffsetSeq>>()...};
  589. std::string res = absl::StrCat("@0", types[0], "(", sizes[0], ")");
  590. for (size_t i = 0; i != NumOffsets - 1; ++i) {
  591. absl::StrAppend(&res, "[", size_[i], "]; @", offsets[i + 1], types[i + 1],
  592. "(", sizes[i + 1], ")");
  593. }
  594. // NumSizes is a constant that may be zero. Some compilers cannot see that
  595. // inside the if statement "size_[NumSizes - 1]" must be valid.
  596. int last = static_cast<int>(NumSizes) - 1;
  597. if (NumTypes == NumSizes && last >= 0) {
  598. absl::StrAppend(&res, "[", size_[last], "]");
  599. }
  600. return res;
  601. }
  602. private:
  603. // Arguments of `Layout::Partial()` or `Layout::Layout()`.
  604. size_t size_[NumSizes > 0 ? NumSizes : 1];
  605. };
  606. template <size_t NumSizes, class... Ts>
  607. using LayoutType = LayoutImpl<
  608. std::tuple<Ts...>, absl::make_index_sequence<NumSizes>,
  609. absl::make_index_sequence<adl_barrier::Min(sizeof...(Ts), NumSizes + 1)>>;
  610. } // namespace internal_layout
  611. // Descriptor of arrays of various types and sizes laid out in memory one after
  612. // another. See the top of the file for documentation.
  613. //
  614. // Check out the public API of internal_layout::LayoutImpl above. The type is
  615. // internal to the library but its methods are public, and they are inherited
  616. // by `Layout`.
  617. template <class... Ts>
  618. class Layout : public internal_layout::LayoutType<sizeof...(Ts), Ts...> {
  619. public:
  620. static_assert(sizeof...(Ts) > 0, "At least one field is required");
  621. static_assert(
  622. absl::conjunction<internal_layout::IsLegalElementType<Ts>...>::value,
  623. "Invalid element type (see IsLegalElementType)");
  624. // The result type of `Partial()` with `NumSizes` arguments.
  625. template <size_t NumSizes>
  626. using PartialType = internal_layout::LayoutType<NumSizes, Ts...>;
  627. // `Layout` knows the element types of the arrays we want to lay out in
  628. // memory but not the number of elements in each array.
  629. // `Partial(size1, ..., sizeN)` allows us to specify the latter. The
  630. // resulting immutable object can be used to obtain pointers to the
  631. // individual arrays.
  632. //
  633. // It's allowed to pass fewer array sizes than the number of arrays. E.g.,
  634. // if all you need is to the offset of the second array, you only need to
  635. // pass one argument -- the number of elements in the first array.
  636. //
  637. // // int[3] followed by 4 bytes of padding and an unknown number of
  638. // // doubles.
  639. // auto x = Layout<int, double>::Partial(3);
  640. // // doubles start at byte 16.
  641. // assert(x.Offset<1>() == 16);
  642. //
  643. // If you know the number of elements in all arrays, you can still call
  644. // `Partial()` but it's more convenient to use the constructor of `Layout`.
  645. //
  646. // Layout<int, double> x(3, 5);
  647. //
  648. // Note: The sizes of the arrays must be specified in number of elements,
  649. // not in bytes.
  650. //
  651. // Requires: `sizeof...(Sizes) <= sizeof...(Ts)`.
  652. // Requires: all arguments are convertible to `size_t`.
  653. template <class... Sizes>
  654. static constexpr PartialType<sizeof...(Sizes)> Partial(Sizes&&... sizes) {
  655. static_assert(sizeof...(Sizes) <= sizeof...(Ts), "");
  656. return PartialType<sizeof...(Sizes)>(absl::forward<Sizes>(sizes)...);
  657. }
  658. // Creates a layout with the sizes of all arrays specified. If you know
  659. // only the sizes of the first N arrays (where N can be zero), you can use
  660. // `Partial()` defined above. The constructor is essentially equivalent to
  661. // calling `Partial()` and passing in all array sizes; the constructor is
  662. // provided as a convenient abbreviation.
  663. //
  664. // Note: The sizes of the arrays must be specified in number of elements,
  665. // not in bytes.
  666. constexpr explicit Layout(internal_layout::TypeToSize<Ts>... sizes)
  667. : internal_layout::LayoutType<sizeof...(Ts), Ts...>(sizes...) {}
  668. };
  669. } // namespace container_internal
  670. ABSL_NAMESPACE_END
  671. } // namespace absl
  672. #endif // ABSL_CONTAINER_INTERNAL_LAYOUT_H_