19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/DebugLog.h"
22#include "llvm/Support/InterleavedRange.h"
25#define DEBUG_TYPE "vector-unroll"
35 if (
auto constExpr = dyn_cast<AffineConstantExpr>(expr))
36 return constExpr.getValue() == 0;
41 for (
const auto &dim : llvm::enumerate(permutationMap.
getResults())) {
42 int64_t elementOffset = elementOffsets[dim.index()];
43 if (isBroadcast(dim.value()) || elementOffset == 0)
45 unsigned pos = cast<AffineDimExpr>(dim.value()).getPosition();
50 affine::AffineApplyOp::create(builder, loc, map,
indices[pos]);
62 assert(offsets.size() <= originalIndices.size() &&
63 "Offsets should not exceed the number of original indices");
66 auto start =
indices.size() - offsets.size();
67 for (
auto [i, offset] : llvm::enumerate(offsets)) {
69 indices[start + i] = arith::AddIOp::create(
70 rewriter, loc, originalIndices[start + i],
86 return builder.
create(state);
101static std::optional<SmallVector<int64_t>>
103 VectorUnrollOpInterface &iface,
bool allowMasked =
false) {
104 auto op = iface.getOperation();
106 if (
options.filterConstraint && failed(
options.filterConstraint(op))) {
107 LDBG() <<
"--no filter constraint -> BAIL";
112 auto tS = iface.getDefaultUnrollTargetShape();
116 auto maskableOp = dyn_cast<vector::MaskableOpInterface>(op);
117 if (!allowMasked && maskableOp && maskableOp.isMasked()) {
118 LDBG() <<
"--op is masked -> BAIL";
121 auto maybeUnrollShape = iface.getIterationShapeToUnroll();
122 if (!maybeUnrollShape) {
123 LDBG() <<
"--could not get shape of op " << *op <<
" -> BAIL";
126 LDBG() <<
"--vector op shape: " << llvm::interleaved(*maybeUnrollShape);
128 std::optional<SmallVector<int64_t>> targetShape =
131 LDBG() <<
"--no unrolling target shape defined " << *op <<
"-> SKIP";
134 LDBG() <<
"--target shape: " << llvm::interleaved(*targetShape);
137 if (!maybeShapeRatio) {
138 LDBG() <<
"--could not compute integral shape ratio -> BAIL";
141 if (llvm::all_of(*maybeShapeRatio, [](
int64_t v) {
return v == 1; })) {
142 LDBG() <<
"--no unrolling needed -> SKIP";
145 LDBG() <<
"--found an integral shape ratio to unroll to -> SUCCESS";
151template <
typename TransferOpTy>
157 if (xferOp.getVectorType().getRank() != xferOp.getTransferRank())
159 xferOp,
"masked transfer with a vector element type");
163 if (!xferOp.getPermutationMap().isMinorIdentity())
165 xferOp,
"masked transfer with a non-minor-identity map");
166 if (xferOp.getVectorType().isScalable())
178 vector::MaskingOpInterface maskingOp,
184 loc, maskingOp.getMask(), offsets, sizes, strides);
186 if (maskingOp.hasPassthru())
187 passthru = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
188 loc, maskingOp.getPassthru(), offsets, sizes, strides);
193struct UnrollTransferReadPattern
195 UnrollTransferReadPattern(MLIRContext *context,
196 const vector::UnrollVectorOptions &options,
197 PatternBenefit benefit = 1)
198 : MaskableOpRewritePattern<vector::TransferReadOp>(context, benefit),
202 matchAndRewriteMaskableOp(vector::TransferReadOp readOp,
203 vector::MaskingOpInterface maskingOp,
204 PatternRewriter &rewriter)
const override {
206 if (readOp.getTransferRank() == 0)
208 if (readOp.getMask())
216 auto iface = dyn_cast<VectorUnrollOpInterface>(readOp.getOperation());
220 auto sourceVectorType = readOp.getVectorType();
221 SmallVector<int64_t> strides(targetShape->size(), 1);
222 Location loc = readOp.getLoc();
223 ArrayRef<int64_t> originalSize = sourceVectorType.getShape();
227 if (originalSize.size() != targetShape->size())
230 "expected source input vector rank to match target shape rank");
234 arith::ConstantOp::create(rewriter, loc, sourceVectorType,
237 VectorType::get(*targetShape, sourceVectorType.getElementType());
238 SmallVector<Value> originalIndices(readOp.getIndices().begin(),
239 readOp.getIndices().end());
240 SmallVector<int64_t> loopOrder =
241 readOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
242 for (SmallVector<int64_t> elementOffsets :
243 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
245 sliceTransferIndices(elementOffsets, originalIndices,
246 readOp.getPermutationMap(), loc, rewriter);
247 Operation *slicedRead = vector::TransferReadOp::create(
248 rewriter, loc, targetType, readOp.getBase(),
indices,
249 readOp.getPermutationMapAttr(), readOp.getPadding(), readOp.getMask(),
250 readOp.getInBoundsAttr());
251 slicedRead =
maskTile(rewriter, loc, slicedRead, maskingOp,
252 elementOffsets, *targetShape, strides);
261 vector::UnrollVectorOptions options;
264struct UnrollTransferWritePattern
266 UnrollTransferWritePattern(MLIRContext *context,
267 const vector::UnrollVectorOptions &options,
268 PatternBenefit benefit = 1)
269 : MaskableOpRewritePattern<vector::TransferWriteOp>(context, benefit),
273 matchAndRewriteMaskableOp(vector::TransferWriteOp writeOp,
274 vector::MaskingOpInterface maskingOp,
275 PatternRewriter &rewriter)
const override {
277 if (writeOp.getTransferRank() == 0)
280 if (writeOp.getMask())
288 auto iface = dyn_cast<VectorUnrollOpInterface>(writeOp.getOperation());
292 auto sourceVectorType = writeOp.getVectorType();
293 SmallVector<int64_t> strides(targetShape->size(), 1);
294 Location loc = writeOp.getLoc();
295 ArrayRef<int64_t> originalSize = sourceVectorType.getShape();
299 if (originalSize.size() != targetShape->size())
302 "expected source input vector rank to match target shape rank");
304 SmallVector<Value> originalIndices(writeOp.getIndices().begin(),
305 writeOp.getIndices().end());
306 SmallVector<int64_t> loopOrder =
307 writeOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
309 for (SmallVector<int64_t> elementOffsets :
310 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
311 Value slicedVector = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
312 loc, writeOp.getVector(), elementOffsets, *targetShape, strides);
314 sliceTransferIndices(elementOffsets, originalIndices,
315 writeOp.getPermutationMap(), loc, rewriter);
316 Operation *slicedWrite = vector::TransferWriteOp::create(
317 rewriter, loc, slicedVector,
318 resultTensor ? resultTensor : writeOp.getBase(),
indices,
319 writeOp.getPermutationMapAttr(), writeOp.getInBoundsAttr());
320 slicedWrite =
maskTile(rewriter, loc, slicedWrite, maskingOp,
321 elementOffsets, *targetShape, strides);
324 resultTensor = slicedWrite->
getResult(0);
331 vector::UnrollVectorOptions options;
334struct OffsetMapInfo {
335 static unsigned getHashValue(
const SmallVector<int64_t> &v) {
336 return static_cast<unsigned>(llvm::hash_combine_range(v));
339 static bool isEqual(
const SmallVector<int64_t> &
lhs,
340 const SmallVector<int64_t> &
rhs) {
345struct UnrollContractionPattern
347 UnrollContractionPattern(MLIRContext *context,
348 const vector::UnrollVectorOptions &options,
349 PatternBenefit benefit = 1)
350 : OpRewritePattern<vector::ContractionOp>(context, benefit),
353 LogicalResult matchAndRewrite(vector::ContractionOp contractOp,
354 PatternRewriter &rewriter)
const override {
356 auto iface = dyn_cast<VectorUnrollOpInterface>(contractOp.getOperation());
360 auto dstVecType = cast<VectorType>(contractOp.getResultType());
361 SmallVector<int64_t> originalSize = *contractOp.getIterationShapeToUnroll();
363 Location loc = contractOp.getLoc();
364 unsigned accIndex = vector::ContractionOp::getAccOperandIndex();
365 AffineMap dstAffineMap = contractOp.getIndexingMapsArray()[accIndex];
367 SmallVector<int64_t>, Value,
368 llvm::DenseMap<SmallVector<int64_t>, unsigned, OffsetMapInfo>>
373 SmallVector<int64_t> loopOrder =
374 contractOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
375 if (!options.unrollOrderForContractOp.empty()) {
376 assert(options.unrollOrderForContractOp.size() == originalSize.size() &&
377 "Invalid loop order provided!");
378 loopOrder = options.unrollOrderForContractOp;
381 for (SmallVector<int64_t> offsets :
382 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
383 SmallVector<Value> slicesOperands(contractOp.getNumOperands());
386 auto extractOperand = [&](
unsigned index, Value operand,
387 AffineMap permutationMap,
388 ArrayRef<int64_t> operandOffets) {
390 permutationMap, ArrayRef<int64_t>(*targetShape));
391 SmallVector<int64_t> operandStrides(operandOffets.size(), 1);
392 slicesOperands[index] =
394 loc, operand, operandOffets, operandShape, operandStrides);
398 AffineMap lhsPermutationMap = contractOp.getIndexingMapsArray()[0];
399 SmallVector<int64_t> lhsOffets =
401 extractOperand(0, contractOp.getLhs(), lhsPermutationMap, lhsOffets);
404 AffineMap rhsPermutationMap = contractOp.getIndexingMapsArray()[1];
405 SmallVector<int64_t> rhsOffets =
407 extractOperand(1, contractOp.getRhs(), rhsPermutationMap, rhsOffets);
409 AffineMap accPermutationMap = contractOp.getIndexingMapsArray()[2];
410 SmallVector<int64_t> accOffets =
414 auto *accIt = accCache.find(accOffets);
415 if (accIt != accCache.end())
416 slicesOperands[2] = accIt->second;
418 extractOperand(2, contractOp.getAcc(), accPermutationMap, accOffets);
420 SmallVector<int64_t> dstShape =
422 auto targetType = VectorType::get(dstShape, dstVecType.getElementType());
424 rewriter, loc, contractOp, slicesOperands, targetType);
426 SmallVector<int64_t> dstOffets =
430 accCache[dstOffets] = newOp->
getResult(0);
433 Value
result = arith::ConstantOp::create(rewriter, loc, dstVecType,
435 for (
const auto &it : accCache) {
436 SmallVector<int64_t> dstStrides(it.first.size(), 1);
438 loc, it.second,
result, it.first, dstStrides);
445 vector::UnrollVectorOptions options;
448struct UnrollMultiReductionPattern
450 UnrollMultiReductionPattern(MLIRContext *context,
451 const vector::UnrollVectorOptions &options,
452 PatternBenefit benefit = 1)
453 : OpRewritePattern<vector::MultiDimReductionOp>(context, benefit),
456 LogicalResult matchAndRewrite(vector::MultiDimReductionOp reductionOp,
457 PatternRewriter &rewriter)
const override {
460 auto iface = dyn_cast<VectorUnrollOpInterface>(reductionOp.getOperation());
461 std::optional<SmallVector<int64_t>> targetShape =
465 SmallVector<int64_t> originalSize =
466 *reductionOp.getIterationShapeToUnroll();
467 Location loc = reductionOp.getLoc();
468 auto resultType = reductionOp->getResult(0).getType();
473 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
474 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
479 if (resultType.isIntOrFloat()) {
480 Value accumulator = reductionOp.getAcc();
481 for (SmallVector<int64_t> offsets :
482 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
483 SmallVector<int64_t> operandStrides(offsets.size(), 1);
484 Value slicedOperand =
486 loc, reductionOp.getSource(), offsets, adjustedTargetShape,
489 rewriter, loc, reductionOp, {slicedOperand, accumulator},
493 rewriter.
replaceOp(reductionOp, accumulator);
499 SmallVector<int64_t>, Value,
500 llvm::DenseMap<SmallVector<int64_t>, unsigned, OffsetMapInfo>>
505 for (SmallVector<int64_t> offsets :
506 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
507 SmallVector<Value> operands;
508 SmallVector<int64_t> operandStrides(offsets.size(), 1);
509 Value slicedOperand =
511 loc, reductionOp.getSource(), offsets, adjustedTargetShape,
513 operands.push_back(slicedOperand);
514 SmallVector<int64_t> dstShape;
515 SmallVector<int64_t> destOffset;
516 for (
size_t i : llvm::seq(
size_t(0), adjustedTargetShape.size())) {
517 if (!reductionOp.isReducedDim(i)) {
518 destOffset.push_back(offsets[i]);
519 dstShape.push_back(adjustedTargetShape[i]);
523 SmallVector<int64_t> accStrides(destOffset.size(), 1);
526 auto *accIt = accCache.find(destOffset);
527 if (accIt != accCache.end())
530 acc = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
531 loc, reductionOp.getAcc(), destOffset, dstShape, accStrides);
532 operands.push_back(acc);
533 auto targetType = VectorType::get(
534 dstShape, reductionOp.getSourceVectorType().getElementType());
536 operands, targetType);
538 accCache[destOffset] =
result;
541 Value
result = arith::ConstantOp::create(
542 rewriter, loc, reductionOp.getDestType(),
544 for (
const auto &it : accCache) {
545 SmallVector<int64_t> dstStrides(it.first.size(), 1);
547 loc, it.second,
result, it.first, dstStrides);
554 vector::UnrollVectorOptions options;
558 UnrollElementwisePattern(MLIRContext *context,
559 const vector::UnrollVectorOptions &options,
560 PatternBenefit benefit = 1)
561 : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
564 LogicalResult matchAndRewrite(Operation *op,
565 PatternRewriter &rewriter)
const override {
569 auto iface = dyn_cast<VectorUnrollOpInterface>(op);
575 int64_t targetShapeRank = targetShape->size();
577 SmallVector<int64_t> originalSize = *iface.getIterationShapeToUnroll();
578 int64_t originalShapeRank = originalSize.size();
580 Location loc = op->
getLoc();
583 SmallVector<int64_t> adjustedTargetShape(originalShapeRank);
584 int64_t rankDiff = originalShapeRank - targetShapeRank;
585 std::fill(adjustedTargetShape.begin(),
586 adjustedTargetShape.begin() + rankDiff, 1);
587 std::copy(targetShape->begin(), targetShape->end(),
588 adjustedTargetShape.begin() + rankDiff);
590 int64_t adjustedTargetShapeRank = adjustedTargetShape.size();
592 Value
result = arith::ConstantOp::create(rewriter, loc, dstVecType,
594 SmallVector<int64_t> strides(adjustedTargetShapeRank, 1);
595 VectorType unrolledVecType =
596 VectorType::get(*targetShape, dstVecType.getElementType());
599 for (SmallVector<int64_t> offsets :
600 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
601 SmallVector<Value> extractOperands;
603 auto vecType = dyn_cast<VectorType>(operand.get().getType());
605 extractOperands.push_back(operand.get());
608 Value extracted = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
609 loc, operand.get(), offsets, adjustedTargetShape, strides);
612 if (adjustedTargetShapeRank > targetShapeRank) {
614 loc, VectorType::get(*targetShape, vecType.getElementType()),
617 extractOperands.push_back(extracted);
621 rewriter, loc, op, extractOperands, unrolledVecType);
623 Value computeResult = newOp->
getResult(0);
626 SmallVector<int64_t> insertStrides =
627 (adjustedTargetShapeRank > targetShapeRank)
628 ? SmallVector<int64_t>(targetShapeRank, 1)
632 loc, computeResult,
result, offsets, insertStrides);
639 vector::UnrollVectorOptions options;
642struct UnrollReductionPattern :
public OpRewritePattern<vector::ReductionOp> {
643 UnrollReductionPattern(MLIRContext *context,
644 const vector::UnrollVectorOptions &options,
645 PatternBenefit benefit = 1)
646 : OpRewritePattern<vector::ReductionOp>(context, benefit),
649 LogicalResult matchAndRewrite(vector::ReductionOp reductionOp,
650 PatternRewriter &rewriter)
const override {
652 auto iface = cast<VectorUnrollOpInterface>(*reductionOp);
653 std::optional<SmallVector<int64_t>> targetShape =
657 SmallVector<int64_t> originalSize =
658 *reductionOp.getIterationShapeToUnroll();
661 Location loc = reductionOp.getLoc();
662 Value accumulator =
nullptr;
663 for (SmallVector<int64_t> offsets :
664 StaticTileOffsetRange(originalSize, *targetShape)) {
665 SmallVector<int64_t> strides(offsets.size(), 1);
666 Value slicedOperand =
668 loc, reductionOp.getVector(), offsets, *targetShape, strides);
670 rewriter, loc, reductionOp, slicedOperand, reductionOp.getType());
683 rewriter.
replaceOp(reductionOp, accumulator);
688 const vector::UnrollVectorOptions options;
691struct UnrollTransposePattern :
public OpRewritePattern<vector::TransposeOp> {
692 UnrollTransposePattern(MLIRContext *context,
693 const vector::UnrollVectorOptions &options,
694 PatternBenefit benefit = 1)
695 : OpRewritePattern<vector::TransposeOp>(context, benefit),
698 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
699 PatternRewriter &rewriter)
const override {
700 if (transposeOp.getResultVectorType().getRank() == 0)
703 auto iface = cast<VectorUnrollOpInterface>(*transposeOp);
707 auto originalVectorType = transposeOp.getResultVectorType();
708 SmallVector<int64_t> strides(targetShape->size(), 1);
709 Location loc = transposeOp.getLoc();
710 ArrayRef<int64_t> originalSize = originalVectorType.getShape();
714 arith::ConstantOp::create(rewriter, loc, originalVectorType,
716 ArrayRef<int64_t> permutation = transposeOp.getPermutation();
719 for (SmallVector<int64_t> elementOffsets :
720 StaticTileOffsetRange(originalSize, *targetShape)) {
721 SmallVector<int64_t> permutedOffsets(elementOffsets.size());
722 SmallVector<int64_t> permutedShape(elementOffsets.size());
724 for (
auto indices : llvm::enumerate(permutation)) {
725 permutedOffsets[
indices.value()] = elementOffsets[
indices.index()];
728 Value slicedOperand =
730 loc, transposeOp.getVector(), permutedOffsets, permutedShape,
732 Value transposedSlice = rewriter.
createOrFold<vector::TransposeOp>(
733 loc, slicedOperand, permutation);
735 loc, transposedSlice,
result, elementOffsets, strides);
742 vector::UnrollVectorOptions options;
746 UnrollGatherPattern(MLIRContext *context,
747 const vector::UnrollVectorOptions &options,
748 PatternBenefit benefit = 1)
749 : OpRewritePattern<vector::GatherOp>(context, benefit), options(options) {
752 LogicalResult matchAndRewrite(vector::GatherOp gatherOp,
753 PatternRewriter &rewriter)
const override {
754 VectorType sourceVectorType = gatherOp.getVectorType();
755 if (sourceVectorType.getRank() == 0)
758 auto iface = cast<VectorUnrollOpInterface>(*gatherOp);
762 SmallVector<int64_t> strides(targetShape->size(), 1);
763 Location loc = gatherOp.getLoc();
764 ArrayRef<int64_t> originalSize = gatherOp.getVectorType().getShape();
768 arith::ConstantOp::create(rewriter, loc, sourceVectorType,
771 VectorType::get(*targetShape, sourceVectorType.getElementType());
773 SmallVector<int64_t> loopOrder =
774 gatherOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
775 for (SmallVector<int64_t> elementOffsets :
776 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
780 Value indexSubVec = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
781 loc, gatherOp.getIndices(), elementOffsets, *targetShape, strides);
782 Value maskSubVec = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
783 loc, gatherOp.getMask(), elementOffsets, *targetShape, strides);
784 Value passThruSubVec =
786 loc, gatherOp.getPassThru(), elementOffsets, *targetShape,
788 auto slicedGather = vector::GatherOp::create(
789 rewriter, loc, targetType, gatherOp.getBase(), gatherOp.getOffsets(),
790 indexSubVec, maskSubVec, passThruSubVec);
793 loc, slicedGather,
result, elementOffsets, strides);
800 vector::UnrollVectorOptions options;
804 UnrollLoadPattern(MLIRContext *context,
805 const vector::UnrollVectorOptions &options,
806 PatternBenefit benefit = 1)
807 : OpRewritePattern<vector::LoadOp>(context, benefit), options(options) {}
809 LogicalResult matchAndRewrite(vector::LoadOp loadOp,
810 PatternRewriter &rewriter)
const override {
811 VectorType vecType = loadOp.getVectorType();
814 auto iface = cast<VectorUnrollOpInterface>(*loadOp);
819 Location loc = loadOp.getLoc();
820 ArrayRef<int64_t> originalShape = vecType.getShape();
821 SmallVector<int64_t> strides(targetShape->size(), 1);
823 Value
result = arith::ConstantOp::create(rewriter, loc, vecType,
826 SmallVector<int64_t> loopOrder =
827 loadOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
830 VectorType::get(*targetShape, vecType.getElementType());
832 for (SmallVector<int64_t> offsets :
833 StaticTileOffsetRange(originalShape, *targetShape, loopOrder)) {
836 Value slicedLoad = vector::LoadOp::create(rewriter, loc, targetVecType,
839 loc, slicedLoad,
result, offsets, strides);
846 vector::UnrollVectorOptions options;
850 UnrollStorePattern(MLIRContext *context,
851 const vector::UnrollVectorOptions &options,
852 PatternBenefit benefit = 1)
853 : OpRewritePattern<vector::StoreOp>(context, benefit), options(options) {}
855 LogicalResult matchAndRewrite(vector::StoreOp storeOp,
856 PatternRewriter &rewriter)
const override {
857 VectorType vecType = storeOp.getVectorType();
860 auto iface = cast<VectorUnrollOpInterface>(*storeOp);
865 Location loc = storeOp.getLoc();
866 ArrayRef<int64_t> originalShape = vecType.getShape();
867 SmallVector<int64_t> strides(targetShape->size(), 1);
869 Value base = storeOp.getBase();
870 Value vector = storeOp.getValueToStore();
872 SmallVector<int64_t> loopOrder =
873 storeOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
875 for (SmallVector<int64_t> offsets :
876 StaticTileOffsetRange(originalShape, *targetShape, loopOrder)) {
880 loc, vector, offsets, *targetShape, strides);
881 vector::StoreOp::create(rewriter, loc,
slice, base,
indices);
888 vector::UnrollVectorOptions options;
891struct UnrollBroadcastPattern :
public OpRewritePattern<vector::BroadcastOp> {
892 UnrollBroadcastPattern(MLIRContext *context,
893 const vector::UnrollVectorOptions &options,
894 PatternBenefit benefit = 1)
895 : OpRewritePattern<vector::BroadcastOp>(context, benefit),
898 LogicalResult matchAndRewrite(vector::BroadcastOp broadcastOp,
899 PatternRewriter &rewriter)
const override {
901 auto iface = cast<VectorUnrollOpInterface>(*broadcastOp);
906 Location loc = broadcastOp.getLoc();
907 VectorType srcType = dyn_cast<VectorType>(broadcastOp.getSourceType());
908 VectorType resType = broadcastOp.getResultVectorType();
910 SmallVector<int64_t> originalShape =
911 *broadcastOp.getIterationShapeToUnroll();
914 SmallVector<int64_t> adjustedTargetShape(originalShape.size(), 1);
915 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
917 VectorType targetType =
918 resType.cloneWith(adjustedTargetShape, resType.getElementType());
919 Value
result = arith::ConstantOp::create(rewriter, loc, resType,
922 SmallVector<int64_t> strides(originalShape.size(), 1);
924 for (SmallVector<int64_t> offsets :
925 StaticTileOffsetRange(originalShape, adjustedTargetShape)) {
929 newSrc = broadcastOp.getSource();
932 int64_t rank = srcType.getRank();
933 SmallVector<int64_t> srcOffsets(offsets.end() - rank, offsets.end());
934 SmallVector<int64_t> srcShape(adjustedTargetShape.end() - rank,
935 adjustedTargetShape.end());
936 SmallVector<int64_t> srcStrides(strides.end() - rank, strides.end());
938 for (int64_t i = 0; i < rank; ++i) {
939 if (srcType.getDimSize(i) == 1) {
944 newSrc = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
945 loc, broadcastOp.getSource(), srcOffsets, srcShape, srcStrides);
960 vector::UnrollVectorOptions options;
980struct UnrollToElements final :
public OpRewritePattern<vector::ToElementsOp> {
981 UnrollToElements(MLIRContext *context,
982 const vector::UnrollVectorOptions &options,
983 PatternBenefit benefit = 1)
984 : OpRewritePattern<vector::ToElementsOp>(context, benefit),
987 LogicalResult matchAndRewrite(vector::ToElementsOp op,
988 PatternRewriter &rewriter)
const override {
991 FailureOr<SmallVector<Value>>
result =
996 SmallVector<Value> vectors = *
result;
998 SmallVector<Value> results;
999 for (Value vector : vectors) {
1001 vector::ToElementsOp::create(rewriter, op.getLoc(), vector);
1002 llvm::append_range(results, subElements.getResults());
1009 vector::UnrollVectorOptions options;
1039 UnrollStepPattern(MLIRContext *context,
1040 const vector::UnrollVectorOptions &options,
1041 PatternBenefit benefit = 1)
1042 : OpRewritePattern<vector::StepOp>(context, benefit), options(options) {}
1044 LogicalResult matchAndRewrite(vector::StepOp stepOp,
1045 PatternRewriter &rewriter)
const override {
1047 auto iface = cast<VectorUnrollOpInterface>(*stepOp);
1048 std::optional<SmallVector<int64_t>> targetShape =
1053 VectorType vecType = stepOp.getType();
1054 if (vecType.isScalable()) {
1058 int64_t originalSize = vecType.getShape()[0];
1059 Location loc = stepOp.getLoc();
1060 SmallVector<int64_t> strides(1, 1);
1062 Value
result = arith::ConstantOp::create(rewriter, loc, vecType,
1065 auto targetVecType =
1066 VectorType::get(*targetShape, vecType.getElementType());
1067 Value baseStep = vector::StepOp::create(rewriter, loc, targetVecType);
1068 for (
const SmallVector<int64_t> &offsets :
1069 StaticTileOffsetRange({originalSize}, *targetShape)) {
1070 Value bcastOffset = arith::ConstantOp::create(
1071 rewriter, loc, targetVecType,
1074 IntegerAttr::get(targetVecType.getElementType(), offsets[0])));
1076 arith::AddIOp::create(rewriter, loc, baseStep, bcastOffset);
1079 loc, tileStep,
result, offsets, strides);
1086 vector::UnrollVectorOptions options;
1107 UnrollFromElements(MLIRContext *context,
1108 const vector::UnrollVectorOptions &options,
1109 PatternBenefit benefit = 1)
1110 : OpRewritePattern<vector::FromElementsOp>(context, benefit),
1113 LogicalResult matchAndRewrite(vector::FromElementsOp op,
1114 PatternRewriter &rewriter)
const override {
1117 auto unrollFromElementsFn = [&](PatternRewriter &rewriter, Location loc,
1118 VectorType subTy, int64_t index) {
1119 size_t subTyNumElements = subTy.getNumElements();
1120 assert((index + 1) * subTyNumElements <= allElements.size() &&
1123 allElements.slice(index * subTyNumElements, subTyNumElements);
1124 return vector::FromElementsOp::create(rewriter, loc, subTy, subElements);
1131 vector::UnrollVectorOptions options;
1167struct UnrollCreateMaskPattern :
public OpRewritePattern<vector::CreateMaskOp> {
1168 UnrollCreateMaskPattern(MLIRContext *context,
1169 const vector::UnrollVectorOptions &options,
1170 PatternBenefit benefit = 1)
1171 : OpRewritePattern<vector::CreateMaskOp>(context, benefit),
1174 LogicalResult matchAndRewrite(vector::CreateMaskOp createMaskOp,
1175 PatternRewriter &rewriter)
const override {
1177 auto iface = cast<VectorUnrollOpInterface>(*createMaskOp);
1182 VectorType resultType = createMaskOp.getVectorType();
1183 SmallVector<int64_t> originalSize =
1184 *createMaskOp.getIterationShapeToUnroll();
1185 Location loc = createMaskOp.getLoc();
1189 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
1190 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
1192 Value
result = arith::ConstantOp::create(rewriter, loc, resultType,
1194 VectorType targetVectorType =
1195 VectorType::get(adjustedTargetShape, rewriter.
getI1Type());
1196 SmallVector<int64_t> strides(adjustedTargetShape.size(), 1);
1200 for (SmallVector<int64_t> offsets :
1201 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
1202 SmallVector<Value> unrolledOperands;
1204 for (
auto [i, originalMaskOperand] :
1205 llvm::enumerate(createMaskOp.getOperands())) {
1208 Value adjustedMaskSize = rewriter.
createOrFold<arith::SubIOp>(
1209 loc, originalMaskOperand, offsetVal);
1212 rewriter, loc, adjustedTargetShape[i]);
1214 rewriter.
createOrFold<arith::MaxSIOp>(loc, adjustedMaskSize, zero);
1215 Value unrolledOperand = rewriter.
createOrFold<arith::MinSIOp>(
1216 loc, nonNegative, unrolledDimSize);
1217 unrolledOperands.push_back(unrolledOperand);
1220 auto unrolledMask = rewriter.
createOrFold<vector::CreateMaskOp>(
1221 loc, targetVectorType, unrolledOperands);
1223 loc, unrolledMask,
result, offsets, strides);
1230 vector::UnrollVectorOptions options;
1265struct UnrollConstantMaskPattern
1267 UnrollConstantMaskPattern(MLIRContext *context,
1268 const vector::UnrollVectorOptions &options,
1269 PatternBenefit benefit = 1)
1270 : OpRewritePattern<vector::ConstantMaskOp>(context, benefit),
1273 LogicalResult matchAndRewrite(vector::ConstantMaskOp constantMaskOp,
1274 PatternRewriter &rewriter)
const override {
1276 auto iface = cast<VectorUnrollOpInterface>(*constantMaskOp);
1281 VectorType resultType = constantMaskOp.getVectorType();
1282 SmallVector<int64_t> originalSize =
1283 *constantMaskOp.getIterationShapeToUnroll();
1284 Location loc = constantMaskOp.getLoc();
1288 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
1289 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
1291 Value
result = arith::ConstantOp::create(rewriter, loc, resultType,
1293 VectorType targetVectorType =
1294 VectorType::get(adjustedTargetShape, rewriter.
getI1Type());
1295 SmallVector<int64_t> strides(adjustedTargetShape.size(), 1);
1299 for (
const SmallVector<int64_t> &offsets :
1300 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
1301 SmallVector<int64_t> unrolledMaskDims;
1303 for (
auto [i, originalMaskDim] :
1304 llvm::enumerate(constantMaskOp.getMaskDimSizes())) {
1307 int64_t adjustedMaskSize =
1308 std::max(originalMaskDim - offsets[i],
static_cast<int64_t
>(0));
1309 int64_t unrolledMaskDim =
1310 std::min(adjustedMaskSize, adjustedTargetShape[i]);
1311 unrolledMaskDims.push_back(unrolledMaskDim);
1317 if (llvm::is_contained(unrolledMaskDims, 0))
1318 unrolledMaskDims.assign(unrolledMaskDims.size(), 0);
1320 auto unrolledMask = rewriter.
createOrFold<vector::ConstantMaskOp>(
1321 loc, targetVectorType, unrolledMaskDims);
1323 loc, unrolledMask,
result, offsets, strides);
1330 vector::UnrollVectorOptions options;
1348 if (extractShape.empty() ||
shape.empty() ||
1349 extractShape.size() >
shape.size())
1352 while (extractShape.size() > 1 && extractShape.front() == 1)
1353 extractShape = extractShape.drop_front();
1355 while (
shape.size() > 1 &&
shape.front() == 1) {
1359 size_t rankDiff =
shape.size() - extractShape.size();
1360 if (!llvm::equal(extractShape.drop_front(),
shape.drop_front(rankDiff + 1)))
1363 int64_t extractElements = ShapedType::getNumElements(extractShape);
1364 int64_t shapeElements = ShapedType::getNumElements(
shape);
1365 return shapeElements % extractElements == 0;
1387static std::optional<SmallVector<int64_t>>
1391 int64_t remainingElements = targetElements;
1394 for (
int i = sourceShape.size() - 1; i >= 0 && remainingElements > 1; --i) {
1395 int64_t takeFromDim = std::min(remainingElements, sourceShape[i]);
1396 extractShape.insert(extractShape.begin(), takeFromDim);
1398 if (remainingElements % takeFromDim != 0)
1399 return std::nullopt;
1400 remainingElements /= takeFromDim;
1404 while (extractShape.size() < sourceShape.size())
1405 extractShape.insert(extractShape.begin(), 1);
1407 if (ShapedType::getNumElements(extractShape) != targetElements)
1408 return std::nullopt;
1410 return extractShape;
1426struct ShapeCastReassociationGroup {
1427 int64_t srcBegin, srcEnd;
1428 int64_t resBegin, resEnd;
1434static std::optional<SmallVector<ShapeCastReassociationGroup>>
1439 int64_t srcRank = sourceShape.size(), resRank = resultShape.size();
1440 while (si < srcRank && ri < resRank) {
1441 int64_t srcBegin = si, resBegin = ri;
1442 int64_t srcProd = sourceShape[si++];
1443 int64_t resProd = resultShape[ri++];
1445 while (srcProd != resProd) {
1446 if (srcProd < resProd) {
1448 return std::nullopt;
1449 srcProd *= sourceShape[si++];
1452 return std::nullopt;
1453 resProd *= resultShape[ri++];
1457 while (si < srcRank && sourceShape[si] == 1)
1459 while (ri < resRank && resultShape[ri] == 1)
1461 groups.push_back({srcBegin, si, resBegin, ri});
1463 if (si != srcRank || ri != resRank)
1464 return std::nullopt;
1515struct UnrollShapeCastPattern :
public OpRewritePattern<vector::ShapeCastOp> {
1516 UnrollShapeCastPattern(MLIRContext *context,
1517 const vector::UnrollVectorOptions &options,
1518 PatternBenefit benefit = 1)
1519 : OpRewritePattern<vector::ShapeCastOp>(context, benefit),
1522 LogicalResult matchAndRewrite(vector::ShapeCastOp shapeCastOp,
1523 PatternRewriter &rewriter)
const override {
1525 auto iface = cast<VectorUnrollOpInterface>(*shapeCastOp);
1530 VectorType sourceType = shapeCastOp.getSourceVectorType();
1531 VectorType resultType = shapeCastOp.getResultVectorType();
1532 ArrayRef<int64_t> sourceShape = sourceType.getShape();
1533 ArrayRef<int64_t> resultShape = resultType.getShape();
1537 std::optional<SmallVector<ShapeCastReassociationGroup>> groups =
1538 computeShapeCastGroups(sourceShape, resultShape);
1541 shapeCastOp,
"cannot align source and result reassociation groups");
1545 SmallVector<int64_t> paddedTarget(resultShape.size(), 1);
1546 llvm::copy(*targetShape,
1547 paddedTarget.end() -
static_cast<int64_t
>(targetShape->size()));
1550 SmallVector<int64_t> extractShapeStorage;
1551 for (
const ShapeCastReassociationGroup &g : *groups) {
1552 ArrayRef<int64_t> resSub =
1553 resultShape.slice(g.resBegin, g.resEnd - g.resBegin);
1554 ArrayRef<int64_t> tgtSub = ArrayRef<int64_t>(paddedTarget)
1555 .slice(g.resBegin, g.resEnd - g.resBegin);
1556 if (!isContiguous(tgtSub, resSub))
1558 shapeCastOp,
"target shape is not contiguous within a "
1559 "reassociation group of the result vector shape");
1561 ArrayRef<int64_t> srcSub =
1562 sourceShape.slice(g.srcBegin, g.srcEnd - g.srcBegin);
1563 int64_t groupTargetElements = ShapedType::getNumElements(tgtSub);
1564 std::optional<SmallVector<int64_t>> groupExtract =
1565 calculateSourceExtractShape(srcSub, groupTargetElements);
1568 shapeCastOp,
"cannot extract the target number of elements "
1569 "contiguously from a source reassociation group");
1570 extractShapeStorage.append(groupExtract->begin(), groupExtract->end());
1572 ArrayRef<int64_t> extractShape = extractShapeStorage;
1574 Location loc = shapeCastOp.getLoc();
1577 Value
result = arith::ConstantOp::create(rewriter, loc, resultType,
1580 VectorType targetType =
1581 VectorType::get(*targetShape, sourceType.getElementType());
1584 SmallVector<int64_t> insertStrides(targetShape->size(), 1);
1586 for (SmallVector<int64_t> resultOffsets :
1587 StaticTileOffsetRange(resultShape, *targetShape)) {
1588 SmallVector<int64_t> sourceOffsets =
1589 calculateSourceOffsets(resultOffsets, sourceShape, resultShape);
1590 Value sourceChunk = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
1591 loc, shapeCastOp.getSource(), sourceOffsets, extractShape,
1593 Value targetChunk = rewriter.
createOrFold<vector::ShapeCastOp>(
1594 loc, targetType, sourceChunk);
1596 loc, targetChunk,
result, resultOffsets, insertStrides);
1604 vector::UnrollVectorOptions options;
1622 UnrollBitCastPattern(MLIRContext *context,
1623 const vector::UnrollVectorOptions &options,
1624 PatternBenefit benefit = 1)
1625 : OpRewritePattern<vector::BitCastOp>(context, benefit),
1628 LogicalResult matchAndRewrite(vector::BitCastOp bitCastOp,
1629 PatternRewriter &rewriter)
const override {
1631 auto iface = cast<VectorUnrollOpInterface>(*bitCastOp);
1635 "failed to get target shape");
1637 VectorType sourceType = bitCastOp.getSourceVectorType();
1638 VectorType resultType = bitCastOp.getResultVectorType();
1639 ArrayRef<int64_t> resultShape = resultType.getShape();
1640 Location loc = bitCastOp.getLoc();
1642 if (targetShape->size() != resultShape.size())
1644 bitCastOp,
"target shape rank must match result rank");
1646 unsigned sourceElementBits = sourceType.getElementTypeBitWidth();
1647 unsigned resultElementBits = resultType.getElementTypeBitWidth();
1649 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1650 targetShape->end());
1651 int64_t lastDim = sourceSliceShape.size() - 1;
1653 sourceSliceShape[lastDim] =
1654 ((*targetShape)[lastDim] * resultElementBits) / sourceElementBits;
1656 Value
result = arith::ConstantOp::create(rewriter, loc, resultType,
1658 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1659 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1661 VectorType targetType =
1662 VectorType::get(*targetShape, resultType.getElementType());
1664 for (SmallVector<int64_t> resultOffsets :
1665 StaticTileOffsetRange(resultShape, *targetShape)) {
1666 SmallVector<int64_t> sourceOffsets = resultOffsets;
1667 sourceOffsets[lastDim] =
1668 (resultOffsets[lastDim] * resultElementBits) / sourceElementBits;
1670 Value sourceSlice = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
1671 loc, bitCastOp.getSource(), sourceOffsets, sourceSliceShape,
1673 Value bitcastSlice = rewriter.
createOrFold<vector::BitCastOp>(
1674 loc, targetType, sourceSlice);
1676 loc, bitcastSlice,
result, resultOffsets, resultStrides);
1684 vector::UnrollVectorOptions options;
1704struct UnrollInterleavePattern :
public OpRewritePattern<vector::InterleaveOp> {
1705 UnrollInterleavePattern(MLIRContext *context,
1706 const vector::UnrollVectorOptions &options,
1707 PatternBenefit benefit = 1)
1708 : OpRewritePattern<vector::InterleaveOp>(context, benefit),
1711 LogicalResult matchAndRewrite(vector::InterleaveOp interleaveOp,
1712 PatternRewriter &rewriter)
const override {
1714 auto iface = cast<VectorUnrollOpInterface>(*interleaveOp);
1718 "failed to get target shape");
1720 VectorType resultType = interleaveOp.getResultVectorType();
1721 ArrayRef<int64_t> resultShape = resultType.getShape();
1722 Location loc = interleaveOp.getLoc();
1724 if (targetShape->size() != resultShape.size())
1726 interleaveOp,
"target shape rank must match result rank");
1728 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1729 targetShape->end());
1730 int64_t lastDim = sourceSliceShape.size() - 1;
1731 sourceSliceShape[lastDim] = (*targetShape)[lastDim] / 2;
1733 Value
result = arith::ConstantOp::create(rewriter, loc, resultType,
1735 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1736 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1738 VectorType targetType =
1739 VectorType::get(*targetShape, resultType.getElementType());
1741 for (SmallVector<int64_t> resultOffsets :
1742 StaticTileOffsetRange(resultShape, *targetShape)) {
1743 SmallVector<int64_t> sourceOffsets = resultOffsets;
1744 sourceOffsets[lastDim] = resultOffsets[lastDim] / 2;
1746 Value lhsSlice = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
1747 loc, interleaveOp.getLhs(), sourceOffsets, sourceSliceShape,
1749 Value rhsSlice = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
1750 loc, interleaveOp.getRhs(), sourceOffsets, sourceSliceShape,
1752 Value interleaveSlice = rewriter.
createOrFold<vector::InterleaveOp>(
1753 loc, targetType, lhsSlice, rhsSlice);
1755 loc, interleaveSlice,
result, resultOffsets, resultStrides);
1763 vector::UnrollVectorOptions options;
1784struct UnrollDeinterleavePattern
1786 UnrollDeinterleavePattern(MLIRContext *context,
1787 const vector::UnrollVectorOptions &options,
1788 PatternBenefit benefit = 1)
1789 : OpRewritePattern<vector::DeinterleaveOp>(context, benefit),
1792 LogicalResult matchAndRewrite(vector::DeinterleaveOp deinterleaveOp,
1793 PatternRewriter &rewriter)
const override {
1795 auto iface = cast<VectorUnrollOpInterface>(*deinterleaveOp);
1799 "failed to get target shape");
1801 VectorType resultType = deinterleaveOp.getResultVectorType();
1802 ArrayRef<int64_t> resultShape = resultType.getShape();
1803 Location loc = deinterleaveOp.getLoc();
1805 if (targetShape->size() != resultShape.size())
1807 deinterleaveOp,
"target shape rank must match result rank");
1809 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1810 targetShape->end());
1811 int64_t lastDim = sourceSliceShape.size() - 1;
1812 sourceSliceShape[lastDim] = (*targetShape)[lastDim] * 2;
1814 Value resultOdd = arith::ConstantOp::create(
1815 rewriter, loc, resultType, rewriter.
getZeroAttr(resultType));
1816 Value resultEven = arith::ConstantOp::create(
1817 rewriter, loc, resultType, rewriter.
getZeroAttr(resultType));
1818 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1819 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1821 for (SmallVector<int64_t> resultOffsets :
1822 StaticTileOffsetRange(resultShape, *targetShape)) {
1823 SmallVector<int64_t> sourceOffsets = resultOffsets;
1824 sourceOffsets[lastDim] = resultOffsets[lastDim] * 2;
1826 Value sourceSlice = rewriter.
createOrFold<vector::ExtractStridedSliceOp>(
1827 loc, deinterleaveOp.getSource(), sourceOffsets, sourceSliceShape,
1830 auto deinterleaveSlice =
1831 vector::DeinterleaveOp::create(rewriter, loc, sourceSlice);
1833 resultOdd = rewriter.
createOrFold<vector::InsertStridedSliceOp>(
1834 loc, deinterleaveSlice.getResultEven(), resultOdd, resultOffsets,
1836 resultEven = rewriter.
createOrFold<vector::InsertStridedSliceOp>(
1837 loc, deinterleaveSlice.getResultOdd(), resultEven, resultOffsets,
1846 vector::UnrollVectorOptions options;
1850void mlir::vector::populateVectorUnrollPatterns(
1853 patterns.
add<UnrollTransferReadPattern, UnrollTransferWritePattern,
1854 UnrollContractionPattern, UnrollElementwisePattern,
1855 UnrollReductionPattern, UnrollMultiReductionPattern,
1856 UnrollTransposePattern, UnrollGatherPattern, UnrollLoadPattern,
1857 UnrollStorePattern, UnrollBroadcastPattern, UnrollFromElements,
1858 UnrollToElements, UnrollStepPattern, UnrollShapeCastPattern,
1859 UnrollCreateMaskPattern, UnrollConstantMaskPattern,
1860 UnrollBitCastPattern, UnrollInterleavePattern,
1865void mlir::vector::populateVectorContractUnrollPatterns(
1872void mlir::vector::populateVectorToElementsUnrollPatterns(
1878void mlir::vector::populateVectorFromElementsUnrollPatterns(
static LogicalResult extractStrides(AffineExpr e, AffineExpr multiplicativeFactor, MutableArrayRef< AffineExpr > strides, AffineExpr &offset)
Takes a single AffineExpr e and populates the strides array with the strides expressions for each dim...
static llvm::ManagedStatic< PassManagerOptions > options
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static LogicalResult checkSupportedMaskedTransferUnrolling(TransferOpTy xferOp, PatternRewriter &rewriter)
Fail if xferOp, masked by an enclosing vector.mask, is masked in a way that the transfer unrolling pa...
static SmallVector< Value > sliceLoadStoreIndices(PatternRewriter &rewriter, Location loc, OperandRange originalIndices, ArrayRef< int64_t > offsets)
static Operation * maskTile(PatternRewriter &rewriter, Location loc, Operation *tiledXferOp, vector::MaskingOpInterface maskingOp, ArrayRef< int64_t > offsets, ArrayRef< int64_t > sizes, ArrayRef< int64_t > strides)
Wrap tiledXferOp, the new transfer for one tile, in a vector.mask with the tile of maskingOp's mask (...
static std::optional< SmallVector< int64_t > > getTargetShape(const vector::UnrollVectorOptions &options, VectorUnrollOpInterface &iface, bool allowMasked=false)
Return the target shape for unrolling for the given op, provided through its VectorUnrollOpInterface ...
static Operation * cloneOpWithOperandsAndTypes(OpBuilder &builder, Location loc, Operation *op, ArrayRef< Value > operands, ArrayRef< Type > resultTypes)
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
ArrayRef< AffineExpr > getResults() const
TypedAttr getZeroAttr(Type type)
MLIRContext * getContext() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
This class helps build Operations.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
This class implements the operand iterators for the Operation class.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
MutableArrayRef< OpOperand > getOpOperands()
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
result_range getResults()
unsigned getNumResults()
Return the number of results held by this operation.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
RewritePattern is the common base class for all DAG to DAG replacements.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
FailureOr< SmallVector< Value > > unrollVectorValue(TypedValue< VectorType >, RewriterBase &)
Generic utility for unrolling values of type vector<NxAxBx...> to N values of type vector<AxBx....
LogicalResult unrollVectorOp(Operation *op, PatternRewriter &rewriter, UnrollVectorOpFn unrollFn)
Include the generated interface declarations.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
SmallVector< T > applyPermutationMap(AffineMap map, llvm::ArrayRef< T > source)
Apply a permutation from map to source and return the result.
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.
A pattern for ops that implement MaskableOpInterface and that might be masked (i.e.
Options that control the vector unrolling.