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/Builders.h"
284ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h"
295f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h"
30b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
315f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h"
324ead2cf7SAlex Zinenko 
334ead2cf7SAlex Zinenko using namespace mlir;
344ead2cf7SAlex Zinenko using namespace mlir::edsc;
354ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics;
364ead2cf7SAlex Zinenko using vector::TransferReadOp;
374ead2cf7SAlex Zinenko using vector::TransferWriteOp;
384ead2cf7SAlex Zinenko 
39af5be38aSNicolas Vasilache // Return a list of Values that correspond to multiple AffineApplyOp, one for
40af5be38aSNicolas Vasilache // each result of `map`. Each `expr` in `map` is canonicalized and folded
41af5be38aSNicolas Vasilache // greedily according to its operands.
42af5be38aSNicolas Vasilache // TODO: factor out in a common location that both linalg and vector can use.
43af5be38aSNicolas Vasilache static SmallVector<Value, 4>
44af5be38aSNicolas Vasilache applyMapToValues(OpBuilder &b, Location loc, AffineMap map, ValueRange values) {
45af5be38aSNicolas Vasilache   SmallVector<Value, 4> res;
46af5be38aSNicolas Vasilache   res.reserve(map.getNumResults());
47af5be38aSNicolas Vasilache   unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols();
48af5be38aSNicolas Vasilache   // For each `expr` in `map`, applies the `expr` to the values extracted from
49af5be38aSNicolas Vasilache   // ranges. If the resulting application can be folded into a Value, the
50af5be38aSNicolas Vasilache   // folding occurs eagerly. Otherwise, an affine.apply operation is emitted.
51af5be38aSNicolas Vasilache   for (auto expr : map.getResults()) {
52af5be38aSNicolas Vasilache     AffineMap map = AffineMap::get(numDims, numSym, expr);
53af5be38aSNicolas Vasilache     SmallVector<Value, 4> operands(values.begin(), values.end());
54af5be38aSNicolas Vasilache     fullyComposeAffineMapAndOperands(&map, &operands);
55af5be38aSNicolas Vasilache     canonicalizeMapAndOperands(&map, &operands);
56af5be38aSNicolas Vasilache     res.push_back(b.createOrFold<AffineApplyOp>(loc, map, operands));
57af5be38aSNicolas Vasilache   }
58af5be38aSNicolas Vasilache   return res;
59af5be38aSNicolas Vasilache }
60af5be38aSNicolas Vasilache 
61350dadaaSBenjamin Kramer namespace {
624ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector
634ead2cf7SAlex Zinenko /// transfer operations (read and write).
644ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR
654ead2cf7SAlex Zinenko /// manipulation.
664ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as:
674ead2cf7SAlex Zinenko ///
684ead2cf7SAlex Zinenko /// ```
694ead2cf7SAlex Zinenko ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
704ead2cf7SAlex Zinenko ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
714ead2cf7SAlex Zinenko ///     vector<(major_dims) x (minor_dims) x type>
724ead2cf7SAlex Zinenko /// ```
734ead2cf7SAlex Zinenko ///
744ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
754ead2cf7SAlex Zinenko /// higher).
764ead2cf7SAlex Zinenko ///
774ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling:
784ead2cf7SAlex Zinenko ///
794ead2cf7SAlex Zinenko /// ```
804ead2cf7SAlex Zinenko ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
814ead2cf7SAlex Zinenko ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
824ead2cf7SAlex Zinenko ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
834ead2cf7SAlex Zinenko ///       %v = vector_transfer_read(
844ead2cf7SAlex Zinenko ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
854ead2cf7SAlex Zinenko ///          %ivs_minor):
864ead2cf7SAlex Zinenko ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
874ead2cf7SAlex Zinenko ///         vector<(minor_dims) x type>;
884ead2cf7SAlex Zinenko ///       store(%v, %tmp);
894ead2cf7SAlex Zinenko ///     } else {
904ead2cf7SAlex Zinenko ///       %v = splat(vector<(minor_dims) x type>, %fill)
914ead2cf7SAlex Zinenko ///       store(%v, %tmp, %ivs_major);
924ead2cf7SAlex Zinenko ///     }
934ead2cf7SAlex Zinenko ///   }
944ead2cf7SAlex Zinenko ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
954ead2cf7SAlex Zinenko //      vector<(major_dims) x (minor_dims) x type>
964ead2cf7SAlex Zinenko /// ```
974ead2cf7SAlex Zinenko ///
984ead2cf7SAlex Zinenko template <typename ConcreteOp>
994ead2cf7SAlex Zinenko class NDTransferOpHelper {
1004ead2cf7SAlex Zinenko public:
1017c3c5b11SNicolas Vasilache   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
1027c3c5b11SNicolas Vasilache                      const VectorTransferToSCFOptions &options)
1037c3c5b11SNicolas Vasilache       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
1044ead2cf7SAlex Zinenko         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
1054ead2cf7SAlex Zinenko         op(xferOp.getOperation()) {
1064ead2cf7SAlex Zinenko     vectorType = xferOp.getVectorType();
1079db53a18SRiver Riddle     // TODO: when we go to k > 1-D vectors adapt minorRank.
1084ead2cf7SAlex Zinenko     minorRank = 1;
1094ead2cf7SAlex Zinenko     majorRank = vectorType.getRank() - minorRank;
11026c8f908SThomas Raoux     leadingRank = xferOp.getLeadingShapedRank();
1114ead2cf7SAlex Zinenko     majorVectorType =
1124ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_front(majorRank),
1134ead2cf7SAlex Zinenko                         vectorType.getElementType());
1144ead2cf7SAlex Zinenko     minorVectorType =
1154ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_back(minorRank),
1164ead2cf7SAlex Zinenko                         vectorType.getElementType());
1174ead2cf7SAlex Zinenko     /// Memref of minor vector type is used for individual transfers.
11826c8f908SThomas Raoux     memRefMinorVectorType = MemRefType::get(
11926c8f908SThomas Raoux         majorVectorType.getShape(), minorVectorType, {},
12026c8f908SThomas Raoux         xferOp.getShapedType().template cast<MemRefType>().getMemorySpace());
1214ead2cf7SAlex Zinenko   }
1224ead2cf7SAlex Zinenko 
1234ead2cf7SAlex Zinenko   LogicalResult doReplace();
1244ead2cf7SAlex Zinenko 
1254ead2cf7SAlex Zinenko private:
1264ead2cf7SAlex Zinenko   /// Creates the loop nest on the "major" dimensions and calls the
1274ead2cf7SAlex Zinenko   /// `loopBodyBuilder` lambda in the context of the loop nest.
128307dc7b2SBenjamin Kramer   void
129307dc7b2SBenjamin Kramer   emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange,
130307dc7b2SBenjamin Kramer                                     ValueRange, const MemRefBoundsCapture &)>
131307dc7b2SBenjamin Kramer                 loopBodyBuilder);
1324ead2cf7SAlex Zinenko 
1334ead2cf7SAlex Zinenko   /// Common state to lower vector transfer ops.
1344ead2cf7SAlex Zinenko   PatternRewriter &rewriter;
1357c3c5b11SNicolas Vasilache   const VectorTransferToSCFOptions &options;
1364ead2cf7SAlex Zinenko   Location loc;
1374ead2cf7SAlex Zinenko   std::unique_ptr<ScopedContext> scope;
1384ead2cf7SAlex Zinenko   ConcreteOp xferOp;
1394ead2cf7SAlex Zinenko   Operation *op;
1404ead2cf7SAlex Zinenko   // A vector transfer copies data between:
1414ead2cf7SAlex Zinenko   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
1424ead2cf7SAlex Zinenko   //   - vector<(major_dims) x (minor_dims) x type>
1434ead2cf7SAlex Zinenko   unsigned minorRank;         // for now always 1
1444ead2cf7SAlex Zinenko   unsigned majorRank;         // vector rank - minorRank
1454ead2cf7SAlex Zinenko   unsigned leadingRank;       // memref rank - vector rank
1464ead2cf7SAlex Zinenko   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
1474ead2cf7SAlex Zinenko   VectorType majorVectorType; // vector<(major_dims) x type>
1484ead2cf7SAlex Zinenko   VectorType minorVectorType; // vector<(minor_dims) x type>
1494ead2cf7SAlex Zinenko   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
1504ead2cf7SAlex Zinenko };
1514ead2cf7SAlex Zinenko 
1524ead2cf7SAlex Zinenko template <typename ConcreteOp>
153307dc7b2SBenjamin Kramer void NDTransferOpHelper<ConcreteOp>::emitLoops(
154307dc7b2SBenjamin Kramer     llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange,
155307dc7b2SBenjamin Kramer                             const MemRefBoundsCapture &)>
156307dc7b2SBenjamin Kramer         loopBodyBuilder) {
1574ead2cf7SAlex Zinenko   /// Loop nest operates on the major dimensions
15826c8f908SThomas Raoux   MemRefBoundsCapture memrefBoundsCapture(xferOp.source());
1597c3c5b11SNicolas Vasilache 
1607c3c5b11SNicolas Vasilache   if (options.unroll) {
1617c3c5b11SNicolas Vasilache     auto shape = majorVectorType.getShape();
1627c3c5b11SNicolas Vasilache     auto strides = computeStrides(shape);
1637c3c5b11SNicolas Vasilache     unsigned numUnrolledInstances = computeMaxLinearIndex(shape);
1647c3c5b11SNicolas Vasilache     ValueRange indices(xferOp.indices());
1657c3c5b11SNicolas Vasilache     for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) {
1667c3c5b11SNicolas Vasilache       SmallVector<int64_t, 4> offsets = delinearize(strides, idx);
1677c3c5b11SNicolas Vasilache       SmallVector<Value, 4> offsetValues =
1687c3c5b11SNicolas Vasilache           llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value {
1697c3c5b11SNicolas Vasilache             return std_constant_index(off);
1707c3c5b11SNicolas Vasilache           }));
1717c3c5b11SNicolas Vasilache       loopBodyBuilder(offsetValues, indices.take_front(leadingRank),
1727c3c5b11SNicolas Vasilache                       indices.drop_front(leadingRank).take_front(majorRank),
1737c3c5b11SNicolas Vasilache                       indices.take_back(minorRank), memrefBoundsCapture);
1747c3c5b11SNicolas Vasilache     }
1757c3c5b11SNicolas Vasilache   } else {
1764ead2cf7SAlex Zinenko     VectorBoundsCapture vectorBoundsCapture(majorVectorType);
1774ead2cf7SAlex Zinenko     auto majorLbs = vectorBoundsCapture.getLbs();
1784ead2cf7SAlex Zinenko     auto majorUbs = vectorBoundsCapture.getUbs();
1794ead2cf7SAlex Zinenko     auto majorSteps = vectorBoundsCapture.getSteps();
1803f5bd53eSAlex Zinenko     affineLoopNestBuilder(
1813f5bd53eSAlex Zinenko         majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) {
1824ead2cf7SAlex Zinenko           ValueRange indices(xferOp.indices());
1834ead2cf7SAlex Zinenko           loopBodyBuilder(majorIvs, indices.take_front(leadingRank),
1844ead2cf7SAlex Zinenko                           indices.drop_front(leadingRank).take_front(majorRank),
1854ead2cf7SAlex Zinenko                           indices.take_back(minorRank), memrefBoundsCapture);
1864ead2cf7SAlex Zinenko         });
1874ead2cf7SAlex Zinenko   }
1887c3c5b11SNicolas Vasilache }
1894ead2cf7SAlex Zinenko 
190bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) {
191bd87c6bcSNicolas Vasilache   if (auto cstOp = v.getDefiningOp<ConstantIndexOp>())
192bd87c6bcSNicolas Vasilache     return cstOp.getValue();
193bd87c6bcSNicolas Vasilache   if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>())
194bd87c6bcSNicolas Vasilache     if (affineApplyOp.getAffineMap().isSingleConstant())
195bd87c6bcSNicolas Vasilache       return affineApplyOp.getAffineMap().getSingleConstantResult();
196bd87c6bcSNicolas Vasilache   return None;
197bd87c6bcSNicolas Vasilache }
198bd87c6bcSNicolas Vasilache 
199bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding
200bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go
201bd87c6bcSNicolas Vasilache // away once scf.if folds properly.
202bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) {
203bd87c6bcSNicolas Vasilache   using namespace mlir::edsc::op;
204bd87c6bcSNicolas Vasilache   auto maybeCstV = extractConstantIndex(v);
205bd87c6bcSNicolas Vasilache   auto maybeCstUb = extractConstantIndex(ub);
206bd87c6bcSNicolas Vasilache   if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb)
207bd87c6bcSNicolas Vasilache     return Value();
208bd87c6bcSNicolas Vasilache   return slt(v, ub);
209bd87c6bcSNicolas Vasilache }
210bd87c6bcSNicolas Vasilache 
211239eff50SBenjamin Kramer ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
212239eff50SBenjamin Kramer ///      `majorIvsPlusOffsets`.
213af5be38aSNicolas Vasilache ///   2. Return a value of i1 that determines whether the first
214af5be38aSNicolas Vasilache ///   `majorIvs.rank()`
215239eff50SBenjamin Kramer ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
216239eff50SBenjamin Kramer static Value
217239eff50SBenjamin Kramer emitInBoundsCondition(PatternRewriter &rewriter,
218239eff50SBenjamin Kramer                       VectorTransferOpInterface xferOp, unsigned leadingRank,
2194ead2cf7SAlex Zinenko                       ValueRange majorIvs, ValueRange majorOffsets,
220307dc7b2SBenjamin Kramer                       const MemRefBoundsCapture &memrefBounds,
2217c3c5b11SNicolas Vasilache                       SmallVectorImpl<Value> &majorIvsPlusOffsets) {
2227c3c5b11SNicolas Vasilache   Value inBoundsCondition;
2234ead2cf7SAlex Zinenko   majorIvsPlusOffsets.reserve(majorIvs.size());
2241870e787SNicolas Vasilache   unsigned idx = 0;
2258dace28fSJakub Lichman   SmallVector<Value, 4> bounds =
226af5be38aSNicolas Vasilache       applyMapToValues(rewriter, xferOp.getLoc(), xferOp.permutation_map(),
227af5be38aSNicolas Vasilache                        memrefBounds.getUbs());
2288dace28fSJakub Lichman   for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) {
2294ead2cf7SAlex Zinenko     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
2304ead2cf7SAlex Zinenko     using namespace mlir::edsc::op;
2314ead2cf7SAlex Zinenko     majorIvsPlusOffsets.push_back(iv + off);
2321870e787SNicolas Vasilache     if (xferOp.isMaskedDim(leadingRank + idx)) {
233bd87c6bcSNicolas Vasilache       Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub);
234bd87c6bcSNicolas Vasilache       if (inBoundsCond)
235bd87c6bcSNicolas Vasilache         inBoundsCondition = (inBoundsCondition)
236bd87c6bcSNicolas Vasilache                                 ? (inBoundsCondition && inBoundsCond)
237bd87c6bcSNicolas Vasilache                                 : inBoundsCond;
2381870e787SNicolas Vasilache     }
2391870e787SNicolas Vasilache     ++idx;
2404ead2cf7SAlex Zinenko   }
2417c3c5b11SNicolas Vasilache   return inBoundsCondition;
2424ead2cf7SAlex Zinenko }
2434ead2cf7SAlex Zinenko 
244247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations.
245247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
246247e185dSNicolas Vasilache                                      Operation *op) {
247247e185dSNicolas Vasilache   auto &b = ScopedContext::getBuilderRef();
248247e185dSNicolas Vasilache   OpBuilder::InsertionGuard guard(b);
249a4b8c2deSJakub Lichman   Operation *scope =
250a4b8c2deSJakub Lichman       op->getParentWithTrait<OpTrait::AutomaticAllocationScope>();
251a4b8c2deSJakub Lichman   assert(scope && "Expected op to be inside automatic allocation scope");
252a4b8c2deSJakub Lichman   b.setInsertionPointToStart(&scope->getRegion(0).front());
2538d64df9fSNicolas Vasilache   Value res = std_alloca(memRefMinorVectorType);
254247e185dSNicolas Vasilache   return res;
255247e185dSNicolas Vasilache }
256247e185dSNicolas Vasilache 
2574ead2cf7SAlex Zinenko template <>
2584ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
2597c3c5b11SNicolas Vasilache   Value alloc, result;
2607c3c5b11SNicolas Vasilache   if (options.unroll)
2617c3c5b11SNicolas Vasilache     result = std_splat(vectorType, xferOp.padding());
2627c3c5b11SNicolas Vasilache   else
263247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
2644ead2cf7SAlex Zinenko 
2654ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
2664ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
267307dc7b2SBenjamin Kramer                 const MemRefBoundsCapture &memrefBounds) {
2687c3c5b11SNicolas Vasilache     /// Lambda to load 1-D vector in the current loop ivs + offset context.
2697c3c5b11SNicolas Vasilache     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
2704ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
2714ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
2724ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
2734ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
2744ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
27526c8f908SThomas Raoux       Value memref = xferOp.source();
27647cbd9f9SNicolas Vasilache       auto map =
27726c8f908SThomas Raoux           getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType);
2781870e787SNicolas Vasilache       ArrayAttr masked;
279cc0a58d7SNicolas Vasilache       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
2801870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
281cc0a58d7SNicolas Vasilache         masked = b.getBoolArrayAttr({false});
2821870e787SNicolas Vasilache       }
2837c3c5b11SNicolas Vasilache       return vector_transfer_read(minorVectorType, memref, indexing,
2847c3c5b11SNicolas Vasilache                                   AffineMapAttr::get(map), xferOp.padding(),
2857c3c5b11SNicolas Vasilache                                   masked);
2864ead2cf7SAlex Zinenko     };
2877c3c5b11SNicolas Vasilache 
2887c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
2897c3c5b11SNicolas Vasilache     // context.
2907c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
2917c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
292239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
293239eff50SBenjamin Kramer         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
2947c3c5b11SNicolas Vasilache 
2957c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
2967c3c5b11SNicolas Vasilache       // 2. If the condition is not null, we need an IfOp, which may yield
2977c3c5b11SNicolas Vasilache       // if `options.unroll` is true.
2987c3c5b11SNicolas Vasilache       SmallVector<Type, 1> resultType;
2997c3c5b11SNicolas Vasilache       if (options.unroll)
3007c3c5b11SNicolas Vasilache         resultType.push_back(vectorType);
3017c3c5b11SNicolas Vasilache 
302cadb7ccfSAlex Zinenko       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
303cadb7ccfSAlex Zinenko       // splat a 1-D vector.
304cadb7ccfSAlex Zinenko       ValueRange ifResults = conditionBuilder(
305cadb7ccfSAlex Zinenko           resultType, inBoundsCondition,
306cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
3077c3c5b11SNicolas Vasilache             Value vector = load1DVector(majorIvsPlusOffsets);
308cadb7ccfSAlex Zinenko             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
3097c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `else` branch.
3107c3c5b11SNicolas Vasilache             if (options.unroll) {
3117c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
312cadb7ccfSAlex Zinenko               return {vector};
3137c3c5b11SNicolas Vasilache             }
314cadb7ccfSAlex Zinenko             // 3.b. Otherwise, just go through the temporary `alloc`.
3154ead2cf7SAlex Zinenko             std_store(vector, alloc, majorIvs);
316cadb7ccfSAlex Zinenko             return {};
317cadb7ccfSAlex Zinenko           },
318cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
3197c3c5b11SNicolas Vasilache             Value vector = std_splat(minorVectorType, xferOp.padding());
320cadb7ccfSAlex Zinenko             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
3217c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `then` branch.
3227c3c5b11SNicolas Vasilache             if (options.unroll) {
3237c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
324cadb7ccfSAlex Zinenko               return {vector};
3257c3c5b11SNicolas Vasilache             }
326cadb7ccfSAlex Zinenko             // 3.d. Otherwise, just go through the temporary `alloc`.
3277c3c5b11SNicolas Vasilache             std_store(vector, alloc, majorIvs);
328cadb7ccfSAlex Zinenko             return {};
3297c3c5b11SNicolas Vasilache           });
330cadb7ccfSAlex Zinenko 
3317c3c5b11SNicolas Vasilache       if (!resultType.empty())
332cadb7ccfSAlex Zinenko         result = *ifResults.begin();
3337c3c5b11SNicolas Vasilache     } else {
3347c3c5b11SNicolas Vasilache       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
3357c3c5b11SNicolas Vasilache       Value loaded1D = load1DVector(majorIvsPlusOffsets);
3367c3c5b11SNicolas Vasilache       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
3377c3c5b11SNicolas Vasilache       // aggregate.
3387c3c5b11SNicolas Vasilache       if (options.unroll)
3397c3c5b11SNicolas Vasilache         result = vector_insert(loaded1D, result, majorIvs);
3407c3c5b11SNicolas Vasilache       // 5.b. Otherwise, just go through the temporary `alloc`.
3417c3c5b11SNicolas Vasilache       else
3427c3c5b11SNicolas Vasilache         std_store(loaded1D, alloc, majorIvs);
3437c3c5b11SNicolas Vasilache     }
3447c3c5b11SNicolas Vasilache   });
3457c3c5b11SNicolas Vasilache 
346a9b5edc5SBenjamin Kramer   assert((!options.unroll ^ (bool)result) &&
347a9b5edc5SBenjamin Kramer          "Expected resulting Value iff unroll");
3487c3c5b11SNicolas Vasilache   if (!result)
3497c3c5b11SNicolas Vasilache     result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
3507c3c5b11SNicolas Vasilache   rewriter.replaceOp(op, result);
3514ead2cf7SAlex Zinenko 
3524ead2cf7SAlex Zinenko   return success();
3534ead2cf7SAlex Zinenko }
3544ead2cf7SAlex Zinenko 
3554ead2cf7SAlex Zinenko template <>
3564ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
3577c3c5b11SNicolas Vasilache   Value alloc;
3587c3c5b11SNicolas Vasilache   if (!options.unroll) {
359247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
3604ead2cf7SAlex Zinenko     std_store(xferOp.vector(),
3614ead2cf7SAlex Zinenko               vector_type_cast(MemRefType::get({}, vectorType), alloc));
3627c3c5b11SNicolas Vasilache   }
3634ead2cf7SAlex Zinenko 
3644ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
3654ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
366307dc7b2SBenjamin Kramer                 const MemRefBoundsCapture &memrefBounds) {
3677c3c5b11SNicolas Vasilache     // Lower to 1-D vector_transfer_write and let recursion handle it.
3687c3c5b11SNicolas Vasilache     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
3694ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
3704ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
3714ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
3724ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
3734ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
3747c3c5b11SNicolas Vasilache       Value result;
3757c3c5b11SNicolas Vasilache       // If `options.unroll` is true, extract the 1-D vector from the
3767c3c5b11SNicolas Vasilache       // aggregate.
3777c3c5b11SNicolas Vasilache       if (options.unroll)
3787c3c5b11SNicolas Vasilache         result = vector_extract(xferOp.vector(), majorIvs);
3797c3c5b11SNicolas Vasilache       else
3807c3c5b11SNicolas Vasilache         result = std_load(alloc, majorIvs);
38147cbd9f9SNicolas Vasilache       auto map =
38226c8f908SThomas Raoux           getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType);
3831870e787SNicolas Vasilache       ArrayAttr masked;
384cc0a58d7SNicolas Vasilache       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
3851870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
386cc0a58d7SNicolas Vasilache         masked = b.getBoolArrayAttr({false});
3871870e787SNicolas Vasilache       }
38826c8f908SThomas Raoux       vector_transfer_write(result, xferOp.source(), indexing,
3891870e787SNicolas Vasilache                             AffineMapAttr::get(map), masked);
3904ead2cf7SAlex Zinenko     };
3917c3c5b11SNicolas Vasilache 
3927c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
3937c3c5b11SNicolas Vasilache     // context.
3947c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
3957c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
396239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
397239eff50SBenjamin Kramer         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
3987c3c5b11SNicolas Vasilache 
3997c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
4007c3c5b11SNicolas Vasilache       // 2.a. If the condition is not null, we need an IfOp, to write
4017c3c5b11SNicolas Vasilache       // conditionally. Progressively lower to a 1-D transfer write.
402cadb7ccfSAlex Zinenko       conditionBuilder(inBoundsCondition,
403cadb7ccfSAlex Zinenko                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
4047c3c5b11SNicolas Vasilache     } else {
4057c3c5b11SNicolas Vasilache       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
4067c3c5b11SNicolas Vasilache       emitTransferWrite(majorIvsPlusOffsets);
4077c3c5b11SNicolas Vasilache     }
4084ead2cf7SAlex Zinenko   });
4094ead2cf7SAlex Zinenko 
4104ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
4114ead2cf7SAlex Zinenko 
4124ead2cf7SAlex Zinenko   return success();
4134ead2cf7SAlex Zinenko }
4144ead2cf7SAlex Zinenko 
415df63eedeSBenjamin Kramer } // namespace
416df63eedeSBenjamin Kramer 
4174ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote
4184ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found,
4194ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
4204ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop.
4214ead2cf7SAlex Zinenko template <typename TransferOpTy>
4224ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) {
4234ead2cf7SAlex Zinenko   // rank of the remote memory access, coalescing behavior occurs on the
4244ead2cf7SAlex Zinenko   // innermost memory dimension.
42526c8f908SThomas Raoux   auto remoteRank = transfer.getShapedType().getRank();
4264ead2cf7SAlex Zinenko   // Iterate over the results expressions of the permutation map to determine
4274ead2cf7SAlex Zinenko   // the loop order for creating pointwise copies between remote and local
4284ead2cf7SAlex Zinenko   // memories.
4294ead2cf7SAlex Zinenko   int coalescedIdx = -1;
4304ead2cf7SAlex Zinenko   auto exprs = transfer.permutation_map().getResults();
4314ead2cf7SAlex Zinenko   for (auto en : llvm::enumerate(exprs)) {
4324ead2cf7SAlex Zinenko     auto dim = en.value().template dyn_cast<AffineDimExpr>();
4334ead2cf7SAlex Zinenko     if (!dim) {
4344ead2cf7SAlex Zinenko       continue;
4354ead2cf7SAlex Zinenko     }
4364ead2cf7SAlex Zinenko     auto memRefDim = dim.getPosition();
4374ead2cf7SAlex Zinenko     if (memRefDim == remoteRank - 1) {
4384ead2cf7SAlex Zinenko       // memRefDim has coalescing properties, it should be swapped in the last
4394ead2cf7SAlex Zinenko       // position.
4404ead2cf7SAlex Zinenko       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
4414ead2cf7SAlex Zinenko       coalescedIdx = en.index();
4424ead2cf7SAlex Zinenko     }
4434ead2cf7SAlex Zinenko   }
4444ead2cf7SAlex Zinenko   return coalescedIdx;
4454ead2cf7SAlex Zinenko }
4464ead2cf7SAlex Zinenko 
4474ead2cf7SAlex Zinenko template <typename TransferOpTy>
4483393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
4497c3c5b11SNicolas Vasilache     VectorTransferToSCFOptions options, MLIRContext *context)
4507c3c5b11SNicolas Vasilache     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
4517c3c5b11SNicolas Vasilache       options(options) {}
4524ead2cf7SAlex Zinenko 
4537c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer.
4547c3c5b11SNicolas Vasilache template <typename TransferOpTy>
4553393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
4567c3c5b11SNicolas Vasilache     TransferOpTy transfer) const {
4574ead2cf7SAlex Zinenko   auto vectorType = transfer.getVectorType();
4588d64df9fSNicolas Vasilache   return MemRefType::get(vectorType.getShape().drop_back(),
4598d64df9fSNicolas Vasilache                          VectorType::get(vectorType.getShape().take_back(),
4608d64df9fSNicolas Vasilache                                          vectorType.getElementType()),
4618d64df9fSNicolas Vasilache                          {}, 0);
4624ead2cf7SAlex Zinenko }
4634ead2cf7SAlex Zinenko 
464239eff50SBenjamin Kramer static void emitWithBoundsChecks(
465239eff50SBenjamin Kramer     PatternRewriter &rewriter, VectorTransferOpInterface transfer,
466307dc7b2SBenjamin Kramer     ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture,
467239eff50SBenjamin Kramer     function_ref<void(ArrayRef<Value>)> inBoundsFun,
468239eff50SBenjamin Kramer     function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) {
469239eff50SBenjamin Kramer   // Permute the incoming indices according to the permutation map.
470239eff50SBenjamin Kramer   SmallVector<Value, 4> indices =
471af5be38aSNicolas Vasilache       applyMapToValues(rewriter, transfer.getLoc(), transfer.permutation_map(),
472af5be38aSNicolas Vasilache                        transfer.indices());
473239eff50SBenjamin Kramer 
474239eff50SBenjamin Kramer   // Generate a bounds check if necessary.
475239eff50SBenjamin Kramer   SmallVector<Value, 4> majorIvsPlusOffsets;
476239eff50SBenjamin Kramer   Value inBoundsCondition =
477239eff50SBenjamin Kramer       emitInBoundsCondition(rewriter, transfer, 0, ivs, indices,
478239eff50SBenjamin Kramer                             memRefBoundsCapture, majorIvsPlusOffsets);
479239eff50SBenjamin Kramer 
480239eff50SBenjamin Kramer   // Apply the permutation map to the ivs. The permutation map may not use all
481239eff50SBenjamin Kramer   // the inputs.
482239eff50SBenjamin Kramer   SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size());
483239eff50SBenjamin Kramer   for (unsigned memRefDim = 0; memRefDim < transfer.indices().size();
484239eff50SBenjamin Kramer        ++memRefDim) {
485239eff50SBenjamin Kramer     // Linear search on a small number of entries.
486239eff50SBenjamin Kramer     int loopIndex = -1;
487239eff50SBenjamin Kramer     auto exprs = transfer.permutation_map().getResults();
488239eff50SBenjamin Kramer     for (auto en : llvm::enumerate(exprs)) {
489239eff50SBenjamin Kramer       auto expr = en.value();
490239eff50SBenjamin Kramer       auto dim = expr.dyn_cast<AffineDimExpr>();
491239eff50SBenjamin Kramer       // Sanity check.
492239eff50SBenjamin Kramer       assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) &&
493239eff50SBenjamin Kramer              "Expected dim or 0 in permutationMap");
494239eff50SBenjamin Kramer       if (dim && memRefDim == dim.getPosition()) {
495239eff50SBenjamin Kramer         loopIndex = en.index();
496239eff50SBenjamin Kramer         break;
497239eff50SBenjamin Kramer       }
498239eff50SBenjamin Kramer     }
499239eff50SBenjamin Kramer 
500239eff50SBenjamin Kramer     using namespace edsc::op;
501239eff50SBenjamin Kramer     auto i = transfer.indices()[memRefDim];
502239eff50SBenjamin Kramer     scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex];
503239eff50SBenjamin Kramer   }
504239eff50SBenjamin Kramer 
505239eff50SBenjamin Kramer   if (inBoundsCondition)
506239eff50SBenjamin Kramer     conditionBuilder(
507239eff50SBenjamin Kramer         /* scf.if */ inBoundsCondition, // {
508239eff50SBenjamin Kramer         [&] { inBoundsFun(scalarAccessExprs); },
509239eff50SBenjamin Kramer         // } else {
510239eff50SBenjamin Kramer         outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); }
511239eff50SBenjamin Kramer                        : function_ref<void()>()
512239eff50SBenjamin Kramer         // }
513239eff50SBenjamin Kramer     );
514239eff50SBenjamin Kramer   else
515239eff50SBenjamin Kramer     inBoundsFun(scalarAccessExprs);
516239eff50SBenjamin Kramer }
517239eff50SBenjamin Kramer 
51851d30c34SBenjamin Kramer namespace mlir {
51951d30c34SBenjamin Kramer 
5204ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of:
5214ead2cf7SAlex Zinenko ///   1. local memory allocation;
5224ead2cf7SAlex Zinenko ///   2. perfect loop nest over:
5234ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
524307dc7b2SBenjamin Kramer ///      a. scalar store to original memref (with padding).
5254ead2cf7SAlex Zinenko ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
5264ead2cf7SAlex Zinenko ///   4. local memory deallocation.
5274ead2cf7SAlex Zinenko ///
5284ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no
5294ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
530307dc7b2SBenjamin Kramer /// padding.
5314ead2cf7SAlex Zinenko 
5324ead2cf7SAlex Zinenko /// Performs the rewrite.
5334ead2cf7SAlex Zinenko template <>
5343393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
5354ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
5364ead2cf7SAlex Zinenko   using namespace mlir::edsc::op;
5374ead2cf7SAlex Zinenko 
5384ead2cf7SAlex Zinenko   TransferReadOp transfer = cast<TransferReadOp>(op);
53926c8f908SThomas Raoux   auto memRefType = transfer.getShapedType().dyn_cast<MemRefType>();
54026c8f908SThomas Raoux   if (!memRefType)
54126c8f908SThomas Raoux     return failure();
542dfb7b3feSBenjamin Kramer   // Fall back to a loop if the fastest varying stride is not 1 or it is
543dfb7b3feSBenjamin Kramer   // permuted.
544dfb7b3feSBenjamin Kramer   int64_t offset;
545dfb7b3feSBenjamin Kramer   SmallVector<int64_t, 4> strides;
54626c8f908SThomas Raoux   auto successStrides = getStridesAndOffset(memRefType, strides, offset);
547dfb7b3feSBenjamin Kramer   if (succeeded(successStrides) && strides.back() == 1 &&
548dfb7b3feSBenjamin Kramer       transfer.permutation_map().isMinorIdentity()) {
5494ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
5504ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
5517c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
5527c3c5b11SNicolas Vasilache           .doReplace();
5534ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
5544ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
5554ead2cf7SAlex Zinenko       return failure();
5564ead2cf7SAlex Zinenko   }
5574ead2cf7SAlex Zinenko 
5584ead2cf7SAlex Zinenko   // Conservative lowering to scalar load / stores.
5594ead2cf7SAlex Zinenko   // 1. Setup all the captures.
5604ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
56126c8f908SThomas Raoux   StdIndexedValue remote(transfer.source());
56226c8f908SThomas Raoux   MemRefBoundsCapture memRefBoundsCapture(transfer.source());
5634ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
5644ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
5654ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
5664ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
5674ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
5684ead2cf7SAlex Zinenko                                    coalescedIdx);
5694ead2cf7SAlex Zinenko 
5704ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
5714ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
5724ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
5734ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
5744ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
5754ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
5764ead2cf7SAlex Zinenko 
5774ead2cf7SAlex Zinenko   // 2. Emit alloc-copy-load-dealloc.
5789be61784SNicolas Vasilache   MLIRContext *ctx = op->getContext();
5798d64df9fSNicolas Vasilache   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
5804ead2cf7SAlex Zinenko   StdIndexedValue local(tmp);
581d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
582239eff50SBenjamin Kramer     auto ivsStorage = llvm::to_vector<8>(loopIvs);
5834ead2cf7SAlex Zinenko     // Swap the ivs which will reorder memory accesses.
5844ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
585239eff50SBenjamin Kramer       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
586239eff50SBenjamin Kramer 
587239eff50SBenjamin Kramer     ArrayRef<Value> ivs(ivsStorage);
5881b97cdf8SRiver Riddle     Value pos = std_index_cast(IntegerType::get(ctx, 32), ivs.back());
589239eff50SBenjamin Kramer     Value inVector = local(ivs.drop_back());
590239eff50SBenjamin Kramer     auto loadValue = [&](ArrayRef<Value> indices) {
591239eff50SBenjamin Kramer       Value vector = vector_insert_element(remote(indices), inVector, pos);
592239eff50SBenjamin Kramer       local(ivs.drop_back()) = vector;
593239eff50SBenjamin Kramer     };
594239eff50SBenjamin Kramer     auto loadPadding = [&](ArrayRef<Value>) {
595239eff50SBenjamin Kramer       Value vector = vector_insert_element(transfer.padding(), inVector, pos);
596239eff50SBenjamin Kramer       local(ivs.drop_back()) = vector;
597239eff50SBenjamin Kramer     };
598239eff50SBenjamin Kramer     emitWithBoundsChecks(
599239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
600239eff50SBenjamin Kramer         memRefBoundsCapture, loadValue, loadPadding);
6014ead2cf7SAlex Zinenko   });
6029be61784SNicolas Vasilache   Value vectorValue = std_load(vector_type_cast(tmp));
6034ead2cf7SAlex Zinenko 
6044ead2cf7SAlex Zinenko   // 3. Propagate.
6054ead2cf7SAlex Zinenko   rewriter.replaceOp(op, vectorValue);
6064ead2cf7SAlex Zinenko   return success();
6074ead2cf7SAlex Zinenko }
6084ead2cf7SAlex Zinenko 
6094ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of:
6104ead2cf7SAlex Zinenko ///   1. local memory allocation;
6114ead2cf7SAlex Zinenko ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
6124ead2cf7SAlex Zinenko ///   3. perfect loop nest over:
6134ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
614307dc7b2SBenjamin Kramer ///      a. scalar store to original memref (if in bounds).
6154ead2cf7SAlex Zinenko ///   4. local memory deallocation.
6164ead2cf7SAlex Zinenko ///
6174ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no
618307dc7b2SBenjamin Kramer /// out-of-bounds accesses are possible.
6194ead2cf7SAlex Zinenko template <>
6203393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
6214ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
6224ead2cf7SAlex Zinenko   using namespace edsc::op;
6234ead2cf7SAlex Zinenko 
6244ead2cf7SAlex Zinenko   TransferWriteOp transfer = cast<TransferWriteOp>(op);
62526c8f908SThomas Raoux   auto memRefType = transfer.getShapedType().template dyn_cast<MemRefType>();
62626c8f908SThomas Raoux   if (!memRefType)
62726c8f908SThomas Raoux     return failure();
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;
63326c8f908SThomas Raoux   auto successStrides = getStridesAndOffset(memRefType, strides, offset);
634dfb7b3feSBenjamin Kramer   if (succeeded(successStrides) && strides.back() == 1 &&
635dfb7b3feSBenjamin Kramer       transfer.permutation_map().isMinorIdentity()) {
6364ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
6374ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
6387c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
6394ead2cf7SAlex Zinenko           .doReplace();
6404ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
6414ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
6424ead2cf7SAlex Zinenko       return failure();
6434ead2cf7SAlex Zinenko   }
6444ead2cf7SAlex Zinenko 
6454ead2cf7SAlex Zinenko   // 1. Setup all the captures.
6464ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
64726c8f908SThomas Raoux   StdIndexedValue remote(transfer.source());
64826c8f908SThomas Raoux   MemRefBoundsCapture memRefBoundsCapture(transfer.source());
6494ead2cf7SAlex Zinenko   Value vectorValue(transfer.vector());
6504ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
6514ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
6524ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
6534ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
6544ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
6554ead2cf7SAlex Zinenko                                    coalescedIdx);
6564ead2cf7SAlex Zinenko 
6574ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
6584ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
6594ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
6604ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
6614ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
6624ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
6634ead2cf7SAlex Zinenko 
6644ead2cf7SAlex Zinenko   // 2. Emit alloc-store-copy-dealloc.
6658d64df9fSNicolas Vasilache   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
6664ead2cf7SAlex Zinenko   StdIndexedValue local(tmp);
6674ead2cf7SAlex Zinenko   Value vec = vector_type_cast(tmp);
6684ead2cf7SAlex Zinenko   std_store(vectorValue, vec);
669d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
670239eff50SBenjamin Kramer     auto ivsStorage = llvm::to_vector<8>(loopIvs);
671239eff50SBenjamin Kramer     // Swap the ivsStorage which will reorder memory accesses.
6724ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
673239eff50SBenjamin Kramer       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
674239eff50SBenjamin Kramer 
675239eff50SBenjamin Kramer     ArrayRef<Value> ivs(ivsStorage);
6768d64df9fSNicolas Vasilache     Value pos =
6771b97cdf8SRiver Riddle         std_index_cast(IntegerType::get(op->getContext(), 32), ivs.back());
678239eff50SBenjamin Kramer     auto storeValue = [&](ArrayRef<Value> indices) {
679239eff50SBenjamin Kramer       Value scalar = vector_extract_element(local(ivs.drop_back()), pos);
6808d64df9fSNicolas Vasilache       remote(indices) = scalar;
681239eff50SBenjamin Kramer     };
682239eff50SBenjamin Kramer     emitWithBoundsChecks(
683239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
684239eff50SBenjamin Kramer         memRefBoundsCapture, storeValue);
6854ead2cf7SAlex Zinenko   });
6864ead2cf7SAlex Zinenko 
6878d64df9fSNicolas Vasilache   // 3. Erase.
6884ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
6894ead2cf7SAlex Zinenko   return success();
6904ead2cf7SAlex Zinenko }
6914ead2cf7SAlex Zinenko 
6923393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns(
6937c3c5b11SNicolas Vasilache     OwningRewritePatternList &patterns, MLIRContext *context,
6947c3c5b11SNicolas Vasilache     const VectorTransferToSCFOptions &options) {
6954ead2cf7SAlex Zinenko   patterns.insert<VectorTransferRewriter<vector::TransferReadOp>,
6967c3c5b11SNicolas Vasilache                   VectorTransferRewriter<vector::TransferWriteOp>>(options,
6977c3c5b11SNicolas Vasilache                                                                    context);
6984ead2cf7SAlex Zinenko }
6993393cc4cSNicolas Vasilache 
7003393cc4cSNicolas Vasilache } // namespace mlir
7013393cc4cSNicolas Vasilache 
7025f9e0466SNicolas Vasilache namespace {
7035f9e0466SNicolas Vasilache 
7045f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass
7055f9e0466SNicolas Vasilache     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
7065f9e0466SNicolas Vasilache   ConvertVectorToSCFPass() = default;
7075f9e0466SNicolas Vasilache   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
7085f9e0466SNicolas Vasilache     this->fullUnroll = options.unroll;
7095f9e0466SNicolas Vasilache   }
7105f9e0466SNicolas Vasilache 
7115f9e0466SNicolas Vasilache   void runOnFunction() override {
7125f9e0466SNicolas Vasilache     OwningRewritePatternList patterns;
7135f9e0466SNicolas Vasilache     auto *context = getFunction().getContext();
7145f9e0466SNicolas Vasilache     populateVectorToSCFConversionPatterns(
7155f9e0466SNicolas Vasilache         patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll));
716*e21adfa3SRiver Riddle     (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
7175f9e0466SNicolas Vasilache   }
7185f9e0466SNicolas Vasilache };
7195f9e0466SNicolas Vasilache 
7205f9e0466SNicolas Vasilache } // namespace
7215f9e0466SNicolas Vasilache 
7225f9e0466SNicolas Vasilache std::unique_ptr<Pass>
7235f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
7245f9e0466SNicolas Vasilache   return std::make_unique<ConvertVectorToSCFPass>(options);
7255f9e0466SNicolas Vasilache }
726