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