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 namespace {
44 /// Helper class captures the common information needed to lower N>1-D vector
45 /// transfer operations (read and write).
46 /// On construction, this class opens an edsc::ScopedContext for simpler IR
47 /// manipulation.
48 /// In pseudo-IR, for an n-D vector_transfer_read such as:
49 ///
50 /// ```
51 ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
52 ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
53 ///     vector<(major_dims) x (minor_dims) x type>
54 /// ```
55 ///
56 /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
57 /// higher).
58 ///
59 /// This is the entry point to emitting pseudo-IR resembling:
60 ///
61 /// ```
62 ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
63 ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
64 ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
65 ///       %v = vector_transfer_read(
66 ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
67 ///          %ivs_minor):
68 ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
69 ///         vector<(minor_dims) x type>;
70 ///       store(%v, %tmp);
71 ///     } else {
72 ///       %v = splat(vector<(minor_dims) x type>, %fill)
73 ///       store(%v, %tmp, %ivs_major);
74 ///     }
75 ///   }
76 ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
77 //      vector<(major_dims) x (minor_dims) x type>
78 /// ```
79 ///
80 template <typename ConcreteOp>
81 class NDTransferOpHelper {
82 public:
83   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
84                      const VectorTransferToSCFOptions &options)
85       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
86         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
87         op(xferOp.getOperation()) {
88     vectorType = xferOp.getVectorType();
89     // TODO(ntv, ajcbik): when we go to k > 1-D vectors adapt minorRank.
90     minorRank = 1;
91     majorRank = vectorType.getRank() - minorRank;
92     leadingRank = xferOp.getMemRefType().getRank() - (majorRank + minorRank);
93     majorVectorType =
94         VectorType::get(vectorType.getShape().take_front(majorRank),
95                         vectorType.getElementType());
96     minorVectorType =
97         VectorType::get(vectorType.getShape().take_back(minorRank),
98                         vectorType.getElementType());
99     /// Memref of minor vector type is used for individual transfers.
100     memRefMinorVectorType =
101         MemRefType::get(majorVectorType.getShape(), minorVectorType, {},
102                         xferOp.getMemRefType().getMemorySpace());
103   }
104 
105   LogicalResult doReplace();
106 
107 private:
108   /// Creates the loop nest on the "major" dimensions and calls the
109   /// `loopBodyBuilder` lambda in the context of the loop nest.
110   template <typename Lambda>
111   void emitLoops(Lambda loopBodyBuilder);
112 
113   /// Operate within the body of `emitLoops` to:
114   ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
115   ///      `majorIvsPlusOffsets`.
116   ///   2. Return a boolean that determines whether the first `majorIvs.rank()`
117   ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
118   Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets,
119                               MemRefBoundsCapture &memrefBounds,
120                               SmallVectorImpl<Value> &majorIvsPlusOffsets);
121 
122   /// Common state to lower vector transfer ops.
123   PatternRewriter &rewriter;
124   const VectorTransferToSCFOptions &options;
125   Location loc;
126   std::unique_ptr<ScopedContext> scope;
127   ConcreteOp xferOp;
128   Operation *op;
129   // A vector transfer copies data between:
130   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
131   //   - vector<(major_dims) x (minor_dims) x type>
132   unsigned minorRank;         // for now always 1
133   unsigned majorRank;         // vector rank - minorRank
134   unsigned leadingRank;       // memref rank - vector rank
135   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
136   VectorType majorVectorType; // vector<(major_dims) x type>
137   VectorType minorVectorType; // vector<(minor_dims) x type>
138   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
139 };
140 
141 template <typename ConcreteOp>
142 template <typename Lambda>
143 void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) {
144   /// Loop nest operates on the major dimensions
145   MemRefBoundsCapture memrefBoundsCapture(xferOp.memref());
146 
147   if (options.unroll) {
148     auto shape = majorVectorType.getShape();
149     auto strides = computeStrides(shape);
150     unsigned numUnrolledInstances = computeMaxLinearIndex(shape);
151     ValueRange indices(xferOp.indices());
152     for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) {
153       SmallVector<int64_t, 4> offsets = delinearize(strides, idx);
154       SmallVector<Value, 4> offsetValues =
155           llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value {
156             return std_constant_index(off);
157           }));
158       loopBodyBuilder(offsetValues, indices.take_front(leadingRank),
159                       indices.drop_front(leadingRank).take_front(majorRank),
160                       indices.take_back(minorRank), memrefBoundsCapture);
161     }
162   } else {
163     VectorBoundsCapture vectorBoundsCapture(majorVectorType);
164     auto majorLbs = vectorBoundsCapture.getLbs();
165     auto majorUbs = vectorBoundsCapture.getUbs();
166     auto majorSteps = vectorBoundsCapture.getSteps();
167     SmallVector<Value, 8> majorIvs(vectorBoundsCapture.rank());
168     AffineLoopNestBuilder(majorIvs, majorLbs, majorUbs, majorSteps)([&] {
169       ValueRange indices(xferOp.indices());
170       loopBodyBuilder(majorIvs, indices.take_front(leadingRank),
171                       indices.drop_front(leadingRank).take_front(majorRank),
172                       indices.take_back(minorRank), memrefBoundsCapture);
173     });
174   }
175 }
176 
177 template <typename ConcreteOp>
178 Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition(
179     ValueRange majorIvs, ValueRange majorOffsets,
180     MemRefBoundsCapture &memrefBounds,
181     SmallVectorImpl<Value> &majorIvsPlusOffsets) {
182   Value inBoundsCondition;
183   majorIvsPlusOffsets.reserve(majorIvs.size());
184   unsigned idx = 0;
185   for (auto it : llvm::zip(majorIvs, majorOffsets, memrefBounds.getUbs())) {
186     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
187     using namespace mlir::edsc::op;
188     majorIvsPlusOffsets.push_back(iv + off);
189     if (xferOp.isMaskedDim(leadingRank + idx)) {
190       Value inBounds = majorIvsPlusOffsets.back() < ub;
191       inBoundsCondition =
192           (inBoundsCondition) ? (inBoundsCondition && inBounds) : inBounds;
193     }
194     ++idx;
195   }
196   return inBoundsCondition;
197 }
198 
199 // TODO: Parallelism and threadlocal considerations.
200 static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
201                                      Operation *op) {
202   auto &b = ScopedContext::getBuilderRef();
203   OpBuilder::InsertionGuard guard(b);
204   b.setInsertionPointToStart(&op->getParentOfType<FuncOp>().front());
205   Value res =
206       std_alloca(memRefMinorVectorType, ValueRange{}, b.getI64IntegerAttr(128));
207   return res;
208 }
209 
210 template <>
211 LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
212   Value alloc, result;
213   if (options.unroll)
214     result = std_splat(vectorType, xferOp.padding());
215   else
216     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
217 
218   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
219                 ValueRange majorOffsets, ValueRange minorOffsets,
220                 MemRefBoundsCapture &memrefBounds) {
221     /// Lambda to load 1-D vector in the current loop ivs + offset context.
222     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
223       SmallVector<Value, 8> indexing;
224       indexing.reserve(leadingRank + majorRank + minorRank);
225       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
226       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
227       indexing.append(minorOffsets.begin(), minorOffsets.end());
228       Value memref = xferOp.memref();
229       auto map = TransferReadOp::getTransferMinorIdentityMap(
230           xferOp.getMemRefType(), minorVectorType);
231       ArrayAttr masked;
232       if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
233         OpBuilder &b = ScopedContext::getBuilderRef();
234         masked = b.getBoolArrayAttr({true});
235       }
236       return vector_transfer_read(minorVectorType, memref, indexing,
237                                   AffineMapAttr::get(map), xferOp.padding(),
238                                   masked);
239     };
240 
241     // 1. Compute the inBoundsCondition in the current loops ivs + offset
242     // context.
243     SmallVector<Value, 4> majorIvsPlusOffsets;
244     Value inBoundsCondition = emitInBoundsCondition(
245         majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
246 
247     if (inBoundsCondition) {
248       // 2. If the condition is not null, we need an IfOp, which may yield
249       // if `options.unroll` is true.
250       SmallVector<Type, 1> resultType;
251       if (options.unroll)
252         resultType.push_back(vectorType);
253 
254       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
255       // splat a 1-D vector.
256       ValueRange ifResults = conditionBuilder(
257           resultType, inBoundsCondition,
258           [&]() -> scf::ValueVector {
259             Value vector = load1DVector(majorIvsPlusOffsets);
260             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
261             // aggregate. We must yield and merge with the `else` branch.
262             if (options.unroll) {
263               vector = vector_insert(vector, result, majorIvs);
264               return {vector};
265             }
266             // 3.b. Otherwise, just go through the temporary `alloc`.
267             std_store(vector, alloc, majorIvs);
268             return {};
269           },
270           [&]() -> scf::ValueVector {
271             Value vector = std_splat(minorVectorType, xferOp.padding());
272             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
273             // aggregate. We must yield and merge with the `then` branch.
274             if (options.unroll) {
275               vector = vector_insert(vector, result, majorIvs);
276               return {vector};
277             }
278             // 3.d. Otherwise, just go through the temporary `alloc`.
279             std_store(vector, alloc, majorIvs);
280             return {};
281           });
282 
283       if (!resultType.empty())
284         result = *ifResults.begin();
285     } else {
286       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
287       Value loaded1D = load1DVector(majorIvsPlusOffsets);
288       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
289       // aggregate.
290       if (options.unroll)
291         result = vector_insert(loaded1D, result, majorIvs);
292       // 5.b. Otherwise, just go through the temporary `alloc`.
293       else
294         std_store(loaded1D, alloc, majorIvs);
295     }
296   });
297 
298   assert((!options.unroll ^ (bool)result) &&
299          "Expected resulting Value iff unroll");
300   if (!result)
301     result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
302   rewriter.replaceOp(op, result);
303 
304   return success();
305 }
306 
307 template <>
308 LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
309   Value alloc;
310   if (!options.unroll) {
311     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
312     std_store(xferOp.vector(),
313               vector_type_cast(MemRefType::get({}, vectorType), alloc));
314   }
315 
316   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
317                 ValueRange majorOffsets, ValueRange minorOffsets,
318                 MemRefBoundsCapture &memrefBounds) {
319     // Lower to 1-D vector_transfer_write and let recursion handle it.
320     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
321       SmallVector<Value, 8> indexing;
322       indexing.reserve(leadingRank + majorRank + minorRank);
323       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
324       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
325       indexing.append(minorOffsets.begin(), minorOffsets.end());
326       Value result;
327       // If `options.unroll` is true, extract the 1-D vector from the
328       // aggregate.
329       if (options.unroll)
330         result = vector_extract(xferOp.vector(), majorIvs);
331       else
332         result = std_load(alloc, majorIvs);
333       auto map = TransferWriteOp::getTransferMinorIdentityMap(
334           xferOp.getMemRefType(), minorVectorType);
335       ArrayAttr masked;
336       if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
337         OpBuilder &b = ScopedContext::getBuilderRef();
338         masked = b.getBoolArrayAttr({true});
339       }
340       vector_transfer_write(result, xferOp.memref(), indexing,
341                             AffineMapAttr::get(map), masked);
342     };
343 
344     // 1. Compute the inBoundsCondition in the current loops ivs + offset
345     // context.
346     SmallVector<Value, 4> majorIvsPlusOffsets;
347     Value inBoundsCondition = emitInBoundsCondition(
348         majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
349 
350     if (inBoundsCondition) {
351       // 2.a. If the condition is not null, we need an IfOp, to write
352       // conditionally. Progressively lower to a 1-D transfer write.
353       conditionBuilder(inBoundsCondition,
354                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
355     } else {
356       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
357       emitTransferWrite(majorIvsPlusOffsets);
358     }
359   });
360 
361   rewriter.eraseOp(op);
362 
363   return success();
364 }
365 
366 } // namespace
367 
368 /// Analyzes the `transfer` to find an access dimension along the fastest remote
369 /// MemRef dimension. If such a dimension with coalescing properties is found,
370 /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
371 /// LoopNestBuilder captures it in the innermost loop.
372 template <typename TransferOpTy>
373 static int computeCoalescedIndex(TransferOpTy transfer) {
374   // rank of the remote memory access, coalescing behavior occurs on the
375   // innermost memory dimension.
376   auto remoteRank = transfer.getMemRefType().getRank();
377   // Iterate over the results expressions of the permutation map to determine
378   // the loop order for creating pointwise copies between remote and local
379   // memories.
380   int coalescedIdx = -1;
381   auto exprs = transfer.permutation_map().getResults();
382   for (auto en : llvm::enumerate(exprs)) {
383     auto dim = en.value().template dyn_cast<AffineDimExpr>();
384     if (!dim) {
385       continue;
386     }
387     auto memRefDim = dim.getPosition();
388     if (memRefDim == remoteRank - 1) {
389       // memRefDim has coalescing properties, it should be swapped in the last
390       // position.
391       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
392       coalescedIdx = en.index();
393     }
394   }
395   return coalescedIdx;
396 }
397 
398 /// Emits remote memory accesses that are clipped to the boundaries of the
399 /// MemRef.
400 template <typename TransferOpTy>
401 static SmallVector<Value, 8>
402 clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) {
403   using namespace mlir::edsc;
404 
405   Value zero(std_constant_index(0)), one(std_constant_index(1));
406   SmallVector<Value, 8> memRefAccess(transfer.indices());
407   SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size());
408   // Indices accessing to remote memory are clipped and their expressions are
409   // returned in clippedScalarAccessExprs.
410   for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size();
411        ++memRefDim) {
412     // Linear search on a small number of entries.
413     int loopIndex = -1;
414     auto exprs = transfer.permutation_map().getResults();
415     for (auto en : llvm::enumerate(exprs)) {
416       auto expr = en.value();
417       auto dim = expr.template dyn_cast<AffineDimExpr>();
418       // Sanity check.
419       assert(
420           (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) &&
421           "Expected dim or 0 in permutationMap");
422       if (dim && memRefDim == dim.getPosition()) {
423         loopIndex = en.index();
424         break;
425       }
426     }
427 
428     // We cannot distinguish atm between unrolled dimensions that implement
429     // the "always full" tile abstraction and need clipping from the other
430     // ones. So we conservatively clip everything.
431     using namespace edsc::op;
432     auto N = bounds.ub(memRefDim);
433     auto i = memRefAccess[memRefDim];
434     if (loopIndex < 0) {
435       auto N_minus_1 = N - one;
436       auto select_1 = std_select(i < N, i, N_minus_1);
437       clippedScalarAccessExprs[memRefDim] =
438           std_select(i < zero, zero, select_1);
439     } else {
440       auto ii = ivs[loopIndex];
441       auto i_plus_ii = i + ii;
442       auto N_minus_1 = N - one;
443       auto select_1 = std_select(i_plus_ii < N, i_plus_ii, N_minus_1);
444       clippedScalarAccessExprs[memRefDim] =
445           std_select(i_plus_ii < zero, zero, select_1);
446     }
447   }
448 
449   return clippedScalarAccessExprs;
450 }
451 
452 namespace mlir {
453 
454 template <typename TransferOpTy>
455 VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
456     VectorTransferToSCFOptions options, MLIRContext *context)
457     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
458       options(options) {}
459 
460 /// Used for staging the transfer in a local buffer.
461 template <typename TransferOpTy>
462 MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
463     TransferOpTy transfer) const {
464   auto vectorType = transfer.getVectorType();
465   return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {},
466                          0);
467 }
468 
469 /// Lowers TransferReadOp into a combination of:
470 ///   1. local memory allocation;
471 ///   2. perfect loop nest over:
472 ///      a. scalar load from local buffers (viewed as a scalar memref);
473 ///      a. scalar store to original memref (with clipping).
474 ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
475 ///   4. local memory deallocation.
476 ///
477 /// Lowers the data transfer part of a TransferReadOp while ensuring no
478 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
479 /// clipping. This means that a given value in memory can be read multiple
480 /// times and concurrently.
481 ///
482 /// Important notes about clipping and "full-tiles only" abstraction:
483 /// =================================================================
484 /// When using clipping for dealing with boundary conditions, the same edge
485 /// value will appear multiple times (a.k.a edge padding). This is fine if the
486 /// subsequent vector operations are all data-parallel but **is generally
487 /// incorrect** in the presence of reductions or extract operations.
488 ///
489 /// More generally, clipping is a scalar abstraction that is expected to work
490 /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs.
491 /// To deal with real vector_load and DMAs, a "padded allocation + view"
492 /// abstraction with the ability to read out-of-memref-bounds (but still within
493 /// the allocated region) is necessary.
494 ///
495 /// Whether using scalar loops or vector_load/DMAs to perform the transfer,
496 /// junk values will be materialized in the vectors and generally need to be
497 /// filtered out and replaced by the "neutral element". This neutral element is
498 /// op-dependent so, in the future, we expect to create a vector filter and
499 /// apply it to a splatted constant vector with the proper neutral element at
500 /// each ssa-use. This filtering is not necessary for pure data-parallel
501 /// operations.
502 ///
503 /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which
504 /// also have concurrency implications. Note that by using clipped scalar stores
505 /// in the presence of data-parallel only operations, we generate code that
506 /// writes the same value multiple time on the edge locations.
507 ///
508 /// TODO(ntv): implement alternatives to clipping.
509 /// TODO(ntv): support non-data-parallel operations.
510 
511 /// Performs the rewrite.
512 template <>
513 LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
514     Operation *op, PatternRewriter &rewriter) const {
515   using namespace mlir::edsc::op;
516 
517   TransferReadOp transfer = cast<TransferReadOp>(op);
518   if (AffineMap::isMinorIdentity(transfer.permutation_map())) {
519     // If > 1D, emit a bunch of loops around 1-D vector transfers.
520     if (transfer.getVectorType().getRank() > 1)
521       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
522           .doReplace();
523     // If 1-D this is now handled by the target-specific lowering.
524     if (transfer.getVectorType().getRank() == 1)
525       return failure();
526   }
527 
528   // Conservative lowering to scalar load / stores.
529   // 1. Setup all the captures.
530   ScopedContext scope(rewriter, transfer.getLoc());
531   StdIndexedValue remote(transfer.memref());
532   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
533   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
534   int coalescedIdx = computeCoalescedIndex(transfer);
535   // Swap the vectorBoundsCapture which will reorder loop bounds.
536   if (coalescedIdx >= 0)
537     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
538                                    coalescedIdx);
539 
540   auto lbs = vectorBoundsCapture.getLbs();
541   auto ubs = vectorBoundsCapture.getUbs();
542   SmallVector<Value, 8> steps;
543   steps.reserve(vectorBoundsCapture.getSteps().size());
544   for (auto step : vectorBoundsCapture.getSteps())
545     steps.push_back(std_constant_index(step));
546 
547   // 2. Emit alloc-copy-load-dealloc.
548   Value tmp = std_alloc(tmpMemRefType(transfer));
549   StdIndexedValue local(tmp);
550   Value vec = vector_type_cast(tmp);
551   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
552     auto ivs = llvm::to_vector<8>(loopIvs);
553     // Swap the ivs which will reorder memory accesses.
554     if (coalescedIdx >= 0)
555       std::swap(ivs.back(), ivs[coalescedIdx]);
556     // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist).
557     local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs));
558   });
559   Value vectorValue = std_load(vec);
560   (std_dealloc(tmp)); // vexing parse
561 
562   // 3. Propagate.
563   rewriter.replaceOp(op, vectorValue);
564   return success();
565 }
566 
567 /// Lowers TransferWriteOp into a combination of:
568 ///   1. local memory allocation;
569 ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
570 ///   3. perfect loop nest over:
571 ///      a. scalar load from local buffers (viewed as a scalar memref);
572 ///      a. scalar store to original memref (with clipping).
573 ///   4. local memory deallocation.
574 ///
575 /// More specifically, lowers the data transfer part while ensuring no
576 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
577 /// clipping. This means that a given value in memory can be written to multiple
578 /// times and concurrently.
579 ///
580 /// See `Important notes about clipping and full-tiles only abstraction` in the
581 /// description of `readClipped` above.
582 ///
583 /// TODO(ntv): implement alternatives to clipping.
584 /// TODO(ntv): support non-data-parallel operations.
585 template <>
586 LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
587     Operation *op, PatternRewriter &rewriter) const {
588   using namespace edsc::op;
589 
590   TransferWriteOp transfer = cast<TransferWriteOp>(op);
591   if (AffineMap::isMinorIdentity(transfer.permutation_map())) {
592     // If > 1D, emit a bunch of loops around 1-D vector transfers.
593     if (transfer.getVectorType().getRank() > 1)
594       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
595           .doReplace();
596     // If 1-D this is now handled by the target-specific lowering.
597     if (transfer.getVectorType().getRank() == 1)
598       return failure();
599   }
600 
601   // 1. Setup all the captures.
602   ScopedContext scope(rewriter, transfer.getLoc());
603   StdIndexedValue remote(transfer.memref());
604   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
605   Value vectorValue(transfer.vector());
606   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
607   int coalescedIdx = computeCoalescedIndex(transfer);
608   // Swap the vectorBoundsCapture which will reorder loop bounds.
609   if (coalescedIdx >= 0)
610     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
611                                    coalescedIdx);
612 
613   auto lbs = vectorBoundsCapture.getLbs();
614   auto ubs = vectorBoundsCapture.getUbs();
615   SmallVector<Value, 8> steps;
616   steps.reserve(vectorBoundsCapture.getSteps().size());
617   for (auto step : vectorBoundsCapture.getSteps())
618     steps.push_back(std_constant_index(step));
619 
620   // 2. Emit alloc-store-copy-dealloc.
621   Value tmp = std_alloc(tmpMemRefType(transfer));
622   StdIndexedValue local(tmp);
623   Value vec = vector_type_cast(tmp);
624   std_store(vectorValue, vec);
625   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
626     auto ivs = llvm::to_vector<8>(loopIvs);
627     // Swap the ivs which will reorder memory accesses.
628     if (coalescedIdx >= 0)
629       std::swap(ivs.back(), ivs[coalescedIdx]);
630     // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist).
631     remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs);
632   });
633   (std_dealloc(tmp)); // vexing parse...
634 
635   rewriter.eraseOp(op);
636   return success();
637 }
638 
639 void populateVectorToSCFConversionPatterns(
640     OwningRewritePatternList &patterns, MLIRContext *context,
641     const VectorTransferToSCFOptions &options) {
642   patterns.insert<VectorTransferRewriter<vector::TransferReadOp>,
643                   VectorTransferRewriter<vector::TransferWriteOp>>(options,
644                                                                    context);
645 }
646 
647 } // namespace mlir
648 
649 namespace {
650 
651 struct ConvertVectorToSCFPass
652     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
653   ConvertVectorToSCFPass() = default;
654   ConvertVectorToSCFPass(const ConvertVectorToSCFPass &pass) {}
655   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
656     this->fullUnroll = options.unroll;
657   }
658 
659   void runOnFunction() override {
660     OwningRewritePatternList patterns;
661     auto *context = getFunction().getContext();
662     populateVectorToSCFConversionPatterns(
663         patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll));
664     applyPatternsAndFoldGreedily(getFunction(), patterns);
665   }
666 };
667 
668 } // namespace
669 
670 std::unique_ptr<Pass>
671 mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
672   return std::make_unique<ConvertVectorToSCFPass>(options);
673 }
674