/
storage_flatten.cc
1936 lines (1645 loc) · 67 KB
/
storage_flatten.cc
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file storage_flatten.cc
* \brief Flattens storage from multi-dimensional array to 1D buffer access
*/
// The pass definition originates from Halide pipeline.
#include <tvm/arith/analyzer.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/registry.h>
#include <tvm/target/target_info.h>
#include <tvm/te/operation.h>
#include <tvm/tir/buffer.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
#include <unordered_map>
#include <unordered_set>
#include "../../arith/ir_visitor_with_analyzer.h"
#include "../../runtime/thread_storage_scope.h"
#include "arg_binder.h"
#include "ir_utils.h"
namespace tvm {
namespace tir {
using arith::IRVisitorWithAnalyzer;
using runtime::StorageRank;
using runtime::StorageScope;
using runtime::ThreadScope;
/* Make buffer realize extents and buffer shapes consistent
*
* For external buffers, verify that the extents of BufferRealize
* nodes match the shape of the external buffer. For internal
* buffers, rewrite the shape of the Buffer objects to match the
* extent of the BufferRealize, and rewrite indices of
* BufferLoad/BufferStore nodes to match.
*/
class BufferShapeLegalize : public StmtExprMutator {
public:
static transform::Pass Pass() {
auto pass_func = [](PrimFunc func, IRModule m, transform::PassContext ctx) {
IRVisitorWithAnalyzer bound_analyzer;
bound_analyzer(func->body);
auto pass = BufferShapeLegalize(func->buffer_map, &bound_analyzer);
auto fptr = func.CopyOnWrite();
fptr->body = pass(std::move(fptr->body));
if (auto map = func->attrs.GetAttr<Map<Buffer, Array<IndexMap>>>("layout_transform_map")) {
func = WithAttr(std::move(func), "layout_transform_map", pass.UpdateIndexMap(map.value()));
}
return func;
};
return transform::CreatePrimFuncPass(pass_func, 0, "tir.BufferShapeLegalize", {});
}
explicit BufferShapeLegalize(const Map<Var, Buffer>& extern_buffer_map,
IRVisitorWithAnalyzer* bound_analyzer)
: bound_analyzer_(bound_analyzer) {
for (auto kv : extern_buffer_map) {
Buffer buf = kv.second;
extern_buffers_.insert(buf);
BufferEntry remap;
remap.remap_to = buf;
remap.index_offsets = Array<PrimExpr>(buf->shape.size(), 0);
remap.in_scope = true;
buf_map_[buf] = remap;
}
}
Map<Buffer, Array<IndexMap>> UpdateIndexMap(const Map<Buffer, Array<IndexMap>>& orig) {
Map<Buffer, Array<IndexMap>> output;
for (const auto& kv : orig) {
auto it = buf_map_.find(kv.first);
if (it != buf_map_.end()) {
output.Set(it->second.remap_to, kv.second);
} else {
output.Set(kv.first, kv.second);
}
}
return output;
}
PrimExpr VisitExpr_(const VarNode* op) final {
auto it = var_remap_.find(op);
if (it != var_remap_.end()) {
return it->second;
} else {
return GetRef<PrimExpr>(op);
}
}
Stmt VisitStmt_(const BufferRealizeNode* op) final {
// BufferRealizeNode for an external buffer serves as an
// annotation of the external buffers, and should not be changed.
// Instead, verify that the bounds match the external
// buffer.
if (extern_buffers_.count(op->buffer)) {
CHECK_EQ(op->buffer->shape.size(), op->bounds.size())
<< "External buffer realize has mismatched dimension";
Stmt stmt = StmtExprMutator::VisitStmt_(op);
op = stmt.as<BufferRealizeNode>();
ICHECK(op);
for (size_t i = 0; i < op->bounds.size(); i++) {
PrimExpr eq = bound_analyzer_->Simplify(op->buffer->shape[i] == op->bounds[i]->extent);
std::ostringstream ss;
ss << "Dim " << i << " of external buffer " << op->buffer->name << " has shape "
<< op->buffer->shape[i] << ", but is only realized for extent " << op->bounds[i]->extent;
if (auto eq_int = eq.as<IntImmNode>()) {
ICHECK(eq_int->value) << ss.str();
} else {
stmt = AssertStmt(eq, tvm::tir::StringImm(ss.str()), stmt);
}
}
return stmt;
}
// Compute the new buffer shape, new realization bounds, and the
// offsets to be applied to buffer access.
Array<PrimExpr> realized_shape;
Array<PrimExpr> index_offsets;
Array<Range> new_bounds;
for (size_t i = 0; i < op->bounds.size(); i++) {
const Range& bound = op->bounds[i];
realized_shape.push_back(bound->extent);
index_offsets.push_back(bound->min);
new_bounds.push_back({0, bound->extent});
}
if (op->buffer->shape.size()) {
ICHECK_EQ(op->buffer->shape.size(), realized_shape.size())
<< "Inconsistency between dimension of buffer " << op->buffer
<< " and dimension of its realized bounds.";
}
Buffer key = op->buffer;
Buffer buf = op->buffer;
auto write_ptr = buf.CopyOnWrite();
write_ptr->shape = realized_shape;
{
BufferEntry remap;
remap.remap_to = buf;
remap.index_offsets = index_offsets;
remap.in_scope = true;
buf_map_[key] = remap;
}
Stmt stmt = BufferRealize(buf, new_bounds, op->condition, this->VisitStmt(op->body), op->span);
buf_map_.at(key).in_scope = false;
return stmt;
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
auto node = Downcast<BufferStore>(StmtExprMutator::VisitStmt_(op));
return VisitBufferAccess(std::move(node));
}
PrimExpr VisitExpr_(const BufferLoadNode* op) final {
auto node = Downcast<BufferLoad>(StmtExprMutator::VisitExpr_(op));
return VisitBufferAccess(std::move(node));
}
template <typename Node>
Node VisitBufferAccess(Node node) {
auto it = buf_map_.find(node->buffer);
if (it != buf_map_.end()) {
const BufferEntry& entry = it->second;
ICHECK(entry.in_scope) << "Cannot access an out-of-scope buffer";
Array<PrimExpr> indices = node->indices;
if (entry.index_offsets.size()) {
ICHECK_GE(entry.index_offsets.size(), indices.size())
<< "Cannot bind buffer to a shape of lower dimension.";
Array<PrimExpr> new_indices;
// Pad leading indices with zero, matching the "fuzzy_match"
// behavior from ArgBinder::BindBuffer.
size_t diff = entry.index_offsets.size() - indices.size();
for (size_t i = 0; i < diff; i++) {
new_indices.push_back(0);
}
// Offset indices used to access buffers of a reduced size.
for (size_t i = 0; i < indices.size(); i++) {
PrimExpr offset = entry.index_offsets[i + diff];
new_indices.push_back(indices[i] - offset);
}
indices = new_indices;
}
auto write_ptr = node.CopyOnWrite();
write_ptr->indices = indices;
write_ptr->buffer = entry.remap_to;
}
return node;
}
Stmt VisitStmt_(const AttrStmtNode* op) final {
if (op->node->IsInstance<tir::BufferNode>()) {
// Visit body before checking internal_buf_map_, because we
// don't know if the BufferNode needs to be changed until we
// look in the body for a BufferRealizeNode with different
// extents.
Stmt body = this->VisitStmt(op->body);
Buffer buffer = Downcast<tir::Buffer>(op->node);
auto it = buf_map_.find(buffer);
if (it != buf_map_.end()) {
buffer = it->second.remap_to;
return AttrStmt(it->second.remap_to, op->attr_key, op->value, body);
}
return AttrStmt(buffer, op->attr_key, op->value, body);
} else if (op->attr_key == attr::buffer_bind_scope) {
return HandleBufferBindScope(op);
}
return StmtExprMutator::VisitStmt_(op);
}
private:
// Any buffers that give views into a resized buffer should be
// updated, both to refer to the resized buffer and to have the view
// window updated. For example, suppose B1 is a 1-D buffer of size
// 100 which is only realized on the range (10,50), and buffer V1 is
// a view into B1[25:35]. When B1 is replaced with B2, a buffer of
// size 40 realized on the range (0,40), V1 must be replaced to be a
// view into B2[15:25].
Stmt HandleBufferBindScope(const AttrStmtNode* op) {
Array<ObjectRef> arr = Downcast<Array<ObjectRef>>(op->node);
ICHECK_EQ(arr.size(), 2U);
Buffer buffer = Downcast<Buffer>(arr[0]);
ICHECK(buffer.defined());
Buffer target = Downcast<Buffer>(arr[1]);
ICHECK(target.defined());
auto it = buf_map_.find(target);
ICHECK(it != buf_map_.end()) << "attr::buffer_bind_scope target " << target << " not in scope.";
const BufferEntry& target_remap = it->second;
ICHECK(target_remap.in_scope) << "Cannot bind " << buffer->name
<< " to the out-of-scope buffer " << target_remap.remap_to->name;
Call tuple = Downcast<Call>(op->value);
ICHECK(tuple.defined() && tuple->op.same_as(builtin::tvm_tuple()));
Array<PrimExpr> new_tuple_args;
Array<PrimExpr> realized_begins;
Array<PrimExpr> view_shape;
ICHECK_EQ(tuple->args.size(), target_remap.index_offsets.size() * 2)
<< "attr::buffer_bind_scope to define " << buffer << " as a view into " << target
<< " does match dimensionality of " << target;
for (size_t i = 0; i < target_remap.index_offsets.size(); i++) {
PrimExpr parent_begin = tuple->args[2 * i];
PrimExpr view_extent = tuple->args[2 * i + 1];
// Offset the begin of the buffer view by the offset of the target buffer.
new_tuple_args.push_back(parent_begin - target_remap.index_offsets[i]);
// Keep the extent of the buffer view the same.
new_tuple_args.push_back(view_extent);
// Use the extent of the buffer view to define the buffer view's shape.
view_shape.push_back(view_extent);
// Within the buffer view, indices start at 0.
realized_begins.push_back(0);
}
// If a view is binding to a buffer of a higher dimensionality,
// then the leading dimensions should be padded out with shape of
// 1.
ICHECK_GE(view_shape.size(), buffer->shape.size())
<< "Cannot bind " << buffer << " to a shape of lower dimension.";
if (view_shape.size() > buffer->shape.size()) {
size_t diff = view_shape.size() - buffer->shape.size();
Array<PrimExpr> padded_shape;
for (size_t i = 0; i < diff; i++) {
padded_shape.push_back(1);
}
for (auto dim : buffer->shape) {
padded_shape.push_back(dim);
}
view_shape = std::move(padded_shape);
}
// If a buffer has strides defined, and is being remapped into a
// shape with additional dimensions, then define dummy values for
// the strides.
Array<PrimExpr> realized_strides = buffer->strides;
if ((realized_strides.size() > 0) && (realized_strides.size() != view_shape.size())) {
ICHECK_GE(view_shape.size(), realized_strides.size())
<< "Cannot bind the strides of " << buffer << " to a shape of lower dimension";
size_t diff = view_shape.size() - buffer->strides.size();
Array<PrimExpr> updated_strides;
for (size_t i = 0; i < diff; i++) {
updated_strides.push_back(Var("stride", buffer->shape[0].dtype()));
}
for (auto stride : buffer->strides) {
updated_strides.push_back(stride);
}
realized_strides = updated_strides;
}
Buffer key = buffer;
auto write_ptr = buffer.CopyOnWrite();
write_ptr->shape = view_shape;
write_ptr->strides = realized_strides;
{
BufferEntry remap;
remap.index_offsets = realized_begins;
remap.remap_to = buffer;
remap.in_scope = true;
buf_map_[key] = remap;
}
// Define remappings of any Variables referencing Buffer internals
// (e.g. Store/Load nodes). Passing fuzzy_match=true allows the
// remapped buffer to have a number of dimensions.
ArgBinder binder(&var_remap_);
binder.BindBuffer(key, buffer, key->name, true);
Stmt body = this->VisitStmt(op->body);
body = MergeNest(binder.asserts(), body);
body = MergeNest(binder.init_nest(), body);
Stmt stmt = AttrStmt(Array<ObjectRef>{buffer, target_remap.remap_to}, op->attr_key,
Call(tuple->dtype, tuple->op, new_tuple_args, tuple->span), body);
for (const Var& v : binder.defs()) {
var_remap_.erase(v.get());
}
buf_map_.at(key).in_scope = false;
return stmt;
}
std::unordered_map<const VarNode*, PrimExpr> var_remap_;
std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual> extern_buffers_;
struct BufferEntry {
Buffer remap_to;
Array<PrimExpr> index_offsets;
bool in_scope;
};
std::unordered_map<Buffer, BufferEntry, ObjectPtrHash, ObjectPtrEqual> buf_map_;
IRVisitorWithAnalyzer* bound_analyzer_;
};
/* Apply dimension alignment restrictions
*
* Buffers annotated with attr::buffer_dim_align may need to have
* strides defined such that they are no longer in a compact shape.
* After this pass, buffers have stride definitions to include these
* alignment restrictions, and attr::buffer_dim_align annotations have
* been removed.
*/
class BufferStrideLegalize : public StmtExprMutator {
public:
static transform::Pass Pass() {
auto pass_func = [](PrimFunc func, IRModule m, transform::PassContext ctx) {
IRVisitorWithAnalyzer bound_analyzer;
bound_analyzer(func->body);
auto pass = BufferStrideLegalize(func->buffer_map, &bound_analyzer);
auto fptr = func.CopyOnWrite();
fptr->body = pass(std::move(fptr->body));
fptr->buffer_map = pass.UpdatedExternBufferMap();
if (auto map = func->attrs.GetAttr<Map<Buffer, Array<IndexMap>>>("layout_transform_map")) {
func = WithAttr(std::move(func), "layout_transform_map", pass.UpdateIndexMap(map.value()));
}
return func;
};
return transform::CreatePrimFuncPass(pass_func, 0, "tir.BufferStrideLegalize", {});
}
explicit BufferStrideLegalize(const Map<Var, Buffer>& extern_buffer_map,
IRVisitorWithAnalyzer* bound_analyzer)
: bound_analyzer_(bound_analyzer) {
for (auto kv : extern_buffer_map) {
Buffer buf = kv.second;
Buffer with_strides = WithStrides(buf);
{
BufferEntry entry;
entry.remap_to = with_strides;
entry.in_scope = true;
buf_map_[buf] = entry;
}
updated_extern_buffer_map_.Set(kv.first, with_strides);
}
}
Map<Buffer, Array<IndexMap>> UpdateIndexMap(const Map<Buffer, Array<IndexMap>>& orig) {
Map<Buffer, Array<IndexMap>> output;
for (const auto& kv : orig) {
auto it = buf_map_.find(kv.first);
if (it != buf_map_.end()) {
output.Set(it->second.remap_to, kv.second);
} else {
output.Set(kv.first, kv.second);
}
}
return output;
}
Map<Var, Buffer> UpdatedExternBufferMap() const { return updated_extern_buffer_map_; }
Buffer WithStrides(Buffer buf) {
auto cache_key = buf;
auto it = buf_map_.find(cache_key);
if (it != buf_map_.end()) {
const BufferEntry& entry = it->second;
ICHECK(entry.in_scope) << "Cannot annotate an out-of-scope buffer";
return entry.remap_to;
}
Array<PrimExpr> shape = buf->shape;
if (buf->strides.size()) {
ICHECK_EQ(buf->strides.size(), buf->shape.size())
<< "Buffer " << buf << " has inconsistent strides/shape.";
} else if (dim_align_.count(buf) == 0) {
// Keeping this to have matched behavior to previous version.
// There are many parts of the codebase that assume that a
// strided array cannot be compact. For example,
// ArgBinder::BindBuffer and tir.Specialize. To avoid breaking
// these, do not define the strides unless required for a
// non-compact array.
} else if (shape.size() == 0) {
// Can't define the strides for a buffer without a known shape.
} else {
// With everything checked, can now define the updated strides
std::vector<PrimExpr> rstrides;
const std::vector<DimAlignInfo>& avec = dim_align_[buf];
int first_dim = 0;
PrimExpr stride = make_const(shape[first_dim].dtype(), 1);
for (size_t i = shape.size(); i != 0; --i) {
size_t dim = i - 1;
if (dim < avec.size() && avec[dim].align_factor != 0) {
PrimExpr factor = make_const(stride.dtype(), avec[dim].align_factor);
PrimExpr offset = make_const(stride.dtype(), avec[dim].align_offset);
stride = stride + indexmod(factor + offset - indexmod(stride, factor), factor);
stride = bound_analyzer_->Simplify(stride);
}
rstrides.push_back(stride);
stride = stride * shape[dim];
}
buf.CopyOnWrite()->strides = Array<PrimExpr>(rstrides.rbegin(), rstrides.rend());
}
BufferEntry entry;
entry.remap_to = buf;
entry.in_scope = true;
buf_map_[cache_key] = entry;
return buf;
}
Stmt VisitStmt_(const AttrStmtNode* op) final {
if (op->attr_key == attr::buffer_dim_align) {
auto buffer = Downcast<tir::Buffer>(op->node);
const CallNode* tuple = op->value.as<CallNode>();
ICHECK(tuple && tuple->op.same_as(builtin::tvm_tuple()));
auto& vinfo = dim_align_[buffer];
int dim = tuple->args[0].as<IntImmNode>()->value;
if (static_cast<size_t>(dim) >= vinfo.size()) {
vinfo.resize(dim + 1);
}
vinfo[dim].align_factor = tuple->args[1].as<IntImmNode>()->value;
vinfo[dim].align_offset = tuple->args[2].as<IntImmNode>()->value;
return this->VisitStmt(op->body);
} else if (op->attr_key == attr::buffer_bind_scope) {
Array<ObjectRef> arr = Downcast<Array<ObjectRef>>(op->node);
ICHECK_EQ(arr.size(), 2U);
Buffer source = Downcast<Buffer>(arr[0]);
Buffer target_with_strides = WithStrides(Downcast<Buffer>(arr[1]));
Buffer source_with_strides = WithStrides(source);
Stmt body = this->VisitStmt(op->body);
buf_map_[source].in_scope = false;
return AttrStmt(Array<ObjectRef>{source_with_strides, target_with_strides}, op->attr_key,
op->value, body, op->span);
} else {
return StmtExprMutator::VisitStmt_(op);
}
}
// AllocateNodes may be present from tvm.tir.ir_builder. This can
// be simplified in the future by having AllocateNode hold a buffer,
// rather than a buffer_var.
Stmt VisitStmt_(const AllocateNode* op) final {
buffer_var_defines_.insert(op->buffer_var.get());
return StmtExprMutator::VisitStmt_(op);
}
Stmt VisitStmt_(const AllocateConstNode* op) final {
buffer_var_defines_.insert(op->buffer_var.get());
return StmtExprMutator::VisitStmt_(op);
}
Stmt VisitStmt_(const LetStmtNode* op) final {
if (op->var.dtype().is_handle()) {
buffer_var_defines_.insert(op->var.get());
}
return StmtExprMutator::VisitStmt_(op);
}
PrimExpr VisitExpr_(const LetNode* op) final {
if (op->var.dtype().is_handle()) {
buffer_var_defines_.insert(op->var.get());
}
return StmtExprMutator::VisitExpr_(op);
}
Stmt VisitStmt_(const BufferRealizeNode* op) final {
Buffer key = op->buffer;
Buffer with_strides = WithStrides(op->buffer);
Stmt stmt = StmtExprMutator::VisitStmt_(op);
buf_map_[key].in_scope = false;
op = stmt.as<BufferRealizeNode>();
ICHECK(op);
return BufferRealize(with_strides, op->bounds, op->condition, op->body, op->span);
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
auto node = Downcast<BufferStore>(StmtExprMutator::VisitStmt_(op));
return VisitBufferAccess(std::move(node));
}
PrimExpr VisitExpr_(const BufferLoadNode* op) final {
auto node = Downcast<BufferLoad>(StmtExprMutator::VisitExpr_(op));
return VisitBufferAccess(std::move(node));
}
template <typename Node>
Node VisitBufferAccess(Node node) {
auto it = buf_map_.find(node->buffer);
ICHECK(it == buf_map_.end() || it->second.in_scope)
<< "Cannot access a buffer " << node->buffer->name << ", out of scope";
auto with_strides = WithStrides(node->buffer);
if (!with_strides.same_as(node->buffer)) {
node.CopyOnWrite()->buffer = with_strides;
}
return node;
}
private:
Map<Var, Buffer> updated_extern_buffer_map_;
struct DimAlignInfo {
int align_factor{0};
int align_offset{0};
};
// Dimension alignment
std::unordered_map<Buffer, std::vector<DimAlignInfo>, ObjectPtrHash, ObjectPtrEqual> dim_align_;
struct BufferEntry {
Buffer remap_to;
bool in_scope;
};
std::unordered_map<Buffer, BufferEntry, ObjectPtrHash, ObjectPtrEqual> buf_map_;
// Set of vars that have occurred in an AllocateNode, but haven't
// yet occurred in a BufferLoad/BufferStore.
std::unordered_set<const VarNode*> buffer_var_defines_;
IRVisitorWithAnalyzer* bound_analyzer_;
};
/* Use the scope of IterVar to determine storage scope.
*
* For buffers that do not have an explicit storage scope defined, a
* reasonable storage scope may be defined based on the thread scope
* that contains the buffer's allocation. All other buffers without a
* scope are assigned to global scope.
*/
class ThreadScopePropagate : public StmtExprMutator {
public:
static transform::Pass Pass() {
auto pass_func = [](PrimFunc func, IRModule m, transform::PassContext ctx) {
auto pass = ThreadScopePropagate(func->buffer_map);
auto fptr = func.CopyOnWrite();
fptr->body = pass(std::move(fptr->body));
if (auto map = func->attrs.GetAttr<Map<Buffer, Array<IndexMap>>>("layout_transform_map")) {
func = WithAttr(std::move(func), "layout_transform_map", pass.UpdateIndexMap(map.value()));
}
return func;
};
return transform::CreatePrimFuncPass(pass_func, 0, "tir.ThreadScopePropagate", {});
}
explicit ThreadScopePropagate(const Map<Var, Buffer>& extern_buffer_map) {
// External buffers shouldn't be overwritten, even if they have a
// BufferRealizeNode.
for (auto kv : extern_buffer_map) {
external_buffers_.insert(kv.second);
}
}
Map<Buffer, Array<IndexMap>> UpdateIndexMap(const Map<Buffer, Array<IndexMap>>& orig) {
Map<Buffer, Array<IndexMap>> output;
for (const auto& kv : orig) {
auto it = buf_remap_.find(kv.first->data);
if (it != buf_remap_.end()) {
output.Set(it->second, kv.second);
} else {
output.Set(kv.first, kv.second);
}
}
return output;
}
PrimExpr VisitExpr_(const VarNode* op) final {
auto it = buf_remap_.find(GetRef<Var>(op));
if (it != buf_remap_.end()) {
return it->second->data;
} else {
return GetRef<PrimExpr>(op);
}
}
Stmt VisitStmt_(const AttrStmtNode* op) final {
ICHECK_NE(op->attr_key, attr::buffer_dim_align)
<< "StorageFlattener assumes that all buffers have accurate strides, "
<< "and all buffer_dim_align annotations are removed. "
<< "Please run BufferStrideLegalize first.";
if (op->attr_key == attr::thread_extent) {
IterVar iv = Downcast<IterVar>(op->node);
ThreadScope ts = ThreadScope::Create(iv->thread_tag);
curr_thread_scope_.push_back(ts);
Stmt stmt = StmtExprMutator::VisitStmt_(op);
curr_thread_scope_.pop_back();
return stmt;
} else if (op->attr_key == attr::buffer_bind_scope) {
return HandleBufferBindScope(op);
} else {
return StmtExprMutator::VisitStmt_(op);
}
}
Stmt VisitStmt_(const BufferRealizeNode* op) final {
Var old_var = op->buffer->data;
// Don't remap buffers that already have an explicit scope,
// or external buffers.
std::string str_scope = GetPtrStorageScope(old_var);
if ((str_scope.length() > 0) || external_buffers_.count(op->buffer)) {
return StmtExprMutator::VisitStmt_(op);
}
ICHECK_EQ(buf_remap_.count(old_var), 0)
<< "Buffer var " << op->buffer->data << " appears in multiple BufferRealize nodes";
StorageScope skey;
if (curr_thread_scope_.size() == 0) {
skey.rank = StorageRank::kGlobal;
} else {
skey.rank = runtime::DefaultStorageRank(curr_thread_scope_.back().rank);
}
auto ptr_type = old_var->type_annotation.as<PointerTypeNode>();
ICHECK(ptr_type);
Var new_var(old_var->name_hint, PointerType(ptr_type->element_type, skey.to_string()),
old_var->span);
Buffer buf = op->buffer;
buf.CopyOnWrite()->data = new_var;
buf_remap_[old_var] = buf;
Stmt body = this->VisitStmt(op->body);
return BufferRealize(buf, op->bounds, op->condition, body, op->span);
}
PrimExpr VisitExpr_(const BufferLoadNode* op) final {
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<BufferLoadNode>();
ICHECK(op);
auto it = buf_remap_.find(op->buffer->data);
if (it != buf_remap_.end()) {
return BufferLoad(it->second, op->indices, op->span);
} else {
return expr;
}
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
Stmt stmt = StmtExprMutator::VisitStmt_(op);
op = stmt.as<BufferStoreNode>();
ICHECK(op);
auto it = buf_remap_.find(op->buffer->data);
if (it != buf_remap_.end()) {
return BufferStore(it->second, op->value, op->indices, op->span);
} else {
return stmt;
}
}
private:
// If the rewritten buffers are part of a buffer_bind_scope, either
// as the buffer view or as the buffer being viewed, then the
// buffer_bind_scope must be rewritten to refer to the updated
// buffers.
Stmt HandleBufferBindScope(const AttrStmtNode* op) {
Array<ObjectRef> arr = Downcast<Array<ObjectRef>>(op->node);
ICHECK_EQ(arr.size(), 2U);
Buffer buffer = Downcast<Buffer>(arr[0]);
ICHECK(buffer.defined());
Buffer target = Downcast<Buffer>(arr[1]);
ICHECK(target.defined());
bool needs_rewrite = false;
{
auto it = buf_remap_.find(buffer->data);
if (it != buf_remap_.end()) {
needs_rewrite = true;
buffer = it->second;
}
}
{
auto it = buf_remap_.find(target->data);
if (it != buf_remap_.end()) {
needs_rewrite = true;
target = it->second;
}
}
if (needs_rewrite) {
Stmt body = this->VisitStmt(op->body);
return AttrStmt(Array<ObjectRef>{buffer, target}, op->attr_key, op->value, body);
} else {
return StmtExprMutator::VisitStmt_(op);
}
}
std::unordered_map<Var, Buffer, ObjectPtrHash, ObjectPtrEqual> buf_remap_;
std::unordered_set<Buffer, ObjectPtrHash, ObjectPtrEqual> external_buffers_;
// The current thread scope.
std::vector<ThreadScope> curr_thread_scope_;
};
/* Map buffer binds to their source buffer
*
* Buffers defined using an attr::buffer_bind_scope annotation are
* views into some linked buffer, potentially into some restricted
* subregion of that buffer. This pass identifies such buffers, then
* rewrites all access of the bound buffers to be access into the
* linked buffer.
*/
class BufferBindUnwrapper : public StmtExprMutator {
public:
static transform::Pass Pass() {
auto pass_func = [](PrimFunc func, IRModule m, transform::PassContext ctx) {
IRVisitorWithAnalyzer bound_analyzer;
bound_analyzer(func->body);
auto pass = BufferBindUnwrapper(func->buffer_map, &bound_analyzer);
auto fptr = func.CopyOnWrite();
fptr->body = pass(std::move(fptr->body));
return func;
};
return transform::CreatePrimFuncPass(pass_func, 0, "tir.BufferBindUnwrapper", {});
}
explicit BufferBindUnwrapper(const Map<Var, Buffer>& extern_buffer_map,
IRVisitorWithAnalyzer* bound_analyzer)
: bound_analyzer_(bound_analyzer) {
for (auto kv : extern_buffer_map) {
BufferEntry e;
e.buffer = kv.second;
e.external = true;
var_to_buffer_[kv.second->data.get()] = kv.second;
buf_map_[kv.second.get()] = std::move(e);
}
}
Map<Buffer, Array<IndexMap>> UpdateIndexMap(const Map<Buffer, Array<IndexMap>>& orig) {
Map<Buffer, Array<IndexMap>> output;
for (const auto& kv : orig) {
const BufferEntry& e = GetBufferEntry(kv.first);
if (e.remap) {
output.Set(e.remap->target, kv.second);
} else {
output.Set(kv.first, kv.second);
}
}
return output;
}
Stmt VisitStmt_(const AttrStmtNode* op) final {
ICHECK_NE(op->attr_key, attr::buffer_dim_align)
<< "BufferBindUnwrapper assumes that all buffers have accurate strides, "
<< "and all buffer_dim_align annotations are removed. "
<< "Please run BufferStrideLegalize first.";
if (op->attr_key == attr::buffer_bind_scope) {
return HandleBufferBindScope(op);
} else {
return StmtExprMutator::VisitStmt_(op);
}
}
PrimExpr VisitExpr_(const VarNode* op) final {
ICHECK(!illegal_vars_.count(op)) << "Variable " << op->name_hint << " is not well defined. "
<< "(e.g. use of buffer.elem_offset for a non-flat buffer)";
auto it = var_remap_.find(op);
if (it != var_remap_.end()) {
return it->second;
} else {
return GetRef<PrimExpr>(op);
}
}
Array<PrimExpr> remap_indices(Array<PrimExpr> indices, Array<PrimExpr> begins,
Array<PrimExpr> extents) {
ICHECK_EQ(begins.size(), extents.size());
if (begins.size() == 0) {
return indices;
}
ICHECK_EQ(begins.size(), indices.size());
Array<PrimExpr> out;
for (size_t i = 0; i < begins.size(); i++) {
out.push_back(begins[i] + indices[i]);
}
return out;
}
Array<Range> remap_bounds(Array<Range> bounds, Array<PrimExpr> begins, Array<PrimExpr> extents) {
ICHECK_EQ(begins.size(), extents.size());
if (begins.size() == 0) {
return bounds;
}
ICHECK_EQ(begins.size(), bounds.size());
Array<Range> out;
for (size_t i = 0; i < begins.size(); i++) {
out.push_back(Range::FromMinExtent(bounds[i]->min + begins[i], bounds[i]->extent));
}
return out;
}
// AllocateNodes may be present from tvm.tir.ir_builder. This can
// be simplified in the future by having AllocateNode hold a buffer,
// rather than a buffer_var.
Stmt VisitStmt_(const AllocateNode* op) final {
buffer_var_defines_.insert(op->buffer_var.get());
return StmtExprMutator::VisitStmt_(op);
}
Stmt VisitStmt_(const AllocateConstNode* op) final {
buffer_var_defines_.insert(op->buffer_var.get());
return StmtExprMutator::VisitStmt_(op);
}
Stmt VisitStmt_(const LetStmtNode* op) final {
if (op->var.dtype().is_handle()) {
buffer_var_defines_.insert(op->var.get());
}
return StmtExprMutator::VisitStmt_(op);
}
PrimExpr VisitExpr_(const LetNode* op) final {
if (op->var.dtype().is_handle()) {
buffer_var_defines_.insert(op->var.get());
}
return StmtExprMutator::VisitExpr_(op);
}
PrimExpr VisitExpr_(const BufferLoadNode* op) final {
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<BufferLoadNode>();
const BufferEntry& e = GetBufferEntry(op->buffer);
if (e.remap) {
return BufferLoad(e.remap->target,
remap_indices(op->indices, e.remap->begins, e.remap->extents), op->span);
} else {
return expr;
}
}
Stmt VisitStmt_(const BufferStoreNode* op) final {
Stmt stmt = StmtExprMutator::VisitStmt_(op);
op = stmt.as<BufferStoreNode>();
const BufferEntry& e = GetBufferEntry(op->buffer);
if (e.remap) {
return BufferStore(e.remap->target, op->value,
remap_indices(op->indices, e.remap->begins, e.remap->extents), op->span);
} else {
return stmt;
}
}
Stmt VisitStmt_(const BufferRealizeNode* op) final {
const auto& key = op->buffer.get();
bool is_external = false;
if (buf_map_.count(key)) {
ICHECK(buf_map_.at(key).external)
<< "BufferRealize node for internal buffer " << op->buffer << " occurred multiple times.";
is_external = true;
} else {
BufferEntry e;
e.bounds = op->bounds;
e.buffer = op->buffer;
var_to_buffer_[op->buffer->data.get()] = op->buffer;
buf_map_[key] = std::move(e);
}
Stmt stmt = StmtExprMutator::VisitStmt_(op);
if (is_external) {
buf_map_[key].in_scope = false;
}
return stmt;
}
Stmt VisitStmt_(const PrefetchNode* op) final {
Stmt stmt = StmtExprMutator::VisitStmt_(op);
op = stmt.as<PrefetchNode>();
ICHECK(op != nullptr);
const BufferEntry& e = GetBufferEntry(op->buffer);
ICHECK(e.in_scope) << "Read a buffer that is already out of scope";
ICHECK_EQ(e.buffer->shape.size(), op->bounds.size())
<< "Prefetch dim should be the same as buffer dim";
if (e.remap) {