The check to see if an item was already on the heap was randomly hitting.
[jitcs.git] / include / jitcs_tmpalloc.h
blob9b61a58196ee1b3e11238c06609dc398afa3a79d
1 //===-- jitcs_tmpalloc.h - Never-free allocator class -----------*- C++ -*-===//
2 //
3 // TempAllocator is a never-free allocator. All allocated data is written into
4 // a list of memory blocks. All data is freed en bloc. No destructors are
5 // called!
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef _JITCS_TMPALLOC_H_
10 #define _JITCS_TMPALLOC_H_
12 #include "jitcs_adt_ref.h"
13 #include "jitcs_adt_refcounter.h"
14 #include "jitcs_adt_slice.h"
15 #include "jitcs_base.h"
16 #include <list>
17 #include <vector>
19 namespace jitcs {
21 class TempAllocator {
22 public:
23 enum { MINIMUM_BLOCK_SIZE= 4096 };
25 public:
26 TempAllocator();
27 ~TempAllocator();
29 public:
30 template <typename T>
31 T* allocTyped() {
32 return reinterpret_cast<T*>(_alloc(sizeof(T), alignof(T)));
34 template <typename T>
35 Slice<T> allocTypedArray(size_t sz) {
36 return Slice<T>(reinterpret_cast<T*>(_alloc(sizeof(T) * sz, alignof(T))),
37 sz);
40 private:
41 // called from RefCounter
42 friend class RefCounter<TempAllocator>;
43 void _incRef() { ++_refCnt; }
44 void _decRef() { if (!--_refCnt) _clean(true); }
46 private:
47 u8* _alloc(size_t sz, size_t alignment);
48 // drop all current allocations to this allocator, and start from scratch
49 void _clean(bool keepbest);
51 private:
52 typedef std::list< std::vector<u8> > BlockList;
53 BlockList _blocks;
54 BlockList::iterator _curblock;
55 u8* _cur;
56 size_t _rem;
57 size_t _allocatedSpace;
58 size_t _refCnt;
61 // allocator helper object to allocate quickly from a TempAllocator
62 template <typename T>
63 class StreamAllocator {
64 public:
65 StreamAllocator(TempAllocator& a, size_t n)
66 : _allocator(a)
67 , _ptr(nullptr)
68 , _end(nullptr)
69 , _allocN(n) {
70 _JITCS_ALWAYS_CHECK_(_allocN > 0);
73 public:
74 inline Ref<T> alloc() {
75 if (_ptr != _end)
76 return _ptr++;
77 return _alloc();
80 private:
81 Ref<T> _alloc() {
82 _ptr = _allocator.allocTypedArray<T>(_allocN).ptr();
83 _end = _ptr + _allocN;
84 return _ptr++;
87 private:
88 TempAllocator &_allocator;
89 T *_ptr, *_end;
90 size_t _allocN;
93 } // end of namespace jitcs
95 #endif
96 // _JITCS_TMPALLOC_H_