-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathHalideRuntime.h
2221 lines (1903 loc) · 99.6 KB
/
HalideRuntime.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef HALIDE_HALIDERUNTIME_H
#define HALIDE_HALIDERUNTIME_H
#ifndef COMPILING_HALIDE_RUNTIME
#ifdef __cplusplus
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string_view>
#else
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#endif
#else
#include "runtime_internal.h"
#endif
// Note that the canonical Halide version is considered to be defined here
// (rather than in the build system); we redundantly define the value in
// our CMake build, so that we ensure that the in-build metadata (eg soversion)
// matches, but keeping the canonical version here makes it easier to keep
// downstream build systems (eg Blaze/Bazel) properly in sync with the source.
#define HALIDE_VERSION_MAJOR 20
#define HALIDE_VERSION_MINOR 0
#define HALIDE_VERSION_PATCH 0
#ifdef __cplusplus
// Forward declare type to allow naming typed handles.
// See Type.h for documentation.
template<typename T>
struct halide_handle_traits;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
// Note that (for MSVC) you should not use "inline" along with HALIDE_ALWAYS_INLINE;
// it is not necessary, and may produce warnings for some build configurations.
#define HALIDE_ALWAYS_INLINE __forceinline
#define HALIDE_NEVER_INLINE __declspec(noinline)
#else
// Note that (for Posixy compilers) you should always use "inline" along with HALIDE_ALWAYS_INLINE;
// otherwise some corner-case scenarios may erroneously report link errors.
#define HALIDE_ALWAYS_INLINE inline __attribute__((always_inline))
#define HALIDE_NEVER_INLINE __attribute__((noinline))
#endif
#ifndef HALIDE_MUST_USE_RESULT
#ifdef __has_attribute
#if __has_attribute(nodiscard)
// C++17 or later
#define HALIDE_MUST_USE_RESULT [[nodiscard]]
#elif __has_attribute(warn_unused_result)
// Clang/GCC
#define HALIDE_MUST_USE_RESULT __attribute__((warn_unused_result))
#else
#define HALIDE_MUST_USE_RESULT
#endif
#else
#define HALIDE_MUST_USE_RESULT
#endif
#endif
// Annotation for AOT and JIT calls -- if undefined, use no annotation.
// To ensure that all results are checked, do something like
//
// -DHALIDE_FUNCTION_ATTRS=HALIDE_MUST_USE_RESULT
//
// in your C++ compiler options
#ifndef HALIDE_FUNCTION_ATTRS
#define HALIDE_FUNCTION_ATTRS
#endif
#ifndef HALIDE_EXPORT_SYMBOL
#ifdef _MSC_VER
#define HALIDE_EXPORT_SYMBOL __declspec(dllexport)
#else
#define HALIDE_EXPORT_SYMBOL __attribute__((visibility("default")))
#endif
#endif
#ifndef COMPILING_HALIDE_RUNTIME
// ASAN builds can cause linker errors for Float16, so sniff for that and
// don't enable it by default.
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define HALIDE_RUNTIME_ASAN_DETECTED
#endif
#endif
#if defined(__SANITIZE_ADDRESS__) && !defined(HALIDE_RUNTIME_ASAN_DETECTED)
#define HALIDE_RUNTIME_ASAN_DETECTED
#endif
#if !defined(HALIDE_RUNTIME_ASAN_DETECTED)
// clang had _Float16 added as a reserved name in clang 8, but
// doesn't actually support it on most platforms until clang 15.
// Ideally there would be a better way to detect if the type
// is supported, even in a compiler independent fashion, but
// coming up with one has proven elusive.
#if defined(__clang__) && (__clang_major__ >= 15) && !defined(__EMSCRIPTEN__) && !defined(__i386__)
#if defined(__is_identifier)
#if !__is_identifier(_Float16)
#define HALIDE_CPP_COMPILER_HAS_FLOAT16
#endif
#endif
#endif
// Similarly, detecting _Float16 for gcc is problematic.
// For now, we say that if >= v12, and compiling on x86 or arm,
// we assume support. This may need revision.
#if defined(__GNUC__) && (__GNUC__ >= 12)
#if defined(__x86_64__) || (defined(__i386__) && (__GNUC__ >= 14) && defined(__SSE2__)) || ((defined(__arm__) || defined(__aarch64__)) && (__GNUC__ >= 13))
#define HALIDE_CPP_COMPILER_HAS_FLOAT16
#endif
#endif
#endif // !HALIDE_RUNTIME_ASAN_DETECTED
#endif // !COMPILING_HALIDE_RUNTIME
/** \file
*
* This file declares the routines used by Halide internally in its
* runtime. On platforms that support weak linking, these can be
* replaced with user-defined versions by defining an extern "C"
* function with the same name and signature.
*
* When doing Just In Time (JIT) compilation members of
* some_pipeline_or_func.jit_handlers() must be replaced instead. The
* corresponding methods are documented below.
*
* All of these functions take a "void *user_context" parameter as their
* first argument; if the Halide kernel that calls back to any of these
* functions has been compiled with the UserContext feature set on its Target,
* then the value of that pointer passed from the code that calls the
* Halide kernel is piped through to the function.
*
* Some of these are also useful to call when using the default
* implementation. E.g. halide_shutdown_thread_pool.
*
* Note that even on platforms with weak linking, some linker setups
* may not respect the override you provide. E.g. if the override is
* in a shared library and the halide object files are linked directly
* into the output, the builtin versions of the runtime functions will
* be called. See your linker documentation for more details. On
* Linux, LD_DYNAMIC_WEAK=1 may help.
*
*/
// Forward-declare to suppress warnings if compiling as C.
struct halide_buffer_t;
/** Print a message to stderr. Main use is to support tracing
* functionality, print, and print_when calls. Also called by the default
* halide_error. This function can be replaced in JITed code by using
* halide_custom_print and providing an implementation of halide_print
* in AOT code. See Func::set_custom_print.
*/
// @{
extern void halide_print(void *user_context, const char *);
extern void halide_default_print(void *user_context, const char *);
typedef void (*halide_print_t)(void *, const char *);
extern halide_print_t halide_set_custom_print(halide_print_t print);
// @}
/** Halide calls this function on runtime errors (for example bounds
* checking failures). This function can be replaced in JITed code by
* using Func::set_error_handler, or in AOT code by calling
* halide_set_error_handler. In AOT code on platforms that support
* weak linking (i.e. not Windows), you can also override it by simply
* defining your own halide_error.
*/
// @{
extern void halide_error(void *user_context, const char *);
extern void halide_default_error(void *user_context, const char *);
typedef void (*halide_error_handler_t)(void *, const char *);
extern halide_error_handler_t halide_set_error_handler(halide_error_handler_t handler);
// @}
/** Cross-platform mutex. Must be initialized with zero and implementation
* must treat zero as an unlocked mutex with no waiters, etc.
*/
struct halide_mutex {
uintptr_t _private[1];
};
/** Cross platform condition variable. Must be initialized to 0. */
struct halide_cond {
uintptr_t _private[1];
};
/** A basic set of mutex and condition variable functions, which call
* platform specific code for mutual exclusion. Equivalent to posix
* calls. */
//@{
extern void halide_mutex_lock(struct halide_mutex *mutex);
extern void halide_mutex_unlock(struct halide_mutex *mutex);
extern void halide_cond_signal(struct halide_cond *cond);
extern void halide_cond_broadcast(struct halide_cond *cond);
extern void halide_cond_wait(struct halide_cond *cond, struct halide_mutex *mutex);
//@}
/** Functions for constructing/destroying/locking/unlocking arrays of mutexes. */
struct halide_mutex_array;
//@{
extern struct halide_mutex_array *halide_mutex_array_create(uint64_t sz);
extern void halide_mutex_array_destroy(void *user_context, void *array);
extern int halide_mutex_array_lock(struct halide_mutex_array *array, int entry);
extern int halide_mutex_array_unlock(struct halide_mutex_array *array, int entry);
//@}
/** Define halide_do_par_for to replace the default thread pool
* implementation. halide_shutdown_thread_pool can also be called to
* release resources used by the default thread pool on platforms
* where it makes sense. See Func::set_custom_do_task and
* Func::set_custom_do_par_for. Should return zero if all the jobs
* return zero, or an arbitrarily chosen return value from one of the
* jobs otherwise.
*/
//@{
typedef int (*halide_task_t)(void *user_context, int task_number, uint8_t *closure);
extern int halide_do_par_for(void *user_context,
halide_task_t task,
int min, int size, uint8_t *closure);
extern void halide_shutdown_thread_pool(void);
//@}
/** Set a custom method for performing a parallel for loop. Returns
* the old do_par_for handler. */
typedef int (*halide_do_par_for_t)(void *, halide_task_t, int, int, uint8_t *);
extern halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t do_par_for);
/** An opaque struct representing a semaphore. Used by the task system for async tasks. */
struct halide_semaphore_t {
uint64_t _private[2];
};
/** A struct representing a semaphore and a number of items that must
* be acquired from it. Used in halide_parallel_task_t below. */
struct halide_semaphore_acquire_t {
struct halide_semaphore_t *semaphore;
int count;
};
extern int halide_semaphore_init(struct halide_semaphore_t *, int n);
extern int halide_semaphore_release(struct halide_semaphore_t *, int n);
extern bool halide_semaphore_try_acquire(struct halide_semaphore_t *, int n);
typedef int (*halide_semaphore_init_t)(struct halide_semaphore_t *, int);
typedef int (*halide_semaphore_release_t)(struct halide_semaphore_t *, int);
typedef bool (*halide_semaphore_try_acquire_t)(struct halide_semaphore_t *, int);
/** A task representing a serial for loop evaluated over some range.
* Note that task_parent is a pass through argument that should be
* passed to any dependent taks that are invoked using halide_do_parallel_tasks
* underneath this call. */
typedef int (*halide_loop_task_t)(void *user_context, int min, int extent,
uint8_t *closure, void *task_parent);
/** A parallel task to be passed to halide_do_parallel_tasks. This
* task may recursively call halide_do_parallel_tasks, and there may
* be complex dependencies between seemingly unrelated tasks expressed
* using semaphores. If you are using a custom task system, care must
* be taken to avoid potential deadlock. This can be done by carefully
* respecting the static metadata at the end of the task struct.*/
struct halide_parallel_task_t {
// The function to call. It takes a user context, a min and
// extent, a closure, and a task system pass through argument.
halide_loop_task_t fn;
// The closure to pass it
uint8_t *closure;
// The name of the function to be called. For debugging purposes only.
const char *name;
// An array of semaphores that must be acquired before the
// function is called. Must be reacquired for every call made.
struct halide_semaphore_acquire_t *semaphores;
int num_semaphores;
// The entire range the function should be called over. This range
// may be sliced up and the function called multiple times.
int min, extent;
// A parallel task provides several pieces of metadata to prevent
// unbounded resource usage or deadlock.
// The first is the minimum number of execution contexts (call
// stacks or threads) necessary for the function to run to
// completion. This may be greater than one when there is nested
// parallelism with internal producer-consumer relationships
// (calling the function recursively spawns and blocks on parallel
// sub-tasks that communicate with each other via semaphores). If
// a parallel runtime calls the function when fewer than this many
// threads are idle, it may need to create more threads to
// complete the task, or else risk deadlock due to committing all
// threads to tasks that cannot complete without more.
//
// FIXME: Note that extern stages are assumed to only require a
// single thread to complete. If the extern stage is itself a
// Halide pipeline, this may be an underestimate.
int min_threads;
// The calls to the function should be in serial order from min to min+extent-1, with only
// one executing at a time. If false, any order is fine, and
// concurrency is fine.
bool serial;
};
/** Enqueue some number of the tasks described above and wait for them
* to complete. While waiting, the calling threads assists with either
* the tasks enqueued, or other non-blocking tasks in the task
* system. Note that task_parent should be NULL for top-level calls
* and the pass through argument if this call is being made from
* another task. */
extern int halide_do_parallel_tasks(void *user_context, int num_tasks,
struct halide_parallel_task_t *tasks,
void *task_parent);
/** If you use the default do_par_for, you can still set a custom
* handler to perform each individual task. Returns the old handler. */
//@{
typedef int (*halide_do_task_t)(void *, halide_task_t, int, uint8_t *);
extern halide_do_task_t halide_set_custom_do_task(halide_do_task_t do_task);
extern int halide_do_task(void *user_context, halide_task_t f, int idx,
uint8_t *closure);
//@}
/** The version of do_task called for loop tasks. By default calls the
* loop task with the same arguments. */
// @{
typedef int (*halide_do_loop_task_t)(void *, halide_loop_task_t, int, int, uint8_t *, void *);
extern halide_do_loop_task_t halide_set_custom_do_loop_task(halide_do_loop_task_t do_task);
extern int halide_do_loop_task(void *user_context, halide_loop_task_t f, int min, int extent,
uint8_t *closure, void *task_parent);
//@}
/** Provide an entire custom tasking runtime via function
* pointers. Note that do_task and semaphore_try_acquire are only ever
* called by halide_default_do_par_for and
* halide_default_do_parallel_tasks, so it's only necessary to provide
* those if you are mixing in the default implementations of
* do_par_for and do_parallel_tasks. */
// @{
typedef int (*halide_do_parallel_tasks_t)(void *, int, struct halide_parallel_task_t *,
void *task_parent);
extern void halide_set_custom_parallel_runtime(
halide_do_par_for_t,
halide_do_task_t,
halide_do_loop_task_t,
halide_do_parallel_tasks_t,
halide_semaphore_init_t,
halide_semaphore_try_acquire_t,
halide_semaphore_release_t);
// @}
/** The default versions of the parallel runtime functions. */
// @{
extern int halide_default_do_par_for(void *user_context,
halide_task_t task,
int min, int size, uint8_t *closure);
extern int halide_default_do_parallel_tasks(void *user_context,
int num_tasks,
struct halide_parallel_task_t *tasks,
void *task_parent);
extern int halide_default_do_task(void *user_context, halide_task_t f, int idx,
uint8_t *closure);
extern int halide_default_do_loop_task(void *user_context, halide_loop_task_t f,
int min, int extent,
uint8_t *closure, void *task_parent);
extern int halide_default_semaphore_init(struct halide_semaphore_t *, int n);
extern int halide_default_semaphore_release(struct halide_semaphore_t *, int n);
extern bool halide_default_semaphore_try_acquire(struct halide_semaphore_t *, int n);
// @}
struct halide_thread;
/** Spawn a thread. Returns a handle to the thread for the purposes of
* joining it. The thread must be joined in order to clean up any
* resources associated with it. */
extern struct halide_thread *halide_spawn_thread(void (*f)(void *), void *closure);
/** Join a thread. */
extern void halide_join_thread(struct halide_thread *);
/** Get or set the number of threads used by Halide's thread pool. Set returns
* the old number.
*
* n < 0 : error condition
* n == 0 : use a reasonable system default (typically, number of cpus online).
* n == 1 : use exactly one thread; this will always enforce serial execution
* n > 1 : use a pool of exactly n threads.
*
* (Note that this is only guaranteed when using the default implementations
* of halide_do_par_for(); custom implementations may completely ignore values
* passed to halide_set_num_threads().)
*/
// @{
extern int halide_get_num_threads();
extern int halide_set_num_threads(int n);
// @}
/** Halide calls these functions to allocate and free memory. To
* replace in AOT code, use the halide_set_custom_malloc and
* halide_set_custom_free, or (on platforms that support weak
* linking), simply define these functions yourself. In JIT-compiled
* code use Func::set_custom_allocator.
*
* If you override them, and find yourself wanting to call the default
* implementation from within your override, use
* halide_default_malloc/free.
*
* Note that halide_malloc must return a pointer aligned to the
* maximum meaningful alignment for the platform for the purpose of
* vector loads and stores, *and* with an allocated size that is (at least)
* an integral multiple of that same alignment. The default implementation
* uses 32-byte alignment on arm and 64-byte alignment on x86. Additionally,
* it must be safe to read at least 8 bytes before the start and beyond the end.
*/
//@{
extern void *halide_malloc(void *user_context, size_t x);
extern void halide_free(void *user_context, void *ptr);
extern void *halide_default_malloc(void *user_context, size_t x);
extern void halide_default_free(void *user_context, void *ptr);
typedef void *(*halide_malloc_t)(void *, size_t);
typedef void (*halide_free_t)(void *, void *);
extern halide_malloc_t halide_set_custom_malloc(halide_malloc_t user_malloc);
extern halide_free_t halide_set_custom_free(halide_free_t user_free);
//@}
/** Halide calls these functions to interact with the underlying
* system runtime functions. To replace in AOT code on platforms that
* support weak linking, define these functions yourself, or use
* the halide_set_custom_load_library() and halide_set_custom_get_library_symbol()
* functions. In JIT-compiled code, use JITSharedRuntime::set_default_handlers().
*
* halide_load_library and halide_get_library_symbol are equivalent to
* dlopen and dlsym. halide_get_symbol(sym) is equivalent to
* dlsym(RTLD_DEFAULT, sym).
*/
//@{
extern void *halide_get_symbol(const char *name);
extern void *halide_load_library(const char *name);
extern void *halide_get_library_symbol(void *lib, const char *name);
extern void *halide_default_get_symbol(const char *name);
extern void *halide_default_load_library(const char *name);
extern void *halide_default_get_library_symbol(void *lib, const char *name);
typedef void *(*halide_get_symbol_t)(const char *name);
typedef void *(*halide_load_library_t)(const char *name);
typedef void *(*halide_get_library_symbol_t)(void *lib, const char *name);
extern halide_get_symbol_t halide_set_custom_get_symbol(halide_get_symbol_t user_get_symbol);
extern halide_load_library_t halide_set_custom_load_library(halide_load_library_t user_load_library);
extern halide_get_library_symbol_t halide_set_custom_get_library_symbol(halide_get_library_symbol_t user_get_library_symbol);
//@}
/** Called when debug_to_file is used inside %Halide code. See
* Func::debug_to_file for how this is called
*
* Cannot be replaced in JITted code at present.
*/
extern int32_t halide_debug_to_file(void *user_context, const char *filename,
struct halide_buffer_t *buf);
/** Types in the halide type system. They can be ints, unsigned ints,
* or floats (of various bit-widths), or a handle (which is always 64-bits).
* Note that the int/uint/float values do not imply a specific bit width
* (the bit width is expected to be encoded in a separate value).
*/
typedef enum halide_type_code_t
#if (__cplusplus >= 201103L || _MSVC_LANG >= 201103L)
: uint8_t
#endif
{
halide_type_int = 0, ///< signed integers
halide_type_uint = 1, ///< unsigned integers
halide_type_float = 2, ///< IEEE floating point numbers
halide_type_handle = 3, ///< opaque pointer type (void *)
halide_type_bfloat = 4, ///< floating point numbers in the bfloat format
} halide_type_code_t;
// Note that while __attribute__ can go before or after the declaration,
// __declspec apparently is only allowed before.
#ifndef HALIDE_ATTRIBUTE_ALIGN
#ifdef _MSC_VER
#define HALIDE_ATTRIBUTE_ALIGN(x) __declspec(align(x))
#else
#define HALIDE_ATTRIBUTE_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
/** A runtime tag for a type in the halide type system. Can be ints,
* unsigned ints, or floats of various bit-widths (the 'bits'
* field). Can also be vectors of the same (by setting the 'lanes'
* field to something larger than one). This struct should be
* exactly 32-bits in size. */
struct halide_type_t {
/** The basic type code: signed integer, unsigned integer, or floating point. */
#if (__cplusplus >= 201103L || _MSVC_LANG >= 201103L)
HALIDE_ATTRIBUTE_ALIGN(1)
halide_type_code_t code; // halide_type_code_t
#else
HALIDE_ATTRIBUTE_ALIGN(1)
uint8_t code; // halide_type_code_t
#endif
/** The number of bits of precision of a single scalar value of this type. */
HALIDE_ATTRIBUTE_ALIGN(1)
uint8_t bits;
/** How many elements in a vector. This is 1 for scalar types. */
HALIDE_ATTRIBUTE_ALIGN(2)
uint16_t lanes;
#if (__cplusplus >= 201103L || _MSVC_LANG >= 201103L)
/** Construct a runtime representation of a Halide type from:
* code: The fundamental type from an enum.
* bits: The bit size of one element.
* lanes: The number of vector elements in the type. */
HALIDE_ALWAYS_INLINE constexpr halide_type_t(halide_type_code_t code, uint8_t bits, uint16_t lanes = 1)
: code(code), bits(bits), lanes(lanes) {
}
/** Default constructor is required e.g. to declare halide_trace_event
* instances. */
HALIDE_ALWAYS_INLINE constexpr halide_type_t()
: code((halide_type_code_t)0), bits(0), lanes(0) {
}
HALIDE_ALWAYS_INLINE constexpr halide_type_t with_lanes(uint16_t new_lanes) const {
return halide_type_t((halide_type_code_t)code, bits, new_lanes);
}
HALIDE_ALWAYS_INLINE constexpr halide_type_t element_of() const {
return with_lanes(1);
}
/** Compare two types for equality. */
HALIDE_ALWAYS_INLINE constexpr bool operator==(const halide_type_t &other) const {
return as_u32() == other.as_u32();
}
HALIDE_ALWAYS_INLINE constexpr bool operator!=(const halide_type_t &other) const {
return !(*this == other);
}
HALIDE_ALWAYS_INLINE constexpr bool operator<(const halide_type_t &other) const {
return as_u32() < other.as_u32();
}
/** Size in bytes for a single element, even if width is not 1, of this type. */
HALIDE_ALWAYS_INLINE constexpr int bytes() const {
return (bits + 7) / 8;
}
HALIDE_ALWAYS_INLINE constexpr uint32_t as_u32() const {
// Note that this produces a result that is identical to memcpy'ing 'this'
// into a u32 (on a little-endian machine, anyway), and at -O1 or greater
// on Clang, the compiler knows this and optimizes this into a single 32-bit move.
// (At -O0 it will look awful.)
return static_cast<uint8_t>(code) |
(static_cast<uint16_t>(bits) << 8) |
(static_cast<uint32_t>(lanes) << 16);
}
#endif
};
#if (__cplusplus >= 201103L || _MSVC_LANG >= 201103L)
static_assert(sizeof(halide_type_t) == sizeof(uint32_t), "size mismatch in halide_type_t");
#endif
enum halide_trace_event_code_t { halide_trace_load = 0,
halide_trace_store = 1,
halide_trace_begin_realization = 2,
halide_trace_end_realization = 3,
halide_trace_produce = 4,
halide_trace_end_produce = 5,
halide_trace_consume = 6,
halide_trace_end_consume = 7,
halide_trace_begin_pipeline = 8,
halide_trace_end_pipeline = 9,
halide_trace_tag = 10 };
struct halide_trace_event_t {
/** The name of the Func or Pipeline that this event refers to */
const char *func;
/** If the event type is a load or a store, this points to the
* value being loaded or stored. Use the type field to safely cast
* this to a concrete pointer type and retrieve it. For other
* events this is null. */
void *value;
/** For loads and stores, an array which contains the location
* being accessed. For vector loads or stores it is an array of
* vectors of coordinates (the vector dimension is innermost).
*
* For realization or production-related events, this will contain
* the mins and extents of the region being accessed, in the order
* min0, extent0, min1, extent1, ...
*
* For pipeline-related events, this will be null.
*/
int32_t *coordinates;
/** For halide_trace_tag, this points to a read-only null-terminated string
* of arbitrary text. For all other events, this will be null.
*/
const char *trace_tag;
/** If the event type is a load or a store, this is the type of
* the data. Otherwise, the value is meaningless. */
struct halide_type_t type;
/** The type of event */
enum halide_trace_event_code_t event;
/* The ID of the parent event (see below for an explanation of
* event ancestry). */
int32_t parent_id;
/** If this was a load or store of a Tuple-valued Func, this is
* which tuple element was accessed. */
int32_t value_index;
/** The length of the coordinates array */
int32_t dimensions;
};
/** Called when Funcs are marked as trace_load, trace_store, or
* trace_realization. See Func::set_custom_trace. The default
* implementation either prints events via halide_print, or if
* HL_TRACE_FILE is defined, dumps the trace to that file in a
* sequence of trace packets. The header for a trace packet is defined
* below. If the trace is going to be large, you may want to make the
* file a named pipe, and then read from that pipe into gzip.
*
* halide_trace returns a unique ID which will be passed to future
* events that "belong" to the earlier event as the parent id. The
* ownership hierarchy looks like:
*
* begin_pipeline
* +--trace_tag (if any)
* +--trace_tag (if any)
* ...
* +--begin_realization
* | +--produce
* | | +--load/store
* | | +--end_produce
* | +--consume
* | | +--load
* | | +--end_consume
* | +--end_realization
* +--end_pipeline
*
* Threading means that ownership cannot be inferred from the ordering
* of events. There can be many active realizations of a given
* function, or many active productions for a single
* realization. Within a single production, the ordering of events is
* meaningful.
*
* Note that all trace_tag events (if any) will occur just after the begin_pipeline
* event, but before any begin_realization events. All trace_tags for a given Func
* will be emitted in the order added.
*/
// @}
extern int32_t halide_trace(void *user_context, const struct halide_trace_event_t *event);
extern int32_t halide_default_trace(void *user_context, const struct halide_trace_event_t *event);
typedef int32_t (*halide_trace_t)(void *user_context, const struct halide_trace_event_t *);
extern halide_trace_t halide_set_custom_trace(halide_trace_t trace);
// @}
/** The header of a packet in a binary trace. All fields are 32-bit. */
struct halide_trace_packet_t {
/** The total size of this packet in bytes. Always a multiple of
* four. Equivalently, the number of bytes until the next
* packet. */
uint32_t size;
/** The id of this packet (for the purpose of parent_id). */
int32_t id;
/** The remaining fields are equivalent to those in halide_trace_event_t */
// @{
struct halide_type_t type;
enum halide_trace_event_code_t event;
int32_t parent_id;
int32_t value_index;
int32_t dimensions;
// @}
#if (__cplusplus >= 201103L || _MSVC_LANG >= 201103L)
/** Get the coordinates array, assuming this packet is laid out in
* memory as it was written. The coordinates array comes
* immediately after the packet header. */
HALIDE_ALWAYS_INLINE const int *coordinates() const {
return (const int *)(this + 1);
}
HALIDE_ALWAYS_INLINE int *coordinates() {
return (int *)(this + 1);
}
/** Get the value, assuming this packet is laid out in memory as
* it was written. The packet comes immediately after the coordinates
* array. */
HALIDE_ALWAYS_INLINE const void *value() const {
return (const void *)(coordinates() + dimensions);
}
HALIDE_ALWAYS_INLINE void *value() {
return (void *)(coordinates() + dimensions);
}
/** Get the func name, assuming this packet is laid out in memory
* as it was written. It comes after the value. */
HALIDE_ALWAYS_INLINE const char *func() const {
return (const char *)value() + type.lanes * type.bytes();
}
HALIDE_ALWAYS_INLINE char *func() {
return (char *)value() + type.lanes * type.bytes();
}
/** Get the trace_tag (if any), assuming this packet is laid out in memory
* as it was written. It comes after the func name. If there is no trace_tag,
* this will return a pointer to an empty string. */
HALIDE_ALWAYS_INLINE const char *trace_tag() const {
const char *f = func();
// strlen may not be available here
while (*f++) {
// nothing
}
return f;
}
HALIDE_ALWAYS_INLINE char *trace_tag() {
char *f = func();
// strlen may not be available here
while (*f++) {
// nothing
}
return f;
}
#endif
};
/** Set the file descriptor that Halide should write binary trace
* events to. If called with 0 as the argument, Halide outputs trace
* information to stdout in a human-readable format. If never called,
* Halide checks the for existence of an environment variable called
* HL_TRACE_FILE and opens that file. If HL_TRACE_FILE is not defined,
* it outputs trace information to stdout in a human-readable
* format. */
extern void halide_set_trace_file(int fd);
/** Halide calls this to retrieve the file descriptor to write binary
* trace events to. The default implementation returns the value set
* by halide_set_trace_file. Implement it yourself if you wish to use
* a custom file descriptor per user_context. Return zero from your
* implementation to tell Halide to print human-readable trace
* information to stdout. */
extern int halide_get_trace_file(void *user_context);
/** If tracing is writing to a file. This call closes that file
* (flushing the trace). Returns zero on success. */
extern int halide_shutdown_trace(void);
/** All Halide GPU or device backend implementations provide an
* interface to be used with halide_device_malloc, etc. This is
* accessed via the functions below.
*/
/** An opaque struct containing per-GPU API implementations of the
* device functions. */
struct halide_device_interface_impl_t;
/** Each GPU API provides a halide_device_interface_t struct pointing
* to the code that manages device allocations. You can access these
* functions directly from the struct member function pointers, or by
* calling the functions declared below. Note that the global
* functions are not available when using Halide as a JIT compiler.
* If you are using raw halide_buffer_t in that context you must use
* the function pointers in the device_interface struct.
*
* The function pointers below are currently the same for every GPU
* API; only the impl field varies. These top-level functions do the
* bookkeeping that is common across all GPU APIs, and then dispatch
* to more API-specific functions via another set of function pointers
* hidden inside the impl field.
*/
struct halide_device_interface_t {
int (*device_malloc)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_free)(void *user_context, struct halide_buffer_t *buf);
int (*device_sync)(void *user_context, struct halide_buffer_t *buf);
void (*device_release)(void *user_context,
const struct halide_device_interface_t *device_interface);
int (*copy_to_host)(void *user_context, struct halide_buffer_t *buf);
int (*copy_to_device)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_and_host_malloc)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_and_host_free)(void *user_context, struct halide_buffer_t *buf);
int (*buffer_copy)(void *user_context, struct halide_buffer_t *src,
const struct halide_device_interface_t *dst_device_interface, struct halide_buffer_t *dst);
int (*device_crop)(void *user_context, const struct halide_buffer_t *src,
struct halide_buffer_t *dst);
int (*device_slice)(void *user_context, const struct halide_buffer_t *src,
int slice_dim, int slice_pos, struct halide_buffer_t *dst);
int (*device_release_crop)(void *user_context, struct halide_buffer_t *buf);
int (*wrap_native)(void *user_context, struct halide_buffer_t *buf, uint64_t handle,
const struct halide_device_interface_t *device_interface);
int (*detach_native)(void *user_context, struct halide_buffer_t *buf);
int (*compute_capability)(void *user_context, int *major, int *minor);
const struct halide_device_interface_impl_t *impl;
};
/** Release all data associated with the given device interface, in
* particular all resources (memory, texture, context handles)
* allocated by Halide. Must be called explicitly when using AOT
* compilation. This is *not* thread-safe with respect to actively
* running Halide code. Ensure all pipelines are finished before
* calling this. */
extern void halide_device_release(void *user_context,
const struct halide_device_interface_t *device_interface);
/** Copy image data from device memory to host memory. This must be called
* explicitly to copy back the results of a GPU-based filter. */
extern int halide_copy_to_host(void *user_context, struct halide_buffer_t *buf);
/** Copy image data from host memory to device memory. This should not
* be called directly; Halide handles copying to the device
* automatically. If interface is NULL and the buf has a non-zero dev
* field, the device associated with the dev handle will be
* used. Otherwise if the dev field is 0 and interface is NULL, an
* error is returned. */
extern int halide_copy_to_device(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
/** Copy data from one buffer to another. The buffers may have
* different shapes and sizes, but the destination buffer's shape must
* be contained within the source buffer's shape. That is, for each
* dimension, the min on the destination buffer must be greater than
* or equal to the min on the source buffer, and min+extent on the
* destination buffer must be less that or equal to min+extent on the
* source buffer. The source data is pulled from either device or
* host memory on the source, depending on the dirty flags. host is
* preferred if both are valid. The dst_device_interface parameter
* controls the destination memory space. NULL means host memory. */
extern int halide_buffer_copy(void *user_context, struct halide_buffer_t *src,
const struct halide_device_interface_t *dst_device_interface,
struct halide_buffer_t *dst);
/** Give the destination buffer a device allocation which is an alias
* for the same coordinate range in the source buffer. Modifies the
* device, device_interface, and the device_dirty flag only. Only
* supported by some device APIs (others will return
* halide_error_code_device_crop_unsupported). Call
* halide_device_release_crop instead of halide_device_free to clean
* up resources associated with the cropped view. Do not free the
* device allocation on the source buffer while the destination buffer
* still lives. Note that the two buffers do not share dirty flags, so
* care must be taken to update them together as needed. Note that src
* and dst are required to have the same number of dimensions.
*
* Note also that (in theory) device interfaces which support cropping may
* still not support cropping a crop (instead, create a new crop of the parent
* buffer); in practice, no known implementation has this limitation, although
* it is possible that some future implementations may require it. */
extern int halide_device_crop(void *user_context,
const struct halide_buffer_t *src,
struct halide_buffer_t *dst);
/** Give the destination buffer a device allocation which is an alias
* for a similar coordinate range in the source buffer, but with one dimension
* sliced away in the dst. Modifies the device, device_interface, and the
* device_dirty flag only. Only supported by some device APIs (others will return
* halide_error_code_device_crop_unsupported). Call
* halide_device_release_crop instead of halide_device_free to clean
* up resources associated with the sliced view. Do not free the
* device allocation on the source buffer while the destination buffer
* still lives. Note that the two buffers do not share dirty flags, so
* care must be taken to update them together as needed. Note that the dst buffer
* must have exactly one fewer dimension than the src buffer, and that slice_dim
* and slice_pos must be valid within src. */
extern int halide_device_slice(void *user_context,
const struct halide_buffer_t *src,
int slice_dim, int slice_pos,
struct halide_buffer_t *dst);
/** Release any resources associated with a cropped/sliced view of another
* buffer. */
extern int halide_device_release_crop(void *user_context,
struct halide_buffer_t *buf);
/** Wait for current GPU operations to complete. Calling this explicitly
* should rarely be necessary, except maybe for profiling. */
extern int halide_device_sync(void *user_context, struct halide_buffer_t *buf);
/**
* Wait for current GPU operations to complete. Calling this explicitly
* should rarely be necessary, except maybe for profiling.
* This variation of the synchronizing is useful when a synchronization is desirable
* without specifying any buffer to synchronize on.
* Calling this with a null device_interface is always illegal.
*/
extern int halide_device_sync_global(void *user_context,
const struct halide_device_interface_t *device_interface);
/** Allocate device memory to back a halide_buffer_t. */
extern int halide_device_malloc(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
/** Free device memory. */
extern int halide_device_free(void *user_context, struct halide_buffer_t *buf);
/** Wrap or detach a native device handle, setting the device field
* and device_interface field as appropriate for the given GPU
* API. The meaning of the opaque handle is specific to the device
* interface, so if you know the device interface in use, call the
* more specific functions in the runtime headers for your specific
* device API instead (e.g. HalideRuntimeCuda.h). */
// @{
extern int halide_device_wrap_native(void *user_context,
struct halide_buffer_t *buf,
uint64_t handle,
const struct halide_device_interface_t *device_interface);
extern int halide_device_detach_native(void *user_context, struct halide_buffer_t *buf);
// @}
/** Selects which gpu device to use. 0 is usually the display
* device. If never called, Halide uses the environment variable
* HL_GPU_DEVICE. If that variable is unset, Halide uses the last
* device. Set this to -1 to use the last device. */
extern void halide_set_gpu_device(int n);
/** Halide calls this to get the desired halide gpu device
* setting. Implement this yourself to use a different gpu device per
* user_context. The default implementation returns the value set by
* halide_set_gpu_device, or the environment variable
* HL_GPU_DEVICE. */
extern int halide_get_gpu_device(void *user_context);
/** Set the soft maximum amount of memory, in bytes, that the LRU
* cache will use to memoize Func results. This is not a strict
* maximum in that concurrency and simultaneous use of memoized
* reults larger than the cache size can both cause it to
* temporariliy be larger than the size specified here.
*/
extern void halide_memoization_cache_set_size(int64_t size);
/** Given a cache key for a memoized result, currently constructed
* from the Func name and top-level Func name plus the arguments of
* the computation, determine if the result is in the cache and
* return it if so. (The internals of the cache key should be
* considered opaque by this function.) If this routine returns true,
* it is a cache miss. Otherwise, it will return false and the
* buffers passed in will be filled, via copying, with memoized
* data. The last argument is a list if halide_buffer_t pointers which
* represents the outputs of the memoized Func. If the Func does not
* return a Tuple, there will only be one halide_buffer_t in the list. The
* tuple_count parameters determines the length of the list.
*
* The return values are:
* -1: Signals an error.
* 0: Success and cache hit.
* 1: Success and cache miss.
*/
extern int halide_memoization_cache_lookup(void *user_context, const uint8_t *cache_key, int32_t size,
struct halide_buffer_t *realized_bounds,
int32_t tuple_count, struct halide_buffer_t **tuple_buffers);
/** Given a cache key for a memoized result, currently constructed
* from the Func name and top-level Func name plus the arguments of
* the computation, store the result in the cache for futre access by
* halide_memoization_cache_lookup. (The internals of the cache key
* should be considered opaque by this function.) Data is copied out
* from the inputs and inputs are unmodified. The last argument is a
* list if halide_buffer_t pointers which represents the outputs of the
* memoized Func. If the Func does not return a Tuple, there will
* only be one halide_buffer_t in the list. The tuple_count parameters
* determines the length of the list.
*
* If there is a memory allocation failure, the store does not store
* the data into the cache.
*
* If has_eviction_key is true, the entry is marked with eviction_key to
* allow removing the key with halide_memoization_cache_evict.
*/
extern int halide_memoization_cache_store(void *user_context, const uint8_t *cache_key, int32_t size,
struct halide_buffer_t *realized_bounds,
int32_t tuple_count,
struct halide_buffer_t **tuple_buffers,
bool has_eviction_key, uint64_t eviction_key);