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   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
483 }
484 
485 /// Generic vectorization function that rewrites the body of a `linalgOp` into
486 /// vector form. Generic vectorization proceeds as follows:
487 ///   1. Verify the `linalgOp` has one non-empty region.
488 ///   2. Values defined above the region are mapped to themselves and will be
489 ///   broadcasted on a per-need basis by their consumers.
490 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
491 ///   load).
492 ///   TODO: Reuse opportunities for RAR dependencies.
493 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
494 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
495 ///   indices.
496 ///   5. Iteratively call vectorizeOneOp on the region operations.
497 ///
498 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
499 /// performed to the maximal common vector size implied by the `linalgOp`
500 /// iteration space. This eager broadcasting is introduced in the
501 /// permutation_map of the vector.transfer_read operations. The eager
502 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
503 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
504 /// the absence of good canonicalizations, the amount of work increases.
505 /// This is not deemed a problem as we expect canonicalizations and foldings to
506 /// aggressively clean up the useless work.
507 LogicalResult vectorizeAsLinalgGeneric(
508     OpBuilder &b, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults,
509     bool broadcastToMaximalCommonShape = false,
510     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
511   Block *block = linalgOp.getBlock();
512 
513   // 2. Values defined above the region can only be broadcast for now. Make them
514   // map to themselves.
515   BlockAndValueMapping bvm;
516   SetVector<Value> valuesSet;
517   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
518   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
519 
520   if (linalgOp.getNumOutputs() == 0)
521     return failure();
522 
523   // TODO: the common vector shape is equal to the static loop sizes only when
524   // all indexing maps are projected permutations. For convs and stencils the
525   // logic will need to evolve.
526   SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes();
527 
528   // 3. Turn all BBArgs into vector.transfer_read / load.
529   SmallVector<AffineMap> indexings;
530   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
531     BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber());
532     if (linalgOp.isScalar(opOperand)) {
533       bvm.map(bbarg, opOperand->get());
534       continue;
535     }
536     // TODO: 0-d vectors.
537     Type readType;
538     AffineMap map;
539     if (linalgOp.getShape(opOperand).empty()) {
540       readType = bbarg.getType();
541     } else {
542       if (broadcastToMaximalCommonShape) {
543         map = inverseAndBroadcastProjectedPermuation(
544             linalgOp.getTiedIndexingMap(opOperand));
545         readType = VectorType::get(commonVectorShape,
546                                    getElementTypeOrSelf(opOperand->get()));
547       } else {
548         map = inversePermutation(
549             reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
550         readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
551                                    getElementTypeOrSelf(opOperand->get()));
552       }
553     }
554     Value readValue = buildVectorRead(b, opOperand->get(), readType, map);
555     LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue);
556     bvm.map(bbarg, readValue);
557     bvm.map(opOperand->get(), readValue);
558   }
559 
560   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
561   // 4a. Register CustomVectorizationHook for yieldOp.
562   CustomVectorizationHook vectorizeYield =
563       [&](Operation *op,
564           const BlockAndValueMapping &bvm) -> VectorizationResult {
565     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
566   };
567   hooks.push_back(vectorizeYield);
568 
569   // 4b. Register CustomVectorizationHook for indexOp.
570   CustomVectorizationHook vectorizeIndex =
571       [&](Operation *op,
572           const BlockAndValueMapping &bvm) -> VectorizationResult {
573     return vectorizeLinalgIndex(b, op, linalgOp);
574   };
575   hooks.push_back(vectorizeIndex);
576 
577   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
578   for (Operation &op : block->getOperations()) {
579     VectorizationResult result = vectorizeOneOp(b, &op, bvm, hooks);
580     if (result.status == VectorizationStatus::Failure) {
581       LDBG("failed to vectorize: " << op);
582       return failure();
583     }
584     if (result.status == VectorizationStatus::NewOp) {
585       LDBG("new vector op: " << *result.newOp;);
586       bvm.map(op.getResults(), result.newOp->getResults());
587     }
588   }
589 
590   return success();
591 }
592 
593 static LogicalResult vectorizeContraction(OpBuilder &b, LinalgOp linalgOp,
594                                           SmallVectorImpl<Value> &newResults) {
595   assert(isaContractionOpInterface(linalgOp) &&
596          "expected vectorizeContraction preconditions to be met");
597   Location loc = linalgOp.getLoc();
598   // Vectorize other ops as vector contraction.
599   // TODO: interface.
600   LDBG(""
601            << "Rewrite linalg op as vector.contract: ";
602        linalgOp.dump());
603   // Special function that describes how to vectorize the multiplication op in a
604   // linalg contraction.
605   CustomVectorizationHook vectorizeContraction =
606       [&](Operation *op,
607           const BlockAndValueMapping &bvm) -> VectorizationResult {
608     if (!isa<arith::MulIOp, arith::MulFOp>(op))
609       return VectorizationResult{VectorizationStatus::Failure, nullptr};
610     ArrayRef<int64_t> outShape =
611         linalgOp.getShape(linalgOp.getOutputOperand(0));
612     Type vType;
613     if (outShape.empty()) {
614       vType = op->getResult(0).getType();
615     } else {
616       SmallVector<int64_t> resultShape = applyPermutationMap(
617           inversePermutation(reindexIndexingMap(
618               linalgOp.getTiedIndexingMap(linalgOp.getOutputOperand(0)))),
619           outShape);
620       vType = VectorType::get(resultShape, op->getResult(0).getType());
621     }
622     auto zero = b.create<arith::ConstantOp>(loc, vType, b.getZeroAttr(vType));
623     // Indexing maps at the time of vector.transfer_read are adjusted to order
624     // vector dimensions in the same order as the canonical linalg op iteration
625     // space order.
626     // The indexings for the contraction therefore need to be adjusted.
627     // TODO: consider dropping contraction special casing altogether, this will
628     // require more advanced canonicalizations involving vector.multi_reduction
629     // that are not yet available.
630     SmallVector<AffineMap> indexingMaps;
631     indexingMaps.reserve(linalgOp.getNumInputsAndOutputs());
632     llvm::transform(linalgOp.getIndexingMaps(),
633                     std::back_inserter(indexingMaps),
634                     [](AffineMap indexingMap) {
635                       return inversePermutation(reindexIndexingMap(indexingMap))
636                           .compose(indexingMap);
637                     });
638     Operation *contract = b.create<vector::ContractionOp>(
639         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
640         b.getAffineMapArrayAttr(indexingMaps), linalgOp.iterator_types());
641     return VectorizationResult{VectorizationStatus::NewOp, contract};
642   };
643   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
644                                   /*broadcastToMaximalCommonShape=*/false,
645                                   {vectorizeContraction});
646 }
647 
648 static bool allIndexingsAreProjectedPermutation(LinalgOp op) {
649   return llvm::all_of(op.getIndexingMaps(), [](AffineMap m) {
650     return m.isProjectedPermutation(/*allowZerosInResults=*/true);
651   });
652 }
653 
654 // TODO: probably need some extra checks for reduction followed by consumer
655 // ops that may not commute (e.g. linear reduction + non-linear instructions).
656 static LogicalResult reductionPreconditions(LinalgOp op) {
657   if (llvm::none_of(op.iterator_types(), isReductionIterator)) {
658     LDBG("reduction precondition failed: no reduction iterator");
659     return failure();
660   }
661   for (OpOperand *opOperand : op.getOutputOperands()) {
662     Operation *reduceOp = matchLinalgReduction(opOperand);
663     if (!reduceOp || !getKindForOp(reduceOp)) {
664       LDBG("reduction precondition failed: reduction detection failed");
665       return failure();
666     }
667   }
668   return success();
669 }
670 
671 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
672   auto linalgOp = cast<linalg::LinalgOp>(op);
673   // All types must be static shape to go to vector.
674   if (linalgOp.hasDynamicShape()) {
675     LDBG("precondition failed: dynamic shape");
676     return failure();
677   }
678   if (isElementwise(op))
679     return success();
680   if (isaContractionOpInterface(linalgOp))
681     return success();
682   // TODO: the common vector shape is equal to the static loop sizes only when
683   // all indexing maps are projected permutations. For convs and stencils the
684   // logic will need to evolve.
685   if (!allIndexingsAreProjectedPermutation(linalgOp)) {
686     LDBG("precondition failed: not projected permutations");
687     return failure();
688   }
689   if (failed(reductionPreconditions(linalgOp))) {
690     LDBG("precondition failed: reduction preconditions");
691     return failure();
692   }
693   return success();
694 }
695 
696 LogicalResult
697 mlir::linalg::vectorizeLinalgOp(OpBuilder &b, Operation *op,
698                                 SmallVectorImpl<Value> &newResults) {
699   if (failed(vectorizeLinalgOpPrecondition(op)))
700     return failure();
701 
702   auto linalgOp = cast<LinalgOp>(op);
703   if (isaContractionOpInterface(linalgOp))
704     return vectorizeContraction(b, linalgOp, newResults);
705 
706   LDBG(""
707        << "Vectorize linalg op as a generic by broadcasting to "
708           "maximal common shape: "
709        << *op);
710   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
711                                   /*broadcastToMaximalCommonShape=*/true);
712 }
713 
714 //----------------------------------------------------------------------------//
715 // Misc. vectorization patterns.
716 //----------------------------------------------------------------------------//
717 
718 /// Helper function that retrieves the value of an IntegerAttr.
719 static int64_t getIntFromAttr(Attribute attr) {
720   return attr.cast<IntegerAttr>().getInt();
721 }
722 
723 /// Given an ArrayRef of OpFoldResults, return a vector of Values. IntegerAttrs
724 /// are converted to ConstantIndexOps. Other attribute types are not supported.
725 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
726                                            ArrayRef<OpFoldResult> ofrs) {
727   SmallVector<Value> result;
728   llvm::for_each(ofrs, [&](auto o) {
729     if (auto val = o.template dyn_cast<Value>()) {
730       result.push_back(val);
731     } else {
732       result.push_back(builder.create<arith::ConstantIndexOp>(
733           loc, getIntFromAttr(o.template get<Attribute>())));
734     }
735   });
736   return result;
737 }
738 
739 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp and
740 /// InsertSliceOp. For now, only constant padding values are supported.
741 /// If there is enough static type information, TransferReadOps and
742 /// TransferWriteOps may be generated instead of InsertSliceOps.
743 struct GenericPadTensorOpVectorizationPattern
744     : public GeneralizePadTensorOpPattern {
745   GenericPadTensorOpVectorizationPattern(MLIRContext *context,
746                                          PatternBenefit benefit = 1)
747       : GeneralizePadTensorOpPattern(context, tryVectorizeCopy, benefit) {}
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   static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter,
752                                         PadTensorOp padOp, Value dest) {
753     auto sourceType = padOp.getSourceType();
754     auto resultType = padOp.getResultType();
755 
756     // Copy cannot be vectorized if pad value is non-constant and source shape
757     // is dynamic. In case of a dynamic source shape, padding must be appended
758     // by TransferReadOp, but TransferReadOp supports only constant padding.
759     auto padValue = padOp.getConstantPaddingValue();
760     if (!padValue) {
761       if (!sourceType.hasStaticShape())
762         return failure();
763       // Create dummy padding value.
764       auto elemType = sourceType.getElementType();
765       padValue = rewriter.create<arith::ConstantOp>(
766           padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType));
767     }
768 
769     SmallVector<int64_t> vecShape;
770     SmallVector<bool> readInBounds;
771     SmallVector<bool> writeInBounds;
772     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
773       if (!sourceType.isDynamicDim(i)) {
774         vecShape.push_back(sourceType.getDimSize(i));
775         // Source shape is statically known: Neither read nor write are out-of-
776         // bounds.
777         readInBounds.push_back(true);
778         writeInBounds.push_back(true);
779       } else if (!resultType.isDynamicDim(i)) {
780         // Source shape is not statically known, but result shape is. Vectorize
781         // with size of result shape. This may be larger than the source size.
782         vecShape.push_back(resultType.getDimSize(i));
783         // Read may be out-of-bounds because the result size could be larger
784         // than the source size.
785         readInBounds.push_back(false);
786         // Write is out-of-bounds if low padding > 0.
787         writeInBounds.push_back(
788             getConstantIntValue(padOp.getMixedLowPad()[i]) ==
789             static_cast<int64_t>(0));
790       } else {
791         // Neither source nor result dim of padOp is static. Cannot vectorize
792         // the copy.
793         return failure();
794       }
795     }
796     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
797 
798     // Generate TransferReadOp.
799     SmallVector<Value> readIndices(
800         vecType.getRank(),
801         rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
802     auto read = rewriter.create<vector::TransferReadOp>(
803         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
804         readInBounds);
805 
806     // If `dest` is a FillOp and the TransferWriteOp would overwrite the entire
807     // tensor, write directly to the FillOp's operand.
808     if (llvm::equal(vecShape, resultType.getShape()) &&
809         llvm::all_of(writeInBounds, [](bool b) { return b; }))
810       if (auto fill = dest.getDefiningOp<FillOp>())
811         dest = fill.output();
812 
813     // Generate TransferWriteOp.
814     auto writeIndices =
815         ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad());
816     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
817         padOp, read, dest, writeIndices, writeInBounds);
818 
819     return success();
820   }
821 };
822 
823 /// Base pattern for rewriting PadTensorOps whose result is consumed by a given
824 /// operation type OpTy.
825 template <typename OpTy>
826 struct VectorizePadTensorOpUserPattern : public OpRewritePattern<PadTensorOp> {
827   using OpRewritePattern<PadTensorOp>::OpRewritePattern;
828 
829   LogicalResult matchAndRewrite(PadTensorOp padOp,
830                                 PatternRewriter &rewriter) const final {
831     bool changed = false;
832     // Insert users in vector, because some users may be replaced/removed.
833     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
834       if (auto op = dyn_cast<OpTy>(user))
835         changed |= rewriteUser(rewriter, padOp, op).succeeded();
836     return success(changed);
837   }
838 
839 protected:
840   virtual LogicalResult rewriteUser(PatternRewriter &rewriter,
841                                     PadTensorOp padOp, OpTy op) const = 0;
842 };
843 
844 /// Rewrite use of PadTensorOp result in TransferReadOp. E.g.:
845 /// ```
846 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
847 /// %r = vector.transfer_read %0[%c0, %c0], %cst
848 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
849 /// ```
850 /// is rewritten to:
851 /// ```
852 /// %r = vector.transfer_read %src[%c0, %c0], %padding
853 ///     {in_bounds = [true, true]}
854 ///     : tensor<?x?xf32>, vector<17x5xf32>
855 /// ```
856 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
857 /// sure that the original padding value %cst was never used.
858 ///
859 /// This rewrite is possible if:
860 /// - `xferOp` has no out-of-bounds dims or mask.
861 /// - Low padding is static 0.
862 /// - Single, scalar padding value.
863 struct PadTensorOpVectorizationWithTransferReadPattern
864     : public VectorizePadTensorOpUserPattern<vector::TransferReadOp> {
865   using VectorizePadTensorOpUserPattern<
866       vector::TransferReadOp>::VectorizePadTensorOpUserPattern;
867 
868   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
869                             vector::TransferReadOp xferOp) const override {
870     // Low padding must be static 0.
871     if (!padOp.hasZeroLowPad())
872       return failure();
873     // Pad value must be a constant.
874     auto padValue = padOp.getConstantPaddingValue();
875     if (!padValue)
876       return failure();
877     // Padding value of existing `xferOp` is unused.
878     if (xferOp.hasOutOfBoundsDim() || xferOp.mask())
879       return failure();
880 
881     rewriter.updateRootInPlace(xferOp, [&]() {
882       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
883       xferOp->setAttr(xferOp.getInBoundsAttrName(),
884                       rewriter.getBoolArrayAttr(inBounds));
885       xferOp.sourceMutable().assign(padOp.source());
886       xferOp.paddingMutable().assign(padValue);
887     });
888 
889     return success();
890   }
891 };
892 
893 /// Rewrite use of PadTensorOp result in TransferWriteOp.
894 /// This pattern rewrites TransferWriteOps that write to a padded tensor value,
895 /// where the same amount of padding is immediately removed again after the
896 /// write. In such cases, the TransferWriteOp can write to the non-padded tensor
897 /// value and apply out-of-bounds masking. E.g.:
898 /// ```
899 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
900 ///     : tensor<...> to tensor<?x?xf32>
901 /// %1 = linalg.pad_tensor %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
902 /// %2 = vector.transfer_write %vec, %1[...]
903 ///     : vector<17x5xf32>, tensor<17x5xf32>
904 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
905 ///     : tensor<17x5xf32> to tensor<?x?xf32>
906 /// ```
907 /// is rewritten to:
908 /// ```
909 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
910 ///     : tensor<...> to tensor<?x?xf32>
911 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>, tensor<?x?xf32>
912 /// ```
913 /// Note: It is important that the ExtractSliceOp %r resizes the result of the
914 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an even
915 /// smaller size). Otherwise, %r's new (dynamic) dimensions would differ from
916 /// %r's old dimensions.
917 ///
918 /// This rewrite is possible if:
919 /// - Low padding is static 0.
920 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
921 ///   ExtractSliceOp trims the same amount of padding that was added beforehand.
922 /// - Single, scalar padding value.
923 struct PadTensorOpVectorizationWithTransferWritePattern
924     : public VectorizePadTensorOpUserPattern<vector::TransferWriteOp> {
925   using VectorizePadTensorOpUserPattern<
926       vector::TransferWriteOp>::VectorizePadTensorOpUserPattern;
927 
928   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
929                             vector::TransferWriteOp xferOp) const override {
930     // Low padding must be static 0.
931     if (!padOp.hasZeroLowPad())
932       return failure();
933     // Pad value must be a constant.
934     auto padValue = padOp.getConstantPaddingValue();
935     if (!padValue)
936       return failure();
937     // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
938     if (!xferOp->hasOneUse())
939       return failure();
940     auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
941     if (!trimPadding)
942       return failure();
943     // Only static zero offsets supported when trimming padding.
944     if (!trimPadding.hasZeroOffset())
945       return failure();
946     // trimPadding must remove the amount of padding that was added earlier.
947     if (!hasSameTensorSize(padOp.source(), trimPadding))
948       return failure();
949 
950     // Insert the new TransferWriteOp at position of the old TransferWriteOp.
951     rewriter.setInsertionPoint(xferOp);
952 
953     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
954     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
955         xferOp, padOp.source().getType(), xferOp.vector(), padOp.source(),
956         xferOp.indices(), xferOp.permutation_mapAttr(), xferOp.mask(),
957         rewriter.getBoolArrayAttr(inBounds));
958     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
959 
960     return success();
961   }
962 
963   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
964   /// i.e., same dimensions.
965   ///
966   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
967   /// dimensions, this function tries to infer the (static) tensor size by
968   /// looking at the defining op and utilizing op-specific knowledge.
969   ///
970   /// This is a conservative analysis. In case equal tensor sizes cannot be
971   /// proven statically, this analysis returns `false` even though the tensor
972   /// sizes may turn out to be equal at runtime.
973   bool hasSameTensorSize(Value beforePadding,
974                          tensor::ExtractSliceOp afterTrimming) const {
975     // If the input to PadTensorOp is a CastOp, try with with both CastOp result
976     // and CastOp operand.
977     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
978       if (hasSameTensorSize(castOp.source(), afterTrimming))
979         return true;
980 
981     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
982     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
983     // Only RankedTensorType supported.
984     if (!t1 || !t2)
985       return false;
986     // Rank of both values must be the same.
987     if (t1.getRank() != t2.getRank())
988       return false;
989 
990     // All static dimensions must be the same. Mixed cases (e.g., dimension
991     // static in `t1` but dynamic in `t2`) are not supported.
992     for (unsigned i = 0; i < t1.getRank(); ++i) {
993       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
994         return false;
995       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
996         return false;
997     }
998 
999     // Nothing more to check if all dimensions are static.
1000     if (t1.getNumDynamicDims() == 0)
1001       return true;
1002 
1003     // All dynamic sizes must be the same. The only supported case at the moment
1004     // is when `beforePadding` is an ExtractSliceOp (or a cast thereof).
1005 
1006     // Apart from CastOp, only ExtractSliceOp is supported.
1007     auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
1008     if (!beforeSlice)
1009       return false;
1010 
1011     assert(static_cast<size_t>(t1.getRank()) ==
1012            beforeSlice.getMixedSizes().size());
1013     assert(static_cast<size_t>(t2.getRank()) ==
1014            afterTrimming.getMixedSizes().size());
1015 
1016     for (unsigned i = 0; i < t1.getRank(); ++i) {
1017       // Skip static dimensions.
1018       if (!t1.isDynamicDim(i))
1019         continue;
1020       auto size1 = beforeSlice.getMixedSizes()[i];
1021       auto size2 = afterTrimming.getMixedSizes()[i];
1022 
1023       // Case 1: Same value or same constant int.
1024       if (isEqualConstantIntOrValue(size1, size2))
1025         continue;
1026 
1027       // Other cases: Take a deeper look at defining ops of values.
1028       auto v1 = size1.dyn_cast<Value>();
1029       auto v2 = size2.dyn_cast<Value>();
1030       if (!v1 || !v2)
1031         return false;
1032 
1033       // Case 2: Both values are identical AffineMinOps. (Should not happen if
1034       // CSE is run.)
1035       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
1036       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
1037       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() &&
1038           minOp1.operands() == minOp2.operands())
1039         continue;
1040 
1041       // Add additional cases as needed.
1042     }
1043 
1044     // All tests passed.
1045     return true;
1046   }
1047 };
1048 
1049 /// Rewrite use of PadTensorOp result in InsertSliceOp. E.g.:
1050 /// ```
1051 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
1052 /// %r = tensor.insert_slice %0
1053 ///     into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
1054 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
1055 /// ```
1056 /// is rewritten to:
1057 /// ```
1058 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
1059 ///     : tensor<?x?xf32>, vector<17x5xf32>
1060 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
1061 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
1062 /// ```
1063 ///
1064 /// This rewrite is possible if:
1065 /// - Low padding is static 0.
1066 /// - `padOp` result shape is static.
1067 /// - The entire padded tensor is inserted.
1068 ///   (Implies that sizes of `insertOp` are all static.)
1069 /// - Only unit strides in `insertOp`.
1070 /// - Single, scalar padding value.
1071 struct PadTensorOpVectorizationWithInsertSlicePattern
1072     : public VectorizePadTensorOpUserPattern<tensor::InsertSliceOp> {
1073   using VectorizePadTensorOpUserPattern<
1074       tensor::InsertSliceOp>::VectorizePadTensorOpUserPattern;
1075 
1076   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
1077                             tensor::InsertSliceOp insertOp) const override {
1078     // Low padding must be static 0.
1079     if (!padOp.hasZeroLowPad())
1080       return failure();
1081     // Only unit stride supported.
1082     if (!insertOp.hasUnitStride())
1083       return failure();
1084     // Pad value must be a constant.
1085     auto padValue = padOp.getConstantPaddingValue();
1086     if (!padValue)
1087       return failure();
1088     // Dynamic shapes not supported.
1089     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
1090       return failure();
1091 
1092     auto vecType = VectorType::get(padOp.getType().getShape(),
1093                                    padOp.getType().getElementType());
1094     unsigned vecRank = vecType.getRank();
1095     unsigned tensorRank = insertOp.getType().getRank();
1096 
1097     // Check if sizes match: Insert the entire tensor into most minor dims.
1098     // (No permutations allowed.)
1099     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1100     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1101     if (!llvm::all_of(
1102             llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
1103               return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
1104             }))
1105       return failure();
1106 
1107     // Insert the TransferReadOp and TransferWriteOp at the position of the
1108     // InsertSliceOp.
1109     rewriter.setInsertionPoint(insertOp);
1110 
1111     // Generate TransferReadOp: Read entire source tensor and add high padding.
1112     SmallVector<Value> readIndices(
1113         vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
1114     auto read = rewriter.create<vector::TransferReadOp>(
1115         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1116 
1117     // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
1118     // specified offsets. Write is fully in-bounds because a InsertSliceOp's
1119     // source must fit into the destination at the specified offsets.
1120     auto writeIndices =
1121         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1122     SmallVector<bool> inBounds(vecRank, true);
1123     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1124         insertOp, read, insertOp.dest(), writeIndices, inBounds);
1125 
1126     return success();
1127   }
1128 };
1129 
1130 void mlir::linalg::populatePadTensorOpVectorizationPatterns(
1131     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1132   patterns.add<GenericPadTensorOpVectorizationPattern>(patterns.getContext(),
1133                                                        baseBenefit);
1134   // Try these specialized patterns first before resorting to the generic one.
1135   patterns.add<PadTensorOpVectorizationWithTransferReadPattern,
1136                PadTensorOpVectorizationWithTransferWritePattern,
1137                PadTensorOpVectorizationWithInsertSlicePattern>(
1138       patterns.getContext(), baseBenefit.getBenefit() + 1);
1139 }
1140 
1141 // TODO: cleanup all the convolution vectorization patterns.
1142 template <class ConvOp, int N>
1143 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
1144     ConvOp op, PatternRewriter &rewriter) const {
1145   Location loc = op.getLoc();
1146   MLIRContext *context = op.getContext();
1147 
1148   OpOperand *input = op.getInputOperand(0);
1149   OpOperand *kernel = op.getInputOperand(1);
1150   OpOperand *output = op.getOutputOperand(0);
1151   ArrayRef<int64_t> inShape = op.getShape(input);
1152   ArrayRef<int64_t> kShape = op.getShape(kernel);
1153 
1154   if (llvm::any_of(inShape, ShapedType::isDynamic) ||
1155       llvm::any_of(kShape, ShapedType::isDynamic))
1156     return failure();
1157 
1158   SmallVector<AffineExpr, 4> mapping;
1159   SmallVector<int64_t, 4> vectorDims;
1160   // Fail to apply when the size of not vectorized dimension is not 1.
1161   for (unsigned i = 0; i < N; i++) {
1162     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
1163       return failure();
1164 
1165     if (mask[i] && inShape[i] != kShape[i])
1166       return failure();
1167 
1168     if (mask[i]) {
1169       mapping.push_back(getAffineDimExpr(i, context));
1170       vectorDims.push_back(inShape[i]);
1171     }
1172   }
1173 
1174   int64_t rank = op.getRank(input);
1175   int64_t numDims = mapping.size();
1176   Type elemType = getElementTypeOrSelf(input->get());
1177 
1178   auto map = AffineMap::get(rank, 0, mapping, context);
1179   SmallVector<Value, 4> zeros(rank,
1180                               rewriter.create<arith::ConstantIndexOp>(loc, 0));
1181   auto vecType = VectorType::get(vectorDims, elemType);
1182 
1183   auto inputVec = rewriter.create<vector::TransferReadOp>(
1184       loc, vecType, input->get(), zeros, map);
1185   auto kernelVec = rewriter.create<vector::TransferReadOp>(
1186       loc, vecType, kernel->get(), zeros, map);
1187 
1188   auto acc = rewriter.create<arith::ConstantOp>(loc, elemType,
1189                                                 rewriter.getZeroAttr(elemType));
1190 
1191   std::array<AffineMap, 3> indexingMaps{
1192       AffineMap::getMultiDimIdentityMap(numDims, context),
1193       AffineMap::getMultiDimIdentityMap(numDims, context),
1194       AffineMap::get(numDims, 0, {}, context)};
1195 
1196   std::vector<StringRef> iteratorTypes(numDims, "reduction");
1197 
1198   auto result = rewriter.create<vector::ContractionOp>(
1199       loc, inputVec, kernelVec, acc,
1200       rewriter.getAffineMapArrayAttr(indexingMaps),
1201       rewriter.getStrArrayAttr(iteratorTypes));
1202 
1203   rewriter.create<memref::StoreOp>(loc, result, output->get(),
1204                                    ValueRange(zeros));
1205   rewriter.eraseOp(op);
1206   return success();
1207 }
1208 
1209 /// Inserts tiling, promotion and vectorization pattern for ConvOp
1210 /// conversion into corresponding pattern lists.
1211 template <typename ConvOp, unsigned N>
1212 static void populateVectorizationPatterns(
1213     RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns,
1214     RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) {
1215   auto *context = tilingPatterns.getContext();
1216   if (tileSizes.size() < N)
1217     return;
1218 
1219   constexpr static StringRef kTiledMarker = "TILED";
1220   constexpr static StringRef kPromotedMarker = "PROMOTED";
1221   tilingPatterns.add<LinalgTilingPattern<ConvOp>>(
1222       context, LinalgTilingOptions().setTileSizes(tileSizes),
1223       LinalgTransformationFilter(ArrayRef<Identifier>{},
1224                                  Identifier::get(kTiledMarker, context)));
1225 
1226   promotionPatterns.add<LinalgPromotionPattern<ConvOp>>(
1227       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
1228       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
1229                                  Identifier::get(kPromotedMarker, context)));
1230 
1231   SmallVector<bool, 4> mask(N);
1232   int offset = tileSizes.size() - N;
1233   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
1234                  [](int64_t i) -> bool { return i > 1; });
1235 
1236   vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask);
1237 }
1238 
1239 void mlir::linalg::populateConvVectorizationPatterns(
1240     MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns,
1241     ArrayRef<int64_t> tileSizes) {
1242   RewritePatternSet tiling(context);
1243   RewritePatternSet promotion(context);
1244   RewritePatternSet vectorization(context);
1245   populateVectorizationPatterns<Conv1DOp, 1>(tiling, promotion, vectorization,
1246                                              tileSizes);
1247 
1248   populateVectorizationPatterns<Conv2DOp, 2>(tiling, promotion, vectorization,
1249                                              tileSizes);
1250 
1251   populateVectorizationPatterns<Conv3DOp, 3>(tiling, promotion, vectorization,
1252                                              tileSizes);
1253 
1254   populateVectorizationPatterns<Conv1DNwcWcfOp, 3>(tiling, promotion,
1255                                                    vectorization, tileSizes);
1256 
1257   populateVectorizationPatterns<Conv2DNhwcHwcfOp, 4>(tiling, promotion,
1258                                                      vectorization, tileSizes);
1259 
1260   populateVectorizationPatterns<Conv3DNdhwcDhwcfOp, 5>(
1261       tiling, promotion, vectorization, tileSizes);
1262 
1263   patterns.push_back(std::move(tiling));
1264   patterns.push_back(std::move(promotion));
1265   patterns.push_back(std::move(vectorization));
1266 }
1267 
1268 //----------------------------------------------------------------------------//
1269 // Forwarding patterns
1270 //----------------------------------------------------------------------------//
1271 
1272 /// Check whether there is any interleaved use of any `values` between `firstOp`
1273 /// and `secondOp`. Conservatively return `true` if any op or value is in a
1274 /// different block.
1275 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1276                                     ValueRange values) {
1277   if (firstOp->getBlock() != secondOp->getBlock() ||
1278       !firstOp->isBeforeInBlock(secondOp)) {
1279     LDBG("interleavedUses precondition failed, firstOp: "
1280          << *firstOp << ", second op: " << *secondOp);
1281     return true;
1282   }
1283   for (auto v : values) {
1284     for (auto &u : v.getUses()) {
1285       Operation *owner = u.getOwner();
1286       if (owner == firstOp || owner == secondOp)
1287         continue;
1288       // TODO: this is too conservative, use dominance info in the future.
1289       if (owner->getBlock() == firstOp->getBlock() &&
1290           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1291         continue;
1292       LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp
1293                                     << ", second op: " << *secondOp);
1294       return true;
1295     }
1296   }
1297   return false;
1298 }
1299 
1300 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
1301 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1302   memref::SubViewOp subViewOp;
1303   for (auto &u : v.getUses()) {
1304     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1305       if (subViewOp)
1306         return memref::SubViewOp();
1307       subViewOp = newSubViewOp;
1308     }
1309   }
1310   return subViewOp;
1311 }
1312 
1313 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1314 /// when available.
1315 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1316     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1317 
1318   // Transfer into `view`.
1319   Value viewOrAlloc = xferOp.source();
1320   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1321       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1322     return failure();
1323 
1324   LDBG(viewOrAlloc);
1325 
1326   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1327   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1328   if (!subViewOp)
1329     return failure();
1330   Value subView = subViewOp.getResult();
1331   LDBG("with subView " << subView);
1332 
1333   // Find the copy into `subView` without interleaved uses.
1334   CopyOp copyOp;
1335   for (auto &u : subView.getUses()) {
1336     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1337       assert(newCopyOp.output().getType().isa<MemRefType>());
1338       if (newCopyOp.output() != subView)
1339         continue;
1340       LDBG("copy candidate " << *newCopyOp);
1341       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1342         continue;
1343       copyOp = newCopyOp;
1344       break;
1345     }
1346   }
1347   if (!copyOp)
1348     return failure();
1349   LDBG("with copy " << *copyOp);
1350 
1351   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
1352   FillOp maybeFillOp;
1353   for (auto &u : viewOrAlloc.getUses()) {
1354     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1355       assert(newFillOp.output().getType().isa<MemRefType>());
1356       if (newFillOp.output() != viewOrAlloc)
1357         continue;
1358       LDBG("fill candidate " << *newFillOp);
1359       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1360         continue;
1361       maybeFillOp = newFillOp;
1362       break;
1363     }
1364   }
1365   // Ensure padding matches.
1366   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
1367     return failure();
1368   if (maybeFillOp)
1369     LDBG("with maybeFillOp " << *maybeFillOp);
1370 
1371   // `in` is the subview that linalg.copy reads. Replace it.
1372   Value in = copyOp.input();
1373 
1374   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1375   // The `masked` attribute is only valid on this padded buffer.
1376   // When forwarding to vector.transfer_read, the attribute must be reset
1377   // conservatively.
1378   Value res = rewriter.create<vector::TransferReadOp>(
1379       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
1380       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
1381 
1382   if (maybeFillOp)
1383     rewriter.eraseOp(maybeFillOp);
1384   rewriter.eraseOp(copyOp);
1385   rewriter.replaceOp(xferOp, res);
1386 
1387   return success();
1388 }
1389 
1390 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1391 /// when available.
1392 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1393     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1394   // Transfer into `viewOrAlloc`.
1395   Value viewOrAlloc = xferOp.source();
1396   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1397       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1398     return failure();
1399 
1400   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1401   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1402   if (!subViewOp)
1403     return failure();
1404   Value subView = subViewOp.getResult();
1405 
1406   // Find the copy from `subView` without interleaved uses.
1407   CopyOp copyOp;
1408   for (auto &u : subViewOp.getResult().getUses()) {
1409     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1410       if (newCopyOp.getInputOperand(0)->get() != subView)
1411         continue;
1412       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1413         continue;
1414       copyOp = newCopyOp;
1415       break;
1416     }
1417   }
1418   if (!copyOp)
1419     return failure();
1420 
1421   // `out` is the subview copied into that we replace.
1422   assert(copyOp.output().getType().isa<MemRefType>());
1423   Value out = copyOp.output();
1424 
1425   // Forward vector.transfer into copy.
1426   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1427   // The `masked` attribute is only valid on this padded buffer.
1428   // When forwarding to vector.transfer_write, the attribute must be reset
1429   // conservatively.
1430   rewriter.create<vector::TransferWriteOp>(
1431       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
1432       xferOp.permutation_map(), ArrayAttr());
1433 
1434   rewriter.eraseOp(copyOp);
1435   rewriter.eraseOp(xferOp);
1436 
1437   return success();
1438 }
1439