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/Dialect/Linalg/Analysis/DependenceAnalysis.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16 #include "mlir/Dialect/Linalg/Utils/Utils.h"
17 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
18 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
19 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
20 #include "mlir/Dialect/Vector/VectorOps.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/Matchers.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Support/LLVM.h"
26 #include "mlir/Transforms/RegionUtils.h"
27 #include "llvm/ADT/ScopeExit.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <type_traits>
31 
32 using namespace mlir;
33 using namespace mlir::edsc;
34 using namespace mlir::edsc::intrinsics;
35 using namespace mlir::linalg;
36 
37 using llvm::dbgs;
38 
39 #define DEBUG_TYPE "linalg-vectorization"
40 
41 /// Return the unique instance of OpType in `block` if it is indeed unique.
42 /// Return null if none or more than 1 instances exist.
43 template <typename OpType> static OpType getSingleOpOfType(Block &block) {
44   OpType res;
45   block.walk([&](OpType op) {
46     if (res) {
47       res = nullptr;
48       return WalkResult::interrupt();
49     }
50     res = op;
51     return WalkResult::advance();
52   });
53   return res;
54 }
55 
56 /// Helper data structure to represent the result of vectorization.
57 /// In certain specific cases, like terminators, we do not want to propagate/
58 enum VectorizationStatus {
59   /// Op failed to vectorize.
60   Failure = 0,
61   /// Op vectorized and custom function took care of replacement logic
62   NoReplace,
63   /// Op vectorized into a new Op whose results will replace original Op's
64   /// results.
65   NewOp
66   // TODO: support values if Op vectorized to Many-Ops whose results we need to
67   // aggregate for replacement.
68 };
69 struct VectorizationResult {
70   /// Return status from vectorizing the current op.
71   enum VectorizationStatus status = VectorizationStatus::Failure;
72   /// New vectorized operation to replace the current op.
73   /// Replacement behavior is specified by `status`.
74   Operation *newOp;
75 };
76 
77 /// Return a vector type of the same shape and element type as the (assumed)
78 /// ShapedType of `v`.
79 static VectorType extractVectorTypeFromShapedValue(Value v) {
80   auto st = v.getType().cast<ShapedType>();
81   if (st.isa<MemRefType>() && st.getShape().empty())
82     return VectorType();
83   return VectorType::get(st.getShape(), st.getElementType());
84 }
85 
86 /// Build a vector.transfer_read from `source` at indices set to all `0`.
87 /// If source has rank zero, build an memref.load.
88 /// Return the produced value.
89 static Value buildVectorRead(OpBuilder &builder, Value source,
90                              VectorType vectorType, AffineMap map) {
91   edsc::ScopedContext scope(builder);
92   auto shapedType = source.getType().cast<ShapedType>();
93   if (vectorType) {
94     SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0));
95     if (map)
96       return vector_transfer_read(vectorType, source, indices, map);
97     return vector_transfer_read(vectorType, source, indices);
98   }
99   return memref_load(source);
100 }
101 
102 /// Build a vector.transfer_write of `value` into `dest` at indices set to all
103 /// `0`. If `dest` has null rank, build an memref.store.
104 /// Return the produced value or null if no value is produced.
105 static Value buildVectorWrite(OpBuilder &builder, Value value, Value dest) {
106   edsc::ScopedContext scope(builder);
107   Operation *write;
108   auto shapedType = dest.getType().cast<ShapedType>();
109   if (VectorType vectorType = extractVectorTypeFromShapedValue(dest)) {
110     SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0));
111     if (vectorType != value.getType())
112       value = vector_broadcast(vectorType, value);
113     write = vector_transfer_write(value, dest, indices);
114   } else {
115     write = memref_store(value, dest);
116   }
117   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write);
118   if (!write->getResults().empty())
119     return write->getResult(0);
120   return Value();
121 }
122 
123 /// If value of assumed VectorType has a shape different than `shape`, buil and
124 /// return a new vector.broadcast to `shape`.
125 /// Otherwise, just return value.
126 static Value broadcastIfNeeded(OpBuilder &builder, Value value,
127                                ArrayRef<int64_t> shape) {
128   auto vecType = value.getType().dyn_cast<VectorType>();
129   if (shape.empty() || (vecType != nullptr && vecType.getShape() == shape))
130     return value;
131   auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType()
132                                                    : value.getType());
133   return builder.create<vector::BroadcastOp>(
134       builder.getInsertionPoint()->getLoc(), newVecType, value);
135 }
136 
137 // Custom vectorization function type. Produce a vector form of Operation*
138 // assuming all its vectorized operands are already in the BlockAndValueMapping.
139 // Return nullptr if the Operation cannot be vectorized.
140 using CustomVectorizationHook = std::function<VectorizationResult(
141     Operation *, const BlockAndValueMapping &)>;
142 
143 /// Helper function to vectorize the terminator of a `linalgOp`. New result
144 /// vector values are appended to `newResults`. Return
145 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
146 /// should not try to map produced operations and instead return the results
147 /// using the `newResults` vector making them available to the
148 /// vectorization algorithm for RAUW. This function is meant to be used as a
149 /// CustomVectorizationHook.
150 static VectorizationResult
151 vectorizeLinalgYield(OpBuilder &builder, Operation *op,
152                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
153                      SmallVectorImpl<Value> &newResults) {
154   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
155   if (!yieldOp)
156     return VectorizationResult{VectorizationStatus::Failure, nullptr};
157   for (auto outputs : llvm::enumerate(yieldOp.values())) {
158     // TODO: Scan for an opportunity for reuse.
159     // TODO: use a map.
160     Value vectorValue = bvm.lookup(outputs.value());
161     Value newResult = buildVectorWrite(builder, vectorValue,
162                                        linalgOp.getOutput(outputs.index()));
163     if (newResult)
164       newResults.push_back(newResult);
165   }
166   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
167 }
168 
169 /// Helper function to vectorize the index operations of a `linalgOp`. Return
170 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it
171 /// should map the produced operations. This function is meant to be used as a
172 /// CustomVectorizationHook.
173 static VectorizationResult
174 vectorizeLinalgIndex(OpBuilder &builder, Operation *op, LinalgOp linalgOp) {
175   IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
176   if (!indexOp)
177     return VectorizationResult{VectorizationStatus::Failure, nullptr};
178   auto loc = indexOp.getLoc();
179   // Compute the static loop sizes of the index op.
180   auto targetShape = linalgOp.computeStaticLoopSizes();
181   // Compute a one-dimensional index vector for the index op dimension.
182   SmallVector<int64_t> constantSeq(
183       llvm::seq<int64_t>(0, targetShape[indexOp.dim()]));
184   ConstantOp constantOp =
185       builder.create<ConstantOp>(loc, builder.getIndexVectorAttr(constantSeq));
186   // Return the one-dimensional index vector if it lives in the trailing
187   // dimension of the iteration space since the vectorization algorithm in this
188   // case can handle the broadcast.
189   if (indexOp.dim() == targetShape.size() - 1)
190     return VectorizationResult{VectorizationStatus::NewOp, constantOp};
191   // Otherwise permute the targetShape to move the index dimension last,
192   // broadcast the one-dimensional index vector to the permuted shape, and
193   // finally transpose the broadcasted index vector to undo the permutation.
194   std::swap(targetShape[indexOp.dim()], targetShape.back());
195   auto broadCastOp = builder.create<vector::BroadcastOp>(
196       loc, VectorType::get(targetShape, builder.getIndexType()), constantOp);
197   SmallVector<int64_t> transposition(
198       llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
199   std::swap(transposition.back(), transposition[indexOp.dim()]);
200   auto transposeOp =
201       builder.create<vector::TransposeOp>(loc, broadCastOp, transposition);
202   return VectorizationResult{VectorizationStatus::NewOp, transposeOp};
203 }
204 
205 /// Generic vectorization for a single operation `op`, given already vectorized
206 /// operands carried by `bvm`. Vectorization occurs as follows:
207 ///   1. Try to apply any of the `customVectorizationHooks` and return its
208 ///   result on success.
209 ///   2. Clone any constant in the current scope without vectorization: each
210 ///   consumer of the constant will later determine the shape to which the
211 ///   constant needs to be broadcast to.
212 ///   3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
213 ///   of the `customVectorizationHooks` to cover such cases.
214 ///   4. Clone `op` in vector form to a vector of shape prescribed by the first
215 ///   operand of maximal rank. Other operands have smaller rank and are
216 ///   broadcast accordingly. It is assumed this broadcast is always legal,
217 ///   otherwise, it means one of the `customVectorizationHooks` is incorrect.
218 ///
219 /// This function assumes all operands of `op` have been vectorized and are in
220 /// the `bvm` mapping. As a consequence, this function is meant to be called on
221 /// a topologically-sorted list of ops.
222 /// This function does not update `bvm` but returns a VectorizationStatus that
223 /// instructs the caller what `bvm` update needs to occur.
224 static VectorizationResult
225 vectorizeOneOp(OpBuilder &builder, Operation *op,
226                const BlockAndValueMapping &bvm,
227                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
228   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op);
229 
230   // 1. Try to apply any CustomVectorizationHook.
231   if (!customVectorizationHooks.empty()) {
232     for (auto &customFunc : customVectorizationHooks) {
233       VectorizationResult result = customFunc(op, bvm);
234       if (result.status == VectorizationStatus::Failure)
235         continue;
236       return result;
237     }
238   }
239 
240   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
241   // Clone so that the constant is not confined to the linalgOp block .
242   if (isa<ConstantOp>(op))
243     return VectorizationResult{VectorizationStatus::NewOp, builder.clone(*op)};
244 
245   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
246   if (!OpTrait::hasElementwiseMappableTraits(op))
247     return VectorizationResult{VectorizationStatus::Failure, nullptr};
248 
249   // 4. Generic vectorization path for ElementwiseMappable ops.
250   //   a. first get the first max ranked shape.
251   SmallVector<int64_t, 4> firstMaxRankedShape;
252   for (Value operand : op->getOperands()) {
253     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
254     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
255       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
256   }
257   //   b. broadcast each op if needed.
258   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
259     return firstMaxRankedShape.empty()
260                ? bvm.lookup(v)
261                : broadcastIfNeeded(builder, bvm.lookup(v), firstMaxRankedShape);
262   });
263   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
264   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
265     return firstMaxRankedShape.empty()
266                ? t
267                : VectorType::get(firstMaxRankedShape, t);
268   });
269 
270   // Build and return the new op.
271   OperationState state(op->getLoc(), op->getName());
272   state.addAttributes(op->getAttrs());
273   state.addOperands(llvm::to_vector<4>(vectorizedOperands));
274   state.addTypes(llvm::to_vector<4>(returnTypes));
275   return VectorizationResult{VectorizationStatus::NewOp,
276                              builder.createOperation(state)};
277 }
278 
279 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
280 static bool hasOnlyScalarElementwiseOp(Region &r) {
281   if (!llvm::hasSingleElement(r))
282     return false;
283   for (Operation &op : r.front()) {
284     if (!(isa<ConstantOp, linalg::YieldOp, linalg::IndexOp>(op) ||
285           OpTrait::hasElementwiseMappableTraits(&op)) ||
286         llvm::any_of(op.getResultTypes(),
287                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
288       return false;
289   }
290   return true;
291 }
292 
293 // Return true if the op is an element-wise linalg op.
294 static bool isElementwise(Operation *op) {
295   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
296   if (!linalgOp)
297     return false;
298   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
299     return false;
300   // TODO: relax the restrictions on indexing map.
301   for (unsigned i = 0, e = linalgOp.getNumOutputs(); i < e; i++) {
302     if (!linalgOp.getOutputIndexingMap(i).isIdentity())
303       return false;
304   }
305   if (linalgOp->getNumRegions() != 1)
306     return false;
307   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
308 }
309 
310 // Calculate the map to apply to transfer_read to convert the input shape into
311 // the output shape.
312 static AffineMap getTransferReadMap(LinalgOp linalgOp, unsigned argIndex) {
313   AffineMap linalgMap = linalgOp.getIndexingMap(argIndex);
314   MLIRContext *context = linalgMap.getContext();
315   AffineExpr zero = mlir::getAffineConstantExpr(0, context);
316   SmallVector<AffineExpr, 4> exprs(linalgMap.getNumInputs(), zero);
317   for (unsigned i : llvm::seq(unsigned(0), linalgMap.getNumResults())) {
318     exprs[linalgMap.getDimPosition(i)] = getAffineDimExpr(i, context);
319   }
320   return AffineMap::get(linalgMap.getNumResults(), /*symbolCount=*/0, exprs,
321                         context);
322 }
323 
324 /// Generic vectorization function that rewrites the body of a `linalgOp` into
325 /// vector form. Generic vectorization proceeds as follows:
326 ///   1. Verify the `linalgOp` has one non-empty region.
327 ///   2. Values defined above the region are mapped to themselves and will be
328 ///   broadcasted on a per-need basis by their consumers.
329 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
330 ///   load).
331 ///   TODO: Reuse opportunities for RAR dependencies.
332 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
333 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
334 ///   indices.
335 ///   5. Iteratively call vectorizeOneOp on the region operations.
336 LogicalResult vectorizeAsLinalgGeneric(
337     OpBuilder &builder, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults,
338     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
339   // 1. Fail to vectorize if the operation does not have one non-empty region.
340   if (linalgOp->getNumRegions() != 1 || linalgOp->getRegion(0).empty())
341     return failure();
342   auto &block = linalgOp->getRegion(0).front();
343 
344   BlockAndValueMapping bvm;
345   // 2. Values defined above the region can only be broadcast for now. Make them
346   // map to themselves.
347   SetVector<Value> valuesSet;
348   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
349   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
350 
351   // 3. Turn all BBArgs into vector.transfer_read / load.
352   SmallVector<AffineMap> indexings;
353   for (auto bbarg : block.getArguments()) {
354     Value vectorArg = linalgOp.getShapedOperand(bbarg.getArgNumber());
355     AffineMap map;
356     VectorType vectorType = extractVectorTypeFromShapedValue(vectorArg);
357     if (isElementwise(linalgOp) &&
358         !linalgOp.getIndexingMap(bbarg.getArgNumber()).isMinorIdentity()) {
359       // Currently assume we don't support output permutations.
360       assert(linalgOp.getNumOutputs() > 0 &&
361              linalgOp.getOutputIndexingMap(0).isIdentity());
362       ArrayRef<int64_t> outputShape =
363           linalgOp.getOutputShapedType(0).getShape();
364       vectorType = VectorType::get(outputShape, vectorType.getElementType());
365       map = getTransferReadMap(linalgOp, bbarg.getArgNumber());
366     }
367     Value vectorRead = buildVectorRead(builder, vectorArg, vectorType, map);
368     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
369                       << bbarg.getArgNumber() << "): " << vectorRead);
370     bvm.map(bbarg, vectorRead);
371     bvm.map(vectorArg, vectorRead);
372   }
373 
374   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
375   // 4a. Register CustomVectorizationHook for yieldOp.
376   CustomVectorizationHook vectorizeYield =
377       [&](Operation *op,
378           const BlockAndValueMapping &bvm) -> VectorizationResult {
379     return vectorizeLinalgYield(builder, op, bvm, linalgOp, newResults);
380   };
381   hooks.push_back(vectorizeYield);
382 
383   // 4b. Register CustomVectorizationHook for indexOp.
384   CustomVectorizationHook vectorizeIndex =
385       [&](Operation *op,
386           const BlockAndValueMapping &bvm) -> VectorizationResult {
387     return vectorizeLinalgIndex(builder, op, linalgOp);
388   };
389   hooks.push_back(vectorizeIndex);
390 
391   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
392   for (Operation &op : block.getOperations()) {
393     VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks);
394     if (result.status == VectorizationStatus::Failure) {
395       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
396       return failure();
397     }
398     if (result.status == VectorizationStatus::NewOp) {
399       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
400                         << *result.newOp;);
401       bvm.map(op.getResults(), result.newOp->getResults());
402     }
403   }
404 
405   return success();
406 }
407 
408 static LogicalResult vectorizeContraction(OpBuilder &builder, LinalgOp linalgOp,
409                                           SmallVectorImpl<Value> &newResults) {
410   assert(isaContractionOpInterface(linalgOp) &&
411          "expected vectorizeContraction preconditions to be met");
412   Location loc = linalgOp.getLoc();
413   // Vectorize other ops as vector contraction.
414   // TODO: interface.
415   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
416                     << "Rewrite linalg op as vector.contract: ";
417              linalgOp.dump());
418   // Special function that describes how to vectorize the multiplication op in a
419   // linalg contraction.
420   CustomVectorizationHook vectorizeContraction =
421       [&](Operation *op,
422           const BlockAndValueMapping &bvm) -> VectorizationResult {
423     if (!isa<MulIOp, MulFOp>(op))
424       return VectorizationResult{VectorizationStatus::Failure, nullptr};
425     auto outShape = linalgOp.getOutputShapedType(0).getShape();
426     auto vType = outShape.empty()
427                      ? op->getResult(0).getType()
428                      : VectorType::get(outShape, op->getResult(0).getType());
429     auto zero =
430         builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType));
431     Operation *contract = builder.create<vector::ContractionOp>(
432         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
433         linalgOp.indexing_maps(), linalgOp.iterator_types());
434     return VectorizationResult{VectorizationStatus::NewOp, contract};
435   };
436   return vectorizeAsLinalgGeneric(builder, linalgOp, newResults,
437                                   {vectorizeContraction});
438 }
439 
440 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
441   auto linalgOp = cast<linalg::LinalgOp>(op);
442   // All types must be static shape to go to vector.
443   for (Value operand : linalgOp.getShapedOperands())
444     if (!operand.getType().cast<ShapedType>().hasStaticShape())
445       return failure();
446   for (Type outputTensorType : linalgOp.getOutputTensorTypes())
447     if (!outputTensorType.cast<ShapedType>().hasStaticShape())
448       return failure();
449   if (isElementwise(op))
450     return success();
451   return success(isaContractionOpInterface(linalgOp));
452 }
453 
454 LogicalResult
455 mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op,
456                                 SmallVectorImpl<Value> &newResults) {
457   if (failed(vectorizeLinalgOpPrecondition(op)))
458     return failure();
459 
460   edsc::ScopedContext scope(builder, op->getLoc());
461   if (isElementwise(op)) {
462     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
463                       << "Vectorize linalg op as a generic: " << *op);
464     return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op), newResults);
465   }
466 
467   return vectorizeContraction(builder, cast<LinalgOp>(op), newResults);
468 }
469 
470 //----------------------------------------------------------------------------//
471 // Misc. vectorization patterns.
472 //----------------------------------------------------------------------------//
473 
474 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and
475 /// TransferWriteOp. For now, this only applies when all low and high paddings
476 /// are determined to be zero.
477 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite(
478     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
479   // Helper function to determine whether an OpFoldResult is not a zero Index.
480   auto isNotZeroIndex = [](OpFoldResult ofr) {
481     if (Attribute attr = ofr.dyn_cast<Attribute>())
482       return attr.cast<IntegerAttr>().getInt() != 0;
483     Value v = ofr.get<Value>();
484     if (auto constOp = v.getDefiningOp<ConstantOp>())
485       if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>())
486         return intAttr.getValue().getSExtValue() != 0;
487     return true;
488   };
489 
490   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
491   // Bail on non-static shapes.
492   if (!resultShapedType.hasStaticShape())
493     return failure();
494 
495   // If any pad_low is not a static 0, needs a mask. Bail for now.
496   if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex))
497     return failure();
498   VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result());
499   if (!vectorType)
500     return failure();
501 
502   // Only support padding with a constant for now, i.e. either:
503   //   1. A BBarg from a different block.
504   //   2. A value defined outside of the current block.
505   Block &block = padOp.region().front();
506   auto yieldOp = cast<YieldOp>(block.getTerminator());
507   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
508   Value padValue = yieldOp.values().front();
509   Operation *definingOp = padValue.getDefiningOp();
510   if (definingOp && definingOp->getBlock() == &block)
511     return failure();
512   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
513     return failure();
514 
515   // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail.
516   if (llvm::any_of(padOp.getMixedHighPad(),
517                    [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); }))
518     return failure();
519 
520   // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] +
521   // TransferWriteOp@[0..0].
522   SmallVector<Value> indices(
523       resultShapedType.getRank(),
524       rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
525   Value read = rewriter.create<vector::TransferReadOp>(
526       padOp.getLoc(), vectorType, padOp.source(), indices, padValue);
527   Value init =
528       rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(),
529                                     resultShapedType.getElementType());
530   rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init,
531                                                        indices);
532 
533   return success();
534 }
535 
536 // TODO: cleanup all the convolution vectorization patterns.
537 template <class ConvOp, int N>
538 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
539     ConvOp op, PatternRewriter &rewriter) const {
540   Location loc = op.getLoc();
541   MLIRContext *context = op.getContext();
542   edsc::ScopedContext scope(rewriter, loc);
543 
544   ShapedType inShapeType = op.getInputShapedType(0);
545   ShapedType kShapeType = op.getInputShapedType(1);
546 
547   ArrayRef<int64_t> inShape = inShapeType.getShape();
548   ArrayRef<int64_t> kShape = kShapeType.getShape();
549 
550   if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape())
551     return failure();
552 
553   SmallVector<AffineExpr, 4> mapping;
554   SmallVector<int64_t, 4> vectorDims;
555   // Fail to apply when the size of not vectorized dimension is not 1.
556   for (unsigned i = 0; i < N; i++) {
557     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
558       return failure();
559 
560     if (mask[i] && inShape[i] != kShape[i])
561       return failure();
562 
563     if (mask[i]) {
564       mapping.push_back(getAffineDimExpr(i, context));
565       vectorDims.push_back(inShape[i]);
566     }
567   }
568 
569   Value input = op.getInput(0);
570   Value kernel = op.getInput(1);
571   Value output = op.getOutputBuffer(0);
572 
573   unsigned rank = inShapeType.getRank();
574   unsigned numDims = mapping.size();
575   Type elemType = inShapeType.getElementType();
576 
577   auto map = AffineMap::get(rank, 0, mapping, context);
578   SmallVector<Value, 4> zeros(rank, std_constant_index(0));
579   auto vecType = VectorType::get(vectorDims, elemType);
580 
581   auto inputVec = vector_transfer_read(vecType, input, zeros, map);
582   auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map);
583 
584   auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType));
585 
586   std::array<AffineMap, 3> indexingMaps{
587       AffineMap::getMultiDimIdentityMap(numDims, context),
588       AffineMap::getMultiDimIdentityMap(numDims, context),
589       AffineMap::get(numDims, 0, {}, context)};
590 
591   std::vector<StringRef> iteratorTypes(numDims, "reduction");
592 
593   auto result = rewriter.create<vector::ContractionOp>(
594       loc, inputVec, kernelVec, acc,
595       rewriter.getAffineMapArrayAttr(indexingMaps),
596       rewriter.getStrArrayAttr(iteratorTypes));
597 
598   rewriter.create<memref::StoreOp>(loc, result, output, ValueRange(zeros));
599   rewriter.eraseOp(op);
600   return success();
601 }
602 
603 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>;
604 
605 /// Inserts tiling, promotion and vectorization pattern for ConvOp
606 /// conversion into corresponding pattern lists.
607 template <typename ConvOp, unsigned N>
608 static void populateVectorizationPatterns(
609     RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns,
610     RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) {
611   auto *context = tilingPatterns.getContext();
612   if (tileSizes.size() < N)
613     return;
614 
615   constexpr static StringRef kTiledMarker = "TILED";
616   constexpr static StringRef kPromotedMarker = "PROMOTED";
617   tilingPatterns.add<LinalgTilingPattern<ConvOp>>(
618       context, LinalgTilingOptions().setTileSizes(tileSizes),
619       LinalgTransformationFilter(ArrayRef<Identifier>{},
620                                  Identifier::get(kTiledMarker, context)));
621 
622   promotionPatterns.add<LinalgPromotionPattern<ConvOp>>(
623       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
624       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
625                                  Identifier::get(kPromotedMarker, context)));
626 
627   SmallVector<bool, 4> mask(N);
628   int offset = tileSizes.size() - N;
629   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
630                  [](int64_t i) -> bool { return i > 1; });
631 
632   vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask);
633 }
634 
635 void mlir::linalg::populateConvVectorizationPatterns(
636     MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns,
637     ArrayRef<int64_t> tileSizes) {
638   RewritePatternSet tiling(context);
639   RewritePatternSet promotion(context);
640   RewritePatternSet vectorization(context);
641   populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization,
642                                             tileSizes);
643 
644   populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization,
645                                               tileSizes);
646   populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>(
647       tiling, promotion, vectorization, tileSizes);
648 
649   populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization,
650                                               tileSizes);
651   populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>(
652       tiling, promotion, vectorization, tileSizes);
653 
654   populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization,
655                                              tileSizes);
656 
657   populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization,
658                                                tileSizes);
659   populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>(
660       tiling, promotion, vectorization, tileSizes);
661 
662   populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization,
663                                                tileSizes);
664   populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>(
665       tiling, promotion, vectorization, tileSizes);
666 
667   populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization,
668                                               tileSizes);
669 
670   populateVectorizationPatterns<ConvNDHWCOp, 5>(tiling, promotion,
671                                                 vectorization, tileSizes);
672   populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>(
673       tiling, promotion, vectorization, tileSizes);
674 
675   populateVectorizationPatterns<ConvNCDHWOp, 5>(tiling, promotion,
676                                                 vectorization, tileSizes);
677   populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>(
678       tiling, promotion, vectorization, tileSizes);
679 
680   patterns.push_back(std::move(tiling));
681   patterns.push_back(std::move(promotion));
682   patterns.push_back(std::move(vectorization));
683 }
684 
685 //----------------------------------------------------------------------------//
686 // Forwarding patterns
687 //----------------------------------------------------------------------------//
688 
689 /// Check whether there is any interleaved use of any `values` between `firstOp`
690 /// and `secondOp`. Conservatively return `true` if any op or value is in a
691 /// different block.
692 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
693                                     ValueRange values) {
694   if (firstOp->getBlock() != secondOp->getBlock() ||
695       !firstOp->isBeforeInBlock(secondOp)) {
696     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
697                             << "interleavedUses precondition failed, firstOp: "
698                             << *firstOp << ", second op: " << *secondOp);
699     return true;
700   }
701   for (auto v : values) {
702     for (auto &u : v.getUses()) {
703       Operation *owner = u.getOwner();
704       if (owner == firstOp || owner == secondOp)
705         continue;
706       // TODO: this is too conservative, use dominance info in the future.
707       if (owner->getBlock() == firstOp->getBlock() &&
708           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
709         continue;
710       LLVM_DEBUG(llvm::dbgs()
711                  << "\n[" DEBUG_TYPE "]: "
712                  << " found interleaved op " << *owner
713                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
714       return true;
715     }
716   }
717   return false;
718 }
719 
720 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
721 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
722   memref::SubViewOp subViewOp;
723   for (auto &u : v.getUses()) {
724     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
725       if (subViewOp)
726         return memref::SubViewOp();
727       subViewOp = newSubViewOp;
728     }
729   }
730   return subViewOp;
731 }
732 
733 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
734 /// when available.
735 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
736     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
737 
738   // Transfer into `view`.
739   Value viewOrAlloc = xferOp.source();
740   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
741       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
742     return failure();
743 
744   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
745 
746   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
747   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
748   if (!subViewOp)
749     return failure();
750   Value subView = subViewOp.getResult();
751   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
752                           << "with subView " << subView);
753 
754   // Find the copy into `subView` without interleaved uses.
755   CopyOp copyOp;
756   for (auto &u : subView.getUses()) {
757     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
758       if (newCopyOp.getOutputBuffer(0) != subView)
759         continue;
760       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
761                               << "copy candidate " << *newCopyOp);
762       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
763         continue;
764       copyOp = newCopyOp;
765       break;
766     }
767   }
768   if (!copyOp)
769     return failure();
770   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
771                           << "with copy " << *copyOp);
772 
773   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
774   FillOp maybeFillOp;
775   for (auto &u : viewOrAlloc.getUses()) {
776     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
777       if (newFillOp.getOutputBuffer(0) != viewOrAlloc)
778         continue;
779       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
780                               << "fill candidate " << *newFillOp);
781       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
782         continue;
783       maybeFillOp = newFillOp;
784       break;
785     }
786   }
787   // Ensure padding matches.
788   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
789     return failure();
790   if (maybeFillOp)
791     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
792                             << "with maybeFillOp " << *maybeFillOp);
793 
794   // `in` is the subview that linalg.copy reads. Replace it.
795   Value in = copyOp.getInput(0);
796 
797   // linalg.copy + linalg.fill can be used to create a padded local buffer.
798   // The `masked` attribute is only valid on this padded buffer.
799   // When forwarding to vector.transfer_read, the attribute must be reset
800   // conservatively.
801   Value res = rewriter.create<vector::TransferReadOp>(
802       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
803       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
804 
805   if (maybeFillOp)
806     rewriter.eraseOp(maybeFillOp);
807   rewriter.eraseOp(copyOp);
808   rewriter.replaceOp(xferOp, res);
809 
810   return success();
811 }
812 
813 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
814 /// when available.
815 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
816     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
817   // Transfer into `viewOrAlloc`.
818   Value viewOrAlloc = xferOp.source();
819   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
820       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
821     return failure();
822 
823   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
824   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
825   if (!subViewOp)
826     return failure();
827   Value subView = subViewOp.getResult();
828 
829   // Find the copy from `subView` without interleaved uses.
830   CopyOp copyOp;
831   for (auto &u : subViewOp.getResult().getUses()) {
832     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
833       if (newCopyOp.getInput(0) != subView)
834         continue;
835       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
836         continue;
837       copyOp = newCopyOp;
838       break;
839     }
840   }
841   if (!copyOp)
842     return failure();
843 
844   // `out` is the subview copied into that we replace.
845   Value out = copyOp.getOutputBuffer(0);
846 
847   // Forward vector.transfer into copy.
848   // linalg.copy + linalg.fill can be used to create a padded local buffer.
849   // The `masked` attribute is only valid on this padded buffer.
850   // When forwarding to vector.transfer_write, the attribute must be reset
851   // conservatively.
852   rewriter.create<vector::TransferWriteOp>(
853       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
854       xferOp.permutation_map(), ArrayAttr());
855 
856   rewriter.eraseOp(copyOp);
857   rewriter.eraseOp(xferOp);
858 
859   return success();
860 }
861