1 //===----------------------------------------------------------------------===//
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 #ifndef _LIBCPP___TYPE_TRAITS_DATASIZEOF_H
10 #define _LIBCPP___TYPE_TRAITS_DATASIZEOF_H
11 
12 #include <__config>
13 #include <__type_traits/is_class.h>
14 #include <__type_traits/is_final.h>
15 #include <cstddef>
16 
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 #  pragma GCC system_header
19 #endif
20 
21 // This trait provides the size of a type excluding any tail padding.
22 //
23 // It is useful in contexts where performing an operation using the full size of the class (including padding) may
24 // have unintended side effects, such as overwriting a derived class' member when writing the tail padding of a class
25 // through a pointer-to-base.
26 
27 _LIBCPP_BEGIN_NAMESPACE_STD
28 
29 template <class _Tp>
30 struct __libcpp_datasizeof {
31 #if __has_extension(datasizeof)
32   static const size_t value = __datasizeof(_Tp);
33 #else
34 // NOLINTNEXTLINE(readability-redundant-preprocessor) This is https://llvm.org/PR64825
35 #  if __has_cpp_attribute(__no_unique_address__)
36   template <class = char>
37   struct _FirstPaddingByte {
38     [[__no_unique_address__]] _Tp __v_;
39     char __first_padding_byte_;
40   };
41 #  else
42   template <bool = __libcpp_is_final<_Tp>::value || !is_class<_Tp>::value>
43   struct _FirstPaddingByte : _Tp {
44     char __first_padding_byte_;
45   };
46 
47   template <>
48   struct _FirstPaddingByte<true> {
49     _Tp __v_;
50     char __first_padding_byte_;
51   };
52 #  endif // __has_cpp_attribute(__no_unique_address__)
53 
54   // _FirstPaddingByte<> is sometimes non-standard layout. Using `offsetof` is UB in that case, but GCC and Clang allow
55   // the use as an extension.
56   _LIBCPP_DIAGNOSTIC_PUSH
57   _LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Winvalid-offsetof")
58   static const size_t value = offsetof(_FirstPaddingByte<>, __first_padding_byte_);
59   _LIBCPP_DIAGNOSTIC_POP
60 #endif   // __has_extension(datasizeof)
61 };
62 
63 _LIBCPP_END_NAMESPACE_STD
64 
65 #endif // _LIBCPP___TYPE_TRAITS_DATASIZEOF_H
66