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 43350dadaaSBenjamin Kramer namespace { 444ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector 454ead2cf7SAlex Zinenko /// transfer operations (read and write). 464ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR 474ead2cf7SAlex Zinenko /// manipulation. 484ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as: 494ead2cf7SAlex Zinenko /// 504ead2cf7SAlex Zinenko /// ``` 514ead2cf7SAlex Zinenko /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 524ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 534ead2cf7SAlex Zinenko /// vector<(major_dims) x (minor_dims) x type> 544ead2cf7SAlex Zinenko /// ``` 554ead2cf7SAlex Zinenko /// 564ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 574ead2cf7SAlex Zinenko /// higher). 584ead2cf7SAlex Zinenko /// 594ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling: 604ead2cf7SAlex Zinenko /// 614ead2cf7SAlex Zinenko /// ``` 624ead2cf7SAlex Zinenko /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 634ead2cf7SAlex Zinenko /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 644ead2cf7SAlex Zinenko /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 654ead2cf7SAlex Zinenko /// %v = vector_transfer_read( 664ead2cf7SAlex Zinenko /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 674ead2cf7SAlex Zinenko /// %ivs_minor): 684ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 694ead2cf7SAlex Zinenko /// vector<(minor_dims) x type>; 704ead2cf7SAlex Zinenko /// store(%v, %tmp); 714ead2cf7SAlex Zinenko /// } else { 724ead2cf7SAlex Zinenko /// %v = splat(vector<(minor_dims) x type>, %fill) 734ead2cf7SAlex Zinenko /// store(%v, %tmp, %ivs_major); 744ead2cf7SAlex Zinenko /// } 754ead2cf7SAlex Zinenko /// } 764ead2cf7SAlex Zinenko /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 774ead2cf7SAlex Zinenko // vector<(major_dims) x (minor_dims) x type> 784ead2cf7SAlex Zinenko /// ``` 794ead2cf7SAlex Zinenko /// 804ead2cf7SAlex Zinenko template <typename ConcreteOp> 814ead2cf7SAlex Zinenko class NDTransferOpHelper { 824ead2cf7SAlex Zinenko public: 837c3c5b11SNicolas Vasilache NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 847c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) 857c3c5b11SNicolas Vasilache : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 864ead2cf7SAlex Zinenko scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 874ead2cf7SAlex Zinenko op(xferOp.getOperation()) { 884ead2cf7SAlex Zinenko vectorType = xferOp.getVectorType(); 899db53a18SRiver Riddle // TODO: when we go to k > 1-D vectors adapt minorRank. 904ead2cf7SAlex Zinenko minorRank = 1; 914ead2cf7SAlex Zinenko majorRank = vectorType.getRank() - minorRank; 92ec2f2cecSNicolas Vasilache leadingRank = xferOp.getLeadingMemRefRank(); 934ead2cf7SAlex Zinenko majorVectorType = 944ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_front(majorRank), 954ead2cf7SAlex Zinenko vectorType.getElementType()); 964ead2cf7SAlex Zinenko minorVectorType = 974ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_back(minorRank), 984ead2cf7SAlex Zinenko vectorType.getElementType()); 994ead2cf7SAlex Zinenko /// Memref of minor vector type is used for individual transfers. 1004ead2cf7SAlex Zinenko memRefMinorVectorType = 1014ead2cf7SAlex Zinenko MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 1024ead2cf7SAlex Zinenko xferOp.getMemRefType().getMemorySpace()); 1034ead2cf7SAlex Zinenko } 1044ead2cf7SAlex Zinenko 1054ead2cf7SAlex Zinenko LogicalResult doReplace(); 1064ead2cf7SAlex Zinenko 1074ead2cf7SAlex Zinenko private: 1084ead2cf7SAlex Zinenko /// Creates the loop nest on the "major" dimensions and calls the 1094ead2cf7SAlex Zinenko /// `loopBodyBuilder` lambda in the context of the loop nest. 1104ead2cf7SAlex Zinenko template <typename Lambda> 1114ead2cf7SAlex Zinenko void emitLoops(Lambda loopBodyBuilder); 1124ead2cf7SAlex Zinenko 1134ead2cf7SAlex Zinenko /// Operate within the body of `emitLoops` to: 1147c3c5b11SNicolas Vasilache /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 1157c3c5b11SNicolas Vasilache /// `majorIvsPlusOffsets`. 1167c3c5b11SNicolas Vasilache /// 2. Return a boolean that determines whether the first `majorIvs.rank()` 1174ead2cf7SAlex Zinenko /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 1187c3c5b11SNicolas Vasilache Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets, 1194ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds, 1207c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets); 1214ead2cf7SAlex Zinenko 1224ead2cf7SAlex Zinenko /// Common state to lower vector transfer ops. 1234ead2cf7SAlex Zinenko PatternRewriter &rewriter; 1247c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options; 1254ead2cf7SAlex Zinenko Location loc; 1264ead2cf7SAlex Zinenko std::unique_ptr<ScopedContext> scope; 1274ead2cf7SAlex Zinenko ConcreteOp xferOp; 1284ead2cf7SAlex Zinenko Operation *op; 1294ead2cf7SAlex Zinenko // A vector transfer copies data between: 1304ead2cf7SAlex Zinenko // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 1314ead2cf7SAlex Zinenko // - vector<(major_dims) x (minor_dims) x type> 1324ead2cf7SAlex Zinenko unsigned minorRank; // for now always 1 1334ead2cf7SAlex Zinenko unsigned majorRank; // vector rank - minorRank 1344ead2cf7SAlex Zinenko unsigned leadingRank; // memref rank - vector rank 1354ead2cf7SAlex Zinenko VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 1364ead2cf7SAlex Zinenko VectorType majorVectorType; // vector<(major_dims) x type> 1374ead2cf7SAlex Zinenko VectorType minorVectorType; // vector<(minor_dims) x type> 1384ead2cf7SAlex Zinenko MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 1394ead2cf7SAlex Zinenko }; 1404ead2cf7SAlex Zinenko 1414ead2cf7SAlex Zinenko template <typename ConcreteOp> 1424ead2cf7SAlex Zinenko template <typename Lambda> 1434ead2cf7SAlex Zinenko void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) { 1444ead2cf7SAlex Zinenko /// Loop nest operates on the major dimensions 1454ead2cf7SAlex Zinenko MemRefBoundsCapture memrefBoundsCapture(xferOp.memref()); 1467c3c5b11SNicolas Vasilache 1477c3c5b11SNicolas Vasilache if (options.unroll) { 1487c3c5b11SNicolas Vasilache auto shape = majorVectorType.getShape(); 1497c3c5b11SNicolas Vasilache auto strides = computeStrides(shape); 1507c3c5b11SNicolas Vasilache unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 1517c3c5b11SNicolas Vasilache ValueRange indices(xferOp.indices()); 1527c3c5b11SNicolas Vasilache for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 1537c3c5b11SNicolas Vasilache SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 1547c3c5b11SNicolas Vasilache SmallVector<Value, 4> offsetValues = 1557c3c5b11SNicolas Vasilache llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 1567c3c5b11SNicolas Vasilache return std_constant_index(off); 1577c3c5b11SNicolas Vasilache })); 1587c3c5b11SNicolas Vasilache loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 1597c3c5b11SNicolas Vasilache indices.drop_front(leadingRank).take_front(majorRank), 1607c3c5b11SNicolas Vasilache indices.take_back(minorRank), memrefBoundsCapture); 1617c3c5b11SNicolas Vasilache } 1627c3c5b11SNicolas Vasilache } else { 1634ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(majorVectorType); 1644ead2cf7SAlex Zinenko auto majorLbs = vectorBoundsCapture.getLbs(); 1654ead2cf7SAlex Zinenko auto majorUbs = vectorBoundsCapture.getUbs(); 1664ead2cf7SAlex Zinenko auto majorSteps = vectorBoundsCapture.getSteps(); 1673f5bd53eSAlex Zinenko affineLoopNestBuilder( 1683f5bd53eSAlex Zinenko majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) { 1694ead2cf7SAlex Zinenko ValueRange indices(xferOp.indices()); 1704ead2cf7SAlex Zinenko loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 1714ead2cf7SAlex Zinenko indices.drop_front(leadingRank).take_front(majorRank), 1724ead2cf7SAlex Zinenko indices.take_back(minorRank), memrefBoundsCapture); 1734ead2cf7SAlex Zinenko }); 1744ead2cf7SAlex Zinenko } 1757c3c5b11SNicolas Vasilache } 1764ead2cf7SAlex Zinenko 177bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) { 178bd87c6bcSNicolas Vasilache if (auto cstOp = v.getDefiningOp<ConstantIndexOp>()) 179bd87c6bcSNicolas Vasilache return cstOp.getValue(); 180bd87c6bcSNicolas Vasilache if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>()) 181bd87c6bcSNicolas Vasilache if (affineApplyOp.getAffineMap().isSingleConstant()) 182bd87c6bcSNicolas Vasilache return affineApplyOp.getAffineMap().getSingleConstantResult(); 183bd87c6bcSNicolas Vasilache return None; 184bd87c6bcSNicolas Vasilache } 185bd87c6bcSNicolas Vasilache 186bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding 187bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go 188bd87c6bcSNicolas Vasilache // away once scf.if folds properly. 189bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) { 190bd87c6bcSNicolas Vasilache using namespace mlir::edsc::op; 191bd87c6bcSNicolas Vasilache auto maybeCstV = extractConstantIndex(v); 192bd87c6bcSNicolas Vasilache auto maybeCstUb = extractConstantIndex(ub); 193bd87c6bcSNicolas Vasilache if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb) 194bd87c6bcSNicolas Vasilache return Value(); 195bd87c6bcSNicolas Vasilache return slt(v, ub); 196bd87c6bcSNicolas Vasilache } 197bd87c6bcSNicolas Vasilache 1984ead2cf7SAlex Zinenko template <typename ConcreteOp> 1997c3c5b11SNicolas Vasilache Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition( 2004ead2cf7SAlex Zinenko ValueRange majorIvs, ValueRange majorOffsets, 2017c3c5b11SNicolas Vasilache MemRefBoundsCapture &memrefBounds, 2027c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets) { 2037c3c5b11SNicolas Vasilache Value inBoundsCondition; 2044ead2cf7SAlex Zinenko majorIvsPlusOffsets.reserve(majorIvs.size()); 2051870e787SNicolas Vasilache unsigned idx = 0; 2064ead2cf7SAlex Zinenko for (auto it : llvm::zip(majorIvs, majorOffsets, memrefBounds.getUbs())) { 2074ead2cf7SAlex Zinenko Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 2084ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 2094ead2cf7SAlex Zinenko majorIvsPlusOffsets.push_back(iv + off); 2101870e787SNicolas Vasilache if (xferOp.isMaskedDim(leadingRank + idx)) { 211bd87c6bcSNicolas Vasilache Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub); 212bd87c6bcSNicolas Vasilache if (inBoundsCond) 213bd87c6bcSNicolas Vasilache inBoundsCondition = (inBoundsCondition) 214bd87c6bcSNicolas Vasilache ? (inBoundsCondition && inBoundsCond) 215bd87c6bcSNicolas Vasilache : inBoundsCond; 2161870e787SNicolas Vasilache } 2171870e787SNicolas Vasilache ++idx; 2184ead2cf7SAlex Zinenko } 2197c3c5b11SNicolas Vasilache return inBoundsCondition; 2204ead2cf7SAlex Zinenko } 2214ead2cf7SAlex Zinenko 222247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations. 223247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType, 224247e185dSNicolas Vasilache Operation *op) { 225247e185dSNicolas Vasilache auto &b = ScopedContext::getBuilderRef(); 226247e185dSNicolas Vasilache OpBuilder::InsertionGuard guard(b); 227*a4b8c2deSJakub Lichman Operation *scope = 228*a4b8c2deSJakub Lichman op->getParentWithTrait<OpTrait::AutomaticAllocationScope>(); 229*a4b8c2deSJakub Lichman assert(scope && "Expected op to be inside automatic allocation scope"); 230*a4b8c2deSJakub Lichman b.setInsertionPointToStart(&scope->getRegion(0).front()); 231247e185dSNicolas Vasilache Value res = 232247e185dSNicolas Vasilache std_alloca(memRefMinorVectorType, ValueRange{}, b.getI64IntegerAttr(128)); 233247e185dSNicolas Vasilache return res; 234247e185dSNicolas Vasilache } 235247e185dSNicolas Vasilache 2364ead2cf7SAlex Zinenko template <> 2374ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 2387c3c5b11SNicolas Vasilache Value alloc, result; 2397c3c5b11SNicolas Vasilache if (options.unroll) 2407c3c5b11SNicolas Vasilache result = std_splat(vectorType, xferOp.padding()); 2417c3c5b11SNicolas Vasilache else 242247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 2434ead2cf7SAlex Zinenko 2444ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 2454ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 2464ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds) { 2477c3c5b11SNicolas Vasilache /// Lambda to load 1-D vector in the current loop ivs + offset context. 2487c3c5b11SNicolas Vasilache auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 2494ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 2504ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 2514ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 2524ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 2534ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 25436cdc17fSNicolas Vasilache Value memref = xferOp.memref(); 25547cbd9f9SNicolas Vasilache auto map = 25647cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 2571870e787SNicolas Vasilache ArrayAttr masked; 258cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 2591870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 260cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 2611870e787SNicolas Vasilache } 2627c3c5b11SNicolas Vasilache return vector_transfer_read(minorVectorType, memref, indexing, 2637c3c5b11SNicolas Vasilache AffineMapAttr::get(map), xferOp.padding(), 2647c3c5b11SNicolas Vasilache masked); 2654ead2cf7SAlex Zinenko }; 2667c3c5b11SNicolas Vasilache 2677c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 2687c3c5b11SNicolas Vasilache // context. 2697c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 2707c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 2717c3c5b11SNicolas Vasilache majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 2727c3c5b11SNicolas Vasilache 2737c3c5b11SNicolas Vasilache if (inBoundsCondition) { 2747c3c5b11SNicolas Vasilache // 2. If the condition is not null, we need an IfOp, which may yield 2757c3c5b11SNicolas Vasilache // if `options.unroll` is true. 2767c3c5b11SNicolas Vasilache SmallVector<Type, 1> resultType; 2777c3c5b11SNicolas Vasilache if (options.unroll) 2787c3c5b11SNicolas Vasilache resultType.push_back(vectorType); 2797c3c5b11SNicolas Vasilache 280cadb7ccfSAlex Zinenko // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise 281cadb7ccfSAlex Zinenko // splat a 1-D vector. 282cadb7ccfSAlex Zinenko ValueRange ifResults = conditionBuilder( 283cadb7ccfSAlex Zinenko resultType, inBoundsCondition, 284cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 2857c3c5b11SNicolas Vasilache Value vector = load1DVector(majorIvsPlusOffsets); 286cadb7ccfSAlex Zinenko // 3.a. If `options.unroll` is true, insert the 1-D vector in the 2877c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `else` branch. 2887c3c5b11SNicolas Vasilache if (options.unroll) { 2897c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 290cadb7ccfSAlex Zinenko return {vector}; 2917c3c5b11SNicolas Vasilache } 292cadb7ccfSAlex Zinenko // 3.b. Otherwise, just go through the temporary `alloc`. 2934ead2cf7SAlex Zinenko std_store(vector, alloc, majorIvs); 294cadb7ccfSAlex Zinenko return {}; 295cadb7ccfSAlex Zinenko }, 296cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 2977c3c5b11SNicolas Vasilache Value vector = std_splat(minorVectorType, xferOp.padding()); 298cadb7ccfSAlex Zinenko // 3.c. If `options.unroll` is true, insert the 1-D vector in the 2997c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `then` branch. 3007c3c5b11SNicolas Vasilache if (options.unroll) { 3017c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 302cadb7ccfSAlex Zinenko return {vector}; 3037c3c5b11SNicolas Vasilache } 304cadb7ccfSAlex Zinenko // 3.d. Otherwise, just go through the temporary `alloc`. 3057c3c5b11SNicolas Vasilache std_store(vector, alloc, majorIvs); 306cadb7ccfSAlex Zinenko return {}; 3077c3c5b11SNicolas Vasilache }); 308cadb7ccfSAlex Zinenko 3097c3c5b11SNicolas Vasilache if (!resultType.empty()) 310cadb7ccfSAlex Zinenko result = *ifResults.begin(); 3117c3c5b11SNicolas Vasilache } else { 3127c3c5b11SNicolas Vasilache // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 3137c3c5b11SNicolas Vasilache Value loaded1D = load1DVector(majorIvsPlusOffsets); 3147c3c5b11SNicolas Vasilache // 5.a. If `options.unroll` is true, insert the 1-D vector in the 3157c3c5b11SNicolas Vasilache // aggregate. 3167c3c5b11SNicolas Vasilache if (options.unroll) 3177c3c5b11SNicolas Vasilache result = vector_insert(loaded1D, result, majorIvs); 3187c3c5b11SNicolas Vasilache // 5.b. Otherwise, just go through the temporary `alloc`. 3197c3c5b11SNicolas Vasilache else 3207c3c5b11SNicolas Vasilache std_store(loaded1D, alloc, majorIvs); 3217c3c5b11SNicolas Vasilache } 3227c3c5b11SNicolas Vasilache }); 3237c3c5b11SNicolas Vasilache 324a9b5edc5SBenjamin Kramer assert((!options.unroll ^ (bool)result) && 325a9b5edc5SBenjamin Kramer "Expected resulting Value iff unroll"); 3267c3c5b11SNicolas Vasilache if (!result) 3277c3c5b11SNicolas Vasilache result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3287c3c5b11SNicolas Vasilache rewriter.replaceOp(op, result); 3294ead2cf7SAlex Zinenko 3304ead2cf7SAlex Zinenko return success(); 3314ead2cf7SAlex Zinenko } 3324ead2cf7SAlex Zinenko 3334ead2cf7SAlex Zinenko template <> 3344ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 3357c3c5b11SNicolas Vasilache Value alloc; 3367c3c5b11SNicolas Vasilache if (!options.unroll) { 337247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 3384ead2cf7SAlex Zinenko std_store(xferOp.vector(), 3394ead2cf7SAlex Zinenko vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3407c3c5b11SNicolas Vasilache } 3414ead2cf7SAlex Zinenko 3424ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 3434ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 3444ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds) { 3457c3c5b11SNicolas Vasilache // Lower to 1-D vector_transfer_write and let recursion handle it. 3467c3c5b11SNicolas Vasilache auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 3474ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 3484ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 3494ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 3504ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 3514ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 3527c3c5b11SNicolas Vasilache Value result; 3537c3c5b11SNicolas Vasilache // If `options.unroll` is true, extract the 1-D vector from the 3547c3c5b11SNicolas Vasilache // aggregate. 3557c3c5b11SNicolas Vasilache if (options.unroll) 3567c3c5b11SNicolas Vasilache result = vector_extract(xferOp.vector(), majorIvs); 3577c3c5b11SNicolas Vasilache else 3587c3c5b11SNicolas Vasilache result = std_load(alloc, majorIvs); 35947cbd9f9SNicolas Vasilache auto map = 36047cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 3611870e787SNicolas Vasilache ArrayAttr masked; 362cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 3631870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 364cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 3651870e787SNicolas Vasilache } 3667c3c5b11SNicolas Vasilache vector_transfer_write(result, xferOp.memref(), indexing, 3671870e787SNicolas Vasilache AffineMapAttr::get(map), masked); 3684ead2cf7SAlex Zinenko }; 3697c3c5b11SNicolas Vasilache 3707c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 3717c3c5b11SNicolas Vasilache // context. 3727c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 3737c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 3747c3c5b11SNicolas Vasilache majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 3757c3c5b11SNicolas Vasilache 3767c3c5b11SNicolas Vasilache if (inBoundsCondition) { 3777c3c5b11SNicolas Vasilache // 2.a. If the condition is not null, we need an IfOp, to write 3787c3c5b11SNicolas Vasilache // conditionally. Progressively lower to a 1-D transfer write. 379cadb7ccfSAlex Zinenko conditionBuilder(inBoundsCondition, 380cadb7ccfSAlex Zinenko [&] { emitTransferWrite(majorIvsPlusOffsets); }); 3817c3c5b11SNicolas Vasilache } else { 3827c3c5b11SNicolas Vasilache // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 3837c3c5b11SNicolas Vasilache emitTransferWrite(majorIvsPlusOffsets); 3847c3c5b11SNicolas Vasilache } 3854ead2cf7SAlex Zinenko }); 3864ead2cf7SAlex Zinenko 3874ead2cf7SAlex Zinenko rewriter.eraseOp(op); 3884ead2cf7SAlex Zinenko 3894ead2cf7SAlex Zinenko return success(); 3904ead2cf7SAlex Zinenko } 3914ead2cf7SAlex Zinenko 392da95a0d8SNicolas Vasilache } // namespace 393da95a0d8SNicolas Vasilache 3944ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote 3954ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found, 3964ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 3974ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop. 3984ead2cf7SAlex Zinenko template <typename TransferOpTy> 3994ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) { 4004ead2cf7SAlex Zinenko // rank of the remote memory access, coalescing behavior occurs on the 4014ead2cf7SAlex Zinenko // innermost memory dimension. 4024ead2cf7SAlex Zinenko auto remoteRank = transfer.getMemRefType().getRank(); 4034ead2cf7SAlex Zinenko // Iterate over the results expressions of the permutation map to determine 4044ead2cf7SAlex Zinenko // the loop order for creating pointwise copies between remote and local 4054ead2cf7SAlex Zinenko // memories. 4064ead2cf7SAlex Zinenko int coalescedIdx = -1; 4074ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4084ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4094ead2cf7SAlex Zinenko auto dim = en.value().template dyn_cast<AffineDimExpr>(); 4104ead2cf7SAlex Zinenko if (!dim) { 4114ead2cf7SAlex Zinenko continue; 4124ead2cf7SAlex Zinenko } 4134ead2cf7SAlex Zinenko auto memRefDim = dim.getPosition(); 4144ead2cf7SAlex Zinenko if (memRefDim == remoteRank - 1) { 4154ead2cf7SAlex Zinenko // memRefDim has coalescing properties, it should be swapped in the last 4164ead2cf7SAlex Zinenko // position. 4174ead2cf7SAlex Zinenko assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 4184ead2cf7SAlex Zinenko coalescedIdx = en.index(); 4194ead2cf7SAlex Zinenko } 4204ead2cf7SAlex Zinenko } 4214ead2cf7SAlex Zinenko return coalescedIdx; 4224ead2cf7SAlex Zinenko } 4234ead2cf7SAlex Zinenko 4244ead2cf7SAlex Zinenko /// Emits remote memory accesses that are clipped to the boundaries of the 4254ead2cf7SAlex Zinenko /// MemRef. 4264ead2cf7SAlex Zinenko template <typename TransferOpTy> 4274ead2cf7SAlex Zinenko static SmallVector<Value, 8> 4284ead2cf7SAlex Zinenko clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) { 4294ead2cf7SAlex Zinenko using namespace mlir::edsc; 4304ead2cf7SAlex Zinenko 4314ead2cf7SAlex Zinenko Value zero(std_constant_index(0)), one(std_constant_index(1)); 4324ead2cf7SAlex Zinenko SmallVector<Value, 8> memRefAccess(transfer.indices()); 4334ead2cf7SAlex Zinenko SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size()); 4344ead2cf7SAlex Zinenko // Indices accessing to remote memory are clipped and their expressions are 4354ead2cf7SAlex Zinenko // returned in clippedScalarAccessExprs. 4364ead2cf7SAlex Zinenko for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size(); 4374ead2cf7SAlex Zinenko ++memRefDim) { 4384ead2cf7SAlex Zinenko // Linear search on a small number of entries. 4394ead2cf7SAlex Zinenko int loopIndex = -1; 4404ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4414ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4424ead2cf7SAlex Zinenko auto expr = en.value(); 4434ead2cf7SAlex Zinenko auto dim = expr.template dyn_cast<AffineDimExpr>(); 4444ead2cf7SAlex Zinenko // Sanity check. 4454ead2cf7SAlex Zinenko assert( 4464ead2cf7SAlex Zinenko (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) && 4474ead2cf7SAlex Zinenko "Expected dim or 0 in permutationMap"); 4484ead2cf7SAlex Zinenko if (dim && memRefDim == dim.getPosition()) { 4494ead2cf7SAlex Zinenko loopIndex = en.index(); 4504ead2cf7SAlex Zinenko break; 4514ead2cf7SAlex Zinenko } 4524ead2cf7SAlex Zinenko } 4534ead2cf7SAlex Zinenko 4544ead2cf7SAlex Zinenko // We cannot distinguish atm between unrolled dimensions that implement 4554ead2cf7SAlex Zinenko // the "always full" tile abstraction and need clipping from the other 4564ead2cf7SAlex Zinenko // ones. So we conservatively clip everything. 4574ead2cf7SAlex Zinenko using namespace edsc::op; 4584ead2cf7SAlex Zinenko auto N = bounds.ub(memRefDim); 4594ead2cf7SAlex Zinenko auto i = memRefAccess[memRefDim]; 4604ead2cf7SAlex Zinenko if (loopIndex < 0) { 4614ead2cf7SAlex Zinenko auto N_minus_1 = N - one; 46225055a4fSAdam D Straw auto select_1 = std_select(slt(i, N), i, N_minus_1); 4634ead2cf7SAlex Zinenko clippedScalarAccessExprs[memRefDim] = 46425055a4fSAdam D Straw std_select(slt(i, zero), zero, select_1); 4654ead2cf7SAlex Zinenko } else { 4664ead2cf7SAlex Zinenko auto ii = ivs[loopIndex]; 4674ead2cf7SAlex Zinenko auto i_plus_ii = i + ii; 4684ead2cf7SAlex Zinenko auto N_minus_1 = N - one; 46925055a4fSAdam D Straw auto select_1 = std_select(slt(i_plus_ii, N), i_plus_ii, N_minus_1); 4704ead2cf7SAlex Zinenko clippedScalarAccessExprs[memRefDim] = 47125055a4fSAdam D Straw std_select(slt(i_plus_ii, zero), zero, select_1); 4724ead2cf7SAlex Zinenko } 4734ead2cf7SAlex Zinenko } 4744ead2cf7SAlex Zinenko 4754ead2cf7SAlex Zinenko return clippedScalarAccessExprs; 4764ead2cf7SAlex Zinenko } 4774ead2cf7SAlex Zinenko 4783393cc4cSNicolas Vasilache namespace mlir { 4793393cc4cSNicolas Vasilache 4804ead2cf7SAlex Zinenko template <typename TransferOpTy> 4813393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 4827c3c5b11SNicolas Vasilache VectorTransferToSCFOptions options, MLIRContext *context) 4837c3c5b11SNicolas Vasilache : RewritePattern(TransferOpTy::getOperationName(), 1, context), 4847c3c5b11SNicolas Vasilache options(options) {} 4854ead2cf7SAlex Zinenko 4867c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer. 4877c3c5b11SNicolas Vasilache template <typename TransferOpTy> 4883393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 4897c3c5b11SNicolas Vasilache TransferOpTy transfer) const { 4904ead2cf7SAlex Zinenko auto vectorType = transfer.getVectorType(); 4917c3c5b11SNicolas Vasilache return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {}, 4927c3c5b11SNicolas Vasilache 0); 4934ead2cf7SAlex Zinenko } 4944ead2cf7SAlex Zinenko 4954ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of: 4964ead2cf7SAlex Zinenko /// 1. local memory allocation; 4974ead2cf7SAlex Zinenko /// 2. perfect loop nest over: 4984ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 4994ead2cf7SAlex Zinenko /// a. scalar store to original memref (with clipping). 5004ead2cf7SAlex Zinenko /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 5014ead2cf7SAlex Zinenko /// 4. local memory deallocation. 5024ead2cf7SAlex Zinenko /// 5034ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no 5044ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 5054ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be read multiple 5064ead2cf7SAlex Zinenko /// times and concurrently. 5074ead2cf7SAlex Zinenko /// 5084ead2cf7SAlex Zinenko /// Important notes about clipping and "full-tiles only" abstraction: 5094ead2cf7SAlex Zinenko /// ================================================================= 5104ead2cf7SAlex Zinenko /// When using clipping for dealing with boundary conditions, the same edge 5114ead2cf7SAlex Zinenko /// value will appear multiple times (a.k.a edge padding). This is fine if the 5124ead2cf7SAlex Zinenko /// subsequent vector operations are all data-parallel but **is generally 5134ead2cf7SAlex Zinenko /// incorrect** in the presence of reductions or extract operations. 5144ead2cf7SAlex Zinenko /// 5154ead2cf7SAlex Zinenko /// More generally, clipping is a scalar abstraction that is expected to work 5164ead2cf7SAlex Zinenko /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs. 5174ead2cf7SAlex Zinenko /// To deal with real vector_load and DMAs, a "padded allocation + view" 5184ead2cf7SAlex Zinenko /// abstraction with the ability to read out-of-memref-bounds (but still within 5194ead2cf7SAlex Zinenko /// the allocated region) is necessary. 5204ead2cf7SAlex Zinenko /// 5214ead2cf7SAlex Zinenko /// Whether using scalar loops or vector_load/DMAs to perform the transfer, 5224ead2cf7SAlex Zinenko /// junk values will be materialized in the vectors and generally need to be 5234ead2cf7SAlex Zinenko /// filtered out and replaced by the "neutral element". This neutral element is 5244ead2cf7SAlex Zinenko /// op-dependent so, in the future, we expect to create a vector filter and 5254ead2cf7SAlex Zinenko /// apply it to a splatted constant vector with the proper neutral element at 5264ead2cf7SAlex Zinenko /// each ssa-use. This filtering is not necessary for pure data-parallel 5274ead2cf7SAlex Zinenko /// operations. 5284ead2cf7SAlex Zinenko /// 5294ead2cf7SAlex Zinenko /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which 5304ead2cf7SAlex Zinenko /// also have concurrency implications. Note that by using clipped scalar stores 5314ead2cf7SAlex Zinenko /// in the presence of data-parallel only operations, we generate code that 5324ead2cf7SAlex Zinenko /// writes the same value multiple time on the edge locations. 5334ead2cf7SAlex Zinenko /// 5349db53a18SRiver Riddle /// TODO: implement alternatives to clipping. 5359db53a18SRiver Riddle /// TODO: support non-data-parallel operations. 5364ead2cf7SAlex Zinenko 5374ead2cf7SAlex Zinenko /// Performs the rewrite. 5384ead2cf7SAlex Zinenko template <> 5393393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite( 5404ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 5414ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 5424ead2cf7SAlex Zinenko 5434ead2cf7SAlex Zinenko TransferReadOp transfer = cast<TransferReadOp>(op); 544ec2f2cecSNicolas Vasilache if (transfer.permutation_map().isMinorIdentity()) { 5454ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 5464ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 5477c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 5487c3c5b11SNicolas Vasilache .doReplace(); 5494ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 5504ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 5514ead2cf7SAlex Zinenko return failure(); 5524ead2cf7SAlex Zinenko } 5534ead2cf7SAlex Zinenko 5544ead2cf7SAlex Zinenko // Conservative lowering to scalar load / stores. 5554ead2cf7SAlex Zinenko // 1. Setup all the captures. 5564ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 5574ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 5584ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 5594ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 5604ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 5614ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 5624ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5634ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 5644ead2cf7SAlex Zinenko coalescedIdx); 5654ead2cf7SAlex Zinenko 5664ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 5674ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 5684ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 5694ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 5704ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 5714ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 5724ead2cf7SAlex Zinenko 5734ead2cf7SAlex Zinenko // 2. Emit alloc-copy-load-dealloc. 5744ead2cf7SAlex Zinenko Value tmp = std_alloc(tmpMemRefType(transfer)); 5754ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 5764ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 577d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 578d1560f39SAlex Zinenko auto ivs = llvm::to_vector<8>(loopIvs); 5794ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 5804ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5814ead2cf7SAlex Zinenko std::swap(ivs.back(), ivs[coalescedIdx]); 5824ead2cf7SAlex Zinenko // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 5834ead2cf7SAlex Zinenko local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs)); 5844ead2cf7SAlex Zinenko }); 5854ead2cf7SAlex Zinenko Value vectorValue = std_load(vec); 5864ead2cf7SAlex Zinenko (std_dealloc(tmp)); // vexing parse 5874ead2cf7SAlex Zinenko 5884ead2cf7SAlex Zinenko // 3. Propagate. 5894ead2cf7SAlex Zinenko rewriter.replaceOp(op, vectorValue); 5904ead2cf7SAlex Zinenko return success(); 5914ead2cf7SAlex Zinenko } 5924ead2cf7SAlex Zinenko 5934ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of: 5944ead2cf7SAlex Zinenko /// 1. local memory allocation; 5954ead2cf7SAlex Zinenko /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 5964ead2cf7SAlex Zinenko /// 3. perfect loop nest over: 5974ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 5984ead2cf7SAlex Zinenko /// a. scalar store to original memref (with clipping). 5994ead2cf7SAlex Zinenko /// 4. local memory deallocation. 6004ead2cf7SAlex Zinenko /// 6014ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no 6024ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 6034ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be written to multiple 6044ead2cf7SAlex Zinenko /// times and concurrently. 6054ead2cf7SAlex Zinenko /// 6064ead2cf7SAlex Zinenko /// See `Important notes about clipping and full-tiles only abstraction` in the 6074ead2cf7SAlex Zinenko /// description of `readClipped` above. 6084ead2cf7SAlex Zinenko /// 6099db53a18SRiver Riddle /// TODO: implement alternatives to clipping. 6109db53a18SRiver Riddle /// TODO: support non-data-parallel operations. 6114ead2cf7SAlex Zinenko template <> 6123393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 6134ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 6144ead2cf7SAlex Zinenko using namespace edsc::op; 6154ead2cf7SAlex Zinenko 6164ead2cf7SAlex Zinenko TransferWriteOp transfer = cast<TransferWriteOp>(op); 617ec2f2cecSNicolas Vasilache if (transfer.permutation_map().isMinorIdentity()) { 6184ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 6194ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 6207c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 6214ead2cf7SAlex Zinenko .doReplace(); 6224ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 6234ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 6244ead2cf7SAlex Zinenko return failure(); 6254ead2cf7SAlex Zinenko } 6264ead2cf7SAlex Zinenko 6274ead2cf7SAlex Zinenko // 1. Setup all the captures. 6284ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 6294ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 6304ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 6314ead2cf7SAlex Zinenko Value vectorValue(transfer.vector()); 6324ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 6334ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 6344ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 6354ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6364ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 6374ead2cf7SAlex Zinenko coalescedIdx); 6384ead2cf7SAlex Zinenko 6394ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 6404ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 6414ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 6424ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 6434ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 6444ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 6454ead2cf7SAlex Zinenko 6464ead2cf7SAlex Zinenko // 2. Emit alloc-store-copy-dealloc. 6474ead2cf7SAlex Zinenko Value tmp = std_alloc(tmpMemRefType(transfer)); 6484ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 6494ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 6504ead2cf7SAlex Zinenko std_store(vectorValue, vec); 651d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 652d1560f39SAlex Zinenko auto ivs = llvm::to_vector<8>(loopIvs); 6534ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 6544ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6554ead2cf7SAlex Zinenko std::swap(ivs.back(), ivs[coalescedIdx]); 6564ead2cf7SAlex Zinenko // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 6574ead2cf7SAlex Zinenko remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs); 6584ead2cf7SAlex Zinenko }); 6594ead2cf7SAlex Zinenko (std_dealloc(tmp)); // vexing parse... 6604ead2cf7SAlex Zinenko 6614ead2cf7SAlex Zinenko rewriter.eraseOp(op); 6624ead2cf7SAlex Zinenko return success(); 6634ead2cf7SAlex Zinenko } 6644ead2cf7SAlex Zinenko 6653393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns( 6667c3c5b11SNicolas Vasilache OwningRewritePatternList &patterns, MLIRContext *context, 6677c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) { 6684ead2cf7SAlex Zinenko patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 6697c3c5b11SNicolas Vasilache VectorTransferRewriter<vector::TransferWriteOp>>(options, 6707c3c5b11SNicolas Vasilache context); 6714ead2cf7SAlex Zinenko } 6723393cc4cSNicolas Vasilache 6733393cc4cSNicolas Vasilache } // namespace mlir 6743393cc4cSNicolas Vasilache 6755f9e0466SNicolas Vasilache namespace { 6765f9e0466SNicolas Vasilache 6775f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass 6785f9e0466SNicolas Vasilache : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> { 6795f9e0466SNicolas Vasilache ConvertVectorToSCFPass() = default; 6805f9e0466SNicolas Vasilache ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 6815f9e0466SNicolas Vasilache this->fullUnroll = options.unroll; 6825f9e0466SNicolas Vasilache } 6835f9e0466SNicolas Vasilache 6845f9e0466SNicolas Vasilache void runOnFunction() override { 6855f9e0466SNicolas Vasilache OwningRewritePatternList patterns; 6865f9e0466SNicolas Vasilache auto *context = getFunction().getContext(); 6875f9e0466SNicolas Vasilache populateVectorToSCFConversionPatterns( 6885f9e0466SNicolas Vasilache patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll)); 6895f9e0466SNicolas Vasilache applyPatternsAndFoldGreedily(getFunction(), patterns); 6905f9e0466SNicolas Vasilache } 6915f9e0466SNicolas Vasilache }; 6925f9e0466SNicolas Vasilache 6935f9e0466SNicolas Vasilache } // namespace 6945f9e0466SNicolas Vasilache 6955f9e0466SNicolas Vasilache std::unique_ptr<Pass> 6965f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 6975f9e0466SNicolas Vasilache return std::make_unique<ConvertVectorToSCFPass>(options); 6985f9e0466SNicolas Vasilache } 699