1//===- TestOpsSyntax.cpp - Operations for testing syntax ------------------===//
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 "TestOpsSyntax.h"
10#include "TestDialect.h"
11#include "TestOpsConversion.h"
12#include "TestOpsCore.h"
13#include "mlir/IR/OpImplementation.h"
14#include "llvm/Support/Base64.h"
15
16using namespace mlir;
17using namespace test;
18
19//===----------------------------------------------------------------------===//
20// Test Format* operations
21//===----------------------------------------------------------------------===//
22
23//===----------------------------------------------------------------------===//
24// Parsing
25//===----------------------------------------------------------------------===//
26
27static ParseResult parseCustomOptionalOperand(
28 OpAsmParser &parser,
29 std::optional<OpAsmParser::UnresolvedOperand> &optOperand) {
30 if (succeeded(Result: parser.parseOptionalLParen())) {
31 optOperand.emplace();
32 if (parser.parseOperand(result&: *optOperand) || parser.parseRParen())
33 return failure();
34 }
35 return success();
36}
37
38static ParseResult parseCustomDirectiveOperands(
39 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
40 std::optional<OpAsmParser::UnresolvedOperand> &optOperand,
41 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands) {
42 if (parser.parseOperand(result&: operand))
43 return failure();
44 if (succeeded(Result: parser.parseOptionalComma())) {
45 optOperand.emplace();
46 if (parser.parseOperand(result&: *optOperand))
47 return failure();
48 }
49 if (parser.parseArrow() || parser.parseLParen() ||
50 parser.parseOperandList(result&: varOperands) || parser.parseRParen())
51 return failure();
52 return success();
53}
54static ParseResult
55parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType,
56 Type &optOperandType,
57 SmallVectorImpl<Type> &varOperandTypes) {
58 if (parser.parseColon())
59 return failure();
60
61 if (parser.parseType(result&: operandType))
62 return failure();
63 if (succeeded(Result: parser.parseOptionalComma())) {
64 if (parser.parseType(result&: optOperandType))
65 return failure();
66 }
67 if (parser.parseArrow() || parser.parseLParen() ||
68 parser.parseTypeList(result&: varOperandTypes) || parser.parseRParen())
69 return failure();
70 return success();
71}
72static ParseResult
73parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType,
74 Type optOperandType,
75 const SmallVectorImpl<Type> &varOperandTypes) {
76 if (parser.parseKeyword(keyword: "type_refs_capture"))
77 return failure();
78
79 Type operandType2, optOperandType2;
80 SmallVector<Type, 1> varOperandTypes2;
81 if (parseCustomDirectiveResults(parser, operandType&: operandType2, optOperandType&: optOperandType2,
82 varOperandTypes&: varOperandTypes2))
83 return failure();
84
85 if (operandType != operandType2 || optOperandType != optOperandType2 ||
86 varOperandTypes != varOperandTypes2)
87 return failure();
88
89 return success();
90}
91static ParseResult parseCustomDirectiveOperandsAndTypes(
92 OpAsmParser &parser, OpAsmParser::UnresolvedOperand &operand,
93 std::optional<OpAsmParser::UnresolvedOperand> &optOperand,
94 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &varOperands,
95 Type &operandType, Type &optOperandType,
96 SmallVectorImpl<Type> &varOperandTypes) {
97 if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) ||
98 parseCustomDirectiveResults(parser, operandType, optOperandType,
99 varOperandTypes))
100 return failure();
101 return success();
102}
103static ParseResult parseCustomDirectiveRegions(
104 OpAsmParser &parser, Region &region,
105 SmallVectorImpl<std::unique_ptr<Region>> &varRegions) {
106 if (parser.parseRegion(region))
107 return failure();
108 if (failed(Result: parser.parseOptionalComma()))
109 return success();
110 std::unique_ptr<Region> varRegion = std::make_unique<Region>();
111 if (parser.parseRegion(region&: *varRegion))
112 return failure();
113 varRegions.emplace_back(Args: std::move(varRegion));
114 return success();
115}
116static ParseResult
117parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor,
118 SmallVectorImpl<Block *> &varSuccessors) {
119 if (parser.parseSuccessor(dest&: successor))
120 return failure();
121 if (failed(Result: parser.parseOptionalComma()))
122 return success();
123 Block *varSuccessor;
124 if (parser.parseSuccessor(dest&: varSuccessor))
125 return failure();
126 varSuccessors.append(NumInputs: 2, Elt: varSuccessor);
127 return success();
128}
129static ParseResult parseCustomDirectiveAttributes(OpAsmParser &parser,
130 IntegerAttr &attr,
131 IntegerAttr &optAttr) {
132 if (parser.parseAttribute(result&: attr))
133 return failure();
134 if (succeeded(Result: parser.parseOptionalComma())) {
135 if (parser.parseAttribute(result&: optAttr))
136 return failure();
137 }
138 return success();
139}
140static ParseResult parseCustomDirectiveSpacing(OpAsmParser &parser,
141 mlir::StringAttr &attr) {
142 return parser.parseAttribute(result&: attr);
143}
144static ParseResult parseCustomDirectiveAttrDict(OpAsmParser &parser,
145 NamedAttrList &attrs) {
146 return parser.parseOptionalAttrDict(result&: attrs);
147}
148static ParseResult parseCustomDirectiveOptionalOperandRef(
149 OpAsmParser &parser,
150 std::optional<OpAsmParser::UnresolvedOperand> &optOperand) {
151 int64_t operandCount = 0;
152 if (parser.parseInteger(result&: operandCount))
153 return failure();
154 bool expectedOptionalOperand = operandCount == 0;
155 return success(IsSuccess: expectedOptionalOperand != optOperand.has_value());
156}
157
158//===----------------------------------------------------------------------===//
159// Printing
160//===----------------------------------------------------------------------===//
161
162static void printCustomOptionalOperand(OpAsmPrinter &printer, Operation *,
163 Value optOperand) {
164 if (optOperand)
165 printer << "(" << optOperand << ") ";
166}
167
168static void printCustomDirectiveOperands(OpAsmPrinter &printer, Operation *,
169 Value operand, Value optOperand,
170 OperandRange varOperands) {
171 printer << operand;
172 if (optOperand)
173 printer << ", " << optOperand;
174 printer << " -> (" << varOperands << ")";
175}
176static void printCustomDirectiveResults(OpAsmPrinter &printer, Operation *,
177 Type operandType, Type optOperandType,
178 TypeRange varOperandTypes) {
179 printer << " : " << operandType;
180 if (optOperandType)
181 printer << ", " << optOperandType;
182 printer << " -> (" << varOperandTypes << ")";
183}
184static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer,
185 Operation *op, Type operandType,
186 Type optOperandType,
187 TypeRange varOperandTypes) {
188 printer << " type_refs_capture ";
189 printCustomDirectiveResults(printer, op, operandType, optOperandType,
190 varOperandTypes);
191}
192static void printCustomDirectiveOperandsAndTypes(
193 OpAsmPrinter &printer, Operation *op, Value operand, Value optOperand,
194 OperandRange varOperands, Type operandType, Type optOperandType,
195 TypeRange varOperandTypes) {
196 printCustomDirectiveOperands(printer, op, operand, optOperand, varOperands);
197 printCustomDirectiveResults(printer, op, operandType, optOperandType,
198 varOperandTypes);
199}
200static void printCustomDirectiveRegions(OpAsmPrinter &printer, Operation *,
201 Region &region,
202 MutableArrayRef<Region> varRegions) {
203 printer.printRegion(blocks&: region);
204 if (!varRegions.empty()) {
205 printer << ", ";
206 for (Region &region : varRegions)
207 printer.printRegion(blocks&: region);
208 }
209}
210static void printCustomDirectiveSuccessors(OpAsmPrinter &printer, Operation *,
211 Block *successor,
212 SuccessorRange varSuccessors) {
213 printer << successor;
214 if (!varSuccessors.empty())
215 printer << ", " << varSuccessors.front();
216}
217static void printCustomDirectiveAttributes(OpAsmPrinter &printer, Operation *,
218 Attribute attribute,
219 Attribute optAttribute) {
220 printer << attribute;
221 if (optAttribute)
222 printer << ", " << optAttribute;
223}
224static void printCustomDirectiveSpacing(OpAsmPrinter &printer, Operation *op,
225 Attribute attribute) {
226 printer << attribute;
227}
228static void printCustomDirectiveAttrDict(OpAsmPrinter &printer, Operation *op,
229 DictionaryAttr attrs) {
230 printer.printOptionalAttrDict(attrs: attrs.getValue());
231}
232
233static void printCustomDirectiveOptionalOperandRef(OpAsmPrinter &printer,
234 Operation *op,
235 Value optOperand) {
236 printer << (optOperand ? "1" : "0");
237}
238//===----------------------------------------------------------------------===//
239// Test parser.
240//===----------------------------------------------------------------------===//
241
242ParseResult ParseIntegerLiteralOp::parse(OpAsmParser &parser,
243 OperationState &result) {
244 if (parser.parseOptionalColon())
245 return success();
246 uint64_t numResults;
247 if (parser.parseInteger(numResults))
248 return failure();
249
250 IndexType type = parser.getBuilder().getIndexType();
251 for (unsigned i = 0; i < numResults; ++i)
252 result.addTypes(type);
253 return success();
254}
255
256void ParseIntegerLiteralOp::print(OpAsmPrinter &p) {
257 if (unsigned numResults = getNumResults())
258 p << " : " << numResults;
259}
260
261ParseResult ParseWrappedKeywordOp::parse(OpAsmParser &parser,
262 OperationState &result) {
263 StringRef keyword;
264 if (parser.parseKeyword(&keyword))
265 return failure();
266 result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword));
267 return success();
268}
269
270void ParseWrappedKeywordOp::print(OpAsmPrinter &p) { p << " " << getKeyword(); }
271
272ParseResult ParseB64BytesOp::parse(OpAsmParser &parser,
273 OperationState &result) {
274 std::vector<char> bytes;
275 if (parser.parseBase64Bytes(&bytes))
276 return failure();
277 result.addAttribute("b64", parser.getBuilder().getStringAttr(
278 StringRef(&bytes.front(), bytes.size())));
279 return success();
280}
281
282void ParseB64BytesOp::print(OpAsmPrinter &p) {
283 p << " \"" << llvm::encodeBase64(getB64()) << "\"";
284}
285
286::llvm::LogicalResult FormatInferType2Op::inferReturnTypes(
287 ::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location,
288 ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes,
289 PropertyRef properties, ::mlir::RegionRange regions,
290 ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) {
291 inferredReturnTypes.assign({::mlir::IntegerType::get(context, 16)});
292 return ::mlir::success();
293}
294
295//===----------------------------------------------------------------------===//
296// Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`.
297//===----------------------------------------------------------------------===//
298
299ParseResult WrappingRegionOp::parse(OpAsmParser &parser,
300 OperationState &result) {
301 if (parser.parseKeyword("wraps"))
302 return failure();
303
304 // Parse the wrapped op in a region
305 Region &body = *result.addRegion();
306 body.push_back(new Block);
307 Block &block = body.back();
308 Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
309 if (!wrappedOp)
310 return failure();
311
312 // Create a return terminator in the inner region, pass as operand to the
313 // terminator the returned values from the wrapped operation.
314 SmallVector<Value, 8> returnOperands(wrappedOp->getResults());
315 OpBuilder builder(parser.getContext());
316 builder.setInsertionPointToEnd(&block);
317 TestReturnOp::create(builder, wrappedOp->getLoc(), returnOperands);
318
319 // Get the results type for the wrapping op from the terminator operands.
320 Operation &returnOp = body.back().back();
321 result.types.append(returnOp.operand_type_begin(),
322 returnOp.operand_type_end());
323
324 // Use the location of the wrapped op for the "test.wrapping_region" op.
325 result.location = wrappedOp->getLoc();
326
327 return success();
328}
329
330void WrappingRegionOp::print(OpAsmPrinter &p) {
331 p << " wraps ";
332 p.printGenericOp(&getRegion().front().front());
333}
334
335//===----------------------------------------------------------------------===//
336// Test PrettyPrintedRegionOp - exercising the following parser APIs
337// parseGenericOperationAfterOpName
338// parseCustomOperationName
339//===----------------------------------------------------------------------===//
340
341ParseResult PrettyPrintedRegionOp::parse(OpAsmParser &parser,
342 OperationState &result) {
343
344 SMLoc loc = parser.getCurrentLocation();
345 Location currLocation = parser.getEncodedSourceLoc(loc);
346
347 // Parse the operands.
348 SmallVector<OpAsmParser::UnresolvedOperand, 2> operands;
349 if (parser.parseOperandList(operands))
350 return failure();
351
352 // Check if we are parsing the pretty-printed version
353 // test.pretty_printed_region start <inner-op> end : <functional-type>
354 // Else fallback to parsing the "non pretty-printed" version.
355 if (!succeeded(parser.parseOptionalKeyword("start")))
356 return parser.parseGenericOperationAfterOpName(result,
357 llvm::ArrayRef(operands));
358
359 FailureOr<OperationName> parseOpNameInfo = parser.parseCustomOperationName();
360 if (failed(parseOpNameInfo))
361 return failure();
362
363 StringAttr innerOpName = parseOpNameInfo->getIdentifier();
364
365 FunctionType opFntype;
366 std::optional<Location> explicitLoc;
367 if (parser.parseKeyword("end") || parser.parseColon() ||
368 parser.parseType(opFntype) ||
369 parser.parseOptionalLocationSpecifier(explicitLoc))
370 return failure();
371
372 // If location of the op is explicitly provided, then use it; Else use
373 // the parser's current location.
374 Location opLoc = explicitLoc.value_or(currLocation);
375
376 // Derive the SSA-values for op's operands.
377 if (parser.resolveOperands(operands, opFntype.getInputs(), loc,
378 result.operands))
379 return failure();
380
381 // Add a region for op.
382 Region &region = *result.addRegion();
383
384 // Create a basic-block inside op's region.
385 Block &block = region.emplaceBlock();
386
387 // Create and insert an "inner-op" operation in the block.
388 // Just for testing purposes, we can assume that inner op is a binary op with
389 // result and operand types all same as the test-op's first operand.
390 Type innerOpType = opFntype.getInput(0);
391 Value lhs = block.addArgument(innerOpType, opLoc);
392 Value rhs = block.addArgument(innerOpType, opLoc);
393
394 OpBuilder builder(parser.getBuilder().getContext());
395 builder.setInsertionPointToStart(&block);
396
397 Operation *innerOp =
398 builder.create(opLoc, innerOpName, /*operands=*/{lhs, rhs}, innerOpType);
399
400 // Insert a return statement in the block returning the inner-op's result.
401 TestReturnOp::create(builder, innerOp->getLoc(), innerOp->getResults());
402
403 // Populate the op operation-state with result-type and location.
404 result.addTypes(opFntype.getResults());
405 result.location = innerOp->getLoc();
406
407 return success();
408}
409
410void PrettyPrintedRegionOp::print(OpAsmPrinter &p) {
411 p << ' ';
412 p.printOperands(getOperands());
413
414 Operation &innerOp = getRegion().front().front();
415 // Assuming that region has a single non-terminator inner-op, if the inner-op
416 // meets some criteria (which in this case is a simple one based on the name
417 // of inner-op), then we can print the entire region in a succinct way.
418 // Here we assume that the prototype of "test.special.op" can be trivially
419 // derived while parsing it back.
420 if (innerOp.getName().getStringRef() == "test.special.op") {
421 p << " start test.special.op end";
422 } else {
423 p << " (";
424 p.printRegion(getRegion());
425 p << ")";
426 }
427
428 p << " : ";
429 p.printFunctionalType(*this);
430}
431
432//===----------------------------------------------------------------------===//
433// Test PolyForOp - parse list of region arguments.
434//===----------------------------------------------------------------------===//
435
436ParseResult PolyForOp::parse(OpAsmParser &parser, OperationState &result) {
437 SmallVector<OpAsmParser::Argument, 4> ivsInfo;
438 // Parse list of region arguments without a delimiter.
439 if (parser.parseArgumentList(ivsInfo, OpAsmParser::Delimiter::None))
440 return failure();
441
442 // Parse the body region.
443 Region *body = result.addRegion();
444 for (auto &iv : ivsInfo)
445 iv.type = parser.getBuilder().getIndexType();
446 return parser.parseRegion(*body, ivsInfo);
447}
448
449void PolyForOp::print(OpAsmPrinter &p) {
450 p << " ";
451 llvm::interleaveComma(getRegion().getArguments(), p, [&](auto arg) {
452 p.printRegionArgument(arg, /*argAttrs =*/{}, /*omitType=*/true);
453 });
454 p << " ";
455 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
456}
457
458void PolyForOp::getAsmBlockArgumentNames(Region &region,
459 OpAsmSetValueNameFn setNameFn) {
460 auto arrayAttr =
461 getOperation()->getDiscardableAttrOfType<ArrayAttr>("arg_names");
462 if (!arrayAttr)
463 return;
464 auto args = getRegion().front().getArguments();
465 auto e = std::min(arrayAttr.size(), args.size());
466 for (unsigned i = 0; i < e; ++i) {
467 if (auto strAttr = dyn_cast<StringAttr>(arrayAttr[i]))
468 setNameFn(args[i], strAttr.getValue());
469 }
470}
471
472//===----------------------------------------------------------------------===//
473// TestAttrWithLoc - parse/printOptionalLocationSpecifier
474//===----------------------------------------------------------------------===//
475
476static ParseResult parseOptionalLoc(OpAsmParser &p, Attribute &loc) {
477 std::optional<Location> result;
478 SMLoc sourceLoc = p.getCurrentLocation();
479 if (p.parseOptionalLocationSpecifier(result))
480 return failure();
481 if (result)
482 loc = *result;
483 else
484 loc = p.getEncodedSourceLoc(loc: sourceLoc);
485 return success();
486}
487
488static void printOptionalLoc(OpAsmPrinter &p, Operation *op, Attribute loc) {
489 p.printOptionalLocationSpecifier(loc: cast<LocationAttr>(Val&: loc));
490}
491
492//===----------------------------------------------------------------------===//
493// ParseCustomOperationNameAPI
494//===----------------------------------------------------------------------===//
495
496static ParseResult parseCustomOperationNameEntry(OpAsmParser &p,
497 Attribute &name) {
498 FailureOr<OperationName> opName = p.parseCustomOperationName();
499 if (failed(Result: opName))
500 return ParseResult::failure();
501
502 name = p.getBuilder().getStringAttr(bytes: opName->getStringRef());
503 return ParseResult::success();
504}
505
506static void printCustomOperationNameEntry(OpAsmPrinter &p, Operation *op,
507 Attribute name) {
508 p << cast<StringAttr>(Val&: name).getValue();
509}
510
511#define GET_OP_CLASSES
512#include "TestOpsSyntax.cpp.inc"
513
514void TestDialect::registerOpsSyntax() {
515 addOperations<
516#define GET_OP_LIST
517#include "TestOpsSyntax.cpp.inc"
518 >();
519}
520