-
Notifications
You must be signed in to change notification settings - Fork 193
/
Copy pathlowerer_impl.cpp
3380 lines (2921 loc) · 141 KB
/
lowerer_impl.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 <taco/lower/mode_format_compressed.h>
#include "taco/lower/lowerer_impl.h"
#include "taco/index_notation/index_notation.h"
#include "taco/index_notation/tensor_operator.h"
#include "taco/index_notation/index_notation_nodes.h"
#include "taco/index_notation/index_notation_visitor.h"
#include "taco/index_notation/provenance_graph.h"
#include "taco/ir/ir.h"
#include "ir/ir_generators.h"
#include "taco/ir/ir_visitor.h"
#include "taco/ir/simplify.h"
#include "taco/lower/iterator.h"
#include "taco/lower/merge_lattice.h"
#include "mode_access.h"
#include "taco/util/collections.h"
#include "taco/util/env.h"
using namespace std;
using namespace taco::ir;
using taco::util::combine;
namespace taco {
class LowererImpl::Visitor : public IndexNotationVisitorStrict {
public:
Visitor(LowererImpl* impl) : impl(impl) {}
Stmt lower(IndexStmt stmt) {
this->stmt = Stmt();
impl->accessibleIterators.scope();
IndexStmtVisitorStrict::visit(stmt);
impl->accessibleIterators.unscope();
return this->stmt;
}
Expr lower(IndexExpr expr) {
this->expr = Expr();
IndexExprVisitorStrict::visit(expr);
return this->expr;
}
private:
LowererImpl* impl;
Expr expr;
Stmt stmt;
using IndexNotationVisitorStrict::visit;
void visit(const AssignmentNode* node) { stmt = impl->lowerAssignment(node); }
void visit(const YieldNode* node) { stmt = impl->lowerYield(node); }
void visit(const ForallNode* node) { stmt = impl->lowerForall(node); }
void visit(const WhereNode* node) { stmt = impl->lowerWhere(node); }
void visit(const MultiNode* node) { stmt = impl->lowerMulti(node); }
void visit(const SuchThatNode* node) { stmt = impl->lowerSuchThat(node); }
void visit(const SequenceNode* node) { stmt = impl->lowerSequence(node); }
void visit(const AccessNode* node) { expr = impl->lowerAccess(node); }
void visit(const LiteralNode* node) { expr = impl->lowerLiteral(node); }
void visit(const NegNode* node) { expr = impl->lowerNeg(node); }
void visit(const AddNode* node) { expr = impl->lowerAdd(node); }
void visit(const SubNode* node) { expr = impl->lowerSub(node); }
void visit(const MulNode* node) { expr = impl->lowerMul(node); }
void visit(const DivNode* node) { expr = impl->lowerDiv(node); }
void visit(const SqrtNode* node) { expr = impl->lowerSqrt(node); }
void visit(const CastNode* node) { expr = impl->lowerCast(node); }
void visit(const CallIntrinsicNode* node) { expr = impl->lowerCallIntrinsic(node); }
void visit(const CallNode* node) { expr = impl->lowerTensorOp(node); }
void visit(const ReductionNode* node) {
taco_ierror << "Reduction nodes not supported in concrete index notation";
}
void visit(const IndexVarNode* node) { expr = impl->lowerIndexVar(node); }
};
LowererImpl::LowererImpl() : visitor(new Visitor(this)) {
}
static void createCapacityVars(const map<TensorVar, Expr>& tensorVars,
map<Expr, Expr>* capacityVars) {
for (auto& tensorVar : tensorVars) {
Expr tensor = tensorVar.second;
Expr capacityVar = Var::make(util::toString(tensor) + "_capacity", Int());
capacityVars->insert({tensor, capacityVar});
}
}
static void createReducedValueVars(const vector<Access>& inputAccesses,
map<Access, Expr>* reducedValueVars) {
for (const auto& access : inputAccesses) {
const TensorVar inputTensor = access.getTensorVar();
const std::string name = inputTensor.getName() + "_val";
const Datatype type = inputTensor.getType().getDataType();
reducedValueVars->insert({access, Var::make(name, type)});
}
}
/// Returns true iff `stmt` modifies an array
static bool hasStores(Stmt stmt) {
struct FindStores : IRVisitor {
bool hasStore;
using IRVisitor::visit;
void visit(const Store* stmt) {
hasStore = true;
}
bool hasStores(Stmt stmt) {
hasStore = false;
stmt.accept(this);
return hasStore;
}
};
return stmt.defined() && FindStores().hasStores(stmt);
}
Stmt
LowererImpl::lower(IndexStmt stmt, string name,
bool assemble, bool compute, bool pack, bool unpack)
{
this->assemble = assemble;
this->compute = compute;
this->funcname = name;
definedIndexVarsOrdered = {};
definedIndexVars = {};
loopOrderAllowsShortCircuit = allForFreeLoopsBeforeAllReductionLoops(stmt);
// Create result and parameter variables
vector<TensorVar> results = getResults(stmt);
vector<TensorVar> arguments = getArguments(stmt);
vector<TensorVar> temporaries = getTemporaries(stmt);
// Create datastructure needed for temporary workspace hoisting/reuse
temporaryInitialization = getTemporaryLocations(stmt);
// Convert tensor results and arguments IR variables
map<TensorVar, Expr> resultVars;
vector<Expr> resultsIR = createVars(results, &resultVars, unpack);
tensorVars.insert(resultVars.begin(), resultVars.end());
vector<Expr> argumentsIR = createVars(arguments, &tensorVars, pack);
// Create variables for index sets on result tensors.
vector<Expr> indexSetArgs;
for (auto& access : getResultAccesses(stmt).first) {
// Any accesses that have index sets will be added.
if (access.hasIndexSetModes()) {
for (size_t i = 0; i < access.getIndexVars().size(); i++) {
if (access.isModeIndexSet(i)) {
auto t = access.getModeIndexSetTensor(i);
if (tensorVars.count(t) == 0) {
ir::Expr irVar = ir::Var::make(t.getName(), t.getType().getDataType(), true, true, pack);
tensorVars.insert({t, irVar});
indexSetArgs.push_back(irVar);
}
}
}
}
}
argumentsIR.insert(argumentsIR.begin(), indexSetArgs.begin(), indexSetArgs.end());
// Create variables for temporaries
// TODO Remove this
for (auto& temp : temporaries) {
ir::Expr irVar = ir::Var::make(temp.getName(), temp.getType().getDataType(),
true, true);
tensorVars.insert({temp, irVar});
}
// Create variables for keeping track of result values array capacity
createCapacityVars(resultVars, &capacityVars);
// Create iterators
iterators = Iterators(stmt, tensorVars);
provGraph = ProvenanceGraph(stmt);
for (const IndexVar& indexVar : provGraph.getAllIndexVars()) {
if (iterators.modeIterators().count(indexVar)) {
indexVarToExprMap.insert({indexVar, iterators.modeIterators()[indexVar].getIteratorVar()});
}
else {
indexVarToExprMap.insert({indexVar, Var::make(indexVar.getName(), Int())});
}
}
vector<Access> inputAccesses, resultAccesses;
set<Access> reducedAccesses;
inputAccesses = getArgumentAccesses(stmt);
std::tie(resultAccesses, reducedAccesses) = getResultAccesses(stmt);
// Create variables that represent the reduced values of duplicated tensor
// components
createReducedValueVars(inputAccesses, &reducedValueVars);
map<TensorVar, Expr> scalars;
// Define and initialize dimension variables
set<TensorVar> temporariesSet(temporaries.begin(), temporaries.end());
vector<IndexVar> indexVars = getIndexVars(stmt);
for (auto& indexVar : indexVars) {
Expr dimension;
// getDimension extracts an Expr that holds the dimension
// of a particular tensor mode. This Expr should be used as a loop bound
// when iterating over the dimension of the target tensor.
auto getDimension = [&](const TensorVar& tv, const Access& a, int mode) {
// If the tensor mode is windowed, then the dimension for iteration is the bounds
// of the window. Otherwise, it is the actual dimension of the mode.
if (a.isModeWindowed(mode)) {
// The mode value used to access .levelIterator is 1-indexed, while
// the mode input to getDimension is 0-indexed. So, we shift it up by 1.
auto iter = iterators.levelIterator(ModeAccess(a, mode+1));
return ir::Div::make(ir::Sub::make(iter.getWindowUpperBound(), iter.getWindowLowerBound()), iter.getStride());
} else if (a.isModeIndexSet(mode)) {
// If the mode has an index set, then the dimension is the size of
// the index set.
return ir::Literal::make(a.getIndexSet(mode).size());
} else {
return GetProperty::make(tensorVars.at(tv), TensorProperty::Dimension, mode);
}
};
match(stmt,
function<void(const AssignmentNode*, Matcher*)>([&](
const AssignmentNode* n, Matcher* m) {
m->match(n->rhs);
if (!dimension.defined()) {
auto ivars = n->lhs.getIndexVars();
auto tv = n->lhs.getTensorVar();
int loc = (int)distance(ivars.begin(),
find(ivars.begin(),ivars.end(), indexVar));
if(!util::contains(temporariesSet, tv)) {
dimension = getDimension(tv, n->lhs, loc);
}
}
}),
function<void(const AccessNode*)>([&](const AccessNode* n) {
auto indexVars = n->indexVars;
if (util::contains(indexVars, indexVar)) {
int loc = (int)distance(indexVars.begin(),
find(indexVars.begin(),indexVars.end(),
indexVar));
if(!util::contains(temporariesSet, n->tensorVar)) {
dimension = getDimension(n->tensorVar, Access(n), loc);
}
}
})
);
dimensions.insert({indexVar, dimension});
underivedBounds.insert({indexVar, {ir::Literal::make(0), dimension}});
}
// Define and initialize scalar results and arguments
if (generateComputeCode()) {
for (auto& result : results) {
if (isScalar(result.getType())) {
taco_iassert(!util::contains(scalars, result));
taco_iassert(util::contains(tensorVars, result));
scalars.insert({result, tensorVars.at(result)});
header.push_back(defineScalarVariable(result, true));
}
}
for (auto& argument : arguments) {
if (isScalar(argument.getType())) {
taco_iassert(!util::contains(scalars, argument));
taco_iassert(util::contains(tensorVars, argument));
scalars.insert({argument, tensorVars.at(argument)});
header.push_back(defineScalarVariable(argument, false));
}
}
}
// Allocate memory for scalar results
if (generateAssembleCode()) {
for (auto& result : results) {
if (result.getOrder() == 0) {
Expr resultIR = resultVars.at(result);
Expr vals = GetProperty::make(resultIR, TensorProperty::Values);
header.push_back(Allocate::make(vals, 1));
}
}
}
// Allocate and initialize append and insert mode indices
Stmt initializeResults = initResultArrays(resultAccesses, inputAccesses,
reducedAccesses);
// Lower the index statement to compute and/or assemble
Stmt body = lower(stmt);
// Post-process result modes and allocate memory for values if necessary
Stmt finalizeResults = finalizeResultArrays(resultAccesses);
// Store scalar stack variables back to results
if (generateComputeCode()) {
for (auto& result : results) {
if (isScalar(result.getType())) {
taco_iassert(util::contains(scalars, result));
taco_iassert(util::contains(tensorVars, result));
Expr resultIR = scalars.at(result);
Expr varValueIR = tensorVars.at(result);
Expr valuesArrIR = GetProperty::make(resultIR, TensorProperty::Values);
footer.push_back(Store::make(valuesArrIR, 0, varValueIR, markAssignsAtomicDepth > 0, atomicParallelUnit));
}
}
}
// Create function
return Function::make(name, resultsIR, argumentsIR,
Block::blanks(Block::make(header),
initializeResults,
body,
finalizeResults,
Block::make(footer)));
}
Stmt LowererImpl::lowerAssignment(Assignment assignment)
{
TensorVar result = assignment.getLhs().getTensorVar();
Stmt computeStmt;
Expr rhs = lower(assignment.getRhs());
if (generateComputeCode()) {
Expr var = getTensorVar(result);
// Assignment to scalar variables.
if (isScalar(result.getType())) {
if (!assignment.getOperator().defined()) {
return Assign::make(var, rhs);
}
else {
if (isa<taco::Add>(assignment.getOperator())) {
return addAssign(var, rhs, markAssignsAtomicDepth > 0 && !util::contains(whereTemps, result),
atomicParallelUnit);
}
taco_iassert(isa<taco::Call>(assignment.getOperator()));
Call op = to<Call>(assignment.getOperator());
Expr assignOp = op.getFunc()({var, rhs});
Stmt assign = Assign::make(var, assignOp, markAssignsAtomicDepth > 0 && !util::contains(whereTemps, result),
atomicParallelUnit);
std::vector<Property> properties = op.getProperties();
assign = Block::make(assign, emitEarlyExit(var, properties));
return assign;
}
}
// Assignments to tensor variables (non-scalar).
else {
Expr values = getValuesArray(result);
Expr loc = generateValueLocExpr(assignment.getLhs());
if (!assignment.getOperator().defined()) {
computeStmt = Store::make(values, loc, rhs);
}
else {
if (isa<taco::Add>(assignment.getOperator())) {
computeStmt = compoundStore(values, loc, rhs, markAssignsAtomicDepth > 0, atomicParallelUnit);
} else {
taco_iassert(isa<taco::Call>(assignment.getOperator()));
Call op = to<Call>(assignment.getOperator());
Expr assignOp = op.getFunc()({Load::make(values, loc), rhs});
computeStmt = Store::make(values, loc, assignOp,
markAssignsAtomicDepth > 0 && !util::contains(whereTemps, result),
atomicParallelUnit);
std::vector<Property> properties = op.getProperties();
computeStmt = Block::make(computeStmt, emitEarlyExit(Load::make(values, loc), properties));
}
}
taco_iassert(computeStmt.defined());
}
}
// TODO: If only assembling so defer allocating value memory to the end when
// we'll know exactly how much we need.
if (generateAssembleCode() || generateComputeCode()) {
bool temporaryWithSparseAcceleration = util::contains(tempToIndexList, result);
if(generateComputeCode() && !temporaryWithSparseAcceleration) {
taco_iassert(computeStmt.defined());
return computeStmt;
}
if(temporaryWithSparseAcceleration) {
Expr values = getValuesArray(result);
Expr loc = generateValueLocExpr(assignment.getLhs());
Stmt initialStorage = computeStmt;
if(assignment.getOperator().defined()) {
// computeStmt is a compund stmt so we need to emit an initial store into the temporary
initialStorage = Store::make(values, loc, rhs, markAssignsAtomicDepth > 0, atomicParallelUnit);
}
Expr bitGuardArr = tempToBitGuard.at(result);
Expr indexList = tempToIndexList.at(result);
Expr indexListSize = tempToIndexListSize.at(result);
Stmt markBitGuardAsTrue = Store::make(bitGuardArr, loc, ir::Literal::make(true), markAssignsAtomicDepth > 0, atomicParallelUnit);
Stmt trackIndex = Store::make(indexList, indexListSize, loc, markAssignsAtomicDepth > 0, atomicParallelUnit);
Expr incrementSize = ir::Add::make(indexListSize, ir::Literal::make(1));
Stmt incrementStmt = Assign::make(indexListSize, incrementSize, markAssignsAtomicDepth > 0, atomicParallelUnit);
Stmt firstWriteAtIndex = Block::make(initialStorage, trackIndex, markBitGuardAsTrue, incrementStmt);
if(!generateComputeCode()) {
firstWriteAtIndex = Block::make(trackIndex, markBitGuardAsTrue, incrementStmt);
}
Expr readBitGuard = Load::make(bitGuardArr, loc);
Stmt finalStmt = IfThenElse::make(ir::Neg::make(readBitGuard), firstWriteAtIndex, computeStmt);
return finalStmt;
}
return Stmt();
}
// We're neither assembling or computing so we emit nothing.
else {
return Stmt();
}
taco_unreachable;
return Stmt();
}
Stmt LowererImpl::lowerYield(Yield yield) {
std::vector<Expr> coords;
for (auto& indexVar : yield.getIndexVars()) {
coords.push_back(getCoordinateVar(indexVar));
}
Expr val = lower(yield.getExpr());
return ir::Yield::make(coords, val);
}
static pair<vector<Iterator>, vector<Iterator>>
splitAppenderAndInserters(const vector<Iterator>& results) {
vector<Iterator> appenders;
vector<Iterator> inserters;
// TODO: Choose insert when the current forall is nested inside a reduction
for (auto& result : results) {
taco_iassert(result.hasAppend() || result.hasInsert())
<< "Results must support append or insert";
if (result.hasAppend()) {
appenders.push_back(result);
}
else {
taco_iassert(result.hasInsert());
inserters.push_back(result);
}
}
return {appenders, inserters};
}
Stmt LowererImpl::lowerForall(Forall forall)
{
bool hasExactBound = provGraph.hasExactBound(forall.getIndexVar());
bool forallNeedsUnderivedGuards = !hasExactBound && emitUnderivedGuards;
if (!ignoreVectorize && forallNeedsUnderivedGuards &&
(forall.getParallelUnit() == ParallelUnit::CPUVector ||
forall.getUnrollFactor() > 0)) {
return lowerForallCloned(forall);
}
if (forall.getParallelUnit() != ParallelUnit::NotParallel) {
inParallelLoopDepth++;
}
// Recover any available parents that were not recoverable previously
vector<Stmt> recoverySteps;
for (const IndexVar& varToRecover : provGraph.newlyRecoverableParents(forall.getIndexVar(), definedIndexVars)) {
// place pos guard
if (forallNeedsUnderivedGuards && provGraph.isCoordVariable(varToRecover) &&
provGraph.getChildren(varToRecover).size() == 1 &&
provGraph.isPosVariable(provGraph.getChildren(varToRecover)[0])) {
IndexVar posVar = provGraph.getChildren(varToRecover)[0];
std::vector<ir::Expr> iterBounds = provGraph.deriveIterBounds(posVar, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
Expr minGuard = Lt::make(indexVarToExprMap[posVar], iterBounds[0]);
Expr maxGuard = Gte::make(indexVarToExprMap[posVar], iterBounds[1]);
Expr guardCondition = Or::make(minGuard, maxGuard);
if (isa<ir::Literal>(ir::simplify(iterBounds[0])) && ir::simplify(iterBounds[0]).as<ir::Literal>()->equalsScalar(0)) {
guardCondition = maxGuard;
}
ir::Stmt guard = ir::IfThenElse::make(guardCondition, ir::Continue::make());
recoverySteps.push_back(guard);
}
Expr recoveredValue = provGraph.recoverVariable(varToRecover, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
taco_iassert(indexVarToExprMap.count(varToRecover));
recoverySteps.push_back(VarDecl::make(indexVarToExprMap[varToRecover], recoveredValue));
// After we've recovered this index variable, some iterators are now
// accessible for use when declaring locator access variables. So, generate
// the accessors for those locator variables as part of the recovery process.
// This is necessary after a fuse transformation, for example: If we fuse
// two index variables (i, j) into f, then after we've generated the loop for
// f, all locate accessors for i and j are now available for use.
std::vector<Iterator> itersForVar;
for (auto& iters : iterators.levelIterators()) {
// Collect all level iterators that have locate and iterate over
// the recovered index variable.
if (iters.second.getIndexVar() == varToRecover && iters.second.hasLocate()) {
itersForVar.push_back(iters.second);
}
}
// Finally, declare all of the collected iterators' position access variables.
recoverySteps.push_back(this->declLocatePosVars(itersForVar));
// place underived guard
std::vector<ir::Expr> iterBounds = provGraph.deriveIterBounds(varToRecover, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
if (forallNeedsUnderivedGuards && underivedBounds.count(varToRecover) &&
!provGraph.hasPosDescendant(varToRecover)) {
// FIXME: [Olivia] Check this with someone
// Removed underived guard if indexVar is bounded is divisible by its split child indexVar
vector<IndexVar> children = provGraph.getChildren(varToRecover);
bool hasDirectDivBound = false;
std::vector<ir::Expr> iterBoundsInner = provGraph.deriveIterBounds(forall.getIndexVar(), definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
for (auto& c: children) {
if (provGraph.hasExactBound(c) && provGraph.derivationPath(varToRecover, c).size() == 2) {
std::vector<ir::Expr> iterBoundsUnderivedChild = provGraph.deriveIterBounds(c, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
if (iterBoundsUnderivedChild[1].as<ir::Literal>()->getValue<int>() % iterBoundsInner[1].as<ir::Literal>()->getValue<int>() == 0)
hasDirectDivBound = true;
break;
}
}
if (!hasDirectDivBound) {
Stmt guard = IfThenElse::make(Gte::make(indexVarToExprMap[varToRecover], underivedBounds[varToRecover][1]),
Continue::make());
recoverySteps.push_back(guard);
}
}
// If this index variable was divided into multiple equal chunks, then we
// must add an extra guard to make sure that further scheduling operations
// on descendent index variables exceed the bounds of each equal portion of
// the loop. For a concrete example, consider a loop of size 10 that is divided
// into two equal components -- 5 and 5. If the loop is then transformed
// with .split(..., 3), each inner chunk of 5 will be split into chunks of
// 3. Without an extra guard, the second chunk of 3 in the first group of 5
// may attempt to perform an iteration for the second group of 5, which is
// incorrect.
if (this->provGraph.isDivided(varToRecover)) {
// Collect the children iteration variables.
auto children = this->provGraph.getChildren(varToRecover);
auto outer = children[0];
auto inner = children[1];
// Find the iteration bounds of the inner variable -- that is the size
// that the outer loop was broken into.
auto bounds = this->provGraph.deriveIterBounds(inner, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
// Use the difference between the bounds to find the size of the loop.
auto dimLen = ir::Sub::make(bounds[1], bounds[0]);
// For a variable f divided into into f1 and f2, the guard ensures that
// for iteration f, f should be within f1 * dimLen and (f1 + 1) * dimLen.
auto guard = ir::Gte::make(this->indexVarToExprMap[varToRecover], ir::Mul::make(ir::Add::make(this->indexVarToExprMap[outer], 1), dimLen));
recoverySteps.push_back(IfThenElse::make(guard, ir::Continue::make()));
}
}
Stmt recoveryStmt = Block::make(recoverySteps);
taco_iassert(!definedIndexVars.count(forall.getIndexVar()));
definedIndexVars.insert(forall.getIndexVar());
definedIndexVarsOrdered.push_back(forall.getIndexVar());
if (forall.getParallelUnit() != ParallelUnit::NotParallel) {
taco_iassert(!parallelUnitSizes.count(forall.getParallelUnit()));
taco_iassert(!parallelUnitIndexVars.count(forall.getParallelUnit()));
parallelUnitIndexVars[forall.getParallelUnit()] = forall.getIndexVar();
vector<Expr> bounds = provGraph.deriveIterBounds(forall.getIndexVar(), definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
parallelUnitSizes[forall.getParallelUnit()] = ir::Sub::make(bounds[1], bounds[0]);
}
MergeLattice caseLattice = MergeLattice::make(forall, iterators, provGraph, definedIndexVars, whereTempsToResult);
// std::cout << "case lattice: " << forall.getIndexVar() << " " << caseLattice << std::endl;
// std::cout << "merge lattice: " << forall.getIndexVar() << " " << caseLattice.getLoopLattice() << std::endl;
vector<Access> resultAccesses;
set<Access> reducedAccesses;
std::tie(resultAccesses, reducedAccesses) = getResultAccesses(forall);
// Pre-allocate/initialize memory of value arrays that are full below this
// loops index variable
Stmt preInitValues = initResultArrays(forall.getIndexVar(), resultAccesses,
getArgumentAccesses(forall),
reducedAccesses);
// Emit temporary initialization if forall is sequential and leads to a where statement
vector<Stmt> temporaryValuesInitFree = {Stmt(), Stmt()};
auto temp = temporaryInitialization.find(forall);
if (temp != temporaryInitialization.end() && forall.getParallelUnit() == ParallelUnit::NotParallel && !isScalar(temp->second.getTemporary().getType()))
temporaryValuesInitFree = codeToInitializeTemporary(temp->second);
Stmt loops;
// Emit a loop that iterates over over a single iterator (optimization)
if (caseLattice.iterators().size() == 1 && caseLattice.iterators()[0].isUnique() && false) {
MergeLattice loopLattice = caseLattice.getLoopLattice();
MergePoint point = loopLattice.points()[0];
Iterator iterator = loopLattice.iterators()[0];
vector<Iterator> locators = point.locators();
vector<Iterator> appenders;
vector<Iterator> inserters;
tie(appenders, inserters) = splitAppenderAndInserters(point.results());
std::vector<IndexVar> underivedAncestors = provGraph.getUnderivedAncestors(iterator.getIndexVar());
IndexVar posDescendant;
bool hasPosDescendant = false;
if (!underivedAncestors.empty()) {
hasPosDescendant = provGraph.getPosIteratorFullyDerivedDescendant(underivedAncestors[0], &posDescendant);
}
bool isWhereProducer = false;
vector<Iterator> results = point.results();
for (Iterator result : results) {
for (auto it = tensorVars.begin(); it != tensorVars.end(); it++) {
if (it->second == result.getTensor()) {
if (whereTempsToResult.count(it->first)) {
isWhereProducer = true;
break;
}
}
}
}
// For now, this only works when consuming a single workspace.
bool canAccelWithSparseIteration = inParallelLoopDepth == 0 && provGraph.isFullyDerived(iterator.getIndexVar()) &&
iterator.isDimensionIterator() && locators.size() == 1;
if (canAccelWithSparseIteration) {
bool indexListsExist = false;
// We are iterating over a dimension and locating into a temporary with a tracker to keep indices. Instead, we
// can just iterate over the indices and locate into the dense workspace.
for (auto it = tensorVars.begin(); it != tensorVars.end(); ++it) {
if (it->second == locators[0].getTensor() && util::contains(tempToIndexList, it->first)) {
indexListsExist = true;
break;
}
}
canAccelWithSparseIteration &= indexListsExist;
}
if (!isWhereProducer && hasPosDescendant && underivedAncestors.size() > 1 && provGraph.isPosVariable(iterator.getIndexVar()) && posDescendant == forall.getIndexVar()) {
loops = lowerForallFusedPosition(forall, iterator, locators, inserters, appenders, caseLattice,
reducedAccesses, recoveryStmt);
}
else if (canAccelWithSparseIteration) {
loops = lowerForallDenseAcceleration(forall, locators, inserters, appenders, caseLattice, reducedAccesses, recoveryStmt);
}
// Emit dimension coordinate iteration loop
else if (iterator.isDimensionIterator()) {
loops = lowerForallDimension(forall, point.locators(), inserters, appenders, caseLattice,
reducedAccesses, recoveryStmt);
}
// Emit position iteration loop
else if (iterator.hasPosIter()) {
loops = lowerForallPosition(forall, iterator, locators, inserters, appenders, caseLattice,
reducedAccesses, recoveryStmt);
}
// Emit coordinate iteration loop
else {
taco_iassert(iterator.hasCoordIter());
// taco_not_supported_yet
loops = Stmt();
}
}
// Emit general loops to merge multiple iterators
else {
std::vector<IndexVar> underivedAncestors = provGraph.getUnderivedAncestors(forall.getIndexVar());
taco_iassert(underivedAncestors.size() == 1); // TODO: add support for fused coordinate of pos loop
loops = lowerMergeLattice(caseLattice, underivedAncestors[0],
forall.getStmt(), reducedAccesses);
}
taco_iassert(loops.defined());
// std::cout << "LOOPS " << loops << std::endl;
if (!generateComputeCode() && !hasStores(loops)) {
// If assembly loop does not modify output arrays, then it can be safely
// omitted.
loops = Stmt();
}
definedIndexVars.erase(forall.getIndexVar());
definedIndexVarsOrdered.pop_back();
if (forall.getParallelUnit() != ParallelUnit::NotParallel) {
inParallelLoopDepth--;
taco_iassert(parallelUnitSizes.count(forall.getParallelUnit()));
taco_iassert(parallelUnitIndexVars.count(forall.getParallelUnit()));
parallelUnitIndexVars.erase(forall.getParallelUnit());
parallelUnitSizes.erase(forall.getParallelUnit());
}
return Block::blanks(preInitValues,
temporaryValuesInitFree[0],
loops,
temporaryValuesInitFree[1]);
}
Stmt LowererImpl::lowerForallCloned(Forall forall) {
// want to emit guards outside of loop to prevent unstructured loop exits
// construct guard
// underived or pos variables that have a descendant that has not been defined yet
vector<IndexVar> varsWithGuard;
for (auto var : provGraph.getAllIndexVars()) {
if (provGraph.isRecoverable(var, definedIndexVars)) {
continue; // already recovered
}
if (provGraph.isUnderived(var) && !provGraph.hasPosDescendant(var)) { // if there is pos descendant then will be guarded already
varsWithGuard.push_back(var);
}
else if (provGraph.isPosVariable(var)) {
// if parent is coord then this is variable that will be guarded when indexing into coord array
if(provGraph.getParents(var).size() == 1 && provGraph.isCoordVariable(provGraph.getParents(var)[0])) {
varsWithGuard.push_back(var);
}
}
}
// determine min and max values for vars given already defined variables.
// we do a recovery where we fill in undefined variables with either 0's or the max of their iteration
std::map<IndexVar, Expr> minVarValues;
std::map<IndexVar, Expr> maxVarValues;
set<IndexVar> definedForGuard = definedIndexVars;
vector<Stmt> guardRecoverySteps;
Expr maxOffset = 0;
bool setMaxOffset = false;
for (auto var : varsWithGuard) {
std::vector<IndexVar> currentDefinedVarOrder = definedIndexVarsOrdered; // TODO: get defined vars at time of this recovery
std::map<IndexVar, Expr> minChildValues = indexVarToExprMap;
std::map<IndexVar, Expr> maxChildValues = indexVarToExprMap;
for (auto child : provGraph.getFullyDerivedDescendants(var)) {
if (!definedIndexVars.count(child)) {
std::vector<ir::Expr> childBounds = provGraph.deriveIterBounds(child, currentDefinedVarOrder, underivedBounds, indexVarToExprMap, iterators);
minChildValues[child] = childBounds[0];
maxChildValues[child] = childBounds[1];
// recover new parents
for (const IndexVar& varToRecover : provGraph.newlyRecoverableParents(child, definedForGuard)) {
Expr recoveredValue = provGraph.recoverVariable(varToRecover, definedIndexVarsOrdered, underivedBounds,
minChildValues, iterators);
Expr maxRecoveredValue = provGraph.recoverVariable(varToRecover, definedIndexVarsOrdered, underivedBounds,
maxChildValues, iterators);
if (!setMaxOffset) { // TODO: work on simplifying this
maxOffset = ir::Add::make(maxOffset, ir::Sub::make(maxRecoveredValue, recoveredValue));
setMaxOffset = true;
}
taco_iassert(indexVarToExprMap.count(varToRecover));
guardRecoverySteps.push_back(VarDecl::make(indexVarToExprMap[varToRecover], recoveredValue));
definedForGuard.insert(varToRecover);
}
definedForGuard.insert(child);
}
}
minVarValues[var] = provGraph.recoverVariable(var, currentDefinedVarOrder, underivedBounds, minChildValues, iterators);
maxVarValues[var] = provGraph.recoverVariable(var, currentDefinedVarOrder, underivedBounds, maxChildValues, iterators);
}
// Build guards
Expr guardCondition;
for (auto var : varsWithGuard) {
std::vector<ir::Expr> iterBounds = provGraph.deriveIterBounds(var, definedIndexVarsOrdered, underivedBounds, indexVarToExprMap, iterators);
Expr minGuard = Lt::make(minVarValues[var], iterBounds[0]);
Expr maxGuard = Gte::make(ir::Add::make(maxVarValues[var], ir::simplify(maxOffset)), iterBounds[1]);
Expr guardConditionCurrent = Or::make(minGuard, maxGuard);
if (isa<ir::Literal>(ir::simplify(iterBounds[0])) && ir::simplify(iterBounds[0]).as<ir::Literal>()->equalsScalar(0)) {
guardConditionCurrent = maxGuard;
}
if (guardCondition.defined()) {
guardCondition = Or::make(guardConditionCurrent, guardCondition);
}
else {
guardCondition = guardConditionCurrent;
}
}
Stmt unvectorizedLoop;
// build loop with guards (not vectorized)
if (!varsWithGuard.empty()) {
ignoreVectorize = true;
unvectorizedLoop = lowerForall(forall);
ignoreVectorize = false;
}
// build loop without guards
emitUnderivedGuards = false;
Stmt vectorizedLoop = lowerForall(forall);
emitUnderivedGuards = true;
// return guarded loops
return Block::make(Block::make(guardRecoverySteps), IfThenElse::make(guardCondition, unvectorizedLoop, vectorizedLoop));
}
Stmt LowererImpl::searchForFusedPositionStart(Forall forall, Iterator posIterator) {
vector<Stmt> searchForUnderivedStart;
vector<IndexVar> underivedAncestors = provGraph.getUnderivedAncestors(forall.getIndexVar());
ir::Expr last_block_start_temporary;
for (int i = (int) underivedAncestors.size() - 2; i >= 0; i--) {
Iterator posIteratorLevel = posIterator;
for (int j = (int) underivedAncestors.size() - 2; j > i; j--) { // take parent of iterator enough times to get correct level
posIteratorLevel = posIteratorLevel.getParent();
}
// want to get size of pos array not of crd_array
ir::Expr parentSize = 1; // to find size of segment walk down sizes of iterator chain
Iterator rootIterator = posIterator;
while (!rootIterator.isRoot()) {
rootIterator = rootIterator.getParent();
}
while (rootIterator.getChild() != posIteratorLevel) {
rootIterator = rootIterator.getChild();
if (rootIterator.hasAppend()) {
parentSize = rootIterator.getSize(parentSize);
} else if (rootIterator.hasInsert()) {
parentSize = ir::Mul::make(parentSize, rootIterator.getWidth());
}
}
// emit bounds search on cpu just bounds, on gpu search in blocks
if (parallelUnitIndexVars.count(ParallelUnit::GPUBlock)) {
Expr values_per_block;
{
// we do a recovery where we fill in undefined variables with 0's to get start target (just like for vector guards)
std::map<IndexVar, Expr> zeroedChildValues = indexVarToExprMap;
zeroedChildValues[parallelUnitIndexVars[ParallelUnit::GPUBlock]] = 1;
set<IndexVar> zeroDefinedIndexVars = {parallelUnitIndexVars[ParallelUnit::GPUBlock]};
for (IndexVar child : provGraph.getFullyDerivedDescendants(posIterator.getIndexVar())) {
if (child != parallelUnitIndexVars[ParallelUnit::GPUBlock]) {
zeroedChildValues[child] = 0;
// recover new parents
for (const IndexVar &varToRecover : provGraph.newlyRecoverableParents(child, zeroDefinedIndexVars)) {
Expr recoveredValue = provGraph.recoverVariable(varToRecover, definedIndexVarsOrdered, underivedBounds,
zeroedChildValues, iterators);
taco_iassert(indexVarToExprMap.count(varToRecover));
zeroedChildValues[varToRecover] = recoveredValue;
zeroDefinedIndexVars.insert(varToRecover);
if (varToRecover == posIterator.getIndexVar()) {
break;
}
}
zeroDefinedIndexVars.insert(child);
}
}
values_per_block = zeroedChildValues[posIterator.getIndexVar()];
}
IndexVar underived = underivedAncestors[i];
ir::Expr blockStarts_temporary = ir::Var::make(underived.getName() + "_blockStarts",
getCoordinateVar(underived).type(), true, false);
header.push_back(ir::VarDecl::make(blockStarts_temporary, 0));
header.push_back(
Allocate::make(blockStarts_temporary, ir::Add::make(parallelUnitSizes[ParallelUnit::GPUBlock], 1)));
footer.push_back(Free::make(blockStarts_temporary));
Expr blockSize;
if (parallelUnitSizes.count(ParallelUnit::GPUThread)) {
blockSize = parallelUnitSizes[ParallelUnit::GPUThread];
if (parallelUnitSizes.count(ParallelUnit::GPUWarp)) {
blockSize = ir::Mul::make(blockSize, parallelUnitSizes[ParallelUnit::GPUWarp]);
}
} else {
std::vector<IndexVar> definedIndexVarsMatched = definedIndexVarsOrdered;
// find sub forall that tells us block size
match(forall.getStmt(),
function<void(const ForallNode *, Matcher *)>([&](
const ForallNode *n, Matcher *m) {
if (n->parallel_unit == ParallelUnit::GPUThread) {
vector<Expr> bounds = provGraph.deriveIterBounds(forall.getIndexVar(), definedIndexVarsMatched,
underivedBounds, indexVarToExprMap, iterators);
blockSize = ir::Sub::make(bounds[1], bounds[0]);
}
definedIndexVarsMatched.push_back(n->indexVar);
})
);
}
taco_iassert(blockSize.defined());
if (i == (int) underivedAncestors.size() - 2) {
std::vector<Expr> args = {
posIteratorLevel.getMode().getModePack().getArray(0), // array
blockStarts_temporary, // results
ir::Literal::zero(posIteratorLevel.getBeginVar().type()), // arrayStart
parentSize, // arrayEnd
values_per_block, // values_per_block
blockSize, // block_size
parallelUnitSizes[ParallelUnit::GPUBlock] // num_blocks
};
header.push_back(ir::Assign::make(blockStarts_temporary,
ir::Call::make("taco_binarySearchBeforeBlockLaunch", args,
getCoordinateVar(underived).type())));
}
else {
std::vector<Expr> args = {
posIteratorLevel.getMode().getModePack().getArray(0), // array
blockStarts_temporary, // results
ir::Literal::zero(posIteratorLevel.getBeginVar().type()), // arrayStart
parentSize, // arrayEnd
last_block_start_temporary, // targets
blockSize, // block_size
parallelUnitSizes[ParallelUnit::GPUBlock] // num_blocks
};
header.push_back(ir::Assign::make(blockStarts_temporary,
ir::Call::make("taco_binarySearchIndirectBeforeBlockLaunch", args,
getCoordinateVar(underived).type())));
}
searchForUnderivedStart.push_back(VarDecl::make(posIteratorLevel.getBeginVar(),
ir::Load::make(blockStarts_temporary,
indexVarToExprMap[parallelUnitIndexVars[ParallelUnit::GPUBlock]])));
searchForUnderivedStart.push_back(VarDecl::make(posIteratorLevel.getEndVar(),
ir::Load::make(blockStarts_temporary, ir::Add::make(
indexVarToExprMap[parallelUnitIndexVars[ParallelUnit::GPUBlock]],
1))));
last_block_start_temporary = blockStarts_temporary;
} else {
header.push_back(VarDecl::make(posIteratorLevel.getBeginVar(), ir::Literal::zero(posIteratorLevel.getBeginVar().type())));
header.push_back(VarDecl::make(posIteratorLevel.getEndVar(), parentSize));
}
// we do a recovery where we fill in undefined variables with 0's to get start target (just like for vector guards)
Expr underivedStartTarget;
if (i == (int) underivedAncestors.size() - 2) {
std::map<IndexVar, Expr> minChildValues = indexVarToExprMap;
set<IndexVar> minDefinedIndexVars = definedIndexVars;
minDefinedIndexVars.erase(forall.getIndexVar());
for (IndexVar child : provGraph.getFullyDerivedDescendants(posIterator.getIndexVar())) {
if (!minDefinedIndexVars.count(child)) {
std::vector<ir::Expr> childBounds = provGraph.deriveIterBounds(child, definedIndexVarsOrdered,
underivedBounds,
indexVarToExprMap, iterators);
minChildValues[child] = childBounds[0];
// recover new parents
for (const IndexVar &varToRecover : provGraph.newlyRecoverableParents(child, minDefinedIndexVars)) {
Expr recoveredValue = provGraph.recoverVariable(varToRecover, definedIndexVarsOrdered, underivedBounds,
minChildValues, iterators);
taco_iassert(indexVarToExprMap.count(varToRecover));
searchForUnderivedStart.push_back(VarDecl::make(indexVarToExprMap[varToRecover], recoveredValue));
minDefinedIndexVars.insert(varToRecover);
if (varToRecover == posIterator.getIndexVar()) {
break;
}
}
minDefinedIndexVars.insert(child);
}
}
underivedStartTarget = indexVarToExprMap[posIterator.getIndexVar()];
}
else {
underivedStartTarget = this->iterators.modeIterator(underivedAncestors[i+1]).getPosVar();
}
vector<Expr> binarySearchArgs = {
posIteratorLevel.getMode().getModePack().getArray(0), // array
posIteratorLevel.getBeginVar(), // arrayStart
posIteratorLevel.getEndVar(), // arrayEnd
underivedStartTarget // target
};
Expr posVarUnknown = this->iterators.modeIterator(underivedAncestors[i]).getPosVar();
searchForUnderivedStart.push_back(ir::VarDecl::make(posVarUnknown,
ir::Call::make("taco_binarySearchBefore", binarySearchArgs,
getCoordinateVar(underivedAncestors[i]).type())));
Stmt locateCoordVar;
if (posIteratorLevel.getParent().hasPosIter()) {
locateCoordVar = ir::VarDecl::make(indexVarToExprMap[underivedAncestors[i]], ir::Load::make(posIteratorLevel.getParent().getMode().getModePack().getArray(1), posVarUnknown));
}
else {
locateCoordVar = ir::VarDecl::make(indexVarToExprMap[underivedAncestors[i]], posVarUnknown);
}
searchForUnderivedStart.push_back(locateCoordVar);
}
return ir::Block::make(searchForUnderivedStart);
}
Stmt LowererImpl::lowerForallDimension(Forall forall,
vector<Iterator> locators,
vector<Iterator> inserters,
vector<Iterator> appenders,
MergeLattice caseLattice,
set<Access> reducedAccesses,
ir::Stmt recoveryStmt)
{
Expr coordinate = getCoordinateVar(forall.getIndexVar());
if (forall.getParallelUnit() != ParallelUnit::NotParallel && forall.getOutputRaceStrategy() == OutputRaceStrategy::Atomics) {
markAssignsAtomicDepth++;
atomicParallelUnit = forall.getParallelUnit();
}
Stmt body = lowerForallBody(coordinate, forall.getStmt(), locators, inserters,
appenders, caseLattice, reducedAccesses);
if (forall.getParallelUnit() != ParallelUnit::NotParallel && forall.getOutputRaceStrategy() == OutputRaceStrategy::Atomics) {
markAssignsAtomicDepth--;