-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ScheduleFunctions.cpp
2633 lines (2297 loc) · 109 KB
/
ScheduleFunctions.cpp
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
#include <algorithm>
#include <set>
#include <utility>
#include "ApplySplit.h"
#include "CSE.h"
#include "CodeGen_GPU_Dev.h"
#include "ExprUsesVar.h"
#include "Func.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Inline.h"
#include "Prefetch.h"
#include "Qualify.h"
#include "ScheduleFunctions.h"
#include "Simplify.h"
#include "Solve.h"
#include "Substitute.h"
#include "Target.h"
#include "Var.h"
namespace Halide {
namespace Internal {
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
namespace {
// A structure representing a containing LetStmt, IfThenElse, or For
// loop. Used in build_provide_loop_nest below. Both If and IfInner represent
// IfThenElse stmts, however, IfInner should not be reordered to outside of
// a for loop.
struct Container {
enum Type { For,
Let,
If,
IfInner };
Type type;
// If it's a for loop, the index in the dims list.
int dim_idx;
string name;
Expr value;
Container(Type type, int dim_idx, string name, Expr value)
: type(type), dim_idx(dim_idx), name(std::move(name)), value(std::move(value)) {
}
};
bool var_name_match(const string &v1, const string &v2) {
return ((v1 == v2) ||
Internal::ends_with(v1, "." + v2) ||
Internal::ends_with(v2, "." + v1));
}
class ContainsImpureCall : public IRVisitor {
using IRVisitor::visit;
void visit(const Call *op) override {
if (!op->is_pure()) {
result = true;
} else {
IRVisitor::visit(op);
}
}
public:
bool result = false;
};
bool contains_impure_call(const Expr &expr) {
ContainsImpureCall is_not_pure;
expr.accept(&is_not_pure);
return is_not_pure.result;
}
// A mutator that performs a substitute operation only on either the values or the
// arguments of Provide nodes.
class SubstituteIn : public IRGraphMutator {
const string &name;
const Expr &value;
bool calls;
bool provides;
using IRMutator::visit;
Stmt visit(const Provide *p) override {
if (!provides) {
return IRMutator::visit(p);
}
vector<Expr> args;
bool changed = false;
for (const Expr &i : p->args) {
args.push_back(graph_substitute(name, value, i));
changed = changed || !args.back().same_as(i);
}
if (changed) {
return Provide::make(p->name, p->values, args, p->predicate);
} else {
return p;
}
}
Expr visit(const Call *op) override {
Expr result = IRMutator::visit(op);
if (calls && op->call_type == Call::Halide) {
result = graph_substitute(name, value, op);
}
return result;
}
public:
SubstituteIn(const string &name, const Expr &value, bool calls, bool provides)
: name(name), value(value), calls(calls), provides(provides) {
}
};
Stmt substitute_in(const string &name, const Expr &value, bool calls, bool provides, const Stmt &s) {
return SubstituteIn(name, value, calls, provides).mutate(s);
}
class AddPredicates : public IRGraphMutator {
const Expr &cond;
const Function &func;
ApplySplitResult::Type type;
using IRMutator::visit;
Stmt visit(const Provide *p) override {
auto [args, changed_args] = mutate_with_changes(p->args);
auto [values, changed_values] = mutate_with_changes(p->values);
Expr predicate = mutate(p->predicate);
if (type == ApplySplitResult::BlendProvides) {
int idx = 0;
for (Expr &v : values) {
v = select(cond, v, Call::make(func, args, idx++));
}
return Provide::make(p->name, values, args, predicate);
} else if (type == ApplySplitResult::PredicateProvides) {
return Provide::make(p->name, values, args, predicate && cond);
} else if (changed_args || changed_values || !predicate.same_as(p->predicate)) {
return Provide::make(p->name, values, args, predicate);
} else {
return p;
}
}
Expr visit(const Call *op) override {
Expr result = IRMutator::visit(op);
if (type == ApplySplitResult::PredicateCalls && op->call_type == Call::Halide) {
result = Call::make(op->type, Call::if_then_else, {cond, result}, Call::PureIntrinsic);
}
return result;
}
public:
AddPredicates(const Expr &cond, const Function &func, ApplySplitResult::Type type)
: cond(cond), func(func), type(type) {
}
};
Stmt add_predicates(const Expr &cond, const Function &func, ApplySplitResult::Type type, const Stmt &s) {
return AddPredicates(cond, func, type).mutate(s);
}
// Build a loop nest about a provide node using a schedule
Stmt build_loop_nest(
const Stmt &body,
const string &prefix,
int start_fuse,
const Function &func,
const Definition &def,
bool is_update) {
const auto &dims = func.args();
const auto &func_s = func.schedule();
const auto &stage_s = def.schedule();
const auto &predicates = def.split_predicate();
// We'll build it from inside out, starting from the body,
// then wrapping it in for loops.
Stmt stmt = body;
// A map of the dimensions for which we know the extent is a
// multiple of some Expr. This can happen due to a bound, or
// align_bounds directive, or if a dim comes from the inside
// of a split.
map<string, Expr> dim_extent_alignment;
// First hunt through the bounds for them.
for (const Bound &i : func_s.bounds()) {
if (i.extent.defined()) {
dim_extent_alignment[i.var] = i.extent;
}
if (i.modulus.defined()) {
dim_extent_alignment[i.var] = i.modulus;
}
}
// Then use any reduction domain.
for (const ReductionVariable &i : stage_s.rvars()) {
dim_extent_alignment[i.var] = i.extent;
}
vector<Split> splits = stage_s.splits();
// Find all the predicated inner variables. We can't split these.
set<string> predicated_vars;
for (const Split &split : splits) {
if (split.tail == TailStrategy::PredicateLoads || split.tail == TailStrategy::PredicateStores) {
predicated_vars.insert(split.inner);
}
}
// Define the function args in terms of the loop variables using the splits
for (const Split &split : splits) {
user_assert(predicated_vars.count(split.old_var) == 0)
<< "Cannot split a loop variable resulting from a split using PredicateLoads or PredicateStores.";
vector<ApplySplitResult> splits_result = apply_split(split, is_update, prefix, dim_extent_alignment);
// To ensure we substitute all indices used in call or provide,
// we need to substitute all lets in, so we correctly guard x in
// an example like let a = 2*x in a + f[a].
stmt = substitute_in_all_lets(stmt);
for (const auto &res : splits_result) {
if (res.is_substitution()) {
stmt = graph_substitute(res.name, res.value, stmt);
} else if (res.is_substitution_in_calls()) {
stmt = substitute_in(res.name, res.value, true, false, stmt);
} else if (res.is_substitution_in_provides()) {
stmt = substitute_in(res.name, res.value, false, true, stmt);
} else if (res.is_blend_provides() ||
res.is_predicate_calls() ||
res.is_predicate_provides()) {
stmt = add_predicates(res.value, func, res.type, stmt);
} else if (res.is_let()) {
stmt = LetStmt::make(res.name, res.value, stmt);
} else {
internal_assert(res.is_predicate());
stmt = IfThenElse::make(res.value, stmt, Stmt());
}
}
stmt = common_subexpression_elimination(stmt);
}
// Order the Ifs, Fors, and Lets for bounds inference
// to generate tighter bounds and put the bound variables
// in the right place.
// This is not a generic loop invariant code motion step.
// In particular there are dangling references to bound
// variables that are not defined yet, so we can't rely
// the loop invariant code motion pass.
// All containing lets and fors. Outermost first.
vector<Container> nest;
nest.reserve(stage_s.dims().size());
// Put the desired loop nest into the containers vector.
for (int i = (int)stage_s.dims().size() - 1; i >= 0; i--) {
const Dim &dim = stage_s.dims()[i];
nest.emplace_back(Container::For, i, prefix + dim.var, Expr());
}
vector<Container> pred_container;
// Strip off the lets/ifs into the containers vector.
while (!stmt.same_as(body)) {
const auto *let = stmt.as<LetStmt>();
const auto *if_else = stmt.as<IfThenElse>();
if (let) {
nest.emplace_back(Container::Let, 0, let->name, let->value);
stmt = let->body;
} else if (if_else && !if_else->else_case.defined()) {
pred_container.emplace_back(Container::If, 0, "", if_else->condition);
stmt = if_else->then_case;
} else {
break;
}
}
// Add appropriate predicates on the fused loop vars to ensure we don't
// go out of bounds. Ignore the __outermost dims since it's going to be
// removed later anyway. These have to be added as outermost as possible as
// some let stmts (e.g. the rebase let stmt) might depend on this vars;
// otherwise, this may mess up the bounds_touched computation.
int n_predicates_inner = 0;
for (int i = start_fuse; (i >= 0) && (i < (int)stage_s.dims().size() - 1); ++i) {
string dim_var = prefix + stage_s.dims()[i].var;
Expr var = Variable::make(Int(32), dim_var);
Expr max = Variable::make(Int(32), dim_var + ".loop_max");
Expr min = Variable::make(Int(32), dim_var + ".loop_min");
// Use 'var', the variable which bounds we're constraining as the
// container name, so that we can use it later to check if a LetStmt
// value depends on 'var'.
nest.emplace_back(Container::IfInner, 0, dim_var, likely(var >= min));
nest.emplace_back(Container::IfInner, 0, dim_var, likely(var <= max));
n_predicates_inner += 2;
}
// Put all the reduction domain predicates into the containers vector.
for (Expr pred : predicates) {
pred = qualify(prefix, pred);
// Add a likely qualifier if there isn't already one
if (Call::as_intrinsic(pred, {Call::likely, Call::likely_if_innermost})) {
pred = likely(pred);
}
pred_container.emplace_back(Container::If, 0, "", pred);
}
int n_predicates = (int)(pred_container.size());
nest.insert(nest.end(), pred_container.begin(), pred_container.end());
// Resort the containers vector so that lets are as far outwards
// as possible. Use reverse insertion sort. Start at the first letstmt.
for (int i = (int)stage_s.dims().size(); i < (int)nest.size() - n_predicates_inner - n_predicates; i++) {
// Only push up LetStmts.
internal_assert(nest[i].value.defined());
internal_assert(nest[i].type == Container::Let);
if (!is_pure(nest[i].value)) {
continue;
}
for (int j = i - 1; j >= 0; j--) {
// Try to push it up by one.
internal_assert(nest[j + 1].value.defined());
if (!expr_uses_var(nest[j + 1].value, nest[j].name)) {
std::swap(nest[j + 1], nest[j]);
} else {
break;
}
}
}
// Sort the predicate guards for the fused loops so they are as far outwards
// as possible. IfInnner should not be reordered to outside of a for loop.
for (int i = (int)nest.size() - n_predicates_inner - n_predicates;
i < (int)nest.size() - n_predicates;
i++) {
// Only push up IfThenElse.
internal_assert(nest[i].value.defined());
internal_assert(nest[i].type == Container::IfInner);
// Cannot lift out the predicate guard if it contains call to non-pure function
if (contains_impure_call(nest[i].value)) {
continue;
}
for (int j = i - 1; j >= 0; j--) {
// Try to push it up by one.
internal_assert(nest[j + 1].value.defined());
if (!expr_uses_var(nest[j + 1].value, nest[j].name) &&
(nest[j].type != Container::For)) {
std::swap(nest[j + 1], nest[j]);
} else {
break;
}
}
}
// Sort the ifs so they are as far outwards as possible.
// BoxesTouched trims the domain of a variable within a scope of if-then-else
// based on the likely condition. However, it doesn't do it transitively; it
// doesn't trim the domains of other variables that directly/indirectly
// depend on the original variable in the likely condition outside the scope
// of the if-then-else. That's why it's necessary to move the ifs as far
// outwards as possible, so that those variables can have tighter bounds.
for (int i = (int)nest.size() - n_predicates; i < (int)nest.size(); i++) {
// Only push up IfThenElse.
internal_assert(nest[i].value.defined());
internal_assert(nest[i].type == Container::If);
// Cannot lift out the 'if' if it contains call to non-pure function
if (contains_impure_call(nest[i].value)) {
continue;
}
for (int j = i - 1; j >= 0; j--) {
// Try to push it up by one.
internal_assert(nest[j + 1].value.defined());
if (!expr_uses_var(nest[j + 1].value, nest[j].name)) {
std::swap(nest[j + 1], nest[j]);
} else {
break;
}
}
}
// Rewrap the statement in the containing lets and fors.
for (int i = (int)nest.size() - 1; i >= 0; i--) {
if (nest[i].type == Container::Let) {
internal_assert(nest[i].value.defined());
stmt = LetStmt::make(nest[i].name, nest[i].value, stmt);
} else if ((nest[i].type == Container::If) || (nest[i].type == Container::IfInner)) {
internal_assert(nest[i].value.defined());
stmt = IfThenElse::make(nest[i].value, stmt, Stmt());
} else {
internal_assert(nest[i].type == Container::For);
const Dim &dim = stage_s.dims()[nest[i].dim_idx];
Expr min = Variable::make(Int(32), nest[i].name + ".loop_min");
Expr extent = Variable::make(Int(32), nest[i].name + ".loop_extent");
stmt = For::make(nest[i].name, min, extent, dim.for_type, dim.partition_policy, dim.device_api, stmt);
}
}
// Define the bounds on the split dimensions using the bounds
// on the function args. If it is a purify, we should use the bounds
// from the dims instead.
for (size_t i = splits.size(); i > 0; i--) {
const Split &split = splits[i - 1];
vector<std::pair<string, Expr>> let_stmts = compute_loop_bounds_after_split(split, prefix);
for (const auto &let_stmt : let_stmts) {
stmt = LetStmt::make(let_stmt.first, let_stmt.second, stmt);
}
}
// Define the bounds on the outermost dummy dimension.
{
string o = prefix + Var::outermost().name();
stmt = LetStmt::make(o + ".loop_min", 0, stmt);
stmt = LetStmt::make(o + ".loop_max", 0, stmt);
stmt = LetStmt::make(o + ".loop_extent", 1, stmt);
}
// Define the loop mins and extents in terms of the mins and maxs produced by bounds inference
for (const std::string &i : dims) {
string var = prefix + i;
Expr max = Variable::make(Int(32), var + ".max");
Expr min = Variable::make(Int(32), var + ".min"); // Inject instance name here? (compute instance names during lowering)
stmt = LetStmt::make(var + ".loop_extent",
(max + 1) - min,
stmt);
stmt = LetStmt::make(var + ".loop_min", min, stmt);
stmt = LetStmt::make(var + ".loop_max", max, stmt);
}
// Define the loop mins and extents for the reduction domain (if there is any)
// in terms of the mins and maxs produced by bounds inference
for (const ReductionVariable &rv : stage_s.rvars()) {
string p = prefix + rv.var;
Expr rmin = Variable::make(Int(32), p + ".min");
Expr rmax = Variable::make(Int(32), p + ".max");
stmt = LetStmt::make(p + ".loop_min", rmin, stmt);
stmt = LetStmt::make(p + ".loop_max", rmax, stmt);
stmt = LetStmt::make(p + ".loop_extent", rmax - rmin + 1, stmt);
}
return stmt;
}
// Build a loop nest about a provide node using a schedule
Stmt build_provide_loop_nest(const map<string, Function> &env,
const string &prefix,
const Function &func,
const Definition &def,
int start_fuse,
bool is_update) {
internal_assert(!is_update == def.is_init());
// Default stored values
vector<Expr> site(def.args().size());
vector<Expr> values(def.values().size());
for (size_t i = 0; i < values.size(); i++) {
Expr v = def.values()[i];
v = qualify(prefix, v);
values[i] = v;
debug(3) << "Value " << i << " = " << v << "\n";
}
// Default stored locations
for (size_t i = 0; i < def.args().size(); i++) {
Expr s = def.args()[i];
s = qualify(prefix, s);
site[i] = s;
debug(3) << "Site " << i << " = " << s << "\n";
}
// Make the (multi-dimensional multi-valued) store node.
Stmt body = Provide::make(func.name(), values, site, const_true());
if (def.schedule().atomic()) { // Add atomic node.
bool any_unordered_parallel = false;
for (const auto &d : def.schedule().dims()) {
any_unordered_parallel |= is_unordered_parallel(d.for_type);
}
if (any_unordered_parallel) {
// If required, we will allocate a mutex buffer called func.name() + ".mutex"
// The buffer is added in the AddAtomicMutex pass.
body = Atomic::make(func.name(), func.name() + ".mutex", body);
} else {
// No mutex is required if there is no parallelism, and it
// wouldn't work if all parallelism is synchronous
// (e.g. vectorization). Vectorization and the like will
// need to handle atomic nodes specially, by either
// emitting VectorReduce ops or scalarizing.
body = Atomic::make(func.name(), std::string{}, body);
}
}
// Default schedule/values if there is no specialization
Stmt stmt = build_loop_nest(body, prefix, start_fuse, func, def, is_update);
stmt = inject_placeholder_prefetch(stmt, env, prefix, def.schedule().prefetches());
// Make any specialized copies
const vector<Specialization> &specializations = def.specializations();
for (size_t i = specializations.size(); i > 0; i--) {
const Specialization &s = specializations[i - 1];
if (s.failure_message.empty()) {
Stmt then_case = build_provide_loop_nest(env, prefix, func, s.definition, start_fuse, is_update);
stmt = IfThenElse::make(s.condition, then_case, stmt);
} else {
internal_assert(equal(s.condition, const_true()));
// specialize_fail() should only be possible on the final specialization
internal_assert(i == specializations.size());
Expr specialize_fail_error =
Internal::Call::make(Int(32),
"halide_error_specialize_fail",
{StringImm::make(s.failure_message)},
Internal::Call::Extern);
// Since this is the final specialization, we can make
// this the else clause
stmt = AssertStmt::make(const_false(), specialize_fail_error);
}
}
return stmt;
}
// Turn a function into a loop nest that computes it. It will
// refer to external vars of the form function_name.arg_name.min
// and function_name.arg_name.extent to define the bounds over
// which it should be realized. It will compute at least those
// bounds (depending on splits, it may compute more). This loop
// won't do any allocation.
Stmt build_extern_produce(const map<string, Function> &env, Function f, const Target &target) {
// Call the external function
// Build an argument list
vector<Expr> extern_call_args;
const vector<ExternFuncArgument> &args = f.extern_arguments();
const string &extern_name = f.extern_function_name();
// We need to generate crops of the input and output buffers if the
// extern stage has some non-extern loops, aside from the outermost
// placeholder.
bool needs_crops = false;
if (!f.definition().schedule().dims().empty()) {
size_t extern_count = 0;
for (const Dim &d : f.definition().schedule().dims()) {
extern_count += d.for_type == ForType::Extern ? 1 : 0;
}
needs_crops = extern_count + 1 < f.definition().schedule().dims().size();
}
vector<pair<string, Expr>> lets;
// Iterate through all of the input args to the extern
// function building a suitable argument list for the
// extern function call.
vector<pair<Expr, int>> buffers_to_annotate;
vector<Expr> buffers_contents_to_annotate;
vector<pair<Expr, string>> buffers_to_check;
vector<pair<Expr, Expr>> cropped_buffers;
for (const ExternFuncArgument &arg : args) {
if (arg.is_expr()) {
extern_call_args.push_back(arg.expr);
} else if (arg.is_func()) {
Function input(arg.func);
if (!needs_crops && input.schedule().store_level() == input.schedule().compute_level()) {
for (int k = 0; k < input.outputs(); k++) {
string buf_name = input.name();
if (input.outputs() > 1) {
buf_name += "." + std::to_string(k);
}
buf_name += ".buffer";
Expr buffer = Variable::make(type_of<struct halide_buffer_t *>(), buf_name);
extern_call_args.push_back(buffer);
buffers_to_annotate.emplace_back(buffer, input.dimensions());
buffers_contents_to_annotate.push_back(buffer);
}
} else {
// Make a local crop of just the region required,
// in case the input was folded. We have no
// protocol for passing folded buffers to extern
// stages, so if the fold does indeed occur, we'll
// assert later that the crop doesn't cross over a
// fold.
string stage_name = input.name() + ".s" + std::to_string(input.updates().size()) + ".";
const vector<string> &input_args = input.args();
for (int k = 0; k < input.outputs(); k++) {
string src_buf_name = input.name();
if (input.outputs() > 1) {
src_buf_name += "." + std::to_string(k);
}
src_buf_name += ".buffer";
Expr src_buffer = Variable::make(type_of<struct halide_buffer_t *>(), src_buf_name);
Expr alloca_size = Call::make(Int(32), Call::size_of_halide_buffer_t, {}, Call::Intrinsic);
Expr cropped_input = Call::make(type_of<struct halide_buffer_t *>(), Call::alloca,
{alloca_size}, Call::Intrinsic);
vector<Expr> args(5);
args[0] = cropped_input;
args[1] = Call::make(type_of<struct halide_dimension_t *>(), Call::alloca,
{(int)sizeof(halide_dimension_t) * input.dimensions()}, Call::Intrinsic);
args[2] = src_buffer;
vector<Expr> mins, extents;
internal_assert(input.dimensions() == (int)input_args.size());
for (const string &arg : input_args) {
string var = stage_name + arg;
Expr min = Variable::make(Int(32), var + ".min");
Expr max = Variable::make(Int(32), var + ".max");
mins.push_back(min);
extents.push_back(max - min + 1);
}
args[3] = Call::make(type_of<const int *>(), Call::make_struct, mins, Call::Intrinsic);
args[4] = Call::make(type_of<const int *>(), Call::make_struct, extents, Call::Intrinsic);
cropped_input = Call::make(type_of<struct halide_buffer_t *>(), Call::buffer_crop,
args, Call::Extern);
string buf_name = input.name() + "." + std::to_string(k) + ".tmp_buffer";
extern_call_args.push_back(Variable::make(type_of<struct halide_buffer_t *>(), buf_name));
buffers_to_annotate.emplace_back(extern_call_args.back(), input.dimensions());
buffers_contents_to_annotate.push_back(cropped_input);
cropped_buffers.emplace_back(extern_call_args.back(), src_buffer);
lets.emplace_back(buf_name, cropped_input);
}
}
} else if (arg.is_buffer()) {
Buffer<> b = arg.buffer;
Parameter p(b.type(), true, b.dimensions(), b.name());
p.set_buffer(b);
Expr buf = Variable::make(type_of<struct halide_buffer_t *>(), b.name() + ".buffer", p);
extern_call_args.push_back(buf);
buffers_to_annotate.emplace_back(buf, b.dimensions());
buffers_contents_to_annotate.push_back(buf);
} else if (arg.is_image_param()) {
Parameter p = arg.image_param;
Expr buf = Variable::make(type_of<struct halide_buffer_t *>(), p.name() + ".buffer", p);
extern_call_args.push_back(buf);
// Do not annotate ImageParams: both the halide_buffer_t itself,
// and the contents it points to, should be filled by the caller;
// if we mark it here, we might mask a missed initialization.
// buffers_to_annotate.push_back(buf);
// buffers_contents_to_annotate.push_back(buf);
} else {
internal_error << "Bad ExternFuncArgument type\n";
}
}
// Grab the halide_buffer_t's representing the output. If the
// store level matches the compute level, then we can use the
// ones already injected by allocation bounds inference. If
// it's the output to the pipeline then it will similarly be
// in the symbol table.
if (!needs_crops && f.schedule().store_level() == f.schedule().compute_level()) {
for (int j = 0; j < f.outputs(); j++) {
string buf_name = f.name();
if (f.outputs() > 1) {
buf_name += "." + std::to_string(j);
}
buf_name += ".buffer";
Expr buffer = Variable::make(type_of<struct halide_buffer_t *>(), buf_name);
extern_call_args.push_back(buffer);
// Since this is a temporary, internal-only buffer, make sure it's marked.
// (but not the contents! callee is expected to fill that in.)
buffers_to_annotate.emplace_back(buffer, f.dimensions());
buffers_to_check.emplace_back(buffer, buf_name);
}
} else {
// Store level doesn't match compute level. Make an output
// buffer just for this subregion.
string stage_name = f.name() + ".s0.";
const vector<string> &f_args = f.args();
for (int j = 0; j < f.outputs(); j++) {
string src_buf_name = f.name();
if (f.outputs() > 1) {
src_buf_name += "." + std::to_string(j);
}
src_buf_name += ".buffer";
Expr src_buffer = Variable::make(type_of<struct halide_buffer_t *>(), src_buf_name);
Expr alloca_size = Call::make(Int(32), Call::size_of_halide_buffer_t, {}, Call::Intrinsic);
Expr output_buffer_t = Call::make(type_of<struct halide_buffer_t *>(), Call::alloca,
{alloca_size}, Call::Intrinsic);
vector<Expr> args(5);
args[0] = output_buffer_t;
args[1] = Call::make(type_of<struct halide_dimension_t *>(), Call::alloca,
{(int)sizeof(halide_dimension_t) * f.dimensions()}, Call::Intrinsic);
args[2] = src_buffer;
vector<Expr> mins, extents;
internal_assert(f.dimensions() == (int)f_args.size());
for (const string &arg : f_args) {
string var = stage_name + arg;
Expr min = Variable::make(Int(32), var + ".min");
Expr max = Variable::make(Int(32), var + ".max");
mins.push_back(min);
extents.push_back(max - min + 1);
}
args[3] = Call::make(type_of<const int *>(), Call::make_struct, mins, Call::Intrinsic);
args[4] = Call::make(type_of<const int *>(), Call::make_struct, extents, Call::Intrinsic);
output_buffer_t = Call::make(type_of<struct halide_buffer_t *>(), Call::buffer_crop, args,
Call::Extern);
string buf_name = f.name() + "." + std::to_string(j) + ".tmp_buffer";
extern_call_args.push_back(Variable::make(type_of<struct halide_buffer_t *>(), buf_name));
// Since this is a temporary, internal-only buffer, make sure it's marked.
// (but not the contents! callee is expected to fill that in.)
buffers_to_annotate.emplace_back(extern_call_args.back(), f.dimensions());
cropped_buffers.emplace_back(extern_call_args.back(), src_buffer);
lets.emplace_back(buf_name, output_buffer_t);
buffers_to_check.emplace_back(extern_call_args.back(), buf_name);
}
}
Stmt pre_call, post_call;
if (target.has_feature(Target::MSAN)) {
// Mark the buffers as initialized before calling out.
for (const auto &p : buffers_to_annotate) {
Expr buffer = p.first;
int dimensions = p.second;
// Return type is really 'void', but no way to represent that in our IR.
// Precedent (from halide_print, etc) is to use Int(32) and ignore the result.
Expr sizeof_buffer_t = cast<uint64_t>(
Call::make(Int(32), Call::size_of_halide_buffer_t, {}, Call::Intrinsic));
Stmt mark_buffer =
Evaluate::make(Call::make(Int(32), "halide_msan_annotate_memory_is_initialized",
{buffer, sizeof_buffer_t}, Call::Extern));
Expr shape = Call::make(type_of<halide_dimension_t *>(), Call::buffer_get_shape, {buffer},
Call::Extern);
Expr shape_size = Expr((uint64_t)(sizeof(halide_dimension_t) * dimensions));
Stmt mark_shape =
Evaluate::make(Call::make(Int(32), "halide_msan_annotate_memory_is_initialized",
{shape, shape_size}, Call::Extern));
mark_buffer = Block::make(mark_buffer, mark_shape);
if (!is_no_op(pre_call)) {
pre_call = Block::make(pre_call, mark_buffer);
} else {
pre_call = mark_buffer;
}
}
for (const auto &buffer : buffers_contents_to_annotate) {
// Return type is really 'void', but no way to represent that in our IR.
// Precedent (from halide_print, etc) is to use Int(32) and ignore the result.
Stmt mark_contents = Evaluate::make(
Call::make(Int(32), "halide_msan_annotate_buffer_is_initialized", {buffer}, Call::Extern));
if (!is_no_op(pre_call)) {
pre_call = Block::make(pre_call, mark_contents);
} else {
pre_call = mark_contents;
}
}
// Check the output buffer(s) from define_extern() calls to be sure they are fully initialized.
for (const auto &p : buffers_to_check) {
Expr buffer = p.first;
string buf_name = p.second;
Stmt check_contents = Evaluate::make(
Call::make(Int(32), "halide_msan_check_buffer_is_initialized", {buffer, Expr(buf_name)}, Call::Extern));
if (!is_no_op(post_call)) {
post_call = Block::make(post_call, check_contents);
} else {
post_call = check_contents;
}
}
}
// Make the extern call
Expr e = f.make_call_to_extern_definition(extern_call_args, target);
// Check if it succeeded
string result_name = unique_name('t');
Expr result = Variable::make(Int(32), result_name);
Expr error = Call::make(Int(32), "halide_error_extern_stage_failed",
{extern_name, result}, Call::Extern);
Stmt check = AssertStmt::make(EQ::make(result, 0), error);
if (!cropped_buffers.empty()) {
// We need to check that all cropped buffers are non-null (since Call::buffer_crop can return nullptr)
for (const auto &p : cropped_buffers) {
Expr cropped = p.first;
Expr cropped_u64 = reinterpret(UInt(64), cropped);
Expr error = Call::make(Int(32), "halide_error_device_crop_failed", std::vector<Expr>(), Call::Extern);
Stmt assertion = AssertStmt::make(cropped_u64 != 0, error);
if (!is_no_op(pre_call)) {
pre_call = Block::make(pre_call, assertion);
} else {
pre_call = assertion;
}
}
// We need to clean up the temporary crops we made for the
// outputs in case any of them have device allocations.
vector<Expr> cleanup_args;
// Make a struct with the buffers and their uncropped parents
for (const auto &p : cropped_buffers) {
// The cropped halide_buffer_t
cleanup_args.push_back(p.first);
// Its parent
cleanup_args.push_back(p.second);
}
if (cropped_buffers.size() > 1) {
// NULL-terminate it
cleanup_args.push_back(make_zero(type_of<struct halide_buffer_t *>()));
}
Expr cleanup_struct = Call::make(Handle(),
Call::make_struct,
cleanup_args,
Call::Intrinsic);
// Insert cleanup before checking the result of the extern stage.
string destructor_name = unique_name('d');
const char *fn = (cropped_buffers.size() == 1 ? "_halide_buffer_retire_crop_after_extern_stage" : "_halide_buffer_retire_crops_after_extern_stage");
Expr cleanup = Call::make(Int(32), fn, {cleanup_struct}, Call::Extern);
check = Block::make(Evaluate::make(cleanup), check);
}
check = LetStmt::make(result_name, e, check);
if (pre_call.defined()) {
check = Block::make(pre_call, check);
}
for (const auto &let : lets) {
check = LetStmt::make(let.first, let.second, check);
}
if (post_call.defined()) {
check = Block::make(check, post_call);
}
Definition f_def_no_pred = f.definition().get_copy();
f_def_no_pred.predicate() = const_true();
return build_loop_nest(check, f.name() + ".s0.", -1, f, f_def_no_pred, false);
}
// A schedule may include explicit bounds on some dimension. This
// injects assertions that check that those bounds are sufficiently
// large to cover the inferred bounds required.
Stmt inject_explicit_bounds(Stmt body, Function func) {
const FuncSchedule &s = func.schedule();
for (size_t stage = 0; stage <= func.updates().size(); stage++) {
for (auto b : s.bounds()) {
string prefix = func.name() + ".s" + std::to_string(stage) + "." + b.var;
string min_name = prefix + ".min_unbounded";
string max_name = prefix + ".max_unbounded";
Expr min_var = Variable::make(Int(32), min_name);
Expr max_var = Variable::make(Int(32), max_name);
if (!b.min.defined()) {
b.min = min_var;
}
if (!b.extent.defined()) {
// This is just a bounds alignment, which always expands the region computed.
continue;
}
Expr max_val = (b.extent + b.min) - 1;
Expr min_val = b.min;
Expr check = (min_val <= min_var) && (max_val >= max_var);
Expr error_msg = Call::make(Int(32), "halide_error_explicit_bounds_too_small",
{b.var, func.name(), min_val, max_val, min_var, max_var},
Call::Extern);
body = Block::make(AssertStmt::make(check, error_msg), body);
}
}
return body;
}
class IsUsedInStmt : public IRVisitor {
const string &func;
using IRVisitor::visit;
void visit(const Call *op) override {
IRVisitor::visit(op);
if (op->name == func) {
result = true;
}
}
// A reference to the function's buffers counts as a use
void visit(const Variable *op) override {
if (op->type.is_handle() &&
starts_with(op->name, func + ".") &&
ends_with(op->name, ".buffer")) {
result = true;
}
}
public:
bool result = false;
explicit IsUsedInStmt(const Function &f)
: func(f.name()) {
}
};
// Check if function 'f' is ever used in Stmt 's'.
bool function_is_used_in_stmt(const Function &f, const Stmt &s) {
IsUsedInStmt is_called(f);
s.accept(&is_called);
return is_called.result;
}
class IsRealizedInStmt : public IRVisitor {
const string &func;
using IRVisitor::visit;
void visit(const Realize *op) override {
IRVisitor::visit(op);
result = result || (op->name == func);
}
public:
bool result = false;
explicit IsRealizedInStmt(const Function &f)
: func(f.name()) {
}
};
// Check if function 'f' is already realized in Stmt 's'.
bool function_is_already_realized_in_stmt(const Function &f, const Stmt &s) {
IsRealizedInStmt is_realized(f);
s.accept(&is_realized);
return is_realized.result;
}
class InjectStmt : public IRMutator {
public:
const Stmt &injected_stmt;
bool found_level = false;
const LoopLevel &level;
InjectStmt(const Stmt &s, const LoopLevel &level)
: injected_stmt(s), level(level) {
}
private:
using IRMutator::visit;
Stmt visit(const For *for_loop) override {
Stmt body = mutate(for_loop->body);
if (level.match(for_loop->name)) {
body = Block::make(body, injected_stmt);
found_level = true;
}
if (body.same_as(for_loop->body)) {
return for_loop;
} else {
return For::make(for_loop->name,
for_loop->min,
for_loop->extent,
for_loop->for_type,
for_loop->partition_policy,
for_loop->device_api,
body);
}
}
};
// Inject 'injected' into 'root' at 'level'.
Stmt inject_stmt(Stmt root, Stmt injected, const LoopLevel &level) {
if (!root.defined()) {
return injected;
}
if (!injected.defined()) {
return root;
}
if (level.is_inlined() || level.is_root()) {
return Block::make(root, injected);
}
InjectStmt injector(injected, level);
root = injector.mutate(root);
internal_assert(injector.found_level);
return root;
}
// Collect all let stmts that define the loop min, max, and extent.
class CollectBounds : public IRVisitor {