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