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 //===----------------------------------------------------------------------===//
10 // This file defines the MallocAllocator and BumpPtrAllocator interfaces.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_ALLOCATOR_H
15 #define LLVM_SUPPORT_ALLOCATOR_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Memory.h"
28 template <typename T> struct ReferenceAdder {
31 template <typename T> struct ReferenceAdder<T &> {
35 class MallocAllocator {
42 void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
44 template <typename T> T *Allocate() {
45 return static_cast<T *>(malloc(sizeof(T)));
48 template <typename T> T *Allocate(size_t Num) {
49 return static_cast<T *>(malloc(sizeof(T) * Num));
52 void Deallocate(const void *Ptr) { free(const_cast<void *>(Ptr)); }
54 void PrintStats() const {}
57 /// SlabAllocator - This class can be used to parameterize the underlying
58 /// allocation strategy for the bump allocator. In particular, this is used
59 /// by the JIT to allocate contiguous swathes of executable memory. The
60 /// interface uses MemSlab's instead of void *'s so that the allocator
61 /// doesn't have to remember the size of the pointer it allocated.
64 virtual ~SlabAllocator();
65 virtual void *Allocate(size_t Size) = 0;
66 virtual void Deallocate(void *Slab, size_t Size) = 0;
69 /// MallocSlabAllocator - The default slab allocator for the bump allocator
70 /// is an adapter class for MallocAllocator that just forwards the method
71 /// calls and translates the arguments.
72 class MallocSlabAllocator : public SlabAllocator {
73 /// Allocator - The underlying allocator that we forward to.
75 MallocAllocator Allocator;
78 MallocSlabAllocator() : Allocator() {}
79 virtual ~MallocSlabAllocator();
80 void *Allocate(size_t Size) override;
81 void Deallocate(void *Slab, size_t Size) override;
84 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
86 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
87 /// memory rather than relying on boundless contiguous heap. However, it has
88 /// bump-pointer semantics in that is a monotonically growing pool of memory
89 /// where every allocation is found by merely allocating the next N bytes in
90 /// the slab, or the next N bytes in the next slab.
92 /// Note that this also has a threshold for forcing allocations above a certain
93 /// size into their own slab.
94 template <size_t SlabSize = 4096, size_t SizeThreshold = SlabSize>
95 class BumpPtrAllocatorImpl {
96 BumpPtrAllocatorImpl(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
97 void operator=(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
100 static_assert(SizeThreshold <= SlabSize,
101 "The SizeThreshold must be at most the SlabSize to ensure "
102 "that objects larger than a slab go into their own memory "
105 BumpPtrAllocatorImpl()
106 : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
107 Allocator(DefaultSlabAllocator) {}
108 BumpPtrAllocatorImpl(SlabAllocator &Allocator)
109 : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator(Allocator) {
111 ~BumpPtrAllocatorImpl() {
112 DeallocateSlabs(Slabs.begin(), Slabs.end());
113 DeallocateCustomSizedSlabs();
116 /// \brief Deallocate all but the current slab and reset the current pointer
117 /// to the beginning of it, freeing all memory allocated so far.
124 CurPtr = (char *)Slabs.front();
125 End = CurPtr + SlabSize;
127 // Deallocate all but the first slab, and all custome sized slabs.
128 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
129 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
130 DeallocateCustomSizedSlabs();
131 CustomSizedSlabs.clear();
134 /// \brief Allocate space at the specified alignment.
135 void *Allocate(size_t Size, size_t Alignment) {
136 if (!CurPtr) // Start a new slab if we haven't allocated one already.
139 // Keep track of how many bytes we've allocated.
140 BytesAllocated += Size;
142 // 0-byte alignment means 1-byte alignment.
146 // Allocate the aligned space, going forwards from CurPtr.
147 char *Ptr = alignPtr(CurPtr, Alignment);
149 // Check if we can hold it.
150 if (Ptr + Size <= End) {
152 // Update the allocation point of this memory block in MemorySanitizer.
153 // Without this, MemorySanitizer messages for values originated from here
154 // will point to the allocation of the entire slab.
155 __msan_allocated_memory(Ptr, Size);
159 // If Size is really big, allocate a separate slab for it.
160 size_t PaddedSize = Size + Alignment - 1;
161 if (PaddedSize > SizeThreshold) {
162 void *NewSlab = Allocator.Allocate(PaddedSize);
163 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
165 Ptr = alignPtr((char *)NewSlab, Alignment);
166 assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
167 __msan_allocated_memory(Ptr, Size);
171 // Otherwise, start a new slab and try again.
173 Ptr = alignPtr(CurPtr, Alignment);
175 assert(CurPtr <= End && "Unable to allocate memory!");
176 __msan_allocated_memory(Ptr, Size);
180 /// \brief Allocate space for one object without constructing it.
181 template <typename T> T *Allocate() {
182 return static_cast<T *>(Allocate(sizeof(T), AlignOf<T>::Alignment));
185 /// \brief Allocate space for an array of objects without constructing them.
186 template <typename T> T *Allocate(size_t Num) {
187 return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
190 /// \brief Allocate space for an array of objects with the specified alignment
191 /// and without constructing them.
192 template <typename T> T *Allocate(size_t Num, size_t Alignment) {
193 // Round EltSize up to the specified alignment.
194 size_t EltSize = (sizeof(T) + Alignment - 1) & (-Alignment);
195 return static_cast<T *>(Allocate(Num * EltSize, Alignment));
198 void Deallocate(const void * /*Ptr*/) {}
200 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
202 size_t getTotalMemory() const {
203 size_t TotalMemory = 0;
204 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
205 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
206 for (auto &PtrAndSize : CustomSizedSlabs)
207 TotalMemory += PtrAndSize.second;
211 void PrintStats() const {
212 // We call out to an external function to actually print the message as the
213 // printing code uses Allocator.h in its implementation.
214 extern void printBumpPtrAllocatorStats(
215 unsigned NumSlabs, size_t BytesAllocated, size_t TotalMemory);
217 printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated, getTotalMemory());
221 /// \brief The current pointer into the current slab.
223 /// This points to the next free byte in the slab.
226 /// \brief The end of the current slab.
229 /// \brief The slabs allocated so far.
230 SmallVector<void *, 4> Slabs;
232 /// \brief Custom-sized slabs allocated for too-large allocation requests.
233 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
235 /// \brief How many bytes we've allocated.
237 /// Used so that we can compute how much space was wasted.
238 size_t BytesAllocated;
240 /// \brief The default allocator used if one is not provided.
241 MallocSlabAllocator DefaultSlabAllocator;
243 /// \brief The underlying allocator we use to get slabs of memory.
245 /// This defaults to MallocSlabAllocator, which wraps malloc, but it could be
246 /// changed to use a custom allocator.
247 SlabAllocator &Allocator;
249 static size_t computeSlabSize(unsigned SlabIdx) {
250 // Scale the actual allocated slab size based on the number of slabs
251 // allocated. Every 128 slabs allocated, we double the allocated size to
252 // reduce allocation frequency, but saturate at multiplying the slab size by
254 return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
257 /// \brief Allocate a new slab and move the bump pointers over into the new
258 /// slab, modifying CurPtr and End.
259 void StartNewSlab() {
260 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
262 void *NewSlab = Allocator.Allocate(AllocatedSlabSize);
263 Slabs.push_back(NewSlab);
264 CurPtr = (char *)(NewSlab);
265 End = ((char *)NewSlab) + AllocatedSlabSize;
268 /// \brief Deallocate a sequence of slabs.
269 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
270 SmallVectorImpl<void *>::iterator E) {
271 for (; I != E; ++I) {
272 size_t AllocatedSlabSize =
273 computeSlabSize(std::distance(Slabs.begin(), I));
275 // Poison the memory so stale pointers crash sooner. Note we must
276 // preserve the Size and NextPtr fields at the beginning.
277 sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
278 memset(*I, 0xCD, AllocatedSlabSize);
280 Allocator.Deallocate(*I, AllocatedSlabSize);
284 /// \brief Deallocate all memory for custom sized slabs.
285 void DeallocateCustomSizedSlabs() {
286 for (auto &PtrAndSize : CustomSizedSlabs) {
287 void *Ptr = PtrAndSize.first;
289 size_t Size = PtrAndSize.second;
290 // Poison the memory so stale pointers crash sooner. Note we must
291 // preserve the Size and NextPtr fields at the beginning.
292 sys::Memory::setRangeWritable(Ptr, Size);
293 memset(Ptr, 0xCD, Size);
295 Allocator.Deallocate(Ptr, Size);
299 template <typename T> friend class SpecificBumpPtrAllocator;
302 /// \brief The standard BumpPtrAllocator which just uses the default template
304 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
306 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
309 /// This allows calling the destructor in DestroyAll() and when the allocator is
311 template <typename T> class SpecificBumpPtrAllocator {
312 BumpPtrAllocator Allocator;
315 SpecificBumpPtrAllocator() : Allocator() {}
316 SpecificBumpPtrAllocator(SlabAllocator &allocator) : Allocator(allocator) {}
318 ~SpecificBumpPtrAllocator() { DestroyAll(); }
320 /// Call the destructor of each allocated object and deallocate all but the
321 /// current slab and reset the current pointer to the beginning of it, freeing
322 /// all memory allocated so far.
324 auto DestroyElements = [](char *Begin, char *End) {
325 assert(Begin == alignPtr(Begin, alignOf<T>()));
326 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
327 reinterpret_cast<T *>(Ptr)->~T();
330 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
332 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
333 std::distance(Allocator.Slabs.begin(), I));
334 char *Begin = alignPtr((char *)*I, alignOf<T>());
335 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
336 : (char *)*I + AllocatedSlabSize;
338 DestroyElements(Begin, End);
341 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
342 void *Ptr = PtrAndSize.first;
343 size_t Size = PtrAndSize.second;
344 DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
350 /// \brief Allocate space for an array of objects without constructing them.
351 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
356 } // end namespace llvm
358 template <size_t SlabSize, size_t SizeThreshold>
360 operator new(size_t Size,
361 llvm::BumpPtrAllocatorImpl<SlabSize, SizeThreshold> &Allocator) {
371 return Allocator.Allocate(
372 Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
375 template <size_t SlabSize, size_t SizeThreshold>
376 void operator delete(void *,
377 llvm::BumpPtrAllocatorImpl<SlabSize, SizeThreshold> &) {}
379 #endif // LLVM_SUPPORT_ALLOCATOR_H