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