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