[Allocator] Hack around the fact that GCC can't compile the
[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 /// \file
10 ///
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
17 /// AllocatorBase.
18 ///
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_SUPPORT_ALLOCATOR_H
22 #define LLVM_SUPPORT_ALLOCATOR_H
23
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"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdlib>
33
34 namespace llvm {
35 template <typename T> struct ReferenceAdder {
36   typedef T &result;
37 };
38 template <typename T> struct ReferenceAdder<T &> {
39   typedef T result;
40 };
41
42 /// \brief CRTP base class providing obvious overloads for the core \c
43 /// Allocate() methods of LLVM-style allocators.
44 ///
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 {
49 public:
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) {
53 #ifdef __clang__
54     static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
55                       &AllocatorBase::Allocate) !=
56                       static_cast<void *(DerivedT::*)(size_t, size_t)>(
57                           &DerivedT::Allocate),
58                   "Class derives from AllocatorBase without implementing the "
59                   "core Allocate(size_t, size_t) overload!");
60 #endif
61     return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
62   }
63
64   /// \brief Allocate space for one object without constructing it.
65   template <typename T> T *Allocate() {
66     return static_cast<T *>(Allocate(sizeof(T), AlignOf<T>::Alignment));
67   }
68
69   /// \brief Allocate space for an array of objects without constructing them.
70   template <typename T> T *Allocate(size_t Num) {
71     return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
72   }
73
74   /// \brief Allocate space for an array of objects with the specified alignment
75   /// and without constructing them.
76   template <typename T> T *Allocate(size_t Num, size_t Alignment) {
77     // Round EltSize up to the specified alignment.
78     size_t EltSize = (sizeof(T) + Alignment - 1) & (-Alignment);
79     return static_cast<T *>(Allocate(Num * EltSize, Alignment));
80   }
81 };
82
83 class MallocAllocator : public AllocatorBase<MallocAllocator> {
84 public:
85   MallocAllocator() {}
86   ~MallocAllocator() {}
87
88   void Reset() {}
89
90   void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
91
92   // Pull in base class overloads.
93   using AllocatorBase<MallocAllocator>::Allocate;
94
95   void Deallocate(const void *Ptr) { free(const_cast<void *>(Ptr)); }
96
97   void PrintStats() const {}
98 };
99
100 /// MallocSlabAllocator - The default slab allocator for the bump allocator
101 /// is an adapter class for MallocAllocator that just forwards the method
102 /// calls and translates the arguments.
103 class MallocSlabAllocator {
104   /// Allocator - The underlying allocator that we forward to.
105   ///
106   MallocAllocator Allocator;
107
108 public:
109   void *Allocate(size_t Size) { return Allocator.Allocate(Size, 0); }
110   void Deallocate(void *Slab, size_t Size) { Allocator.Deallocate(Slab); }
111 };
112
113 namespace detail {
114
115 // We call out to an external function to actually print the message as the
116 // printing code uses Allocator.h in its implementation.
117 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
118                                 size_t TotalMemory);
119 } // End namespace detail.
120
121 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
122 ///
123 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
124 /// memory rather than relying on boundless contiguous heap. However, it has
125 /// bump-pointer semantics in that is a monotonically growing pool of memory
126 /// where every allocation is found by merely allocating the next N bytes in
127 /// the slab, or the next N bytes in the next slab.
128 ///
129 /// Note that this also has a threshold for forcing allocations above a certain
130 /// size into their own slab.
131 ///
132 /// The BumpPtrAllocatorImpl template defaults to using a MallocSlabAllocator
133 /// object, which wraps malloc, to allocate memory, but it can be changed to
134 /// use a custom allocator.
135 template <typename AllocatorT = MallocSlabAllocator, size_t SlabSize = 4096,
136           size_t SizeThreshold = SlabSize>
137 class BumpPtrAllocatorImpl
138     : public AllocatorBase<
139           BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
140   BumpPtrAllocatorImpl(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
141   void operator=(const BumpPtrAllocatorImpl &) LLVM_DELETED_FUNCTION;
142
143 public:
144   static_assert(SizeThreshold <= SlabSize,
145                 "The SizeThreshold must be at most the SlabSize to ensure "
146                 "that objects larger than a slab go into their own memory "
147                 "allocation.");
148
149   BumpPtrAllocatorImpl()
150       : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
151   template <typename T>
152   BumpPtrAllocatorImpl(T &&Allocator)
153       : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
154         Allocator(std::forward<T &&>(Allocator)) {}
155   ~BumpPtrAllocatorImpl() {
156     DeallocateSlabs(Slabs.begin(), Slabs.end());
157     DeallocateCustomSizedSlabs();
158   }
159
160   /// \brief Deallocate all but the current slab and reset the current pointer
161   /// to the beginning of it, freeing all memory allocated so far.
162   void Reset() {
163     if (Slabs.empty())
164       return;
165
166     // Reset the state.
167     BytesAllocated = 0;
168     CurPtr = (char *)Slabs.front();
169     End = CurPtr + SlabSize;
170
171     // Deallocate all but the first slab, and all custome sized slabs.
172     DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
173     Slabs.erase(std::next(Slabs.begin()), Slabs.end());
174     DeallocateCustomSizedSlabs();
175     CustomSizedSlabs.clear();
176   }
177
178   /// \brief Allocate space at the specified alignment.
179   void *Allocate(size_t Size, size_t Alignment) {
180     if (!CurPtr) // Start a new slab if we haven't allocated one already.
181       StartNewSlab();
182
183     // Keep track of how many bytes we've allocated.
184     BytesAllocated += Size;
185
186     // 0-byte alignment means 1-byte alignment.
187     if (Alignment == 0)
188       Alignment = 1;
189
190     // Allocate the aligned space, going forwards from CurPtr.
191     char *Ptr = alignPtr(CurPtr, Alignment);
192
193     // Check if we can hold it.
194     if (Ptr + Size <= End) {
195       CurPtr = Ptr + Size;
196       // Update the allocation point of this memory block in MemorySanitizer.
197       // Without this, MemorySanitizer messages for values originated from here
198       // will point to the allocation of the entire slab.
199       __msan_allocated_memory(Ptr, Size);
200       return Ptr;
201     }
202
203     // If Size is really big, allocate a separate slab for it.
204     size_t PaddedSize = Size + Alignment - 1;
205     if (PaddedSize > SizeThreshold) {
206       void *NewSlab = Allocator.Allocate(PaddedSize);
207       CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
208
209       Ptr = alignPtr((char *)NewSlab, Alignment);
210       assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + PaddedSize);
211       __msan_allocated_memory(Ptr, Size);
212       return Ptr;
213     }
214
215     // Otherwise, start a new slab and try again.
216     StartNewSlab();
217     Ptr = alignPtr(CurPtr, Alignment);
218     CurPtr = Ptr + Size;
219     assert(CurPtr <= End && "Unable to allocate memory!");
220     __msan_allocated_memory(Ptr, Size);
221     return Ptr;
222   }
223
224   // Pull in base class overloads.
225   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
226
227   void Deallocate(const void * /*Ptr*/) {}
228
229   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
230
231   size_t getTotalMemory() const {
232     size_t TotalMemory = 0;
233     for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
234       TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
235     for (auto &PtrAndSize : CustomSizedSlabs)
236       TotalMemory += PtrAndSize.second;
237     return TotalMemory;
238   }
239
240   void PrintStats() const {
241     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
242                                        getTotalMemory());
243   }
244
245 private:
246   /// \brief The current pointer into the current slab.
247   ///
248   /// This points to the next free byte in the slab.
249   char *CurPtr;
250
251   /// \brief The end of the current slab.
252   char *End;
253
254   /// \brief The slabs allocated so far.
255   SmallVector<void *, 4> Slabs;
256
257   /// \brief Custom-sized slabs allocated for too-large allocation requests.
258   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
259
260   /// \brief How many bytes we've allocated.
261   ///
262   /// Used so that we can compute how much space was wasted.
263   size_t BytesAllocated;
264
265   /// \brief The allocator instance we use to get slabs of memory.
266   AllocatorT Allocator;
267
268   static size_t computeSlabSize(unsigned SlabIdx) {
269     // Scale the actual allocated slab size based on the number of slabs
270     // allocated. Every 128 slabs allocated, we double the allocated size to
271     // reduce allocation frequency, but saturate at multiplying the slab size by
272     // 2^30.
273     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
274   }
275
276   /// \brief Allocate a new slab and move the bump pointers over into the new
277   /// slab, modifying CurPtr and End.
278   void StartNewSlab() {
279     size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
280
281     void *NewSlab = Allocator.Allocate(AllocatedSlabSize);
282     Slabs.push_back(NewSlab);
283     CurPtr = (char *)(NewSlab);
284     End = ((char *)NewSlab) + AllocatedSlabSize;
285   }
286
287   /// \brief Deallocate a sequence of slabs.
288   void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
289                        SmallVectorImpl<void *>::iterator E) {
290     for (; I != E; ++I) {
291       size_t AllocatedSlabSize =
292           computeSlabSize(std::distance(Slabs.begin(), I));
293 #ifndef NDEBUG
294       // Poison the memory so stale pointers crash sooner.  Note we must
295       // preserve the Size and NextPtr fields at the beginning.
296       sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
297       memset(*I, 0xCD, AllocatedSlabSize);
298 #endif
299       Allocator.Deallocate(*I, AllocatedSlabSize);
300     }
301   }
302
303   /// \brief Deallocate all memory for custom sized slabs.
304   void DeallocateCustomSizedSlabs() {
305     for (auto &PtrAndSize : CustomSizedSlabs) {
306       void *Ptr = PtrAndSize.first;
307       size_t Size = PtrAndSize.second;
308 #ifndef NDEBUG
309       // Poison the memory so stale pointers crash sooner.  Note we must
310       // preserve the Size and NextPtr fields at the beginning.
311       sys::Memory::setRangeWritable(Ptr, Size);
312       memset(Ptr, 0xCD, Size);
313 #endif
314       Allocator.Deallocate(Ptr, Size);
315     }
316   }
317
318   template <typename T> friend class SpecificBumpPtrAllocator;
319 };
320
321 /// \brief The standard BumpPtrAllocator which just uses the default template
322 /// paramaters.
323 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
324
325 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
326 /// allocated.
327 ///
328 /// This allows calling the destructor in DestroyAll() and when the allocator is
329 /// destroyed.
330 template <typename T> class SpecificBumpPtrAllocator {
331   BumpPtrAllocator Allocator;
332
333 public:
334   SpecificBumpPtrAllocator() : Allocator() {}
335
336   ~SpecificBumpPtrAllocator() { DestroyAll(); }
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 == alignPtr(Begin, alignOf<T>()));
344       for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
345         reinterpret_cast<T *>(Ptr)->~T();
346     };
347
348     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
349          ++I) {
350       size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
351           std::distance(Allocator.Slabs.begin(), I));
352       char *Begin = alignPtr((char *)*I, alignOf<T>());
353       char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
354                                                : (char *)*I + AllocatedSlabSize;
355
356       DestroyElements(Begin, End);
357     }
358
359     for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
360       void *Ptr = PtrAndSize.first;
361       size_t Size = PtrAndSize.second;
362       DestroyElements(alignPtr((char *)Ptr, alignOf<T>()), (char *)Ptr + Size);
363     }
364
365     Allocator.Reset();
366   }
367
368   /// \brief Allocate space for an array of objects without constructing them.
369   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
370
371 private:
372 };
373
374 }  // end namespace llvm
375
376 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
377 void *operator new(size_t Size,
378                    llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
379                                               SizeThreshold> &Allocator) {
380   struct S {
381     char c;
382     union {
383       double D;
384       long double LD;
385       long long L;
386       void *P;
387     } x;
388   };
389   return Allocator.Allocate(
390       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
391 }
392
393 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
394 void operator delete(
395     void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
396 }
397
398 #endif // LLVM_SUPPORT_ALLOCATOR_H