Allocator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. //===- Allocator.h - Simple memory allocation abstraction -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. ///
  10. /// This file defines the BumpPtrAllocator interface. BumpPtrAllocator conforms
  11. /// to the LLVM "Allocator" concept and is similar to MallocAllocator, but
  12. /// objects cannot be deallocated. Their lifetime is tied to the lifetime of the
  13. /// allocator.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #ifndef LLVM_SUPPORT_ALLOCATOR_H
  17. #define LLVM_SUPPORT_ALLOCATOR_H
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/Support/Alignment.h"
  21. #include "llvm/Support/AllocatorBase.h"
  22. #include "llvm/Support/Compiler.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemAlloc.h"
  26. #include <algorithm>
  27. #include <cassert>
  28. #include <cstddef>
  29. #include <cstdint>
  30. #include <cstdlib>
  31. #include <iterator>
  32. #include <type_traits>
  33. #include <utility>
  34. namespace llvm {
  35. namespace detail {
  36. // We call out to an external function to actually print the message as the
  37. // printing code uses Allocator.h in its implementation.
  38. void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
  39. size_t TotalMemory);
  40. } // end namespace detail
  41. /// Allocate memory in an ever growing pool, as if by bump-pointer.
  42. ///
  43. /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
  44. /// memory rather than relying on a boundless contiguous heap. However, it has
  45. /// bump-pointer semantics in that it is a monotonically growing pool of memory
  46. /// where every allocation is found by merely allocating the next N bytes in
  47. /// the slab, or the next N bytes in the next slab.
  48. ///
  49. /// Note that this also has a threshold for forcing allocations above a certain
  50. /// size into their own slab.
  51. ///
  52. /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
  53. /// object, which wraps malloc, to allocate memory, but it can be changed to
  54. /// use a custom allocator.
  55. ///
  56. /// The GrowthDelay specifies after how many allocated slabs the allocator
  57. /// increases the size of the slabs.
  58. template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
  59. size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
  60. class BumpPtrAllocatorImpl
  61. : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
  62. SizeThreshold, GrowthDelay>>,
  63. private AllocatorT {
  64. public:
  65. static_assert(SizeThreshold <= SlabSize,
  66. "The SizeThreshold must be at most the SlabSize to ensure "
  67. "that objects larger than a slab go into their own memory "
  68. "allocation.");
  69. static_assert(GrowthDelay > 0,
  70. "GrowthDelay must be at least 1 which already increases the"
  71. "slab size after each allocated slab.");
  72. BumpPtrAllocatorImpl() = default;
  73. template <typename T>
  74. BumpPtrAllocatorImpl(T &&Allocator)
  75. : AllocatorT(std::forward<T &&>(Allocator)) {}
  76. // Manually implement a move constructor as we must clear the old allocator's
  77. // slabs as a matter of correctness.
  78. BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
  79. : AllocatorT(static_cast<AllocatorT &&>(Old)), CurPtr(Old.CurPtr),
  80. End(Old.End), Slabs(std::move(Old.Slabs)),
  81. CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
  82. BytesAllocated(Old.BytesAllocated), RedZoneSize(Old.RedZoneSize) {
  83. Old.CurPtr = Old.End = nullptr;
  84. Old.BytesAllocated = 0;
  85. Old.Slabs.clear();
  86. Old.CustomSizedSlabs.clear();
  87. }
  88. ~BumpPtrAllocatorImpl() {
  89. DeallocateSlabs(Slabs.begin(), Slabs.end());
  90. DeallocateCustomSizedSlabs();
  91. }
  92. BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
  93. DeallocateSlabs(Slabs.begin(), Slabs.end());
  94. DeallocateCustomSizedSlabs();
  95. CurPtr = RHS.CurPtr;
  96. End = RHS.End;
  97. BytesAllocated = RHS.BytesAllocated;
  98. RedZoneSize = RHS.RedZoneSize;
  99. Slabs = std::move(RHS.Slabs);
  100. CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
  101. AllocatorT::operator=(static_cast<AllocatorT &&>(RHS));
  102. RHS.CurPtr = RHS.End = nullptr;
  103. RHS.BytesAllocated = 0;
  104. RHS.Slabs.clear();
  105. RHS.CustomSizedSlabs.clear();
  106. return *this;
  107. }
  108. /// Deallocate all but the current slab and reset the current pointer
  109. /// to the beginning of it, freeing all memory allocated so far.
  110. void Reset() {
  111. // Deallocate all but the first slab, and deallocate all custom-sized slabs.
  112. DeallocateCustomSizedSlabs();
  113. CustomSizedSlabs.clear();
  114. if (Slabs.empty())
  115. return;
  116. // Reset the state.
  117. BytesAllocated = 0;
  118. CurPtr = (char *)Slabs.front();
  119. End = CurPtr + SlabSize;
  120. __asan_poison_memory_region(*Slabs.begin(), computeSlabSize(0));
  121. DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
  122. Slabs.erase(std::next(Slabs.begin()), Slabs.end());
  123. }
  124. /// Allocate space at the specified alignment.
  125. LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
  126. Allocate(size_t Size, Align Alignment) {
  127. // Keep track of how many bytes we've allocated.
  128. BytesAllocated += Size;
  129. size_t Adjustment = offsetToAlignedAddr(CurPtr, Alignment);
  130. assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow");
  131. size_t SizeToAllocate = Size;
  132. #if LLVM_ADDRESS_SANITIZER_BUILD
  133. // Add trailing bytes as a "red zone" under ASan.
  134. SizeToAllocate += RedZoneSize;
  135. #endif
  136. // Check if we have enough space.
  137. if (Adjustment + SizeToAllocate <= size_t(End - CurPtr)) {
  138. char *AlignedPtr = CurPtr + Adjustment;
  139. CurPtr = AlignedPtr + SizeToAllocate;
  140. // Update the allocation point of this memory block in MemorySanitizer.
  141. // Without this, MemorySanitizer messages for values originated from here
  142. // will point to the allocation of the entire slab.
  143. __msan_allocated_memory(AlignedPtr, Size);
  144. // Similarly, tell ASan about this space.
  145. __asan_unpoison_memory_region(AlignedPtr, Size);
  146. return AlignedPtr;
  147. }
  148. // If Size is really big, allocate a separate slab for it.
  149. size_t PaddedSize = SizeToAllocate + Alignment.value() - 1;
  150. if (PaddedSize > SizeThreshold) {
  151. void *NewSlab =
  152. AllocatorT::Allocate(PaddedSize, alignof(std::max_align_t));
  153. // We own the new slab and don't want anyone reading anyting other than
  154. // pieces returned from this method. So poison the whole slab.
  155. __asan_poison_memory_region(NewSlab, PaddedSize);
  156. CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
  157. uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
  158. assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
  159. char *AlignedPtr = (char*)AlignedAddr;
  160. __msan_allocated_memory(AlignedPtr, Size);
  161. __asan_unpoison_memory_region(AlignedPtr, Size);
  162. return AlignedPtr;
  163. }
  164. // Otherwise, start a new slab and try again.
  165. StartNewSlab();
  166. uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
  167. assert(AlignedAddr + SizeToAllocate <= (uintptr_t)End &&
  168. "Unable to allocate memory!");
  169. char *AlignedPtr = (char*)AlignedAddr;
  170. CurPtr = AlignedPtr + SizeToAllocate;
  171. __msan_allocated_memory(AlignedPtr, Size);
  172. __asan_unpoison_memory_region(AlignedPtr, Size);
  173. return AlignedPtr;
  174. }
  175. inline LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
  176. Allocate(size_t Size, size_t Alignment) {
  177. assert(Alignment > 0 && "0-byte alignment is not allowed. Use 1 instead.");
  178. return Allocate(Size, Align(Alignment));
  179. }
  180. // Pull in base class overloads.
  181. using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
  182. // Bump pointer allocators are expected to never free their storage; and
  183. // clients expect pointers to remain valid for non-dereferencing uses even
  184. // after deallocation.
  185. void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
  186. __asan_poison_memory_region(Ptr, Size);
  187. }
  188. // Pull in base class overloads.
  189. using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
  190. size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
  191. /// \return An index uniquely and reproducibly identifying
  192. /// an input pointer \p Ptr in the given allocator.
  193. /// The returned value is negative iff the object is inside a custom-size
  194. /// slab.
  195. /// Returns an empty optional if the pointer is not found in the allocator.
  196. llvm::Optional<int64_t> identifyObject(const void *Ptr) {
  197. const char *P = static_cast<const char *>(Ptr);
  198. int64_t InSlabIdx = 0;
  199. for (size_t Idx = 0, E = Slabs.size(); Idx < E; Idx++) {
  200. const char *S = static_cast<const char *>(Slabs[Idx]);
  201. if (P >= S && P < S + computeSlabSize(Idx))
  202. return InSlabIdx + static_cast<int64_t>(P - S);
  203. InSlabIdx += static_cast<int64_t>(computeSlabSize(Idx));
  204. }
  205. // Use negative index to denote custom sized slabs.
  206. int64_t InCustomSizedSlabIdx = -1;
  207. for (size_t Idx = 0, E = CustomSizedSlabs.size(); Idx < E; Idx++) {
  208. const char *S = static_cast<const char *>(CustomSizedSlabs[Idx].first);
  209. size_t Size = CustomSizedSlabs[Idx].second;
  210. if (P >= S && P < S + Size)
  211. return InCustomSizedSlabIdx - static_cast<int64_t>(P - S);
  212. InCustomSizedSlabIdx -= static_cast<int64_t>(Size);
  213. }
  214. return None;
  215. }
  216. /// A wrapper around identifyObject that additionally asserts that
  217. /// the object is indeed within the allocator.
  218. /// \return An index uniquely and reproducibly identifying
  219. /// an input pointer \p Ptr in the given allocator.
  220. int64_t identifyKnownObject(const void *Ptr) {
  221. Optional<int64_t> Out = identifyObject(Ptr);
  222. assert(Out && "Wrong allocator used");
  223. return *Out;
  224. }
  225. /// A wrapper around identifyKnownObject. Accepts type information
  226. /// about the object and produces a smaller identifier by relying on
  227. /// the alignment information. Note that sub-classes may have different
  228. /// alignment, so the most base class should be passed as template parameter
  229. /// in order to obtain correct results. For that reason automatic template
  230. /// parameter deduction is disabled.
  231. /// \return An index uniquely and reproducibly identifying
  232. /// an input pointer \p Ptr in the given allocator. This identifier is
  233. /// different from the ones produced by identifyObject and
  234. /// identifyAlignedObject.
  235. template <typename T>
  236. int64_t identifyKnownAlignedObject(const void *Ptr) {
  237. int64_t Out = identifyKnownObject(Ptr);
  238. assert(Out % alignof(T) == 0 && "Wrong alignment information");
  239. return Out / alignof(T);
  240. }
  241. size_t getTotalMemory() const {
  242. size_t TotalMemory = 0;
  243. for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
  244. TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
  245. for (auto &PtrAndSize : CustomSizedSlabs)
  246. TotalMemory += PtrAndSize.second;
  247. return TotalMemory;
  248. }
  249. size_t getBytesAllocated() const { return BytesAllocated; }
  250. void setRedZoneSize(size_t NewSize) {
  251. RedZoneSize = NewSize;
  252. }
  253. void PrintStats() const {
  254. detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
  255. getTotalMemory());
  256. }
  257. private:
  258. /// The current pointer into the current slab.
  259. ///
  260. /// This points to the next free byte in the slab.
  261. char *CurPtr = nullptr;
  262. /// The end of the current slab.
  263. char *End = nullptr;
  264. /// The slabs allocated so far.
  265. SmallVector<void *, 4> Slabs;
  266. /// Custom-sized slabs allocated for too-large allocation requests.
  267. SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
  268. /// How many bytes we've allocated.
  269. ///
  270. /// Used so that we can compute how much space was wasted.
  271. size_t BytesAllocated = 0;
  272. /// The number of bytes to put between allocations when running under
  273. /// a sanitizer.
  274. size_t RedZoneSize = 1;
  275. static size_t computeSlabSize(unsigned SlabIdx) {
  276. // Scale the actual allocated slab size based on the number of slabs
  277. // allocated. Every GrowthDelay slabs allocated, we double
  278. // the allocated size to reduce allocation frequency, but saturate at
  279. // multiplying the slab size by 2^30.
  280. return SlabSize *
  281. ((size_t)1 << std::min<size_t>(30, SlabIdx / GrowthDelay));
  282. }
  283. /// Allocate a new slab and move the bump pointers over into the new
  284. /// slab, modifying CurPtr and End.
  285. void StartNewSlab() {
  286. size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
  287. void *NewSlab =
  288. AllocatorT::Allocate(AllocatedSlabSize, alignof(std::max_align_t));
  289. // We own the new slab and don't want anyone reading anything other than
  290. // pieces returned from this method. So poison the whole slab.
  291. __asan_poison_memory_region(NewSlab, AllocatedSlabSize);
  292. Slabs.push_back(NewSlab);
  293. CurPtr = (char *)(NewSlab);
  294. End = ((char *)NewSlab) + AllocatedSlabSize;
  295. }
  296. /// Deallocate a sequence of slabs.
  297. void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
  298. SmallVectorImpl<void *>::iterator E) {
  299. for (; I != E; ++I) {
  300. size_t AllocatedSlabSize =
  301. computeSlabSize(std::distance(Slabs.begin(), I));
  302. AllocatorT::Deallocate(*I, AllocatedSlabSize, alignof(std::max_align_t));
  303. }
  304. }
  305. /// Deallocate all memory for custom sized slabs.
  306. void DeallocateCustomSizedSlabs() {
  307. for (auto &PtrAndSize : CustomSizedSlabs) {
  308. void *Ptr = PtrAndSize.first;
  309. size_t Size = PtrAndSize.second;
  310. AllocatorT::Deallocate(Ptr, Size, alignof(std::max_align_t));
  311. }
  312. }
  313. template <typename T> friend class SpecificBumpPtrAllocator;
  314. };
  315. /// The standard BumpPtrAllocator which just uses the default template
  316. /// parameters.
  317. typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
  318. /// A BumpPtrAllocator that allows only elements of a specific type to be
  319. /// allocated.
  320. ///
  321. /// This allows calling the destructor in DestroyAll() and when the allocator is
  322. /// destroyed.
  323. template <typename T> class SpecificBumpPtrAllocator {
  324. BumpPtrAllocator Allocator;
  325. public:
  326. SpecificBumpPtrAllocator() {
  327. // Because SpecificBumpPtrAllocator walks the memory to call destructors,
  328. // it can't have red zones between allocations.
  329. Allocator.setRedZoneSize(0);
  330. }
  331. SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
  332. : Allocator(std::move(Old.Allocator)) {}
  333. ~SpecificBumpPtrAllocator() { DestroyAll(); }
  334. SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
  335. Allocator = std::move(RHS.Allocator);
  336. return *this;
  337. }
  338. /// Call the destructor of each allocated object and deallocate all but the
  339. /// current slab and reset the current pointer to the beginning of it, freeing
  340. /// all memory allocated so far.
  341. void DestroyAll() {
  342. auto DestroyElements = [](char *Begin, char *End) {
  343. assert(Begin == (char *)alignAddr(Begin, Align::Of<T>()));
  344. for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
  345. reinterpret_cast<T *>(Ptr)->~T();
  346. };
  347. for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
  348. ++I) {
  349. size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
  350. std::distance(Allocator.Slabs.begin(), I));
  351. char *Begin = (char *)alignAddr(*I, Align::Of<T>());
  352. char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
  353. : (char *)*I + AllocatedSlabSize;
  354. DestroyElements(Begin, End);
  355. }
  356. for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
  357. void *Ptr = PtrAndSize.first;
  358. size_t Size = PtrAndSize.second;
  359. DestroyElements((char *)alignAddr(Ptr, Align::Of<T>()),
  360. (char *)Ptr + Size);
  361. }
  362. Allocator.Reset();
  363. }
  364. /// Allocate space for an array of objects without constructing them.
  365. T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
  366. };
  367. } // end namespace llvm
  368. template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
  369. size_t GrowthDelay>
  370. void *
  371. operator new(size_t Size,
  372. llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold,
  373. GrowthDelay> &Allocator) {
  374. return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
  375. alignof(std::max_align_t)));
  376. }
  377. template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
  378. size_t GrowthDelay>
  379. void operator delete(void *,
  380. llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
  381. SizeThreshold, GrowthDelay> &) {
  382. }
  383. #endif // LLVM_SUPPORT_ALLOCATOR_H