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/Linalg/Analysis/DependenceAnalysis.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
16 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
17 #include "mlir/Dialect/Linalg/Utils/Utils.h"
18 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
19 #include "mlir/Dialect/Vector/VectorOps.h"
20 #include "mlir/IR/AffineExpr.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Pass/Pass.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Transforms/RegionUtils.h"
26 #include "llvm/ADT/ScopeExit.h"
27 #include "llvm/ADT/Sequence.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/TypeSwitch.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <type_traits>
33 
34 using namespace mlir;
35 using namespace mlir::linalg;
36 
37 using llvm::dbgs;
38 
39 #define DEBUG_TYPE "linalg-vectorization"
40 
41 /// Return the unique instance of OpType in `block` if it is indeed unique.
42 /// Return null if none or more than 1 instances exist.
43 template <typename OpType>
44 static OpType getSingleOpOfType(Block &block) {
45   OpType res;
46   block.walk([&](OpType op) {
47     if (res) {
48       res = nullptr;
49       return WalkResult::interrupt();
50     }
51     res = op;
52     return WalkResult::advance();
53   });
54   return res;
55 }
56 
57 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a
58 /// projectedPermutation, compress the unused dimensions to serve as a
59 /// permutation_map for a vector transfer operation.
60 /// For example, given a linalg op such as:
61 ///
62 /// ```
63 ///   %0 = linalg.generic {
64 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>,
65 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)>
66 ///      }
67 ///     ins(%0 : tensor<2x3x4xf32>)
68 ///    outs(%1 : tensor<5x6xf32>)
69 /// ```
70 ///
71 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine
72 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second
73 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`.
74 static AffineMap reindexIndexingMap(AffineMap map) {
75   assert(map.isProjectedPermutation() && "expected projected permutation");
76   auto res = compressUnusedDims(map);
77   assert(res.getNumDims() == res.getNumResults() &&
78          "expected reindexed map with same number of dims and results");
79   return res;
80 }
81 
82 /// Helper data structure to represent the result of vectorization.
83 /// In certain specific cases, like terminators, we do not want to propagate/
84 enum VectorizationStatus {
85   /// Op failed to vectorize.
86   Failure = 0,
87   /// Op vectorized and custom function took care of replacement logic
88   NoReplace,
89   /// Op vectorized into a new Op whose results will replace original Op's
90   /// results.
91   NewOp
92   // TODO: support values if Op vectorized to Many-Ops whose results we need to
93   // aggregate for replacement.
94 };
95 struct VectorizationResult {
96   /// Return status from vectorizing the current op.
97   enum VectorizationStatus status = VectorizationStatus::Failure;
98   /// New vectorized operation to replace the current op.
99   /// Replacement behavior is specified by `status`.
100   Operation *newOp;
101 };
102 
103 /// Return a vector type of the same shape and element type as the (assumed)
104 /// ShapedType of `v`.
105 static VectorType extractVectorTypeFromShapedValue(Value v) {
106   auto st = v.getType().cast<ShapedType>();
107   if (st.isa<MemRefType>() && st.getShape().empty())
108     return VectorType();
109   return VectorType::get(st.getShape(), st.getElementType());
110 }
111 
112 /// Given an `outputOperand` of a LinalgOp, compute the intersection of the
113 /// forward slice starting from `outputOperand` and the backward slice
114 /// starting from the corresponding linalg.yield operand.
115 /// This intersection is assumed to have a single binary operation that is
116 /// the reduction operation. Multiple reduction operations would impose an
117 /// ordering between reduction dimensions and is currently unsupported in
118 /// Linalg. This limitation is motivated by the fact that e.g.
119 /// min(max(X)) != max(min(X))
120 // TODO: use in LinalgOp verification, there is a circular dependency atm.
121 static Operation *getSingleBinaryOpAssumedReduction(OpOperand *outputOperand) {
122   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
123   auto yieldOp = cast<YieldOp>(linalgOp->getRegion(0).front().getTerminator());
124   unsigned yieldNum =
125       outputOperand->getOperandNumber() - linalgOp.getNumInputs();
126   llvm::SetVector<Operation *> backwardSlice, forwardSlice;
127   BlockArgument bbArg = linalgOp->getRegion(0).front().getArgument(
128       outputOperand->getOperandNumber());
129   Value yieldVal = yieldOp->getOperand(yieldNum);
130   getBackwardSlice(yieldVal, &backwardSlice, [&](Operation *op) {
131     return op->getParentOp() == linalgOp;
132   });
133   backwardSlice.insert(yieldVal.getDefiningOp());
134   getForwardSlice(bbArg, &forwardSlice,
135                   [&](Operation *op) { return op->getParentOp() == linalgOp; });
136   // Search for the (assumed unique) elementwiseMappable op at the intersection
137   // of forward and backward slices.
138   Operation *reductionOp = nullptr;
139   for (Operation *op : llvm::reverse(backwardSlice)) {
140     if (!forwardSlice.contains(op))
141       continue;
142     if (OpTrait::hasElementwiseMappableTraits(op)) {
143       if (reductionOp) {
144         // Reduction detection fails: found more than 1 elementwise-mappable op.
145         return nullptr;
146       }
147       reductionOp = op;
148     }
149   }
150   // TODO: also assert no other subsequent ops break the reduction.
151   return reductionOp;
152 }
153 
154 /// If `value` of assumed VectorType has a shape different than `shape`, try to
155 /// build and return a new vector.broadcast to `shape`.
156 /// Otherwise, just return `value`.
157 // TODO: this is best effort atm and there is currently no guarantee of
158 // correctness for the broadcast semantics.
159 static Value broadcastIfNeeded(OpBuilder &b, Value value,
160                                ArrayRef<int64_t> shape) {
161   unsigned numDimsGtOne = std::count_if(shape.begin(), shape.end(),
162                                         [](int64_t val) { return val > 1; });
163   auto vecType = value.getType().dyn_cast<VectorType>();
164   if (shape.empty() ||
165       (vecType != nullptr &&
166        (vecType.getShape() == shape || vecType.getRank() > numDimsGtOne)))
167     return value;
168   auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType()
169                                                    : value.getType());
170   return b.create<vector::BroadcastOp>(b.getInsertionPoint()->getLoc(),
171                                        newVecType, value);
172 }
173 
174 static llvm::Optional<vector::CombiningKind>
175 getKindForOp(Operation *reductionOp) {
176   if (!reductionOp)
177     return llvm::None;
178   return llvm::TypeSwitch<Operation *, llvm::Optional<vector::CombiningKind>>(
179              reductionOp)
180       .Case<AddIOp, AddFOp>([&](auto op) {
181         return llvm::Optional<vector::CombiningKind>{
182             vector::CombiningKind::ADD};
183       })
184       .Default([&](auto op) { return llvm::None; });
185 }
186 
187 /// If value of assumed VectorType has a shape different than `shape`, build and
188 /// return a new vector.broadcast to `shape`.
189 /// Otherwise, just return value.
190 static Value reduceIfNeeded(OpBuilder &b, VectorType targetVectorType,
191                             Value value, OpOperand *outputOperand) {
192   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
193   assert(targetVectorType.getShape() == linalgOp.getShape(outputOperand));
194   auto vecType = value.getType().dyn_cast<VectorType>();
195   if (!vecType || vecType.getShape() == targetVectorType.getShape())
196     return value;
197   // At this point, we know we need to reduce. Detect the reduction operator.
198   // TODO: Use the generic reduction detection util.
199   Operation *reductionOp = getSingleBinaryOpAssumedReduction(outputOperand);
200   unsigned pos = 0;
201   MLIRContext *ctx = b.getContext();
202   SmallVector<AffineExpr> exprs;
203   for (auto s : linalgOp.iterator_types())
204     if (isParallelIterator(s))
205       exprs.push_back(getAffineDimExpr(pos++, ctx));
206   auto loc = value.getLoc();
207   // TODO: reuse common CombiningKing logic and support more than add.
208   auto maybeKind = getKindForOp(reductionOp);
209   assert(maybeKind && "Failed precondition: could not get reduction kind");
210   unsigned idx = 0;
211   SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false);
212   for (auto attr : linalgOp.iterator_types()) {
213     if (isReductionIteratorType(attr))
214       reductionMask[idx] = true;
215     ++idx;
216   }
217   return b.create<vector::MultiDimReductionOp>(loc, value, reductionMask,
218                                                *maybeKind);
219 }
220 
221 /// Build a vector.transfer_read from `source` at indices set to all `0`.
222 /// If source has rank zero, build an memref.load.
223 /// Return the produced value.
224 static Value buildVectorRead(OpBuilder &b, Value source, VectorType vectorType,
225                              AffineMap map) {
226   Location loc = source.getLoc();
227   auto shapedType = source.getType().cast<ShapedType>();
228   SmallVector<Value> indices(shapedType.getRank(),
229                              b.create<ConstantIndexOp>(loc, 0));
230   return b.create<vector::TransferReadOp>(loc, vectorType, source, indices,
231                                           map);
232 }
233 
234 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set
235 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp
236 /// currently being vectorized. If `dest` has null rank, build an memref.store.
237 /// Return the produced value or null if no value is produced.
238 static Value buildVectorWrite(OpBuilder &b, Value value,
239                               OpOperand *outputOperand) {
240   Operation *write;
241   Location loc = value.getLoc();
242   if (VectorType vectorType =
243           extractVectorTypeFromShapedValue(outputOperand->get())) {
244     auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
245     AffineMap map =
246         reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand));
247     SmallVector<Value> indices(linalgOp.getRank(outputOperand),
248                                b.create<ConstantIndexOp>(loc, 0));
249     value = broadcastIfNeeded(b, value, vectorType.getShape());
250     value = reduceIfNeeded(b, vectorType, value, outputOperand);
251     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
252                                               indices, map);
253   } else {
254     write = b.create<memref::StoreOp>(loc, value, outputOperand->get());
255   }
256   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write);
257   if (!write->getResults().empty())
258     return write->getResult(0);
259   return Value();
260 }
261 
262 // Custom vectorization function type. Produce a vector form of Operation*
263 // assuming all its vectorized operands are already in the BlockAndValueMapping.
264 // Return nullptr if the Operation cannot be vectorized.
265 using CustomVectorizationHook = std::function<VectorizationResult(
266     Operation *, const BlockAndValueMapping &)>;
267 
268 /// Helper function to vectorize the terminator of a `linalgOp`. New result
269 /// vector values are appended to `newResults`. Return
270 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
271 /// should not try to map produced operations and instead return the results
272 /// using the `newResults` vector making them available to the
273 /// vectorization algorithm for RAUW. This function is meant to be used as a
274 /// CustomVectorizationHook.
275 static VectorizationResult
276 vectorizeLinalgYield(OpBuilder &b, Operation *op,
277                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
278                      SmallVectorImpl<Value> &newResults) {
279   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
280   if (!yieldOp)
281     return VectorizationResult{VectorizationStatus::Failure, nullptr};
282   for (auto outputs : llvm::enumerate(yieldOp.values())) {
283     // TODO: Scan for an opportunity for reuse.
284     // TODO: use a map.
285     Value vectorValue = bvm.lookup(outputs.value());
286     Value newResult = buildVectorWrite(
287         b, vectorValue, linalgOp.getOutputOperand(outputs.index()));
288     if (newResult)
289       newResults.push_back(newResult);
290   }
291   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
292 }
293 
294 /// Helper function to vectorize the index operations of a `linalgOp`. Return
295 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it
296 /// should map the produced operations. This function is meant to be used as a
297 /// CustomVectorizationHook.
298 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op,
299                                                 LinalgOp linalgOp) {
300   IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
301   if (!indexOp)
302     return VectorizationResult{VectorizationStatus::Failure, nullptr};
303   auto loc = indexOp.getLoc();
304   // Compute the static loop sizes of the index op.
305   auto targetShape = linalgOp.computeStaticLoopSizes();
306   // Compute a one-dimensional index vector for the index op dimension.
307   SmallVector<int64_t> constantSeq =
308       llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()]));
309   ConstantOp constantOp =
310       b.create<ConstantOp>(loc, b.getIndexVectorAttr(constantSeq));
311   // Return the one-dimensional index vector if it lives in the trailing
312   // dimension of the iteration space since the vectorization algorithm in this
313   // case can handle the broadcast.
314   if (indexOp.dim() == targetShape.size() - 1)
315     return VectorizationResult{VectorizationStatus::NewOp, constantOp};
316   // Otherwise permute the targetShape to move the index dimension last,
317   // broadcast the one-dimensional index vector to the permuted shape, and
318   // finally transpose the broadcasted index vector to undo the permutation.
319   std::swap(targetShape[indexOp.dim()], targetShape.back());
320   auto broadCastOp = b.create<vector::BroadcastOp>(
321       loc, VectorType::get(targetShape, b.getIndexType()), constantOp);
322   SmallVector<int64_t> transposition =
323       llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
324   std::swap(transposition.back(), transposition[indexOp.dim()]);
325   auto transposeOp =
326       b.create<vector::TransposeOp>(loc, broadCastOp, transposition);
327   return VectorizationResult{VectorizationStatus::NewOp, transposeOp};
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, Operation *op, const BlockAndValueMapping &bvm,
351                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
352   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op);
353 
354   // 1. Try to apply any CustomVectorizationHook.
355   if (!customVectorizationHooks.empty()) {
356     for (auto &customFunc : customVectorizationHooks) {
357       VectorizationResult result = customFunc(op, bvm);
358       if (result.status == VectorizationStatus::Failure)
359         continue;
360       return result;
361     }
362   }
363 
364   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
365   // Clone so that the constant is not confined to the linalgOp block .
366   if (isa<ConstantOp>(op))
367     return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)};
368 
369   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
370   if (!OpTrait::hasElementwiseMappableTraits(op))
371     return VectorizationResult{VectorizationStatus::Failure, nullptr};
372 
373   // 4. Generic vectorization path for ElementwiseMappable ops.
374   //   a. first get the first max ranked shape.
375   SmallVector<int64_t, 4> firstMaxRankedShape;
376   for (Value operand : op->getOperands()) {
377     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
378     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
379       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
380   }
381   //   b. broadcast each op if needed.
382   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
383     return firstMaxRankedShape.empty()
384                ? bvm.lookup(v)
385                : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape);
386   });
387   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
388   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
389     return firstMaxRankedShape.empty()
390                ? t
391                : VectorType::get(firstMaxRankedShape, t);
392   });
393 
394   // Build and return the new op.
395   OperationState state(op->getLoc(), op->getName());
396   state.addAttributes(op->getAttrs());
397   state.addOperands(llvm::to_vector<4>(vectorizedOperands));
398   state.addTypes(llvm::to_vector<4>(returnTypes));
399   return VectorizationResult{VectorizationStatus::NewOp,
400                              b.createOperation(state)};
401 }
402 
403 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
404 static bool hasOnlyScalarElementwiseOp(Region &r) {
405   if (!llvm::hasSingleElement(r))
406     return false;
407   for (Operation &op : r.front()) {
408     if (!(isa<ConstantOp, linalg::YieldOp, linalg::IndexOp>(op) ||
409           OpTrait::hasElementwiseMappableTraits(&op)) ||
410         llvm::any_of(op.getResultTypes(),
411                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
412       return false;
413   }
414   return true;
415 }
416 
417 // Return true if the op is an element-wise linalg op.
418 static bool isElementwise(Operation *op) {
419   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
420   if (!linalgOp)
421     return false;
422   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
423     return false;
424   // TODO: relax the restrictions on indexing map.
425   for (OpOperand *opOperand : linalgOp.getOutputOperands()) {
426     if (!linalgOp.getTiedIndexingMap(opOperand).isIdentity())
427       return false;
428   }
429   if (linalgOp->getNumRegions() != 1)
430     return false;
431   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
432 }
433 
434 /// Generic vectorization function that rewrites the body of a `linalgOp` into
435 /// vector form. Generic vectorization proceeds as follows:
436 ///   1. Verify the `linalgOp` has one non-empty region.
437 ///   2. Values defined above the region are mapped to themselves and will be
438 ///   broadcasted on a per-need basis by their consumers.
439 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
440 ///   load).
441 ///   TODO: Reuse opportunities for RAR dependencies.
442 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
443 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
444 ///   indices.
445 ///   5. Iteratively call vectorizeOneOp on the region operations.
446 ///
447 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
448 /// performed to the maximal common vector size implied by the `linalgOp`
449 /// iteration space. This eager broadcasting is introduced in the
450 /// permutation_map of the vector.transfer_read operations. The eager
451 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
452 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
453 /// the absence of good canonicalizations, the amount of work increases.
454 /// This is not deemed a problem as we expect canonicalizations and foldings to
455 /// aggressively clean up the useless work.
456 LogicalResult vectorizeAsLinalgGeneric(
457     OpBuilder &b, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults,
458     bool broadcastToMaximalCommonShape = false,
459     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
460   // 1. Fail to vectorize if the operation does not have one non-empty region.
461   if (linalgOp->getNumRegions() != 1 || linalgOp->getRegion(0).empty())
462     return failure();
463   auto &block = linalgOp->getRegion(0).front();
464 
465   // 2. Values defined above the region can only be broadcast for now. Make them
466   // map to themselves.
467   BlockAndValueMapping bvm;
468   SetVector<Value> valuesSet;
469   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
470   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
471 
472   if (linalgOp.getNumOutputs() == 0)
473     return failure();
474 
475   // TODO: the common vector shape is equal to the static loop sizes only when
476   // all indexing maps are projected permutations. For convs and stencils the
477   // logic will need to evolve.
478   SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes();
479 
480   // 3. Turn all BBArgs into vector.transfer_read / load.
481   SmallVector<AffineMap> indexings;
482   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
483     BlockArgument bbarg = block.getArgument(opOperand->getOperandNumber());
484     if (linalgOp.isScalar(opOperand)) {
485       bvm.map(bbarg, opOperand->get());
486       continue;
487     }
488     // TODO: 0-d vectors.
489     if (linalgOp.getShape(opOperand).empty()) {
490       Value loaded =
491           b.create<memref::LoadOp>(linalgOp.getLoc(), opOperand->get());
492       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
493                         << bbarg.getArgNumber() << "): " << loaded);
494       bvm.map(bbarg, loaded);
495       bvm.map(opOperand->get(), loaded);
496       continue;
497     }
498     AffineMap map;
499     VectorType vectorType;
500     if (broadcastToMaximalCommonShape) {
501       map = inverseAndBroadcastProjectedPermuation(
502           linalgOp.getTiedIndexingMap(opOperand));
503       vectorType = VectorType::get(commonVectorShape,
504                                    getElementTypeOrSelf(opOperand->get()));
505     } else {
506       map = inversePermutation(
507           reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
508       vectorType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
509                                    getElementTypeOrSelf(opOperand->get()));
510     }
511     Value vectorRead = buildVectorRead(b, opOperand->get(), vectorType, map);
512     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
513                       << bbarg.getArgNumber() << "): " << vectorRead);
514     bvm.map(bbarg, vectorRead);
515     bvm.map(opOperand->get(), vectorRead);
516   }
517 
518   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
519   // 4a. Register CustomVectorizationHook for yieldOp.
520   CustomVectorizationHook vectorizeYield =
521       [&](Operation *op,
522           const BlockAndValueMapping &bvm) -> VectorizationResult {
523     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
524   };
525   hooks.push_back(vectorizeYield);
526 
527   // 4b. Register CustomVectorizationHook for indexOp.
528   CustomVectorizationHook vectorizeIndex =
529       [&](Operation *op,
530           const BlockAndValueMapping &bvm) -> VectorizationResult {
531     return vectorizeLinalgIndex(b, op, linalgOp);
532   };
533   hooks.push_back(vectorizeIndex);
534 
535   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
536   for (Operation &op : block.getOperations()) {
537     VectorizationResult result = vectorizeOneOp(b, &op, bvm, hooks);
538     if (result.status == VectorizationStatus::Failure) {
539       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
540       return failure();
541     }
542     if (result.status == VectorizationStatus::NewOp) {
543       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
544                         << *result.newOp;);
545       bvm.map(op.getResults(), result.newOp->getResults());
546     }
547   }
548 
549   return success();
550 }
551 
552 static LogicalResult vectorizeContraction(OpBuilder &b, LinalgOp linalgOp,
553                                           SmallVectorImpl<Value> &newResults) {
554   assert(isaContractionOpInterface(linalgOp) &&
555          "expected vectorizeContraction preconditions to be met");
556   Location loc = linalgOp.getLoc();
557   // Vectorize other ops as vector contraction.
558   // TODO: interface.
559   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
560                     << "Rewrite linalg op as vector.contract: ";
561              linalgOp.dump());
562   // Special function that describes how to vectorize the multiplication op in a
563   // linalg contraction.
564   CustomVectorizationHook vectorizeContraction =
565       [&](Operation *op,
566           const BlockAndValueMapping &bvm) -> VectorizationResult {
567     if (!isa<MulIOp, MulFOp>(op))
568       return VectorizationResult{VectorizationStatus::Failure, nullptr};
569     ArrayRef<int64_t> outShape =
570         linalgOp.getShape(linalgOp.getOutputOperand(0));
571     auto vType = outShape.empty()
572                      ? op->getResult(0).getType()
573                      : VectorType::get(outShape, op->getResult(0).getType());
574     auto zero = b.create<ConstantOp>(loc, vType, b.getZeroAttr(vType));
575     // Indexing maps at the time of vector.transfer_read are adjusted to order
576     // vector dimensions in the same order as the canonical linalg op iteration
577     // space order.
578     // The indexings for the contraction therefore need to be adjusted.
579     // TODO: consider dropping contraction special casing altogether, this will
580     // require more advanced canonicalizations involving vector.multi_reduction
581     // that are not yet available.
582     SmallVector<AffineMap> indexingMaps;
583     indexingMaps.reserve(linalgOp.getNumInputsAndOutputs());
584     llvm::transform(linalgOp.getIndexingMaps(),
585                     std::back_inserter(indexingMaps),
586                     [](AffineMap indexingMap) {
587                       return inversePermutation(reindexIndexingMap(indexingMap))
588                           .compose(indexingMap);
589                     });
590     Operation *contract = b.create<vector::ContractionOp>(
591         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
592         b.getAffineMapArrayAttr(indexingMaps), linalgOp.iterator_types());
593     return VectorizationResult{VectorizationStatus::NewOp, contract};
594   };
595   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
596                                   /*broadcastToMaximalCommonShape=*/false,
597                                   {vectorizeContraction});
598 }
599 
600 static bool allIndexingsAreProjectedPermutation(LinalgOp op) {
601   return llvm::all_of(op.getIndexingMaps(),
602                       [](AffineMap m) { return m.isProjectedPermutation(); });
603 }
604 
605 // TODO: probably need some extra checks for reduction followed by consumer
606 // ops that may not commute (e.g. linear reduction + non-linear instructions).
607 static LogicalResult reductionPreconditions(LinalgOp op) {
608   if (llvm::none_of(op.iterator_types(), isReductionIteratorType))
609     return failure();
610   for (OpOperand *opOperand : op.getOutputOperands()) {
611     Operation *reductionOp = getSingleBinaryOpAssumedReduction(opOperand);
612     if (!getKindForOp(reductionOp))
613       return failure();
614   }
615   return success();
616 }
617 
618 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
619   auto linalgOp = cast<linalg::LinalgOp>(op);
620   // All types must be static shape to go to vector.
621   if (linalgOp.hasDynamicShape())
622     return failure();
623   if (isElementwise(op))
624     return success();
625   if (isaContractionOpInterface(linalgOp))
626     return success();
627   // TODO: the common vector shape is equal to the static loop sizes only when
628   // all indexing maps are projected permutations. For convs and stencils the
629   // logic will need to evolve.
630   if (allIndexingsAreProjectedPermutation(linalgOp) &&
631       succeeded(reductionPreconditions(linalgOp)))
632     return success();
633   return failure();
634 }
635 
636 LogicalResult
637 mlir::linalg::vectorizeLinalgOp(OpBuilder &b, Operation *op,
638                                 SmallVectorImpl<Value> &newResults) {
639   if (failed(vectorizeLinalgOpPrecondition(op)))
640     return failure();
641 
642   auto linalgOp = cast<LinalgOp>(op);
643   if (isaContractionOpInterface(linalgOp))
644     return vectorizeContraction(b, linalgOp, newResults);
645 
646   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
647                     << "Vectorize linalg op as a generic by broadcasting to "
648                        "maximal common shape: "
649                     << *op);
650   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
651                                   /*broadcastToMaximalCommonShape=*/true);
652 }
653 
654 //----------------------------------------------------------------------------//
655 // Misc. vectorization patterns.
656 //----------------------------------------------------------------------------//
657 
658 /// Helper function that retrieves the value of an IntegerAttr.
659 static int64_t getIntFromAttr(Attribute attr) {
660   return attr.cast<IntegerAttr>().getInt();
661 }
662 
663 /// Given an ArrayRef of OpFoldResults, return a vector of Values. IntegerAttrs
664 /// are converted to ConstantIndexOps. Other attribute types are not supported.
665 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
666                                            ArrayRef<OpFoldResult> ofrs) {
667   SmallVector<Value> result;
668   llvm::for_each(ofrs, [&](auto o) {
669     if (auto val = o.template dyn_cast<Value>()) {
670       result.push_back(val);
671     } else {
672       result.push_back(builder.create<ConstantIndexOp>(
673           loc, getIntFromAttr(o.template get<Attribute>())));
674     }
675   });
676   return result;
677 }
678 
679 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp and
680 /// SubTensorInsertOp. For now, only constant padding values are supported.
681 /// If there is enough static type information, TransferReadOps and
682 /// TransferWriteOps may be generated instead of SubTensorInsertOps.
683 struct GenericPadTensorOpVectorizationPattern
684     : public OpRewritePattern<PadTensorOp> {
685   using OpRewritePattern<PadTensorOp>::OpRewritePattern;
686 
687   LogicalResult matchAndRewrite(PadTensorOp padOp,
688                                 PatternRewriter &rewriter) const final {
689     // Given an OpFoldResult, return an index-typed value.
690     auto getIdxValue = [&](OpFoldResult ofr) {
691       if (auto val = ofr.dyn_cast<Value>())
692         return val;
693       return rewriter.create<ConstantIndexOp>(
694           padOp.getLoc(), getIntFromAttr(ofr.get<Attribute>())).getResult();
695     };
696 
697     auto resultType = padOp.getResultType();
698     // Compute size of InitTensorOp. Any combination of static/dynamic is
699     // supported.
700     SmallVector<Value> dynSizes;
701     SmallVector<int64_t> staticSizes;
702     for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
703       if (resultType.isDynamicDim(dim)) {
704         auto srcSize = rewriter.createOrFold<memref::DimOp>(
705             padOp.getLoc(), padOp.source(), dim);
706         // Add low and high padding value.
707         auto plusLow = rewriter.createOrFold<AddIOp>(
708             padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
709         auto plusHigh = rewriter.createOrFold<AddIOp>(
710             padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
711         dynSizes.push_back(plusHigh);
712       }
713       staticSizes.push_back(resultType.getDimSize(dim));
714     }
715 
716     // Init tensor and fill it with padding.
717     Value init = rewriter.create<InitTensorOp>(
718         padOp.getLoc(), dynSizes, staticSizes, resultType.getElementType());
719     Value fill = tryVectorizeFill(rewriter, padOp, init, dynSizes);
720 
721     // Try vectorizing the copy of source.
722     if (tryVectorizeCopy(rewriter, padOp, fill).succeeded())
723       return success();
724 
725     // Neither source type nor PadTensorOp result type have static shape. Such
726     // PadTensorOps cannot be vectorized. Generate a SubTensorInsertOp instead
727     // for copying the PadOp source.
728 
729     auto sourceType = padOp.getSourceType();
730     // Compute size of source of PadTensorOp.
731     SmallVector<OpFoldResult> srcSizes;
732     for (unsigned dim = 0; dim < sourceType.getRank(); ++dim) {
733       if (sourceType.isDynamicDim(dim)) {
734         srcSizes.push_back(rewriter.createOrFold<memref::DimOp>(
735             padOp.getLoc(), padOp.source(), dim));
736       } else {
737         srcSizes.push_back(rewriter.getIndexAttr(sourceType.getDimSize(dim)));
738       }
739     }
740     // Strides of SubTensorInsertOp are all 1.
741     SmallVector<OpFoldResult> strides(sourceType.getRank(),
742                                       rewriter.getIndexAttr(1));
743     rewriter.replaceOpWithNewOp<SubTensorInsertOp>(
744         padOp, padOp.source(), fill, padOp.getMixedLowPad(), srcSizes, strides);
745 
746     return success();
747   }
748 
749   /// Vectorize the filling of `dest`. This is possible if the padOp is padding
750   /// with a constant value. Otherwise, generate a tensor::GenerateOp.
751   Value tryVectorizeFill(PatternRewriter &rewriter, PadTensorOp padOp,
752                          Value dest, const SmallVector<Value> &dynSizes) const {
753     // Fill can be vectorized if padValue is a constant. (If there is enough
754     // static type information, the FillOp will be vectorized by another
755     // pattern.)
756     auto padValue = padOp.getConstantPaddingValue();
757     if (padValue)
758       return rewriter.create<FillOp>(padOp.getLoc(), dest, padValue).result();
759 
760     // Fill could not be vectorized: Lower to tensor::GenerateOp with region.
761     auto generateOp = rewriter.create<tensor::GenerateOp>(
762         padOp.getLoc(), padOp.getResultType(), dynSizes);
763     // Copy region to new op.
764     BlockAndValueMapping bvm;
765     padOp.region().cloneInto(&generateOp.getRegion(), bvm);
766     // Rewrite linalg::YieldOp to tensor::YieldOp.
767     OpBuilder::InsertionGuard guard(rewriter);
768     auto yieldOp = dyn_cast<linalg::YieldOp>(
769         generateOp.getRegion().front().getTerminator());
770     assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator");
771     assert(yieldOp.values().size() == 1);
772     rewriter.setInsertionPoint(yieldOp);
773     rewriter.replaceOpWithNewOp<tensor::YieldOp>(yieldOp, yieldOp.values()[0]);
774     return generateOp;
775   }
776 
777   /// Vectorize the copying of a PadTensorOp's source. This is possible if each
778   /// dimension size is statically know in the source type or the result type
779   /// (or both).
780   LogicalResult tryVectorizeCopy(PatternRewriter &rewriter, PadTensorOp padOp,
781                                  Value dest) const {
782     auto sourceType = padOp.getSourceType();
783     auto resultType = padOp.getResultType();
784 
785     // Copy cannot be vectorized if pad value is non-constant and source shape
786     // is dynamic. In case of a dynamic source shape, padding must be appended
787     // by TransferReadOp, but TransferReadOp supports only constant padding.
788     auto padValue = padOp.getConstantPaddingValue();
789     if (!padValue) {
790       if (!sourceType.hasStaticShape()) return failure();
791       // Create dummy padding value.
792       auto elemType = sourceType.getElementType();
793       padValue = rewriter.create<ConstantOp>(padOp.getLoc(), elemType,
794                                              rewriter.getZeroAttr(elemType));
795     }
796 
797     SmallVector<int64_t> vecShape;
798     SmallVector<bool> readInBounds;
799     SmallVector<bool> writeInBounds;
800     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
801       if (!sourceType.isDynamicDim(i)) {
802         vecShape.push_back(sourceType.getDimSize(i));
803         // Source shape is statically known: Neither read nor write are out-of-
804         // bounds.
805         readInBounds.push_back(true);
806         writeInBounds.push_back(true);
807       } else if (!resultType.isDynamicDim(i)) {
808         // Source shape is not statically known, but result shape is. Vectorize
809         // with size of result shape. This may be larger than the source size.
810         vecShape.push_back(resultType.getDimSize(i));
811         // Read may be out-of-bounds because the result size could be larger
812         // than the source size.
813         readInBounds.push_back(false);
814         // Write is out-of-bounds if low padding > 0.
815         writeInBounds.push_back(
816             isEqualConstantIntOrValue(padOp.getMixedLowPad()[i],
817                                       rewriter.getIndexAttr(0)));
818       } else {
819         // Neither source nor result dim of padOp is static. Cannot vectorize
820         // the copy.
821         return failure();
822       }
823     }
824     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
825 
826     // Generate TransferReadOp.
827     SmallVector<Value> readIndices(
828         vecType.getRank(), rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
829     auto read = rewriter.create<vector::TransferReadOp>(
830         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
831         readInBounds);
832 
833     // Generate TransferWriteOp.
834     auto writeIndices = ofrToIndexValues(
835         rewriter, padOp.getLoc(), padOp.getMixedLowPad());
836     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
837         padOp, read, dest, writeIndices, writeInBounds);
838 
839     return success();
840   }
841 };
842 
843 /// Base pattern for rewriting PadTensorOps whose result is consumed by a given
844 /// operation type OpTy.
845 template <typename OpTy>
846 struct VectorizePadTensorOpUserPattern : public OpRewritePattern<PadTensorOp> {
847   using OpRewritePattern<PadTensorOp>::OpRewritePattern;
848 
849   LogicalResult matchAndRewrite(PadTensorOp padOp,
850                                 PatternRewriter &rewriter) const final {
851     bool changed = false;
852     // Insert users in vector, because some users may be replaced/removed.
853     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
854       if (auto op = dyn_cast<OpTy>(user))
855         changed |= rewriteUser(rewriter, padOp, op).succeeded();
856     return success(changed);
857   }
858 
859  protected:
860   virtual LogicalResult rewriteUser(
861       PatternRewriter &rewriter, PadTensorOp padOp, OpTy op) const = 0;
862 };
863 
864 /// Rewrite use of PadTensorOp result in TransferReadOp. E.g.:
865 /// ```
866 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
867 /// %r = vector.transfer_read %0[%c0, %c0], %cst
868 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
869 /// ```
870 /// is rewritten to:
871 /// ```
872 /// %r = vector.transfer_read %src[%c0, %c0], %padding
873 ///     {in_bounds = [true, true]}
874 ///     : tensor<?x?xf32>, vector<17x5xf32>
875 /// ```
876 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
877 /// sure that the original padding value %cst was never used.
878 ///
879 /// This rewrite is possible if:
880 /// - `xferOp` has no out-of-bounds dims or mask.
881 /// - Low padding is static 0.
882 /// - Single, scalar padding value.
883 struct PadTensorOpVectorizationWithTransferReadPattern
884     : public VectorizePadTensorOpUserPattern<vector::TransferReadOp> {
885   using VectorizePadTensorOpUserPattern<vector::TransferReadOp>
886       ::VectorizePadTensorOpUserPattern;
887 
888   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
889                             vector::TransferReadOp xferOp) const override {
890     // Low padding must be static 0.
891     if (!padOp.hasZeroLowPad()) return failure();
892     // Pad value must be a constant.
893     auto padValue = padOp.getConstantPaddingValue();
894     if (!padValue) return failure();
895     // Padding value of existing `xferOp` is unused.
896     if (xferOp.hasOutOfBoundsDim() || xferOp.mask()) return failure();
897 
898     rewriter.updateRootInPlace(xferOp, [&]() {
899       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
900       xferOp->setAttr(xferOp.getInBoundsAttrName(),
901                       rewriter.getBoolArrayAttr(inBounds));
902       xferOp.sourceMutable().assign(padOp.source());
903       xferOp.paddingMutable().assign(padValue);
904     });
905 
906     return success();
907   }
908 };
909 
910 /// Rewrite use of PadTensorOp result in TransferWriteOp.
911 /// This pattern rewrites TransferWriteOps that write to a padded tensor value,
912 /// where the same amount of padding is immediately removed again after the
913 /// write. In such cases, the TransferWriteOp can write to the non-padded tensor
914 /// value and apply out-of-bounds masking. E.g.:
915 /// ```
916 /// %0 = subtensor ...[...] [%s0, %s1] [1, 1] : tensor<...> to tensor<?x?xf32>
917 /// %1 = linalg.pad_tensor %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
918 /// %2 = vector.transfer_write %vec, %1[...]
919 ///     : vector<17x5xf32>, tensor<17x5xf32>
920 /// %r = subtensor %2[0, 0] [%s0, %s1] [1, 1]
921 ///     : tensor<17x5xf32> to tensor<?x?xf32>
922 /// ```
923 /// is rewritten to:
924 /// ```
925 /// %0 = subtensor ...[...] [%s0, %s1] [1, 1] : tensor<...> to tensor<?x?xf32>
926 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>, tensor<?x?xf32>
927 /// ```
928 /// Note: It is important that the SubTensorOp %r resizes the result of the
929 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an even
930 /// smaller size). Otherwise, %r's new (dynamic) dimensions would differ from
931 /// %r's old dimensions.
932 ///
933 /// This rewrite is possible if:
934 /// - Low padding is static 0.
935 /// - `xferOp` has exactly one use, which is a SubTensorOp. This SubTensorOp
936 ///   trims the same amount of padding that was added beforehand.
937 /// - Single, scalar padding value.
938 struct PadTensorOpVectorizationWithTransferWritePattern
939     : public VectorizePadTensorOpUserPattern<vector::TransferWriteOp> {
940   using VectorizePadTensorOpUserPattern<vector::TransferWriteOp>
941       ::VectorizePadTensorOpUserPattern;
942 
943   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
944                             vector::TransferWriteOp xferOp) const override {
945     // Low padding must be static 0.
946     if (!padOp.hasZeroLowPad()) return failure();
947     // Pad value must be a constant.
948     auto padValue = padOp.getConstantPaddingValue();
949     if (!padValue) return failure();
950     // TransferWriteOp result must be directly consumed by a SubTensorOp.
951     if (!xferOp->hasOneUse()) return failure();
952     auto trimPadding = dyn_cast<SubTensorOp>(*xferOp->user_begin());
953     if (!trimPadding) return failure();
954     // Only static zero offsets supported when trimming padding.
955     if (!trimPadding.hasZeroOffset()) return failure();
956     // trimPadding must remove the amount of padding that was added earlier.
957     if (!hasSameTensorSize(padOp.source(), trimPadding)) return failure();
958 
959     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
960     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
961         xferOp, padOp.source().getType(), xferOp.vector(), padOp.source(),
962         xferOp.indices(), xferOp.permutation_mapAttr(), xferOp.mask(),
963         rewriter.getBoolArrayAttr(inBounds));
964     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
965 
966     return success();
967   }
968 
969   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
970   /// i.e., same dimensions.
971   ///
972   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
973   /// dimensions, this function tries to infer the (static) tensor size by
974   /// looking at the defining op and utilizing op-specific knowledge.
975   ///
976   /// This is a conservative analysis. In case equal tensor sizes cannot be
977   /// proven statically, this analysis returns `false` even though the tensor
978   /// sizes may turn out to be equal at runtime.
979   bool hasSameTensorSize(Value beforePadding, SubTensorOp afterTrimming) const {
980     // If the input to PadTensorOp is a CastOp, try with with both CastOp result
981     // and CastOp operand.
982     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
983       if (hasSameTensorSize(castOp.source(), afterTrimming)) return true;
984 
985     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
986     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
987     // Only RankedTensorType supported.
988     if (!t1 || !t2) return false;
989     // Rank of both values must be the same.
990     if (t1.getRank() != t2.getRank()) return false;
991 
992     // All static dimensions must be the same. Mixed cases (e.g., dimension
993     // static in `t1` but dynamic in `t2`) are not supported.
994     for (unsigned i = 0; i < t1.getRank(); ++i) {
995       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
996         return false;
997       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
998         return false;
999     }
1000 
1001     // Nothing more to check if all dimensions are static.
1002     if (t1.getNumDynamicDims() == 0) return true;
1003 
1004     // All dynamic sizes must be the same. The only supported case at the moment
1005     // is when `beforePadding` is a SubTensorOp (or a cast thereof).
1006 
1007     // Apart from CastOp, only SubTensorOp is supported.
1008     auto beforeSubtensor = beforePadding.getDefiningOp<SubTensorOp>();
1009     if (!beforeSubtensor) return false;
1010 
1011     assert(static_cast<size_t>(t1.getRank())
1012            == beforeSubtensor.getMixedSizes().size());
1013     assert(static_cast<size_t>(t2.getRank())
1014            == afterTrimming.getMixedSizes().size());
1015 
1016     for (unsigned i = 0; i < t1.getRank(); ++i) {
1017       // Skip static dimensions.
1018       if (!t1.isDynamicDim(i)) continue;
1019       auto size1 = beforeSubtensor.getMixedSizes()[i];
1020       auto size2 = afterTrimming.getMixedSizes()[i];
1021 
1022       // Case 1: Same value or same constant int.
1023       if (isEqualConstantIntOrValue(size1, size2)) continue;
1024 
1025       // Other cases: Take a deeper look at defining ops of values.
1026       auto v1 = size1.dyn_cast<Value>();
1027       auto v2 = size2.dyn_cast<Value>();
1028       if (!v1 || !v2) return false;
1029 
1030       // Case 2: Both values are identical AffineMinOps. (Should not happen if
1031       // CSE is run.)
1032       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
1033       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
1034       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap()
1035           && minOp1.operands() == minOp2.operands()) continue;
1036 
1037       // Add additional cases as needed.
1038     }
1039 
1040     // All tests passed.
1041     return true;
1042   }
1043 };
1044 
1045 /// Rewrite use of PadTensorOp result in SubtensorInsertOp. E.g.:
1046 /// ```
1047 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
1048 /// %r = subtensor_insert %0 into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
1049 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
1050 /// ```
1051 /// is rewritten to:
1052 /// ```
1053 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
1054 ///     : tensor<?x?xf32>, vector<17x5xf32>
1055 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
1056 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
1057 /// ```
1058 ///
1059 /// This rewrite is possible if:
1060 /// - Low padding is static 0.
1061 /// - `padOp` result shape is static.
1062 /// - The entire padded tensor is inserted.
1063 ///   (Implies that sizes of `insertOp` are all static.)
1064 /// - Only unit strides in `insertOp`.
1065 /// - Single, scalar padding value.
1066 struct PadTensorOpVectorizationWithSubTensorInsertPattern
1067     : public VectorizePadTensorOpUserPattern<SubTensorInsertOp> {
1068   using VectorizePadTensorOpUserPattern<SubTensorInsertOp>
1069       ::VectorizePadTensorOpUserPattern;
1070 
1071   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
1072                             SubTensorInsertOp insertOp) const override {
1073     // Low padding must be static 0.
1074     if (!padOp.hasZeroLowPad()) return failure();
1075     // Only unit stride supported.
1076     if (!insertOp.hasUnitStride()) return failure();
1077     // Pad value must be a constant.
1078     auto padValue = padOp.getConstantPaddingValue();
1079     if (!padValue)
1080       return failure();
1081     // Dynamic shapes not supported.
1082     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
1083       return failure();
1084 
1085     auto vecType = VectorType::get(padOp.getType().getShape(),
1086                                    padOp.getType().getElementType());
1087     unsigned vecRank = vecType.getRank();
1088     unsigned tensorRank = insertOp.getType().getRank();
1089 
1090     // Check if sizes match: Insert the entire tensor into most minor dims.
1091     // (No permutations allowed.)
1092     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1093     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1094     if (!llvm::all_of(
1095             llvm::zip(insertOp.getMixedSizes(), expectedSizes),
1096             [](auto it) { return isEqualConstantInt(std::get<0>(it),
1097                                                     std::get<1>(it)); }))
1098       return failure();
1099 
1100     // Generate TransferReadOp: Read entire source tensor and add high padding.
1101     SmallVector<Value> readIndices(
1102         vecRank, rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
1103     auto read = rewriter.create<vector::TransferReadOp>(
1104         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1105 
1106     // Generate TransferWriteOp: Write to SubTensorInsertOp's dest tensor at
1107     // specified offsets. Write is fully in-bounds because a SubTensorInsertOp's
1108     // source must fit into the destination at the specified offsets.
1109     auto writeIndices =
1110         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1111     SmallVector<bool> inBounds(vecRank, true);
1112     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1113         insertOp, read, insertOp.dest(), writeIndices, inBounds);
1114 
1115     return success();
1116   }
1117 };
1118 
1119 void mlir::linalg::populatePadTensorOpVectorizationPatterns(
1120     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1121   patterns.add<GenericPadTensorOpVectorizationPattern>(
1122       patterns.getContext(), baseBenefit);
1123   // Try these specialized patterns first before resorting to the generic one.
1124   patterns.add<PadTensorOpVectorizationWithTransferReadPattern,
1125                PadTensorOpVectorizationWithTransferWritePattern,
1126                PadTensorOpVectorizationWithSubTensorInsertPattern>(
1127       patterns.getContext(), baseBenefit.getBenefit() + 1);
1128 }
1129 
1130 // TODO: cleanup all the convolution vectorization patterns.
1131 template <class ConvOp, int N>
1132 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
1133     ConvOp op, PatternRewriter &rewriter) const {
1134   Location loc = op.getLoc();
1135   MLIRContext *context = op.getContext();
1136 
1137   OpOperand *input = op.getInputOperand(0);
1138   OpOperand *kernel = op.getInputOperand(1);
1139   OpOperand *output = op.getOutputOperand(0);
1140   ArrayRef<int64_t> inShape = op.getShape(input);
1141   ArrayRef<int64_t> kShape = op.getShape(kernel);
1142 
1143   if (llvm::any_of(inShape, ShapedType::isDynamic) ||
1144       llvm::any_of(kShape, ShapedType::isDynamic))
1145     return failure();
1146 
1147   SmallVector<AffineExpr, 4> mapping;
1148   SmallVector<int64_t, 4> vectorDims;
1149   // Fail to apply when the size of not vectorized dimension is not 1.
1150   for (unsigned i = 0; i < N; i++) {
1151     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
1152       return failure();
1153 
1154     if (mask[i] && inShape[i] != kShape[i])
1155       return failure();
1156 
1157     if (mask[i]) {
1158       mapping.push_back(getAffineDimExpr(i, context));
1159       vectorDims.push_back(inShape[i]);
1160     }
1161   }
1162 
1163   int64_t rank = op.getRank(input);
1164   int64_t numDims = mapping.size();
1165   Type elemType = getElementTypeOrSelf(input->get());
1166 
1167   auto map = AffineMap::get(rank, 0, mapping, context);
1168   SmallVector<Value, 4> zeros(rank, rewriter.create<ConstantIndexOp>(loc, 0));
1169   auto vecType = VectorType::get(vectorDims, elemType);
1170 
1171   auto inputVec = rewriter.create<vector::TransferReadOp>(
1172       loc, vecType, input->get(), zeros, map);
1173   auto kernelVec = rewriter.create<vector::TransferReadOp>(
1174       loc, vecType, kernel->get(), zeros, map);
1175 
1176   auto acc = rewriter.create<ConstantOp>(loc, elemType,
1177                                          rewriter.getZeroAttr(elemType));
1178 
1179   std::array<AffineMap, 3> indexingMaps{
1180       AffineMap::getMultiDimIdentityMap(numDims, context),
1181       AffineMap::getMultiDimIdentityMap(numDims, context),
1182       AffineMap::get(numDims, 0, {}, context)};
1183 
1184   std::vector<StringRef> iteratorTypes(numDims, "reduction");
1185 
1186   auto result = rewriter.create<vector::ContractionOp>(
1187       loc, inputVec, kernelVec, acc,
1188       rewriter.getAffineMapArrayAttr(indexingMaps),
1189       rewriter.getStrArrayAttr(iteratorTypes));
1190 
1191   rewriter.create<memref::StoreOp>(loc, result, output->get(),
1192                                    ValueRange(zeros));
1193   rewriter.eraseOp(op);
1194   return success();
1195 }
1196 
1197 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>;
1198 
1199 /// Inserts tiling, promotion and vectorization pattern for ConvOp
1200 /// conversion into corresponding pattern lists.
1201 template <typename ConvOp, unsigned N>
1202 static void populateVectorizationPatterns(
1203     RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns,
1204     RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) {
1205   auto *context = tilingPatterns.getContext();
1206   if (tileSizes.size() < N)
1207     return;
1208 
1209   constexpr static StringRef kTiledMarker = "TILED";
1210   constexpr static StringRef kPromotedMarker = "PROMOTED";
1211   tilingPatterns.add<LinalgTilingPattern<ConvOp>>(
1212       context, LinalgTilingOptions().setTileSizes(tileSizes),
1213       LinalgTransformationFilter(ArrayRef<Identifier>{},
1214                                  Identifier::get(kTiledMarker, context)));
1215 
1216   promotionPatterns.add<LinalgPromotionPattern<ConvOp>>(
1217       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
1218       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
1219                                  Identifier::get(kPromotedMarker, context)));
1220 
1221   SmallVector<bool, 4> mask(N);
1222   int offset = tileSizes.size() - N;
1223   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
1224                  [](int64_t i) -> bool { return i > 1; });
1225 
1226   vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask);
1227 }
1228 
1229 void mlir::linalg::populateConvVectorizationPatterns(
1230     MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns,
1231     ArrayRef<int64_t> tileSizes) {
1232   RewritePatternSet tiling(context);
1233   RewritePatternSet promotion(context);
1234   RewritePatternSet vectorization(context);
1235   populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization,
1236                                             tileSizes);
1237 
1238   populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization,
1239                                               tileSizes);
1240   populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>(
1241       tiling, promotion, vectorization, tileSizes);
1242 
1243   populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization,
1244                                               tileSizes);
1245   populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>(
1246       tiling, promotion, vectorization, tileSizes);
1247 
1248   populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization,
1249                                              tileSizes);
1250 
1251   populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization,
1252                                                tileSizes);
1253   populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>(
1254       tiling, promotion, vectorization, tileSizes);
1255 
1256   populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization,
1257                                                tileSizes);
1258   populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>(
1259       tiling, promotion, vectorization, tileSizes);
1260 
1261   populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization,
1262                                               tileSizes);
1263 
1264   populateVectorizationPatterns<ConvNDHWCOp, 5>(tiling, promotion,
1265                                                 vectorization, tileSizes);
1266   populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>(
1267       tiling, promotion, vectorization, tileSizes);
1268 
1269   populateVectorizationPatterns<ConvNCDHWOp, 5>(tiling, promotion,
1270                                                 vectorization, tileSizes);
1271   populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>(
1272       tiling, promotion, vectorization, tileSizes);
1273 
1274   patterns.push_back(std::move(tiling));
1275   patterns.push_back(std::move(promotion));
1276   patterns.push_back(std::move(vectorization));
1277 }
1278 
1279 //----------------------------------------------------------------------------//
1280 // Forwarding patterns
1281 //----------------------------------------------------------------------------//
1282 
1283 /// Check whether there is any interleaved use of any `values` between `firstOp`
1284 /// and `secondOp`. Conservatively return `true` if any op or value is in a
1285 /// different block.
1286 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1287                                     ValueRange values) {
1288   if (firstOp->getBlock() != secondOp->getBlock() ||
1289       !firstOp->isBeforeInBlock(secondOp)) {
1290     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1291                             << "interleavedUses precondition failed, firstOp: "
1292                             << *firstOp << ", second op: " << *secondOp);
1293     return true;
1294   }
1295   for (auto v : values) {
1296     for (auto &u : v.getUses()) {
1297       Operation *owner = u.getOwner();
1298       if (owner == firstOp || owner == secondOp)
1299         continue;
1300       // TODO: this is too conservative, use dominance info in the future.
1301       if (owner->getBlock() == firstOp->getBlock() &&
1302           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1303         continue;
1304       LLVM_DEBUG(llvm::dbgs()
1305                  << "\n[" DEBUG_TYPE "]: "
1306                  << " found interleaved op " << *owner
1307                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
1308       return true;
1309     }
1310   }
1311   return false;
1312 }
1313 
1314 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
1315 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1316   memref::SubViewOp subViewOp;
1317   for (auto &u : v.getUses()) {
1318     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1319       if (subViewOp)
1320         return memref::SubViewOp();
1321       subViewOp = newSubViewOp;
1322     }
1323   }
1324   return subViewOp;
1325 }
1326 
1327 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1328 /// when available.
1329 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1330     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1331 
1332   // Transfer into `view`.
1333   Value viewOrAlloc = xferOp.source();
1334   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1335       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1336     return failure();
1337 
1338   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
1339 
1340   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1341   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1342   if (!subViewOp)
1343     return failure();
1344   Value subView = subViewOp.getResult();
1345   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1346                           << "with subView " << subView);
1347 
1348   // Find the copy into `subView` without interleaved uses.
1349   CopyOp copyOp;
1350   for (auto &u : subView.getUses()) {
1351     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1352       assert(newCopyOp.output().getType().isa<MemRefType>());
1353       if (newCopyOp.output() != subView)
1354         continue;
1355       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1356                               << "copy candidate " << *newCopyOp);
1357       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1358         continue;
1359       copyOp = newCopyOp;
1360       break;
1361     }
1362   }
1363   if (!copyOp)
1364     return failure();
1365   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1366                           << "with copy " << *copyOp);
1367 
1368   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
1369   FillOp maybeFillOp;
1370   for (auto &u : viewOrAlloc.getUses()) {
1371     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1372       assert(newFillOp.output().getType().isa<MemRefType>());
1373       if (newFillOp.output() != viewOrAlloc)
1374         continue;
1375       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1376                               << "fill candidate " << *newFillOp);
1377       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1378         continue;
1379       maybeFillOp = newFillOp;
1380       break;
1381     }
1382   }
1383   // Ensure padding matches.
1384   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
1385     return failure();
1386   if (maybeFillOp)
1387     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1388                             << "with maybeFillOp " << *maybeFillOp);
1389 
1390   // `in` is the subview that linalg.copy reads. Replace it.
1391   Value in = copyOp.input();
1392 
1393   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1394   // The `masked` attribute is only valid on this padded buffer.
1395   // When forwarding to vector.transfer_read, the attribute must be reset
1396   // conservatively.
1397   Value res = rewriter.create<vector::TransferReadOp>(
1398       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
1399       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
1400 
1401   if (maybeFillOp)
1402     rewriter.eraseOp(maybeFillOp);
1403   rewriter.eraseOp(copyOp);
1404   rewriter.replaceOp(xferOp, res);
1405 
1406   return success();
1407 }
1408 
1409 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1410 /// when available.
1411 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1412     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1413   // Transfer into `viewOrAlloc`.
1414   Value viewOrAlloc = xferOp.source();
1415   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1416       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1417     return failure();
1418 
1419   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1420   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1421   if (!subViewOp)
1422     return failure();
1423   Value subView = subViewOp.getResult();
1424 
1425   // Find the copy from `subView` without interleaved uses.
1426   CopyOp copyOp;
1427   for (auto &u : subViewOp.getResult().getUses()) {
1428     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1429       if (newCopyOp.getInputOperand(0)->get() != subView)
1430         continue;
1431       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1432         continue;
1433       copyOp = newCopyOp;
1434       break;
1435     }
1436   }
1437   if (!copyOp)
1438     return failure();
1439 
1440   // `out` is the subview copied into that we replace.
1441   assert(copyOp.output().getType().isa<MemRefType>());
1442   Value out = copyOp.output();
1443 
1444   // Forward vector.transfer into copy.
1445   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1446   // The `masked` attribute is only valid on this padded buffer.
1447   // When forwarding to vector.transfer_write, the attribute must be reset
1448   // conservatively.
1449   rewriter.create<vector::TransferWriteOp>(
1450       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
1451       xferOp.permutation_map(), ArrayAttr());
1452 
1453   rewriter.eraseOp(copyOp);
1454   rewriter.eraseOp(xferOp);
1455 
1456   return success();
1457 }
1458