1 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file defines the MallocAllocator and BumpPtrAllocator interfaces. Both
12 /// of these conform to an LLVM "Allocator" concept which consists of an
13 /// Allocate method accepting a size and alignment, and a Deallocate accepting
14 /// a pointer and size. Further, the LLVM "Allocator" concept has overloads of
15 /// Allocate and Deallocate for setting size and alignment based on the final
16 /// type. These overloads are typically provided by a base class template \c
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_SUPPORT_ALLOCATOR_H
22 #define LLVM_SUPPORT_ALLOCATOR_H
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/AlignOf.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Memory.h"
35 template <typename T> struct ReferenceAdder {
38 template <typename T> struct ReferenceAdder<T &> {
42 /// \brief CRTP base class providing obvious overloads for the core \c
43 /// Allocate() methods of LLVM-style allocators.
45 /// This base class both documents the full public interface exposed by all
46 /// LLVM-style allocators, and redirects all of the overloads to a single core
47 /// set of methods which the derived class must define.
48 template <typename DerivedT> class AllocatorBase {
50 /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method
51 /// must be implemented by \c DerivedT.
52 void *Allocate(size_t Size, size_t Alignment) {
54 static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
55 &AllocatorBase::Allocate) !=
56 static_cast<void *(DerivedT::*)(size_t, size_t)>(
58 "Class derives from AllocatorBase without implementing the "
59 "core Allocate(size_t, size_t) overload!");
61 return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
64 /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this
66 void Deallocate(const void *Ptr) {
68 static_assert(static_cast<void (AllocatorBase::*)(const void *)>(
69 &AllocatorBase::Deallocate) !=
70 static_cast<void (DerivedT::*)(const void *)>(
71 &DerivedT::Deallocate),
72 "Class derives from AllocatorBase without implementing the "
73 "core Deallocate(void *) overload!");
75 return static_cast<DerivedT *>(this)->Deallocate(Ptr);
78 // The rest of these methods are helpers that redirect to one of the above
81 /// \brief Allocate space for one object without constructing it.
82 template <typename T> T *Allocate() {
83 return static_cast<T *>(Allocate(sizeof(T), AlignOf<T>::Alignment));
86 /// \brief Allocate space for an array of objects without constructing them.
87 template <typename T> T *Allocate(size_t Num) {
88 return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
91 /// \brief Allocate space for an array of objects with the specified alignment
92 /// and without constructing them.
93 template <typename T> T *Allocate(size_t Num, size_t Alignment) {
94 // Round EltSize up to the specified alignment.
95 size_t EltSize = (sizeof(T) + Alignment - 1) & (-Alignment);
96 return static_cast<T *>(Allocate(Num * EltSize, Alignment));
99 /// \brief Deallocate space for one object without destroying it.
100 template <typename T> void Deallocate(T *Ptr) {
101 Deallocate(static_cast<const void *>(Ptr));
104 /// \brief Allocate space for an array of objects without constructing them.
105 template <typename T> void Deallocate(T *Ptr, size_t /*Num*/) {
106 Deallocate(static_cast<const void *>(Ptr));
110 class MallocAllocator : public AllocatorBase<MallocAllocator> {
113 ~MallocAllocator() {}
117 void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
119 // Pull in base class overloads.
120 using AllocatorBase<MallocAllocator>::Allocate;
122 void Deallocate(const void *Ptr) { free(const_cast<void *>(Ptr)); }
124 // Pull in base class overloads.
125 using AllocatorBase<MallocAllocator>::Deallocate;
127 void PrintStats() const {}
130 /// MallocSlabAllocator - The default slab allocator for the bump allocator
131 /// is an adapter class for MallocAllocator that just forwards the method
132 /// calls and translates the arguments.
133 class MallocSlabAllocator {
134 /// Allocator - The underlying allocator that we forward to.
136 MallocAllocator Allocator;
139 void *Allocate(size_t Size) { return Allocator.Allocate(Size, 0); }
140 void Deallocate(void *Slab, size_t Size) { Allocator.Deallocate(Slab); }
145 // We call out to an external function to actually print the message as the
146 // printing code uses Allocator.h in its implementation.
147 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
149 } // End namespace detail.
151 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
153 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
154 /// memory rather than relying on boundless contiguous heap. However, it has
155 /// bump-pointer semantics in that is a monotonically growing pool of memory
156 /// where every allocation is found by merely allocating the next N bytes in
157 /// the slab, or the next N bytes in the next slab.
159 /// Note that this also has a threshold for forcing allocations above a certain
160 /// size into their own slab.
162 /// The BumpPtrAllocatorImpl template defaults to using a MallocSlabAllocator
163 /// object, which wraps malloc, to allocate memory, but it can be changed to
164 /// use a custom allocator.
165 template <typename AllocatorT = MallocSlabAllocator, size_t SlabSize = 4096,
166 size_t SizeThreshold = SlabSize>
167 class BumpPtrAllocatorImpl
168 : public AllocatorBase<
169 BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
170 BumpPtrAllocatorImpl(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
171 void operator=(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
174 static_assert(SizeThreshold <= SlabSize,
175 "The SizeThreshold must be at most the SlabSize to ensure "
176 "that objects larger than a slab go into their own memory "
179 BumpPtrAllocatorImpl()
180 : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
181 template <typename T>
182 BumpPtrAllocatorImpl(T &&Allocator)
183 : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
184 Allocator(std::forward<T &&>(Allocator)) {}
185 ~BumpPtrAllocatorImpl() {
186 DeallocateSlabs(Slabs.begin(), Slabs.end());
187 DeallocateCustomSizedSlabs();
190 /// \brief Deallocate all but the current slab and reset the current pointer
191 /// to the beginning of it, freeing all memory allocated so far.
198 CurPtr = (char *)Slabs.front();
199 End = CurPtr + SlabSize;
201 // Deallocate all but the first slab, and all custome sized slabs.
202 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
203 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
204 DeallocateCustomSizedSlabs();
205 CustomSizedSlabs.clear();
208 /// \brief Allocate space at the specified alignment.
209 void *Allocate(size_t Size, size_t Alignment) {
210 if (!CurPtr) // Start a new slab if we haven't allocated one already.
213 // Keep track of how many bytes we've allocated.
214 BytesAllocated += Size;
216 // 0-byte alignment means 1-byte alignment.
220 // Allocate the aligned space, going forwards from CurPtr.
221 char *Ptr = alignPtr(CurPtr, Alignment);
223 // Check if we can hold it.
224 if (Ptr + Size <= End) {
226 // Update the allocation point of this memory block in MemorySanitizer.
227 // Without this, MemorySanitizer messages for values originated from here
228 // will point to the allocation of the entire slab.
229 __msan_allocated_memory(Ptr, Size);
233 // If Size is really big, allocate a separate slab for it.
234 size_t PaddedSize = Size + Alignment - 1;
235 if (PaddedSize > SizeThreshold) {
236 void *NewSlab = Allocator.Allocate(PaddedSize);
237 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
239 Ptr = alignPtr((char *)NewSlab, Alignment);
240 assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
241 __msan_allocated_memory(Ptr, Size);
245 // Otherwise, start a new slab and try again.
247 Ptr = alignPtr(CurPtr, Alignment);
249 assert(CurPtr <= End && "Unable to allocate memory!");
250 __msan_allocated_memory(Ptr, Size);
254 // Pull in base class overloads.
255 using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
257 void Deallocate(const void * /*Ptr*/) {}
259 // Pull in base class overloads.
260 using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
262 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
264 size_t getTotalMemory() const {
265 size_t TotalMemory = 0;
266 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
267 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
268 for (auto &PtrAndSize : CustomSizedSlabs)
269 TotalMemory += PtrAndSize.second;
273 void PrintStats() const {
274 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
279 /// \brief The current pointer into the current slab.
281 /// This points to the next free byte in the slab.
284 /// \brief The end of the current slab.
287 /// \brief The slabs allocated so far.
288 SmallVector<void *, 4> Slabs;
290 /// \brief Custom-sized slabs allocated for too-large allocation requests.
291 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
293 /// \brief How many bytes we've allocated.
295 /// Used so that we can compute how much space was wasted.
296 size_t BytesAllocated;
298 /// \brief The allocator instance we use to get slabs of memory.
299 AllocatorT Allocator;
301 static size_t computeSlabSize(unsigned SlabIdx) {
302 // Scale the actual allocated slab size based on the number of slabs
303 // allocated. Every 128 slabs allocated, we double the allocated size to
304 // reduce allocation frequency, but saturate at multiplying the slab size by
306 return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
309 /// \brief Allocate a new slab and move the bump pointers over into the new
310 /// slab, modifying CurPtr and End.
311 void StartNewSlab() {
312 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
314 void *NewSlab = Allocator.Allocate(AllocatedSlabSize);
315 Slabs.push_back(NewSlab);
316 CurPtr = (char *)(NewSlab);
317 End = ((char *)NewSlab) + AllocatedSlabSize;
320 /// \brief Deallocate a sequence of slabs.
321 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
322 SmallVectorImpl<void *>::iterator E) {
323 for (; I != E; ++I) {
324 size_t AllocatedSlabSize =
325 computeSlabSize(std::distance(Slabs.begin(), I));
327 // Poison the memory so stale pointers crash sooner. Note we must
328 // preserve the Size and NextPtr fields at the beginning.
329 sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
330 memset(*I, 0xCD, AllocatedSlabSize);
332 Allocator.Deallocate(*I, AllocatedSlabSize);
336 /// \brief Deallocate all memory for custom sized slabs.
337 void DeallocateCustomSizedSlabs() {
338 for (auto &PtrAndSize : CustomSizedSlabs) {
339 void *Ptr = PtrAndSize.first;
340 size_t Size = PtrAndSize.second;
342 // Poison the memory so stale pointers crash sooner. Note we must
343 // preserve the Size and NextPtr fields at the beginning.
344 sys::Memory::setRangeWritable(Ptr, Size);
345 memset(Ptr, 0xCD, Size);
347 Allocator.Deallocate(Ptr, Size);
351 template <typename T> friend class SpecificBumpPtrAllocator;
354 /// \brief The standard BumpPtrAllocator which just uses the default template
356 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
358 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
361 /// This allows calling the destructor in DestroyAll() and when the allocator is
363 template <typename T> class SpecificBumpPtrAllocator {
364 BumpPtrAllocator Allocator;
367 SpecificBumpPtrAllocator() : Allocator() {}
369 ~SpecificBumpPtrAllocator() { DestroyAll(); }
371 /// Call the destructor of each allocated object and deallocate all but the
372 /// current slab and reset the current pointer to the beginning of it, freeing
373 /// all memory allocated so far.
375 auto DestroyElements = [](char *Begin, char *End) {
376 assert(Begin == alignPtr(Begin, alignOf<T>()));
377 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
378 reinterpret_cast<T *>(Ptr)->~T();
381 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
383 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
384 std::distance(Allocator.Slabs.begin(), I));
385 char *Begin = alignPtr((char *)*I, alignOf<T>());
386 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
387 : (char *)*I + AllocatedSlabSize;
389 DestroyElements(Begin, End);
392 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
393 void *Ptr = PtrAndSize.first;
394 size_t Size = PtrAndSize.second;
395 DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
401 /// \brief Allocate space for an array of objects without constructing them.
402 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
407 } // end namespace llvm
409 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
410 void *operator new(size_t Size,
411 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
412 SizeThreshold> &Allocator) {
422 return Allocator.Allocate(
423 Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
426 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
427 void operator delete(
428 void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
431 #endif // LLVM_SUPPORT_ALLOCATOR_H