1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the linalg dialect Vectorization transformations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Analysis/SliceAnalysis.h" 14 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h" 15 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 16 #include "mlir/Dialect/Func/IR/FuncOps.h" 17 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 18 #include "mlir/Dialect/Linalg/IR/Linalg.h" 19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 20 #include "mlir/Dialect/Linalg/Utils/Utils.h" 21 #include "mlir/Dialect/Tensor/IR/Tensor.h" 22 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 23 #include "mlir/Dialect/Vector/IR/VectorOps.h" 24 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h" 25 #include "mlir/IR/AffineExpr.h" 26 #include "mlir/IR/Matchers.h" 27 #include "mlir/IR/PatternMatch.h" 28 #include "mlir/Pass/Pass.h" 29 #include "mlir/Support/LLVM.h" 30 #include "mlir/Transforms/RegionUtils.h" 31 #include "llvm/ADT/ScopeExit.h" 32 #include "llvm/ADT/Sequence.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/TypeSwitch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <type_traits> 38 39 using namespace mlir; 40 using namespace mlir::linalg; 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 /// Try to vectorize `convOp` as a convolution. 48 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, 49 LinalgOp convOp); 50 51 /// Return the unique instance of OpType in `block` if it is indeed unique. 52 /// Return null if none or more than 1 instances exist. 53 template <typename OpType> 54 static OpType getSingleOpOfType(Block &block) { 55 OpType res; 56 block.walk([&](OpType op) { 57 if (res) { 58 res = nullptr; 59 return WalkResult::interrupt(); 60 } 61 res = op; 62 return WalkResult::advance(); 63 }); 64 return res; 65 } 66 67 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a 68 /// projectedPermutation, compress the unused dimensions to serve as a 69 /// permutation_map for a vector transfer operation. 70 /// For example, given a linalg op such as: 71 /// 72 /// ``` 73 /// %0 = linalg.generic { 74 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>, 75 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)> 76 /// } 77 /// ins(%0 : tensor<2x3x4xf32>) 78 /// outs(%1 : tensor<5x6xf32>) 79 /// ``` 80 /// 81 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine 82 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second 83 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`. 84 static AffineMap reindexIndexingMap(AffineMap map) { 85 assert(map.isProjectedPermutation(/*allowZeroInResults=*/true) && 86 "expected projected permutation"); 87 auto res = compressUnusedDims(map); 88 assert(res.getNumDims() == res.getNumResults() && 89 "expected reindexed map with same number of dims and results"); 90 return res; 91 } 92 93 /// Helper data structure to represent the result of vectorization. 94 /// In certain specific cases, like terminators, we do not want to propagate/ 95 enum VectorizationStatus { 96 /// Op failed to vectorize. 97 Failure = 0, 98 /// Op vectorized and custom function took care of replacement logic 99 NoReplace, 100 /// Op vectorized into a new Op whose results will replace original Op's 101 /// results. 102 NewOp 103 // TODO: support values if Op vectorized to Many-Ops whose results we need to 104 // aggregate for replacement. 105 }; 106 struct VectorizationResult { 107 /// Return status from vectorizing the current op. 108 enum VectorizationStatus status = VectorizationStatus::Failure; 109 /// New vectorized operation to replace the current op. 110 /// Replacement behavior is specified by `status`. 111 Operation *newOp; 112 }; 113 114 llvm::Optional<vector::CombiningKind> 115 mlir::linalg::getCombinerOpKind(Operation *combinerOp) { 116 using ::mlir::vector::CombiningKind; 117 118 if (!combinerOp) 119 return llvm::None; 120 return llvm::TypeSwitch<Operation *, llvm::Optional<CombiningKind>>( 121 combinerOp) 122 .Case<arith::AddIOp, arith::AddFOp>( 123 [&](auto op) { return CombiningKind::ADD; }) 124 .Case<arith::AndIOp>([&](auto op) { return CombiningKind::AND; }) 125 .Case<arith::MaxSIOp>([&](auto op) { return CombiningKind::MAXSI; }) 126 .Case<arith::MaxFOp>([&](auto op) { return CombiningKind::MAXF; }) 127 .Case<arith::MinSIOp>([&](auto op) { return CombiningKind::MINSI; }) 128 .Case<arith::MinFOp>([&](auto op) { return CombiningKind::MINF; }) 129 .Case<arith::MulIOp, arith::MulFOp>( 130 [&](auto op) { return CombiningKind::MUL; }) 131 .Case<arith::OrIOp>([&](auto op) { return CombiningKind::OR; }) 132 .Case<arith::XOrIOp>([&](auto op) { return CombiningKind::XOR; }) 133 .Default([&](auto op) { return llvm::None; }); 134 } 135 136 /// Check whether `outputOperand` is a reduction with a single combiner 137 /// operation. Return the combiner operation of the reduction. Return 138 /// nullptr otherwise. Multiple reduction operations would impose an 139 /// ordering between reduction dimensions and is currently unsupported in 140 /// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) != 141 /// max(min(X)) 142 // TODO: use in LinalgOp verification, there is a circular dependency atm. 143 static Operation *matchLinalgReduction(OpOperand *outputOperand) { 144 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner()); 145 unsigned outputPos = 146 outputOperand->getOperandNumber() - linalgOp.getNumInputs(); 147 // Only single combiner operations are supported for now. 148 SmallVector<Operation *, 4> combinerOps; 149 if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) || 150 combinerOps.size() != 1) 151 return nullptr; 152 153 // Return the combiner operation. 154 return combinerOps[0]; 155 } 156 157 /// Broadcast `value` to a vector of `shape` if possible. Return value 158 /// otherwise. 159 static Value broadcastIfNeeded(OpBuilder &b, Value value, 160 ArrayRef<int64_t> shape) { 161 // If no shape to broadcast to, just return `value`. 162 if (shape.empty()) 163 return value; 164 VectorType targetVectorType = 165 VectorType::get(shape, getElementTypeOrSelf(value)); 166 if (vector::isBroadcastableTo(value.getType(), targetVectorType) != 167 vector::BroadcastableToResult::Success) 168 return value; 169 Location loc = b.getInsertionPoint()->getLoc(); 170 return b.createOrFold<vector::BroadcastOp>(loc, targetVectorType, value); 171 } 172 173 /// Create MultiDimReductionOp to compute the reduction for `reductionOp`. This 174 /// assumes that `reductionOp` has two operands and one of them is the reduction 175 /// initial value. 176 static Value buildMultiDimReduce(OpBuilder &b, Operation *reduceOp, 177 Value valueToReduce, 178 const SmallVector<bool> &reductionMask) { 179 auto maybeKind = getCombinerOpKind(reduceOp); 180 assert(maybeKind && "Failed precondition: could not get reduction kind"); 181 return b.create<vector::MultiDimReductionOp>( 182 reduceOp->getLoc(), valueToReduce, reductionMask, *maybeKind); 183 } 184 185 static SmallVector<bool> getReductionMask(LinalgOp linalgOp) { 186 unsigned idx = 0; 187 SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false); 188 for (auto attr : linalgOp.iterator_types()) { 189 if (isReductionIterator(attr)) 190 reductionMask[idx] = true; 191 ++idx; 192 } 193 return reductionMask; 194 } 195 196 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set 197 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp 198 /// currently being vectorized. If `dest` has null rank, build an memref.store. 199 /// Return the produced value or null if no value is produced. 200 static Value buildVectorWrite(OpBuilder &b, Value value, 201 OpOperand *outputOperand) { 202 Operation *write; 203 Location loc = value.getLoc(); 204 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner()); 205 ArrayRef<int64_t> shape = linalgOp.getShape(outputOperand); 206 auto vectorType = VectorType::get( 207 shape, getElementTypeOrSelf(outputOperand->get().getType())); 208 if (vectorType.getRank() > 0) { 209 // 0-d case is still special: do not invert the reindexing map. 210 AffineMap map = 211 reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand)); 212 SmallVector<int64_t> transposeShape = 213 applyPermutationMap(inversePermutation(map), vectorType.getShape()); 214 assert(!transposeShape.empty() && "unexpected empty transpose shape"); 215 vectorType = VectorType::get(transposeShape, vectorType.getElementType()); 216 SmallVector<Value> indices(linalgOp.getRank(outputOperand), 217 b.create<arith::ConstantIndexOp>(loc, 0)); 218 value = broadcastIfNeeded(b, value, vectorType.getShape()); 219 write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(), 220 indices, map); 221 } else { 222 if (!value.getType().isa<VectorType>()) 223 value = b.create<vector::BroadcastOp>(loc, vectorType, value); 224 assert(value.getType() == vectorType && "incorrect type"); 225 write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(), 226 ValueRange{}); 227 } 228 LDBG("vectorized op: " << *write); 229 if (!write->getResults().empty()) 230 return write->getResult(0); 231 return Value(); 232 } 233 234 // Custom vectorization function type. Produce a vector form of Operation* 235 // assuming all its vectorized operands are already in the BlockAndValueMapping. 236 // Return nullptr if the Operation cannot be vectorized. 237 using CustomVectorizationHook = std::function<VectorizationResult( 238 Operation *, const BlockAndValueMapping &)>; 239 240 /// Helper function to vectorize the terminator of a `linalgOp`. New result 241 /// vector values are appended to `newResults`. Return 242 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it 243 /// should not try to map produced operations and instead return the results 244 /// using the `newResults` vector making them available to the 245 /// vectorization algorithm for RAUW. This function is meant to be used as a 246 /// CustomVectorizationHook. 247 static VectorizationResult 248 vectorizeLinalgYield(OpBuilder &b, Operation *op, 249 const BlockAndValueMapping &bvm, LinalgOp linalgOp, 250 SmallVectorImpl<Value> &newResults) { 251 auto yieldOp = dyn_cast<linalg::YieldOp>(op); 252 if (!yieldOp) 253 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 254 for (const auto &outputs : llvm::enumerate(yieldOp.values())) { 255 // TODO: Scan for an opportunity for reuse. 256 // TODO: use a map. 257 Value vectorValue = bvm.lookup(outputs.value()); 258 Value newResult = buildVectorWrite( 259 b, vectorValue, linalgOp.getOutputOperand(outputs.index())); 260 if (newResult) 261 newResults.push_back(newResult); 262 } 263 return VectorizationResult{VectorizationStatus::NoReplace, nullptr}; 264 } 265 266 /// Helper function to vectorize the index operations of a `linalgOp`. Return 267 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it 268 /// should map the produced operations. This function is meant to be used as a 269 /// CustomVectorizationHook. 270 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op, 271 LinalgOp linalgOp) { 272 IndexOp indexOp = dyn_cast<linalg::IndexOp>(op); 273 if (!indexOp) 274 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 275 auto loc = indexOp.getLoc(); 276 // Compute the static loop sizes of the index op. 277 auto targetShape = linalgOp.computeStaticLoopSizes(); 278 // Compute a one-dimensional index vector for the index op dimension. 279 SmallVector<int64_t> constantSeq = 280 llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()])); 281 auto constantOp = 282 b.create<arith::ConstantOp>(loc, b.getIndexVectorAttr(constantSeq)); 283 // Return the one-dimensional index vector if it lives in the trailing 284 // dimension of the iteration space since the vectorization algorithm in this 285 // case can handle the broadcast. 286 if (indexOp.dim() == targetShape.size() - 1) 287 return VectorizationResult{VectorizationStatus::NewOp, constantOp}; 288 // Otherwise permute the targetShape to move the index dimension last, 289 // broadcast the one-dimensional index vector to the permuted shape, and 290 // finally transpose the broadcasted index vector to undo the permutation. 291 std::swap(targetShape[indexOp.dim()], targetShape.back()); 292 auto broadCastOp = b.create<vector::BroadcastOp>( 293 loc, VectorType::get(targetShape, b.getIndexType()), constantOp); 294 SmallVector<int64_t> transposition = 295 llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops())); 296 std::swap(transposition.back(), transposition[indexOp.dim()]); 297 auto transposeOp = 298 b.create<vector::TransposeOp>(loc, broadCastOp, transposition); 299 return VectorizationResult{VectorizationStatus::NewOp, transposeOp}; 300 } 301 302 /// Emit reduction operations if the shapes of the value to reduce is different 303 /// that the result shape. 304 static Operation *reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op, 305 Value reduceValue, Value initialValue, 306 const BlockAndValueMapping &bvm) { 307 Value reduceVec = bvm.lookup(reduceValue); 308 Value outputVec = bvm.lookup(initialValue); 309 auto reduceType = reduceVec.getType().dyn_cast<VectorType>(); 310 auto outputType = outputVec.getType().dyn_cast<VectorType>(); 311 // Reduce only if needed as the value may already have been reduce for 312 // contraction vectorization. 313 if (!reduceType || 314 (outputType && reduceType.getShape() == outputType.getShape())) 315 return nullptr; 316 SmallVector<bool> reductionMask = getReductionMask(linalgOp); 317 Value reduce = buildMultiDimReduce(b, op, reduceVec, reductionMask); 318 return b.create(op->getLoc(), op->getName().getIdentifier(), 319 /*operands=*/{reduce, outputVec}, reduce.getType(), 320 op->getAttrs()); 321 } 322 323 /// Generic vectorization for a single operation `op`, given already vectorized 324 /// operands carried by `bvm`. Vectorization occurs as follows: 325 /// 1. Try to apply any of the `customVectorizationHooks` and return its 326 /// result on success. 327 /// 2. Clone any constant in the current scope without vectorization: each 328 /// consumer of the constant will later determine the shape to which the 329 /// constant needs to be broadcast to. 330 /// 3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose 331 /// of the `customVectorizationHooks` to cover such cases. 332 /// 4. Clone `op` in vector form to a vector of shape prescribed by the first 333 /// operand of maximal rank. Other operands have smaller rank and are 334 /// broadcast accordingly. It is assumed this broadcast is always legal, 335 /// otherwise, it means one of the `customVectorizationHooks` is incorrect. 336 /// 337 /// This function assumes all operands of `op` have been vectorized and are in 338 /// the `bvm` mapping. As a consequence, this function is meant to be called on 339 /// a topologically-sorted list of ops. 340 /// This function does not update `bvm` but returns a VectorizationStatus that 341 /// instructs the caller what `bvm` update needs to occur. 342 static VectorizationResult 343 vectorizeOneOp(OpBuilder &b, LinalgOp linalgOp, Operation *op, 344 const BlockAndValueMapping &bvm, 345 ArrayRef<CustomVectorizationHook> customVectorizationHooks) { 346 LDBG("vectorize op " << *op); 347 348 // 1. Try to apply any CustomVectorizationHook. 349 if (!customVectorizationHooks.empty()) { 350 for (auto &customFunc : customVectorizationHooks) { 351 VectorizationResult result = customFunc(op, bvm); 352 if (result.status == VectorizationStatus::Failure) 353 continue; 354 return result; 355 } 356 } 357 358 // 2. Constant ops don't get vectorized but rather broadcasted at their users. 359 // Clone so that the constant is not confined to the linalgOp block . 360 if (isa<arith::ConstantOp, func::ConstantOp>(op)) 361 return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)}; 362 363 // 3. Only ElementwiseMappable are allowed in the generic vectorization. 364 if (!OpTrait::hasElementwiseMappableTraits(op)) 365 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 366 367 // 4 . Check if the operation is a reduction. 368 SmallVector<std::pair<Value, Value>> reductionOperands; 369 for (Value operand : op->getOperands()) { 370 auto arg = operand.dyn_cast<BlockArgument>(); 371 if (!arg || arg.getArgNumber() < linalgOp.getNumInputs()) 372 continue; 373 SmallVector<Operation *> reductionOps; 374 Value reduceValue = matchReduction( 375 linalgOp.getRegionOutputArgs(), 376 arg.getArgNumber() - linalgOp.getNumInputs(), reductionOps); 377 if (!reduceValue) 378 continue; 379 reductionOperands.push_back(std::make_pair(reduceValue, operand)); 380 } 381 if (!reductionOperands.empty()) { 382 assert(reductionOperands.size() == 1); 383 Operation *reduceOp = 384 reduceIfNeeded(b, linalgOp, op, reductionOperands[0].first, 385 reductionOperands[0].second, bvm); 386 if (reduceOp) 387 return VectorizationResult{VectorizationStatus::NewOp, reduceOp}; 388 } 389 390 // 5. Generic vectorization path for ElementwiseMappable ops. 391 // a. first get the first max ranked shape. 392 SmallVector<int64_t, 4> firstMaxRankedShape; 393 for (Value operand : op->getOperands()) { 394 auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>(); 395 if (vt && firstMaxRankedShape.size() < vt.getShape().size()) 396 firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end()); 397 } 398 // b. broadcast each op if needed. 399 auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) { 400 return firstMaxRankedShape.empty() 401 ? bvm.lookup(v) 402 : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape); 403 }); 404 // c. for elementwise, the result is the vector with the firstMaxRankedShape 405 auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) { 406 return firstMaxRankedShape.empty() 407 ? t 408 : VectorType::get(firstMaxRankedShape, t); 409 }); 410 411 // Build and return the new op. 412 return VectorizationResult{ 413 VectorizationStatus::NewOp, 414 b.create(op->getLoc(), op->getName().getIdentifier(), 415 llvm::to_vector<4>(vectorizedOperands), 416 llvm::to_vector<4>(returnTypes), op->getAttrs())}; 417 } 418 419 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp. 420 static bool hasOnlyScalarElementwiseOp(Region &r) { 421 if (!llvm::hasSingleElement(r)) 422 return false; 423 for (Operation &op : r.front()) { 424 if (!(isa<arith::ConstantOp, func::ConstantOp, linalg::YieldOp, 425 linalg::IndexOp>(op) || 426 OpTrait::hasElementwiseMappableTraits(&op)) || 427 llvm::any_of(op.getResultTypes(), 428 [](Type type) { return !type.isIntOrIndexOrFloat(); })) 429 return false; 430 } 431 return true; 432 } 433 434 // Return true if the op is an element-wise linalg op. 435 static bool isElementwise(Operation *op) { 436 auto linalgOp = dyn_cast<linalg::LinalgOp>(op); 437 if (!linalgOp) 438 return false; 439 if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops()) 440 return false; 441 // TODO: relax the restrictions on indexing map. 442 for (OpOperand *opOperand : linalgOp.getOutputOperands()) { 443 if (!linalgOp.getTiedIndexingMap(opOperand).isIdentity()) 444 return false; 445 } 446 return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0)); 447 } 448 449 /// Generic vectorization function that rewrites the body of a `linalgOp` into 450 /// vector form. Generic vectorization proceeds as follows: 451 /// 1. Verify the `linalgOp` has one non-empty region. 452 /// 2. Values defined above the region are mapped to themselves and will be 453 /// broadcasted on a per-need basis by their consumers. 454 /// 3. Each region argument is vectorized into a vector.transfer_read (or 0-d 455 /// load). 456 /// TODO: Reuse opportunities for RAR dependencies. 457 /// 4a. Register CustomVectorizationHook for YieldOp to capture the results. 458 /// 4b. Register CustomVectorizationHook for IndexOp to access the iteration 459 /// indices. 460 /// 5. Iteratively call vectorizeOneOp on the region operations. 461 /// 462 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is 463 /// performed to the maximal common vector size implied by the `linalgOp` 464 /// iteration space. This eager broadcasting is introduced in the 465 /// permutation_map of the vector.transfer_read operations. The eager 466 /// broadcasting makes it trivial to detrmine where broadcast, transposes and 467 /// reductions should occur, without any bookkeeping. The tradeoff is that, in 468 /// the absence of good canonicalizations, the amount of work increases. 469 /// This is not deemed a problem as we expect canonicalizations and foldings to 470 /// aggressively clean up the useless work. 471 static LogicalResult 472 vectorizeAsLinalgGeneric(OpBuilder &b, LinalgOp linalgOp, 473 SmallVectorImpl<Value> &newResults) { 474 Block *block = linalgOp.getBlock(); 475 476 // 2. Values defined above the region can only be broadcast for now. Make them 477 // map to themselves. 478 BlockAndValueMapping bvm; 479 SetVector<Value> valuesSet; 480 mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet); 481 bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef()); 482 483 if (linalgOp.getNumOutputs() == 0) 484 return failure(); 485 486 // TODO: the common vector shape is equal to the static loop sizes only when 487 // all indexing maps are projected permutations. For convs and stencils the 488 // logic will need to evolve. 489 SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes(); 490 491 // 3. Turn all BBArgs into vector.transfer_read / load. 492 Location loc = linalgOp.getLoc(); 493 Value zero = b.create<arith::ConstantIndexOp>(loc, 0); 494 for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) { 495 BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber()); 496 if (linalgOp.isScalar(opOperand)) { 497 bvm.map(bbarg, opOperand->get()); 498 continue; 499 } 500 VectorType readType; 501 AffineMap map; 502 // TODO: can we keep this simplification? 503 // if (linalgOp.getShape(opOperand).empty()) { 504 // readType = VectorType::get({}, bbarg.getType()); 505 // } else { 506 if (opOperand->getOperandNumber() < linalgOp.getNumInputs()) { 507 map = inverseAndBroadcastProjectedPermutation( 508 linalgOp.getTiedIndexingMap(opOperand)); 509 readType = VectorType::get(commonVectorShape, 510 getElementTypeOrSelf(opOperand->get())); 511 } else { 512 map = inversePermutation( 513 reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand))); 514 readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)), 515 getElementTypeOrSelf(opOperand->get())); 516 } 517 // } 518 519 auto shape = linalgOp.getShape(opOperand); 520 SmallVector<Value> indices(shape.size(), zero); 521 Value readValue = b.create<vector::TransferReadOp>( 522 loc, readType, opOperand->get(), indices, map); 523 // Not all ops support 0-d vectors, extract the scalar for now. 524 // TODO: remove this. 525 if (readValue.getType().cast<VectorType>().getRank() == 0) 526 readValue = b.create<vector::ExtractElementOp>(loc, readValue); 527 528 LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue); 529 bvm.map(bbarg, readValue); 530 bvm.map(opOperand->get(), readValue); 531 } 532 533 SmallVector<CustomVectorizationHook> hooks; 534 // 4a. Register CustomVectorizationHook for yieldOp. 535 CustomVectorizationHook vectorizeYield = 536 [&](Operation *op, 537 const BlockAndValueMapping &bvm) -> VectorizationResult { 538 return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults); 539 }; 540 hooks.push_back(vectorizeYield); 541 542 // 4b. Register CustomVectorizationHook for indexOp. 543 CustomVectorizationHook vectorizeIndex = 544 [&](Operation *op, 545 const BlockAndValueMapping &bvm) -> VectorizationResult { 546 return vectorizeLinalgIndex(b, op, linalgOp); 547 }; 548 hooks.push_back(vectorizeIndex); 549 550 // 5. Iteratively call `vectorizeOneOp` to each op in the slice. 551 for (Operation &op : block->getOperations()) { 552 VectorizationResult result = vectorizeOneOp(b, linalgOp, &op, bvm, hooks); 553 if (result.status == VectorizationStatus::Failure) { 554 LDBG("failed to vectorize: " << op); 555 return failure(); 556 } 557 if (result.status == VectorizationStatus::NewOp) { 558 LDBG("new vector op: " << *result.newOp;); 559 bvm.map(op.getResults(), result.newOp->getResults()); 560 } 561 } 562 563 return success(); 564 } 565 566 /// Helper function to vectorize a `linalgOp` with contraction semantics in a 567 /// generic fashion. 568 /// This helper is needed atm because the truly generic implementation requires 569 /// good vector.multi_reduce folding patterns that are currently NYI. 570 // TODO: drop reliance on a specific pattern. 571 static bool allIndexingsAreProjectedPermutation(LinalgOp op) { 572 return llvm::all_of(op.getIndexingMaps(), [](AffineMap m) { 573 return m.isProjectedPermutation(/*allowZeroInResults=*/true); 574 }); 575 } 576 577 // TODO: probably need some extra checks for reduction followed by consumer 578 // ops that may not commute (e.g. linear reduction + non-linear instructions). 579 static LogicalResult reductionPreconditions(LinalgOp op) { 580 if (llvm::none_of(op.iterator_types(), isReductionIterator)) { 581 LDBG("reduction precondition failed: no reduction iterator"); 582 return failure(); 583 } 584 for (OpOperand *opOperand : op.getOutputOperands()) { 585 Operation *reduceOp = matchLinalgReduction(opOperand); 586 if (!reduceOp || !getCombinerOpKind(reduceOp)) { 587 LDBG("reduction precondition failed: reduction detection failed"); 588 return failure(); 589 } 590 } 591 return success(); 592 } 593 594 static LogicalResult vectorizeStaticLinalgOpPrecondition(linalg::LinalgOp op) { 595 if (isElementwise(op)) 596 return success(); 597 // TODO: isaConvolutionOpInterface that can also infer from generic features. 598 // But we will still need stride/dilation attributes that will be annoying to 599 // reverse-engineer... 600 if (isa<ConvolutionOpInterface>(op.getOperation())) 601 return success(); 602 // TODO: the common vector shape is equal to the static loop sizes only when 603 // all indexing maps are projected permutations. For convs and stencils the 604 // logic will need to evolve. 605 if (!allIndexingsAreProjectedPermutation(op)) { 606 LDBG("precondition failed: not projected permutations"); 607 return failure(); 608 } 609 if (failed(reductionPreconditions(op))) { 610 LDBG("precondition failed: reduction preconditions"); 611 return failure(); 612 } 613 return success(); 614 } 615 616 static LogicalResult vectorizeLinalgOpPrecondition(LinalgOp linalgOp) { 617 // All types must be static shape to go to vector. 618 if (linalgOp.hasDynamicShape()) { 619 LDBG("precondition failed: dynamic shape"); 620 return failure(); 621 } 622 return vectorizeStaticLinalgOpPrecondition(linalgOp); 623 } 624 625 LogicalResult mlir::linalg::vectorize(RewriterBase &rewriter, 626 LinalgOp linalgOp) { 627 if (failed(vectorizeLinalgOpPrecondition(linalgOp))) 628 return failure(); 629 630 SmallVector<Value> results; 631 // TODO: isaConvolutionOpInterface that can also infer from generic 632 // features. Will require stride/dilation attributes inference. 633 FailureOr<Operation *> convOr = vectorizeConvolution(rewriter, linalgOp); 634 if (succeeded(convOr)) { 635 llvm::append_range(results, (*convOr)->getResults()); 636 } else { 637 if (failed(vectorizeLinalgOpPrecondition(linalgOp))) 638 return failure(); 639 LDBG("Vectorize generic by broadcasting to a common shape: " << linalgOp); 640 if (failed(vectorizeAsLinalgGeneric(rewriter, linalgOp, results))) 641 return failure(); 642 } 643 644 if (!results.empty()) 645 rewriter.replaceOp(linalgOp, results); 646 else 647 rewriter.eraseOp(linalgOp); 648 649 return success(); 650 } 651 652 LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter, 653 memref::CopyOp copyOp) { 654 655 auto srcType = copyOp.source().getType().cast<MemRefType>(); 656 auto dstType = copyOp.target().getType().cast<MemRefType>(); 657 if (!srcType.hasStaticShape() || !dstType.hasStaticShape()) 658 return failure(); 659 660 auto readType = 661 VectorType::get(srcType.getShape(), getElementTypeOrSelf(srcType)); 662 auto writeType = 663 VectorType::get(dstType.getShape(), getElementTypeOrSelf(dstType)); 664 665 Location loc = copyOp->getLoc(); 666 Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0); 667 SmallVector<Value> indices(srcType.getRank(), zero); 668 669 Value readValue = rewriter.create<vector::TransferReadOp>( 670 loc, readType, copyOp.source(), indices, 671 rewriter.getMultiDimIdentityMap(srcType.getRank())); 672 if (readValue.getType().cast<VectorType>().getRank() == 0) { 673 readValue = rewriter.create<vector::ExtractElementOp>(loc, readValue); 674 readValue = rewriter.create<vector::BroadcastOp>(loc, writeType, readValue); 675 } 676 Operation *writeValue = rewriter.create<vector::TransferWriteOp>( 677 loc, readValue, copyOp.target(), indices, 678 rewriter.getMultiDimIdentityMap(srcType.getRank())); 679 copyOp->getParentOfType<FuncOp>().dump(); 680 rewriter.replaceOp(copyOp, writeValue->getResults()); 681 return success(); 682 } 683 684 //----------------------------------------------------------------------------// 685 // Misc. vectorization patterns. 686 //----------------------------------------------------------------------------// 687 688 /// Helper function that retrieves the value of an IntegerAttr. 689 static int64_t getIntFromAttr(Attribute attr) { 690 return attr.cast<IntegerAttr>().getInt(); 691 } 692 693 /// Given an ArrayRef of OpFoldResults, return a vector of Values. 694 /// IntegerAttrs are converted to ConstantIndexOps. Other attribute types are 695 /// not supported. 696 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc, 697 ArrayRef<OpFoldResult> ofrs) { 698 SmallVector<Value> result; 699 llvm::for_each(ofrs, [&](auto o) { 700 if (auto val = o.template dyn_cast<Value>()) { 701 result.push_back(val); 702 } else { 703 result.push_back(builder.create<arith::ConstantIndexOp>( 704 loc, getIntFromAttr(o.template get<Attribute>()))); 705 } 706 }); 707 return result; 708 } 709 710 /// Rewrite a tensor::PadOp into a sequence of InitTensorOp, FillOp and 711 /// InsertSliceOp. For now, only constant padding values are supported. 712 /// If there is enough static type information, TransferReadOps and 713 /// TransferWriteOps may be generated instead of InsertSliceOps. 714 struct GenericPadOpVectorizationPattern : public GeneralizePadOpPattern { 715 GenericPadOpVectorizationPattern(MLIRContext *context, 716 PatternBenefit benefit = 1) 717 : GeneralizePadOpPattern(context, tryVectorizeCopy, benefit) {} 718 /// Vectorize the copying of a tensor::PadOp's source. This is possible if 719 /// each dimension size is statically know in the source type or the result 720 /// type (or both). 721 static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter, 722 tensor::PadOp padOp, Value dest) { 723 auto sourceType = padOp.getSourceType(); 724 auto resultType = padOp.getResultType(); 725 726 // Copy cannot be vectorized if pad value is non-constant and source shape 727 // is dynamic. In case of a dynamic source shape, padding must be appended 728 // by TransferReadOp, but TransferReadOp supports only constant padding. 729 auto padValue = padOp.getConstantPaddingValue(); 730 if (!padValue) { 731 if (!sourceType.hasStaticShape()) 732 return failure(); 733 // Create dummy padding value. 734 auto elemType = sourceType.getElementType(); 735 padValue = rewriter.create<arith::ConstantOp>( 736 padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType)); 737 } 738 739 SmallVector<int64_t> vecShape; 740 SmallVector<bool> readInBounds; 741 SmallVector<bool> writeInBounds; 742 for (unsigned i = 0; i < sourceType.getRank(); ++i) { 743 if (!sourceType.isDynamicDim(i)) { 744 vecShape.push_back(sourceType.getDimSize(i)); 745 // Source shape is statically known: Neither read nor write are 746 // out-of- bounds. 747 readInBounds.push_back(true); 748 writeInBounds.push_back(true); 749 } else if (!resultType.isDynamicDim(i)) { 750 // Source shape is not statically known, but result shape is. 751 // Vectorize with size of result shape. This may be larger than the 752 // source size. 753 vecShape.push_back(resultType.getDimSize(i)); 754 // Read may be out-of-bounds because the result size could be larger 755 // than the source size. 756 readInBounds.push_back(false); 757 // Write is out-of-bounds if low padding > 0. 758 writeInBounds.push_back( 759 getConstantIntValue(padOp.getMixedLowPad()[i]) == 760 static_cast<int64_t>(0)); 761 } else { 762 // Neither source nor result dim of padOp is static. Cannot vectorize 763 // the copy. 764 return failure(); 765 } 766 } 767 auto vecType = VectorType::get(vecShape, sourceType.getElementType()); 768 769 // Generate TransferReadOp. 770 SmallVector<Value> readIndices( 771 vecType.getRank(), 772 rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0)); 773 auto read = rewriter.create<vector::TransferReadOp>( 774 padOp.getLoc(), vecType, padOp.source(), readIndices, padValue, 775 ArrayRef<bool>{readInBounds}); 776 777 // If `dest` is a FillOp and the TransferWriteOp would overwrite the 778 // entire tensor, write directly to the FillOp's operand. 779 if (llvm::equal(vecShape, resultType.getShape()) && 780 llvm::all_of(writeInBounds, [](bool b) { return b; })) 781 if (auto fill = dest.getDefiningOp<FillOp>()) 782 dest = fill.output(); 783 784 // Generate TransferWriteOp. 785 auto writeIndices = 786 ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad()); 787 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 788 padOp, read, dest, writeIndices, ArrayRef<bool>{writeInBounds}); 789 790 return success(); 791 } 792 }; 793 794 /// Base pattern for rewriting tensor::PadOps whose result is consumed by a 795 /// given operation type OpTy. 796 template <typename OpTy> 797 struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> { 798 using OpRewritePattern<tensor::PadOp>::OpRewritePattern; 799 800 LogicalResult matchAndRewrite(tensor::PadOp padOp, 801 PatternRewriter &rewriter) const final { 802 bool changed = false; 803 // Insert users in vector, because some users may be replaced/removed. 804 for (auto *user : llvm::to_vector<4>(padOp->getUsers())) 805 if (auto op = dyn_cast<OpTy>(user)) 806 changed |= rewriteUser(rewriter, padOp, op).succeeded(); 807 return success(changed); 808 } 809 810 protected: 811 virtual LogicalResult rewriteUser(PatternRewriter &rewriter, 812 tensor::PadOp padOp, OpTy op) const = 0; 813 }; 814 815 /// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.: 816 /// ``` 817 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32> 818 /// %r = vector.transfer_read %0[%c0, %c0], %cst 819 /// {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32> 820 /// ``` 821 /// is rewritten to: 822 /// ``` 823 /// %r = vector.transfer_read %src[%c0, %c0], %padding 824 /// {in_bounds = [true, true]} 825 /// : tensor<?x?xf32>, vector<17x5xf32> 826 /// ``` 827 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be 828 /// sure that the original padding value %cst was never used. 829 /// 830 /// This rewrite is possible if: 831 /// - `xferOp` has no out-of-bounds dims or mask. 832 /// - Low padding is static 0. 833 /// - Single, scalar padding value. 834 struct PadOpVectorizationWithTransferReadPattern 835 : public VectorizePadOpUserPattern<vector::TransferReadOp> { 836 using VectorizePadOpUserPattern< 837 vector::TransferReadOp>::VectorizePadOpUserPattern; 838 839 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 840 vector::TransferReadOp xferOp) const override { 841 // Low padding must be static 0. 842 if (!padOp.hasZeroLowPad()) 843 return failure(); 844 // Pad value must be a constant. 845 auto padValue = padOp.getConstantPaddingValue(); 846 if (!padValue) 847 return failure(); 848 // Padding value of existing `xferOp` is unused. 849 if (xferOp.hasOutOfBoundsDim() || xferOp.getMask()) 850 return failure(); 851 852 rewriter.updateRootInPlace(xferOp, [&]() { 853 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false); 854 xferOp->setAttr(xferOp.getInBoundsAttrName(), 855 rewriter.getBoolArrayAttr(inBounds)); 856 xferOp.getSourceMutable().assign(padOp.source()); 857 xferOp.getPaddingMutable().assign(padValue); 858 }); 859 860 return success(); 861 } 862 }; 863 864 /// Rewrite use of tensor::PadOp result in TransferWriteOp. 865 /// This pattern rewrites TransferWriteOps that write to a padded tensor 866 /// value, where the same amount of padding is immediately removed again after 867 /// the write. In such cases, the TransferWriteOp can write to the non-padded 868 /// tensor value and apply out-of-bounds masking. E.g.: 869 /// ``` 870 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1] 871 /// : tensor<...> to tensor<?x?xf32> 872 /// %1 = linalg.pad_tensor %0 ... : tensor<?x?xf32> to tensor<17x5xf32> 873 /// %2 = vector.transfer_write %vec, %1[...] 874 /// : vector<17x5xf32>, tensor<17x5xf32> 875 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1] 876 /// : tensor<17x5xf32> to tensor<?x?xf32> 877 /// ``` 878 /// is rewritten to: 879 /// ``` 880 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1] 881 /// : tensor<...> to tensor<?x?xf32> 882 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>, 883 /// tensor<?x?xf32> 884 /// ``` 885 /// Note: It is important that the ExtractSliceOp %r resizes the result of the 886 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an 887 /// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ 888 /// from %r's old dimensions. 889 /// 890 /// This rewrite is possible if: 891 /// - Low padding is static 0. 892 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This 893 /// ExtractSliceOp trims the same amount of padding that was added 894 /// beforehand. 895 /// - Single, scalar padding value. 896 struct PadOpVectorizationWithTransferWritePattern 897 : public VectorizePadOpUserPattern<vector::TransferWriteOp> { 898 using VectorizePadOpUserPattern< 899 vector::TransferWriteOp>::VectorizePadOpUserPattern; 900 901 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 902 vector::TransferWriteOp xferOp) const override { 903 // TODO: support 0-d corner case. 904 if (xferOp.getTransferRank() == 0) 905 return failure(); 906 907 // Low padding must be static 0. 908 if (!padOp.hasZeroLowPad()) 909 return failure(); 910 // Pad value must be a constant. 911 auto padValue = padOp.getConstantPaddingValue(); 912 if (!padValue) 913 return failure(); 914 // TransferWriteOp result must be directly consumed by an ExtractSliceOp. 915 if (!xferOp->hasOneUse()) 916 return failure(); 917 auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin()); 918 if (!trimPadding) 919 return failure(); 920 // Only static zero offsets supported when trimming padding. 921 if (!trimPadding.hasZeroOffset()) 922 return failure(); 923 // trimPadding must remove the amount of padding that was added earlier. 924 if (!hasSameTensorSize(padOp.source(), trimPadding)) 925 return failure(); 926 927 // Insert the new TransferWriteOp at position of the old TransferWriteOp. 928 rewriter.setInsertionPoint(xferOp); 929 930 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false); 931 auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 932 xferOp, padOp.source().getType(), xferOp.getVector(), padOp.source(), 933 xferOp.getIndices(), xferOp.getPermutationMapAttr(), xferOp.getMask(), 934 rewriter.getBoolArrayAttr(inBounds)); 935 rewriter.replaceOp(trimPadding, newXferOp->getResult(0)); 936 937 return success(); 938 } 939 940 /// Check if `beforePadding` and `afterTrimming` have the same tensor size, 941 /// i.e., same dimensions. 942 /// 943 /// Dimensions may be static, dynamic or mix of both. In case of dynamic 944 /// dimensions, this function tries to infer the (static) tensor size by 945 /// looking at the defining op and utilizing op-specific knowledge. 946 /// 947 /// This is a conservative analysis. In case equal tensor sizes cannot be 948 /// proven statically, this analysis returns `false` even though the tensor 949 /// sizes may turn out to be equal at runtime. 950 bool hasSameTensorSize(Value beforePadding, 951 tensor::ExtractSliceOp afterTrimming) const { 952 // If the input to tensor::PadOp is a CastOp, try with with both CastOp 953 // result and CastOp operand. 954 if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>()) 955 if (hasSameTensorSize(castOp.source(), afterTrimming)) 956 return true; 957 958 auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>(); 959 auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>(); 960 // Only RankedTensorType supported. 961 if (!t1 || !t2) 962 return false; 963 // Rank of both values must be the same. 964 if (t1.getRank() != t2.getRank()) 965 return false; 966 967 // All static dimensions must be the same. Mixed cases (e.g., dimension 968 // static in `t1` but dynamic in `t2`) are not supported. 969 for (unsigned i = 0; i < t1.getRank(); ++i) { 970 if (t1.isDynamicDim(i) != t2.isDynamicDim(i)) 971 return false; 972 if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i)) 973 return false; 974 } 975 976 // Nothing more to check if all dimensions are static. 977 if (t1.getNumDynamicDims() == 0) 978 return true; 979 980 // All dynamic sizes must be the same. The only supported case at the 981 // moment is when `beforePadding` is an ExtractSliceOp (or a cast 982 // thereof). 983 984 // Apart from CastOp, only ExtractSliceOp is supported. 985 auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>(); 986 if (!beforeSlice) 987 return false; 988 989 assert(static_cast<size_t>(t1.getRank()) == 990 beforeSlice.getMixedSizes().size()); 991 assert(static_cast<size_t>(t2.getRank()) == 992 afterTrimming.getMixedSizes().size()); 993 994 for (unsigned i = 0; i < t1.getRank(); ++i) { 995 // Skip static dimensions. 996 if (!t1.isDynamicDim(i)) 997 continue; 998 auto size1 = beforeSlice.getMixedSizes()[i]; 999 auto size2 = afterTrimming.getMixedSizes()[i]; 1000 1001 // Case 1: Same value or same constant int. 1002 if (isEqualConstantIntOrValue(size1, size2)) 1003 continue; 1004 1005 // Other cases: Take a deeper look at defining ops of values. 1006 auto v1 = size1.dyn_cast<Value>(); 1007 auto v2 = size2.dyn_cast<Value>(); 1008 if (!v1 || !v2) 1009 return false; 1010 1011 // Case 2: Both values are identical AffineMinOps. (Should not happen if 1012 // CSE is run.) 1013 auto minOp1 = v1.getDefiningOp<AffineMinOp>(); 1014 auto minOp2 = v2.getDefiningOp<AffineMinOp>(); 1015 if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() && 1016 minOp1.operands() == minOp2.operands()) 1017 continue; 1018 1019 // Add additional cases as needed. 1020 } 1021 1022 // All tests passed. 1023 return true; 1024 } 1025 }; 1026 1027 /// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.: 1028 /// ``` 1029 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32> 1030 /// %r = tensor.insert_slice %0 1031 /// into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1] 1032 /// : tensor<17x5xf32> into tensor<?x?x17x5xf32> 1033 /// ``` 1034 /// is rewritten to: 1035 /// ``` 1036 /// %0 = vector.transfer_read %src[%c0, %c0], %padding 1037 /// : tensor<?x?xf32>, vector<17x5xf32> 1038 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0] 1039 /// {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32> 1040 /// ``` 1041 /// 1042 /// This rewrite is possible if: 1043 /// - Low padding is static 0. 1044 /// - `padOp` result shape is static. 1045 /// - The entire padded tensor is inserted. 1046 /// (Implies that sizes of `insertOp` are all static.) 1047 /// - Only unit strides in `insertOp`. 1048 /// - Single, scalar padding value. 1049 /// - `padOp` result not used as destination. 1050 struct PadOpVectorizationWithInsertSlicePattern 1051 : public VectorizePadOpUserPattern<tensor::InsertSliceOp> { 1052 using VectorizePadOpUserPattern< 1053 tensor::InsertSliceOp>::VectorizePadOpUserPattern; 1054 1055 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 1056 tensor::InsertSliceOp insertOp) const override { 1057 // Low padding must be static 0. 1058 if (!padOp.hasZeroLowPad()) 1059 return failure(); 1060 // Only unit stride supported. 1061 if (!insertOp.hasUnitStride()) 1062 return failure(); 1063 // Pad value must be a constant. 1064 auto padValue = padOp.getConstantPaddingValue(); 1065 if (!padValue) 1066 return failure(); 1067 // Dynamic shapes not supported. 1068 if (!padOp.result().getType().cast<ShapedType>().hasStaticShape()) 1069 return failure(); 1070 // Pad result not used as destination. 1071 if (insertOp.dest() == padOp.result()) 1072 return failure(); 1073 1074 auto vecType = VectorType::get(padOp.getType().getShape(), 1075 padOp.getType().getElementType()); 1076 unsigned vecRank = vecType.getRank(); 1077 unsigned tensorRank = insertOp.getType().getRank(); 1078 1079 // Check if sizes match: Insert the entire tensor into most minor dims. 1080 // (No permutations allowed.) 1081 SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1); 1082 expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end()); 1083 if (!llvm::all_of( 1084 llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) { 1085 return getConstantIntValue(std::get<0>(it)) == std::get<1>(it); 1086 })) 1087 return failure(); 1088 1089 // Insert the TransferReadOp and TransferWriteOp at the position of the 1090 // InsertSliceOp. 1091 rewriter.setInsertionPoint(insertOp); 1092 1093 // Generate TransferReadOp: Read entire source tensor and add high 1094 // padding. 1095 SmallVector<Value> readIndices( 1096 vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0)); 1097 auto read = rewriter.create<vector::TransferReadOp>( 1098 padOp.getLoc(), vecType, padOp.source(), readIndices, padValue); 1099 1100 // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at 1101 // specified offsets. Write is fully in-bounds because a InsertSliceOp's 1102 // source must fit into the destination at the specified offsets. 1103 auto writeIndices = 1104 ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets()); 1105 SmallVector<bool> inBounds(vecRank, true); 1106 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 1107 insertOp, read, insertOp.dest(), writeIndices, 1108 ArrayRef<bool>{inBounds}); 1109 1110 return success(); 1111 } 1112 }; 1113 1114 void mlir::linalg::populatePadOpVectorizationPatterns( 1115 RewritePatternSet &patterns, PatternBenefit baseBenefit) { 1116 patterns.add<GenericPadOpVectorizationPattern>(patterns.getContext(), 1117 baseBenefit); 1118 // Try these specialized patterns first before resorting to the generic one. 1119 patterns.add<PadOpVectorizationWithTransferReadPattern, 1120 PadOpVectorizationWithTransferWritePattern, 1121 PadOpVectorizationWithInsertSlicePattern>( 1122 patterns.getContext(), baseBenefit.getBenefit() + 1); 1123 } 1124 1125 //----------------------------------------------------------------------------// 1126 // Forwarding patterns 1127 //----------------------------------------------------------------------------// 1128 1129 /// Check whether there is any interleaved use of any `values` between 1130 /// `firstOp` and `secondOp`. Conservatively return `true` if any op or value 1131 /// is in a different block. 1132 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 1133 ValueRange values) { 1134 if (firstOp->getBlock() != secondOp->getBlock() || 1135 !firstOp->isBeforeInBlock(secondOp)) { 1136 LDBG("interleavedUses precondition failed, firstOp: " 1137 << *firstOp << ", second op: " << *secondOp); 1138 return true; 1139 } 1140 for (auto v : values) { 1141 for (auto &u : v.getUses()) { 1142 Operation *owner = u.getOwner(); 1143 if (owner == firstOp || owner == secondOp) 1144 continue; 1145 // TODO: this is too conservative, use dominance info in the future. 1146 if (owner->getBlock() == firstOp->getBlock() && 1147 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 1148 continue; 1149 LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp 1150 << ", second op: " << *secondOp); 1151 return true; 1152 } 1153 } 1154 return false; 1155 } 1156 1157 /// Return the unique subview use of `v` if it is indeed unique, null 1158 /// otherwise. 1159 static memref::SubViewOp getSubViewUseIfUnique(Value v) { 1160 memref::SubViewOp subViewOp; 1161 for (auto &u : v.getUses()) { 1162 if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) { 1163 if (subViewOp) 1164 return memref::SubViewOp(); 1165 subViewOp = newSubViewOp; 1166 } 1167 } 1168 return subViewOp; 1169 } 1170 1171 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 1172 /// when available. 1173 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 1174 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 1175 1176 // TODO: support mask. 1177 if (xferOp.getMask()) 1178 return failure(); 1179 1180 // Transfer into `view`. 1181 Value viewOrAlloc = xferOp.getSource(); 1182 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1183 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1184 return failure(); 1185 1186 LDBG(viewOrAlloc); 1187 1188 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1189 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1190 if (!subViewOp) 1191 return failure(); 1192 Value subView = subViewOp.getResult(); 1193 LDBG("with subView " << subView); 1194 1195 // Find the copy into `subView` without interleaved uses. 1196 memref::CopyOp copyOp; 1197 for (auto &u : subView.getUses()) { 1198 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) { 1199 assert(newCopyOp.target().getType().isa<MemRefType>()); 1200 if (newCopyOp.target() != subView) 1201 continue; 1202 LDBG("copy candidate " << *newCopyOp); 1203 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 1204 continue; 1205 copyOp = newCopyOp; 1206 break; 1207 } 1208 } 1209 if (!copyOp) 1210 return failure(); 1211 LDBG("with copy " << *copyOp); 1212 1213 // Find the fill into `viewOrAlloc` without interleaved uses before the 1214 // copy. 1215 FillOp maybeFillOp; 1216 for (auto &u : viewOrAlloc.getUses()) { 1217 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 1218 assert(newFillOp.output().getType().isa<MemRefType>()); 1219 if (newFillOp.output() != viewOrAlloc) 1220 continue; 1221 LDBG("fill candidate " << *newFillOp); 1222 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 1223 continue; 1224 maybeFillOp = newFillOp; 1225 break; 1226 } 1227 } 1228 // Ensure padding matches. 1229 if (maybeFillOp && xferOp.getPadding() != maybeFillOp.value()) 1230 return failure(); 1231 if (maybeFillOp) 1232 LDBG("with maybeFillOp " << *maybeFillOp); 1233 1234 // `in` is the subview that memref.copy reads. Replace it. 1235 Value in = copyOp.source(); 1236 1237 // memref.copy + linalg.fill can be used to create a padded local buffer. 1238 // The `masked` attribute is only valid on this padded buffer. 1239 // When forwarding to vector.transfer_read, the attribute must be reset 1240 // conservatively. 1241 Value res = rewriter.create<vector::TransferReadOp>( 1242 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.getIndices(), 1243 xferOp.getPermutationMapAttr(), xferOp.getPadding(), xferOp.getMask(), 1244 // in_bounds is explicitly reset 1245 /*inBoundsAttr=*/ArrayAttr()); 1246 1247 if (maybeFillOp) 1248 rewriter.eraseOp(maybeFillOp); 1249 rewriter.eraseOp(copyOp); 1250 rewriter.replaceOp(xferOp, res); 1251 1252 return success(); 1253 } 1254 1255 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 1256 /// when available. 1257 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 1258 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 1259 // TODO: support mask. 1260 if (xferOp.getMask()) 1261 return failure(); 1262 1263 // Transfer into `viewOrAlloc`. 1264 Value viewOrAlloc = xferOp.getSource(); 1265 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1266 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1267 return failure(); 1268 1269 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1270 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1271 if (!subViewOp) 1272 return failure(); 1273 Value subView = subViewOp.getResult(); 1274 1275 // Find the copy from `subView` without interleaved uses. 1276 memref::CopyOp copyOp; 1277 for (auto &u : subViewOp.getResult().getUses()) { 1278 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) { 1279 if (newCopyOp.source() != subView) 1280 continue; 1281 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 1282 continue; 1283 copyOp = newCopyOp; 1284 break; 1285 } 1286 } 1287 if (!copyOp) 1288 return failure(); 1289 1290 // `out` is the subview copied into that we replace. 1291 assert(copyOp.target().getType().isa<MemRefType>()); 1292 Value out = copyOp.target(); 1293 1294 // Forward vector.transfer into copy. 1295 // memref.copy + linalg.fill can be used to create a padded local buffer. 1296 // The `masked` attribute is only valid on this padded buffer. 1297 // When forwarding to vector.transfer_write, the attribute must be reset 1298 // conservatively. 1299 rewriter.create<vector::TransferWriteOp>( 1300 xferOp.getLoc(), xferOp.getVector(), out, xferOp.getIndices(), 1301 xferOp.getPermutationMapAttr(), xferOp.getMask(), 1302 // in_bounds is explicitly reset 1303 /*inBoundsAttr=*/ArrayAttr()); 1304 1305 rewriter.eraseOp(copyOp); 1306 rewriter.eraseOp(xferOp); 1307 1308 return success(); 1309 } 1310 1311 //===----------------------------------------------------------------------===// 1312 // Convolution vectorization patterns 1313 //===----------------------------------------------------------------------===// 1314 1315 template <int N> 1316 static void bindShapeDims(ShapedType shapedType) {} 1317 1318 template <int N, typename IntTy, typename... IntTy2> 1319 static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) { 1320 val = shapedType.getShape()[N]; 1321 bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...); 1322 } 1323 1324 /// Bind a pack of int& to the leading dimensions of shapedType.getShape(). 1325 template <typename... IntTy> 1326 static void bindShapeDims(ShapedType shapedType, IntTy &...vals) { 1327 bindShapeDims<0>(shapedType, vals...); 1328 } 1329 1330 namespace { 1331 /// Generate a vector implementation for either: 1332 /// ``` 1333 /// Op def: ( n, w, c, kw, f ) 1334 /// Iters: ({Par(), Par(), Par(), Red(), Red()}) 1335 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1336 /// ``` 1337 /// kw is unrolled, w is unrolled iff dilationW > 1. 1338 /// 1339 /// or 1340 /// 1341 /// ``` 1342 /// Op def: ( n, w, c, kw ) 1343 /// Iters: ({Par(), Par(), Par(), Red()}) 1344 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1345 /// ``` 1346 /// kw is unrolled, w is unrolled iff dilationW > 1. 1347 struct Conv1DNwcGenerator : public StructuredGenerator<LinalgOp> { 1348 Conv1DNwcGenerator(OpBuilder &builder, LinalgOp linalgOp, int strideW, 1349 int dilationW) 1350 : StructuredGenerator<LinalgOp>(builder, linalgOp), strideW(strideW), 1351 dilationW(dilationW) { 1352 // Determine whether `linalgOp` can be generated with this generator 1353 if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1) 1354 return; 1355 lhsShaped = linalgOp.inputs()[0]; 1356 rhsShaped = linalgOp.inputs()[1]; 1357 resShaped = linalgOp.outputs()[0]; 1358 lhsShapedType = lhsShaped.getType().dyn_cast<ShapedType>(); 1359 rhsShapedType = rhsShaped.getType().dyn_cast<ShapedType>(); 1360 resShapedType = resShaped.getType().dyn_cast<ShapedType>(); 1361 if (!lhsShapedType || !rhsShapedType || !resShapedType) 1362 return; 1363 if (lhsShapedType.getRank() != 3 || 1364 (rhsShapedType.getRank() != 2 && rhsShapedType.getRank() != 3) || 1365 resShapedType.getRank() != 3) 1366 return; 1367 1368 // Check for reduction `add` preceded by `mul`. 1369 Operation *reduceOp = matchLinalgReduction(linalgOp.getOutputOperand(0)); 1370 if (!reduceOp) 1371 return; 1372 llvm::Optional<vector::CombiningKind> maybeKind; 1373 maybeKind = getCombinerOpKind(reduceOp); 1374 if (!maybeKind || *maybeKind != vector::CombiningKind::ADD) 1375 return; 1376 maybeKind = getCombinerOpKind(&(linalgOp->getRegion(0).front().front())); 1377 if (!maybeKind || *maybeKind != vector::CombiningKind::MUL) 1378 return; 1379 1380 // The op is now known to be valid. 1381 valid = true; 1382 } 1383 1384 /// Generate a vector implementation for: 1385 /// ``` 1386 /// Op def: ( n, w, c, kw, f ) 1387 /// Iters: ({Par(), Par(), Par(), Red(), Red()}) 1388 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1389 /// ``` 1390 /// kw is always unrolled. 1391 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is 1392 /// > 1. 1393 FailureOr<Operation *> conv() { 1394 if (!valid) 1395 return failure(); 1396 1397 int64_t nSize, wSize, cSize, kwSize, fSize; 1398 // kernel{kw, c, f} 1399 bindShapeDims(rhsShapedType, kwSize, cSize, fSize); 1400 // out{n, w, f} 1401 bindShapeDims(resShapedType, nSize, wSize); 1402 1403 vector::TransferWriteOp write; 1404 Value zero = builder.create<arith::ConstantIndexOp>(loc, 0); 1405 1406 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1. 1407 // When strideW == 1, we can batch the contiguous loads and avoid 1408 // unrolling 1409 int64_t wSizeStep = strideW == 1 ? wSize : 1; 1410 1411 Type lhsEltType = lhsShapedType.getElementType(); 1412 Type rhsEltType = rhsShapedType.getElementType(); 1413 Type resEltType = resShapedType.getElementType(); 1414 VectorType lhsType = VectorType::get( 1415 {nSize, 1416 // iw = ow * sw + kw * dw - 1 1417 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14) 1418 // Perform the proper inclusive -> exclusive -> inclusive. 1419 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1, 1420 cSize}, 1421 lhsEltType); 1422 VectorType rhsType = VectorType::get({kwSize, cSize, fSize}, rhsEltType); 1423 VectorType resType = VectorType::get({nSize, wSize, fSize}, resEltType); 1424 1425 // Read lhs slice of size {w * strideW + kw * dilationW, c, f} @ [0, 0, 1426 // 0]. 1427 Value lhs = builder.create<vector::TransferReadOp>( 1428 loc, lhsType, lhsShaped, ValueRange{zero, zero, zero}); 1429 // Read rhs slice of size {kw, c, f} @ [0, 0, 0]. 1430 Value rhs = builder.create<vector::TransferReadOp>( 1431 loc, rhsType, rhsShaped, ValueRange{zero, zero, zero}); 1432 // Read res slice of size {n, w, f} @ [0, 0, 0]. 1433 Value res = builder.create<vector::TransferReadOp>( 1434 loc, resType, resShaped, ValueRange{zero, zero, zero}); 1435 1436 //===------------------------------------------------------------------===// 1437 // Begin vector-only rewrite part 1438 //===------------------------------------------------------------------===// 1439 // Unroll along kw and read slices of lhs and rhs. 1440 SmallVector<Value> lhsVals, rhsVals, resVals; 1441 // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0]. 1442 for (int64_t kw = 0; kw < kwSize; ++kw) { 1443 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1444 lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1445 loc, lhs, 1446 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0}, 1447 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1448 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1449 } 1450 } 1451 // Extract rhs slice of size {c, f} @ [kw]. 1452 for (int64_t kw = 0; kw < kwSize; ++kw) { 1453 rhsVals.push_back(builder.create<vector::ExtractOp>( 1454 loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw})); 1455 } 1456 // Extract res slice: {n, wSizeStep, f} @ [0, w, 0]. 1457 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1458 resVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1459 loc, res, 1460 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1461 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, fSize}, 1462 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1463 } 1464 1465 auto linearIndex = [&](int64_t kw, int64_t w) { 1466 return kw * (wSize / wSizeStep) + w; 1467 }; 1468 1469 // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f} 1470 for (int64_t kw = 0; kw < kwSize; ++kw) { 1471 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1472 resVals[w] = conv1dSliceAsContraction( 1473 builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]); 1474 } 1475 } 1476 1477 // Write back res slice: {n, wSizeStep, f} @ [0, w, 0]. 1478 // This does not depend on kw. 1479 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1480 res = builder.create<vector::InsertStridedSliceOp>( 1481 loc, resVals[w], res, 1482 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1483 /*strides=*/ArrayRef<int64_t>{1, 1, 1}); 1484 } 1485 //===------------------------------------------------------------------===// 1486 // End vector-only rewrite part 1487 //===------------------------------------------------------------------===// 1488 1489 // Write back res slice of size {n, w, f} @ [0, 0, 0]. 1490 return builder 1491 .create<vector::TransferWriteOp>(loc, res, resShaped, 1492 ValueRange{zero, zero, zero}) 1493 .getOperation(); 1494 } 1495 1496 // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f} 1497 Value conv1dSliceAsContraction(OpBuilder &b, Location loc, Value lhs, 1498 Value rhs, Value res) { 1499 StringRef par = Par().strRef, red = Red().strRef; 1500 AffineExpr n, w, f, c; 1501 bindDims(ctx, n, w, f, c); 1502 return builder.create<vector::ContractionOp>( 1503 loc, lhs, rhs, res, 1504 /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}}, 1505 /*iteratorTypes=*/ArrayRef<StringRef>{par, par, par, red}); 1506 } 1507 1508 /// Generate a vector implementation for: 1509 /// ``` 1510 /// Op def: ( n, w, c, kw) 1511 /// Iters: ({Par(), Par(), Par(), Red()}) 1512 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1513 /// ``` 1514 /// kw is always unrolled. 1515 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is 1516 /// > 1. 1517 FailureOr<Operation *> depthwiseConv() { 1518 if (!valid) 1519 return failure(); 1520 1521 int64_t nSize, wSize, cSize, kwSize; 1522 // kernel{kw, c} 1523 bindShapeDims(rhsShapedType, kwSize, cSize); 1524 // out{n, w, c} 1525 bindShapeDims(resShapedType, nSize, wSize); 1526 1527 vector::TransferWriteOp write; 1528 Value zero = builder.create<arith::ConstantIndexOp>(loc, 0); 1529 1530 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1. 1531 // When strideW == 1, we can batch the contiguous loads and avoid 1532 // unrolling 1533 int64_t wSizeStep = strideW == 1 ? wSize : 1; 1534 1535 Type lhsEltType = lhsShapedType.getElementType(); 1536 Type rhsEltType = rhsShapedType.getElementType(); 1537 Type resEltType = resShapedType.getElementType(); 1538 VectorType lhsType = VectorType::get( 1539 {nSize, 1540 // iw = ow * sw + kw * dw - 1 1541 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14) 1542 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1, 1543 cSize}, 1544 lhsEltType); 1545 VectorType rhsType = VectorType::get({kwSize, cSize}, rhsEltType); 1546 VectorType resType = VectorType::get({nSize, wSize, cSize}, resEltType); 1547 1548 // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0, 1549 // 0]. 1550 Value lhs = builder.create<vector::TransferReadOp>( 1551 loc, lhsType, lhsShaped, ValueRange{zero, zero, zero}); 1552 // Read rhs slice of size {kw, c} @ [0, 0]. 1553 Value rhs = builder.create<vector::TransferReadOp>(loc, rhsType, rhsShaped, 1554 ValueRange{zero, zero}); 1555 // Read res slice of size {n, w, c} @ [0, 0, 0]. 1556 Value res = builder.create<vector::TransferReadOp>( 1557 loc, resType, resShaped, ValueRange{zero, zero, zero}); 1558 1559 //===------------------------------------------------------------------===// 1560 // Begin vector-only rewrite part 1561 //===------------------------------------------------------------------===// 1562 // Unroll along kw and read slices of lhs and rhs. 1563 SmallVector<Value> lhsVals, rhsVals, resVals; 1564 // Extract lhs slice of size {n, wSizeStep, c} 1565 // @ [0, sw * w + dw * kw, 0]. 1566 for (int64_t kw = 0; kw < kwSize; ++kw) { 1567 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1568 lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1569 loc, lhs, 1570 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0}, 1571 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1572 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1573 } 1574 } 1575 // Extract rhs slice of size {c} @ [kw]. 1576 for (int64_t kw = 0; kw < kwSize; ++kw) { 1577 rhsVals.push_back(builder.create<vector::ExtractOp>( 1578 loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw})); 1579 } 1580 // Extract res slice: {n, wSizeStep, c} @ [0, w, 0]. 1581 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1582 resVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1583 loc, res, 1584 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1585 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1586 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1587 } 1588 1589 auto linearIndex = [&](int64_t kw, int64_t w) { 1590 return kw * (wSize / wSizeStep) + w; 1591 }; 1592 1593 // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c} 1594 for (int64_t kw = 0; kw < kwSize; ++kw) { 1595 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1596 resVals[w] = depthwiseConv1dSliceAsFma( 1597 builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]); 1598 } 1599 } 1600 1601 // Write back res slice: {n, wSizeStep, c} @ [0, w, 0]. 1602 // This does not depend on kw. 1603 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1604 res = builder.create<vector::InsertStridedSliceOp>( 1605 loc, resVals[w], res, 1606 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1607 /*strides=*/ArrayRef<int64_t>{1, 1, 1}); 1608 } 1609 //===------------------------------------------------------------------===// 1610 // End vector-only rewrite part 1611 //===------------------------------------------------------------------===// 1612 1613 // Write back res slice of size {n, w, c} @ [0, 0, 0]. 1614 return builder 1615 .create<vector::TransferWriteOp>(loc, res, resShaped, 1616 ValueRange{zero, zero, zero}) 1617 .getOperation(); 1618 } 1619 1620 /// Lower lhs{n, w, c} * rhs{c} -> res{n, w, c} to fma. 1621 Value depthwiseConv1dSliceAsFma(OpBuilder &b, Location loc, Value lhs, 1622 Value rhs, Value res) { 1623 Value bcast = builder.create<vector::BroadcastOp>(loc, res.getType(), rhs); 1624 return b.create<vector::FMAOp>(loc, lhs, bcast, res); 1625 } 1626 1627 /// Entry point that transposes into the common form: 1628 /// {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1629 FailureOr<Operation *> generateConv() { 1630 AffineExpr n, w, f, kw, c; 1631 bindDims(ctx, n, w, f, kw, c); 1632 if (!iters({Par(), Par(), Par(), Red(), Red()})) 1633 return failure(); 1634 1635 // No transposition needed. 1636 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c}, 1637 /*rhsIndex*/ {kw, c, f}, 1638 /*resIndex*/ {n, w, f}})) 1639 return conv(); 1640 return failure(); 1641 } 1642 1643 /// Entry point that transposes into the common form: 1644 /// {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1645 FailureOr<Operation *> generateDilatedConv() { 1646 AffineExpr n, w, c, kw; 1647 bindDims(ctx, n, w, c, kw); 1648 if (!iters({Par(), Par(), Par(), Red()})) 1649 return failure(); 1650 1651 // No transposition needed. 1652 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c}, 1653 /*rhsIndex*/ {kw, c}, 1654 /*resIndex*/ {n, w, c}})) 1655 return depthwiseConv(); 1656 return failure(); 1657 } 1658 1659 private: 1660 bool valid = false; 1661 int strideW, dilationW; 1662 Value lhsShaped, rhsShaped, resShaped; 1663 ShapedType lhsShapedType, rhsShapedType, resShapedType; 1664 }; 1665 } // namespace 1666 1667 /// Helper function to vectorize a LinalgOp with convolution semantics. 1668 // TODO: extend the generic vectorization to support windows and drop this. 1669 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, LinalgOp op) { 1670 // The ConvolutionOpInterface gives us guarantees of existence for 1671 // strides/dilations. However, we do not need to rely on those, we can simply 1672 // use them if present, otherwise use the default and let the generic conv. 1673 // matcher in the ConvGenerator succeed or fail. 1674 auto strides = op->getAttrOfType<DenseIntElementsAttr>("strides"); 1675 auto dilations = op->getAttrOfType<DenseIntElementsAttr>("dilations"); 1676 auto stride = strides ? *strides.getValues<uint64_t>().begin() : 1; 1677 auto dilation = dilations ? *dilations.getValues<uint64_t>().begin() : 1; 1678 Conv1DNwcGenerator e(b, op, stride, dilation); 1679 auto res = e.generateConv(); 1680 if (succeeded(res)) 1681 return res; 1682 return e.generateDilatedConv(); 1683 } 1684 1685 struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> { 1686 using OpInterfaceRewritePattern::OpInterfaceRewritePattern; 1687 1688 LogicalResult matchAndRewrite(LinalgOp op, 1689 PatternRewriter &rewriter) const override { 1690 FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op); 1691 if (failed(resultOrFail)) 1692 return failure(); 1693 Operation *newOp = *resultOrFail; 1694 if (newOp->getNumResults() == 0) { 1695 rewriter.eraseOp(op.getOperation()); 1696 return success(); 1697 } 1698 assert(newOp->getNumResults() == 1 && "expected single result"); 1699 rewriter.replaceOp(op.getOperation(), newOp->getResult(0)); 1700 return success(); 1701 } 1702 }; 1703 1704 void mlir::linalg::populateConvolutionVectorizationPatterns( 1705 RewritePatternSet &patterns, PatternBenefit benefit) { 1706 patterns.add<VectorizeConvolution>(patterns.getContext(), benefit); 1707 } 1708