9e567e567af0ff3f61a5df403ad54ae83bbf1af8
[oota-llvm.git] / include / llvm / Support / Allocator.h
1 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MallocAllocator and BumpPtrAllocator interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_ALLOCATOR_H
15 #define LLVM_SUPPORT_ALLOCATOR_H
16
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"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstddef>
25 #include <cstdlib>
26
27 namespace llvm {
28 template <typename T> struct ReferenceAdder {
29   typedef T &result;
30 };
31 template <typename T> struct ReferenceAdder<T &> {
32   typedef T result;
33 };
34
35 class MallocAllocator {
36 public:
37   MallocAllocator() {}
38   ~MallocAllocator() {}
39
40   void Reset() {}
41
42   void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
43
44   template <typename T> T *Allocate() {
45     return static_cast<T *>(malloc(sizeof(T)));
46   }
47
48   template <typename T> T *Allocate(size_t Num) {
49     return static_cast<T *>(malloc(sizeof(T) * Num));
50   }
51
52   void Deallocate(const void *Ptr) { free(const_cast<void *>(Ptr)); }
53
54   void PrintStats() const {}
55 };
56
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.
62 class SlabAllocator {
63 public:
64   virtual ~SlabAllocator();
65   virtual void *Allocate(size_t Size) = 0;
66   virtual void Deallocate(void *Slab, size_t Size) = 0;
67 };
68
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.
74   ///
75   MallocAllocator Allocator;
76
77 public:
78   MallocSlabAllocator() : Allocator() {}
79   virtual ~MallocSlabAllocator();
80   void *Allocate(size_t Size) override;
81   void Deallocate(void *Slab, size_t Size) override;
82 };
83
84 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
85 ///
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.
91 ///
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;
98
99 public:
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 "
103                 "allocation.");
104
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) {
110   }
111   ~BumpPtrAllocatorImpl() {
112     DeallocateSlabs(Slabs.begin(), Slabs.end());
113     DeallocateCustomSizedSlabs();
114   }
115
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.
118   void Reset() {
119     if (Slabs.empty())
120       return;
121
122     // Reset the state.
123     BytesAllocated = 0;
124     CurPtr = (char *)Slabs.front();
125     End = CurPtr + SlabSize;
126
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();
132   }
133
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.
137       StartNewSlab();
138
139     // Keep track of how many bytes we've allocated.
140     BytesAllocated += Size;
141
142     // 0-byte alignment means 1-byte alignment.
143     if (Alignment == 0)
144       Alignment = 1;
145
146     // Allocate the aligned space, going forwards from CurPtr.
147     char *Ptr = alignPtr(CurPtr, Alignment);
148
149     // Check if we can hold it.
150     if (Ptr + Size <= End) {
151       CurPtr = Ptr + Size;
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);
156       return Ptr;
157     }
158
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));
164
165       Ptr = alignPtr((char *)NewSlab, Alignment);
166       assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
167       __msan_allocated_memory(Ptr, Size);
168       return Ptr;
169     }
170
171     // Otherwise, start a new slab and try again.
172     StartNewSlab();
173     Ptr = alignPtr(CurPtr, Alignment);
174     CurPtr = Ptr + Size;
175     assert(CurPtr <= End && "Unable to allocate memory!");
176     __msan_allocated_memory(Ptr, Size);
177     return Ptr;
178   }
179
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));
183   }
184
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));
188   }
189
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));
196   }
197
198   void Deallocate(const void * /*Ptr*/) {}
199
200   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
201
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;
208     return TotalMemory;
209   }
210
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);
216
217     printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated, getTotalMemory());
218   }
219
220 private:
221   /// \brief The current pointer into the current slab.
222   ///
223   /// This points to the next free byte in the slab.
224   char *CurPtr;
225
226   /// \brief The end of the current slab.
227   char *End;
228
229   /// \brief The slabs allocated so far.
230   SmallVector<void *, 4> Slabs;
231
232   /// \brief Custom-sized slabs allocated for too-large allocation requests.
233   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
234
235   /// \brief How many bytes we've allocated.
236   ///
237   /// Used so that we can compute how much space was wasted.
238   size_t BytesAllocated;
239
240   /// \brief The default allocator used if one is not provided.
241   MallocSlabAllocator DefaultSlabAllocator;
242
243   /// \brief The underlying allocator we use to get slabs of memory.
244   ///
245   /// This defaults to MallocSlabAllocator, which wraps malloc, but it could be
246   /// changed to use a custom allocator.
247   SlabAllocator &Allocator;
248
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
253     // 2^30.
254     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
255   }
256
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());
261
262     void *NewSlab = Allocator.Allocate(AllocatedSlabSize);
263     Slabs.push_back(NewSlab);
264     CurPtr = (char *)(NewSlab);
265     End = ((char *)NewSlab) + AllocatedSlabSize;
266   }
267
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));
274 #ifndef NDEBUG
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);
279 #endif
280       Allocator.Deallocate(*I, AllocatedSlabSize);
281     }
282   }
283
284   /// \brief Deallocate all memory for custom sized slabs.
285   void DeallocateCustomSizedSlabs() {
286     for (auto &PtrAndSize : CustomSizedSlabs) {
287       void *Ptr = PtrAndSize.first;
288       size_t Size = PtrAndSize.second;
289 #ifndef NDEBUG
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);
294 #endif
295       Allocator.Deallocate(Ptr, Size);
296     }
297   }
298
299   template <typename T> friend class SpecificBumpPtrAllocator;
300 };
301
302 /// \brief The standard BumpPtrAllocator which just uses the default template
303 /// paramaters.
304 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
305
306 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
307 /// allocated.
308 ///
309 /// This allows calling the destructor in DestroyAll() and when the allocator is
310 /// destroyed.
311 template <typename T> class SpecificBumpPtrAllocator {
312   BumpPtrAllocator Allocator;
313
314 public:
315   SpecificBumpPtrAllocator() : Allocator() {}
316   SpecificBumpPtrAllocator(SlabAllocator &allocator) : Allocator(allocator) {}
317
318   ~SpecificBumpPtrAllocator() { DestroyAll(); }
319
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.
323   void DestroyAll() {
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();
328     };
329
330     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
331          ++I) {
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;
337
338       DestroyElements(Begin, End);
339     }
340
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);
345     }
346
347     Allocator.Reset();
348   }
349
350   /// \brief Allocate space for an array of objects without constructing them.
351   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
352
353 private:
354 };
355
356 }  // end namespace llvm
357
358 template <size_t SlabSize, size_t SizeThreshold>
359 void *
360 operator new(size_t Size,
361              llvm::BumpPtrAllocatorImpl<SlabSize, SizeThreshold> &Allocator) {
362   struct S {
363     char c;
364     union {
365       double D;
366       long double LD;
367       long long L;
368       void *P;
369     } x;
370   };
371   return Allocator.Allocate(
372       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
373 }
374
375 template <size_t SlabSize, size_t SizeThreshold>
376 void operator delete(void *,
377                      llvm::BumpPtrAllocatorImpl<SlabSize, SizeThreshold> &) {}
378
379 #endif // LLVM_SUPPORT_ALLOCATOR_H