1 //===- Fusion.cpp - Implementation of linalg Fusion -----------------------===// 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 Fusion pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PassDetail.h" 14 #include "mlir/Dialect/Affine/IR/AffineOps.h" 15 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 18 #include "mlir/Dialect/Linalg/Passes.h" 19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 20 #include "mlir/Dialect/Linalg/Utils/Utils.h" 21 #include "mlir/Dialect/MemRef/IR/MemRef.h" 22 #include "mlir/Dialect/Tensor/IR/Tensor.h" 23 #include "mlir/IR/AffineExpr.h" 24 #include "mlir/IR/AffineMap.h" 25 #include "mlir/IR/Dominance.h" 26 #include "mlir/Support/LLVM.h" 27 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 28 #include "mlir/Transforms/RegionUtils.h" 29 #include "llvm/ADT/MapVector.h" 30 #include "llvm/ADT/ScopeExit.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 34 #include <set> 35 36 #define DEBUG_TYPE "linalg-fusion" 37 38 using namespace mlir; 39 using namespace mlir::linalg; 40 41 using llvm::dbgs; 42 43 /// Implements a simple high-level fusion pass on linalg structured operations. 44 /// 45 /// In each block, linalg ops are processed in reverse textual order. 46 /// Given a linalg op `O`, fusion occurs by: 47 /// 1. inspecting the linalg ops that write into the views read by `O`. There 48 /// are 2 cases: 49 /// a) buffer case: use the SSA value of the views and a simple alias 50 /// analysis on subview ops to determine producer-consumer dependences; 51 /// b) tensor case: use SSA use-def chains on extract_slice ops; 52 /// 2. greedily fuse the linalg ops that produce the subview/extract_slice. 53 /// 3. inspect the fused ops and determine whether they have other remaining 54 /// LinalgOp uses. If not, then erase the original producing linalg op. 55 /// 56 /// More advanced use cases, analyses as well as profitability heuristics are 57 /// left for future work. 58 59 struct ShapeDimension { 60 Value shape; 61 unsigned dimension; 62 }; 63 64 // Given an `op`, returns the first (`shape`, `dimension`) pair that identifies 65 // the loop range at `loopDepth`. The semantics of the loopToOperandRangesMaps 66 // guarantees at least one such dimension is found. If multiple candidates exist 67 // they must agree by construction (i.e. have the same size) and we just return 68 // the first one. 69 static ShapeDimension 70 getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth, 71 bool fromSubViewOpOnly = false) { 72 // Iterate over the inputs and outputs in order. 73 // Extract the subranges from the linearized ranges. 74 for (OpOperand *opOperand : op.getInputAndOutputOperands()) { 75 // The method `getRangeFromOperandShape` requires using SubViewOp or 76 // ExtractSliceOps. If the value isn't defined from there continue. 77 // todo: The method should be adapted to get the values from 78 // `ViewInterface`. The interface needs a `getOrCreateRanges` method which 79 // currently returns a `linalg.range`. The fix here is to move this op to 80 // `std` dialect and add the method to `ViewInterface`. 81 if (fromSubViewOpOnly && 82 !isa_and_nonnull<memref::SubViewOp, tensor::ExtractSliceOp>( 83 opOperand->get().getDefiningOp())) 84 continue; 85 86 AffineMap map = op.getTiedIndexingMap(opOperand); 87 LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange I/O idx: " 88 << opOperand->getOperandNumber() << "\n"); 89 LLVM_DEBUG(llvm::dbgs() 90 << "getShapeDefiningLoopRange map: " << map << "\n"); 91 SmallVector<Value, 8> shapeRanges(map.getNumResults(), nullptr); 92 for (auto en : llvm::enumerate(map.getResults())) { 93 auto dimExpr = en.value().dyn_cast<AffineDimExpr>(); 94 if (!dimExpr) 95 continue; 96 if (loopDepth == en.value().cast<AffineDimExpr>().getPosition()) { 97 LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange loopDepth: " 98 << loopDepth << "\n"); 99 LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange shape: " 100 << opOperand->get() << "\n"); 101 return ShapeDimension{opOperand->get(), 102 static_cast<unsigned>(en.index())}; 103 } 104 } 105 } 106 llvm_unreachable("Expect to be able to extract a shape defining loop range"); 107 } 108 109 // Return tiled operands for the fused producer op. When fusing into 110 // `linalg.tiled_loop` one has to update `input` and `output` arguments of the 111 // loop correspondingly. 112 // Each input tensor of the producer op has to be added to `inputs` of the 113 // `tiled_loop` if it is not present there already. Each output tensor has to 114 // be added either to `inputs` or to `outputs` of `linalg.tiled_loop` depending 115 // on whether the correponding result is an input or an output to the loop. 116 // 117 // NOTE: This way of updating the arguments of the `tiled_loop` assumes that the 118 // intermediate result is not used by any other operation but the consumer. A 119 // more generic way is to append all missing output tensors of the producer to 120 // the tiled loop outputs and hence modify the number of the results, since we 121 // would need to add the intermediate results to `linalg.yield`. After that a 122 // canonicalization pass would move the unused output args of the `tiled_loop` 123 // to the `input` section. 124 static SmallVector<Value> getTiledOperands(OpBuilder &b, LinalgOp producer) { 125 auto tiledLoop = dyn_cast<TiledLoopOp>(b.getBlock()->getParentOp()); 126 if (!tiledLoop) 127 return producer.getInputAndOutputOperands(); 128 129 SmallVector<Value> tiledOperands; 130 assert(producer.hasTensorSemantics() && 131 "only fusion on tensors is currently supported for TiledLinalgOp"); 132 133 for (OpOperand *producerInput : producer.getInputOperands()) { 134 OpOperand *addedInput = tiledLoop.findInputOperand(producerInput->get()); 135 if (addedInput == nullptr) 136 addedInput = &tiledLoop.appendInputOperand(b, producerInput->get()); 137 BlockArgument addedBlockArg = tiledLoop.getTiedBlockArgument(*addedInput); 138 tiledOperands.push_back(addedBlockArg); 139 } 140 for (OpOperand *producerOutput : producer.getOutputOperands()) { 141 OpResult result = producer.getTiedOpResult(producerOutput); 142 OpOperand *resultInputOperand = tiledLoop.findInputOperand(result); 143 OpOperand *resultOutputOperand = tiledLoop.findOutputOperand(result); 144 assert((resultInputOperand != nullptr) ^ (resultOutputOperand != nullptr) && 145 "The result should be present in `input` or `output` args of " 146 "`tiled_loop"); 147 148 bool isInput = resultInputOperand; 149 int opNumber = isInput ? resultInputOperand->getOperandNumber() 150 : resultOutputOperand->getOperandNumber(); 151 152 OpOperand *addedOutput = tiledLoop.findOutputOperand(producerOutput->get()); 153 if (addedOutput == nullptr) 154 addedOutput = 155 isInput ? &tiledLoop.appendInputOperand(b, producerOutput->get()) 156 : &tiledLoop.appendOutputOperand(b, producerOutput->get()); 157 158 OpOperand &resultOperand = tiledLoop->getOpOperand(opNumber); 159 auto addedBlockArg = tiledLoop.getTiedBlockArgument(*addedOutput); 160 auto resultOperandBlockArg = tiledLoop.getTiedBlockArgument(resultOperand); 161 resultOperandBlockArg.replaceAllUsesWith(addedBlockArg); 162 tiledLoop.eraseOperand(b, resultOperand); 163 tiledOperands.push_back(addedBlockArg); 164 } 165 return tiledOperands; 166 } 167 168 /// Fuses the producer by cloning the `producer`. The `fusedLoopsAndRanges` 169 /// provides the loop range information for the fused loops. The rest are 170 /// obtained from the producer itself, since they are not tiled + fused. 171 static LinalgOp fuse(OpBuilder &b, LinalgOp producer, 172 const DenseMap<unsigned, Range> &fusedLoopsAndRanges) { 173 SmallVector<Value, 8> ivs, tileSizes, sizeBounds; 174 SmallVector<Range, 8> loopRanges; 175 Location loc = producer.getLoc(); 176 auto zero = b.create<ConstantIndexOp>(loc, 0); 177 auto one = b.create<ConstantIndexOp>(loc, 1); 178 179 for (unsigned i = 0, e = producer.getNumLoops(); i < e; ++i) { 180 auto it = fusedLoopsAndRanges.find(i); 181 if (it != fusedLoopsAndRanges.end()) { 182 ivs.push_back(it->second.offset); 183 tileSizes.push_back(it->second.size); 184 sizeBounds.push_back(nullptr); 185 loopRanges.push_back(it->second); 186 LLVM_DEBUG(llvm::dbgs() << "tiled loop#" << i << " with LoopRange " 187 << loopRanges.back() << "\n"); 188 } else { 189 auto shapeDim = getShapeDefiningLoopRange(producer, i); 190 Value dim = b.createOrFold<memref::DimOp>(loc, shapeDim.shape, 191 shapeDim.dimension); 192 tileSizes.push_back(zero); 193 sizeBounds.push_back(dim); 194 loopRanges.push_back(Range{zero, dim, one}); 195 LLVM_DEBUG(llvm::dbgs() << "full loop#" << i << " with LoopRange " 196 << loopRanges.back() << "\n"); 197 } 198 } 199 200 SmallVector<Value, 8> clonedShapes; 201 clonedShapes.reserve(producer.getNumInputsAndOutputs()); 202 203 // Compute subranges for all tensor input/output operands. 204 clonedShapes.append(makeTiledShapes(b, loc, producer, 205 getTiledOperands(b, producer), ivs, 206 tileSizes, sizeBounds)); 207 208 // Append the other operands. 209 auto operands = producer.getAssumedNonShapedOperands(); 210 clonedShapes.append(operands.begin(), operands.end()); 211 212 // Iterate over the results in order. 213 // Extract the subtensor type from the linearized range. 214 // Since we do not enforce any canonicalizations on the fly, this is always 215 // fully dynamic at construction time. 216 SmallVector<Type, 4> resultTypes; 217 resultTypes.reserve(producer->getNumResults()); 218 for (RankedTensorType t : producer.getOutputTensorTypes()) { 219 unsigned rank = t.getRank(); 220 SmallVector<int64_t, 4> staticOffsetsVector( 221 rank, ShapedType::kDynamicStrideOrOffset); 222 SmallVector<int64_t, 4> staticSizesVector(rank, ShapedType::kDynamicSize); 223 SmallVector<int64_t, 4> staticStridesVector( 224 rank, ShapedType::kDynamicStrideOrOffset); 225 resultTypes.push_back(tensor::ExtractSliceOp::inferResultType( 226 t.cast<RankedTensorType>(), staticOffsetsVector, staticSizesVector, 227 staticStridesVector)); 228 } 229 230 Operation *clonedOp = producer.clone(b, loc, resultTypes, clonedShapes); 231 // When the producer has index semantics, we have to transform the indices of 232 // the producer according to the tiling of the consumer, i.e. offset them by 233 // the values computed in `loopRanges`. 234 if (producer.hasIndexSemantics()) { 235 assert(clonedOp->getNumRegions() == 1 && 236 clonedOp->getRegion(0).getBlocks().size() == 1 && 237 "expected producer to have one block."); 238 // Shift all indices by the tile offset. 239 Block &block = clonedOp->getRegion(0).front(); 240 for (IndexOp indexOp : block.getOps<IndexOp>()) { 241 OpBuilder::InsertionGuard g(b); 242 b.setInsertionPointAfter(indexOp); 243 AffineExpr index, offset; 244 bindDims(b.getContext(), index, offset); 245 AffineApplyOp applyOp = b.create<AffineApplyOp>( 246 indexOp.getLoc(), index + offset, 247 ValueRange{indexOp.getResult(), loopRanges[indexOp.dim()].offset}); 248 indexOp.getResult().replaceAllUsesExcept(applyOp, applyOp); 249 } 250 } 251 252 return clonedOp; 253 } 254 255 /// Get the loop range for a dimension `dim` based on the `shapedOperand`. It is 256 /// expected to be defined by a subview op or an extract_slice op. 257 static Range getRangeFromOperandShape(OpBuilder &b, Location loc, 258 Value shapedOperand, unsigned dim) { 259 Operation *shapeProducingOp = shapedOperand.getDefiningOp(); 260 if (auto subViewOp = dyn_cast<memref::SubViewOp>(shapeProducingOp)) 261 return subViewOp.getOrCreateRanges(b, loc)[dim]; 262 if (auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(shapeProducingOp)) 263 return sliceOp.getOrCreateRanges(b, loc)[dim]; 264 llvm_unreachable("SubviewOp or ExtractSliceOp expected"); 265 } 266 267 /// Fuses the producer into the loop immediately enclosing the consumer. 268 /// This is achieved by "recomputing" the producer at the time it 269 /// is needed just before the consumer. 270 static LinalgOp fuse(OpBuilder &b, LinalgOp producerOp, AffineMap producerMap, 271 OpOperand &consumerOpOperand) { 272 LLVM_DEBUG(llvm::dbgs() << "Producer map: " << producerMap << "\n"); 273 DenseMap<unsigned, Range> fusedLoopsAndRanges; 274 Value shapedOperand = consumerOpOperand.get(); 275 for (auto en : llvm::enumerate(producerMap.getResults())) { 276 unsigned posInProducerLoop = en.value().cast<AffineDimExpr>().getPosition(); 277 fusedLoopsAndRanges[posInProducerLoop] = getRangeFromOperandShape( 278 b, consumerOpOperand.getOwner()->getLoc(), shapedOperand, en.index()); 279 } 280 return fuse(b, producerOp, fusedLoopsAndRanges); 281 } 282 283 // Encode structural fusion safety preconditions. 284 // Some of these will be lifted in the future with better analysis. 285 static bool isStructurallyFusableProducer(LinalgOp producer, Value consumedView, 286 LinalgOp consumer) { 287 assert(producer.hasBufferSemantics() && 288 "expected linalg op with buffer semantics"); 289 assert(consumer.hasBufferSemantics() && 290 "expected linalg op with buffer semantics"); 291 if (producer.getNumOutputs() != 1) { 292 LLVM_DEBUG(llvm::dbgs() << "\nNot structurally fusable (multi-output)"); 293 return false; 294 } 295 // Only fuse when the producer block dominates. 296 DominanceInfo dom(producer.getOperation()); 297 if (!dom.dominates(producer->getBlock(), consumer->getBlock())) { 298 LLVM_DEBUG( 299 llvm::dbgs() 300 << "\nNot structurally fusable (producer block does not dominate)"); 301 return false; 302 } 303 return true; 304 } 305 306 bool mlir::linalg::isProducerLastWriteOfView(const LinalgDependenceGraph &graph, 307 LinalgOp consumer, 308 Value consumedView, 309 LinalgOp producer) { 310 assert(producer.hasBufferSemantics() && 311 "expected linalg op with buffer semantics"); 312 assert(consumer.hasBufferSemantics() && 313 "expected linalg op with buffer semantics"); 314 // Make some simple structural checks that alleviate the need for more 315 // complex analyses. 316 if (!isStructurallyFusableProducer(producer, consumedView, consumer)) { 317 LLVM_DEBUG(llvm::dbgs() << "\n***Not static last write due to structure:\t" 318 << *producer.getOperation()); 319 return false; 320 } 321 // Check for any interleaved write to consumedView. 322 if (!graph.findCoveringWrites(producer, consumer, consumedView).empty()) { 323 LLVM_DEBUG(llvm::dbgs() << "\n***Not fusable due to interleaved write:\t" 324 << *producer.getOperation()); 325 return false; 326 } 327 return true; 328 } 329 330 bool mlir::linalg::isFusableInto(const LinalgDependenceGraph &graph, 331 LinalgOp consumer, Value consumedView, 332 LinalgOp producer) { 333 assert(producer.hasBufferSemantics() && 334 "expected linalg op with buffer semantics"); 335 assert(consumer.hasBufferSemantics() && 336 "expected linalg op with buffer semantics"); 337 if (!isProducerLastWriteOfView(graph, consumer, consumedView, producer)) 338 return false; 339 // Check for any fusion-preventing dependence to any shape read/written that 340 // would violate dependences. 341 if (!graph.findCoveringDependences(producer, consumer).empty()) { 342 LLVM_DEBUG(llvm::dbgs() 343 << "\n***Not fusable due to an interleaved dependence:\t" 344 << *producer.getOperation()); 345 return false; 346 } 347 if (auto convOp = dyn_cast<linalg::ConvOp>(producer.getOperation())) { 348 // TODO: add a level of indirection to linalg.generic. 349 if (convOp.padding()) 350 return false; 351 } 352 if (auto convOp = dyn_cast<linalg::ConvOp>(consumer.getOperation())) { 353 // TODO: add a level of indirection to linalg.generic. 354 if (convOp.padding()) 355 return false; 356 } 357 return true; 358 } 359 360 /// For `consumer` with buffer semantics, find the Linalg operation on buffers 361 /// that is the last writer of `consumerOpOperand`. For now the fusable 362 /// dependence is returned as an instance of the `dependenceGraph`. 363 static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 364 findFusableProducer(OpOperand &consumerOpOperand, 365 const LinalgDependenceGraph &dependenceGraph) { 366 LLVM_DEBUG(llvm::dbgs() << "findFusableProducer for: " 367 << consumerOpOperand.get() << " @" 368 << consumerOpOperand.getOperandNumber() << " in " 369 << *consumerOpOperand.getOwner() << "\n"); 370 LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner()); 371 if (!consumerOp) 372 return {}; 373 374 // Only consider RAW and WAW atm. 375 for (auto depType : { 376 LinalgDependenceGraph::DependenceType::RAW, 377 LinalgDependenceGraph::DependenceType::WAW, 378 }) { 379 LLVM_DEBUG(llvm::dbgs() 380 << "Dependencies into: " << *consumerOp.getOperation() << "\n"); 381 for (auto dependence : llvm::make_filter_range( 382 dependenceGraph.getDependencesInto(consumerOp, depType), 383 [&](LinalgDependenceGraph::LinalgDependenceGraphElem elem) { 384 LLVM_DEBUG(llvm::dbgs() << "Inspect dependence btw: " 385 << elem.getIndexingValue() << " and " 386 << elem.getDependentValue() << "\n"); 387 Value v = elem.getIndexingValue(); 388 Optional<unsigned> operandNum = 389 elem.getIndexingOpViewOperandNum(); 390 return isa<LinalgOp>(elem.getDependentOp()) && 391 v == consumerOpOperand.get() && operandNum && 392 operandNum.getValue() == 393 consumerOpOperand.getOperandNumber(); 394 })) { 395 // Consumer consumes this view, `isStructurallyFusableProducer` also 396 // checks whether it is a strict subview of the producer view. 397 auto producer = cast<LinalgOp>(dependence.getDependentOp()); 398 LLVM_DEBUG(llvm::dbgs() 399 << "\n" 400 << LinalgDependenceGraph::getDependenceTypeStr(depType) 401 << "producer: " << *dependence.getDependentOp() 402 << " view: " << dependence.getDependentValue() << "\n"); 403 404 // If the producer and consumer have tensor semantics, the only dependence 405 // between them is through a RAW dependence and they are fusable by 406 // construction. For buffer semantics need additional checks. 407 if (producer.hasBufferSemantics() && consumerOp.hasBufferSemantics() && 408 isFusableInto(dependenceGraph, consumerOp, consumerOpOperand.get(), 409 producer)) 410 return dependence; 411 if (producer.hasTensorSemantics() && consumerOp.hasTensorSemantics()) { 412 assert(dependence.dependenceType == 413 LinalgDependenceGraph::DependenceType::RAW); 414 return dependence; 415 } 416 } 417 } 418 return {}; 419 } 420 421 Optional<FusionInfo> 422 mlir::linalg::fuseProducerOfBuffer(OpBuilder &b, OpOperand &consumerOpOperand, 423 const LinalgDependenceGraph &graph) { 424 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> fusableDependence = 425 findFusableProducer(consumerOpOperand, graph); 426 if (!fusableDependence) 427 return llvm::None; 428 429 LinalgOp producerOp = dyn_cast<LinalgOp>(fusableDependence->getDependentOp()); 430 if (!producerOp) 431 return llvm::None; 432 433 // If producer is already in the same block as consumer, we are done. 434 if (consumerOpOperand.get().getParentBlock() == 435 fusableDependence->getDependentValue().getParentBlock()) 436 return llvm::None; 437 438 Optional<AffineMap> producerMap = 439 fusableDependence->getDependentOpViewIndexingMap(); 440 if (!producerMap) 441 return llvm::None; 442 443 // Must be a subview or an extract_slice to guarantee there are loops we can 444 // fuse into. 445 auto subView = consumerOpOperand.get().getDefiningOp<memref::SubViewOp>(); 446 if (!subView) { 447 LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subview)"); 448 return llvm::None; 449 } 450 451 // Fuse `producer` just before `consumer`. 452 OpBuilder::InsertionGuard g(b); 453 b.setInsertionPoint(consumerOpOperand.getOwner()); 454 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " 455 << *consumerOpOperand.getOwner() << "\n"); 456 457 auto fusedProducer = fuse(b, producerOp, *producerMap, consumerOpOperand); 458 return FusionInfo{producerOp, fusedProducer}; 459 } 460 461 /// Walk back use-def chain through scf::For yields. 462 /// Sets `producer` and `outputIndex` if it finds a producer LinalgOp 463 464 // TODO(ravishankarm, ntv): This can be moved into the dependence graphs 465 // dependence tracking since the dependence tracking is similar to what is done 466 // w.r.t to buffers. 467 static void getProducerOfTensor(Value tensor, OpResult &opResult) { 468 if (!tensor.getType().isa<RankedTensorType>()) 469 return; 470 471 while (true) { 472 LLVM_DEBUG(llvm::dbgs() << "\ngetProducerOfTensor: " << tensor); 473 if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) { 474 opResult = tensor.cast<OpResult>(); 475 return; 476 } 477 if (auto sliceOp = tensor.getDefiningOp<tensor::ExtractSliceOp>()) { 478 tensor = sliceOp.source(); 479 continue; 480 } 481 if (auto blockArg = tensor.dyn_cast<BlockArgument>()) { 482 if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) { 483 tensor = *(forOp.getIterOperands().begin() + blockArg.getArgNumber()); 484 continue; 485 } 486 } 487 return; 488 } 489 } 490 491 Optional<FusionInfo> 492 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand) { 493 Value inputTensor = consumerOpOperand.get(); 494 OpResult producerOpResult; 495 getProducerOfTensor(inputTensor, producerOpResult); 496 if (!producerOpResult) { 497 LLVM_DEBUG(llvm::dbgs() << "\nUnable to find producer"); 498 return {}; 499 } 500 return fuseProducerOfTensor(b, producerOpResult, consumerOpOperand); 501 } 502 503 Optional<FusionInfo> 504 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpResult producerOpResult, 505 OpOperand &consumerOpOperand) { 506 auto producerOp = dyn_cast<LinalgOp>(producerOpResult.getOwner()); 507 if (!producerOp) 508 return llvm::None; 509 510 LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner()); 511 if (!consumerOp) 512 return llvm::None; 513 514 Value inputTensor = consumerOpOperand.get(); 515 516 // Must be an extract_slice op to guarantee there are loops we can fuse into. 517 auto sliceOp = inputTensor.getDefiningOp<tensor::ExtractSliceOp>(); 518 if (!sliceOp) { 519 LLVM_DEBUG(llvm::dbgs() 520 << "\nNot fusable, not an extract_slice op: " << inputTensor); 521 return {}; 522 } 523 524 // If producer is already in the same block as consumer, we are done. 525 if (consumerOpOperand.get().getParentBlock() == 526 producerOpResult.getParentBlock()) 527 return {}; 528 529 // Insert fused `producer` just before `consumer`. 530 OpBuilder::InsertionGuard g(b); 531 b.setInsertionPoint(consumerOp); 532 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumerOp << "\n"); 533 OpOperand *opOperand = 534 producerOp.getOutputOperand(producerOpResult.getResultNumber()); 535 LinalgOp fusedProducer = 536 fuse(b, producerOp, producerOp.getTiedIndexingMap(opOperand), 537 consumerOpOperand); 538 539 // Replace use. 540 // Canonicalizations are not guaranteed to have happened before constructing 541 // `fusedProducer`. In the tensor case this can result in temporary type 542 // mismatches. Insert a `tensor.cast` op to propagate the transformation 543 // invariant that types are compatible. 544 Value def = fusedProducer->getResult(producerOpResult.getResultNumber()); 545 Type consumerType = consumerOpOperand.get().getType(); 546 if (consumerType != def.getType()) 547 def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def); 548 consumerOpOperand.set(def); 549 return FusionInfo{cast<LinalgOp>(producerOpResult.getOwner()), fusedProducer}; 550 } 551 552 /// Prune all dimensions that are of reduction iterator type from `map`. 553 static AffineMap pruneReductionDimsFromMap(ArrayRef<Attribute> iteratorTypes, 554 AffineMap map) { 555 llvm::SmallDenseSet<unsigned> projectedDims; 556 for (auto attr : llvm::enumerate(iteratorTypes)) { 557 if (!isParallelIterator(attr.value())) 558 projectedDims.insert(attr.index()); 559 } 560 return getProjectedMap(map, projectedDims); 561 } 562 563 /// Returns the mapping from iterations in the consumer that write to the same 564 /// location as the iterations in the producer. To do so use 565 /// - indexing map of the fused view in the consumer : consumerIndexMap 566 /// - indexing map of the fused view in the producer : producerIndexMap 567 /// consumerLoopToProducerLoop = 568 /// inverse(producerIndexMap).compose(consumerIndexMap) 569 static Optional<AffineMap> getConsumerLoopToProducerLoopMap( 570 LinalgDependenceGraph::LinalgDependenceGraphElem dependence) { 571 auto producer = dyn_cast<LinalgOp>(dependence.getDependentOp()); 572 if (!producer) 573 return None; 574 575 Optional<AffineMap> producerIndexingMap = 576 dependence.getDependentOpViewIndexingMap(); 577 Optional<AffineMap> consumerIndexingMap = 578 dependence.getIndexingOpViewIndexingMap(); 579 if (!producerIndexingMap || !consumerIndexingMap) 580 return None; 581 582 AffineMap prunedProducerIndexingMap = pruneReductionDimsFromMap( 583 producer.iterator_types().getValue(), *producerIndexingMap); 584 if (!prunedProducerIndexingMap.isPermutation()) 585 return None; 586 587 if (consumerIndexingMap->getNumResults() != 588 prunedProducerIndexingMap.getNumResults()) 589 return None; 590 591 LLVM_DEBUG({ 592 llvm::dbgs() << "\t producerMap : "; 593 producerIndexingMap->print(llvm::dbgs()); 594 llvm::dbgs() << " pruned : "; 595 prunedProducerIndexingMap.print(llvm::dbgs()); 596 llvm::dbgs() << "\n"; 597 llvm::dbgs() << "\t consumerMap : "; 598 consumerIndexingMap->print(llvm::dbgs()); 599 llvm::dbgs() << "\n"; 600 }); 601 602 AffineMap invProducerIndexMap = inversePermutation(prunedProducerIndexingMap); 603 if (!invProducerIndexMap) 604 return None; 605 606 return invProducerIndexMap.compose(*consumerIndexingMap); 607 } 608 609 /// Given a projected permutation `map`, returns true if the map changes the 610 /// order in which the fused loop dimension appear. 611 static bool doesTransposeAccess(AffineMap map, 612 const std::set<unsigned> &fusableLoops) { 613 Optional<unsigned> lastFusableLoop; 614 for (unsigned pos : llvm::map_range(map.getResults(), [](AffineExpr expr) { 615 return expr.cast<AffineDimExpr>().getPosition(); 616 })) { 617 if (!fusableLoops.count(pos)) 618 continue; 619 if (!lastFusableLoop) { 620 lastFusableLoop = pos; 621 continue; 622 } 623 if (pos <= lastFusableLoop.getValue()) 624 return true; 625 lastFusableLoop = pos; 626 } 627 return false; 628 } 629 630 /// Returns the positions of the loop in `op` that can be tiled based on the 631 /// operations that are to be fused with it. For example, in a 632 /// 633 /// linalg.matmul ins(%a, %b : ...) outs(%c : ...) 634 /// 635 /// if the producer of %a needs to be fused with this op, only the `i` loop of 636 /// the matmul can be tiled while fusing. If producer of %a, and %b are to be 637 /// fused, then no loops can be tiled while fusing. The conditions used are: 638 /// 1. Only parallel loops can be used for tile + fuse. Find the number of 639 /// common outer parallel loops between the op and its producers being fused. 640 /// 2. Of the parallel loops only some can be fused. Only those loops can be 641 /// fused such where the fusable loops iteration space only touches one tile 642 /// of the fused operation. This is because the producer (which is writing 643 /// the fused subview) has update semantics. 644 /// 645 /// Since an inverse computation is needed, we need to consider the projection 646 /// of the producerIndexMap w.r.t the parallel loops. The actual fusable loops 647 /// are the dimensions of the consumerLoopToProducerLoop map that correspond to 648 /// parallel loops and appear in the result of the map 649 /// 650 /// Example 1: 651 /// linalg.fill(%c, %cst) 652 /// linalg.matmul ins(%a, %b) outs(%c) 653 /// Number of parallel loops : 2 654 /// producerIndexMap = affine_map<(i, j) ->(i , j)> 655 /// consumerIndexMap = affine_map<(i, j, k) -> (i, j)> 656 /// consumerLoopToProducerLoop = affine_map<(i, j, k) -> (i, j)> 657 /// Fused dimensions : i, j 658 /// 659 /// Example 2: 660 /// linalg.matmul ins(%a, %b) outs(%c) 661 /// linalg.generic {indexing_maps = [affine_map<(i, j) -> (j, i)>, ... 662 /// iterator_types = ["parallel", "parallel"]} 663 /// ins(%c) ... 664 /// 665 /// Number of parallel loops = 2: 666 /// producerIndexMap (projected to parallel loops) = 667 /// affine_map<(i, j) -> (i, j)> 668 /// consumerLoopToProducerLoop2 = affine_map<(i, j) -> (j, i)> 669 /// Fused dimensions : i, j 670 /// 671 /// Example 3: 672 /// linalg.copy(%s, %b) 673 /// linalg.matmul ins(%a, %b) outs(%c) 674 /// 675 /// Number of parallel loops = 2 676 /// produceIndexMap : affine_map<(i, j) -> (i, j)> 677 /// consumerLoopToProduceLoops = affine_map<(i, j, k) -> (k, j)> 678 /// submap with only parallel loops = affine_map<(i, j) -> (j)> 679 /// Fused dimensions : j 680 static std::set<unsigned> 681 collectFusableLoops(ArrayRef<LinalgOp> ops, 682 const FusableOpDependencesTy &fusableDependences) { 683 assert(!ops.empty()); 684 auto getNumOuterParallelLoops = [](LinalgOp linalgOp) { 685 return linalgOp.iterator_types() 686 .getValue() 687 .take_while([](Attribute attr) -> bool { 688 return attr.cast<StringAttr>().getValue() == 689 getParallelIteratorTypeName(); 690 }) 691 .size(); 692 }; 693 694 size_t numOuterParallelLoops = getNumOuterParallelLoops(ops.back()); 695 for (auto op : ops.drop_back()) { 696 numOuterParallelLoops = 697 std::min(numOuterParallelLoops, getNumOuterParallelLoops(op)); 698 } 699 700 std::set<unsigned> fusableLoops; 701 auto range = llvm::seq<unsigned>(0, numOuterParallelLoops); 702 fusableLoops.insert(range.begin(), range.end()); 703 704 for (auto op : reverse(ops)) { 705 for (auto dependence : fusableDependences.lookup(op)) { 706 LLVM_DEBUG({ 707 llvm::dbgs() << "\t fusable :"; 708 for (unsigned i : fusableLoops) 709 llvm::dbgs() << " " << i; 710 llvm::dbgs() << "\n"; 711 }); 712 713 Optional<AffineMap> consumerLoopToProducerLoop = 714 getConsumerLoopToProducerLoopMap(dependence); 715 if (!consumerLoopToProducerLoop) { 716 op.emitRemark("failed to get map from consumer loop to producer loop"); 717 return {}; 718 } 719 // todo: This condition is only an implementation limitation. When fusing 720 // the operation, if the accesses in the producer/consumer are transposes 721 // of each other, the loop bounds for the tiled producer can be 722 // manipulated accordingly. This requires some additional bookkeeping in 723 // the implementation of tile+fuse that is deferred to later. 724 if (doesTransposeAccess(*consumerLoopToProducerLoop, fusableLoops)) { 725 op.emitRemark("unhandled fusion when fusion requires permutation"); 726 return {}; 727 } 728 729 std::set<unsigned> candidates; 730 for (AffineExpr expr : consumerLoopToProducerLoop->getResults()) { 731 unsigned position = expr.cast<AffineDimExpr>().getPosition(); 732 if (fusableLoops.count(position)) 733 candidates.insert(position); 734 } 735 LLVM_DEBUG({ 736 llvm::dbgs() << "\t candidates :"; 737 for (unsigned i : candidates) 738 llvm::dbgs() << " " << i; 739 llvm::dbgs() << "\n"; 740 }); 741 if (candidates.empty()) 742 return {}; 743 std::swap(candidates, fusableLoops); 744 } 745 } 746 747 return fusableLoops; 748 } 749 750 /// Find all dependences that are fusable. 751 FusableOpDependencesTy mlir::linalg::findAllFusableDependences( 752 ArrayRef<LinalgOp> ops, const LinalgDependenceGraph &dependenceGraph) { 753 FusableOpDependencesTy fusableDependences; 754 DenseMap<Operation *, SmallVector<AffineMap, 1>> fusedProducerIndexingMap; 755 for (LinalgOp op : reverse(ops)) { 756 for (OpOperand *opOperand : op.getInputAndOutputOperands()) { 757 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 758 fusableDependence = findFusableProducer(*opOperand, dependenceGraph); 759 if (!fusableDependence) 760 continue; 761 LinalgOp producerOp = 762 dyn_cast<LinalgOp>(fusableDependence->getDependentOp()); 763 if (!producerOp) 764 continue; 765 // Do not fuse dependences that are to operations not in the same basic 766 // block. This avoid moving fused operations across loops that might 767 // themselves carry dependency making the fusion illegal. 768 if (producerOp->getBlock() != op->getBlock()) 769 continue; 770 771 // Make sure that the indexing map of the view used for fusion in the 772 // producer is a projected permutation. 773 Optional<AffineMap> producerMap = 774 fusableDependence->getDependentOpViewIndexingMap(); 775 Optional<AffineMap> consumerMap = 776 fusableDependence->getIndexingOpViewIndexingMap(); 777 assert( 778 consumerMap && 779 "unable to find indexing map of operand/result of indexing OpView"); 780 fusedProducerIndexingMap[producerOp.getOperation()].push_back( 781 *consumerMap); 782 if (!producerMap || !producerMap->isProjectedPermutation() || 783 !consumerMap->isProjectedPermutation()) 784 continue; 785 786 fusableDependences[producerOp.getOperation()].push_back( 787 *fusableDependence); 788 } 789 } 790 // TODO: Currently fusion would not be legal if the fusable dependence is to 791 // the same producer but different indexing map in the consumer. Fix this, but 792 // in the meanwhile disallow such a fusion. 793 for (auto useIndexingMapsList : fusedProducerIndexingMap) { 794 AffineMap map1 = useIndexingMapsList.second.front(); 795 for (AffineMap map2 : 796 ArrayRef<AffineMap>(useIndexingMapsList.second).drop_front()) { 797 if (map1 != map2) { 798 fusableDependences.erase(useIndexingMapsList.first); 799 break; 800 } 801 } 802 } 803 return fusableDependences; 804 } 805 806 /// Tile the fused loops in the root operation, by setting the tile sizes for 807 /// all other loops to zero (those will be tiled later). 808 static Optional<TiledLinalgOp> 809 tileRootOperation(OpBuilder &b, LinalgOp op, ArrayRef<Value> tileSizeVector, 810 const LinalgTilingOptions &options, 811 const std::set<unsigned> &fusedLoops) { 812 SmallVector<Value, 4> tileSizes(tileSizeVector.begin(), tileSizeVector.end()); 813 auto zero = b.create<ConstantIndexOp>(op.getLoc(), 0); 814 for (unsigned i = 0, e = tileSizes.size(); i != e; ++i) 815 if (!fusedLoops.count(i)) 816 tileSizes[i] = zero; 817 LinalgTilingOptions tileFusedLoopsOptions = options; 818 tileFusedLoopsOptions.setTileSizes(tileSizes); 819 return tileLinalgOp(b, op, tileFusedLoopsOptions); 820 } 821 822 /// Fuse the operations in `fusionCandidates` with `tiledOp`. Latter is expected 823 /// to be a tiled operation such that it is valid to fuse all operations in 824 /// `fusionCandidates`, i.e. move the operation within the inter-tile loops of 825 /// `tiledOp`. 826 static SmallVector<LinalgOp, 1> 827 fuseOperations(OpBuilder &b, LinalgOp rootOp, TiledLinalgOp tiledLinalgOp, 828 ArrayRef<LinalgOp> fusionCandidates, 829 const FusableOpDependencesTy &fusableDependences, 830 const std::set<unsigned> &fusedLoops) { 831 LinalgOp tiledOp = tiledLinalgOp.op; 832 OpBuilder::InsertionGuard guard(b); 833 b.setInsertionPoint(tiledOp); 834 835 DenseMap<unsigned, Range> fusedLoopsAndRanges; 836 for (unsigned loop : fusedLoops) { 837 ShapeDimension shapeDim = getShapeDefiningLoopRange(tiledOp, loop, true); 838 fusedLoopsAndRanges[loop] = getRangeFromOperandShape( 839 b, tiledOp.getLoc(), shapeDim.shape, shapeDim.dimension); 840 } 841 842 SmallVector<LinalgOp, 1> fusedOps(fusionCandidates.size()); 843 DenseMap<Operation *, LinalgOp> origOpToFusedOp; 844 origOpToFusedOp[rootOp.getOperation()] = tiledOp; 845 for (auto candidate : enumerate(llvm::reverse(fusionCandidates))) { 846 LinalgOp origOp = candidate.value(); 847 LinalgOp fusedOp = fuse(b, origOp, fusedLoopsAndRanges); 848 origOpToFusedOp[origOp.getOperation()] = fusedOp; 849 fusedOps[fusionCandidates.size() - candidate.index() - 1] = fusedOp; 850 851 // Prepare the builder for the next insertion point. 852 auto guard = llvm::make_scope_exit([&]() { b.setInsertionPoint(fusedOp); }); 853 if (!origOp.hasTensorSemantics()) 854 continue; 855 856 // If the producer consumer operations are linalg operations on tensors, the 857 // dependence is due to value produced (as a return tensor) by the producer 858 // and used in the consumer. The returned value of the fused op needs to be 859 // made the operand of the tiled/fused consumer operation. By construction 860 // the value returned by the producer is the value used by the consumer. 861 for (auto &dependence : fusableDependences.lookup(origOp.getOperation())) { 862 if (dependence.dependenceType != 863 LinalgDependenceGraph::DependenceType::RAW) 864 continue; 865 866 unsigned resultIndex = 867 dependence.getDependentOpViewResultNum().getValue(); 868 LinalgOp consumer = origOpToFusedOp.lookup(dependence.getIndexingOp()); 869 if (!consumer) 870 continue; 871 872 Value replacementValue = fusedOp.getOperation()->getResult(resultIndex); 873 consumer.getOperation()->setOperand( 874 dependence.getIndexingOpViewOperandNum().getValue(), 875 replacementValue); 876 } 877 878 // At this point, all Linalg uses of the tensors produced by `origOp` have 879 // been replaced. However, there may still be "output tensor"-like uses 880 // coming from WAW dependencies. 881 // All these uses are iter_args of the outermost loop (TODO: add a check). 882 // Such iter_args uses serve 2 purposes: 883 // 1. give a shape to the output 884 // 2. encode destructive updates that may be inplaceable by bufferization. 885 // To keep the second type of information while letting the unfused op die 886 // unused, we need to forward the producer output operand. 887 if (auto forOp = dyn_cast<scf::ForOp>(tiledLinalgOp.loops.front())) { 888 for (auto &operand : forOp.getIterOpOperands()) { 889 if (auto opResult = operand.get().dyn_cast<OpResult>()) { 890 if (opResult.getOwner() == origOp) { 891 Value output = 892 origOp.getOutputOperand(opResult.getResultNumber())->get(); 893 assert(output.getType().isa<RankedTensorType>()); 894 operand.set(output); 895 } 896 } 897 } 898 } 899 } 900 return fusedOps; 901 } 902 903 static Optional<TiledAndFusedLinalgOps> 904 tileAndFuseLinalgOpsImpl(OpBuilder &b, ArrayRef<LinalgOp> ops, 905 const LinalgDependenceGraph &dependenceGraph, 906 const LinalgTilingOptions &tilingOptions) { 907 if (ops.size() < 2) 908 return llvm::None; 909 LinalgOp rootOp = ops.back(); 910 if (!llvm::all_of( 911 ops, 912 [](LinalgOp linalgOp) { return linalgOp.hasBufferSemantics(); }) && 913 !llvm::all_of(ops, [](LinalgOp linalgOp) { 914 return linalgOp.hasTensorSemantics(); 915 })) { 916 rootOp.emitError( 917 "unable to fuse operations that have tensor semantics with operations " 918 "that have buffer semantics and viceversa."); 919 return llvm::None; 920 } 921 // TODO: Support interchange with tile + fuse. This might actually help do 922 // better fusion. 923 if (!tilingOptions.interchangeVector.empty()) { 924 rootOp.emitRemark("unable to handle tile and fuse with interchange"); 925 return llvm::None; 926 } 927 928 OpBuilder::InsertionGuard guard(b); 929 b.setInsertionPoint(rootOp); 930 931 // Find all the producers. 932 LLVM_DEBUG(llvm::dbgs() << "findAllFusableDependences\n"); 933 FusableOpDependencesTy fusableDependences = 934 findAllFusableDependences(ops, dependenceGraph); 935 if (fusableDependences.empty()) { 936 LLVM_DEBUG(llvm::dbgs() << "no fusable dependencies found\n"); 937 return llvm::None; 938 } 939 940 TiledAndFusedLinalgOps ret; 941 // Find the loops that can be tiled and fused. 942 LLVM_DEBUG(llvm::dbgs() << "collectFusableLoops\n"); 943 ret.fusedLoopDims = collectFusableLoops(ops, fusableDependences); 944 945 // If there are no fusable dependences or there are no tile+fusable loops, 946 // just return. 947 if (ret.fusedLoopDims.empty()) { 948 LLVM_DEBUG(llvm::dbgs() << "no fusable loops found\n"); 949 return llvm::None; 950 } 951 952 // Tile the fused loops in the last operation in the list. 953 SmallVector<Value, 4> tileSizeVector = 954 tilingOptions.tileSizeComputationFunction(b, rootOp); 955 Optional<TiledLinalgOp> tiledRootOp = tileRootOperation( 956 b, rootOp, tileSizeVector, tilingOptions, ret.fusedLoopDims); 957 if (!tiledRootOp) { 958 rootOp.emitRemark("failed to tile the fused loops"); 959 return llvm::None; 960 } 961 ret.op = tiledRootOp->op; 962 ret.fusedLoops.assign(tiledRootOp->loops.begin(), tiledRootOp->loops.end()); 963 964 // Fuse the other operations into the fused inter-tile loops produced above. 965 ret.fusedProducers = fuseOperations(b, rootOp, *tiledRootOp, ops.drop_back(), 966 fusableDependences, ret.fusedLoopDims); 967 968 return ret; 969 } 970 971 Optional<TiledAndFusedLinalgOps> 972 mlir::linalg::tileAndFuseLinalgOps(OpBuilder &b, ArrayRef<LinalgOp> ops, 973 const LinalgDependenceGraph &dependenceGraph, 974 const LinalgTilingOptions &tilingOptions) { 975 switch (tilingOptions.loopType) { 976 case LinalgTilingLoopType::Loops: 977 case LinalgTilingLoopType::ParallelLoops: 978 case LinalgTilingLoopType::TiledLoops: 979 return tileAndFuseLinalgOpsImpl(b, ops, dependenceGraph, tilingOptions); 980 default:; 981 } 982 return llvm::None; 983 } 984