1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Functionality related to memory alignment. */
9 #ifndef mozilla_Alignment_h
10 #define mozilla_Alignment_h
18 * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many
19 * bytes of alignment a given type needs.
31 static const size_t alignment
= sizeof(Aligner
) - sizeof(T
);
34 #define MOZ_ALIGNOF(T) mozilla::AlignmentFinder<T>::alignment
37 * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types.
41 * MOZ_ALIGNED_DECL(char arr[2], 8);
43 * will declare a two-character array |arr| aligned to 8 bytes.
47 # define MOZ_ALIGNED_DECL(_type, _align) \
48 _type __attribute__((aligned(_align)))
49 #elif defined(_MSC_VER)
50 # define MOZ_ALIGNED_DECL(_type, _align) \
51 __declspec(align(_align)) _type
53 # warning "We don't know how to align variables on this compiler."
54 # define MOZ_ALIGNED_DECL(_type, _align) _type
58 * AlignedElem<N> is a structure whose alignment is guaranteed to be at least N
61 * We support 1, 2, 4, 8, and 16-bit alignment.
63 template<size_t Align
>
67 * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where
68 * foo is a template parameter.
74 MOZ_ALIGNED_DECL(uint8_t elem
, 1);
80 MOZ_ALIGNED_DECL(uint8_t elem
, 2);
86 MOZ_ALIGNED_DECL(uint8_t elem
, 4);
92 MOZ_ALIGNED_DECL(uint8_t elem
, 8);
96 struct AlignedElem
<16>
98 MOZ_ALIGNED_DECL(uint8_t elem
, 16);
102 * This utility pales in comparison to Boost's aligned_storage. The utility
103 * simply assumes that uint64_t is enough alignment for anyone. This may need
104 * to be extended one day...
106 * As an important side effect, pulling the storage into this template is
107 * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving
108 * false negatives when we cast from the char buffer to whatever type we've
109 * constructed using the bytes.
111 template<size_t Nbytes
>
112 struct AlignedStorage
119 const void* addr() const { return u
.bytes
; }
120 void* addr() { return u
.bytes
; }
124 struct AlignedStorage2
127 char bytes
[sizeof(T
)];
131 const T
* addr() const { return reinterpret_cast<const T
*>(u
.bytes
); }
132 T
* addr() { return static_cast<T
*>(static_cast<void*>(u
.bytes
)); }
135 } /* namespace mozilla */
137 #endif /* mozilla_Alignment_h */