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