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