add a method to BumpPtrAllocator that allows allocating elements
[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 //
10 // This file defines the MallocAllocator and BumpPtrAllocator interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_ALLOCATOR_H
15 #define LLVM_SUPPORT_ALLOCATOR_H
16
17 #include "llvm/Support/AlignOf.h"
18 #include <cstdlib>
19
20 namespace llvm {
21     
22 class MallocAllocator {
23 public:
24   MallocAllocator() {}
25   ~MallocAllocator() {}
26   
27   void Reset() {}
28
29   void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
30   
31   template <typename T>
32   T *Allocate() { return static_cast<T*>(malloc(sizeof(T))); }
33   
34   template <typename T>
35   T *Allocate(size_t Num) { 
36     return static_cast<T*>(malloc(sizeof(T)*Num));
37   }
38   
39   void Deallocate(void *Ptr) { free(Ptr); }
40
41   void PrintStats() const {}
42 };
43
44 /// BumpPtrAllocator - This allocator is useful for containers that need very
45 /// simple memory allocation strategies.  In particular, this just keeps
46 /// allocating memory, and never deletes it until the entire block is dead. This
47 /// makes allocation speedy, but must only be used when the trade-off is ok.
48 class BumpPtrAllocator {
49   BumpPtrAllocator(const BumpPtrAllocator &); // do not implement
50   void operator=(const BumpPtrAllocator &);   // do not implement
51
52   void *TheMemory;
53 public:
54   BumpPtrAllocator();
55   ~BumpPtrAllocator();
56   
57   void Reset();
58
59   void *Allocate(size_t Size, size_t Alignment);
60
61   /// Allocate space, but do not construct, one object.
62   ///
63   template <typename T>
64   T *Allocate() { 
65     return static_cast<T*>(Allocate(sizeof(T),AlignOf<T>::Alignment));
66   }
67   
68   /// Allocate space for an array of objects.  This does not construct the
69   /// objects though.
70   template <typename T>
71   T *Allocate(size_t Num) { 
72     return static_cast<T*>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
73   }
74   
75   /// Allocate space for a specific count of elements and with a specified
76   /// alignment.
77   template <typename T>
78   T *Allocate(size_t Num, unsigned Alignment) { 
79     // Round EltSize up to the specified alignment.
80     unsigned EltSize = (sizeof(T)+Alignment-1)&~Alignment;
81     return static_cast<T*>(Allocate(Num * EltSize, Alignment));
82   }
83   
84   
85   void Deallocate(void * /*Ptr*/) {}
86
87   void PrintStats() const;
88 };
89
90 }  // end namespace llvm
91
92 #endif