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