1 //===- TestDialect.cpp - MLIR Dialect for Testing -------------------------===// 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 "TestAttributes.h" 11 #include "TestInterfaces.h" 12 #include "TestTypes.h" 13 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 14 #include "mlir/Dialect/DLTI/DLTI.h" 15 #include "mlir/Dialect/Func/IR/FuncOps.h" 16 #include "mlir/Dialect/Tensor/IR/Tensor.h" 17 #include "mlir/IR/BuiltinOps.h" 18 #include "mlir/IR/DialectImplementation.h" 19 #include "mlir/IR/ExtensibleDialect.h" 20 #include "mlir/IR/PatternMatch.h" 21 #include "mlir/IR/TypeUtilities.h" 22 #include "mlir/IR/Verifier.h" 23 #include "mlir/Reducer/ReductionPatternInterface.h" 24 #include "mlir/Transforms/FoldUtils.h" 25 #include "mlir/Transforms/InliningUtils.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSwitch.h" 28 29 // Include this before the using namespace lines below to 30 // test that we don't have namespace dependencies. 31 #include "TestOpsDialect.cpp.inc" 32 33 using namespace mlir; 34 using namespace test; 35 36 void test::registerTestDialect(DialectRegistry ®istry) { 37 registry.insert<TestDialect>(); 38 } 39 40 //===----------------------------------------------------------------------===// 41 // TestDialect Interfaces 42 //===----------------------------------------------------------------------===// 43 44 namespace { 45 46 /// Testing the correctness of some traits. 47 static_assert( 48 llvm::is_detected<OpTrait::has_implicit_terminator_t, 49 SingleBlockImplicitTerminatorOp>::value, 50 "has_implicit_terminator_t does not match SingleBlockImplicitTerminatorOp"); 51 static_assert(OpTrait::hasSingleBlockImplicitTerminator< 52 SingleBlockImplicitTerminatorOp>::value, 53 "hasSingleBlockImplicitTerminator does not match " 54 "SingleBlockImplicitTerminatorOp"); 55 56 // Test support for interacting with the AsmPrinter. 57 struct TestOpAsmInterface : public OpAsmDialectInterface { 58 using OpAsmDialectInterface::OpAsmDialectInterface; 59 60 AliasResult getAlias(Attribute attr, raw_ostream &os) const final { 61 StringAttr strAttr = attr.dyn_cast<StringAttr>(); 62 if (!strAttr) 63 return AliasResult::NoAlias; 64 65 // Check the contents of the string attribute to see what the test alias 66 // should be named. 67 Optional<StringRef> aliasName = 68 StringSwitch<Optional<StringRef>>(strAttr.getValue()) 69 .Case("alias_test:dot_in_name", StringRef("test.alias")) 70 .Case("alias_test:trailing_digit", StringRef("test_alias0")) 71 .Case("alias_test:prefixed_digit", StringRef("0_test_alias")) 72 .Case("alias_test:sanitize_conflict_a", 73 StringRef("test_alias_conflict0")) 74 .Case("alias_test:sanitize_conflict_b", 75 StringRef("test_alias_conflict0_")) 76 .Case("alias_test:tensor_encoding", StringRef("test_encoding")) 77 .Default(llvm::None); 78 if (!aliasName) 79 return AliasResult::NoAlias; 80 81 os << *aliasName; 82 return AliasResult::FinalAlias; 83 } 84 85 AliasResult getAlias(Type type, raw_ostream &os) const final { 86 if (auto tupleType = type.dyn_cast<TupleType>()) { 87 if (tupleType.size() > 0 && 88 llvm::all_of(tupleType.getTypes(), [](Type elemType) { 89 return elemType.isa<SimpleAType>(); 90 })) { 91 os << "test_tuple"; 92 return AliasResult::FinalAlias; 93 } 94 } 95 if (auto intType = type.dyn_cast<TestIntegerType>()) { 96 if (intType.getSignedness() == 97 TestIntegerType::SignednessSemantics::Unsigned && 98 intType.getWidth() == 8) { 99 os << "test_ui8"; 100 return AliasResult::FinalAlias; 101 } 102 } 103 return AliasResult::NoAlias; 104 } 105 }; 106 107 struct TestDialectFoldInterface : public DialectFoldInterface { 108 using DialectFoldInterface::DialectFoldInterface; 109 110 /// Registered hook to check if the given region, which is attached to an 111 /// operation that is *not* isolated from above, should be used when 112 /// materializing constants. 113 bool shouldMaterializeInto(Region *region) const final { 114 // If this is a one region operation, then insert into it. 115 return isa<OneRegionOp>(region->getParentOp()); 116 } 117 }; 118 119 /// This class defines the interface for handling inlining with standard 120 /// operations. 121 struct TestInlinerInterface : public DialectInlinerInterface { 122 using DialectInlinerInterface::DialectInlinerInterface; 123 124 //===--------------------------------------------------------------------===// 125 // Analysis Hooks 126 //===--------------------------------------------------------------------===// 127 128 bool isLegalToInline(Operation *call, Operation *callable, 129 bool wouldBeCloned) const final { 130 // Don't allow inlining calls that are marked `noinline`. 131 return !call->hasAttr("noinline"); 132 } 133 bool isLegalToInline(Region *, Region *, bool, 134 BlockAndValueMapping &) const final { 135 // Inlining into test dialect regions is legal. 136 return true; 137 } 138 bool isLegalToInline(Operation *, Region *, bool, 139 BlockAndValueMapping &) const final { 140 return true; 141 } 142 143 bool shouldAnalyzeRecursively(Operation *op) const final { 144 // Analyze recursively if this is not a functional region operation, it 145 // froms a separate functional scope. 146 return !isa<FunctionalRegionOp>(op); 147 } 148 149 //===--------------------------------------------------------------------===// 150 // Transformation Hooks 151 //===--------------------------------------------------------------------===// 152 153 /// Handle the given inlined terminator by replacing it with a new operation 154 /// as necessary. 155 void handleTerminator(Operation *op, 156 ArrayRef<Value> valuesToRepl) const final { 157 // Only handle "test.return" here. 158 auto returnOp = dyn_cast<TestReturnOp>(op); 159 if (!returnOp) 160 return; 161 162 // Replace the values directly with the return operands. 163 assert(returnOp.getNumOperands() == valuesToRepl.size()); 164 for (const auto &it : llvm::enumerate(returnOp.getOperands())) 165 valuesToRepl[it.index()].replaceAllUsesWith(it.value()); 166 } 167 168 /// Attempt to materialize a conversion for a type mismatch between a call 169 /// from this dialect, and a callable region. This method should generate an 170 /// operation that takes 'input' as the only operand, and produces a single 171 /// result of 'resultType'. If a conversion can not be generated, nullptr 172 /// should be returned. 173 Operation *materializeCallConversion(OpBuilder &builder, Value input, 174 Type resultType, 175 Location conversionLoc) const final { 176 // Only allow conversion for i16/i32 types. 177 if (!(resultType.isSignlessInteger(16) || 178 resultType.isSignlessInteger(32)) || 179 !(input.getType().isSignlessInteger(16) || 180 input.getType().isSignlessInteger(32))) 181 return nullptr; 182 return builder.create<TestCastOp>(conversionLoc, resultType, input); 183 } 184 185 void processInlinedCallBlocks( 186 Operation *call, 187 iterator_range<Region::iterator> inlinedBlocks) const final { 188 if (!isa<ConversionCallOp>(call)) 189 return; 190 191 // Set attributed on all ops in the inlined blocks. 192 for (Block &block : inlinedBlocks) { 193 block.walk([&](Operation *op) { 194 op->setAttr("inlined_conversion", UnitAttr::get(call->getContext())); 195 }); 196 } 197 } 198 }; 199 200 struct TestReductionPatternInterface : public DialectReductionPatternInterface { 201 public: 202 TestReductionPatternInterface(Dialect *dialect) 203 : DialectReductionPatternInterface(dialect) {} 204 205 void populateReductionPatterns(RewritePatternSet &patterns) const final { 206 populateTestReductionPatterns(patterns); 207 } 208 }; 209 210 } // namespace 211 212 //===----------------------------------------------------------------------===// 213 // Dynamic operations 214 //===----------------------------------------------------------------------===// 215 216 std::unique_ptr<DynamicOpDefinition> getDynamicGenericOp(TestDialect *dialect) { 217 return DynamicOpDefinition::get( 218 "dynamic_generic", dialect, [](Operation *op) { return success(); }, 219 [](Operation *op) { return success(); }); 220 } 221 222 std::unique_ptr<DynamicOpDefinition> 223 getDynamicOneOperandTwoResultsOp(TestDialect *dialect) { 224 return DynamicOpDefinition::get( 225 "dynamic_one_operand_two_results", dialect, 226 [](Operation *op) { 227 if (op->getNumOperands() != 1) { 228 op->emitOpError() 229 << "expected 1 operand, but had " << op->getNumOperands(); 230 return failure(); 231 } 232 if (op->getNumResults() != 2) { 233 op->emitOpError() 234 << "expected 2 results, but had " << op->getNumResults(); 235 return failure(); 236 } 237 return success(); 238 }, 239 [](Operation *op) { return success(); }); 240 } 241 242 std::unique_ptr<DynamicOpDefinition> 243 getDynamicCustomParserPrinterOp(TestDialect *dialect) { 244 auto verifier = [](Operation *op) { 245 if (op->getNumOperands() == 0 && op->getNumResults() == 0) 246 return success(); 247 op->emitError() << "operation should have no operands and no results"; 248 return failure(); 249 }; 250 auto regionVerifier = [](Operation *op) { return success(); }; 251 252 auto parser = [](OpAsmParser &parser, OperationState &state) { 253 return parser.parseKeyword("custom_keyword"); 254 }; 255 256 auto printer = [](Operation *op, OpAsmPrinter &printer, llvm::StringRef) { 257 printer << op->getName() << " custom_keyword"; 258 }; 259 260 return DynamicOpDefinition::get("dynamic_custom_parser_printer", dialect, 261 verifier, regionVerifier, parser, printer); 262 } 263 264 //===----------------------------------------------------------------------===// 265 // TestDialect 266 //===----------------------------------------------------------------------===// 267 268 static void testSideEffectOpGetEffect( 269 Operation *op, 270 SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>> &effects); 271 272 // This is the implementation of a dialect fallback for `TestEffectOpInterface`. 273 struct TestOpEffectInterfaceFallback 274 : public TestEffectOpInterface::FallbackModel< 275 TestOpEffectInterfaceFallback> { 276 static bool classof(Operation *op) { 277 bool isSupportedOp = 278 op->getName().getStringRef() == "test.unregistered_side_effect_op"; 279 assert(isSupportedOp && "Unexpected dispatch"); 280 return isSupportedOp; 281 } 282 283 void 284 getEffects(Operation *op, 285 SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>> 286 &effects) const { 287 testSideEffectOpGetEffect(op, effects); 288 } 289 }; 290 291 void TestDialect::initialize() { 292 registerAttributes(); 293 registerTypes(); 294 addOperations< 295 #define GET_OP_LIST 296 #include "TestOps.cpp.inc" 297 >(); 298 registerDynamicOp(getDynamicGenericOp(this)); 299 registerDynamicOp(getDynamicOneOperandTwoResultsOp(this)); 300 registerDynamicOp(getDynamicCustomParserPrinterOp(this)); 301 302 addInterfaces<TestOpAsmInterface, TestDialectFoldInterface, 303 TestInlinerInterface, TestReductionPatternInterface>(); 304 allowUnknownOperations(); 305 306 // Instantiate our fallback op interface that we'll use on specific 307 // unregistered op. 308 fallbackEffectOpInterfaces = new TestOpEffectInterfaceFallback; 309 } 310 TestDialect::~TestDialect() { 311 delete static_cast<TestOpEffectInterfaceFallback *>( 312 fallbackEffectOpInterfaces); 313 } 314 315 Operation *TestDialect::materializeConstant(OpBuilder &builder, Attribute value, 316 Type type, Location loc) { 317 return builder.create<TestOpConstant>(loc, type, value); 318 } 319 320 ::mlir::LogicalResult FormatInferType2Op::inferReturnTypes( 321 ::mlir::MLIRContext *context, ::llvm::Optional<::mlir::Location> location, 322 ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, 323 ::mlir::RegionRange regions, 324 ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) { 325 inferredReturnTypes.assign({::mlir::IntegerType::get(context, 16)}); 326 return ::mlir::success(); 327 } 328 329 void *TestDialect::getRegisteredInterfaceForOp(TypeID typeID, 330 OperationName opName) { 331 if (opName.getIdentifier() == "test.unregistered_side_effect_op" && 332 typeID == TypeID::get<TestEffectOpInterface>()) 333 return fallbackEffectOpInterfaces; 334 return nullptr; 335 } 336 337 LogicalResult TestDialect::verifyOperationAttribute(Operation *op, 338 NamedAttribute namedAttr) { 339 if (namedAttr.getName() == "test.invalid_attr") 340 return op->emitError() << "invalid to use 'test.invalid_attr'"; 341 return success(); 342 } 343 344 LogicalResult TestDialect::verifyRegionArgAttribute(Operation *op, 345 unsigned regionIndex, 346 unsigned argIndex, 347 NamedAttribute namedAttr) { 348 if (namedAttr.getName() == "test.invalid_attr") 349 return op->emitError() << "invalid to use 'test.invalid_attr'"; 350 return success(); 351 } 352 353 LogicalResult 354 TestDialect::verifyRegionResultAttribute(Operation *op, unsigned regionIndex, 355 unsigned resultIndex, 356 NamedAttribute namedAttr) { 357 if (namedAttr.getName() == "test.invalid_attr") 358 return op->emitError() << "invalid to use 'test.invalid_attr'"; 359 return success(); 360 } 361 362 Optional<Dialect::ParseOpHook> 363 TestDialect::getParseOperationHook(StringRef opName) const { 364 if (opName == "test.dialect_custom_printer") { 365 return ParseOpHook{[](OpAsmParser &parser, OperationState &state) { 366 return parser.parseKeyword("custom_format"); 367 }}; 368 } 369 if (opName == "test.dialect_custom_format_fallback") { 370 return ParseOpHook{[](OpAsmParser &parser, OperationState &state) { 371 return parser.parseKeyword("custom_format_fallback"); 372 }}; 373 } 374 return None; 375 } 376 377 llvm::unique_function<void(Operation *, OpAsmPrinter &)> 378 TestDialect::getOperationPrinter(Operation *op) const { 379 StringRef opName = op->getName().getStringRef(); 380 if (opName == "test.dialect_custom_printer") { 381 return [](Operation *op, OpAsmPrinter &printer) { 382 printer.getStream() << " custom_format"; 383 }; 384 } 385 if (opName == "test.dialect_custom_format_fallback") { 386 return [](Operation *op, OpAsmPrinter &printer) { 387 printer.getStream() << " custom_format_fallback"; 388 }; 389 } 390 return {}; 391 } 392 393 //===----------------------------------------------------------------------===// 394 // TestBranchOp 395 //===----------------------------------------------------------------------===// 396 397 SuccessorOperands TestBranchOp::getSuccessorOperands(unsigned index) { 398 assert(index == 0 && "invalid successor index"); 399 return SuccessorOperands(getTargetOperandsMutable()); 400 } 401 402 //===----------------------------------------------------------------------===// 403 // TestProducingBranchOp 404 //===----------------------------------------------------------------------===// 405 406 SuccessorOperands TestProducingBranchOp::getSuccessorOperands(unsigned index) { 407 assert(index <= 1 && "invalid successor index"); 408 if (index == 1) 409 return SuccessorOperands(getFirstOperandsMutable()); 410 return SuccessorOperands(getSecondOperandsMutable()); 411 } 412 413 //===----------------------------------------------------------------------===// 414 // TestProducingBranchOp 415 //===----------------------------------------------------------------------===// 416 417 SuccessorOperands TestInternalBranchOp::getSuccessorOperands(unsigned index) { 418 assert(index <= 1 && "invalid successor index"); 419 if (index == 0) 420 return SuccessorOperands(0, getSuccessOperandsMutable()); 421 return SuccessorOperands(1, getErrorOperandsMutable()); 422 } 423 424 //===----------------------------------------------------------------------===// 425 // TestDialectCanonicalizerOp 426 //===----------------------------------------------------------------------===// 427 428 static LogicalResult 429 dialectCanonicalizationPattern(TestDialectCanonicalizerOp op, 430 PatternRewriter &rewriter) { 431 rewriter.replaceOpWithNewOp<arith::ConstantOp>( 432 op, rewriter.getI32IntegerAttr(42)); 433 return success(); 434 } 435 436 void TestDialect::getCanonicalizationPatterns( 437 RewritePatternSet &results) const { 438 results.add(&dialectCanonicalizationPattern); 439 } 440 441 //===----------------------------------------------------------------------===// 442 // TestCallOp 443 //===----------------------------------------------------------------------===// 444 445 LogicalResult TestCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) { 446 // Check that the callee attribute was specified. 447 auto fnAttr = (*this)->getAttrOfType<FlatSymbolRefAttr>("callee"); 448 if (!fnAttr) 449 return emitOpError("requires a 'callee' symbol reference attribute"); 450 if (!symbolTable.lookupNearestSymbolFrom<FunctionOpInterface>(*this, fnAttr)) 451 return emitOpError() << "'" << fnAttr.getValue() 452 << "' does not reference a valid function"; 453 return success(); 454 } 455 456 //===----------------------------------------------------------------------===// 457 // TestFoldToCallOp 458 //===----------------------------------------------------------------------===// 459 460 namespace { 461 struct FoldToCallOpPattern : public OpRewritePattern<FoldToCallOp> { 462 using OpRewritePattern<FoldToCallOp>::OpRewritePattern; 463 464 LogicalResult matchAndRewrite(FoldToCallOp op, 465 PatternRewriter &rewriter) const override { 466 rewriter.replaceOpWithNewOp<func::CallOp>(op, TypeRange(), 467 op.getCalleeAttr(), ValueRange()); 468 return success(); 469 } 470 }; 471 } // namespace 472 473 void FoldToCallOp::getCanonicalizationPatterns(RewritePatternSet &results, 474 MLIRContext *context) { 475 results.add<FoldToCallOpPattern>(context); 476 } 477 478 //===----------------------------------------------------------------------===// 479 // Test Format* operations 480 //===----------------------------------------------------------------------===// 481 482 //===----------------------------------------------------------------------===// 483 // Parsing 484 485 static ParseResult parseCustomOptionalOperand( 486 OpAsmParser &parser, Optional<OpAsmParser::UnresolvedOperand> &optOperand) { 487 if (succeeded(parser.parseOptionalLParen())) { 488 optOperand.emplace(); 489 if (parser.parseOperand(*optOperand) || parser.parseRParen()) 490 return failure(); 491 } 492 return success(); 493 } 494 495 static ParseResult parseCustomDirectiveOperands( 496 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand, 497 Optional<OpAsmParser::UnresolvedOperand> &optOperand, 498 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands) { 499 if (parser.parseOperand(operand)) 500 return failure(); 501 if (succeeded(parser.parseOptionalComma())) { 502 optOperand.emplace(); 503 if (parser.parseOperand(*optOperand)) 504 return failure(); 505 } 506 if (parser.parseArrow() || parser.parseLParen() || 507 parser.parseOperandList(varOperands) || parser.parseRParen()) 508 return failure(); 509 return success(); 510 } 511 static ParseResult 512 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType, 513 Type &optOperandType, 514 SmallVectorImpl<Type> &varOperandTypes) { 515 if (parser.parseColon()) 516 return failure(); 517 518 if (parser.parseType(operandType)) 519 return failure(); 520 if (succeeded(parser.parseOptionalComma())) { 521 if (parser.parseType(optOperandType)) 522 return failure(); 523 } 524 if (parser.parseArrow() || parser.parseLParen() || 525 parser.parseTypeList(varOperandTypes) || parser.parseRParen()) 526 return failure(); 527 return success(); 528 } 529 static ParseResult 530 parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType, 531 Type optOperandType, 532 const SmallVectorImpl<Type> &varOperandTypes) { 533 if (parser.parseKeyword("type_refs_capture")) 534 return failure(); 535 536 Type operandType2, optOperandType2; 537 SmallVector<Type, 1> varOperandTypes2; 538 if (parseCustomDirectiveResults(parser, operandType2, optOperandType2, 539 varOperandTypes2)) 540 return failure(); 541 542 if (operandType != operandType2 || optOperandType != optOperandType2 || 543 varOperandTypes != varOperandTypes2) 544 return failure(); 545 546 return success(); 547 } 548 static ParseResult parseCustomDirectiveOperandsAndTypes( 549 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand, 550 Optional<OpAsmParser::UnresolvedOperand> &optOperand, 551 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands, 552 Type &operandType, Type &optOperandType, 553 SmallVectorImpl<Type> &varOperandTypes) { 554 if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) || 555 parseCustomDirectiveResults(parser, operandType, optOperandType, 556 varOperandTypes)) 557 return failure(); 558 return success(); 559 } 560 static ParseResult parseCustomDirectiveRegions( 561 OpAsmParser &parser, Region ®ion, 562 SmallVectorImpl<std::unique_ptr<Region>> &varRegions) { 563 if (parser.parseRegion(region)) 564 return failure(); 565 if (failed(parser.parseOptionalComma())) 566 return success(); 567 std::unique_ptr<Region> varRegion = std::make_unique<Region>(); 568 if (parser.parseRegion(*varRegion)) 569 return failure(); 570 varRegions.emplace_back(std::move(varRegion)); 571 return success(); 572 } 573 static ParseResult 574 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor, 575 SmallVectorImpl<Block *> &varSuccessors) { 576 if (parser.parseSuccessor(successor)) 577 return failure(); 578 if (failed(parser.parseOptionalComma())) 579 return success(); 580 Block *varSuccessor; 581 if (parser.parseSuccessor(varSuccessor)) 582 return failure(); 583 varSuccessors.append(2, varSuccessor); 584 return success(); 585 } 586 static ParseResult parseCustomDirectiveAttributes(OpAsmParser &parser, 587 IntegerAttr &attr, 588 IntegerAttr &optAttr) { 589 if (parser.parseAttribute(attr)) 590 return failure(); 591 if (succeeded(parser.parseOptionalComma())) { 592 if (parser.parseAttribute(optAttr)) 593 return failure(); 594 } 595 return success(); 596 } 597 598 static ParseResult parseCustomDirectiveAttrDict(OpAsmParser &parser, 599 NamedAttrList &attrs) { 600 return parser.parseOptionalAttrDict(attrs); 601 } 602 static ParseResult parseCustomDirectiveOptionalOperandRef( 603 OpAsmParser &parser, Optional<OpAsmParser::UnresolvedOperand> &optOperand) { 604 int64_t operandCount = 0; 605 if (parser.parseInteger(operandCount)) 606 return failure(); 607 bool expectedOptionalOperand = operandCount == 0; 608 return success(expectedOptionalOperand != optOperand.hasValue()); 609 } 610 611 //===----------------------------------------------------------------------===// 612 // Printing 613 614 static void printCustomOptionalOperand(OpAsmPrinter &printer, Operation *, 615 Value optOperand) { 616 if (optOperand) 617 printer << "(" << optOperand << ") "; 618 } 619 620 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Operation *, 621 Value operand, Value optOperand, 622 OperandRange varOperands) { 623 printer << operand; 624 if (optOperand) 625 printer << ", " << optOperand; 626 printer << " -> (" << varOperands << ")"; 627 } 628 static void printCustomDirectiveResults(OpAsmPrinter &printer, Operation *, 629 Type operandType, Type optOperandType, 630 TypeRange varOperandTypes) { 631 printer << " : " << operandType; 632 if (optOperandType) 633 printer << ", " << optOperandType; 634 printer << " -> (" << varOperandTypes << ")"; 635 } 636 static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer, 637 Operation *op, Type operandType, 638 Type optOperandType, 639 TypeRange varOperandTypes) { 640 printer << " type_refs_capture "; 641 printCustomDirectiveResults(printer, op, operandType, optOperandType, 642 varOperandTypes); 643 } 644 static void printCustomDirectiveOperandsAndTypes( 645 OpAsmPrinter &printer, Operation *op, Value operand, Value optOperand, 646 OperandRange varOperands, Type operandType, Type optOperandType, 647 TypeRange varOperandTypes) { 648 printCustomDirectiveOperands(printer, op, operand, optOperand, varOperands); 649 printCustomDirectiveResults(printer, op, operandType, optOperandType, 650 varOperandTypes); 651 } 652 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Operation *, 653 Region ®ion, 654 MutableArrayRef<Region> varRegions) { 655 printer.printRegion(region); 656 if (!varRegions.empty()) { 657 printer << ", "; 658 for (Region ®ion : varRegions) 659 printer.printRegion(region); 660 } 661 } 662 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer, Operation *, 663 Block *successor, 664 SuccessorRange varSuccessors) { 665 printer << successor; 666 if (!varSuccessors.empty()) 667 printer << ", " << varSuccessors.front(); 668 } 669 static void printCustomDirectiveAttributes(OpAsmPrinter &printer, Operation *, 670 Attribute attribute, 671 Attribute optAttribute) { 672 printer << attribute; 673 if (optAttribute) 674 printer << ", " << optAttribute; 675 } 676 677 static void printCustomDirectiveAttrDict(OpAsmPrinter &printer, Operation *op, 678 DictionaryAttr attrs) { 679 printer.printOptionalAttrDict(attrs.getValue()); 680 } 681 682 static void printCustomDirectiveOptionalOperandRef(OpAsmPrinter &printer, 683 Operation *op, 684 Value optOperand) { 685 printer << (optOperand ? "1" : "0"); 686 } 687 688 //===----------------------------------------------------------------------===// 689 // Test IsolatedRegionOp - parse passthrough region arguments. 690 //===----------------------------------------------------------------------===// 691 692 ParseResult IsolatedRegionOp::parse(OpAsmParser &parser, 693 OperationState &result) { 694 // Parse the input operand. 695 OpAsmParser::Argument argInfo; 696 argInfo.type = parser.getBuilder().getIndexType(); 697 if (parser.parseOperand(argInfo.ssaName) || 698 parser.resolveOperand(argInfo.ssaName, argInfo.type, result.operands)) 699 return failure(); 700 701 // Parse the body region, and reuse the operand info as the argument info. 702 Region *body = result.addRegion(); 703 return parser.parseRegion(*body, argInfo, /*enableNameShadowing=*/true); 704 } 705 706 void IsolatedRegionOp::print(OpAsmPrinter &p) { 707 p << "test.isolated_region "; 708 p.printOperand(getOperand()); 709 p.shadowRegionArgs(getRegion(), getOperand()); 710 p << ' '; 711 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false); 712 } 713 714 //===----------------------------------------------------------------------===// 715 // Test SSACFGRegionOp 716 //===----------------------------------------------------------------------===// 717 718 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) { 719 return RegionKind::SSACFG; 720 } 721 722 //===----------------------------------------------------------------------===// 723 // Test GraphRegionOp 724 //===----------------------------------------------------------------------===// 725 726 ParseResult GraphRegionOp::parse(OpAsmParser &parser, OperationState &result) { 727 // Parse the body region, and reuse the operand info as the argument info. 728 Region *body = result.addRegion(); 729 return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}); 730 } 731 732 void GraphRegionOp::print(OpAsmPrinter &p) { 733 p << "test.graph_region "; 734 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false); 735 } 736 737 RegionKind GraphRegionOp::getRegionKind(unsigned index) { 738 return RegionKind::Graph; 739 } 740 741 //===----------------------------------------------------------------------===// 742 // Test AffineScopeOp 743 //===----------------------------------------------------------------------===// 744 745 ParseResult AffineScopeOp::parse(OpAsmParser &parser, OperationState &result) { 746 // Parse the body region, and reuse the operand info as the argument info. 747 Region *body = result.addRegion(); 748 return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}); 749 } 750 751 void AffineScopeOp::print(OpAsmPrinter &p) { 752 p << "test.affine_scope "; 753 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false); 754 } 755 756 //===----------------------------------------------------------------------===// 757 // Test parser. 758 //===----------------------------------------------------------------------===// 759 760 ParseResult ParseIntegerLiteralOp::parse(OpAsmParser &parser, 761 OperationState &result) { 762 if (parser.parseOptionalColon()) 763 return success(); 764 uint64_t numResults; 765 if (parser.parseInteger(numResults)) 766 return failure(); 767 768 IndexType type = parser.getBuilder().getIndexType(); 769 for (unsigned i = 0; i < numResults; ++i) 770 result.addTypes(type); 771 return success(); 772 } 773 774 void ParseIntegerLiteralOp::print(OpAsmPrinter &p) { 775 if (unsigned numResults = getNumResults()) 776 p << " : " << numResults; 777 } 778 779 ParseResult ParseWrappedKeywordOp::parse(OpAsmParser &parser, 780 OperationState &result) { 781 StringRef keyword; 782 if (parser.parseKeyword(&keyword)) 783 return failure(); 784 result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword)); 785 return success(); 786 } 787 788 void ParseWrappedKeywordOp::print(OpAsmPrinter &p) { p << " " << getKeyword(); } 789 790 //===----------------------------------------------------------------------===// 791 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`. 792 793 ParseResult WrappingRegionOp::parse(OpAsmParser &parser, 794 OperationState &result) { 795 if (parser.parseKeyword("wraps")) 796 return failure(); 797 798 // Parse the wrapped op in a region 799 Region &body = *result.addRegion(); 800 body.push_back(new Block); 801 Block &block = body.back(); 802 Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin()); 803 if (!wrappedOp) 804 return failure(); 805 806 // Create a return terminator in the inner region, pass as operand to the 807 // terminator the returned values from the wrapped operation. 808 SmallVector<Value, 8> returnOperands(wrappedOp->getResults()); 809 OpBuilder builder(parser.getContext()); 810 builder.setInsertionPointToEnd(&block); 811 builder.create<TestReturnOp>(wrappedOp->getLoc(), returnOperands); 812 813 // Get the results type for the wrapping op from the terminator operands. 814 Operation &returnOp = body.back().back(); 815 result.types.append(returnOp.operand_type_begin(), 816 returnOp.operand_type_end()); 817 818 // Use the location of the wrapped op for the "test.wrapping_region" op. 819 result.location = wrappedOp->getLoc(); 820 821 return success(); 822 } 823 824 void WrappingRegionOp::print(OpAsmPrinter &p) { 825 p << " wraps "; 826 p.printGenericOp(&getRegion().front().front()); 827 } 828 829 //===----------------------------------------------------------------------===// 830 // Test PrettyPrintedRegionOp - exercising the following parser APIs 831 // parseGenericOperationAfterOpName 832 // parseCustomOperationName 833 //===----------------------------------------------------------------------===// 834 835 ParseResult PrettyPrintedRegionOp::parse(OpAsmParser &parser, 836 OperationState &result) { 837 838 SMLoc loc = parser.getCurrentLocation(); 839 Location currLocation = parser.getEncodedSourceLoc(loc); 840 841 // Parse the operands. 842 SmallVector<OpAsmParser::UnresolvedOperand, 2> operands; 843 if (parser.parseOperandList(operands)) 844 return failure(); 845 846 // Check if we are parsing the pretty-printed version 847 // test.pretty_printed_region start <inner-op> end : <functional-type> 848 // Else fallback to parsing the "non pretty-printed" version. 849 if (!succeeded(parser.parseOptionalKeyword("start"))) 850 return parser.parseGenericOperationAfterOpName( 851 result, llvm::makeArrayRef(operands)); 852 853 FailureOr<OperationName> parseOpNameInfo = parser.parseCustomOperationName(); 854 if (failed(parseOpNameInfo)) 855 return failure(); 856 857 StringAttr innerOpName = parseOpNameInfo->getIdentifier(); 858 859 FunctionType opFntype; 860 Optional<Location> explicitLoc; 861 if (parser.parseKeyword("end") || parser.parseColon() || 862 parser.parseType(opFntype) || 863 parser.parseOptionalLocationSpecifier(explicitLoc)) 864 return failure(); 865 866 // If location of the op is explicitly provided, then use it; Else use 867 // the parser's current location. 868 Location opLoc = explicitLoc.getValueOr(currLocation); 869 870 // Derive the SSA-values for op's operands. 871 if (parser.resolveOperands(operands, opFntype.getInputs(), loc, 872 result.operands)) 873 return failure(); 874 875 // Add a region for op. 876 Region ®ion = *result.addRegion(); 877 878 // Create a basic-block inside op's region. 879 Block &block = region.emplaceBlock(); 880 881 // Create and insert an "inner-op" operation in the block. 882 // Just for testing purposes, we can assume that inner op is a binary op with 883 // result and operand types all same as the test-op's first operand. 884 Type innerOpType = opFntype.getInput(0); 885 Value lhs = block.addArgument(innerOpType, opLoc); 886 Value rhs = block.addArgument(innerOpType, opLoc); 887 888 OpBuilder builder(parser.getBuilder().getContext()); 889 builder.setInsertionPointToStart(&block); 890 891 Operation *innerOp = 892 builder.create(opLoc, innerOpName, /*operands=*/{lhs, rhs}, innerOpType); 893 894 // Insert a return statement in the block returning the inner-op's result. 895 builder.create<TestReturnOp>(innerOp->getLoc(), innerOp->getResults()); 896 897 // Populate the op operation-state with result-type and location. 898 result.addTypes(opFntype.getResults()); 899 result.location = innerOp->getLoc(); 900 901 return success(); 902 } 903 904 void PrettyPrintedRegionOp::print(OpAsmPrinter &p) { 905 p << ' '; 906 p.printOperands(getOperands()); 907 908 Operation &innerOp = getRegion().front().front(); 909 // Assuming that region has a single non-terminator inner-op, if the inner-op 910 // meets some criteria (which in this case is a simple one based on the name 911 // of inner-op), then we can print the entire region in a succinct way. 912 // Here we assume that the prototype of "special.op" can be trivially derived 913 // while parsing it back. 914 if (innerOp.getName().getStringRef().equals("special.op")) { 915 p << " start special.op end"; 916 } else { 917 p << " ("; 918 p.printRegion(getRegion()); 919 p << ")"; 920 } 921 922 p << " : "; 923 p.printFunctionalType(*this); 924 } 925 926 //===----------------------------------------------------------------------===// 927 // Test PolyForOp - parse list of region arguments. 928 //===----------------------------------------------------------------------===// 929 930 ParseResult PolyForOp::parse(OpAsmParser &parser, OperationState &result) { 931 SmallVector<OpAsmParser::Argument, 4> ivsInfo; 932 // Parse list of region arguments without a delimiter. 933 if (parser.parseArgumentList(ivsInfo, OpAsmParser::Delimiter::None)) 934 return failure(); 935 936 // Parse the body region. 937 Region *body = result.addRegion(); 938 for (auto &iv : ivsInfo) 939 iv.type = parser.getBuilder().getIndexType(); 940 return parser.parseRegion(*body, ivsInfo); 941 } 942 943 void PolyForOp::print(OpAsmPrinter &p) { p.printGenericOp(*this); } 944 945 void PolyForOp::getAsmBlockArgumentNames(Region ®ion, 946 OpAsmSetValueNameFn setNameFn) { 947 auto arrayAttr = getOperation()->getAttrOfType<ArrayAttr>("arg_names"); 948 if (!arrayAttr) 949 return; 950 auto args = getRegion().front().getArguments(); 951 auto e = std::min(arrayAttr.size(), args.size()); 952 for (unsigned i = 0; i < e; ++i) { 953 if (auto strAttr = arrayAttr[i].dyn_cast<StringAttr>()) 954 setNameFn(args[i], strAttr.getValue()); 955 } 956 } 957 958 //===----------------------------------------------------------------------===// 959 // Test removing op with inner ops. 960 //===----------------------------------------------------------------------===// 961 962 namespace { 963 struct TestRemoveOpWithInnerOps 964 : public OpRewritePattern<TestOpWithRegionPattern> { 965 using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern; 966 967 void initialize() { setDebugName("TestRemoveOpWithInnerOps"); } 968 969 LogicalResult matchAndRewrite(TestOpWithRegionPattern op, 970 PatternRewriter &rewriter) const override { 971 rewriter.eraseOp(op); 972 return success(); 973 } 974 }; 975 } // namespace 976 977 void TestOpWithRegionPattern::getCanonicalizationPatterns( 978 RewritePatternSet &results, MLIRContext *context) { 979 results.add<TestRemoveOpWithInnerOps>(context); 980 } 981 982 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) { 983 return getOperand(); 984 } 985 986 OpFoldResult TestOpConstant::fold(ArrayRef<Attribute> operands) { 987 return getValue(); 988 } 989 990 LogicalResult TestOpWithVariadicResultsAndFolder::fold( 991 ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) { 992 for (Value input : this->getOperands()) { 993 results.push_back(input); 994 } 995 return success(); 996 } 997 998 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) { 999 assert(operands.size() == 1); 1000 if (operands.front()) { 1001 (*this)->setAttr("attr", operands.front()); 1002 return getResult(); 1003 } 1004 return {}; 1005 } 1006 1007 OpFoldResult TestPassthroughFold::fold(ArrayRef<Attribute> operands) { 1008 return getOperand(); 1009 } 1010 1011 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes( 1012 MLIRContext *, Optional<Location> location, ValueRange operands, 1013 DictionaryAttr attributes, RegionRange regions, 1014 SmallVectorImpl<Type> &inferredReturnTypes) { 1015 if (operands[0].getType() != operands[1].getType()) { 1016 return emitOptionalError(location, "operand type mismatch ", 1017 operands[0].getType(), " vs ", 1018 operands[1].getType()); 1019 } 1020 inferredReturnTypes.assign({operands[0].getType()}); 1021 return success(); 1022 } 1023 1024 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents( 1025 MLIRContext *context, Optional<Location> location, ValueShapeRange operands, 1026 DictionaryAttr attributes, RegionRange regions, 1027 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { 1028 // Create return type consisting of the last element of the first operand. 1029 auto operandType = operands.front().getType(); 1030 auto sval = operandType.dyn_cast<ShapedType>(); 1031 if (!sval) { 1032 return emitOptionalError(location, "only shaped type operands allowed"); 1033 } 1034 int64_t dim = 1035 sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize; 1036 auto type = IntegerType::get(context, 17); 1037 inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type)); 1038 return success(); 1039 } 1040 1041 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes( 1042 OpBuilder &builder, ValueRange operands, 1043 llvm::SmallVectorImpl<Value> &shapes) { 1044 shapes = SmallVector<Value, 1>{ 1045 builder.createOrFold<tensor::DimOp>(getLoc(), operands.front(), 0)}; 1046 return success(); 1047 } 1048 1049 LogicalResult OpWithResultShapeInterfaceOp::reifyReturnTypeShapes( 1050 OpBuilder &builder, ValueRange operands, 1051 llvm::SmallVectorImpl<Value> &shapes) { 1052 Location loc = getLoc(); 1053 shapes.reserve(operands.size()); 1054 for (Value operand : llvm::reverse(operands)) { 1055 auto rank = operand.getType().cast<RankedTensorType>().getRank(); 1056 auto currShape = llvm::to_vector<4>( 1057 llvm::map_range(llvm::seq<int64_t>(0, rank), [&](int64_t dim) -> Value { 1058 return builder.createOrFold<tensor::DimOp>(loc, operand, dim); 1059 })); 1060 shapes.push_back(builder.create<tensor::FromElementsOp>( 1061 getLoc(), RankedTensorType::get({rank}, builder.getIndexType()), 1062 currShape)); 1063 } 1064 return success(); 1065 } 1066 1067 LogicalResult OpWithResultShapePerDimInterfaceOp::reifyResultShapes( 1068 OpBuilder &builder, ReifiedRankedShapedTypeDims &shapes) { 1069 Location loc = getLoc(); 1070 shapes.reserve(getNumOperands()); 1071 for (Value operand : llvm::reverse(getOperands())) { 1072 auto currShape = llvm::to_vector<4>(llvm::map_range( 1073 llvm::seq<int64_t>( 1074 0, operand.getType().cast<RankedTensorType>().getRank()), 1075 [&](int64_t dim) -> Value { 1076 return builder.createOrFold<tensor::DimOp>(loc, operand, dim); 1077 })); 1078 shapes.emplace_back(std::move(currShape)); 1079 } 1080 return success(); 1081 } 1082 1083 //===----------------------------------------------------------------------===// 1084 // Test SideEffect interfaces 1085 //===----------------------------------------------------------------------===// 1086 1087 namespace { 1088 /// A test resource for side effects. 1089 struct TestResource : public SideEffects::Resource::Base<TestResource> { 1090 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestResource) 1091 1092 StringRef getName() final { return "<Test>"; } 1093 }; 1094 } // namespace 1095 1096 static void testSideEffectOpGetEffect( 1097 Operation *op, 1098 SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>> 1099 &effects) { 1100 auto effectsAttr = op->getAttrOfType<AffineMapAttr>("effect_parameter"); 1101 if (!effectsAttr) 1102 return; 1103 1104 effects.emplace_back(TestEffects::Concrete::get(), effectsAttr); 1105 } 1106 1107 void SideEffectOp::getEffects( 1108 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) { 1109 // Check for an effects attribute on the op instance. 1110 ArrayAttr effectsAttr = (*this)->getAttrOfType<ArrayAttr>("effects"); 1111 if (!effectsAttr) 1112 return; 1113 1114 // If there is one, it is an array of dictionary attributes that hold 1115 // information on the effects of this operation. 1116 for (Attribute element : effectsAttr) { 1117 DictionaryAttr effectElement = element.cast<DictionaryAttr>(); 1118 1119 // Get the specific memory effect. 1120 MemoryEffects::Effect *effect = 1121 StringSwitch<MemoryEffects::Effect *>( 1122 effectElement.get("effect").cast<StringAttr>().getValue()) 1123 .Case("allocate", MemoryEffects::Allocate::get()) 1124 .Case("free", MemoryEffects::Free::get()) 1125 .Case("read", MemoryEffects::Read::get()) 1126 .Case("write", MemoryEffects::Write::get()); 1127 1128 // Check for a non-default resource to use. 1129 SideEffects::Resource *resource = SideEffects::DefaultResource::get(); 1130 if (effectElement.get("test_resource")) 1131 resource = TestResource::get(); 1132 1133 // Check for a result to affect. 1134 if (effectElement.get("on_result")) 1135 effects.emplace_back(effect, getResult(), resource); 1136 else if (Attribute ref = effectElement.get("on_reference")) 1137 effects.emplace_back(effect, ref.cast<SymbolRefAttr>(), resource); 1138 else 1139 effects.emplace_back(effect, resource); 1140 } 1141 } 1142 1143 void SideEffectOp::getEffects( 1144 SmallVectorImpl<TestEffects::EffectInstance> &effects) { 1145 testSideEffectOpGetEffect(getOperation(), effects); 1146 } 1147 1148 //===----------------------------------------------------------------------===// 1149 // StringAttrPrettyNameOp 1150 //===----------------------------------------------------------------------===// 1151 1152 // This op has fancy handling of its SSA result name. 1153 ParseResult StringAttrPrettyNameOp::parse(OpAsmParser &parser, 1154 OperationState &result) { 1155 // Add the result types. 1156 for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) 1157 result.addTypes(parser.getBuilder().getIntegerType(32)); 1158 1159 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 1160 return failure(); 1161 1162 // If the attribute dictionary contains no 'names' attribute, infer it from 1163 // the SSA name (if specified). 1164 bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) { 1165 return attr.getName() == "names"; 1166 }); 1167 1168 // If there was no name specified, check to see if there was a useful name 1169 // specified in the asm file. 1170 if (hadNames || parser.getNumResults() == 0) 1171 return success(); 1172 1173 SmallVector<StringRef, 4> names; 1174 auto *context = result.getContext(); 1175 1176 for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) { 1177 auto resultName = parser.getResultName(i); 1178 StringRef nameStr; 1179 if (!resultName.first.empty() && !isdigit(resultName.first[0])) 1180 nameStr = resultName.first; 1181 1182 names.push_back(nameStr); 1183 } 1184 1185 auto namesAttr = parser.getBuilder().getStrArrayAttr(names); 1186 result.attributes.push_back({StringAttr::get(context, "names"), namesAttr}); 1187 return success(); 1188 } 1189 1190 void StringAttrPrettyNameOp::print(OpAsmPrinter &p) { 1191 // Note that we only need to print the "name" attribute if the asmprinter 1192 // result name disagrees with it. This can happen in strange cases, e.g. 1193 // when there are conflicts. 1194 bool namesDisagree = getNames().size() != getNumResults(); 1195 1196 SmallString<32> resultNameStr; 1197 for (size_t i = 0, e = getNumResults(); i != e && !namesDisagree; ++i) { 1198 resultNameStr.clear(); 1199 llvm::raw_svector_ostream tmpStream(resultNameStr); 1200 p.printOperand(getResult(i), tmpStream); 1201 1202 auto expectedName = getNames()[i].dyn_cast<StringAttr>(); 1203 if (!expectedName || 1204 tmpStream.str().drop_front() != expectedName.getValue()) { 1205 namesDisagree = true; 1206 } 1207 } 1208 1209 if (namesDisagree) 1210 p.printOptionalAttrDictWithKeyword((*this)->getAttrs()); 1211 else 1212 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), {"names"}); 1213 } 1214 1215 // We set the SSA name in the asm syntax to the contents of the name 1216 // attribute. 1217 void StringAttrPrettyNameOp::getAsmResultNames( 1218 function_ref<void(Value, StringRef)> setNameFn) { 1219 1220 auto value = getNames(); 1221 for (size_t i = 0, e = value.size(); i != e; ++i) 1222 if (auto str = value[i].dyn_cast<StringAttr>()) 1223 if (!str.getValue().empty()) 1224 setNameFn(getResult(i), str.getValue()); 1225 } 1226 1227 void CustomResultsNameOp::getAsmResultNames( 1228 function_ref<void(Value, StringRef)> setNameFn) { 1229 ArrayAttr value = getNames(); 1230 for (size_t i = 0, e = value.size(); i != e; ++i) 1231 if (auto str = value[i].dyn_cast<StringAttr>()) 1232 if (!str.getValue().empty()) 1233 setNameFn(getResult(i), str.getValue()); 1234 } 1235 1236 //===----------------------------------------------------------------------===// 1237 // ResultTypeWithTraitOp 1238 //===----------------------------------------------------------------------===// 1239 1240 LogicalResult ResultTypeWithTraitOp::verify() { 1241 if ((*this)->getResultTypes()[0].hasTrait<TypeTrait::TestTypeTrait>()) 1242 return success(); 1243 return emitError("result type should have trait 'TestTypeTrait'"); 1244 } 1245 1246 //===----------------------------------------------------------------------===// 1247 // AttrWithTraitOp 1248 //===----------------------------------------------------------------------===// 1249 1250 LogicalResult AttrWithTraitOp::verify() { 1251 if (getAttr().hasTrait<AttributeTrait::TestAttrTrait>()) 1252 return success(); 1253 return emitError("'attr' attribute should have trait 'TestAttrTrait'"); 1254 } 1255 1256 //===----------------------------------------------------------------------===// 1257 // RegionIfOp 1258 //===----------------------------------------------------------------------===// 1259 1260 void RegionIfOp::print(OpAsmPrinter &p) { 1261 p << " "; 1262 p.printOperands(getOperands()); 1263 p << ": " << getOperandTypes(); 1264 p.printArrowTypeList(getResultTypes()); 1265 p << " then "; 1266 p.printRegion(getThenRegion(), 1267 /*printEntryBlockArgs=*/true, 1268 /*printBlockTerminators=*/true); 1269 p << " else "; 1270 p.printRegion(getElseRegion(), 1271 /*printEntryBlockArgs=*/true, 1272 /*printBlockTerminators=*/true); 1273 p << " join "; 1274 p.printRegion(getJoinRegion(), 1275 /*printEntryBlockArgs=*/true, 1276 /*printBlockTerminators=*/true); 1277 } 1278 1279 ParseResult RegionIfOp::parse(OpAsmParser &parser, OperationState &result) { 1280 SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfos; 1281 SmallVector<Type, 2> operandTypes; 1282 1283 result.regions.reserve(3); 1284 Region *thenRegion = result.addRegion(); 1285 Region *elseRegion = result.addRegion(); 1286 Region *joinRegion = result.addRegion(); 1287 1288 // Parse operand, type and arrow type lists. 1289 if (parser.parseOperandList(operandInfos) || 1290 parser.parseColonTypeList(operandTypes) || 1291 parser.parseArrowTypeList(result.types)) 1292 return failure(); 1293 1294 // Parse all attached regions. 1295 if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) || 1296 parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) || 1297 parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {})) 1298 return failure(); 1299 1300 return parser.resolveOperands(operandInfos, operandTypes, 1301 parser.getCurrentLocation(), result.operands); 1302 } 1303 1304 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) { 1305 assert(index < 2 && "invalid region index"); 1306 return getOperands(); 1307 } 1308 1309 void RegionIfOp::getSuccessorRegions( 1310 Optional<unsigned> index, ArrayRef<Attribute> operands, 1311 SmallVectorImpl<RegionSuccessor> ®ions) { 1312 // We always branch to the join region. 1313 if (index.hasValue()) { 1314 if (index.getValue() < 2) 1315 regions.push_back(RegionSuccessor(&getJoinRegion(), getJoinArgs())); 1316 else 1317 regions.push_back(RegionSuccessor(getResults())); 1318 return; 1319 } 1320 1321 // The then and else regions are the entry regions of this op. 1322 regions.push_back(RegionSuccessor(&getThenRegion(), getThenArgs())); 1323 regions.push_back(RegionSuccessor(&getElseRegion(), getElseArgs())); 1324 } 1325 1326 void RegionIfOp::getRegionInvocationBounds( 1327 ArrayRef<Attribute> operands, 1328 SmallVectorImpl<InvocationBounds> &invocationBounds) { 1329 // Each region is invoked at most once. 1330 invocationBounds.assign(/*NumElts=*/3, /*Elt=*/{0, 1}); 1331 } 1332 1333 //===----------------------------------------------------------------------===// 1334 // AnyCondOp 1335 //===----------------------------------------------------------------------===// 1336 1337 void AnyCondOp::getSuccessorRegions(Optional<unsigned> index, 1338 ArrayRef<Attribute> operands, 1339 SmallVectorImpl<RegionSuccessor> ®ions) { 1340 // The parent op branches into the only region, and the region branches back 1341 // to the parent op. 1342 if (index) 1343 regions.emplace_back(&getRegion()); 1344 else 1345 regions.emplace_back(getResults()); 1346 } 1347 1348 void AnyCondOp::getRegionInvocationBounds( 1349 ArrayRef<Attribute> operands, 1350 SmallVectorImpl<InvocationBounds> &invocationBounds) { 1351 invocationBounds.emplace_back(1, 1); 1352 } 1353 1354 //===----------------------------------------------------------------------===// 1355 // SingleNoTerminatorCustomAsmOp 1356 //===----------------------------------------------------------------------===// 1357 1358 ParseResult SingleNoTerminatorCustomAsmOp::parse(OpAsmParser &parser, 1359 OperationState &state) { 1360 Region *body = state.addRegion(); 1361 if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{})) 1362 return failure(); 1363 return success(); 1364 } 1365 1366 void SingleNoTerminatorCustomAsmOp::print(OpAsmPrinter &printer) { 1367 printer.printRegion( 1368 getRegion(), /*printEntryBlockArgs=*/false, 1369 // This op has a single block without terminators. But explicitly mark 1370 // as not printing block terminators for testing. 1371 /*printBlockTerminators=*/false); 1372 } 1373 1374 //===----------------------------------------------------------------------===// 1375 // TestVerifiersOp 1376 //===----------------------------------------------------------------------===// 1377 1378 LogicalResult TestVerifiersOp::verify() { 1379 if (!getRegion().hasOneBlock()) 1380 return emitOpError("`hasOneBlock` trait hasn't been verified"); 1381 1382 Operation *definingOp = getInput().getDefiningOp(); 1383 if (definingOp && failed(mlir::verify(definingOp))) 1384 return emitOpError("operand hasn't been verified"); 1385 1386 emitRemark("success run of verifier"); 1387 1388 return success(); 1389 } 1390 1391 LogicalResult TestVerifiersOp::verifyRegions() { 1392 if (!getRegion().hasOneBlock()) 1393 return emitOpError("`hasOneBlock` trait hasn't been verified"); 1394 1395 for (Block &block : getRegion()) 1396 for (Operation &op : block) 1397 if (failed(mlir::verify(&op))) 1398 return emitOpError("nested op hasn't been verified"); 1399 1400 emitRemark("success run of region verifier"); 1401 1402 return success(); 1403 } 1404 1405 #include "TestOpEnums.cpp.inc" 1406 #include "TestOpInterfaces.cpp.inc" 1407 #include "TestOpStructs.cpp.inc" 1408 #include "TestTypeInterfaces.cpp.inc" 1409 1410 #define GET_OP_CLASSES 1411 #include "TestOps.cpp.inc" 1412