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