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