memory_resource 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // <experimental/memory_resource> -*- C++ -*-
  2. // Copyright (C) 2015-2020 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file experimental/memory_resource
  21. * This is a TS C++ Library header.
  22. * @ingroup libfund-ts
  23. */
  24. #ifndef _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE
  25. #define _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE 1
  26. #pragma GCC system_header
  27. #if __cplusplus >= 201402L
  28. #include <memory> // align, uses_allocator, __uses_alloc
  29. #include <experimental/utility> // pair, experimental::erased_type
  30. #include <atomic> // atomic
  31. #include <new> // placement new
  32. #include <cstddef> // max_align_t
  33. #include <ext/new_allocator.h>
  34. #include <debug/assertions.h>
  35. /// @cond
  36. namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
  37. {
  38. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  39. template<typename _Tp> class malloc_allocator;
  40. _GLIBCXX_END_NAMESPACE_VERSION
  41. } // namespace __gnu_cxx
  42. /// @endcond
  43. namespace std {
  44. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  45. namespace experimental {
  46. inline namespace fundamentals_v2 {
  47. namespace pmr {
  48. #define __cpp_lib_experimental_memory_resources 201402L
  49. // Standard memory resources
  50. // 8.5 Class memory_resource
  51. class memory_resource;
  52. // 8.6 Class template polymorphic_allocator
  53. template<typename _Tp>
  54. class polymorphic_allocator;
  55. template<typename _Alloc, typename _Resource = memory_resource>
  56. class __resource_adaptor_imp;
  57. // 8.7 Alias template resource_adaptor
  58. template<typename _Alloc>
  59. using resource_adaptor = __resource_adaptor_imp<
  60. typename allocator_traits<_Alloc>::template rebind_alloc<char>>;
  61. // 8.8 Global memory resources
  62. memory_resource* new_delete_resource() noexcept;
  63. memory_resource* null_memory_resource() noexcept;
  64. memory_resource* get_default_resource() noexcept;
  65. memory_resource* set_default_resource(memory_resource* __r) noexcept;
  66. // TODO 8.9 Pool resource classes
  67. class memory_resource
  68. {
  69. static constexpr size_t _S_max_align = alignof(max_align_t);
  70. public:
  71. memory_resource() = default;
  72. memory_resource(const memory_resource&) = default;
  73. virtual ~memory_resource() = default;
  74. memory_resource& operator=(const memory_resource&) = default;
  75. _GLIBCXX_NODISCARD void*
  76. allocate(size_t __bytes, size_t __alignment = _S_max_align)
  77. { return do_allocate(__bytes, __alignment); }
  78. void
  79. deallocate(void* __p, size_t __bytes, size_t __alignment = _S_max_align)
  80. { return do_deallocate(__p, __bytes, __alignment); }
  81. bool
  82. is_equal(const memory_resource& __other) const noexcept
  83. { return do_is_equal(__other); }
  84. protected:
  85. virtual void*
  86. do_allocate(size_t __bytes, size_t __alignment) = 0;
  87. virtual void
  88. do_deallocate(void* __p, size_t __bytes, size_t __alignment) = 0;
  89. virtual bool
  90. do_is_equal(const memory_resource& __other) const noexcept = 0;
  91. };
  92. inline bool
  93. operator==(const memory_resource& __a, const memory_resource& __b) noexcept
  94. { return &__a == &__b || __a.is_equal(__b); }
  95. inline bool
  96. operator!=(const memory_resource& __a, const memory_resource& __b) noexcept
  97. { return !(__a == __b); }
  98. template<typename _Tp>
  99. class polymorphic_allocator
  100. {
  101. public:
  102. using value_type = _Tp;
  103. polymorphic_allocator() noexcept
  104. : _M_resource(get_default_resource())
  105. { }
  106. polymorphic_allocator(memory_resource* __r)
  107. : _M_resource(__r)
  108. { _GLIBCXX_DEBUG_ASSERT(__r); }
  109. polymorphic_allocator(const polymorphic_allocator& __other) = default;
  110. template <typename _Up>
  111. polymorphic_allocator(const polymorphic_allocator<_Up>&
  112. __other) noexcept
  113. : _M_resource(__other.resource())
  114. { }
  115. polymorphic_allocator&
  116. operator=(const polymorphic_allocator& __rhs) = default;
  117. _GLIBCXX_NODISCARD _Tp* allocate(size_t __n)
  118. { return static_cast<_Tp*>(_M_resource->allocate(__n * sizeof(_Tp),
  119. alignof(_Tp))); }
  120. void
  121. deallocate(_Tp* __p, size_t __n)
  122. { _M_resource->deallocate(__p, __n * sizeof(_Tp), alignof(_Tp)); }
  123. template <typename _Tp1, typename... _Args> //used here
  124. void
  125. construct(_Tp1* __p, _Args&&... __args)
  126. {
  127. std::__uses_allocator_construct(this->resource(), __p,
  128. std::forward<_Args>(__args)...);
  129. }
  130. // Specializations for pair using piecewise construction
  131. template <typename _Tp1, typename _Tp2,
  132. typename... _Args1, typename... _Args2>
  133. void
  134. construct(pair<_Tp1, _Tp2>* __p, piecewise_construct_t,
  135. tuple<_Args1...> __x, tuple<_Args2...> __y)
  136. {
  137. memory_resource* const __resource = this->resource();
  138. auto __x_use_tag =
  139. std::__use_alloc<_Tp1, memory_resource*, _Args1...>(__resource);
  140. auto __y_use_tag =
  141. std::__use_alloc<_Tp2, memory_resource*, _Args2...>(__resource);
  142. ::new(__p) std::pair<_Tp1, _Tp2>(piecewise_construct,
  143. _M_construct_p(__x_use_tag, __x),
  144. _M_construct_p(__y_use_tag, __y));
  145. }
  146. template <typename _Tp1, typename _Tp2>
  147. void
  148. construct(pair<_Tp1,_Tp2>* __p)
  149. { this->construct(__p, piecewise_construct, tuple<>(), tuple<>()); }
  150. template <typename _Tp1, typename _Tp2, typename _Up, typename _Vp>
  151. void
  152. construct(pair<_Tp1,_Tp2>* __p, _Up&& __x, _Vp&& __y)
  153. {
  154. this->construct(__p, piecewise_construct,
  155. forward_as_tuple(std::forward<_Up>(__x)),
  156. forward_as_tuple(std::forward<_Vp>(__y)));
  157. }
  158. template <typename _Tp1, typename _Tp2, typename _Up, typename _Vp>
  159. void
  160. construct(pair<_Tp1,_Tp2>* __p, const std::pair<_Up, _Vp>& __pr)
  161. {
  162. this->construct(__p, piecewise_construct,
  163. forward_as_tuple(__pr.first),
  164. forward_as_tuple(__pr.second));
  165. }
  166. template <typename _Tp1, typename _Tp2, typename _Up, typename _Vp>
  167. void
  168. construct(pair<_Tp1,_Tp2>* __p, pair<_Up, _Vp>&& __pr)
  169. {
  170. this->construct(__p, piecewise_construct,
  171. forward_as_tuple(std::forward<_Up>(__pr.first)),
  172. forward_as_tuple(std::forward<_Vp>(__pr.second)));
  173. }
  174. template <typename _Up>
  175. void
  176. destroy(_Up* __p)
  177. { __p->~_Up(); }
  178. // Return a default-constructed allocator (no allocator propagation)
  179. polymorphic_allocator
  180. select_on_container_copy_construction() const
  181. { return polymorphic_allocator(); }
  182. memory_resource* resource() const { return _M_resource; }
  183. private:
  184. using __uses_alloc1_ = __uses_alloc1<memory_resource*>;
  185. using __uses_alloc2_ = __uses_alloc2<memory_resource*>;
  186. template<typename _Tuple>
  187. _Tuple&&
  188. _M_construct_p(__uses_alloc0, _Tuple& __t)
  189. { return std::move(__t); }
  190. template<typename... _Args>
  191. decltype(auto)
  192. _M_construct_p(__uses_alloc1_ __ua, tuple<_Args...>& __t)
  193. { return tuple_cat(make_tuple(allocator_arg, *(__ua._M_a)),
  194. std::move(__t)); }
  195. template<typename... _Args>
  196. decltype(auto)
  197. _M_construct_p(__uses_alloc2_ __ua, tuple<_Args...>& __t)
  198. { return tuple_cat(std::move(__t), make_tuple(*(__ua._M_a))); }
  199. memory_resource* _M_resource;
  200. };
  201. template <class _Tp1, class _Tp2>
  202. bool
  203. operator==(const polymorphic_allocator<_Tp1>& __a,
  204. const polymorphic_allocator<_Tp2>& __b) noexcept
  205. { return *__a.resource() == *__b.resource(); }
  206. template <class _Tp1, class _Tp2>
  207. bool
  208. operator!=(const polymorphic_allocator<_Tp1>& __a,
  209. const polymorphic_allocator<_Tp2>& __b) noexcept
  210. { return !(__a == __b); }
  211. /// @cond undocumented
  212. class __resource_adaptor_common
  213. {
  214. template<typename, typename> friend class __resource_adaptor_imp;
  215. struct _AlignMgr
  216. {
  217. _AlignMgr(size_t __nbytes, size_t __align)
  218. : _M_nbytes(__nbytes), _M_align(__align)
  219. { }
  220. // Total size that needs to be allocated.
  221. size_t
  222. _M_alloc_size() const { return _M_buf_size() + _M_token_size(); }
  223. void*
  224. _M_adjust(void* __ptr) const
  225. {
  226. const auto __orig_ptr = static_cast<char*>(__ptr);
  227. size_t __space = _M_buf_size();
  228. // Align the pointer within the buffer:
  229. std::align(_M_align, _M_nbytes, __ptr, __space);
  230. const auto __aligned_ptr = static_cast<char*>(__ptr);
  231. const auto __token_size = _M_token_size();
  232. // Store token immediately after the aligned block:
  233. char* const __end = __aligned_ptr + _M_nbytes;
  234. if (__token_size == 1)
  235. _S_write<unsigned char>(__end, __aligned_ptr - __orig_ptr);
  236. else if (__token_size == sizeof(short))
  237. _S_write<unsigned short>(__end, __aligned_ptr - __orig_ptr);
  238. else if (__token_size == sizeof(int) && sizeof(int) < sizeof(char*))
  239. _S_write<unsigned int>(__end, __aligned_ptr - __orig_ptr);
  240. else // (__token_size == sizeof(char*))
  241. // Just store the original pointer:
  242. _S_write<char*>(__end, __orig_ptr);
  243. return __aligned_ptr;
  244. }
  245. char*
  246. _M_unadjust(char* __ptr) const
  247. {
  248. const char* const __end = __ptr + _M_nbytes;
  249. char* __orig_ptr;
  250. const auto __token_size = _M_token_size();
  251. // Read the token and restore the original pointer:
  252. if (__token_size == 1)
  253. __orig_ptr = __ptr - _S_read<unsigned char>(__end);
  254. else if (__token_size == sizeof(short))
  255. __orig_ptr = __ptr - _S_read<unsigned short>(__end);
  256. else if (__token_size == sizeof(int)
  257. && sizeof(int) < sizeof(char*))
  258. __orig_ptr = __ptr - _S_read<unsigned int>(__end);
  259. else // (__token_size == sizeof(char*))
  260. __orig_ptr = _S_read<char*>(__end);
  261. // The adjustment is always less than the requested alignment,
  262. // so if that isn't true now then either the wrong size was passed
  263. // to deallocate or the token was overwritten by a buffer overflow:
  264. __glibcxx_assert(static_cast<size_t>(__ptr - __orig_ptr) < _M_align);
  265. return __orig_ptr;
  266. }
  267. private:
  268. size_t _M_nbytes;
  269. size_t _M_align;
  270. // Number of bytes needed to fit block of given size and alignment.
  271. size_t
  272. _M_buf_size() const { return _M_nbytes + _M_align - 1; }
  273. // Number of additional bytes needed to write the token.
  274. int
  275. _M_token_size() const
  276. {
  277. if (_M_align <= (1ul << __CHAR_BIT__))
  278. return 1;
  279. if (_M_align <= (1ul << (sizeof(short) * __CHAR_BIT__)))
  280. return sizeof(short);
  281. if (_M_align <= (1ull << (sizeof(int) * __CHAR_BIT__)))
  282. return sizeof(int);
  283. return sizeof(char*);
  284. }
  285. template<typename _Tp>
  286. static void
  287. _S_write(void* __to, _Tp __val)
  288. { __builtin_memcpy(__to, &__val, sizeof(_Tp)); }
  289. template<typename _Tp>
  290. static _Tp
  291. _S_read(const void* __from)
  292. {
  293. _Tp __val;
  294. __builtin_memcpy(&__val, __from, sizeof(_Tp));
  295. return __val;
  296. }
  297. };
  298. };
  299. /// @endcond
  300. // 8.7.1 __resource_adaptor_imp
  301. template<typename _Alloc, typename _Resource>
  302. class __resource_adaptor_imp
  303. : public _Resource, private __resource_adaptor_common
  304. {
  305. using memory_resource = _Resource;
  306. static_assert(is_same<char,
  307. typename allocator_traits<_Alloc>::value_type>::value,
  308. "Allocator's value_type is char");
  309. static_assert(is_same<char*,
  310. typename allocator_traits<_Alloc>::pointer>::value,
  311. "Allocator's pointer type is value_type*");
  312. static_assert(is_same<const char*,
  313. typename allocator_traits<_Alloc>::const_pointer>::value,
  314. "Allocator's const_pointer type is value_type const*");
  315. static_assert(is_same<void*,
  316. typename allocator_traits<_Alloc>::void_pointer>::value,
  317. "Allocator's void_pointer type is void*");
  318. static_assert(is_same<const void*,
  319. typename allocator_traits<_Alloc>::const_void_pointer>::value,
  320. "Allocator's const_void_pointer type is void const*");
  321. public:
  322. using allocator_type = _Alloc;
  323. __resource_adaptor_imp() = default;
  324. __resource_adaptor_imp(const __resource_adaptor_imp&) = default;
  325. __resource_adaptor_imp(__resource_adaptor_imp&&) = default;
  326. explicit __resource_adaptor_imp(const _Alloc& __a2)
  327. : _M_alloc(__a2)
  328. { }
  329. explicit __resource_adaptor_imp(_Alloc&& __a2)
  330. : _M_alloc(std::move(__a2))
  331. { }
  332. __resource_adaptor_imp&
  333. operator=(const __resource_adaptor_imp&) = default;
  334. allocator_type get_allocator() const noexcept { return _M_alloc; }
  335. protected:
  336. virtual void*
  337. do_allocate(size_t __bytes, size_t __alignment) override
  338. {
  339. // Cannot use max_align_t on 32-bit Solaris x86, see PR libstdc++/77691
  340. #if ! (defined __sun__ && defined __i386__)
  341. if (__alignment == alignof(max_align_t))
  342. return _M_allocate<alignof(max_align_t)>(__bytes);
  343. #endif
  344. switch (__alignment)
  345. {
  346. case 1:
  347. return _M_alloc.allocate(__bytes);
  348. case 2:
  349. return _M_allocate<2>(__bytes);
  350. case 4:
  351. return _M_allocate<4>(__bytes);
  352. case 8:
  353. return _M_allocate<8>(__bytes);
  354. }
  355. const _AlignMgr __mgr(__bytes, __alignment);
  356. // Assume _M_alloc returns 1-byte aligned memory, so allocate enough
  357. // space to fit a block of the right size and alignment, plus some
  358. // extra bytes to store a token for retrieving the original pointer.
  359. return __mgr._M_adjust(_M_alloc.allocate(__mgr._M_alloc_size()));
  360. }
  361. virtual void
  362. do_deallocate(void* __ptr, size_t __bytes, size_t __alignment) noexcept
  363. override
  364. {
  365. #if ! (defined __sun__ && defined __i386__)
  366. if (__alignment == alignof(max_align_t))
  367. return (void) _M_deallocate<alignof(max_align_t)>(__ptr, __bytes);
  368. #endif
  369. switch (__alignment)
  370. {
  371. case 1:
  372. return (void) _M_alloc.deallocate((char*)__ptr, __bytes);
  373. case 2:
  374. return (void) _M_deallocate<2>(__ptr, __bytes);
  375. case 4:
  376. return (void) _M_deallocate<4>(__ptr, __bytes);
  377. case 8:
  378. return (void) _M_deallocate<8>(__ptr, __bytes);
  379. }
  380. const _AlignMgr __mgr(__bytes, __alignment);
  381. // Use the stored token to retrieve the original pointer.
  382. _M_alloc.deallocate(__mgr._M_unadjust((char*)__ptr),
  383. __mgr._M_alloc_size());
  384. }
  385. virtual bool
  386. do_is_equal(const memory_resource& __other) const noexcept override
  387. {
  388. if (auto __p = dynamic_cast<const __resource_adaptor_imp*>(&__other))
  389. return _M_alloc == __p->_M_alloc;
  390. return false;
  391. }
  392. private:
  393. template<size_t _Num>
  394. struct _Aligned_type { alignas(_Num) char __c[_Num]; };
  395. // Rebind the allocator to the specified type and use it to allocate.
  396. template<size_t _Num, typename _Tp = _Aligned_type<_Num>>
  397. void*
  398. _M_allocate(size_t __bytes)
  399. {
  400. typename allocator_traits<_Alloc>::template
  401. rebind_alloc<_Tp> __a2(_M_alloc);
  402. const size_t __n = (__bytes + _Num - 1) / _Num;
  403. return __a2.allocate(__n);
  404. }
  405. // Rebind the allocator to the specified type and use it to deallocate.
  406. template<size_t _Num, typename _Tp = _Aligned_type<_Num>>
  407. void
  408. _M_deallocate(void* __ptr, size_t __bytes) noexcept
  409. {
  410. typename allocator_traits<_Alloc>::template
  411. rebind_alloc<_Tp> __a2(_M_alloc);
  412. const size_t __n = (__bytes + _Num - 1) / _Num;
  413. __a2.deallocate((_Tp*)__ptr, __n);
  414. }
  415. _Alloc _M_alloc{};
  416. };
  417. // Global memory resources
  418. inline memory_resource*
  419. new_delete_resource() noexcept
  420. {
  421. using type = resource_adaptor<__gnu_cxx::new_allocator<char>>;
  422. alignas(type) static unsigned char __buf[sizeof(type)];
  423. static type* __r = new(__buf) type;
  424. return __r;
  425. }
  426. inline memory_resource*
  427. null_memory_resource() noexcept
  428. {
  429. class type final : public memory_resource
  430. {
  431. void*
  432. do_allocate(size_t, size_t) override
  433. { std::__throw_bad_alloc(); }
  434. void
  435. do_deallocate(void*, size_t, size_t) noexcept override
  436. { }
  437. bool
  438. do_is_equal(const memory_resource& __other) const noexcept override
  439. { return this == &__other; }
  440. };
  441. alignas(type) static unsigned char __buf[sizeof(type)];
  442. static type* __r = new(__buf) type;
  443. return __r;
  444. }
  445. // The default memory resource
  446. /// @cond undocumented
  447. inline std::atomic<memory_resource*>&
  448. __get_default_resource()
  449. {
  450. using type = atomic<memory_resource*>;
  451. alignas(type) static unsigned char __buf[sizeof(type)];
  452. static type* __r = new(__buf) type(new_delete_resource());
  453. return *__r;
  454. }
  455. /// @endcond
  456. /// Get the current default resource.
  457. inline memory_resource*
  458. get_default_resource() noexcept
  459. { return __get_default_resource().load(); }
  460. /// Change the default resource and return the previous one.
  461. inline memory_resource*
  462. set_default_resource(memory_resource* __r) noexcept
  463. {
  464. if (__r == nullptr)
  465. __r = new_delete_resource();
  466. return __get_default_resource().exchange(__r);
  467. }
  468. } // namespace pmr
  469. } // namespace fundamentals_v2
  470. } // namespace experimental
  471. _GLIBCXX_END_NAMESPACE_VERSION
  472. } // namespace std
  473. #endif // C++14
  474. #endif // _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE