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 producer, unsigned producerIdx, 262 LinalgOp consumer, unsigned consumerIdx) { 263 AffineMap producerMap = producer.getOutputIndexingMap(producerIdx); 264 LLVM_DEBUG(llvm::dbgs() << "Producer Idx: " << producerIdx 265 << ", producer map: " << producerMap << "\n"); 266 DenseMap<unsigned, Range> fusedLoopsAndRanges; 267 Location loc = consumer.getLoc(); 268 Value shapedOperand = consumer.getShapedOperand(consumerIdx); 269 for (auto en : llvm::enumerate(producerMap.getResults())) { 270 unsigned posInProducerLoop = en.value().cast<AffineDimExpr>().getPosition(); 271 fusedLoopsAndRanges[posInProducerLoop] = 272 getRangeFromOperandShape(b, loc, shapedOperand, en.index()); 273 } 274 return fuse(b, producer, fusedLoopsAndRanges); 275 } 276 277 // Encode structural fusion safety preconditions. 278 // Some of these will be lifted in the future with better analysis. 279 static bool isStructurallyFusableProducer(LinalgOp producer, Value consumedView, 280 LinalgOp consumer) { 281 assert(producer.hasBufferSemantics() && 282 "expected linalg op with buffer semantics"); 283 assert(consumer.hasBufferSemantics() && 284 "expected linalg op with buffer semantics"); 285 if (producer.getNumOutputs() != 1) { 286 LLVM_DEBUG(llvm::dbgs() << "\nNot structurally fusable (multi-output)"); 287 return false; 288 } 289 // Only fuse when the producer block dominates. 290 DominanceInfo dom(producer.getOperation()); 291 if (!dom.dominates(producer->getBlock(), consumer->getBlock())) { 292 LLVM_DEBUG( 293 llvm::dbgs() 294 << "\nNot structurally fusable (producer block does not dominate)"); 295 return false; 296 } 297 return true; 298 } 299 300 bool mlir::linalg::isProducerLastWriteOfView(const LinalgDependenceGraph &graph, 301 LinalgOp consumer, 302 Value consumedView, 303 LinalgOp producer) { 304 assert(producer.hasBufferSemantics() && 305 "expected linalg op with buffer semantics"); 306 assert(consumer.hasBufferSemantics() && 307 "expected linalg op with buffer semantics"); 308 // Make some simple structural checks that alleviate the need for more 309 // complex analyses. 310 if (!isStructurallyFusableProducer(producer, consumedView, consumer)) { 311 LLVM_DEBUG(llvm::dbgs() << "\n***Not static last write due to structure:\t" 312 << *producer.getOperation()); 313 return false; 314 } 315 // Check for any interleaved write to consumedView. 316 if (!graph.findCoveringWrites(producer, consumer, consumedView).empty()) { 317 LLVM_DEBUG(llvm::dbgs() << "\n***Not fusable due to interleaved write:\t" 318 << *producer.getOperation()); 319 return false; 320 } 321 return true; 322 } 323 324 bool mlir::linalg::isFusableInto(const LinalgDependenceGraph &graph, 325 LinalgOp consumer, Value consumedView, 326 LinalgOp producer) { 327 assert(producer.hasBufferSemantics() && 328 "expected linalg op with buffer semantics"); 329 assert(consumer.hasBufferSemantics() && 330 "expected linalg op with buffer semantics"); 331 if (!isProducerLastWriteOfView(graph, consumer, consumedView, producer)) 332 return false; 333 // Check for any fusion-preventing dependence to any shape read/written that 334 // would violate dependences. 335 if (!graph.findCoveringDependences(producer, consumer).empty()) { 336 LLVM_DEBUG(llvm::dbgs() 337 << "\n***Not fusable due to an interleaved dependence:\t" 338 << *producer.getOperation()); 339 return false; 340 } 341 if (auto convOp = dyn_cast<linalg::ConvOp>(producer.getOperation())) { 342 // TODO: add a level of indirection to linalg.generic. 343 if (convOp.padding()) 344 return false; 345 } 346 if (auto convOp = dyn_cast<linalg::ConvOp>(consumer.getOperation())) { 347 // TODO: add a level of indirection to linalg.generic. 348 if (convOp.padding()) 349 return false; 350 } 351 return true; 352 } 353 354 static bool isSameSubView(Value a, Value b) { 355 if (a == b) 356 return true; 357 auto sva = a.getDefiningOp<SubViewOp>(); 358 auto svb = b.getDefiningOp<SubViewOp>(); 359 if (!sva || !svb) 360 return false; 361 if (!isSameSubView(sva.getViewSource(), svb.getViewSource())) 362 return false; 363 if (sva.getType() != svb.getType()) 364 return false; 365 if (sva.getNumOperands() != svb.getNumOperands()) 366 return false; 367 if (sva.static_offsets() != svb.static_offsets()) 368 return false; 369 if (sva.static_sizes() != svb.static_sizes()) 370 return false; 371 if (sva.static_strides() != svb.static_strides()) 372 return false; 373 /// Skip the "source" operand. 374 for (unsigned idx = 1, e = sva.getNumOperands(); idx != e; ++idx) 375 if (sva.getOperand(idx) != svb.getOperand(idx)) 376 return false; 377 return true; 378 } 379 380 static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 381 findFusableProducer(LinalgOp consumer, unsigned consumerIdx, 382 const LinalgDependenceGraph &dependenceGraph) { 383 assert(consumer.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(consumer, depType), 392 [consumerIdx]( 393 LinalgDependenceGraph::LinalgDependenceGraphElem elem) { 394 return elem.indexingOpView->getOperandNumber() == consumerIdx; 395 })) { 396 397 // Check that the dependence is indeed on the input `consumerIdx` view. 398 Value consumedView = dependence.indexingOpView->get(); 399 if (!isSameSubView(consumer.getShapedOperand(consumerIdx), consumedView)) 400 continue; 401 402 // Consumer consumes this view, `isStructurallyFusableProducer` also 403 // checks whether it is a strict subview of the producer view. 404 auto producer = cast<LinalgOp>(dependence.dependentOpView->getOwner()); 405 Value producedView = dependence.dependentOpView->get(); 406 LLVM_DEBUG(llvm::dbgs() 407 << "\n" 408 << LinalgDependenceGraph::getDependenceTypeStr(depType) 409 << "producer: " << *dependence.dependentOpView->getOwner() 410 << " view: " << dependence.dependentOpView->get() 411 << " output index: " 412 << dependence.dependentOpView->getOperandNumber() - 413 producer.getNumInputs() 414 << "\n"); 415 (void)producedView; 416 417 // Simple fusability checks. 418 if (!isFusableInto(dependenceGraph, consumer, consumedView, producer)) 419 continue; 420 421 return dependence; 422 } 423 } 424 return {}; 425 } 426 427 Optional<FusionInfo> 428 mlir::linalg::fuseProducerOfBuffer(OpBuilder &b, LinalgOp consumer, 429 unsigned consumerIdx, 430 const LinalgDependenceGraph &graph) { 431 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> fusableDependence = 432 findFusableProducer(consumer, consumerIdx, graph); 433 if (!fusableDependence) 434 return {}; 435 436 LinalgOp producerOp = 437 cast<LinalgOp>(fusableDependence->dependentOpView->getOwner()); 438 // If producer is already in the same block as consumer, we are done. 439 if (consumer->getBlock() == producerOp->getBlock()) 440 return {}; 441 442 unsigned producerIdx = 443 fusableDependence->dependentOpView->getOperandNumber() - 444 producerOp.getNumInputs(); 445 Value consumerView = consumer.getShapedOperand(consumerIdx); 446 447 // Must be a subview or a slice to guarantee there are loops we can fuse 448 // into. 449 auto subView = consumerView.getDefiningOp<SubViewOp>(); 450 auto slice = consumerView.getDefiningOp<SliceOp>(); 451 if (!subView && !slice) { 452 LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subview or slice)"); 453 return {}; 454 } 455 456 // Fuse `producer` just before `consumer`. 457 OpBuilder::InsertionGuard g(b); 458 b.setInsertionPoint(consumer.getOperation()); 459 ScopedContext scope(b, consumer.getLoc()); 460 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumer << "\n"); 461 462 auto fusedProducer = fuse(b, producerOp, producerIdx, consumer, consumerIdx); 463 return FusionInfo{producerOp, fusedProducer}; 464 } 465 466 /// Walk back use-def chain through scf::For yields. 467 /// Sets `producer` and `outputIndex` if it finds a producer LinalgOp 468 static void getProducerOfTensor(Value tensor, LinalgOp &producer, 469 unsigned &outputIndex) { 470 if (!tensor.getType().isa<RankedTensorType>()) 471 return; 472 473 while (true) { 474 if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) { 475 producer = linalgOp; 476 outputIndex = tensor.cast<OpResult>().getResultNumber(); 477 return; 478 } 479 if (auto subTensorOp = tensor.getDefiningOp<SubTensorOp>()) { 480 tensor = subTensorOp.source(); 481 continue; 482 } 483 if (auto blockArg = tensor.dyn_cast<BlockArgument>()) { 484 if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) { 485 tensor = forOp.getResult(blockArg.getArgNumber()); 486 continue; 487 } 488 } 489 return; 490 } 491 } 492 493 Optional<FusionInfo> mlir::linalg::fuseProducerOfTensor(OpBuilder &b, 494 LinalgOp consumer, 495 unsigned consumerIdx) { 496 Value inputTensor = consumer.getInput(consumerIdx); 497 LinalgOp producerOp; 498 unsigned producerIdx; 499 getProducerOfTensor(inputTensor, producerOp, producerIdx); 500 501 // Must be a subtensor to guarantee there are loops we can fuse into. 502 auto subTensor = inputTensor.getDefiningOp<SubTensorOp>(); 503 if (!subTensor || !producerOp) { 504 LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subtensor)"); 505 return {}; 506 } 507 508 // If producer is already in the same block as consumer, we are done. 509 if (consumer->getBlock() == producerOp->getBlock()) 510 return {}; 511 512 // Insert fused `producer` just before `consumer`. 513 OpBuilder::InsertionGuard g(b); 514 b.setInsertionPoint(consumer.getOperation()); 515 ScopedContext scope(b, consumer.getLoc()); 516 LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumer << "\n"); 517 LinalgOp fusedProducer = 518 fuse(b, producerOp, producerIdx, consumer, consumerIdx); 519 520 // Replace use. 521 // Canonicalizations are not guaranteed to have happened before constructing 522 // `fusedProducer`. In the tensor case this can result in temporary type 523 // mismatches. Insert a `tensor.cast` op to propagate the transformation 524 // invariant that types are compatible. 525 Value def = fusedProducer->getResult(producerIdx); 526 OpOperand &use = consumer->getOpOperand(consumerIdx); 527 Type consumerType = use.get().getType(); 528 if (consumerType != def.getType()) 529 def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def); 530 use.set(def); 531 return FusionInfo{producerOp, fusedProducer}; 532 } 533 534 /// Prune all dimensions that are of reduction iterator type from `map`. 535 static AffineMap pruneReductionDimsFromMap(ArrayRef<Attribute> iteratorTypes, 536 AffineMap map) { 537 SmallVector<unsigned, 2> projectedDims; 538 for (auto attr : llvm::enumerate(iteratorTypes)) { 539 if (!isParallelIterator(attr.value())) 540 projectedDims.push_back(attr.index()); 541 } 542 return getProjectedMap(map, projectedDims); 543 } 544 545 /// Returns the mapping from iterations in the consumer that write to the same 546 /// location as the iterations in the producer. To do so use 547 /// - indexing map of the fused view in the consumer : consumerIndexMap 548 /// - indexing map of the fused view in the producer : producerIndexMap 549 /// consumerLoopToProducerLoop = 550 /// inverse(producerIndexMap).compose(consumerIndexMap) 551 static Optional<AffineMap> getConsumerLoopToProducerLoopMap( 552 LinalgDependenceGraph::LinalgDependenceGraphElem dependence) { 553 auto producer = cast<LinalgOp>(dependence.dependentOpView->getOwner()); 554 AffineMap producerIndexingMap = 555 producer.getIndexingMap(dependence.dependentOpView->getOperandNumber()); 556 auto consumer = cast<LinalgOp>(dependence.indexingOpView->getOwner()); 557 AffineMap consumerIndexingMap = 558 consumer.getIndexingMap(dependence.indexingOpView->getOperandNumber()); 559 560 AffineMap prunedProducerIndexingMap = pruneReductionDimsFromMap( 561 producer.iterator_types().getValue(), producerIndexingMap); 562 if (!prunedProducerIndexingMap.isPermutation()) 563 return None; 564 565 if (consumerIndexingMap.getNumResults() != 566 prunedProducerIndexingMap.getNumResults()) 567 return None; 568 569 LLVM_DEBUG({ 570 llvm::dbgs() << "\t producerMap : "; 571 producerIndexingMap.print(llvm::dbgs()); 572 llvm::dbgs() << " pruned : "; 573 prunedProducerIndexingMap.print(llvm::dbgs()); 574 llvm::dbgs() << "\n"; 575 llvm::dbgs() << "\t consumerMap : "; 576 consumerIndexingMap.print(llvm::dbgs()); 577 llvm::dbgs() << "\n"; 578 }); 579 580 AffineMap invProducerIndexMap = inversePermutation(prunedProducerIndexingMap); 581 if (!invProducerIndexMap) 582 return None; 583 584 return invProducerIndexMap.compose(consumerIndexingMap); 585 } 586 587 /// Given a projected permutation `map`, returns true if the map changes the 588 /// order in which the fused loop dimension appear. 589 static bool doesTransposeAccess(AffineMap map, 590 const std::set<unsigned> &fusableLoops) { 591 Optional<unsigned> lastFusableLoop; 592 for (unsigned pos : llvm::map_range(map.getResults(), [](AffineExpr expr) { 593 return expr.cast<AffineDimExpr>().getPosition(); 594 })) { 595 if (!fusableLoops.count(pos)) 596 continue; 597 if (!lastFusableLoop) { 598 lastFusableLoop = pos; 599 continue; 600 } 601 if (pos <= lastFusableLoop.getValue()) 602 return true; 603 lastFusableLoop = pos; 604 } 605 return false; 606 } 607 608 /// Returns the positions of the loop in `op` that can be tiled based on the 609 /// operations that are to be fused with it. For example, in a 610 /// 611 /// linalg.matmul ins(%a, %b : ...) outs(%c : ...) 612 /// 613 /// if the producer of %a needs to be fused with this op, only the `i` loop of 614 /// the matmul can be tiled while fusing. If producer of %a, and %b are to be 615 /// fused, then no loops can be tiled while fusing. The conditions used are: 616 /// 1. Only parallel loops can be used for tile + fuse. Find the number of 617 /// common outer parallel loops between the op and its producers being fused. 618 /// 2. Of the parallel loops only some can be fused. Only those loops can be 619 /// fused such where the fusable loops iteration space only touches one tile 620 /// of the fused operation. This is because the producer (which is writing 621 /// the fused subview) has update semantics. 622 /// 623 /// Since an inverse computation is needed, we need to consider the projection 624 /// of the producerIndexMap w.r.t the parallel loops. The actual fusable loops 625 /// are the dimensions of the consumerLoopToProducerLoop map that correspond to 626 /// parallel loops and appear in the result of the map 627 /// 628 /// Example 1: 629 /// linalg.fill(%c, %cst) 630 /// linalg.matmul ins(%a, %b) outs(%c) 631 /// Number of parallel loops : 2 632 /// producerIndexMap = affine_map<(i, j) ->(i , j)> 633 /// consumerIndexMap = affine_map<(i, j, k) -> (i, j)> 634 /// consumerLoopToProducerLoop = affine_map<(i, j, k) -> (i, j)> 635 /// Fused dimensions : i, j 636 /// 637 /// Example 2: 638 /// linalg.matmul ins(%a, %b) outs(%c) 639 /// linalg.generic {indexing_maps = [affine_map<(i, j) -> (j, i)>, ... 640 /// iterator_types = ["parallel", "parallel"]} 641 /// ins(%c) ... 642 /// 643 /// Number of parallel loops = 2: 644 /// producerIndexMap (projected to parallel loops) = 645 /// affine_map<(i, j) -> (i, j)> 646 /// consumerLoopToProducerLoop2 = affine_map<(i, j) -> (j, i)> 647 /// Fused dimensions : i, j 648 /// 649 /// Example 3: 650 /// linalg.copy(%s, %b) 651 /// linalg.matmul ins(%a, %b) outs(%c) 652 /// 653 /// Number of parallel loops = 2 654 /// produceIndexMap : affine_map<(i, j) -> (i, j)> 655 /// consumerLoopToProduceLoops = affine_map<(i, j, k) -> (k, j)> 656 /// submap with only parallel loops = affine_map<(i, j) -> (j)> 657 /// Fused dimensions : j 658 static std::set<unsigned> 659 collectFusableLoops(ArrayRef<LinalgOp> ops, 660 const FusableOpDependencesTy &fusableDependences) { 661 assert(!ops.empty()); 662 auto getNumOuterParallelLoops = [](LinalgOp linalgOp) { 663 return linalgOp.iterator_types() 664 .getValue() 665 .take_while([](Attribute attr) -> bool { 666 return attr.cast<StringAttr>().getValue() == 667 getParallelIteratorTypeName(); 668 }) 669 .size(); 670 }; 671 672 size_t numOuterParallelLoops = getNumOuterParallelLoops(ops.back()); 673 for (auto op : ops.drop_back()) { 674 numOuterParallelLoops = 675 std::min(numOuterParallelLoops, getNumOuterParallelLoops(op)); 676 } 677 678 std::set<unsigned> fusableLoops; 679 auto range = llvm::seq<unsigned>(0, numOuterParallelLoops); 680 fusableLoops.insert(range.begin(), range.end()); 681 682 for (auto op : reverse(ops)) { 683 for (auto dependence : fusableDependences.lookup(op)) { 684 LLVM_DEBUG({ 685 llvm::dbgs() << "\t fusable :"; 686 for (unsigned i : fusableLoops) 687 llvm::dbgs() << " " << i; 688 llvm::dbgs() << "\n"; 689 }); 690 691 Optional<AffineMap> consumerLoopToProducerLoop = 692 getConsumerLoopToProducerLoopMap(dependence); 693 if (!consumerLoopToProducerLoop) { 694 op.emitRemark("failed to get map from consumer loop to producer loop"); 695 return {}; 696 } 697 // todo: This condition is only an implementation limitation. When fusing 698 // the operation, if the accesses in the producer/consumer are transposes 699 // of each other, the loop bounds for the tiled producer can be 700 // manipulated accordingly. This requires some additional bookkeeping in 701 // the implementation of tile+fuse that is defered to later. 702 if (doesTransposeAccess(*consumerLoopToProducerLoop, fusableLoops)) { 703 op.emitRemark("unhandled fusion when fusion requires permutation"); 704 return {}; 705 } 706 707 std::set<unsigned> candidates; 708 for (AffineExpr expr : consumerLoopToProducerLoop->getResults()) { 709 unsigned position = expr.cast<AffineDimExpr>().getPosition(); 710 if (fusableLoops.count(position)) 711 candidates.insert(position); 712 } 713 LLVM_DEBUG({ 714 llvm::dbgs() << "\t candidates :"; 715 for (unsigned i : candidates) 716 llvm::dbgs() << " " << i; 717 llvm::dbgs() << "\n"; 718 }); 719 if (candidates.empty()) 720 return {}; 721 std::swap(candidates, fusableLoops); 722 } 723 } 724 725 return fusableLoops; 726 } 727 728 /// Find all dependences that are fusable. 729 FusableOpDependencesTy mlir::linalg::findAllFusableDependences( 730 ArrayRef<LinalgOp> ops, const LinalgDependenceGraph &dependenceGraph) { 731 FusableOpDependencesTy fusableDependences; 732 // TODO: Currently fusion would not be legal if the fusable dependence is to 733 // the same producer but different indexing map in the consumer. Fix this, but 734 // in the meanwhile disallow such a fusion. 735 DenseMap<Operation *, AffineMap> fusedProducerIndexingMap; 736 for (LinalgOp op : reverse(ops)) { 737 for (auto operandIndex : 738 llvm::seq<unsigned>(0, op.getNumShapedOperands())) { 739 Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> 740 fusableDependence = 741 findFusableProducer(op, operandIndex, dependenceGraph); 742 if (!fusableDependence) 743 continue; 744 LinalgOp producerOp = 745 cast<LinalgOp>(fusableDependence->dependentOpView->getOwner()); 746 // Do not fuse dependences that are to operations not in the same basic 747 // block. This avoid moving fused operations across loops that might 748 // themselves carry dependency making the fusion illegal. 749 if (producerOp->getBlock() != op->getBlock()) { 750 op.emitRemark("unhandled fusion of ops in different basic blocks"); 751 return FusableOpDependencesTy{}; 752 } 753 // Make sure that the indexing map of the view used for fusion in the 754 // producer is a projected permutation. 755 unsigned producerIdx = 756 fusableDependence->dependentOpView->getOperandNumber(); 757 AffineMap producerMap = producerOp.getIndexingMap(producerIdx); 758 if (!producerMap.isProjectedPermutation()) { 759 op.emitRemark( 760 "unhandled non permutation indexing map for fused view in " 761 "producer for operand at index ") 762 << operandIndex; 763 return FusableOpDependencesTy{}; 764 } 765 766 unsigned consumerIdx = 767 fusableDependence->indexingOpView->getOperandNumber(); 768 AffineMap consumerMap = op.getIndexingMap(consumerIdx); 769 if (!consumerMap.isProjectedPermutation()) { 770 op.emitRemark( 771 "unhandled case where indexing map for fused view in the consumer " 772 "is " 773 "not a projected permuration while fusing at index ") 774 << operandIndex; 775 return FusableOpDependencesTy{}; 776 } 777 778 // Check if the producer is already a fusion candidate. Cannot fuse this 779 // dependence if it has a different indexing map when used in the 780 // consumer. 781 if (fusedProducerIndexingMap.count(producerOp.getOperation()) && 782 fusedProducerIndexingMap[producerOp.getOperation()] != consumerMap) { 783 op.emitRemark( 784 "unhandled fusion to the same producer but with different " 785 "indexing maps"); 786 return FusableOpDependencesTy{}; 787 } 788 fusedProducerIndexingMap[producerOp.getOperation()] = consumerMap; 789 790 fusableDependences[producerOp.getOperation()].push_back( 791 *fusableDependence); 792 } 793 } 794 return fusableDependences; 795 } 796 797 /// Tile the fused loops in the root operation, by setting the tile sizes for 798 /// all other loops to zero (those will be tiled later). 799 static Optional<TiledLinalgOp> tileRootOperation( 800 OpBuilder &builder, LinalgOp op, ArrayRef<Value> tileSizeVector, 801 const LinalgTilingOptions &options, const std::set<unsigned> &fusedLoops) { 802 SmallVector<Value, 4> tileSizes(tileSizeVector.begin(), tileSizeVector.end()); 803 auto zero = std_constant_index(0); 804 for (unsigned i = 0, e = tileSizes.size(); i != e; ++i) 805 if (!fusedLoops.count(i)) 806 tileSizes[i] = zero; 807 LinalgTilingOptions tileFusedLoopsOptions = options; 808 tileFusedLoopsOptions.setTileSizes(tileSizes); 809 return tileLinalgOp(builder, op, tileFusedLoopsOptions); 810 } 811 812 /// Fuse the operations in `fusionCandidates` with `tiledOp`. Latter is expected 813 /// to be a tiled operation such that it is valid to fuse all operations in 814 /// `fusionCandidates`, i.e. move the operation within the inter-tile loops of 815 /// `tiledOp`. 816 static SmallVector<LinalgOp, 1> 817 fuseOperations(OpBuilder &builder, LinalgOp tiledOp, 818 ArrayRef<LinalgOp> fusionCandidates, 819 const FusableOpDependencesTy &fusableDependences, 820 const std::set<unsigned> &fusedLoops) { 821 OpBuilder::InsertionGuard guard(builder); 822 builder.setInsertionPoint(tiledOp); 823 DenseMap<unsigned, Range> fusedLoopsAndRanges; 824 for (unsigned loop : fusedLoops) { 825 ShapeDimension shapeDim = getShapeDefiningLoopRange(tiledOp, loop, true); 826 fusedLoopsAndRanges[loop] = getRangeFromOperandShape( 827 builder, tiledOp.getLoc(), shapeDim.shape, shapeDim.dimension); 828 } 829 830 SmallVector<LinalgOp, 1> fusedOps(fusionCandidates.size()); 831 for (auto candidate : enumerate(llvm::reverse(fusionCandidates))) { 832 LinalgOp fusedOp = fuse(builder, candidate.value(), fusedLoopsAndRanges); 833 fusedOps[fusionCandidates.size() - candidate.index() - 1] = fusedOp; 834 builder.setInsertionPoint(fusedOp); 835 } 836 return fusedOps; 837 } 838 839 template <typename LoopType> 840 static Optional<TiledAndFusedLinalgOps> 841 tileAndFuseLinalgOpsImpl(OpBuilder &builder, ArrayRef<LinalgOp> ops, 842 const LinalgDependenceGraph &dependenceGraph, 843 const LinalgTilingOptions &tilingOptions) { 844 if (ops.empty()) 845 return llvm::None; 846 LinalgOp rootOp = ops.back(); 847 for (auto op : enumerate(ops)) { 848 // TODO: Nothing in the fusion of sequence of ops is specific to 849 // buffers. This check can be removed after it is tested on tensors. 850 LinalgOp linalgOp = op.value(); 851 if (!linalgOp.hasBufferSemantics()) { 852 linalgOp.emitError("tile and fuse only tested for buffer operation"); 853 return llvm::None; 854 } 855 } 856 // TODO: Support interchange with tile + fuse. This might actually help do 857 // better fusion. 858 if (!tilingOptions.interchangeVector.empty()) { 859 rootOp.emitError("unable to handle tile and fuse with interchange"); 860 return llvm::None; 861 } 862 863 OpBuilder::InsertionGuard guard(builder); 864 builder.setInsertionPoint(rootOp); 865 ScopedContext scope(builder, rootOp.getLoc()); 866 867 // Find all the producers. 868 FusableOpDependencesTy fusableDependences = 869 findAllFusableDependences(ops, dependenceGraph); 870 if (fusableDependences.empty()) 871 return llvm::None; 872 873 TiledAndFusedLinalgOps ret; 874 // Find the loops that can be tiled and fused. 875 ret.fusedLoopDims = collectFusableLoops(ops, fusableDependences); 876 877 // If there are no fusable dependences or there are no tile+fusable loops, 878 // just return. 879 if (ret.fusedLoopDims.empty()) { 880 return llvm::None; 881 } 882 883 // Tile the fused loops in the last operation in the list. 884 SmallVector<Value, 4> tileSizeVector = 885 tilingOptions.tileSizeComputationFunction(builder, rootOp); 886 Optional<TiledLinalgOp> tiledRootOp = tileRootOperation( 887 builder, rootOp, tileSizeVector, tilingOptions, ret.fusedLoopDims); 888 if (!tiledRootOp) { 889 rootOp.emitError("failed to tile the fused loops"); 890 return llvm::None; 891 } 892 ret.op = tiledRootOp->op; 893 ret.fusedLoops.assign(tiledRootOp->loops.begin(), tiledRootOp->loops.end()); 894 895 // Fuse the other operations into the fused inter-tile loops produced above. 896 ret.fusedProducers = fuseOperations(builder, ret.op, ops.drop_back(), 897 fusableDependences, ret.fusedLoopDims); 898 return ret; 899 } 900 901 Optional<TiledAndFusedLinalgOps> 902 mlir::linalg::tileAndFuseLinalgOps(OpBuilder &builder, ArrayRef<LinalgOp> ops, 903 const LinalgDependenceGraph &dependenceGraph, 904 const LinalgTilingOptions &tilingOptions) { 905 switch (tilingOptions.loopType) { 906 case LinalgTilingLoopType::Loops: 907 return tileAndFuseLinalgOpsImpl<scf::ForOp>(builder, ops, dependenceGraph, 908 tilingOptions); 909 case LinalgTilingLoopType::ParallelLoops: 910 return tileAndFuseLinalgOpsImpl<scf::ParallelOp>( 911 builder, ops, dependenceGraph, tilingOptions); 912 default:; 913 } 914 return llvm::None; 915 } 916