1 //===- TestPatterns.cpp - Test dialect pattern driver ---------------------===// 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 "TestDialect.h" 10 #include "TestTypes.h" 11 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 12 #include "mlir/Dialect/Func/IR/FuncOps.h" 13 #include "mlir/Dialect/Func/Transforms/FuncConversions.h" 14 #include "mlir/Dialect/Tensor/IR/Tensor.h" 15 #include "mlir/IR/Matchers.h" 16 #include "mlir/Pass/Pass.h" 17 #include "mlir/Transforms/DialectConversion.h" 18 #include "mlir/Transforms/FoldUtils.h" 19 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 20 21 using namespace mlir; 22 using namespace test; 23 24 // Native function for testing NativeCodeCall 25 static Value chooseOperand(Value input1, Value input2, BoolAttr choice) { 26 return choice.getValue() ? input1 : input2; 27 } 28 29 static void createOpI(PatternRewriter &rewriter, Location loc, Value input) { 30 rewriter.create<OpI>(loc, input); 31 } 32 33 static void handleNoResultOp(PatternRewriter &rewriter, 34 OpSymbolBindingNoResult op) { 35 // Turn the no result op to a one-result op. 36 rewriter.create<OpSymbolBindingB>(op.getLoc(), op.getOperand().getType(), 37 op.getOperand()); 38 } 39 40 static bool getFirstI32Result(Operation *op, Value &value) { 41 if (!Type(op->getResult(0).getType()).isSignlessInteger(32)) 42 return false; 43 value = op->getResult(0); 44 return true; 45 } 46 47 static Value bindNativeCodeCallResult(Value value) { return value; } 48 49 static SmallVector<Value, 2> bindMultipleNativeCodeCallResult(Value input1, 50 Value input2) { 51 return SmallVector<Value, 2>({input2, input1}); 52 } 53 54 // Test that natives calls are only called once during rewrites. 55 // OpM_Test will return Pi, increased by 1 for each subsequent calls. 56 // This let us check the number of times OpM_Test was called by inspecting 57 // the returned value in the MLIR output. 58 static int64_t opMIncreasingValue = 314159265; 59 static Attribute opMTest(PatternRewriter &rewriter, Value val) { 60 int64_t i = opMIncreasingValue++; 61 return rewriter.getIntegerAttr(rewriter.getIntegerType(32), i); 62 } 63 64 namespace { 65 #include "TestPatterns.inc" 66 } // namespace 67 68 //===----------------------------------------------------------------------===// 69 // Test Reduce Pattern Interface 70 //===----------------------------------------------------------------------===// 71 72 void test::populateTestReductionPatterns(RewritePatternSet &patterns) { 73 populateWithGenerated(patterns); 74 } 75 76 //===----------------------------------------------------------------------===// 77 // Canonicalizer Driver. 78 //===----------------------------------------------------------------------===// 79 80 namespace { 81 struct FoldingPattern : public RewritePattern { 82 public: 83 FoldingPattern(MLIRContext *context) 84 : RewritePattern(TestOpInPlaceFoldAnchor::getOperationName(), 85 /*benefit=*/1, context) {} 86 87 LogicalResult matchAndRewrite(Operation *op, 88 PatternRewriter &rewriter) const override { 89 // Exercise OperationFolder API for a single-result operation that is folded 90 // upon construction. The operation being created through the folder has an 91 // in-place folder, and it should be still present in the output. 92 // Furthermore, the folder should not crash when attempting to recover the 93 // (unchanged) operation result. 94 OperationFolder folder(op->getContext()); 95 Value result = folder.create<TestOpInPlaceFold>( 96 rewriter, op->getLoc(), rewriter.getIntegerType(32), op->getOperand(0), 97 rewriter.getI32IntegerAttr(0)); 98 assert(result); 99 rewriter.replaceOp(op, result); 100 return success(); 101 } 102 }; 103 104 /// This pattern creates a foldable operation at the entry point of the block. 105 /// This tests the situation where the operation folder will need to replace an 106 /// operation with a previously created constant that does not initially 107 /// dominate the operation to replace. 108 struct FolderInsertBeforePreviouslyFoldedConstantPattern 109 : public OpRewritePattern<TestCastOp> { 110 public: 111 using OpRewritePattern<TestCastOp>::OpRewritePattern; 112 113 LogicalResult matchAndRewrite(TestCastOp op, 114 PatternRewriter &rewriter) const override { 115 if (!op->hasAttr("test_fold_before_previously_folded_op")) 116 return failure(); 117 rewriter.setInsertionPointToStart(op->getBlock()); 118 119 auto constOp = rewriter.create<arith::ConstantOp>( 120 op.getLoc(), rewriter.getBoolAttr(true)); 121 rewriter.replaceOpWithNewOp<TestCastOp>(op, rewriter.getI32Type(), 122 Value(constOp)); 123 return success(); 124 } 125 }; 126 127 /// This pattern matches test.op_commutative2 with the first operand being 128 /// another test.op_commutative2 with a constant on the right side and fold it 129 /// away by propagating it as its result. This is intend to check that patterns 130 /// are applied after the commutative property moves constant to the right. 131 struct FolderCommutativeOp2WithConstant 132 : public OpRewritePattern<TestCommutative2Op> { 133 public: 134 using OpRewritePattern<TestCommutative2Op>::OpRewritePattern; 135 136 LogicalResult matchAndRewrite(TestCommutative2Op op, 137 PatternRewriter &rewriter) const override { 138 auto operand = 139 dyn_cast_or_null<TestCommutative2Op>(op->getOperand(0).getDefiningOp()); 140 if (!operand) 141 return failure(); 142 Attribute constInput; 143 if (!matchPattern(operand->getOperand(1), m_Constant(&constInput))) 144 return failure(); 145 rewriter.replaceOp(op, operand->getOperand(1)); 146 return success(); 147 } 148 }; 149 150 struct TestPatternDriver 151 : public PassWrapper<TestPatternDriver, OperationPass<func::FuncOp>> { 152 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestPatternDriver) 153 154 TestPatternDriver() = default; 155 TestPatternDriver(const TestPatternDriver &other) : PassWrapper(other) {} 156 157 StringRef getArgument() const final { return "test-patterns"; } 158 StringRef getDescription() const final { return "Run test dialect patterns"; } 159 void runOnOperation() override { 160 mlir::RewritePatternSet patterns(&getContext()); 161 populateWithGenerated(patterns); 162 163 // Verify named pattern is generated with expected name. 164 patterns.add<FoldingPattern, TestNamedPatternRule, 165 FolderInsertBeforePreviouslyFoldedConstantPattern, 166 FolderCommutativeOp2WithConstant>(&getContext()); 167 168 GreedyRewriteConfig config; 169 config.useTopDownTraversal = this->useTopDownTraversal; 170 (void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns), 171 config); 172 } 173 174 Option<bool> useTopDownTraversal{ 175 *this, "top-down", 176 llvm::cl::desc("Seed the worklist in general top-down order"), 177 llvm::cl::init(GreedyRewriteConfig().useTopDownTraversal)}; 178 }; 179 180 struct TestStrictPatternDriver 181 : public PassWrapper<TestStrictPatternDriver, OperationPass<func::FuncOp>> { 182 public: 183 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestStrictPatternDriver) 184 185 TestStrictPatternDriver() = default; 186 TestStrictPatternDriver(const TestStrictPatternDriver &other) 187 : PassWrapper(other) {} 188 189 StringRef getArgument() const final { return "test-strict-pattern-driver"; } 190 StringRef getDescription() const final { 191 return "Run strict mode of pattern driver"; 192 } 193 194 void runOnOperation() override { 195 mlir::RewritePatternSet patterns(&getContext()); 196 patterns.add<InsertSameOp, ReplaceWithSameOp, EraseOp>(&getContext()); 197 SmallVector<Operation *> ops; 198 getOperation()->walk([&](Operation *op) { 199 StringRef opName = op->getName().getStringRef(); 200 if (opName == "test.insert_same_op" || 201 opName == "test.replace_with_same_op" || opName == "test.erase_op") { 202 ops.push_back(op); 203 } 204 }); 205 206 // Check if these transformations introduce visiting of operations that 207 // are not in the `ops` set (The new created ops are valid). An invalid 208 // operation will trigger the assertion while processing. 209 (void)applyOpPatternsAndFold(makeArrayRef(ops), std::move(patterns), 210 /*strict=*/true); 211 } 212 213 private: 214 // New inserted operation is valid for further transformation. 215 class InsertSameOp : public RewritePattern { 216 public: 217 InsertSameOp(MLIRContext *context) 218 : RewritePattern("test.insert_same_op", /*benefit=*/1, context) {} 219 220 LogicalResult matchAndRewrite(Operation *op, 221 PatternRewriter &rewriter) const override { 222 if (op->hasAttr("skip")) 223 return failure(); 224 225 Operation *newOp = 226 rewriter.create(op->getLoc(), op->getName().getIdentifier(), 227 op->getOperands(), op->getResultTypes()); 228 op->setAttr("skip", rewriter.getBoolAttr(true)); 229 newOp->setAttr("skip", rewriter.getBoolAttr(true)); 230 231 return success(); 232 } 233 }; 234 235 // Replace an operation may introduce the re-visiting of its users. 236 class ReplaceWithSameOp : public RewritePattern { 237 public: 238 ReplaceWithSameOp(MLIRContext *context) 239 : RewritePattern("test.replace_with_same_op", /*benefit=*/1, context) {} 240 241 LogicalResult matchAndRewrite(Operation *op, 242 PatternRewriter &rewriter) const override { 243 Operation *newOp = 244 rewriter.create(op->getLoc(), op->getName().getIdentifier(), 245 op->getOperands(), op->getResultTypes()); 246 rewriter.replaceOp(op, newOp->getResults()); 247 return success(); 248 } 249 }; 250 251 // Remove an operation may introduce the re-visiting of its opreands. 252 class EraseOp : public RewritePattern { 253 public: 254 EraseOp(MLIRContext *context) 255 : RewritePattern("test.erase_op", /*benefit=*/1, context) {} 256 LogicalResult matchAndRewrite(Operation *op, 257 PatternRewriter &rewriter) const override { 258 rewriter.eraseOp(op); 259 return success(); 260 } 261 }; 262 }; 263 264 } // namespace 265 266 //===----------------------------------------------------------------------===// 267 // ReturnType Driver. 268 //===----------------------------------------------------------------------===// 269 270 namespace { 271 // Generate ops for each instance where the type can be successfully inferred. 272 template <typename OpTy> 273 static void invokeCreateWithInferredReturnType(Operation *op) { 274 auto *context = op->getContext(); 275 auto fop = op->getParentOfType<func::FuncOp>(); 276 auto location = UnknownLoc::get(context); 277 OpBuilder b(op); 278 b.setInsertionPointAfter(op); 279 280 // Use permutations of 2 args as operands. 281 assert(fop.getNumArguments() >= 2); 282 for (int i = 0, e = fop.getNumArguments(); i < e; ++i) { 283 for (int j = 0; j < e; ++j) { 284 std::array<Value, 2> values = {{fop.getArgument(i), fop.getArgument(j)}}; 285 SmallVector<Type, 2> inferredReturnTypes; 286 if (succeeded(OpTy::inferReturnTypes( 287 context, llvm::None, values, op->getAttrDictionary(), 288 op->getRegions(), inferredReturnTypes))) { 289 OperationState state(location, OpTy::getOperationName()); 290 // TODO: Expand to regions. 291 OpTy::build(b, state, values, op->getAttrs()); 292 (void)b.create(state); 293 } 294 } 295 } 296 } 297 298 static void reifyReturnShape(Operation *op) { 299 OpBuilder b(op); 300 301 // Use permutations of 2 args as operands. 302 auto shapedOp = cast<OpWithShapedTypeInferTypeInterfaceOp>(op); 303 SmallVector<Value, 2> shapes; 304 if (failed(shapedOp.reifyReturnTypeShapes(b, op->getOperands(), shapes)) || 305 !llvm::hasSingleElement(shapes)) 306 return; 307 for (const auto &it : llvm::enumerate(shapes)) { 308 op->emitRemark() << "value " << it.index() << ": " 309 << it.value().getDefiningOp(); 310 } 311 } 312 313 struct TestReturnTypeDriver 314 : public PassWrapper<TestReturnTypeDriver, OperationPass<func::FuncOp>> { 315 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestReturnTypeDriver) 316 317 void getDependentDialects(DialectRegistry ®istry) const override { 318 registry.insert<tensor::TensorDialect>(); 319 } 320 StringRef getArgument() const final { return "test-return-type"; } 321 StringRef getDescription() const final { return "Run return type functions"; } 322 323 void runOnOperation() override { 324 if (getOperation().getName() == "testCreateFunctions") { 325 std::vector<Operation *> ops; 326 // Collect ops to avoid triggering on inserted ops. 327 for (auto &op : getOperation().getBody().front()) 328 ops.push_back(&op); 329 // Generate test patterns for each, but skip terminator. 330 for (auto *op : llvm::makeArrayRef(ops).drop_back()) { 331 // Test create method of each of the Op classes below. The resultant 332 // output would be in reverse order underneath `op` from which 333 // the attributes and regions are used. 334 invokeCreateWithInferredReturnType<OpWithInferTypeInterfaceOp>(op); 335 invokeCreateWithInferredReturnType< 336 OpWithShapedTypeInferTypeInterfaceOp>(op); 337 }; 338 return; 339 } 340 if (getOperation().getName() == "testReifyFunctions") { 341 std::vector<Operation *> ops; 342 // Collect ops to avoid triggering on inserted ops. 343 for (auto &op : getOperation().getBody().front()) 344 if (isa<OpWithShapedTypeInferTypeInterfaceOp>(op)) 345 ops.push_back(&op); 346 // Generate test patterns for each, but skip terminator. 347 for (auto *op : ops) 348 reifyReturnShape(op); 349 } 350 } 351 }; 352 } // namespace 353 354 namespace { 355 struct TestDerivedAttributeDriver 356 : public PassWrapper<TestDerivedAttributeDriver, 357 OperationPass<func::FuncOp>> { 358 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestDerivedAttributeDriver) 359 360 StringRef getArgument() const final { return "test-derived-attr"; } 361 StringRef getDescription() const final { 362 return "Run test derived attributes"; 363 } 364 void runOnOperation() override; 365 }; 366 } // namespace 367 368 void TestDerivedAttributeDriver::runOnOperation() { 369 getOperation().walk([](DerivedAttributeOpInterface dOp) { 370 auto dAttr = dOp.materializeDerivedAttributes(); 371 if (!dAttr) 372 return; 373 for (auto d : dAttr) 374 dOp.emitRemark() << d.getName().getValue() << " = " << d.getValue(); 375 }); 376 } 377 378 //===----------------------------------------------------------------------===// 379 // Legalization Driver. 380 //===----------------------------------------------------------------------===// 381 382 namespace { 383 //===----------------------------------------------------------------------===// 384 // Region-Block Rewrite Testing 385 386 /// This pattern is a simple pattern that inlines the first region of a given 387 /// operation into the parent region. 388 struct TestRegionRewriteBlockMovement : public ConversionPattern { 389 TestRegionRewriteBlockMovement(MLIRContext *ctx) 390 : ConversionPattern("test.region", 1, ctx) {} 391 392 LogicalResult 393 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 394 ConversionPatternRewriter &rewriter) const final { 395 // Inline this region into the parent region. 396 auto &parentRegion = *op->getParentRegion(); 397 auto &opRegion = op->getRegion(0); 398 if (op->getAttr("legalizer.should_clone")) 399 rewriter.cloneRegionBefore(opRegion, parentRegion, parentRegion.end()); 400 else 401 rewriter.inlineRegionBefore(opRegion, parentRegion, parentRegion.end()); 402 403 if (op->getAttr("legalizer.erase_old_blocks")) { 404 while (!opRegion.empty()) 405 rewriter.eraseBlock(&opRegion.front()); 406 } 407 408 // Drop this operation. 409 rewriter.eraseOp(op); 410 return success(); 411 } 412 }; 413 /// This pattern is a simple pattern that generates a region containing an 414 /// illegal operation. 415 struct TestRegionRewriteUndo : public RewritePattern { 416 TestRegionRewriteUndo(MLIRContext *ctx) 417 : RewritePattern("test.region_builder", 1, ctx) {} 418 419 LogicalResult matchAndRewrite(Operation *op, 420 PatternRewriter &rewriter) const final { 421 // Create the region operation with an entry block containing arguments. 422 OperationState newRegion(op->getLoc(), "test.region"); 423 newRegion.addRegion(); 424 auto *regionOp = rewriter.create(newRegion); 425 auto *entryBlock = rewriter.createBlock(®ionOp->getRegion(0)); 426 entryBlock->addArgument(rewriter.getIntegerType(64), 427 rewriter.getUnknownLoc()); 428 429 // Add an explicitly illegal operation to ensure the conversion fails. 430 rewriter.create<ILLegalOpF>(op->getLoc(), rewriter.getIntegerType(32)); 431 rewriter.create<TestValidOp>(op->getLoc(), ArrayRef<Value>()); 432 433 // Drop this operation. 434 rewriter.eraseOp(op); 435 return success(); 436 } 437 }; 438 /// A simple pattern that creates a block at the end of the parent region of the 439 /// matched operation. 440 struct TestCreateBlock : public RewritePattern { 441 TestCreateBlock(MLIRContext *ctx) 442 : RewritePattern("test.create_block", /*benefit=*/1, ctx) {} 443 444 LogicalResult matchAndRewrite(Operation *op, 445 PatternRewriter &rewriter) const final { 446 Region ®ion = *op->getParentRegion(); 447 Type i32Type = rewriter.getIntegerType(32); 448 Location loc = op->getLoc(); 449 rewriter.createBlock(®ion, region.end(), {i32Type, i32Type}, {loc, loc}); 450 rewriter.create<TerminatorOp>(loc); 451 rewriter.replaceOp(op, {}); 452 return success(); 453 } 454 }; 455 456 /// A simple pattern that creates a block containing an invalid operation in 457 /// order to trigger the block creation undo mechanism. 458 struct TestCreateIllegalBlock : public RewritePattern { 459 TestCreateIllegalBlock(MLIRContext *ctx) 460 : RewritePattern("test.create_illegal_block", /*benefit=*/1, ctx) {} 461 462 LogicalResult matchAndRewrite(Operation *op, 463 PatternRewriter &rewriter) const final { 464 Region ®ion = *op->getParentRegion(); 465 Type i32Type = rewriter.getIntegerType(32); 466 Location loc = op->getLoc(); 467 rewriter.createBlock(®ion, region.end(), {i32Type, i32Type}, {loc, loc}); 468 // Create an illegal op to ensure the conversion fails. 469 rewriter.create<ILLegalOpF>(loc, i32Type); 470 rewriter.create<TerminatorOp>(loc); 471 rewriter.replaceOp(op, {}); 472 return success(); 473 } 474 }; 475 476 /// A simple pattern that tests the undo mechanism when replacing the uses of a 477 /// block argument. 478 struct TestUndoBlockArgReplace : public ConversionPattern { 479 TestUndoBlockArgReplace(MLIRContext *ctx) 480 : ConversionPattern("test.undo_block_arg_replace", /*benefit=*/1, ctx) {} 481 482 LogicalResult 483 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 484 ConversionPatternRewriter &rewriter) const final { 485 auto illegalOp = 486 rewriter.create<ILLegalOpF>(op->getLoc(), rewriter.getF32Type()); 487 rewriter.replaceUsesOfBlockArgument(op->getRegion(0).getArgument(0), 488 illegalOp); 489 rewriter.updateRootInPlace(op, [] {}); 490 return success(); 491 } 492 }; 493 494 /// A rewrite pattern that tests the undo mechanism when erasing a block. 495 struct TestUndoBlockErase : public ConversionPattern { 496 TestUndoBlockErase(MLIRContext *ctx) 497 : ConversionPattern("test.undo_block_erase", /*benefit=*/1, ctx) {} 498 499 LogicalResult 500 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 501 ConversionPatternRewriter &rewriter) const final { 502 Block *secondBlock = &*std::next(op->getRegion(0).begin()); 503 rewriter.setInsertionPointToStart(secondBlock); 504 rewriter.create<ILLegalOpF>(op->getLoc(), rewriter.getF32Type()); 505 rewriter.eraseBlock(secondBlock); 506 rewriter.updateRootInPlace(op, [] {}); 507 return success(); 508 } 509 }; 510 511 //===----------------------------------------------------------------------===// 512 // Type-Conversion Rewrite Testing 513 514 /// This patterns erases a region operation that has had a type conversion. 515 struct TestDropOpSignatureConversion : public ConversionPattern { 516 TestDropOpSignatureConversion(MLIRContext *ctx, TypeConverter &converter) 517 : ConversionPattern(converter, "test.drop_region_op", 1, ctx) {} 518 LogicalResult 519 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 520 ConversionPatternRewriter &rewriter) const override { 521 Region ®ion = op->getRegion(0); 522 Block *entry = ®ion.front(); 523 524 // Convert the original entry arguments. 525 TypeConverter &converter = *getTypeConverter(); 526 TypeConverter::SignatureConversion result(entry->getNumArguments()); 527 if (failed(converter.convertSignatureArgs(entry->getArgumentTypes(), 528 result)) || 529 failed(rewriter.convertRegionTypes(®ion, converter, &result))) 530 return failure(); 531 532 // Convert the region signature and just drop the operation. 533 rewriter.eraseOp(op); 534 return success(); 535 } 536 }; 537 /// This pattern simply updates the operands of the given operation. 538 struct TestPassthroughInvalidOp : public ConversionPattern { 539 TestPassthroughInvalidOp(MLIRContext *ctx) 540 : ConversionPattern("test.invalid", 1, ctx) {} 541 LogicalResult 542 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 543 ConversionPatternRewriter &rewriter) const final { 544 rewriter.replaceOpWithNewOp<TestValidOp>(op, llvm::None, operands, 545 llvm::None); 546 return success(); 547 } 548 }; 549 /// This pattern handles the case of a split return value. 550 struct TestSplitReturnType : public ConversionPattern { 551 TestSplitReturnType(MLIRContext *ctx) 552 : ConversionPattern("test.return", 1, ctx) {} 553 LogicalResult 554 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 555 ConversionPatternRewriter &rewriter) const final { 556 // Check for a return of F32. 557 if (op->getNumOperands() != 1 || !op->getOperand(0).getType().isF32()) 558 return failure(); 559 560 // Check if the first operation is a cast operation, if it is we use the 561 // results directly. 562 auto *defOp = operands[0].getDefiningOp(); 563 if (auto packerOp = 564 llvm::dyn_cast_or_null<UnrealizedConversionCastOp>(defOp)) { 565 rewriter.replaceOpWithNewOp<TestReturnOp>(op, packerOp.getOperands()); 566 return success(); 567 } 568 569 // Otherwise, fail to match. 570 return failure(); 571 } 572 }; 573 574 //===----------------------------------------------------------------------===// 575 // Multi-Level Type-Conversion Rewrite Testing 576 struct TestChangeProducerTypeI32ToF32 : public ConversionPattern { 577 TestChangeProducerTypeI32ToF32(MLIRContext *ctx) 578 : ConversionPattern("test.type_producer", 1, ctx) {} 579 LogicalResult 580 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 581 ConversionPatternRewriter &rewriter) const final { 582 // If the type is I32, change the type to F32. 583 if (!Type(*op->result_type_begin()).isSignlessInteger(32)) 584 return failure(); 585 rewriter.replaceOpWithNewOp<TestTypeProducerOp>(op, rewriter.getF32Type()); 586 return success(); 587 } 588 }; 589 struct TestChangeProducerTypeF32ToF64 : public ConversionPattern { 590 TestChangeProducerTypeF32ToF64(MLIRContext *ctx) 591 : ConversionPattern("test.type_producer", 1, ctx) {} 592 LogicalResult 593 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 594 ConversionPatternRewriter &rewriter) const final { 595 // If the type is F32, change the type to F64. 596 if (!Type(*op->result_type_begin()).isF32()) 597 return rewriter.notifyMatchFailure(op, "expected single f32 operand"); 598 rewriter.replaceOpWithNewOp<TestTypeProducerOp>(op, rewriter.getF64Type()); 599 return success(); 600 } 601 }; 602 struct TestChangeProducerTypeF32ToInvalid : public ConversionPattern { 603 TestChangeProducerTypeF32ToInvalid(MLIRContext *ctx) 604 : ConversionPattern("test.type_producer", 10, ctx) {} 605 LogicalResult 606 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 607 ConversionPatternRewriter &rewriter) const final { 608 // Always convert to B16, even though it is not a legal type. This tests 609 // that values are unmapped correctly. 610 rewriter.replaceOpWithNewOp<TestTypeProducerOp>(op, rewriter.getBF16Type()); 611 return success(); 612 } 613 }; 614 struct TestUpdateConsumerType : public ConversionPattern { 615 TestUpdateConsumerType(MLIRContext *ctx) 616 : ConversionPattern("test.type_consumer", 1, ctx) {} 617 LogicalResult 618 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 619 ConversionPatternRewriter &rewriter) const final { 620 // Verify that the incoming operand has been successfully remapped to F64. 621 if (!operands[0].getType().isF64()) 622 return failure(); 623 rewriter.replaceOpWithNewOp<TestTypeConsumerOp>(op, operands[0]); 624 return success(); 625 } 626 }; 627 628 //===----------------------------------------------------------------------===// 629 // Non-Root Replacement Rewrite Testing 630 /// This pattern generates an invalid operation, but replaces it before the 631 /// pattern is finished. This checks that we don't need to legalize the 632 /// temporary op. 633 struct TestNonRootReplacement : public RewritePattern { 634 TestNonRootReplacement(MLIRContext *ctx) 635 : RewritePattern("test.replace_non_root", 1, ctx) {} 636 637 LogicalResult matchAndRewrite(Operation *op, 638 PatternRewriter &rewriter) const final { 639 auto resultType = *op->result_type_begin(); 640 auto illegalOp = rewriter.create<ILLegalOpF>(op->getLoc(), resultType); 641 auto legalOp = rewriter.create<LegalOpB>(op->getLoc(), resultType); 642 643 rewriter.replaceOp(illegalOp, {legalOp}); 644 rewriter.replaceOp(op, {illegalOp}); 645 return success(); 646 } 647 }; 648 649 //===----------------------------------------------------------------------===// 650 // Recursive Rewrite Testing 651 /// This pattern is applied to the same operation multiple times, but has a 652 /// bounded recursion. 653 struct TestBoundedRecursiveRewrite 654 : public OpRewritePattern<TestRecursiveRewriteOp> { 655 using OpRewritePattern<TestRecursiveRewriteOp>::OpRewritePattern; 656 657 void initialize() { 658 // The conversion target handles bounding the recursion of this pattern. 659 setHasBoundedRewriteRecursion(); 660 } 661 662 LogicalResult matchAndRewrite(TestRecursiveRewriteOp op, 663 PatternRewriter &rewriter) const final { 664 // Decrement the depth of the op in-place. 665 rewriter.updateRootInPlace(op, [&] { 666 op->setAttr("depth", rewriter.getI64IntegerAttr(op.getDepth() - 1)); 667 }); 668 return success(); 669 } 670 }; 671 672 struct TestNestedOpCreationUndoRewrite 673 : public OpRewritePattern<IllegalOpWithRegionAnchor> { 674 using OpRewritePattern<IllegalOpWithRegionAnchor>::OpRewritePattern; 675 676 LogicalResult matchAndRewrite(IllegalOpWithRegionAnchor op, 677 PatternRewriter &rewriter) const final { 678 // rewriter.replaceOpWithNewOp<IllegalOpWithRegion>(op); 679 rewriter.replaceOpWithNewOp<IllegalOpWithRegion>(op); 680 return success(); 681 }; 682 }; 683 684 // This pattern matches `test.blackhole` and delete this op and its producer. 685 struct TestReplaceEraseOp : public OpRewritePattern<BlackHoleOp> { 686 using OpRewritePattern<BlackHoleOp>::OpRewritePattern; 687 688 LogicalResult matchAndRewrite(BlackHoleOp op, 689 PatternRewriter &rewriter) const final { 690 Operation *producer = op.getOperand().getDefiningOp(); 691 // Always erase the user before the producer, the framework should handle 692 // this correctly. 693 rewriter.eraseOp(op); 694 rewriter.eraseOp(producer); 695 return success(); 696 }; 697 }; 698 699 // This pattern replaces explicitly illegal op with explicitly legal op, 700 // but in addition creates unregistered operation. 701 struct TestCreateUnregisteredOp : public OpRewritePattern<ILLegalOpG> { 702 using OpRewritePattern<ILLegalOpG>::OpRewritePattern; 703 704 LogicalResult matchAndRewrite(ILLegalOpG op, 705 PatternRewriter &rewriter) const final { 706 IntegerAttr attr = rewriter.getI32IntegerAttr(0); 707 Value val = rewriter.create<arith::ConstantOp>(op->getLoc(), attr); 708 rewriter.replaceOpWithNewOp<LegalOpC>(op, val); 709 return success(); 710 }; 711 }; 712 } // namespace 713 714 namespace { 715 struct TestTypeConverter : public TypeConverter { 716 using TypeConverter::TypeConverter; 717 TestTypeConverter() { 718 addConversion(convertType); 719 addArgumentMaterialization(materializeCast); 720 addSourceMaterialization(materializeCast); 721 } 722 723 static LogicalResult convertType(Type t, SmallVectorImpl<Type> &results) { 724 // Drop I16 types. 725 if (t.isSignlessInteger(16)) 726 return success(); 727 728 // Convert I64 to F64. 729 if (t.isSignlessInteger(64)) { 730 results.push_back(FloatType::getF64(t.getContext())); 731 return success(); 732 } 733 734 // Convert I42 to I43. 735 if (t.isInteger(42)) { 736 results.push_back(IntegerType::get(t.getContext(), 43)); 737 return success(); 738 } 739 740 // Split F32 into F16,F16. 741 if (t.isF32()) { 742 results.assign(2, FloatType::getF16(t.getContext())); 743 return success(); 744 } 745 746 // Otherwise, convert the type directly. 747 results.push_back(t); 748 return success(); 749 } 750 751 /// Hook for materializing a conversion. This is necessary because we generate 752 /// 1->N type mappings. 753 static Optional<Value> materializeCast(OpBuilder &builder, Type resultType, 754 ValueRange inputs, Location loc) { 755 return builder.create<TestCastOp>(loc, resultType, inputs).getResult(); 756 } 757 }; 758 759 struct TestLegalizePatternDriver 760 : public PassWrapper<TestLegalizePatternDriver, OperationPass<ModuleOp>> { 761 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestLegalizePatternDriver) 762 763 StringRef getArgument() const final { return "test-legalize-patterns"; } 764 StringRef getDescription() const final { 765 return "Run test dialect legalization patterns"; 766 } 767 /// The mode of conversion to use with the driver. 768 enum class ConversionMode { Analysis, Full, Partial }; 769 770 TestLegalizePatternDriver(ConversionMode mode) : mode(mode) {} 771 772 void getDependentDialects(DialectRegistry ®istry) const override { 773 registry.insert<func::FuncDialect>(); 774 } 775 776 void runOnOperation() override { 777 TestTypeConverter converter; 778 mlir::RewritePatternSet patterns(&getContext()); 779 populateWithGenerated(patterns); 780 patterns 781 .add<TestRegionRewriteBlockMovement, TestRegionRewriteUndo, 782 TestCreateBlock, TestCreateIllegalBlock, TestUndoBlockArgReplace, 783 TestUndoBlockErase, TestPassthroughInvalidOp, TestSplitReturnType, 784 TestChangeProducerTypeI32ToF32, TestChangeProducerTypeF32ToF64, 785 TestChangeProducerTypeF32ToInvalid, TestUpdateConsumerType, 786 TestNonRootReplacement, TestBoundedRecursiveRewrite, 787 TestNestedOpCreationUndoRewrite, TestReplaceEraseOp, 788 TestCreateUnregisteredOp>(&getContext()); 789 patterns.add<TestDropOpSignatureConversion>(&getContext(), converter); 790 mlir::populateFunctionOpInterfaceTypeConversionPattern<func::FuncOp>( 791 patterns, converter); 792 mlir::populateCallOpTypeConversionPattern(patterns, converter); 793 794 // Define the conversion target used for the test. 795 ConversionTarget target(getContext()); 796 target.addLegalOp<ModuleOp>(); 797 target.addLegalOp<LegalOpA, LegalOpB, LegalOpC, TestCastOp, TestValidOp, 798 TerminatorOp>(); 799 target 800 .addIllegalOp<ILLegalOpF, TestRegionBuilderOp, TestOpWithRegionFold>(); 801 target.addDynamicallyLegalOp<TestReturnOp>([](TestReturnOp op) { 802 // Don't allow F32 operands. 803 return llvm::none_of(op.getOperandTypes(), 804 [](Type type) { return type.isF32(); }); 805 }); 806 target.addDynamicallyLegalOp<func::FuncOp>([&](func::FuncOp op) { 807 return converter.isSignatureLegal(op.getFunctionType()) && 808 converter.isLegal(&op.getBody()); 809 }); 810 target.addDynamicallyLegalOp<func::CallOp>( 811 [&](func::CallOp op) { return converter.isLegal(op); }); 812 813 // TestCreateUnregisteredOp creates `arith.constant` operation, 814 // which was not added to target intentionally to test 815 // correct error code from conversion driver. 816 target.addDynamicallyLegalOp<ILLegalOpG>([](ILLegalOpG) { return false; }); 817 818 // Expect the type_producer/type_consumer operations to only operate on f64. 819 target.addDynamicallyLegalOp<TestTypeProducerOp>( 820 [](TestTypeProducerOp op) { return op.getType().isF64(); }); 821 target.addDynamicallyLegalOp<TestTypeConsumerOp>([](TestTypeConsumerOp op) { 822 return op.getOperand().getType().isF64(); 823 }); 824 825 // Check support for marking certain operations as recursively legal. 826 target.markOpRecursivelyLegal<func::FuncOp, ModuleOp>([](Operation *op) { 827 return static_cast<bool>( 828 op->getAttrOfType<UnitAttr>("test.recursively_legal")); 829 }); 830 831 // Mark the bound recursion operation as dynamically legal. 832 target.addDynamicallyLegalOp<TestRecursiveRewriteOp>( 833 [](TestRecursiveRewriteOp op) { return op.getDepth() == 0; }); 834 835 // Handle a partial conversion. 836 if (mode == ConversionMode::Partial) { 837 DenseSet<Operation *> unlegalizedOps; 838 if (failed(applyPartialConversion( 839 getOperation(), target, std::move(patterns), &unlegalizedOps))) { 840 getOperation()->emitRemark() << "applyPartialConversion failed"; 841 } 842 // Emit remarks for each legalizable operation. 843 for (auto *op : unlegalizedOps) 844 op->emitRemark() << "op '" << op->getName() << "' is not legalizable"; 845 return; 846 } 847 848 // Handle a full conversion. 849 if (mode == ConversionMode::Full) { 850 // Check support for marking unknown operations as dynamically legal. 851 target.markUnknownOpDynamicallyLegal([](Operation *op) { 852 return (bool)op->getAttrOfType<UnitAttr>("test.dynamically_legal"); 853 }); 854 855 if (failed(applyFullConversion(getOperation(), target, 856 std::move(patterns)))) { 857 getOperation()->emitRemark() << "applyFullConversion failed"; 858 } 859 return; 860 } 861 862 // Otherwise, handle an analysis conversion. 863 assert(mode == ConversionMode::Analysis); 864 865 // Analyze the convertible operations. 866 DenseSet<Operation *> legalizedOps; 867 if (failed(applyAnalysisConversion(getOperation(), target, 868 std::move(patterns), legalizedOps))) 869 return signalPassFailure(); 870 871 // Emit remarks for each legalizable operation. 872 for (auto *op : legalizedOps) 873 op->emitRemark() << "op '" << op->getName() << "' is legalizable"; 874 } 875 876 /// The mode of conversion to use. 877 ConversionMode mode; 878 }; 879 } // namespace 880 881 static llvm::cl::opt<TestLegalizePatternDriver::ConversionMode> 882 legalizerConversionMode( 883 "test-legalize-mode", 884 llvm::cl::desc("The legalization mode to use with the test driver"), 885 llvm::cl::init(TestLegalizePatternDriver::ConversionMode::Partial), 886 llvm::cl::values( 887 clEnumValN(TestLegalizePatternDriver::ConversionMode::Analysis, 888 "analysis", "Perform an analysis conversion"), 889 clEnumValN(TestLegalizePatternDriver::ConversionMode::Full, "full", 890 "Perform a full conversion"), 891 clEnumValN(TestLegalizePatternDriver::ConversionMode::Partial, 892 "partial", "Perform a partial conversion"))); 893 894 //===----------------------------------------------------------------------===// 895 // ConversionPatternRewriter::getRemappedValue testing. This method is used 896 // to get the remapped value of an original value that was replaced using 897 // ConversionPatternRewriter. 898 namespace { 899 struct TestRemapValueTypeConverter : public TypeConverter { 900 using TypeConverter::TypeConverter; 901 902 TestRemapValueTypeConverter() { 903 addConversion( 904 [](Float32Type type) { return Float64Type::get(type.getContext()); }); 905 addConversion([](Type type) { return type; }); 906 } 907 }; 908 909 /// Converter that replaces a one-result one-operand OneVResOneVOperandOp1 with 910 /// a one-operand two-result OneVResOneVOperandOp1 by replicating its original 911 /// operand twice. 912 /// 913 /// Example: 914 /// %1 = test.one_variadic_out_one_variadic_in1"(%0) 915 /// is replaced with: 916 /// %1 = test.one_variadic_out_one_variadic_in1"(%0, %0) 917 struct OneVResOneVOperandOp1Converter 918 : public OpConversionPattern<OneVResOneVOperandOp1> { 919 using OpConversionPattern<OneVResOneVOperandOp1>::OpConversionPattern; 920 921 LogicalResult 922 matchAndRewrite(OneVResOneVOperandOp1 op, OpAdaptor adaptor, 923 ConversionPatternRewriter &rewriter) const override { 924 auto origOps = op.getOperands(); 925 assert(std::distance(origOps.begin(), origOps.end()) == 1 && 926 "One operand expected"); 927 Value origOp = *origOps.begin(); 928 SmallVector<Value, 2> remappedOperands; 929 // Replicate the remapped original operand twice. Note that we don't used 930 // the remapped 'operand' since the goal is testing 'getRemappedValue'. 931 remappedOperands.push_back(rewriter.getRemappedValue(origOp)); 932 remappedOperands.push_back(rewriter.getRemappedValue(origOp)); 933 934 rewriter.replaceOpWithNewOp<OneVResOneVOperandOp1>(op, op.getResultTypes(), 935 remappedOperands); 936 return success(); 937 } 938 }; 939 940 /// A rewriter pattern that tests that blocks can be merged. 941 struct TestRemapValueInRegion 942 : public OpConversionPattern<TestRemappedValueRegionOp> { 943 using OpConversionPattern<TestRemappedValueRegionOp>::OpConversionPattern; 944 945 LogicalResult 946 matchAndRewrite(TestRemappedValueRegionOp op, OpAdaptor adaptor, 947 ConversionPatternRewriter &rewriter) const final { 948 Block &block = op.getBody().front(); 949 Operation *terminator = block.getTerminator(); 950 951 // Merge the block into the parent region. 952 Block *parentBlock = op->getBlock(); 953 Block *finalBlock = rewriter.splitBlock(parentBlock, op->getIterator()); 954 rewriter.mergeBlocks(&block, parentBlock, ValueRange()); 955 rewriter.mergeBlocks(finalBlock, parentBlock, ValueRange()); 956 957 // Replace the results of this operation with the remapped terminator 958 // values. 959 SmallVector<Value> terminatorOperands; 960 if (failed(rewriter.getRemappedValues(terminator->getOperands(), 961 terminatorOperands))) 962 return failure(); 963 964 rewriter.eraseOp(terminator); 965 rewriter.replaceOp(op, terminatorOperands); 966 return success(); 967 } 968 }; 969 970 struct TestRemappedValue 971 : public mlir::PassWrapper<TestRemappedValue, OperationPass<func::FuncOp>> { 972 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestRemappedValue) 973 974 StringRef getArgument() const final { return "test-remapped-value"; } 975 StringRef getDescription() const final { 976 return "Test public remapped value mechanism in ConversionPatternRewriter"; 977 } 978 void runOnOperation() override { 979 TestRemapValueTypeConverter typeConverter; 980 981 mlir::RewritePatternSet patterns(&getContext()); 982 patterns.add<OneVResOneVOperandOp1Converter>(&getContext()); 983 patterns.add<TestChangeProducerTypeF32ToF64, TestUpdateConsumerType>( 984 &getContext()); 985 patterns.add<TestRemapValueInRegion>(typeConverter, &getContext()); 986 987 mlir::ConversionTarget target(getContext()); 988 target.addLegalOp<ModuleOp, func::FuncOp, TestReturnOp>(); 989 990 // Expect the type_producer/type_consumer operations to only operate on f64. 991 target.addDynamicallyLegalOp<TestTypeProducerOp>( 992 [](TestTypeProducerOp op) { return op.getType().isF64(); }); 993 target.addDynamicallyLegalOp<TestTypeConsumerOp>([](TestTypeConsumerOp op) { 994 return op.getOperand().getType().isF64(); 995 }); 996 997 // We make OneVResOneVOperandOp1 legal only when it has more that one 998 // operand. This will trigger the conversion that will replace one-operand 999 // OneVResOneVOperandOp1 with two-operand OneVResOneVOperandOp1. 1000 target.addDynamicallyLegalOp<OneVResOneVOperandOp1>( 1001 [](Operation *op) { return op->getNumOperands() > 1; }); 1002 1003 if (failed(mlir::applyFullConversion(getOperation(), target, 1004 std::move(patterns)))) { 1005 signalPassFailure(); 1006 } 1007 } 1008 }; 1009 } // namespace 1010 1011 //===----------------------------------------------------------------------===// 1012 // Test patterns without a specific root operation kind 1013 //===----------------------------------------------------------------------===// 1014 1015 namespace { 1016 /// This pattern matches and removes any operation in the test dialect. 1017 struct RemoveTestDialectOps : public RewritePattern { 1018 RemoveTestDialectOps(MLIRContext *context) 1019 : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {} 1020 1021 LogicalResult matchAndRewrite(Operation *op, 1022 PatternRewriter &rewriter) const override { 1023 if (!isa<TestDialect>(op->getDialect())) 1024 return failure(); 1025 rewriter.eraseOp(op); 1026 return success(); 1027 } 1028 }; 1029 1030 struct TestUnknownRootOpDriver 1031 : public mlir::PassWrapper<TestUnknownRootOpDriver, 1032 OperationPass<func::FuncOp>> { 1033 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestUnknownRootOpDriver) 1034 1035 StringRef getArgument() const final { 1036 return "test-legalize-unknown-root-patterns"; 1037 } 1038 StringRef getDescription() const final { 1039 return "Test public remapped value mechanism in ConversionPatternRewriter"; 1040 } 1041 void runOnOperation() override { 1042 mlir::RewritePatternSet patterns(&getContext()); 1043 patterns.add<RemoveTestDialectOps>(&getContext()); 1044 1045 mlir::ConversionTarget target(getContext()); 1046 target.addIllegalDialect<TestDialect>(); 1047 if (failed(applyPartialConversion(getOperation(), target, 1048 std::move(patterns)))) 1049 signalPassFailure(); 1050 } 1051 }; 1052 } // namespace 1053 1054 //===----------------------------------------------------------------------===// 1055 // Test patterns that uses operations and types defined at runtime 1056 //===----------------------------------------------------------------------===// 1057 1058 namespace { 1059 /// This pattern matches dynamic operations 'test.one_operand_two_results' and 1060 /// replace them with dynamic operations 'test.generic_dynamic_op'. 1061 struct RewriteDynamicOp : public RewritePattern { 1062 RewriteDynamicOp(MLIRContext *context) 1063 : RewritePattern("test.dynamic_one_operand_two_results", /*benefit=*/1, 1064 context) {} 1065 1066 LogicalResult matchAndRewrite(Operation *op, 1067 PatternRewriter &rewriter) const override { 1068 assert(op->getName().getStringRef() == 1069 "test.dynamic_one_operand_two_results" && 1070 "rewrite pattern should only match operations with the right name"); 1071 1072 OperationState state(op->getLoc(), "test.dynamic_generic", 1073 op->getOperands(), op->getResultTypes(), 1074 op->getAttrs()); 1075 auto *newOp = rewriter.create(state); 1076 rewriter.replaceOp(op, newOp->getResults()); 1077 return success(); 1078 } 1079 }; 1080 1081 struct TestRewriteDynamicOpDriver 1082 : public PassWrapper<TestRewriteDynamicOpDriver, 1083 OperationPass<func::FuncOp>> { 1084 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestRewriteDynamicOpDriver) 1085 1086 void getDependentDialects(DialectRegistry ®istry) const override { 1087 registry.insert<TestDialect>(); 1088 } 1089 StringRef getArgument() const final { return "test-rewrite-dynamic-op"; } 1090 StringRef getDescription() const final { 1091 return "Test rewritting on dynamic operations"; 1092 } 1093 void runOnOperation() override { 1094 RewritePatternSet patterns(&getContext()); 1095 patterns.add<RewriteDynamicOp>(&getContext()); 1096 1097 ConversionTarget target(getContext()); 1098 target.addIllegalOp( 1099 OperationName("test.dynamic_one_operand_two_results", &getContext())); 1100 target.addLegalOp(OperationName("test.dynamic_generic", &getContext())); 1101 if (failed(applyPartialConversion(getOperation(), target, 1102 std::move(patterns)))) 1103 signalPassFailure(); 1104 } 1105 }; 1106 } // end anonymous namespace 1107 1108 //===----------------------------------------------------------------------===// 1109 // Test type conversions 1110 //===----------------------------------------------------------------------===// 1111 1112 namespace { 1113 struct TestTypeConversionProducer 1114 : public OpConversionPattern<TestTypeProducerOp> { 1115 using OpConversionPattern<TestTypeProducerOp>::OpConversionPattern; 1116 LogicalResult 1117 matchAndRewrite(TestTypeProducerOp op, OpAdaptor adaptor, 1118 ConversionPatternRewriter &rewriter) const final { 1119 Type resultType = op.getType(); 1120 Type convertedType = getTypeConverter() 1121 ? getTypeConverter()->convertType(resultType) 1122 : resultType; 1123 if (resultType.isa<FloatType>()) 1124 resultType = rewriter.getF64Type(); 1125 else if (resultType.isInteger(16)) 1126 resultType = rewriter.getIntegerType(64); 1127 else if (resultType.isa<test::TestRecursiveType>() && 1128 convertedType != resultType) 1129 resultType = convertedType; 1130 else 1131 return failure(); 1132 1133 rewriter.replaceOpWithNewOp<TestTypeProducerOp>(op, resultType); 1134 return success(); 1135 } 1136 }; 1137 1138 /// Call signature conversion and then fail the rewrite to trigger the undo 1139 /// mechanism. 1140 struct TestSignatureConversionUndo 1141 : public OpConversionPattern<TestSignatureConversionUndoOp> { 1142 using OpConversionPattern<TestSignatureConversionUndoOp>::OpConversionPattern; 1143 1144 LogicalResult 1145 matchAndRewrite(TestSignatureConversionUndoOp op, OpAdaptor adaptor, 1146 ConversionPatternRewriter &rewriter) const final { 1147 (void)rewriter.convertRegionTypes(&op->getRegion(0), *getTypeConverter()); 1148 return failure(); 1149 } 1150 }; 1151 1152 /// Call signature conversion without providing a type converter to handle 1153 /// materializations. 1154 struct TestTestSignatureConversionNoConverter 1155 : public OpConversionPattern<TestSignatureConversionNoConverterOp> { 1156 TestTestSignatureConversionNoConverter(TypeConverter &converter, 1157 MLIRContext *context) 1158 : OpConversionPattern<TestSignatureConversionNoConverterOp>(context), 1159 converter(converter) {} 1160 1161 LogicalResult 1162 matchAndRewrite(TestSignatureConversionNoConverterOp op, OpAdaptor adaptor, 1163 ConversionPatternRewriter &rewriter) const final { 1164 Region ®ion = op->getRegion(0); 1165 Block *entry = ®ion.front(); 1166 1167 // Convert the original entry arguments. 1168 TypeConverter::SignatureConversion result(entry->getNumArguments()); 1169 if (failed( 1170 converter.convertSignatureArgs(entry->getArgumentTypes(), result))) 1171 return failure(); 1172 rewriter.updateRootInPlace( 1173 op, [&] { rewriter.applySignatureConversion(®ion, result); }); 1174 return success(); 1175 } 1176 1177 TypeConverter &converter; 1178 }; 1179 1180 /// Just forward the operands to the root op. This is essentially a no-op 1181 /// pattern that is used to trigger target materialization. 1182 struct TestTypeConsumerForward 1183 : public OpConversionPattern<TestTypeConsumerOp> { 1184 using OpConversionPattern<TestTypeConsumerOp>::OpConversionPattern; 1185 1186 LogicalResult 1187 matchAndRewrite(TestTypeConsumerOp op, OpAdaptor adaptor, 1188 ConversionPatternRewriter &rewriter) const final { 1189 rewriter.updateRootInPlace(op, 1190 [&] { op->setOperands(adaptor.getOperands()); }); 1191 return success(); 1192 } 1193 }; 1194 1195 struct TestTypeConversionAnotherProducer 1196 : public OpRewritePattern<TestAnotherTypeProducerOp> { 1197 using OpRewritePattern<TestAnotherTypeProducerOp>::OpRewritePattern; 1198 1199 LogicalResult matchAndRewrite(TestAnotherTypeProducerOp op, 1200 PatternRewriter &rewriter) const final { 1201 rewriter.replaceOpWithNewOp<TestTypeProducerOp>(op, op.getType()); 1202 return success(); 1203 } 1204 }; 1205 1206 struct TestTypeConversionDriver 1207 : public PassWrapper<TestTypeConversionDriver, OperationPass<ModuleOp>> { 1208 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestTypeConversionDriver) 1209 1210 void getDependentDialects(DialectRegistry ®istry) const override { 1211 registry.insert<TestDialect>(); 1212 } 1213 StringRef getArgument() const final { 1214 return "test-legalize-type-conversion"; 1215 } 1216 StringRef getDescription() const final { 1217 return "Test various type conversion functionalities in DialectConversion"; 1218 } 1219 1220 void runOnOperation() override { 1221 // Initialize the type converter. 1222 TypeConverter converter; 1223 1224 /// Add the legal set of type conversions. 1225 converter.addConversion([](Type type) -> Type { 1226 // Treat F64 as legal. 1227 if (type.isF64()) 1228 return type; 1229 // Allow converting BF16/F16/F32 to F64. 1230 if (type.isBF16() || type.isF16() || type.isF32()) 1231 return FloatType::getF64(type.getContext()); 1232 // Otherwise, the type is illegal. 1233 return nullptr; 1234 }); 1235 converter.addConversion([](IntegerType type, SmallVectorImpl<Type> &) { 1236 // Drop all integer types. 1237 return success(); 1238 }); 1239 converter.addConversion( 1240 // Convert a recursive self-referring type into a non-self-referring 1241 // type named "outer_converted_type" that contains a SimpleAType. 1242 [&](test::TestRecursiveType type, SmallVectorImpl<Type> &results, 1243 ArrayRef<Type> callStack) -> Optional<LogicalResult> { 1244 // If the type is already converted, return it to indicate that it is 1245 // legal. 1246 if (type.getName() == "outer_converted_type") { 1247 results.push_back(type); 1248 return success(); 1249 } 1250 1251 // If the type is on the call stack more than once (it is there at 1252 // least once because of the _current_ call, which is always the last 1253 // element on the stack), we've hit the recursive case. Just return 1254 // SimpleAType here to create a non-recursive type as a result. 1255 if (llvm::is_contained(callStack.drop_back(), type)) { 1256 results.push_back(test::SimpleAType::get(type.getContext())); 1257 return success(); 1258 } 1259 1260 // Convert the body recursively. 1261 auto result = test::TestRecursiveType::get(type.getContext(), 1262 "outer_converted_type"); 1263 if (failed(result.setBody(converter.convertType(type.getBody())))) 1264 return failure(); 1265 results.push_back(result); 1266 return success(); 1267 }); 1268 1269 /// Add the legal set of type materializations. 1270 converter.addSourceMaterialization([](OpBuilder &builder, Type resultType, 1271 ValueRange inputs, 1272 Location loc) -> Value { 1273 // Allow casting from F64 back to F32. 1274 if (!resultType.isF16() && inputs.size() == 1 && 1275 inputs[0].getType().isF64()) 1276 return builder.create<TestCastOp>(loc, resultType, inputs).getResult(); 1277 // Allow producing an i32 or i64 from nothing. 1278 if ((resultType.isInteger(32) || resultType.isInteger(64)) && 1279 inputs.empty()) 1280 return builder.create<TestTypeProducerOp>(loc, resultType); 1281 // Allow producing an i64 from an integer. 1282 if (resultType.isa<IntegerType>() && inputs.size() == 1 && 1283 inputs[0].getType().isa<IntegerType>()) 1284 return builder.create<TestCastOp>(loc, resultType, inputs).getResult(); 1285 // Otherwise, fail. 1286 return nullptr; 1287 }); 1288 1289 // Initialize the conversion target. 1290 mlir::ConversionTarget target(getContext()); 1291 target.addDynamicallyLegalOp<TestTypeProducerOp>([](TestTypeProducerOp op) { 1292 auto recursiveType = op.getType().dyn_cast<test::TestRecursiveType>(); 1293 return op.getType().isF64() || op.getType().isInteger(64) || 1294 (recursiveType && 1295 recursiveType.getName() == "outer_converted_type"); 1296 }); 1297 target.addDynamicallyLegalOp<func::FuncOp>([&](func::FuncOp op) { 1298 return converter.isSignatureLegal(op.getFunctionType()) && 1299 converter.isLegal(&op.getBody()); 1300 }); 1301 target.addDynamicallyLegalOp<TestCastOp>([&](TestCastOp op) { 1302 // Allow casts from F64 to F32. 1303 return (*op.operand_type_begin()).isF64() && op.getType().isF32(); 1304 }); 1305 target.addDynamicallyLegalOp<TestSignatureConversionNoConverterOp>( 1306 [&](TestSignatureConversionNoConverterOp op) { 1307 return converter.isLegal(op.getRegion().front().getArgumentTypes()); 1308 }); 1309 1310 // Initialize the set of rewrite patterns. 1311 RewritePatternSet patterns(&getContext()); 1312 patterns.add<TestTypeConsumerForward, TestTypeConversionProducer, 1313 TestSignatureConversionUndo, 1314 TestTestSignatureConversionNoConverter>(converter, 1315 &getContext()); 1316 patterns.add<TestTypeConversionAnotherProducer>(&getContext()); 1317 mlir::populateFunctionOpInterfaceTypeConversionPattern<func::FuncOp>( 1318 patterns, converter); 1319 1320 if (failed(applyPartialConversion(getOperation(), target, 1321 std::move(patterns)))) 1322 signalPassFailure(); 1323 } 1324 }; 1325 } // namespace 1326 1327 //===----------------------------------------------------------------------===// 1328 // Test Target Materialization With No Uses 1329 //===----------------------------------------------------------------------===// 1330 1331 namespace { 1332 struct ForwardOperandPattern : public OpConversionPattern<TestTypeChangerOp> { 1333 using OpConversionPattern<TestTypeChangerOp>::OpConversionPattern; 1334 1335 LogicalResult 1336 matchAndRewrite(TestTypeChangerOp op, OpAdaptor adaptor, 1337 ConversionPatternRewriter &rewriter) const final { 1338 rewriter.replaceOp(op, adaptor.getOperands()); 1339 return success(); 1340 } 1341 }; 1342 1343 struct TestTargetMaterializationWithNoUses 1344 : public PassWrapper<TestTargetMaterializationWithNoUses, 1345 OperationPass<ModuleOp>> { 1346 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID( 1347 TestTargetMaterializationWithNoUses) 1348 1349 StringRef getArgument() const final { 1350 return "test-target-materialization-with-no-uses"; 1351 } 1352 StringRef getDescription() const final { 1353 return "Test a special case of target materialization in DialectConversion"; 1354 } 1355 1356 void runOnOperation() override { 1357 TypeConverter converter; 1358 converter.addConversion([](Type t) { return t; }); 1359 converter.addConversion([](IntegerType intTy) -> Type { 1360 if (intTy.getWidth() == 16) 1361 return IntegerType::get(intTy.getContext(), 64); 1362 return intTy; 1363 }); 1364 converter.addTargetMaterialization( 1365 [](OpBuilder &builder, Type type, ValueRange inputs, Location loc) { 1366 return builder.create<TestCastOp>(loc, type, inputs).getResult(); 1367 }); 1368 1369 ConversionTarget target(getContext()); 1370 target.addIllegalOp<TestTypeChangerOp>(); 1371 1372 RewritePatternSet patterns(&getContext()); 1373 patterns.add<ForwardOperandPattern>(converter, &getContext()); 1374 1375 if (failed(applyPartialConversion(getOperation(), target, 1376 std::move(patterns)))) 1377 signalPassFailure(); 1378 } 1379 }; 1380 } // namespace 1381 1382 //===----------------------------------------------------------------------===// 1383 // Test Block Merging 1384 //===----------------------------------------------------------------------===// 1385 1386 namespace { 1387 /// A rewriter pattern that tests that blocks can be merged. 1388 struct TestMergeBlock : public OpConversionPattern<TestMergeBlocksOp> { 1389 using OpConversionPattern<TestMergeBlocksOp>::OpConversionPattern; 1390 1391 LogicalResult 1392 matchAndRewrite(TestMergeBlocksOp op, OpAdaptor adaptor, 1393 ConversionPatternRewriter &rewriter) const final { 1394 Block &firstBlock = op.getBody().front(); 1395 Operation *branchOp = firstBlock.getTerminator(); 1396 Block *secondBlock = &*(std::next(op.getBody().begin())); 1397 auto succOperands = branchOp->getOperands(); 1398 SmallVector<Value, 2> replacements(succOperands); 1399 rewriter.eraseOp(branchOp); 1400 rewriter.mergeBlocks(secondBlock, &firstBlock, replacements); 1401 rewriter.updateRootInPlace(op, [] {}); 1402 return success(); 1403 } 1404 }; 1405 1406 /// A rewrite pattern to tests the undo mechanism of blocks being merged. 1407 struct TestUndoBlocksMerge : public ConversionPattern { 1408 TestUndoBlocksMerge(MLIRContext *ctx) 1409 : ConversionPattern("test.undo_blocks_merge", /*benefit=*/1, ctx) {} 1410 LogicalResult 1411 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 1412 ConversionPatternRewriter &rewriter) const final { 1413 Block &firstBlock = op->getRegion(0).front(); 1414 Operation *branchOp = firstBlock.getTerminator(); 1415 Block *secondBlock = &*(std::next(op->getRegion(0).begin())); 1416 rewriter.setInsertionPointToStart(secondBlock); 1417 rewriter.create<ILLegalOpF>(op->getLoc(), rewriter.getF32Type()); 1418 auto succOperands = branchOp->getOperands(); 1419 SmallVector<Value, 2> replacements(succOperands); 1420 rewriter.eraseOp(branchOp); 1421 rewriter.mergeBlocks(secondBlock, &firstBlock, replacements); 1422 rewriter.updateRootInPlace(op, [] {}); 1423 return success(); 1424 } 1425 }; 1426 1427 /// A rewrite mechanism to inline the body of the op into its parent, when both 1428 /// ops can have a single block. 1429 struct TestMergeSingleBlockOps 1430 : public OpConversionPattern<SingleBlockImplicitTerminatorOp> { 1431 using OpConversionPattern< 1432 SingleBlockImplicitTerminatorOp>::OpConversionPattern; 1433 1434 LogicalResult 1435 matchAndRewrite(SingleBlockImplicitTerminatorOp op, OpAdaptor adaptor, 1436 ConversionPatternRewriter &rewriter) const final { 1437 SingleBlockImplicitTerminatorOp parentOp = 1438 op->getParentOfType<SingleBlockImplicitTerminatorOp>(); 1439 if (!parentOp) 1440 return failure(); 1441 Block &innerBlock = op.getRegion().front(); 1442 TerminatorOp innerTerminator = 1443 cast<TerminatorOp>(innerBlock.getTerminator()); 1444 rewriter.mergeBlockBefore(&innerBlock, op); 1445 rewriter.eraseOp(innerTerminator); 1446 rewriter.eraseOp(op); 1447 rewriter.updateRootInPlace(op, [] {}); 1448 return success(); 1449 } 1450 }; 1451 1452 struct TestMergeBlocksPatternDriver 1453 : public PassWrapper<TestMergeBlocksPatternDriver, 1454 OperationPass<ModuleOp>> { 1455 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestMergeBlocksPatternDriver) 1456 1457 StringRef getArgument() const final { return "test-merge-blocks"; } 1458 StringRef getDescription() const final { 1459 return "Test Merging operation in ConversionPatternRewriter"; 1460 } 1461 void runOnOperation() override { 1462 MLIRContext *context = &getContext(); 1463 mlir::RewritePatternSet patterns(context); 1464 patterns.add<TestMergeBlock, TestUndoBlocksMerge, TestMergeSingleBlockOps>( 1465 context); 1466 ConversionTarget target(*context); 1467 target.addLegalOp<func::FuncOp, ModuleOp, TerminatorOp, TestBranchOp, 1468 TestTypeConsumerOp, TestTypeProducerOp, TestReturnOp>(); 1469 target.addIllegalOp<ILLegalOpF>(); 1470 1471 /// Expect the op to have a single block after legalization. 1472 target.addDynamicallyLegalOp<TestMergeBlocksOp>( 1473 [&](TestMergeBlocksOp op) -> bool { 1474 return llvm::hasSingleElement(op.getBody()); 1475 }); 1476 1477 /// Only allow `test.br` within test.merge_blocks op. 1478 target.addDynamicallyLegalOp<TestBranchOp>([&](TestBranchOp op) -> bool { 1479 return op->getParentOfType<TestMergeBlocksOp>(); 1480 }); 1481 1482 /// Expect that all nested test.SingleBlockImplicitTerminator ops are 1483 /// inlined. 1484 target.addDynamicallyLegalOp<SingleBlockImplicitTerminatorOp>( 1485 [&](SingleBlockImplicitTerminatorOp op) -> bool { 1486 return !op->getParentOfType<SingleBlockImplicitTerminatorOp>(); 1487 }); 1488 1489 DenseSet<Operation *> unlegalizedOps; 1490 (void)applyPartialConversion(getOperation(), target, std::move(patterns), 1491 &unlegalizedOps); 1492 for (auto *op : unlegalizedOps) 1493 op->emitRemark() << "op '" << op->getName() << "' is not legalizable"; 1494 } 1495 }; 1496 } // namespace 1497 1498 //===----------------------------------------------------------------------===// 1499 // Test Selective Replacement 1500 //===----------------------------------------------------------------------===// 1501 1502 namespace { 1503 /// A rewrite mechanism to inline the body of the op into its parent, when both 1504 /// ops can have a single block. 1505 struct TestSelectiveOpReplacementPattern : public OpRewritePattern<TestCastOp> { 1506 using OpRewritePattern<TestCastOp>::OpRewritePattern; 1507 1508 LogicalResult matchAndRewrite(TestCastOp op, 1509 PatternRewriter &rewriter) const final { 1510 if (op.getNumOperands() != 2) 1511 return failure(); 1512 OperandRange operands = op.getOperands(); 1513 1514 // Replace non-terminator uses with the first operand. 1515 rewriter.replaceOpWithIf(op, operands[0], [](OpOperand &operand) { 1516 return operand.getOwner()->hasTrait<OpTrait::IsTerminator>(); 1517 }); 1518 // Replace everything else with the second operand if the operation isn't 1519 // dead. 1520 rewriter.replaceOp(op, op.getOperand(1)); 1521 return success(); 1522 } 1523 }; 1524 1525 struct TestSelectiveReplacementPatternDriver 1526 : public PassWrapper<TestSelectiveReplacementPatternDriver, 1527 OperationPass<>> { 1528 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID( 1529 TestSelectiveReplacementPatternDriver) 1530 1531 StringRef getArgument() const final { 1532 return "test-pattern-selective-replacement"; 1533 } 1534 StringRef getDescription() const final { 1535 return "Test selective replacement in the PatternRewriter"; 1536 } 1537 void runOnOperation() override { 1538 MLIRContext *context = &getContext(); 1539 mlir::RewritePatternSet patterns(context); 1540 patterns.add<TestSelectiveOpReplacementPattern>(context); 1541 (void)applyPatternsAndFoldGreedily(getOperation()->getRegions(), 1542 std::move(patterns)); 1543 } 1544 }; 1545 } // namespace 1546 1547 //===----------------------------------------------------------------------===// 1548 // PassRegistration 1549 //===----------------------------------------------------------------------===// 1550 1551 namespace mlir { 1552 namespace test { 1553 void registerPatternsTestPass() { 1554 PassRegistration<TestReturnTypeDriver>(); 1555 1556 PassRegistration<TestDerivedAttributeDriver>(); 1557 1558 PassRegistration<TestPatternDriver>(); 1559 PassRegistration<TestStrictPatternDriver>(); 1560 1561 PassRegistration<TestLegalizePatternDriver>([] { 1562 return std::make_unique<TestLegalizePatternDriver>(legalizerConversionMode); 1563 }); 1564 1565 PassRegistration<TestRemappedValue>(); 1566 1567 PassRegistration<TestUnknownRootOpDriver>(); 1568 1569 PassRegistration<TestTypeConversionDriver>(); 1570 PassRegistration<TestTargetMaterializationWithNoUses>(); 1571 1572 PassRegistration<TestRewriteDynamicOpDriver>(); 1573 1574 PassRegistration<TestMergeBlocksPatternDriver>(); 1575 PassRegistration<TestSelectiveReplacementPatternDriver>(); 1576 } 1577 } // namespace test 1578 } // namespace mlir 1579