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;
}
|