1 //===- ElementwiseOpFusion.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 on tensors operations pass. 10 // 11 //===----------------------------------------------------------------------===// 12 #include "PassDetail.h" 13 #include "mlir/Dialect/Affine/IR/AffineOps.h" 14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 16 #include "mlir/Dialect/Linalg/Passes.h" 17 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 18 #include "mlir/Dialect/Linalg/Utils/Utils.h" 19 #include "mlir/IR/AffineExpr.h" 20 #include "mlir/IR/AffineMap.h" 21 #include "mlir/IR/Matchers.h" 22 #include "mlir/IR/PatternMatch.h" 23 #include "mlir/Support/LLVM.h" 24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 25 26 using namespace mlir; 27 using namespace mlir::linalg; 28 29 /// Append to `fusedOpIndexingMapAttrs` the indexing maps for the operands of 30 /// the `producer` to use in the fused operation given the indexing map of the 31 /// result of the producer in the consumer. 32 static AffineMap getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp( 33 OpOperand *producerOpOperand, AffineMap producerResultIndexMap, 34 AffineMap fusedConsumerArgIndexMap) { 35 // The indexing map in the consumer op (fusedConsumerArgIndexMap) is a map 36 // from consumer loop -> consumer arg tensor index/producer result tensor 37 // index. The fused loop is same as the consumer loop. For each producer arg 38 // the indexing map to be computed is a map from consumer loop -> producer 39 // arg tensor index. 40 // producerResultIndexMap is a map from producer loop -> tensor index. 41 // Compute the inverse to get map from tensor index -> producer loop. 42 // The inverse is a map from producer result tensor index -> producer loop. 43 AffineMap invProducerResultIndexMap = 44 inversePermutation(producerResultIndexMap); 45 assert(invProducerResultIndexMap && 46 "expected producer result indexig map to be invertible"); 47 48 LinalgOp producer = cast<LinalgOp>(producerOpOperand->getOwner()); 49 // argMap is a map from producer loop -> producer arg tensor index. 50 AffineMap argMap = producer.getTiedIndexingMap(producerOpOperand); 51 52 // Compose argMap with invProducerResultIndexMap to get a map from 53 // producer result tensor index -> producer arg tensor index. 54 AffineMap t1 = argMap.compose(invProducerResultIndexMap); 55 56 // Compose t1 with fusedConsumerArgIndexMap gives an indexing map from 57 // consumer loop/ fused loop -> producer arg tensor index. 58 return t1.compose(fusedConsumerArgIndexMap); 59 } 60 61 /// Conditions for elementwise fusion of generic operations. 62 static bool areElementwiseOpsFusable(GenericOp producer, GenericOp consumer, 63 OpOperand *consumerOpOperand) { 64 // Producer and consumer must have tensor semantics. 65 if (!producer.hasTensorSemantics() || !consumer.hasTensorSemantics()) 66 return false; 67 68 // Verify that 69 // - the producer has all "parallel" iterator type. 70 if (producer.getNumParallelLoops() != producer.getNumLoops()) 71 return false; 72 73 // Only allow fusing the producer of an input operand for now. 74 // TODO: allow fusing the producer of an output operand. 75 if (!consumer.isInputTensor(consumerOpOperand)) 76 return false; 77 78 // Get the consumer index map. The number of results of the consumer index 79 // map must match the number of loops of the producer. 80 AffineMap consumerIndexMap = consumer.getTiedIndexingMap(consumerOpOperand); 81 if (consumerIndexMap.getNumResults() != producer.getNumLoops()) 82 return false; 83 84 // Currently support only operations with single result. 85 if (producer.getNumOutputs() != 1) 86 return false; 87 88 // Finally the index_map for the result must be invertible. For now just 89 // verify it is a permutation. 90 AffineMap producerResultIndexMap = 91 producer.getTiedIndexingMap(producer.getOutputOperand(0)); 92 if (!producerResultIndexMap.isPermutation()) 93 return false; 94 95 // Ensure that the fusion does not remove size information required to 96 // get the loop bounds. For non-reduction generics, this is trivially the 97 // case due to the output operand. For reductions, we need to check that after 98 // the fusion, each loop dimension has at least one input that defines it. 99 if ((consumer.getNumReductionLoops())) { 100 llvm::BitVector coveredDims(consumer.getNumLoops(), false); 101 102 auto addToCoveredDims = [&](AffineMap map) { 103 for (auto result : map.getResults()) 104 if (auto dimExpr = result.dyn_cast<AffineDimExpr>()) 105 coveredDims[dimExpr.getPosition()] = true; 106 }; 107 108 for (auto pair : 109 llvm::zip(consumer->getOperands(), consumer.getIndexingMaps())) { 110 Value operand = std::get<0>(pair); 111 if (operand == consumerOpOperand->get()) 112 continue; 113 AffineMap operandMap = std::get<1>(pair); 114 addToCoveredDims(operandMap); 115 } 116 117 for (OpOperand *operand : producer.getInputOperands()) { 118 AffineMap newIndexingMap = 119 getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp( 120 operand, producerResultIndexMap, consumerIndexMap); 121 addToCoveredDims(newIndexingMap); 122 } 123 if (!coveredDims.all()) 124 return false; 125 } 126 127 return true; 128 } 129 130 /// Generate the region of the fused tensor operation. The region of the fused 131 /// op must be empty. 132 static void 133 generateFusedElementwiseOpRegion(PatternRewriter &rewriter, GenericOp fusedOp, 134 AffineMap consumerToProducerLoopsMap, 135 OpOperand *consumerOpOperand, 136 unsigned nloops) { 137 auto producer = cast<GenericOp>(consumerOpOperand->get().getDefiningOp()); 138 auto consumer = cast<GenericOp>(consumerOpOperand->getOwner()); 139 // Build the region of the fused op. 140 Block &producerBlock = producer->getRegion(0).front(); 141 Block &consumerBlock = consumer->getRegion(0).front(); 142 Block *fusedBlock = new Block(); 143 fusedOp.region().push_back(fusedBlock); 144 BlockAndValueMapping mapper; 145 OpBuilder::InsertionGuard guard(rewriter); 146 rewriter.setInsertionPointToStart(fusedBlock); 147 148 // 2. Add an index operation for every fused loop dimension and use the 149 // `consumerToProducerLoopsMap` to map the producer indices. 150 if (producer.hasIndexSemantics()) { 151 // Add an index operation for every fused loop dimension. 152 unsigned numFusedOpLoops = 153 std::max(producer.getNumLoops(), consumer.getNumLoops()); 154 SmallVector<Value> fusedIndices; 155 fusedIndices.reserve(numFusedOpLoops); 156 llvm::transform(llvm::seq<uint64_t>(0, numFusedOpLoops), 157 std::back_inserter(fusedIndices), [&](uint64_t dim) { 158 return rewriter.create<IndexOp>(producer.getLoc(), dim); 159 }); 160 for (IndexOp indexOp : 161 llvm::make_early_inc_range(producerBlock.getOps<IndexOp>())) { 162 Value newIndex = rewriter.create<mlir::AffineApplyOp>( 163 producer.getLoc(), 164 consumerToProducerLoopsMap.getSubMap(indexOp.dim()), fusedIndices); 165 mapper.map(indexOp.getResult(), newIndex); 166 } 167 } 168 // TODO: allow fusing the producer of an output operand. 169 assert(consumer.isInputTensor(consumerOpOperand) && 170 "expected producer of input operand"); 171 // 3. Consumer input operands up to consumerIdx (exclusive). 172 for (BlockArgument bbArg : consumerBlock.getArguments().take_front( 173 consumerOpOperand->getOperandNumber())) // input assumption. 174 mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType())); 175 176 // Replacing consumerIdx requires getting the cloned, yielded, value from 177 // the (cloned) producer block. This happens in step 9. 178 179 // 4. Splice in producer's input operands. 180 for (BlockArgument bbArg : 181 producerBlock.getArguments().take_front(producer.getNumInputs())) 182 mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType())); 183 184 // 4.b. Producer output operand/map that is fused needs to be mapped to the 185 // producer bbArg if it is an "initTensor" (i.e. its value is actually read). 186 assert(producer->getNumResults() == 1 && "expected single result producer"); 187 if (producer.isInitTensor(producer.getOutputOperand(0))) { 188 BlockArgument bbArg = producerBlock.getArguments() 189 .drop_front(producer.getNumInputs()) 190 // TODO: bbArg index of 191 .front(); 192 mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType())); 193 } 194 // 5. Remaining consumer's input operands (drop past index `consumerIdx`). 195 for (BlockArgument bbArg : 196 consumerBlock.getArguments() 197 .take_front(consumer.getNumInputs()) 198 .drop_front(consumerOpOperand->getOperandNumber() + 1)) 199 mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType())); 200 // 6. All of consumer's output operands. 201 for (BlockArgument bbArg : 202 consumerBlock.getArguments().take_back(consumer.getNumOutputs())) 203 mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType())); 204 // 7. All of producer's output operands except the one fused. 205 // TODO: allow fusion of multi-result producers. 206 assert(producer->getNumResults() == 1 && "expected single result producer"); 207 208 // 8. Clone all producer operations except for the yield and index operations 209 // to the fused operation. 210 for (auto &op : producerBlock.without_terminator()) { 211 if (!isa<IndexOp>(op)) 212 rewriter.clone(op, mapper); 213 } 214 // 9. Now we can map the consumerBlock's `consumerIdx` block argument. Just 215 // forward the yield operand. 216 auto yieldOp = cast<linalg::YieldOp>(producerBlock.getTerminator()); 217 // TODO: allow fusion of multi-result producers. 218 assert(producer->getNumResults() == 1 && "expected single result producer"); 219 unsigned producerResultNumber = 0; 220 Value replacement = 221 mapper.lookupOrDefault(yieldOp.getOperand(producerResultNumber)); 222 // Sanity checks, if replacement is not already in the mapper then it must be 223 // produced outside. 224 if (replacement == yieldOp.getOperand(producerResultNumber)) { 225 if (auto bb = replacement.dyn_cast<BlockArgument>()) 226 assert(bb.getOwner() != &producerBlock && 227 "yielded block argument must have been mapped"); 228 else 229 assert(!producer->isAncestor(replacement.getDefiningOp()) && 230 "yielded value must have been mapped"); 231 } 232 mapper.map(consumerBlock.getArgument(consumerOpOperand->getOperandNumber()), 233 replacement); 234 // 10. Clone operations from the consumer to the fused op. 235 for (auto &op : consumerBlock.getOperations()) 236 rewriter.clone(op, mapper); 237 238 // Sanity checks. 239 assert(fusedBlock->getNumArguments() == fusedOp.getNumOperands() && 240 "Ill-formed GenericOp region"); 241 } 242 243 static Optional<SmallVector<Value>> 244 fuseElementwiseOpsImpl(GenericOp producer, OpOperand *consumerOpOperand, 245 const ControlElementwiseOpsFusionFn &controlFn, 246 PatternRewriter &rewriter) { 247 auto consumer = cast<GenericOp>(consumerOpOperand->getOwner()); 248 if (!areElementwiseOpsFusable(producer, consumer, consumerOpOperand) || 249 !controlFn(producer->getResult(0), *consumerOpOperand)) 250 return llvm::None; 251 252 // TODO: allow fusing the producer of an output operand. 253 assert(consumer.isInputTensor(consumerOpOperand) && 254 "expected producer of input operand"); 255 256 // Compute the fused operands list and indexing maps. 257 SmallVector<Value> fusedOperands; 258 SmallVector<AffineMap> fusedIndexMaps; 259 fusedOperands.reserve(producer->getNumOperands() + 260 consumer->getNumOperands()); 261 fusedIndexMaps.reserve(producer->getNumOperands() + 262 consumer->getNumOperands()); 263 // In the following, numbering matches that of `generateFusedTensorOpRegion`. 264 // 3. Consumer input operands/maps up to consumerIdx (exclusive). 265 SmallVector<OpOperand *> consumerInputs = consumer.getInputOperands(); 266 SmallVector<OpOperand *>::iterator it = 267 llvm::find(consumerInputs, consumerOpOperand); 268 assert(it != consumerInputs.end() && "expected to find the consumer operand"); 269 for (OpOperand *opOperand : llvm::make_range(consumerInputs.begin(), it)) { 270 fusedOperands.push_back(opOperand->get()); 271 fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand)); 272 } 273 // 4. Splice in producer's input operands/maps. 274 assert(producer->getNumResults() == 1 && "expected single result producer"); 275 AffineMap producerResultIndexMap = 276 producer.getTiedIndexingMap(producer.getOutputOperand(0)); 277 for (OpOperand *opOperand : producer.getInputOperands()) { 278 fusedOperands.push_back(opOperand->get()); 279 // Compute indexing maps for the producer args in the fused operation. 280 AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp( 281 opOperand, producerResultIndexMap, 282 consumer.getTiedIndexingMap(consumerOpOperand)); 283 fusedIndexMaps.push_back(map); 284 } 285 // 4.b. Producer output operand/map that is fused needs to be passed if it is 286 // an "initTensor" (i.e. its value is actually read). 287 assert(producer->getNumResults() == 1 && "expected single result producer"); 288 if (producer.isInitTensor(producer.getOutputOperand(0))) { 289 fusedOperands.push_back(producer.getOutputOperand(0)->get()); 290 // Compute indexing maps for the producer args in the fused operation. 291 AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp( 292 producer.getOutputOperand(0), producerResultIndexMap, 293 consumer.getTiedIndexingMap(consumerOpOperand)); 294 fusedIndexMaps.push_back(map); 295 } 296 // 5. Remaining consumer's input operands/maps (drop past index 297 // `consumerIdx`). 298 for (OpOperand *opOperand : 299 llvm::make_range(std::next(it), consumerInputs.end())) { 300 fusedOperands.push_back(opOperand->get()); 301 fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand)); 302 } 303 // 6. All of consumer's output operands (skip operands: added by the builder). 304 for (OpOperand *opOperand : consumer.getOutputOperands()) 305 fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand)); 306 // 7. All of producer's output operands/maps except the one fused. 307 // TODO: allow fusion of multi-result producers. 308 assert(producer->getNumResults() == 1 && "expected single result producer"); 309 310 // Generate the fused op. 311 SmallVector<Value> consumerOutputs = consumer.getOutputOperands(); 312 auto fusedOp = rewriter.create<GenericOp>( 313 consumer.getLoc(), consumer->getResultTypes(), 314 /*inputs=*/fusedOperands, 315 // TODO: handle outputs. 316 consumerOutputs, rewriter.getAffineMapArrayAttr(fusedIndexMaps), 317 consumer.iterator_types(), 318 /*doc=*/nullptr, 319 /*library_call=*/nullptr); 320 321 // Construct an AffineMap from consumer loops to producer loops. 322 // consumer loop -> tensor index 323 AffineMap consumerResultIndexMap = 324 consumer.getTiedIndexingMap(consumerOpOperand); 325 // tensor index -> producer loop 326 AffineMap invProducerResultIndexMap = 327 inversePermutation(producerResultIndexMap); 328 assert(invProducerResultIndexMap && 329 "expected producer result indexig map to be invertible"); 330 // consumer loop -> producer loop 331 AffineMap consumerToProducerLoopsMap = 332 invProducerResultIndexMap.compose(consumerResultIndexMap); 333 334 generateFusedElementwiseOpRegion(rewriter, fusedOp, 335 consumerToProducerLoopsMap, 336 consumerOpOperand, consumer.getNumLoops()); 337 return SmallVector<Value>(fusedOp->getResults()); 338 } 339 340 /// Linearize the expressions in `sourceMap` based on the `reassociationMaps` 341 /// provided, given the shape of the source tensor that corresponds to the 342 /// `sourceMap`. Note that this implicitly assumes that the tensors dimensions 343 /// are "row-major" ordered logically. 344 /// 345 /// For example: 346 /// 347 /// %0 = op ... : tensor<?x?x4x5xf32> 348 /// with output index_map `affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>` 349 /// 350 /// and reshape: 351 /// %1 = linalg.tensor_collapse_shape %0 [[0], [0, 1, 2]] : 352 /// tensor<?x?x4x5xf32> into tensor<?x?xf32> 353 /// 354 /// would be rewritten into: 355 /// %0 = op ... : tensor<?x?x4x5xf32> 356 /// with output index_map 357 /// `affine_map<(d0, d1, d2, d3) -> (d0, d1 * 20 + d2 * 5 + d3)>` 358 template <typename TensorReshapeOp> 359 static AffineMap linearizeCollapsedDims(AffineMap sourceMap, 360 TensorReshapeOp reshapeOp) { 361 constexpr bool isExpanding = 362 std::is_same<TensorReshapeOp, TensorExpandShapeOp>::value; 363 ArrayRef<int64_t> sourceShape = 364 (isExpanding ? reshapeOp.getResultType().getShape() 365 : reshapeOp.getSrcType().getShape()); 366 SmallVector<AffineExpr> resultExprs; 367 ArrayRef<AffineExpr> sourceExprs = sourceMap.getResults(); 368 MLIRContext *context = sourceMap.getContext(); 369 370 // Compute the result exprs based on the reassociation maps. 371 for (auto &indices : reshapeOp.getReassociationIndices()) { 372 // Assume that they are in-order and contiguous (already checked in 373 // verifier). 374 assert(!indices.empty()); 375 SmallVector<int64_t> sizes; 376 SmallVector<AffineExpr> dimExprs; 377 for (auto en : llvm::zip(sourceShape.slice(indices[0], indices.size()), 378 sourceExprs.slice(indices[0], indices.size()))) { 379 if (std::get<0>(en) == 1) 380 continue; 381 sizes.push_back(std::get<0>(en)); 382 dimExprs.push_back(std::get<1>(en)); 383 } 384 AffineExpr linearizedExpr = 385 makeCanonicalStridedLayoutExpr(sizes, dimExprs, context); 386 resultExprs.push_back(linearizedExpr); 387 } 388 return AffineMap::get(sourceMap.getNumDims(), sourceMap.getNumSymbols(), 389 resultExprs, context); 390 } 391 392 // TensorExpandShapeOp is fusable with its consumer (i.e. reshape as a 393 // producer). Fusing when operand has higher rank will require use of mods and 394 // divs in the indexing maps of the fused op which would make it non-invertible. 395 static bool isTensorReshapeOpFoldableByLinearization( 396 TensorExpandShapeOp expandOp, AffineMap useIndexMap, bool asProducer) { 397 if (!asProducer) 398 return false; 399 return useIndexMap.isPermutation(); 400 } 401 402 // TensorCollapseShapeOp is fusable with its producer (i.e. reshape as a 403 // consumer). 404 static bool isTensorReshapeOpFoldableByLinearization( 405 TensorCollapseShapeOp collapseOp, AffineMap useIndexMap, bool asProducer) { 406 if (asProducer) 407 return false; 408 return useIndexMap.isPermutation(); 409 } 410 411 /// Check if the reshape operation is only expansion into/collapsing of 412 /// unit-dimension. 413 template <typename TensorReshapeOp> 414 static bool isUnitDimExpansionOnly(TensorReshapeOp reshapeOp) { 415 constexpr bool isExpanding = 416 std::is_same<TensorReshapeOp, TensorExpandShapeOp>::value; 417 ArrayRef<int64_t> expandedShape = 418 (isExpanding ? reshapeOp.getResultType().getShape() 419 : reshapeOp.getSrcType().getShape()); 420 for (auto &indices : reshapeOp.getReassociationIndices()) { 421 unsigned numUnitDims = 0; 422 for (int64_t position : indices) 423 if (expandedShape[position] == 1) 424 numUnitDims++; 425 if (numUnitDims != indices.size() - 1) 426 return false; 427 } 428 return true; 429 } 430 431 /// Conditions for folding a generic operation with a reshape op by expanding 432 /// the iteration space dimensionality for tensor operations. These are 433 /// preconditions assumed by `foldReshapeByDimExpansion` which implements the 434 /// following fusion pattern. 435 /// 436 /// Consider 437 /// 438 /// %c = linalg.generic ins(%a, %b : memref<?x?x?xf32>, memref<?x?xf32>) 439 /// indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d0, d2)>, 440 /// affine_map<(d0, d1, d2) -> (d1, d2)>, 441 /// affine_map<(d0, d1, d2) -> (d0, d2, d1)>] 442 /// %d = linalg.tensor_expand_shape %c [[0, 1], [2], [3, 4, 5]] 443 /// : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32> 444 /// 445 /// The reshape can be folded into the `genericOp` if its loop dimensionality 446 /// is increased to match the result (operand) of the tensor_expand_shape. 447 /// The indexing_map of the fused tensor in the `genericOp` and the 448 /// reassociation map helps compute the indexing maps of the modified op. 449 /// For the above example, based on the reassociation map it 450 /// can be concluded that 451 /// 452 /// - The loop used to access the first dimension of the fused tensor is split 453 /// into two. 454 /// - The loop used to access the second dimension of the fused tensor is kept 455 /// as is. 456 /// - The loop used to access the third dimension of the fused tensor is split 457 /// into three. 458 /// 459 /// i.e. (e0, e1, e2, e3, e4) is the domain of the indexing map of the modified 460 /// op, then 461 /// 462 /// d0 -> e0, e1 463 /// d1 -> e2, e3, e4 464 /// d2 -> e5 465 /// 466 /// substituting this, the generic op can be rewritten as 467 /// 468 /// %d = linalg.generic ins(%0, %1 : ) 469 /// indexing_maps = 470 /// [affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e0, e1, e5)>, 471 /// affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e5)>, 472 /// affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e5, e2, e3, e4)>] 473 /// 474 /// Since operands to the linalg generic are now 5D, reshapes can be introduced 475 /// to make it consistent 476 /// 477 /// %0 = linalg.tensor_expand_shape %a [[0, 1, 2], [3, 4], [5]] 478 /// : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32> 479 /// %1 = linalg.tensor_expand_shape %b [[0, 1, 2], [3]] 480 /// : tensor<?x?x?xf32> into tensor<?x?x?x?xf32> 481 /// 482 /// The added reshapes are again expanding patterns, so they will get fused 483 /// with its producers if possible. 484 static bool isFusableWithReshapeByDimExpansion(GenericOp genericOp, 485 OpOperand *fusableOpOperand) { 486 // Is fusable only if: 487 // - All the indexing maps for operands and results are projected 488 // permutations. 489 // - The fused tensor is not a scalar. 490 // - All the loops are parallel loops. 491 return genericOp.hasTensorSemantics() && 492 llvm::all_of(genericOp.indexing_maps().getValue(), 493 [](Attribute attr) { 494 return attr.cast<AffineMapAttr>() 495 .getValue() 496 .isProjectedPermutation(); 497 }) && 498 genericOp.getTiedIndexingMap(fusableOpOperand).getNumResults() > 0 && 499 llvm::all_of(genericOp.iterator_types(), [](Attribute attr) { 500 return attr.cast<StringAttr>().getValue() == 501 getParallelIteratorTypeName(); 502 }); 503 } 504 505 namespace { 506 /// Information needed to expand a generic operation to fold the reshape with 507 /// it. 508 class ExpansionInfo { 509 public: 510 // Computes the mapping from original dimensions of the op to the dimensions 511 // of the expanded op given the `indexingMap` of the fused operand/result of 512 // the generic op, the `reassocationMaps` of the reshape op and the shape of 513 // the expanded op. 514 LogicalResult compute(LinalgOp linalgOp, OpOperand *fusableOpOperand, 515 ArrayRef<AffineMap> reassociationMaps, 516 ArrayRef<int64_t> expandedShape, 517 PatternRewriter &rewriter); 518 unsigned getOrigOpNumDims() const { return reassociation.size(); } 519 unsigned getExpandedOpNumDims() const { return expandedOpNumDims; } 520 ReassociationIndicesRef getExpandedDims(unsigned i) const { 521 return reassociation[i]; 522 } 523 ArrayRef<int64_t> getExpandedShapeOfDim(unsigned i) const { 524 return expandedShapeMap[i]; 525 } 526 527 private: 528 /// Reassociation from the dimensions in the original operation to the 529 /// dimension of the expanded operation. 530 SmallVector<ReassociationIndices> reassociation; 531 /// Mapping from extent of loops in the original operation, to the extent of 532 /// loops in the expanded operation. 533 SmallVector<SmallVector<int64_t>> expandedShapeMap; 534 unsigned expandedOpNumDims; 535 }; 536 } // namespace 537 538 LogicalResult ExpansionInfo::compute(LinalgOp linalgOp, 539 OpOperand *fusableOpOperand, 540 ArrayRef<AffineMap> reassociationMaps, 541 ArrayRef<int64_t> expandedShape, 542 PatternRewriter &rewriter) { 543 if (reassociationMaps.empty()) 544 return failure(); 545 AffineMap fusedIndexMap = linalgOp.getTiedIndexingMap(fusableOpOperand); 546 547 Optional<SmallVector<int64_t, 4>> originalLoopRange = 548 linalgOp.getStaticLoopRanges(); 549 if (!originalLoopRange) 550 return rewriter.notifyMatchFailure(linalgOp, "unable to find loop range"); 551 552 reassociation.clear(); 553 expandedShapeMap.clear(); 554 // Compute the number of dimension in the expanded op that correspond to each 555 // dimension of the original op. 556 SmallVector<unsigned> numExpandedDims(fusedIndexMap.getNumDims(), 1); 557 expandedShapeMap.resize(fusedIndexMap.getNumDims()); 558 for (auto resultExpr : llvm::enumerate(fusedIndexMap.getResults())) { 559 unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition(); 560 AffineMap foldedDims = reassociationMaps[resultExpr.index()]; 561 numExpandedDims[pos] = foldedDims.getNumResults(); 562 ArrayRef<int64_t> shape = 563 expandedShape.slice(foldedDims.getDimPosition(0), numExpandedDims[pos]); 564 expandedShapeMap[pos].assign(shape.begin(), shape.end()); 565 } 566 // The remaining dimensions remain the same. 567 for (unsigned i : llvm::seq<unsigned>(0, fusedIndexMap.getNumDims())) 568 if (expandedShapeMap[i].empty()) 569 expandedShapeMap[i] = {(*originalLoopRange)[i]}; 570 571 // Compute reassociation map from the original op to the expanded op. 572 unsigned sum = 0; 573 reassociation.reserve(fusedIndexMap.getNumDims()); 574 for (auto numFoldedDim : llvm::enumerate(numExpandedDims)) { 575 auto seq = llvm::seq<int64_t>(sum, sum + numFoldedDim.value()); 576 reassociation.emplace_back(seq.begin(), seq.end()); 577 sum += numFoldedDim.value(); 578 } 579 expandedOpNumDims = sum; 580 return success(); 581 } 582 583 /// Epanding the body of a linalg operation requires adaptations of the accessed 584 /// loop indices. Specifically, access of indices in the original operation need 585 /// to be replaced with linearizations of indices in the expanded op. That 586 /// requires the shape of the expanded dimensions to be static (at least all but 587 /// the most significant). For now check that these are all statically sized. 588 /// Note that this could be extended to handle dynamic case, but the 589 /// implementation below uses `affine.apply` which seems to have issues when the 590 /// shapes are not static. 591 LogicalResult isGenericOpExpandable(GenericOp genericOp, 592 const ExpansionInfo &expansionInfo, 593 PatternRewriter &rewriter) { 594 if (!genericOp.hasIndexSemantics()) 595 return success(); 596 for (unsigned i : llvm::seq<unsigned>(0, expansionInfo.getOrigOpNumDims())) { 597 ArrayRef<int64_t> expandedShape = expansionInfo.getExpandedShapeOfDim(i); 598 if (expandedShape.size() == 1) 599 continue; 600 for (int64_t shape : expandedShape.drop_front()) { 601 if (ShapedType::isDynamic(shape)) { 602 return rewriter.notifyMatchFailure( 603 genericOp, "cannot expand due to index semantics and dynamic dims"); 604 } 605 } 606 } 607 return success(); 608 } 609 610 /// Return the indexing map to use in the expanded op for a given the 611 /// `indexingMap` of the original operation. 612 static AffineMap 613 getIndexingMapInExpandedOp(OpBuilder &builder, AffineMap indexingMap, 614 const ExpansionInfo &expansionInfo) { 615 SmallVector<AffineExpr> newExprs; 616 for (AffineExpr expr : indexingMap.getResults()) { 617 unsigned pos = expr.cast<AffineDimExpr>().getPosition(); 618 SmallVector<AffineExpr, 4> expandedExprs = llvm::to_vector<4>( 619 llvm::map_range(expansionInfo.getExpandedDims(pos), [&](int64_t v) { 620 return builder.getAffineDimExpr(static_cast<unsigned>(v)); 621 })); 622 newExprs.append(expandedExprs.begin(), expandedExprs.end()); 623 } 624 return AffineMap::get(expansionInfo.getExpandedOpNumDims(), 625 indexingMap.getNumSymbols(), newExprs, 626 builder.getContext()); 627 } 628 629 /// Return the type of the operand/result to use in the expanded op given the 630 /// type in the original op. 631 static RankedTensorType getExpandedType(RankedTensorType originalType, 632 AffineMap indexingMap, 633 const ExpansionInfo &expansionInfo) { 634 SmallVector<int64_t> expandedShape; 635 for (AffineExpr expr : indexingMap.getResults()) { 636 unsigned dim = expr.cast<AffineDimExpr>().getPosition(); 637 auto dimExpansion = expansionInfo.getExpandedShapeOfDim(dim); 638 expandedShape.append(dimExpansion.begin(), dimExpansion.end()); 639 } 640 return RankedTensorType::get(expandedShape, originalType.getElementType()); 641 } 642 643 /// Returns the reassociation maps to use in the `linalg.tensor_expand_shape` 644 /// operation to convert the operands of the original operation to operands of 645 /// the expanded operation. The same method is used to compute the 646 /// `linalg.tensor_collapse_shape` used to collapse the result of the expanded 647 /// op to get the value that can replace all uses of the results of the original 648 /// op. 649 static SmallVector<ReassociationIndices> 650 getReassociationForExpansion(AffineMap indexingMap, 651 const ExpansionInfo &expansionInfo) { 652 SmallVector<ReassociationIndices> reassociation; 653 unsigned numReshapeDims = 0; 654 for (AffineExpr expr : indexingMap.getResults()) { 655 unsigned dim = expr.cast<AffineDimExpr>().getPosition(); 656 auto numExpandedDims = expansionInfo.getExpandedDims(dim).size(); 657 SmallVector<int64_t, 2> indices = llvm::to_vector<2>( 658 llvm::seq<int64_t>(numReshapeDims, numReshapeDims + numExpandedDims)); 659 reassociation.emplace_back(std::move(indices)); 660 numReshapeDims += numExpandedDims; 661 } 662 return reassociation; 663 } 664 665 /// Update the body of an expanded linalg operation having index semantics. The 666 /// indices of the original operation need to be recovered by linearizing the 667 /// indices of the correspoding dimensions of the expanded operation. For now it 668 /// is assumed that the shapes of the expanded operation needed for 669 /// linearization are static. 670 static void updateExpandedGenericOpRegion(PatternRewriter &rewriter, 671 Location loc, Region &fusedRegion, 672 const ExpansionInfo &expansionInfo) { 673 // Replace the original indices by the linearization of the expanded indices. 674 for (IndexOp indexOp : 675 llvm::make_early_inc_range(fusedRegion.front().getOps<IndexOp>())) { 676 ArrayRef<int64_t> expandedDims = 677 expansionInfo.getExpandedDims(indexOp.dim()); 678 assert(!expandedDims.empty() && "expected valid expansion info"); 679 680 // Skip index operations that are not affected by the expansion. 681 if (expandedDims.size() == 1 && 682 expandedDims.front() == (int64_t)indexOp.dim()) 683 continue; 684 685 // Linearize the expanded indices of the original index dimension. 686 OpBuilder::InsertionGuard guard(rewriter); 687 rewriter.setInsertionPointAfter(indexOp); 688 ArrayRef<int64_t> expandedDimsShape = 689 expansionInfo.getExpandedShapeOfDim(indexOp.dim()).drop_front(); 690 SmallVector<Value> expandedIndices; 691 expandedIndices.reserve(expandedDims.size() - 1); 692 llvm::transform( 693 expandedDims.drop_front(), std::back_inserter(expandedIndices), 694 [&](int64_t dim) { return rewriter.create<IndexOp>(loc, dim); }); 695 Value newIndex = rewriter.create<IndexOp>(loc, expandedDims.front()); 696 for (auto it : llvm::zip(expandedDimsShape, expandedIndices)) { 697 assert(!ShapedType::isDynamic(std::get<0>(it))); 698 AffineExpr idx, acc; 699 bindDims(rewriter.getContext(), idx, acc); 700 newIndex = rewriter.create<AffineApplyOp>( 701 indexOp.getLoc(), idx + acc * std::get<0>(it), 702 ValueRange{std::get<1>(it), newIndex}); 703 } 704 rewriter.replaceOp(indexOp, newIndex); 705 } 706 } 707 708 /// Implements the fusion of a tensor_collapse_shape or a tensor_expand_shape op 709 /// and a generic op as explained in `isFusableWithReshapeByExpansion`. Assumes 710 /// that those conditions have been satisfied. 711 static Optional<SmallVector<Value>> 712 fuseWithReshapeByExpansion(GenericOp genericOp, Operation *reshapeOp, 713 OpOperand *fusableOpOperand, 714 PatternRewriter &rewriter) { 715 assert(isFusableWithReshapeByDimExpansion(genericOp, fusableOpOperand) && 716 "preconditions for fuse operation failed"); 717 // Check if reshape is expanding or collapsing. 718 auto expandingReshapeOp = dyn_cast<TensorExpandShapeOp>(*reshapeOp); 719 auto collapsingReshapeOp = dyn_cast<TensorCollapseShapeOp>(*reshapeOp); 720 bool isExpanding = (expandingReshapeOp != nullptr); 721 RankedTensorType expandedType = isExpanding 722 ? expandingReshapeOp.getResultType() 723 : collapsingReshapeOp.getSrcType(); 724 725 ExpansionInfo expansionInfo; 726 if (failed(expansionInfo.compute( 727 genericOp, fusableOpOperand, 728 isExpanding ? expandingReshapeOp.getReassociationMaps() 729 : collapsingReshapeOp.getReassociationMaps(), 730 expandedType.getShape(), rewriter))) 731 return llvm::None; 732 733 if (failed(isGenericOpExpandable(genericOp, expansionInfo, rewriter))) 734 return llvm::None; 735 736 SmallVector<AffineMap, 4> expandedOpIndexingMaps = llvm::to_vector<4>( 737 llvm::map_range(genericOp.getIndexingMaps(), [&](AffineMap m) { 738 return getIndexingMapInExpandedOp(rewriter, m, expansionInfo); 739 })); 740 741 SmallVector<Value> expandedOpOperands; 742 expandedOpOperands.reserve(genericOp.getNumInputs()); 743 for (OpOperand *opOperand : genericOp.getInputOperands()) { 744 if (opOperand == fusableOpOperand) { 745 expandedOpOperands.push_back(isExpanding ? expandingReshapeOp.src() 746 : collapsingReshapeOp.src()); 747 continue; 748 } 749 if (genericOp.isInputTensor(opOperand)) { 750 AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand); 751 RankedTensorType expandedOperandType = 752 getExpandedType(opOperand->get().getType().cast<RankedTensorType>(), 753 indexingMap, expansionInfo); 754 if (expandedOperandType != opOperand->get().getType()) { 755 // Reshape the operand to get the right type. 756 SmallVector<ReassociationIndices> reassociation = 757 getReassociationForExpansion(indexingMap, expansionInfo); 758 expandedOpOperands.push_back(rewriter.create<TensorExpandShapeOp>( 759 genericOp.getLoc(), expandedOperandType, opOperand->get(), 760 reassociation)); 761 continue; 762 } 763 } 764 expandedOpOperands.push_back(opOperand->get()); 765 } 766 767 Location loc = genericOp.getLoc(); 768 SmallVector<Value> outputs; 769 for (OpOperand *opOperand : genericOp.getOutputOperands()) { 770 AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand); 771 RankedTensorType expandedOutputType = 772 getExpandedType(opOperand->get().getType().cast<RankedTensorType>(), 773 indexingMap, expansionInfo); 774 if (expandedOutputType != opOperand->get().getType()) { 775 SmallVector<ReassociationIndices> reassociation = 776 getReassociationForExpansion(indexingMap, expansionInfo); 777 outputs.push_back(rewriter.create<TensorExpandShapeOp>( 778 genericOp.getLoc(), expandedOutputType, opOperand->get(), 779 reassociation)); 780 } 781 } 782 783 // The iterator types of the expanded op are all parallel. 784 SmallVector<StringRef> iteratorTypes(expansionInfo.getExpandedOpNumDims(), 785 getParallelIteratorTypeName()); 786 787 TypeRange resultTypes = ValueRange(outputs).getTypes(); 788 auto fusedOp = 789 rewriter.create<GenericOp>(genericOp.getLoc(), resultTypes, 790 /*inputs=*/expandedOpOperands, outputs, 791 expandedOpIndexingMaps, iteratorTypes); 792 Region &fusedRegion = fusedOp->getRegion(0); 793 Region &originalRegion = genericOp->getRegion(0); 794 rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.begin()); 795 796 // Update the index accesses after the expansion. 797 updateExpandedGenericOpRegion(rewriter, loc, fusedRegion, expansionInfo); 798 799 // Reshape the result values to their original shape if this is a collapsing 800 // reshape folded into its consumer. 801 SmallVector<Value> resultVals; 802 for (OpResult opResult : genericOp->getOpResults()) { 803 int64_t resultNumber = opResult.getResultNumber(); 804 if (!isExpanding && resultTypes[resultNumber] != opResult.getType()) { 805 SmallVector<ReassociationIndices> reassociation = 806 getReassociationForExpansion( 807 genericOp.getTiedIndexingMap( 808 genericOp.getOutputOperand(resultNumber)), 809 expansionInfo); 810 resultVals.push_back(rewriter.create<TensorCollapseShapeOp>( 811 genericOp.getLoc(), opResult.getType(), 812 fusedOp->getResult(resultNumber), reassociation)); 813 } else { 814 resultVals.push_back(fusedOp->getResult(resultNumber)); 815 } 816 } 817 // Assuming a single result. 818 return resultVals; 819 } 820 821 namespace { 822 823 /// Pattern to fold tensor_expand_shape op with its consumer by using the source 824 /// of the reshape op as the operand in the consumer (instead of the result of 825 /// the tensor_collapse_shape). The corresponding index map in the consumer 826 /// needs to be modified to linearize the folded dimension. 827 /// 828 /// For example, 829 /// 830 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)> 831 /// %0 = linalg.tensor_expand_shape %arg0 [[0], [1, 2], [3]] 832 /// tensor<?x?x?xf32> into tensor<?x?x4x?xf32> 833 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... } 834 /// ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ... 835 /// -> tensor<?x?x4x?xf32> 836 /// 837 /// can be folded into 838 /// 839 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)> 840 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)> 841 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... } 842 /// ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ... 843 /// -> tensor<?x?x4x?xf32> 844 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp> 845 struct FoldProducerReshapeOpByLinearization 846 : public OpRewritePattern<GenericOp> { 847 using OpRewritePattern<GenericOp>::OpRewritePattern; 848 849 LogicalResult matchAndRewrite(GenericOp genericOp, 850 PatternRewriter &rewriter) const override { 851 if (!genericOp.hasTensorSemantics()) 852 return failure(); 853 SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands(); 854 for (auto en : llvm::enumerate(inputOperands)) { 855 auto reshapeOp = en.value()->get().getDefiningOp<TensorReshapeOp>(); 856 if (!reshapeOp) 857 continue; 858 859 if (!isTensorReshapeOpFoldableByLinearization( 860 reshapeOp, genericOp.getTiedIndexingMap(en.value()), 861 /*asProducer =*/true) || 862 (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp))) 863 continue; 864 865 // Compute the fused operands list, 866 SmallVector<Value> fusedOperands = genericOp.getInputOperands(); 867 fusedOperands[en.index()] = reshapeOp.src(); 868 SmallVector<Value> outputOperands = genericOp.getOutputOperands(); 869 llvm::append_range(fusedOperands, outputOperands); 870 871 // Compute indexing_maps for the fused operation. The indexing_maps for 872 // the operands of the consumers that arent fused are the same. 873 SmallVector<AffineMap> fusedIndexMaps = genericOp.getIndexingMaps(); 874 875 // Accepted consumer maps are either identity or permutation. 876 auto invMap = inversePermutation(fusedIndexMaps[en.index()]); 877 878 // Compute the indexing map to use for the result of the producer. 879 AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp); 880 // The modified map cannot have symbols. 881 if (modifiedMap.getNumSymbols()) 882 return failure(); 883 for (AffineExpr expr : modifiedMap.getResults()) { 884 if (!expr.isPureAffine()) 885 return failure(); 886 } 887 fusedIndexMaps[en.index()] = modifiedMap; 888 889 // Further check that the resulting index maps can be fused and 890 // inverted. Without this the resultant op is not legal. 891 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 892 return rewriter.notifyMatchFailure( 893 genericOp, "fused op loop bound computation failed"); 894 } 895 896 rewriter.startRootUpdate(genericOp); 897 genericOp->setOperands(fusedOperands); 898 genericOp.indexing_mapsAttr( 899 rewriter.getAffineMapArrayAttr(fusedIndexMaps)); 900 rewriter.finalizeRootUpdate(genericOp); 901 return success(); 902 } 903 return failure(); 904 } 905 }; 906 907 static SmallVector<ReassociationIndices> 908 getReassociationIndices(ArrayRef<AffineMap> maps) { 909 SmallVector<ReassociationIndices> reassociation; 910 for (AffineMap map : maps) { 911 ReassociationIndices indices; 912 for (unsigned i = 0, e = map.getNumResults(); i < e; i++) { 913 unsigned pos = map.getResult(i).cast<AffineDimExpr>().getPosition(); 914 indices.push_back(pos); 915 } 916 reassociation.push_back(indices); 917 } 918 return reassociation; 919 } 920 921 /// Pattern to move rank reducing reshape after an elementwise linalg generic 922 /// op. This is useful to expose more fusion opportunities between named ops and 923 /// generic ops. This can only be done if there is no broadcast or permuation 924 /// within the dimensions we need to merge. 925 /// 926 /// For example, 927 /// 928 /// %0 = linalg.tensor_expand_shape %A [[0, 1], [2]] 929 /// : tensor<12544x16xf32> into tensor<112x112x16xf32> 930 /// %2 = linalg.generic {indexing_maps = [ 931 /// affine_map<(d0, d1, d2) -> (d0, d1, d2)>, 932 /// affine_map<(d0, d1, d2) -> (d2)>, 933 /// affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = 934 /// ["parallel", "parallel", "parallel"]} { 935 /// } -> tensor<112x112x16xf32> 936 /// 937 /// into 938 /// 939 /// %2 = linalg.generic {indexing_maps = [ 940 /// affine_map<(d0, d1) -> (d0, d1)>, 941 /// affine_map<(d0, d1) -> (d1)>, 942 /// affine_map<(d0, d1) -> (d0, d1)>], 943 /// iterator_types = ["parallel", "parallel"]} ins(%arg0, %arg1 944 /// : tensor<12544x16xf32>, tensor<16xf32>) outs(%1 : tensor<12544x16xf32>) { 945 /// } -> tensor<12544x16xf32> 946 /// %3 = linalg.tensor_expand_shape %2 [[0, 1], [2]] 947 /// : tensor<12544x16xf32> into tensor<112x112x16xf32> 948 struct PushExpandingReshape : public OpRewritePattern<GenericOp> { 949 using OpRewritePattern<GenericOp>::OpRewritePattern; 950 951 LogicalResult matchAndRewrite(GenericOp genericOp, 952 PatternRewriter &rewriter) const override { 953 // Only apply to elementwise linalg on tensor. 954 if (!genericOp.hasTensorSemantics() || 955 genericOp.getNumParallelLoops() != genericOp.getNumLoops()) 956 return failure(); 957 // Only support identity output maps. It could be extended to permuations if 958 // needed. 959 if (llvm::any_of(genericOp.getOutputOperands(), [&](OpOperand *opOperand) { 960 return !genericOp.getTiedIndexingMap(opOperand).isIdentity(); 961 })) 962 return failure(); 963 int64_t destRank = genericOp.getNumParallelLoops(); 964 SmallVector<Value> newOperands = genericOp.getInputOperands(); 965 TensorExpandShapeOp reshapeFound; 966 // 1. Look for tensor_expand_shape operands and figure out save the 967 // dimensions merged. 968 SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands(); 969 for (auto en : llvm::enumerate(inputOperands)) { 970 auto reshapeOp = 971 en.value()->get().template getDefiningOp<TensorExpandShapeOp>(); 972 if (!reshapeOp) 973 continue; 974 // TODO: We could support non-identity map as long as the merged 975 // dimensions are still contiguous. 976 if (!genericOp.getTiedIndexingMap(en.value()).isIdentity()) 977 continue; 978 if (reshapeFound) { 979 // Only support a second reshape op if it has the same reassociate maps. 980 if (reshapeFound.getReassociationMaps() == 981 reshapeOp.getReassociationMaps()) 982 newOperands[en.index()] = reshapeOp.src(); 983 continue; 984 } 985 reshapeFound = reshapeOp; 986 newOperands[en.index()] = reshapeOp.src(); 987 } 988 if (!reshapeFound) 989 return failure(); 990 991 // Calculate the reassociation indices and rassociated reverse map. 992 SmallVector<ReassociationIndices> reassociation = 993 getReassociationIndices(reshapeFound.getReassociationMaps()); 994 SmallVector<unsigned> remap(destRank); 995 for (auto &indices : llvm::enumerate(reassociation)) { 996 for (int64_t index : indices.value()) { 997 remap[index] = indices.index(); 998 } 999 } 1000 // 2. Verify that we can merge the dimensions in the linalg and that we 1001 // don't need to create new reshapes operands. Inserting new reshape 1002 // operands would defeat the purpose of the transformation. 1003 for (auto en : llvm::enumerate(inputOperands)) { 1004 if (en.value()->get() == newOperands[en.index()]) { 1005 AffineMap map = genericOp.getTiedIndexingMap(en.value()); 1006 for (unsigned i : llvm::seq(unsigned(0), map.getNumResults())) { 1007 if (reassociation[remap[map.getDimPosition(i)]].size() > 1) 1008 return failure(); 1009 } 1010 } 1011 } 1012 1013 // 3. Calculate the affine map remapping and the reassociation to apply to 1014 // output tensors. 1015 SmallVector<AffineMap> newMaps; 1016 unsigned newRank = reassociation.size(); 1017 for (auto map : genericOp.getIndexingMaps()) { 1018 SmallVector<AffineExpr> newExprs; 1019 for (auto expr : map.getResults()) { 1020 unsigned position = expr.template cast<AffineDimExpr>().getPosition(); 1021 // Skip dimension merged except for the last of the group. 1022 if (reassociation[remap[position]].back() == position) { 1023 newExprs.push_back( 1024 getAffineDimExpr(remap[position], genericOp.getContext())); 1025 } 1026 } 1027 newMaps.push_back( 1028 AffineMap::get(newRank, 0, newExprs, genericOp.getContext())); 1029 } 1030 1031 // 4. Reshape the output tensors. 1032 SmallVector<Value> newOutputs; 1033 SmallVector<Type> newOutputTypes; 1034 for (auto output : genericOp.outputs()) { 1035 auto newOutputType = RankedTensorType::get( 1036 reshapeFound.getSrcType().getShape(), 1037 output.getType().template cast<RankedTensorType>().getElementType()); 1038 Value newOutput = rewriter.create<TensorCollapseShapeOp>( 1039 genericOp->getLoc(), newOutputType, output, reassociation); 1040 newOutputTypes.push_back(newOutputType); 1041 newOutputs.push_back(newOutput); 1042 } 1043 // 5. Create a new generic op with lowerer rank. 1044 SmallVector<StringRef> iteratorTypes(newRank, 1045 getParallelIteratorTypeName()); 1046 auto newOp = rewriter.create<GenericOp>(genericOp->getLoc(), newOutputTypes, 1047 newOperands, newOutputs, newMaps, 1048 iteratorTypes); 1049 rewriter.inlineRegionBefore(genericOp.region(), newOp.region(), 1050 newOp.region().begin()); 1051 // 6. Reshape the so that the type matches the uses. 1052 SmallVector<Value> newResults; 1053 for (auto result : llvm::enumerate(newOp->getResults())) { 1054 newResults.push_back(rewriter.create<TensorExpandShapeOp>( 1055 genericOp->getLoc(), genericOp.getOutputTensorTypes()[result.index()], 1056 result.value(), reassociation)); 1057 } 1058 rewriter.replaceOp(genericOp, newResults); 1059 return success(); 1060 } 1061 }; 1062 1063 /// Pattern to fuse a tensor_collapse_shape op with its consumer generic op, 1064 /// when the reshape op is collapsing dimensions. The dimensionality of the loop 1065 /// in the consumer is expanded. 1066 class FoldWithProducerReshapeOpByExpansion 1067 : public OpRewritePattern<GenericOp> { 1068 public: 1069 FoldWithProducerReshapeOpByExpansion( 1070 MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes, 1071 PatternBenefit benefit = 1) 1072 : OpRewritePattern<GenericOp>(context, benefit), 1073 controlFoldingReshapes(foldReshapes) {} 1074 1075 LogicalResult matchAndRewrite(GenericOp genericOp, 1076 PatternRewriter &rewriter) const override { 1077 for (OpOperand *opOperand : genericOp.getInputTensorOperands()) { 1078 TensorCollapseShapeOp reshapeOp = 1079 opOperand->get().getDefiningOp<TensorCollapseShapeOp>(); 1080 if (!reshapeOp) 1081 continue; 1082 // Fold only if 1083 // - The tensor reshape op is folding. 1084 // - All constraints of fusing with reshape by expansion are met. 1085 if (!isFusableWithReshapeByDimExpansion(genericOp, opOperand) || 1086 (!controlFoldingReshapes(reshapeOp->getResult(0), *opOperand))) 1087 continue; 1088 1089 Optional<SmallVector<Value>> replacementValues = 1090 fuseWithReshapeByExpansion(genericOp, reshapeOp, opOperand, rewriter); 1091 if (!replacementValues) 1092 return failure(); 1093 rewriter.replaceOp(genericOp, replacementValues.getValue()); 1094 return success(); 1095 } 1096 return failure(); 1097 } 1098 1099 private: 1100 ControlElementwiseOpsFusionFn controlFoldingReshapes; 1101 }; 1102 1103 /// Pattern to fold tensor_collapse_shape or tensor_expand_shape op with its 1104 /// producer. The corresponding index map in the consumer needs to be modified 1105 /// to linearize the folded dimension. 1106 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp> 1107 struct FoldConsumerReshapeOpByLinearization 1108 : public OpRewritePattern<TensorReshapeOp> { 1109 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 1110 1111 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 1112 PatternRewriter &rewriter) const override { 1113 GenericOp producer = reshapeOp.src().template getDefiningOp<GenericOp>(); 1114 if (!producer || !producer.hasTensorSemantics() || 1115 producer.getNumOutputs() != 1 || 1116 !isTensorReshapeOpFoldableByLinearization( 1117 reshapeOp, 1118 producer.getTiedIndexingMap(producer.getOutputOperand(0)), 1119 /*asProducer =*/false) || 1120 (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp))) 1121 return failure(); 1122 // The indexing_maps for the operands of the fused operation are same as 1123 // those for the operands of the producer. 1124 SmallVector<AffineMap> fusedIndexMaps = producer.getIndexingMaps(); 1125 1126 auto invMap = inversePermutation( 1127 producer.getTiedIndexingMap(producer.getOutputOperand(0))); 1128 1129 // Compute the indexing map to use for the operand of the producer. 1130 AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp); 1131 for (AffineExpr expr : modifiedMap.getResults()) { 1132 if (!expr.isPureAffine()) { 1133 return rewriter.notifyMatchFailure( 1134 producer, "fused op indexing map is not affine"); 1135 } 1136 } 1137 fusedIndexMaps.back() = modifiedMap; 1138 1139 // Further check that the resulting index maps can be fused and 1140 // inverted. Without this the resultant op is not legal. 1141 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 1142 return rewriter.notifyMatchFailure( 1143 producer, "fused op loop bound computation failed"); 1144 } 1145 1146 Location loc = producer.getLoc(); 1147 SmallVector<Value> inputOperands = producer.getInputOperands(); 1148 Value output = rewriter.create<TensorReshapeOp>( 1149 loc, producer.getOutputOperand(0)->get(), 1150 reshapeOp.getReassociationExprs()); 1151 auto fusedOp = rewriter.create<GenericOp>( 1152 loc, reshapeOp.getResultType(), 1153 /*inputs=*/inputOperands, 1154 // TODO: handle outputs. 1155 /*outputs=*/output, rewriter.getAffineMapArrayAttr(fusedIndexMaps), 1156 producer.iterator_types(), 1157 /*doc=*/nullptr, 1158 /*library_call=*/nullptr); 1159 auto &fusedRegion = fusedOp->getRegion(0); 1160 rewriter.cloneRegionBefore(producer->getRegion(0), fusedRegion, 1161 fusedRegion.begin()); 1162 rewriter.replaceOp(reshapeOp, fusedOp->getResults()); 1163 return success(); 1164 } 1165 }; 1166 1167 /// Pattern to fold a tensor_expand_shape op with its producer generic op 1168 /// by expanding the dimensionality of the loop in the producer op. 1169 struct FoldReshapeWithGenericOpByExpansion 1170 : public OpRewritePattern<TensorExpandShapeOp> { 1171 1172 FoldReshapeWithGenericOpByExpansion( 1173 MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes, 1174 PatternBenefit benefit = 1) 1175 : OpRewritePattern<TensorExpandShapeOp>(context, benefit), 1176 controlFoldingReshapes(foldReshapes) {} 1177 1178 LogicalResult matchAndRewrite(TensorExpandShapeOp reshapeOp, 1179 PatternRewriter &rewriter) const override { 1180 // Fold only if all constraints of fusing with reshape by expansion are met. 1181 GenericOp producer = reshapeOp.src().getDefiningOp<GenericOp>(); 1182 if (!producer || producer.getNumOutputs() != 1 || 1183 !isFusableWithReshapeByDimExpansion(producer, 1184 producer.getOutputOperand(0)) || 1185 !controlFoldingReshapes(producer->getResult(0), 1186 reshapeOp->getOpOperand(0))) 1187 return failure(); 1188 Optional<SmallVector<Value>> replacementValues = fuseWithReshapeByExpansion( 1189 producer, reshapeOp, producer.getOutputOperand(0), rewriter); 1190 if (!replacementValues) 1191 return failure(); 1192 rewriter.replaceOp(reshapeOp, replacementValues.getValue()); 1193 return success(); 1194 } 1195 1196 private: 1197 ControlElementwiseOpsFusionFn controlFoldingReshapes; 1198 }; 1199 1200 /// Pattern to fold a generic op with a splat constant/scalar constant. Does not 1201 /// handle cases where the constant is not single-valued. 1202 class FoldScalarOrSplatConstant : public OpRewritePattern<GenericOp> { 1203 public: 1204 FoldScalarOrSplatConstant(MLIRContext *context, 1205 ControlElementwiseOpsFusionFn &fun, 1206 PatternBenefit benefit = 1) 1207 : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {} 1208 1209 LogicalResult matchAndRewrite(GenericOp genericOp, 1210 PatternRewriter &rewriter) const override { 1211 if (!genericOp.hasTensorSemantics()) 1212 return failure(); 1213 for (OpOperand *opOperand : genericOp.getInputOperands()) { 1214 Operation *def = opOperand->get().getDefiningOp(); 1215 Attribute constantAttr; 1216 auto isScalarOrSplatConstantOp = [&constantAttr](Operation *def) -> bool { 1217 { 1218 DenseElementsAttr splatAttr; 1219 if (matchPattern(def, m_Constant<DenseElementsAttr>(&splatAttr)) && 1220 splatAttr.isSplat() && 1221 splatAttr.getType().getElementType().isIntOrFloat()) { 1222 constantAttr = splatAttr.getSplatValue<Attribute>(); 1223 return true; 1224 } 1225 } 1226 { 1227 IntegerAttr intAttr; 1228 if (matchPattern(def, m_Constant<IntegerAttr>(&intAttr))) { 1229 constantAttr = intAttr; 1230 return true; 1231 } 1232 } 1233 { 1234 FloatAttr floatAttr; 1235 if (matchPattern(def, m_Constant<FloatAttr>(&floatAttr))) { 1236 constantAttr = floatAttr; 1237 return true; 1238 } 1239 } 1240 return false; 1241 }; 1242 1243 auto resultValue = opOperand->get().dyn_cast<OpResult>(); 1244 if (!def || !resultValue || !isScalarOrSplatConstantOp(def) || 1245 !controlFn(resultValue, *opOperand)) 1246 continue; 1247 1248 // The operands and the indexing_maps of the fused operation the same as 1249 // the operands and indexing_maps of the generic operations with the 1250 // values at the constant index dropped. 1251 SmallVector<AffineMap> fusedIndexMaps; 1252 SmallVector<Value> fusedOperands; 1253 SmallVector<Location> fusedLocs{genericOp.getLoc()}; 1254 fusedIndexMaps.reserve(genericOp.getNumInputsAndOutputs()); 1255 fusedOperands.reserve(genericOp.getNumInputs()); 1256 fusedLocs.reserve(fusedLocs.size() + genericOp.getNumInputs()); 1257 for (OpOperand *inputOperand : genericOp.getInputOperands()) { 1258 if (inputOperand == opOperand) 1259 continue; 1260 Value inputValue = inputOperand->get(); 1261 fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(inputOperand)); 1262 fusedOperands.push_back(inputValue); 1263 fusedLocs.push_back(inputValue.getLoc()); 1264 } 1265 for (OpOperand *outputOperand : genericOp.getOutputOperands()) 1266 fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(outputOperand)); 1267 1268 // Check if the operation shapes to loops map is computable. 1269 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 1270 return rewriter.notifyMatchFailure( 1271 genericOp, "fused op loop bound computation failed"); 1272 } 1273 1274 // Create a constant scalar value from the splat constant. 1275 Value scalarConstant = rewriter.create<arith::ConstantOp>( 1276 def->getLoc(), constantAttr, constantAttr.getType()); 1277 1278 SmallVector<Value> outputOperands = genericOp.getOutputOperands(); 1279 auto fusedOp = rewriter.create<GenericOp>( 1280 rewriter.getFusedLoc(fusedLocs), genericOp->getResultTypes(), 1281 /*inputs=*/fusedOperands, 1282 /*outputs=*/outputOperands, 1283 rewriter.getAffineMapArrayAttr(fusedIndexMaps), 1284 genericOp.iterator_types(), 1285 /*doc=*/nullptr, 1286 /*library_call=*/nullptr); 1287 1288 // Map the block argument corresponding to the replaced argument with the 1289 // scalar constant. 1290 Region ®ion = genericOp->getRegion(0); 1291 Block &entryBlock = *region.begin(); 1292 BlockAndValueMapping mapping; 1293 mapping.map(entryBlock.getArgument(opOperand->getOperandNumber()), 1294 scalarConstant); 1295 Region &fusedRegion = fusedOp->getRegion(0); 1296 rewriter.cloneRegionBefore(region, fusedRegion, fusedRegion.begin(), 1297 mapping); 1298 rewriter.replaceOp(genericOp, fusedOp->getResults()); 1299 return success(); 1300 } 1301 return failure(); 1302 } 1303 1304 private: 1305 ControlElementwiseOpsFusionFn controlFn; 1306 }; 1307 1308 /// Base class for constant folding linalg.generic ops with N inputs, 1 output, 1309 /// and permutation indexing maps. 1310 /// 1311 /// `ConcreteType` should provide methods with signatures 1312 /// 1313 /// ```c++ 1314 /// bool matchIndexingMaps(GenericOp genericOp) const; 1315 /// RegionComputationFn getRegionComputeFn(GenericOp) const; 1316 /// ``` 1317 /// 1318 /// The latter inspects the region and returns the computation inside as a 1319 /// functor. The functor will be invoked with constant elements for all inputs 1320 /// and should return the corresponding computea constant element for output. 1321 template <typename ConcreteType> 1322 class FoldConstantBase : public OpRewritePattern<GenericOp> { 1323 public: 1324 struct APIntOrFloat { 1325 Optional<APInt> apInt; 1326 Optional<APFloat> apFloat; 1327 }; 1328 struct APIntOrFloatArray { 1329 SmallVector<APInt> apInts; 1330 SmallVector<APFloat> apFloats; 1331 }; 1332 using RegionComputationFn = 1333 std::function<APIntOrFloat(const APIntOrFloatArray &)>; 1334 1335 FoldConstantBase(MLIRContext *context, 1336 const ControlElementwiseOpsFusionFn &controlFn, 1337 PatternBenefit benefit = 1) 1338 : OpRewritePattern<GenericOp>(context, benefit), controlFn(controlFn) {} 1339 1340 LogicalResult matchAndRewrite(GenericOp genericOp, 1341 PatternRewriter &rewriter) const override { 1342 if (genericOp.hasBufferSemantics()) 1343 return failure(); 1344 1345 // Only support ops generating one output for now. 1346 if (genericOp.getNumOutputs() != 1) 1347 return failure(); 1348 1349 auto outputType = genericOp.getResultTypes().front().dyn_cast<ShapedType>(); 1350 // Require the output types to be static give we are generating constants. 1351 if (!outputType || !outputType.hasStaticShape()) 1352 return failure(); 1353 1354 if (!llvm::all_of(genericOp.getInputOperands(), [](OpOperand *operand) { 1355 return operand->get().getType().isa<ShapedType>(); 1356 })) 1357 return failure(); 1358 1359 // Make sure all element types are the same. 1360 auto getOperandElementType = [](OpOperand *operand) { 1361 return operand->get().getType().cast<ShapedType>().getElementType(); 1362 }; 1363 if (!llvm::is_splat(llvm::map_range(genericOp.getInputAndOutputOperands(), 1364 getOperandElementType))) 1365 return failure(); 1366 1367 // We can only handle the case where we have int/float elements. 1368 auto elementType = outputType.getElementType(); 1369 if (!elementType.isIntOrFloat()) 1370 return failure(); 1371 1372 // Require all indexing maps to be permutations for now. This is common and 1373 // it simplifies input/output access greatly: we can do the data shuffling 1374 // entirely in the compiler, without needing to turn all indices into 1375 // Values, and then do affine apply on them, and then match back the 1376 // constant again. 1377 if (!llvm::all_of(genericOp.getIndexingMaps(), 1378 [](AffineMap map) { return map.isPermutation(); })) 1379 return failure(); 1380 1381 for (OpOperand *operand : genericOp.getOutputOperands()) { 1382 if (genericOp.payloadUsesValueFromOperand(operand)) 1383 return failure(); 1384 } 1385 1386 // Further check the indexing maps are okay for the ConcreteType. 1387 if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(genericOp)) 1388 return failure(); 1389 1390 // Defer to the concrete type to check the region and discover the 1391 // computation inside. 1392 RegionComputationFn computeFn = 1393 static_cast<const ConcreteType *>(this)->getRegionComputeFn(genericOp); 1394 if (!computeFn) 1395 return failure(); 1396 1397 // All inputs should be constants. 1398 int numInputs = genericOp.getNumInputs(); 1399 SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs); 1400 for (auto operand : llvm::enumerate(genericOp.getInputOperands())) { 1401 if (!matchPattern(operand.value()->get(), 1402 m_Constant(&inputValues[operand.index()]))) 1403 return failure(); 1404 } 1405 1406 // Identified this as a potential candidate for folding. Now check the 1407 // policy to see whether we are allowed to proceed. 1408 for (int i = 0; i < numInputs; ++i) { 1409 OpOperand *consumer = genericOp.getInputOperand(i); 1410 OpResult producer = consumer->get().cast<OpResult>(); 1411 if (!controlFn(producer, *consumer)) 1412 return failure(); 1413 } 1414 1415 auto linalgOp = cast<LinalgOp>(genericOp.getOperation()); 1416 SmallVector<int64_t, 4> loopBounds = linalgOp.computeStaticLoopSizes(); 1417 int64_t numElements = outputType.getNumElements(); 1418 1419 // Use APInt/APFloat instead of Attribute here for constructing the output. 1420 // This helps to avoid blowing up compiler memory usage: Attributes would 1421 // unify the following cases but they have lifetime as the MLIRContext. 1422 SmallVector<APInt> intOutputValues; 1423 SmallVector<APFloat> fpOutputValues; 1424 if (elementType.template isa<FloatType>()) 1425 fpOutputValues.resize(numElements, APFloat(0.f)); 1426 else 1427 intOutputValues.resize(numElements); 1428 1429 // Return the constant dim positions from the given permutation map. 1430 auto getDimPositions = [](AffineMap map) { 1431 SmallVector<unsigned> dims; 1432 dims.reserve(map.getNumResults()); 1433 for (AffineExpr result : map.getResults()) { 1434 dims.push_back(result.cast<AffineDimExpr>().getPosition()); 1435 } 1436 return dims; 1437 }; 1438 1439 SmallVector<SmallVector<unsigned>> inputDims; 1440 for (int i = 0; i < numInputs; ++i) 1441 inputDims.push_back(getDimPositions(genericOp.getIndexingMaps()[i])); 1442 auto outputDims = getDimPositions(genericOp.getIndexingMaps().back()); 1443 auto outputShape = outputType.getShape(); 1444 1445 // Allocate small vectors for index delinearization. Initial values do not 1446 // matter here as they will be overwritten later. 1447 SmallVector<uint64_t> indices(loopBounds.size(), 0); 1448 SmallVector<uint64_t> dstIndices(loopBounds.size(), 0); 1449 SmallVector<SmallVector<uint64_t>> srcIndices( 1450 numInputs, SmallVector<uint64_t>(loopBounds.size(), 0)); 1451 SmallVector<uint64_t> srcLinearIndices(numInputs, 0); 1452 uint64_t dstLinearIndex = 0; 1453 1454 // Allocate spaces for compute function inputs. Initial values do not matter 1455 // here as they will be overwritten later. 1456 APIntOrFloatArray computeFnInputs; 1457 1458 auto inputShapes = llvm::to_vector<4>( 1459 llvm::map_range(genericOp.getInputOperands(), [](OpOperand *operand) { 1460 return operand->get().getType().cast<ShapedType>().getShape(); 1461 })); 1462 1463 // Given a `linearIndex`, remap it to a linear index to access linalg op 1464 // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`, 1465 // `srcLinearIndices`, `dstLinearIndex` in place. 1466 auto computeRemappedLinearIndex = [&](int linearIndex) { 1467 int totalCount = linearIndex; 1468 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) { 1469 indices[dim] = totalCount % loopBounds[dim]; 1470 totalCount /= loopBounds[dim]; 1471 } 1472 1473 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) { 1474 for (int i = 0; i < numInputs; ++i) 1475 srcIndices[i][dim] = indices[inputDims[i][dim]]; 1476 dstIndices[dim] = indices[outputDims[dim]]; 1477 } 1478 1479 dstLinearIndex = dstIndices.front(); 1480 for (int i = 0; i < numInputs; ++i) 1481 srcLinearIndices[i] = srcIndices[i].front(); 1482 1483 for (int dim = 1; dim < outputType.getRank(); ++dim) { 1484 dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim]; 1485 for (int i = 0; i < numInputs; ++i) 1486 srcLinearIndices[i] = 1487 srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim]; 1488 } 1489 }; 1490 1491 bool isFloat = elementType.isa<FloatType>(); 1492 if (isFloat) { 1493 SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges; 1494 for (int i = 0; i < numInputs; ++i) 1495 inFpRanges.push_back(inputValues[i].getValues<APFloat>()); 1496 1497 computeFnInputs.apFloats.resize(numInputs, APFloat(0.f)); 1498 1499 // Transpose the input constant. Because we don't know its rank in 1500 // advance, we need to loop over the range [0, element count) and 1501 // delinearize the index. 1502 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) { 1503 computeRemappedLinearIndex(linearIndex); 1504 1505 // Collect constant elements for all inputs at this loop iteration. 1506 for (int i = 0; i < numInputs; ++i) 1507 computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]]; 1508 1509 // Invoke the computation to get the corresponding constant output 1510 // element. 1511 fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat; 1512 } 1513 } else { 1514 SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges; 1515 for (int i = 0; i < numInputs; ++i) 1516 inIntRanges.push_back(inputValues[i].getValues<APInt>()); 1517 1518 computeFnInputs.apInts.resize(numInputs); 1519 1520 // Transpose the input constant. Because we don't know its rank in 1521 // advance, we need to loop over the range [0, element count) and 1522 // delinearize the index. 1523 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) { 1524 computeRemappedLinearIndex(linearIndex); 1525 1526 // Collect constant elements for all inputs at this loop iteration. 1527 for (int i = 0; i < numInputs; ++i) 1528 computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]]; 1529 1530 // Invoke the computation to get the corresponding constant output 1531 // element. 1532 intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt; 1533 } 1534 } 1535 1536 DenseElementsAttr outputAttr = 1537 isFloat ? DenseElementsAttr::get(outputType, fpOutputValues) 1538 : DenseElementsAttr::get(outputType, intOutputValues); 1539 1540 rewriter.replaceOpWithNewOp<ConstantOp>(genericOp, outputAttr); 1541 return success(); 1542 } 1543 1544 private: 1545 ControlElementwiseOpsFusionFn controlFn; 1546 }; 1547 1548 // Folds linalg.generic ops that are actually transposes on constant values. 1549 struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> { 1550 using FoldConstantBase::FoldConstantBase; 1551 1552 bool matchIndexingMaps(GenericOp genericOp) const { 1553 // We should have one input and one output. 1554 return genericOp.getIndexingMaps().size() == 2; 1555 } 1556 1557 RegionComputationFn getRegionComputeFn(GenericOp genericOp) const { 1558 // Make sure the region only contains a yield op. 1559 Block &body = genericOp.region().front(); 1560 if (!llvm::hasSingleElement(body)) 1561 return nullptr; 1562 auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator()); 1563 if (!yieldOp) 1564 return nullptr; 1565 1566 // The yield op should return the block argument corresponds to the input. 1567 for (Value yieldVal : yieldOp.values()) { 1568 auto yieldArg = yieldVal.dyn_cast<BlockArgument>(); 1569 if (!yieldArg || yieldArg.getOwner() != &body) 1570 return nullptr; 1571 if (yieldArg.getArgNumber() != 0) 1572 return nullptr; 1573 } 1574 1575 // No computation; just return the orginal value. 1576 return [](const APIntOrFloatArray &inputs) { 1577 if (inputs.apFloats.empty()) 1578 return APIntOrFloat{inputs.apInts.front(), llvm::None}; 1579 return APIntOrFloat{llvm::None, inputs.apFloats.front()}; 1580 }; 1581 } 1582 1583 ControlElementwiseOpsFusionFn controlFn; 1584 }; 1585 1586 } // namespace 1587 1588 static Optional<SmallVector<Value>> 1589 fuseElementwiseOps(PatternRewriter &rewriter, OpOperand *consumerOpOperand, 1590 GenericOp producer, 1591 const ControlElementwiseOpsFusionFn &controlFn) { 1592 if (producer->getNumResults() != 1) 1593 return llvm::None; 1594 1595 return fuseElementwiseOpsImpl(producer, consumerOpOperand, controlFn, 1596 rewriter); 1597 } 1598 1599 bool mlir::linalg::skipUnitDimReshape(const OpResult &producer, 1600 OpOperand &consumer) { 1601 if (auto producerCollapseOp = 1602 dyn_cast<linalg::TensorCollapseShapeOp>(producer.getOwner())) { 1603 return !isUnitDimExpansionOnly(producerCollapseOp); 1604 } 1605 if (auto consumerExpandOp = 1606 dyn_cast<linalg::TensorExpandShapeOp>(consumer.getOwner())) { 1607 return !isUnitDimExpansionOnly(consumerExpandOp); 1608 } 1609 return true; 1610 } 1611 1612 namespace { 1613 /// Patterns to fuse a generic op, with the producer of its operands. 1614 class FuseElementwiseOps : public OpRewritePattern<GenericOp> { 1615 public: 1616 FuseElementwiseOps(MLIRContext *context, ControlElementwiseOpsFusionFn &fun, 1617 PatternBenefit benefit = 1) 1618 : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {} 1619 1620 LogicalResult matchAndRewrite(GenericOp genericOp, 1621 PatternRewriter &rewriter) const override { 1622 // Find the first operand that is defined by another generic op on tensors. 1623 for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) { 1624 auto producer = 1625 dyn_cast_or_null<GenericOp>(opOperand->get().getDefiningOp()); 1626 if (!producer || !producer.hasTensorSemantics()) 1627 continue; 1628 Optional<SmallVector<Value>> fusedOpResults = 1629 fuseElementwiseOps(rewriter, opOperand, producer, controlFn); 1630 if (fusedOpResults) { 1631 rewriter.replaceOp(genericOp, *fusedOpResults); 1632 return success(); 1633 } 1634 } 1635 return failure(); 1636 } 1637 1638 private: 1639 ControlElementwiseOpsFusionFn controlFn; 1640 }; 1641 1642 /// Pass that fuses generic ops on tensors. Used only for testing. 1643 struct LinalgElementwiseOpFusionPass 1644 : public LinalgElementwiseOpFusionBase<LinalgElementwiseOpFusionPass> { 1645 void runOnOperation() override { 1646 Operation *op = getOperation(); 1647 RewritePatternSet patterns(op->getContext()); 1648 ControlElementwiseOpsFusionFn allowFoldingFn = 1649 [](const OpResult &producer, const OpOperand &consumer) { 1650 return true; 1651 }; 1652 populateElementwiseOpsFusionPatterns( 1653 patterns, 1654 LinalgElementwiseFusionOptions().setControlFoldingReshapes( 1655 allowFoldingUnitDimReshapes ? allowFoldingFn : skipUnitDimReshape)); 1656 1657 // Use TopDownTraversal for compile time reasons 1658 GreedyRewriteConfig grc; 1659 grc.useTopDownTraversal = true; 1660 (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns), 1661 grc); 1662 } 1663 }; 1664 1665 /// Pass to test folding of reshape ops with generic ops by linearization. 1666 struct FoldReshapeOpsByLinearizationPass 1667 : public LinalgFoldReshapeOpsByLinearizationBase< 1668 FoldReshapeOpsByLinearizationPass> { 1669 void runOnOperation() override { 1670 Operation *op = getOperation(); 1671 RewritePatternSet patterns(op->getContext()); 1672 populateFoldReshapeOpsByLinearizationPatterns(patterns); 1673 if (allowFoldingUnitDimReshapes) { 1674 populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns); 1675 } 1676 (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns)); 1677 } 1678 }; 1679 1680 /// Forces `outs` operands of linalg operations to use `linalg.init_tensor` if 1681 /// the value of the `outs` operand is not used within the op. This is only 1682 /// implemented for `linalg.generic` operations for now, but should hold for all 1683 /// linalg structured ops. 1684 struct RemoveOutsDependency : public OpRewritePattern<GenericOp> { 1685 using OpRewritePattern<GenericOp>::OpRewritePattern; 1686 1687 LogicalResult matchAndRewrite(GenericOp op, 1688 PatternRewriter &rewriter) const override { 1689 rewriter.startRootUpdate(op); 1690 bool modifiedOutput = false; 1691 Location loc = op.getLoc(); 1692 for (OpOperand *opOperand : op.getOutputOperands()) { 1693 if (!op.payloadUsesValueFromOperand(opOperand)) { 1694 Value operandVal = opOperand->get(); 1695 auto operandType = operandVal.getType().dyn_cast<RankedTensorType>(); 1696 if (!operandType) 1697 continue; 1698 1699 // If outs is already an `init_tensor` operation, nothing to do. 1700 auto definingOp = operandVal.getDefiningOp<InitTensorOp>(); 1701 if (definingOp) 1702 continue; 1703 modifiedOutput = true; 1704 SmallVector<Value> dynamicDims; 1705 for (auto dim : llvm::enumerate(operandType.getShape())) { 1706 if (dim.value() != ShapedType::kDynamicSize) 1707 continue; 1708 dynamicDims.push_back(rewriter.createOrFold<tensor::DimOp>( 1709 loc, operandVal, dim.index())); 1710 } 1711 Value initTensor = rewriter.create<InitTensorOp>( 1712 loc, dynamicDims, operandType.getShape(), 1713 operandType.getElementType()); 1714 op->setOperand(opOperand->getOperandNumber(), initTensor); 1715 } 1716 } 1717 if (!modifiedOutput) { 1718 rewriter.cancelRootUpdate(op); 1719 return failure(); 1720 } 1721 rewriter.finalizeRootUpdate(op); 1722 return success(); 1723 } 1724 }; 1725 1726 } // namespace 1727 1728 void mlir::linalg::populateFoldReshapeOpsByLinearizationPatterns( 1729 RewritePatternSet &patterns) { 1730 patterns 1731 .add<FoldProducerReshapeOpByLinearization<false, TensorCollapseShapeOp>, 1732 FoldProducerReshapeOpByLinearization<false, TensorExpandShapeOp>, 1733 FoldConsumerReshapeOpByLinearization<false, TensorCollapseShapeOp>, 1734 FoldConsumerReshapeOpByLinearization<false, TensorExpandShapeOp>>( 1735 patterns.getContext()); 1736 } 1737 1738 void mlir::linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns( 1739 RewritePatternSet &patterns) { 1740 patterns 1741 .add<FoldProducerReshapeOpByLinearization<true, TensorCollapseShapeOp>, 1742 FoldProducerReshapeOpByLinearization<true, TensorExpandShapeOp>, 1743 FoldConsumerReshapeOpByLinearization<true, TensorCollapseShapeOp>, 1744 FoldConsumerReshapeOpByLinearization<true, TensorExpandShapeOp>>( 1745 patterns.getContext()); 1746 } 1747 1748 void mlir::linalg::populateFoldReshapeOpsByExpansionPatterns( 1749 RewritePatternSet &patterns, 1750 ControlElementwiseOpsFusionFn controlFoldingReshapes) { 1751 patterns.add<FoldReshapeWithGenericOpByExpansion>(patterns.getContext(), 1752 controlFoldingReshapes); 1753 patterns.add<FoldWithProducerReshapeOpByExpansion>(patterns.getContext(), 1754 controlFoldingReshapes); 1755 } 1756 1757 void mlir::linalg::populateElementwiseOpsFusionPatterns( 1758 RewritePatternSet &patterns, LinalgElementwiseFusionOptions options) { 1759 auto *context = patterns.getContext(); 1760 patterns.add<FuseElementwiseOps, FoldScalarOrSplatConstant, 1761 FoldConstantTranspose>(context, 1762 options.controlElementwiseOpsFusionFn); 1763 patterns.add<RemoveOutsDependency>(context); 1764 populateFoldReshapeOpsByExpansionPatterns(patterns, 1765 options.controlFoldingReshapesFn); 1766 AffineApplyOp::getCanonicalizationPatterns(patterns, context); 1767 GenericOp::getCanonicalizationPatterns(patterns, context); 1768 TensorExpandShapeOp::getCanonicalizationPatterns(patterns, context); 1769 TensorCollapseShapeOp::getCanonicalizationPatterns(patterns, context); 1770 context->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns( 1771 patterns); 1772 } 1773 1774 void mlir::linalg::populatePushReshapeOpsPatterns(RewritePatternSet &patterns) { 1775 auto *context = patterns.getContext(); 1776 patterns.add<PushExpandingReshape>(context); 1777 } 1778 1779 std::unique_ptr<Pass> mlir::createLinalgElementwiseOpFusionPass() { 1780 return std::make_unique<LinalgElementwiseOpFusionPass>(); 1781 } 1782 1783 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() { 1784 return std::make_unique<FoldReshapeOpsByLinearizationPass>(); 1785 } 1786