1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===//
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 the linalg dialect Vectorization transformations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Analysis/SliceAnalysis.h"
14 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
15 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
16 #include "mlir/Dialect/Func/IR/FuncOps.h"
17 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
18 #include "mlir/Dialect/Linalg/IR/Linalg.h"
19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/Tensor/IR/Tensor.h"
22 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
23 #include "mlir/Dialect/Vector/IR/VectorOps.h"
24 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h"
25 #include "mlir/IR/AffineExpr.h"
26 #include "mlir/IR/Matchers.h"
27 #include "mlir/IR/PatternMatch.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Support/LLVM.h"
30 #include "mlir/Transforms/RegionUtils.h"
31 #include "llvm/ADT/ScopeExit.h"
32 #include "llvm/ADT/Sequence.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <type_traits>
38 
39 using namespace mlir;
40 using namespace mlir::linalg;
41 
42 #define DEBUG_TYPE "linalg-vectorization"
43 
44 #define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ")
45 #define LDBG(X) LLVM_DEBUG(DBGS() << X)
46 
47 /// Try to vectorize `convOp` as a convolution.
48 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b,
49                                                    LinalgOp convOp);
50 
51 /// Return the unique instance of OpType in `block` if it is indeed unique.
52 /// Return null if none or more than 1 instances exist.
53 template <typename OpType>
54 static OpType getSingleOpOfType(Block &block) {
55   OpType res;
56   block.walk([&](OpType op) {
57     if (res) {
58       res = nullptr;
59       return WalkResult::interrupt();
60     }
61     res = op;
62     return WalkResult::advance();
63   });
64   return res;
65 }
66 
67 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a
68 /// projectedPermutation, compress the unused dimensions to serve as a
69 /// permutation_map for a vector transfer operation.
70 /// For example, given a linalg op such as:
71 ///
72 /// ```
73 ///   %0 = linalg.generic {
74 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>,
75 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)>
76 ///      }
77 ///     ins(%0 : tensor<2x3x4xf32>)
78 ///    outs(%1 : tensor<5x6xf32>)
79 /// ```
80 ///
81 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine
82 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second
83 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`.
84 static AffineMap reindexIndexingMap(AffineMap map) {
85   assert(map.isProjectedPermutation(/*allowZeroInResults=*/true) &&
86          "expected projected permutation");
87   auto res = compressUnusedDims(map);
88   assert(res.getNumDims() == res.getNumResults() &&
89          "expected reindexed map with same number of dims and results");
90   return res;
91 }
92 
93 /// Helper data structure to represent the result of vectorization.
94 /// In certain specific cases, like terminators, we do not want to propagate/
95 enum VectorizationStatus {
96   /// Op failed to vectorize.
97   Failure = 0,
98   /// Op vectorized and custom function took care of replacement logic
99   NoReplace,
100   /// Op vectorized into a new Op whose results will replace original Op's
101   /// results.
102   NewOp
103   // TODO: support values if Op vectorized to Many-Ops whose results we need to
104   // aggregate for replacement.
105 };
106 struct VectorizationResult {
107   /// Return status from vectorizing the current op.
108   enum VectorizationStatus status = VectorizationStatus::Failure;
109   /// New vectorized operation to replace the current op.
110   /// Replacement behavior is specified by `status`.
111   Operation *newOp;
112 };
113 
114 llvm::Optional<vector::CombiningKind>
115 mlir::linalg::getCombinerOpKind(Operation *combinerOp) {
116   using ::mlir::vector::CombiningKind;
117 
118   if (!combinerOp)
119     return llvm::None;
120   return llvm::TypeSwitch<Operation *, llvm::Optional<CombiningKind>>(
121              combinerOp)
122       .Case<arith::AddIOp, arith::AddFOp>(
123           [&](auto op) { return CombiningKind::ADD; })
124       .Case<arith::AndIOp>([&](auto op) { return CombiningKind::AND; })
125       .Case<arith::MaxSIOp>([&](auto op) { return CombiningKind::MAXSI; })
126       .Case<arith::MaxFOp>([&](auto op) { return CombiningKind::MAXF; })
127       .Case<arith::MinSIOp>([&](auto op) { return CombiningKind::MINSI; })
128       .Case<arith::MinFOp>([&](auto op) { return CombiningKind::MINF; })
129       .Case<arith::MulIOp, arith::MulFOp>(
130           [&](auto op) { return CombiningKind::MUL; })
131       .Case<arith::OrIOp>([&](auto op) { return CombiningKind::OR; })
132       .Case<arith::XOrIOp>([&](auto op) { return CombiningKind::XOR; })
133       .Default([&](auto op) { return llvm::None; });
134 }
135 
136 /// Check whether `outputOperand` is a reduction with a single combiner
137 /// operation. Return the combiner operation of the reduction. Return
138 /// nullptr otherwise. Multiple reduction operations would impose an
139 /// ordering between reduction dimensions and is currently unsupported in
140 /// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) !=
141 /// max(min(X))
142 // TODO: use in LinalgOp verification, there is a circular dependency atm.
143 static Operation *matchLinalgReduction(OpOperand *outputOperand) {
144   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
145   unsigned outputPos =
146       outputOperand->getOperandNumber() - linalgOp.getNumInputs();
147   // Only single combiner operations are supported for now.
148   SmallVector<Operation *, 4> combinerOps;
149   if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) ||
150       combinerOps.size() != 1)
151     return nullptr;
152 
153   // Return the combiner operation.
154   return combinerOps[0];
155 }
156 
157 /// Broadcast `value` to a vector of `shape` if possible. Return value
158 /// otherwise.
159 static Value broadcastIfNeeded(OpBuilder &b, Value value,
160                                ArrayRef<int64_t> shape) {
161   // If no shape to broadcast to, just return `value`.
162   if (shape.empty())
163     return value;
164   VectorType targetVectorType =
165       VectorType::get(shape, getElementTypeOrSelf(value));
166   if (vector::isBroadcastableTo(value.getType(), targetVectorType) !=
167       vector::BroadcastableToResult::Success)
168     return value;
169   Location loc = b.getInsertionPoint()->getLoc();
170   return b.createOrFold<vector::BroadcastOp>(loc, targetVectorType, value);
171 }
172 
173 /// Create MultiDimReductionOp to compute the reduction for `reductionOp`. This
174 /// assumes that `reductionOp` has two operands and one of them is the reduction
175 /// initial value.
176 static Value buildMultiDimReduce(OpBuilder &b, Operation *reduceOp,
177                                  Value valueToReduce,
178                                  const SmallVector<bool> &reductionMask) {
179   auto maybeKind = getCombinerOpKind(reduceOp);
180   assert(maybeKind && "Failed precondition: could not get reduction kind");
181   return b.create<vector::MultiDimReductionOp>(
182       reduceOp->getLoc(), valueToReduce, reductionMask, *maybeKind);
183 }
184 
185 static SmallVector<bool> getReductionMask(LinalgOp linalgOp) {
186   unsigned idx = 0;
187   SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false);
188   for (auto attr : linalgOp.iterator_types()) {
189     if (isReductionIterator(attr))
190       reductionMask[idx] = true;
191     ++idx;
192   }
193   return reductionMask;
194 }
195 
196 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set
197 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp
198 /// currently being vectorized. If `dest` has null rank, build an memref.store.
199 /// Return the produced value or null if no value is produced.
200 static Value buildVectorWrite(OpBuilder &b, Value value,
201                               OpOperand *outputOperand) {
202   Operation *write;
203   Location loc = value.getLoc();
204   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
205   ArrayRef<int64_t> shape = linalgOp.getShape(outputOperand);
206   auto vectorType = VectorType::get(
207       shape, getElementTypeOrSelf(outputOperand->get().getType()));
208   if (vectorType.getRank() > 0) {
209     // 0-d case is still special: do not invert the reindexing map.
210     AffineMap map =
211         reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand));
212     SmallVector<int64_t> transposeShape =
213         applyPermutationMap(inversePermutation(map), vectorType.getShape());
214     assert(!transposeShape.empty() && "unexpected empty transpose shape");
215     vectorType = VectorType::get(transposeShape, vectorType.getElementType());
216     SmallVector<Value> indices(linalgOp.getRank(outputOperand),
217                                b.create<arith::ConstantIndexOp>(loc, 0));
218     value = broadcastIfNeeded(b, value, vectorType.getShape());
219     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
220                                               indices, map);
221   } else {
222     if (!value.getType().isa<VectorType>())
223       value = b.create<vector::BroadcastOp>(loc, vectorType, value);
224     assert(value.getType() == vectorType && "incorrect type");
225     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
226                                               ValueRange{});
227   }
228   LDBG("vectorized op: " << *write);
229   if (!write->getResults().empty())
230     return write->getResult(0);
231   return Value();
232 }
233 
234 // Custom vectorization function type. Produce a vector form of Operation*
235 // assuming all its vectorized operands are already in the BlockAndValueMapping.
236 // Return nullptr if the Operation cannot be vectorized.
237 using CustomVectorizationHook = std::function<VectorizationResult(
238     Operation *, const BlockAndValueMapping &)>;
239 
240 /// Helper function to vectorize the terminator of a `linalgOp`. New result
241 /// vector values are appended to `newResults`. Return
242 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
243 /// should not try to map produced operations and instead return the results
244 /// using the `newResults` vector making them available to the
245 /// vectorization algorithm for RAUW. This function is meant to be used as a
246 /// CustomVectorizationHook.
247 static VectorizationResult
248 vectorizeLinalgYield(OpBuilder &b, Operation *op,
249                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
250                      SmallVectorImpl<Value> &newResults) {
251   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
252   if (!yieldOp)
253     return VectorizationResult{VectorizationStatus::Failure, nullptr};
254   for (const auto &outputs : llvm::enumerate(yieldOp.values())) {
255     // TODO: Scan for an opportunity for reuse.
256     // TODO: use a map.
257     Value vectorValue = bvm.lookup(outputs.value());
258     Value newResult = buildVectorWrite(
259         b, vectorValue, linalgOp.getOutputOperand(outputs.index()));
260     if (newResult)
261       newResults.push_back(newResult);
262   }
263   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
264 }
265 
266 /// Helper function to vectorize the index operations of a `linalgOp`. Return
267 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it
268 /// should map the produced operations. This function is meant to be used as a
269 /// CustomVectorizationHook.
270 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op,
271                                                 LinalgOp linalgOp) {
272   IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
273   if (!indexOp)
274     return VectorizationResult{VectorizationStatus::Failure, nullptr};
275   auto loc = indexOp.getLoc();
276   // Compute the static loop sizes of the index op.
277   auto targetShape = linalgOp.computeStaticLoopSizes();
278   // Compute a one-dimensional index vector for the index op dimension.
279   SmallVector<int64_t> constantSeq =
280       llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()]));
281   auto constantOp =
282       b.create<arith::ConstantOp>(loc, b.getIndexVectorAttr(constantSeq));
283   // Return the one-dimensional index vector if it lives in the trailing
284   // dimension of the iteration space since the vectorization algorithm in this
285   // case can handle the broadcast.
286   if (indexOp.dim() == targetShape.size() - 1)
287     return VectorizationResult{VectorizationStatus::NewOp, constantOp};
288   // Otherwise permute the targetShape to move the index dimension last,
289   // broadcast the one-dimensional index vector to the permuted shape, and
290   // finally transpose the broadcasted index vector to undo the permutation.
291   std::swap(targetShape[indexOp.dim()], targetShape.back());
292   auto broadCastOp = b.create<vector::BroadcastOp>(
293       loc, VectorType::get(targetShape, b.getIndexType()), constantOp);
294   SmallVector<int64_t> transposition =
295       llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
296   std::swap(transposition.back(), transposition[indexOp.dim()]);
297   auto transposeOp =
298       b.create<vector::TransposeOp>(loc, broadCastOp, transposition);
299   return VectorizationResult{VectorizationStatus::NewOp, transposeOp};
300 }
301 
302 /// Create a new vectorized verstion of `op` with the given operands and types.
303 static Operation *createVectorizedOp(OpBuilder &b, Operation *op,
304                                      ValueRange newOperands,
305                                      ArrayRef<Type> types) {
306   OperationState state(op->getLoc(), op->getName());
307   state.addAttributes(op->getAttrs());
308   state.addOperands(newOperands);
309   state.addTypes(types);
310   return b.createOperation(state);
311 }
312 
313 /// Emit reduction operations if the shapes of the value to reduce is different
314 /// that the result shape.
315 static Operation *reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op,
316                                  Value reduceValue, Value initialValue,
317                                  const BlockAndValueMapping &bvm) {
318   Value reduceVec = bvm.lookup(reduceValue);
319   Value outputVec = bvm.lookup(initialValue);
320   auto reduceType = reduceVec.getType().dyn_cast<VectorType>();
321   auto outputType = outputVec.getType().dyn_cast<VectorType>();
322   // Reduce only if needed as the value may already have been reduce for
323   // contraction vectorization.
324   if (!reduceType ||
325       (outputType && reduceType.getShape() == outputType.getShape()))
326     return nullptr;
327   SmallVector<bool> reductionMask = getReductionMask(linalgOp);
328   Value reduce = buildMultiDimReduce(b, op, reduceVec, reductionMask);
329   return createVectorizedOp(b, op, {reduce, outputVec}, reduce.getType());
330 }
331 
332 /// Generic vectorization for a single operation `op`, given already vectorized
333 /// operands carried by `bvm`. Vectorization occurs as follows:
334 ///   1. Try to apply any of the `customVectorizationHooks` and return its
335 ///   result on success.
336 ///   2. Clone any constant in the current scope without vectorization: each
337 ///   consumer of the constant will later determine the shape to which the
338 ///   constant needs to be broadcast to.
339 ///   3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
340 ///   of the `customVectorizationHooks` to cover such cases.
341 ///   4. Clone `op` in vector form to a vector of shape prescribed by the first
342 ///   operand of maximal rank. Other operands have smaller rank and are
343 ///   broadcast accordingly. It is assumed this broadcast is always legal,
344 ///   otherwise, it means one of the `customVectorizationHooks` is incorrect.
345 ///
346 /// This function assumes all operands of `op` have been vectorized and are in
347 /// the `bvm` mapping. As a consequence, this function is meant to be called on
348 /// a topologically-sorted list of ops.
349 /// This function does not update `bvm` but returns a VectorizationStatus that
350 /// instructs the caller what `bvm` update needs to occur.
351 static VectorizationResult
352 vectorizeOneOp(OpBuilder &b, LinalgOp linalgOp, Operation *op,
353                const BlockAndValueMapping &bvm,
354                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
355   LDBG("vectorize op " << *op);
356 
357   // 1. Try to apply any CustomVectorizationHook.
358   if (!customVectorizationHooks.empty()) {
359     for (auto &customFunc : customVectorizationHooks) {
360       VectorizationResult result = customFunc(op, bvm);
361       if (result.status == VectorizationStatus::Failure)
362         continue;
363       return result;
364     }
365   }
366 
367   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
368   // Clone so that the constant is not confined to the linalgOp block .
369   if (isa<arith::ConstantOp, func::ConstantOp>(op))
370     return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)};
371 
372   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
373   if (!OpTrait::hasElementwiseMappableTraits(op))
374     return VectorizationResult{VectorizationStatus::Failure, nullptr};
375 
376   // 4 . Check if the operation is a reduction.
377   SmallVector<std::pair<Value, Value>> reductionOperands;
378   for (Value operand : op->getOperands()) {
379     auto arg = operand.dyn_cast<BlockArgument>();
380     if (!arg || arg.getArgNumber() < linalgOp.getNumInputs())
381       continue;
382     SmallVector<Operation *> reductionOps;
383     Value reduceValue = matchReduction(
384         linalgOp.getRegionOutputArgs(),
385         arg.getArgNumber() - linalgOp.getNumInputs(), reductionOps);
386     if (!reduceValue)
387       continue;
388     reductionOperands.push_back(std::make_pair(reduceValue, operand));
389   }
390   if (!reductionOperands.empty()) {
391     assert(reductionOperands.size() == 1);
392     Operation *reduceOp =
393         reduceIfNeeded(b, linalgOp, op, reductionOperands[0].first,
394                        reductionOperands[0].second, bvm);
395     if (reduceOp)
396       return VectorizationResult{VectorizationStatus::NewOp, reduceOp};
397   }
398 
399   // 5. Generic vectorization path for ElementwiseMappable ops.
400   //   a. first get the first max ranked shape.
401   SmallVector<int64_t, 4> firstMaxRankedShape;
402   for (Value operand : op->getOperands()) {
403     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
404     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
405       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
406   }
407   //   b. broadcast each op if needed.
408   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
409     return firstMaxRankedShape.empty()
410                ? bvm.lookup(v)
411                : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape);
412   });
413   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
414   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
415     return firstMaxRankedShape.empty()
416                ? t
417                : VectorType::get(firstMaxRankedShape, t);
418   });
419 
420   // Build and return the new op.
421   return VectorizationResult{
422       VectorizationStatus::NewOp,
423       createVectorizedOp(b, op, llvm::to_vector<4>(vectorizedOperands),
424                          llvm::to_vector<4>(returnTypes))};
425 }
426 
427 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
428 static bool hasOnlyScalarElementwiseOp(Region &r) {
429   if (!llvm::hasSingleElement(r))
430     return false;
431   for (Operation &op : r.front()) {
432     if (!(isa<arith::ConstantOp, func::ConstantOp, linalg::YieldOp,
433               linalg::IndexOp>(op) ||
434           OpTrait::hasElementwiseMappableTraits(&op)) ||
435         llvm::any_of(op.getResultTypes(),
436                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
437       return false;
438   }
439   return true;
440 }
441 
442 // Return true if the op is an element-wise linalg op.
443 static bool isElementwise(Operation *op) {
444   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
445   if (!linalgOp)
446     return false;
447   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
448     return false;
449   // TODO: relax the restrictions on indexing map.
450   for (OpOperand *opOperand : linalgOp.getOutputOperands()) {
451     if (!linalgOp.getTiedIndexingMap(opOperand).isIdentity())
452       return false;
453   }
454   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
455 }
456 
457 /// Generic vectorization function that rewrites the body of a `linalgOp` into
458 /// vector form. Generic vectorization proceeds as follows:
459 ///   1. Verify the `linalgOp` has one non-empty region.
460 ///   2. Values defined above the region are mapped to themselves and will be
461 ///   broadcasted on a per-need basis by their consumers.
462 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
463 ///   load).
464 ///   TODO: Reuse opportunities for RAR dependencies.
465 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
466 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
467 ///   indices.
468 ///   5. Iteratively call vectorizeOneOp on the region operations.
469 ///
470 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
471 /// performed to the maximal common vector size implied by the `linalgOp`
472 /// iteration space. This eager broadcasting is introduced in the
473 /// permutation_map of the vector.transfer_read operations. The eager
474 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
475 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
476 /// the absence of good canonicalizations, the amount of work increases.
477 /// This is not deemed a problem as we expect canonicalizations and foldings to
478 /// aggressively clean up the useless work.
479 static LogicalResult
480 vectorizeAsLinalgGeneric(OpBuilder &b, LinalgOp linalgOp,
481                          SmallVectorImpl<Value> &newResults) {
482   Block *block = linalgOp.getBlock();
483 
484   // 2. Values defined above the region can only be broadcast for now. Make them
485   // map to themselves.
486   BlockAndValueMapping bvm;
487   SetVector<Value> valuesSet;
488   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
489   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
490 
491   if (linalgOp.getNumOutputs() == 0)
492     return failure();
493 
494   // TODO: the common vector shape is equal to the static loop sizes only when
495   // all indexing maps are projected permutations. For convs and stencils the
496   // logic will need to evolve.
497   SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes();
498 
499   // 3. Turn all BBArgs into vector.transfer_read / load.
500   Location loc = linalgOp.getLoc();
501   Value zero = b.create<arith::ConstantIndexOp>(loc, 0);
502   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
503     BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber());
504     if (linalgOp.isScalar(opOperand)) {
505       bvm.map(bbarg, opOperand->get());
506       continue;
507     }
508     VectorType readType;
509     AffineMap map;
510     // TODO: can we keep this simplification?
511     // if (linalgOp.getShape(opOperand).empty()) {
512     //   readType = VectorType::get({}, bbarg.getType());
513     // } else {
514     if (opOperand->getOperandNumber() < linalgOp.getNumInputs()) {
515       map = inverseAndBroadcastProjectedPermuation(
516           linalgOp.getTiedIndexingMap(opOperand));
517       readType = VectorType::get(commonVectorShape,
518                                  getElementTypeOrSelf(opOperand->get()));
519     } else {
520       map = inversePermutation(
521           reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
522       readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
523                                  getElementTypeOrSelf(opOperand->get()));
524     }
525     // }
526 
527     auto shape = linalgOp.getShape(opOperand);
528     SmallVector<Value> indices(shape.size(), zero);
529     Value readValue = b.create<vector::TransferReadOp>(
530         loc, readType, opOperand->get(), indices, map);
531     // Not all ops support 0-d vectors, extract the scalar for now.
532     // TODO: remove this.
533     if (readValue.getType().cast<VectorType>().getRank() == 0)
534       readValue = b.create<vector::ExtractElementOp>(loc, readValue);
535 
536     LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue);
537     bvm.map(bbarg, readValue);
538     bvm.map(opOperand->get(), readValue);
539   }
540 
541   SmallVector<CustomVectorizationHook> hooks;
542   // 4a. Register CustomVectorizationHook for yieldOp.
543   CustomVectorizationHook vectorizeYield =
544       [&](Operation *op,
545           const BlockAndValueMapping &bvm) -> VectorizationResult {
546     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
547   };
548   hooks.push_back(vectorizeYield);
549 
550   // 4b. Register CustomVectorizationHook for indexOp.
551   CustomVectorizationHook vectorizeIndex =
552       [&](Operation *op,
553           const BlockAndValueMapping &bvm) -> VectorizationResult {
554     return vectorizeLinalgIndex(b, op, linalgOp);
555   };
556   hooks.push_back(vectorizeIndex);
557 
558   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
559   for (Operation &op : block->getOperations()) {
560     VectorizationResult result = vectorizeOneOp(b, linalgOp, &op, bvm, hooks);
561     if (result.status == VectorizationStatus::Failure) {
562       LDBG("failed to vectorize: " << op);
563       return failure();
564     }
565     if (result.status == VectorizationStatus::NewOp) {
566       LDBG("new vector op: " << *result.newOp;);
567       bvm.map(op.getResults(), result.newOp->getResults());
568     }
569   }
570 
571   return success();
572 }
573 
574 /// Helper function to vectorize a `linalgOp` with contraction semantics in a
575 /// generic fashion.
576 /// This helper is needed atm because the truly generic implementation requires
577 /// good vector.multi_reduce folding patterns that are currently NYI.
578 // TODO: drop reliance on a specific pattern.
579 static bool allIndexingsAreProjectedPermutation(LinalgOp op) {
580   return llvm::all_of(op.getIndexingMaps(), [](AffineMap m) {
581     return m.isProjectedPermutation(/*allowZeroInResults=*/true);
582   });
583 }
584 
585 // TODO: probably need some extra checks for reduction followed by consumer
586 // ops that may not commute (e.g. linear reduction + non-linear instructions).
587 static LogicalResult reductionPreconditions(LinalgOp op) {
588   if (llvm::none_of(op.iterator_types(), isReductionIterator)) {
589     LDBG("reduction precondition failed: no reduction iterator");
590     return failure();
591   }
592   for (OpOperand *opOperand : op.getOutputOperands()) {
593     Operation *reduceOp = matchLinalgReduction(opOperand);
594     if (!reduceOp || !getCombinerOpKind(reduceOp)) {
595       LDBG("reduction precondition failed: reduction detection failed");
596       return failure();
597     }
598   }
599   return success();
600 }
601 
602 static LogicalResult vectorizeStaticLinalgOpPrecondition(linalg::LinalgOp op) {
603   if (isElementwise(op))
604     return success();
605   // TODO: isaConvolutionOpInterface that can also infer from generic features.
606   // But we will still need stride/dilation attributes that will be annoying to
607   // reverse-engineer...
608   if (isa<ConvolutionOpInterface>(op.getOperation()))
609     return success();
610   // TODO: the common vector shape is equal to the static loop sizes only when
611   // all indexing maps are projected permutations. For convs and stencils the
612   // logic will need to evolve.
613   if (!allIndexingsAreProjectedPermutation(op)) {
614     LDBG("precondition failed: not projected permutations");
615     return failure();
616   }
617   if (failed(reductionPreconditions(op))) {
618     LDBG("precondition failed: reduction preconditions");
619     return failure();
620   }
621   return success();
622 }
623 
624 static LogicalResult vectorizeLinalgOpPrecondition(LinalgOp linalgOp) {
625   // All types must be static shape to go to vector.
626   if (linalgOp.hasDynamicShape()) {
627     LDBG("precondition failed: dynamic shape");
628     return failure();
629   }
630   return vectorizeStaticLinalgOpPrecondition(linalgOp);
631 }
632 
633 LogicalResult mlir::linalg::vectorize(RewriterBase &rewriter,
634                                       LinalgOp linalgOp) {
635   if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
636     return failure();
637 
638   SmallVector<Value> results;
639   // TODO: isaConvolutionOpInterface that can also infer from generic
640   // features. Will require stride/dilation attributes inference.
641   FailureOr<Operation *> convOr = vectorizeConvolution(rewriter, linalgOp);
642   if (succeeded(convOr)) {
643     llvm::append_range(results, (*convOr)->getResults());
644   } else {
645     if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
646       return failure();
647     LDBG("Vectorize generic by broadcasting to a common shape: " << linalgOp);
648     if (failed(vectorizeAsLinalgGeneric(rewriter, linalgOp, results)))
649       return failure();
650   }
651 
652   if (!results.empty())
653     rewriter.replaceOp(linalgOp, results);
654   else
655     rewriter.eraseOp(linalgOp);
656 
657   return success();
658 }
659 
660 LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter,
661                                           memref::CopyOp copyOp) {
662 
663   auto srcType = copyOp.source().getType().cast<MemRefType>();
664   auto dstType = copyOp.target().getType().cast<MemRefType>();
665   if (!srcType.hasStaticShape() || !dstType.hasStaticShape())
666     return failure();
667 
668   auto readType =
669       VectorType::get(srcType.getShape(), getElementTypeOrSelf(srcType));
670   auto writeType =
671       VectorType::get(dstType.getShape(), getElementTypeOrSelf(dstType));
672 
673   Location loc = copyOp->getLoc();
674   Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
675   SmallVector<Value> indices(srcType.getRank(), zero);
676 
677   Value readValue = rewriter.create<vector::TransferReadOp>(
678       loc, readType, copyOp.source(), indices,
679       rewriter.getMultiDimIdentityMap(srcType.getRank()));
680   if (readValue.getType().cast<VectorType>().getRank() == 0) {
681     readValue = rewriter.create<vector::ExtractElementOp>(loc, readValue);
682     readValue = rewriter.create<vector::BroadcastOp>(loc, writeType, readValue);
683   }
684   Operation *writeValue = rewriter.create<vector::TransferWriteOp>(
685       loc, readValue, copyOp.target(), indices,
686       rewriter.getMultiDimIdentityMap(srcType.getRank()));
687   copyOp->getParentOfType<FuncOp>().dump();
688   rewriter.replaceOp(copyOp, writeValue->getResults());
689   return success();
690 }
691 
692 //----------------------------------------------------------------------------//
693 // Misc. vectorization patterns.
694 //----------------------------------------------------------------------------//
695 
696 /// Helper function that retrieves the value of an IntegerAttr.
697 static int64_t getIntFromAttr(Attribute attr) {
698   return attr.cast<IntegerAttr>().getInt();
699 }
700 
701 /// Given an ArrayRef of OpFoldResults, return a vector of Values.
702 /// IntegerAttrs are converted to ConstantIndexOps. Other attribute types are
703 /// not supported.
704 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
705                                            ArrayRef<OpFoldResult> ofrs) {
706   SmallVector<Value> result;
707   llvm::for_each(ofrs, [&](auto o) {
708     if (auto val = o.template dyn_cast<Value>()) {
709       result.push_back(val);
710     } else {
711       result.push_back(builder.create<arith::ConstantIndexOp>(
712           loc, getIntFromAttr(o.template get<Attribute>())));
713     }
714   });
715   return result;
716 }
717 
718 /// Rewrite a tensor::PadOp into a sequence of InitTensorOp, FillOp and
719 /// InsertSliceOp. For now, only constant padding values are supported.
720 /// If there is enough static type information, TransferReadOps and
721 /// TransferWriteOps may be generated instead of InsertSliceOps.
722 struct GenericPadOpVectorizationPattern : public GeneralizePadOpPattern {
723   GenericPadOpVectorizationPattern(MLIRContext *context,
724                                    PatternBenefit benefit = 1)
725       : GeneralizePadOpPattern(context, tryVectorizeCopy, benefit) {}
726   /// Vectorize the copying of a tensor::PadOp's source. This is possible if
727   /// each dimension size is statically know in the source type or the result
728   /// type (or both).
729   static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter,
730                                         tensor::PadOp padOp, Value dest) {
731     auto sourceType = padOp.getSourceType();
732     auto resultType = padOp.getResultType();
733 
734     // Copy cannot be vectorized if pad value is non-constant and source shape
735     // is dynamic. In case of a dynamic source shape, padding must be appended
736     // by TransferReadOp, but TransferReadOp supports only constant padding.
737     auto padValue = padOp.getConstantPaddingValue();
738     if (!padValue) {
739       if (!sourceType.hasStaticShape())
740         return failure();
741       // Create dummy padding value.
742       auto elemType = sourceType.getElementType();
743       padValue = rewriter.create<arith::ConstantOp>(
744           padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType));
745     }
746 
747     SmallVector<int64_t> vecShape;
748     SmallVector<bool> readInBounds;
749     SmallVector<bool> writeInBounds;
750     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
751       if (!sourceType.isDynamicDim(i)) {
752         vecShape.push_back(sourceType.getDimSize(i));
753         // Source shape is statically known: Neither read nor write are
754         // out-of- bounds.
755         readInBounds.push_back(true);
756         writeInBounds.push_back(true);
757       } else if (!resultType.isDynamicDim(i)) {
758         // Source shape is not statically known, but result shape is.
759         // Vectorize with size of result shape. This may be larger than the
760         // source size.
761         vecShape.push_back(resultType.getDimSize(i));
762         // Read may be out-of-bounds because the result size could be larger
763         // than the source size.
764         readInBounds.push_back(false);
765         // Write is out-of-bounds if low padding > 0.
766         writeInBounds.push_back(
767             getConstantIntValue(padOp.getMixedLowPad()[i]) ==
768             static_cast<int64_t>(0));
769       } else {
770         // Neither source nor result dim of padOp is static. Cannot vectorize
771         // the copy.
772         return failure();
773       }
774     }
775     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
776 
777     // Generate TransferReadOp.
778     SmallVector<Value> readIndices(
779         vecType.getRank(),
780         rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
781     auto read = rewriter.create<vector::TransferReadOp>(
782         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
783         ArrayRef<bool>{readInBounds});
784 
785     // If `dest` is a FillOp and the TransferWriteOp would overwrite the
786     // entire tensor, write directly to the FillOp's operand.
787     if (llvm::equal(vecShape, resultType.getShape()) &&
788         llvm::all_of(writeInBounds, [](bool b) { return b; }))
789       if (auto fill = dest.getDefiningOp<FillOp>())
790         dest = fill.output();
791 
792     // Generate TransferWriteOp.
793     auto writeIndices =
794         ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad());
795     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
796         padOp, read, dest, writeIndices, ArrayRef<bool>{writeInBounds});
797 
798     return success();
799   }
800 };
801 
802 /// Base pattern for rewriting tensor::PadOps whose result is consumed by a
803 /// given operation type OpTy.
804 template <typename OpTy>
805 struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> {
806   using OpRewritePattern<tensor::PadOp>::OpRewritePattern;
807 
808   LogicalResult matchAndRewrite(tensor::PadOp padOp,
809                                 PatternRewriter &rewriter) const final {
810     bool changed = false;
811     // Insert users in vector, because some users may be replaced/removed.
812     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
813       if (auto op = dyn_cast<OpTy>(user))
814         changed |= rewriteUser(rewriter, padOp, op).succeeded();
815     return success(changed);
816   }
817 
818 protected:
819   virtual LogicalResult rewriteUser(PatternRewriter &rewriter,
820                                     tensor::PadOp padOp, OpTy op) const = 0;
821 };
822 
823 /// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.:
824 /// ```
825 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
826 /// %r = vector.transfer_read %0[%c0, %c0], %cst
827 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
828 /// ```
829 /// is rewritten to:
830 /// ```
831 /// %r = vector.transfer_read %src[%c0, %c0], %padding
832 ///     {in_bounds = [true, true]}
833 ///     : tensor<?x?xf32>, vector<17x5xf32>
834 /// ```
835 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
836 /// sure that the original padding value %cst was never used.
837 ///
838 /// This rewrite is possible if:
839 /// - `xferOp` has no out-of-bounds dims or mask.
840 /// - Low padding is static 0.
841 /// - Single, scalar padding value.
842 struct PadOpVectorizationWithTransferReadPattern
843     : public VectorizePadOpUserPattern<vector::TransferReadOp> {
844   using VectorizePadOpUserPattern<
845       vector::TransferReadOp>::VectorizePadOpUserPattern;
846 
847   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
848                             vector::TransferReadOp xferOp) const override {
849     // Low padding must be static 0.
850     if (!padOp.hasZeroLowPad())
851       return failure();
852     // Pad value must be a constant.
853     auto padValue = padOp.getConstantPaddingValue();
854     if (!padValue)
855       return failure();
856     // Padding value of existing `xferOp` is unused.
857     if (xferOp.hasOutOfBoundsDim() || xferOp.mask())
858       return failure();
859 
860     rewriter.updateRootInPlace(xferOp, [&]() {
861       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
862       xferOp->setAttr(xferOp.getInBoundsAttrName(),
863                       rewriter.getBoolArrayAttr(inBounds));
864       xferOp.sourceMutable().assign(padOp.source());
865       xferOp.paddingMutable().assign(padValue);
866     });
867 
868     return success();
869   }
870 };
871 
872 /// Rewrite use of tensor::PadOp result in TransferWriteOp.
873 /// This pattern rewrites TransferWriteOps that write to a padded tensor
874 /// value, where the same amount of padding is immediately removed again after
875 /// the write. In such cases, the TransferWriteOp can write to the non-padded
876 /// tensor value and apply out-of-bounds masking. E.g.:
877 /// ```
878 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
879 ///     : tensor<...> to tensor<?x?xf32>
880 /// %1 = linalg.pad_tensor %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
881 /// %2 = vector.transfer_write %vec, %1[...]
882 ///     : vector<17x5xf32>, tensor<17x5xf32>
883 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
884 ///     : tensor<17x5xf32> to tensor<?x?xf32>
885 /// ```
886 /// is rewritten to:
887 /// ```
888 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
889 ///     : tensor<...> to tensor<?x?xf32>
890 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>,
891 /// tensor<?x?xf32>
892 /// ```
893 /// Note: It is important that the ExtractSliceOp %r resizes the result of the
894 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an
895 /// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ
896 /// from %r's old dimensions.
897 ///
898 /// This rewrite is possible if:
899 /// - Low padding is static 0.
900 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
901 ///   ExtractSliceOp trims the same amount of padding that was added
902 ///   beforehand.
903 /// - Single, scalar padding value.
904 struct PadOpVectorizationWithTransferWritePattern
905     : public VectorizePadOpUserPattern<vector::TransferWriteOp> {
906   using VectorizePadOpUserPattern<
907       vector::TransferWriteOp>::VectorizePadOpUserPattern;
908 
909   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
910                             vector::TransferWriteOp xferOp) const override {
911     // TODO: support 0-d corner case.
912     if (xferOp.getTransferRank() == 0)
913       return failure();
914 
915     // Low padding must be static 0.
916     if (!padOp.hasZeroLowPad())
917       return failure();
918     // Pad value must be a constant.
919     auto padValue = padOp.getConstantPaddingValue();
920     if (!padValue)
921       return failure();
922     // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
923     if (!xferOp->hasOneUse())
924       return failure();
925     auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
926     if (!trimPadding)
927       return failure();
928     // Only static zero offsets supported when trimming padding.
929     if (!trimPadding.hasZeroOffset())
930       return failure();
931     // trimPadding must remove the amount of padding that was added earlier.
932     if (!hasSameTensorSize(padOp.source(), trimPadding))
933       return failure();
934 
935     // Insert the new TransferWriteOp at position of the old TransferWriteOp.
936     rewriter.setInsertionPoint(xferOp);
937 
938     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
939     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
940         xferOp, padOp.source().getType(), xferOp.vector(), padOp.source(),
941         xferOp.indices(), xferOp.permutation_mapAttr(), xferOp.mask(),
942         rewriter.getBoolArrayAttr(inBounds));
943     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
944 
945     return success();
946   }
947 
948   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
949   /// i.e., same dimensions.
950   ///
951   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
952   /// dimensions, this function tries to infer the (static) tensor size by
953   /// looking at the defining op and utilizing op-specific knowledge.
954   ///
955   /// This is a conservative analysis. In case equal tensor sizes cannot be
956   /// proven statically, this analysis returns `false` even though the tensor
957   /// sizes may turn out to be equal at runtime.
958   bool hasSameTensorSize(Value beforePadding,
959                          tensor::ExtractSliceOp afterTrimming) const {
960     // If the input to tensor::PadOp is a CastOp, try with with both CastOp
961     // result and CastOp operand.
962     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
963       if (hasSameTensorSize(castOp.source(), afterTrimming))
964         return true;
965 
966     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
967     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
968     // Only RankedTensorType supported.
969     if (!t1 || !t2)
970       return false;
971     // Rank of both values must be the same.
972     if (t1.getRank() != t2.getRank())
973       return false;
974 
975     // All static dimensions must be the same. Mixed cases (e.g., dimension
976     // static in `t1` but dynamic in `t2`) are not supported.
977     for (unsigned i = 0; i < t1.getRank(); ++i) {
978       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
979         return false;
980       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
981         return false;
982     }
983 
984     // Nothing more to check if all dimensions are static.
985     if (t1.getNumDynamicDims() == 0)
986       return true;
987 
988     // All dynamic sizes must be the same. The only supported case at the
989     // moment is when `beforePadding` is an ExtractSliceOp (or a cast
990     // thereof).
991 
992     // Apart from CastOp, only ExtractSliceOp is supported.
993     auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
994     if (!beforeSlice)
995       return false;
996 
997     assert(static_cast<size_t>(t1.getRank()) ==
998            beforeSlice.getMixedSizes().size());
999     assert(static_cast<size_t>(t2.getRank()) ==
1000            afterTrimming.getMixedSizes().size());
1001 
1002     for (unsigned i = 0; i < t1.getRank(); ++i) {
1003       // Skip static dimensions.
1004       if (!t1.isDynamicDim(i))
1005         continue;
1006       auto size1 = beforeSlice.getMixedSizes()[i];
1007       auto size2 = afterTrimming.getMixedSizes()[i];
1008 
1009       // Case 1: Same value or same constant int.
1010       if (isEqualConstantIntOrValue(size1, size2))
1011         continue;
1012 
1013       // Other cases: Take a deeper look at defining ops of values.
1014       auto v1 = size1.dyn_cast<Value>();
1015       auto v2 = size2.dyn_cast<Value>();
1016       if (!v1 || !v2)
1017         return false;
1018 
1019       // Case 2: Both values are identical AffineMinOps. (Should not happen if
1020       // CSE is run.)
1021       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
1022       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
1023       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() &&
1024           minOp1.operands() == minOp2.operands())
1025         continue;
1026 
1027       // Add additional cases as needed.
1028     }
1029 
1030     // All tests passed.
1031     return true;
1032   }
1033 };
1034 
1035 /// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.:
1036 /// ```
1037 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
1038 /// %r = tensor.insert_slice %0
1039 ///     into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
1040 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
1041 /// ```
1042 /// is rewritten to:
1043 /// ```
1044 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
1045 ///     : tensor<?x?xf32>, vector<17x5xf32>
1046 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
1047 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
1048 /// ```
1049 ///
1050 /// This rewrite is possible if:
1051 /// - Low padding is static 0.
1052 /// - `padOp` result shape is static.
1053 /// - The entire padded tensor is inserted.
1054 ///   (Implies that sizes of `insertOp` are all static.)
1055 /// - Only unit strides in `insertOp`.
1056 /// - Single, scalar padding value.
1057 /// - `padOp` result not used as destination.
1058 struct PadOpVectorizationWithInsertSlicePattern
1059     : public VectorizePadOpUserPattern<tensor::InsertSliceOp> {
1060   using VectorizePadOpUserPattern<
1061       tensor::InsertSliceOp>::VectorizePadOpUserPattern;
1062 
1063   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
1064                             tensor::InsertSliceOp insertOp) const override {
1065     // Low padding must be static 0.
1066     if (!padOp.hasZeroLowPad())
1067       return failure();
1068     // Only unit stride supported.
1069     if (!insertOp.hasUnitStride())
1070       return failure();
1071     // Pad value must be a constant.
1072     auto padValue = padOp.getConstantPaddingValue();
1073     if (!padValue)
1074       return failure();
1075     // Dynamic shapes not supported.
1076     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
1077       return failure();
1078     // Pad result not used as destination.
1079     if (insertOp.dest() == padOp.result())
1080       return failure();
1081 
1082     auto vecType = VectorType::get(padOp.getType().getShape(),
1083                                    padOp.getType().getElementType());
1084     unsigned vecRank = vecType.getRank();
1085     unsigned tensorRank = insertOp.getType().getRank();
1086 
1087     // Check if sizes match: Insert the entire tensor into most minor dims.
1088     // (No permutations allowed.)
1089     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1090     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1091     if (!llvm::all_of(
1092             llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
1093               return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
1094             }))
1095       return failure();
1096 
1097     // Insert the TransferReadOp and TransferWriteOp at the position of the
1098     // InsertSliceOp.
1099     rewriter.setInsertionPoint(insertOp);
1100 
1101     // Generate TransferReadOp: Read entire source tensor and add high
1102     // padding.
1103     SmallVector<Value> readIndices(
1104         vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
1105     auto read = rewriter.create<vector::TransferReadOp>(
1106         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1107 
1108     // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
1109     // specified offsets. Write is fully in-bounds because a InsertSliceOp's
1110     // source must fit into the destination at the specified offsets.
1111     auto writeIndices =
1112         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1113     SmallVector<bool> inBounds(vecRank, true);
1114     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1115         insertOp, read, insertOp.dest(), writeIndices,
1116         ArrayRef<bool>{inBounds});
1117 
1118     return success();
1119   }
1120 };
1121 
1122 void mlir::linalg::populatePadOpVectorizationPatterns(
1123     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1124   patterns.add<GenericPadOpVectorizationPattern>(patterns.getContext(),
1125                                                  baseBenefit);
1126   // Try these specialized patterns first before resorting to the generic one.
1127   patterns.add<PadOpVectorizationWithTransferReadPattern,
1128                PadOpVectorizationWithTransferWritePattern,
1129                PadOpVectorizationWithInsertSlicePattern>(
1130       patterns.getContext(), baseBenefit.getBenefit() + 1);
1131 }
1132 
1133 //----------------------------------------------------------------------------//
1134 // Forwarding patterns
1135 //----------------------------------------------------------------------------//
1136 
1137 /// Check whether there is any interleaved use of any `values` between
1138 /// `firstOp` and `secondOp`. Conservatively return `true` if any op or value
1139 /// is in a different block.
1140 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1141                                     ValueRange values) {
1142   if (firstOp->getBlock() != secondOp->getBlock() ||
1143       !firstOp->isBeforeInBlock(secondOp)) {
1144     LDBG("interleavedUses precondition failed, firstOp: "
1145          << *firstOp << ", second op: " << *secondOp);
1146     return true;
1147   }
1148   for (auto v : values) {
1149     for (auto &u : v.getUses()) {
1150       Operation *owner = u.getOwner();
1151       if (owner == firstOp || owner == secondOp)
1152         continue;
1153       // TODO: this is too conservative, use dominance info in the future.
1154       if (owner->getBlock() == firstOp->getBlock() &&
1155           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1156         continue;
1157       LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp
1158                                     << ", second op: " << *secondOp);
1159       return true;
1160     }
1161   }
1162   return false;
1163 }
1164 
1165 /// Return the unique subview use of `v` if it is indeed unique, null
1166 /// otherwise.
1167 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1168   memref::SubViewOp subViewOp;
1169   for (auto &u : v.getUses()) {
1170     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1171       if (subViewOp)
1172         return memref::SubViewOp();
1173       subViewOp = newSubViewOp;
1174     }
1175   }
1176   return subViewOp;
1177 }
1178 
1179 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1180 /// when available.
1181 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1182     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1183 
1184   // TODO: support mask.
1185   if (xferOp.mask())
1186     return failure();
1187 
1188   // Transfer into `view`.
1189   Value viewOrAlloc = xferOp.source();
1190   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1191       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1192     return failure();
1193 
1194   LDBG(viewOrAlloc);
1195 
1196   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1197   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1198   if (!subViewOp)
1199     return failure();
1200   Value subView = subViewOp.getResult();
1201   LDBG("with subView " << subView);
1202 
1203   // Find the copy into `subView` without interleaved uses.
1204   memref::CopyOp copyOp;
1205   for (auto &u : subView.getUses()) {
1206     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1207       assert(newCopyOp.target().getType().isa<MemRefType>());
1208       if (newCopyOp.target() != subView)
1209         continue;
1210       LDBG("copy candidate " << *newCopyOp);
1211       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1212         continue;
1213       copyOp = newCopyOp;
1214       break;
1215     }
1216   }
1217   if (!copyOp)
1218     return failure();
1219   LDBG("with copy " << *copyOp);
1220 
1221   // Find the fill into `viewOrAlloc` without interleaved uses before the
1222   // copy.
1223   FillOp maybeFillOp;
1224   for (auto &u : viewOrAlloc.getUses()) {
1225     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1226       assert(newFillOp.output().getType().isa<MemRefType>());
1227       if (newFillOp.output() != viewOrAlloc)
1228         continue;
1229       LDBG("fill candidate " << *newFillOp);
1230       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1231         continue;
1232       maybeFillOp = newFillOp;
1233       break;
1234     }
1235   }
1236   // Ensure padding matches.
1237   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
1238     return failure();
1239   if (maybeFillOp)
1240     LDBG("with maybeFillOp " << *maybeFillOp);
1241 
1242   // `in` is the subview that memref.copy reads. Replace it.
1243   Value in = copyOp.source();
1244 
1245   // memref.copy + linalg.fill can be used to create a padded local buffer.
1246   // The `masked` attribute is only valid on this padded buffer.
1247   // When forwarding to vector.transfer_read, the attribute must be reset
1248   // conservatively.
1249   Value res = rewriter.create<vector::TransferReadOp>(
1250       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
1251       xferOp.permutation_mapAttr(), xferOp.padding(), xferOp.mask(),
1252       // in_bounds is explicitly reset
1253       /*inBoundsAttr=*/ArrayAttr());
1254 
1255   if (maybeFillOp)
1256     rewriter.eraseOp(maybeFillOp);
1257   rewriter.eraseOp(copyOp);
1258   rewriter.replaceOp(xferOp, res);
1259 
1260   return success();
1261 }
1262 
1263 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1264 /// when available.
1265 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1266     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1267   // TODO: support mask.
1268   if (xferOp.mask())
1269     return failure();
1270 
1271   // Transfer into `viewOrAlloc`.
1272   Value viewOrAlloc = xferOp.source();
1273   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1274       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1275     return failure();
1276 
1277   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1278   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1279   if (!subViewOp)
1280     return failure();
1281   Value subView = subViewOp.getResult();
1282 
1283   // Find the copy from `subView` without interleaved uses.
1284   memref::CopyOp copyOp;
1285   for (auto &u : subViewOp.getResult().getUses()) {
1286     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1287       if (newCopyOp.source() != subView)
1288         continue;
1289       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1290         continue;
1291       copyOp = newCopyOp;
1292       break;
1293     }
1294   }
1295   if (!copyOp)
1296     return failure();
1297 
1298   // `out` is the subview copied into that we replace.
1299   assert(copyOp.target().getType().isa<MemRefType>());
1300   Value out = copyOp.target();
1301 
1302   // Forward vector.transfer into copy.
1303   // memref.copy + linalg.fill can be used to create a padded local buffer.
1304   // The `masked` attribute is only valid on this padded buffer.
1305   // When forwarding to vector.transfer_write, the attribute must be reset
1306   // conservatively.
1307   rewriter.create<vector::TransferWriteOp>(
1308       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
1309       xferOp.permutation_mapAttr(), xferOp.mask(),
1310       // in_bounds is explicitly reset
1311       /*inBoundsAttr=*/ArrayAttr());
1312 
1313   rewriter.eraseOp(copyOp);
1314   rewriter.eraseOp(xferOp);
1315 
1316   return success();
1317 }
1318 
1319 //===----------------------------------------------------------------------===//
1320 // Convolution vectorization patterns
1321 //===----------------------------------------------------------------------===//
1322 
1323 template <int N>
1324 static void bindShapeDims(ShapedType shapedType) {}
1325 
1326 template <int N, typename IntTy, typename... IntTy2>
1327 static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) {
1328   val = shapedType.getShape()[N];
1329   bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...);
1330 }
1331 
1332 /// Bind a pack of int& to the leading dimensions of shapedType.getShape().
1333 template <typename... IntTy>
1334 static void bindShapeDims(ShapedType shapedType, IntTy &...vals) {
1335   bindShapeDims<0>(shapedType, vals...);
1336 }
1337 
1338 namespace {
1339 /// Generate a vector implementation for either:
1340 /// ```
1341 ///   Op def: (     n,     w,     c,    kw,    f  )
1342 ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1343 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1344 /// ```
1345 /// kw is unrolled, w is unrolled iff dilationW > 1.
1346 ///
1347 /// or
1348 ///
1349 /// ```
1350 ///   Op def: (     n,     w,     c,    kw )
1351 ///    Iters: ({Par(), Par(), Par(), Red()})
1352 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1353 /// ```
1354 /// kw is unrolled, w is unrolled iff dilationW > 1.
1355 struct Conv1DNwcGenerator : public StructuredGenerator<LinalgOp> {
1356   Conv1DNwcGenerator(OpBuilder &builder, LinalgOp linalgOp, int strideW,
1357                      int dilationW)
1358       : StructuredGenerator<LinalgOp>(builder, linalgOp), strideW(strideW),
1359         dilationW(dilationW) {
1360     // Determine whether `linalgOp` can be generated with this generator
1361     if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1)
1362       return;
1363     lhsShaped = linalgOp.inputs()[0];
1364     rhsShaped = linalgOp.inputs()[1];
1365     resShaped = linalgOp.outputs()[0];
1366     lhsShapedType = lhsShaped.getType().dyn_cast<ShapedType>();
1367     rhsShapedType = rhsShaped.getType().dyn_cast<ShapedType>();
1368     resShapedType = resShaped.getType().dyn_cast<ShapedType>();
1369     if (!lhsShapedType || !rhsShapedType || !resShapedType)
1370       return;
1371     if (lhsShapedType.getRank() != 3 ||
1372         (rhsShapedType.getRank() != 2 && rhsShapedType.getRank() != 3) ||
1373         resShapedType.getRank() != 3)
1374       return;
1375 
1376     // Check for reduction `add` preceded by `mul`.
1377     Operation *reduceOp = matchLinalgReduction(linalgOp.getOutputOperand(0));
1378     if (!reduceOp)
1379       return;
1380     llvm::Optional<vector::CombiningKind> maybeKind;
1381     maybeKind = getCombinerOpKind(reduceOp);
1382     if (!maybeKind || *maybeKind != vector::CombiningKind::ADD)
1383       return;
1384     maybeKind = getCombinerOpKind(&(linalgOp->getRegion(0).front().front()));
1385     if (!maybeKind || *maybeKind != vector::CombiningKind::MUL)
1386       return;
1387 
1388     // The op is now known to be valid.
1389     valid = true;
1390   }
1391 
1392   /// Generate a vector implementation for:
1393   /// ```
1394   ///   Op def: (     n,     w,     c,    kw,    f  )
1395   ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1396   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1397   /// ```
1398   /// kw is always unrolled.
1399   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1400   /// > 1.
1401   FailureOr<Operation *> conv() {
1402     if (!valid)
1403       return failure();
1404 
1405     int64_t nSize, wSize, cSize, kwSize, fSize;
1406     // kernel{kw, c, f}
1407     bindShapeDims(rhsShapedType, kwSize, cSize, fSize);
1408     // out{n, w, f}
1409     bindShapeDims(resShapedType, nSize, wSize);
1410 
1411     vector::TransferWriteOp write;
1412     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1413 
1414     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1415     // When strideW == 1, we can batch the contiguous loads and avoid
1416     // unrolling
1417     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1418 
1419     Type lhsEltType = lhsShapedType.getElementType();
1420     Type rhsEltType = rhsShapedType.getElementType();
1421     Type resEltType = resShapedType.getElementType();
1422     VectorType lhsType = VectorType::get(
1423         {nSize,
1424          // iw = ow * sw + kw *  dw - 1
1425          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1426          // Perform the proper inclusive -> exclusive -> inclusive.
1427          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1428          cSize},
1429         lhsEltType);
1430     VectorType rhsType = VectorType::get({kwSize, cSize, fSize}, rhsEltType);
1431     VectorType resType = VectorType::get({nSize, wSize, fSize}, resEltType);
1432 
1433     // Read lhs slice of size {w * strideW + kw * dilationW, c, f} @ [0, 0,
1434     // 0].
1435     Value lhs = builder.create<vector::TransferReadOp>(
1436         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1437     // Read rhs slice of size {kw, c, f} @ [0, 0, 0].
1438     Value rhs = builder.create<vector::TransferReadOp>(
1439         loc, rhsType, rhsShaped, ValueRange{zero, zero, zero});
1440     // Read res slice of size {n, w, f} @ [0, 0, 0].
1441     Value res = builder.create<vector::TransferReadOp>(
1442         loc, resType, resShaped, ValueRange{zero, zero, zero});
1443 
1444     //===------------------------------------------------------------------===//
1445     // Begin vector-only rewrite part
1446     //===------------------------------------------------------------------===//
1447     // Unroll along kw and read slices of lhs and rhs.
1448     SmallVector<Value> lhsVals, rhsVals, resVals;
1449     // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0].
1450     for (int64_t kw = 0; kw < kwSize; ++kw) {
1451       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1452         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1453             loc, lhs,
1454             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1455             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1456             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1457       }
1458     }
1459     // Extract rhs slice of size {c, f} @ [kw].
1460     for (int64_t kw = 0; kw < kwSize; ++kw) {
1461       rhsVals.push_back(builder.create<vector::ExtractOp>(
1462           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1463     }
1464     // Extract res slice: {n, wSizeStep, f} @ [0, w, 0].
1465     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1466       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1467           loc, res,
1468           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1469           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, fSize},
1470           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1471     }
1472 
1473     auto linearIndex = [&](int64_t kw, int64_t w) {
1474       return kw * (wSize / wSizeStep) + w;
1475     };
1476 
1477     // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f}
1478     for (int64_t kw = 0; kw < kwSize; ++kw) {
1479       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1480         resVals[w] = conv1dSliceAsContraction(
1481             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1482       }
1483     }
1484 
1485     // Write back res slice: {n, wSizeStep, f} @ [0, w, 0].
1486     // This does not depend on kw.
1487     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1488       res = builder.create<vector::InsertStridedSliceOp>(
1489           loc, resVals[w], res,
1490           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1491           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1492     }
1493     //===------------------------------------------------------------------===//
1494     // End vector-only rewrite part
1495     //===------------------------------------------------------------------===//
1496 
1497     // Write back res slice of size {n, w, f} @ [0, 0, 0].
1498     return builder
1499         .create<vector::TransferWriteOp>(loc, res, resShaped,
1500                                          ValueRange{zero, zero, zero})
1501         .getOperation();
1502   }
1503 
1504   // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f}
1505   Value conv1dSliceAsContraction(OpBuilder &b, Location loc, Value lhs,
1506                                  Value rhs, Value res) {
1507     StringRef par = Par().strRef, red = Red().strRef;
1508     AffineExpr n, w, f, c;
1509     bindDims(ctx, n, w, f, c);
1510     return builder.create<vector::ContractionOp>(
1511         loc, lhs, rhs, res,
1512         /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}},
1513         /*iteratorTypes=*/ArrayRef<StringRef>{par, par, par, red});
1514   }
1515 
1516   /// Generate a vector implementation for:
1517   /// ```
1518   ///   Op def: (     n,     w,     c,    kw)
1519   ///    Iters: ({Par(), Par(), Par(), Red()})
1520   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1521   /// ```
1522   /// kw is always unrolled.
1523   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1524   /// > 1.
1525   FailureOr<Operation *> depthwiseConv() {
1526     if (!valid)
1527       return failure();
1528 
1529     int64_t nSize, wSize, cSize, kwSize;
1530     // kernel{kw, c}
1531     bindShapeDims(rhsShapedType, kwSize, cSize);
1532     // out{n, w, c}
1533     bindShapeDims(resShapedType, nSize, wSize);
1534 
1535     vector::TransferWriteOp write;
1536     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1537 
1538     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1539     // When strideW == 1, we can batch the contiguous loads and avoid
1540     // unrolling
1541     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1542 
1543     Type lhsEltType = lhsShapedType.getElementType();
1544     Type rhsEltType = rhsShapedType.getElementType();
1545     Type resEltType = resShapedType.getElementType();
1546     VectorType lhsType = VectorType::get(
1547         {nSize,
1548          // iw = ow * sw + kw *  dw - 1
1549          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1550          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1551          cSize},
1552         lhsEltType);
1553     VectorType rhsType = VectorType::get({kwSize, cSize}, rhsEltType);
1554     VectorType resType = VectorType::get({nSize, wSize, cSize}, resEltType);
1555 
1556     // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0,
1557     // 0].
1558     Value lhs = builder.create<vector::TransferReadOp>(
1559         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1560     // Read rhs slice of size {kw, c} @ [0, 0].
1561     Value rhs = builder.create<vector::TransferReadOp>(loc, rhsType, rhsShaped,
1562                                                        ValueRange{zero, zero});
1563     // Read res slice of size {n, w, c} @ [0, 0, 0].
1564     Value res = builder.create<vector::TransferReadOp>(
1565         loc, resType, resShaped, ValueRange{zero, zero, zero});
1566 
1567     //===------------------------------------------------------------------===//
1568     // Begin vector-only rewrite part
1569     //===------------------------------------------------------------------===//
1570     // Unroll along kw and read slices of lhs and rhs.
1571     SmallVector<Value> lhsVals, rhsVals, resVals;
1572     // Extract lhs slice of size {n, wSizeStep, c}
1573     //   @ [0, sw * w + dw * kw, 0].
1574     for (int64_t kw = 0; kw < kwSize; ++kw) {
1575       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1576         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1577             loc, lhs,
1578             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1579             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1580             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1581       }
1582     }
1583     // Extract rhs slice of size {c} @ [kw].
1584     for (int64_t kw = 0; kw < kwSize; ++kw) {
1585       rhsVals.push_back(builder.create<vector::ExtractOp>(
1586           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1587     }
1588     // Extract res slice: {n, wSizeStep, c} @ [0, w, 0].
1589     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1590       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1591           loc, res,
1592           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1593           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1594           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1595     }
1596 
1597     auto linearIndex = [&](int64_t kw, int64_t w) {
1598       return kw * (wSize / wSizeStep) + w;
1599     };
1600 
1601     // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c}
1602     for (int64_t kw = 0; kw < kwSize; ++kw) {
1603       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1604         resVals[w] = depthwiseConv1dSliceAsFma(
1605             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1606       }
1607     }
1608 
1609     // Write back res slice: {n, wSizeStep, c} @ [0, w, 0].
1610     // This does not depend on kw.
1611     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1612       res = builder.create<vector::InsertStridedSliceOp>(
1613           loc, resVals[w], res,
1614           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1615           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1616     }
1617     //===------------------------------------------------------------------===//
1618     // End vector-only rewrite part
1619     //===------------------------------------------------------------------===//
1620 
1621     // Write back res slice of size {n, w, c} @ [0, 0, 0].
1622     return builder
1623         .create<vector::TransferWriteOp>(loc, res, resShaped,
1624                                          ValueRange{zero, zero, zero})
1625         .getOperation();
1626   }
1627 
1628   /// Lower lhs{n, w, c} * rhs{c} -> res{n, w, c} to fma.
1629   Value depthwiseConv1dSliceAsFma(OpBuilder &b, Location loc, Value lhs,
1630                                   Value rhs, Value res) {
1631     Value bcast = builder.create<vector::BroadcastOp>(loc, res.getType(), rhs);
1632     return b.create<vector::FMAOp>(loc, lhs, bcast, res);
1633   }
1634 
1635   /// Entry point that transposes into the common form:
1636   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1637   FailureOr<Operation *> generateConv() {
1638     AffineExpr n, w, f, kw, c;
1639     bindDims(ctx, n, w, f, kw, c);
1640     if (!iters({Par(), Par(), Par(), Red(), Red()}))
1641       return failure();
1642 
1643     // No transposition needed.
1644     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1645                 /*rhsIndex*/ {kw, c, f},
1646                 /*resIndex*/ {n, w, f}}))
1647       return conv();
1648     return failure();
1649   }
1650 
1651   /// Entry point that transposes into the common form:
1652   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1653   FailureOr<Operation *> generateDilatedConv() {
1654     AffineExpr n, w, c, kw;
1655     bindDims(ctx, n, w, c, kw);
1656     if (!iters({Par(), Par(), Par(), Red()}))
1657       return failure();
1658 
1659     // No transposition needed.
1660     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1661                 /*rhsIndex*/ {kw, c},
1662                 /*resIndex*/ {n, w, c}}))
1663       return depthwiseConv();
1664     return failure();
1665   }
1666 
1667 private:
1668   bool valid = false;
1669   int strideW, dilationW;
1670   Value lhsShaped, rhsShaped, resShaped;
1671   ShapedType lhsShapedType, rhsShapedType, resShapedType;
1672 };
1673 } // namespace
1674 
1675 /// Helper function to vectorize a LinalgOp with convolution semantics.
1676 // TODO: extend the generic vectorization to support windows and drop this.
1677 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, LinalgOp op) {
1678   // The ConvolutionOpInterface gives us guarantees of existence for
1679   // strides/dilations. However, we do not need to rely on those, we can simply
1680   // use them if present, otherwise use the default and let the generic conv.
1681   // matcher in the ConvGenerator succeed or fail.
1682   auto strides = op->getAttrOfType<DenseIntElementsAttr>("strides");
1683   auto dilations = op->getAttrOfType<DenseIntElementsAttr>("dilations");
1684   auto stride = strides ? *strides.getValues<uint64_t>().begin() : 1;
1685   auto dilation = dilations ? *dilations.getValues<uint64_t>().begin() : 1;
1686   Conv1DNwcGenerator e(b, op, stride, dilation);
1687   auto res = e.generateConv();
1688   if (succeeded(res))
1689     return res;
1690   return e.generateDilatedConv();
1691 }
1692 
1693 struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> {
1694   using OpInterfaceRewritePattern::OpInterfaceRewritePattern;
1695 
1696   LogicalResult matchAndRewrite(LinalgOp op,
1697                                 PatternRewriter &rewriter) const override {
1698     FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op);
1699     if (failed(resultOrFail))
1700       return failure();
1701     Operation *newOp = *resultOrFail;
1702     if (newOp->getNumResults() == 0) {
1703       rewriter.eraseOp(op.getOperation());
1704       return success();
1705     }
1706     assert(newOp->getNumResults() == 1 && "expected single result");
1707     rewriter.replaceOp(op.getOperation(), newOp->getResult(0));
1708     return success();
1709   }
1710 };
1711 
1712 void mlir::linalg::populateConvolutionVectorizationPatterns(
1713     RewritePatternSet &patterns, PatternBenefit benefit) {
1714   patterns.add<VectorizeConvolution>(patterns.getContext(), benefit);
1715 }
1716