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