1 //===--- Allocator.cpp - Simple memory allocation abstraction -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BumpPtrAllocator interface.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Allocator.h"
18 //===----------------------------------------------------------------------===//
19 // MemRegion class implementation
20 //===----------------------------------------------------------------------===//
23 /// MemRegion - This is one chunk of the BumpPtrAllocator.
29 void Init(unsigned size, unsigned Alignment, MemRegion *next) {
32 NextPtr = (char*)(this+1);
35 NextPtr = (char*)((intptr_t)(NextPtr+Alignment-1) &
36 ~(intptr_t)(Alignment-1));
39 const MemRegion *getNext() const { return Next; }
40 unsigned getNumBytesAllocated() const {
41 return NextPtr-(const char*)this;
44 /// Allocate - Allocate and return at least the specified number of bytes.
46 void *Allocate(unsigned AllocSize, unsigned Alignment, MemRegion **RegPtr) {
47 // Round size up to an even multiple of the alignment.
48 AllocSize = (AllocSize+Alignment-1) & ~(Alignment-1);
50 // If there is space in this region, return it.
51 if (unsigned(NextPtr+AllocSize-(char*)this) <= RegionSize) {
52 void *Result = NextPtr;
57 // Otherwise, we have to allocate a new chunk. Create one twice as big as
59 MemRegion *NewRegion = (MemRegion *)malloc(RegionSize*2);
60 NewRegion->Init(RegionSize*2, Alignment, this);
62 // Update the current "first region" pointer to point to the new region.
65 // Try allocating from it now.
66 return NewRegion->Allocate(AllocSize, Alignment, RegPtr);
69 /// Deallocate - Release all memory for this region to the system.
72 MemRegion *next = Next;
80 //===----------------------------------------------------------------------===//
81 // BumpPtrAllocator class implementation
82 //===----------------------------------------------------------------------===//
84 BumpPtrAllocator::BumpPtrAllocator() {
85 TheMemory = malloc(4096);
86 ((MemRegion*)TheMemory)->Init(4096, 1, 0);
89 BumpPtrAllocator::~BumpPtrAllocator() {
90 ((MemRegion*)TheMemory)->Deallocate();
93 void *BumpPtrAllocator::Allocate(unsigned Size, unsigned Align) {
94 return ((MemRegion*)TheMemory)->Allocate(Size, Align,(MemRegion**)&TheMemory);
97 void BumpPtrAllocator::PrintStats() const {
98 unsigned BytesUsed = 0;
99 unsigned NumRegions = 0;
100 const MemRegion *R = (MemRegion*)TheMemory;
101 for (; R; R = R->getNext(), ++NumRegions)
102 BytesUsed += R->getNumBytesAllocated();
104 std::cerr << "\nNumber of memory regions: " << NumRegions << "\n";
105 std::cerr << "Bytes allocated: " << BytesUsed << "\n";