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