forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAffineOps.cpp
More file actions
4573 lines (4037 loc) · 184 KB
/
Copy pathAffineOps.cpp
File metadata and controls
4573 lines (4037 loc) · 184 KB
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
//===- AffineOps.cpp - MLIR Affine Operations -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Interfaces/ShapedOpInterfaces.h"
#include "mlir/Support/MathExtras.h"
#include "mlir/Transforms/InliningUtils.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVectorExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#include <numeric>
#include <optional>
using namespace mlir;
using namespace mlir::affine;
#define DEBUG_TYPE "affine-ops"
#include "mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc"
/// A utility function to check if a value is defined at the top level of
/// `region` or is an argument of `region`. A value of index type defined at the
/// top level of a `AffineScope` region is always a valid symbol for all
/// uses in that region.
bool mlir::affine::isTopLevelValue(Value value, Region *region) {
if (auto arg = llvm::dyn_cast<BlockArgument>(value))
return arg.getParentRegion() == region;
return value.getDefiningOp()->getParentRegion() == region;
}
/// Checks if `value` known to be a legal affine dimension or symbol in `src`
/// region remains legal if the operation that uses it is inlined into `dest`
/// with the given value mapping. `legalityCheck` is either `isValidDim` or
/// `isValidSymbol`, depending on the value being required to remain a valid
/// dimension or symbol.
static bool
remainsLegalAfterInline(Value value, Region *src, Region *dest,
const IRMapping &mapping,
function_ref<bool(Value, Region *)> legalityCheck) {
// If the value is a valid dimension for any other reason than being
// a top-level value, it will remain valid: constants get inlined
// with the function, transitive affine applies also get inlined and
// will be checked themselves, etc.
if (!isTopLevelValue(value, src))
return true;
// If it's a top-level value because it's a block operand, i.e. a
// function argument, check whether the value replacing it after
// inlining is a valid dimension in the new region.
if (llvm::isa<BlockArgument>(value))
return legalityCheck(mapping.lookup(value), dest);
// If it's a top-level value because it's defined in the region,
// it can only be inlined if the defining op is a constant or a
// `dim`, which can appear anywhere and be valid, since the defining
// op won't be top-level anymore after inlining.
Attribute operandCst;
bool isDimLikeOp = isa<ShapedDimOpInterface>(value.getDefiningOp());
return matchPattern(value.getDefiningOp(), m_Constant(&operandCst)) ||
isDimLikeOp;
}
/// Checks if all values known to be legal affine dimensions or symbols in `src`
/// remain so if their respective users are inlined into `dest`.
static bool
remainsLegalAfterInline(ValueRange values, Region *src, Region *dest,
const IRMapping &mapping,
function_ref<bool(Value, Region *)> legalityCheck) {
return llvm::all_of(values, [&](Value v) {
return remainsLegalAfterInline(v, src, dest, mapping, legalityCheck);
});
}
/// Checks if an affine read or write operation remains legal after inlining
/// from `src` to `dest`.
template <typename OpTy>
static bool remainsLegalAfterInline(OpTy op, Region *src, Region *dest,
const IRMapping &mapping) {
static_assert(llvm::is_one_of<OpTy, AffineReadOpInterface,
AffineWriteOpInterface>::value,
"only ops with affine read/write interface are supported");
AffineMap map = op.getAffineMap();
ValueRange dimOperands = op.getMapOperands().take_front(map.getNumDims());
ValueRange symbolOperands =
op.getMapOperands().take_back(map.getNumSymbols());
if (!remainsLegalAfterInline(
dimOperands, src, dest, mapping,
static_cast<bool (*)(Value, Region *)>(isValidDim)))
return false;
if (!remainsLegalAfterInline(
symbolOperands, src, dest, mapping,
static_cast<bool (*)(Value, Region *)>(isValidSymbol)))
return false;
return true;
}
/// Checks if an affine apply operation remains legal after inlining from `src`
/// to `dest`.
// Use "unused attribute" marker to silence clang-tidy warning stemming from
// the inability to see through "llvm::TypeSwitch".
template <>
bool LLVM_ATTRIBUTE_UNUSED remainsLegalAfterInline(AffineApplyOp op,
Region *src, Region *dest,
const IRMapping &mapping) {
// If it's a valid dimension, we need to check that it remains so.
if (isValidDim(op.getResult(), src))
return remainsLegalAfterInline(
op.getMapOperands(), src, dest, mapping,
static_cast<bool (*)(Value, Region *)>(isValidDim));
// Otherwise it must be a valid symbol, check that it remains so.
return remainsLegalAfterInline(
op.getMapOperands(), src, dest, mapping,
static_cast<bool (*)(Value, Region *)>(isValidSymbol));
}
//===----------------------------------------------------------------------===//
// AffineDialect Interfaces
//===----------------------------------------------------------------------===//
namespace {
/// This class defines the interface for handling inlining with affine
/// operations.
struct AffineInlinerInterface : public DialectInlinerInterface {
using DialectInlinerInterface::DialectInlinerInterface;
//===--------------------------------------------------------------------===//
// Analysis Hooks
//===--------------------------------------------------------------------===//
/// Returns true if the given region 'src' can be inlined into the region
/// 'dest' that is attached to an operation registered to the current dialect.
/// 'wouldBeCloned' is set if the region is cloned into its new location
/// rather than moved, indicating there may be other users.
bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
IRMapping &valueMapping) const final {
// We can inline into affine loops and conditionals if this doesn't break
// affine value categorization rules.
Operation *destOp = dest->getParentOp();
if (!isa<AffineParallelOp, AffineForOp, AffineIfOp>(destOp))
return false;
// Multi-block regions cannot be inlined into affine constructs, all of
// which require single-block regions.
if (!llvm::hasSingleElement(*src))
return false;
// Side-effecting operations that the affine dialect cannot understand
// should not be inlined.
Block &srcBlock = src->front();
for (Operation &op : srcBlock) {
// Ops with no side effects are fine,
if (auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
if (iface.hasNoEffect())
continue;
}
// Assuming the inlined region is valid, we only need to check if the
// inlining would change it.
bool remainsValid =
llvm::TypeSwitch<Operation *, bool>(&op)
.Case<AffineApplyOp, AffineReadOpInterface,
AffineWriteOpInterface>([&](auto op) {
return remainsLegalAfterInline(op, src, dest, valueMapping);
})
.Default([](Operation *) {
// Conservatively disallow inlining ops we cannot reason about.
return false;
});
if (!remainsValid)
return false;
}
return true;
}
/// Returns true if the given operation 'op', that is registered to this
/// dialect, can be inlined into the given region, false otherwise.
bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
IRMapping &valueMapping) const final {
// Always allow inlining affine operations into a region that is marked as
// affine scope, or into affine loops and conditionals. There are some edge
// cases when inlining *into* affine structures, but that is handled in the
// other 'isLegalToInline' hook above.
Operation *parentOp = region->getParentOp();
return parentOp->hasTrait<OpTrait::AffineScope>() ||
isa<AffineForOp, AffineParallelOp, AffineIfOp>(parentOp);
}
/// Affine regions should be analyzed recursively.
bool shouldAnalyzeRecursively(Operation *op) const final { return true; }
};
} // namespace
//===----------------------------------------------------------------------===//
// AffineDialect
//===----------------------------------------------------------------------===//
void AffineDialect::initialize() {
addOperations<AffineDmaStartOp, AffineDmaWaitOp,
#define GET_OP_LIST
#include "mlir/Dialect/Affine/IR/AffineOps.cpp.inc"
>();
addInterfaces<AffineInlinerInterface>();
}
/// Materialize a single constant operation from a given attribute value with
/// the desired resultant type.
Operation *AffineDialect::materializeConstant(OpBuilder &builder,
Attribute value, Type type,
Location loc) {
return arith::ConstantOp::materialize(builder, value, type, loc);
}
/// A utility function to check if a value is defined at the top level of an
/// op with trait `AffineScope`. If the value is defined in an unlinked region,
/// conservatively assume it is not top-level. A value of index type defined at
/// the top level is always a valid symbol.
bool mlir::affine::isTopLevelValue(Value value) {
if (auto arg = llvm::dyn_cast<BlockArgument>(value)) {
// The block owning the argument may be unlinked, e.g. when the surrounding
// region has not yet been attached to an Op, at which point the parent Op
// is null.
Operation *parentOp = arg.getOwner()->getParentOp();
return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
}
// The defining Op may live in an unlinked block so its parent Op may be null.
Operation *parentOp = value.getDefiningOp()->getParentOp();
return parentOp && parentOp->hasTrait<OpTrait::AffineScope>();
}
/// Returns the closest region enclosing `op` that is held by an operation with
/// trait `AffineScope`; `nullptr` if there is no such region.
Region *mlir::affine::getAffineScope(Operation *op) {
auto *curOp = op;
while (auto *parentOp = curOp->getParentOp()) {
if (parentOp->hasTrait<OpTrait::AffineScope>())
return curOp->getParentRegion();
curOp = parentOp;
}
return nullptr;
}
// A Value can be used as a dimension id iff it meets one of the following
// conditions:
// *) It is valid as a symbol.
// *) It is an induction variable.
// *) It is the result of affine apply operation with dimension id arguments.
bool mlir::affine::isValidDim(Value value) {
// The value must be an index type.
if (!value.getType().isIndex())
return false;
if (auto *defOp = value.getDefiningOp())
return isValidDim(value, getAffineScope(defOp));
// This value has to be a block argument for an op that has the
// `AffineScope` trait or for an affine.for or affine.parallel.
auto *parentOp = llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
return parentOp && (parentOp->hasTrait<OpTrait::AffineScope>() ||
isa<AffineForOp, AffineParallelOp>(parentOp));
}
// Value can be used as a dimension id iff it meets one of the following
// conditions:
// *) It is valid as a symbol.
// *) It is an induction variable.
// *) It is the result of an affine apply operation with dimension id operands.
bool mlir::affine::isValidDim(Value value, Region *region) {
// The value must be an index type.
if (!value.getType().isIndex())
return false;
// All valid symbols are okay.
if (isValidSymbol(value, region))
return true;
auto *op = value.getDefiningOp();
if (!op) {
// This value has to be a block argument for an affine.for or an
// affine.parallel.
auto *parentOp = llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
return isa<AffineForOp, AffineParallelOp>(parentOp);
}
// Affine apply operation is ok if all of its operands are ok.
if (auto applyOp = dyn_cast<AffineApplyOp>(op))
return applyOp.isValidDim(region);
// The dim op is okay if its operand memref/tensor is defined at the top
// level.
if (auto dimOp = dyn_cast<ShapedDimOpInterface>(op))
return isTopLevelValue(dimOp.getShapedValue());
return false;
}
/// Returns true if the 'index' dimension of the `memref` defined by
/// `memrefDefOp` is a statically shaped one or defined using a valid symbol
/// for `region`.
template <typename AnyMemRefDefOp>
static bool isMemRefSizeValidSymbol(AnyMemRefDefOp memrefDefOp, unsigned index,
Region *region) {
auto memRefType = memrefDefOp.getType();
// Statically shaped.
if (!memRefType.isDynamicDim(index))
return true;
// Get the position of the dimension among dynamic dimensions;
unsigned dynamicDimPos = memRefType.getDynamicDimIndex(index);
return isValidSymbol(*(memrefDefOp.getDynamicSizes().begin() + dynamicDimPos),
region);
}
/// Returns true if the result of the dim op is a valid symbol for `region`.
static bool isDimOpValidSymbol(ShapedDimOpInterface dimOp, Region *region) {
// The dim op is okay if its source is defined at the top level.
if (isTopLevelValue(dimOp.getShapedValue()))
return true;
// Conservatively handle remaining BlockArguments as non-valid symbols.
// E.g. scf.for iterArgs.
if (llvm::isa<BlockArgument>(dimOp.getShapedValue()))
return false;
// The dim op is also okay if its operand memref is a view/subview whose
// corresponding size is a valid symbol.
std::optional<int64_t> index = getConstantIntValue(dimOp.getDimension());
// Be conservative if we can't understand the dimension.
if (!index.has_value())
return false;
int64_t i = index.value();
return TypeSwitch<Operation *, bool>(dimOp.getShapedValue().getDefiningOp())
.Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
[&](auto op) { return isMemRefSizeValidSymbol(op, i, region); })
.Default([](Operation *) { return false; });
}
// A value can be used as a symbol (at all its use sites) iff it meets one of
// the following conditions:
// *) It is a constant.
// *) Its defining op or block arg appearance is immediately enclosed by an op
// with `AffineScope` trait.
// *) It is the result of an affine.apply operation with symbol operands.
// *) It is a result of the dim op on a memref whose corresponding size is a
// valid symbol.
bool mlir::affine::isValidSymbol(Value value) {
if (!value)
return false;
// The value must be an index type.
if (!value.getType().isIndex())
return false;
// Check that the value is a top level value.
if (isTopLevelValue(value))
return true;
if (auto *defOp = value.getDefiningOp())
return isValidSymbol(value, getAffineScope(defOp));
return false;
}
/// A value can be used as a symbol for `region` iff it meets one of the
/// following conditions:
/// *) It is a constant.
/// *) It is the result of an affine apply operation with symbol arguments.
/// *) It is a result of the dim op on a memref whose corresponding size is
/// a valid symbol.
/// *) It is defined at the top level of 'region' or is its argument.
/// *) It dominates `region`'s parent op.
/// If `region` is null, conservatively assume the symbol definition scope does
/// not exist and only accept the values that would be symbols regardless of
/// the surrounding region structure, i.e. the first three cases above.
bool mlir::affine::isValidSymbol(Value value, Region *region) {
// The value must be an index type.
if (!value.getType().isIndex())
return false;
// A top-level value is a valid symbol.
if (region && ::isTopLevelValue(value, region))
return true;
auto *defOp = value.getDefiningOp();
if (!defOp) {
// A block argument that is not a top-level value is a valid symbol if it
// dominates region's parent op.
Operation *regionOp = region ? region->getParentOp() : nullptr;
if (regionOp && !regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
if (auto *parentOpRegion = region->getParentOp()->getParentRegion())
return isValidSymbol(value, parentOpRegion);
return false;
}
// Constant operation is ok.
Attribute operandCst;
if (matchPattern(defOp, m_Constant(&operandCst)))
return true;
// Affine apply operation is ok if all of its operands are ok.
if (auto applyOp = dyn_cast<AffineApplyOp>(defOp))
return applyOp.isValidSymbol(region);
// Dim op results could be valid symbols at any level.
if (auto dimOp = dyn_cast<ShapedDimOpInterface>(defOp))
return isDimOpValidSymbol(dimOp, region);
// Check for values dominating `region`'s parent op.
Operation *regionOp = region ? region->getParentOp() : nullptr;
if (regionOp && !regionOp->hasTrait<OpTrait::IsIsolatedFromAbove>())
if (auto *parentRegion = region->getParentOp()->getParentRegion())
return isValidSymbol(value, parentRegion);
return false;
}
// Returns true if 'value' is a valid index to an affine operation (e.g.
// affine.load, affine.store, affine.dma_start, affine.dma_wait) where
// `region` provides the polyhedral symbol scope. Returns false otherwise.
static bool isValidAffineIndexOperand(Value value, Region *region) {
return isValidDim(value, region) || isValidSymbol(value, region);
}
/// Prints dimension and symbol list.
static void printDimAndSymbolList(Operation::operand_iterator begin,
Operation::operand_iterator end,
unsigned numDims, OpAsmPrinter &printer) {
OperandRange operands(begin, end);
printer << '(' << operands.take_front(numDims) << ')';
if (operands.size() > numDims)
printer << '[' << operands.drop_front(numDims) << ']';
}
/// Parses dimension and symbol list and returns true if parsing failed.
ParseResult mlir::affine::parseDimAndSymbolList(
OpAsmParser &parser, SmallVectorImpl<Value> &operands, unsigned &numDims) {
SmallVector<OpAsmParser::UnresolvedOperand, 8> opInfos;
if (parser.parseOperandList(opInfos, OpAsmParser::Delimiter::Paren))
return failure();
// Store number of dimensions for validation by caller.
numDims = opInfos.size();
// Parse the optional symbol operands.
auto indexTy = parser.getBuilder().getIndexType();
return failure(parser.parseOperandList(
opInfos, OpAsmParser::Delimiter::OptionalSquare) ||
parser.resolveOperands(opInfos, indexTy, operands));
}
/// Utility function to verify that a set of operands are valid dimension and
/// symbol identifiers. The operands should be laid out such that the dimension
/// operands are before the symbol operands. This function returns failure if
/// there was an invalid operand. An operation is provided to emit any necessary
/// errors.
template <typename OpTy>
static LogicalResult
verifyDimAndSymbolIdentifiers(OpTy &op, Operation::operand_range operands,
unsigned numDims) {
unsigned opIt = 0;
for (auto operand : operands) {
if (opIt++ < numDims) {
if (!isValidDim(operand, getAffineScope(op)))
return op.emitOpError("operand cannot be used as a dimension id");
} else if (!isValidSymbol(operand, getAffineScope(op))) {
return op.emitOpError("operand cannot be used as a symbol");
}
}
return success();
}
//===----------------------------------------------------------------------===//
// AffineApplyOp
//===----------------------------------------------------------------------===//
AffineValueMap AffineApplyOp::getAffineValueMap() {
return AffineValueMap(getAffineMap(), getOperands(), getResult());
}
ParseResult AffineApplyOp::parse(OpAsmParser &parser, OperationState &result) {
auto &builder = parser.getBuilder();
auto indexTy = builder.getIndexType();
AffineMapAttr mapAttr;
unsigned numDims;
if (parser.parseAttribute(mapAttr, "map", result.attributes) ||
parseDimAndSymbolList(parser, result.operands, numDims) ||
parser.parseOptionalAttrDict(result.attributes))
return failure();
auto map = mapAttr.getValue();
if (map.getNumDims() != numDims ||
numDims + map.getNumSymbols() != result.operands.size()) {
return parser.emitError(parser.getNameLoc(),
"dimension or symbol index mismatch");
}
result.types.append(map.getNumResults(), indexTy);
return success();
}
void AffineApplyOp::print(OpAsmPrinter &p) {
p << " " << getMapAttr();
printDimAndSymbolList(operand_begin(), operand_end(),
getAffineMap().getNumDims(), p);
p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{"map"});
}
LogicalResult AffineApplyOp::verify() {
// Check input and output dimensions match.
AffineMap affineMap = getMap();
// Verify that operand count matches affine map dimension and symbol count.
if (getNumOperands() != affineMap.getNumDims() + affineMap.getNumSymbols())
return emitOpError(
"operand count and affine map dimension and symbol count must match");
// Verify that the map only produces one result.
if (affineMap.getNumResults() != 1)
return emitOpError("mapping must produce one value");
return success();
}
// The result of the affine apply operation can be used as a dimension id if all
// its operands are valid dimension ids.
bool AffineApplyOp::isValidDim() {
return llvm::all_of(getOperands(),
[](Value op) { return affine::isValidDim(op); });
}
// The result of the affine apply operation can be used as a dimension id if all
// its operands are valid dimension ids with the parent operation of `region`
// defining the polyhedral scope for symbols.
bool AffineApplyOp::isValidDim(Region *region) {
return llvm::all_of(getOperands(),
[&](Value op) { return ::isValidDim(op, region); });
}
// The result of the affine apply operation can be used as a symbol if all its
// operands are symbols.
bool AffineApplyOp::isValidSymbol() {
return llvm::all_of(getOperands(),
[](Value op) { return affine::isValidSymbol(op); });
}
// The result of the affine apply operation can be used as a symbol in `region`
// if all its operands are symbols in `region`.
bool AffineApplyOp::isValidSymbol(Region *region) {
return llvm::all_of(getOperands(), [&](Value operand) {
return affine::isValidSymbol(operand, region);
});
}
OpFoldResult AffineApplyOp::fold(FoldAdaptor adaptor) {
auto map = getAffineMap();
// Fold dims and symbols to existing values.
auto expr = map.getResult(0);
if (auto dim = expr.dyn_cast<AffineDimExpr>())
return getOperand(dim.getPosition());
if (auto sym = expr.dyn_cast<AffineSymbolExpr>())
return getOperand(map.getNumDims() + sym.getPosition());
// Otherwise, default to folding the map.
SmallVector<Attribute, 1> result;
if (failed(map.constantFold(adaptor.getMapOperands(), result)))
return {};
return result[0];
}
/// Returns the largest known divisor of `e`. Exploits information from the
/// values in `operands`.
static int64_t getLargestKnownDivisor(AffineExpr e, ArrayRef<Value> operands) {
// This method isn't aware of `operands`.
int64_t div = e.getLargestKnownDivisor();
// We now make use of operands for the case `e` is a dim expression.
// TODO: More powerful simplification would have to modify
// getLargestKnownDivisor to take `operands` and exploit that information as
// well for dim/sym expressions, but in that case, getLargestKnownDivisor
// can't be part of the IR library but of the `Analysis` library. The IR
// library can only really depend on simple O(1) checks.
auto dimExpr = e.dyn_cast<AffineDimExpr>();
// If it's not a dim expr, `div` is the best we have.
if (!dimExpr)
return div;
// We simply exploit information from loop IVs.
// We don't need to use mlir::getLargestKnownDivisorOfValue since the other
// desired simplifications are expected to be part of other
// canonicalizations. Also, mlir::getLargestKnownDivisorOfValue is part of the
// LoopAnalysis library.
Value operand = operands[dimExpr.getPosition()];
int64_t operandDivisor = 1;
// TODO: With the right accessors, this can be extended to
// LoopLikeOpInterface.
if (AffineForOp forOp = getForInductionVarOwner(operand)) {
if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() == 0) {
operandDivisor = forOp.getStep();
} else {
uint64_t lbLargestKnownDivisor =
forOp.getLowerBoundMap().getLargestKnownDivisorOfMapExprs();
operandDivisor = std::gcd(lbLargestKnownDivisor, forOp.getStep());
}
}
return operandDivisor;
}
/// Check if `e` is known to be: 0 <= `e` < `k`. Handles the simple cases of `e`
/// being an affine dim expression or a constant.
static bool isNonNegativeBoundedBy(AffineExpr e, ArrayRef<Value> operands,
int64_t k) {
if (auto constExpr = e.dyn_cast<AffineConstantExpr>()) {
int64_t constVal = constExpr.getValue();
return constVal >= 0 && constVal < k;
}
auto dimExpr = e.dyn_cast<AffineDimExpr>();
if (!dimExpr)
return false;
Value operand = operands[dimExpr.getPosition()];
// TODO: With the right accessors, this can be extended to
// LoopLikeOpInterface.
if (AffineForOp forOp = getForInductionVarOwner(operand)) {
if (forOp.hasConstantLowerBound() && forOp.getConstantLowerBound() >= 0 &&
forOp.hasConstantUpperBound() && forOp.getConstantUpperBound() <= k) {
return true;
}
}
// We don't consider other cases like `operand` being defined by a constant or
// an affine.apply op since such cases will already be handled by other
// patterns and propagation of loop IVs or constant would happen.
return false;
}
/// Check if expression `e` is of the form d*e_1 + e_2 where 0 <= e_2 < d.
/// Set `div` to `d`, `quotientTimesDiv` to e_1 and `rem` to e_2 if the
/// expression is in that form.
static bool isQTimesDPlusR(AffineExpr e, ArrayRef<Value> operands, int64_t &div,
AffineExpr "ientTimesDiv, AffineExpr &rem) {
auto bin = e.dyn_cast<AffineBinaryOpExpr>();
if (!bin || bin.getKind() != AffineExprKind::Add)
return false;
AffineExpr llhs = bin.getLHS();
AffineExpr rlhs = bin.getRHS();
div = getLargestKnownDivisor(llhs, operands);
if (isNonNegativeBoundedBy(rlhs, operands, div)) {
quotientTimesDiv = llhs;
rem = rlhs;
return true;
}
div = getLargestKnownDivisor(rlhs, operands);
if (isNonNegativeBoundedBy(llhs, operands, div)) {
quotientTimesDiv = rlhs;
rem = llhs;
return true;
}
return false;
}
/// Gets the constant lower bound on an `iv`.
static std::optional<int64_t> getLowerBound(Value iv) {
AffineForOp forOp = getForInductionVarOwner(iv);
if (forOp && forOp.hasConstantLowerBound())
return forOp.getConstantLowerBound();
return std::nullopt;
}
/// Gets the constant upper bound on an affine.for `iv`.
static std::optional<int64_t> getUpperBound(Value iv) {
AffineForOp forOp = getForInductionVarOwner(iv);
if (!forOp || !forOp.hasConstantUpperBound())
return std::nullopt;
// If its lower bound is also known, we can get a more precise bound
// whenever the step is not one.
if (forOp.hasConstantLowerBound()) {
return forOp.getConstantUpperBound() - 1 -
(forOp.getConstantUpperBound() - forOp.getConstantLowerBound() - 1) %
forOp.getStep();
}
return forOp.getConstantUpperBound() - 1;
}
/// Get a lower or upper (depending on `isUpper`) bound for `expr` while using
/// the constant lower and upper bounds for its inputs provided in
/// `constLowerBounds` and `constUpperBounds`. Return std::nullopt if such a
/// bound can't be computed. This method only handles simple sum of product
/// expressions (w.r.t constant coefficients) so as to not depend on anything
/// heavyweight in `Analysis`. Expressions of the form: c0*d0 + c1*d1 + c2*s0 +
/// ... + c_n are handled. Expressions involving floordiv, ceildiv, mod or
/// semi-affine ones will lead std::nullopt being returned.
static std::optional<int64_t>
getBoundForExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols,
ArrayRef<std::optional<int64_t>> constLowerBounds,
ArrayRef<std::optional<int64_t>> constUpperBounds,
bool isUpper) {
// Handle divs and mods.
if (auto binOpExpr = expr.dyn_cast<AffineBinaryOpExpr>()) {
// If the LHS of a floor or ceil is bounded and the RHS is a constant, we
// can compute an upper bound.
if (binOpExpr.getKind() == AffineExprKind::FloorDiv) {
auto rhsConst = binOpExpr.getRHS().dyn_cast<AffineConstantExpr>();
if (!rhsConst || rhsConst.getValue() < 1)
return std::nullopt;
auto bound = getBoundForExpr(binOpExpr.getLHS(), numDims, numSymbols,
constLowerBounds, constUpperBounds, isUpper);
if (!bound)
return std::nullopt;
return mlir::floorDiv(*bound, rhsConst.getValue());
}
if (binOpExpr.getKind() == AffineExprKind::CeilDiv) {
auto rhsConst = binOpExpr.getRHS().dyn_cast<AffineConstantExpr>();
if (rhsConst && rhsConst.getValue() >= 1) {
auto bound =
getBoundForExpr(binOpExpr.getLHS(), numDims, numSymbols,
constLowerBounds, constUpperBounds, isUpper);
if (!bound)
return std::nullopt;
return mlir::ceilDiv(*bound, rhsConst.getValue());
}
return std::nullopt;
}
if (binOpExpr.getKind() == AffineExprKind::Mod) {
// lhs mod c is always <= c - 1 and non-negative. In addition, if `lhs` is
// bounded such that lb <= lhs <= ub and lb floordiv c == ub floordiv c
// (same "interval"), then lb mod c <= lhs mod c <= ub mod c.
auto rhsConst = binOpExpr.getRHS().dyn_cast<AffineConstantExpr>();
if (rhsConst && rhsConst.getValue() >= 1) {
int64_t rhsConstVal = rhsConst.getValue();
auto lb = getBoundForExpr(binOpExpr.getLHS(), numDims, numSymbols,
constLowerBounds, constUpperBounds,
/*isUpper=*/false);
auto ub = getBoundForExpr(binOpExpr.getLHS(), numDims, numSymbols,
constLowerBounds, constUpperBounds, isUpper);
if (ub && lb &&
floorDiv(*lb, rhsConstVal) == floorDiv(*ub, rhsConstVal))
return isUpper ? mod(*ub, rhsConstVal) : mod(*lb, rhsConstVal);
return isUpper ? rhsConstVal - 1 : 0;
}
}
}
// Flatten the expression.
SimpleAffineExprFlattener flattener(numDims, numSymbols);
flattener.walkPostOrder(expr);
ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
// TODO: Handle local variables. We can get hold of flattener.localExprs and
// get bound on the local expr recursively.
if (flattener.numLocals > 0)
return std::nullopt;
int64_t bound = 0;
// Substitute the constant lower or upper bound for the dimensional or
// symbolic input depending on `isUpper` to determine the bound.
for (unsigned i = 0, e = numDims + numSymbols; i < e; ++i) {
if (flattenedExpr[i] > 0) {
auto &constBound = isUpper ? constUpperBounds[i] : constLowerBounds[i];
if (!constBound)
return std::nullopt;
bound += *constBound * flattenedExpr[i];
} else if (flattenedExpr[i] < 0) {
auto &constBound = isUpper ? constLowerBounds[i] : constUpperBounds[i];
if (!constBound)
return std::nullopt;
bound += *constBound * flattenedExpr[i];
}
}
// Constant term.
bound += flattenedExpr.back();
return bound;
}
/// Determine a constant upper bound for `expr` if one exists while exploiting
/// values in `operands`. Note that the upper bound is an inclusive one. `expr`
/// is guaranteed to be less than or equal to it.
static std::optional<int64_t> getUpperBound(AffineExpr expr, unsigned numDims,
unsigned numSymbols,
ArrayRef<Value> operands) {
// Get the constant lower or upper bounds on the operands.
SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
constLowerBounds.reserve(operands.size());
constUpperBounds.reserve(operands.size());
for (Value operand : operands) {
constLowerBounds.push_back(getLowerBound(operand));
constUpperBounds.push_back(getUpperBound(operand));
}
if (auto constExpr = expr.dyn_cast<AffineConstantExpr>())
return constExpr.getValue();
return getBoundForExpr(expr, numDims, numSymbols, constLowerBounds,
constUpperBounds,
/*isUpper=*/true);
}
/// Determine a constant lower bound for `expr` if one exists while exploiting
/// values in `operands`. Note that the upper bound is an inclusive one. `expr`
/// is guaranteed to be less than or equal to it.
static std::optional<int64_t> getLowerBound(AffineExpr expr, unsigned numDims,
unsigned numSymbols,
ArrayRef<Value> operands) {
// Get the constant lower or upper bounds on the operands.
SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
constLowerBounds.reserve(operands.size());
constUpperBounds.reserve(operands.size());
for (Value operand : operands) {
constLowerBounds.push_back(getLowerBound(operand));
constUpperBounds.push_back(getUpperBound(operand));
}
std::optional<int64_t> lowerBound;
if (auto constExpr = expr.dyn_cast<AffineConstantExpr>()) {
lowerBound = constExpr.getValue();
} else {
lowerBound = getBoundForExpr(expr, numDims, numSymbols, constLowerBounds,
constUpperBounds,
/*isUpper=*/false);
}
return lowerBound;
}
/// Simplify `expr` while exploiting information from the values in `operands`.
static void simplifyExprAndOperands(AffineExpr &expr, unsigned numDims,
unsigned numSymbols,
ArrayRef<Value> operands) {
// We do this only for certain floordiv/mod expressions.
auto binExpr = expr.dyn_cast<AffineBinaryOpExpr>();
if (!binExpr)
return;
// Simplify the child expressions first.
AffineExpr lhs = binExpr.getLHS();
AffineExpr rhs = binExpr.getRHS();
simplifyExprAndOperands(lhs, numDims, numSymbols, operands);
simplifyExprAndOperands(rhs, numDims, numSymbols, operands);
expr = getAffineBinaryOpExpr(binExpr.getKind(), lhs, rhs);
binExpr = expr.dyn_cast<AffineBinaryOpExpr>();
if (!binExpr || (expr.getKind() != AffineExprKind::FloorDiv &&
expr.getKind() != AffineExprKind::CeilDiv &&
expr.getKind() != AffineExprKind::Mod)) {
return;
}
// The `lhs` and `rhs` may be different post construction of simplified expr.
lhs = binExpr.getLHS();
rhs = binExpr.getRHS();
auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
if (!rhsConst)
return;
int64_t rhsConstVal = rhsConst.getValue();
// Undefined exprsessions aren't touched; IR can still be valid with them.
if (rhsConstVal <= 0)
return;
// Exploit constant lower/upper bounds to simplify a floordiv or mod.
MLIRContext *context = expr.getContext();
std::optional<int64_t> lhsLbConst =
getLowerBound(lhs, numDims, numSymbols, operands);
std::optional<int64_t> lhsUbConst =
getUpperBound(lhs, numDims, numSymbols, operands);
if (lhsLbConst && lhsUbConst) {
int64_t lhsLbConstVal = *lhsLbConst;
int64_t lhsUbConstVal = *lhsUbConst;
// lhs floordiv c is a single value lhs is bounded in a range `c` that has
// the same quotient.
if (binExpr.getKind() == AffineExprKind::FloorDiv &&
floorDiv(lhsLbConstVal, rhsConstVal) ==
floorDiv(lhsUbConstVal, rhsConstVal)) {
expr =
getAffineConstantExpr(floorDiv(lhsLbConstVal, rhsConstVal), context);
return;
}
// lhs ceildiv c is a single value if the entire range has the same ceil
// quotient.
if (binExpr.getKind() == AffineExprKind::CeilDiv &&
ceilDiv(lhsLbConstVal, rhsConstVal) ==
ceilDiv(lhsUbConstVal, rhsConstVal)) {
expr =
getAffineConstantExpr(ceilDiv(lhsLbConstVal, rhsConstVal), context);
return;
}
// lhs mod c is lhs if the entire range has quotient 0 w.r.t the rhs.
if (binExpr.getKind() == AffineExprKind::Mod && lhsLbConstVal >= 0 &&
lhsLbConstVal < rhsConstVal && lhsUbConstVal < rhsConstVal) {
expr = lhs;
return;
}
}
// Simplify expressions of the form e = (e_1 + e_2) floordiv c or (e_1 + e_2)
// mod c, where e_1 is a multiple of `k` and 0 <= e_2 < k. In such cases, if
// `c` % `k` == 0, (e_1 + e_2) floordiv c can be simplified to e_1 floordiv c.
// And when k % c == 0, (e_1 + e_2) mod c can be simplified to e_2 mod c.
AffineExpr quotientTimesDiv, rem;
int64_t divisor;
if (isQTimesDPlusR(lhs, operands, divisor, quotientTimesDiv, rem)) {
if (rhsConstVal % divisor == 0 &&
binExpr.getKind() == AffineExprKind::FloorDiv) {
expr = quotientTimesDiv.floorDiv(rhsConst);
} else if (divisor % rhsConstVal == 0 &&
binExpr.getKind() == AffineExprKind::Mod) {
expr = rem % rhsConst;
}
return;
}
// Handle the simple case when the LHS expression can be either upper
// bounded or is a known multiple of RHS constant.
// lhs floordiv c -> 0 if 0 <= lhs < c,
// lhs mod c -> 0 if lhs % c = 0.
if ((isNonNegativeBoundedBy(lhs, operands, rhsConstVal) &&
binExpr.getKind() == AffineExprKind::FloorDiv) ||
(getLargestKnownDivisor(lhs, operands) % rhsConstVal == 0 &&
binExpr.getKind() == AffineExprKind::Mod)) {
expr = getAffineConstantExpr(0, expr.getContext());
}
}
/// Simplify the expressions in `map` while making use of lower or upper bounds
/// of its operands. If `isMax` is true, the map is to be treated as a max of
/// its result expressions, and min otherwise. Eg: min (d0, d1) -> (8, 4 * d0 +
/// d1) can be simplified to (8) if the operands are respectively lower bounded
/// by 2 and 0 (the second expression can't be lower than 8).
static void simplifyMinOrMaxExprWithOperands(AffineMap &map,
ArrayRef<Value> operands,
bool isMax) {
// Can't simplify.
if (operands.empty())
return;
// Get the upper or lower bound on an affine.for op IV using its range.
// Get the constant lower or upper bounds on the operands.
SmallVector<std::optional<int64_t>> constLowerBounds, constUpperBounds;
constLowerBounds.reserve(operands.size());
constUpperBounds.reserve(operands.size());
for (Value operand : operands) {
constLowerBounds.push_back(getLowerBound(operand));
constUpperBounds.push_back(getUpperBound(operand));
}
// We will compute the lower and upper bounds on each of the expressions
// Then, we will check (depending on max or min) as to whether a specific
// bound is redundant by checking if its highest (in case of max) and its
// lowest (in the case of min) value is already lower than (or higher than)
// the lower bound (or upper bound in the case of min) of another bound.
SmallVector<std::optional<int64_t>, 4> lowerBounds, upperBounds;
lowerBounds.reserve(map.getNumResults());
upperBounds.reserve(map.getNumResults());
for (AffineExpr e : map.getResults()) {
if (auto constExpr = e.dyn_cast<AffineConstantExpr>()) {
lowerBounds.push_back(constExpr.getValue());
upperBounds.push_back(constExpr.getValue());
} else {
lowerBounds.push_back(getBoundForExpr(e, map.getNumDims(),
map.getNumSymbols(),
constLowerBounds, constUpperBounds,
/*isUpper=*/false));
upperBounds.push_back(getBoundForExpr(e, map.getNumDims(),
map.getNumSymbols(),
constLowerBounds, constUpperBounds,
/*isUpper=*/true));
}
}
// Collect expressions that are not redundant.
SmallVector<AffineExpr, 4> irredundantExprs;
for (auto exprEn : llvm::enumerate(map.getResults())) {
AffineExpr e = exprEn.value();
unsigned i = exprEn.index();
// Some expressions can be turned into constants.
if (lowerBounds[i] && upperBounds[i] && *lowerBounds[i] == *upperBounds[i])
e = getAffineConstantExpr(*lowerBounds[i], e.getContext());
// Check if the expression is redundant.
if (isMax) {
if (!upperBounds[i]) {
irredundantExprs.push_back(e);
continue;
}
// If there exists another expression such that its lower bound is greater
// than this expression's upper bound, it's redundant.