29#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/Debug.h"
35#define GEN_PASS_DEF_AFFINEVECTORIZE
36#include "mlir/Dialect/Affine/Transforms/Passes.h.inc"
578#define DEBUG_TYPE "early-vect"
585 int fastestVaryingMemRefDimension);
591static std::optional<NestedPattern>
595 int64_t d0 = fastestVaryingPattern.empty() ? -1 : fastestVaryingPattern[0];
596 int64_t d1 = fastestVaryingPattern.size() < 2 ? -1 : fastestVaryingPattern[1];
597 int64_t d2 = fastestVaryingPattern.size() < 3 ? -1 : fastestVaryingPattern[2];
598 switch (vectorRank) {
616 llvm::IsaPred<vector::TransferReadOp, vector::TransferWriteOp>);
624struct Vectorize :
public affine::impl::AffineVectorizeBase<Vectorize> {
627 void runOnOperation()
override;
633 unsigned patternDepth,
634 VectorizationStrategy *strategy) {
635 assert(patternDepth > depthInPattern &&
636 "patternDepth is greater than depthInPattern");
637 if (patternDepth - depthInPattern > strategy->vectorSizes.size()) {
641 strategy->loopToVectorDim[loop] =
642 strategy->vectorSizes.size() - (patternDepth - depthInPattern);
661 unsigned depthInPattern,
662 unsigned patternDepth,
663 VectorizationStrategy *strategy) {
664 for (
auto m : matches) {
666 patternDepth, strategy))) {
670 patternDepth, strategy);
679struct VectorizationState {
692 void registerOpVectorReplacement(Operation *replaced, Operation *
replacement);
705 void registerValueVectorReplacement(Value replaced, Operation *
replacement);
712 void registerBlockArgVectorReplacement(BlockArgument replaced,
725 void registerValueScalarReplacement(Value replaced, Value
replacement);
737 void registerLoopResultScalarReplacement(Value replaced, Value
replacement);
741 void getScalarValueReplacementsFor(
ValueRange inputVals,
742 SmallVectorImpl<Value> &replacedVals);
745 void finishVectorizationPattern(AffineForOp rootLoop);
754 IRMapping valueVectorReplacement;
757 IRMapping valueScalarReplacement;
759 DenseMap<Value, Value> loopResultScalarReplacement;
769 const VectorizationStrategy *strategy =
nullptr;
774 void registerValueVectorReplacementImpl(Value replaced, Value
replacement);
788void VectorizationState::registerOpVectorReplacement(
Operation *replaced,
790 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ commit vectorized op:\n");
791 LLVM_DEBUG(dbgs() << *replaced <<
"\n");
792 LLVM_DEBUG(dbgs() <<
"into\n");
796 "Unexpected replaced and replacement results");
797 assert(opVectorReplacement.count(replaced) == 0 &&
"already registered");
800 for (
auto resultTuple :
802 registerValueVectorReplacementImpl(std::get<0>(resultTuple),
803 std::get<1>(resultTuple));
817void VectorizationState::registerValueVectorReplacement(
820 "Expected single-result replacement");
821 registerValueVectorReplacementImpl(replaced,
replacement->getResult(0));
829void VectorizationState::registerBlockArgVectorReplacement(
830 BlockArgument replaced, BlockArgument
replacement) {
831 registerValueVectorReplacementImpl(replaced,
replacement);
834void VectorizationState::registerValueVectorReplacementImpl(Value replaced,
836 assert(!valueVectorReplacement.
contains(replaced) &&
837 "Vector replacement already registered");
839 "Expected vector type in vector replacement");
853void VectorizationState::registerValueScalarReplacement(Value replaced,
855 assert(!valueScalarReplacement.
contains(replaced) &&
856 "Scalar value replacement already registered");
858 "Expected scalar type in scalar replacement");
871void VectorizationState::registerLoopResultScalarReplacement(
874 assert(loopResultScalarReplacement.count(replaced) == 0 &&
875 "already registered");
876 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ will replace a result of the loop "
879 loopResultScalarReplacement[replaced] =
replacement;
883void VectorizationState::getScalarValueReplacementsFor(
884 ValueRange inputVals, SmallVectorImpl<Value> &replacedVals) {
885 for (Value inputVal : inputVals)
886 replacedVals.push_back(valueScalarReplacement.
lookupOrDefault(inputVal));
891 LLVM_DEBUG(dbgs() <<
"[early-vect]+++++ erasing:\n" << forOp <<
"\n");
900 LLVM_DEBUG(dbgs() <<
"[early-vect]+++++ erasing user:\n" << *user <<
"\n");
906void VectorizationState::finishVectorizationPattern(AffineForOp rootLoop) {
907 LLVM_DEBUG(dbgs() <<
"\n[early-vect] Finalizing vectorization\n");
914 VectorizationState &state,
919 auto afOp = AffineApplyOp::create(state.builder, op->
getLoc(), singleResMap,
921 results.push_back(afOp);
930 int fastestVaryingMemRefDimension) {
931 return [¶llelLoops, fastestVaryingMemRefDimension](
Operation &forOp) {
932 auto loop = cast<AffineForOp>(forOp);
933 if (!parallelLoops.contains(loop))
936 auto vectorizableBody =
938 if (!vectorizableBody)
940 return memRefDim == -1 || fastestVaryingMemRefDimension == -1 ||
941 memRefDim == fastestVaryingMemRefDimension;
948 const VectorizationStrategy *strategy) {
949 assert(!isa<VectorType>(scalarTy) &&
"Expected scalar type");
950 return VectorType::get(strategy->vectorSizes, scalarTy);
957 VectorizationState &state) {
958 Type scalarTy = constOp.getType();
959 if (!VectorType::isValidElementType(scalarTy))
968 while (parentOp && !state.vecLoopToVecDim.count(parentOp))
970 assert(parentOp && state.vecLoopToVecDim.count(parentOp) &&
971 isa<AffineForOp>(parentOp) &&
"Expected a vectorized for op");
972 auto vecForOp = cast<AffineForOp>(parentOp);
975 arith::ConstantOp::create(state.builder, constOp.getLoc(), vecAttr);
978 state.registerOpVectorReplacement(constOp, newConstOp);
985 if (isa<IndexType>(scalarTy)) {
986 auto scalarConstOp = arith::ConstantOp::create(
987 state.builder, constOp.getLoc(), constOp.getValue());
988 state.registerValueScalarReplacement(constOp.getResult(),
989 scalarConstOp.getResult());
998 VectorizationState &state) {
1000 for (
Value operand : applyOp.getOperands()) {
1001 if (state.valueVectorReplacement.
contains(operand)) {
1003 dbgs() <<
"\n[early-vect]+++++ affine.apply on vector operand\n");
1007 if (!updatedOperand)
1008 updatedOperand = operand;
1009 updatedOperands.push_back(updatedOperand);
1012 auto newApplyOp = AffineApplyOp::create(
1013 state.builder, applyOp.getLoc(), applyOp.getAffineMap(), updatedOperands);
1016 state.registerValueScalarReplacement(applyOp.getResult(),
1017 newApplyOp.getResult());
1026 VectorizationState &state) {
1028 if (!VectorType::isValidElementType(scalarTy))
1031 Attribute valueAttr = getIdentityValueAttr(
1032 reductionKind, scalarTy, state.builder, oldOperand.
getLoc());
1036 arith::ConstantOp::create(state.builder, oldOperand.
getLoc(), vecAttr);
1049 assert(state.strategy->vectorSizes.size() == 1 &&
1050 "Creating a mask non-1-D vectors is not supported.");
1051 assert(vecForOp.getStep() == state.strategy->vectorSizes[0] &&
1052 "Creating a mask for loops with non-unit original step size is not "
1056 if (
Value mask = state.vecLoopToMask.lookup(vecForOp))
1061 if (vecForOp.hasConstantBounds()) {
1063 vecForOp.getConstantUpperBound() - vecForOp.getConstantLowerBound();
1064 if (originalTripCount % vecForOp.getStepAsInt() == 0)
1085 AffineMap ubMap = vecForOp.getUpperBoundMap();
1088 ub = AffineApplyOp::create(state.builder, loc, vecForOp.getUpperBoundMap(),
1089 vecForOp.getUpperBoundOperands());
1091 ub = AffineMinOp::create(state.builder, loc, vecForOp.getUpperBoundMap(),
1092 vecForOp.getUpperBoundOperands());
1098 {ub, vecForOp.getInductionVar()});
1101 ub.getDefiningOp()->erase();
1103 Type maskTy = VectorType::get(state.strategy->vectorSizes,
1106 vector::CreateMaskOp::create(state.builder, loc, maskTy, itersLeft);
1108 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ creating a mask:\n"
1109 << itersLeft <<
"\n"
1112 state.vecLoopToMask[vecForOp] = mask;
1122 const VectorizationStrategy *strategy) {
1124 if (forOp && strategy->loopToVectorDim.count(forOp) == 0)
1127 for (
auto loopToDim : strategy->loopToVectorDim) {
1128 auto loop = cast<AffineForOp>(loopToDim.first);
1129 if (!loop.isDefinedOutsideOfLoop(value))
1139 VectorizationState &state) {
1141 Value uniformScalarRepl =
1146 auto bcastOp = BroadcastOp::create(state.builder, uniformVal.
getLoc(),
1147 vectorTy, uniformScalarRepl);
1148 state.registerValueVectorReplacement(uniformVal, bcastOp);
1170 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ vectorize operand: " << operand);
1173 LLVM_DEBUG(dbgs() <<
" -> already vectorized: " << vecRepl);
1180 assert(!isa<VectorType>(operand.
getType()) &&
1181 "Vector op not found in replacement map");
1184 if (
auto constOp = operand.
getDefiningOp<arith::ConstantOp>()) {
1186 LLVM_DEBUG(dbgs() <<
"-> constant: " << vecConstant);
1187 return vecConstant.getResult();
1193 LLVM_DEBUG(dbgs() <<
"-> uniform: " << *vecUniform);
1200 LLVM_DEBUG(dbgs() <<
"-> unsupported block argument\n");
1203 LLVM_DEBUG(dbgs() <<
"-> non-vectorizable\n");
1212 for (
auto &kvp : loopToVectorDim) {
1213 AffineForOp forOp = cast<AffineForOp>(kvp.first);
1218 unsigned nonInvariant = 0;
1220 if (invariants.count(idx))
1223 if (++nonInvariant > 1) {
1224 LLVM_DEBUG(dbgs() <<
"[early‑vect] Bail out: IV "
1225 << forOp.getInductionVar() <<
" drives "
1226 << nonInvariant <<
" indices\n");
1241 VectorizationState &state) {
1242 MemRefType memRefType = loadOp.getMemRefType();
1243 Type elementType = memRefType.getElementType();
1244 auto vectorType = VectorType::get(state.strategy->vectorSizes, elementType);
1248 state.getScalarValueReplacementsFor(loadOp.getMapOperands(), mapOperands);
1252 indices.reserve(memRefType.getRank());
1253 if (loadOp.getAffineMap() !=
1256 for (
auto op : mapOperands) {
1257 if (op.getDefiningOp<AffineApplyOp>())
1263 indices.append(mapOperands.begin(), mapOperands.end());
1271 indices, state.vecLoopToVecDim);
1272 if (!permutationMap) {
1273 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ can't compute permutationMap\n");
1276 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ permutationMap: ");
1277 LLVM_DEBUG(permutationMap.print(dbgs()));
1280 state.builder, loadOp.getLoc(), loadOp.getMemRef(), vectorType,
1286 state.registerOpVectorReplacement(loadOp, transfer);
1297 VectorizationState &state) {
1298 MemRefType memRefType = storeOp.getMemRefType();
1305 state.getScalarValueReplacementsFor(storeOp.getMapOperands(), mapOperands);
1309 indices.reserve(memRefType.getRank());
1310 if (storeOp.getAffineMap() !=
1315 indices.append(mapOperands.begin(), mapOperands.end());
1322 indices, state.vecLoopToVecDim);
1323 if (!permutationMap)
1325 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ permutationMap: ");
1326 LLVM_DEBUG(permutationMap.print(dbgs()));
1330 if (llvm::any_of(permutationMap.getResults(),
1331 llvm::IsaPred<AffineConstantExpr>)) {
1332 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ store permutation map has "
1333 "broadcast dims, bailing out\n");
1338 state.builder, storeOp.getLoc(), vectorValue, storeOp.getMemRef(),
1340 false, permutationMap);
1341 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ vectorized store: " << *transfer);
1344 state.registerOpVectorReplacement(storeOp, transfer);
1351 Value value, VectorizationState &state) {
1353 if (!VectorType::isValidElementType(scalarTy))
1355 Attribute valueAttr = getIdentityValueAttr(reductionKind, scalarTy,
1356 state.builder, value.
getLoc());
1357 if (
auto constOp = value.
getDefiningOp<arith::ConstantOp>())
1358 return constOp.getValue() == valueAttr;
1369 VectorizationState &state) {
1370 const VectorizationStrategy &strategy = *state.strategy;
1371 auto loopToVecDimIt = strategy.loopToVectorDim.find(forOp);
1372 bool isLoopVecDim = loopToVecDimIt != strategy.loopToVectorDim.end();
1375 if (isLoopVecDim && forOp.getNumIterOperands() > 0 && forOp.getStep() != 1) {
1378 <<
"\n[early-vect]+++++ unsupported step size for reduction loop: "
1379 << forOp.getStep() <<
"\n");
1388 unsigned vectorDim = loopToVecDimIt->second;
1389 assert(vectorDim < strategy.vectorSizes.size() &&
"vector dim overflow");
1390 int64_t forOpVecFactor = strategy.vectorSizes[vectorDim];
1391 newStep = forOp.getStepAsInt() * forOpVecFactor;
1393 newStep = forOp.getStepAsInt();
1398 if (isLoopVecDim && forOp.getNumIterOperands() > 0) {
1399 auto it = strategy.reductionLoops.find(forOp);
1400 assert(it != strategy.reductionLoops.end() &&
1401 "Reduction descriptors not found when vectorizing a reduction loop");
1402 reductions = it->second;
1403 assert(reductions.size() == forOp.getNumIterOperands() &&
1404 "The size of reductions array must match the number of iter_args");
1409 if (!isLoopVecDim) {
1410 for (
auto operand : forOp.getInits())
1416 for (
auto redAndOperand : llvm::zip(reductions, forOp.getInits())) {
1418 std::get<0>(redAndOperand).kind, std::get<1>(redAndOperand), state));
1426 state.getScalarValueReplacementsFor(forOp.getLowerBoundOperands(),
1428 state.getScalarValueReplacementsFor(forOp.getUpperBoundOperands(),
1430 auto vecForOp = AffineForOp::create(
1431 state.builder, forOp.getLoc(), lbOperands, forOp.getLowerBoundMap(),
1432 ubOperands, forOp.getUpperBoundMap(), newStep, vecIterOperands,
1451 state.registerOpVectorReplacement(forOp, vecForOp);
1452 state.registerValueScalarReplacement(forOp.getInductionVar(),
1453 vecForOp.getInductionVar());
1454 for (
auto iterTuple :
1455 llvm ::zip(forOp.getRegionIterArgs(), vecForOp.getRegionIterArgs()))
1456 state.registerBlockArgVectorReplacement(std::get<0>(iterTuple),
1457 std::get<1>(iterTuple));
1460 for (
unsigned i = 0; i < vecForOp.getNumIterOperands(); ++i) {
1464 vecForOp.getLoc(), vecForOp.getResult(i));
1465 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ creating a vector reduction: "
1469 Value origInit = forOp.getOperand(forOp.getNumControlOperands() + i);
1470 Value finalRes = reducedRes;
1474 reducedRes.
getLoc(), reducedRes, origInit);
1475 state.registerLoopResultScalarReplacement(forOp.getResult(i), finalRes);
1480 state.vecLoopToVecDim[vecForOp] = loopToVecDimIt->second;
1488 if (isLoopVecDim && forOp.getNumIterOperands() > 0)
1500 vectorTypes.push_back(
1501 VectorType::get(state.strategy->vectorSizes,
result.getType()));
1507 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ an operand failed vectorize\n");
1510 vectorOperands.push_back(vecOperand);
1523 state.registerOpVectorReplacement(op, vecOp);
1532 VectorizationState &state) {
1545 if (
Value mask = state.vecLoopToMask.lookup(newParentOp)) {
1550 cast<AffineForOp>(newParentOp).getRegionIterArgs(), i, combinerOps);
1551 assert(reducedVal &&
"expect non-null value for parallel reduction loop");
1552 assert(combinerOps.size() == 1 &&
"expect only one combiner op");
1554 Value neutralVal = cast<AffineForOp>(newParentOp).getInits()[i];
1556 Value maskedReducedVal = arith::SelectOp::create(
1557 state.builder, reducedVal.
getLoc(), mask, reducedVal, neutralVal);
1559 dbgs() <<
"\n[early-vect]+++++ masking an input to a binary op that"
1560 "produces value for a yield Op: "
1561 << maskedReducedVal);
1562 combinerOps.back()->replaceUsesOfWith(reducedVal, maskedReducedVal);
1580 VectorizationState &state) {
1582 assert(!isa<vector::TransferReadOp>(op) &&
1583 "vector.transfer_read cannot be further vectorized");
1584 assert(!isa<vector::TransferWriteOp>(op) &&
1585 "vector.transfer_write cannot be further vectorized");
1587 if (
auto loadOp = dyn_cast<AffineLoadOp>(op))
1589 if (
auto storeOp = dyn_cast<AffineStoreOp>(op))
1591 if (
auto forOp = dyn_cast<AffineForOp>(op))
1593 if (
auto yieldOp = dyn_cast<AffineYieldOp>(op))
1595 if (
auto constant = dyn_cast<arith::ConstantOp>(op))
1597 if (
auto applyOp = dyn_cast<AffineApplyOp>(op))
1615 assert(currentLevel <= loops.size() &&
"Unexpected currentLevel");
1616 if (currentLevel == loops.size())
1617 loops.emplace_back();
1641 const VectorizationStrategy &strategy) {
1642 assert(loops[0].size() == 1 &&
"Expected single root loop");
1643 AffineForOp rootLoop = loops[0][0];
1644 VectorizationState state(rootLoop.getContext());
1646 state.strategy = &strategy;
1656 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ loop is not vectorizable");
1669 LLVM_DEBUG(dbgs() <<
"[early-vect]+++++ Vectorizing: " << *op);
1673 dbgs() <<
"[early-vect]+++++ failed vectorizing the operation: "
1681 if (opVecResult.wasInterrupted()) {
1682 LLVM_DEBUG(dbgs() <<
"[early-vect]+++++ failed vectorization for: "
1683 << rootLoop <<
"\n");
1685 auto vecRootLoopIt = state.opVectorReplacement.find(rootLoop);
1686 if (vecRootLoopIt != state.opVectorReplacement.end()) {
1687 auto vecRootLoop = cast<AffineForOp>(vecRootLoopIt->second);
1697 for (
auto resPair : state.loopResultScalarReplacement)
1698 resPair.first.replaceAllUsesWith(resPair.second);
1700 assert(state.opVectorReplacement.count(rootLoop) == 1 &&
1701 "Expected vector replacement for loop nest");
1702 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ success vectorizing pattern");
1703 LLVM_DEBUG(dbgs() <<
"\n[early-vect]+++++ vectorization result:\n"
1704 << *state.opVectorReplacement[rootLoop]);
1707 state.finishVectorizationPattern(rootLoop);
1715 const VectorizationStrategy &strategy) {
1716 std::vector<SmallVector<AffineForOp, 2>> loopsToVectorize;
1728 assert(intersectionBuckets.empty() &&
"Expected empty output");
1733 AffineForOp matchRoot = cast<AffineForOp>(match.getMatchedOperation());
1734 bool intersects =
false;
1735 for (
int i = 0, end = intersectionBuckets.size(); i < end; ++i) {
1736 AffineForOp bucketRoot = bucketRoots[i];
1738 if (bucketRoot->isAncestor(matchRoot)) {
1739 intersectionBuckets[i].push_back(match);
1745 if (matchRoot->isAncestor(bucketRoot)) {
1746 bucketRoots[i] = matchRoot;
1747 intersectionBuckets[i].push_back(match);
1756 bucketRoots.push_back(matchRoot);
1757 intersectionBuckets.emplace_back();
1758 intersectionBuckets.back().push_back(match);
1773 assert((reductionLoops.empty() || vectorSizes.size() == 1) &&
1774 "Vectorizing reductions is supported only for 1-D vectors");
1777 std::optional<NestedPattern> pattern =
1778 makePattern(loops, vectorSizes.size(), fastestVaryingPattern);
1780 LLVM_DEBUG(dbgs() <<
"\n[early-vect] pattern couldn't be computed\n");
1784 LLVM_DEBUG(dbgs() <<
"\n******************************************");
1785 LLVM_DEBUG(dbgs() <<
"\n******************************************");
1786 LLVM_DEBUG(dbgs() <<
"\n[early-vect] new pattern on parent op\n");
1787 LLVM_DEBUG(dbgs() << *parentOp <<
"\n");
1789 unsigned patternDepth = pattern->getDepth();
1794 pattern->match(parentOp, &allMatches);
1795 std::vector<SmallVector<NestedMatch, 8>> intersectionBuckets;
1801 for (
auto &intersectingMatches : intersectionBuckets) {
1803 VectorizationStrategy strategy;
1805 strategy.vectorSizes.assign(vectorSizes.begin(), vectorSizes.end());
1806 strategy.reductionLoops = reductionLoops;
1808 patternDepth, &strategy))) {
1822 LLVM_DEBUG(dbgs() <<
"\n");
1825void affine::vectorizeChildAffineLoops(
1826 Operation *parentOp,
bool vectorizeReductions,
1827 ArrayRef<int64_t> vectorSizes, ArrayRef<int64_t> fastestVaryingPattern) {
1833 if (vectorizeReductions) {
1834 parentOp->
walk([¶llelLoops, &reductionLoops](AffineForOp loop) {
1835 SmallVector<LoopReduction, 2> reductions;
1836 if (isLoopParallel(loop, &reductions)) {
1837 parallelLoops.insert(loop);
1839 if (!reductions.empty())
1840 reductionLoops[loop] = reductions;
1844 parentOp->
walk([¶llelLoops](AffineForOp loop) {
1845 if (isLoopParallel(loop))
1846 parallelLoops.insert(loop);
1851 NestedPatternContext mlContext;
1852 vectorizeLoops(parentOp, parallelLoops, vectorSizes, fastestVaryingPattern,
1858void Vectorize::runOnOperation() {
1859 func::FuncOp f = getOperation();
1860 if (vectorSizes.empty()) {
1861 f.emitError(
"The 'virtual-vector-size' option must be specified.");
1862 return signalPassFailure();
1865 if (llvm::any_of(vectorSizes, [](int64_t size) {
return size <= 0; })) {
1867 "The 'virtual-vector-size' option must contain only positive values.");
1868 return signalPassFailure();
1871 if (!fastestVaryingPattern.empty() &&
1872 fastestVaryingPattern.size() != vectorSizes.size()) {
1873 f.emitRemark(
"Fastest varying pattern specified with different size than "
1874 "the vector size.");
1875 return signalPassFailure();
1878 if (vectorizeReductions && vectorSizes.size() != 1) {
1879 f.emitError(
"Vectorizing reductions is supported only for 1-D vectors.");
1880 return signalPassFailure();
1883 vectorizeChildAffineLoops(f, vectorizeReductions, vectorSizes,
1884 fastestVaryingPattern);
1900 if (loops[0].size() != 1)
1904 for (
int i = 1, end = loops.size(); i < end; ++i) {
1905 for (AffineForOp loop : loops[i]) {
1908 if (none_of(loops[i - 1], [&](AffineForOp maybeParent) {
1909 return maybeParent->isProperAncestor(loop);
1915 for (AffineForOp sibling : loops[i]) {
1916 if (sibling->isProperAncestor(loop))
1933void mlir::affine::vectorizeAffineLoops(
1935 ArrayRef<int64_t> vectorSizes, ArrayRef<int64_t> fastestVaryingPattern,
1938 NestedPatternContext mlContext;
1939 vectorizeLoops(parentOp, loops, vectorSizes, fastestVaryingPattern,
1978LogicalResult mlir::affine::vectorizeAffineLoopNest(
1979 std::vector<SmallVector<AffineForOp, 2>> &loops,
1980 const VectorizationStrategy &strategy) {
1982 NestedPatternContext mlContext;
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static Operation * vectorizeUniform(Value uniformVal, VectorizationState &state)
Generates a broadcast op for the provided uniform value using the vectorization strategy in 'state'.
static std::optional< NestedPattern > makePattern(const DenseSet< Operation * > ¶llelLoops, int vectorRank, ArrayRef< int64_t > fastestVaryingPattern)
Creates a vectorization pattern from the command line arguments.
static LogicalResult vectorizeRootMatch(NestedMatch m, const VectorizationStrategy &strategy)
Extracts the matched loops and vectorizes them following a topological order.
static void vectorizeLoopIfProfitable(Operation *loop, unsigned depthInPattern, unsigned patternDepth, VectorizationStrategy *strategy)
static LogicalResult verifyLoopNesting(const std::vector< SmallVector< AffineForOp, 2 > > &loops)
Verify that affine loops in 'loops' meet the nesting criteria expected by SuperVectorizer:
static Operation * vectorizeOneOperation(Operation *op, VectorizationState &state)
Encodes Operation-specific behavior for vectorization.
static bool isNeutralElementConst(arith::AtomicRMWKind reductionKind, Value value, VectorizationState &state)
Returns true if value is a constant equal to the neutral element of the given vectorizable reduction.
static void eraseUsers(Operation *op)
Recursively erases the users of the results of 'op'.
static LogicalResult vectorizeLoopNest(std::vector< SmallVector< AffineForOp, 2 > > &loops, const VectorizationStrategy &strategy)
Internal implementation to vectorize affine loops from a single loop nest using an n-D vectorization ...
static Operation * vectorizeAffineLoad(AffineLoadOp loadOp, VectorizationState &state)
Vectorizes an affine load with the vectorization strategy in 'state' by generating a 'vector....
static Operation * vectorizeAffineForOp(AffineForOp forOp, VectorizationState &state)
Vectorizes a loop with the vectorization strategy in 'state'.
static Operation * vectorizeAffineApplyOp(AffineApplyOp applyOp, VectorizationState &state)
We have no need to vectorize affine.apply.
static LogicalResult analyzeProfitability(ArrayRef< NestedMatch > matches, unsigned depthInPattern, unsigned patternDepth, VectorizationStrategy *strategy)
Implements a simple strawman strategy for vectorization.
static FilterFunctionType isVectorizableLoopPtrFactory(const DenseSet< Operation * > ¶llelLoops, int fastestVaryingMemRefDimension)
Forward declaration.
static bool isIVMappedToMultipleIndices(ArrayRef< Value > indices, const DenseMap< Operation *, unsigned > &loopToVectorDim)
Returns true if any vectorized loop IV drives more than one index.
static arith::ConstantOp vectorizeConstant(arith::ConstantOp constOp, VectorizationState &state)
Tries to transform a scalar constant into a vector constant.
static bool isUniformDefinition(Value value, const VectorizationStrategy *strategy)
Returns true if the provided value is vector uniform given the vectorization strategy.
static void eraseLoopNest(AffineForOp forOp)
Erases a loop nest, including all its nested operations.
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
static void getMatchedAffineLoops(NestedMatch match, std::vector< SmallVector< AffineForOp, 2 > > &loops)
Converts all the nested loops in 'match' to a 2D vector container that preserves the relative nesting...
static Value vectorizeOperand(Value operand, VectorizationState &state)
Tries to vectorize a given operand by applying the following logic:
static void getMatchedAffineLoopsRec(NestedMatch match, unsigned currentLevel, std::vector< SmallVector< AffineForOp, 2 > > &loops)
Recursive implementation to convert all the nested loops in 'match' to a 2D vector container that pre...
static Operation * vectorizeAffineYieldOp(AffineYieldOp yieldOp, VectorizationState &state)
Vectorizes a yield operation by widening its types.
static arith::ConstantOp createInitialVector(arith::AtomicRMWKind reductionKind, Value oldOperand, VectorizationState &state)
Creates a constant vector filled with the neutral elements of the given reduction.
static Operation * widenOp(Operation *op, VectorizationState &state)
Vectorizes arbitrary operation by plain widening.
static Operation * vectorizeAffineStore(AffineStoreOp storeOp, VectorizationState &state)
Vectorizes an affine store with the vectorization strategy in 'state' by generating a 'vector....
static NestedPattern & vectorTransferPattern()
static void vectorizeLoops(Operation *parentOp, DenseSet< Operation * > &loops, ArrayRef< int64_t > vectorSizes, ArrayRef< int64_t > fastestVaryingPattern, const ReductionLoopMap &reductionLoops)
Internal implementation to vectorize affine loops in 'loops' using the n-D vectorization factors in '...
static void computeMemoryOpIndices(Operation *op, AffineMap map, ValueRange mapOperands, VectorizationState &state, SmallVectorImpl< Value > &results)
static void computeIntersectionBuckets(ArrayRef< NestedMatch > matches, std::vector< SmallVector< NestedMatch, 8 > > &intersectionBuckets)
Traverses all the loop matches and classifies them into intersection buckets.
static Value createMask(AffineForOp vecForOp, VectorizationState &state)
Creates a mask used to filter out garbage elements in the last iteration of unaligned loops.
static AffineMap makePermutationMap(ArrayRef< Value > indices, const DenseMap< Operation *, unsigned > &enclosingLoopToVectorDim)
Constructs a permutation map from memref indices to vector dimension.
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: () -> ().
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
Attributes are known-constant values of operations.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
AffineMap getMultiDimIdentityMap(unsigned rank)
IntegerType getIntegerType(unsigned width)
AffineExpr getAffineDimExpr(unsigned position)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation is the basic unit of execution within MLIR.
bool use_empty()
Returns true if this operation has no uses.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
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.
operand_range getOperands()
Returns an iterator on the underlying Value's.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
result_range getResults()
user_iterator user_begin()
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
This class provides an abstraction over the different types of ranges over Values.
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.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static WalkResult advance()
static WalkResult interrupt()
An NestedPattern captures nested patterns in the IR.
ArrayRef< NestedMatch > getMatchedChildren()
Operation * getMatchedOperation() const
NestedPattern For(const NestedPattern &child)
NestedPattern Op(FilterFunctionType filter=defaultFilterFunction)
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
DenseMap< Operation *, SmallVector< LoopReduction, 2 > > ReductionLoopMap
bool isVectorizableLoopBody(AffineForOp loop, NestedPattern &vectorTransferMatcher)
Checks whether the loop is structurally vectorizable; i.e.:
DenseSet< Value, DenseMapInfo< Value > > getInvariantAccesses(Value iv, ArrayRef< Value > indices)
Given an induction variable iv of type AffineForOp and indices of type IndexType, returns the set of ...
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
std::function< bool(Operation &)> FilterFunctionType
A NestedPattern is a nested operation walker that:
Value getReductionOp(AtomicRMWKind op, OpBuilder &builder, Location loc, Value lhs, Value rhs)
Returns the value obtained by applying the reduction operation kind associated with a binary AtomicRM...
Operation * createWriteOrMaskedWrite(OpBuilder &builder, Location loc, Value vecToStore, Value dest, SmallVector< Value > writeIndices={}, bool useInBoundsInsteadOfMasking=false, AffineMap permutationMap=AffineMap())
Create a TransferWriteOp of vecToStore into dest.
Value createReadOrMaskedRead(OpBuilder &builder, Location loc, Value source, const VectorType &vecToReadTy, std::optional< Value > padValue=std::nullopt, bool useInBoundsInsteadOfMasking=false, ArrayRef< Value > indices={}, AffineMap permutationMap=AffineMap())
Creates a TransferReadOp from source.
Value getVectorReductionOp(arith::AtomicRMWKind op, OpBuilder &builder, Location loc, Value vector)
Returns the value obtained by reducing the vector into a scalar using the operation kind associated w...
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
VectorizationState(RewriterBase &rewriter)
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.