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 &registry) {
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 // TestProducingBranchOp
346 //===----------------------------------------------------------------------===//
347 
348 Optional<MutableOperandRange>
349 TestProducingBranchOp::getMutableSuccessorOperands(unsigned index) {
350   assert(index <= 1 && "invalid successor index");
351   if (index == 1) {
352     return getFirstOperandsMutable();
353   }
354   return getSecondOperandsMutable();
355 }
356 
357 //===----------------------------------------------------------------------===//
358 // TestDialectCanonicalizerOp
359 //===----------------------------------------------------------------------===//
360 
361 static LogicalResult
362 dialectCanonicalizationPattern(TestDialectCanonicalizerOp op,
363                                PatternRewriter &rewriter) {
364   rewriter.replaceOpWithNewOp<arith::ConstantOp>(
365       op, rewriter.getI32IntegerAttr(42));
366   return success();
367 }
368 
369 void TestDialect::getCanonicalizationPatterns(
370     RewritePatternSet &results) const {
371   results.add(&dialectCanonicalizationPattern);
372 }
373 
374 //===----------------------------------------------------------------------===//
375 // TestCallOp
376 //===----------------------------------------------------------------------===//
377 
378 LogicalResult TestCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
379   // Check that the callee attribute was specified.
380   auto fnAttr = (*this)->getAttrOfType<FlatSymbolRefAttr>("callee");
381   if (!fnAttr)
382     return emitOpError("requires a 'callee' symbol reference attribute");
383   if (!symbolTable.lookupNearestSymbolFrom<FunctionOpInterface>(*this, fnAttr))
384     return emitOpError() << "'" << fnAttr.getValue()
385                          << "' does not reference a valid function";
386   return success();
387 }
388 
389 //===----------------------------------------------------------------------===//
390 // TestFoldToCallOp
391 //===----------------------------------------------------------------------===//
392 
393 namespace {
394 struct FoldToCallOpPattern : public OpRewritePattern<FoldToCallOp> {
395   using OpRewritePattern<FoldToCallOp>::OpRewritePattern;
396 
397   LogicalResult matchAndRewrite(FoldToCallOp op,
398                                 PatternRewriter &rewriter) const override {
399     rewriter.replaceOpWithNewOp<func::CallOp>(op, TypeRange(),
400                                               op.getCalleeAttr(), ValueRange());
401     return success();
402   }
403 };
404 } // namespace
405 
406 void FoldToCallOp::getCanonicalizationPatterns(RewritePatternSet &results,
407                                                MLIRContext *context) {
408   results.add<FoldToCallOpPattern>(context);
409 }
410 
411 //===----------------------------------------------------------------------===//
412 // Test Format* operations
413 //===----------------------------------------------------------------------===//
414 
415 //===----------------------------------------------------------------------===//
416 // Parsing
417 
418 static ParseResult parseCustomOptionalOperand(
419     OpAsmParser &parser, Optional<OpAsmParser::UnresolvedOperand> &optOperand) {
420   if (succeeded(parser.parseOptionalLParen())) {
421     optOperand.emplace();
422     if (parser.parseOperand(*optOperand) || parser.parseRParen())
423       return failure();
424   }
425   return success();
426 }
427 
428 static ParseResult parseCustomDirectiveOperands(
429     OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
430     Optional<OpAsmParser::UnresolvedOperand> &optOperand,
431     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands) {
432   if (parser.parseOperand(operand))
433     return failure();
434   if (succeeded(parser.parseOptionalComma())) {
435     optOperand.emplace();
436     if (parser.parseOperand(*optOperand))
437       return failure();
438   }
439   if (parser.parseArrow() || parser.parseLParen() ||
440       parser.parseOperandList(varOperands) || parser.parseRParen())
441     return failure();
442   return success();
443 }
444 static ParseResult
445 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType,
446                             Type &optOperandType,
447                             SmallVectorImpl<Type> &varOperandTypes) {
448   if (parser.parseColon())
449     return failure();
450 
451   if (parser.parseType(operandType))
452     return failure();
453   if (succeeded(parser.parseOptionalComma())) {
454     if (parser.parseType(optOperandType))
455       return failure();
456   }
457   if (parser.parseArrow() || parser.parseLParen() ||
458       parser.parseTypeList(varOperandTypes) || parser.parseRParen())
459     return failure();
460   return success();
461 }
462 static ParseResult
463 parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType,
464                                  Type optOperandType,
465                                  const SmallVectorImpl<Type> &varOperandTypes) {
466   if (parser.parseKeyword("type_refs_capture"))
467     return failure();
468 
469   Type operandType2, optOperandType2;
470   SmallVector<Type, 1> varOperandTypes2;
471   if (parseCustomDirectiveResults(parser, operandType2, optOperandType2,
472                                   varOperandTypes2))
473     return failure();
474 
475   if (operandType != operandType2 || optOperandType != optOperandType2 ||
476       varOperandTypes != varOperandTypes2)
477     return failure();
478 
479   return success();
480 }
481 static ParseResult parseCustomDirectiveOperandsAndTypes(
482     OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
483     Optional<OpAsmParser::UnresolvedOperand> &optOperand,
484     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands,
485     Type &operandType, Type &optOperandType,
486     SmallVectorImpl<Type> &varOperandTypes) {
487   if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) ||
488       parseCustomDirectiveResults(parser, operandType, optOperandType,
489                                   varOperandTypes))
490     return failure();
491   return success();
492 }
493 static ParseResult parseCustomDirectiveRegions(
494     OpAsmParser &parser, Region &region,
495     SmallVectorImpl<std::unique_ptr<Region>> &varRegions) {
496   if (parser.parseRegion(region))
497     return failure();
498   if (failed(parser.parseOptionalComma()))
499     return success();
500   std::unique_ptr<Region> varRegion = std::make_unique<Region>();
501   if (parser.parseRegion(*varRegion))
502     return failure();
503   varRegions.emplace_back(std::move(varRegion));
504   return success();
505 }
506 static ParseResult
507 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor,
508                                SmallVectorImpl<Block *> &varSuccessors) {
509   if (parser.parseSuccessor(successor))
510     return failure();
511   if (failed(parser.parseOptionalComma()))
512     return success();
513   Block *varSuccessor;
514   if (parser.parseSuccessor(varSuccessor))
515     return failure();
516   varSuccessors.append(2, varSuccessor);
517   return success();
518 }
519 static ParseResult parseCustomDirectiveAttributes(OpAsmParser &parser,
520                                                   IntegerAttr &attr,
521                                                   IntegerAttr &optAttr) {
522   if (parser.parseAttribute(attr))
523     return failure();
524   if (succeeded(parser.parseOptionalComma())) {
525     if (parser.parseAttribute(optAttr))
526       return failure();
527   }
528   return success();
529 }
530 
531 static ParseResult parseCustomDirectiveAttrDict(OpAsmParser &parser,
532                                                 NamedAttrList &attrs) {
533   return parser.parseOptionalAttrDict(attrs);
534 }
535 static ParseResult parseCustomDirectiveOptionalOperandRef(
536     OpAsmParser &parser, Optional<OpAsmParser::UnresolvedOperand> &optOperand) {
537   int64_t operandCount = 0;
538   if (parser.parseInteger(operandCount))
539     return failure();
540   bool expectedOptionalOperand = operandCount == 0;
541   return success(expectedOptionalOperand != optOperand.hasValue());
542 }
543 
544 //===----------------------------------------------------------------------===//
545 // Printing
546 
547 static void printCustomOptionalOperand(OpAsmPrinter &printer, Operation *,
548                                        Value optOperand) {
549   if (optOperand)
550     printer << "(" << optOperand << ") ";
551 }
552 
553 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Operation *,
554                                          Value operand, Value optOperand,
555                                          OperandRange varOperands) {
556   printer << operand;
557   if (optOperand)
558     printer << ", " << optOperand;
559   printer << " -> (" << varOperands << ")";
560 }
561 static void printCustomDirectiveResults(OpAsmPrinter &printer, Operation *,
562                                         Type operandType, Type optOperandType,
563                                         TypeRange varOperandTypes) {
564   printer << " : " << operandType;
565   if (optOperandType)
566     printer << ", " << optOperandType;
567   printer << " -> (" << varOperandTypes << ")";
568 }
569 static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer,
570                                              Operation *op, Type operandType,
571                                              Type optOperandType,
572                                              TypeRange varOperandTypes) {
573   printer << " type_refs_capture ";
574   printCustomDirectiveResults(printer, op, operandType, optOperandType,
575                               varOperandTypes);
576 }
577 static void printCustomDirectiveOperandsAndTypes(
578     OpAsmPrinter &printer, Operation *op, Value operand, Value optOperand,
579     OperandRange varOperands, Type operandType, Type optOperandType,
580     TypeRange varOperandTypes) {
581   printCustomDirectiveOperands(printer, op, operand, optOperand, varOperands);
582   printCustomDirectiveResults(printer, op, operandType, optOperandType,
583                               varOperandTypes);
584 }
585 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Operation *,
586                                         Region &region,
587                                         MutableArrayRef<Region> varRegions) {
588   printer.printRegion(region);
589   if (!varRegions.empty()) {
590     printer << ", ";
591     for (Region &region : varRegions)
592       printer.printRegion(region);
593   }
594 }
595 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer, Operation *,
596                                            Block *successor,
597                                            SuccessorRange varSuccessors) {
598   printer << successor;
599   if (!varSuccessors.empty())
600     printer << ", " << varSuccessors.front();
601 }
602 static void printCustomDirectiveAttributes(OpAsmPrinter &printer, Operation *,
603                                            Attribute attribute,
604                                            Attribute optAttribute) {
605   printer << attribute;
606   if (optAttribute)
607     printer << ", " << optAttribute;
608 }
609 
610 static void printCustomDirectiveAttrDict(OpAsmPrinter &printer, Operation *op,
611                                          DictionaryAttr attrs) {
612   printer.printOptionalAttrDict(attrs.getValue());
613 }
614 
615 static void printCustomDirectiveOptionalOperandRef(OpAsmPrinter &printer,
616                                                    Operation *op,
617                                                    Value optOperand) {
618   printer << (optOperand ? "1" : "0");
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // Test IsolatedRegionOp - parse passthrough region arguments.
623 //===----------------------------------------------------------------------===//
624 
625 ParseResult IsolatedRegionOp::parse(OpAsmParser &parser,
626                                     OperationState &result) {
627   OpAsmParser::UnresolvedOperand argInfo;
628   Type argType = parser.getBuilder().getIndexType();
629 
630   // Parse the input operand.
631   if (parser.parseOperand(argInfo) ||
632       parser.resolveOperand(argInfo, argType, result.operands))
633     return failure();
634 
635   // Parse the body region, and reuse the operand info as the argument info.
636   Region *body = result.addRegion();
637   return parser.parseRegion(*body, argInfo, argType, /*argLocations=*/{},
638                             /*enableNameShadowing=*/true);
639 }
640 
641 void IsolatedRegionOp::print(OpAsmPrinter &p) {
642   p << "test.isolated_region ";
643   p.printOperand(getOperand());
644   p.shadowRegionArgs(getRegion(), getOperand());
645   p << ' ';
646   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
647 }
648 
649 //===----------------------------------------------------------------------===//
650 // Test SSACFGRegionOp
651 //===----------------------------------------------------------------------===//
652 
653 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) {
654   return RegionKind::SSACFG;
655 }
656 
657 //===----------------------------------------------------------------------===//
658 // Test GraphRegionOp
659 //===----------------------------------------------------------------------===//
660 
661 ParseResult GraphRegionOp::parse(OpAsmParser &parser, OperationState &result) {
662   // Parse the body region, and reuse the operand info as the argument info.
663   Region *body = result.addRegion();
664   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
665 }
666 
667 void GraphRegionOp::print(OpAsmPrinter &p) {
668   p << "test.graph_region ";
669   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
670 }
671 
672 RegionKind GraphRegionOp::getRegionKind(unsigned index) {
673   return RegionKind::Graph;
674 }
675 
676 //===----------------------------------------------------------------------===//
677 // Test AffineScopeOp
678 //===----------------------------------------------------------------------===//
679 
680 ParseResult AffineScopeOp::parse(OpAsmParser &parser, OperationState &result) {
681   // Parse the body region, and reuse the operand info as the argument info.
682   Region *body = result.addRegion();
683   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
684 }
685 
686 void AffineScopeOp::print(OpAsmPrinter &p) {
687   p << "test.affine_scope ";
688   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
689 }
690 
691 //===----------------------------------------------------------------------===//
692 // Test parser.
693 //===----------------------------------------------------------------------===//
694 
695 ParseResult ParseIntegerLiteralOp::parse(OpAsmParser &parser,
696                                          OperationState &result) {
697   if (parser.parseOptionalColon())
698     return success();
699   uint64_t numResults;
700   if (parser.parseInteger(numResults))
701     return failure();
702 
703   IndexType type = parser.getBuilder().getIndexType();
704   for (unsigned i = 0; i < numResults; ++i)
705     result.addTypes(type);
706   return success();
707 }
708 
709 void ParseIntegerLiteralOp::print(OpAsmPrinter &p) {
710   if (unsigned numResults = getNumResults())
711     p << " : " << numResults;
712 }
713 
714 ParseResult ParseWrappedKeywordOp::parse(OpAsmParser &parser,
715                                          OperationState &result) {
716   StringRef keyword;
717   if (parser.parseKeyword(&keyword))
718     return failure();
719   result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword));
720   return success();
721 }
722 
723 void ParseWrappedKeywordOp::print(OpAsmPrinter &p) { p << " " << getKeyword(); }
724 
725 //===----------------------------------------------------------------------===//
726 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`.
727 
728 ParseResult WrappingRegionOp::parse(OpAsmParser &parser,
729                                     OperationState &result) {
730   if (parser.parseKeyword("wraps"))
731     return failure();
732 
733   // Parse the wrapped op in a region
734   Region &body = *result.addRegion();
735   body.push_back(new Block);
736   Block &block = body.back();
737   Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
738   if (!wrappedOp)
739     return failure();
740 
741   // Create a return terminator in the inner region, pass as operand to the
742   // terminator the returned values from the wrapped operation.
743   SmallVector<Value, 8> returnOperands(wrappedOp->getResults());
744   OpBuilder builder(parser.getContext());
745   builder.setInsertionPointToEnd(&block);
746   builder.create<TestReturnOp>(wrappedOp->getLoc(), returnOperands);
747 
748   // Get the results type for the wrapping op from the terminator operands.
749   Operation &returnOp = body.back().back();
750   result.types.append(returnOp.operand_type_begin(),
751                       returnOp.operand_type_end());
752 
753   // Use the location of the wrapped op for the "test.wrapping_region" op.
754   result.location = wrappedOp->getLoc();
755 
756   return success();
757 }
758 
759 void WrappingRegionOp::print(OpAsmPrinter &p) {
760   p << " wraps ";
761   p.printGenericOp(&getRegion().front().front());
762 }
763 
764 //===----------------------------------------------------------------------===//
765 // Test PrettyPrintedRegionOp -  exercising the following parser APIs
766 //   parseGenericOperationAfterOpName
767 //   parseCustomOperationName
768 //===----------------------------------------------------------------------===//
769 
770 ParseResult PrettyPrintedRegionOp::parse(OpAsmParser &parser,
771                                          OperationState &result) {
772 
773   SMLoc loc = parser.getCurrentLocation();
774   Location currLocation = parser.getEncodedSourceLoc(loc);
775 
776   // Parse the operands.
777   SmallVector<OpAsmParser::UnresolvedOperand, 2> operands;
778   if (parser.parseOperandList(operands))
779     return failure();
780 
781   // Check if we are parsing the pretty-printed version
782   //  test.pretty_printed_region start <inner-op> end : <functional-type>
783   // Else fallback to parsing the "non pretty-printed" version.
784   if (!succeeded(parser.parseOptionalKeyword("start")))
785     return parser.parseGenericOperationAfterOpName(
786         result, llvm::makeArrayRef(operands));
787 
788   FailureOr<OperationName> parseOpNameInfo = parser.parseCustomOperationName();
789   if (failed(parseOpNameInfo))
790     return failure();
791 
792   StringRef innerOpName = parseOpNameInfo->getStringRef();
793 
794   FunctionType opFntype;
795   Optional<Location> explicitLoc;
796   if (parser.parseKeyword("end") || parser.parseColon() ||
797       parser.parseType(opFntype) ||
798       parser.parseOptionalLocationSpecifier(explicitLoc))
799     return failure();
800 
801   // If location of the op is explicitly provided, then use it; Else use
802   // the parser's current location.
803   Location opLoc = explicitLoc.getValueOr(currLocation);
804 
805   // Derive the SSA-values for op's operands.
806   if (parser.resolveOperands(operands, opFntype.getInputs(), loc,
807                              result.operands))
808     return failure();
809 
810   // Add a region for op.
811   Region &region = *result.addRegion();
812 
813   // Create a basic-block inside op's region.
814   Block &block = region.emplaceBlock();
815 
816   // Create and insert an "inner-op" operation in the block.
817   // Just for testing purposes, we can assume that inner op is a binary op with
818   // result and operand types all same as the test-op's first operand.
819   Type innerOpType = opFntype.getInput(0);
820   Value lhs = block.addArgument(innerOpType, opLoc);
821   Value rhs = block.addArgument(innerOpType, opLoc);
822 
823   OpBuilder builder(parser.getBuilder().getContext());
824   builder.setInsertionPointToStart(&block);
825 
826   OperationState innerOpState(opLoc, innerOpName);
827   innerOpState.operands.push_back(lhs);
828   innerOpState.operands.push_back(rhs);
829   innerOpState.addTypes(innerOpType);
830 
831   Operation *innerOp = builder.createOperation(innerOpState);
832 
833   // Insert a return statement in the block returning the inner-op's result.
834   builder.create<TestReturnOp>(innerOp->getLoc(), innerOp->getResults());
835 
836   // Populate the op operation-state with result-type and location.
837   result.addTypes(opFntype.getResults());
838   result.location = innerOp->getLoc();
839 
840   return success();
841 }
842 
843 void PrettyPrintedRegionOp::print(OpAsmPrinter &p) {
844   p << ' ';
845   p.printOperands(getOperands());
846 
847   Operation &innerOp = getRegion().front().front();
848   // Assuming that region has a single non-terminator inner-op, if the inner-op
849   // meets some criteria (which in this case is a simple one  based on the name
850   // of inner-op), then we can print the entire region in a succinct way.
851   // Here we assume that the prototype of "special.op" can be trivially derived
852   // while parsing it back.
853   if (innerOp.getName().getStringRef().equals("special.op")) {
854     p << " start special.op end";
855   } else {
856     p << " (";
857     p.printRegion(getRegion());
858     p << ")";
859   }
860 
861   p << " : ";
862   p.printFunctionalType(*this);
863 }
864 
865 //===----------------------------------------------------------------------===//
866 // Test PolyForOp - parse list of region arguments.
867 //===----------------------------------------------------------------------===//
868 
869 ParseResult PolyForOp::parse(OpAsmParser &parser, OperationState &result) {
870   SmallVector<OpAsmParser::UnresolvedOperand, 4> ivsInfo;
871   // Parse list of region arguments without a delimiter.
872   if (parser.parseRegionArgumentList(ivsInfo))
873     return failure();
874 
875   // Parse the body region.
876   Region *body = result.addRegion();
877   auto &builder = parser.getBuilder();
878   SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
879   return parser.parseRegion(*body, ivsInfo, argTypes);
880 }
881 
882 void PolyForOp::print(OpAsmPrinter &p) { p.printGenericOp(*this); }
883 
884 void PolyForOp::getAsmBlockArgumentNames(Region &region,
885                                          OpAsmSetValueNameFn setNameFn) {
886   auto arrayAttr = getOperation()->getAttrOfType<ArrayAttr>("arg_names");
887   if (!arrayAttr)
888     return;
889   auto args = getRegion().front().getArguments();
890   auto e = std::min(arrayAttr.size(), args.size());
891   for (unsigned i = 0; i < e; ++i) {
892     if (auto strAttr = arrayAttr[i].dyn_cast<StringAttr>())
893       setNameFn(args[i], strAttr.getValue());
894   }
895 }
896 
897 //===----------------------------------------------------------------------===//
898 // Test removing op with inner ops.
899 //===----------------------------------------------------------------------===//
900 
901 namespace {
902 struct TestRemoveOpWithInnerOps
903     : public OpRewritePattern<TestOpWithRegionPattern> {
904   using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;
905 
906   void initialize() { setDebugName("TestRemoveOpWithInnerOps"); }
907 
908   LogicalResult matchAndRewrite(TestOpWithRegionPattern op,
909                                 PatternRewriter &rewriter) const override {
910     rewriter.eraseOp(op);
911     return success();
912   }
913 };
914 } // namespace
915 
916 void TestOpWithRegionPattern::getCanonicalizationPatterns(
917     RewritePatternSet &results, MLIRContext *context) {
918   results.add<TestRemoveOpWithInnerOps>(context);
919 }
920 
921 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
922   return getOperand();
923 }
924 
925 OpFoldResult TestOpConstant::fold(ArrayRef<Attribute> operands) {
926   return getValue();
927 }
928 
929 LogicalResult TestOpWithVariadicResultsAndFolder::fold(
930     ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) {
931   for (Value input : this->getOperands()) {
932     results.push_back(input);
933   }
934   return success();
935 }
936 
937 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) {
938   assert(operands.size() == 1);
939   if (operands.front()) {
940     (*this)->setAttr("attr", operands.front());
941     return getResult();
942   }
943   return {};
944 }
945 
946 OpFoldResult TestPassthroughFold::fold(ArrayRef<Attribute> operands) {
947   return getOperand();
948 }
949 
950 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes(
951     MLIRContext *, Optional<Location> location, ValueRange operands,
952     DictionaryAttr attributes, RegionRange regions,
953     SmallVectorImpl<Type> &inferredReturnTypes) {
954   if (operands[0].getType() != operands[1].getType()) {
955     return emitOptionalError(location, "operand type mismatch ",
956                              operands[0].getType(), " vs ",
957                              operands[1].getType());
958   }
959   inferredReturnTypes.assign({operands[0].getType()});
960   return success();
961 }
962 
963 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents(
964     MLIRContext *context, Optional<Location> location, ValueShapeRange operands,
965     DictionaryAttr attributes, RegionRange regions,
966     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
967   // Create return type consisting of the last element of the first operand.
968   auto operandType = operands.front().getType();
969   auto sval = operandType.dyn_cast<ShapedType>();
970   if (!sval) {
971     return emitOptionalError(location, "only shaped type operands allowed");
972   }
973   int64_t dim =
974       sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize;
975   auto type = IntegerType::get(context, 17);
976   inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type));
977   return success();
978 }
979 
980 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes(
981     OpBuilder &builder, ValueRange operands,
982     llvm::SmallVectorImpl<Value> &shapes) {
983   shapes = SmallVector<Value, 1>{
984       builder.createOrFold<tensor::DimOp>(getLoc(), operands.front(), 0)};
985   return success();
986 }
987 
988 LogicalResult OpWithResultShapeInterfaceOp::reifyReturnTypeShapes(
989     OpBuilder &builder, ValueRange operands,
990     llvm::SmallVectorImpl<Value> &shapes) {
991   Location loc = getLoc();
992   shapes.reserve(operands.size());
993   for (Value operand : llvm::reverse(operands)) {
994     auto rank = operand.getType().cast<RankedTensorType>().getRank();
995     auto currShape = llvm::to_vector<4>(
996         llvm::map_range(llvm::seq<int64_t>(0, rank), [&](int64_t dim) -> Value {
997           return builder.createOrFold<tensor::DimOp>(loc, operand, dim);
998         }));
999     shapes.push_back(builder.create<tensor::FromElementsOp>(
1000         getLoc(), RankedTensorType::get({rank}, builder.getIndexType()),
1001         currShape));
1002   }
1003   return success();
1004 }
1005 
1006 LogicalResult OpWithResultShapePerDimInterfaceOp::reifyResultShapes(
1007     OpBuilder &builder, ReifiedRankedShapedTypeDims &shapes) {
1008   Location loc = getLoc();
1009   shapes.reserve(getNumOperands());
1010   for (Value operand : llvm::reverse(getOperands())) {
1011     auto currShape = llvm::to_vector<4>(llvm::map_range(
1012         llvm::seq<int64_t>(
1013             0, operand.getType().cast<RankedTensorType>().getRank()),
1014         [&](int64_t dim) -> Value {
1015           return builder.createOrFold<tensor::DimOp>(loc, operand, dim);
1016         }));
1017     shapes.emplace_back(std::move(currShape));
1018   }
1019   return success();
1020 }
1021 
1022 //===----------------------------------------------------------------------===//
1023 // Test SideEffect interfaces
1024 //===----------------------------------------------------------------------===//
1025 
1026 namespace {
1027 /// A test resource for side effects.
1028 struct TestResource : public SideEffects::Resource::Base<TestResource> {
1029   StringRef getName() final { return "<Test>"; }
1030 };
1031 } // namespace
1032 
1033 static void testSideEffectOpGetEffect(
1034     Operation *op,
1035     SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>>
1036         &effects) {
1037   auto effectsAttr = op->getAttrOfType<AffineMapAttr>("effect_parameter");
1038   if (!effectsAttr)
1039     return;
1040 
1041   effects.emplace_back(TestEffects::Concrete::get(), effectsAttr);
1042 }
1043 
1044 void SideEffectOp::getEffects(
1045     SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
1046   // Check for an effects attribute on the op instance.
1047   ArrayAttr effectsAttr = (*this)->getAttrOfType<ArrayAttr>("effects");
1048   if (!effectsAttr)
1049     return;
1050 
1051   // If there is one, it is an array of dictionary attributes that hold
1052   // information on the effects of this operation.
1053   for (Attribute element : effectsAttr) {
1054     DictionaryAttr effectElement = element.cast<DictionaryAttr>();
1055 
1056     // Get the specific memory effect.
1057     MemoryEffects::Effect *effect =
1058         StringSwitch<MemoryEffects::Effect *>(
1059             effectElement.get("effect").cast<StringAttr>().getValue())
1060             .Case("allocate", MemoryEffects::Allocate::get())
1061             .Case("free", MemoryEffects::Free::get())
1062             .Case("read", MemoryEffects::Read::get())
1063             .Case("write", MemoryEffects::Write::get());
1064 
1065     // Check for a non-default resource to use.
1066     SideEffects::Resource *resource = SideEffects::DefaultResource::get();
1067     if (effectElement.get("test_resource"))
1068       resource = TestResource::get();
1069 
1070     // Check for a result to affect.
1071     if (effectElement.get("on_result"))
1072       effects.emplace_back(effect, getResult(), resource);
1073     else if (Attribute ref = effectElement.get("on_reference"))
1074       effects.emplace_back(effect, ref.cast<SymbolRefAttr>(), resource);
1075     else
1076       effects.emplace_back(effect, resource);
1077   }
1078 }
1079 
1080 void SideEffectOp::getEffects(
1081     SmallVectorImpl<TestEffects::EffectInstance> &effects) {
1082   testSideEffectOpGetEffect(getOperation(), effects);
1083 }
1084 
1085 //===----------------------------------------------------------------------===//
1086 // StringAttrPrettyNameOp
1087 //===----------------------------------------------------------------------===//
1088 
1089 // This op has fancy handling of its SSA result name.
1090 ParseResult StringAttrPrettyNameOp::parse(OpAsmParser &parser,
1091                                           OperationState &result) {
1092   // Add the result types.
1093   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i)
1094     result.addTypes(parser.getBuilder().getIntegerType(32));
1095 
1096   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1097     return failure();
1098 
1099   // If the attribute dictionary contains no 'names' attribute, infer it from
1100   // the SSA name (if specified).
1101   bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) {
1102     return attr.getName() == "names";
1103   });
1104 
1105   // If there was no name specified, check to see if there was a useful name
1106   // specified in the asm file.
1107   if (hadNames || parser.getNumResults() == 0)
1108     return success();
1109 
1110   SmallVector<StringRef, 4> names;
1111   auto *context = result.getContext();
1112 
1113   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) {
1114     auto resultName = parser.getResultName(i);
1115     StringRef nameStr;
1116     if (!resultName.first.empty() && !isdigit(resultName.first[0]))
1117       nameStr = resultName.first;
1118 
1119     names.push_back(nameStr);
1120   }
1121 
1122   auto namesAttr = parser.getBuilder().getStrArrayAttr(names);
1123   result.attributes.push_back({StringAttr::get(context, "names"), namesAttr});
1124   return success();
1125 }
1126 
1127 void StringAttrPrettyNameOp::print(OpAsmPrinter &p) {
1128   // Note that we only need to print the "name" attribute if the asmprinter
1129   // result name disagrees with it.  This can happen in strange cases, e.g.
1130   // when there are conflicts.
1131   bool namesDisagree = getNames().size() != getNumResults();
1132 
1133   SmallString<32> resultNameStr;
1134   for (size_t i = 0, e = getNumResults(); i != e && !namesDisagree; ++i) {
1135     resultNameStr.clear();
1136     llvm::raw_svector_ostream tmpStream(resultNameStr);
1137     p.printOperand(getResult(i), tmpStream);
1138 
1139     auto expectedName = getNames()[i].dyn_cast<StringAttr>();
1140     if (!expectedName ||
1141         tmpStream.str().drop_front() != expectedName.getValue()) {
1142       namesDisagree = true;
1143     }
1144   }
1145 
1146   if (namesDisagree)
1147     p.printOptionalAttrDictWithKeyword((*this)->getAttrs());
1148   else
1149     p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), {"names"});
1150 }
1151 
1152 // We set the SSA name in the asm syntax to the contents of the name
1153 // attribute.
1154 void StringAttrPrettyNameOp::getAsmResultNames(
1155     function_ref<void(Value, StringRef)> setNameFn) {
1156 
1157   auto value = getNames();
1158   for (size_t i = 0, e = value.size(); i != e; ++i)
1159     if (auto str = value[i].dyn_cast<StringAttr>())
1160       if (!str.getValue().empty())
1161         setNameFn(getResult(i), str.getValue());
1162 }
1163 
1164 //===----------------------------------------------------------------------===//
1165 // ResultTypeWithTraitOp
1166 //===----------------------------------------------------------------------===//
1167 
1168 LogicalResult ResultTypeWithTraitOp::verify() {
1169   if ((*this)->getResultTypes()[0].hasTrait<TypeTrait::TestTypeTrait>())
1170     return success();
1171   return emitError("result type should have trait 'TestTypeTrait'");
1172 }
1173 
1174 //===----------------------------------------------------------------------===//
1175 // AttrWithTraitOp
1176 //===----------------------------------------------------------------------===//
1177 
1178 LogicalResult AttrWithTraitOp::verify() {
1179   if (getAttr().hasTrait<AttributeTrait::TestAttrTrait>())
1180     return success();
1181   return emitError("'attr' attribute should have trait 'TestAttrTrait'");
1182 }
1183 
1184 //===----------------------------------------------------------------------===//
1185 // RegionIfOp
1186 //===----------------------------------------------------------------------===//
1187 
1188 void RegionIfOp::print(OpAsmPrinter &p) {
1189   p << " ";
1190   p.printOperands(getOperands());
1191   p << ": " << getOperandTypes();
1192   p.printArrowTypeList(getResultTypes());
1193   p << " then ";
1194   p.printRegion(getThenRegion(),
1195                 /*printEntryBlockArgs=*/true,
1196                 /*printBlockTerminators=*/true);
1197   p << " else ";
1198   p.printRegion(getElseRegion(),
1199                 /*printEntryBlockArgs=*/true,
1200                 /*printBlockTerminators=*/true);
1201   p << " join ";
1202   p.printRegion(getJoinRegion(),
1203                 /*printEntryBlockArgs=*/true,
1204                 /*printBlockTerminators=*/true);
1205 }
1206 
1207 ParseResult RegionIfOp::parse(OpAsmParser &parser, OperationState &result) {
1208   SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfos;
1209   SmallVector<Type, 2> operandTypes;
1210 
1211   result.regions.reserve(3);
1212   Region *thenRegion = result.addRegion();
1213   Region *elseRegion = result.addRegion();
1214   Region *joinRegion = result.addRegion();
1215 
1216   // Parse operand, type and arrow type lists.
1217   if (parser.parseOperandList(operandInfos) ||
1218       parser.parseColonTypeList(operandTypes) ||
1219       parser.parseArrowTypeList(result.types))
1220     return failure();
1221 
1222   // Parse all attached regions.
1223   if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) ||
1224       parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) ||
1225       parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {}))
1226     return failure();
1227 
1228   return parser.resolveOperands(operandInfos, operandTypes,
1229                                 parser.getCurrentLocation(), result.operands);
1230 }
1231 
1232 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) {
1233   assert(index < 2 && "invalid region index");
1234   return getOperands();
1235 }
1236 
1237 void RegionIfOp::getSuccessorRegions(
1238     Optional<unsigned> index, ArrayRef<Attribute> operands,
1239     SmallVectorImpl<RegionSuccessor> &regions) {
1240   // We always branch to the join region.
1241   if (index.hasValue()) {
1242     if (index.getValue() < 2)
1243       regions.push_back(RegionSuccessor(&getJoinRegion(), getJoinArgs()));
1244     else
1245       regions.push_back(RegionSuccessor(getResults()));
1246     return;
1247   }
1248 
1249   // The then and else regions are the entry regions of this op.
1250   regions.push_back(RegionSuccessor(&getThenRegion(), getThenArgs()));
1251   regions.push_back(RegionSuccessor(&getElseRegion(), getElseArgs()));
1252 }
1253 
1254 void RegionIfOp::getRegionInvocationBounds(
1255     ArrayRef<Attribute> operands,
1256     SmallVectorImpl<InvocationBounds> &invocationBounds) {
1257   // Each region is invoked at most once.
1258   invocationBounds.assign(/*NumElts=*/3, /*Elt=*/{0, 1});
1259 }
1260 
1261 //===----------------------------------------------------------------------===//
1262 // AnyCondOp
1263 //===----------------------------------------------------------------------===//
1264 
1265 void AnyCondOp::getSuccessorRegions(Optional<unsigned> index,
1266                                     ArrayRef<Attribute> operands,
1267                                     SmallVectorImpl<RegionSuccessor> &regions) {
1268   // The parent op branches into the only region, and the region branches back
1269   // to the parent op.
1270   if (index)
1271     regions.emplace_back(&getRegion());
1272   else
1273     regions.emplace_back(getResults());
1274 }
1275 
1276 void AnyCondOp::getRegionInvocationBounds(
1277     ArrayRef<Attribute> operands,
1278     SmallVectorImpl<InvocationBounds> &invocationBounds) {
1279   invocationBounds.emplace_back(1, 1);
1280 }
1281 
1282 //===----------------------------------------------------------------------===//
1283 // SingleNoTerminatorCustomAsmOp
1284 //===----------------------------------------------------------------------===//
1285 
1286 ParseResult SingleNoTerminatorCustomAsmOp::parse(OpAsmParser &parser,
1287                                                  OperationState &state) {
1288   Region *body = state.addRegion();
1289   if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}))
1290     return failure();
1291   return success();
1292 }
1293 
1294 void SingleNoTerminatorCustomAsmOp::print(OpAsmPrinter &printer) {
1295   printer.printRegion(
1296       getRegion(), /*printEntryBlockArgs=*/false,
1297       // This op has a single block without terminators. But explicitly mark
1298       // as not printing block terminators for testing.
1299       /*printBlockTerminators=*/false);
1300 }
1301 
1302 #include "TestOpEnums.cpp.inc"
1303 #include "TestOpInterfaces.cpp.inc"
1304 #include "TestOpStructs.cpp.inc"
1305 #include "TestTypeInterfaces.cpp.inc"
1306 
1307 #define GET_OP_CLASSES
1308 #include "TestOps.cpp.inc"
1309