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