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