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 allocators
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     if (Slabs.empty())
00191       return;
00192 
00193     // Reset the state.
00194     BytesAllocated = 0;
00195     CurPtr = (char *)Slabs.front();
00196     End = CurPtr + SlabSize;
00197 
00198     // Deallocate all but the first slab, and all custome sized slabs.
00199     DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
00200     Slabs.erase(std::next(Slabs.begin()), Slabs.end());
00201     DeallocateCustomSizedSlabs();
00202     CustomSizedSlabs.clear();
00203   }
00204 
00205   /// \brief Allocate space at the specified alignment.
00206   LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
00207   Allocate(size_t Size, size_t Alignment) {
00208     assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead.");
00209 
00210     // Keep track of how many bytes we've allocated.
00211     BytesAllocated += Size;
00212 
00213     size_t Adjustment = alignmentAdjustment(CurPtr, Alignment);
00214     assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow");
00215 
00216     // Check if we have enough space.
00217     if (Adjustment + Size <= size_t(End - CurPtr)) {
00218       char *AlignedPtr = CurPtr + Adjustment;
00219       CurPtr = AlignedPtr + Size;
00220       // Update the allocation point of this memory block in MemorySanitizer.
00221       // Without this, MemorySanitizer messages for values originated from here
00222       // will point to the allocation of the entire slab.
00223       __msan_allocated_memory(AlignedPtr, Size);
00224       return AlignedPtr;
00225     }
00226 
00227     // If Size is really big, allocate a separate slab for it.
00228     size_t PaddedSize = Size + Alignment - 1;
00229     if (PaddedSize > SizeThreshold) {
00230       void *NewSlab = Allocator.Allocate(PaddedSize, 0);
00231       CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
00232 
00233       uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
00234       assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize);
00235       char *AlignedPtr = (char*)AlignedAddr;
00236       __msan_allocated_memory(AlignedPtr, Size);
00237       return AlignedPtr;
00238     }
00239 
00240     // Otherwise, start a new slab and try again.
00241     StartNewSlab();
00242     uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
00243     assert(AlignedAddr + Size <= (uintptr_t)End &&
00244            "Unable to allocate memory!");
00245     char *AlignedPtr = (char*)AlignedAddr;
00246     CurPtr = AlignedPtr + Size;
00247     __msan_allocated_memory(AlignedPtr, Size);
00248     return AlignedPtr;
00249   }
00250 
00251   // Pull in base class overloads.
00252   using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
00253 
00254   void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {}
00255 
00256   // Pull in base class overloads.
00257   using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
00258 
00259   size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
00260 
00261   size_t getTotalMemory() const {
00262     size_t TotalMemory = 0;
00263     for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
00264       TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
00265     for (auto &PtrAndSize : CustomSizedSlabs)
00266       TotalMemory += PtrAndSize.second;
00267     return TotalMemory;
00268   }
00269 
00270   void PrintStats() const {
00271     detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
00272                                        getTotalMemory());
00273   }
00274 
00275 private:
00276   /// \brief The current pointer into the current slab.
00277   ///
00278   /// This points to the next free byte in the slab.
00279   char *CurPtr;
00280 
00281   /// \brief The end of the current slab.
00282   char *End;
00283 
00284   /// \brief The slabs allocated so far.
00285   SmallVector<void *, 4> Slabs;
00286 
00287   /// \brief Custom-sized slabs allocated for too-large allocation requests.
00288   SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
00289 
00290   /// \brief How many bytes we've allocated.
00291   ///
00292   /// Used so that we can compute how much space was wasted.
00293   size_t BytesAllocated;
00294 
00295   /// \brief The allocator instance we use to get slabs of memory.
00296   AllocatorT Allocator;
00297 
00298   static size_t computeSlabSize(unsigned SlabIdx) {
00299     // Scale the actual allocated slab size based on the number of slabs
00300     // allocated. Every 128 slabs allocated, we double the allocated size to
00301     // reduce allocation frequency, but saturate at multiplying the slab size by
00302     // 2^30.
00303     return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128));
00304   }
00305 
00306   /// \brief Allocate a new slab and move the bump pointers over into the new
00307   /// slab, modifying CurPtr and End.
00308   void StartNewSlab() {
00309     size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
00310 
00311     void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0);
00312     Slabs.push_back(NewSlab);
00313     CurPtr = (char *)(NewSlab);
00314     End = ((char *)NewSlab) + AllocatedSlabSize;
00315   }
00316 
00317   /// \brief Deallocate a sequence of slabs.
00318   void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
00319                        SmallVectorImpl<void *>::iterator E) {
00320     for (; I != E; ++I) {
00321       size_t AllocatedSlabSize =
00322           computeSlabSize(std::distance(Slabs.begin(), I));
00323 #ifndef NDEBUG
00324       // Poison the memory so stale pointers crash sooner.  Note we must
00325       // preserve the Size and NextPtr fields at the beginning.
00326       if (AllocatedSlabSize != 0) {
00327         sys::Memory::setRangeWritable(*I, AllocatedSlabSize);
00328         memset(*I, 0xCD, AllocatedSlabSize);
00329       }
00330 #endif
00331       Allocator.Deallocate(*I, AllocatedSlabSize);
00332     }
00333   }
00334 
00335   /// \brief Deallocate all memory for custom sized slabs.
00336   void DeallocateCustomSizedSlabs() {
00337     for (auto &PtrAndSize : CustomSizedSlabs) {
00338       void *Ptr = PtrAndSize.first;
00339       size_t Size = PtrAndSize.second;
00340 #ifndef NDEBUG
00341       // Poison the memory so stale pointers crash sooner.  Note we must
00342       // preserve the Size and NextPtr fields at the beginning.
00343       sys::Memory::setRangeWritable(Ptr, Size);
00344       memset(Ptr, 0xCD, Size);
00345 #endif
00346       Allocator.Deallocate(Ptr, Size);
00347     }
00348   }
00349 
00350   template <typename T> friend class SpecificBumpPtrAllocator;
00351 };
00352 
00353 /// \brief The standard BumpPtrAllocator which just uses the default template
00354 /// paramaters.
00355 typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
00356 
00357 /// \brief A BumpPtrAllocator that allows only elements of a specific type to be
00358 /// allocated.
00359 ///
00360 /// This allows calling the destructor in DestroyAll() and when the allocator is
00361 /// destroyed.
00362 template <typename T> class SpecificBumpPtrAllocator {
00363   BumpPtrAllocator Allocator;
00364 
00365 public:
00366   SpecificBumpPtrAllocator() : Allocator() {}
00367   SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
00368       : Allocator(std::move(Old.Allocator)) {}
00369   ~SpecificBumpPtrAllocator() { DestroyAll(); }
00370 
00371   SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
00372     Allocator = std::move(RHS.Allocator);
00373     return *this;
00374   }
00375 
00376   /// Call the destructor of each allocated object and deallocate all but the
00377   /// current slab and reset the current pointer to the beginning of it, freeing
00378   /// all memory allocated so far.
00379   void DestroyAll() {
00380     auto DestroyElements = [](char *Begin, char *End) {
00381       assert(Begin == (char*)alignAddr(Begin, alignOf<T>()));
00382       for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
00383         reinterpret_cast<T *>(Ptr)->~T();
00384     };
00385 
00386     for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
00387          ++I) {
00388       size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
00389           std::distance(Allocator.Slabs.begin(), I));
00390       char *Begin = (char*)alignAddr(*I, alignOf<T>());
00391       char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
00392                                                : (char *)*I + AllocatedSlabSize;
00393 
00394       DestroyElements(Begin, End);
00395     }
00396 
00397     for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
00398       void *Ptr = PtrAndSize.first;
00399       size_t Size = PtrAndSize.second;
00400       DestroyElements((char*)alignAddr(Ptr, alignOf<T>()), (char *)Ptr + Size);
00401     }
00402 
00403     Allocator.Reset();
00404   }
00405 
00406   /// \brief Allocate space for an array of objects without constructing them.
00407   T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
00408 };
00409 
00410 }  // end namespace llvm
00411 
00412 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00413 void *operator new(size_t Size,
00414                    llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
00415                                               SizeThreshold> &Allocator) {
00416   struct S {
00417     char c;
00418     union {
00419       double D;
00420       long double LD;
00421       long long L;
00422       void *P;
00423     } x;
00424   };
00425   return Allocator.Allocate(
00426       Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x)));
00427 }
00428 
00429 template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold>
00430 void operator delete(
00431     void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) {
00432 }
00433 
00434 #endif // LLVM_SUPPORT_ALLOCATOR_H