-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathVectorOps.cpp
6904 lines (6092 loc) · 270 KB
/
VectorOps.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
//===- VectorOps.cpp - MLIR Vector Dialect 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
//
//===----------------------------------------------------------------------===//
//
// This file implements convenience types for working with super-vectorization
// operations, in particular super-vector loads and stores.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h"
#include "mlir/Dialect/Affine/IR/ValueBoundsOpInterfaceImpl.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Utils/Utils.h"
#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/UB/IR/UBOps.h"
#include "mlir/Dialect/Utils/IndexingUtils.h"
#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Interfaces/SubsetOpInterface.h"
#include "mlir/Interfaces/ValueBoundsOpInterface.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/InliningUtils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Casting.h"
#include <cassert>
#include <cstdint>
#include <numeric>
#include "mlir/Dialect/Vector/IR/VectorDialect.cpp.inc"
// Pull in all enum type and utility function definitions.
#include "mlir/Dialect/Vector/IR/VectorEnums.cpp.inc"
using namespace mlir;
using namespace mlir::vector;
/// Helper enum to classify mask value.
enum class MaskFormat {
AllTrue = 0,
AllFalse = 1,
Unknown = 2,
};
/// Helper method to classify a mask value. Currently, the method
/// looks "under the hood" of a constant value with dense attributes
/// and a constant mask operation (since the client may be called at
/// various stages during progressive lowering).
static MaskFormat getMaskFormat(Value mask) {
if (auto c = mask.getDefiningOp<arith::ConstantOp>()) {
// Inspect constant dense values. We count up for bits that
// are set, count down for bits that are cleared, and bail
// when a mix is detected.
if (auto denseElts = llvm::dyn_cast<DenseIntElementsAttr>(c.getValue())) {
int64_t val = 0;
for (bool b : denseElts.getValues<bool>())
if (b && val >= 0)
val++;
else if (!b && val <= 0)
val--;
else
return MaskFormat::Unknown;
if (val > 0)
return MaskFormat::AllTrue;
if (val < 0)
return MaskFormat::AllFalse;
}
} else if (auto m = mask.getDefiningOp<ConstantMaskOp>()) {
// Inspect constant mask index. If the index exceeds the
// dimension size, all bits are set. If the index is zero
// or less, no bits are set.
ArrayRef<int64_t> masks = m.getMaskDimSizes();
auto shape = m.getType().getShape();
bool allTrue = true;
bool allFalse = true;
for (auto [maskIdx, dimSize] : llvm::zip_equal(masks, shape)) {
if (maskIdx < dimSize)
allTrue = false;
if (maskIdx > 0)
allFalse = false;
}
if (allTrue)
return MaskFormat::AllTrue;
if (allFalse)
return MaskFormat::AllFalse;
} else if (auto m = mask.getDefiningOp<CreateMaskOp>()) {
// Finds all-false create_masks. An all-true create_mask requires all
// dims to be constants, so that'll be folded to a constant_mask, then
// detected in the constant_mask case.
auto maskOperands = m.getOperands();
for (Value operand : maskOperands) {
if (auto constantOp = operand.getDefiningOp<arith::ConstantOp>()) {
int64_t dimSize =
llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
if (dimSize <= 0)
return MaskFormat::AllFalse;
}
}
return MaskFormat::Unknown;
}
return MaskFormat::Unknown;
}
/// Default callback to build a region with a 'vector.yield' terminator with no
/// arguments.
void mlir::vector::buildTerminatedBody(OpBuilder &builder, Location loc) {
builder.create<vector::YieldOp>(loc);
}
// Helper for verifying combining kinds in contractions and reductions.
static bool isSupportedCombiningKind(CombiningKind combiningKind,
Type elementType) {
switch (combiningKind) {
case CombiningKind::ADD:
case CombiningKind::MUL:
return elementType.isIntOrIndexOrFloat();
case CombiningKind::MINUI:
case CombiningKind::MINSI:
case CombiningKind::MAXUI:
case CombiningKind::MAXSI:
case CombiningKind::AND:
case CombiningKind::OR:
case CombiningKind::XOR:
return elementType.isIntOrIndex();
case CombiningKind::MINNUMF:
case CombiningKind::MAXNUMF:
case CombiningKind::MINIMUMF:
case CombiningKind::MAXIMUMF:
return llvm::isa<FloatType>(elementType);
}
return false;
}
/// Returns the effective rank of the vector to read/write for Xfer Ops
///
/// When the element type of the shaped type is _a scalar_, this will simply
/// return the rank of the vector ( the result for xfer_read or the value to
/// store for xfer_write).
///
/// When the element type of the base shaped type is _a vector_, returns the
/// difference between the original vector type and the element type of the
/// shaped type.
///
/// EXAMPLE 1 (element type is _a scalar_):
/// - shapedType = tensor<10x20xf32>, vectorType = vector<2x4xf32>
/// - shapedType.getElementType() = f32 (rank 0)
/// - vectorType.getRank() = 2
/// - Result = 2 - 0 = 2
///
/// EXAMPLE 2 (element type is _a vector_):
/// - shapedType = tensor<10xvector<20xf32>>, vectorType = vector<20xf32>
/// - shapedType.getElementType() = vector<20xf32> (rank 1)
/// - vectorType.getRank() = 1
/// - Result = 1 - 1 = 0
///
/// This is used to determine the number of minor dimensions for identity maps
/// in vector transfer Ops.
static unsigned getEffectiveVectorRankForXferOp(ShapedType shapedType,
VectorType vectorType) {
unsigned elementVectorRank = 0;
VectorType elementVectorType =
llvm::dyn_cast<VectorType>(shapedType.getElementType());
if (elementVectorType)
elementVectorRank += elementVectorType.getRank();
return vectorType.getRank() - elementVectorRank;
}
AffineMap mlir::vector::getTransferMinorIdentityMap(ShapedType shapedType,
VectorType vectorType) {
// 0-d transfers are to/from tensor<t>/memref<t> and vector<1xt>.
// TODO: replace once we have 0-d vectors.
if (shapedType.getRank() == 0 &&
vectorType.getShape() == ArrayRef<int64_t>{1})
return AffineMap::get(
/*numDims=*/0, /*numSymbols=*/0,
getAffineConstantExpr(0, shapedType.getContext()));
return AffineMap::getMinorIdentityMap(
shapedType.getRank(),
getEffectiveVectorRankForXferOp(shapedType, vectorType),
shapedType.getContext());
}
/// Check if `write` is of a constant splat and the masked `read` is padded with
/// the same splat value -- meaning it could be the same value as the initial
/// constant splat.
static bool isSplatWriteConsistentWithMaskedRead(vector::TransferWriteOp write,
vector::TransferReadOp read) {
auto readMask = read.getMask();
auto writeMask = write.getMask();
// Check if the masks are consistent. The splat value could be the same if the
// read is masked (and padded with the splat value), and the write is unmasked
// or has the same mask. Note this does not allow the case where the write is
// masked and the read is unmasked, as then the read could be of more elements
// than the write (which may not be the same value).
bool couldBeSameSplat = readMask && (!writeMask || writeMask == readMask);
if (!couldBeSameSplat)
return false;
// Check for constant splat (as the source of the write).
DenseElementsAttr splatAttr;
if (!matchPattern(write.getVector(),
m_Constant<DenseElementsAttr>(&splatAttr)) ||
!splatAttr.isSplat()) {
return false;
}
// The padding of the read and the constant splat value must be the same.
Attribute padAttr;
if (!matchPattern(read.getPadding(), m_Constant(&padAttr)))
return false;
return padAttr == splatAttr.getSplatValue<Attribute>();
}
bool mlir::vector::checkSameValueRAW(vector::TransferWriteOp defWrite,
vector::TransferReadOp read) {
return !defWrite.hasOutOfBoundsDim() &&
defWrite.getIndices() == read.getIndices() &&
defWrite.getVectorType() == read.getVectorType() &&
defWrite.getPermutationMap() == read.getPermutationMap() &&
((!defWrite.getMask() && !read.getMask()) ||
isSplatWriteConsistentWithMaskedRead(defWrite, read));
}
bool mlir::vector::checkSameValueWAW(vector::TransferWriteOp write,
vector::TransferWriteOp priorWrite) {
return priorWrite.getIndices() == write.getIndices() &&
priorWrite.getMask() == write.getMask() &&
priorWrite.getVectorType() == write.getVectorType() &&
priorWrite.getPermutationMap() == write.getPermutationMap();
}
bool mlir::vector::isDisjointTransferIndices(
VectorTransferOpInterface transferA, VectorTransferOpInterface transferB,
bool testDynamicValueUsingBounds) {
// For simplicity only look at transfer of same type.
if (transferA.getVectorType() != transferB.getVectorType())
return false;
unsigned rankOffset = transferA.getLeadingShapedRank();
for (unsigned i = 0, e = transferA.getIndices().size(); i < e; i++) {
Value indexA = transferA.getIndices()[i];
Value indexB = transferB.getIndices()[i];
std::optional<int64_t> cstIndexA = getConstantIntValue(indexA);
std::optional<int64_t> cstIndexB = getConstantIntValue(indexB);
if (i < rankOffset) {
// For leading dimensions, if we can prove that index are different we
// know we are accessing disjoint slices.
if (cstIndexA.has_value() && cstIndexB.has_value()) {
if (*cstIndexA != *cstIndexB)
return true;
continue;
}
if (testDynamicValueUsingBounds) {
// First try to see if we can fully compose and simplify the affine
// expression as a fast track.
FailureOr<uint64_t> delta =
affine::fullyComposeAndComputeConstantDelta(indexA, indexB);
if (succeeded(delta) && *delta != 0)
return true;
FailureOr<bool> testEqual =
ValueBoundsConstraintSet::areEqual(indexA, indexB);
if (succeeded(testEqual) && !testEqual.value())
return true;
}
} else {
// For this dimension, we slice a part of the memref we need to make sure
// the intervals accessed don't overlap.
int64_t vectorDim = transferA.getVectorType().getDimSize(i - rankOffset);
if (cstIndexA.has_value() && cstIndexB.has_value()) {
int64_t distance = std::abs(*cstIndexA - *cstIndexB);
if (distance >= vectorDim)
return true;
continue;
}
if (testDynamicValueUsingBounds) {
// First try to see if we can fully compose and simplify the affine
// expression as a fast track.
FailureOr<int64_t> delta =
affine::fullyComposeAndComputeConstantDelta(indexA, indexB);
if (succeeded(delta) && std::abs(*delta) >= vectorDim)
return true;
FailureOr<int64_t> computeDelta =
ValueBoundsConstraintSet::computeConstantDelta(indexA, indexB);
if (succeeded(computeDelta)) {
if (std::abs(computeDelta.value()) >= vectorDim)
return true;
}
}
}
}
return false;
}
bool mlir::vector::isDisjointTransferSet(VectorTransferOpInterface transferA,
VectorTransferOpInterface transferB,
bool testDynamicValueUsingBounds) {
if (transferA.getSource() != transferB.getSource())
return false;
return isDisjointTransferIndices(transferA, transferB,
testDynamicValueUsingBounds);
}
// Helper to iterate over n-D vector slice elements. Calculate the next
// `position` in the n-D vector of size `shape`, applying an offset `offsets`.
// Modifies the `position` in place. Returns a failure when `position` becomes
// the end position.
static LogicalResult incSlicePosition(MutableArrayRef<int64_t> position,
ArrayRef<int64_t> shape,
ArrayRef<int64_t> offsets) {
for (auto [posInDim, dimSize, offsetInDim] :
llvm::reverse(llvm::zip_equal(position, shape, offsets))) {
++posInDim;
if (posInDim < dimSize + offsetInDim)
return success();
// Carry the overflow to the next loop iteration.
posInDim = offsetInDim;
}
return failure();
}
/// Returns the integer numbers in `values`. `values` are expected to be
/// constant operations.
SmallVector<int64_t> vector::getAsIntegers(ArrayRef<Value> values) {
SmallVector<int64_t> ints;
llvm::transform(values, std::back_inserter(ints), [](Value value) {
auto constOp = value.getDefiningOp<arith::ConstantIndexOp>();
assert(constOp && "Unexpected non-constant index");
return constOp.value();
});
return ints;
}
/// Returns the integer numbers in `foldResults`. `foldResults` are expected to
/// be constant operations.
SmallVector<int64_t> vector::getAsIntegers(ArrayRef<OpFoldResult> foldResults) {
SmallVector<int64_t> ints;
llvm::transform(
foldResults, std::back_inserter(ints), [](OpFoldResult foldResult) {
assert(isa<Attribute>(foldResult) && "Unexpected non-constant index");
return cast<IntegerAttr>(cast<Attribute>(foldResult)).getInt();
});
return ints;
}
/// Convert `foldResults` into Values. Integer attributes are converted to
/// constant op.
SmallVector<Value> vector::getAsValues(OpBuilder &builder, Location loc,
ArrayRef<OpFoldResult> foldResults) {
SmallVector<Value> values;
llvm::transform(foldResults, std::back_inserter(values),
[&](OpFoldResult foldResult) {
if (auto attr = dyn_cast<Attribute>(foldResult))
return builder
.create<arith::ConstantIndexOp>(
loc, cast<IntegerAttr>(attr).getInt())
.getResult();
return cast<Value>(foldResult);
});
return values;
}
std::optional<int64_t> vector::getConstantVscaleMultiplier(Value value) {
if (value.getDefiningOp<vector::VectorScaleOp>())
return 1;
auto mul = value.getDefiningOp<arith::MulIOp>();
if (!mul)
return {};
auto lhs = mul.getLhs();
auto rhs = mul.getRhs();
if (lhs.getDefiningOp<vector::VectorScaleOp>())
return getConstantIntValue(rhs);
if (rhs.getDefiningOp<vector::VectorScaleOp>())
return getConstantIntValue(lhs);
return {};
}
//===----------------------------------------------------------------------===//
// CombiningKindAttr
//===----------------------------------------------------------------------===//
namespace mlir {
namespace vector {
namespace detail {
struct BitmaskEnumStorage : public AttributeStorage {
using KeyTy = uint64_t;
BitmaskEnumStorage(KeyTy val) : value(val) {}
bool operator==(const KeyTy &key) const { return value == key; }
static BitmaskEnumStorage *construct(AttributeStorageAllocator &allocator,
const KeyTy &key) {
return new (allocator.allocate<BitmaskEnumStorage>())
BitmaskEnumStorage(key);
}
KeyTy value = 0;
};
} // namespace detail
} // namespace vector
} // namespace mlir
//===----------------------------------------------------------------------===//
// VectorDialect
//===----------------------------------------------------------------------===//
namespace {
/// This class defines the interface for handling inlining with vector dialect
/// operations.
struct VectorInlinerInterface : public DialectInlinerInterface {
using DialectInlinerInterface::DialectInlinerInterface;
/// All vector dialect ops can be inlined.
bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
return true;
}
};
} // namespace
void VectorDialect::initialize() {
addAttributes<
#define GET_ATTRDEF_LIST
#include "mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc"
>();
addOperations<
#define GET_OP_LIST
#include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
>();
addInterfaces<VectorInlinerInterface>();
declarePromisedInterfaces<bufferization::BufferizableOpInterface,
TransferReadOp, TransferWriteOp, GatherOp, MaskOp,
YieldOp>();
declarePromisedInterfaces<SubsetOpInterface, TransferReadOp,
TransferWriteOp>();
declarePromisedInterface<SubsetExtractionOpInterface, TransferReadOp>();
declarePromisedInterface<SubsetInsertionOpInterface, TransferWriteOp>();
declarePromisedInterface<ConvertToLLVMPatternInterface, VectorDialect>();
}
/// Materialize a single constant operation from a given attribute value with
/// the desired resultant type.
Operation *VectorDialect::materializeConstant(OpBuilder &builder,
Attribute value, Type type,
Location loc) {
if (isa<ub::PoisonAttrInterface>(value))
return value.getDialect().materializeConstant(builder, value, type, loc);
return arith::ConstantOp::materialize(builder, value, type, loc);
}
IntegerType vector::getVectorSubscriptType(Builder &builder) {
return builder.getIntegerType(64);
}
ArrayAttr vector::getVectorSubscriptAttr(Builder &builder,
ArrayRef<int64_t> values) {
return builder.getI64ArrayAttr(values);
}
//===----------------------------------------------------------------------===//
// MultiDimReductionOp
//===----------------------------------------------------------------------===//
void vector::MultiDimReductionOp::build(OpBuilder &builder,
OperationState &result, Value source,
Value acc, ArrayRef<bool> reductionMask,
CombiningKind kind) {
SmallVector<int64_t> reductionDims;
for (const auto &en : llvm::enumerate(reductionMask))
if (en.value())
reductionDims.push_back(en.index());
build(builder, result, kind, source, acc, reductionDims);
}
OpFoldResult MultiDimReductionOp::fold(FoldAdaptor adaptor) {
// Single parallel dim, this is a noop.
if (getSourceVectorType().getRank() == 1 && !isReducedDim(0))
return getSource();
return {};
}
std::optional<SmallVector<int64_t, 4>>
MultiDimReductionOp::getShapeForUnroll() {
return llvm::to_vector<4>(getSourceVectorType().getShape());
}
LogicalResult MultiDimReductionOp::verify() {
SmallVector<int64_t> targetShape;
SmallVector<bool> scalableDims;
Type inferredReturnType;
auto sourceScalableDims = getSourceVectorType().getScalableDims();
for (auto [dimIdx, dimSize] :
llvm::enumerate(getSourceVectorType().getShape()))
if (!llvm::any_of(getReductionDims(),
[dimIdx = dimIdx](int64_t reductionDimIdx) {
return reductionDimIdx == static_cast<int64_t>(dimIdx);
})) {
targetShape.push_back(dimSize);
scalableDims.push_back(sourceScalableDims[dimIdx]);
}
// TODO: update to also allow 0-d vectors when available.
if (targetShape.empty())
inferredReturnType = getSourceVectorType().getElementType();
else
inferredReturnType = VectorType::get(
targetShape, getSourceVectorType().getElementType(), scalableDims);
if (getType() != inferredReturnType)
return emitOpError() << "destination type " << getType()
<< " is incompatible with source type "
<< getSourceVectorType();
return success();
}
/// Returns the mask type expected by this operation.
Type MultiDimReductionOp::getExpectedMaskType() {
auto vecType = getSourceVectorType();
return VectorType::get(vecType.getShape(),
IntegerType::get(vecType.getContext(), /*width=*/1),
vecType.getScalableDims());
}
namespace {
// Only unit dimensions that are being reduced are folded. If the dimension is
// unit, but not reduced, it is not folded, thereby keeping the output type the
// same. If not all dimensions which are reduced are of unit dimension, this
// transformation does nothing. This is just a generalization of
// ElideSingleElementReduction for ReduceOp.
struct ElideUnitDimsInMultiDimReduction
: public OpRewritePattern<MultiDimReductionOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(MultiDimReductionOp reductionOp,
PatternRewriter &rewriter) const override {
ArrayRef<int64_t> shape = reductionOp.getSourceVectorType().getShape();
for (const auto &dim : enumerate(shape)) {
if (reductionOp.isReducedDim(dim.index()) && dim.value() != 1)
return failure();
}
// Vector mask setup.
OpBuilder::InsertionGuard guard(rewriter);
Operation *rootOp;
Value mask;
if (reductionOp.isMasked()) {
rewriter.setInsertionPoint(reductionOp.getMaskingOp());
rootOp = reductionOp.getMaskingOp();
mask = reductionOp.getMaskingOp().getMask();
} else {
rootOp = reductionOp;
}
Location loc = reductionOp.getLoc();
Value acc = reductionOp.getAcc();
Value cast;
if (auto dstVecType = dyn_cast<VectorType>(reductionOp.getDestType())) {
if (mask) {
VectorType newMaskType =
VectorType::get(dstVecType.getShape(), rewriter.getI1Type(),
dstVecType.getScalableDims());
mask = rewriter.create<vector::ShapeCastOp>(loc, newMaskType, mask);
}
cast = rewriter.create<vector::ShapeCastOp>(
loc, reductionOp.getDestType(), reductionOp.getSource());
} else {
// This means we are reducing all the dimensions, and all reduction
// dimensions are of size 1. So a simple extraction would do.
if (mask)
mask = rewriter.create<vector::ExtractOp>(loc, mask);
cast = rewriter.create<vector::ExtractOp>(loc, reductionOp.getSource());
}
Value result =
vector::makeArithReduction(rewriter, loc, reductionOp.getKind(), acc,
cast, /*fastmath=*/nullptr, mask);
rewriter.replaceOp(rootOp, result);
return success();
}
};
} // namespace
void MultiDimReductionOp::getCanonicalizationPatterns(
RewritePatternSet &results, MLIRContext *context) {
results.add<ElideUnitDimsInMultiDimReduction>(context);
}
//===----------------------------------------------------------------------===//
// ReductionOp
//===----------------------------------------------------------------------===//
void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
CombiningKind kind, Value vector,
arith::FastMathFlags fastMathFlags) {
build(builder, result, kind, vector, /*acc=*/Value(), fastMathFlags);
}
void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
CombiningKind kind, Value vector, Value acc,
arith::FastMathFlags fastMathFlags) {
build(builder, result,
llvm::cast<VectorType>(vector.getType()).getElementType(), kind, vector,
acc, fastMathFlags);
}
LogicalResult ReductionOp::verify() {
// Verify for 0-D and 1-D vector.
int64_t rank = getSourceVectorType().getRank();
if (rank > 1)
return emitOpError("unsupported reduction rank: ") << rank;
// Verify supported reduction kind.
Type eltType = getDest().getType();
if (!isSupportedCombiningKind(getKind(), eltType))
return emitOpError("unsupported reduction type '")
<< eltType << "' for kind '" << stringifyCombiningKind(getKind())
<< "'";
return success();
}
// MaskableOpInterface methods.
/// Returns the mask type expected by this operation.
Type ReductionOp::getExpectedMaskType() {
auto vecType = getSourceVectorType();
return VectorType::get(vecType.getShape(),
IntegerType::get(vecType.getContext(), /*width=*/1),
vecType.getScalableDims());
}
Value mlir::vector::getVectorReductionOp(arith::AtomicRMWKind op,
OpBuilder &builder, Location loc,
Value vector) {
switch (op) {
case arith::AtomicRMWKind::addf:
case arith::AtomicRMWKind::addi:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::ADD, vector);
case arith::AtomicRMWKind::mulf:
case arith::AtomicRMWKind::muli:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MUL, vector);
case arith::AtomicRMWKind::minimumf:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MINIMUMF, vector);
case arith::AtomicRMWKind::mins:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MINSI, vector);
case arith::AtomicRMWKind::minu:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MINUI, vector);
case arith::AtomicRMWKind::maximumf:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MAXIMUMF, vector);
case arith::AtomicRMWKind::maxs:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MAXSI, vector);
case arith::AtomicRMWKind::maxu:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::MAXUI, vector);
case arith::AtomicRMWKind::andi:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::AND, vector);
case arith::AtomicRMWKind::ori:
return builder.create<vector::ReductionOp>(vector.getLoc(),
CombiningKind::OR, vector);
// TODO: Add remaining reduction operations.
default:
(void)emitOptionalError(loc, "Reduction operation type not supported");
break;
}
return nullptr;
}
std::optional<SmallVector<int64_t, 4>> ReductionOp::getShapeForUnroll() {
return llvm::to_vector<4>(getSourceVectorType().getShape());
}
namespace {
struct ElideSingleElementReduction : public OpRewritePattern<ReductionOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(ReductionOp reductionOp,
PatternRewriter &rewriter) const override {
// Vector mask setup.
OpBuilder::InsertionGuard guard(rewriter);
auto maskableOp =
cast<vector::MaskableOpInterface>(reductionOp.getOperation());
Operation *rootOp;
Value mask;
if (maskableOp.isMasked()) {
rewriter.setInsertionPoint(maskableOp.getMaskingOp());
rootOp = maskableOp.getMaskingOp();
mask = maskableOp.getMaskingOp().getMask();
} else {
rootOp = reductionOp;
}
auto vectorType = reductionOp.getSourceVectorType();
if (vectorType.getRank() != 0 && vectorType.getDimSize(0) != 1)
return failure();
Location loc = reductionOp.getLoc();
if (mask)
mask = rewriter.create<ExtractOp>(loc, mask);
Value result = rewriter.create<ExtractOp>(loc, reductionOp.getVector());
if (Value acc = reductionOp.getAcc())
result = vector::makeArithReduction(rewriter, loc, reductionOp.getKind(),
result, acc,
reductionOp.getFastmathAttr(), mask);
rewriter.replaceOp(rootOp, result);
return success();
}
};
} // namespace
void ReductionOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<ElideSingleElementReduction>(context);
}
//===----------------------------------------------------------------------===//
// ContractionOp
//===----------------------------------------------------------------------===//
void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
Value lhs, Value rhs, Value acc,
ArrayRef<ArrayRef<AffineExpr>> indexingExprs,
ArrayRef<IteratorType> iteratorTypes) {
result.addOperands({lhs, rhs, acc});
result.addTypes(acc.getType());
result.addAttribute(
getIndexingMapsAttrName(result.name),
builder.getAffineMapArrayAttr(
AffineMap::inferFromExprList(indexingExprs, builder.getContext())));
result.addAttribute(
getIteratorTypesAttrName(result.name),
builder.getArrayAttr(llvm::to_vector(llvm::map_range(
iteratorTypes, [&](IteratorType t) -> mlir::Attribute {
return IteratorTypeAttr::get(builder.getContext(), t);
}))));
}
void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
Value lhs, Value rhs, Value acc,
ArrayAttr indexingMaps,
ArrayAttr iteratorTypes) {
build(builder, result, lhs, rhs, acc, indexingMaps, iteratorTypes,
ContractionOp::getDefaultKind());
}
void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
Value lhs, Value rhs, Value acc,
ArrayAttr indexingMaps,
ArrayAttr iteratorTypes, CombiningKind kind) {
result.addOperands({lhs, rhs, acc});
result.addTypes(acc.getType());
result.addAttribute(getIndexingMapsAttrName(result.name), indexingMaps);
result.addAttribute(getIteratorTypesAttrName(result.name), iteratorTypes);
result.addAttribute(getKindAttrName(result.name),
CombiningKindAttr::get(builder.getContext(), kind));
}
ParseResult ContractionOp::parse(OpAsmParser &parser, OperationState &result) {
OpAsmParser::UnresolvedOperand lhsInfo;
OpAsmParser::UnresolvedOperand rhsInfo;
OpAsmParser::UnresolvedOperand accInfo;
SmallVector<OpAsmParser::UnresolvedOperand, 2> masksInfo;
SmallVector<Type, 2> types;
Type resultType;
auto loc = parser.getCurrentLocation();
DictionaryAttr dictAttr;
// TODO: Unify linalg op attribute parsing.
if (parser.parseAttribute(dictAttr) || parser.parseOperand(lhsInfo) ||
parser.parseComma() || parser.parseOperand(rhsInfo) ||
parser.parseComma() || parser.parseOperand(accInfo) ||
parser.parseTrailingOperandList(masksInfo) ||
parser.parseOptionalAttrDict(result.attributes) ||
parser.parseColonTypeList(types) ||
parser.parseKeywordType("into", resultType) ||
parser.resolveOperand(lhsInfo, types[0], result.operands) ||
parser.resolveOperand(rhsInfo, types[1], result.operands) ||
parser.resolveOperand(accInfo, resultType, result.operands) ||
parser.addTypeToList(resultType, result.types))
return failure();
result.attributes.append(dictAttr.getValue().begin(),
dictAttr.getValue().end());
// Convert array of string into an array of IteratyType enums. This is needed,
// because tests still use the old format when 'iterator_types' attribute is
// represented as an array of strings.
// TODO: Remove this conversion once tests are fixed.
auto iteratorTypes = dyn_cast_or_null<ArrayAttr>(
result.attributes.get(getIteratorTypesAttrName(result.name)));
if (!iteratorTypes) {
return parser.emitError(loc)
<< "expected " << getIteratorTypesAttrName(result.name)
<< " array attribute";
}
SmallVector<Attribute> iteratorTypeAttrs;
for (StringRef s : iteratorTypes.getAsValueRange<StringAttr>()) {
auto maybeIteratorType = symbolizeIteratorType(s);
if (!maybeIteratorType.has_value())
return parser.emitError(loc) << "unexpected iterator_type (" << s << ")";
iteratorTypeAttrs.push_back(
IteratorTypeAttr::get(parser.getContext(), maybeIteratorType.value()));
}
result.attributes.set(getIteratorTypesAttrName(result.name),
parser.getBuilder().getArrayAttr(iteratorTypeAttrs));
if (!result.attributes.get(getKindAttrName(result.name))) {
result.addAttribute(
getKindAttrName(result.name),
CombiningKindAttr::get(result.getContext(),
ContractionOp::getDefaultKind()));
}
if (masksInfo.empty())
return success();
if (masksInfo.size() != 2)
return parser.emitError(parser.getNameLoc(),
"expected zero or exactly 2 vector mask operands");
auto lhsType = llvm::cast<VectorType>(types[0]);
auto rhsType = llvm::cast<VectorType>(types[1]);
auto maskElementType = parser.getBuilder().getI1Type();
std::array<VectorType, 2> maskTypes = {
VectorType::Builder(lhsType).setElementType(maskElementType),
VectorType::Builder(rhsType).setElementType(maskElementType)};
if (parser.resolveOperands(masksInfo, maskTypes, loc, result.operands))
return failure();
return success();
}
void ContractionOp::print(OpAsmPrinter &p) {
// TODO: Unify printing code with linalg ops.
auto attrNames = getTraitAttrNames();
llvm::StringSet<> traitAttrsSet;
traitAttrsSet.insert_range(attrNames);
SmallVector<NamedAttribute, 8> attrs;
for (auto attr : (*this)->getAttrs()) {
if (attr.getName() == getIteratorTypesAttrName()) {
auto iteratorTypes =
llvm::cast<ArrayAttr>(attr.getValue())
.getAsValueRange<IteratorTypeAttr, IteratorType>();
// Convert IteratorType enums into the string representation. This is
// needed, because tests still use the old format when 'iterator_types'
// attribute is represented as an array of strings.
// TODO: Remove this conversion once tests are fixed.
SmallVector<Attribute> iteratorTypeNames = llvm::to_vector(
llvm::map_range(iteratorTypes, [&](IteratorType t) -> Attribute {
return StringAttr::get(getContext(), stringifyIteratorType(t));
}));
attrs.emplace_back(getIteratorTypesAttrName(),
ArrayAttr::get(getContext(), iteratorTypeNames));
} else if (traitAttrsSet.count(attr.getName().strref()) > 0)
attrs.push_back(attr);
}
auto dictAttr = DictionaryAttr::get(getContext(), attrs);
p << " " << dictAttr << " " << getLhs() << ", ";
p << getRhs() << ", " << getAcc();
p.printOptionalAttrDict((*this)->getAttrs(), attrNames);
p << " : " << getLhs().getType() << ", " << getRhs().getType() << " into "
<< getResultType();
}
static bool verifyDimMap(VectorType lhsType, VectorType rhsType,
const std::vector<std::pair<int64_t, int64_t>> &map) {
for (auto &dimPair : map) {
if (dimPair.first < 0 || dimPair.first >= lhsType.getRank() ||
dimPair.second < 0 || dimPair.second >= rhsType.getRank() ||
lhsType.getDimSize(dimPair.first) != rhsType.getDimSize(dimPair.second))
return false;
}
return true;
}
static LogicalResult verifyOutputShape(
ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType,
Type resType,
const std::vector<std::pair<int64_t, int64_t>> &contractingDimMap,
const std::vector<std::pair<int64_t, int64_t>> &batchDimMap) {
DenseSet<int64_t> lhsContractingDimSet;
DenseSet<int64_t> rhsContractingDimSet;
for (auto &dimPair : contractingDimMap) {
lhsContractingDimSet.insert(dimPair.first);
rhsContractingDimSet.insert(dimPair.second);
}
DenseSet<int64_t> rhsBatchDimSet(llvm::from_range,
llvm::make_second_range(batchDimMap));
// Add free and batch dimensions from 'lhsType' to 'expectedResultDims'.
SmallVector<int64_t, 4> expectedResultDims;
for (int64_t i = 0, e = lhsType.getRank(); i < e; ++i) {
if (lhsContractingDimSet.count(i) > 0)
continue;
expectedResultDims.push_back(lhsType.getDimSize(i));
}
// Add free dimensions from 'rhsType' to 'expectedResultDims'.
for (int64_t i = 0, e = rhsType.getRank(); i < e; ++i) {
if (rhsContractingDimSet.count(i) > 0 || rhsBatchDimSet.count(i) > 0)
continue;
expectedResultDims.push_back(rhsType.getDimSize(i));
}
// Verify 'expectedResultDims'.
if (expectedResultDims.empty()) {
// No batch or free dimension implies a scalar result.
if (llvm::isa<VectorType>(resType) || llvm::isa<VectorType>(accType))
return op.emitOpError("invalid accumulator/result vector shape");
} else {
// At least one batch or free dimension implies a vector result.
auto resVectorType = llvm::dyn_cast<VectorType>(resType);
auto accVectorType = llvm::dyn_cast<VectorType>(accType);
if (!resVectorType || !accVectorType)
return op.emitOpError("invalid accumulator/result vector shape");
// Infer expected result vector type. Lhs + rhs map and lhs + rhs vector
// types fully define the result vector type. This assumes the affine maps
// are well-formed, which must have been verified already.
MLIRContext *ctx = op.getContext();
AffineMap lhsMap = op.getIndexingMapsArray()[0];
AffineMap rhsMap = op.getIndexingMapsArray()[1];
if (getUnusedDimsBitVector({lhsMap, rhsMap}).any())
return op.emitOpError(
"expected all dimensions to be either a LHS or a RHS dimension");
SmallVector<AffineExpr, 4> extents(lhsMap.getNumInputs());
for (auto pair :
{std::make_pair(lhsType, lhsMap), std::make_pair(rhsType, rhsMap)}) {
VectorType v = pair.first;
auto map = pair.second;
for (unsigned idx = 0, e = v.getRank(); idx < e; ++idx) {
unsigned pos = map.getDimPosition(idx);
if (!extents[pos])
extents[pos] = getAffineConstantExpr(v.getShape()[idx], ctx);
}
}
if (!llvm::all_of(extents, [](AffineExpr e) { return e; }))
return op.emitOpError("expected all dimensions to get an extent as "
"either a LHS or a RHS dimension");
AffineMap resMap = op.getIndexingMapsArray()[2];
auto extentsMap = AffineMap::get(/*dimCount=*/extents.size(),
/*symbolCount=*/0, extents, ctx);
// Compose the resMap with the extentsMap, which is a constant map.
AffineMap expectedMap = simplifyAffineMap(resMap.compose(extentsMap));
assert(llvm::all_of(expectedMap.getResults(),
llvm::IsaPred<AffineConstantExpr>) &&
"expected constant extent along all dimensions.");
// Extract the expected shape and build the type.
auto expectedShape = llvm::to_vector<4>(
llvm::map_range(expectedMap.getResults(), [](AffineExpr e) {
return cast<AffineConstantExpr>(e).getValue();
}));
auto expected =
VectorType::get(expectedShape, resVectorType.getElementType(),
resVectorType.getScalableDims());
if (resVectorType != expected || accVectorType != expected)
return op.emitOpError(
"invalid accumulator/result vector shape, expected: ")
<< expected;
}
return success();
}
LogicalResult ContractionOp::verify() {
VectorType lhsType = getLhsType();