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 // Current reshape only supports expansion of a dynamic dim when only one of 612 // the expanded dims are dynamic. 613 for (auto originalShape : llvm::enumerate(expansionInfo.getOriginalShape())) 614 if (ShapedType::isDynamic(originalShape.value())) { 615 // All but one of the expanded dims must be static. 616 bool foundDynamicExpandedDim = false; 617 for (auto expandedShape : 618 expansionInfo.getExpandedShapeOfDim(originalShape.index())) { 619 if (ShapedType::isDynamic(expandedShape)) { 620 if (foundDynamicExpandedDim) { 621 return rewriter.notifyMatchFailure( 622 genericOp, 623 "cannot expanded dynamic dims into multiple dynamic dims"); 624 } 625 foundDynamicExpandedDim = true; 626 } 627 } 628 if (!foundDynamicExpandedDim) { 629 return rewriter.notifyMatchFailure( 630 genericOp, "dynamic dim expansion needs at least one dynamic dim " 631 "in result shape"); 632 } 633 } 634 635 if (!genericOp.hasIndexSemantics()) 636 return success(); 637 for (unsigned i : llvm::seq<unsigned>(0, expansionInfo.getOrigOpNumDims())) { 638 ArrayRef<int64_t> expandedShape = expansionInfo.getExpandedShapeOfDim(i); 639 if (expandedShape.size() == 1) 640 continue; 641 for (int64_t shape : expandedShape.drop_front()) { 642 if (ShapedType::isDynamic(shape)) { 643 return rewriter.notifyMatchFailure( 644 genericOp, "cannot expand due to index semantics and dynamic dims"); 645 } 646 } 647 } 648 return success(); 649 } 650 651 /// Return the indexing map to use in the expanded op for a given the 652 /// `indexingMap` of the original operation. 653 static AffineMap 654 getIndexingMapInExpandedOp(OpBuilder &builder, AffineMap indexingMap, 655 const ExpansionInfo &expansionInfo) { 656 SmallVector<AffineExpr> newExprs; 657 for (AffineExpr expr : indexingMap.getResults()) { 658 unsigned pos = expr.cast<AffineDimExpr>().getPosition(); 659 SmallVector<AffineExpr, 4> expandedExprs = llvm::to_vector<4>( 660 llvm::map_range(expansionInfo.getExpandedDims(pos), [&](int64_t v) { 661 return builder.getAffineDimExpr(static_cast<unsigned>(v)); 662 })); 663 newExprs.append(expandedExprs.begin(), expandedExprs.end()); 664 } 665 return AffineMap::get(expansionInfo.getExpandedOpNumDims(), 666 indexingMap.getNumSymbols(), newExprs, 667 builder.getContext()); 668 } 669 670 /// Return the type of the operand/result to use in the expanded op given the 671 /// type in the original op. 672 static RankedTensorType getExpandedType(RankedTensorType originalType, 673 AffineMap indexingMap, 674 const ExpansionInfo &expansionInfo) { 675 SmallVector<int64_t> expandedShape; 676 for (AffineExpr expr : indexingMap.getResults()) { 677 unsigned dim = expr.cast<AffineDimExpr>().getPosition(); 678 auto dimExpansion = expansionInfo.getExpandedShapeOfDim(dim); 679 expandedShape.append(dimExpansion.begin(), dimExpansion.end()); 680 } 681 return RankedTensorType::get(expandedShape, originalType.getElementType()); 682 } 683 684 /// Returns the reassociation maps to use in the `tensor.expand_shape` 685 /// operation to convert the operands of the original operation to operands of 686 /// the expanded operation. The same method is used to compute the 687 /// `tensor.collapse_shape` used to collapse the result of the expanded 688 /// op to get the value that can replace all uses of the results of the original 689 /// op. 690 static SmallVector<ReassociationIndices> 691 getReassociationForExpansion(AffineMap indexingMap, 692 const ExpansionInfo &expansionInfo) { 693 SmallVector<ReassociationIndices> reassociation; 694 unsigned numReshapeDims = 0; 695 for (AffineExpr expr : indexingMap.getResults()) { 696 unsigned dim = expr.cast<AffineDimExpr>().getPosition(); 697 auto numExpandedDims = expansionInfo.getExpandedDims(dim).size(); 698 SmallVector<int64_t, 2> indices = llvm::to_vector<2>( 699 llvm::seq<int64_t>(numReshapeDims, numReshapeDims + numExpandedDims)); 700 reassociation.emplace_back(std::move(indices)); 701 numReshapeDims += numExpandedDims; 702 } 703 return reassociation; 704 } 705 706 /// Update the body of an expanded linalg operation having index semantics. The 707 /// indices of the original operation need to be recovered by linearizing the 708 /// indices of the correspoding dimensions of the expanded operation. For now it 709 /// is assumed that the shapes of the expanded operation needed for 710 /// linearization are static. 711 static void updateExpandedGenericOpRegion(PatternRewriter &rewriter, 712 Location loc, Region &fusedRegion, 713 const ExpansionInfo &expansionInfo) { 714 // Replace the original indices by the linearization of the expanded indices. 715 for (IndexOp indexOp : 716 llvm::make_early_inc_range(fusedRegion.front().getOps<IndexOp>())) { 717 ArrayRef<int64_t> expandedDims = 718 expansionInfo.getExpandedDims(indexOp.dim()); 719 assert(!expandedDims.empty() && "expected valid expansion info"); 720 721 // Skip index operations that are not affected by the expansion. 722 if (expandedDims.size() == 1 && 723 expandedDims.front() == (int64_t)indexOp.dim()) 724 continue; 725 726 // Linearize the expanded indices of the original index dimension. 727 OpBuilder::InsertionGuard guard(rewriter); 728 rewriter.setInsertionPointAfter(indexOp); 729 ArrayRef<int64_t> expandedDimsShape = 730 expansionInfo.getExpandedShapeOfDim(indexOp.dim()).drop_front(); 731 SmallVector<Value> expandedIndices; 732 expandedIndices.reserve(expandedDims.size() - 1); 733 llvm::transform( 734 expandedDims.drop_front(), std::back_inserter(expandedIndices), 735 [&](int64_t dim) { return rewriter.create<IndexOp>(loc, dim); }); 736 Value newIndex = rewriter.create<IndexOp>(loc, expandedDims.front()); 737 for (auto it : llvm::zip(expandedDimsShape, expandedIndices)) { 738 assert(!ShapedType::isDynamic(std::get<0>(it))); 739 AffineExpr idx, acc; 740 bindDims(rewriter.getContext(), idx, acc); 741 newIndex = rewriter.create<AffineApplyOp>( 742 indexOp.getLoc(), idx + acc * std::get<0>(it), 743 ValueRange{std::get<1>(it), newIndex}); 744 } 745 rewriter.replaceOp(indexOp, newIndex); 746 } 747 } 748 749 /// Implements the fusion of a tensor_collapse_shape or a tensor_expand_shape op 750 /// and a generic op as explained in `isFusableWithReshapeByExpansion`. Assumes 751 /// that those conditions have been satisfied. 752 static Optional<SmallVector<Value>> 753 fuseWithReshapeByExpansion(GenericOp genericOp, Operation *reshapeOp, 754 OpOperand *fusableOpOperand, 755 PatternRewriter &rewriter) { 756 assert(isFusableWithReshapeByDimExpansion(genericOp, fusableOpOperand) && 757 "preconditions for fuse operation failed"); 758 // Check if reshape is expanding or collapsing. 759 auto expandingReshapeOp = dyn_cast<tensor::ExpandShapeOp>(*reshapeOp); 760 auto collapsingReshapeOp = dyn_cast<tensor::CollapseShapeOp>(*reshapeOp); 761 bool isExpanding = (expandingReshapeOp != nullptr); 762 RankedTensorType expandedType = isExpanding 763 ? expandingReshapeOp.getResultType() 764 : collapsingReshapeOp.getSrcType(); 765 RankedTensorType collapsedType = isExpanding 766 ? expandingReshapeOp.getSrcType() 767 : collapsingReshapeOp.getResultType(); 768 769 ExpansionInfo expansionInfo; 770 if (failed(expansionInfo.compute( 771 genericOp, fusableOpOperand, 772 isExpanding ? expandingReshapeOp.getReassociationMaps() 773 : collapsingReshapeOp.getReassociationMaps(), 774 expandedType.getShape(), collapsedType.getShape(), rewriter))) 775 return llvm::None; 776 777 if (failed(isGenericOpExpandable(genericOp, expansionInfo, rewriter))) 778 return llvm::None; 779 780 SmallVector<AffineMap, 4> expandedOpIndexingMaps = llvm::to_vector<4>( 781 llvm::map_range(genericOp.getIndexingMaps(), [&](AffineMap m) { 782 return getIndexingMapInExpandedOp(rewriter, m, expansionInfo); 783 })); 784 785 SmallVector<Value> expandedOpOperands; 786 expandedOpOperands.reserve(genericOp.getNumInputs()); 787 for (OpOperand *opOperand : genericOp.getInputOperands()) { 788 if (opOperand == fusableOpOperand) { 789 expandedOpOperands.push_back(isExpanding ? expandingReshapeOp.src() 790 : collapsingReshapeOp.src()); 791 continue; 792 } 793 if (genericOp.isInputTensor(opOperand)) { 794 AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand); 795 RankedTensorType expandedOperandType = 796 getExpandedType(opOperand->get().getType().cast<RankedTensorType>(), 797 indexingMap, expansionInfo); 798 if (expandedOperandType != opOperand->get().getType()) { 799 // Reshape the operand to get the right type. 800 SmallVector<ReassociationIndices> reassociation = 801 getReassociationForExpansion(indexingMap, expansionInfo); 802 expandedOpOperands.push_back(rewriter.create<tensor::ExpandShapeOp>( 803 genericOp.getLoc(), expandedOperandType, opOperand->get(), 804 reassociation)); 805 continue; 806 } 807 } 808 expandedOpOperands.push_back(opOperand->get()); 809 } 810 811 Location loc = genericOp.getLoc(); 812 SmallVector<Value> outputs; 813 for (OpOperand *opOperand : genericOp.getOutputOperands()) { 814 AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand); 815 RankedTensorType expandedOutputType = 816 getExpandedType(opOperand->get().getType().cast<RankedTensorType>(), 817 indexingMap, expansionInfo); 818 if (expandedOutputType != opOperand->get().getType()) { 819 SmallVector<ReassociationIndices> reassociation = 820 getReassociationForExpansion(indexingMap, expansionInfo); 821 outputs.push_back(rewriter.create<tensor::ExpandShapeOp>( 822 genericOp.getLoc(), expandedOutputType, opOperand->get(), 823 reassociation)); 824 } 825 } 826 827 // The iterator types of the expanded op are all parallel. 828 SmallVector<StringRef> iteratorTypes(expansionInfo.getExpandedOpNumDims(), 829 getParallelIteratorTypeName()); 830 831 TypeRange resultTypes = ValueRange(outputs).getTypes(); 832 auto fusedOp = 833 rewriter.create<GenericOp>(genericOp.getLoc(), resultTypes, 834 /*inputs=*/expandedOpOperands, outputs, 835 expandedOpIndexingMaps, iteratorTypes); 836 Region &fusedRegion = fusedOp->getRegion(0); 837 Region &originalRegion = genericOp->getRegion(0); 838 rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.begin()); 839 840 // Update the index accesses after the expansion. 841 updateExpandedGenericOpRegion(rewriter, loc, fusedRegion, expansionInfo); 842 843 // Reshape the result values to their original shape if this is a collapsing 844 // reshape folded into its consumer. 845 SmallVector<Value> resultVals; 846 for (OpResult opResult : genericOp->getOpResults()) { 847 int64_t resultNumber = opResult.getResultNumber(); 848 if (!isExpanding && resultTypes[resultNumber] != opResult.getType()) { 849 SmallVector<ReassociationIndices> reassociation = 850 getReassociationForExpansion( 851 genericOp.getTiedIndexingMap( 852 genericOp.getOutputOperand(resultNumber)), 853 expansionInfo); 854 resultVals.push_back(rewriter.create<tensor::CollapseShapeOp>( 855 genericOp.getLoc(), opResult.getType(), 856 fusedOp->getResult(resultNumber), reassociation)); 857 } else { 858 resultVals.push_back(fusedOp->getResult(resultNumber)); 859 } 860 } 861 // Assuming a single result. 862 return resultVals; 863 } 864 865 namespace { 866 867 /// Pattern to fold tensor_expand_shape op with its consumer by using the source 868 /// of the reshape op as the operand in the consumer (instead of the result of 869 /// the tensor_collapse_shape). The corresponding index map in the consumer 870 /// needs to be modified to linearize the folded dimension. 871 /// 872 /// For example, 873 /// 874 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)> 875 /// %0 = tensor.expand_shape %arg0 [[0], [1, 2], [3]] 876 /// tensor<?x?x?xf32> into tensor<?x?x4x?xf32> 877 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... } 878 /// ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ... 879 /// -> tensor<?x?x4x?xf32> 880 /// 881 /// can be folded into 882 /// 883 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)> 884 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)> 885 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... } 886 /// ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ... 887 /// -> tensor<?x?x4x?xf32> 888 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp> 889 struct FoldProducerReshapeOpByLinearization 890 : public OpRewritePattern<GenericOp> { 891 using OpRewritePattern<GenericOp>::OpRewritePattern; 892 893 LogicalResult matchAndRewrite(GenericOp genericOp, 894 PatternRewriter &rewriter) const override { 895 if (!genericOp.hasTensorSemantics()) 896 return failure(); 897 SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands(); 898 for (const auto &en : llvm::enumerate(inputOperands)) { 899 auto reshapeOp = en.value()->get().getDefiningOp<TensorReshapeOp>(); 900 if (!reshapeOp) 901 continue; 902 903 if (!isTensorReshapeOpFoldableByLinearization( 904 reshapeOp, genericOp.getTiedIndexingMap(en.value()), 905 /*asProducer =*/true) || 906 (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp))) 907 continue; 908 909 // Compute the fused operands list, 910 SmallVector<Value> fusedOperands = genericOp.getInputOperands(); 911 fusedOperands[en.index()] = reshapeOp.src(); 912 SmallVector<Value> outputOperands = genericOp.getOutputOperands(); 913 llvm::append_range(fusedOperands, outputOperands); 914 915 // Compute indexing_maps for the fused operation. The indexing_maps for 916 // the operands of the consumers that arent fused are the same. 917 SmallVector<AffineMap> fusedIndexMaps = genericOp.getIndexingMaps(); 918 919 // Accepted consumer maps are either identity or permutation. 920 auto invMap = inversePermutation(fusedIndexMaps[en.index()]); 921 922 // Compute the indexing map to use for the result of the producer. 923 AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp); 924 // The modified map cannot have symbols. 925 if (modifiedMap.getNumSymbols()) 926 return failure(); 927 for (AffineExpr expr : modifiedMap.getResults()) { 928 if (!expr.isPureAffine()) 929 return failure(); 930 } 931 fusedIndexMaps[en.index()] = modifiedMap; 932 933 // Further check that the resulting index maps can be fused and 934 // inverted. Without this the resultant op is not legal. 935 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 936 return rewriter.notifyMatchFailure( 937 genericOp, "fused op loop bound computation failed"); 938 } 939 940 rewriter.startRootUpdate(genericOp); 941 genericOp->setOperands(fusedOperands); 942 genericOp.indexing_mapsAttr( 943 rewriter.getAffineMapArrayAttr(fusedIndexMaps)); 944 rewriter.finalizeRootUpdate(genericOp); 945 return success(); 946 } 947 return failure(); 948 } 949 }; 950 951 static SmallVector<ReassociationIndices> 952 getReassociationIndices(ArrayRef<AffineMap> maps) { 953 SmallVector<ReassociationIndices> reassociation; 954 for (AffineMap map : maps) { 955 ReassociationIndices indices; 956 for (unsigned i = 0, e = map.getNumResults(); i < e; i++) { 957 unsigned pos = map.getResult(i).cast<AffineDimExpr>().getPosition(); 958 indices.push_back(pos); 959 } 960 reassociation.push_back(indices); 961 } 962 return reassociation; 963 } 964 965 /// Pattern to move rank reducing reshape after an elementwise linalg generic 966 /// op. This is useful to expose more fusion opportunities between named ops and 967 /// generic ops. This can only be done if there is no broadcast or permuation 968 /// within the dimensions we need to merge. 969 /// 970 /// For example, 971 /// 972 /// %0 = tensor.expand_shape %A [[0, 1], [2]] 973 /// : tensor<12544x16xf32> into tensor<112x112x16xf32> 974 /// %2 = linalg.generic {indexing_maps = [ 975 /// affine_map<(d0, d1, d2) -> (d0, d1, d2)>, 976 /// affine_map<(d0, d1, d2) -> (d2)>, 977 /// affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = 978 /// ["parallel", "parallel", "parallel"]} { 979 /// } -> tensor<112x112x16xf32> 980 /// 981 /// into 982 /// 983 /// %2 = linalg.generic {indexing_maps = [ 984 /// affine_map<(d0, d1) -> (d0, d1)>, 985 /// affine_map<(d0, d1) -> (d1)>, 986 /// affine_map<(d0, d1) -> (d0, d1)>], 987 /// iterator_types = ["parallel", "parallel"]} ins(%arg0, %arg1 988 /// : tensor<12544x16xf32>, tensor<16xf32>) outs(%1 : tensor<12544x16xf32>) { 989 /// } -> tensor<12544x16xf32> 990 /// %3 = tensor.expand_shape %2 [[0, 1], [2]] 991 /// : tensor<12544x16xf32> into tensor<112x112x16xf32> 992 struct PushExpandingReshape : public OpRewritePattern<GenericOp> { 993 using OpRewritePattern<GenericOp>::OpRewritePattern; 994 995 LogicalResult matchAndRewrite(GenericOp genericOp, 996 PatternRewriter &rewriter) const override { 997 // Only apply to elementwise linalg on tensor. 998 if (!genericOp.hasTensorSemantics() || 999 genericOp.getNumParallelLoops() != genericOp.getNumLoops()) 1000 return failure(); 1001 // Only support identity output maps. It could be extended to permuations if 1002 // needed. 1003 if (llvm::any_of(genericOp.getOutputOperands(), [&](OpOperand *opOperand) { 1004 return !genericOp.getTiedIndexingMap(opOperand).isIdentity(); 1005 })) 1006 return failure(); 1007 int64_t destRank = genericOp.getNumParallelLoops(); 1008 SmallVector<Value> newOperands = genericOp.getInputOperands(); 1009 tensor::ExpandShapeOp reshapeFound; 1010 // 1. Look for tensor_expand_shape operands and figure out save the 1011 // dimensions merged. 1012 SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands(); 1013 for (const auto &en : llvm::enumerate(inputOperands)) { 1014 auto reshapeOp = 1015 en.value()->get().template getDefiningOp<tensor::ExpandShapeOp>(); 1016 if (!reshapeOp) 1017 continue; 1018 // TODO: We could support non-identity map as long as the merged 1019 // dimensions are still contiguous. 1020 if (!genericOp.getTiedIndexingMap(en.value()).isIdentity()) 1021 continue; 1022 if (reshapeFound) { 1023 // Only support a second reshape op if it has the same reassociate maps. 1024 if (reshapeFound.getReassociationMaps() == 1025 reshapeOp.getReassociationMaps()) 1026 newOperands[en.index()] = reshapeOp.src(); 1027 continue; 1028 } 1029 reshapeFound = reshapeOp; 1030 newOperands[en.index()] = reshapeOp.src(); 1031 } 1032 if (!reshapeFound) 1033 return failure(); 1034 1035 // Calculate the reassociation indices and rassociated reverse map. 1036 SmallVector<ReassociationIndices> reassociation = 1037 getReassociationIndices(reshapeFound.getReassociationMaps()); 1038 SmallVector<unsigned> remap(destRank); 1039 for (auto &indices : llvm::enumerate(reassociation)) { 1040 for (int64_t index : indices.value()) { 1041 remap[index] = indices.index(); 1042 } 1043 } 1044 // 2. Verify that we can merge the dimensions in the linalg and that we 1045 // don't need to create new reshapes operands. Inserting new reshape 1046 // operands would defeat the purpose of the transformation. 1047 for (const auto &en : llvm::enumerate(inputOperands)) { 1048 if (en.value()->get() == newOperands[en.index()]) { 1049 AffineMap map = genericOp.getTiedIndexingMap(en.value()); 1050 for (unsigned i : llvm::seq(unsigned(0), map.getNumResults())) { 1051 if (reassociation[remap[map.getDimPosition(i)]].size() > 1) 1052 return failure(); 1053 } 1054 } 1055 } 1056 1057 // 3. Calculate the affine map remapping and the reassociation to apply to 1058 // output tensors. 1059 SmallVector<AffineMap> newMaps; 1060 unsigned newRank = reassociation.size(); 1061 for (auto map : genericOp.getIndexingMaps()) { 1062 SmallVector<AffineExpr> newExprs; 1063 for (auto expr : map.getResults()) { 1064 unsigned position = expr.template cast<AffineDimExpr>().getPosition(); 1065 // Skip dimension merged except for the last of the group. 1066 if (reassociation[remap[position]].back() == position) { 1067 newExprs.push_back( 1068 getAffineDimExpr(remap[position], genericOp.getContext())); 1069 } 1070 } 1071 newMaps.push_back( 1072 AffineMap::get(newRank, 0, newExprs, genericOp.getContext())); 1073 } 1074 1075 // 4. Reshape the output tensors. 1076 SmallVector<Value> newOutputs; 1077 SmallVector<Type> newOutputTypes; 1078 for (auto output : genericOp.outputs()) { 1079 auto newOutputType = RankedTensorType::get( 1080 reshapeFound.getSrcType().getShape(), 1081 output.getType().template cast<RankedTensorType>().getElementType()); 1082 Value newOutput = rewriter.create<tensor::CollapseShapeOp>( 1083 genericOp->getLoc(), newOutputType, output, reassociation); 1084 newOutputTypes.push_back(newOutputType); 1085 newOutputs.push_back(newOutput); 1086 } 1087 // 5. Create a new generic op with lowerer rank. 1088 SmallVector<StringRef> iteratorTypes(newRank, 1089 getParallelIteratorTypeName()); 1090 auto newOp = rewriter.create<GenericOp>(genericOp->getLoc(), newOutputTypes, 1091 newOperands, newOutputs, newMaps, 1092 iteratorTypes); 1093 rewriter.inlineRegionBefore(genericOp.region(), newOp.region(), 1094 newOp.region().begin()); 1095 // 6. Reshape the so that the type matches the uses. 1096 SmallVector<Value> newResults; 1097 for (const auto &result : llvm::enumerate(newOp->getResults())) { 1098 newResults.push_back(rewriter.create<tensor::ExpandShapeOp>( 1099 genericOp->getLoc(), genericOp.getOutputTensorTypes()[result.index()], 1100 result.value(), reassociation)); 1101 } 1102 rewriter.replaceOp(genericOp, newResults); 1103 return success(); 1104 } 1105 }; 1106 1107 /// Pattern to fuse a tensor_collapse_shape op with its consumer generic op, 1108 /// when the reshape op is collapsing dimensions. The dimensionality of the loop 1109 /// in the consumer is expanded. 1110 class FoldWithProducerReshapeOpByExpansion 1111 : public OpRewritePattern<GenericOp> { 1112 public: 1113 FoldWithProducerReshapeOpByExpansion( 1114 MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes, 1115 PatternBenefit benefit = 1) 1116 : OpRewritePattern<GenericOp>(context, benefit), 1117 controlFoldingReshapes(std::move(foldReshapes)) {} 1118 1119 LogicalResult matchAndRewrite(GenericOp genericOp, 1120 PatternRewriter &rewriter) const override { 1121 for (OpOperand *opOperand : genericOp.getInputTensorOperands()) { 1122 tensor::CollapseShapeOp reshapeOp = 1123 opOperand->get().getDefiningOp<tensor::CollapseShapeOp>(); 1124 if (!reshapeOp) 1125 continue; 1126 // Fold only if 1127 // - The tensor reshape op is folding. 1128 // - All constraints of fusing with reshape by expansion are met. 1129 if (!isFusableWithReshapeByDimExpansion(genericOp, opOperand) || 1130 (!controlFoldingReshapes(reshapeOp->getResult(0), *opOperand))) 1131 continue; 1132 1133 Optional<SmallVector<Value>> replacementValues = 1134 fuseWithReshapeByExpansion(genericOp, reshapeOp, opOperand, rewriter); 1135 if (!replacementValues) 1136 return failure(); 1137 rewriter.replaceOp(genericOp, replacementValues.getValue()); 1138 return success(); 1139 } 1140 return failure(); 1141 } 1142 1143 private: 1144 ControlElementwiseOpsFusionFn controlFoldingReshapes; 1145 }; 1146 1147 /// Pattern to fold tensor_collapse_shape or tensor_expand_shape op with its 1148 /// producer. The corresponding index map in the consumer needs to be modified 1149 /// to linearize the folded dimension. 1150 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp> 1151 struct FoldConsumerReshapeOpByLinearization 1152 : public OpRewritePattern<TensorReshapeOp> { 1153 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 1154 1155 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 1156 PatternRewriter &rewriter) const override { 1157 GenericOp producer = reshapeOp.src().template getDefiningOp<GenericOp>(); 1158 if (!producer || !producer.hasTensorSemantics() || 1159 producer.getNumOutputs() != 1 || 1160 !isTensorReshapeOpFoldableByLinearization( 1161 reshapeOp, 1162 producer.getTiedIndexingMap(producer.getOutputOperand(0)), 1163 /*asProducer =*/false) || 1164 (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp))) 1165 return failure(); 1166 // The indexing_maps for the operands of the fused operation are same as 1167 // those for the operands of the producer. 1168 SmallVector<AffineMap> fusedIndexMaps = producer.getIndexingMaps(); 1169 1170 auto invMap = inversePermutation( 1171 producer.getTiedIndexingMap(producer.getOutputOperand(0))); 1172 1173 // Compute the indexing map to use for the operand of the producer. 1174 AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp); 1175 for (AffineExpr expr : modifiedMap.getResults()) { 1176 if (!expr.isPureAffine()) { 1177 return rewriter.notifyMatchFailure( 1178 producer, "fused op indexing map is not affine"); 1179 } 1180 } 1181 fusedIndexMaps.back() = modifiedMap; 1182 1183 // Further check that the resulting index maps can be fused and 1184 // inverted. Without this the resultant op is not legal. 1185 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 1186 return rewriter.notifyMatchFailure( 1187 producer, "fused op loop bound computation failed"); 1188 } 1189 1190 Location loc = producer.getLoc(); 1191 SmallVector<Value> inputOperands = producer.getInputOperands(); 1192 Value output = rewriter.create<TensorReshapeOp>( 1193 loc, producer.getOutputOperand(0)->get(), 1194 reshapeOp.getReassociationExprs()); 1195 auto fusedOp = rewriter.create<GenericOp>( 1196 loc, reshapeOp.getResultType(), 1197 /*inputs=*/inputOperands, 1198 // TODO: handle outputs. 1199 /*outputs=*/output, rewriter.getAffineMapArrayAttr(fusedIndexMaps), 1200 producer.iterator_types(), 1201 /*doc=*/nullptr, 1202 /*library_call=*/nullptr); 1203 auto &fusedRegion = fusedOp->getRegion(0); 1204 rewriter.cloneRegionBefore(producer->getRegion(0), fusedRegion, 1205 fusedRegion.begin()); 1206 rewriter.replaceOp(reshapeOp, fusedOp->getResults()); 1207 return success(); 1208 } 1209 }; 1210 1211 /// Pattern to fold a tensor_expand_shape op with its producer generic op 1212 /// by expanding the dimensionality of the loop in the producer op. 1213 struct FoldReshapeWithGenericOpByExpansion 1214 : public OpRewritePattern<tensor::ExpandShapeOp> { 1215 1216 FoldReshapeWithGenericOpByExpansion( 1217 MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes, 1218 PatternBenefit benefit = 1) 1219 : OpRewritePattern<tensor::ExpandShapeOp>(context, benefit), 1220 controlFoldingReshapes(std::move(foldReshapes)) {} 1221 1222 LogicalResult matchAndRewrite(tensor::ExpandShapeOp reshapeOp, 1223 PatternRewriter &rewriter) const override { 1224 // Fold only if all constraints of fusing with reshape by expansion are met. 1225 GenericOp producer = reshapeOp.src().getDefiningOp<GenericOp>(); 1226 if (!producer || producer.getNumOutputs() != 1 || 1227 !isFusableWithReshapeByDimExpansion(producer, 1228 producer.getOutputOperand(0)) || 1229 !controlFoldingReshapes(producer->getResult(0), 1230 reshapeOp->getOpOperand(0))) 1231 return failure(); 1232 Optional<SmallVector<Value>> replacementValues = fuseWithReshapeByExpansion( 1233 producer, reshapeOp, producer.getOutputOperand(0), rewriter); 1234 if (!replacementValues) 1235 return failure(); 1236 rewriter.replaceOp(reshapeOp, replacementValues.getValue()); 1237 return success(); 1238 } 1239 1240 private: 1241 ControlElementwiseOpsFusionFn controlFoldingReshapes; 1242 }; 1243 1244 /// Pattern to fold a generic op with a splat constant/scalar constant. Does not 1245 /// handle cases where the constant is not single-valued. 1246 class FoldScalarOrSplatConstant : public OpRewritePattern<GenericOp> { 1247 public: 1248 FoldScalarOrSplatConstant(MLIRContext *context, 1249 ControlElementwiseOpsFusionFn &fun, 1250 PatternBenefit benefit = 1) 1251 : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {} 1252 1253 LogicalResult matchAndRewrite(GenericOp genericOp, 1254 PatternRewriter &rewriter) const override { 1255 if (!genericOp.hasTensorSemantics()) 1256 return failure(); 1257 for (OpOperand *opOperand : genericOp.getInputOperands()) { 1258 Operation *def = opOperand->get().getDefiningOp(); 1259 Attribute constantAttr; 1260 auto isScalarOrSplatConstantOp = [&constantAttr](Operation *def) -> bool { 1261 { 1262 DenseElementsAttr splatAttr; 1263 if (matchPattern(def, m_Constant<DenseElementsAttr>(&splatAttr)) && 1264 splatAttr.isSplat() && 1265 splatAttr.getType().getElementType().isIntOrFloat()) { 1266 constantAttr = splatAttr.getSplatValue<Attribute>(); 1267 return true; 1268 } 1269 } 1270 { 1271 IntegerAttr intAttr; 1272 if (matchPattern(def, m_Constant<IntegerAttr>(&intAttr))) { 1273 constantAttr = intAttr; 1274 return true; 1275 } 1276 } 1277 { 1278 FloatAttr floatAttr; 1279 if (matchPattern(def, m_Constant<FloatAttr>(&floatAttr))) { 1280 constantAttr = floatAttr; 1281 return true; 1282 } 1283 } 1284 return false; 1285 }; 1286 1287 auto resultValue = opOperand->get().dyn_cast<OpResult>(); 1288 if (!def || !resultValue || !isScalarOrSplatConstantOp(def) || 1289 !controlFn(resultValue, *opOperand)) 1290 continue; 1291 1292 // The operands and the indexing_maps of the fused operation the same as 1293 // the operands and indexing_maps of the generic operations with the 1294 // values at the constant index dropped. 1295 SmallVector<AffineMap> fusedIndexMaps; 1296 SmallVector<Value> fusedOperands; 1297 SmallVector<Location> fusedLocs{genericOp.getLoc()}; 1298 fusedIndexMaps.reserve(genericOp.getNumInputsAndOutputs()); 1299 fusedOperands.reserve(genericOp.getNumInputs()); 1300 fusedLocs.reserve(fusedLocs.size() + genericOp.getNumInputs()); 1301 for (OpOperand *inputOperand : genericOp.getInputOperands()) { 1302 if (inputOperand == opOperand) 1303 continue; 1304 Value inputValue = inputOperand->get(); 1305 fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(inputOperand)); 1306 fusedOperands.push_back(inputValue); 1307 fusedLocs.push_back(inputValue.getLoc()); 1308 } 1309 for (OpOperand *outputOperand : genericOp.getOutputOperands()) 1310 fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(outputOperand)); 1311 1312 // Check if the operation shapes to loops map is computable. 1313 if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) { 1314 return rewriter.notifyMatchFailure( 1315 genericOp, "fused op loop bound computation failed"); 1316 } 1317 1318 // Create a constant scalar value from the splat constant. 1319 Value scalarConstant = rewriter.create<arith::ConstantOp>( 1320 def->getLoc(), constantAttr, constantAttr.getType()); 1321 1322 SmallVector<Value> outputOperands = genericOp.getOutputOperands(); 1323 auto fusedOp = rewriter.create<GenericOp>( 1324 rewriter.getFusedLoc(fusedLocs), genericOp->getResultTypes(), 1325 /*inputs=*/fusedOperands, 1326 /*outputs=*/outputOperands, 1327 rewriter.getAffineMapArrayAttr(fusedIndexMaps), 1328 genericOp.iterator_types(), 1329 /*doc=*/nullptr, 1330 /*library_call=*/nullptr); 1331 1332 // Map the block argument corresponding to the replaced argument with the 1333 // scalar constant. 1334 Region ®ion = genericOp->getRegion(0); 1335 Block &entryBlock = *region.begin(); 1336 BlockAndValueMapping mapping; 1337 mapping.map(entryBlock.getArgument(opOperand->getOperandNumber()), 1338 scalarConstant); 1339 Region &fusedRegion = fusedOp->getRegion(0); 1340 rewriter.cloneRegionBefore(region, fusedRegion, fusedRegion.begin(), 1341 mapping); 1342 rewriter.replaceOp(genericOp, fusedOp->getResults()); 1343 return success(); 1344 } 1345 return failure(); 1346 } 1347 1348 private: 1349 ControlElementwiseOpsFusionFn controlFn; 1350 }; 1351 1352 /// Base class for constant folding linalg.generic ops with N inputs, 1 output, 1353 /// and permutation indexing maps. 1354 /// 1355 /// `ConcreteType` should provide methods with signatures 1356 /// 1357 /// ```c++ 1358 /// bool matchIndexingMaps(GenericOp genericOp) const; 1359 /// RegionComputationFn getRegionComputeFn(GenericOp) const; 1360 /// ``` 1361 /// 1362 /// The latter inspects the region and returns the computation inside as a 1363 /// functor. The functor will be invoked with constant elements for all inputs 1364 /// and should return the corresponding computea constant element for output. 1365 template <typename ConcreteType> 1366 class FoldConstantBase : public OpRewritePattern<GenericOp> { 1367 public: 1368 struct APIntOrFloat { 1369 Optional<APInt> apInt; 1370 Optional<APFloat> apFloat; 1371 }; 1372 struct APIntOrFloatArray { 1373 SmallVector<APInt> apInts; 1374 SmallVector<APFloat> apFloats; 1375 }; 1376 using RegionComputationFn = 1377 std::function<APIntOrFloat(const APIntOrFloatArray &)>; 1378 1379 FoldConstantBase(MLIRContext *context, 1380 const ControlElementwiseOpsFusionFn &controlFn, 1381 PatternBenefit benefit = 1) 1382 : OpRewritePattern<GenericOp>(context, benefit), controlFn(controlFn) {} 1383 1384 LogicalResult matchAndRewrite(GenericOp genericOp, 1385 PatternRewriter &rewriter) const override { 1386 if (genericOp.hasBufferSemantics()) 1387 return failure(); 1388 1389 // Only support ops generating one output for now. 1390 if (genericOp.getNumOutputs() != 1) 1391 return failure(); 1392 1393 auto outputType = genericOp.getResultTypes().front().dyn_cast<ShapedType>(); 1394 // Require the output types to be static give we are generating constants. 1395 if (!outputType || !outputType.hasStaticShape()) 1396 return failure(); 1397 1398 if (!llvm::all_of(genericOp.getInputOperands(), [](OpOperand *operand) { 1399 return operand->get().getType().isa<ShapedType>(); 1400 })) 1401 return failure(); 1402 1403 // Make sure all element types are the same. 1404 auto getOperandElementType = [](OpOperand *operand) { 1405 return operand->get().getType().cast<ShapedType>().getElementType(); 1406 }; 1407 if (!llvm::is_splat(llvm::map_range(genericOp.getInputAndOutputOperands(), 1408 getOperandElementType))) 1409 return failure(); 1410 1411 // We can only handle the case where we have int/float elements. 1412 auto elementType = outputType.getElementType(); 1413 if (!elementType.isIntOrFloat()) 1414 return failure(); 1415 1416 // Require all indexing maps to be permutations for now. This is common and 1417 // it simplifies input/output access greatly: we can do the data shuffling 1418 // entirely in the compiler, without needing to turn all indices into 1419 // Values, and then do affine apply on them, and then match back the 1420 // constant again. 1421 if (!llvm::all_of(genericOp.getIndexingMaps(), 1422 [](AffineMap map) { return map.isPermutation(); })) 1423 return failure(); 1424 1425 for (OpOperand *operand : genericOp.getOutputOperands()) { 1426 if (genericOp.payloadUsesValueFromOperand(operand)) 1427 return failure(); 1428 } 1429 1430 // Further check the indexing maps are okay for the ConcreteType. 1431 if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(genericOp)) 1432 return failure(); 1433 1434 // Defer to the concrete type to check the region and discover the 1435 // computation inside. 1436 RegionComputationFn computeFn = 1437 static_cast<const ConcreteType *>(this)->getRegionComputeFn(genericOp); 1438 if (!computeFn) 1439 return failure(); 1440 1441 // All inputs should be constants. 1442 int numInputs = genericOp.getNumInputs(); 1443 SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs); 1444 for (const auto &operand : llvm::enumerate(genericOp.getInputOperands())) { 1445 if (!matchPattern(operand.value()->get(), 1446 m_Constant(&inputValues[operand.index()]))) 1447 return failure(); 1448 } 1449 1450 // Identified this as a potential candidate for folding. Now check the 1451 // policy to see whether we are allowed to proceed. 1452 for (int i = 0; i < numInputs; ++i) { 1453 OpOperand *consumer = genericOp.getInputOperand(i); 1454 OpResult producer = consumer->get().cast<OpResult>(); 1455 if (!controlFn(producer, *consumer)) 1456 return failure(); 1457 } 1458 1459 auto linalgOp = cast<LinalgOp>(genericOp.getOperation()); 1460 SmallVector<int64_t, 4> loopBounds = linalgOp.computeStaticLoopSizes(); 1461 int64_t numElements = outputType.getNumElements(); 1462 1463 // Use APInt/APFloat instead of Attribute here for constructing the output. 1464 // This helps to avoid blowing up compiler memory usage: Attributes would 1465 // unify the following cases but they have lifetime as the MLIRContext. 1466 SmallVector<APInt> intOutputValues; 1467 SmallVector<APFloat> fpOutputValues; 1468 if (elementType.template isa<FloatType>()) 1469 fpOutputValues.resize(numElements, APFloat(0.f)); 1470 else 1471 intOutputValues.resize(numElements); 1472 1473 // Return the constant dim positions from the given permutation map. 1474 auto getDimPositions = [](AffineMap map) { 1475 SmallVector<unsigned> dims; 1476 dims.reserve(map.getNumResults()); 1477 for (AffineExpr result : map.getResults()) { 1478 dims.push_back(result.cast<AffineDimExpr>().getPosition()); 1479 } 1480 return dims; 1481 }; 1482 1483 SmallVector<SmallVector<unsigned>> inputDims; 1484 for (int i = 0; i < numInputs; ++i) 1485 inputDims.push_back(getDimPositions(genericOp.getIndexingMaps()[i])); 1486 auto outputDims = getDimPositions(genericOp.getIndexingMaps().back()); 1487 auto outputShape = outputType.getShape(); 1488 1489 // Allocate small vectors for index delinearization. Initial values do not 1490 // matter here as they will be overwritten later. 1491 SmallVector<uint64_t> indices(loopBounds.size(), 0); 1492 SmallVector<uint64_t> dstIndices(loopBounds.size(), 0); 1493 SmallVector<SmallVector<uint64_t>> srcIndices( 1494 numInputs, SmallVector<uint64_t>(loopBounds.size(), 0)); 1495 SmallVector<uint64_t> srcLinearIndices(numInputs, 0); 1496 uint64_t dstLinearIndex = 0; 1497 1498 // Allocate spaces for compute function inputs. Initial values do not matter 1499 // here as they will be overwritten later. 1500 APIntOrFloatArray computeFnInputs; 1501 1502 auto inputShapes = llvm::to_vector<4>( 1503 llvm::map_range(genericOp.getInputOperands(), [](OpOperand *operand) { 1504 return operand->get().getType().cast<ShapedType>().getShape(); 1505 })); 1506 1507 // Given a `linearIndex`, remap it to a linear index to access linalg op 1508 // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`, 1509 // `srcLinearIndices`, `dstLinearIndex` in place. 1510 auto computeRemappedLinearIndex = [&](int linearIndex) { 1511 int totalCount = linearIndex; 1512 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) { 1513 indices[dim] = totalCount % loopBounds[dim]; 1514 totalCount /= loopBounds[dim]; 1515 } 1516 1517 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) { 1518 for (int i = 0; i < numInputs; ++i) 1519 srcIndices[i][dim] = indices[inputDims[i][dim]]; 1520 dstIndices[dim] = indices[outputDims[dim]]; 1521 } 1522 1523 dstLinearIndex = dstIndices.front(); 1524 for (int i = 0; i < numInputs; ++i) 1525 srcLinearIndices[i] = srcIndices[i].front(); 1526 1527 for (int dim = 1; dim < outputType.getRank(); ++dim) { 1528 dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim]; 1529 for (int i = 0; i < numInputs; ++i) 1530 srcLinearIndices[i] = 1531 srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim]; 1532 } 1533 }; 1534 1535 bool isFloat = elementType.isa<FloatType>(); 1536 if (isFloat) { 1537 SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges; 1538 for (int i = 0; i < numInputs; ++i) 1539 inFpRanges.push_back(inputValues[i].getValues<APFloat>()); 1540 1541 computeFnInputs.apFloats.resize(numInputs, APFloat(0.f)); 1542 1543 // Transpose the input constant. Because we don't know its rank in 1544 // advance, we need to loop over the range [0, element count) and 1545 // delinearize the index. 1546 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) { 1547 computeRemappedLinearIndex(linearIndex); 1548 1549 // Collect constant elements for all inputs at this loop iteration. 1550 for (int i = 0; i < numInputs; ++i) 1551 computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]]; 1552 1553 // Invoke the computation to get the corresponding constant output 1554 // element. 1555 fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat; 1556 } 1557 } else { 1558 SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges; 1559 for (int i = 0; i < numInputs; ++i) 1560 inIntRanges.push_back(inputValues[i].getValues<APInt>()); 1561 1562 computeFnInputs.apInts.resize(numInputs); 1563 1564 // Transpose the input constant. Because we don't know its rank in 1565 // advance, we need to loop over the range [0, element count) and 1566 // delinearize the index. 1567 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) { 1568 computeRemappedLinearIndex(linearIndex); 1569 1570 // Collect constant elements for all inputs at this loop iteration. 1571 for (int i = 0; i < numInputs; ++i) 1572 computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]]; 1573 1574 // Invoke the computation to get the corresponding constant output 1575 // element. 1576 intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt; 1577 } 1578 } 1579 1580 DenseElementsAttr outputAttr = 1581 isFloat ? DenseElementsAttr::get(outputType, fpOutputValues) 1582 : DenseElementsAttr::get(outputType, intOutputValues); 1583 1584 rewriter.replaceOpWithNewOp<ConstantOp>(genericOp, outputAttr); 1585 return success(); 1586 } 1587 1588 private: 1589 ControlElementwiseOpsFusionFn controlFn; 1590 }; 1591 1592 // Folds linalg.generic ops that are actually transposes on constant values. 1593 struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> { 1594 using FoldConstantBase::FoldConstantBase; 1595 1596 bool matchIndexingMaps(GenericOp genericOp) const { 1597 // We should have one input and one output. 1598 return genericOp.getIndexingMaps().size() == 2; 1599 } 1600 1601 RegionComputationFn getRegionComputeFn(GenericOp genericOp) const { 1602 // Make sure the region only contains a yield op. 1603 Block &body = genericOp.region().front(); 1604 if (!llvm::hasSingleElement(body)) 1605 return nullptr; 1606 auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator()); 1607 if (!yieldOp) 1608 return nullptr; 1609 1610 // The yield op should return the block argument corresponds to the input. 1611 for (Value yieldVal : yieldOp.values()) { 1612 auto yieldArg = yieldVal.dyn_cast<BlockArgument>(); 1613 if (!yieldArg || yieldArg.getOwner() != &body) 1614 return nullptr; 1615 if (yieldArg.getArgNumber() != 0) 1616 return nullptr; 1617 } 1618 1619 // No computation; just return the orginal value. 1620 return [](const APIntOrFloatArray &inputs) { 1621 if (inputs.apFloats.empty()) 1622 return APIntOrFloat{inputs.apInts.front(), llvm::None}; 1623 return APIntOrFloat{llvm::None, inputs.apFloats.front()}; 1624 }; 1625 } 1626 1627 ControlElementwiseOpsFusionFn controlFn; 1628 }; 1629 1630 } // namespace 1631 1632 static Optional<SmallVector<Value>> 1633 fuseElementwiseOps(PatternRewriter &rewriter, OpOperand *consumerOpOperand, 1634 GenericOp producer, 1635 const ControlElementwiseOpsFusionFn &controlFn) { 1636 if (producer->getNumResults() != 1) 1637 return llvm::None; 1638 1639 return fuseElementwiseOpsImpl(producer, consumerOpOperand, controlFn, 1640 rewriter); 1641 } 1642 1643 bool mlir::linalg::skipUnitDimReshape(const OpResult &producer, 1644 OpOperand &consumer) { 1645 if (auto producerCollapseOp = 1646 dyn_cast<tensor::CollapseShapeOp>(producer.getOwner())) { 1647 return !isUnitDimExpansionOnly(producerCollapseOp); 1648 } 1649 if (auto consumerExpandOp = 1650 dyn_cast<tensor::ExpandShapeOp>(consumer.getOwner())) { 1651 return !isUnitDimExpansionOnly(consumerExpandOp); 1652 } 1653 return true; 1654 } 1655 1656 namespace { 1657 /// Patterns to fuse a generic op, with the producer of its operands. 1658 class FuseElementwiseOps : public OpRewritePattern<GenericOp> { 1659 public: 1660 FuseElementwiseOps(MLIRContext *context, ControlElementwiseOpsFusionFn &fun, 1661 PatternBenefit benefit = 1) 1662 : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {} 1663 1664 LogicalResult matchAndRewrite(GenericOp genericOp, 1665 PatternRewriter &rewriter) const override { 1666 // Find the first operand that is defined by another generic op on tensors. 1667 for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) { 1668 auto producer = 1669 dyn_cast_or_null<GenericOp>(opOperand->get().getDefiningOp()); 1670 if (!producer || !producer.hasTensorSemantics()) 1671 continue; 1672 Optional<SmallVector<Value>> fusedOpResults = 1673 fuseElementwiseOps(rewriter, opOperand, producer, controlFn); 1674 if (fusedOpResults) { 1675 rewriter.replaceOp(genericOp, *fusedOpResults); 1676 return success(); 1677 } 1678 } 1679 return failure(); 1680 } 1681 1682 private: 1683 ControlElementwiseOpsFusionFn controlFn; 1684 }; 1685 1686 /// Pass that fuses generic ops on tensors. Used only for testing. 1687 struct LinalgElementwiseOpFusionPass 1688 : public LinalgElementwiseOpFusionBase<LinalgElementwiseOpFusionPass> { 1689 void runOnOperation() override { 1690 Operation *op = getOperation(); 1691 RewritePatternSet patterns(op->getContext()); 1692 ControlElementwiseOpsFusionFn allowFoldingFn = 1693 [](const OpResult &producer, const OpOperand &consumer) { 1694 return true; 1695 }; 1696 populateElementwiseOpsFusionPatterns( 1697 patterns, 1698 LinalgElementwiseFusionOptions().setControlFoldingReshapes( 1699 allowFoldingUnitDimReshapes ? allowFoldingFn : skipUnitDimReshape)); 1700 1701 // Use TopDownTraversal for compile time reasons 1702 GreedyRewriteConfig grc; 1703 grc.useTopDownTraversal = true; 1704 (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns), 1705 grc); 1706 } 1707 }; 1708 1709 /// Pass to test folding of reshape ops with generic ops by linearization. 1710 struct FoldReshapeOpsByLinearizationPass 1711 : public LinalgFoldReshapeOpsByLinearizationBase< 1712 FoldReshapeOpsByLinearizationPass> { 1713 void runOnOperation() override { 1714 Operation *op = getOperation(); 1715 RewritePatternSet patterns(op->getContext()); 1716 populateFoldReshapeOpsByLinearizationPatterns(patterns); 1717 if (allowFoldingUnitDimReshapes) { 1718 populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns); 1719 } 1720 (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns)); 1721 } 1722 }; 1723 1724 /// Forces `outs` operands of linalg operations to use `linalg.init_tensor` if 1725 /// the value of the `outs` operand is not used within the op. This is only 1726 /// implemented for `linalg.generic` operations for now, but should hold for all 1727 /// linalg structured ops. 1728 struct RemoveOutsDependency : public OpRewritePattern<GenericOp> { 1729 using OpRewritePattern<GenericOp>::OpRewritePattern; 1730 1731 LogicalResult matchAndRewrite(GenericOp op, 1732 PatternRewriter &rewriter) const override { 1733 rewriter.startRootUpdate(op); 1734 bool modifiedOutput = false; 1735 Location loc = op.getLoc(); 1736 for (OpOperand *opOperand : op.getOutputOperands()) { 1737 if (!op.payloadUsesValueFromOperand(opOperand)) { 1738 Value operandVal = opOperand->get(); 1739 auto operandType = operandVal.getType().dyn_cast<RankedTensorType>(); 1740 if (!operandType) 1741 continue; 1742 1743 // If outs is already an `init_tensor` operation, nothing to do. 1744 auto definingOp = operandVal.getDefiningOp<InitTensorOp>(); 1745 if (definingOp) 1746 continue; 1747 modifiedOutput = true; 1748 SmallVector<Value> dynamicDims; 1749 for (const auto &dim : llvm::enumerate(operandType.getShape())) { 1750 if (dim.value() != ShapedType::kDynamicSize) 1751 continue; 1752 dynamicDims.push_back(rewriter.createOrFold<tensor::DimOp>( 1753 loc, operandVal, dim.index())); 1754 } 1755 Value initTensor = rewriter.create<InitTensorOp>( 1756 loc, dynamicDims, operandType.getShape(), 1757 operandType.getElementType()); 1758 op->setOperand(opOperand->getOperandNumber(), initTensor); 1759 } 1760 } 1761 if (!modifiedOutput) { 1762 rewriter.cancelRootUpdate(op); 1763 return failure(); 1764 } 1765 rewriter.finalizeRootUpdate(op); 1766 return success(); 1767 } 1768 }; 1769 1770 } // namespace 1771 1772 void mlir::linalg::populateFoldReshapeOpsByLinearizationPatterns( 1773 RewritePatternSet &patterns) { 1774 patterns 1775 .add<FoldProducerReshapeOpByLinearization<false, tensor::CollapseShapeOp>, 1776 FoldProducerReshapeOpByLinearization<false, tensor::ExpandShapeOp>, 1777 FoldConsumerReshapeOpByLinearization<false, tensor::CollapseShapeOp>, 1778 FoldConsumerReshapeOpByLinearization<false, tensor::ExpandShapeOp>>( 1779 patterns.getContext()); 1780 } 1781 1782 void mlir::linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns( 1783 RewritePatternSet &patterns) { 1784 patterns 1785 .add<FoldProducerReshapeOpByLinearization<true, tensor::CollapseShapeOp>, 1786 FoldProducerReshapeOpByLinearization<true, tensor::ExpandShapeOp>, 1787 FoldConsumerReshapeOpByLinearization<true, tensor::CollapseShapeOp>, 1788 FoldConsumerReshapeOpByLinearization<true, tensor::ExpandShapeOp>>( 1789 patterns.getContext()); 1790 } 1791 1792 void mlir::linalg::populateFoldReshapeOpsByExpansionPatterns( 1793 RewritePatternSet &patterns, 1794 const ControlElementwiseOpsFusionFn &controlFoldingReshapes) { 1795 patterns.add<FoldReshapeWithGenericOpByExpansion>(patterns.getContext(), 1796 controlFoldingReshapes); 1797 patterns.add<FoldWithProducerReshapeOpByExpansion>(patterns.getContext(), 1798 controlFoldingReshapes); 1799 } 1800 1801 void mlir::linalg::populateElementwiseOpsFusionPatterns( 1802 RewritePatternSet &patterns, LinalgElementwiseFusionOptions options) { 1803 auto *context = patterns.getContext(); 1804 patterns.add<FuseElementwiseOps, FoldScalarOrSplatConstant, 1805 FoldConstantTranspose>(context, 1806 options.controlElementwiseOpsFusionFn); 1807 patterns.add<RemoveOutsDependency>(context); 1808 populateFoldReshapeOpsByExpansionPatterns(patterns, 1809 options.controlFoldingReshapesFn); 1810 AffineApplyOp::getCanonicalizationPatterns(patterns, context); 1811 GenericOp::getCanonicalizationPatterns(patterns, context); 1812 tensor::ExpandShapeOp::getCanonicalizationPatterns(patterns, context); 1813 tensor::CollapseShapeOp::getCanonicalizationPatterns(patterns, context); 1814 context->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns( 1815 patterns); 1816 } 1817 1818 void mlir::linalg::populatePushReshapeOpsPatterns(RewritePatternSet &patterns) { 1819 auto *context = patterns.getContext(); 1820 patterns.add<PushExpandingReshape>(context); 1821 } 1822 1823 std::unique_ptr<Pass> mlir::createLinalgElementwiseOpFusionPass() { 1824 return std::make_unique<LinalgElementwiseOpFusionPass>(); 1825 } 1826 1827 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() { 1828 return std::make_unique<FoldReshapeOpsByLinearizationPass>(); 1829 } 1830