container_memory.h 17 KB

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