1 #ifndef HALIDE_HALIDERUNTIME_H
2 #define HALIDE_HALIDERUNTIME_H
3 
4 #ifndef COMPILING_HALIDE_RUNTIME
5 #include <stdbool.h>
6 #include <stddef.h>
7 #include <stdint.h>
8 #include <string.h>
9 #else
10 #include "runtime_internal.h"
11 #endif
12 
13 #ifdef __cplusplus
14 // Forward declare type to allow naming typed handles.
15 // See Type.h for documentation.
16 template<typename T>
17 struct halide_handle_traits;
18 #endif
19 
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23 
24 #ifdef _MSC_VER
25 // Note that (for MSVC) you should not use "inline" along with HALIDE_ALWAYS_INLINE;
26 // it is not necessary, and may produce warnings for some build configurations.
27 #define HALIDE_ALWAYS_INLINE __forceinline
28 #define HALIDE_NEVER_INLINE __declspec(noinline)
29 #else
30 // Note that (for Posixy compilers) you should always use "inline" along with HALIDE_ALWAYS_INLINE;
31 // otherwise some corner-case scenarios may erroneously report link errors.
32 #define HALIDE_ALWAYS_INLINE inline __attribute__((always_inline))
33 #define HALIDE_NEVER_INLINE __attribute__((noinline))
34 #endif
35 
36 #ifndef HALIDE_MUST_USE_RESULT
37 #ifdef __has_attribute
38 #if __has_attribute(nodiscard)
39 // C++17 or later
40 #define HALIDE_MUST_USE_RESULT [[nodiscard]]
41 #elif __has_attribute(warn_unused_result)
42 // Clang/GCC
43 #define HALIDE_MUST_USE_RESULT __attribute__((warn_unused_result))
44 #else
45 #define HALIDE_MUST_USE_RESULT
46 #endif
47 #else
48 #define HALIDE_MUST_USE_RESULT
49 #endif
50 #endif
51 
52 /** \file
53  *
54  * This file declares the routines used by Halide internally in its
55  * runtime. On platforms that support weak linking, these can be
56  * replaced with user-defined versions by defining an extern "C"
57  * function with the same name and signature.
58  *
59  * When doing Just In Time (JIT) compilation methods on the Func being
60  * compiled must be called instead. The corresponding methods are
61  * documented below.
62  *
63  * All of these functions take a "void *user_context" parameter as their
64  * first argument; if the Halide kernel that calls back to any of these
65  * functions has been compiled with the UserContext feature set on its Target,
66  * then the value of that pointer passed from the code that calls the
67  * Halide kernel is piped through to the function.
68  *
69  * Some of these are also useful to call when using the default
70  * implementation. E.g. halide_shutdown_thread_pool.
71  *
72  * Note that even on platforms with weak linking, some linker setups
73  * may not respect the override you provide. E.g. if the override is
74  * in a shared library and the halide object files are linked directly
75  * into the output, the builtin versions of the runtime functions will
76  * be called. See your linker documentation for more details. On
77  * Linux, LD_DYNAMIC_WEAK=1 may help.
78  *
79  */
80 
81 // Forward-declare to suppress warnings if compiling as C.
82 struct halide_buffer_t;
83 
84 /** Print a message to stderr. Main use is to support tracing
85  * functionality, print, and print_when calls. Also called by the default
86  * halide_error.  This function can be replaced in JITed code by using
87  * halide_custom_print and providing an implementation of halide_print
88  * in AOT code. See Func::set_custom_print.
89  */
90 // @{
91 extern void halide_print(void *user_context, const char *);
92 extern void halide_default_print(void *user_context, const char *);
93 typedef void (*halide_print_t)(void *, const char *);
94 extern halide_print_t halide_set_custom_print(halide_print_t print);
95 // @}
96 
97 /** Halide calls this function on runtime errors (for example bounds
98  * checking failures). This function can be replaced in JITed code by
99  * using Func::set_error_handler, or in AOT code by calling
100  * halide_set_error_handler. In AOT code on platforms that support
101  * weak linking (i.e. not Windows), you can also override it by simply
102  * defining your own halide_error.
103  */
104 // @{
105 extern void halide_error(void *user_context, const char *);
106 extern void halide_default_error(void *user_context, const char *);
107 typedef void (*halide_error_handler_t)(void *, const char *);
108 extern halide_error_handler_t halide_set_error_handler(halide_error_handler_t handler);
109 // @}
110 
111 /** Cross-platform mutex. Must be initialized with zero and implementation
112  * must treat zero as an unlocked mutex with no waiters, etc.
113  */
114 struct halide_mutex {
115     uintptr_t _private[1];
116 };
117 
118 /** Cross platform condition variable. Must be initialized to 0. */
119 struct halide_cond {
120     uintptr_t _private[1];
121 };
122 
123 /** A basic set of mutex and condition variable functions, which call
124  * platform specific code for mutual exclusion. Equivalent to posix
125  * calls. */
126 //@{
127 extern void halide_mutex_lock(struct halide_mutex *mutex);
128 extern void halide_mutex_unlock(struct halide_mutex *mutex);
129 extern void halide_cond_signal(struct halide_cond *cond);
130 extern void halide_cond_broadcast(struct halide_cond *cond);
131 extern void halide_cond_wait(struct halide_cond *cond, struct halide_mutex *mutex);
132 //@}
133 
134 /** Functions for constructing/destroying/locking/unlocking arrays of mutexes. */
135 struct halide_mutex_array;
136 //@{
137 extern struct halide_mutex_array *halide_mutex_array_create(int sz);
138 extern void halide_mutex_array_destroy(void *user_context, void *array);
139 extern int halide_mutex_array_lock(struct halide_mutex_array *array, int entry);
140 extern int halide_mutex_array_unlock(struct halide_mutex_array *array, int entry);
141 //@}
142 
143 /** Define halide_do_par_for to replace the default thread pool
144  * implementation. halide_shutdown_thread_pool can also be called to
145  * release resources used by the default thread pool on platforms
146  * where it makes sense. (E.g. On Mac OS, Grand Central Dispatch is
147  * used so %Halide does not own the threads backing the pool and they
148  * cannot be released.)  See Func::set_custom_do_task and
149  * Func::set_custom_do_par_for. Should return zero if all the jobs
150  * return zero, or an arbitrarily chosen return value from one of the
151  * jobs otherwise.
152  */
153 //@{
154 typedef int (*halide_task_t)(void *user_context, int task_number, uint8_t *closure);
155 extern int halide_do_par_for(void *user_context,
156                              halide_task_t task,
157                              int min, int size, uint8_t *closure);
158 extern void halide_shutdown_thread_pool();
159 //@}
160 
161 /** Set a custom method for performing a parallel for loop. Returns
162  * the old do_par_for handler. */
163 typedef int (*halide_do_par_for_t)(void *, halide_task_t, int, int, uint8_t *);
164 extern halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t do_par_for);
165 
166 /** An opaque struct representing a semaphore. Used by the task system for async tasks. */
167 struct halide_semaphore_t {
168     uint64_t _private[2];
169 };
170 
171 /** A struct representing a semaphore and a number of items that must
172  * be acquired from it. Used in halide_parallel_task_t below. */
173 struct halide_semaphore_acquire_t {
174     struct halide_semaphore_t *semaphore;
175     int count;
176 };
177 extern int halide_semaphore_init(struct halide_semaphore_t *, int n);
178 extern int halide_semaphore_release(struct halide_semaphore_t *, int n);
179 extern bool halide_semaphore_try_acquire(struct halide_semaphore_t *, int n);
180 typedef int (*halide_semaphore_init_t)(struct halide_semaphore_t *, int);
181 typedef int (*halide_semaphore_release_t)(struct halide_semaphore_t *, int);
182 typedef bool (*halide_semaphore_try_acquire_t)(struct halide_semaphore_t *, int);
183 
184 /** A task representing a serial for loop evaluated over some range.
185  * Note that task_parent is a pass through argument that should be
186  * passed to any dependent taks that are invokved using halide_do_parallel_tasks
187  * underneath this call. */
188 typedef int (*halide_loop_task_t)(void *user_context, int min, int extent,
189                                   uint8_t *closure, void *task_parent);
190 
191 /** A parallel task to be passed to halide_do_parallel_tasks. This
192  * task may recursively call halide_do_parallel_tasks, and there may
193  * be complex dependencies between seemingly unrelated tasks expressed
194  * using semaphores. If you are using a custom task system, care must
195  * be taken to avoid potential deadlock. This can be done by carefully
196  * respecting the static metadata at the end of the task struct.*/
197 struct halide_parallel_task_t {
198     // The function to call. It takes a user context, a min and
199     // extent, a closure, and a task system pass through argument.
200     halide_loop_task_t fn;
201 
202     // The closure to pass it
203     uint8_t *closure;
204 
205     // The name of the function to be called. For debugging purposes only.
206     const char *name;
207 
208     // An array of semaphores that must be acquired before the
209     // function is called. Must be reacquired for every call made.
210     struct halide_semaphore_acquire_t *semaphores;
211     int num_semaphores;
212 
213     // The entire range the function should be called over. This range
214     // may be sliced up and the function called multiple times.
215     int min, extent;
216 
217     // A parallel task provides several pieces of metadata to prevent
218     // unbounded resource usage or deadlock.
219 
220     // The first is the minimum number of execution contexts (call
221     // stacks or threads) necessary for the function to run to
222     // completion. This may be greater than one when there is nested
223     // parallelism with internal producer-consumer relationships
224     // (calling the function recursively spawns and blocks on parallel
225     // sub-tasks that communicate with each other via semaphores). If
226     // a parallel runtime calls the function when fewer than this many
227     // threads are idle, it may need to create more threads to
228     // complete the task, or else risk deadlock due to committing all
229     // threads to tasks that cannot complete without more.
230     //
231     // FIXME: Note that extern stages are assumed to only require a
232     // single thread to complete. If the extern stage is itself a
233     // Halide pipeline, this may be an underestimate.
234     int min_threads;
235 
236     // The calls to the function should be in serial order from min to min+extent-1, with only
237     // one executing at a time. If false, any order is fine, and
238     // concurrency is fine.
239     bool serial;
240 };
241 
242 /** Enqueue some number of the tasks described above and wait for them
243  * to complete. While waiting, the calling threads assists with either
244  * the tasks enqueued, or other non-blocking tasks in the task
245  * system. Note that task_parent should be NULL for top-level calls
246  * and the pass through argument if this call is being made from
247  * another task. */
248 extern int halide_do_parallel_tasks(void *user_context, int num_tasks,
249                                     struct halide_parallel_task_t *tasks,
250                                     void *task_parent);
251 
252 /** If you use the default do_par_for, you can still set a custom
253  * handler to perform each individual task. Returns the old handler. */
254 //@{
255 typedef int (*halide_do_task_t)(void *, halide_task_t, int, uint8_t *);
256 extern halide_do_task_t halide_set_custom_do_task(halide_do_task_t do_task);
257 extern int halide_do_task(void *user_context, halide_task_t f, int idx,
258                           uint8_t *closure);
259 //@}
260 
261 /** The version of do_task called for loop tasks. By default calls the
262  * loop task with the same arguments. */
263 // @{
264 typedef int (*halide_do_loop_task_t)(void *, halide_loop_task_t, int, int, uint8_t *, void *);
265 extern halide_do_loop_task_t halide_set_custom_do_loop_task(halide_do_loop_task_t do_task);
266 extern int halide_do_loop_task(void *user_context, halide_loop_task_t f, int min, int extent,
267                                uint8_t *closure, void *task_parent);
268 //@}
269 
270 /** Provide an entire custom tasking runtime via function
271  * pointers. Note that do_task and semaphore_try_acquire are only ever
272  * called by halide_default_do_par_for and
273  * halide_default_do_parallel_tasks, so it's only necessary to provide
274  * those if you are mixing in the default implementations of
275  * do_par_for and do_parallel_tasks. */
276 // @{
277 typedef int (*halide_do_parallel_tasks_t)(void *, int, struct halide_parallel_task_t *,
278                                           void *task_parent);
279 extern void halide_set_custom_parallel_runtime(
280     halide_do_par_for_t,
281     halide_do_task_t,
282     halide_do_loop_task_t,
283     halide_do_parallel_tasks_t,
284     halide_semaphore_init_t,
285     halide_semaphore_try_acquire_t,
286     halide_semaphore_release_t);
287 // @}
288 
289 /** The default versions of the parallel runtime functions. */
290 // @{
291 extern int halide_default_do_par_for(void *user_context,
292                                      halide_task_t task,
293                                      int min, int size, uint8_t *closure);
294 extern int halide_default_do_parallel_tasks(void *user_context,
295                                             int num_tasks,
296                                             struct halide_parallel_task_t *tasks,
297                                             void *task_parent);
298 extern int halide_default_do_task(void *user_context, halide_task_t f, int idx,
299                                   uint8_t *closure);
300 extern int halide_default_do_loop_task(void *user_context, halide_loop_task_t f,
301                                        int min, int extent,
302                                        uint8_t *closure, void *task_parent);
303 extern int halide_default_semaphore_init(struct halide_semaphore_t *, int n);
304 extern int halide_default_semaphore_release(struct halide_semaphore_t *, int n);
305 extern bool halide_default_semaphore_try_acquire(struct halide_semaphore_t *, int n);
306 // @}
307 
308 struct halide_thread;
309 
310 /** Spawn a thread. Returns a handle to the thread for the purposes of
311  * joining it. The thread must be joined in order to clean up any
312  * resources associated with it. */
313 extern struct halide_thread *halide_spawn_thread(void (*f)(void *), void *closure);
314 
315 /** Join a thread. */
316 extern void halide_join_thread(struct halide_thread *);
317 
318 /** Set the number of threads used by Halide's thread pool. Returns
319  * the old number.
320  *
321  * n < 0  : error condition
322  * n == 0 : use a reasonable system default (typically, number of cpus online).
323  * n == 1 : use exactly one thread; this will always enforce serial execution
324  * n > 1  : use a pool of exactly n threads.
325  *
326  * (Note that this is only guaranteed when using the default implementations
327  * of halide_do_par_for(); custom implementations may completely ignore values
328  * passed to halide_set_num_threads().)
329  */
330 extern int halide_set_num_threads(int n);
331 
332 /** Halide calls these functions to allocate and free memory. To
333  * replace in AOT code, use the halide_set_custom_malloc and
334  * halide_set_custom_free, or (on platforms that support weak
335  * linking), simply define these functions yourself. In JIT-compiled
336  * code use Func::set_custom_allocator.
337  *
338  * If you override them, and find yourself wanting to call the default
339  * implementation from within your override, use
340  * halide_default_malloc/free.
341  *
342  * Note that halide_malloc must return a pointer aligned to the
343  * maximum meaningful alignment for the platform for the purpose of
344  * vector loads and stores. The default implementation uses 32-byte
345  * alignment, which is safe for arm and x86. Additionally, it must be
346  * safe to read at least 8 bytes before the start and beyond the
347  * end.
348  */
349 //@{
350 extern void *halide_malloc(void *user_context, size_t x);
351 extern void halide_free(void *user_context, void *ptr);
352 extern void *halide_default_malloc(void *user_context, size_t x);
353 extern void halide_default_free(void *user_context, void *ptr);
354 typedef void *(*halide_malloc_t)(void *, size_t);
355 typedef void (*halide_free_t)(void *, void *);
356 extern halide_malloc_t halide_set_custom_malloc(halide_malloc_t user_malloc);
357 extern halide_free_t halide_set_custom_free(halide_free_t user_free);
358 //@}
359 
360 /** Halide calls these functions to interact with the underlying
361  * system runtime functions. To replace in AOT code on platforms that
362  * support weak linking, define these functions yourself, or use
363  * the halide_set_custom_load_library() and halide_set_custom_get_library_symbol()
364  * functions. In JIT-compiled code, use JITSharedRuntime::set_default_handlers().
365  *
366  * halide_load_library and halide_get_library_symbol are equivalent to
367  * dlopen and dlsym. halide_get_symbol(sym) is equivalent to
368  * dlsym(RTLD_DEFAULT, sym).
369  */
370 //@{
371 extern void *halide_get_symbol(const char *name);
372 extern void *halide_load_library(const char *name);
373 extern void *halide_get_library_symbol(void *lib, const char *name);
374 extern void *halide_default_get_symbol(const char *name);
375 extern void *halide_default_load_library(const char *name);
376 extern void *halide_default_get_library_symbol(void *lib, const char *name);
377 typedef void *(*halide_get_symbol_t)(const char *name);
378 typedef void *(*halide_load_library_t)(const char *name);
379 typedef void *(*halide_get_library_symbol_t)(void *lib, const char *name);
380 extern halide_get_symbol_t halide_set_custom_get_symbol(halide_get_symbol_t user_get_symbol);
381 extern halide_load_library_t halide_set_custom_load_library(halide_load_library_t user_load_library);
382 extern halide_get_library_symbol_t halide_set_custom_get_library_symbol(halide_get_library_symbol_t user_get_library_symbol);
383 //@}
384 
385 /** Called when debug_to_file is used inside %Halide code.  See
386  * Func::debug_to_file for how this is called
387  *
388  * Cannot be replaced in JITted code at present.
389  */
390 extern int32_t halide_debug_to_file(void *user_context, const char *filename,
391                                     int32_t type_code,
392                                     struct halide_buffer_t *buf);
393 
394 /** Types in the halide type system. They can be ints, unsigned ints,
395  * or floats (of various bit-widths), or a handle (which is always 64-bits).
396  * Note that the int/uint/float values do not imply a specific bit width
397  * (the bit width is expected to be encoded in a separate value).
398  */
399 typedef enum halide_type_code_t
400 #if __cplusplus >= 201103L
401     : uint8_t
402 #endif
403 {
404     halide_type_int = 0,     ///< signed integers
405     halide_type_uint = 1,    ///< unsigned integers
406     halide_type_float = 2,   ///< IEEE floating point numbers
407     halide_type_handle = 3,  ///< opaque pointer type (void *)
408     halide_type_bfloat = 4,  ///< floating point numbers in the bfloat format
409 } halide_type_code_t;
410 
411 // Note that while __attribute__ can go before or after the declaration,
412 // __declspec apparently is only allowed before.
413 #ifndef HALIDE_ATTRIBUTE_ALIGN
414 #ifdef _MSC_VER
415 #define HALIDE_ATTRIBUTE_ALIGN(x) __declspec(align(x))
416 #else
417 #define HALIDE_ATTRIBUTE_ALIGN(x) __attribute__((aligned(x)))
418 #endif
419 #endif
420 
421 /** A runtime tag for a type in the halide type system. Can be ints,
422  * unsigned ints, or floats of various bit-widths (the 'bits'
423  * field). Can also be vectors of the same (by setting the 'lanes'
424  * field to something larger than one). This struct should be
425  * exactly 32-bits in size. */
426 struct halide_type_t {
427     /** The basic type code: signed integer, unsigned integer, or floating point. */
428 #if __cplusplus >= 201103L
429     HALIDE_ATTRIBUTE_ALIGN(1)
430     halide_type_code_t code;  // halide_type_code_t
431 #else
432     HALIDE_ATTRIBUTE_ALIGN(1)
433     uint8_t code;  // halide_type_code_t
434 #endif
435 
436     /** The number of bits of precision of a single scalar value of this type. */
437     HALIDE_ATTRIBUTE_ALIGN(1)
438     uint8_t bits;
439 
440     /** How many elements in a vector. This is 1 for scalar types. */
441     HALIDE_ATTRIBUTE_ALIGN(2)
442     uint16_t lanes;
443 
444 #ifdef __cplusplus
445     /** Construct a runtime representation of a Halide type from:
446      * code: The fundamental type from an enum.
447      * bits: The bit size of one element.
448      * lanes: The number of vector elements in the type. */
449     HALIDE_ALWAYS_INLINE halide_type_t(halide_type_code_t code, uint8_t bits, uint16_t lanes = 1)
codehalide_type_t450         : code(code), bits(bits), lanes(lanes) {
451     }
452 
453     /** Default constructor is required e.g. to declare halide_trace_event
454      * instances. */
halide_type_thalide_type_t455     HALIDE_ALWAYS_INLINE halide_type_t()
456         : code((halide_type_code_t)0), bits(0), lanes(0) {
457     }
458 
with_laneshalide_type_t459     HALIDE_ALWAYS_INLINE halide_type_t with_lanes(uint16_t new_lanes) const {
460         return halide_type_t((halide_type_code_t)code, bits, new_lanes);
461     }
462 
463     /** Compare two types for equality. */
464     HALIDE_ALWAYS_INLINE bool operator==(const halide_type_t &other) const {
465         return as_u32() == other.as_u32();
466     }
467 
468     HALIDE_ALWAYS_INLINE bool operator!=(const halide_type_t &other) const {
469         return !(*this == other);
470     }
471 
472     HALIDE_ALWAYS_INLINE bool operator<(const halide_type_t &other) const {
473         return as_u32() < other.as_u32();
474     }
475 
476     /** Size in bytes for a single element, even if width is not 1, of this type. */
byteshalide_type_t477     HALIDE_ALWAYS_INLINE int bytes() const {
478         return (bits + 7) / 8;
479     }
480 
as_u32halide_type_t481     HALIDE_ALWAYS_INLINE uint32_t as_u32() const {
482         uint32_t u;
483         memcpy(&u, this, sizeof(u));
484         return u;
485     }
486 #endif
487 };
488 
489 enum halide_trace_event_code_t { halide_trace_load = 0,
490                                  halide_trace_store = 1,
491                                  halide_trace_begin_realization = 2,
492                                  halide_trace_end_realization = 3,
493                                  halide_trace_produce = 4,
494                                  halide_trace_end_produce = 5,
495                                  halide_trace_consume = 6,
496                                  halide_trace_end_consume = 7,
497                                  halide_trace_begin_pipeline = 8,
498                                  halide_trace_end_pipeline = 9,
499                                  halide_trace_tag = 10 };
500 
501 struct halide_trace_event_t {
502     /** The name of the Func or Pipeline that this event refers to */
503     const char *func;
504 
505     /** If the event type is a load or a store, this points to the
506      * value being loaded or stored. Use the type field to safely cast
507      * this to a concrete pointer type and retrieve it. For other
508      * events this is null. */
509     void *value;
510 
511     /** For loads and stores, an array which contains the location
512      * being accessed. For vector loads or stores it is an array of
513      * vectors of coordinates (the vector dimension is innermost).
514      *
515      * For realization or production-related events, this will contain
516      * the mins and extents of the region being accessed, in the order
517      * min0, extent0, min1, extent1, ...
518      *
519      * For pipeline-related events, this will be null.
520      */
521     int32_t *coordinates;
522 
523     /** For halide_trace_tag, this points to a read-only null-terminated string
524      * of arbitrary text. For all other events, this will be null.
525      */
526     const char *trace_tag;
527 
528     /** If the event type is a load or a store, this is the type of
529      * the data. Otherwise, the value is meaningless. */
530     struct halide_type_t type;
531 
532     /** The type of event */
533     enum halide_trace_event_code_t event;
534 
535     /* The ID of the parent event (see below for an explanation of
536      * event ancestry). */
537     int32_t parent_id;
538 
539     /** If this was a load or store of a Tuple-valued Func, this is
540      * which tuple element was accessed. */
541     int32_t value_index;
542 
543     /** The length of the coordinates array */
544     int32_t dimensions;
545 
546 #ifdef __cplusplus
547     // If we don't explicitly mark the default ctor as inline,
548     // certain build configurations can fail (notably iOS)
halide_trace_event_thalide_trace_event_t549     HALIDE_ALWAYS_INLINE halide_trace_event_t() {
550     }
551 #endif
552 };
553 
554 /** Called when Funcs are marked as trace_load, trace_store, or
555  * trace_realization. See Func::set_custom_trace. The default
556  * implementation either prints events via halide_print, or if
557  * HL_TRACE_FILE is defined, dumps the trace to that file in a
558  * sequence of trace packets. The header for a trace packet is defined
559  * below. If the trace is going to be large, you may want to make the
560  * file a named pipe, and then read from that pipe into gzip.
561  *
562  * halide_trace returns a unique ID which will be passed to future
563  * events that "belong" to the earlier event as the parent id. The
564  * ownership hierarchy looks like:
565  *
566  * begin_pipeline
567  * +--trace_tag (if any)
568  * +--trace_tag (if any)
569  * ...
570  * +--begin_realization
571  * |  +--produce
572  * |  |  +--load/store
573  * |  |  +--end_produce
574  * |  +--consume
575  * |  |  +--load
576  * |  |  +--end_consume
577  * |  +--end_realization
578  * +--end_pipeline
579  *
580  * Threading means that ownership cannot be inferred from the ordering
581  * of events. There can be many active realizations of a given
582  * function, or many active productions for a single
583  * realization. Within a single production, the ordering of events is
584  * meaningful.
585  *
586  * Note that all trace_tag events (if any) will occur just after the begin_pipeline
587  * event, but before any begin_realization events. All trace_tags for a given Func
588  * will be emitted in the order added.
589  */
590 // @}
591 extern int32_t halide_trace(void *user_context, const struct halide_trace_event_t *event);
592 extern int32_t halide_default_trace(void *user_context, const struct halide_trace_event_t *event);
593 typedef int32_t (*halide_trace_t)(void *user_context, const struct halide_trace_event_t *);
594 extern halide_trace_t halide_set_custom_trace(halide_trace_t trace);
595 // @}
596 
597 /** The header of a packet in a binary trace. All fields are 32-bit. */
598 struct halide_trace_packet_t {
599     /** The total size of this packet in bytes. Always a multiple of
600      * four. Equivalently, the number of bytes until the next
601      * packet. */
602     uint32_t size;
603 
604     /** The id of this packet (for the purpose of parent_id). */
605     int32_t id;
606 
607     /** The remaining fields are equivalent to those in halide_trace_event_t */
608     // @{
609     struct halide_type_t type;
610     enum halide_trace_event_code_t event;
611     int32_t parent_id;
612     int32_t value_index;
613     int32_t dimensions;
614     // @}
615 
616 #ifdef __cplusplus
617     // If we don't explicitly mark the default ctor as inline,
618     // certain build configurations can fail (notably iOS)
halide_trace_packet_thalide_trace_packet_t619     HALIDE_ALWAYS_INLINE halide_trace_packet_t() {
620     }
621 
622     /** Get the coordinates array, assuming this packet is laid out in
623      * memory as it was written. The coordinates array comes
624      * immediately after the packet header. */
coordinateshalide_trace_packet_t625     HALIDE_ALWAYS_INLINE const int *coordinates() const {
626         return (const int *)(this + 1);
627     }
628 
coordinateshalide_trace_packet_t629     HALIDE_ALWAYS_INLINE int *coordinates() {
630         return (int *)(this + 1);
631     }
632 
633     /** Get the value, assuming this packet is laid out in memory as
634      * it was written. The packet comes immediately after the coordinates
635      * array. */
valuehalide_trace_packet_t636     HALIDE_ALWAYS_INLINE const void *value() const {
637         return (const void *)(coordinates() + dimensions);
638     }
639 
valuehalide_trace_packet_t640     HALIDE_ALWAYS_INLINE void *value() {
641         return (void *)(coordinates() + dimensions);
642     }
643 
644     /** Get the func name, assuming this packet is laid out in memory
645      * as it was written. It comes after the value. */
funchalide_trace_packet_t646     HALIDE_ALWAYS_INLINE const char *func() const {
647         return (const char *)value() + type.lanes * type.bytes();
648     }
649 
funchalide_trace_packet_t650     HALIDE_ALWAYS_INLINE char *func() {
651         return (char *)value() + type.lanes * type.bytes();
652     }
653 
654     /** Get the trace_tag (if any), assuming this packet is laid out in memory
655      * as it was written. It comes after the func name. If there is no trace_tag,
656      * this will return a pointer to an empty string. */
trace_taghalide_trace_packet_t657     HALIDE_ALWAYS_INLINE const char *trace_tag() const {
658         const char *f = func();
659         // strlen may not be available here
660         while (*f++) {
661             // nothing
662         }
663         return f;
664     }
665 
trace_taghalide_trace_packet_t666     HALIDE_ALWAYS_INLINE char *trace_tag() {
667         char *f = func();
668         // strlen may not be available here
669         while (*f++) {
670             // nothing
671         }
672         return f;
673     }
674 #endif
675 };
676 
677 /** Set the file descriptor that Halide should write binary trace
678  * events to. If called with 0 as the argument, Halide outputs trace
679  * information to stdout in a human-readable format. If never called,
680  * Halide checks the for existence of an environment variable called
681  * HL_TRACE_FILE and opens that file. If HL_TRACE_FILE is not defined,
682  * it outputs trace information to stdout in a human-readable
683  * format. */
684 extern void halide_set_trace_file(int fd);
685 
686 /** Halide calls this to retrieve the file descriptor to write binary
687  * trace events to. The default implementation returns the value set
688  * by halide_set_trace_file. Implement it yourself if you wish to use
689  * a custom file descriptor per user_context. Return zero from your
690  * implementation to tell Halide to print human-readable trace
691  * information to stdout. */
692 extern int halide_get_trace_file(void *user_context);
693 
694 /** If tracing is writing to a file. This call closes that file
695  * (flushing the trace). Returns zero on success. */
696 extern int halide_shutdown_trace();
697 
698 /** All Halide GPU or device backend implementations provide an
699  * interface to be used with halide_device_malloc, etc. This is
700  * accessed via the functions below.
701  */
702 
703 /** An opaque struct containing per-GPU API implementations of the
704  * device functions. */
705 struct halide_device_interface_impl_t;
706 
707 /** Each GPU API provides a halide_device_interface_t struct pointing
708  * to the code that manages device allocations. You can access these
709  * functions directly from the struct member function pointers, or by
710  * calling the functions declared below. Note that the global
711  * functions are not available when using Halide as a JIT compiler.
712  * If you are using raw halide_buffer_t in that context you must use
713  * the function pointers in the device_interface struct.
714  *
715  * The function pointers below are currently the same for every GPU
716  * API; only the impl field varies. These top-level functions do the
717  * bookkeeping that is common across all GPU APIs, and then dispatch
718  * to more API-specific functions via another set of function pointers
719  * hidden inside the impl field.
720  */
721 struct halide_device_interface_t {
722     int (*device_malloc)(void *user_context, struct halide_buffer_t *buf,
723                          const struct halide_device_interface_t *device_interface);
724     int (*device_free)(void *user_context, struct halide_buffer_t *buf);
725     int (*device_sync)(void *user_context, struct halide_buffer_t *buf);
726     void (*device_release)(void *user_context,
727                            const struct halide_device_interface_t *device_interface);
728     int (*copy_to_host)(void *user_context, struct halide_buffer_t *buf);
729     int (*copy_to_device)(void *user_context, struct halide_buffer_t *buf,
730                           const struct halide_device_interface_t *device_interface);
731     int (*device_and_host_malloc)(void *user_context, struct halide_buffer_t *buf,
732                                   const struct halide_device_interface_t *device_interface);
733     int (*device_and_host_free)(void *user_context, struct halide_buffer_t *buf);
734     int (*buffer_copy)(void *user_context, struct halide_buffer_t *src,
735                        const struct halide_device_interface_t *dst_device_interface, struct halide_buffer_t *dst);
736     int (*device_crop)(void *user_context, const struct halide_buffer_t *src,
737                        struct halide_buffer_t *dst);
738     int (*device_slice)(void *user_context, const struct halide_buffer_t *src,
739                         int slice_dim, int slice_pos, struct halide_buffer_t *dst);
740     int (*device_release_crop)(void *user_context, struct halide_buffer_t *buf);
741     int (*wrap_native)(void *user_context, struct halide_buffer_t *buf, uint64_t handle,
742                        const struct halide_device_interface_t *device_interface);
743     int (*detach_native)(void *user_context, struct halide_buffer_t *buf);
744     int (*compute_capability)(void *user_context, int *major, int *minor);
745     const struct halide_device_interface_impl_t *impl;
746 };
747 
748 /** Release all data associated with the given device interface, in
749  * particular all resources (memory, texture, context handles)
750  * allocated by Halide. Must be called explicitly when using AOT
751  * compilation. This is *not* thread-safe with respect to actively
752  * running Halide code. Ensure all pipelines are finished before
753  * calling this. */
754 extern void halide_device_release(void *user_context,
755                                   const struct halide_device_interface_t *device_interface);
756 
757 /** Copy image data from device memory to host memory. This must be called
758  * explicitly to copy back the results of a GPU-based filter. */
759 extern int halide_copy_to_host(void *user_context, struct halide_buffer_t *buf);
760 
761 /** Copy image data from host memory to device memory. This should not
762  * be called directly; Halide handles copying to the device
763  * automatically.  If interface is NULL and the buf has a non-zero dev
764  * field, the device associated with the dev handle will be
765  * used. Otherwise if the dev field is 0 and interface is NULL, an
766  * error is returned. */
767 extern int halide_copy_to_device(void *user_context, struct halide_buffer_t *buf,
768                                  const struct halide_device_interface_t *device_interface);
769 
770 /** Copy data from one buffer to another. The buffers may have
771  * different shapes and sizes, but the destination buffer's shape must
772  * be contained within the source buffer's shape. That is, for each
773  * dimension, the min on the destination buffer must be greater than
774  * or equal to the min on the source buffer, and min+extent on the
775  * destination buffer must be less that or equal to min+extent on the
776  * source buffer. The source data is pulled from either device or
777  * host memory on the source, depending on the dirty flags. host is
778  * preferred if both are valid. The dst_device_interface parameter
779  * controls the destination memory space. NULL means host memory. */
780 extern int halide_buffer_copy(void *user_context, struct halide_buffer_t *src,
781                               const struct halide_device_interface_t *dst_device_interface,
782                               struct halide_buffer_t *dst);
783 
784 /** Give the destination buffer a device allocation which is an alias
785  * for the same coordinate range in the source buffer. Modifies the
786  * device, device_interface, and the device_dirty flag only. Only
787  * supported by some device APIs (others will return
788  * halide_error_code_device_crop_unsupported). Call
789  * halide_device_release_crop instead of halide_device_free to clean
790  * up resources associated with the cropped view. Do not free the
791  * device allocation on the source buffer while the destination buffer
792  * still lives. Note that the two buffers do not share dirty flags, so
793  * care must be taken to update them together as needed. Note that src
794  * and dst are required to have the same number of dimensions.
795  *
796  * Note also that (in theory) device interfaces which support cropping may
797  * still not support cropping a crop (instead, create a new crop of the parent
798  * buffer); in practice, no known implementation has this limitation, although
799  * it is possible that some future implementations may require it. */
800 extern int halide_device_crop(void *user_context,
801                               const struct halide_buffer_t *src,
802                               struct halide_buffer_t *dst);
803 
804 /** Give the destination buffer a device allocation which is an alias
805  * for a similar coordinate range in the source buffer, but with one dimension
806  * sliced away in the dst. Modifies the device, device_interface, and the
807  * device_dirty flag only. Only supported by some device APIs (others will return
808  * halide_error_code_device_crop_unsupported). Call
809  * halide_device_release_crop instead of halide_device_free to clean
810  * up resources associated with the sliced view. Do not free the
811  * device allocation on the source buffer while the destination buffer
812  * still lives. Note that the two buffers do not share dirty flags, so
813  * care must be taken to update them together as needed. Note that the dst buffer
814  * must have exactly one fewer dimension than the src buffer, and that slice_dim
815  * and slice_pos must be valid within src. */
816 extern int halide_device_slice(void *user_context,
817                                const struct halide_buffer_t *src,
818                                int slice_dim, int slice_pos,
819                                struct halide_buffer_t *dst);
820 
821 /** Release any resources associated with a cropped/sliced view of another
822  * buffer. */
823 extern int halide_device_release_crop(void *user_context,
824                                       struct halide_buffer_t *buf);
825 
826 /** Wait for current GPU operations to complete. Calling this explicitly
827  * should rarely be necessary, except maybe for profiling. */
828 extern int halide_device_sync(void *user_context, struct halide_buffer_t *buf);
829 
830 /** Allocate device memory to back a halide_buffer_t. */
831 extern int halide_device_malloc(void *user_context, struct halide_buffer_t *buf,
832                                 const struct halide_device_interface_t *device_interface);
833 
834 /** Free device memory. */
835 extern int halide_device_free(void *user_context, struct halide_buffer_t *buf);
836 
837 /** Wrap or detach a native device handle, setting the device field
838  * and device_interface field as appropriate for the given GPU
839  * API. The meaning of the opaque handle is specific to the device
840  * interface, so if you know the device interface in use, call the
841  * more specific functions in the runtime headers for your specific
842  * device API instead (e.g. HalideRuntimeCuda.h). */
843 // @{
844 extern int halide_device_wrap_native(void *user_context,
845                                      struct halide_buffer_t *buf,
846                                      uint64_t handle,
847                                      const struct halide_device_interface_t *device_interface);
848 extern int halide_device_detach_native(void *user_context, struct halide_buffer_t *buf);
849 // @}
850 
851 /** Selects which gpu device to use. 0 is usually the display
852  * device. If never called, Halide uses the environment variable
853  * HL_GPU_DEVICE. If that variable is unset, Halide uses the last
854  * device. Set this to -1 to use the last device. */
855 extern void halide_set_gpu_device(int n);
856 
857 /** Halide calls this to get the desired halide gpu device
858  * setting. Implement this yourself to use a different gpu device per
859  * user_context. The default implementation returns the value set by
860  * halide_set_gpu_device, or the environment variable
861  * HL_GPU_DEVICE. */
862 extern int halide_get_gpu_device(void *user_context);
863 
864 /** Set the soft maximum amount of memory, in bytes, that the LRU
865  *  cache will use to memoize Func results.  This is not a strict
866  *  maximum in that concurrency and simultaneous use of memoized
867  *  reults larger than the cache size can both cause it to
868  *  temporariliy be larger than the size specified here.
869  */
870 extern void halide_memoization_cache_set_size(int64_t size);
871 
872 /** Given a cache key for a memoized result, currently constructed
873  *  from the Func name and top-level Func name plus the arguments of
874  *  the computation, determine if the result is in the cache and
875  *  return it if so. (The internals of the cache key should be
876  *  considered opaque by this function.) If this routine returns true,
877  *  it is a cache miss. Otherwise, it will return false and the
878  *  buffers passed in will be filled, via copying, with memoized
879  *  data. The last argument is a list if halide_buffer_t pointers which
880  *  represents the outputs of the memoized Func. If the Func does not
881  *  return a Tuple, there will only be one halide_buffer_t in the list. The
882  *  tuple_count parameters determines the length of the list.
883  *
884  * The return values are:
885  * -1: Signals an error.
886  *  0: Success and cache hit.
887  *  1: Success and cache miss.
888  */
889 extern int halide_memoization_cache_lookup(void *user_context, const uint8_t *cache_key, int32_t size,
890                                            struct halide_buffer_t *realized_bounds,
891                                            int32_t tuple_count, struct halide_buffer_t **tuple_buffers);
892 
893 /** Given a cache key for a memoized result, currently constructed
894  *  from the Func name and top-level Func name plus the arguments of
895  *  the computation, store the result in the cache for futre access by
896  *  halide_memoization_cache_lookup. (The internals of the cache key
897  *  should be considered opaque by this function.) Data is copied out
898  *  from the inputs and inputs are unmodified. The last argument is a
899  *  list if halide_buffer_t pointers which represents the outputs of the
900  *  memoized Func. If the Func does not return a Tuple, there will
901  *  only be one halide_buffer_t in the list. The tuple_count parameters
902  *  determines the length of the list.
903  *
904  * If there is a memory allocation failure, the store does not store
905  * the data into the cache.
906  */
907 extern int halide_memoization_cache_store(void *user_context, const uint8_t *cache_key, int32_t size,
908                                           struct halide_buffer_t *realized_bounds,
909                                           int32_t tuple_count,
910                                           struct halide_buffer_t **tuple_buffers);
911 
912 /** If halide_memoization_cache_lookup succeeds,
913  * halide_memoization_cache_release must be called to signal the
914  * storage is no longer being used by the caller. It will be passed
915  * the host pointer of one the buffers returned by
916  * halide_memoization_cache_lookup. That is
917  * halide_memoization_cache_release will be called multiple times for
918  * the case where halide_memoization_cache_lookup is handling multiple
919  * buffers.  (This corresponds to memoizing a Tuple in Halide.) Note
920  * that the host pointer must be sufficient to get to all information
921  * the relase operation needs. The default Halide cache impleemntation
922  * accomplishes this by storing extra data before the start of the user
923  * modifiable host storage.
924  *
925  * This call is like free and does not have a failure return.
926   */
927 extern void halide_memoization_cache_release(void *user_context, void *host);
928 
929 /** Free all memory and resources associated with the memoization cache.
930  * Must be called at a time when no other threads are accessing the cache.
931  */
932 extern void halide_memoization_cache_cleanup();
933 
934 /** Verify that a given range of memory has been initialized; only used when Target::MSAN is enabled.
935  *
936  * The default implementation simply calls the LLVM-provided __msan_check_mem_is_initialized() function.
937  *
938  * The return value should always be zero.
939  */
940 extern int halide_msan_check_memory_is_initialized(void *user_context, const void *ptr, uint64_t len, const char *name);
941 
942 /** Verify that the data pointed to by the halide_buffer_t is initialized (but *not* the halide_buffer_t itself),
943  * using halide_msan_check_memory_is_initialized() for checking.
944  *
945  * The default implementation takes pains to only check the active memory ranges
946  * (skipping padding), and sorting into ranges to always check the smallest number of
947  * ranges, in monotonically increasing memory order.
948  *
949  * Most client code should never need to replace the default implementation.
950  *
951  * The return value should always be zero.
952  */
953 extern int halide_msan_check_buffer_is_initialized(void *user_context, struct halide_buffer_t *buffer, const char *buf_name);
954 
955 /** Annotate that a given range of memory has been initialized;
956  * only used when Target::MSAN is enabled.
957  *
958  * The default implementation simply calls the LLVM-provided __msan_unpoison() function.
959  *
960  * The return value should always be zero.
961  */
962 extern int halide_msan_annotate_memory_is_initialized(void *user_context, const void *ptr, uint64_t len);
963 
964 /** Mark the data pointed to by the halide_buffer_t as initialized (but *not* the halide_buffer_t itself),
965  * using halide_msan_annotate_memory_is_initialized() for marking.
966  *
967  * The default implementation takes pains to only mark the active memory ranges
968  * (skipping padding), and sorting into ranges to always mark the smallest number of
969  * ranges, in monotonically increasing memory order.
970  *
971  * Most client code should never need to replace the default implementation.
972  *
973  * The return value should always be zero.
974  */
975 extern int halide_msan_annotate_buffer_is_initialized(void *user_context, struct halide_buffer_t *buffer);
976 extern void halide_msan_annotate_buffer_is_initialized_as_destructor(void *user_context, void *buffer);
977 
978 /** The error codes that may be returned by a Halide pipeline. */
979 enum halide_error_code_t {
980     /** There was no error. This is the value returned by Halide on success. */
981     halide_error_code_success = 0,
982 
983     /** An uncategorized error occurred. Refer to the string passed to halide_error. */
984     halide_error_code_generic_error = -1,
985 
986     /** A Func was given an explicit bound via Func::bound, but this
987      * was not large enough to encompass the region that is used of
988      * the Func by the rest of the pipeline. */
989     halide_error_code_explicit_bounds_too_small = -2,
990 
991     /** The elem_size field of a halide_buffer_t does not match the size in
992      * bytes of the type of that ImageParam. Probable type mismatch. */
993     halide_error_code_bad_type = -3,
994 
995     /** A pipeline would access memory outside of the halide_buffer_t passed
996      * in. */
997     halide_error_code_access_out_of_bounds = -4,
998 
999     /** A halide_buffer_t was given that spans more than 2GB of memory. */
1000     halide_error_code_buffer_allocation_too_large = -5,
1001 
1002     /** A halide_buffer_t was given with extents that multiply to a number
1003      * greater than 2^31-1 */
1004     halide_error_code_buffer_extents_too_large = -6,
1005 
1006     /** Applying explicit constraints on the size of an input or
1007      * output buffer shrank the size of that buffer below what will be
1008      * accessed by the pipeline. */
1009     halide_error_code_constraints_make_required_region_smaller = -7,
1010 
1011     /** A constraint on a size or stride of an input or output buffer
1012      * was not met by the halide_buffer_t passed in. */
1013     halide_error_code_constraint_violated = -8,
1014 
1015     /** A scalar parameter passed in was smaller than its minimum
1016      * declared value. */
1017     halide_error_code_param_too_small = -9,
1018 
1019     /** A scalar parameter passed in was greater than its minimum
1020      * declared value. */
1021     halide_error_code_param_too_large = -10,
1022 
1023     /** A call to halide_malloc returned NULL. */
1024     halide_error_code_out_of_memory = -11,
1025 
1026     /** A halide_buffer_t pointer passed in was NULL. */
1027     halide_error_code_buffer_argument_is_null = -12,
1028 
1029     /** debug_to_file failed to open or write to the specified
1030      * file. */
1031     halide_error_code_debug_to_file_failed = -13,
1032 
1033     /** The Halide runtime encountered an error while trying to copy
1034      * from device to host. Turn on -debug in your target string to
1035      * see more details. */
1036     halide_error_code_copy_to_host_failed = -14,
1037 
1038     /** The Halide runtime encountered an error while trying to copy
1039      * from host to device. Turn on -debug in your target string to
1040      * see more details. */
1041     halide_error_code_copy_to_device_failed = -15,
1042 
1043     /** The Halide runtime encountered an error while trying to
1044      * allocate memory on device. Turn on -debug in your target string
1045      * to see more details. */
1046     halide_error_code_device_malloc_failed = -16,
1047 
1048     /** The Halide runtime encountered an error while trying to
1049      * synchronize with a device. Turn on -debug in your target string
1050      * to see more details. */
1051     halide_error_code_device_sync_failed = -17,
1052 
1053     /** The Halide runtime encountered an error while trying to free a
1054      * device allocation. Turn on -debug in your target string to see
1055      * more details. */
1056     halide_error_code_device_free_failed = -18,
1057 
1058     /** Buffer has a non-zero device but no device interface, which
1059      * violates a Halide invariant. */
1060     halide_error_code_no_device_interface = -19,
1061 
1062     /** An error occurred when attempting to initialize the Matlab
1063      * runtime. */
1064     halide_error_code_matlab_init_failed = -20,
1065 
1066     /** The type of an mxArray did not match the expected type. */
1067     halide_error_code_matlab_bad_param_type = -21,
1068 
1069     /** There is a bug in the Halide compiler. */
1070     halide_error_code_internal_error = -22,
1071 
1072     /** The Halide runtime encountered an error while trying to launch
1073      * a GPU kernel. Turn on -debug in your target string to see more
1074      * details. */
1075     halide_error_code_device_run_failed = -23,
1076 
1077     /** The Halide runtime encountered a host pointer that violated
1078      * the alignment set for it by way of a call to
1079      * set_host_alignment */
1080     halide_error_code_unaligned_host_ptr = -24,
1081 
1082     /** A fold_storage directive was used on a dimension that is not
1083      * accessed in a monotonically increasing or decreasing fashion. */
1084     halide_error_code_bad_fold = -25,
1085 
1086     /** A fold_storage directive was used with a fold factor that was
1087      * too small to store all the values of a producer needed by the
1088      * consumer. */
1089     halide_error_code_fold_factor_too_small = -26,
1090 
1091     /** User-specified require() expression was not satisfied. */
1092     halide_error_code_requirement_failed = -27,
1093 
1094     /** At least one of the buffer's extents are negative. */
1095     halide_error_code_buffer_extents_negative = -28,
1096 
1097     halide_error_code_unused_29 = -29,
1098 
1099     halide_error_code_unused_30 = -30,
1100 
1101     /** A specialize_fail() schedule branch was selected at runtime. */
1102     halide_error_code_specialize_fail = -31,
1103 
1104     /** The Halide runtime encountered an error while trying to wrap a
1105      * native device handle.  Turn on -debug in your target string to
1106      * see more details. */
1107     halide_error_code_device_wrap_native_failed = -32,
1108 
1109     /** The Halide runtime encountered an error while trying to detach
1110      * a native device handle.  Turn on -debug in your target string
1111      * to see more details. */
1112     halide_error_code_device_detach_native_failed = -33,
1113 
1114     /** The host field on an input or output was null, the device
1115      * field was not zero, and the pipeline tries to use the buffer on
1116      * the host. You may be passing a GPU-only buffer to a pipeline
1117      * which is scheduled to use it on the CPU. */
1118     halide_error_code_host_is_null = -34,
1119 
1120     /** A folded buffer was passed to an extern stage, but the region
1121      * touched wraps around the fold boundary. */
1122     halide_error_code_bad_extern_fold = -35,
1123 
1124     /** Buffer has a non-null device_interface but device is 0, which
1125      * violates a Halide invariant. */
1126     halide_error_code_device_interface_no_device = -36,
1127 
1128     /** Buffer has both host and device dirty bits set, which violates
1129      * a Halide invariant. */
1130     halide_error_code_host_and_device_dirty = -37,
1131 
1132     /** The halide_buffer_t * passed to a halide runtime routine is
1133      * nullptr and this is not allowed. */
1134     halide_error_code_buffer_is_null = -38,
1135 
1136     /** The Halide runtime encountered an error while trying to copy
1137      * from one buffer to another. Turn on -debug in your target
1138      * string to see more details. */
1139     halide_error_code_device_buffer_copy_failed = -39,
1140 
1141     /** Attempted to make cropped/sliced alias of a buffer with a device
1142      * field, but the device_interface does not support cropping. */
1143     halide_error_code_device_crop_unsupported = -40,
1144 
1145     /** Cropping/slicing a buffer failed for some other reason. Turn on -debug
1146      * in your target string. */
1147     halide_error_code_device_crop_failed = -41,
1148 
1149     /** An operation on a buffer required an allocation on a
1150      * particular device interface, but a device allocation already
1151      * existed on a different device interface. Free the old one
1152      * first. */
1153     halide_error_code_incompatible_device_interface = -42,
1154 
1155     /** The dimensions field of a halide_buffer_t does not match the dimensions of that ImageParam. */
1156     halide_error_code_bad_dimensions = -43,
1157 
1158     /** An expression that would perform an integer division or modulo
1159      * by zero was evaluated. */
1160     halide_error_code_device_dirty_with_no_device_support = -44,
1161 
1162 };
1163 
1164 /** Halide calls the functions below on various error conditions. The
1165  * default implementations construct an error message, call
1166  * halide_error, then return the matching error code above. On
1167  * platforms that support weak linking, you can override these to
1168  * catch the errors individually. */
1169 
1170 /** A call into an extern stage for the purposes of bounds inference
1171  * failed. Returns the error code given by the extern stage. */
1172 extern int halide_error_bounds_inference_call_failed(void *user_context, const char *extern_stage_name, int result);
1173 
1174 /** A call to an extern stage failed. Returned the error code given by
1175  * the extern stage. */
1176 extern int halide_error_extern_stage_failed(void *user_context, const char *extern_stage_name, int result);
1177 
1178 /** Various other error conditions. See the enum above for a
1179  * description of each. */
1180 // @{
1181 extern int halide_error_explicit_bounds_too_small(void *user_context, const char *func_name, const char *var_name,
1182                                                   int min_bound, int max_bound, int min_required, int max_required);
1183 extern int halide_error_bad_type(void *user_context, const char *func_name,
1184                                  uint32_t type_given, uint32_t correct_type);  // N.B. The last two args are the bit representation of a halide_type_t
1185 extern int halide_error_bad_dimensions(void *user_context, const char *func_name,
1186                                        int32_t dimensions_given, int32_t correct_dimensions);
1187 extern int halide_error_access_out_of_bounds(void *user_context, const char *func_name,
1188                                              int dimension, int min_touched, int max_touched,
1189                                              int min_valid, int max_valid);
1190 extern int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name,
1191                                                     uint64_t allocation_size, uint64_t max_size);
1192 extern int halide_error_buffer_extents_negative(void *user_context, const char *buffer_name, int dimension, int extent);
1193 extern int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name,
1194                                                  int64_t actual_size, int64_t max_size);
1195 extern int halide_error_constraints_make_required_region_smaller(void *user_context, const char *buffer_name,
1196                                                                  int dimension,
1197                                                                  int constrained_min, int constrained_extent,
1198                                                                  int required_min, int required_extent);
1199 extern int halide_error_constraint_violated(void *user_context, const char *var, int val,
1200                                             const char *constrained_var, int constrained_val);
1201 extern int halide_error_param_too_small_i64(void *user_context, const char *param_name,
1202                                             int64_t val, int64_t min_val);
1203 extern int halide_error_param_too_small_u64(void *user_context, const char *param_name,
1204                                             uint64_t val, uint64_t min_val);
1205 extern int halide_error_param_too_small_f64(void *user_context, const char *param_name,
1206                                             double val, double min_val);
1207 extern int halide_error_param_too_large_i64(void *user_context, const char *param_name,
1208                                             int64_t val, int64_t max_val);
1209 extern int halide_error_param_too_large_u64(void *user_context, const char *param_name,
1210                                             uint64_t val, uint64_t max_val);
1211 extern int halide_error_param_too_large_f64(void *user_context, const char *param_name,
1212                                             double val, double max_val);
1213 extern int halide_error_out_of_memory(void *user_context);
1214 extern int halide_error_buffer_argument_is_null(void *user_context, const char *buffer_name);
1215 extern int halide_error_debug_to_file_failed(void *user_context, const char *func,
1216                                              const char *filename, int error_code);
1217 extern int halide_error_unaligned_host_ptr(void *user_context, const char *func_name, int alignment);
1218 extern int halide_error_host_is_null(void *user_context, const char *func_name);
1219 extern int halide_error_bad_fold(void *user_context, const char *func_name, const char *var_name,
1220                                  const char *loop_name);
1221 extern int halide_error_bad_extern_fold(void *user_context, const char *func_name,
1222                                         int dim, int min, int extent, int valid_min, int fold_factor);
1223 
1224 extern int halide_error_fold_factor_too_small(void *user_context, const char *func_name, const char *var_name,
1225                                               int fold_factor, const char *loop_name, int required_extent);
1226 extern int halide_error_requirement_failed(void *user_context, const char *condition, const char *message);
1227 extern int halide_error_specialize_fail(void *user_context, const char *message);
1228 extern int halide_error_no_device_interface(void *user_context);
1229 extern int halide_error_device_interface_no_device(void *user_context);
1230 extern int halide_error_host_and_device_dirty(void *user_context);
1231 extern int halide_error_buffer_is_null(void *user_context, const char *routine);
1232 extern int halide_error_device_dirty_with_no_device_support(void *user_context, const char *buffer_name);
1233 // @}
1234 
1235 /** Optional features a compilation Target can have.
1236  * Be sure to keep this in sync with the Feature enum in Target.h and the implementation of
1237  * get_runtime_compatible_target in Target.cpp if you add a new feature.
1238  */
1239 typedef enum halide_target_feature_t {
1240     halide_target_feature_jit = 0,          ///< Generate code that will run immediately inside the calling process.
1241     halide_target_feature_debug,            ///< Turn on debug info and output for runtime code.
1242     halide_target_feature_no_asserts,       ///< Disable all runtime checks, for slightly tighter code.
1243     halide_target_feature_no_bounds_query,  ///< Disable the bounds querying functionality.
1244 
1245     halide_target_feature_sse41,  ///< Use SSE 4.1 and earlier instructions. Only relevant on x86.
1246     halide_target_feature_avx,    ///< Use AVX 1 instructions. Only relevant on x86.
1247     halide_target_feature_avx2,   ///< Use AVX 2 instructions. Only relevant on x86.
1248     halide_target_feature_fma,    ///< Enable x86 FMA instruction
1249     halide_target_feature_fma4,   ///< Enable x86 (AMD) FMA4 instruction set
1250     halide_target_feature_f16c,   ///< Enable x86 16-bit float support
1251 
1252     halide_target_feature_armv7s,   ///< Generate code for ARMv7s. Only relevant for 32-bit ARM.
1253     halide_target_feature_no_neon,  ///< Avoid using NEON instructions. Only relevant for 32-bit ARM.
1254 
1255     halide_target_feature_vsx,              ///< Use VSX instructions. Only relevant on POWERPC.
1256     halide_target_feature_power_arch_2_07,  ///< Use POWER ISA 2.07 new instructions. Only relevant on POWERPC.
1257 
1258     halide_target_feature_cuda,               ///< Enable the CUDA runtime. Defaults to compute capability 2.0 (Fermi)
1259     halide_target_feature_cuda_capability30,  ///< Enable CUDA compute capability 3.0 (Kepler)
1260     halide_target_feature_cuda_capability32,  ///< Enable CUDA compute capability 3.2 (Tegra K1)
1261     halide_target_feature_cuda_capability35,  ///< Enable CUDA compute capability 3.5 (Kepler)
1262     halide_target_feature_cuda_capability50,  ///< Enable CUDA compute capability 5.0 (Maxwell)
1263     halide_target_feature_cuda_capability61,  ///< Enable CUDA compute capability 6.1 (Pascal)
1264     halide_target_feature_cuda_capability70,  ///< Enable CUDA compute capability 7.0 (Volta)
1265     halide_target_feature_cuda_capability75,  ///< Enable CUDA compute capability 7.5 (Turing)
1266     halide_target_feature_cuda_capability80,  ///< Enable CUDA compute capability 8.0 (Ampere)
1267 
1268     halide_target_feature_opencl,       ///< Enable the OpenCL runtime.
1269     halide_target_feature_cl_doubles,   ///< Enable double support on OpenCL targets
1270     halide_target_feature_cl_atomic64,  ///< Enable 64-bit atomics operations on OpenCL targets
1271 
1272     halide_target_feature_opengl,         ///< Enable the OpenGL runtime.
1273     halide_target_feature_openglcompute,  ///< Enable OpenGL Compute runtime.
1274 
1275     halide_target_feature_user_context,  ///< Generated code takes a user_context pointer as first argument
1276 
1277     halide_target_feature_matlab,  ///< Generate a mexFunction compatible with Matlab mex libraries. See tools/mex_halide.m.
1278 
1279     halide_target_feature_profile,     ///< Launch a sampling profiler alongside the Halide pipeline that monitors and reports the runtime used by each Func
1280     halide_target_feature_no_runtime,  ///< Do not include a copy of the Halide runtime in any generated object file or assembly
1281 
1282     halide_target_feature_metal,  ///< Enable the (Apple) Metal runtime.
1283 
1284     halide_target_feature_c_plus_plus_mangling,  ///< Generate C++ mangled names for result function, et al
1285 
1286     halide_target_feature_large_buffers,  ///< Enable 64-bit buffer indexing to support buffers > 2GB. Ignored if bits != 64.
1287 
1288     halide_target_feature_hvx_64,                 ///< Enable HVX 64 byte mode.
1289     halide_target_feature_hvx_128,                ///< Enable HVX 128 byte mode.
1290     halide_target_feature_hvx_v62,                ///< Enable Hexagon v62 architecture.
1291     halide_target_feature_fuzz_float_stores,      ///< On every floating point store, set the last bit of the mantissa to zero. Pipelines for which the output is very different with this feature enabled may also produce very different output on different processors.
1292     halide_target_feature_soft_float_abi,         ///< Enable soft float ABI. This only enables the soft float ABI calling convention, which does not necessarily use soft floats.
1293     halide_target_feature_msan,                   ///< Enable hooks for MSAN support.
1294     halide_target_feature_avx512,                 ///< Enable the base AVX512 subset supported by all AVX512 architectures. The specific feature sets are AVX-512F and AVX512-CD. See https://en.wikipedia.org/wiki/AVX-512 for a description of each AVX subset.
1295     halide_target_feature_avx512_knl,             ///< Enable the AVX512 features supported by Knight's Landing chips, such as the Xeon Phi x200. This includes the base AVX512 set, and also AVX512-CD and AVX512-ER.
1296     halide_target_feature_avx512_skylake,         ///< Enable the AVX512 features supported by Skylake Xeon server processors. This adds AVX512-VL, AVX512-BW, and AVX512-DQ to the base set. The main difference from the base AVX512 set is better support for small integer ops. Note that this does not include the Knight's Landing features. Note also that these features are not available on Skylake desktop and mobile processors.
1297     halide_target_feature_avx512_cannonlake,      ///< Enable the AVX512 features expected to be supported by future Cannonlake processors. This includes all of the Skylake features, plus AVX512-IFMA and AVX512-VBMI.
1298     halide_target_feature_hvx_use_shared_object,  ///< Deprecated
1299     halide_target_feature_trace_loads,            ///< Trace all loads done by the pipeline. Equivalent to calling Func::trace_loads on every non-inlined Func.
1300     halide_target_feature_trace_stores,           ///< Trace all stores done by the pipeline. Equivalent to calling Func::trace_stores on every non-inlined Func.
1301     halide_target_feature_trace_realizations,     ///< Trace all realizations done by the pipeline. Equivalent to calling Func::trace_realizations on every non-inlined Func.
1302     halide_target_feature_trace_pipeline,         ///< Trace the pipeline.
1303     halide_target_feature_hvx_v65,                ///< Enable Hexagon v65 architecture.
1304     halide_target_feature_hvx_v66,                ///< Enable Hexagon v66 architecture.
1305     halide_target_feature_cl_half,                ///< Enable half support on OpenCL targets
1306     halide_target_feature_strict_float,           ///< Turn off all non-IEEE floating-point optimization. Currently applies only to LLVM targets.
1307     halide_target_feature_tsan,                   ///< Enable hooks for TSAN support.
1308     halide_target_feature_asan,                   ///< Enable hooks for ASAN support.
1309     halide_target_feature_d3d12compute,           ///< Enable Direct3D 12 Compute runtime.
1310     halide_target_feature_check_unsafe_promises,  ///< Insert assertions for promises.
1311     halide_target_feature_hexagon_dma,            ///< Enable Hexagon DMA buffers.
1312     halide_target_feature_embed_bitcode,          ///< Emulate clang -fembed-bitcode flag.
1313     halide_target_feature_enable_llvm_loop_opt,   ///< Enable loop vectorization + unrolling in LLVM. Overrides halide_target_feature_disable_llvm_loop_opt. (Ignored for non-LLVM targets.)
1314     halide_target_feature_disable_llvm_loop_opt,  ///< Disable loop vectorization + unrolling in LLVM. (Ignored for non-LLVM targets.)
1315     halide_target_feature_wasm_simd128,           ///< Enable +simd128 instructions for WebAssembly codegen.
1316     halide_target_feature_wasm_signext,           ///< Enable +sign-ext instructions for WebAssembly codegen.
1317     halide_target_feature_wasm_sat_float_to_int,  ///< Enable saturating (nontrapping) float-to-int instructions for WebAssembly codegen.
1318     halide_target_feature_sve,                    ///< Enable ARM Scalable Vector Extensions
1319     halide_target_feature_sve2,                   ///< Enable ARM Scalable Vector Extensions v2
1320     halide_target_feature_egl,                    ///< Force use of EGL support.
1321 
1322     halide_target_feature_arm_dot_prod,  ///< Enable ARMv8.2-a dotprod extension (i.e. udot and sdot instructions)
1323     halide_target_feature_end            ///< A sentinel. Every target is considered to have this feature, and setting this feature does nothing.
1324 } halide_target_feature_t;
1325 
1326 /** This function is called internally by Halide in some situations to determine
1327  * if the current execution environment can support the given set of
1328  * halide_target_feature_t flags. The implementation must do the following:
1329  *
1330  * -- If there are flags set in features that the function knows *cannot* be supported, return 0.
1331  * -- Otherwise, return 1.
1332  * -- Note that any flags set in features that the function doesn't know how to test should be ignored;
1333  * this implies that a return value of 1 means "not known to be bad" rather than "known to be good".
1334  *
1335  * In other words: a return value of 0 means "It is not safe to use code compiled with these features",
1336  * while a return value of 1 means "It is not obviously unsafe to use code compiled with these features".
1337  *
1338  * The default implementation simply calls halide_default_can_use_target_features.
1339  *
1340  * Note that `features` points to an array of `count` uint64_t; this array must contain enough
1341  * bits to represent all the currently known features. Any excess bits must be set to zero.
1342  */
1343 // @{
1344 extern int halide_can_use_target_features(int count, const uint64_t *features);
1345 typedef int (*halide_can_use_target_features_t)(int count, const uint64_t *features);
1346 extern halide_can_use_target_features_t halide_set_custom_can_use_target_features(halide_can_use_target_features_t);
1347 // @}
1348 
1349 /**
1350  * This is the default implementation of halide_can_use_target_features; it is provided
1351  * for convenience of user code that may wish to extend halide_can_use_target_features
1352  * but continue providing existing support, e.g.
1353  *
1354  *     int halide_can_use_target_features(int count, const uint64_t *features) {
1355  *          if (features[halide_target_somefeature >> 6] & (1LL << (halide_target_somefeature & 63))) {
1356  *              if (!can_use_somefeature()) {
1357  *                  return 0;
1358  *              }
1359  *          }
1360  *          return halide_default_can_use_target_features(count, features);
1361  *     }
1362  */
1363 extern int halide_default_can_use_target_features(int count, const uint64_t *features);
1364 
1365 typedef struct halide_dimension_t {
1366     int32_t min, extent, stride;
1367 
1368     // Per-dimension flags. None are defined yet (This is reserved for future use).
1369     uint32_t flags;
1370 
1371 #ifdef __cplusplus
halide_dimension_thalide_dimension_t1372     HALIDE_ALWAYS_INLINE halide_dimension_t()
1373         : min(0), extent(0), stride(0), flags(0) {
1374     }
1375     HALIDE_ALWAYS_INLINE halide_dimension_t(int32_t m, int32_t e, int32_t s, uint32_t f = 0)
minhalide_dimension_t1376         : min(m), extent(e), stride(s), flags(f) {
1377     }
1378 
1379     HALIDE_ALWAYS_INLINE bool operator==(const halide_dimension_t &other) const {
1380         return (min == other.min) &&
1381                (extent == other.extent) &&
1382                (stride == other.stride) &&
1383                (flags == other.flags);
1384     }
1385 
1386     HALIDE_ALWAYS_INLINE bool operator!=(const halide_dimension_t &other) const {
1387         return !(*this == other);
1388     }
1389 #endif
1390 } halide_dimension_t;
1391 
1392 #ifdef __cplusplus
1393 }  // extern "C"
1394 #endif
1395 
1396 typedef enum { halide_buffer_flag_host_dirty = 1,
1397                halide_buffer_flag_device_dirty = 2 } halide_buffer_flags;
1398 
1399 /**
1400  * The raw representation of an image passed around by generated
1401  * Halide code. It includes some stuff to track whether the image is
1402  * not actually in main memory, but instead on a device (like a
1403  * GPU). For a more convenient C++ wrapper, use Halide::Buffer<T>. */
1404 typedef struct halide_buffer_t {
1405     /** A device-handle for e.g. GPU memory used to back this buffer. */
1406     uint64_t device;
1407 
1408     /** The interface used to interpret the above handle. */
1409     const struct halide_device_interface_t *device_interface;
1410 
1411     /** A pointer to the start of the data in main memory. In terms of
1412      * the Halide coordinate system, this is the address of the min
1413      * coordinates (defined below). */
1414     uint8_t *host;
1415 
1416     /** flags with various meanings. */
1417     uint64_t flags;
1418 
1419     /** The type of each buffer element. */
1420     struct halide_type_t type;
1421 
1422     /** The dimensionality of the buffer. */
1423     int32_t dimensions;
1424 
1425     /** The shape of the buffer. Halide does not own this array - you
1426      * must manage the memory for it yourself. */
1427     halide_dimension_t *dim;
1428 
1429     /** Pads the buffer up to a multiple of 8 bytes */
1430     void *padding;
1431 
1432 #ifdef __cplusplus
1433     /** Convenience methods for accessing the flags */
1434     // @{
get_flaghalide_buffer_t1435     HALIDE_ALWAYS_INLINE bool get_flag(halide_buffer_flags flag) const {
1436         return (flags & flag) != 0;
1437     }
1438 
set_flaghalide_buffer_t1439     HALIDE_ALWAYS_INLINE void set_flag(halide_buffer_flags flag, bool value) {
1440         if (value) {
1441             flags |= flag;
1442         } else {
1443             flags &= ~flag;
1444         }
1445     }
1446 
host_dirtyhalide_buffer_t1447     HALIDE_ALWAYS_INLINE bool host_dirty() const {
1448         return get_flag(halide_buffer_flag_host_dirty);
1449     }
1450 
device_dirtyhalide_buffer_t1451     HALIDE_ALWAYS_INLINE bool device_dirty() const {
1452         return get_flag(halide_buffer_flag_device_dirty);
1453     }
1454 
1455     HALIDE_ALWAYS_INLINE void set_host_dirty(bool v = true) {
1456         set_flag(halide_buffer_flag_host_dirty, v);
1457     }
1458 
1459     HALIDE_ALWAYS_INLINE void set_device_dirty(bool v = true) {
1460         set_flag(halide_buffer_flag_device_dirty, v);
1461     }
1462     // @}
1463 
1464     /** The total number of elements this buffer represents. Equal to
1465      * the product of the extents */
number_of_elementshalide_buffer_t1466     HALIDE_ALWAYS_INLINE size_t number_of_elements() const {
1467         size_t s = 1;
1468         for (int i = 0; i < dimensions; i++) {
1469             s *= dim[i].extent;
1470         }
1471         return s;
1472     }
1473 
1474     /** A pointer to the element with the lowest address. If all
1475      * strides are positive, equal to the host pointer. */
beginhalide_buffer_t1476     HALIDE_ALWAYS_INLINE uint8_t *begin() const {
1477         ptrdiff_t index = 0;
1478         for (int i = 0; i < dimensions; i++) {
1479             if (dim[i].stride < 0) {
1480                 index += dim[i].stride * (dim[i].extent - 1);
1481             }
1482         }
1483         return host + index * type.bytes();
1484     }
1485 
1486     /** A pointer to one beyond the element with the highest address. */
endhalide_buffer_t1487     HALIDE_ALWAYS_INLINE uint8_t *end() const {
1488         ptrdiff_t index = 0;
1489         for (int i = 0; i < dimensions; i++) {
1490             if (dim[i].stride > 0) {
1491                 index += dim[i].stride * (dim[i].extent - 1);
1492             }
1493         }
1494         index += 1;
1495         return host + index * type.bytes();
1496     }
1497 
1498     /** The total number of bytes spanned by the data in memory. */
size_in_byteshalide_buffer_t1499     HALIDE_ALWAYS_INLINE size_t size_in_bytes() const {
1500         return (size_t)(end() - begin());
1501     }
1502 
1503     /** A pointer to the element at the given location. */
address_ofhalide_buffer_t1504     HALIDE_ALWAYS_INLINE uint8_t *address_of(const int *pos) const {
1505         ptrdiff_t index = 0;
1506         for (int i = 0; i < dimensions; i++) {
1507             index += dim[i].stride * (pos[i] - dim[i].min);
1508         }
1509         return host + index * type.bytes();
1510     }
1511 
1512     /** Attempt to call device_sync for the buffer. If the buffer
1513      * has no device_interface (or no device_sync), this is a quiet no-op.
1514      * Calling this explicitly should rarely be necessary, except for profiling. */
1515     HALIDE_ALWAYS_INLINE int device_sync(void *ctx = NULL) {
1516         if (device_interface && device_interface->device_sync) {
1517             return device_interface->device_sync(ctx, this);
1518         }
1519         return 0;
1520     }
1521 
1522     /** Check if an input buffer passed extern stage is a querying
1523      * bounds. Compared to doing the host pointer check directly,
1524      * this both adds clarity to code and will facilitate moving to
1525      * another representation for bounds query arguments. */
is_bounds_queryhalide_buffer_t1526     HALIDE_ALWAYS_INLINE bool is_bounds_query() const {
1527         return host == NULL && device == 0;
1528     }
1529 
1530 #endif
1531 } halide_buffer_t;
1532 
1533 #ifdef __cplusplus
1534 extern "C" {
1535 #endif
1536 
1537 #ifndef HALIDE_ATTRIBUTE_DEPRECATED
1538 #ifdef HALIDE_ALLOW_DEPRECATED
1539 #define HALIDE_ATTRIBUTE_DEPRECATED(x)
1540 #else
1541 #ifdef _MSC_VER
1542 #define HALIDE_ATTRIBUTE_DEPRECATED(x) __declspec(deprecated(x))
1543 #else
1544 #define HALIDE_ATTRIBUTE_DEPRECATED(x) __attribute__((deprecated(x)))
1545 #endif
1546 #endif
1547 #endif
1548 
1549 /** halide_scalar_value_t is a simple union able to represent all the well-known
1550  * scalar values in a filter argument. Note that it isn't tagged with a type;
1551  * you must ensure you know the proper type before accessing. Most user
1552  * code will never need to create instances of this struct; its primary use
1553  * is to hold def/min/max values in a halide_filter_argument_t. (Note that
1554  * this is conceptually just a union; it's wrapped in a struct to ensure
1555  * that it doesn't get anonymized by LLVM.)
1556  */
1557 struct halide_scalar_value_t {
1558     union {
1559         bool b;
1560         int8_t i8;
1561         int16_t i16;
1562         int32_t i32;
1563         int64_t i64;
1564         uint8_t u8;
1565         uint16_t u16;
1566         uint32_t u32;
1567         uint64_t u64;
1568         float f32;
1569         double f64;
1570         void *handle;
1571     } u;
1572 #ifdef __cplusplus
halide_scalar_value_thalide_scalar_value_t1573     HALIDE_ALWAYS_INLINE halide_scalar_value_t() {
1574         u.u64 = 0;
1575     }
1576 #endif
1577 };
1578 
1579 enum halide_argument_kind_t {
1580     halide_argument_kind_input_scalar = 0,
1581     halide_argument_kind_input_buffer = 1,
1582     halide_argument_kind_output_buffer = 2
1583 };
1584 
1585 /*
1586     These structs must be robust across different compilers and settings; when
1587     modifying them, strive for the following rules:
1588 
1589     1) All fields are explicitly sized. I.e. must use int32_t and not "int"
1590     2) All fields must land on an alignment boundary that is the same as their size
1591     3) Explicit padding is added to make that so
1592     4) The sizeof the struct is padded out to a multiple of the largest natural size thing in the struct
1593     5) don't forget that 32 and 64 bit pointers are different sizes
1594 */
1595 
1596 /**
1597  * Obsolete version of halide_filter_argument_t; only present in
1598  * code that wrote halide_filter_metadata_t version 0.
1599  */
1600 struct halide_filter_argument_t_v0 {
1601     const char *name;
1602     int32_t kind;
1603     int32_t dimensions;
1604     struct halide_type_t type;
1605     const struct halide_scalar_value_t *def, *min, *max;
1606 };
1607 
1608 /**
1609  * halide_filter_argument_t is essentially a plain-C-struct equivalent to
1610  * Halide::Argument; most user code will never need to create one.
1611  */
1612 struct halide_filter_argument_t {
1613     const char *name;    // name of the argument; will never be null or empty.
1614     int32_t kind;        // actually halide_argument_kind_t
1615     int32_t dimensions;  // always zero for scalar arguments
1616     struct halide_type_t type;
1617     // These pointers should always be null for buffer arguments,
1618     // and *may* be null for scalar arguments. (A null value means
1619     // there is no def/min/max/estimate specified for this argument.)
1620     const struct halide_scalar_value_t *scalar_def, *scalar_min, *scalar_max, *scalar_estimate;
1621     // This pointer should always be null for scalar arguments,
1622     // and *may* be null for buffer arguments. If not null, it should always
1623     // point to an array of dimensions*2 pointers, which will be the (min, extent)
1624     // estimates for each dimension of the buffer. (Note that any of the pointers
1625     // may be null as well.)
1626     int64_t const *const *buffer_estimates;
1627 };
1628 
1629 struct halide_filter_metadata_t {
1630 #ifdef __cplusplus
1631     static const int32_t VERSION = 1;
1632 #endif
1633 
1634     /** version of this metadata; currently always 1. */
1635     int32_t version;
1636 
1637     /** The number of entries in the arguments field. This is always >= 1. */
1638     int32_t num_arguments;
1639 
1640     /** An array of the filters input and output arguments; this will never be
1641      * null. The order of arguments is not guaranteed (input and output arguments
1642      * may come in any order); however, it is guaranteed that all arguments
1643      * will have a unique name within a given filter. */
1644     const struct halide_filter_argument_t *arguments;
1645 
1646     /** The Target for which the filter was compiled. This is always
1647      * a canonical Target string (ie a product of Target::to_string). */
1648     const char *target;
1649 
1650     /** The function name of the filter. */
1651     const char *name;
1652 };
1653 
1654 /** halide_register_argv_and_metadata() is a **user-defined** function that
1655  * must be provided in order to use the registration.cc files produced
1656  * by Generators when the 'registration' output is requested. Each registration.cc
1657  * file provides a static initializer that calls this function with the given
1658  * filter's argv-call variant, its metadata, and (optionally) and additional
1659  * textual data that the build system chooses to tack on for its own purposes.
1660  * Note that this will be called at static-initializer time (i.e., before
1661  * main() is called), and in an unpredictable order. Note that extra_key_value_pairs
1662  * may be nullptr; if it's not null, it's expected to be a null-terminated list
1663  * of strings, with an even number of entries. */
1664 void halide_register_argv_and_metadata(
1665     int (*filter_argv_call)(void **),
1666     const struct halide_filter_metadata_t *filter_metadata,
1667     const char *const *extra_key_value_pairs);
1668 
1669 /** The functions below here are relevant for pipelines compiled with
1670  * the -profile target flag, which runs a sampling profiler thread
1671  * alongside the pipeline. */
1672 
1673 /** Per-Func state tracked by the sampling profiler. */
1674 struct halide_profiler_func_stats {
1675     /** Total time taken evaluating this Func (in nanoseconds). */
1676     uint64_t time;
1677 
1678     /** The current memory allocation of this Func. */
1679     uint64_t memory_current;
1680 
1681     /** The peak memory allocation of this Func. */
1682     uint64_t memory_peak;
1683 
1684     /** The total memory allocation of this Func. */
1685     uint64_t memory_total;
1686 
1687     /** The peak stack allocation of this Func's threads. */
1688     uint64_t stack_peak;
1689 
1690     /** The average number of thread pool worker threads active while computing this Func. */
1691     uint64_t active_threads_numerator, active_threads_denominator;
1692 
1693     /** The name of this Func. A global constant string. */
1694     const char *name;
1695 
1696     /** The total number of memory allocation of this Func. */
1697     int num_allocs;
1698 };
1699 
1700 /** Per-pipeline state tracked by the sampling profiler. These exist
1701  * in a linked list. */
1702 struct halide_profiler_pipeline_stats {
1703     /** Total time spent inside this pipeline (in nanoseconds) */
1704     uint64_t time;
1705 
1706     /** The current memory allocation of funcs in this pipeline. */
1707     uint64_t memory_current;
1708 
1709     /** The peak memory allocation of funcs in this pipeline. */
1710     uint64_t memory_peak;
1711 
1712     /** The total memory allocation of funcs in this pipeline. */
1713     uint64_t memory_total;
1714 
1715     /** The average number of thread pool worker threads doing useful
1716      * work while computing this pipeline. */
1717     uint64_t active_threads_numerator, active_threads_denominator;
1718 
1719     /** The name of this pipeline. A global constant string. */
1720     const char *name;
1721 
1722     /** An array containing states for each Func in this pipeline. */
1723     struct halide_profiler_func_stats *funcs;
1724 
1725     /** The next pipeline_stats pointer. It's a void * because types
1726      * in the Halide runtime may not currently be recursive. */
1727     void *next;
1728 
1729     /** The number of funcs in this pipeline. */
1730     int num_funcs;
1731 
1732     /** An internal base id used to identify the funcs in this pipeline. */
1733     int first_func_id;
1734 
1735     /** The number of times this pipeline has been run. */
1736     int runs;
1737 
1738     /** The total number of samples taken inside of this pipeline. */
1739     int samples;
1740 
1741     /** The total number of memory allocation of funcs in this pipeline. */
1742     int num_allocs;
1743 };
1744 
1745 /** The global state of the profiler. */
1746 
1747 struct halide_profiler_state {
1748     /** Guards access to the fields below. If not locked, the sampling
1749      * profiler thread is free to modify things below (including
1750      * reordering the linked list of pipeline stats). */
1751     struct halide_mutex lock;
1752 
1753     /** The amount of time the profiler thread sleeps between samples
1754      * in milliseconds. Defaults to 1 */
1755     int sleep_time;
1756 
1757     /** An internal id used for bookkeeping. */
1758     int first_free_id;
1759 
1760     /** The id of the current running Func. Set by the pipeline, read
1761      * periodically by the profiler thread. */
1762     int current_func;
1763 
1764     /** The number of threads currently doing work. */
1765     int active_threads;
1766 
1767     /** A linked list of stats gathered for each pipeline. */
1768     struct halide_profiler_pipeline_stats *pipelines;
1769 
1770     /** Retrieve remote profiler state. Used so that the sampling
1771      * profiler can follow along with execution that occurs elsewhere,
1772      * e.g. on a DSP. If null, it reads from the int above instead. */
1773     void (*get_remote_profiler_state)(int *func, int *active_workers);
1774 
1775     /** Sampling thread reference to be joined at shutdown. */
1776     struct halide_thread *sampling_thread;
1777 };
1778 
1779 /** Profiler func ids with special meanings. */
1780 enum {
1781     /// current_func takes on this value when not inside Halide code
1782     halide_profiler_outside_of_halide = -1,
1783     /// Set current_func to this value to tell the profiling thread to
1784     /// halt. It will start up again next time you run a pipeline with
1785     /// profiling enabled.
1786     halide_profiler_please_stop = -2
1787 };
1788 
1789 /** Get a pointer to the global profiler state for programmatic
1790  * inspection. Lock it before using to pause the profiler. */
1791 extern struct halide_profiler_state *halide_profiler_get_state();
1792 
1793 /** Get a pointer to the pipeline state associated with pipeline_name.
1794  * This function grabs the global profiler state's lock on entry. */
1795 extern struct halide_profiler_pipeline_stats *halide_profiler_get_pipeline_state(const char *pipeline_name);
1796 
1797 /** Reset profiler state cheaply. May leave threads running or some
1798  * memory allocated but all accumluated statistics are reset.
1799  * WARNING: Do NOT call this method while any halide pipeline is
1800  * running; halide_profiler_memory_allocate/free and
1801  * halide_profiler_stack_peak_update update the profiler pipeline's
1802  * state without grabbing the global profiler state's lock. */
1803 extern void halide_profiler_reset();
1804 
1805 /** Reset all profiler state.
1806  * WARNING: Do NOT call this method while any halide pipeline is
1807  * running; halide_profiler_memory_allocate/free and
1808  * halide_profiler_stack_peak_update update the profiler pipeline's
1809  * state without grabbing the global profiler state's lock. */
1810 void halide_profiler_shutdown();
1811 
1812 /** Print out timing statistics for everything run since the last
1813  * reset. Also happens at process exit. */
1814 extern void halide_profiler_report(void *user_context);
1815 
1816 /// \name "Float16" functions
1817 /// These functions operate of bits (``uint16_t``) representing a half
1818 /// precision floating point number (IEEE-754 2008 binary16).
1819 //{@
1820 
1821 /** Read bits representing a half precision floating point number and return
1822  *  the float that represents the same value */
1823 extern float halide_float16_bits_to_float(uint16_t);
1824 
1825 /** Read bits representing a half precision floating point number and return
1826  *  the double that represents the same value */
1827 extern double halide_float16_bits_to_double(uint16_t);
1828 
1829 // TODO: Conversion functions to half
1830 
1831 //@}
1832 
1833 // Allocating and freeing device memory is often very slow. The
1834 // methods below give Halide's runtime permission to hold onto device
1835 // memory to service future requests instead of returning it to the
1836 // underlying device API. The API does not manage an allocation pool,
1837 // all it does is provide access to a shared counter that acts as a
1838 // limit on the unused memory not yet returned to the underlying
1839 // device API. It makes callbacks to participants when memory needs to
1840 // be released because the limit is about to be exceeded (either
1841 // because the limit has been reduced, or because the memory owned by
1842 // some participant becomes unused).
1843 
1844 /** Tell Halide whether or not it is permitted to hold onto device
1845  * allocations to service future requests instead of returning them
1846  * eagerly to the underlying device API. Many device allocators are
1847  * quite slow, so it can be beneficial to set this to true. The
1848  * default value for now is false.
1849  *
1850  * Note that if enabled, the eviction policy is very simplistic. The
1851  * 32 most-recently used allocations are preserved, regardless of
1852  * their size. Additionally, if a call to cuMalloc results in an
1853  * out-of-memory error, the entire cache is flushed and the allocation
1854  * is retried. See https://github.com/halide/Halide/issues/4093
1855  *
1856  * If set to false, releases all unused device allocations back to the
1857  * underlying device APIs. For finer-grained control, see specific
1858  * methods in each device api runtime. */
1859 extern int halide_reuse_device_allocations(void *user_context, bool);
1860 
1861 /** Determines whether on device_free the memory is returned
1862  * immediately to the device API, or placed on a free list for future
1863  * use. Override and switch based on the user_context for
1864  * finer-grained control. By default just returns the value most
1865  * recently set by the method above. */
1866 extern bool halide_can_reuse_device_allocations(void *user_context);
1867 
1868 struct halide_device_allocation_pool {
1869     int (*release_unused)(void *user_context);
1870     struct halide_device_allocation_pool *next;
1871 };
1872 
1873 /** Register a callback to be informed when
1874  * halide_reuse_device_allocations(false) is called, and all unused
1875  * device allocations must be released. The object passed should have
1876  * global lifetime, and its next field will be clobbered. */
1877 extern void halide_register_device_allocation_pool(struct halide_device_allocation_pool *);
1878 
1879 #ifdef __cplusplus
1880 }  // End extern "C"
1881 #endif
1882 
1883 #ifdef __cplusplus
1884 
1885 namespace {
1886 template<typename T>
1887 struct check_is_pointer;
1888 template<typename T>
1889 struct check_is_pointer<T *> {};
1890 }  // namespace
1891 
1892 /** Construct the halide equivalent of a C type */
1893 template<typename T>
1894 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of() {
1895     // Create a compile-time error if T is not a pointer (without
1896     // using any includes - this code goes into the runtime).
1897     check_is_pointer<T> check;
1898     (void)check;
1899     return halide_type_t(halide_type_handle, 64);
1900 }
1901 
1902 template<>
1903 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<float>() {
1904     return halide_type_t(halide_type_float, 32);
1905 }
1906 
1907 template<>
1908 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<double>() {
1909     return halide_type_t(halide_type_float, 64);
1910 }
1911 
1912 template<>
1913 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<bool>() {
1914     return halide_type_t(halide_type_uint, 1);
1915 }
1916 
1917 template<>
1918 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint8_t>() {
1919     return halide_type_t(halide_type_uint, 8);
1920 }
1921 
1922 template<>
1923 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint16_t>() {
1924     return halide_type_t(halide_type_uint, 16);
1925 }
1926 
1927 template<>
1928 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint32_t>() {
1929     return halide_type_t(halide_type_uint, 32);
1930 }
1931 
1932 template<>
1933 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint64_t>() {
1934     return halide_type_t(halide_type_uint, 64);
1935 }
1936 
1937 template<>
1938 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int8_t>() {
1939     return halide_type_t(halide_type_int, 8);
1940 }
1941 
1942 template<>
1943 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int16_t>() {
1944     return halide_type_t(halide_type_int, 16);
1945 }
1946 
1947 template<>
1948 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int32_t>() {
1949     return halide_type_t(halide_type_int, 32);
1950 }
1951 
1952 template<>
1953 HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int64_t>() {
1954     return halide_type_t(halide_type_int, 64);
1955 }
1956 
1957 #endif
1958 
1959 #endif  // HALIDE_HALIDERUNTIME_H
1960