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