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/StandardOps/EDSC/Intrinsics.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 "llvm/ADT/MapVector.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 32 #include <set> 33 34 #define DEBUG_TYPE "linalg-fusion" 35 36 using namespace mlir; 37 using namespace mlir::edsc; 38 using namespace mlir::edsc::intrinsics; 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 subtensor ops; 52 /// 2. greedily fuse the linalg ops that produce the subview/subtensor. 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 // Fill `offset`, `sizes` and `strides` used to iterate over the shape indexed 60 // by `permutationMap`. 61 static void inferShapeComponents(AffineMap permutationMap, 62 ArrayRef<Range> loopRanges, 63 SmallVectorImpl<Value> &offsets, 64 SmallVectorImpl<Value> &sizes, 65 SmallVectorImpl<Value> &strides) { 66 assert(permutationMap.isProjectedPermutation() && 67 "expected some subset of a permutation map"); 68 SmallVector<Range, 4> shapeRanges(permutationMap.getNumResults()); 69 unsigned idx = 0; 70 for (AffineExpr e : permutationMap.getResults()) { 71 // loopToOperandRangesMaps are permutations-only, just swap indices. 72 unsigned loopPos = e.cast<AffineDimExpr>().getPosition(); 73 shapeRanges[idx++] = loopRanges[loopPos]; 74 } 75 // Construct a new subshape for the tile. 76 unsigned rank = shapeRanges.size(); 77 offsets.reserve(rank); 78 sizes.reserve(rank); 79 strides.reserve(rank); 80 for (auto r : shapeRanges) { 81 offsets.push_back(r.offset); 82 sizes.push_back(r.size); 83 strides.push_back(r.stride); 84 } 85 } 86 87 // Return a cloned version of `op` that operates on `loopRanges`, assumed to be 88 // a subset of the original loop ranges of `op`. 89 // This is achieved by applying the `loopToOperandRangesMaps` permutation maps 90 // to the `loopRanges` in order to obtain view ranges. 91 static LinalgOp cloneWithLoopRanges(OpBuilder &b, Location loc, LinalgOp op, 92 ArrayRef<Range> loopRanges) { 93 SmallVector<Value, 8> clonedShapes; 94 clonedShapes.reserve(op.getNumShapedOperands()); 95 96 // Iterate over the shape operands in order. 97 // Extract the subranges from the linearized ranges. 98 for (auto en : llvm::enumerate(op.getShapedOperands())) { 99 unsigned shapedOperandIdx = en.index(); 100 AffineMap map = op.getIndexingMap(shapedOperandIdx); 101 LLVM_DEBUG(llvm::dbgs() << "shapedOperandIdx: " << shapedOperandIdx 102 << " with indexingMap: " << map << "\n"); 103 SmallVector<Value, 4> offsets, sizes, strides; 104 inferShapeComponents(map, loopRanges, offsets, sizes, strides); 105 Value shape = en.value(); 106 Value sub = shape.getType().isa<MemRefType>() 107 ? b.create<SubViewOp>(loc, shape, offsets, sizes, strides) 108 .getResult() 109 : b.create<SubTensorOp>(loc, shape, offsets, sizes, strides) 110 .getResult(); 111 clonedShapes.push_back(sub); 112 } 113 // Append the other operands. 114 auto operands = op.getAssumedNonShapedOperands(); 115 clonedShapes.append(operands.begin(), operands.end()); 116 117 // Iterate over the results in order. 118 // Extract the subtensor type from the linearized range. 119 // Since we do not enforce any canonicalizations on the fly, this is always 120 // fully dynamic at construction time. 121 SmallVector<Type, 4> resultTypes; 122 resultTypes.reserve(op->getNumResults()); 123 for (RankedTensorType t : op.getOutputTensorTypes()) { 124 unsigned rank = t.getRank(); 125 SmallVector<int64_t, 4> staticOffsetsVector( 126 rank, ShapedType::kDynamicStrideOrOffset); 127 SmallVector<int64_t, 4> staticSizesVector(rank, ShapedType::kDynamicSize); 128 SmallVector<int64_t, 4> staticStridesVector( 129 rank, ShapedType::kDynamicStrideOrOffset); 130 resultTypes.push_back(SubTensorOp::inferResultType( 131 t.cast<RankedTensorType>(), staticOffsetsVector, staticSizesVector, 132 staticStridesVector)); 133 } 134 135 Operation *clonedOp = op.clone(b, loc, resultTypes, clonedShapes); 136 // When the producer is an IndexedGenericOp, we have to transform its block 137 // IV arguments according to the tiling of the consumer, i.e. offset them by 138 // the values computed in `loopRanges`. 139 if (auto indexedGenericOp = dyn_cast<IndexedGenericOp>(clonedOp)) { 140 auto &block = indexedGenericOp.region().front(); 141 OpBuilder::InsertionGuard g(b); 142 b.setInsertionPointToStart(&block); 143 for (unsigned i = 0, e = indexedGenericOp.getNumLoops(); i < e; ++i) { 144 Value oldIndex = block.getArgument(i); 145 // TODO: replace by an affine_apply. 146 AddIOp newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex, 147 loopRanges[i].offset); 148 oldIndex.replaceAllUsesExcept(newIndex, 149 SmallPtrSet<Operation *, 1>{newIndex}); 150 } 151 } 152 153 return clonedOp; 154 } 155 156 struct ShapeDimension { 157 Value shape; 158 unsigned dimension; 159 }; 160 161 // Given an `op`, returns the first (`shape`, `dimension`) pair that identifies 162 // the loop range at `loopDepth`. The semantics of the loopToOperandRangesMaps 163 // guarantees at least one such dimension is found. If multiple candidates exist 164 // they must agree by construction (i.e. have the same size) and we just return 165 // the first one. 166 static ShapeDimension 167 getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth, 168 bool fromSubViewOpOnly = false) { 169 auto maps = op.indexing_maps(); 170 // Iterate over the inputs and outputs in order. 171 // Extract the subranges from the linearized ranges. 172 for (auto en : llvm::enumerate(op.getShapedOperands())) { 173 // The method `getRangeFromOperandShape` requires using SubViewOp or 174 // SubTensorOps. If the value isnt defined from there continue. 175 // todo: The method should be adapted to get the values from 176 // `ViewInterface`. The interface needs a `getOrCreateRanges` method which 177 // currently returns a `linalg.range`. The fix here is to move this op to 178 // `std` dialect and add the method to `ViewInterface`. 179 if (fromSubViewOpOnly && 180 !isa_and_nonnull<SubViewOp, SubTensorOp>(en.value().getDefiningOp())) 181 continue; 182 183 unsigned idx = en.index(); 184 auto map = maps[idx].cast<AffineMapAttr>().getValue(); 185 LLVM_DEBUG(llvm::dbgs() 186 << "getShapeDefiningLoopRange I/O idx: " << idx << "\n"); 187 LLVM_DEBUG(llvm::dbgs() 188 << "getShapeDefiningLoopRange map: " << map << "\n"); 189 Value shape = en.value(); 190 SmallVector<Value, 8> shapeRanges(map.getNumResults(), nullptr); 191 for (auto en2 : llvm::enumerate(map.getResults())) { 192 auto dimExpr = en2.value().dyn_cast<AffineDimExpr>(); 193 if (!dimExpr) 194 continue; 195 if (loopDepth == en2.value().cast<AffineDimExpr>().getPosition()) { 196 LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange loopDepth: " 197 << loopDepth << "\n"); 198 LLVM_DEBUG(llvm::dbgs() 199 << "getShapeDefiningLoopRange shape: " << shape << "\n"); 200 return ShapeDimension{shape, static_cast<unsigned>(en2.index())}; 201 } 202 } 203 } 204 llvm_unreachable("Expect to be able to extract a shape defining loop range"); 205 } 206 207 /// Fuse the producer by cloning the `producer`. The `fusedLoopsAndRanges` 208 /// provides the loop range information for the fused loops. The rest are 209 /// obtained from the producer itself, since they are not tiled + fused. 210 static LinalgOp fuse(OpBuilder &b, LinalgOp producer, 211 const DenseMap<unsigned, Range> &fusedLoopsAndRanges) { 212 213 unsigned nPar = producer.getNumParallelLoops(); 214 unsigned nRed = producer.getNumReductionLoops(); 215 unsigned nWin = producer.getNumWindowLoops(); 216 SmallVector<Range, 8> loopRanges(nPar + nRed + nWin); 217 for (auto fusedLoops : fusedLoopsAndRanges) 218 loopRanges[fusedLoops.first] = fusedLoops.second; 219 220 // Iterate over all dimensions. For the dimensions not identified by the 221 // producer map for `producerIdx`, we need to explicitly compute the shape 222 // that defines the loop ranges using the `producer`. 223 for (unsigned i = 0, nLoops = loopRanges.size(); i < nLoops; ++i) { 224 if (loopRanges[i].offset) 225 LLVM_DEBUG(llvm::dbgs() 226 << "existing LoopRange: " << loopRanges[i] << "\n"); 227 else { 228 auto shapeDim = getShapeDefiningLoopRange(producer, i); 229 loopRanges[i] = Range{std_constant_index(0), 230 std_dim(shapeDim.shape, shapeDim.dimension), 231 std_constant_index(1)}; 232 LLVM_DEBUG(llvm::dbgs() << "new LoopRange: " << loopRanges[i] << "\n"); 233 } 234 } 235 236 return cloneWithLoopRanges(b, producer.getLoc(), producer, loopRanges); 237 } 238 239 /// Get the loop range for a dimension `dim` based on the `shapedOperand`. It is 240 /// expected to be defined by a subview op or a subtensor op. 241 static Range getRangeFromOperandShape(OpBuilder &b, Location loc, 242 Value shapedOperand, unsigned dim) { 243 Operation *shapeProducingOp = shapedOperand.getDefiningOp(); 244 if (auto subViewOp = dyn_cast<SubViewOp>(shapeProducingOp)) 245 return subViewOp.getOrCreateRanges(b, loc)[dim]; 246 if (auto subTensorOp = dyn_cast<SubTensorOp>(shapeProducingOp)) 247 return subTensorOp.getOrCreateRanges(b, loc)[dim]; 248 llvm_unreachable("SubviewOp or SubTensorOp expected"); 249 } 250 251 /// Fuses the producer of `producerIdx` into the loop immediately enclosing 252 /// `consumer`. This is achieved by "recomputing" the `producer` at the time it 253 /// is needed just before the `consumer. 254 /// 255 /// Depending on the type of `consumer.getShapedOperand(consumerIdx)`, there are 256 /// 2 cases: 257 /// 1. Buffer case: `producerIdx` is the index of the buffer in 258 /// `producer.getOutputBuffers()`. 259 /// 2. Tensor case: `producerIdx` is the index of the tensor in 260 /// `producer.getResults()`. 261 static LinalgOp fuse(OpBuilder &b, LinalgOp producerOp, 262 unsigned producerOutNumber, OpOperand &consumerOpOperand) { 263 AffineMap producerMap = producerOp.getOutputIndexingMap(producerOutNumber); 264 LLVM_DEBUG(llvm::dbgs() << "Producer Idx: " << producerOutNumber 265 << ", producer map: " << producerMap << "\n"); 266 DenseMap<unsigned, Range> fusedLoopsAndRanges; 267 Value shapedOperand = consumerOpOperand.get(); 268 for (auto en : llvm::enumerate(producerMap.getResults())) { 269 unsigned posInProducerLoop = en.value().cast<AffineDimExpr>().getPosition(); 270 fusedLoopsAndRanges[posInProducerLoop] = getRangeFromOperandShape( 271 b, consumerOpOperand.getOwner()->getLoc(), shapedOperand, en.index()); 272 } 273 return fuse(b, producerOp, fusedLoopsAndRanges); 274 } 275 276 // Encode structural fusion safety preconditions. 277 // Some of these will be lifted in the future with better analysis. 278 static bool isStructurallyFusableProducer(LinalgOp producer, Value consumedView, 279 LinalgOp consumer) { 280 assert(producer.hasBufferSemantics() && 281 "expected linalg op with buffer semantics"); 282 assert(consumer.hasBufferSemantics() && 283 "expected linalg op with buffer semantics"); 284 if (producer.getNumOutputs() != 1) { 285 LLVM_DEBUG(llvm::dbgs() << "\nNot structurally fusable (multi-output)"); 286 return false; 287 } 288 // Only fuse when the producer block dominates. 289 DominanceInfo dom(producer.getOperation()); 290 if (!dom.dominates(producer->getBlock(), consumer->getBlock())) { 291 LLVM_DEBUG( 292 llvm::dbgs() 293 << "\nNot structurally fusable (producer block does not dominate)"); 294 return false; 295 } 296 return true; 297 } 298 299 bool mlir::linalg::isProducerLastWriteOfView(const LinalgDependenceGraph &graph, 300 LinalgOp consumer, 301 Value consumedView, 302 LinalgOp producer) { 303 assert(producer.hasBufferSemantics() && 304 "expected linalg op with buffer semantics"); 305 assert(consumer.hasBufferSemantics() && 306 "expected linalg op with buffer semantics"); 307 // Make some simple structural checks that alleviate the need for more 308 // complex analyses. 309 if (!isStructurallyFusableProducer(producer, consumedView, consumer)) { 310 LLVM_DEBUG(llvm::dbgs() << "\n***Not static last write due to structure:\t" 311 << *producer.getOperation()); 312 return false; 313 } 314 // Check for any interleaved write to consumedView. 315 if (!graph.findCoveringWrites(producer, consumer, consumedView).empty()) { 316 LLVM_DEBUG(llvm::dbgs() << "\n***Not fusable due to interleaved write:\t" 317 << *producer.getOperation()); 318 return false; 319 } 320 return true; 321 } 322 323 bool mlir::linalg::isFusableInto(const LinalgDependenceGraph &graph, 324 LinalgOp consumer, Value consumedView, 325 LinalgOp producer) { 326 assert(producer.hasBufferSemantics() && 327 "expected linalg op with buffer semantics"); 328 assert(consumer.hasBufferSemantics() && 329 "expected linalg op with buffer semantics"); 330 if (!isProducerLastWriteOfView(graph, consumer, consumedView, producer)) 331 return false; 332 // Check for any fusion-preventing dependence to any shape read/written that 333 // would violate dependences. 334 if (!graph.findCoveringDependences(producer, consumer).empty()) { 335 LLVM_DEBUG(llvm::dbgs() 336 << "\n***Not fusable due to an interleaved dependence:\t" 337 << *producer.getOperation()); 338 return false; 339 } 340 if (auto convOp = dyn_cast<linalg::ConvOp>(producer.getOperation())) { 341 // TODO: add a level of indirection to linalg.generic. 342 if (convOp.padding()) 343 return false; 344 } 345 if (auto convOp = dyn_cast<linalg::ConvOp>(consumer.getOperation())) { 346 // TODO: add a level of indirection to linalg.generic. 347 if (convOp.padding()) 348 return false; 349 } 350 return true; 351 } 352 353 static bool isSameSubView(Value a, Value b) { 354 if (a == b) 355 return true; 356 auto sva = a.getDefiningOp<SubViewOp>(); 357 auto svb = b.getDefiningOp<SubViewOp>(); 358 if (!sva || !svb) 359 return false; 360 if (!isSameSubView(sva.getViewSource(), svb.getViewSource())) 361 return false; 362 if (sva.getType() != svb.getType()) 363 return false; 364 if (sva.getNumOperands() != svb.getNumOperands()) 365 return false; 366 if (sva.static_offsets() != svb.static_offsets()) 367 return false; 368 if (sva.static_sizes() != svb.static_sizes()) 369 return false; 370 if (sva.static_strides() != svb.static_strides()) 371 return false; 372 /// Skip the "source" operand. 373 for (unsigned idx = 1, e = sva.getNumOperands(); idx != e; ++idx) 374 if (sva.getOperand(idx) != svb.getOperand(idx)) 375 return false; 376 return true; 377 } 378 379 static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 380 findFusableProducer(OpOperand &consumerOpOperand, 381 const LinalgDependenceGraph &dependenceGraph) { 382 LinalgOp consumerOp = cast<LinalgOp>(consumerOpOperand.getOwner()); 383 assert(consumerOp.hasBufferSemantics() && "revisit usage of shaped operand"); 384 385 // Only consider RAW and WAW atm. 386 for (auto depType : { 387 LinalgDependenceGraph::DependenceType::RAW, 388 LinalgDependenceGraph::DependenceType::WAW, 389 }) { 390 for (auto dependence : llvm::make_filter_range( 391 dependenceGraph.getDependencesInto(consumerOp, depType), 392 [&](LinalgDependenceGraph::LinalgDependenceGraphElem elem) { 393 return elem.indexingOpView->get() == consumerOpOperand.get() && 394 elem.indexingOpView->getOperandNumber() == 395 consumerOpOperand.getOperandNumber(); 396 })) { 397 398 // Consumer consumes this view, `isStructurallyFusableProducer` also 399 // checks whether it is a strict subview of the producer view. 400 auto producer = cast<LinalgOp>(dependence.dependentOpView->getOwner()); 401 LLVM_DEBUG(llvm::dbgs() 402 << "\n" 403 << LinalgDependenceGraph::getDependenceTypeStr(depType) 404 << "producer: " << *dependence.dependentOpView->getOwner() 405 << " view: " << dependence.dependentOpView->get() 406 << " output index: " 407 << dependence.dependentOpView->getOperandNumber() - 408 producer.getNumInputs() 409 << "\n"); 410 411 // Simple fusability checks. 412 if (!isFusableInto(dependenceGraph, consumerOp, consumerOpOperand.get(), 413 producer)) 414 continue; 415 416 return dependence; 417 } 418 } 419 return {}; 420 } 421 422 Optional<FusionInfo> 423 mlir::linalg::fuseProducerOfBuffer(OpBuilder &b, OpOperand &consumerOpOperand, 424 const LinalgDependenceGraph &graph) { 425 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> fusableDependence = 426 findFusableProducer(consumerOpOperand, graph); 427 if (!fusableDependence) 428 return {}; 429 430 LinalgOp producerOp = 431 cast<LinalgOp>(fusableDependence->dependentOpView->getOwner()); 432 // If producer is already in the same block as consumer, we are done. 433 if (consumerOpOperand.get().getParentBlock() == 434 fusableDependence->dependentOpView->get().getParentBlock()) 435 return {}; 436 437 unsigned producerIdx = 438 fusableDependence->dependentOpView->getOperandNumber() - 439 producerOp.getNumInputs(); 440 441 // Must be a subview or a slice to guarantee there are loops we can fuse 442 // into. 443 auto subView = consumerOpOperand.get().getDefiningOp<SubViewOp>(); 444 auto slice = consumerOpOperand.get().getDefiningOp<SliceOp>(); 445 if (!subView && !slice) { 446 LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subview or slice)"); 447 return {}; 448 } 449 450 // Fuse `producer` just before `consumer`. 451 OpBuilder::InsertionGuard g(b); 452 b.setInsertionPoint(consumerOpOperand.getOwner()); 453 ScopedContext scope(b, consumerOpOperand.getOwner()->getLoc()); 454 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " 455 << *consumerOpOperand.getOwner() << "\n"); 456 457 auto fusedProducer = fuse(b, producerOp, producerIdx, 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 static void getProducerOfTensor(Value tensor, OpResult &opResult) { 464 if (!tensor.getType().isa<RankedTensorType>()) 465 return; 466 467 while (true) { 468 LLVM_DEBUG(llvm::dbgs() << "\ngetProducerOfTensor: " << tensor); 469 if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) { 470 opResult = tensor.cast<OpResult>(); 471 return; 472 } 473 if (auto subTensorOp = tensor.getDefiningOp<SubTensorOp>()) { 474 tensor = subTensorOp.source(); 475 continue; 476 } 477 if (auto blockArg = tensor.dyn_cast<BlockArgument>()) { 478 if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) { 479 tensor = *(forOp.getIterOperands().begin() + blockArg.getArgNumber()); 480 continue; 481 } 482 } 483 return; 484 } 485 } 486 487 Optional<FusionInfo> 488 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand) { 489 Value inputTensor = consumerOpOperand.get(); 490 OpResult producerOpResult; 491 getProducerOfTensor(inputTensor, producerOpResult); 492 if (!producerOpResult) { 493 LLVM_DEBUG(llvm::dbgs() << "\nUnable to find producer"); 494 return {}; 495 } 496 return fuseProducerOfTensor(b, producerOpResult, consumerOpOperand); 497 } 498 499 Optional<FusionInfo> 500 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpResult producerOpResult, 501 OpOperand &consumerOpOperand) { 502 auto producerOp = dyn_cast<LinalgOp>(producerOpResult.getOwner()); 503 assert(producerOp && "expected Linalg producer"); 504 LinalgOp consumerOp = cast<LinalgOp>(consumerOpOperand.getOwner()); 505 Value inputTensor = consumerOpOperand.get(); 506 507 // Must be a subtensor to guarantee there are loops we can fuse into. 508 auto subTensor = inputTensor.getDefiningOp<SubTensorOp>(); 509 if (!subTensor) { 510 LLVM_DEBUG(llvm::dbgs() 511 << "\nNot fusable, not a subtensor: " << inputTensor); 512 return {}; 513 } 514 515 // If producer is already in the same block as consumer, we are done. 516 if (consumerOpOperand.get().getParentBlock() == 517 producerOpResult.getParentBlock()) 518 return {}; 519 520 // Insert fused `producer` just before `consumer`. 521 OpBuilder::InsertionGuard g(b); 522 b.setInsertionPoint(consumerOp); 523 ScopedContext scope(b, consumerOp->getLoc()); 524 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumerOp << "\n"); 525 LinalgOp fusedProducer = fuse( 526 b, producerOp, producerOpResult.getResultNumber(), consumerOpOperand); 527 528 // Replace use. 529 // Canonicalizations are not guaranteed to have happened before constructing 530 // `fusedProducer`. In the tensor case this can result in temporary type 531 // mismatches. Insert a `tensor.cast` op to propagate the transformation 532 // invariant that types are compatible. 533 Value def = fusedProducer->getResult(producerOpResult.getResultNumber()); 534 Type consumerType = consumerOpOperand.get().getType(); 535 if (consumerType != def.getType()) 536 def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def); 537 consumerOpOperand.set(def); 538 return FusionInfo{cast<LinalgOp>(producerOpResult.getOwner()), fusedProducer}; 539 } 540 541 /// Prune all dimensions that are of reduction iterator type from `map`. 542 static AffineMap pruneReductionDimsFromMap(ArrayRef<Attribute> iteratorTypes, 543 AffineMap map) { 544 SmallVector<unsigned, 2> projectedDims; 545 for (auto attr : llvm::enumerate(iteratorTypes)) { 546 if (!isParallelIterator(attr.value())) 547 projectedDims.push_back(attr.index()); 548 } 549 return getProjectedMap(map, projectedDims); 550 } 551 552 /// Returns the mapping from iterations in the consumer that write to the same 553 /// location as the iterations in the producer. To do so use 554 /// - indexing map of the fused view in the consumer : consumerIndexMap 555 /// - indexing map of the fused view in the producer : producerIndexMap 556 /// consumerLoopToProducerLoop = 557 /// inverse(producerIndexMap).compose(consumerIndexMap) 558 static Optional<AffineMap> getConsumerLoopToProducerLoopMap( 559 LinalgDependenceGraph::LinalgDependenceGraphElem dependence) { 560 auto producer = cast<LinalgOp>(dependence.dependentOpView->getOwner()); 561 AffineMap producerIndexingMap = 562 producer.getIndexingMap(dependence.dependentOpView->getOperandNumber()); 563 auto consumer = cast<LinalgOp>(dependence.indexingOpView->getOwner()); 564 AffineMap consumerIndexingMap = 565 consumer.getIndexingMap(dependence.indexingOpView->getOperandNumber()); 566 567 AffineMap prunedProducerIndexingMap = pruneReductionDimsFromMap( 568 producer.iterator_types().getValue(), producerIndexingMap); 569 if (!prunedProducerIndexingMap.isPermutation()) 570 return None; 571 572 if (consumerIndexingMap.getNumResults() != 573 prunedProducerIndexingMap.getNumResults()) 574 return None; 575 576 LLVM_DEBUG({ 577 llvm::dbgs() << "\t producerMap : "; 578 producerIndexingMap.print(llvm::dbgs()); 579 llvm::dbgs() << " pruned : "; 580 prunedProducerIndexingMap.print(llvm::dbgs()); 581 llvm::dbgs() << "\n"; 582 llvm::dbgs() << "\t consumerMap : "; 583 consumerIndexingMap.print(llvm::dbgs()); 584 llvm::dbgs() << "\n"; 585 }); 586 587 AffineMap invProducerIndexMap = inversePermutation(prunedProducerIndexingMap); 588 if (!invProducerIndexMap) 589 return None; 590 591 return invProducerIndexMap.compose(consumerIndexingMap); 592 } 593 594 /// Given a projected permutation `map`, returns true if the map changes the 595 /// order in which the fused loop dimension appear. 596 static bool doesTransposeAccess(AffineMap map, 597 const std::set<unsigned> &fusableLoops) { 598 Optional<unsigned> lastFusableLoop; 599 for (unsigned pos : llvm::map_range(map.getResults(), [](AffineExpr expr) { 600 return expr.cast<AffineDimExpr>().getPosition(); 601 })) { 602 if (!fusableLoops.count(pos)) 603 continue; 604 if (!lastFusableLoop) { 605 lastFusableLoop = pos; 606 continue; 607 } 608 if (pos <= lastFusableLoop.getValue()) 609 return true; 610 lastFusableLoop = pos; 611 } 612 return false; 613 } 614 615 /// Returns the positions of the loop in `op` that can be tiled based on the 616 /// operations that are to be fused with it. For example, in a 617 /// 618 /// linalg.matmul ins(%a, %b : ...) outs(%c : ...) 619 /// 620 /// if the producer of %a needs to be fused with this op, only the `i` loop of 621 /// the matmul can be tiled while fusing. If producer of %a, and %b are to be 622 /// fused, then no loops can be tiled while fusing. The conditions used are: 623 /// 1. Only parallel loops can be used for tile + fuse. Find the number of 624 /// common outer parallel loops between the op and its producers being fused. 625 /// 2. Of the parallel loops only some can be fused. Only those loops can be 626 /// fused such where the fusable loops iteration space only touches one tile 627 /// of the fused operation. This is because the producer (which is writing 628 /// the fused subview) has update semantics. 629 /// 630 /// Since an inverse computation is needed, we need to consider the projection 631 /// of the producerIndexMap w.r.t the parallel loops. The actual fusable loops 632 /// are the dimensions of the consumerLoopToProducerLoop map that correspond to 633 /// parallel loops and appear in the result of the map 634 /// 635 /// Example 1: 636 /// linalg.fill(%c, %cst) 637 /// linalg.matmul ins(%a, %b) outs(%c) 638 /// Number of parallel loops : 2 639 /// producerIndexMap = affine_map<(i, j) ->(i , j)> 640 /// consumerIndexMap = affine_map<(i, j, k) -> (i, j)> 641 /// consumerLoopToProducerLoop = affine_map<(i, j, k) -> (i, j)> 642 /// Fused dimensions : i, j 643 /// 644 /// Example 2: 645 /// linalg.matmul ins(%a, %b) outs(%c) 646 /// linalg.generic {indexing_maps = [affine_map<(i, j) -> (j, i)>, ... 647 /// iterator_types = ["parallel", "parallel"]} 648 /// ins(%c) ... 649 /// 650 /// Number of parallel loops = 2: 651 /// producerIndexMap (projected to parallel loops) = 652 /// affine_map<(i, j) -> (i, j)> 653 /// consumerLoopToProducerLoop2 = affine_map<(i, j) -> (j, i)> 654 /// Fused dimensions : i, j 655 /// 656 /// Example 3: 657 /// linalg.copy(%s, %b) 658 /// linalg.matmul ins(%a, %b) outs(%c) 659 /// 660 /// Number of parallel loops = 2 661 /// produceIndexMap : affine_map<(i, j) -> (i, j)> 662 /// consumerLoopToProduceLoops = affine_map<(i, j, k) -> (k, j)> 663 /// submap with only parallel loops = affine_map<(i, j) -> (j)> 664 /// Fused dimensions : j 665 static std::set<unsigned> 666 collectFusableLoops(ArrayRef<LinalgOp> ops, 667 const FusableOpDependencesTy &fusableDependences) { 668 assert(!ops.empty()); 669 auto getNumOuterParallelLoops = [](LinalgOp linalgOp) { 670 return linalgOp.iterator_types() 671 .getValue() 672 .take_while([](Attribute attr) -> bool { 673 return attr.cast<StringAttr>().getValue() == 674 getParallelIteratorTypeName(); 675 }) 676 .size(); 677 }; 678 679 size_t numOuterParallelLoops = getNumOuterParallelLoops(ops.back()); 680 for (auto op : ops.drop_back()) { 681 numOuterParallelLoops = 682 std::min(numOuterParallelLoops, getNumOuterParallelLoops(op)); 683 } 684 685 std::set<unsigned> fusableLoops; 686 auto range = llvm::seq<unsigned>(0, numOuterParallelLoops); 687 fusableLoops.insert(range.begin(), range.end()); 688 689 for (auto op : reverse(ops)) { 690 for (auto dependence : fusableDependences.lookup(op)) { 691 LLVM_DEBUG({ 692 llvm::dbgs() << "\t fusable :"; 693 for (unsigned i : fusableLoops) 694 llvm::dbgs() << " " << i; 695 llvm::dbgs() << "\n"; 696 }); 697 698 Optional<AffineMap> consumerLoopToProducerLoop = 699 getConsumerLoopToProducerLoopMap(dependence); 700 if (!consumerLoopToProducerLoop) { 701 op.emitRemark("failed to get map from consumer loop to producer loop"); 702 return {}; 703 } 704 // todo: This condition is only an implementation limitation. When fusing 705 // the operation, if the accesses in the producer/consumer are transposes 706 // of each other, the loop bounds for the tiled producer can be 707 // manipulated accordingly. This requires some additional bookkeeping in 708 // the implementation of tile+fuse that is deferred to later. 709 if (doesTransposeAccess(*consumerLoopToProducerLoop, fusableLoops)) { 710 op.emitRemark("unhandled fusion when fusion requires permutation"); 711 return {}; 712 } 713 714 std::set<unsigned> candidates; 715 for (AffineExpr expr : consumerLoopToProducerLoop->getResults()) { 716 unsigned position = expr.cast<AffineDimExpr>().getPosition(); 717 if (fusableLoops.count(position)) 718 candidates.insert(position); 719 } 720 LLVM_DEBUG({ 721 llvm::dbgs() << "\t candidates :"; 722 for (unsigned i : candidates) 723 llvm::dbgs() << " " << i; 724 llvm::dbgs() << "\n"; 725 }); 726 if (candidates.empty()) 727 return {}; 728 std::swap(candidates, fusableLoops); 729 } 730 } 731 732 return fusableLoops; 733 } 734 735 /// Find all dependences that are fusable. 736 FusableOpDependencesTy mlir::linalg::findAllFusableDependences( 737 ArrayRef<LinalgOp> ops, const LinalgDependenceGraph &dependenceGraph) { 738 FusableOpDependencesTy fusableDependences; 739 // TODO: Currently fusion would not be legal if the fusable dependence is to 740 // the same producer but different indexing map in the consumer. Fix this, but 741 // in the meanwhile disallow such a fusion. 742 DenseMap<Operation *, AffineMap> fusedProducerIndexingMap; 743 for (LinalgOp op : reverse(ops)) { 744 for (OpOperand &opOperand : op.getShapedOpOperands()) { 745 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 746 fusableDependence = findFusableProducer(opOperand, dependenceGraph); 747 if (!fusableDependence) 748 continue; 749 LinalgOp producerOp = 750 cast<LinalgOp>(fusableDependence->dependentOpView->getOwner()); 751 // Do not fuse dependences that are to operations not in the same basic 752 // block. This avoid moving fused operations across loops that might 753 // themselves carry dependency making the fusion illegal. 754 if (producerOp->getBlock() != op->getBlock()) { 755 op.emitRemark("unhandled fusion of ops in different basic blocks"); 756 return FusableOpDependencesTy{}; 757 } 758 // Make sure that the indexing map of the view used for fusion in the 759 // producer is a projected permutation. 760 unsigned producerIdx = 761 fusableDependence->dependentOpView->getOperandNumber(); 762 AffineMap producerMap = producerOp.getIndexingMap(producerIdx); 763 if (!producerMap.isProjectedPermutation()) { 764 op.emitRemark( 765 "unhandled non permutation indexing map for fused view in " 766 "producer for operand at index ") 767 << opOperand.getOperandNumber(); 768 return FusableOpDependencesTy{}; 769 } 770 771 unsigned consumerIdx = 772 fusableDependence->indexingOpView->getOperandNumber(); 773 AffineMap consumerMap = op.getIndexingMap(consumerIdx); 774 if (!consumerMap.isProjectedPermutation()) { 775 op.emitRemark( 776 "unhandled case where indexing map for fused view in the consumer " 777 "is not a projected permutation while fusing at index ") 778 << opOperand.getOperandNumber(); 779 return FusableOpDependencesTy{}; 780 } 781 782 // Check if the producer is already a fusion candidate. Cannot fuse this 783 // dependence if it has a different indexing map when used in the 784 // consumer. 785 if (fusedProducerIndexingMap.count(producerOp.getOperation()) && 786 fusedProducerIndexingMap[producerOp.getOperation()] != consumerMap) { 787 op.emitRemark( 788 "unhandled fusion to the same producer but with different " 789 "indexing maps"); 790 return FusableOpDependencesTy{}; 791 } 792 fusedProducerIndexingMap[producerOp.getOperation()] = consumerMap; 793 794 fusableDependences[producerOp.getOperation()].push_back( 795 *fusableDependence); 796 } 797 } 798 return fusableDependences; 799 } 800 801 /// Tile the fused loops in the root operation, by setting the tile sizes for 802 /// all other loops to zero (those will be tiled later). 803 static Optional<TiledLinalgOp> tileRootOperation( 804 OpBuilder &builder, LinalgOp op, ArrayRef<Value> tileSizeVector, 805 const LinalgTilingOptions &options, const std::set<unsigned> &fusedLoops) { 806 SmallVector<Value, 4> tileSizes(tileSizeVector.begin(), tileSizeVector.end()); 807 auto zero = std_constant_index(0); 808 for (unsigned i = 0, e = tileSizes.size(); i != e; ++i) 809 if (!fusedLoops.count(i)) 810 tileSizes[i] = zero; 811 LinalgTilingOptions tileFusedLoopsOptions = options; 812 tileFusedLoopsOptions.setTileSizes(tileSizes); 813 return tileLinalgOp(builder, op, tileFusedLoopsOptions); 814 } 815 816 /// Fuse the operations in `fusionCandidates` with `tiledOp`. Latter is expected 817 /// to be a tiled operation such that it is valid to fuse all operations in 818 /// `fusionCandidates`, i.e. move the operation within the inter-tile loops of 819 /// `tiledOp`. 820 static SmallVector<LinalgOp, 1> 821 fuseOperations(OpBuilder &builder, LinalgOp tiledOp, 822 ArrayRef<LinalgOp> fusionCandidates, 823 const FusableOpDependencesTy &fusableDependences, 824 const std::set<unsigned> &fusedLoops) { 825 OpBuilder::InsertionGuard guard(builder); 826 builder.setInsertionPoint(tiledOp); 827 DenseMap<unsigned, Range> fusedLoopsAndRanges; 828 for (unsigned loop : fusedLoops) { 829 ShapeDimension shapeDim = getShapeDefiningLoopRange(tiledOp, loop, true); 830 fusedLoopsAndRanges[loop] = getRangeFromOperandShape( 831 builder, tiledOp.getLoc(), shapeDim.shape, shapeDim.dimension); 832 } 833 834 SmallVector<LinalgOp, 1> fusedOps(fusionCandidates.size()); 835 for (auto candidate : enumerate(llvm::reverse(fusionCandidates))) { 836 LinalgOp fusedOp = fuse(builder, candidate.value(), fusedLoopsAndRanges); 837 fusedOps[fusionCandidates.size() - candidate.index() - 1] = fusedOp; 838 builder.setInsertionPoint(fusedOp); 839 } 840 return fusedOps; 841 } 842 843 template <typename LoopType> 844 static Optional<TiledAndFusedLinalgOps> 845 tileAndFuseLinalgOpsImpl(OpBuilder &builder, ArrayRef<LinalgOp> ops, 846 const LinalgDependenceGraph &dependenceGraph, 847 const LinalgTilingOptions &tilingOptions) { 848 if (ops.empty()) 849 return llvm::None; 850 LinalgOp rootOp = ops.back(); 851 for (auto op : enumerate(ops)) { 852 // TODO: Nothing in the fusion of sequence of ops is specific to 853 // buffers. This check can be removed after it is tested on tensors. 854 LinalgOp linalgOp = op.value(); 855 if (!linalgOp.hasBufferSemantics()) { 856 linalgOp.emitError("tile and fuse only tested for buffer operation"); 857 return llvm::None; 858 } 859 } 860 // TODO: Support interchange with tile + fuse. This might actually help do 861 // better fusion. 862 if (!tilingOptions.interchangeVector.empty()) { 863 rootOp.emitError("unable to handle tile and fuse with interchange"); 864 return llvm::None; 865 } 866 867 OpBuilder::InsertionGuard guard(builder); 868 builder.setInsertionPoint(rootOp); 869 ScopedContext scope(builder, rootOp.getLoc()); 870 871 // Find all the producers. 872 FusableOpDependencesTy fusableDependences = 873 findAllFusableDependences(ops, dependenceGraph); 874 if (fusableDependences.empty()) 875 return llvm::None; 876 877 TiledAndFusedLinalgOps ret; 878 // Find the loops that can be tiled and fused. 879 ret.fusedLoopDims = collectFusableLoops(ops, fusableDependences); 880 881 // If there are no fusable dependences or there are no tile+fusable loops, 882 // just return. 883 if (ret.fusedLoopDims.empty()) { 884 return llvm::None; 885 } 886 887 // Tile the fused loops in the last operation in the list. 888 SmallVector<Value, 4> tileSizeVector = 889 tilingOptions.tileSizeComputationFunction(builder, rootOp); 890 Optional<TiledLinalgOp> tiledRootOp = tileRootOperation( 891 builder, rootOp, tileSizeVector, tilingOptions, ret.fusedLoopDims); 892 if (!tiledRootOp) { 893 rootOp.emitError("failed to tile the fused loops"); 894 return llvm::None; 895 } 896 ret.op = tiledRootOp->op; 897 ret.fusedLoops.assign(tiledRootOp->loops.begin(), tiledRootOp->loops.end()); 898 899 // Fuse the other operations into the fused inter-tile loops produced above. 900 ret.fusedProducers = fuseOperations(builder, ret.op, ops.drop_back(), 901 fusableDependences, ret.fusedLoopDims); 902 return ret; 903 } 904 905 Optional<TiledAndFusedLinalgOps> 906 mlir::linalg::tileAndFuseLinalgOps(OpBuilder &builder, ArrayRef<LinalgOp> ops, 907 const LinalgDependenceGraph &dependenceGraph, 908 const LinalgTilingOptions &tilingOptions) { 909 switch (tilingOptions.loopType) { 910 case LinalgTilingLoopType::Loops: 911 return tileAndFuseLinalgOpsImpl<scf::ForOp>(builder, ops, dependenceGraph, 912 tilingOptions); 913 case LinalgTilingLoopType::ParallelLoops: 914 return tileAndFuseLinalgOpsImpl<scf::ParallelOp>( 915 builder, ops, dependenceGraph, tilingOptions); 916 default:; 917 } 918 return llvm::None; 919 } 920