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