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 #ifndef ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
16 #define ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
17
18 #include <cassert>
19 #include <cstddef>
20 #include <cstring>
21 #include <memory>
22 #include <new>
23 #include <tuple>
24 #include <type_traits>
25 #include <utility>
26
27 #include "absl/base/config.h"
28 #include "absl/memory/memory.h"
29 #include "absl/meta/type_traits.h"
30 #include "absl/utility/utility.h"
31
32 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
33 #include <sanitizer/asan_interface.h>
34 #endif
35
36 #ifdef ABSL_HAVE_MEMORY_SANITIZER
37 #include <sanitizer/msan_interface.h>
38 #endif
39
40 namespace absl {
41 ABSL_NAMESPACE_BEGIN
42 namespace container_internal {
43
44 template <size_t Alignment>
45 struct alignas(Alignment) AlignedType {};
46
47 // Allocates at least n bytes aligned to the specified alignment.
48 // Alignment must be a power of 2. It must be positive.
49 //
50 // Note that many allocators don't honor alignment requirements above certain
51 // threshold (usually either alignof(std::max_align_t) or alignof(void*)).
52 // Allocate() doesn't apply alignment corrections. If the underlying allocator
53 // returns insufficiently alignment pointer, that's what you are going to get.
54 template <size_t Alignment, class Alloc>
Allocate(Alloc * alloc,size_t n)55 void* Allocate(Alloc* alloc, size_t n) {
56 static_assert(Alignment > 0, "");
57 assert(n && "n must be positive");
58 using M = AlignedType<Alignment>;
59 using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
60 using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
61 // On macOS, "mem_alloc" is a #define with one argument defined in
62 // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
63 // with the "foo(bar)" syntax.
64 A my_mem_alloc(*alloc);
65 void* p = AT::allocate(my_mem_alloc, (n + sizeof(M) - 1) / sizeof(M));
66 assert(reinterpret_cast<uintptr_t>(p) % Alignment == 0 &&
67 "allocator does not respect alignment");
68 return p;
69 }
70
71 // The pointer must have been previously obtained by calling
72 // Allocate<Alignment>(alloc, n).
73 template <size_t Alignment, class Alloc>
Deallocate(Alloc * alloc,void * p,size_t n)74 void Deallocate(Alloc* alloc, void* p, size_t n) {
75 static_assert(Alignment > 0, "");
76 assert(n && "n must be positive");
77 using M = AlignedType<Alignment>;
78 using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
79 using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
80 // On macOS, "mem_alloc" is a #define with one argument defined in
81 // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
82 // with the "foo(bar)" syntax.
83 A my_mem_alloc(*alloc);
84 AT::deallocate(my_mem_alloc, static_cast<M*>(p),
85 (n + sizeof(M) - 1) / sizeof(M));
86 }
87
88 namespace memory_internal {
89
90 // Constructs T into uninitialized storage pointed by `ptr` using the args
91 // specified in the tuple.
92 template <class Alloc, class T, class Tuple, size_t... I>
ConstructFromTupleImpl(Alloc * alloc,T * ptr,Tuple && t,absl::index_sequence<I...>)93 void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t,
94 absl::index_sequence<I...>) {
95 absl::allocator_traits<Alloc>::construct(
96 *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...);
97 }
98
99 template <class T, class F>
100 struct WithConstructedImplF {
101 template <class... Args>
decltypeWithConstructedImplF102 decltype(std::declval<F>()(std::declval<T>())) operator()(
103 Args&&... args) const {
104 return std::forward<F>(f)(T(std::forward<Args>(args)...));
105 }
106 F&& f;
107 };
108
109 template <class T, class Tuple, size_t... Is, class F>
decltype(std::declval<F> ()(std::declval<T> ()))110 decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl(
111 Tuple&& t, absl::index_sequence<Is...>, F&& f) {
112 return WithConstructedImplF<T, F>{std::forward<F>(f)}(
113 std::get<Is>(std::forward<Tuple>(t))...);
114 }
115
116 template <class T, size_t... Is>
117 auto TupleRefImpl(T&& t, absl::index_sequence<Is...>)
118 -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) {
119 return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...);
120 }
121
122 // Returns a tuple of references to the elements of the input tuple. T must be a
123 // tuple.
124 template <class T>
125 auto TupleRef(T&& t) -> decltype(
126 TupleRefImpl(std::forward<T>(t),
127 absl::make_index_sequence<
128 std::tuple_size<typename std::decay<T>::type>::value>())) {
129 return TupleRefImpl(
130 std::forward<T>(t),
131 absl::make_index_sequence<
132 std::tuple_size<typename std::decay<T>::type>::value>());
133 }
134
135 template <class F, class K, class V>
decltype(std::declval<F> ()(std::declval<const K &> (),std::piecewise_construct,std::declval<std::tuple<K>> (),std::declval<V> ()))136 decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct,
137 std::declval<std::tuple<K>>(), std::declval<V>()))
138 DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
139 const auto& key = std::get<0>(p.first);
140 return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
141 std::move(p.second));
142 }
143
144 } // namespace memory_internal
145
146 // Constructs T into uninitialized storage pointed by `ptr` using the args
147 // specified in the tuple.
148 template <class Alloc, class T, class Tuple>
ConstructFromTuple(Alloc * alloc,T * ptr,Tuple && t)149 void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
150 memory_internal::ConstructFromTupleImpl(
151 alloc, ptr, std::forward<Tuple>(t),
152 absl::make_index_sequence<
153 std::tuple_size<typename std::decay<Tuple>::type>::value>());
154 }
155
156 // Constructs T using the args specified in the tuple and calls F with the
157 // constructed value.
158 template <class T, class Tuple, class F>
decltype(std::declval<F> ()(std::declval<T> ()))159 decltype(std::declval<F>()(std::declval<T>())) WithConstructed(
160 Tuple&& t, F&& f) {
161 return memory_internal::WithConstructedImpl<T>(
162 std::forward<Tuple>(t),
163 absl::make_index_sequence<
164 std::tuple_size<typename std::decay<Tuple>::type>::value>(),
165 std::forward<F>(f));
166 }
167
168 // Given arguments of an std::pair's consructor, PairArgs() returns a pair of
169 // tuples with references to the passed arguments. The tuples contain
170 // constructor arguments for the first and the second elements of the pair.
171 //
172 // The following two snippets are equivalent.
173 //
174 // 1. std::pair<F, S> p(args...);
175 //
176 // 2. auto a = PairArgs(args...);
177 // std::pair<F, S> p(std::piecewise_construct,
178 // std::move(a.first), std::move(a.second));
PairArgs()179 inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
180 template <class F, class S>
PairArgs(F && f,S && s)181 std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
182 return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
183 std::forward_as_tuple(std::forward<S>(s))};
184 }
185 template <class F, class S>
PairArgs(const std::pair<F,S> & p)186 std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
187 const std::pair<F, S>& p) {
188 return PairArgs(p.first, p.second);
189 }
190 template <class F, class S>
PairArgs(std::pair<F,S> && p)191 std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
192 return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
193 }
194 template <class F, class S>
195 auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
196 -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
197 memory_internal::TupleRef(std::forward<S>(s)))) {
198 return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
199 memory_internal::TupleRef(std::forward<S>(s)));
200 }
201
202 // A helper function for implementing apply() in map policies.
203 template <class F, class... Args>
204 auto DecomposePair(F&& f, Args&&... args)
205 -> decltype(memory_internal::DecomposePairImpl(
206 std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
207 return memory_internal::DecomposePairImpl(
208 std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
209 }
210
211 // A helper function for implementing apply() in set policies.
212 template <class F, class Arg>
decltype(std::declval<F> ()(std::declval<const Arg &> (),std::declval<Arg> ()))213 decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
214 DecomposeValue(F&& f, Arg&& arg) {
215 const auto& key = arg;
216 return std::forward<F>(f)(key, std::forward<Arg>(arg));
217 }
218
219 // Helper functions for asan and msan.
SanitizerPoisonMemoryRegion(const void * m,size_t s)220 inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) {
221 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
222 ASAN_POISON_MEMORY_REGION(m, s);
223 #endif
224 #ifdef ABSL_HAVE_MEMORY_SANITIZER
225 __msan_poison(m, s);
226 #endif
227 (void)m;
228 (void)s;
229 }
230
SanitizerUnpoisonMemoryRegion(const void * m,size_t s)231 inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) {
232 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
233 ASAN_UNPOISON_MEMORY_REGION(m, s);
234 #endif
235 #ifdef ABSL_HAVE_MEMORY_SANITIZER
236 __msan_unpoison(m, s);
237 #endif
238 (void)m;
239 (void)s;
240 }
241
242 template <typename T>
SanitizerPoisonObject(const T * object)243 inline void SanitizerPoisonObject(const T* object) {
244 SanitizerPoisonMemoryRegion(object, sizeof(T));
245 }
246
247 template <typename T>
SanitizerUnpoisonObject(const T * object)248 inline void SanitizerUnpoisonObject(const T* object) {
249 SanitizerUnpoisonMemoryRegion(object, sizeof(T));
250 }
251
252 namespace memory_internal {
253
254 // If Pair is a standard-layout type, OffsetOf<Pair>::kFirst and
255 // OffsetOf<Pair>::kSecond are equivalent to offsetof(Pair, first) and
256 // offsetof(Pair, second) respectively. Otherwise they are -1.
257 //
258 // The purpose of OffsetOf is to avoid calling offsetof() on non-standard-layout
259 // type, which is non-portable.
260 template <class Pair, class = std::true_type>
261 struct OffsetOf {
262 static constexpr size_t kFirst = static_cast<size_t>(-1);
263 static constexpr size_t kSecond = static_cast<size_t>(-1);
264 };
265
266 template <class Pair>
267 struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> {
268 static constexpr size_t kFirst = offsetof(Pair, first);
269 static constexpr size_t kSecond = offsetof(Pair, second);
270 };
271
272 template <class K, class V>
273 struct IsLayoutCompatible {
274 private:
275 struct Pair {
276 K first;
277 V second;
278 };
279
280 // Is P layout-compatible with Pair?
281 template <class P>
282 static constexpr bool LayoutCompatible() {
283 return std::is_standard_layout<P>() && sizeof(P) == sizeof(Pair) &&
284 alignof(P) == alignof(Pair) &&
285 memory_internal::OffsetOf<P>::kFirst ==
286 memory_internal::OffsetOf<Pair>::kFirst &&
287 memory_internal::OffsetOf<P>::kSecond ==
288 memory_internal::OffsetOf<Pair>::kSecond;
289 }
290
291 public:
292 // Whether pair<const K, V> and pair<K, V> are layout-compatible. If they are,
293 // then it is safe to store them in a union and read from either.
294 static constexpr bool value = std::is_standard_layout<K>() &&
295 std::is_standard_layout<Pair>() &&
296 memory_internal::OffsetOf<Pair>::kFirst == 0 &&
297 LayoutCompatible<std::pair<K, V>>() &&
298 LayoutCompatible<std::pair<const K, V>>();
299 };
300
301 } // namespace memory_internal
302
303 // The internal storage type for key-value containers like flat_hash_map.
304 //
305 // It is convenient for the value_type of a flat_hash_map<K, V> to be
306 // pair<const K, V>; the "const K" prevents accidental modification of the key
307 // when dealing with the reference returned from find() and similar methods.
308 // However, this creates other problems; we want to be able to emplace(K, V)
309 // efficiently with move operations, and similarly be able to move a
310 // pair<K, V> in insert().
311 //
312 // The solution is this union, which aliases the const and non-const versions
313 // of the pair. This also allows flat_hash_map<const K, V> to work, even though
314 // that has the same efficiency issues with move in emplace() and insert() -
315 // but people do it anyway.
316 //
317 // If kMutableKeys is false, only the value member can be accessed.
318 //
319 // If kMutableKeys is true, key can be accessed through all slots while value
320 // and mutable_value must be accessed only via INITIALIZED slots. Slots are
321 // created and destroyed via mutable_value so that the key can be moved later.
322 //
323 // Accessing one of the union fields while the other is active is safe as
324 // long as they are layout-compatible, which is guaranteed by the definition of
325 // kMutableKeys. For C++11, the relevant section of the standard is
326 // https://timsong-cpp.github.io/cppwp/n3337/class.mem#19 (9.2.19)
327 template <class K, class V>
328 union map_slot_type {
329 map_slot_type() {}
330 ~map_slot_type() = delete;
331 using value_type = std::pair<const K, V>;
332 using mutable_value_type =
333 std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
334
335 value_type value;
336 mutable_value_type mutable_value;
337 absl::remove_const_t<K> key;
338 };
339
340 template <class K, class V>
341 struct map_slot_policy {
342 using slot_type = map_slot_type<K, V>;
343 using value_type = std::pair<const K, V>;
344 using mutable_value_type =
345 std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
346
347 private:
348 static void emplace(slot_type* slot) {
349 // The construction of union doesn't do anything at runtime but it allows us
350 // to access its members without violating aliasing rules.
351 new (slot) slot_type;
352 }
353 // If pair<const K, V> and pair<K, V> are layout-compatible, we can accept one
354 // or the other via slot_type. We are also free to access the key via
355 // slot_type::key in this case.
356 using kMutableKeys = memory_internal::IsLayoutCompatible<K, V>;
357
358 public:
359 static value_type& element(slot_type* slot) { return slot->value; }
360 static const value_type& element(const slot_type* slot) {
361 return slot->value;
362 }
363
364 // When C++17 is available, we can use std::launder to provide mutable
365 // access to the key for use in node handle.
366 #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
367 static K& mutable_key(slot_type* slot) {
368 // Still check for kMutableKeys so that we can avoid calling std::launder
369 // unless necessary because it can interfere with optimizations.
370 return kMutableKeys::value ? slot->key
371 : *std::launder(const_cast<K*>(
372 std::addressof(slot->value.first)));
373 }
374 #else // !(defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606)
375 static const K& mutable_key(slot_type* slot) { return key(slot); }
376 #endif
377
378 static const K& key(const slot_type* slot) {
379 return kMutableKeys::value ? slot->key : slot->value.first;
380 }
381
382 template <class Allocator, class... Args>
383 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
384 emplace(slot);
385 if (kMutableKeys::value) {
386 absl::allocator_traits<Allocator>::construct(*alloc, &slot->mutable_value,
387 std::forward<Args>(args)...);
388 } else {
389 absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
390 std::forward<Args>(args)...);
391 }
392 }
393
394 // Construct this slot by moving from another slot.
395 template <class Allocator>
396 static void construct(Allocator* alloc, slot_type* slot, slot_type* other) {
397 emplace(slot);
398 if (kMutableKeys::value) {
399 absl::allocator_traits<Allocator>::construct(
400 *alloc, &slot->mutable_value, std::move(other->mutable_value));
401 } else {
402 absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
403 std::move(other->value));
404 }
405 }
406
407 // Construct this slot by copying from another slot.
408 template <class Allocator>
409 static void construct(Allocator* alloc, slot_type* slot,
410 const slot_type* other) {
411 emplace(slot);
412 absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
413 other->value);
414 }
415
416 template <class Allocator>
417 static void destroy(Allocator* alloc, slot_type* slot) {
418 if (kMutableKeys::value) {
419 absl::allocator_traits<Allocator>::destroy(*alloc, &slot->mutable_value);
420 } else {
421 absl::allocator_traits<Allocator>::destroy(*alloc, &slot->value);
422 }
423 }
424
425 template <class Allocator>
426 static void transfer(Allocator* alloc, slot_type* new_slot,
427 slot_type* old_slot) {
428 emplace(new_slot);
429 #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
430 if (absl::is_trivially_relocatable<value_type>()) {
431 // TODO(b/247130232,b/251814870): remove casts after fixing warnings.
432 std::memcpy(static_cast<void*>(std::launder(&new_slot->value)),
433 static_cast<const void*>(&old_slot->value),
434 sizeof(value_type));
435 return;
436 }
437 #endif
438
439 if (kMutableKeys::value) {
440 absl::allocator_traits<Allocator>::construct(
441 *alloc, &new_slot->mutable_value, std::move(old_slot->mutable_value));
442 } else {
443 absl::allocator_traits<Allocator>::construct(*alloc, &new_slot->value,
444 std::move(old_slot->value));
445 }
446 destroy(alloc, old_slot);
447 }
448 };
449
450 } // namespace container_internal
451 ABSL_NAMESPACE_END
452 } // namespace absl
453
454 #endif // ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
455