about summary refs log tree commit diff
path: root/src/rt/rust_obstack.cpp
blob: f76a80aada9851de4967a9d66d57a667d4256e19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Object stacks, used in lieu of dynamically-sized frames.

#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <stdint.h>

#include "rust_internal.h"
#include "rust_obstack.h"
#include "rust_task.h"

// ISAAC, let go of max()!
#ifdef max
#undef max
#endif

//#define DPRINT(fmt,...)     fprintf(stderr, fmt, ##__VA_ARGS__)
#define DPRINT(fmt,...)

//const size_t DEFAULT_CHUNK_SIZE = 4096;
const size_t DEFAULT_CHUNK_SIZE = 300000;
const size_t DEFAULT_ALIGNMENT = 16;

struct rust_obstack_chunk {
    rust_obstack_chunk *prev;
    size_t size;
    size_t alen;
    size_t pad;
    uint8_t data[];

    rust_obstack_chunk(rust_obstack_chunk *in_prev, size_t in_size)
    : prev(in_prev), size(in_size), alen(0) {}

    void *alloc(size_t len);
    bool free(void *ptr);
};

void *
rust_obstack_chunk::alloc(size_t len) {
    alen = align_to(alen, DEFAULT_ALIGNMENT);

    if (len > size - alen) {
        DPRINT("Not enough space, len=%lu!\n", len);
        assert(0);
        return NULL;    // Not enough space.
    }
    void *result = data + alen;
    alen += len;
    return result;
}

bool
rust_obstack_chunk::free(void *ptr) {
    uint8_t *p = (uint8_t *)ptr;
    if (p < data || p > data + size)
        return false;
    assert(p <= data + alen);
    alen = (size_t)(p - data);
    return true;
}

// Allocates the given number of bytes in a new chunk.
void *
rust_obstack::alloc_new(size_t len) {
    size_t chunk_size = std::max(len, DEFAULT_CHUNK_SIZE);
    void *ptr = task->malloc(sizeof(chunk) + chunk_size, "obstack");
    DPRINT("making new chunk at %p, len %lu\n", ptr, chunk_size);
    chunk = new(ptr) rust_obstack_chunk(chunk, chunk_size);
    return chunk->alloc(len);
}

rust_obstack::~rust_obstack() {
    while (chunk) {
        rust_obstack_chunk *prev = chunk->prev;
        task->free(chunk);
        chunk = prev;
    }
}

void *
rust_obstack::alloc(size_t len) {
    if (!chunk)
        return alloc_new(len);

    DPRINT("alloc sz %u", (uint32_t)len);

    void *ptr = chunk->alloc(len);
    ptr = ptr ? ptr : alloc_new(len);

    return ptr;
}

void
rust_obstack::free(void *ptr) {
    if (!ptr)
        return;

    DPRINT("free ptr %p\n", ptr);

    assert(chunk);
    while (!chunk->free(ptr)) {
        DPRINT("deleting chunk at %p\n", chunk);
        rust_obstack_chunk *prev = chunk->prev;
        task->free(chunk);
        chunk = prev;
        assert(chunk);
    }
}