LLVM  mainline
Allocator.h
Go to the documentation of this file.
00001 //===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 ///
00011 /// This file defines the MallocAllocator and BumpPtrAllocator interfaces. Both
00012 /// of these conform to an LLVM "Allocator" concept which consists of an
00013 /// Allocate method accepting a size and alignment, and a Deallocate accepting
00014 /// a pointer and size. Further, the LLVM "Allocator" concept has overloads of
00015 /// Allocate and Deallocate for setting size and alignment based on the final
00016 /// type. These overloads are typically provided by a base class template \c
00017 /// AllocatorBase.
00018 ///
00019 //===----------------------------------------------------------------------===//
00020 
00021 #ifndef LLVM_SUPPORT_ALLOCATOR_H
00022 #define LLVM_SUPPORT_ALLOCATOR_H
00023 
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/Support/AlignOf.h"
00026 #include "llvm/Support/DataTypes.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Support/Memory.h"
00029 #include <algorithm>
00030 #include <cassert>
00031 #include <cstddef>
00032 #include <cstdlib>
00033 
00034 namespace llvm {
00035 
00036 /// \brief CRTP base class providing obvious overloads for the core \c
00037 /// Allocate() methods of LLVM-style allocators.
00038 ///
00039 /// This base class both documents the full public interface exposed by all
00040 /// LLVM-style allocators, and redirects all of the overloads to a single core
00041 /// set of methods which the derived class must define.
00042 template <typename DerivedT> class AllocatorBase {
00043 public:
00044   /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method
00045   /// must be implemented by \c DerivedT.
00046   void *Allocate(size_t Size, size_t Alignment) {
00047 #ifdef __clang__
00048     static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>(
00049                       &AllocatorBase::Allocate) !=
00050                       static_cast<void *(DerivedT::*)(size_t, size_t)>(
00051                           &DerivedT::Allocate),
00052                   "Class derives from AllocatorBase without implementing the "
00053                   "core Allocate(size_t, size_t) overload!");
00054 #endif
00055     return static_cast<DerivedT *>(this)->Allocate(Size, Alignment);
00056   }
00057 
00058   /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this
00059   /// allocator.
00060   void Deallocate(const void *Ptr, size_t Size) {
00061 #ifdef __clang__
00062     static_assert(static_cast<void (AllocatorBase::*)(const void *, size_t)>(
00063                       &AllocatorBase::Deallocate) !=
00064                       static_cast<void (DerivedT::*)(const void *, size_t)>(
00065                           &DerivedT::Deallocate),
00066                   "Class derives from AllocatorBase without implementing the "
00067                   "core Deallocate(void *) overload!");
00068 #endif
00069     return static_cast<DerivedT *>(this)->Deallocate(Ptr, Size);
00070   }
00071 
00072   // The rest of these methods are helpers that redirect to one of the above
00073   // core methods.
00074 
00075   /// \brief Allocate space for a sequence of objects without constructing them.
00076   template <typename T> T *Allocate(size_t Num = 1) {
00077     return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
00078   }
00079 
00080   /// \brief Deallocate space for a sequence of objects without constructing them.
00081   template <typename T>
00082   typename std::enable_if<
00083       !std::is_same<typename std::remove_cv<T>::type, void>::value, void>::type
00084   Deallocate(T *Ptr, size_t Num = 1) {
00085     Deallocate(static_cast<const void *>(Ptr), Num * sizeof(T));
00086   }
00087 };
00088 
00089 class MallocAllocator : public AllocatorBase<MallocAllocator> {
00090 public:
00091   void Reset() {}
00092 
00093   LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size,
00094                                                 size_t /*Alignment*/) {
00095     return malloc(Size);
00096   }
00097 
00098   // Pull in base class overloads.
00099   using AllocatorBase<MallocAllocator>::Allocate;
00100 
00101   void Deallocate(const void *Ptr, size_t /*Size*/) {
00102     free(const_cast<void *>(Ptr));
00103   }
00104 
00105   // Pull in base class overloads.
00106   using AllocatorBase<MallocAllocator>::Deallocate;
00107 
00108   void PrintStats() const {}
00109 };
00110 
00111 namespace detail {
00112 
00113 // We call out to an external function to actually print the message as the
00114 // printing code uses Allocator.h in its implementation.
00115 void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
00116                                 size_t TotalMemory);
00117 } // End namespace detail.
00118 
00119 /// \brief Allocate memory in an ever growing pool, as if by bump-pointer.
00120 ///
00121 /// This isn't strictly a bump-pointer allocator as it uses backing slabs of
00122 /// memory rather than relying on a boundless contiguous heap. However, it has
00123 /// bump-pointer semantics in that it is a monotonically growing pool of memory
00124 /// where every allocation is found by merely allocating the next N bytes in
00125 /// the slab, or the next N bytes in the next slab.
00126 ///
00127 /// Note that this also has a threshold for forcing allocations above a certain
00128 /// size into their own slab.
00129 ///
00130 /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
00131 /// object, which wraps malloc, to allocate memory, but it can be changed to
00132 /// use a custom allocator.
00133 template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
00134           size_t SizeThreshold = SlabSize>
00135 class BumpPtrAllocatorImpl
00136     : public AllocatorBase<
00137           BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> {
00138 public:
00139   static_assert(SizeThreshold <= SlabSize,
00140                 "The SizeThreshold must be at most the SlabSize to ensure "
00141                 "that objects larger than a slab go into their own memory "
00142                 "allocation.");
00143 
00144   BumpPtrAllocatorImpl()
00145       : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {}
00146   template <typename T>
00147   BumpPtrAllocatorImpl(T &&Allocator)
00148       : CurPtr(nullptr), End(nullptr), BytesAllocated(0),
00149         Allocator(std::forward<T &&>(Allocator)) {}
00150 
00151   // Manually implement a move constructor as we must clear the old allocator's
00152   // slabs as a matter of correctness.
00153   BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
00154       : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)),
00155         CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
00156         BytesAllocated(Old.BytesAllocated),
00157         Allocator(std::move(Old.Allocator)) {
00158     Old.CurPtr = Old.End = nullptr;
00159     Old.BytesAllocated = 0;
00160     Old.Slabs.clear();
00161     Old.CustomSizedSlabs.clear();
00162   }
00163 
00164   ~BumpPtrAllocatorImpl() {
00165     DeallocateSlabs(Slabs.begin(), Slabs.end());
00166     DeallocateCustomSizedSlabs();
00167   }
00168 
00169   BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
00170     DeallocateSlabs(Slabs.begin(), Slabs.end());
00171     DeallocateCustomSizedSlabs();
00172 
00173     CurPtr = RHS.CurPtr;
00174     End = RHS.End;
00175     BytesAllocated = RHS.BytesAllocated;
00176     Slabs = std::move(RHS.Slabs);
00177     CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
00178     Allocator = std::move(RHS.Allocator);
00179 
00180     RHS.CurPtr = RHS.End = nullptr;
00181     RHS.BytesAllocated = 0;
00182     RHS.Slabs.clear();
00183     RHS.CustomSizedSlabs.clear();
00184     return *this;
00185   }
00186 
00187   /// \brief Deallocate all but the current slab and reset the current pointer
00188   /// to the beginning of it, freeing all memory allocated so far.
00189   void Reset() {
00190     DeallocateCustomSizedSlabs();
00191     CustomSizedSlabs.clear();
00192 
00193     if (Slabs.empty())
00194       return;
00195 
00196     // Reset the state.
00197     BytesAllocated = 0;
00198     CurPtr = (char *)Slabs.front();
00199     End = CurPtr + SlabSize;
00200 
00201     // Deallocate all but the first slab, and deallocate all custom-sized slabs.
00202     DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
00203     Slabs.erase(std::next(Slabs.begin()), Slabs.end());
00204   }
00205 
00206   /// \brief Allocate space at the specified alignment.
00207   LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
00208   Allocate(size_t Size, size_t Alignment) {
00209     assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead.");
00210 
00211     // Keep track of how many bytes we've allocated.
00212     BytesAllocated += Size;
00213 
00214     size_t Adjustment = alignmentAdjustment(CurPtr, Alignment);
00215     assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow");
00216 
00217     // Check if we have enough space.
00218     if (Adjustment + Size <= size_t(End - CurPtr)) {
00219       char *AlignedPtr = CurPtr + Adjustment;
00220       CurPtr = AlignedPtr + Size;
00221       // Update the allocation point of this memory block in MemorySanitizer.
00222       // Without this, MemorySanitizer messages for values originated from here
00223       // will point to the allocation of the entire slab.
00224       __msan_allocated_memory(AlignedPtr, Size);
00225       return AlignedPtr;
00226     }
00227 
00228     // If Size is really big, allocate a separate slab for it.
00229     size_t PaddedSize = Size + Alignment - 1;
00230     if (PaddedSize > SizeThreshold) {
00231       void *NewSlab = Allocator.Allocate(PaddedSize, 0);
00232       CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
00233 
00234       uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
00235       assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
00236       char *AlignedPtr = (char*)AlignedAddr;
00237       __msan_allocated_memory(AlignedPtr, Size);
00238       return AlignedPtr;
00239     }
00240 
00241     // Otherwise, start a new slab and try again.
00242     StartNewSlab();
00243     uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
00244     assert(AlignedAddr + Size <= (uintptr_t)End &&
00245            "Unable to allocate memory!");
00246     char *AlignedPtr = (char*)AlignedAddr;
00247     CurPtr = AlignedPtr + Size;
00248     __msan_allocated_memory(AlignedPtr, Size);
00249     return AlignedPtr;
00250   }
00251 
00252   // Pull in base class overloads.
00253   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
00254 
00255   void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
00256 
00257   // Pull in base class overloads.
00258   using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
00259 
00260   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
00261 
00262   size_t getTotalMemory() const {
00263     size_t TotalMemory = 0;
00264     for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
00265       TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
00266     for (auto &PtrAndSize : CustomSizedSlabs)
00267       TotalMemory += PtrAndSize.second;
00268     return TotalMemory;
00269   }
00270 
00271   void PrintStats() const {
00272     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
00273                                        getTotalMemory());
00274   }
00275 
00276 private:
00277   /// \brief The current pointer into the current slab.
00278   ///
00279   /// This points to the next free byte in the slab.
00280   char *CurPtr;
00281 
00282   /// \brief The end of the current slab.
00283   char *End;
00284 
00285   /// \brief The slabs allocated so far.
00286   SmallVector<void *, 4> Slabs;
00287 
00288   /// \brief Custom-sized slabs allocated for too-large allocation requests.
00289   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
00290 
00291   /// \brief How many bytes we've allocated.
00292   ///
00293   /// Used so that we can compute how much space was wasted.
00294   size_t BytesAllocated;
00295 
00296   /// \brief The allocator instance we use to get slabs of memory.
00297   AllocatorT Allocator;
00298 
00299   static size_t computeSlabSize(unsigned SlabIdx) {
00300     // Scale the actual allocated slab size based on the number of slabs
00301     // allocated. Every 128 slabs allocated, we double the allocated size to
00302     // reduce allocation frequency, but saturate at multiplying the slab size by
00303     // 2^30.
00304     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
00305   }
00306 
00307   /// \brief Allocate a new slab and move the bump pointers over into the new
00308   /// slab, modifying CurPtr and End.
00309   void StartNewSlab() {
00310     size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
00311 
00312     void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
00313     Slabs.push_back(NewSlab);
00314     CurPtr = (char *)(NewSlab);
00315     End = ((char *)NewSlab) + AllocatedSlabSize;
00316   }
00317 
00318   /// \brief Deallocate a sequence of slabs.
00319   void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
00320                        SmallVectorImpl<void *>::iterator E) {
00321     for (; I != E; ++I) {
00322       size_t AllocatedSlabSize =
00323           computeSlabSize(std::distance(Slabs.begin(), I));
00324       Allocator.Deallocate(*I, AllocatedSlabSize);
00325     }
00326   }
00327 
00328   /// \brief Deallocate all memory for custom sized slabs.
00329   void DeallocateCustomSizedSlabs() {
00330     for (auto &PtrAndSize : CustomSizedSlabs) {
00331       void *Ptr = PtrAndSize.first;
00332       size_t Size = PtrAndSize.second;
00333       Allocator.Deallocate(Ptr, Size);
00334     }
00335   }
00336 
00337   template <typename T> friend class SpecificBumpPtrAllocator;
00338 };
00339 
00340 /// \brief The standard BumpPtrAllocator which just uses the default template
00341 /// paramaters.
00342 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
00343 
00344 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
00345 /// allocated.
00346 ///
00347 /// This allows calling the destructor in DestroyAll() and when the allocator is
00348 /// destroyed.
00349 template <typename T> class SpecificBumpPtrAllocator {
00350   BumpPtrAllocator Allocator;
00351 
00352 public:
00353   SpecificBumpPtrAllocator() : Allocator() {}
00354   SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
00355       : Allocator(std::move(Old.Allocator)) {}
00356   ~SpecificBumpPtrAllocator() { DestroyAll(); }
00357 
00358   SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
00359     Allocator = std::move(RHS.Allocator);
00360     return *this;
00361   }
00362 
00363   /// Call the destructor of each allocated object and deallocate all but the
00364   /// current slab and reset the current pointer to the beginning of it, freeing
00365   /// all memory allocated so far.
00366   void DestroyAll() {
00367     auto DestroyElements = [](char *Begin, char *End) {
00368       assert(Begin == (char*)alignAddr(Begin, alignOf<T>()));
00369       for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
00370         reinterpret_cast<T *>(Ptr)->~T();
00371     };
00372 
00373     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
00374          ++I) {
00375       size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
00376           std::distance(Allocator.Slabs.begin(), I));
00377       char *Begin = (char*)alignAddr(*I, alignOf<T>());
00378       char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
00379                                                : (char *)*I + AllocatedSlabSize;
00380 
00381       DestroyElements(Begin, End);
00382     }
00383 
00384     for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
00385       void *Ptr = PtrAndSize.first;
00386       size_t Size = PtrAndSize.second;
00387       DestroyElements((char*)alignAddr(Ptr, alignOf<T>()), (char *)Ptr + Size);
00388     }
00389 
00390     Allocator.Reset();
00391   }
00392 
00393   /// \brief Allocate space for an array of objects without constructing them.
00394   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
00395 };
00396 
00397 }  // end namespace llvm
00398 
00399 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00400 void *operator new(size_t Size,
00401                    llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
00402                                               SizeThreshold> &Allocator) {
00403   struct S {
00404     char c;
00405     union {
00406       double D;
00407       long double LD;
00408       long long L;
00409       void *P;
00410     } x;
00411   };
00412   return Allocator.Allocate(
00413       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
00414 }
00415 
00416 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00417 void operator delete(
00418     void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
00419 }
00420 
00421 #endif // LLVM_SUPPORT_ALLOCATOR_H