File: out_of_memory.cpp

package info (click to toggle)
halide 21.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,752 kB
  • sloc: cpp: 289,334; ansic: 22,751; python: 7,486; makefile: 4,299; sh: 2,508; java: 1,549; javascript: 282; pascal: 207; xml: 127; asm: 9
file content (72 lines) | stat: -rw-r--r-- 2,010 bytes parent folder | download | duplicates (3)
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
#include "Halide.h"
#include <stdio.h>

using namespace Halide;

// Not threadsafe!!!
size_t mem_limit = (size_t)-1;
size_t total_allocated = 0;

// Ussing a lookaside instead of increasing the size of the block to hold the
// allocation size keeps the malloc behavior the same with regard to alignement
// and bug behaviors, etc. Cheap enough to be good in testing.
std::map<void *, size_t> allocation_sizes;

extern "C" void *test_malloc(JITUserContext *user_context, size_t x) {
    if (total_allocated + x > mem_limit)
        return nullptr;

    void *result = malloc(x);
    if (result != nullptr) {
        total_allocated += x;
        allocation_sizes[result] = x;
    }

    return result;
}

extern "C" void test_free(JITUserContext *user_context, void *ptr) {
    total_allocated -= allocation_sizes[ptr];
    allocation_sizes.erase(ptr);
    free(ptr);
}

bool error_occurred = false;
extern "C" void handler(JITUserContext *user_context, const char *msg) {
    printf("%s\n", msg);
    error_occurred = true;
}

int main(int argc, char **argv) {
    if (get_jit_target_from_environment().arch == Target::WebAssembly) {
        printf("[SKIP] WebAssembly JIT does not support custom allocators.\n");
        return 0;
    }

    const int big = 1 << 26;
    Var x;
    std::vector<Func> funcs;
    funcs.push_back(lambda(x, cast<uint8_t>(x)));
    for (size_t i = 0; i < 10; i++) {
        Func f;
        f(x) = funcs[i](0) + funcs[i](big);
        funcs[i].compute_at(f, x);
        funcs.push_back(f);
    }

    // Limit ourselves to two stages worth of address space
    mem_limit = big << 1;

    funcs[funcs.size() - 1].jit_handlers().custom_malloc = test_malloc;
    funcs[funcs.size() - 1].jit_handlers().custom_free = test_free;
    funcs[funcs.size() - 1].jit_handlers().custom_error = handler;
    funcs[funcs.size() - 1].realize({1});

    if (!error_occurred) {
        printf("There should have been an error\n");
        return 1;
    }

    printf("Success!\n");
    return 0;
}