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