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 "TestTypes.h"
11 #include "mlir/Dialect/StandardOps/IR/Ops.h"
12 #include "mlir/IR/DialectImplementation.h"
13 #include "mlir/IR/Function.h"
14 #include "mlir/IR/Module.h"
15 #include "mlir/IR/PatternMatch.h"
16 #include "mlir/IR/TypeUtilities.h"
17 #include "mlir/Transforms/FoldUtils.h"
18 #include "mlir/Transforms/InliningUtils.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/StringSwitch.h"
21 
22 using namespace mlir;
23 
24 void mlir::registerTestDialect(DialectRegistry &registry) {
25   registry.insert<TestDialect>();
26 }
27 
28 //===----------------------------------------------------------------------===//
29 // TestDialect Interfaces
30 //===----------------------------------------------------------------------===//
31 
32 namespace {
33 
34 // Test support for interacting with the AsmPrinter.
35 struct TestOpAsmInterface : public OpAsmDialectInterface {
36   using OpAsmDialectInterface::OpAsmDialectInterface;
37 
38   void getAsmResultNames(Operation *op,
39                          OpAsmSetValueNameFn setNameFn) const final {
40     if (auto asmOp = dyn_cast<AsmDialectInterfaceOp>(op))
41       setNameFn(asmOp, "result");
42   }
43 
44   void getAsmBlockArgumentNames(Block *block,
45                                 OpAsmSetValueNameFn setNameFn) const final {
46     auto op = block->getParentOp();
47     auto arrayAttr = op->getAttrOfType<ArrayAttr>("arg_names");
48     if (!arrayAttr)
49       return;
50     auto args = block->getArguments();
51     auto e = std::min(arrayAttr.size(), args.size());
52     for (unsigned i = 0; i < e; ++i) {
53       if (auto strAttr = arrayAttr[i].dyn_cast<StringAttr>())
54         setNameFn(args[i], strAttr.getValue());
55     }
56   }
57 };
58 
59 struct TestDialectFoldInterface : public DialectFoldInterface {
60   using DialectFoldInterface::DialectFoldInterface;
61 
62   /// Registered hook to check if the given region, which is attached to an
63   /// operation that is *not* isolated from above, should be used when
64   /// materializing constants.
65   bool shouldMaterializeInto(Region *region) const final {
66     // If this is a one region operation, then insert into it.
67     return isa<OneRegionOp>(region->getParentOp());
68   }
69 };
70 
71 /// This class defines the interface for handling inlining with standard
72 /// operations.
73 struct TestInlinerInterface : public DialectInlinerInterface {
74   using DialectInlinerInterface::DialectInlinerInterface;
75 
76   //===--------------------------------------------------------------------===//
77   // Analysis Hooks
78   //===--------------------------------------------------------------------===//
79 
80   bool isLegalToInline(Region *, Region *, BlockAndValueMapping &) const final {
81     // Inlining into test dialect regions is legal.
82     return true;
83   }
84   bool isLegalToInline(Operation *, Region *,
85                        BlockAndValueMapping &) const final {
86     return true;
87   }
88 
89   bool shouldAnalyzeRecursively(Operation *op) const final {
90     // Analyze recursively if this is not a functional region operation, it
91     // froms a separate functional scope.
92     return !isa<FunctionalRegionOp>(op);
93   }
94 
95   //===--------------------------------------------------------------------===//
96   // Transformation Hooks
97   //===--------------------------------------------------------------------===//
98 
99   /// Handle the given inlined terminator by replacing it with a new operation
100   /// as necessary.
101   void handleTerminator(Operation *op,
102                         ArrayRef<Value> valuesToRepl) const final {
103     // Only handle "test.return" here.
104     auto returnOp = dyn_cast<TestReturnOp>(op);
105     if (!returnOp)
106       return;
107 
108     // Replace the values directly with the return operands.
109     assert(returnOp.getNumOperands() == valuesToRepl.size());
110     for (const auto &it : llvm::enumerate(returnOp.getOperands()))
111       valuesToRepl[it.index()].replaceAllUsesWith(it.value());
112   }
113 
114   /// Attempt to materialize a conversion for a type mismatch between a call
115   /// from this dialect, and a callable region. This method should generate an
116   /// operation that takes 'input' as the only operand, and produces a single
117   /// result of 'resultType'. If a conversion can not be generated, nullptr
118   /// should be returned.
119   Operation *materializeCallConversion(OpBuilder &builder, Value input,
120                                        Type resultType,
121                                        Location conversionLoc) const final {
122     // Only allow conversion for i16/i32 types.
123     if (!(resultType.isSignlessInteger(16) ||
124           resultType.isSignlessInteger(32)) ||
125         !(input.getType().isSignlessInteger(16) ||
126           input.getType().isSignlessInteger(32)))
127       return nullptr;
128     return builder.create<TestCastOp>(conversionLoc, resultType, input);
129   }
130 };
131 } // end anonymous namespace
132 
133 //===----------------------------------------------------------------------===//
134 // TestDialect
135 //===----------------------------------------------------------------------===//
136 
137 void TestDialect::initialize() {
138   addOperations<
139 #define GET_OP_LIST
140 #include "TestOps.cpp.inc"
141       >();
142   addInterfaces<TestOpAsmInterface, TestDialectFoldInterface,
143                 TestInlinerInterface>();
144   addTypes<TestType, TestRecursiveType>();
145   allowUnknownOperations();
146 }
147 
148 static Type parseTestType(DialectAsmParser &parser,
149                           llvm::SetVector<Type> &stack) {
150   StringRef typeTag;
151   if (failed(parser.parseKeyword(&typeTag)))
152     return Type();
153 
154   if (typeTag == "test_type")
155     return TestType::get(parser.getBuilder().getContext());
156 
157   if (typeTag != "test_rec")
158     return Type();
159 
160   StringRef name;
161   if (parser.parseLess() || parser.parseKeyword(&name))
162     return Type();
163   auto rec = TestRecursiveType::get(parser.getBuilder().getContext(), name);
164 
165   // If this type already has been parsed above in the stack, expect just the
166   // name.
167   if (stack.contains(rec)) {
168     if (failed(parser.parseGreater()))
169       return Type();
170     return rec;
171   }
172 
173   // Otherwise, parse the body and update the type.
174   if (failed(parser.parseComma()))
175     return Type();
176   stack.insert(rec);
177   Type subtype = parseTestType(parser, stack);
178   stack.pop_back();
179   if (!subtype || failed(parser.parseGreater()) || failed(rec.setBody(subtype)))
180     return Type();
181 
182   return rec;
183 }
184 
185 Type TestDialect::parseType(DialectAsmParser &parser) const {
186   llvm::SetVector<Type> stack;
187   return parseTestType(parser, stack);
188 }
189 
190 static void printTestType(Type type, DialectAsmPrinter &printer,
191                           llvm::SetVector<Type> &stack) {
192   if (type.isa<TestType>()) {
193     printer << "test_type";
194     return;
195   }
196 
197   auto rec = type.cast<TestRecursiveType>();
198   printer << "test_rec<" << rec.getName();
199   if (!stack.contains(rec)) {
200     printer << ", ";
201     stack.insert(rec);
202     printTestType(rec.getBody(), printer, stack);
203     stack.pop_back();
204   }
205   printer << ">";
206 }
207 
208 void TestDialect::printType(Type type, DialectAsmPrinter &printer) const {
209   llvm::SetVector<Type> stack;
210   printTestType(type, printer, stack);
211 }
212 
213 LogicalResult TestDialect::verifyOperationAttribute(Operation *op,
214                                                     NamedAttribute namedAttr) {
215   if (namedAttr.first == "test.invalid_attr")
216     return op->emitError() << "invalid to use 'test.invalid_attr'";
217   return success();
218 }
219 
220 LogicalResult TestDialect::verifyRegionArgAttribute(Operation *op,
221                                                     unsigned regionIndex,
222                                                     unsigned argIndex,
223                                                     NamedAttribute namedAttr) {
224   if (namedAttr.first == "test.invalid_attr")
225     return op->emitError() << "invalid to use 'test.invalid_attr'";
226   return success();
227 }
228 
229 LogicalResult
230 TestDialect::verifyRegionResultAttribute(Operation *op, unsigned regionIndex,
231                                          unsigned resultIndex,
232                                          NamedAttribute namedAttr) {
233   if (namedAttr.first == "test.invalid_attr")
234     return op->emitError() << "invalid to use 'test.invalid_attr'";
235   return success();
236 }
237 
238 //===----------------------------------------------------------------------===//
239 // TestBranchOp
240 //===----------------------------------------------------------------------===//
241 
242 Optional<MutableOperandRange>
243 TestBranchOp::getMutableSuccessorOperands(unsigned index) {
244   assert(index == 0 && "invalid successor index");
245   return targetOperandsMutable();
246 }
247 
248 //===----------------------------------------------------------------------===//
249 // TestFoldToCallOp
250 //===----------------------------------------------------------------------===//
251 
252 namespace {
253 struct FoldToCallOpPattern : public OpRewritePattern<FoldToCallOp> {
254   using OpRewritePattern<FoldToCallOp>::OpRewritePattern;
255 
256   LogicalResult matchAndRewrite(FoldToCallOp op,
257                                 PatternRewriter &rewriter) const override {
258     rewriter.replaceOpWithNewOp<CallOp>(op, ArrayRef<Type>(), op.calleeAttr(),
259                                         ValueRange());
260     return success();
261   }
262 };
263 } // end anonymous namespace
264 
265 void FoldToCallOp::getCanonicalizationPatterns(
266     OwningRewritePatternList &results, MLIRContext *context) {
267   results.insert<FoldToCallOpPattern>(context);
268 }
269 
270 //===----------------------------------------------------------------------===//
271 // Test Format* operations
272 //===----------------------------------------------------------------------===//
273 
274 //===----------------------------------------------------------------------===//
275 // Parsing
276 
277 static ParseResult parseCustomDirectiveOperands(
278     OpAsmParser &parser, OpAsmParser::OperandType &operand,
279     Optional<OpAsmParser::OperandType> &optOperand,
280     SmallVectorImpl<OpAsmParser::OperandType> &varOperands) {
281   if (parser.parseOperand(operand))
282     return failure();
283   if (succeeded(parser.parseOptionalComma())) {
284     optOperand.emplace();
285     if (parser.parseOperand(*optOperand))
286       return failure();
287   }
288   if (parser.parseArrow() || parser.parseLParen() ||
289       parser.parseOperandList(varOperands) || parser.parseRParen())
290     return failure();
291   return success();
292 }
293 static ParseResult
294 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType,
295                             Type &optOperandType,
296                             SmallVectorImpl<Type> &varOperandTypes) {
297   if (parser.parseColon())
298     return failure();
299 
300   if (parser.parseType(operandType))
301     return failure();
302   if (succeeded(parser.parseOptionalComma())) {
303     if (parser.parseType(optOperandType))
304       return failure();
305   }
306   if (parser.parseArrow() || parser.parseLParen() ||
307       parser.parseTypeList(varOperandTypes) || parser.parseRParen())
308     return failure();
309   return success();
310 }
311 static ParseResult
312 parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType,
313                                  Type optOperandType,
314                                  const SmallVectorImpl<Type> &varOperandTypes) {
315   if (parser.parseKeyword("type_refs_capture"))
316     return failure();
317 
318   Type operandType2, optOperandType2;
319   SmallVector<Type, 1> varOperandTypes2;
320   if (parseCustomDirectiveResults(parser, operandType2, optOperandType2,
321                                   varOperandTypes2))
322     return failure();
323 
324   if (operandType != operandType2 || optOperandType != optOperandType2 ||
325       varOperandTypes != varOperandTypes2)
326     return failure();
327 
328   return success();
329 }
330 static ParseResult parseCustomDirectiveOperandsAndTypes(
331     OpAsmParser &parser, OpAsmParser::OperandType &operand,
332     Optional<OpAsmParser::OperandType> &optOperand,
333     SmallVectorImpl<OpAsmParser::OperandType> &varOperands, Type &operandType,
334     Type &optOperandType, SmallVectorImpl<Type> &varOperandTypes) {
335   if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) ||
336       parseCustomDirectiveResults(parser, operandType, optOperandType,
337                                   varOperandTypes))
338     return failure();
339   return success();
340 }
341 static ParseResult parseCustomDirectiveRegions(
342     OpAsmParser &parser, Region &region,
343     SmallVectorImpl<std::unique_ptr<Region>> &varRegions) {
344   if (parser.parseRegion(region))
345     return failure();
346   if (failed(parser.parseOptionalComma()))
347     return success();
348   std::unique_ptr<Region> varRegion = std::make_unique<Region>();
349   if (parser.parseRegion(*varRegion))
350     return failure();
351   varRegions.emplace_back(std::move(varRegion));
352   return success();
353 }
354 static ParseResult
355 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor,
356                                SmallVectorImpl<Block *> &varSuccessors) {
357   if (parser.parseSuccessor(successor))
358     return failure();
359   if (failed(parser.parseOptionalComma()))
360     return success();
361   Block *varSuccessor;
362   if (parser.parseSuccessor(varSuccessor))
363     return failure();
364   varSuccessors.append(2, varSuccessor);
365   return success();
366 }
367 
368 //===----------------------------------------------------------------------===//
369 // Printing
370 
371 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Value operand,
372                                          Value optOperand,
373                                          OperandRange varOperands) {
374   printer << operand;
375   if (optOperand)
376     printer << ", " << optOperand;
377   printer << " -> (" << varOperands << ")";
378 }
379 static void printCustomDirectiveResults(OpAsmPrinter &printer, Type operandType,
380                                         Type optOperandType,
381                                         TypeRange varOperandTypes) {
382   printer << " : " << operandType;
383   if (optOperandType)
384     printer << ", " << optOperandType;
385   printer << " -> (" << varOperandTypes << ")";
386 }
387 static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer,
388                                              Type operandType,
389                                              Type optOperandType,
390                                              TypeRange varOperandTypes) {
391   printer << " type_refs_capture ";
392   printCustomDirectiveResults(printer, operandType, optOperandType,
393                               varOperandTypes);
394 }
395 static void
396 printCustomDirectiveOperandsAndTypes(OpAsmPrinter &printer, Value operand,
397                                      Value optOperand, OperandRange varOperands,
398                                      Type operandType, Type optOperandType,
399                                      TypeRange varOperandTypes) {
400   printCustomDirectiveOperands(printer, operand, optOperand, varOperands);
401   printCustomDirectiveResults(printer, operandType, optOperandType,
402                               varOperandTypes);
403 }
404 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Region &region,
405                                         MutableArrayRef<Region> varRegions) {
406   printer.printRegion(region);
407   if (!varRegions.empty()) {
408     printer << ", ";
409     for (Region &region : varRegions)
410       printer.printRegion(region);
411   }
412 }
413 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer,
414                                            Block *successor,
415                                            SuccessorRange varSuccessors) {
416   printer << successor;
417   if (!varSuccessors.empty())
418     printer << ", " << varSuccessors.front();
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // Test IsolatedRegionOp - parse passthrough region arguments.
423 //===----------------------------------------------------------------------===//
424 
425 static ParseResult parseIsolatedRegionOp(OpAsmParser &parser,
426                                          OperationState &result) {
427   OpAsmParser::OperandType argInfo;
428   Type argType = parser.getBuilder().getIndexType();
429 
430   // Parse the input operand.
431   if (parser.parseOperand(argInfo) ||
432       parser.resolveOperand(argInfo, argType, result.operands))
433     return failure();
434 
435   // Parse the body region, and reuse the operand info as the argument info.
436   Region *body = result.addRegion();
437   return parser.parseRegion(*body, argInfo, argType,
438                             /*enableNameShadowing=*/true);
439 }
440 
441 static void print(OpAsmPrinter &p, IsolatedRegionOp op) {
442   p << "test.isolated_region ";
443   p.printOperand(op.getOperand());
444   p.shadowRegionArgs(op.region(), op.getOperand());
445   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
446 }
447 
448 //===----------------------------------------------------------------------===//
449 // Test SSACFGRegionOp
450 //===----------------------------------------------------------------------===//
451 
452 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) {
453   return RegionKind::SSACFG;
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // Test GraphRegionOp
458 //===----------------------------------------------------------------------===//
459 
460 static ParseResult parseGraphRegionOp(OpAsmParser &parser,
461                                       OperationState &result) {
462   // Parse the body region, and reuse the operand info as the argument info.
463   Region *body = result.addRegion();
464   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
465 }
466 
467 static void print(OpAsmPrinter &p, GraphRegionOp op) {
468   p << "test.graph_region ";
469   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
470 }
471 
472 RegionKind GraphRegionOp::getRegionKind(unsigned index) {
473   return RegionKind::Graph;
474 }
475 
476 //===----------------------------------------------------------------------===//
477 // Test AffineScopeOp
478 //===----------------------------------------------------------------------===//
479 
480 static ParseResult parseAffineScopeOp(OpAsmParser &parser,
481                                       OperationState &result) {
482   // Parse the body region, and reuse the operand info as the argument info.
483   Region *body = result.addRegion();
484   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
485 }
486 
487 static void print(OpAsmPrinter &p, AffineScopeOp op) {
488   p << "test.affine_scope ";
489   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
490 }
491 
492 //===----------------------------------------------------------------------===//
493 // Test parser.
494 //===----------------------------------------------------------------------===//
495 
496 static ParseResult parseWrappedKeywordOp(OpAsmParser &parser,
497                                          OperationState &result) {
498   StringRef keyword;
499   if (parser.parseKeyword(&keyword))
500     return failure();
501   result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword));
502   return success();
503 }
504 
505 static void print(OpAsmPrinter &p, WrappedKeywordOp op) {
506   p << WrappedKeywordOp::getOperationName() << " " << op.keyword();
507 }
508 
509 //===----------------------------------------------------------------------===//
510 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`.
511 
512 static ParseResult parseWrappingRegionOp(OpAsmParser &parser,
513                                          OperationState &result) {
514   if (parser.parseKeyword("wraps"))
515     return failure();
516 
517   // Parse the wrapped op in a region
518   Region &body = *result.addRegion();
519   body.push_back(new Block);
520   Block &block = body.back();
521   Operation *wrapped_op = parser.parseGenericOperation(&block, block.begin());
522   if (!wrapped_op)
523     return failure();
524 
525   // Create a return terminator in the inner region, pass as operand to the
526   // terminator the returned values from the wrapped operation.
527   SmallVector<Value, 8> return_operands(wrapped_op->getResults());
528   OpBuilder builder(parser.getBuilder().getContext());
529   builder.setInsertionPointToEnd(&block);
530   builder.create<TestReturnOp>(wrapped_op->getLoc(), return_operands);
531 
532   // Get the results type for the wrapping op from the terminator operands.
533   Operation &return_op = body.back().back();
534   result.types.append(return_op.operand_type_begin(),
535                       return_op.operand_type_end());
536 
537   // Use the location of the wrapped op for the "test.wrapping_region" op.
538   result.location = wrapped_op->getLoc();
539 
540   return success();
541 }
542 
543 static void print(OpAsmPrinter &p, WrappingRegionOp op) {
544   p << op.getOperationName() << " wraps ";
545   p.printGenericOp(&op.region().front().front());
546 }
547 
548 //===----------------------------------------------------------------------===//
549 // Test PolyForOp - parse list of region arguments.
550 //===----------------------------------------------------------------------===//
551 
552 static ParseResult parsePolyForOp(OpAsmParser &parser, OperationState &result) {
553   SmallVector<OpAsmParser::OperandType, 4> ivsInfo;
554   // Parse list of region arguments without a delimiter.
555   if (parser.parseRegionArgumentList(ivsInfo))
556     return failure();
557 
558   // Parse the body region.
559   Region *body = result.addRegion();
560   auto &builder = parser.getBuilder();
561   SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
562   return parser.parseRegion(*body, ivsInfo, argTypes);
563 }
564 
565 //===----------------------------------------------------------------------===//
566 // Test removing op with inner ops.
567 //===----------------------------------------------------------------------===//
568 
569 namespace {
570 struct TestRemoveOpWithInnerOps
571     : public OpRewritePattern<TestOpWithRegionPattern> {
572   using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;
573 
574   LogicalResult matchAndRewrite(TestOpWithRegionPattern op,
575                                 PatternRewriter &rewriter) const override {
576     rewriter.eraseOp(op);
577     return success();
578   }
579 };
580 } // end anonymous namespace
581 
582 void TestOpWithRegionPattern::getCanonicalizationPatterns(
583     OwningRewritePatternList &results, MLIRContext *context) {
584   results.insert<TestRemoveOpWithInnerOps>(context);
585 }
586 
587 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
588   return operand();
589 }
590 
591 LogicalResult TestOpWithVariadicResultsAndFolder::fold(
592     ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) {
593   for (Value input : this->operands()) {
594     results.push_back(input);
595   }
596   return success();
597 }
598 
599 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) {
600   assert(operands.size() == 1);
601   if (operands.front()) {
602     setAttr("attr", operands.front());
603     return getResult();
604   }
605   return {};
606 }
607 
608 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes(
609     MLIRContext *, Optional<Location> location, ValueRange operands,
610     DictionaryAttr attributes, RegionRange regions,
611     SmallVectorImpl<Type> &inferredReturnTypes) {
612   if (operands[0].getType() != operands[1].getType()) {
613     return emitOptionalError(location, "operand type mismatch ",
614                              operands[0].getType(), " vs ",
615                              operands[1].getType());
616   }
617   inferredReturnTypes.assign({operands[0].getType()});
618   return success();
619 }
620 
621 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents(
622     MLIRContext *context, Optional<Location> location, ValueRange operands,
623     DictionaryAttr attributes, RegionRange regions,
624     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
625   // Create return type consisting of the last element of the first operand.
626   auto operandType = *operands.getTypes().begin();
627   auto sval = operandType.dyn_cast<ShapedType>();
628   if (!sval) {
629     return emitOptionalError(location, "only shaped type operands allowed");
630   }
631   int64_t dim =
632       sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize;
633   auto type = IntegerType::get(17, context);
634   inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type));
635   return success();
636 }
637 
638 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes(
639     OpBuilder &builder, llvm::SmallVectorImpl<Value> &shapes) {
640   shapes = SmallVector<Value, 1>{
641       builder.createOrFold<DimOp>(getLoc(), getOperand(0), 0)};
642   return success();
643 }
644 
645 //===----------------------------------------------------------------------===//
646 // Test SideEffect interfaces
647 //===----------------------------------------------------------------------===//
648 
649 namespace {
650 /// A test resource for side effects.
651 struct TestResource : public SideEffects::Resource::Base<TestResource> {
652   StringRef getName() final { return "<Test>"; }
653 };
654 } // end anonymous namespace
655 
656 void SideEffectOp::getEffects(
657     SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
658   // Check for an effects attribute on the op instance.
659   ArrayAttr effectsAttr = getAttrOfType<ArrayAttr>("effects");
660   if (!effectsAttr)
661     return;
662 
663   // If there is one, it is an array of dictionary attributes that hold
664   // information on the effects of this operation.
665   for (Attribute element : effectsAttr) {
666     DictionaryAttr effectElement = element.cast<DictionaryAttr>();
667 
668     // Get the specific memory effect.
669     MemoryEffects::Effect *effect =
670         llvm::StringSwitch<MemoryEffects::Effect *>(
671             effectElement.get("effect").cast<StringAttr>().getValue())
672             .Case("allocate", MemoryEffects::Allocate::get())
673             .Case("free", MemoryEffects::Free::get())
674             .Case("read", MemoryEffects::Read::get())
675             .Case("write", MemoryEffects::Write::get());
676 
677     // Check for a result to affect.
678     Value value;
679     if (effectElement.get("on_result"))
680       value = getResult();
681 
682     // Check for a non-default resource to use.
683     SideEffects::Resource *resource = SideEffects::DefaultResource::get();
684     if (effectElement.get("test_resource"))
685       resource = TestResource::get();
686 
687     effects.emplace_back(effect, value, resource);
688   }
689 }
690 
691 //===----------------------------------------------------------------------===//
692 // StringAttrPrettyNameOp
693 //===----------------------------------------------------------------------===//
694 
695 // This op has fancy handling of its SSA result name.
696 static ParseResult parseStringAttrPrettyNameOp(OpAsmParser &parser,
697                                                OperationState &result) {
698   // Add the result types.
699   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i)
700     result.addTypes(parser.getBuilder().getIntegerType(32));
701 
702   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
703     return failure();
704 
705   // If the attribute dictionary contains no 'names' attribute, infer it from
706   // the SSA name (if specified).
707   bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) {
708     return attr.first == "names";
709   });
710 
711   // If there was no name specified, check to see if there was a useful name
712   // specified in the asm file.
713   if (hadNames || parser.getNumResults() == 0)
714     return success();
715 
716   SmallVector<StringRef, 4> names;
717   auto *context = result.getContext();
718 
719   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) {
720     auto resultName = parser.getResultName(i);
721     StringRef nameStr;
722     if (!resultName.first.empty() && !isdigit(resultName.first[0]))
723       nameStr = resultName.first;
724 
725     names.push_back(nameStr);
726   }
727 
728   auto namesAttr = parser.getBuilder().getStrArrayAttr(names);
729   result.attributes.push_back({Identifier::get("names", context), namesAttr});
730   return success();
731 }
732 
733 static void print(OpAsmPrinter &p, StringAttrPrettyNameOp op) {
734   p << "test.string_attr_pretty_name";
735 
736   // Note that we only need to print the "name" attribute if the asmprinter
737   // result name disagrees with it.  This can happen in strange cases, e.g.
738   // when there are conflicts.
739   bool namesDisagree = op.names().size() != op.getNumResults();
740 
741   SmallString<32> resultNameStr;
742   for (size_t i = 0, e = op.getNumResults(); i != e && !namesDisagree; ++i) {
743     resultNameStr.clear();
744     llvm::raw_svector_ostream tmpStream(resultNameStr);
745     p.printOperand(op.getResult(i), tmpStream);
746 
747     auto expectedName = op.names()[i].dyn_cast<StringAttr>();
748     if (!expectedName ||
749         tmpStream.str().drop_front() != expectedName.getValue()) {
750       namesDisagree = true;
751     }
752   }
753 
754   if (namesDisagree)
755     p.printOptionalAttrDictWithKeyword(op.getAttrs());
756   else
757     p.printOptionalAttrDictWithKeyword(op.getAttrs(), {"names"});
758 }
759 
760 // We set the SSA name in the asm syntax to the contents of the name
761 // attribute.
762 void StringAttrPrettyNameOp::getAsmResultNames(
763     function_ref<void(Value, StringRef)> setNameFn) {
764 
765   auto value = names();
766   for (size_t i = 0, e = value.size(); i != e; ++i)
767     if (auto str = value[i].dyn_cast<StringAttr>())
768       if (!str.getValue().empty())
769         setNameFn(getResult(i), str.getValue());
770 }
771 
772 //===----------------------------------------------------------------------===//
773 // RegionIfOp
774 //===----------------------------------------------------------------------===//
775 
776 static void print(OpAsmPrinter &p, RegionIfOp op) {
777   p << RegionIfOp::getOperationName() << " ";
778   p.printOperands(op.getOperands());
779   p << ": " << op.getOperandTypes();
780   p.printArrowTypeList(op.getResultTypes());
781   p << " then";
782   p.printRegion(op.thenRegion(),
783                 /*printEntryBlockArgs=*/true,
784                 /*printBlockTerminators=*/true);
785   p << " else";
786   p.printRegion(op.elseRegion(),
787                 /*printEntryBlockArgs=*/true,
788                 /*printBlockTerminators=*/true);
789   p << " join";
790   p.printRegion(op.joinRegion(),
791                 /*printEntryBlockArgs=*/true,
792                 /*printBlockTerminators=*/true);
793 }
794 
795 static ParseResult parseRegionIfOp(OpAsmParser &parser,
796                                    OperationState &result) {
797   SmallVector<OpAsmParser::OperandType, 2> operandInfos;
798   SmallVector<Type, 2> operandTypes;
799 
800   result.regions.reserve(3);
801   Region *thenRegion = result.addRegion();
802   Region *elseRegion = result.addRegion();
803   Region *joinRegion = result.addRegion();
804 
805   // Parse operand, type and arrow type lists.
806   if (parser.parseOperandList(operandInfos) ||
807       parser.parseColonTypeList(operandTypes) ||
808       parser.parseArrowTypeList(result.types))
809     return failure();
810 
811   // Parse all attached regions.
812   if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) ||
813       parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) ||
814       parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {}))
815     return failure();
816 
817   return parser.resolveOperands(operandInfos, operandTypes,
818                                 parser.getCurrentLocation(), result.operands);
819 }
820 
821 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) {
822   assert(index < 2 && "invalid region index");
823   return getOperands();
824 }
825 
826 void RegionIfOp::getSuccessorRegions(
827     Optional<unsigned> index, ArrayRef<Attribute> operands,
828     SmallVectorImpl<RegionSuccessor> &regions) {
829   // We always branch to the join region.
830   if (index.hasValue()) {
831     if (index.getValue() < 2)
832       regions.push_back(RegionSuccessor(&joinRegion(), getJoinArgs()));
833     else
834       regions.push_back(RegionSuccessor(getResults()));
835     return;
836   }
837 
838   // The then and else regions are the entry regions of this op.
839   regions.push_back(RegionSuccessor(&thenRegion(), getThenArgs()));
840   regions.push_back(RegionSuccessor(&elseRegion(), getElseArgs()));
841 }
842 
843 #include "TestOpEnums.cpp.inc"
844 #include "TestOpStructs.cpp.inc"
845 #include "TestTypeInterfaces.cpp.inc"
846 
847 #define GET_OP_CLASSES
848 #include "TestOps.cpp.inc"
849