14ead2cf7SAlex Zinenko //===- VectorToSCF.cpp - Conversion from Vector to mix of SCF and Std -----===// 24ead2cf7SAlex Zinenko // 34ead2cf7SAlex Zinenko // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 44ead2cf7SAlex Zinenko // See https://llvm.org/LICENSE.txt for license information. 54ead2cf7SAlex Zinenko // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 64ead2cf7SAlex Zinenko // 74ead2cf7SAlex Zinenko //===----------------------------------------------------------------------===// 84ead2cf7SAlex Zinenko // 94ead2cf7SAlex Zinenko // This file implements target-dependent lowering of vector transfer operations. 104ead2cf7SAlex Zinenko // 114ead2cf7SAlex Zinenko //===----------------------------------------------------------------------===// 124ead2cf7SAlex Zinenko 134ead2cf7SAlex Zinenko #include <type_traits> 144ead2cf7SAlex Zinenko 154ead2cf7SAlex Zinenko #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" 165f9e0466SNicolas Vasilache 175f9e0466SNicolas Vasilache #include "../PassDetail.h" 184ead2cf7SAlex Zinenko #include "mlir/Dialect/Affine/EDSC/Intrinsics.h" 194ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Builders.h" 204ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Intrinsics.h" 214ead2cf7SAlex Zinenko #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 224ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 234ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/VectorOps.h" 247c3c5b11SNicolas Vasilache #include "mlir/Dialect/Vector/VectorUtils.h" 254ead2cf7SAlex Zinenko #include "mlir/IR/AffineExpr.h" 264ead2cf7SAlex Zinenko #include "mlir/IR/AffineMap.h" 274ead2cf7SAlex Zinenko #include "mlir/IR/Attributes.h" 284ead2cf7SAlex Zinenko #include "mlir/IR/Builders.h" 294ead2cf7SAlex Zinenko #include "mlir/IR/Location.h" 304ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h" 314ead2cf7SAlex Zinenko #include "mlir/IR/OperationSupport.h" 324ead2cf7SAlex Zinenko #include "mlir/IR/PatternMatch.h" 334ead2cf7SAlex Zinenko #include "mlir/IR/Types.h" 345f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h" 355f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h" 364ead2cf7SAlex Zinenko 374ead2cf7SAlex Zinenko using namespace mlir; 384ead2cf7SAlex Zinenko using namespace mlir::edsc; 394ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics; 404ead2cf7SAlex Zinenko using vector::TransferReadOp; 414ead2cf7SAlex Zinenko using vector::TransferWriteOp; 424ead2cf7SAlex Zinenko 43*af5be38aSNicolas Vasilache // Return a list of Values that correspond to multiple AffineApplyOp, one for 44*af5be38aSNicolas Vasilache // each result of `map`. Each `expr` in `map` is canonicalized and folded 45*af5be38aSNicolas Vasilache // greedily according to its operands. 46*af5be38aSNicolas Vasilache // TODO: factor out in a common location that both linalg and vector can use. 47*af5be38aSNicolas Vasilache static SmallVector<Value, 4> 48*af5be38aSNicolas Vasilache applyMapToValues(OpBuilder &b, Location loc, AffineMap map, ValueRange values) { 49*af5be38aSNicolas Vasilache SmallVector<Value, 4> res; 50*af5be38aSNicolas Vasilache res.reserve(map.getNumResults()); 51*af5be38aSNicolas Vasilache unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols(); 52*af5be38aSNicolas Vasilache // For each `expr` in `map`, applies the `expr` to the values extracted from 53*af5be38aSNicolas Vasilache // ranges. If the resulting application can be folded into a Value, the 54*af5be38aSNicolas Vasilache // folding occurs eagerly. Otherwise, an affine.apply operation is emitted. 55*af5be38aSNicolas Vasilache for (auto expr : map.getResults()) { 56*af5be38aSNicolas Vasilache AffineMap map = AffineMap::get(numDims, numSym, expr); 57*af5be38aSNicolas Vasilache SmallVector<Value, 4> operands(values.begin(), values.end()); 58*af5be38aSNicolas Vasilache fullyComposeAffineMapAndOperands(&map, &operands); 59*af5be38aSNicolas Vasilache canonicalizeMapAndOperands(&map, &operands); 60*af5be38aSNicolas Vasilache res.push_back(b.createOrFold<AffineApplyOp>(loc, map, operands)); 61*af5be38aSNicolas Vasilache } 62*af5be38aSNicolas Vasilache return res; 63*af5be38aSNicolas Vasilache } 64*af5be38aSNicolas Vasilache 65350dadaaSBenjamin Kramer namespace { 664ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector 674ead2cf7SAlex Zinenko /// transfer operations (read and write). 684ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR 694ead2cf7SAlex Zinenko /// manipulation. 704ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as: 714ead2cf7SAlex Zinenko /// 724ead2cf7SAlex Zinenko /// ``` 734ead2cf7SAlex Zinenko /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 744ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 754ead2cf7SAlex Zinenko /// vector<(major_dims) x (minor_dims) x type> 764ead2cf7SAlex Zinenko /// ``` 774ead2cf7SAlex Zinenko /// 784ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 794ead2cf7SAlex Zinenko /// higher). 804ead2cf7SAlex Zinenko /// 814ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling: 824ead2cf7SAlex Zinenko /// 834ead2cf7SAlex Zinenko /// ``` 844ead2cf7SAlex Zinenko /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 854ead2cf7SAlex Zinenko /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 864ead2cf7SAlex Zinenko /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 874ead2cf7SAlex Zinenko /// %v = vector_transfer_read( 884ead2cf7SAlex Zinenko /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 894ead2cf7SAlex Zinenko /// %ivs_minor): 904ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 914ead2cf7SAlex Zinenko /// vector<(minor_dims) x type>; 924ead2cf7SAlex Zinenko /// store(%v, %tmp); 934ead2cf7SAlex Zinenko /// } else { 944ead2cf7SAlex Zinenko /// %v = splat(vector<(minor_dims) x type>, %fill) 954ead2cf7SAlex Zinenko /// store(%v, %tmp, %ivs_major); 964ead2cf7SAlex Zinenko /// } 974ead2cf7SAlex Zinenko /// } 984ead2cf7SAlex Zinenko /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 994ead2cf7SAlex Zinenko // vector<(major_dims) x (minor_dims) x type> 1004ead2cf7SAlex Zinenko /// ``` 1014ead2cf7SAlex Zinenko /// 1024ead2cf7SAlex Zinenko template <typename ConcreteOp> 1034ead2cf7SAlex Zinenko class NDTransferOpHelper { 1044ead2cf7SAlex Zinenko public: 1057c3c5b11SNicolas Vasilache NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 1067c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) 1077c3c5b11SNicolas Vasilache : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 1084ead2cf7SAlex Zinenko scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 1094ead2cf7SAlex Zinenko op(xferOp.getOperation()) { 1104ead2cf7SAlex Zinenko vectorType = xferOp.getVectorType(); 1119db53a18SRiver Riddle // TODO: when we go to k > 1-D vectors adapt minorRank. 1124ead2cf7SAlex Zinenko minorRank = 1; 1134ead2cf7SAlex Zinenko majorRank = vectorType.getRank() - minorRank; 114ec2f2cecSNicolas Vasilache leadingRank = xferOp.getLeadingMemRefRank(); 1154ead2cf7SAlex Zinenko majorVectorType = 1164ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_front(majorRank), 1174ead2cf7SAlex Zinenko vectorType.getElementType()); 1184ead2cf7SAlex Zinenko minorVectorType = 1194ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_back(minorRank), 1204ead2cf7SAlex Zinenko vectorType.getElementType()); 1214ead2cf7SAlex Zinenko /// Memref of minor vector type is used for individual transfers. 1224ead2cf7SAlex Zinenko memRefMinorVectorType = 1234ead2cf7SAlex Zinenko MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 1244ead2cf7SAlex Zinenko xferOp.getMemRefType().getMemorySpace()); 1254ead2cf7SAlex Zinenko } 1264ead2cf7SAlex Zinenko 1274ead2cf7SAlex Zinenko LogicalResult doReplace(); 1284ead2cf7SAlex Zinenko 1294ead2cf7SAlex Zinenko private: 1304ead2cf7SAlex Zinenko /// Creates the loop nest on the "major" dimensions and calls the 1314ead2cf7SAlex Zinenko /// `loopBodyBuilder` lambda in the context of the loop nest. 132307dc7b2SBenjamin Kramer void 133307dc7b2SBenjamin Kramer emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange, 134307dc7b2SBenjamin Kramer ValueRange, const MemRefBoundsCapture &)> 135307dc7b2SBenjamin Kramer loopBodyBuilder); 1364ead2cf7SAlex Zinenko 1374ead2cf7SAlex Zinenko /// Common state to lower vector transfer ops. 1384ead2cf7SAlex Zinenko PatternRewriter &rewriter; 1397c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options; 1404ead2cf7SAlex Zinenko Location loc; 1414ead2cf7SAlex Zinenko std::unique_ptr<ScopedContext> scope; 1424ead2cf7SAlex Zinenko ConcreteOp xferOp; 1434ead2cf7SAlex Zinenko Operation *op; 1444ead2cf7SAlex Zinenko // A vector transfer copies data between: 1454ead2cf7SAlex Zinenko // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 1464ead2cf7SAlex Zinenko // - vector<(major_dims) x (minor_dims) x type> 1474ead2cf7SAlex Zinenko unsigned minorRank; // for now always 1 1484ead2cf7SAlex Zinenko unsigned majorRank; // vector rank - minorRank 1494ead2cf7SAlex Zinenko unsigned leadingRank; // memref rank - vector rank 1504ead2cf7SAlex Zinenko VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 1514ead2cf7SAlex Zinenko VectorType majorVectorType; // vector<(major_dims) x type> 1524ead2cf7SAlex Zinenko VectorType minorVectorType; // vector<(minor_dims) x type> 1534ead2cf7SAlex Zinenko MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 1544ead2cf7SAlex Zinenko }; 1554ead2cf7SAlex Zinenko 1564ead2cf7SAlex Zinenko template <typename ConcreteOp> 157307dc7b2SBenjamin Kramer void NDTransferOpHelper<ConcreteOp>::emitLoops( 158307dc7b2SBenjamin Kramer llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange, 159307dc7b2SBenjamin Kramer const MemRefBoundsCapture &)> 160307dc7b2SBenjamin Kramer loopBodyBuilder) { 1614ead2cf7SAlex Zinenko /// Loop nest operates on the major dimensions 1624ead2cf7SAlex Zinenko MemRefBoundsCapture memrefBoundsCapture(xferOp.memref()); 1637c3c5b11SNicolas Vasilache 1647c3c5b11SNicolas Vasilache if (options.unroll) { 1657c3c5b11SNicolas Vasilache auto shape = majorVectorType.getShape(); 1667c3c5b11SNicolas Vasilache auto strides = computeStrides(shape); 1677c3c5b11SNicolas Vasilache unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 1687c3c5b11SNicolas Vasilache ValueRange indices(xferOp.indices()); 1697c3c5b11SNicolas Vasilache for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 1707c3c5b11SNicolas Vasilache SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 1717c3c5b11SNicolas Vasilache SmallVector<Value, 4> offsetValues = 1727c3c5b11SNicolas Vasilache llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 1737c3c5b11SNicolas Vasilache return std_constant_index(off); 1747c3c5b11SNicolas Vasilache })); 1757c3c5b11SNicolas Vasilache loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 1767c3c5b11SNicolas Vasilache indices.drop_front(leadingRank).take_front(majorRank), 1777c3c5b11SNicolas Vasilache indices.take_back(minorRank), memrefBoundsCapture); 1787c3c5b11SNicolas Vasilache } 1797c3c5b11SNicolas Vasilache } else { 1804ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(majorVectorType); 1814ead2cf7SAlex Zinenko auto majorLbs = vectorBoundsCapture.getLbs(); 1824ead2cf7SAlex Zinenko auto majorUbs = vectorBoundsCapture.getUbs(); 1834ead2cf7SAlex Zinenko auto majorSteps = vectorBoundsCapture.getSteps(); 1843f5bd53eSAlex Zinenko affineLoopNestBuilder( 1853f5bd53eSAlex Zinenko majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) { 1864ead2cf7SAlex Zinenko ValueRange indices(xferOp.indices()); 1874ead2cf7SAlex Zinenko loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 1884ead2cf7SAlex Zinenko indices.drop_front(leadingRank).take_front(majorRank), 1894ead2cf7SAlex Zinenko indices.take_back(minorRank), memrefBoundsCapture); 1904ead2cf7SAlex Zinenko }); 1914ead2cf7SAlex Zinenko } 1927c3c5b11SNicolas Vasilache } 1934ead2cf7SAlex Zinenko 194bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) { 195bd87c6bcSNicolas Vasilache if (auto cstOp = v.getDefiningOp<ConstantIndexOp>()) 196bd87c6bcSNicolas Vasilache return cstOp.getValue(); 197bd87c6bcSNicolas Vasilache if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>()) 198bd87c6bcSNicolas Vasilache if (affineApplyOp.getAffineMap().isSingleConstant()) 199bd87c6bcSNicolas Vasilache return affineApplyOp.getAffineMap().getSingleConstantResult(); 200bd87c6bcSNicolas Vasilache return None; 201bd87c6bcSNicolas Vasilache } 202bd87c6bcSNicolas Vasilache 203bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding 204bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go 205bd87c6bcSNicolas Vasilache // away once scf.if folds properly. 206bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) { 207bd87c6bcSNicolas Vasilache using namespace mlir::edsc::op; 208bd87c6bcSNicolas Vasilache auto maybeCstV = extractConstantIndex(v); 209bd87c6bcSNicolas Vasilache auto maybeCstUb = extractConstantIndex(ub); 210bd87c6bcSNicolas Vasilache if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb) 211bd87c6bcSNicolas Vasilache return Value(); 212bd87c6bcSNicolas Vasilache return slt(v, ub); 213bd87c6bcSNicolas Vasilache } 214bd87c6bcSNicolas Vasilache 215239eff50SBenjamin Kramer /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 216239eff50SBenjamin Kramer /// `majorIvsPlusOffsets`. 217*af5be38aSNicolas Vasilache /// 2. Return a value of i1 that determines whether the first 218*af5be38aSNicolas Vasilache /// `majorIvs.rank()` 219239eff50SBenjamin Kramer /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 220239eff50SBenjamin Kramer static Value 221239eff50SBenjamin Kramer emitInBoundsCondition(PatternRewriter &rewriter, 222239eff50SBenjamin Kramer VectorTransferOpInterface xferOp, unsigned leadingRank, 2234ead2cf7SAlex Zinenko ValueRange majorIvs, ValueRange majorOffsets, 224307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds, 2257c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets) { 2267c3c5b11SNicolas Vasilache Value inBoundsCondition; 2274ead2cf7SAlex Zinenko majorIvsPlusOffsets.reserve(majorIvs.size()); 2281870e787SNicolas Vasilache unsigned idx = 0; 2298dace28fSJakub Lichman SmallVector<Value, 4> bounds = 230*af5be38aSNicolas Vasilache applyMapToValues(rewriter, xferOp.getLoc(), xferOp.permutation_map(), 231*af5be38aSNicolas Vasilache memrefBounds.getUbs()); 2328dace28fSJakub Lichman for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) { 2334ead2cf7SAlex Zinenko Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 2344ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 2354ead2cf7SAlex Zinenko majorIvsPlusOffsets.push_back(iv + off); 2361870e787SNicolas Vasilache if (xferOp.isMaskedDim(leadingRank + idx)) { 237bd87c6bcSNicolas Vasilache Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub); 238bd87c6bcSNicolas Vasilache if (inBoundsCond) 239bd87c6bcSNicolas Vasilache inBoundsCondition = (inBoundsCondition) 240bd87c6bcSNicolas Vasilache ? (inBoundsCondition && inBoundsCond) 241bd87c6bcSNicolas Vasilache : inBoundsCond; 2421870e787SNicolas Vasilache } 2431870e787SNicolas Vasilache ++idx; 2444ead2cf7SAlex Zinenko } 2457c3c5b11SNicolas Vasilache return inBoundsCondition; 2464ead2cf7SAlex Zinenko } 2474ead2cf7SAlex Zinenko 248247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations. 249247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType, 250247e185dSNicolas Vasilache Operation *op) { 251247e185dSNicolas Vasilache auto &b = ScopedContext::getBuilderRef(); 252247e185dSNicolas Vasilache OpBuilder::InsertionGuard guard(b); 253a4b8c2deSJakub Lichman Operation *scope = 254a4b8c2deSJakub Lichman op->getParentWithTrait<OpTrait::AutomaticAllocationScope>(); 255a4b8c2deSJakub Lichman assert(scope && "Expected op to be inside automatic allocation scope"); 256a4b8c2deSJakub Lichman b.setInsertionPointToStart(&scope->getRegion(0).front()); 2578d64df9fSNicolas Vasilache Value res = std_alloca(memRefMinorVectorType); 258247e185dSNicolas Vasilache return res; 259247e185dSNicolas Vasilache } 260247e185dSNicolas Vasilache 2614ead2cf7SAlex Zinenko template <> 2624ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 2637c3c5b11SNicolas Vasilache Value alloc, result; 2647c3c5b11SNicolas Vasilache if (options.unroll) 2657c3c5b11SNicolas Vasilache result = std_splat(vectorType, xferOp.padding()); 2667c3c5b11SNicolas Vasilache else 267247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 2684ead2cf7SAlex Zinenko 2694ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 2704ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 271307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds) { 2727c3c5b11SNicolas Vasilache /// Lambda to load 1-D vector in the current loop ivs + offset context. 2737c3c5b11SNicolas Vasilache auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 2744ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 2754ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 2764ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 2774ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 2784ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 27936cdc17fSNicolas Vasilache Value memref = xferOp.memref(); 28047cbd9f9SNicolas Vasilache auto map = 28147cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 2821870e787SNicolas Vasilache ArrayAttr masked; 283cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 2841870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 285cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 2861870e787SNicolas Vasilache } 2877c3c5b11SNicolas Vasilache return vector_transfer_read(minorVectorType, memref, indexing, 2887c3c5b11SNicolas Vasilache AffineMapAttr::get(map), xferOp.padding(), 2897c3c5b11SNicolas Vasilache masked); 2904ead2cf7SAlex Zinenko }; 2917c3c5b11SNicolas Vasilache 2927c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 2937c3c5b11SNicolas Vasilache // context. 2947c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 2957c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 296239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()), 297239eff50SBenjamin Kramer leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 2987c3c5b11SNicolas Vasilache 2997c3c5b11SNicolas Vasilache if (inBoundsCondition) { 3007c3c5b11SNicolas Vasilache // 2. If the condition is not null, we need an IfOp, which may yield 3017c3c5b11SNicolas Vasilache // if `options.unroll` is true. 3027c3c5b11SNicolas Vasilache SmallVector<Type, 1> resultType; 3037c3c5b11SNicolas Vasilache if (options.unroll) 3047c3c5b11SNicolas Vasilache resultType.push_back(vectorType); 3057c3c5b11SNicolas Vasilache 306cadb7ccfSAlex Zinenko // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise 307cadb7ccfSAlex Zinenko // splat a 1-D vector. 308cadb7ccfSAlex Zinenko ValueRange ifResults = conditionBuilder( 309cadb7ccfSAlex Zinenko resultType, inBoundsCondition, 310cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 3117c3c5b11SNicolas Vasilache Value vector = load1DVector(majorIvsPlusOffsets); 312cadb7ccfSAlex Zinenko // 3.a. If `options.unroll` is true, insert the 1-D vector in the 3137c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `else` branch. 3147c3c5b11SNicolas Vasilache if (options.unroll) { 3157c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 316cadb7ccfSAlex Zinenko return {vector}; 3177c3c5b11SNicolas Vasilache } 318cadb7ccfSAlex Zinenko // 3.b. Otherwise, just go through the temporary `alloc`. 3194ead2cf7SAlex Zinenko std_store(vector, alloc, majorIvs); 320cadb7ccfSAlex Zinenko return {}; 321cadb7ccfSAlex Zinenko }, 322cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 3237c3c5b11SNicolas Vasilache Value vector = std_splat(minorVectorType, xferOp.padding()); 324cadb7ccfSAlex Zinenko // 3.c. If `options.unroll` is true, insert the 1-D vector in the 3257c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `then` branch. 3267c3c5b11SNicolas Vasilache if (options.unroll) { 3277c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 328cadb7ccfSAlex Zinenko return {vector}; 3297c3c5b11SNicolas Vasilache } 330cadb7ccfSAlex Zinenko // 3.d. Otherwise, just go through the temporary `alloc`. 3317c3c5b11SNicolas Vasilache std_store(vector, alloc, majorIvs); 332cadb7ccfSAlex Zinenko return {}; 3337c3c5b11SNicolas Vasilache }); 334cadb7ccfSAlex Zinenko 3357c3c5b11SNicolas Vasilache if (!resultType.empty()) 336cadb7ccfSAlex Zinenko result = *ifResults.begin(); 3377c3c5b11SNicolas Vasilache } else { 3387c3c5b11SNicolas Vasilache // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 3397c3c5b11SNicolas Vasilache Value loaded1D = load1DVector(majorIvsPlusOffsets); 3407c3c5b11SNicolas Vasilache // 5.a. If `options.unroll` is true, insert the 1-D vector in the 3417c3c5b11SNicolas Vasilache // aggregate. 3427c3c5b11SNicolas Vasilache if (options.unroll) 3437c3c5b11SNicolas Vasilache result = vector_insert(loaded1D, result, majorIvs); 3447c3c5b11SNicolas Vasilache // 5.b. Otherwise, just go through the temporary `alloc`. 3457c3c5b11SNicolas Vasilache else 3467c3c5b11SNicolas Vasilache std_store(loaded1D, alloc, majorIvs); 3477c3c5b11SNicolas Vasilache } 3487c3c5b11SNicolas Vasilache }); 3497c3c5b11SNicolas Vasilache 350a9b5edc5SBenjamin Kramer assert((!options.unroll ^ (bool)result) && 351a9b5edc5SBenjamin Kramer "Expected resulting Value iff unroll"); 3527c3c5b11SNicolas Vasilache if (!result) 3537c3c5b11SNicolas Vasilache result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3547c3c5b11SNicolas Vasilache rewriter.replaceOp(op, result); 3554ead2cf7SAlex Zinenko 3564ead2cf7SAlex Zinenko return success(); 3574ead2cf7SAlex Zinenko } 3584ead2cf7SAlex Zinenko 3594ead2cf7SAlex Zinenko template <> 3604ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 3617c3c5b11SNicolas Vasilache Value alloc; 3627c3c5b11SNicolas Vasilache if (!options.unroll) { 363247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 3644ead2cf7SAlex Zinenko std_store(xferOp.vector(), 3654ead2cf7SAlex Zinenko vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3667c3c5b11SNicolas Vasilache } 3674ead2cf7SAlex Zinenko 3684ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 3694ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 370307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds) { 3717c3c5b11SNicolas Vasilache // Lower to 1-D vector_transfer_write and let recursion handle it. 3727c3c5b11SNicolas Vasilache auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 3734ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 3744ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 3754ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 3764ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 3774ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 3787c3c5b11SNicolas Vasilache Value result; 3797c3c5b11SNicolas Vasilache // If `options.unroll` is true, extract the 1-D vector from the 3807c3c5b11SNicolas Vasilache // aggregate. 3817c3c5b11SNicolas Vasilache if (options.unroll) 3827c3c5b11SNicolas Vasilache result = vector_extract(xferOp.vector(), majorIvs); 3837c3c5b11SNicolas Vasilache else 3847c3c5b11SNicolas Vasilache result = std_load(alloc, majorIvs); 38547cbd9f9SNicolas Vasilache auto map = 38647cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 3871870e787SNicolas Vasilache ArrayAttr masked; 388cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 3891870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 390cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 3911870e787SNicolas Vasilache } 3927c3c5b11SNicolas Vasilache vector_transfer_write(result, xferOp.memref(), indexing, 3931870e787SNicolas Vasilache AffineMapAttr::get(map), masked); 3944ead2cf7SAlex Zinenko }; 3957c3c5b11SNicolas Vasilache 3967c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 3977c3c5b11SNicolas Vasilache // context. 3987c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 3997c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 400239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()), 401239eff50SBenjamin Kramer leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 4027c3c5b11SNicolas Vasilache 4037c3c5b11SNicolas Vasilache if (inBoundsCondition) { 4047c3c5b11SNicolas Vasilache // 2.a. If the condition is not null, we need an IfOp, to write 4057c3c5b11SNicolas Vasilache // conditionally. Progressively lower to a 1-D transfer write. 406cadb7ccfSAlex Zinenko conditionBuilder(inBoundsCondition, 407cadb7ccfSAlex Zinenko [&] { emitTransferWrite(majorIvsPlusOffsets); }); 4087c3c5b11SNicolas Vasilache } else { 4097c3c5b11SNicolas Vasilache // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 4107c3c5b11SNicolas Vasilache emitTransferWrite(majorIvsPlusOffsets); 4117c3c5b11SNicolas Vasilache } 4124ead2cf7SAlex Zinenko }); 4134ead2cf7SAlex Zinenko 4144ead2cf7SAlex Zinenko rewriter.eraseOp(op); 4154ead2cf7SAlex Zinenko 4164ead2cf7SAlex Zinenko return success(); 4174ead2cf7SAlex Zinenko } 4184ead2cf7SAlex Zinenko 419df63eedeSBenjamin Kramer } // namespace 420df63eedeSBenjamin Kramer 4214ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote 4224ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found, 4234ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 4244ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop. 4254ead2cf7SAlex Zinenko template <typename TransferOpTy> 4264ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) { 4274ead2cf7SAlex Zinenko // rank of the remote memory access, coalescing behavior occurs on the 4284ead2cf7SAlex Zinenko // innermost memory dimension. 4294ead2cf7SAlex Zinenko auto remoteRank = transfer.getMemRefType().getRank(); 4304ead2cf7SAlex Zinenko // Iterate over the results expressions of the permutation map to determine 4314ead2cf7SAlex Zinenko // the loop order for creating pointwise copies between remote and local 4324ead2cf7SAlex Zinenko // memories. 4334ead2cf7SAlex Zinenko int coalescedIdx = -1; 4344ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4354ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4364ead2cf7SAlex Zinenko auto dim = en.value().template dyn_cast<AffineDimExpr>(); 4374ead2cf7SAlex Zinenko if (!dim) { 4384ead2cf7SAlex Zinenko continue; 4394ead2cf7SAlex Zinenko } 4404ead2cf7SAlex Zinenko auto memRefDim = dim.getPosition(); 4414ead2cf7SAlex Zinenko if (memRefDim == remoteRank - 1) { 4424ead2cf7SAlex Zinenko // memRefDim has coalescing properties, it should be swapped in the last 4434ead2cf7SAlex Zinenko // position. 4444ead2cf7SAlex Zinenko assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 4454ead2cf7SAlex Zinenko coalescedIdx = en.index(); 4464ead2cf7SAlex Zinenko } 4474ead2cf7SAlex Zinenko } 4484ead2cf7SAlex Zinenko return coalescedIdx; 4494ead2cf7SAlex Zinenko } 4504ead2cf7SAlex Zinenko 4514ead2cf7SAlex Zinenko template <typename TransferOpTy> 4523393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 4537c3c5b11SNicolas Vasilache VectorTransferToSCFOptions options, MLIRContext *context) 4547c3c5b11SNicolas Vasilache : RewritePattern(TransferOpTy::getOperationName(), 1, context), 4557c3c5b11SNicolas Vasilache options(options) {} 4564ead2cf7SAlex Zinenko 4577c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer. 4587c3c5b11SNicolas Vasilache template <typename TransferOpTy> 4593393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 4607c3c5b11SNicolas Vasilache TransferOpTy transfer) const { 4614ead2cf7SAlex Zinenko auto vectorType = transfer.getVectorType(); 4628d64df9fSNicolas Vasilache return MemRefType::get(vectorType.getShape().drop_back(), 4638d64df9fSNicolas Vasilache VectorType::get(vectorType.getShape().take_back(), 4648d64df9fSNicolas Vasilache vectorType.getElementType()), 4658d64df9fSNicolas Vasilache {}, 0); 4664ead2cf7SAlex Zinenko } 4674ead2cf7SAlex Zinenko 468239eff50SBenjamin Kramer static void emitWithBoundsChecks( 469239eff50SBenjamin Kramer PatternRewriter &rewriter, VectorTransferOpInterface transfer, 470307dc7b2SBenjamin Kramer ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture, 471239eff50SBenjamin Kramer function_ref<void(ArrayRef<Value>)> inBoundsFun, 472239eff50SBenjamin Kramer function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) { 473239eff50SBenjamin Kramer // Permute the incoming indices according to the permutation map. 474239eff50SBenjamin Kramer SmallVector<Value, 4> indices = 475*af5be38aSNicolas Vasilache applyMapToValues(rewriter, transfer.getLoc(), transfer.permutation_map(), 476*af5be38aSNicolas Vasilache transfer.indices()); 477239eff50SBenjamin Kramer 478239eff50SBenjamin Kramer // Generate a bounds check if necessary. 479239eff50SBenjamin Kramer SmallVector<Value, 4> majorIvsPlusOffsets; 480239eff50SBenjamin Kramer Value inBoundsCondition = 481239eff50SBenjamin Kramer emitInBoundsCondition(rewriter, transfer, 0, ivs, indices, 482239eff50SBenjamin Kramer memRefBoundsCapture, majorIvsPlusOffsets); 483239eff50SBenjamin Kramer 484239eff50SBenjamin Kramer // Apply the permutation map to the ivs. The permutation map may not use all 485239eff50SBenjamin Kramer // the inputs. 486239eff50SBenjamin Kramer SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size()); 487239eff50SBenjamin Kramer for (unsigned memRefDim = 0; memRefDim < transfer.indices().size(); 488239eff50SBenjamin Kramer ++memRefDim) { 489239eff50SBenjamin Kramer // Linear search on a small number of entries. 490239eff50SBenjamin Kramer int loopIndex = -1; 491239eff50SBenjamin Kramer auto exprs = transfer.permutation_map().getResults(); 492239eff50SBenjamin Kramer for (auto en : llvm::enumerate(exprs)) { 493239eff50SBenjamin Kramer auto expr = en.value(); 494239eff50SBenjamin Kramer auto dim = expr.dyn_cast<AffineDimExpr>(); 495239eff50SBenjamin Kramer // Sanity check. 496239eff50SBenjamin Kramer assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) && 497239eff50SBenjamin Kramer "Expected dim or 0 in permutationMap"); 498239eff50SBenjamin Kramer if (dim && memRefDim == dim.getPosition()) { 499239eff50SBenjamin Kramer loopIndex = en.index(); 500239eff50SBenjamin Kramer break; 501239eff50SBenjamin Kramer } 502239eff50SBenjamin Kramer } 503239eff50SBenjamin Kramer 504239eff50SBenjamin Kramer using namespace edsc::op; 505239eff50SBenjamin Kramer auto i = transfer.indices()[memRefDim]; 506239eff50SBenjamin Kramer scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex]; 507239eff50SBenjamin Kramer } 508239eff50SBenjamin Kramer 509239eff50SBenjamin Kramer if (inBoundsCondition) 510239eff50SBenjamin Kramer conditionBuilder( 511239eff50SBenjamin Kramer /* scf.if */ inBoundsCondition, // { 512239eff50SBenjamin Kramer [&] { inBoundsFun(scalarAccessExprs); }, 513239eff50SBenjamin Kramer // } else { 514239eff50SBenjamin Kramer outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); } 515239eff50SBenjamin Kramer : function_ref<void()>() 516239eff50SBenjamin Kramer // } 517239eff50SBenjamin Kramer ); 518239eff50SBenjamin Kramer else 519239eff50SBenjamin Kramer inBoundsFun(scalarAccessExprs); 520239eff50SBenjamin Kramer } 521239eff50SBenjamin Kramer 52251d30c34SBenjamin Kramer namespace mlir { 52351d30c34SBenjamin Kramer 5244ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of: 5254ead2cf7SAlex Zinenko /// 1. local memory allocation; 5264ead2cf7SAlex Zinenko /// 2. perfect loop nest over: 5274ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 528307dc7b2SBenjamin Kramer /// a. scalar store to original memref (with padding). 5294ead2cf7SAlex Zinenko /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 5304ead2cf7SAlex Zinenko /// 4. local memory deallocation. 5314ead2cf7SAlex Zinenko /// 5324ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no 5334ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 534307dc7b2SBenjamin Kramer /// padding. 5354ead2cf7SAlex Zinenko 5364ead2cf7SAlex Zinenko /// Performs the rewrite. 5374ead2cf7SAlex Zinenko template <> 5383393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite( 5394ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 5404ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 5414ead2cf7SAlex Zinenko 5424ead2cf7SAlex Zinenko TransferReadOp transfer = cast<TransferReadOp>(op); 543dfb7b3feSBenjamin Kramer 544dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 545dfb7b3feSBenjamin Kramer // permuted. 546dfb7b3feSBenjamin Kramer int64_t offset; 547dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 548dfb7b3feSBenjamin Kramer auto successStrides = 549dfb7b3feSBenjamin Kramer getStridesAndOffset(transfer.getMemRefType(), strides, offset); 550dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 551dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 5524ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 5534ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 5547c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 5557c3c5b11SNicolas Vasilache .doReplace(); 5564ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 5574ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 5584ead2cf7SAlex Zinenko return failure(); 5594ead2cf7SAlex Zinenko } 5604ead2cf7SAlex Zinenko 5614ead2cf7SAlex Zinenko // Conservative lowering to scalar load / stores. 5624ead2cf7SAlex Zinenko // 1. Setup all the captures. 5634ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 5644ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 5654ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 5664ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 5674ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 5684ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 5694ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5704ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 5714ead2cf7SAlex Zinenko coalescedIdx); 5724ead2cf7SAlex Zinenko 5734ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 5744ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 5754ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 5764ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 5774ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 5784ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 5794ead2cf7SAlex Zinenko 5804ead2cf7SAlex Zinenko // 2. Emit alloc-copy-load-dealloc. 5819be61784SNicolas Vasilache MLIRContext *ctx = op->getContext(); 5828d64df9fSNicolas Vasilache Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer); 5834ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 584d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 585239eff50SBenjamin Kramer auto ivsStorage = llvm::to_vector<8>(loopIvs); 5864ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 5874ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 588239eff50SBenjamin Kramer std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]); 589239eff50SBenjamin Kramer 590239eff50SBenjamin Kramer ArrayRef<Value> ivs(ivsStorage); 591239eff50SBenjamin Kramer Value pos = std_index_cast(IntegerType::get(32, ctx), ivs.back()); 592239eff50SBenjamin Kramer Value inVector = local(ivs.drop_back()); 593239eff50SBenjamin Kramer auto loadValue = [&](ArrayRef<Value> indices) { 594239eff50SBenjamin Kramer Value vector = vector_insert_element(remote(indices), inVector, pos); 595239eff50SBenjamin Kramer local(ivs.drop_back()) = vector; 596239eff50SBenjamin Kramer }; 597239eff50SBenjamin Kramer auto loadPadding = [&](ArrayRef<Value>) { 598239eff50SBenjamin Kramer Value vector = vector_insert_element(transfer.padding(), inVector, pos); 599239eff50SBenjamin Kramer local(ivs.drop_back()) = vector; 600239eff50SBenjamin Kramer }; 601239eff50SBenjamin Kramer emitWithBoundsChecks( 602239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs, 603239eff50SBenjamin Kramer memRefBoundsCapture, loadValue, loadPadding); 6044ead2cf7SAlex Zinenko }); 6059be61784SNicolas Vasilache Value vectorValue = std_load(vector_type_cast(tmp)); 6064ead2cf7SAlex Zinenko 6074ead2cf7SAlex Zinenko // 3. Propagate. 6084ead2cf7SAlex Zinenko rewriter.replaceOp(op, vectorValue); 6094ead2cf7SAlex Zinenko return success(); 6104ead2cf7SAlex Zinenko } 6114ead2cf7SAlex Zinenko 6124ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of: 6134ead2cf7SAlex Zinenko /// 1. local memory allocation; 6144ead2cf7SAlex Zinenko /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 6154ead2cf7SAlex Zinenko /// 3. perfect loop nest over: 6164ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 617307dc7b2SBenjamin Kramer /// a. scalar store to original memref (if in bounds). 6184ead2cf7SAlex Zinenko /// 4. local memory deallocation. 6194ead2cf7SAlex Zinenko /// 6204ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no 621307dc7b2SBenjamin Kramer /// out-of-bounds accesses are possible. 6224ead2cf7SAlex Zinenko template <> 6233393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 6244ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 6254ead2cf7SAlex Zinenko using namespace edsc::op; 6264ead2cf7SAlex Zinenko 6274ead2cf7SAlex Zinenko TransferWriteOp transfer = cast<TransferWriteOp>(op); 628dfb7b3feSBenjamin Kramer 629dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 630dfb7b3feSBenjamin Kramer // permuted. 631dfb7b3feSBenjamin Kramer int64_t offset; 632dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 633dfb7b3feSBenjamin Kramer auto successStrides = 634dfb7b3feSBenjamin Kramer getStridesAndOffset(transfer.getMemRefType(), strides, offset); 635dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 636dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 6374ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 6384ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 6397c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 6404ead2cf7SAlex Zinenko .doReplace(); 6414ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 6424ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 6434ead2cf7SAlex Zinenko return failure(); 6444ead2cf7SAlex Zinenko } 6454ead2cf7SAlex Zinenko 6464ead2cf7SAlex Zinenko // 1. Setup all the captures. 6474ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 6484ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 6494ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 6504ead2cf7SAlex Zinenko Value vectorValue(transfer.vector()); 6514ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 6524ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 6534ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 6544ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6554ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 6564ead2cf7SAlex Zinenko coalescedIdx); 6574ead2cf7SAlex Zinenko 6584ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 6594ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 6604ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 6614ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 6624ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 6634ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 6644ead2cf7SAlex Zinenko 6654ead2cf7SAlex Zinenko // 2. Emit alloc-store-copy-dealloc. 6668d64df9fSNicolas Vasilache Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer); 6674ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 6684ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 6694ead2cf7SAlex Zinenko std_store(vectorValue, vec); 670d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 671239eff50SBenjamin Kramer auto ivsStorage = llvm::to_vector<8>(loopIvs); 672239eff50SBenjamin Kramer // Swap the ivsStorage which will reorder memory accesses. 6734ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 674239eff50SBenjamin Kramer std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]); 675239eff50SBenjamin Kramer 676239eff50SBenjamin Kramer ArrayRef<Value> ivs(ivsStorage); 6778d64df9fSNicolas Vasilache Value pos = 678239eff50SBenjamin Kramer std_index_cast(IntegerType::get(32, op->getContext()), ivs.back()); 679239eff50SBenjamin Kramer auto storeValue = [&](ArrayRef<Value> indices) { 680239eff50SBenjamin Kramer Value scalar = vector_extract_element(local(ivs.drop_back()), pos); 6818d64df9fSNicolas Vasilache remote(indices) = scalar; 682239eff50SBenjamin Kramer }; 683239eff50SBenjamin Kramer emitWithBoundsChecks( 684239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs, 685239eff50SBenjamin Kramer memRefBoundsCapture, storeValue); 6864ead2cf7SAlex Zinenko }); 6874ead2cf7SAlex Zinenko 6888d64df9fSNicolas Vasilache // 3. Erase. 6894ead2cf7SAlex Zinenko rewriter.eraseOp(op); 6904ead2cf7SAlex Zinenko return success(); 6914ead2cf7SAlex Zinenko } 6924ead2cf7SAlex Zinenko 6933393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns( 6947c3c5b11SNicolas Vasilache OwningRewritePatternList &patterns, MLIRContext *context, 6957c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) { 6964ead2cf7SAlex Zinenko patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 6977c3c5b11SNicolas Vasilache VectorTransferRewriter<vector::TransferWriteOp>>(options, 6987c3c5b11SNicolas Vasilache context); 6994ead2cf7SAlex Zinenko } 7003393cc4cSNicolas Vasilache 7013393cc4cSNicolas Vasilache } // namespace mlir 7023393cc4cSNicolas Vasilache 7035f9e0466SNicolas Vasilache namespace { 7045f9e0466SNicolas Vasilache 7055f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass 7065f9e0466SNicolas Vasilache : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> { 7075f9e0466SNicolas Vasilache ConvertVectorToSCFPass() = default; 7085f9e0466SNicolas Vasilache ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 7095f9e0466SNicolas Vasilache this->fullUnroll = options.unroll; 7105f9e0466SNicolas Vasilache } 7115f9e0466SNicolas Vasilache 7125f9e0466SNicolas Vasilache void runOnFunction() override { 7135f9e0466SNicolas Vasilache OwningRewritePatternList patterns; 7145f9e0466SNicolas Vasilache auto *context = getFunction().getContext(); 7155f9e0466SNicolas Vasilache populateVectorToSCFConversionPatterns( 7165f9e0466SNicolas Vasilache patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll)); 7175f9e0466SNicolas Vasilache applyPatternsAndFoldGreedily(getFunction(), patterns); 7185f9e0466SNicolas Vasilache } 7195f9e0466SNicolas Vasilache }; 7205f9e0466SNicolas Vasilache 7215f9e0466SNicolas Vasilache } // namespace 7225f9e0466SNicolas Vasilache 7235f9e0466SNicolas Vasilache std::unique_ptr<Pass> 7245f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 7255f9e0466SNicolas Vasilache return std::make_unique<ConvertVectorToSCFPass>(options); 7265f9e0466SNicolas Vasilache } 727