1 //===- DialectConversion.cpp - MLIR dialect conversion generic pass -------===// 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 #include "mlir/Transforms/DialectConversion.h" 10 #include "mlir/IR/Block.h" 11 #include "mlir/IR/BlockAndValueMapping.h" 12 #include "mlir/IR/Builders.h" 13 #include "mlir/IR/BuiltinOps.h" 14 #include "mlir/IR/FunctionSupport.h" 15 #include "mlir/Rewrite/PatternApplicator.h" 16 #include "mlir/Transforms/Utils.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/FormatVariadic.h" 21 #include "llvm/Support/SaveAndRestore.h" 22 #include "llvm/Support/ScopedPrinter.h" 23 24 using namespace mlir; 25 using namespace mlir::detail; 26 27 #define DEBUG_TYPE "dialect-conversion" 28 29 /// Recursively collect all of the operations to convert from within 'region'. 30 /// If 'target' is nonnull, operations that are recursively legal have their 31 /// regions pre-filtered to avoid considering them for legalization. 32 static LogicalResult 33 computeConversionSet(iterator_range<Region::iterator> region, 34 Location regionLoc, std::vector<Operation *> &toConvert, 35 ConversionTarget *target = nullptr) { 36 if (llvm::empty(region)) 37 return success(); 38 39 // Traverse starting from the entry block. 40 SmallVector<Block *, 16> worklist(1, &*region.begin()); 41 DenseSet<Block *> visitedBlocks; 42 visitedBlocks.insert(worklist.front()); 43 while (!worklist.empty()) { 44 Block *block = worklist.pop_back_val(); 45 46 // Compute the conversion set of each of the nested operations. 47 for (Operation &op : *block) { 48 toConvert.emplace_back(&op); 49 50 // Don't check this operation's children for conversion if the operation 51 // is recursively legal. 52 auto legalityInfo = target ? target->isLegal(&op) 53 : Optional<ConversionTarget::LegalOpDetails>(); 54 if (legalityInfo && legalityInfo->isRecursivelyLegal) 55 continue; 56 for (auto ®ion : op.getRegions()) { 57 if (failed(computeConversionSet(region.getBlocks(), region.getLoc(), 58 toConvert, target))) 59 return failure(); 60 } 61 } 62 63 // Recurse to children that haven't been visited. 64 for (Block *succ : block->getSuccessors()) 65 if (visitedBlocks.insert(succ).second) 66 worklist.push_back(succ); 67 } 68 69 // Check that all blocks in the region were visited. 70 if (llvm::any_of(llvm::drop_begin(region, 1), 71 [&](Block &block) { return !visitedBlocks.count(&block); })) 72 return emitError(regionLoc, "unreachable blocks were not converted"); 73 return success(); 74 } 75 76 /// A utility function to log a successful result for the given reason. 77 template <typename... Args> 78 static void logSuccess(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) { 79 LLVM_DEBUG({ 80 os.unindent(); 81 os.startLine() << "} -> SUCCESS"; 82 if (!fmt.empty()) 83 os.getOStream() << " : " 84 << llvm::formatv(fmt.data(), std::forward<Args>(args)...); 85 os.getOStream() << "\n"; 86 }); 87 } 88 89 /// A utility function to log a failure result for the given reason. 90 template <typename... Args> 91 static void logFailure(llvm::ScopedPrinter &os, StringRef fmt, Args &&...args) { 92 LLVM_DEBUG({ 93 os.unindent(); 94 os.startLine() << "} -> FAILURE : " 95 << llvm::formatv(fmt.data(), std::forward<Args>(args)...) 96 << "\n"; 97 }); 98 } 99 100 //===----------------------------------------------------------------------===// 101 // ConversionValueMapping 102 //===----------------------------------------------------------------------===// 103 104 namespace { 105 /// This class wraps a BlockAndValueMapping to provide recursive lookup 106 /// functionality, i.e. we will traverse if the mapped value also has a mapping. 107 struct ConversionValueMapping { 108 /// Lookup a mapped value within the map. If a mapping for the provided value 109 /// does not exist then return the provided value. If `desiredType` is 110 /// non-null, returns the most recently mapped value with that type. If an 111 /// operand of that type does not exist, defaults to normal behavior. 112 Value lookupOrDefault(Value from, Type desiredType = nullptr) const; 113 114 /// Lookup a mapped value within the map, or return null if a mapping does not 115 /// exist. If a mapping exists, this follows the same behavior of 116 /// `lookupOrDefault`. 117 Value lookupOrNull(Value from) const; 118 119 /// Map a value to the one provided. 120 void map(Value oldVal, Value newVal) { mapping.map(oldVal, newVal); } 121 122 /// Drop the last mapping for the given value. 123 void erase(Value value) { mapping.erase(value); } 124 125 /// Returns the inverse raw value mapping (without recursive query support). 126 BlockAndValueMapping getInverse() const { return mapping.getInverse(); } 127 128 private: 129 /// Current value mappings. 130 BlockAndValueMapping mapping; 131 }; 132 } // end anonymous namespace 133 134 Value ConversionValueMapping::lookupOrDefault(Value from, 135 Type desiredType) const { 136 // If there was no desired type, simply find the leaf value. 137 if (!desiredType) { 138 // If this value had a valid mapping, unmap that value as well in the case 139 // that it was also replaced. 140 while (auto mappedValue = mapping.lookupOrNull(from)) 141 from = mappedValue; 142 return from; 143 } 144 145 // Otherwise, try to find the deepest value that has the desired type. 146 Value desiredValue; 147 do { 148 if (from.getType() == desiredType) 149 desiredValue = from; 150 151 Value mappedValue = mapping.lookupOrNull(from); 152 if (!mappedValue) 153 break; 154 from = mappedValue; 155 } while (true); 156 157 // If the desired value was found use it, otherwise default to the leaf value. 158 return desiredValue ? desiredValue : from; 159 } 160 161 Value ConversionValueMapping::lookupOrNull(Value from) const { 162 Value result = lookupOrDefault(from); 163 return result == from ? nullptr : result; 164 } 165 166 //===----------------------------------------------------------------------===// 167 // ArgConverter 168 //===----------------------------------------------------------------------===// 169 namespace { 170 /// This class provides a simple interface for converting the types of block 171 /// arguments. This is done by creating a new block that contains the new legal 172 /// types and extracting the block that contains the old illegal types to allow 173 /// for undoing pending rewrites in the case of failure. 174 struct ArgConverter { 175 ArgConverter(PatternRewriter &rewriter) : rewriter(rewriter) {} 176 177 /// This structure contains the information pertaining to an argument that has 178 /// been converted. 179 struct ConvertedArgInfo { 180 ConvertedArgInfo(unsigned newArgIdx, unsigned newArgSize, 181 Value castValue = nullptr) 182 : newArgIdx(newArgIdx), newArgSize(newArgSize), castValue(castValue) {} 183 184 /// The start index of in the new argument list that contains arguments that 185 /// replace the original. 186 unsigned newArgIdx; 187 188 /// The number of arguments that replaced the original argument. 189 unsigned newArgSize; 190 191 /// The cast value that was created to cast from the new arguments to the 192 /// old. This only used if 'newArgSize' > 1. 193 Value castValue; 194 }; 195 196 /// This structure contains information pertaining to a block that has had its 197 /// signature converted. 198 struct ConvertedBlockInfo { 199 ConvertedBlockInfo(Block *origBlock, TypeConverter &converter) 200 : origBlock(origBlock), converter(&converter) {} 201 202 /// The original block that was requested to have its signature converted. 203 Block *origBlock; 204 205 /// The conversion information for each of the arguments. The information is 206 /// None if the argument was dropped during conversion. 207 SmallVector<Optional<ConvertedArgInfo>, 1> argInfo; 208 209 /// The type converter used to convert the arguments. 210 TypeConverter *converter; 211 }; 212 213 /// Return if the signature of the given block has already been converted. 214 bool hasBeenConverted(Block *block) const { 215 return conversionInfo.count(block) || convertedBlocks.count(block); 216 } 217 218 /// Set the type converter to use for the given region. 219 void setConverter(Region *region, TypeConverter *typeConverter) { 220 assert(typeConverter && "expected valid type converter"); 221 regionToConverter[region] = typeConverter; 222 } 223 224 /// Return the type converter to use for the given region, or null if there 225 /// isn't one. 226 TypeConverter *getConverter(Region *region) { 227 return regionToConverter.lookup(region); 228 } 229 230 //===--------------------------------------------------------------------===// 231 // Rewrite Application 232 //===--------------------------------------------------------------------===// 233 234 /// Erase any rewrites registered for the blocks within the given operation 235 /// which is about to be removed. This merely drops the rewrites without 236 /// undoing them. 237 void notifyOpRemoved(Operation *op); 238 239 /// Cleanup and undo any generated conversions for the arguments of block. 240 /// This method replaces the new block with the original, reverting the IR to 241 /// its original state. 242 void discardRewrites(Block *block); 243 244 /// Fully replace uses of the old arguments with the new. 245 void applyRewrites(ConversionValueMapping &mapping); 246 247 /// Materialize any necessary conversions for converted arguments that have 248 /// live users, using the provided `findLiveUser` to search for a user that 249 /// survives the conversion process. 250 LogicalResult 251 materializeLiveConversions(ConversionValueMapping &mapping, 252 OpBuilder &builder, 253 function_ref<Operation *(Value)> findLiveUser); 254 255 //===--------------------------------------------------------------------===// 256 // Conversion 257 //===--------------------------------------------------------------------===// 258 259 /// Attempt to convert the signature of the given block, if successful a new 260 /// block is returned containing the new arguments. Returns `block` if it did 261 /// not require conversion. 262 FailureOr<Block *> 263 convertSignature(Block *block, TypeConverter &converter, 264 ConversionValueMapping &mapping, 265 SmallVectorImpl<BlockArgument> &argReplacements); 266 267 /// Apply the given signature conversion on the given block. The new block 268 /// containing the updated signature is returned. If no conversions were 269 /// necessary, e.g. if the block has no arguments, `block` is returned. 270 /// `converter` is used to generate any necessary cast operations that 271 /// translate between the origin argument types and those specified in the 272 /// signature conversion. 273 Block *applySignatureConversion( 274 Block *block, TypeConverter &converter, 275 TypeConverter::SignatureConversion &signatureConversion, 276 ConversionValueMapping &mapping, 277 SmallVectorImpl<BlockArgument> &argReplacements); 278 279 /// Insert a new conversion into the cache. 280 void insertConversion(Block *newBlock, ConvertedBlockInfo &&info); 281 282 /// A collection of blocks that have had their arguments converted. This is a 283 /// map from the new replacement block, back to the original block. 284 llvm::MapVector<Block *, ConvertedBlockInfo> conversionInfo; 285 286 /// The set of original blocks that were converted. 287 DenseSet<Block *> convertedBlocks; 288 289 /// A mapping from valid regions, to those containing the original blocks of a 290 /// conversion. 291 DenseMap<Region *, std::unique_ptr<Region>> regionMapping; 292 293 /// A mapping of regions to type converters that should be used when 294 /// converting the arguments of blocks within that region. 295 DenseMap<Region *, TypeConverter *> regionToConverter; 296 297 /// The pattern rewriter to use when materializing conversions. 298 PatternRewriter &rewriter; 299 }; 300 } // end anonymous namespace 301 302 //===----------------------------------------------------------------------===// 303 // Rewrite Application 304 305 void ArgConverter::notifyOpRemoved(Operation *op) { 306 if (conversionInfo.empty()) 307 return; 308 309 for (Region ®ion : op->getRegions()) { 310 for (Block &block : region) { 311 // Drop any rewrites from within. 312 for (Operation &nestedOp : block) 313 if (nestedOp.getNumRegions()) 314 notifyOpRemoved(&nestedOp); 315 316 // Check if this block was converted. 317 auto it = conversionInfo.find(&block); 318 if (it == conversionInfo.end()) 319 continue; 320 321 // Drop all uses of the original arguments and delete the original block. 322 Block *origBlock = it->second.origBlock; 323 for (BlockArgument arg : origBlock->getArguments()) 324 arg.dropAllUses(); 325 conversionInfo.erase(it); 326 } 327 } 328 } 329 330 void ArgConverter::discardRewrites(Block *block) { 331 auto it = conversionInfo.find(block); 332 if (it == conversionInfo.end()) 333 return; 334 Block *origBlock = it->second.origBlock; 335 336 // Drop all uses of the new block arguments and replace uses of the new block. 337 for (int i = block->getNumArguments() - 1; i >= 0; --i) 338 block->getArgument(i).dropAllUses(); 339 block->replaceAllUsesWith(origBlock); 340 341 // Move the operations back the original block and the delete the new block. 342 origBlock->getOperations().splice(origBlock->end(), block->getOperations()); 343 origBlock->moveBefore(block); 344 block->erase(); 345 346 convertedBlocks.erase(origBlock); 347 conversionInfo.erase(it); 348 } 349 350 void ArgConverter::applyRewrites(ConversionValueMapping &mapping) { 351 for (auto &info : conversionInfo) { 352 ConvertedBlockInfo &blockInfo = info.second; 353 Block *origBlock = blockInfo.origBlock; 354 355 // Process the remapping for each of the original arguments. 356 for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) { 357 Optional<ConvertedArgInfo> &argInfo = blockInfo.argInfo[i]; 358 BlockArgument origArg = origBlock->getArgument(i); 359 360 // Handle the case of a 1->0 value mapping. 361 if (!argInfo) { 362 if (Value newArg = mapping.lookupOrNull(origArg)) 363 origArg.replaceAllUsesWith(newArg); 364 continue; 365 } 366 367 // Otherwise this is a 1->1+ value mapping. 368 Value castValue = argInfo->castValue; 369 assert(argInfo->newArgSize >= 1 && castValue && "expected 1->1+ mapping"); 370 371 // If the argument is still used, replace it with the generated cast. 372 if (!origArg.use_empty()) 373 origArg.replaceAllUsesWith(mapping.lookupOrDefault(castValue)); 374 } 375 } 376 } 377 378 LogicalResult ArgConverter::materializeLiveConversions( 379 ConversionValueMapping &mapping, OpBuilder &builder, 380 function_ref<Operation *(Value)> findLiveUser) { 381 for (auto &info : conversionInfo) { 382 Block *newBlock = info.first; 383 ConvertedBlockInfo &blockInfo = info.second; 384 Block *origBlock = blockInfo.origBlock; 385 386 // Process the remapping for each of the original arguments. 387 for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) { 388 // FIXME: We should run the below checks even if the type conversion was 389 // 1->N, but a lot of existing lowering rely on the block argument being 390 // blindly replaced. Those usages should be updated, and this if should be 391 // removed. 392 if (blockInfo.argInfo[i]) 393 continue; 394 395 // If the type of this argument changed and the argument is still live, we 396 // need to materialize a conversion. 397 BlockArgument origArg = origBlock->getArgument(i); 398 auto argReplacementValue = mapping.lookupOrDefault(origArg); 399 bool isDroppedArg = argReplacementValue == origArg; 400 if (argReplacementValue.getType() == origArg.getType() && !isDroppedArg) 401 continue; 402 Operation *liveUser = findLiveUser(origArg); 403 if (!liveUser) 404 continue; 405 406 if (OpResult result = argReplacementValue.dyn_cast<OpResult>()) 407 rewriter.setInsertionPointAfter(result.getOwner()); 408 else 409 rewriter.setInsertionPointToStart(newBlock); 410 Value newArg = blockInfo.converter->materializeSourceConversion( 411 rewriter, origArg.getLoc(), origArg.getType(), 412 isDroppedArg ? ValueRange() : ValueRange(argReplacementValue)); 413 if (!newArg) { 414 InFlightDiagnostic diag = 415 emitError(origArg.getLoc()) 416 << "failed to materialize conversion for block argument #" << i 417 << " that remained live after conversion, type was " 418 << origArg.getType(); 419 if (!isDroppedArg) 420 diag << ", with target type " << argReplacementValue.getType(); 421 diag.attachNote(liveUser->getLoc()) 422 << "see existing live user here: " << *liveUser; 423 return failure(); 424 } 425 mapping.map(origArg, newArg); 426 } 427 } 428 return success(); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Conversion 433 434 FailureOr<Block *> ArgConverter::convertSignature( 435 Block *block, TypeConverter &converter, ConversionValueMapping &mapping, 436 SmallVectorImpl<BlockArgument> &argReplacements) { 437 // Check if the block was already converted. If the block is detached, 438 // conservatively assume it is going to be deleted. 439 if (hasBeenConverted(block) || !block->getParent()) 440 return block; 441 442 // Try to convert the signature for the block with the provided converter. 443 if (auto conversion = converter.convertBlockSignature(block)) 444 return applySignatureConversion(block, converter, *conversion, mapping, 445 argReplacements); 446 return failure(); 447 } 448 449 Block *ArgConverter::applySignatureConversion( 450 Block *block, TypeConverter &converter, 451 TypeConverter::SignatureConversion &signatureConversion, 452 ConversionValueMapping &mapping, 453 SmallVectorImpl<BlockArgument> &argReplacements) { 454 // If no arguments are being changed or added, there is nothing to do. 455 unsigned origArgCount = block->getNumArguments(); 456 auto convertedTypes = signatureConversion.getConvertedTypes(); 457 if (origArgCount == 0 && convertedTypes.empty()) 458 return block; 459 460 // Split the block at the beginning to get a new block to use for the updated 461 // signature. 462 Block *newBlock = block->splitBlock(block->begin()); 463 block->replaceAllUsesWith(newBlock); 464 465 SmallVector<Value, 4> newArgRange(newBlock->addArguments(convertedTypes)); 466 ArrayRef<Value> newArgs(newArgRange); 467 468 // Remap each of the original arguments as determined by the signature 469 // conversion. 470 ConvertedBlockInfo info(block, converter); 471 info.argInfo.resize(origArgCount); 472 473 OpBuilder::InsertionGuard guard(rewriter); 474 rewriter.setInsertionPointToStart(newBlock); 475 for (unsigned i = 0; i != origArgCount; ++i) { 476 auto inputMap = signatureConversion.getInputMapping(i); 477 if (!inputMap) 478 continue; 479 BlockArgument origArg = block->getArgument(i); 480 481 // If inputMap->replacementValue is not nullptr, then the argument is 482 // dropped and a replacement value is provided to be the remappedValue. 483 if (inputMap->replacementValue) { 484 assert(inputMap->size == 0 && 485 "invalid to provide a replacement value when the argument isn't " 486 "dropped"); 487 mapping.map(origArg, inputMap->replacementValue); 488 argReplacements.push_back(origArg); 489 continue; 490 } 491 492 // Otherwise, this is a 1->1+ mapping. Call into the provided type converter 493 // to pack the new values. For 1->1 mappings, if there is no materialization 494 // provided, use the argument directly instead. 495 auto replArgs = newArgs.slice(inputMap->inputNo, inputMap->size); 496 Value newArg; 497 498 // If this is a 1->1 mapping and the types of new and replacement arguments 499 // match (i.e. it's an identity map), then the argument is mapped to its 500 // original type. 501 if (replArgs.size() == 1 && replArgs[0].getType() == origArg.getType()) 502 newArg = replArgs[0]; 503 else 504 newArg = converter.materializeArgumentConversion( 505 rewriter, origArg.getLoc(), origArg.getType(), replArgs); 506 507 if (!newArg) { 508 assert(replArgs.size() == 1 && 509 "couldn't materialize the result of 1->N conversion"); 510 newArg = replArgs.front(); 511 } 512 mapping.map(origArg, newArg); 513 argReplacements.push_back(origArg); 514 info.argInfo[i] = 515 ConvertedArgInfo(inputMap->inputNo, inputMap->size, newArg); 516 } 517 518 // Remove the original block from the region and return the new one. 519 insertConversion(newBlock, std::move(info)); 520 return newBlock; 521 } 522 523 void ArgConverter::insertConversion(Block *newBlock, 524 ConvertedBlockInfo &&info) { 525 // Get a region to insert the old block. 526 Region *region = newBlock->getParent(); 527 std::unique_ptr<Region> &mappedRegion = regionMapping[region]; 528 if (!mappedRegion) 529 mappedRegion = std::make_unique<Region>(region->getParentOp()); 530 531 // Move the original block to the mapped region and emplace the conversion. 532 mappedRegion->getBlocks().splice(mappedRegion->end(), region->getBlocks(), 533 info.origBlock->getIterator()); 534 convertedBlocks.insert(info.origBlock); 535 conversionInfo.insert({newBlock, std::move(info)}); 536 } 537 538 //===----------------------------------------------------------------------===// 539 // Rewriter and Translation State 540 //===----------------------------------------------------------------------===// 541 namespace { 542 /// This class contains a snapshot of the current conversion rewriter state. 543 /// This is useful when saving and undoing a set of rewrites. 544 struct RewriterState { 545 RewriterState(unsigned numCreatedOps, unsigned numReplacements, 546 unsigned numArgReplacements, unsigned numBlockActions, 547 unsigned numIgnoredOperations, unsigned numRootUpdates) 548 : numCreatedOps(numCreatedOps), numReplacements(numReplacements), 549 numArgReplacements(numArgReplacements), 550 numBlockActions(numBlockActions), 551 numIgnoredOperations(numIgnoredOperations), 552 numRootUpdates(numRootUpdates) {} 553 554 /// The current number of created operations. 555 unsigned numCreatedOps; 556 557 /// The current number of replacements queued. 558 unsigned numReplacements; 559 560 /// The current number of argument replacements queued. 561 unsigned numArgReplacements; 562 563 /// The current number of block actions performed. 564 unsigned numBlockActions; 565 566 /// The current number of ignored operations. 567 unsigned numIgnoredOperations; 568 569 /// The current number of operations that were updated in place. 570 unsigned numRootUpdates; 571 }; 572 573 /// The state of an operation that was updated by a pattern in-place. This 574 /// contains all of the necessary information to reconstruct an operation that 575 /// was updated in place. 576 class OperationTransactionState { 577 public: 578 OperationTransactionState() = default; 579 OperationTransactionState(Operation *op) 580 : op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()), 581 operands(op->operand_begin(), op->operand_end()), 582 successors(op->successor_begin(), op->successor_end()) {} 583 584 /// Discard the transaction state and reset the state of the original 585 /// operation. 586 void resetOperation() const { 587 op->setLoc(loc); 588 op->setAttrs(attrs); 589 op->setOperands(operands); 590 for (auto it : llvm::enumerate(successors)) 591 op->setSuccessor(it.value(), it.index()); 592 } 593 594 /// Return the original operation of this state. 595 Operation *getOperation() const { return op; } 596 597 private: 598 Operation *op; 599 LocationAttr loc; 600 DictionaryAttr attrs; 601 SmallVector<Value, 8> operands; 602 SmallVector<Block *, 2> successors; 603 }; 604 605 /// This class represents one requested operation replacement via 'replaceOp' or 606 /// 'eraseOp`. 607 struct OpReplacement { 608 OpReplacement() = default; 609 OpReplacement(TypeConverter *converter) : converter(converter) {} 610 611 /// An optional type converter that can be used to materialize conversions 612 /// between the new and old values if necessary. 613 TypeConverter *converter = nullptr; 614 }; 615 616 /// The kind of the block action performed during the rewrite. Actions can be 617 /// undone if the conversion fails. 618 enum class BlockActionKind { 619 Create, 620 Erase, 621 Merge, 622 Move, 623 Split, 624 TypeConversion 625 }; 626 627 /// Original position of the given block in its parent region. During undo 628 /// actions, the block needs to be placed after `insertAfterBlock`. 629 struct BlockPosition { 630 Region *region; 631 Block *insertAfterBlock; 632 }; 633 634 /// Information needed to undo the merge actions. 635 /// - the source block, and 636 /// - the Operation that was the last operation in the dest block before the 637 /// merge (could be null if the dest block was empty). 638 struct MergeInfo { 639 Block *sourceBlock; 640 Operation *destBlockLastInst; 641 }; 642 643 /// The storage class for an undoable block action (one of BlockActionKind), 644 /// contains the information necessary to undo this action. 645 struct BlockAction { 646 static BlockAction getCreate(Block *block) { 647 return {BlockActionKind::Create, block, {}}; 648 } 649 static BlockAction getErase(Block *block, BlockPosition originalPosition) { 650 return {BlockActionKind::Erase, block, {originalPosition}}; 651 } 652 static BlockAction getMerge(Block *block, Block *sourceBlock) { 653 BlockAction action{BlockActionKind::Merge, block, {}}; 654 action.mergeInfo = {sourceBlock, block->empty() ? nullptr : &block->back()}; 655 return action; 656 } 657 static BlockAction getMove(Block *block, BlockPosition originalPosition) { 658 return {BlockActionKind::Move, block, {originalPosition}}; 659 } 660 static BlockAction getSplit(Block *block, Block *originalBlock) { 661 BlockAction action{BlockActionKind::Split, block, {}}; 662 action.originalBlock = originalBlock; 663 return action; 664 } 665 static BlockAction getTypeConversion(Block *block) { 666 return BlockAction{BlockActionKind::TypeConversion, block, {}}; 667 } 668 669 // The action kind. 670 BlockActionKind kind; 671 672 // A pointer to the block that was created by the action. 673 Block *block; 674 675 union { 676 // In use if kind == BlockActionKind::Move or BlockActionKind::Erase, and 677 // contains a pointer to the region that originally contained the block as 678 // well as the position of the block in that region. 679 BlockPosition originalPosition; 680 // In use if kind == BlockActionKind::Split and contains a pointer to the 681 // block that was split into two parts. 682 Block *originalBlock; 683 // In use if kind == BlockActionKind::Merge, and contains the information 684 // needed to undo the merge. 685 MergeInfo mergeInfo; 686 }; 687 }; 688 } // end anonymous namespace 689 690 //===----------------------------------------------------------------------===// 691 // ConversionPatternRewriterImpl 692 //===----------------------------------------------------------------------===// 693 namespace mlir { 694 namespace detail { 695 struct ConversionPatternRewriterImpl { 696 ConversionPatternRewriterImpl(PatternRewriter &rewriter) 697 : argConverter(rewriter) {} 698 699 /// Cleanup and destroy any generated rewrite operations. This method is 700 /// invoked when the conversion process fails. 701 void discardRewrites(); 702 703 /// Apply all requested operation rewrites. This method is invoked when the 704 /// conversion process succeeds. 705 void applyRewrites(); 706 707 //===--------------------------------------------------------------------===// 708 // State Management 709 //===--------------------------------------------------------------------===// 710 711 /// Return the current state of the rewriter. 712 RewriterState getCurrentState(); 713 714 /// Reset the state of the rewriter to a previously saved point. 715 void resetState(RewriterState state); 716 717 /// Erase any blocks that were unlinked from their regions and stored in block 718 /// actions. 719 void eraseDanglingBlocks(); 720 721 /// Undo the block actions (motions, splits) one by one in reverse order until 722 /// "numActionsToKeep" actions remains. 723 void undoBlockActions(unsigned numActionsToKeep = 0); 724 725 /// Remap the given operands to those with potentially different types. The 726 /// provided type converter is used to ensure that the remapped types are 727 /// legal. Returns success if the operands could be remapped, failure 728 /// otherwise. 729 LogicalResult remapValues(Location loc, PatternRewriter &rewriter, 730 TypeConverter *converter, 731 Operation::operand_range operands, 732 SmallVectorImpl<Value> &remapped); 733 734 /// Returns true if the given operation is ignored, and does not need to be 735 /// converted. 736 bool isOpIgnored(Operation *op) const; 737 738 /// Recursively marks the nested operations under 'op' as ignored. This 739 /// removes them from being considered for legalization. 740 void markNestedOpsIgnored(Operation *op); 741 742 //===--------------------------------------------------------------------===// 743 // Type Conversion 744 //===--------------------------------------------------------------------===// 745 746 /// Convert the signature of the given block. 747 FailureOr<Block *> convertBlockSignature( 748 Block *block, TypeConverter &converter, 749 TypeConverter::SignatureConversion *conversion = nullptr); 750 751 /// Apply a signature conversion on the given region, using `converter` for 752 /// materializations if not null. 753 Block * 754 applySignatureConversion(Region *region, 755 TypeConverter::SignatureConversion &conversion, 756 TypeConverter *converter); 757 758 /// Convert the types of block arguments within the given region. 759 FailureOr<Block *> 760 convertRegionTypes(Region *region, TypeConverter &converter, 761 TypeConverter::SignatureConversion *entryConversion); 762 763 /// Convert the types of non-entry block arguments within the given region. 764 LogicalResult convertNonEntryRegionTypes( 765 Region *region, TypeConverter &converter, 766 ArrayRef<TypeConverter::SignatureConversion> blockConversions = {}); 767 768 //===--------------------------------------------------------------------===// 769 // Rewriter Notification Hooks 770 //===--------------------------------------------------------------------===// 771 772 /// PatternRewriter hook for replacing the results of an operation. 773 void notifyOpReplaced(Operation *op, ValueRange newValues); 774 775 /// Notifies that a block is about to be erased. 776 void notifyBlockIsBeingErased(Block *block); 777 778 /// Notifies that a block was created. 779 void notifyCreatedBlock(Block *block); 780 781 /// Notifies that a block was split. 782 void notifySplitBlock(Block *block, Block *continuation); 783 784 /// Notifies that `block` is being merged with `srcBlock`. 785 void notifyBlocksBeingMerged(Block *block, Block *srcBlock); 786 787 /// Notifies that the blocks of a region are about to be moved. 788 void notifyRegionIsBeingInlinedBefore(Region ®ion, Region &parent, 789 Region::iterator before); 790 791 /// Notifies that the blocks of a region were cloned into another. 792 void notifyRegionWasClonedBefore(iterator_range<Region::iterator> &blocks, 793 Location origRegionLoc); 794 795 /// Notifies that a pattern match failed for the given reason. 796 LogicalResult 797 notifyMatchFailure(Location loc, 798 function_ref<void(Diagnostic &)> reasonCallback); 799 800 //===--------------------------------------------------------------------===// 801 // State 802 //===--------------------------------------------------------------------===// 803 804 // Mapping between replaced values that differ in type. This happens when 805 // replacing a value with one of a different type. 806 ConversionValueMapping mapping; 807 808 /// Utility used to convert block arguments. 809 ArgConverter argConverter; 810 811 /// Ordered vector of all of the newly created operations during conversion. 812 std::vector<Operation *> createdOps; 813 814 /// Ordered map of requested operation replacements. 815 llvm::MapVector<Operation *, OpReplacement> replacements; 816 817 /// Ordered vector of any requested block argument replacements. 818 SmallVector<BlockArgument, 4> argReplacements; 819 820 /// Ordered list of block operations (creations, splits, motions). 821 SmallVector<BlockAction, 4> blockActions; 822 823 /// A set of operations that should no longer be considered for legalization, 824 /// but were not directly replace/erased/etc. by a pattern. These are 825 /// generally child operations of other operations who were 826 /// replaced/erased/etc. This is not meant to be an exhaustive list of all 827 /// operations, but the minimal set that can be used to detect if a given 828 /// operation should be `ignored`. For example, we may add the operations that 829 /// define non-empty regions to the set, but not any of the others. This 830 /// simplifies the amount of memory needed as we can query if the parent 831 /// operation was ignored. 832 SetVector<Operation *> ignoredOps; 833 834 /// A transaction state for each of operations that were updated in-place. 835 SmallVector<OperationTransactionState, 4> rootUpdates; 836 837 /// A vector of indices into `replacements` of operations that were replaced 838 /// with values with different result types than the original operation, e.g. 839 /// 1->N conversion of some kind. 840 SmallVector<unsigned, 4> operationsWithChangedResults; 841 842 /// A default type converter, used when block conversions do not have one 843 /// explicitly provided. 844 TypeConverter defaultTypeConverter; 845 846 /// The current conversion pattern that is being rewritten, or nullptr if 847 /// called from outside of a conversion pattern rewrite. 848 const ConversionPattern *currentConversionPattern = nullptr; 849 850 #ifndef NDEBUG 851 /// A set of operations that have pending updates. This tracking isn't 852 /// strictly necessary, and is thus only active during debug builds for extra 853 /// verification. 854 SmallPtrSet<Operation *, 1> pendingRootUpdates; 855 856 /// A logger used to emit diagnostics during the conversion process. 857 llvm::ScopedPrinter logger{llvm::dbgs()}; 858 #endif 859 }; 860 } // end namespace detail 861 } // end namespace mlir 862 863 /// Detach any operations nested in the given operation from their parent 864 /// blocks, and erase the given operation. This can be used when the nested 865 /// operations are scheduled for erasure themselves, so deleting the regions of 866 /// the given operation together with their content would result in double-free. 867 /// This happens, for example, when rolling back op creation in the reverse 868 /// order and if the nested ops were created before the parent op. This function 869 /// does not need to collect nested ops recursively because it is expected to 870 /// also be called for each nested op when it is about to be deleted. 871 static void detachNestedAndErase(Operation *op) { 872 for (Region ®ion : op->getRegions()) { 873 for (Block &block : region.getBlocks()) { 874 while (!block.getOperations().empty()) 875 block.getOperations().remove(block.getOperations().begin()); 876 block.dropAllDefinedValueUses(); 877 } 878 } 879 op->dropAllUses(); 880 op->erase(); 881 } 882 883 void ConversionPatternRewriterImpl::discardRewrites() { 884 // Reset any operations that were updated in place. 885 for (auto &state : rootUpdates) 886 state.resetOperation(); 887 888 undoBlockActions(); 889 890 // Remove any newly created ops. 891 for (auto *op : llvm::reverse(createdOps)) 892 detachNestedAndErase(op); 893 } 894 895 void ConversionPatternRewriterImpl::applyRewrites() { 896 // Apply all of the rewrites replacements requested during conversion. 897 for (auto &repl : replacements) { 898 for (OpResult result : repl.first->getResults()) 899 if (Value newValue = mapping.lookupOrNull(result)) 900 result.replaceAllUsesWith(newValue); 901 902 // If this operation defines any regions, drop any pending argument 903 // rewrites. 904 if (repl.first->getNumRegions()) 905 argConverter.notifyOpRemoved(repl.first); 906 } 907 908 // Apply all of the requested argument replacements. 909 for (BlockArgument arg : argReplacements) { 910 Value repl = mapping.lookupOrDefault(arg); 911 if (repl.isa<BlockArgument>()) { 912 arg.replaceAllUsesWith(repl); 913 continue; 914 } 915 916 // If the replacement value is an operation, we check to make sure that we 917 // don't replace uses that are within the parent operation of the 918 // replacement value. 919 Operation *replOp = repl.cast<OpResult>().getOwner(); 920 Block *replBlock = replOp->getBlock(); 921 arg.replaceUsesWithIf(repl, [&](OpOperand &operand) { 922 Operation *user = operand.getOwner(); 923 return user->getBlock() != replBlock || replOp->isBeforeInBlock(user); 924 }); 925 } 926 927 // In a second pass, erase all of the replaced operations in reverse. This 928 // allows processing nested operations before their parent region is 929 // destroyed. Because we process in reverse order, producers may be deleted 930 // before their users (a pattern deleting a producer and then the consumer) 931 // so we first drop all uses explicitly. 932 for (auto &repl : llvm::reverse(replacements)) { 933 repl.first->dropAllUses(); 934 repl.first->erase(); 935 } 936 937 argConverter.applyRewrites(mapping); 938 939 // Now that the ops have been erased, also erase dangling blocks. 940 eraseDanglingBlocks(); 941 } 942 943 //===----------------------------------------------------------------------===// 944 // State Management 945 946 RewriterState ConversionPatternRewriterImpl::getCurrentState() { 947 return RewriterState(createdOps.size(), replacements.size(), 948 argReplacements.size(), blockActions.size(), 949 ignoredOps.size(), rootUpdates.size()); 950 } 951 952 void ConversionPatternRewriterImpl::resetState(RewriterState state) { 953 // Reset any operations that were updated in place. 954 for (unsigned i = state.numRootUpdates, e = rootUpdates.size(); i != e; ++i) 955 rootUpdates[i].resetOperation(); 956 rootUpdates.resize(state.numRootUpdates); 957 958 // Reset any replaced arguments. 959 for (BlockArgument replacedArg : 960 llvm::drop_begin(argReplacements, state.numArgReplacements)) 961 mapping.erase(replacedArg); 962 argReplacements.resize(state.numArgReplacements); 963 964 // Undo any block actions. 965 undoBlockActions(state.numBlockActions); 966 967 // Reset any replaced operations and undo any saved mappings. 968 for (auto &repl : llvm::drop_begin(replacements, state.numReplacements)) 969 for (auto result : repl.first->getResults()) 970 mapping.erase(result); 971 while (replacements.size() != state.numReplacements) 972 replacements.pop_back(); 973 974 // Pop all of the newly created operations. 975 while (createdOps.size() != state.numCreatedOps) { 976 detachNestedAndErase(createdOps.back()); 977 createdOps.pop_back(); 978 } 979 980 // Pop all of the recorded ignored operations that are no longer valid. 981 while (ignoredOps.size() != state.numIgnoredOperations) 982 ignoredOps.pop_back(); 983 984 // Reset operations with changed results. 985 while (!operationsWithChangedResults.empty() && 986 operationsWithChangedResults.back() >= state.numReplacements) 987 operationsWithChangedResults.pop_back(); 988 } 989 990 void ConversionPatternRewriterImpl::eraseDanglingBlocks() { 991 for (auto &action : blockActions) 992 if (action.kind == BlockActionKind::Erase) 993 delete action.block; 994 } 995 996 void ConversionPatternRewriterImpl::undoBlockActions( 997 unsigned numActionsToKeep) { 998 for (auto &action : 999 llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) { 1000 switch (action.kind) { 1001 // Delete the created block. 1002 case BlockActionKind::Create: { 1003 // Unlink all of the operations within this block, they will be deleted 1004 // separately. 1005 auto &blockOps = action.block->getOperations(); 1006 while (!blockOps.empty()) 1007 blockOps.remove(blockOps.begin()); 1008 action.block->dropAllDefinedValueUses(); 1009 action.block->erase(); 1010 break; 1011 } 1012 // Put the block (owned by action) back into its original position. 1013 case BlockActionKind::Erase: { 1014 auto &blockList = action.originalPosition.region->getBlocks(); 1015 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1016 blockList.insert((insertAfterBlock 1017 ? std::next(Region::iterator(insertAfterBlock)) 1018 : blockList.begin()), 1019 action.block); 1020 break; 1021 } 1022 // Split the block at the position which was originally the end of the 1023 // destination block (owned by action), and put the instructions back into 1024 // the block used before the merge. 1025 case BlockActionKind::Merge: { 1026 Block *sourceBlock = action.mergeInfo.sourceBlock; 1027 Block::iterator splitPoint = 1028 (action.mergeInfo.destBlockLastInst 1029 ? ++Block::iterator(action.mergeInfo.destBlockLastInst) 1030 : action.block->begin()); 1031 sourceBlock->getOperations().splice(sourceBlock->begin(), 1032 action.block->getOperations(), 1033 splitPoint, action.block->end()); 1034 break; 1035 } 1036 // Move the block back to its original position. 1037 case BlockActionKind::Move: { 1038 Region *originalRegion = action.originalPosition.region; 1039 Block *insertAfterBlock = action.originalPosition.insertAfterBlock; 1040 originalRegion->getBlocks().splice( 1041 (insertAfterBlock ? std::next(Region::iterator(insertAfterBlock)) 1042 : originalRegion->end()), 1043 action.block->getParent()->getBlocks(), action.block); 1044 break; 1045 } 1046 // Merge back the block that was split out. 1047 case BlockActionKind::Split: { 1048 action.originalBlock->getOperations().splice( 1049 action.originalBlock->end(), action.block->getOperations()); 1050 action.block->dropAllDefinedValueUses(); 1051 action.block->erase(); 1052 break; 1053 } 1054 // Undo the type conversion. 1055 case BlockActionKind::TypeConversion: { 1056 argConverter.discardRewrites(action.block); 1057 break; 1058 } 1059 } 1060 } 1061 blockActions.resize(numActionsToKeep); 1062 } 1063 1064 LogicalResult ConversionPatternRewriterImpl::remapValues( 1065 Location loc, PatternRewriter &rewriter, TypeConverter *converter, 1066 Operation::operand_range operands, SmallVectorImpl<Value> &remapped) { 1067 remapped.reserve(llvm::size(operands)); 1068 1069 SmallVector<Type, 1> legalTypes; 1070 for (auto it : llvm::enumerate(operands)) { 1071 Value operand = it.value(); 1072 Type origType = operand.getType(); 1073 1074 // If a converter was provided, get the desired legal types for this 1075 // operand. 1076 Type desiredType; 1077 if (converter) { 1078 // If there is no legal conversion, fail to match this pattern. 1079 legalTypes.clear(); 1080 if (failed(converter->convertType(origType, legalTypes))) { 1081 return notifyMatchFailure(loc, [=](Diagnostic &diag) { 1082 diag << "unable to convert type for operand #" << it.index() 1083 << ", type was " << origType; 1084 }); 1085 } 1086 // TODO: There currently isn't any mechanism to do 1->N type conversion 1087 // via the PatternRewriter replacement API, so for now we just ignore it. 1088 if (legalTypes.size() == 1) 1089 desiredType = legalTypes.front(); 1090 } else { 1091 // TODO: What we should do here is just set `desiredType` to `origType` 1092 // and then handle the necessary type conversions after the conversion 1093 // process has finished. Unfortunately a lot of patterns currently rely on 1094 // receiving the new operands even if the types change, so we keep the 1095 // original behavior here for now until all of the patterns relying on 1096 // this get updated. 1097 } 1098 Value newOperand = mapping.lookupOrDefault(operand, desiredType); 1099 1100 // Handle the case where the conversion was 1->1 and the new operand type 1101 // isn't legal. 1102 Type newOperandType = newOperand.getType(); 1103 if (converter && desiredType && newOperandType != desiredType) { 1104 // Attempt to materialize a conversion for this new value. 1105 newOperand = converter->materializeTargetConversion( 1106 rewriter, loc, desiredType, newOperand); 1107 if (!newOperand) { 1108 return notifyMatchFailure(loc, [=](Diagnostic &diag) { 1109 diag << "unable to materialize a conversion for " 1110 "operand #" 1111 << it.index() << ", from " << newOperandType << " to " 1112 << desiredType; 1113 }); 1114 } 1115 } 1116 remapped.push_back(newOperand); 1117 } 1118 return success(); 1119 } 1120 1121 bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const { 1122 // Check to see if this operation was replaced or its parent ignored. 1123 return replacements.count(op) || ignoredOps.count(op->getParentOp()); 1124 } 1125 1126 void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) { 1127 // Walk this operation and collect nested operations that define non-empty 1128 // regions. We mark such operations as 'ignored' so that we know we don't have 1129 // to convert them, or their nested ops. 1130 if (op->getNumRegions() == 0) 1131 return; 1132 op->walk([&](Operation *op) { 1133 if (llvm::any_of(op->getRegions(), 1134 [](Region ®ion) { return !region.empty(); })) 1135 ignoredOps.insert(op); 1136 }); 1137 } 1138 1139 //===----------------------------------------------------------------------===// 1140 // Type Conversion 1141 1142 FailureOr<Block *> ConversionPatternRewriterImpl::convertBlockSignature( 1143 Block *block, TypeConverter &converter, 1144 TypeConverter::SignatureConversion *conversion) { 1145 FailureOr<Block *> result = 1146 conversion ? argConverter.applySignatureConversion( 1147 block, converter, *conversion, mapping, argReplacements) 1148 : argConverter.convertSignature(block, converter, mapping, 1149 argReplacements); 1150 if (Block *newBlock = result.getValue()) { 1151 if (newBlock != block) 1152 blockActions.push_back(BlockAction::getTypeConversion(newBlock)); 1153 } 1154 return result; 1155 } 1156 1157 Block *ConversionPatternRewriterImpl::applySignatureConversion( 1158 Region *region, TypeConverter::SignatureConversion &conversion, 1159 TypeConverter *converter) { 1160 if (!region->empty()) { 1161 return *convertBlockSignature(®ion->front(), 1162 converter ? *converter : defaultTypeConverter, 1163 &conversion); 1164 } 1165 return nullptr; 1166 } 1167 1168 FailureOr<Block *> ConversionPatternRewriterImpl::convertRegionTypes( 1169 Region *region, TypeConverter &converter, 1170 TypeConverter::SignatureConversion *entryConversion) { 1171 argConverter.setConverter(region, &converter); 1172 if (region->empty()) 1173 return nullptr; 1174 1175 if (failed(convertNonEntryRegionTypes(region, converter))) 1176 return failure(); 1177 1178 FailureOr<Block *> newEntry = 1179 convertBlockSignature(®ion->front(), converter, entryConversion); 1180 return newEntry; 1181 } 1182 1183 LogicalResult ConversionPatternRewriterImpl::convertNonEntryRegionTypes( 1184 Region *region, TypeConverter &converter, 1185 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1186 argConverter.setConverter(region, &converter); 1187 if (region->empty()) 1188 return success(); 1189 1190 // Convert the arguments of each block within the region. 1191 int blockIdx = 0; 1192 assert((blockConversions.empty() || 1193 blockConversions.size() == region->getBlocks().size() - 1) && 1194 "expected either to provide no SignatureConversions at all or to " 1195 "provide a SignatureConversion for each non-entry block"); 1196 1197 for (Block &block : 1198 llvm::make_early_inc_range(llvm::drop_begin(*region, 1))) { 1199 TypeConverter::SignatureConversion *blockConversion = 1200 blockConversions.empty() 1201 ? nullptr 1202 : const_cast<TypeConverter::SignatureConversion *>( 1203 &blockConversions[blockIdx++]); 1204 1205 if (failed(convertBlockSignature(&block, converter, blockConversion))) 1206 return failure(); 1207 } 1208 return success(); 1209 } 1210 1211 //===----------------------------------------------------------------------===// 1212 // Rewriter Notification Hooks 1213 1214 void ConversionPatternRewriterImpl::notifyOpReplaced(Operation *op, 1215 ValueRange newValues) { 1216 assert(newValues.size() == op->getNumResults()); 1217 assert(!replacements.count(op) && "operation was already replaced"); 1218 1219 // Track if any of the results changed, e.g. erased and replaced with null. 1220 bool resultChanged = false; 1221 1222 // Create mappings for each of the new result values. 1223 Value newValue, result; 1224 for (auto it : llvm::zip(newValues, op->getResults())) { 1225 std::tie(newValue, result) = it; 1226 if (!newValue) { 1227 resultChanged = true; 1228 continue; 1229 } 1230 // Remap, and check for any result type changes. 1231 mapping.map(result, newValue); 1232 resultChanged |= (newValue.getType() != result.getType()); 1233 } 1234 if (resultChanged) 1235 operationsWithChangedResults.push_back(replacements.size()); 1236 1237 // Record the requested operation replacement. 1238 TypeConverter *converter = nullptr; 1239 if (currentConversionPattern) 1240 converter = currentConversionPattern->getTypeConverter(); 1241 replacements.insert(std::make_pair(op, OpReplacement(converter))); 1242 1243 // Mark this operation as recursively ignored so that we don't need to 1244 // convert any nested operations. 1245 markNestedOpsIgnored(op); 1246 } 1247 1248 void ConversionPatternRewriterImpl::notifyBlockIsBeingErased(Block *block) { 1249 Region *region = block->getParent(); 1250 Block *origPrevBlock = block->getPrevNode(); 1251 blockActions.push_back(BlockAction::getErase(block, {region, origPrevBlock})); 1252 } 1253 1254 void ConversionPatternRewriterImpl::notifyCreatedBlock(Block *block) { 1255 blockActions.push_back(BlockAction::getCreate(block)); 1256 } 1257 1258 void ConversionPatternRewriterImpl::notifySplitBlock(Block *block, 1259 Block *continuation) { 1260 blockActions.push_back(BlockAction::getSplit(continuation, block)); 1261 } 1262 1263 void ConversionPatternRewriterImpl::notifyBlocksBeingMerged(Block *block, 1264 Block *srcBlock) { 1265 blockActions.push_back(BlockAction::getMerge(block, srcBlock)); 1266 } 1267 1268 void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore( 1269 Region ®ion, Region &parent, Region::iterator before) { 1270 if (region.empty()) 1271 return; 1272 Block *laterBlock = ®ion.back(); 1273 for (auto &earlierBlock : llvm::drop_begin(llvm::reverse(region), 1)) { 1274 blockActions.push_back( 1275 BlockAction::getMove(laterBlock, {®ion, &earlierBlock})); 1276 laterBlock = &earlierBlock; 1277 } 1278 blockActions.push_back(BlockAction::getMove(laterBlock, {®ion, nullptr})); 1279 } 1280 1281 void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore( 1282 iterator_range<Region::iterator> &blocks, Location origRegionLoc) { 1283 for (Block &block : blocks) 1284 blockActions.push_back(BlockAction::getCreate(&block)); 1285 1286 // Compute the conversion set for the inlined region. 1287 auto result = computeConversionSet(blocks, origRegionLoc, createdOps); 1288 1289 // This original region has already had its conversion set computed, so there 1290 // shouldn't be any new failures. 1291 (void)result; 1292 assert(succeeded(result) && "expected region to have no unreachable blocks"); 1293 } 1294 1295 LogicalResult ConversionPatternRewriterImpl::notifyMatchFailure( 1296 Location loc, function_ref<void(Diagnostic &)> reasonCallback) { 1297 LLVM_DEBUG({ 1298 Diagnostic diag(loc, DiagnosticSeverity::Remark); 1299 reasonCallback(diag); 1300 logger.startLine() << "** Failure : " << diag.str() << "\n"; 1301 }); 1302 return failure(); 1303 } 1304 1305 //===----------------------------------------------------------------------===// 1306 // ConversionPatternRewriter 1307 //===----------------------------------------------------------------------===// 1308 1309 ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx) 1310 : PatternRewriter(ctx), 1311 impl(new detail::ConversionPatternRewriterImpl(*this)) {} 1312 ConversionPatternRewriter::~ConversionPatternRewriter() {} 1313 1314 /// PatternRewriter hook for replacing the results of an operation when the 1315 /// given functor returns true. 1316 void ConversionPatternRewriter::replaceOpWithIf( 1317 Operation *op, ValueRange newValues, bool *allUsesReplaced, 1318 llvm::unique_function<bool(OpOperand &) const> functor) { 1319 // TODO: To support this we will need to rework a bit of how replacements are 1320 // tracked, given that this isn't guranteed to replace all of the uses of an 1321 // operation. The main change is that now an operation can be replaced 1322 // multiple times, in parts. The current "set" based tracking is mainly useful 1323 // for tracking if a replaced operation should be ignored, i.e. if all of the 1324 // uses will be replaced. 1325 llvm_unreachable( 1326 "replaceOpWithIf is currently not supported by DialectConversion"); 1327 } 1328 1329 /// PatternRewriter hook for replacing the results of an operation. 1330 void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues) { 1331 LLVM_DEBUG({ 1332 impl->logger.startLine() 1333 << "** Replace : '" << op->getName() << "'(" << op << ")\n"; 1334 }); 1335 impl->notifyOpReplaced(op, newValues); 1336 } 1337 1338 /// PatternRewriter hook for erasing a dead operation. The uses of this 1339 /// operation *must* be made dead by the end of the conversion process, 1340 /// otherwise an assert will be issued. 1341 void ConversionPatternRewriter::eraseOp(Operation *op) { 1342 LLVM_DEBUG({ 1343 impl->logger.startLine() 1344 << "** Erase : '" << op->getName() << "'(" << op << ")\n"; 1345 }); 1346 SmallVector<Value, 1> nullRepls(op->getNumResults(), nullptr); 1347 impl->notifyOpReplaced(op, nullRepls); 1348 } 1349 1350 void ConversionPatternRewriter::eraseBlock(Block *block) { 1351 impl->notifyBlockIsBeingErased(block); 1352 1353 // Mark all ops for erasure. 1354 for (Operation &op : *block) 1355 eraseOp(&op); 1356 1357 // Unlink the block from its parent region. The block is kept in the block 1358 // action and will be actually destroyed when rewrites are applied. This 1359 // allows us to keep the operations in the block live and undo the removal by 1360 // re-inserting the block. 1361 block->getParent()->getBlocks().remove(block); 1362 } 1363 1364 Block *ConversionPatternRewriter::applySignatureConversion( 1365 Region *region, TypeConverter::SignatureConversion &conversion, 1366 TypeConverter *converter) { 1367 return impl->applySignatureConversion(region, conversion, converter); 1368 } 1369 1370 FailureOr<Block *> ConversionPatternRewriter::convertRegionTypes( 1371 Region *region, TypeConverter &converter, 1372 TypeConverter::SignatureConversion *entryConversion) { 1373 return impl->convertRegionTypes(region, converter, entryConversion); 1374 } 1375 1376 LogicalResult ConversionPatternRewriter::convertNonEntryRegionTypes( 1377 Region *region, TypeConverter &converter, 1378 ArrayRef<TypeConverter::SignatureConversion> blockConversions) { 1379 return impl->convertNonEntryRegionTypes(region, converter, blockConversions); 1380 } 1381 1382 void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument from, 1383 Value to) { 1384 LLVM_DEBUG({ 1385 Operation *parentOp = from.getOwner()->getParentOp(); 1386 impl->logger.startLine() << "** Replace Argument : '" << from 1387 << "'(in region of '" << parentOp->getName() 1388 << "'(" << from.getOwner()->getParentOp() << ")\n"; 1389 }); 1390 impl->argReplacements.push_back(from); 1391 impl->mapping.map(impl->mapping.lookupOrDefault(from), to); 1392 } 1393 1394 /// Return the converted value that replaces 'key'. Return 'key' if there is 1395 /// no such a converted value. 1396 Value ConversionPatternRewriter::getRemappedValue(Value key) { 1397 return impl->mapping.lookupOrDefault(key); 1398 } 1399 1400 /// PatternRewriter hook for creating a new block with the given arguments. 1401 void ConversionPatternRewriter::notifyBlockCreated(Block *block) { 1402 impl->notifyCreatedBlock(block); 1403 } 1404 1405 /// PatternRewriter hook for splitting a block into two parts. 1406 Block *ConversionPatternRewriter::splitBlock(Block *block, 1407 Block::iterator before) { 1408 auto *continuation = PatternRewriter::splitBlock(block, before); 1409 impl->notifySplitBlock(block, continuation); 1410 return continuation; 1411 } 1412 1413 /// PatternRewriter hook for merging a block into another. 1414 void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest, 1415 ValueRange argValues) { 1416 impl->notifyBlocksBeingMerged(dest, source); 1417 assert(llvm::all_of(source->getPredecessors(), 1418 [dest](Block *succ) { return succ == dest; }) && 1419 "expected 'source' to have no predecessors or only 'dest'"); 1420 assert(argValues.size() == source->getNumArguments() && 1421 "incorrect # of argument replacement values"); 1422 for (auto it : llvm::zip(source->getArguments(), argValues)) 1423 replaceUsesOfBlockArgument(std::get<0>(it), std::get<1>(it)); 1424 dest->getOperations().splice(dest->end(), source->getOperations()); 1425 eraseBlock(source); 1426 } 1427 1428 /// PatternRewriter hook for moving blocks out of a region. 1429 void ConversionPatternRewriter::inlineRegionBefore(Region ®ion, 1430 Region &parent, 1431 Region::iterator before) { 1432 impl->notifyRegionIsBeingInlinedBefore(region, parent, before); 1433 PatternRewriter::inlineRegionBefore(region, parent, before); 1434 } 1435 1436 /// PatternRewriter hook for cloning blocks of one region into another. 1437 void ConversionPatternRewriter::cloneRegionBefore( 1438 Region ®ion, Region &parent, Region::iterator before, 1439 BlockAndValueMapping &mapping) { 1440 if (region.empty()) 1441 return; 1442 PatternRewriter::cloneRegionBefore(region, parent, before, mapping); 1443 1444 // Collect the range of the cloned blocks. 1445 auto clonedBeginIt = mapping.lookup(®ion.front())->getIterator(); 1446 auto clonedBlocks = llvm::make_range(clonedBeginIt, before); 1447 impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc()); 1448 } 1449 1450 /// PatternRewriter hook for creating a new operation. 1451 void ConversionPatternRewriter::notifyOperationInserted(Operation *op) { 1452 LLVM_DEBUG({ 1453 impl->logger.startLine() 1454 << "** Insert : '" << op->getName() << "'(" << op << ")\n"; 1455 }); 1456 impl->createdOps.push_back(op); 1457 } 1458 1459 /// PatternRewriter hook for updating the root operation in-place. 1460 void ConversionPatternRewriter::startRootUpdate(Operation *op) { 1461 #ifndef NDEBUG 1462 impl->pendingRootUpdates.insert(op); 1463 #endif 1464 impl->rootUpdates.emplace_back(op); 1465 } 1466 1467 /// PatternRewriter hook for updating the root operation in-place. 1468 void ConversionPatternRewriter::finalizeRootUpdate(Operation *op) { 1469 // There is nothing to do here, we only need to track the operation at the 1470 // start of the update. 1471 #ifndef NDEBUG 1472 assert(impl->pendingRootUpdates.erase(op) && 1473 "operation did not have a pending in-place update"); 1474 #endif 1475 } 1476 1477 /// PatternRewriter hook for updating the root operation in-place. 1478 void ConversionPatternRewriter::cancelRootUpdate(Operation *op) { 1479 #ifndef NDEBUG 1480 assert(impl->pendingRootUpdates.erase(op) && 1481 "operation did not have a pending in-place update"); 1482 #endif 1483 // Erase the last update for this operation. 1484 auto stateHasOp = [op](const auto &it) { return it.getOperation() == op; }; 1485 auto &rootUpdates = impl->rootUpdates; 1486 auto it = llvm::find_if(llvm::reverse(rootUpdates), stateHasOp); 1487 assert(it != rootUpdates.rend() && "no root update started on op"); 1488 int updateIdx = std::prev(rootUpdates.rend()) - it; 1489 rootUpdates.erase(rootUpdates.begin() + updateIdx); 1490 } 1491 1492 /// PatternRewriter hook for notifying match failure reasons. 1493 LogicalResult ConversionPatternRewriter::notifyMatchFailure( 1494 Operation *op, function_ref<void(Diagnostic &)> reasonCallback) { 1495 return impl->notifyMatchFailure(op->getLoc(), reasonCallback); 1496 } 1497 1498 /// Return a reference to the internal implementation. 1499 detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() { 1500 return *impl; 1501 } 1502 1503 //===----------------------------------------------------------------------===// 1504 // ConversionPattern 1505 //===----------------------------------------------------------------------===// 1506 1507 /// Attempt to match and rewrite the IR root at the specified operation. 1508 LogicalResult 1509 ConversionPattern::matchAndRewrite(Operation *op, 1510 PatternRewriter &rewriter) const { 1511 auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter); 1512 auto &rewriterImpl = dialectRewriter.getImpl(); 1513 1514 // Track the current conversion pattern in the rewriter. 1515 assert(!rewriterImpl.currentConversionPattern && 1516 "already inside of a pattern rewrite"); 1517 llvm::SaveAndRestore<const ConversionPattern *> currentPatternGuard( 1518 rewriterImpl.currentConversionPattern, this); 1519 1520 // Remap the operands of the operation. 1521 SmallVector<Value, 4> operands; 1522 if (failed(rewriterImpl.remapValues(op->getLoc(), rewriter, 1523 getTypeConverter(), op->getOperands(), 1524 operands))) { 1525 return failure(); 1526 } 1527 return matchAndRewrite(op, operands, dialectRewriter); 1528 } 1529 1530 //===----------------------------------------------------------------------===// 1531 // OperationLegalizer 1532 //===----------------------------------------------------------------------===// 1533 1534 namespace { 1535 /// A set of rewrite patterns that can be used to legalize a given operation. 1536 using LegalizationPatterns = SmallVector<const Pattern *, 1>; 1537 1538 /// This class defines a recursive operation legalizer. 1539 class OperationLegalizer { 1540 public: 1541 using LegalizationAction = ConversionTarget::LegalizationAction; 1542 1543 OperationLegalizer(ConversionTarget &targetInfo, 1544 const FrozenRewritePatternSet &patterns); 1545 1546 /// Returns true if the given operation is known to be illegal on the target. 1547 bool isIllegal(Operation *op) const; 1548 1549 /// Attempt to legalize the given operation. Returns success if the operation 1550 /// was legalized, failure otherwise. 1551 LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter); 1552 1553 /// Returns the conversion target in use by the legalizer. 1554 ConversionTarget &getTarget() { return target; } 1555 1556 private: 1557 /// Attempt to legalize the given operation by folding it. 1558 LogicalResult legalizeWithFold(Operation *op, 1559 ConversionPatternRewriter &rewriter); 1560 1561 /// Attempt to legalize the given operation by applying a pattern. Returns 1562 /// success if the operation was legalized, failure otherwise. 1563 LogicalResult legalizeWithPattern(Operation *op, 1564 ConversionPatternRewriter &rewriter); 1565 1566 /// Return true if the given pattern may be applied to the given operation, 1567 /// false otherwise. 1568 bool canApplyPattern(Operation *op, const Pattern &pattern, 1569 ConversionPatternRewriter &rewriter); 1570 1571 /// Legalize the resultant IR after successfully applying the given pattern. 1572 LogicalResult legalizePatternResult(Operation *op, const Pattern &pattern, 1573 ConversionPatternRewriter &rewriter, 1574 RewriterState &curState); 1575 1576 /// Legalizes the actions registered during the execution of a pattern. 1577 LogicalResult legalizePatternBlockActions(Operation *op, 1578 ConversionPatternRewriter &rewriter, 1579 ConversionPatternRewriterImpl &impl, 1580 RewriterState &state, 1581 RewriterState &newState); 1582 LogicalResult legalizePatternCreatedOperations( 1583 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1584 RewriterState &state, RewriterState &newState); 1585 LogicalResult legalizePatternRootUpdates(ConversionPatternRewriter &rewriter, 1586 ConversionPatternRewriterImpl &impl, 1587 RewriterState &state, 1588 RewriterState &newState); 1589 1590 //===--------------------------------------------------------------------===// 1591 // Cost Model 1592 //===--------------------------------------------------------------------===// 1593 1594 /// Build an optimistic legalization graph given the provided patterns. This 1595 /// function populates 'anyOpLegalizerPatterns' and 'legalizerPatterns' with 1596 /// patterns for operations that are not directly legal, but may be 1597 /// transitively legal for the current target given the provided patterns. 1598 void buildLegalizationGraph( 1599 LegalizationPatterns &anyOpLegalizerPatterns, 1600 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1601 1602 /// Compute the benefit of each node within the computed legalization graph. 1603 /// This orders the patterns within 'legalizerPatterns' based upon two 1604 /// criteria: 1605 /// 1) Prefer patterns that have the lowest legalization depth, i.e. 1606 /// represent the more direct mapping to the target. 1607 /// 2) When comparing patterns with the same legalization depth, prefer the 1608 /// pattern with the highest PatternBenefit. This allows for users to 1609 /// prefer specific legalizations over others. 1610 void computeLegalizationGraphBenefit( 1611 LegalizationPatterns &anyOpLegalizerPatterns, 1612 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1613 1614 /// Compute the legalization depth when legalizing an operation of the given 1615 /// type. 1616 unsigned computeOpLegalizationDepth( 1617 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 1618 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1619 1620 /// Apply the conversion cost model to the given set of patterns, and return 1621 /// the smallest legalization depth of any of the patterns. See 1622 /// `computeLegalizationGraphBenefit` for the breakdown of the cost model. 1623 unsigned applyCostModelToPatterns( 1624 LegalizationPatterns &patterns, 1625 DenseMap<OperationName, unsigned> &minOpPatternDepth, 1626 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns); 1627 1628 /// The current set of patterns that have been applied. 1629 SmallPtrSet<const Pattern *, 8> appliedPatterns; 1630 1631 /// The legalization information provided by the target. 1632 ConversionTarget ⌖ 1633 1634 /// The pattern applicator to use for conversions. 1635 PatternApplicator applicator; 1636 }; 1637 } // namespace 1638 1639 OperationLegalizer::OperationLegalizer(ConversionTarget &targetInfo, 1640 const FrozenRewritePatternSet &patterns) 1641 : target(targetInfo), applicator(patterns) { 1642 // The set of patterns that can be applied to illegal operations to transform 1643 // them into legal ones. 1644 DenseMap<OperationName, LegalizationPatterns> legalizerPatterns; 1645 LegalizationPatterns anyOpLegalizerPatterns; 1646 1647 buildLegalizationGraph(anyOpLegalizerPatterns, legalizerPatterns); 1648 computeLegalizationGraphBenefit(anyOpLegalizerPatterns, legalizerPatterns); 1649 } 1650 1651 bool OperationLegalizer::isIllegal(Operation *op) const { 1652 // Check if the target explicitly marked this operation as illegal. 1653 if (auto info = target.getOpAction(op->getName())) { 1654 if (*info == LegalizationAction::Dynamic) 1655 return !target.isLegal(op); 1656 return *info == LegalizationAction::Illegal; 1657 } 1658 1659 return false; 1660 } 1661 1662 LogicalResult 1663 OperationLegalizer::legalize(Operation *op, 1664 ConversionPatternRewriter &rewriter) { 1665 #ifndef NDEBUG 1666 const char *logLineComment = 1667 "//===-------------------------------------------===//\n"; 1668 1669 auto &rewriterImpl = rewriter.getImpl(); 1670 #endif 1671 LLVM_DEBUG({ 1672 auto &os = rewriterImpl.logger; 1673 os.getOStream() << "\n"; 1674 os.startLine() << logLineComment; 1675 os.startLine() << "Legalizing operation : '" << op->getName() << "'(" << op 1676 << ") {\n"; 1677 os.indent(); 1678 1679 // If the operation has no regions, just print it here. 1680 if (op->getNumRegions() == 0) { 1681 op->print(os.startLine(), OpPrintingFlags().printGenericOpForm()); 1682 os.getOStream() << "\n\n"; 1683 } 1684 }); 1685 1686 // Check if this operation is legal on the target. 1687 if (auto legalityInfo = target.isLegal(op)) { 1688 LLVM_DEBUG({ 1689 logSuccess( 1690 rewriterImpl.logger, "operation marked legal by the target{0}", 1691 legalityInfo->isRecursivelyLegal 1692 ? "; NOTE: operation is recursively legal; skipping internals" 1693 : ""); 1694 rewriterImpl.logger.startLine() << logLineComment; 1695 }); 1696 1697 // If this operation is recursively legal, mark its children as ignored so 1698 // that we don't consider them for legalization. 1699 if (legalityInfo->isRecursivelyLegal) 1700 rewriter.getImpl().markNestedOpsIgnored(op); 1701 return success(); 1702 } 1703 1704 // Check to see if the operation is ignored and doesn't need to be converted. 1705 if (rewriter.getImpl().isOpIgnored(op)) { 1706 LLVM_DEBUG({ 1707 logSuccess(rewriterImpl.logger, 1708 "operation marked 'ignored' during conversion"); 1709 rewriterImpl.logger.startLine() << logLineComment; 1710 }); 1711 return success(); 1712 } 1713 1714 // If the operation isn't legal, try to fold it in-place. 1715 // TODO: Should we always try to do this, even if the op is 1716 // already legal? 1717 if (succeeded(legalizeWithFold(op, rewriter))) { 1718 LLVM_DEBUG({ 1719 logSuccess(rewriterImpl.logger, "operation was folded"); 1720 rewriterImpl.logger.startLine() << logLineComment; 1721 }); 1722 return success(); 1723 } 1724 1725 // Otherwise, we need to apply a legalization pattern to this operation. 1726 if (succeeded(legalizeWithPattern(op, rewriter))) { 1727 LLVM_DEBUG({ 1728 logSuccess(rewriterImpl.logger, ""); 1729 rewriterImpl.logger.startLine() << logLineComment; 1730 }); 1731 return success(); 1732 } 1733 1734 LLVM_DEBUG({ 1735 logFailure(rewriterImpl.logger, "no matched legalization pattern"); 1736 rewriterImpl.logger.startLine() << logLineComment; 1737 }); 1738 return failure(); 1739 } 1740 1741 LogicalResult 1742 OperationLegalizer::legalizeWithFold(Operation *op, 1743 ConversionPatternRewriter &rewriter) { 1744 auto &rewriterImpl = rewriter.getImpl(); 1745 RewriterState curState = rewriterImpl.getCurrentState(); 1746 1747 LLVM_DEBUG({ 1748 rewriterImpl.logger.startLine() << "* Fold {\n"; 1749 rewriterImpl.logger.indent(); 1750 }); 1751 1752 // Try to fold the operation. 1753 SmallVector<Value, 2> replacementValues; 1754 rewriter.setInsertionPoint(op); 1755 if (failed(rewriter.tryFold(op, replacementValues))) { 1756 LLVM_DEBUG(logFailure(rewriterImpl.logger, "unable to fold")); 1757 return failure(); 1758 } 1759 1760 // Insert a replacement for 'op' with the folded replacement values. 1761 rewriter.replaceOp(op, replacementValues); 1762 1763 // Recursively legalize any new constant operations. 1764 for (unsigned i = curState.numCreatedOps, e = rewriterImpl.createdOps.size(); 1765 i != e; ++i) { 1766 Operation *cstOp = rewriterImpl.createdOps[i]; 1767 if (failed(legalize(cstOp, rewriter))) { 1768 LLVM_DEBUG(logFailure(rewriterImpl.logger, 1769 "generated constant '{0}' was illegal", 1770 cstOp->getName())); 1771 rewriterImpl.resetState(curState); 1772 return failure(); 1773 } 1774 } 1775 1776 LLVM_DEBUG(logSuccess(rewriterImpl.logger, "")); 1777 return success(); 1778 } 1779 1780 LogicalResult 1781 OperationLegalizer::legalizeWithPattern(Operation *op, 1782 ConversionPatternRewriter &rewriter) { 1783 auto &rewriterImpl = rewriter.getImpl(); 1784 1785 // Functor that returns if the given pattern may be applied. 1786 auto canApply = [&](const Pattern &pattern) { 1787 return canApplyPattern(op, pattern, rewriter); 1788 }; 1789 1790 // Functor that cleans up the rewriter state after a pattern failed to match. 1791 RewriterState curState = rewriterImpl.getCurrentState(); 1792 auto onFailure = [&](const Pattern &pattern) { 1793 LLVM_DEBUG(logFailure(rewriterImpl.logger, "pattern failed to match")); 1794 rewriterImpl.resetState(curState); 1795 appliedPatterns.erase(&pattern); 1796 }; 1797 1798 // Functor that performs additional legalization when a pattern is 1799 // successfully applied. 1800 auto onSuccess = [&](const Pattern &pattern) { 1801 auto result = legalizePatternResult(op, pattern, rewriter, curState); 1802 appliedPatterns.erase(&pattern); 1803 if (failed(result)) 1804 rewriterImpl.resetState(curState); 1805 return result; 1806 }; 1807 1808 // Try to match and rewrite a pattern on this operation. 1809 return applicator.matchAndRewrite(op, rewriter, canApply, onFailure, 1810 onSuccess); 1811 } 1812 1813 bool OperationLegalizer::canApplyPattern(Operation *op, const Pattern &pattern, 1814 ConversionPatternRewriter &rewriter) { 1815 LLVM_DEBUG({ 1816 auto &os = rewriter.getImpl().logger; 1817 os.getOStream() << "\n"; 1818 os.startLine() << "* Pattern : '" << op->getName() << " -> ("; 1819 llvm::interleaveComma(pattern.getGeneratedOps(), llvm::dbgs()); 1820 os.getOStream() << ")' {\n"; 1821 os.indent(); 1822 }); 1823 1824 // Ensure that we don't cycle by not allowing the same pattern to be 1825 // applied twice in the same recursion stack if it is not known to be safe. 1826 if (!pattern.hasBoundedRewriteRecursion() && 1827 !appliedPatterns.insert(&pattern).second) { 1828 LLVM_DEBUG( 1829 logFailure(rewriter.getImpl().logger, "pattern was already applied")); 1830 return false; 1831 } 1832 return true; 1833 } 1834 1835 LogicalResult 1836 OperationLegalizer::legalizePatternResult(Operation *op, const Pattern &pattern, 1837 ConversionPatternRewriter &rewriter, 1838 RewriterState &curState) { 1839 auto &impl = rewriter.getImpl(); 1840 1841 #ifndef NDEBUG 1842 assert(impl.pendingRootUpdates.empty() && "dangling root updates"); 1843 #endif 1844 1845 // Check that the root was either replaced or updated in place. 1846 auto replacedRoot = [&] { 1847 return llvm::any_of( 1848 llvm::drop_begin(impl.replacements, curState.numReplacements), 1849 [op](auto &it) { return it.first == op; }); 1850 }; 1851 auto updatedRootInPlace = [&] { 1852 return llvm::any_of( 1853 llvm::drop_begin(impl.rootUpdates, curState.numRootUpdates), 1854 [op](auto &state) { return state.getOperation() == op; }); 1855 }; 1856 (void)replacedRoot; 1857 (void)updatedRootInPlace; 1858 assert((replacedRoot() || updatedRootInPlace()) && 1859 "expected pattern to replace the root operation"); 1860 1861 // Legalize each of the actions registered during application. 1862 RewriterState newState = impl.getCurrentState(); 1863 if (failed(legalizePatternBlockActions(op, rewriter, impl, curState, 1864 newState)) || 1865 failed(legalizePatternRootUpdates(rewriter, impl, curState, newState)) || 1866 failed(legalizePatternCreatedOperations(rewriter, impl, curState, 1867 newState))) { 1868 return failure(); 1869 } 1870 1871 LLVM_DEBUG(logSuccess(impl.logger, "pattern applied successfully")); 1872 return success(); 1873 } 1874 1875 LogicalResult OperationLegalizer::legalizePatternBlockActions( 1876 Operation *op, ConversionPatternRewriter &rewriter, 1877 ConversionPatternRewriterImpl &impl, RewriterState &state, 1878 RewriterState &newState) { 1879 SmallPtrSet<Operation *, 16> operationsToIgnore; 1880 1881 // If the pattern moved or created any blocks, make sure the types of block 1882 // arguments get legalized. 1883 for (int i = state.numBlockActions, e = newState.numBlockActions; i != e; 1884 ++i) { 1885 auto &action = impl.blockActions[i]; 1886 if (action.kind == BlockActionKind::TypeConversion || 1887 action.kind == BlockActionKind::Erase) 1888 continue; 1889 // Only check blocks outside of the current operation. 1890 Operation *parentOp = action.block->getParentOp(); 1891 if (!parentOp || parentOp == op || action.block->getNumArguments() == 0) 1892 continue; 1893 1894 // If the region of the block has a type converter, try to convert the block 1895 // directly. 1896 if (auto *converter = 1897 impl.argConverter.getConverter(action.block->getParent())) { 1898 if (failed(impl.convertBlockSignature(action.block, *converter))) { 1899 LLVM_DEBUG(logFailure(impl.logger, "failed to convert types of moved " 1900 "block")); 1901 return failure(); 1902 } 1903 continue; 1904 } 1905 1906 // Otherwise, check that this operation isn't one generated by this pattern. 1907 // This is because we will attempt to legalize the parent operation, and 1908 // blocks in regions created by this pattern will already be legalized later 1909 // on. If we haven't built the set yet, build it now. 1910 if (operationsToIgnore.empty()) { 1911 auto createdOps = ArrayRef<Operation *>(impl.createdOps) 1912 .drop_front(state.numCreatedOps); 1913 operationsToIgnore.insert(createdOps.begin(), createdOps.end()); 1914 } 1915 1916 // If this operation should be considered for re-legalization, try it. 1917 if (operationsToIgnore.insert(parentOp).second && 1918 failed(legalize(parentOp, rewriter))) { 1919 LLVM_DEBUG(logFailure( 1920 impl.logger, "operation '{0}'({1}) became illegal after block action", 1921 parentOp->getName(), parentOp)); 1922 return failure(); 1923 } 1924 } 1925 return success(); 1926 } 1927 LogicalResult OperationLegalizer::legalizePatternCreatedOperations( 1928 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1929 RewriterState &state, RewriterState &newState) { 1930 for (int i = state.numCreatedOps, e = newState.numCreatedOps; i != e; ++i) { 1931 Operation *op = impl.createdOps[i]; 1932 if (failed(legalize(op, rewriter))) { 1933 LLVM_DEBUG(logFailure(impl.logger, 1934 "generated operation '{0}'({1}) was illegal", 1935 op->getName(), op)); 1936 return failure(); 1937 } 1938 } 1939 return success(); 1940 } 1941 LogicalResult OperationLegalizer::legalizePatternRootUpdates( 1942 ConversionPatternRewriter &rewriter, ConversionPatternRewriterImpl &impl, 1943 RewriterState &state, RewriterState &newState) { 1944 for (int i = state.numRootUpdates, e = newState.numRootUpdates; i != e; ++i) { 1945 Operation *op = impl.rootUpdates[i].getOperation(); 1946 if (failed(legalize(op, rewriter))) { 1947 LLVM_DEBUG(logFailure(impl.logger, 1948 "operation updated in-place '{0}' was illegal", 1949 op->getName())); 1950 return failure(); 1951 } 1952 } 1953 return success(); 1954 } 1955 1956 //===----------------------------------------------------------------------===// 1957 // Cost Model 1958 1959 void OperationLegalizer::buildLegalizationGraph( 1960 LegalizationPatterns &anyOpLegalizerPatterns, 1961 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 1962 // A mapping between an operation and a set of operations that can be used to 1963 // generate it. 1964 DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps; 1965 // A mapping between an operation and any currently invalid patterns it has. 1966 DenseMap<OperationName, SmallPtrSet<const Pattern *, 2>> invalidPatterns; 1967 // A worklist of patterns to consider for legality. 1968 SetVector<const Pattern *> patternWorklist; 1969 1970 // Build the mapping from operations to the parent ops that may generate them. 1971 applicator.walkAllPatterns([&](const Pattern &pattern) { 1972 Optional<OperationName> root = pattern.getRootKind(); 1973 1974 // If the pattern has no specific root, we can't analyze the relationship 1975 // between the root op and generated operations. Given that, add all such 1976 // patterns to the legalization set. 1977 if (!root) { 1978 anyOpLegalizerPatterns.push_back(&pattern); 1979 return; 1980 } 1981 1982 // Skip operations that are always known to be legal. 1983 if (target.getOpAction(*root) == LegalizationAction::Legal) 1984 return; 1985 1986 // Add this pattern to the invalid set for the root op and record this root 1987 // as a parent for any generated operations. 1988 invalidPatterns[*root].insert(&pattern); 1989 for (auto op : pattern.getGeneratedOps()) 1990 parentOps[op].insert(*root); 1991 1992 // Add this pattern to the worklist. 1993 patternWorklist.insert(&pattern); 1994 }); 1995 1996 // If there are any patterns that don't have a specific root kind, we can't 1997 // make direct assumptions about what operations will never be legalized. 1998 // Note: Technically we could, but it would require an analysis that may 1999 // recurse into itself. It would be better to perform this kind of filtering 2000 // at a higher level than here anyways. 2001 if (!anyOpLegalizerPatterns.empty()) { 2002 for (const Pattern *pattern : patternWorklist) 2003 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 2004 return; 2005 } 2006 2007 while (!patternWorklist.empty()) { 2008 auto *pattern = patternWorklist.pop_back_val(); 2009 2010 // Check to see if any of the generated operations are invalid. 2011 if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) { 2012 Optional<LegalizationAction> action = target.getOpAction(op); 2013 return !legalizerPatterns.count(op) && 2014 (!action || action == LegalizationAction::Illegal); 2015 })) 2016 continue; 2017 2018 // Otherwise, if all of the generated operation are valid, this op is now 2019 // legal so add all of the child patterns to the worklist. 2020 legalizerPatterns[*pattern->getRootKind()].push_back(pattern); 2021 invalidPatterns[*pattern->getRootKind()].erase(pattern); 2022 2023 // Add any invalid patterns of the parent operations to see if they have now 2024 // become legal. 2025 for (auto op : parentOps[*pattern->getRootKind()]) 2026 patternWorklist.set_union(invalidPatterns[op]); 2027 } 2028 } 2029 2030 void OperationLegalizer::computeLegalizationGraphBenefit( 2031 LegalizationPatterns &anyOpLegalizerPatterns, 2032 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2033 // The smallest pattern depth, when legalizing an operation. 2034 DenseMap<OperationName, unsigned> minOpPatternDepth; 2035 2036 // For each operation that is transitively legal, compute a cost for it. 2037 for (auto &opIt : legalizerPatterns) 2038 if (!minOpPatternDepth.count(opIt.first)) 2039 computeOpLegalizationDepth(opIt.first, minOpPatternDepth, 2040 legalizerPatterns); 2041 2042 // Apply the cost model to the patterns that can match any operation. Those 2043 // with a specific operation type are already resolved when computing the op 2044 // legalization depth. 2045 if (!anyOpLegalizerPatterns.empty()) 2046 applyCostModelToPatterns(anyOpLegalizerPatterns, minOpPatternDepth, 2047 legalizerPatterns); 2048 2049 // Apply a cost model to the pattern applicator. We order patterns first by 2050 // depth then benefit. `legalizerPatterns` contains per-op patterns by 2051 // decreasing benefit. 2052 applicator.applyCostModel([&](const Pattern &pattern) { 2053 ArrayRef<const Pattern *> orderedPatternList; 2054 if (Optional<OperationName> rootName = pattern.getRootKind()) 2055 orderedPatternList = legalizerPatterns[*rootName]; 2056 else 2057 orderedPatternList = anyOpLegalizerPatterns; 2058 2059 // If the pattern is not found, then it was removed and cannot be matched. 2060 auto *it = llvm::find(orderedPatternList, &pattern); 2061 if (it == orderedPatternList.end()) 2062 return PatternBenefit::impossibleToMatch(); 2063 2064 // Patterns found earlier in the list have higher benefit. 2065 return PatternBenefit(std::distance(it, orderedPatternList.end())); 2066 }); 2067 } 2068 2069 unsigned OperationLegalizer::computeOpLegalizationDepth( 2070 OperationName op, DenseMap<OperationName, unsigned> &minOpPatternDepth, 2071 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2072 // Check for existing depth. 2073 auto depthIt = minOpPatternDepth.find(op); 2074 if (depthIt != minOpPatternDepth.end()) 2075 return depthIt->second; 2076 2077 // If a mapping for this operation does not exist, then this operation 2078 // is always legal. Return 0 as the depth for a directly legal operation. 2079 auto opPatternsIt = legalizerPatterns.find(op); 2080 if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty()) 2081 return 0u; 2082 2083 // Record this initial depth in case we encounter this op again when 2084 // recursively computing the depth. 2085 minOpPatternDepth.try_emplace(op, std::numeric_limits<unsigned>::max()); 2086 2087 // Apply the cost model to the operation patterns, and update the minimum 2088 // depth. 2089 unsigned minDepth = applyCostModelToPatterns( 2090 opPatternsIt->second, minOpPatternDepth, legalizerPatterns); 2091 minOpPatternDepth[op] = minDepth; 2092 return minDepth; 2093 } 2094 2095 unsigned OperationLegalizer::applyCostModelToPatterns( 2096 LegalizationPatterns &patterns, 2097 DenseMap<OperationName, unsigned> &minOpPatternDepth, 2098 DenseMap<OperationName, LegalizationPatterns> &legalizerPatterns) { 2099 unsigned minDepth = std::numeric_limits<unsigned>::max(); 2100 2101 // Compute the depth for each pattern within the set. 2102 SmallVector<std::pair<const Pattern *, unsigned>, 4> patternsByDepth; 2103 patternsByDepth.reserve(patterns.size()); 2104 for (const Pattern *pattern : patterns) { 2105 unsigned depth = 0; 2106 for (auto generatedOp : pattern->getGeneratedOps()) { 2107 unsigned generatedOpDepth = computeOpLegalizationDepth( 2108 generatedOp, minOpPatternDepth, legalizerPatterns); 2109 depth = std::max(depth, generatedOpDepth + 1); 2110 } 2111 patternsByDepth.emplace_back(pattern, depth); 2112 2113 // Update the minimum depth of the pattern list. 2114 minDepth = std::min(minDepth, depth); 2115 } 2116 2117 // If the operation only has one legalization pattern, there is no need to 2118 // sort them. 2119 if (patternsByDepth.size() == 1) 2120 return minDepth; 2121 2122 // Sort the patterns by those likely to be the most beneficial. 2123 llvm::array_pod_sort(patternsByDepth.begin(), patternsByDepth.end(), 2124 [](const std::pair<const Pattern *, unsigned> *lhs, 2125 const std::pair<const Pattern *, unsigned> *rhs) { 2126 // First sort by the smaller pattern legalization 2127 // depth. 2128 if (lhs->second != rhs->second) 2129 return llvm::array_pod_sort_comparator<unsigned>( 2130 &lhs->second, &rhs->second); 2131 2132 // Then sort by the larger pattern benefit. 2133 auto lhsBenefit = lhs->first->getBenefit(); 2134 auto rhsBenefit = rhs->first->getBenefit(); 2135 return llvm::array_pod_sort_comparator<PatternBenefit>( 2136 &rhsBenefit, &lhsBenefit); 2137 }); 2138 2139 // Update the legalization pattern to use the new sorted list. 2140 patterns.clear(); 2141 for (auto &patternIt : patternsByDepth) 2142 patterns.push_back(patternIt.first); 2143 return minDepth; 2144 } 2145 2146 //===----------------------------------------------------------------------===// 2147 // OperationConverter 2148 //===----------------------------------------------------------------------===// 2149 namespace { 2150 enum OpConversionMode { 2151 // In this mode, the conversion will ignore failed conversions to allow 2152 // illegal operations to co-exist in the IR. 2153 Partial, 2154 2155 // In this mode, all operations must be legal for the given target for the 2156 // conversion to succeed. 2157 Full, 2158 2159 // In this mode, operations are analyzed for legality. No actual rewrites are 2160 // applied to the operations on success. 2161 Analysis, 2162 }; 2163 2164 // This class converts operations to a given conversion target via a set of 2165 // rewrite patterns. The conversion behaves differently depending on the 2166 // conversion mode. 2167 struct OperationConverter { 2168 explicit OperationConverter(ConversionTarget &target, 2169 const FrozenRewritePatternSet &patterns, 2170 OpConversionMode mode, 2171 DenseSet<Operation *> *trackedOps = nullptr) 2172 : opLegalizer(target, patterns), mode(mode), trackedOps(trackedOps) {} 2173 2174 /// Converts the given operations to the conversion target. 2175 LogicalResult convertOperations(ArrayRef<Operation *> ops); 2176 2177 private: 2178 /// Converts an operation with the given rewriter. 2179 LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op); 2180 2181 /// This method is called after the conversion process to legalize any 2182 /// remaining artifacts and complete the conversion. 2183 LogicalResult finalize(ConversionPatternRewriter &rewriter); 2184 2185 /// Legalize the types of converted block arguments. 2186 LogicalResult 2187 legalizeConvertedArgumentTypes(ConversionPatternRewriter &rewriter, 2188 ConversionPatternRewriterImpl &rewriterImpl); 2189 2190 /// Legalize an operation result that was marked as "erased". 2191 LogicalResult 2192 legalizeErasedResult(Operation *op, OpResult result, 2193 ConversionPatternRewriterImpl &rewriterImpl); 2194 2195 /// Legalize an operation result that was replaced with a value of a different 2196 /// type. 2197 LogicalResult 2198 legalizeChangedResultType(Operation *op, OpResult result, Value newValue, 2199 TypeConverter *replConverter, 2200 ConversionPatternRewriter &rewriter, 2201 ConversionPatternRewriterImpl &rewriterImpl, 2202 const BlockAndValueMapping &inverseMapping); 2203 2204 /// The legalizer to use when converting operations. 2205 OperationLegalizer opLegalizer; 2206 2207 /// The conversion mode to use when legalizing operations. 2208 OpConversionMode mode; 2209 2210 /// A set of pre-existing operations. When mode == OpConversionMode::Analysis, 2211 /// this is populated with ops found to be legalizable to the target. 2212 /// When mode == OpConversionMode::Partial, this is populated with ops found 2213 /// *not* to be legalizable to the target. 2214 DenseSet<Operation *> *trackedOps; 2215 }; 2216 } // end anonymous namespace 2217 2218 LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter, 2219 Operation *op) { 2220 // Legalize the given operation. 2221 if (failed(opLegalizer.legalize(op, rewriter))) { 2222 // Handle the case of a failed conversion for each of the different modes. 2223 // Full conversions expect all operations to be converted. 2224 if (mode == OpConversionMode::Full) 2225 return op->emitError() 2226 << "failed to legalize operation '" << op->getName() << "'"; 2227 // Partial conversions allow conversions to fail iff the operation was not 2228 // explicitly marked as illegal. If the user provided a nonlegalizableOps 2229 // set, non-legalizable ops are included. 2230 if (mode == OpConversionMode::Partial) { 2231 if (opLegalizer.isIllegal(op)) 2232 return op->emitError() 2233 << "failed to legalize operation '" << op->getName() 2234 << "' that was explicitly marked illegal"; 2235 if (trackedOps) 2236 trackedOps->insert(op); 2237 } 2238 } else if (mode == OpConversionMode::Analysis) { 2239 // Analysis conversions don't fail if any operations fail to legalize, 2240 // they are only interested in the operations that were successfully 2241 // legalized. 2242 trackedOps->insert(op); 2243 } 2244 return success(); 2245 } 2246 2247 LogicalResult OperationConverter::convertOperations(ArrayRef<Operation *> ops) { 2248 if (ops.empty()) 2249 return success(); 2250 ConversionTarget &target = opLegalizer.getTarget(); 2251 2252 // Compute the set of operations and blocks to convert. 2253 std::vector<Operation *> toConvert; 2254 for (auto *op : ops) { 2255 toConvert.emplace_back(op); 2256 for (auto ®ion : op->getRegions()) 2257 if (failed(computeConversionSet(region.getBlocks(), region.getLoc(), 2258 toConvert, &target))) 2259 return failure(); 2260 } 2261 2262 // Convert each operation and discard rewrites on failure. 2263 ConversionPatternRewriter rewriter(ops.front()->getContext()); 2264 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2265 for (auto *op : toConvert) 2266 if (failed(convert(rewriter, op))) 2267 return rewriterImpl.discardRewrites(), failure(); 2268 2269 // Now that all of the operations have been converted, finalize the conversion 2270 // process to ensure any lingering conversion artifacts are cleaned up and 2271 // legalized. 2272 if (failed(finalize(rewriter))) 2273 return rewriterImpl.discardRewrites(), failure(); 2274 // After a successful conversion, apply rewrites if this is not an analysis 2275 // conversion. 2276 if (mode == OpConversionMode::Analysis) 2277 rewriterImpl.discardRewrites(); 2278 else { 2279 rewriterImpl.applyRewrites(); 2280 2281 // It is possible for a later pattern to erase an op that was originally 2282 // identified as illegal and added to the trackedOps, remove it now after 2283 // replacements have been computed. 2284 if (trackedOps) 2285 for (auto &repl : rewriterImpl.replacements) 2286 trackedOps->erase(repl.first); 2287 } 2288 return success(); 2289 } 2290 2291 LogicalResult 2292 OperationConverter::finalize(ConversionPatternRewriter &rewriter) { 2293 ConversionPatternRewriterImpl &rewriterImpl = rewriter.getImpl(); 2294 2295 // Legalize converted block arguments. 2296 if (failed(legalizeConvertedArgumentTypes(rewriter, rewriterImpl))) 2297 return failure(); 2298 2299 if (rewriterImpl.operationsWithChangedResults.empty()) 2300 return success(); 2301 2302 Optional<BlockAndValueMapping> inverseMapping; 2303 2304 // Process requested operation replacements. 2305 for (unsigned i = 0, e = rewriterImpl.operationsWithChangedResults.size(); 2306 i != e; ++i) { 2307 unsigned replIdx = rewriterImpl.operationsWithChangedResults[i]; 2308 auto &repl = *(rewriterImpl.replacements.begin() + replIdx); 2309 for (OpResult result : repl.first->getResults()) { 2310 Value newValue = rewriterImpl.mapping.lookupOrNull(result); 2311 2312 // If the operation result was replaced with null, all of the uses of this 2313 // value should be replaced. 2314 if (!newValue) { 2315 if (failed(legalizeErasedResult(repl.first, result, rewriterImpl))) 2316 return failure(); 2317 continue; 2318 } 2319 2320 // Otherwise, check to see if the type of the result changed. 2321 if (result.getType() == newValue.getType()) 2322 continue; 2323 2324 // Compute the inverse mapping only if it is really needed. 2325 if (!inverseMapping) 2326 inverseMapping = rewriterImpl.mapping.getInverse(); 2327 2328 // Legalize this result. 2329 rewriter.setInsertionPoint(repl.first); 2330 if (failed(legalizeChangedResultType(repl.first, result, newValue, 2331 repl.second.converter, rewriter, 2332 rewriterImpl, *inverseMapping))) 2333 return failure(); 2334 2335 // Update the end iterator for this loop in the case it was updated 2336 // when legalizing generated conversion operations. 2337 e = rewriterImpl.operationsWithChangedResults.size(); 2338 } 2339 } 2340 return success(); 2341 } 2342 2343 LogicalResult OperationConverter::legalizeConvertedArgumentTypes( 2344 ConversionPatternRewriter &rewriter, 2345 ConversionPatternRewriterImpl &rewriterImpl) { 2346 // Functor used to check if all users of a value will be dead after 2347 // conversion. 2348 auto findLiveUser = [&](Value val) { 2349 auto liveUserIt = llvm::find_if_not(val.getUsers(), [&](Operation *user) { 2350 return rewriterImpl.isOpIgnored(user); 2351 }); 2352 return liveUserIt == val.user_end() ? nullptr : *liveUserIt; 2353 }; 2354 2355 // Materialize any necessary conversions for converted block arguments that 2356 // are still live. 2357 size_t numCreatedOps = rewriterImpl.createdOps.size(); 2358 if (failed(rewriterImpl.argConverter.materializeLiveConversions( 2359 rewriterImpl.mapping, rewriter, findLiveUser))) 2360 return failure(); 2361 2362 // Legalize any newly created operations during argument materialization. 2363 for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) { 2364 if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) { 2365 return rewriterImpl.createdOps[i]->emitError() 2366 << "failed to legalize conversion operation generated for block " 2367 "argument that remained live after conversion"; 2368 } 2369 } 2370 return success(); 2371 } 2372 2373 LogicalResult OperationConverter::legalizeErasedResult( 2374 Operation *op, OpResult result, 2375 ConversionPatternRewriterImpl &rewriterImpl) { 2376 // If the operation result was replaced with null, all of the uses of this 2377 // value should be replaced. 2378 auto liveUserIt = llvm::find_if_not(result.getUsers(), [&](Operation *user) { 2379 return rewriterImpl.isOpIgnored(user); 2380 }); 2381 if (liveUserIt != result.user_end()) { 2382 InFlightDiagnostic diag = op->emitError("failed to legalize operation '") 2383 << op->getName() << "' marked as erased"; 2384 diag.attachNote(liveUserIt->getLoc()) 2385 << "found live user of result #" << result.getResultNumber() << ": " 2386 << *liveUserIt; 2387 return failure(); 2388 } 2389 return success(); 2390 } 2391 2392 /// Finds a user of the given value, or of any other value that the given value 2393 /// replaced, that was not replaced in the conversion process. 2394 static Operation * 2395 findLiveUserOfReplaced(Value value, ConversionPatternRewriterImpl &rewriterImpl, 2396 const BlockAndValueMapping &inverseMapping) { 2397 do { 2398 // Walk the users of this value to see if there are any live users that 2399 // weren't replaced during conversion. 2400 auto liveUserIt = llvm::find_if_not(value.getUsers(), [&](Operation *user) { 2401 return rewriterImpl.isOpIgnored(user); 2402 }); 2403 if (liveUserIt != value.user_end()) 2404 return *liveUserIt; 2405 value = inverseMapping.lookupOrNull(value); 2406 } while (value != nullptr); 2407 return nullptr; 2408 } 2409 2410 LogicalResult OperationConverter::legalizeChangedResultType( 2411 Operation *op, OpResult result, Value newValue, 2412 TypeConverter *replConverter, ConversionPatternRewriter &rewriter, 2413 ConversionPatternRewriterImpl &rewriterImpl, 2414 const BlockAndValueMapping &inverseMapping) { 2415 Operation *liveUser = 2416 findLiveUserOfReplaced(result, rewriterImpl, inverseMapping); 2417 if (!liveUser) 2418 return success(); 2419 2420 // If the replacement has a type converter, attempt to materialize a 2421 // conversion back to the original type. 2422 if (!replConverter) { 2423 // TODO: We should emit an error here, similarly to the case where the 2424 // result is replaced with null. Unfortunately a lot of existing 2425 // patterns rely on this behavior, so until those patterns are updated 2426 // we keep the legacy behavior here of just forwarding the new value. 2427 return success(); 2428 } 2429 2430 // Track the number of created operations so that new ones can be legalized. 2431 size_t numCreatedOps = rewriterImpl.createdOps.size(); 2432 2433 // Materialize a conversion for this live result value. 2434 Type resultType = result.getType(); 2435 Value convertedValue = replConverter->materializeSourceConversion( 2436 rewriter, op->getLoc(), resultType, newValue); 2437 if (!convertedValue) { 2438 InFlightDiagnostic diag = op->emitError() 2439 << "failed to materialize conversion for result #" 2440 << result.getResultNumber() << " of operation '" 2441 << op->getName() 2442 << "' that remained live after conversion"; 2443 diag.attachNote(liveUser->getLoc()) 2444 << "see existing live user here: " << *liveUser; 2445 return failure(); 2446 } 2447 2448 // Legalize all of the newly created conversion operations. 2449 for (int i : llvm::seq<int>(numCreatedOps, rewriterImpl.createdOps.size())) { 2450 if (failed(opLegalizer.legalize(rewriterImpl.createdOps[i], rewriter))) { 2451 return op->emitError("failed to legalize conversion operation generated ") 2452 << "for result #" << result.getResultNumber() << " of operation '" 2453 << op->getName() << "' that remained live after conversion"; 2454 } 2455 } 2456 2457 rewriterImpl.mapping.map(result, convertedValue); 2458 return success(); 2459 } 2460 2461 //===----------------------------------------------------------------------===// 2462 // Type Conversion 2463 //===----------------------------------------------------------------------===// 2464 2465 /// Remap an input of the original signature with a new set of types. The 2466 /// new types are appended to the new signature conversion. 2467 void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo, 2468 ArrayRef<Type> types) { 2469 assert(!types.empty() && "expected valid types"); 2470 remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size()); 2471 addInputs(types); 2472 } 2473 2474 /// Append new input types to the signature conversion, this should only be 2475 /// used if the new types are not intended to remap an existing input. 2476 void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) { 2477 assert(!types.empty() && 2478 "1->0 type remappings don't need to be added explicitly"); 2479 argTypes.append(types.begin(), types.end()); 2480 } 2481 2482 /// Remap an input of the original signature with a range of types in the 2483 /// new signature. 2484 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2485 unsigned newInputNo, 2486 unsigned newInputCount) { 2487 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2488 assert(newInputCount != 0 && "expected valid input count"); 2489 remappedInputs[origInputNo] = 2490 InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr}; 2491 } 2492 2493 /// Remap an input of the original signature to another `replacementValue` 2494 /// value. This would make the signature converter drop this argument. 2495 void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo, 2496 Value replacementValue) { 2497 assert(!remappedInputs[origInputNo] && "input has already been remapped"); 2498 remappedInputs[origInputNo] = 2499 InputMapping{origInputNo, /*size=*/0, replacementValue}; 2500 } 2501 2502 /// This hooks allows for converting a type. 2503 LogicalResult TypeConverter::convertType(Type t, 2504 SmallVectorImpl<Type> &results) { 2505 auto existingIt = cachedDirectConversions.find(t); 2506 if (existingIt != cachedDirectConversions.end()) { 2507 if (existingIt->second) 2508 results.push_back(existingIt->second); 2509 return success(existingIt->second != nullptr); 2510 } 2511 auto multiIt = cachedMultiConversions.find(t); 2512 if (multiIt != cachedMultiConversions.end()) { 2513 results.append(multiIt->second.begin(), multiIt->second.end()); 2514 return success(); 2515 } 2516 2517 // Walk the added converters in reverse order to apply the most recently 2518 // registered first. 2519 size_t currentCount = results.size(); 2520 for (ConversionCallbackFn &converter : llvm::reverse(conversions)) { 2521 if (Optional<LogicalResult> result = converter(t, results)) { 2522 if (!succeeded(*result)) { 2523 cachedDirectConversions.try_emplace(t, nullptr); 2524 return failure(); 2525 } 2526 auto newTypes = ArrayRef<Type>(results).drop_front(currentCount); 2527 if (newTypes.size() == 1) 2528 cachedDirectConversions.try_emplace(t, newTypes.front()); 2529 else 2530 cachedMultiConversions.try_emplace(t, llvm::to_vector<2>(newTypes)); 2531 return success(); 2532 } 2533 } 2534 return failure(); 2535 } 2536 2537 /// This hook simplifies defining 1-1 type conversions. This function returns 2538 /// the type to convert to on success, and a null type on failure. 2539 Type TypeConverter::convertType(Type t) { 2540 // Use the multi-type result version to convert the type. 2541 SmallVector<Type, 1> results; 2542 if (failed(convertType(t, results))) 2543 return nullptr; 2544 2545 // Check to ensure that only one type was produced. 2546 return results.size() == 1 ? results.front() : nullptr; 2547 } 2548 2549 /// Convert the given set of types, filling 'results' as necessary. This 2550 /// returns failure if the conversion of any of the types fails, success 2551 /// otherwise. 2552 LogicalResult TypeConverter::convertTypes(TypeRange types, 2553 SmallVectorImpl<Type> &results) { 2554 for (Type type : types) 2555 if (failed(convertType(type, results))) 2556 return failure(); 2557 return success(); 2558 } 2559 2560 /// Return true if the given type is legal for this type converter, i.e. the 2561 /// type converts to itself. 2562 bool TypeConverter::isLegal(Type type) { return convertType(type) == type; } 2563 /// Return true if the given operation has legal operand and result types. 2564 bool TypeConverter::isLegal(Operation *op) { 2565 return isLegal(op->getOperandTypes()) && isLegal(op->getResultTypes()); 2566 } 2567 2568 /// Return true if the types of block arguments within the region are legal. 2569 bool TypeConverter::isLegal(Region *region) { 2570 return llvm::all_of(*region, [this](Block &block) { 2571 return isLegal(block.getArgumentTypes()); 2572 }); 2573 } 2574 2575 /// Return true if the inputs and outputs of the given function type are 2576 /// legal. 2577 bool TypeConverter::isSignatureLegal(FunctionType ty) { 2578 return isLegal(llvm::concat<const Type>(ty.getInputs(), ty.getResults())); 2579 } 2580 2581 /// This hook allows for converting a specific argument of a signature. 2582 LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type, 2583 SignatureConversion &result) { 2584 // Try to convert the given input type. 2585 SmallVector<Type, 1> convertedTypes; 2586 if (failed(convertType(type, convertedTypes))) 2587 return failure(); 2588 2589 // If this argument is being dropped, there is nothing left to do. 2590 if (convertedTypes.empty()) 2591 return success(); 2592 2593 // Otherwise, add the new inputs. 2594 result.addInputs(inputNo, convertedTypes); 2595 return success(); 2596 } 2597 LogicalResult TypeConverter::convertSignatureArgs(TypeRange types, 2598 SignatureConversion &result, 2599 unsigned origInputOffset) { 2600 for (unsigned i = 0, e = types.size(); i != e; ++i) 2601 if (failed(convertSignatureArg(origInputOffset + i, types[i], result))) 2602 return failure(); 2603 return success(); 2604 } 2605 2606 Value TypeConverter::materializeConversion( 2607 MutableArrayRef<MaterializationCallbackFn> materializations, 2608 OpBuilder &builder, Location loc, Type resultType, ValueRange inputs) { 2609 for (MaterializationCallbackFn &fn : llvm::reverse(materializations)) 2610 if (Optional<Value> result = fn(builder, resultType, inputs, loc)) 2611 return result.getValue(); 2612 return nullptr; 2613 } 2614 2615 /// This function converts the type signature of the given block, by invoking 2616 /// 'convertSignatureArg' for each argument. This function should return a valid 2617 /// conversion for the signature on success, None otherwise. 2618 auto TypeConverter::convertBlockSignature(Block *block) 2619 -> Optional<SignatureConversion> { 2620 SignatureConversion conversion(block->getNumArguments()); 2621 if (failed(convertSignatureArgs(block->getArgumentTypes(), conversion))) 2622 return llvm::None; 2623 return conversion; 2624 } 2625 2626 /// Create a default conversion pattern that rewrites the type signature of a 2627 /// FunctionLike op. This only supports FunctionLike ops which use FunctionType 2628 /// to represent their type. 2629 namespace { 2630 struct FunctionLikeSignatureConversion : public ConversionPattern { 2631 FunctionLikeSignatureConversion(StringRef functionLikeOpName, 2632 MLIRContext *ctx, TypeConverter &converter) 2633 : ConversionPattern(converter, functionLikeOpName, /*benefit=*/1, ctx) {} 2634 2635 /// Hook to implement combined matching and rewriting for FunctionLike ops. 2636 LogicalResult 2637 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 2638 ConversionPatternRewriter &rewriter) const override { 2639 FunctionType type = function_like_impl::getFunctionType(op); 2640 2641 // Convert the original function types. 2642 TypeConverter::SignatureConversion result(type.getNumInputs()); 2643 SmallVector<Type, 1> newResults; 2644 if (failed(typeConverter->convertSignatureArgs(type.getInputs(), result)) || 2645 failed(typeConverter->convertTypes(type.getResults(), newResults)) || 2646 failed(rewriter.convertRegionTypes( 2647 &function_like_impl::getFunctionBody(op), *typeConverter, &result))) 2648 return failure(); 2649 2650 // Update the function signature in-place. 2651 auto newType = FunctionType::get(rewriter.getContext(), 2652 result.getConvertedTypes(), newResults); 2653 2654 rewriter.updateRootInPlace( 2655 op, [&] { function_like_impl::setFunctionType(op, newType); }); 2656 2657 return success(); 2658 } 2659 }; 2660 } // end anonymous namespace 2661 2662 void mlir::populateFunctionLikeTypeConversionPattern( 2663 StringRef functionLikeOpName, RewritePatternSet &patterns, 2664 TypeConverter &converter) { 2665 patterns.add<FunctionLikeSignatureConversion>( 2666 functionLikeOpName, patterns.getContext(), converter); 2667 } 2668 2669 void mlir::populateFuncOpTypeConversionPattern(RewritePatternSet &patterns, 2670 TypeConverter &converter) { 2671 populateFunctionLikeTypeConversionPattern<FuncOp>(patterns, converter); 2672 } 2673 2674 //===----------------------------------------------------------------------===// 2675 // ConversionTarget 2676 //===----------------------------------------------------------------------===// 2677 2678 /// Register a legality action for the given operation. 2679 void ConversionTarget::setOpAction(OperationName op, 2680 LegalizationAction action) { 2681 legalOperations[op] = {action, /*isRecursivelyLegal=*/false, nullptr}; 2682 } 2683 2684 /// Register a legality action for the given dialects. 2685 void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames, 2686 LegalizationAction action) { 2687 for (StringRef dialect : dialectNames) 2688 legalDialects[dialect] = action; 2689 } 2690 2691 /// Get the legality action for the given operation. 2692 auto ConversionTarget::getOpAction(OperationName op) const 2693 -> Optional<LegalizationAction> { 2694 Optional<LegalizationInfo> info = getOpInfo(op); 2695 return info ? info->action : Optional<LegalizationAction>(); 2696 } 2697 2698 /// If the given operation instance is legal on this target, a structure 2699 /// containing legality information is returned. If the operation is not legal, 2700 /// None is returned. 2701 auto ConversionTarget::isLegal(Operation *op) const 2702 -> Optional<LegalOpDetails> { 2703 Optional<LegalizationInfo> info = getOpInfo(op->getName()); 2704 if (!info) 2705 return llvm::None; 2706 2707 // Returns true if this operation instance is known to be legal. 2708 auto isOpLegal = [&] { 2709 // Handle dynamic legality either with the provided legality function. 2710 if (info->action == LegalizationAction::Dynamic) 2711 return info->legalityFn(op); 2712 2713 // Otherwise, the operation is only legal if it was marked 'Legal'. 2714 return info->action == LegalizationAction::Legal; 2715 }; 2716 if (!isOpLegal()) 2717 return llvm::None; 2718 2719 // This operation is legal, compute any additional legality information. 2720 LegalOpDetails legalityDetails; 2721 if (info->isRecursivelyLegal) { 2722 auto legalityFnIt = opRecursiveLegalityFns.find(op->getName()); 2723 if (legalityFnIt != opRecursiveLegalityFns.end()) 2724 legalityDetails.isRecursivelyLegal = legalityFnIt->second(op); 2725 else 2726 legalityDetails.isRecursivelyLegal = true; 2727 } 2728 return legalityDetails; 2729 } 2730 2731 /// Set the dynamic legality callback for the given operation. 2732 void ConversionTarget::setLegalityCallback( 2733 OperationName name, const DynamicLegalityCallbackFn &callback) { 2734 assert(callback && "expected valid legality callback"); 2735 auto infoIt = legalOperations.find(name); 2736 assert(infoIt != legalOperations.end() && 2737 infoIt->second.action == LegalizationAction::Dynamic && 2738 "expected operation to already be marked as dynamically legal"); 2739 infoIt->second.legalityFn = callback; 2740 } 2741 2742 /// Set the recursive legality callback for the given operation and mark the 2743 /// operation as recursively legal. 2744 void ConversionTarget::markOpRecursivelyLegal( 2745 OperationName name, const DynamicLegalityCallbackFn &callback) { 2746 auto infoIt = legalOperations.find(name); 2747 assert(infoIt != legalOperations.end() && 2748 infoIt->second.action != LegalizationAction::Illegal && 2749 "expected operation to already be marked as legal"); 2750 infoIt->second.isRecursivelyLegal = true; 2751 if (callback) 2752 opRecursiveLegalityFns[name] = callback; 2753 else 2754 opRecursiveLegalityFns.erase(name); 2755 } 2756 2757 /// Set the dynamic legality callback for the given dialects. 2758 void ConversionTarget::setLegalityCallback( 2759 ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) { 2760 assert(callback && "expected valid legality callback"); 2761 for (StringRef dialect : dialects) 2762 dialectLegalityFns[dialect] = callback; 2763 } 2764 2765 /// Set the dynamic legality callback for the unknown ops. 2766 void ConversionTarget::setLegalityCallback( 2767 const DynamicLegalityCallbackFn &callback) { 2768 assert(callback && "expected valid legality callback"); 2769 unknownLegalityFn = callback; 2770 } 2771 2772 /// Get the legalization information for the given operation. 2773 auto ConversionTarget::getOpInfo(OperationName op) const 2774 -> Optional<LegalizationInfo> { 2775 // Check for info for this specific operation. 2776 auto it = legalOperations.find(op); 2777 if (it != legalOperations.end()) 2778 return it->second; 2779 // Check for info for the parent dialect. 2780 auto dialectIt = legalDialects.find(op.getDialectNamespace()); 2781 if (dialectIt != legalDialects.end()) { 2782 DynamicLegalityCallbackFn callback; 2783 auto dialectFn = dialectLegalityFns.find(op.getDialectNamespace()); 2784 if (dialectFn != dialectLegalityFns.end()) 2785 callback = dialectFn->second; 2786 return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false, 2787 callback}; 2788 } 2789 // Otherwise, check if we mark unknown operations as dynamic. 2790 if (unknownLegalityFn) 2791 return LegalizationInfo{LegalizationAction::Dynamic, 2792 /*isRecursivelyLegal=*/false, unknownLegalityFn}; 2793 return llvm::None; 2794 } 2795 2796 //===----------------------------------------------------------------------===// 2797 // Op Conversion Entry Points 2798 //===----------------------------------------------------------------------===// 2799 2800 /// Apply a partial conversion on the given operations and all nested 2801 /// operations. This method converts as many operations to the target as 2802 /// possible, ignoring operations that failed to legalize. This method only 2803 /// returns failure if there ops explicitly marked as illegal. 2804 /// If an `unconvertedOps` set is provided, all operations that are found not 2805 /// to be legalizable to the given `target` are placed within that set. (Note 2806 /// that if there is an op explicitly marked as illegal, the conversion 2807 /// terminates and the `unconvertedOps` set will not necessarily be complete.) 2808 LogicalResult 2809 mlir::applyPartialConversion(ArrayRef<Operation *> ops, 2810 ConversionTarget &target, 2811 const FrozenRewritePatternSet &patterns, 2812 DenseSet<Operation *> *unconvertedOps) { 2813 OperationConverter opConverter(target, patterns, OpConversionMode::Partial, 2814 unconvertedOps); 2815 return opConverter.convertOperations(ops); 2816 } 2817 LogicalResult 2818 mlir::applyPartialConversion(Operation *op, ConversionTarget &target, 2819 const FrozenRewritePatternSet &patterns, 2820 DenseSet<Operation *> *unconvertedOps) { 2821 return applyPartialConversion(llvm::makeArrayRef(op), target, patterns, 2822 unconvertedOps); 2823 } 2824 2825 /// Apply a complete conversion on the given operations, and all nested 2826 /// operations. This method will return failure if the conversion of any 2827 /// operation fails. 2828 LogicalResult 2829 mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target, 2830 const FrozenRewritePatternSet &patterns) { 2831 OperationConverter opConverter(target, patterns, OpConversionMode::Full); 2832 return opConverter.convertOperations(ops); 2833 } 2834 LogicalResult 2835 mlir::applyFullConversion(Operation *op, ConversionTarget &target, 2836 const FrozenRewritePatternSet &patterns) { 2837 return applyFullConversion(llvm::makeArrayRef(op), target, patterns); 2838 } 2839 2840 /// Apply an analysis conversion on the given operations, and all nested 2841 /// operations. This method analyzes which operations would be successfully 2842 /// converted to the target if a conversion was applied. All operations that 2843 /// were found to be legalizable to the given 'target' are placed within the 2844 /// provided 'convertedOps' set; note that no actual rewrites are applied to the 2845 /// operations on success and only pre-existing operations are added to the set. 2846 LogicalResult 2847 mlir::applyAnalysisConversion(ArrayRef<Operation *> ops, 2848 ConversionTarget &target, 2849 const FrozenRewritePatternSet &patterns, 2850 DenseSet<Operation *> &convertedOps) { 2851 OperationConverter opConverter(target, patterns, OpConversionMode::Analysis, 2852 &convertedOps); 2853 return opConverter.convertOperations(ops); 2854 } 2855 LogicalResult 2856 mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target, 2857 const FrozenRewritePatternSet &patterns, 2858 DenseSet<Operation *> &convertedOps) { 2859 return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns, 2860 convertedOps); 2861 } 2862