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