Joos1W Compiler Framework
All Classes Functions Typedefs Pages
BumpAllocator.cc
1 #include "utils/BumpAllocator.h"
2 
3 #include <utils/Assert.h>
4 
5 namespace utils {
6 
7 CustomBufferResource::CustomBufferResource(size_t size) {
8  buffers_.emplace_back(size, std::malloc(size));
9  cur_buf_ = buffers_.begin();
10  alloc_top_ = cur_buf_->buf;
11  avail_ = size;
12 }
13 
14 void* CustomBufferResource::do_allocate(std::size_t bytes, std::size_t alignment) {
15  assert((!invalid) &&
16  "attempt to allocate when CustomBufferResource is invalid");
17 
18  // Do not return the same pointer twice, so set min size to 1
19  if(bytes == 0) bytes = 1;
20 
21  // Align the next allocation
22  void* p = std::align(alignment, bytes, alloc_top_, avail_);
23 
24  // Do we have enough space in the current buffer?
25  if(!p) {
26  // Is there no next buffer? Allocate a new one
27  if(std::next(cur_buf_) == buffers_.end()) {
28  size_t new_size = cur_buf_->size * growth_factor;
29  buffers_.emplace_back(new_size, std::malloc(new_size));
30  cur_buf_ = std::prev(buffers_.end());
31  } else {
32  ++cur_buf_;
33  }
34  alloc_top_ = cur_buf_->buf;
35  avail_ = cur_buf_->size;
36  p = cur_buf_->buf;
37  }
38 
39  // Update the allocation pointer and the available space
40  alloc_top_ = static_cast<char*>(alloc_top_) + bytes;
41  avail_ -= bytes;
42 
43  // Return the aligned pointer
44  return p;
45 }
46 
47 void CustomBufferResource::clear_all_buffers() {
48  // memset the memory to 0 to catch use-after-free bugs
49  for(auto& buf : buffers_) {
50  std::memset(buf.buf, 0, buf.size);
51  }
52 }
53 
54 CustomBufferResource::~CustomBufferResource() {
55  for(auto& buf : buffers_) {
56  std::free(buf.buf);
57  }
58 }
59 
60 } // namespace utils