container_memory.h 18 KB

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