1 //===- VectorToSCF.cpp - Conversion from Vector to mix of SCF and Std -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements target-dependent lowering of vector transfer operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <type_traits>
14 
15 #include "mlir/Conversion/VectorToSCF/VectorToSCF.h"
16 
17 #include "../PassDetail.h"
18 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h"
19 #include "mlir/Dialect/SCF/EDSC/Builders.h"
20 #include "mlir/Dialect/SCF/EDSC/Intrinsics.h"
21 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
22 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
23 #include "mlir/Dialect/Vector/VectorOps.h"
24 #include "mlir/Dialect/Vector/VectorUtils.h"
25 #include "mlir/IR/AffineExpr.h"
26 #include "mlir/IR/AffineMap.h"
27 #include "mlir/IR/Attributes.h"
28 #include "mlir/IR/Builders.h"
29 #include "mlir/IR/Location.h"
30 #include "mlir/IR/Matchers.h"
31 #include "mlir/IR/OperationSupport.h"
32 #include "mlir/IR/PatternMatch.h"
33 #include "mlir/IR/Types.h"
34 #include "mlir/Pass/Pass.h"
35 #include "mlir/Transforms/Passes.h"
36 
37 using namespace mlir;
38 using namespace mlir::edsc;
39 using namespace mlir::edsc::intrinsics;
40 using vector::TransferReadOp;
41 using vector::TransferWriteOp;
42 
43 // Return a list of Values that correspond to multiple AffineApplyOp, one for
44 // each result of `map`. Each `expr` in `map` is canonicalized and folded
45 // greedily according to its operands.
46 // TODO: factor out in a common location that both linalg and vector can use.
47 static SmallVector<Value, 4>
48 applyMapToValues(OpBuilder &b, Location loc, AffineMap map, ValueRange values) {
49   SmallVector<Value, 4> res;
50   res.reserve(map.getNumResults());
51   unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols();
52   // For each `expr` in `map`, applies the `expr` to the values extracted from
53   // ranges. If the resulting application can be folded into a Value, the
54   // folding occurs eagerly. Otherwise, an affine.apply operation is emitted.
55   for (auto expr : map.getResults()) {
56     AffineMap map = AffineMap::get(numDims, numSym, expr);
57     SmallVector<Value, 4> operands(values.begin(), values.end());
58     fullyComposeAffineMapAndOperands(&map, &operands);
59     canonicalizeMapAndOperands(&map, &operands);
60     res.push_back(b.createOrFold<AffineApplyOp>(loc, map, operands));
61   }
62   return res;
63 }
64 
65 namespace {
66 /// Helper class captures the common information needed to lower N>1-D vector
67 /// transfer operations (read and write).
68 /// On construction, this class opens an edsc::ScopedContext for simpler IR
69 /// manipulation.
70 /// In pseudo-IR, for an n-D vector_transfer_read such as:
71 ///
72 /// ```
73 ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
74 ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
75 ///     vector<(major_dims) x (minor_dims) x type>
76 /// ```
77 ///
78 /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
79 /// higher).
80 ///
81 /// This is the entry point to emitting pseudo-IR resembling:
82 ///
83 /// ```
84 ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
85 ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
86 ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
87 ///       %v = vector_transfer_read(
88 ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
89 ///          %ivs_minor):
90 ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
91 ///         vector<(minor_dims) x type>;
92 ///       store(%v, %tmp);
93 ///     } else {
94 ///       %v = splat(vector<(minor_dims) x type>, %fill)
95 ///       store(%v, %tmp, %ivs_major);
96 ///     }
97 ///   }
98 ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
99 //      vector<(major_dims) x (minor_dims) x type>
100 /// ```
101 ///
102 template <typename ConcreteOp>
103 class NDTransferOpHelper {
104 public:
105   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
106                      const VectorTransferToSCFOptions &options)
107       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
108         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
109         op(xferOp.getOperation()) {
110     vectorType = xferOp.getVectorType();
111     // TODO: when we go to k > 1-D vectors adapt minorRank.
112     minorRank = 1;
113     majorRank = vectorType.getRank() - minorRank;
114     leadingRank = xferOp.getLeadingMemRefRank();
115     majorVectorType =
116         VectorType::get(vectorType.getShape().take_front(majorRank),
117                         vectorType.getElementType());
118     minorVectorType =
119         VectorType::get(vectorType.getShape().take_back(minorRank),
120                         vectorType.getElementType());
121     /// Memref of minor vector type is used for individual transfers.
122     memRefMinorVectorType =
123         MemRefType::get(majorVectorType.getShape(), minorVectorType, {},
124                         xferOp.getMemRefType().getMemorySpace());
125   }
126 
127   LogicalResult doReplace();
128 
129 private:
130   /// Creates the loop nest on the "major" dimensions and calls the
131   /// `loopBodyBuilder` lambda in the context of the loop nest.
132   void
133   emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange,
134                                     ValueRange, const MemRefBoundsCapture &)>
135                 loopBodyBuilder);
136 
137   /// Common state to lower vector transfer ops.
138   PatternRewriter &rewriter;
139   const VectorTransferToSCFOptions &options;
140   Location loc;
141   std::unique_ptr<ScopedContext> scope;
142   ConcreteOp xferOp;
143   Operation *op;
144   // A vector transfer copies data between:
145   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
146   //   - vector<(major_dims) x (minor_dims) x type>
147   unsigned minorRank;         // for now always 1
148   unsigned majorRank;         // vector rank - minorRank
149   unsigned leadingRank;       // memref rank - vector rank
150   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
151   VectorType majorVectorType; // vector<(major_dims) x type>
152   VectorType minorVectorType; // vector<(minor_dims) x type>
153   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
154 };
155 
156 template <typename ConcreteOp>
157 void NDTransferOpHelper<ConcreteOp>::emitLoops(
158     llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange,
159                             const MemRefBoundsCapture &)>
160         loopBodyBuilder) {
161   /// Loop nest operates on the major dimensions
162   MemRefBoundsCapture memrefBoundsCapture(xferOp.memref());
163 
164   if (options.unroll) {
165     auto shape = majorVectorType.getShape();
166     auto strides = computeStrides(shape);
167     unsigned numUnrolledInstances = computeMaxLinearIndex(shape);
168     ValueRange indices(xferOp.indices());
169     for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) {
170       SmallVector<int64_t, 4> offsets = delinearize(strides, idx);
171       SmallVector<Value, 4> offsetValues =
172           llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value {
173             return std_constant_index(off);
174           }));
175       loopBodyBuilder(offsetValues, indices.take_front(leadingRank),
176                       indices.drop_front(leadingRank).take_front(majorRank),
177                       indices.take_back(minorRank), memrefBoundsCapture);
178     }
179   } else {
180     VectorBoundsCapture vectorBoundsCapture(majorVectorType);
181     auto majorLbs = vectorBoundsCapture.getLbs();
182     auto majorUbs = vectorBoundsCapture.getUbs();
183     auto majorSteps = vectorBoundsCapture.getSteps();
184     affineLoopNestBuilder(
185         majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) {
186           ValueRange indices(xferOp.indices());
187           loopBodyBuilder(majorIvs, indices.take_front(leadingRank),
188                           indices.drop_front(leadingRank).take_front(majorRank),
189                           indices.take_back(minorRank), memrefBoundsCapture);
190         });
191   }
192 }
193 
194 static Optional<int64_t> extractConstantIndex(Value v) {
195   if (auto cstOp = v.getDefiningOp<ConstantIndexOp>())
196     return cstOp.getValue();
197   if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>())
198     if (affineApplyOp.getAffineMap().isSingleConstant())
199       return affineApplyOp.getAffineMap().getSingleConstantResult();
200   return None;
201 }
202 
203 // Missing foldings of scf.if make it necessary to perform poor man's folding
204 // eagerly, especially in the case of unrolling. In the future, this should go
205 // away once scf.if folds properly.
206 static Value onTheFlyFoldSLT(Value v, Value ub) {
207   using namespace mlir::edsc::op;
208   auto maybeCstV = extractConstantIndex(v);
209   auto maybeCstUb = extractConstantIndex(ub);
210   if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb)
211     return Value();
212   return slt(v, ub);
213 }
214 
215 ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
216 ///      `majorIvsPlusOffsets`.
217 ///   2. Return a value of i1 that determines whether the first
218 ///   `majorIvs.rank()`
219 ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
220 static Value
221 emitInBoundsCondition(PatternRewriter &rewriter,
222                       VectorTransferOpInterface xferOp, unsigned leadingRank,
223                       ValueRange majorIvs, ValueRange majorOffsets,
224                       const MemRefBoundsCapture &memrefBounds,
225                       SmallVectorImpl<Value> &majorIvsPlusOffsets) {
226   Value inBoundsCondition;
227   majorIvsPlusOffsets.reserve(majorIvs.size());
228   unsigned idx = 0;
229   SmallVector<Value, 4> bounds =
230       applyMapToValues(rewriter, xferOp.getLoc(), xferOp.permutation_map(),
231                        memrefBounds.getUbs());
232   for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) {
233     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
234     using namespace mlir::edsc::op;
235     majorIvsPlusOffsets.push_back(iv + off);
236     if (xferOp.isMaskedDim(leadingRank + idx)) {
237       Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub);
238       if (inBoundsCond)
239         inBoundsCondition = (inBoundsCondition)
240                                 ? (inBoundsCondition && inBoundsCond)
241                                 : inBoundsCond;
242     }
243     ++idx;
244   }
245   return inBoundsCondition;
246 }
247 
248 // TODO: Parallelism and threadlocal considerations.
249 static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
250                                      Operation *op) {
251   auto &b = ScopedContext::getBuilderRef();
252   OpBuilder::InsertionGuard guard(b);
253   Operation *scope =
254       op->getParentWithTrait<OpTrait::AutomaticAllocationScope>();
255   assert(scope && "Expected op to be inside automatic allocation scope");
256   b.setInsertionPointToStart(&scope->getRegion(0).front());
257   Value res = std_alloca(memRefMinorVectorType);
258   return res;
259 }
260 
261 template <>
262 LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
263   Value alloc, result;
264   if (options.unroll)
265     result = std_splat(vectorType, xferOp.padding());
266   else
267     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
268 
269   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
270                 ValueRange majorOffsets, ValueRange minorOffsets,
271                 const MemRefBoundsCapture &memrefBounds) {
272     /// Lambda to load 1-D vector in the current loop ivs + offset context.
273     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
274       SmallVector<Value, 8> indexing;
275       indexing.reserve(leadingRank + majorRank + minorRank);
276       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
277       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
278       indexing.append(minorOffsets.begin(), minorOffsets.end());
279       Value memref = xferOp.memref();
280       auto map =
281           getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType);
282       ArrayAttr masked;
283       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
284         OpBuilder &b = ScopedContext::getBuilderRef();
285         masked = b.getBoolArrayAttr({false});
286       }
287       return vector_transfer_read(minorVectorType, memref, indexing,
288                                   AffineMapAttr::get(map), xferOp.padding(),
289                                   masked);
290     };
291 
292     // 1. Compute the inBoundsCondition in the current loops ivs + offset
293     // context.
294     SmallVector<Value, 4> majorIvsPlusOffsets;
295     Value inBoundsCondition = emitInBoundsCondition(
296         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
297         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
298 
299     if (inBoundsCondition) {
300       // 2. If the condition is not null, we need an IfOp, which may yield
301       // if `options.unroll` is true.
302       SmallVector<Type, 1> resultType;
303       if (options.unroll)
304         resultType.push_back(vectorType);
305 
306       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
307       // splat a 1-D vector.
308       ValueRange ifResults = conditionBuilder(
309           resultType, inBoundsCondition,
310           [&]() -> scf::ValueVector {
311             Value vector = load1DVector(majorIvsPlusOffsets);
312             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
313             // aggregate. We must yield and merge with the `else` branch.
314             if (options.unroll) {
315               vector = vector_insert(vector, result, majorIvs);
316               return {vector};
317             }
318             // 3.b. Otherwise, just go through the temporary `alloc`.
319             std_store(vector, alloc, majorIvs);
320             return {};
321           },
322           [&]() -> scf::ValueVector {
323             Value vector = std_splat(minorVectorType, xferOp.padding());
324             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
325             // aggregate. We must yield and merge with the `then` branch.
326             if (options.unroll) {
327               vector = vector_insert(vector, result, majorIvs);
328               return {vector};
329             }
330             // 3.d. Otherwise, just go through the temporary `alloc`.
331             std_store(vector, alloc, majorIvs);
332             return {};
333           });
334 
335       if (!resultType.empty())
336         result = *ifResults.begin();
337     } else {
338       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
339       Value loaded1D = load1DVector(majorIvsPlusOffsets);
340       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
341       // aggregate.
342       if (options.unroll)
343         result = vector_insert(loaded1D, result, majorIvs);
344       // 5.b. Otherwise, just go through the temporary `alloc`.
345       else
346         std_store(loaded1D, alloc, majorIvs);
347     }
348   });
349 
350   assert((!options.unroll ^ (bool)result) &&
351          "Expected resulting Value iff unroll");
352   if (!result)
353     result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
354   rewriter.replaceOp(op, result);
355 
356   return success();
357 }
358 
359 template <>
360 LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
361   Value alloc;
362   if (!options.unroll) {
363     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
364     std_store(xferOp.vector(),
365               vector_type_cast(MemRefType::get({}, vectorType), alloc));
366   }
367 
368   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
369                 ValueRange majorOffsets, ValueRange minorOffsets,
370                 const MemRefBoundsCapture &memrefBounds) {
371     // Lower to 1-D vector_transfer_write and let recursion handle it.
372     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
373       SmallVector<Value, 8> indexing;
374       indexing.reserve(leadingRank + majorRank + minorRank);
375       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
376       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
377       indexing.append(minorOffsets.begin(), minorOffsets.end());
378       Value result;
379       // If `options.unroll` is true, extract the 1-D vector from the
380       // aggregate.
381       if (options.unroll)
382         result = vector_extract(xferOp.vector(), majorIvs);
383       else
384         result = std_load(alloc, majorIvs);
385       auto map =
386           getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType);
387       ArrayAttr masked;
388       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
389         OpBuilder &b = ScopedContext::getBuilderRef();
390         masked = b.getBoolArrayAttr({false});
391       }
392       vector_transfer_write(result, xferOp.memref(), indexing,
393                             AffineMapAttr::get(map), masked);
394     };
395 
396     // 1. Compute the inBoundsCondition in the current loops ivs + offset
397     // context.
398     SmallVector<Value, 4> majorIvsPlusOffsets;
399     Value inBoundsCondition = emitInBoundsCondition(
400         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
401         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
402 
403     if (inBoundsCondition) {
404       // 2.a. If the condition is not null, we need an IfOp, to write
405       // conditionally. Progressively lower to a 1-D transfer write.
406       conditionBuilder(inBoundsCondition,
407                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
408     } else {
409       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
410       emitTransferWrite(majorIvsPlusOffsets);
411     }
412   });
413 
414   rewriter.eraseOp(op);
415 
416   return success();
417 }
418 
419 } // namespace
420 
421 /// Analyzes the `transfer` to find an access dimension along the fastest remote
422 /// MemRef dimension. If such a dimension with coalescing properties is found,
423 /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
424 /// LoopNestBuilder captures it in the innermost loop.
425 template <typename TransferOpTy>
426 static int computeCoalescedIndex(TransferOpTy transfer) {
427   // rank of the remote memory access, coalescing behavior occurs on the
428   // innermost memory dimension.
429   auto remoteRank = transfer.getMemRefType().getRank();
430   // Iterate over the results expressions of the permutation map to determine
431   // the loop order for creating pointwise copies between remote and local
432   // memories.
433   int coalescedIdx = -1;
434   auto exprs = transfer.permutation_map().getResults();
435   for (auto en : llvm::enumerate(exprs)) {
436     auto dim = en.value().template dyn_cast<AffineDimExpr>();
437     if (!dim) {
438       continue;
439     }
440     auto memRefDim = dim.getPosition();
441     if (memRefDim == remoteRank - 1) {
442       // memRefDim has coalescing properties, it should be swapped in the last
443       // position.
444       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
445       coalescedIdx = en.index();
446     }
447   }
448   return coalescedIdx;
449 }
450 
451 template <typename TransferOpTy>
452 VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
453     VectorTransferToSCFOptions options, MLIRContext *context)
454     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
455       options(options) {}
456 
457 /// Used for staging the transfer in a local buffer.
458 template <typename TransferOpTy>
459 MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
460     TransferOpTy transfer) const {
461   auto vectorType = transfer.getVectorType();
462   return MemRefType::get(vectorType.getShape().drop_back(),
463                          VectorType::get(vectorType.getShape().take_back(),
464                                          vectorType.getElementType()),
465                          {}, 0);
466 }
467 
468 static void emitWithBoundsChecks(
469     PatternRewriter &rewriter, VectorTransferOpInterface transfer,
470     ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture,
471     function_ref<void(ArrayRef<Value>)> inBoundsFun,
472     function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) {
473   // Permute the incoming indices according to the permutation map.
474   SmallVector<Value, 4> indices =
475       applyMapToValues(rewriter, transfer.getLoc(), transfer.permutation_map(),
476                        transfer.indices());
477 
478   // Generate a bounds check if necessary.
479   SmallVector<Value, 4> majorIvsPlusOffsets;
480   Value inBoundsCondition =
481       emitInBoundsCondition(rewriter, transfer, 0, ivs, indices,
482                             memRefBoundsCapture, majorIvsPlusOffsets);
483 
484   // Apply the permutation map to the ivs. The permutation map may not use all
485   // the inputs.
486   SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size());
487   for (unsigned memRefDim = 0; memRefDim < transfer.indices().size();
488        ++memRefDim) {
489     // Linear search on a small number of entries.
490     int loopIndex = -1;
491     auto exprs = transfer.permutation_map().getResults();
492     for (auto en : llvm::enumerate(exprs)) {
493       auto expr = en.value();
494       auto dim = expr.dyn_cast<AffineDimExpr>();
495       // Sanity check.
496       assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) &&
497              "Expected dim or 0 in permutationMap");
498       if (dim && memRefDim == dim.getPosition()) {
499         loopIndex = en.index();
500         break;
501       }
502     }
503 
504     using namespace edsc::op;
505     auto i = transfer.indices()[memRefDim];
506     scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex];
507   }
508 
509   if (inBoundsCondition)
510     conditionBuilder(
511         /* scf.if */ inBoundsCondition, // {
512         [&] { inBoundsFun(scalarAccessExprs); },
513         // } else {
514         outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); }
515                        : function_ref<void()>()
516         // }
517     );
518   else
519     inBoundsFun(scalarAccessExprs);
520 }
521 
522 namespace mlir {
523 
524 /// Lowers TransferReadOp into a combination of:
525 ///   1. local memory allocation;
526 ///   2. perfect loop nest over:
527 ///      a. scalar load from local buffers (viewed as a scalar memref);
528 ///      a. scalar store to original memref (with padding).
529 ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
530 ///   4. local memory deallocation.
531 ///
532 /// Lowers the data transfer part of a TransferReadOp while ensuring no
533 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
534 /// padding.
535 
536 /// Performs the rewrite.
537 template <>
538 LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
539     Operation *op, PatternRewriter &rewriter) const {
540   using namespace mlir::edsc::op;
541 
542   TransferReadOp transfer = cast<TransferReadOp>(op);
543 
544   // Fall back to a loop if the fastest varying stride is not 1 or it is
545   // permuted.
546   int64_t offset;
547   SmallVector<int64_t, 4> strides;
548   auto successStrides =
549       getStridesAndOffset(transfer.getMemRefType(), strides, offset);
550   if (succeeded(successStrides) && strides.back() == 1 &&
551       transfer.permutation_map().isMinorIdentity()) {
552     // If > 1D, emit a bunch of loops around 1-D vector transfers.
553     if (transfer.getVectorType().getRank() > 1)
554       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
555           .doReplace();
556     // If 1-D this is now handled by the target-specific lowering.
557     if (transfer.getVectorType().getRank() == 1)
558       return failure();
559   }
560 
561   // Conservative lowering to scalar load / stores.
562   // 1. Setup all the captures.
563   ScopedContext scope(rewriter, transfer.getLoc());
564   StdIndexedValue remote(transfer.memref());
565   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
566   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
567   int coalescedIdx = computeCoalescedIndex(transfer);
568   // Swap the vectorBoundsCapture which will reorder loop bounds.
569   if (coalescedIdx >= 0)
570     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
571                                    coalescedIdx);
572 
573   auto lbs = vectorBoundsCapture.getLbs();
574   auto ubs = vectorBoundsCapture.getUbs();
575   SmallVector<Value, 8> steps;
576   steps.reserve(vectorBoundsCapture.getSteps().size());
577   for (auto step : vectorBoundsCapture.getSteps())
578     steps.push_back(std_constant_index(step));
579 
580   // 2. Emit alloc-copy-load-dealloc.
581   MLIRContext *ctx = op->getContext();
582   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
583   StdIndexedValue local(tmp);
584   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
585     auto ivsStorage = llvm::to_vector<8>(loopIvs);
586     // Swap the ivs which will reorder memory accesses.
587     if (coalescedIdx >= 0)
588       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
589 
590     ArrayRef<Value> ivs(ivsStorage);
591     Value pos = std_index_cast(IntegerType::get(32, ctx), ivs.back());
592     Value inVector = local(ivs.drop_back());
593     auto loadValue = [&](ArrayRef<Value> indices) {
594       Value vector = vector_insert_element(remote(indices), inVector, pos);
595       local(ivs.drop_back()) = vector;
596     };
597     auto loadPadding = [&](ArrayRef<Value>) {
598       Value vector = vector_insert_element(transfer.padding(), inVector, pos);
599       local(ivs.drop_back()) = vector;
600     };
601     emitWithBoundsChecks(
602         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
603         memRefBoundsCapture, loadValue, loadPadding);
604   });
605   Value vectorValue = std_load(vector_type_cast(tmp));
606 
607   // 3. Propagate.
608   rewriter.replaceOp(op, vectorValue);
609   return success();
610 }
611 
612 /// Lowers TransferWriteOp into a combination of:
613 ///   1. local memory allocation;
614 ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
615 ///   3. perfect loop nest over:
616 ///      a. scalar load from local buffers (viewed as a scalar memref);
617 ///      a. scalar store to original memref (if in bounds).
618 ///   4. local memory deallocation.
619 ///
620 /// More specifically, lowers the data transfer part while ensuring no
621 /// out-of-bounds accesses are possible.
622 template <>
623 LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
624     Operation *op, PatternRewriter &rewriter) const {
625   using namespace edsc::op;
626 
627   TransferWriteOp transfer = cast<TransferWriteOp>(op);
628 
629   // Fall back to a loop if the fastest varying stride is not 1 or it is
630   // permuted.
631   int64_t offset;
632   SmallVector<int64_t, 4> strides;
633   auto successStrides =
634       getStridesAndOffset(transfer.getMemRefType(), strides, offset);
635   if (succeeded(successStrides) && strides.back() == 1 &&
636       transfer.permutation_map().isMinorIdentity()) {
637     // If > 1D, emit a bunch of loops around 1-D vector transfers.
638     if (transfer.getVectorType().getRank() > 1)
639       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
640           .doReplace();
641     // If 1-D this is now handled by the target-specific lowering.
642     if (transfer.getVectorType().getRank() == 1)
643       return failure();
644   }
645 
646   // 1. Setup all the captures.
647   ScopedContext scope(rewriter, transfer.getLoc());
648   StdIndexedValue remote(transfer.memref());
649   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
650   Value vectorValue(transfer.vector());
651   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
652   int coalescedIdx = computeCoalescedIndex(transfer);
653   // Swap the vectorBoundsCapture which will reorder loop bounds.
654   if (coalescedIdx >= 0)
655     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
656                                    coalescedIdx);
657 
658   auto lbs = vectorBoundsCapture.getLbs();
659   auto ubs = vectorBoundsCapture.getUbs();
660   SmallVector<Value, 8> steps;
661   steps.reserve(vectorBoundsCapture.getSteps().size());
662   for (auto step : vectorBoundsCapture.getSteps())
663     steps.push_back(std_constant_index(step));
664 
665   // 2. Emit alloc-store-copy-dealloc.
666   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
667   StdIndexedValue local(tmp);
668   Value vec = vector_type_cast(tmp);
669   std_store(vectorValue, vec);
670   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
671     auto ivsStorage = llvm::to_vector<8>(loopIvs);
672     // Swap the ivsStorage which will reorder memory accesses.
673     if (coalescedIdx >= 0)
674       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
675 
676     ArrayRef<Value> ivs(ivsStorage);
677     Value pos =
678         std_index_cast(IntegerType::get(32, op->getContext()), ivs.back());
679     auto storeValue = [&](ArrayRef<Value> indices) {
680       Value scalar = vector_extract_element(local(ivs.drop_back()), pos);
681       remote(indices) = scalar;
682     };
683     emitWithBoundsChecks(
684         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
685         memRefBoundsCapture, storeValue);
686   });
687 
688   // 3. Erase.
689   rewriter.eraseOp(op);
690   return success();
691 }
692 
693 void populateVectorToSCFConversionPatterns(
694     OwningRewritePatternList &patterns, MLIRContext *context,
695     const VectorTransferToSCFOptions &options) {
696   patterns.insert<VectorTransferRewriter<vector::TransferReadOp>,
697                   VectorTransferRewriter<vector::TransferWriteOp>>(options,
698                                                                    context);
699 }
700 
701 } // namespace mlir
702 
703 namespace {
704 
705 struct ConvertVectorToSCFPass
706     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
707   ConvertVectorToSCFPass() = default;
708   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
709     this->fullUnroll = options.unroll;
710   }
711 
712   void runOnFunction() override {
713     OwningRewritePatternList patterns;
714     auto *context = getFunction().getContext();
715     populateVectorToSCFConversionPatterns(
716         patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll));
717     applyPatternsAndFoldGreedily(getFunction(), patterns);
718   }
719 };
720 
721 } // namespace
722 
723 std::unique_ptr<Pass>
724 mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
725   return std::make_unique<ConvertVectorToSCFPass>(options);
726 }
727