1 #include "HalideRuntime.h"
2 #include "runtime_internal.h"
3 
4 #include "printer.h"
5 
6 extern "C" {
7 
8 extern void *malloc(size_t);
9 extern void free(void *);
10 
halide_default_malloc(void * user_context,size_t x)11 WEAK void *halide_default_malloc(void *user_context, size_t x) {
12     // Allocate enough space for aligning the pointer we return.
13     const size_t alignment = halide_malloc_alignment();
14     void *orig = malloc(x + alignment);
15     if (orig == NULL) {
16         // Will result in a failed assertion and a call to halide_error
17         return NULL;
18     }
19     // We want to store the original pointer prior to the pointer we return.
20     void *ptr = (void *)(((size_t)orig + alignment + sizeof(void *) - 1) & ~(alignment - 1));
21     ((void **)ptr)[-1] = orig;
22     return ptr;
23 }
24 
halide_default_free(void * user_context,void * ptr)25 WEAK void halide_default_free(void *user_context, void *ptr) {
26     free(((void **)ptr)[-1]);
27 }
28 }
29 
30 namespace Halide {
31 namespace Runtime {
32 namespace Internal {
33 
34 WEAK halide_malloc_t custom_malloc = halide_default_malloc;
35 WEAK halide_free_t custom_free = halide_default_free;
36 
37 }  // namespace Internal
38 }  // namespace Runtime
39 }  // namespace Halide
40 
41 extern "C" {
42 
halide_set_custom_malloc(halide_malloc_t user_malloc)43 WEAK halide_malloc_t halide_set_custom_malloc(halide_malloc_t user_malloc) {
44     halide_malloc_t result = custom_malloc;
45     custom_malloc = user_malloc;
46     return result;
47 }
48 
halide_set_custom_free(halide_free_t user_free)49 WEAK halide_free_t halide_set_custom_free(halide_free_t user_free) {
50     halide_free_t result = custom_free;
51     custom_free = user_free;
52     return result;
53 }
54 
halide_malloc(void * user_context,size_t x)55 WEAK void *halide_malloc(void *user_context, size_t x) {
56     return custom_malloc(user_context, x);
57 }
58 
halide_free(void * user_context,void * ptr)59 WEAK void halide_free(void *user_context, void *ptr) {
60     custom_free(user_context, ptr);
61 }
62 }
63