1//===- TestDialectInterfaces.cpp - Test dialect interface definitions -----===//
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 "TestOps.h"
11#include "TestTypes.h"
12#include "mlir/Bytecode/Encoding.h"
13#include "mlir/Conversion/ConvertToEmitC/ToEmitCInterface.h"
14#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
15#include "mlir/Dialect/EmitC/IR/EmitC.h"
16#include "mlir/Interfaces/FoldInterfaces.h"
17#include "mlir/Reducer/ReductionPatternInterface.h"
18#include "mlir/Transforms/DialectConversion.h"
19#include "mlir/Transforms/InliningUtils.h"
20
21using namespace mlir;
22using namespace test;
23
24//===----------------------------------------------------------------------===//
25// TestDialect Interfaces
26//===----------------------------------------------------------------------===//
27
28namespace {
29
30/// Testing the correctness of some traits.
31static_assert(
32 llvm::is_detected<OpTrait::has_implicit_terminator_t,
33 SingleBlockImplicitTerminatorOp>::value,
34 "has_implicit_terminator_t does not match SingleBlockImplicitTerminatorOp");
35static_assert(OpTrait::hasSingleBlockImplicitTerminator<
36 SingleBlockImplicitTerminatorOp>::value,
37 "hasSingleBlockImplicitTerminator does not match "
38 "SingleBlockImplicitTerminatorOp");
39
40struct TestResourceBlobManagerInterface
41 : public ResourceBlobManagerDialectInterfaceBase<
42 TestDialectResourceBlobHandle> {
43 using ResourceBlobManagerDialectInterfaceBase<
44 TestDialectResourceBlobHandle>::ResourceBlobManagerDialectInterfaceBase;
45};
46
47namespace {
48enum test_encoding {
49 k_attr_params = 0,
50 k_test_i32 = 99,
51 k_test_rec_alias = 100
52};
53} // namespace
54
55// Test support for interacting with the Bytecode reader/writer.
56struct TestBytecodeDialectInterface : public BytecodeDialectInterface {
57 using BytecodeDialectInterface::BytecodeDialectInterface;
58 TestBytecodeDialectInterface(Dialect *dialect)
59 : BytecodeDialectInterface(dialect) {}
60
61 LogicalResult writeType(Type type,
62 DialectBytecodeWriter &writer) const final {
63 if (auto concreteType = llvm::dyn_cast<TestI32Type>(type)) {
64 writer.writeVarInt(value: test_encoding::k_test_i32);
65 return success();
66 }
67 // A mutable, possibly self-referential type. Exercises the cyclic path in
68 // the bytecode reader; see readType below.
69 if (auto recType = llvm::dyn_cast<TestRecursiveAliasType>(type)) {
70 writer.writeVarInt(value: test_encoding::k_test_rec_alias);
71 writer.writeOwnedString(str: recType.getName());
72 Type body = recType.getBody();
73 writer.writeOwnedBool(value: static_cast<bool>(body));
74 if (body)
75 writer.writeType(type: body);
76 return success();
77 }
78 return failure();
79 }
80
81 Type readType(DialectBytecodeReader &reader) const final {
82 uint64_t encoding;
83 if (failed(Result: reader.readVarInt(result&: encoding)))
84 return Type();
85 if (encoding == test_encoding::k_test_i32)
86 return TestI32Type::get(getContext());
87 if (encoding == test_encoding::k_test_rec_alias) {
88 StringRef name;
89 if (failed(Result: reader.readString(result&: name)))
90 return Type();
91
92 // The body may name this very type, so the type has to exist before the
93 // body is read. Publish it first: a reference back to it then resolves
94 // to this incomplete value instead of re-entering the same entry. This
95 // is the bytecode counterpart of tryStartCyclicParse in
96 // TestRecursiveAliasType::parse, and it needs the same stable identity:
97 // completing the type must mutate the published instance.
98 auto rec = TestRecursiveAliasType::get(ctx: getContext(), name);
99 if (failed(Result: reader.tryStartCyclicRead(rec)))
100 return Type();
101
102 bool hasBody = false;
103 if (failed(Result: reader.readBool(result&: hasBody)))
104 return Type();
105 if (hasBody) {
106 Type body;
107 if (failed(Result: reader.readType(result&: body)))
108 return Type();
109 rec.setBody(body);
110 }
111 return rec;
112 }
113 return Type();
114 }
115
116 LogicalResult writeAttribute(Attribute attr,
117 DialectBytecodeWriter &writer) const final {
118 if (auto concreteAttr = llvm::dyn_cast<TestAttrParamsAttr>(attr)) {
119 // Without dialect version metadata, use the textual fallback rather than
120 // emit a historical encoding that a reader would interpret as current.
121 if (writer.getBytecodeVersion() < bytecode::kDialectVersioning)
122 return failure();
123 writer.writeVarInt(value: test_encoding::k_attr_params);
124 auto version = writer.getDialectVersion<TestDialect>();
125 bool useOldEncoding =
126 succeeded(Result: version) &&
127 static_cast<const TestDialectVersion *>(*version)->major_ < 2;
128 writer.writeVarInt(value: useOldEncoding ? concreteAttr.getV1()
129 : concreteAttr.getV0());
130 writer.writeVarInt(value: useOldEncoding ? concreteAttr.getV0()
131 : concreteAttr.getV1());
132 return success();
133 }
134 return failure();
135 }
136
137 Attribute readAttribute(DialectBytecodeReader &reader) const final {
138 auto versionOr = reader.getDialectVersion<test::TestDialect>();
139 // Assume current version if not available through the reader.
140 const auto version =
141 (succeeded(Result: versionOr))
142 ? *reinterpret_cast<const TestDialectVersion *>(*versionOr)
143 : TestDialectVersion();
144 if (version.major_ < 2)
145 return readAttrOldEncoding(reader);
146 if (version.major_ == 2 && version.minor_ == 0)
147 return readAttrNewEncoding(reader);
148 // Forbid reading future versions by returning nullptr.
149 return Attribute();
150 }
151
152 std::unique_ptr<DialectVersion> parseVersion(StringRef version) const final {
153 auto [major, minor] = version.split(Separator: '.');
154 uint32_t majorVersion, minorVersion;
155 if (major.getAsInteger(Radix: 10, Result&: majorVersion) ||
156 minor.getAsInteger(Radix: 10, Result&: minorVersion) || majorVersion > 2 ||
157 (majorVersion == 2 && minorVersion > 0))
158 return nullptr;
159 return std::make_unique<TestDialectVersion>(args&: majorVersion, args&: minorVersion);
160 }
161
162 LogicalResult verifyVersion(Operation *topLevelOp,
163 const DialectVersion &version) const final {
164 if (static_cast<const TestDialectVersion &>(version).major_ >= 2)
165 return success();
166 WalkResult result = topLevelOp->walk(callback: [](TestVersionedOpA op) {
167 if (!op.getModifier())
168 return WalkResult::advance();
169 op.emitOpError("cannot emit test dialect versions before 2.0 with "
170 "'modifier = true'");
171 return WalkResult::interrupt();
172 });
173 if (result.wasInterrupted())
174 return failure();
175 result = topLevelOp->walk(callback: [](TestOpWithVersionedProperties op) {
176 if (op.getProperties().prop.value2 == 0)
177 return WalkResult::advance();
178 op.emitOpError("cannot emit test dialect versions before 2.0 with "
179 "a nonzero 'value2' property");
180 return WalkResult::interrupt();
181 });
182 return failure(IsFailure: result.wasInterrupted());
183 }
184
185 // Emit a specific version of the dialect.
186 void writeVersion(DialectBytecodeWriter &writer) const final {
187 // Construct the current dialect version.
188 test::TestDialectVersion versionToEmit;
189
190 // Check if a target version to emit was specified on the writer configs.
191 auto versionOr = writer.getDialectVersion<test::TestDialect>();
192 if (succeeded(Result: versionOr))
193 versionToEmit =
194 *reinterpret_cast<const test::TestDialectVersion *>(*versionOr);
195 writer.writeVarInt(value: versionToEmit.major_); // major
196 writer.writeVarInt(value: versionToEmit.minor_); // minor
197 }
198
199 std::unique_ptr<DialectVersion>
200 readVersion(DialectBytecodeReader &reader) const final {
201 uint64_t major_, minor_;
202 if (failed(Result: reader.readVarInt(result&: major_)) || failed(Result: reader.readVarInt(result&: minor_)))
203 return nullptr;
204 auto version = std::make_unique<TestDialectVersion>();
205 version->major_ = major_;
206 version->minor_ = minor_;
207 return version;
208 }
209
210 LogicalResult upgradeFromVersion(Operation *topLevelOp,
211 const DialectVersion &version_) const final {
212 const auto &version = static_cast<const TestDialectVersion &>(version_);
213 if ((version.major_ == 2) && (version.minor_ == 0))
214 return success();
215 if (version.major_ > 2 || (version.major_ == 2 && version.minor_ > 0)) {
216 return topLevelOp->emitError()
217 << "current test dialect version is 2.0, can't parse version: "
218 << version.major_ << "." << version.minor_;
219 }
220 // Prior version 2.0, the old op supported only a single attribute called
221 // "dimensions". We can perform the upgrade.
222 topLevelOp->walk(callback: [](TestVersionedOpA op) {
223 // Prior version 2.0, `readProperties` did not process the modifier
224 // attribute. Handle that according to the version here.
225 auto &prop = op.getProperties();
226 prop.modifier = BoolAttr::get(context: op->getContext(), value: false);
227 });
228 return success();
229 }
230
231private:
232 Attribute readAttrNewEncoding(DialectBytecodeReader &reader) const {
233 uint64_t encoding;
234 if (failed(Result: reader.readVarInt(result&: encoding)) ||
235 encoding != test_encoding::k_attr_params)
236 return Attribute();
237 // The new encoding has v0 first, v1 second.
238 uint64_t v0, v1;
239 if (failed(Result: reader.readVarInt(result&: v0)) || failed(Result: reader.readVarInt(result&: v1)))
240 return Attribute();
241 return TestAttrParamsAttr::get(getContext(), static_cast<int>(v0),
242 static_cast<int>(v1));
243 }
244
245 Attribute readAttrOldEncoding(DialectBytecodeReader &reader) const {
246 uint64_t encoding;
247 if (failed(Result: reader.readVarInt(result&: encoding)) ||
248 encoding != test_encoding::k_attr_params)
249 return Attribute();
250 // The old encoding has v1 first, v0 second.
251 uint64_t v0, v1;
252 if (failed(Result: reader.readVarInt(result&: v1)) || failed(Result: reader.readVarInt(result&: v0)))
253 return Attribute();
254 return TestAttrParamsAttr::get(getContext(), static_cast<int>(v0),
255 static_cast<int>(v1));
256 }
257};
258
259// Test support for interacting with the AsmPrinter.
260struct TestOpAsmInterface : public OpAsmDialectInterface {
261 using OpAsmDialectInterface::OpAsmDialectInterface;
262 TestOpAsmInterface(Dialect *dialect, TestResourceBlobManagerInterface &mgr)
263 : OpAsmDialectInterface(dialect), blobManager(mgr) {}
264
265 //===------------------------------------------------------------------===//
266 // Aliases
267 //===------------------------------------------------------------------===//
268
269 AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
270 if (auto nestedAttr = dyn_cast<TestNestedAliasAttr>(attr)) {
271 std::optional<StringRef> aliasName =
272 StringSwitch<std::optional<StringRef>>(nestedAttr.getValue())
273 .Case(S: "alias_test:trailing_digit_conflict_base",
274 Value: StringRef("unique_base"))
275 .Case(S: "alias_test:trailing_digit_conflict_base_conflict",
276 Value: StringRef("unique_base"))
277 .Case(S: "alias_test:trailing_digit_conflict_base1",
278 Value: StringRef("unique_base1"))
279 .Default(Value: std::nullopt);
280 if (!aliasName)
281 return AliasResult::NoAlias;
282 os << *aliasName;
283 return AliasResult::FinalAlias;
284 }
285
286 StringAttr strAttr = dyn_cast<StringAttr>(Val&: attr);
287 if (!strAttr)
288 return AliasResult::NoAlias;
289
290 // Check the contents of the string attribute to see what the test alias
291 // should be named.
292 std::optional<StringRef> aliasName =
293 StringSwitch<std::optional<StringRef>>(strAttr.getValue())
294 .Case(S: "alias_test:dot_in_name", Value: StringRef("test.alias"))
295 .Case(S: "alias_test:trailing_digit", Value: StringRef("test_alias0"))
296 .Case(S: "alias_test:trailing_digit_conflict_a",
297 Value: StringRef("test_alias_conflict0_1_1_1"))
298 .Case(S: "alias_test:trailing_digit_conflict_b",
299 Value: StringRef("test_alias_conflict0"))
300 .Case(S: "alias_test:trailing_digit_conflict_c",
301 Value: StringRef("test_alias_conflict0"))
302 .Case(S: "alias_test:trailing_digit_conflict_d",
303 Value: StringRef("test_alias_conflict0_"))
304 .Case(S: "alias_test:trailing_digit_conflict_e",
305 Value: StringRef("test_alias_conflict0_1"))
306 .Case(S: "alias_test:trailing_digit_conflict_f",
307 Value: StringRef("test_alias_conflict0_1"))
308 .Case(S: "alias_test:trailing_digit_conflict_g",
309 Value: StringRef("test_alias_conflict0_1_"))
310 .Case(S: "alias_test:trailing_digit_conflict_h",
311 Value: StringRef("test_alias_conflict0_1_1"))
312 .Case(S: "alias_test:prefixed_digit", Value: StringRef("0_test_alias"))
313 .Case(S: "alias_test:prefixed_symbol", Value: StringRef("%test"))
314 .Case(S: "alias_test:tensor_encoding", Value: StringRef("test_encoding"))
315 .Default(Value: std::nullopt);
316 if (!aliasName)
317 return AliasResult::NoAlias;
318
319 os << *aliasName;
320 return AliasResult::FinalAlias;
321 }
322
323 AliasResult getAlias(Type type, raw_ostream &os) const final {
324 if (auto tupleType = dyn_cast<TupleType>(Val&: type)) {
325 if (tupleType.size() > 0 &&
326 llvm::all_of(Range: tupleType.getTypes(), P: [](Type elemType) {
327 return isa<SimpleAType>(Val: elemType);
328 })) {
329 os << "test_tuple";
330 return AliasResult::FinalAlias;
331 }
332 }
333 if (auto intType = dyn_cast<TestIntegerType>(Val&: type)) {
334 if (intType.getSignedness() ==
335 TestIntegerType::SignednessSemantics::Unsigned &&
336 intType.getWidth() == 8) {
337 os << "test_ui8";
338 return AliasResult::FinalAlias;
339 }
340 }
341 if (auto recType = dyn_cast<TestRecursiveType>(type)) {
342 if (recType.getName() == "type_to_alias") {
343 // We only make alias for a specific recursive type.
344 os << "testrec";
345 return AliasResult::FinalAlias;
346 }
347 }
348 if (auto recAliasType = dyn_cast<TestRecursiveAliasType>(type)) {
349 os << recAliasType.getName();
350 return AliasResult::FinalAlias;
351 }
352 return AliasResult::NoAlias;
353 }
354
355 //===------------------------------------------------------------------===//
356 // Resources
357 //===------------------------------------------------------------------===//
358
359 std::string
360 getResourceKey(const AsmDialectResourceHandle &handle) const override {
361 return cast<TestDialectResourceBlobHandle>(Val: handle).getKey().str();
362 }
363
364 FailureOr<AsmDialectResourceHandle>
365 declareResource(StringRef key) const final {
366 return blobManager.insert(name: key);
367 }
368
369 LogicalResult parseResource(AsmParsedResourceEntry &entry) const final {
370 FailureOr<AsmResourceBlob> blob = entry.parseAsBlob();
371 if (failed(Result: blob))
372 return failure();
373
374 // Update the blob for this entry.
375 blobManager.update(name: entry.getKey(), newBlob: std::move(*blob));
376 return success();
377 }
378
379 void
380 buildResources(Operation *op,
381 const SetVector<AsmDialectResourceHandle> &referencedResources,
382 AsmResourceBuilder &provider) const final {
383 blobManager.buildResources(provider, referencedResources: referencedResources.getArrayRef());
384 }
385
386private:
387 /// The blob manager for the dialect.
388 TestResourceBlobManagerInterface &blobManager;
389};
390
391struct TestDialectFoldInterface : public DialectFoldInterface {
392 using DialectFoldInterface::DialectFoldInterface;
393
394 /// Registered hook to check if the given region, which is attached to an
395 /// operation that is *not* isolated from above, should be used when
396 /// materializing constants.
397 bool shouldMaterializeInto(Region *region) const final {
398 // If this is a one region operation, then insert into it.
399 return isa<OneRegionOp>(region->getParentOp());
400 }
401};
402
403/// This class defines the interface for handling inlining with standard
404/// operations.
405struct TestInlinerInterface : public DialectInlinerInterface {
406 using DialectInlinerInterface::DialectInlinerInterface;
407
408 //===--------------------------------------------------------------------===//
409 // Analysis Hooks
410 //===--------------------------------------------------------------------===//
411
412 bool isLegalToInline(Operation *call, Operation *callable,
413 bool wouldBeCloned) const final {
414 // Don't allow inlining calls that are marked `noinline`.
415 return !call->hasDiscardableAttr(name: "noinline");
416 }
417 bool isLegalToInline(Region *, Region *, bool, IRMapping &) const final {
418 // Inlining into test dialect regions is legal.
419 return true;
420 }
421 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
422 return true;
423 }
424
425 bool shouldAnalyzeRecursively(Operation *op) const final {
426 // Analyze recursively if this is not a functional region operation, it
427 // froms a separate functional scope.
428 return !isa<FunctionalRegionOp>(op);
429 }
430
431 //===--------------------------------------------------------------------===//
432 // Transformation Hooks
433 //===--------------------------------------------------------------------===//
434
435 /// Handle the given inlined terminator by replacing it with a new operation
436 /// as necessary (multi-block inlining case: replace test.return with a
437 /// branch to the successor block that carries the inlined results).
438 void handleTerminator(Operation *op, Block *newDest) const final {
439 auto returnOp = dyn_cast<TestReturnOp>(op);
440 if (!returnOp)
441 return;
442 OpBuilder builder(op);
443 cf::BranchOp::create(builder, op->getLoc(), newDest,
444 returnOp.getOperands());
445 op->erase();
446 }
447
448 /// Handle the given inlined terminator by replacing it with a new operation
449 /// as necessary.
450 void handleTerminator(Operation *op, ValueRange valuesToRepl) const final {
451 // Only handle "test.return" here.
452 auto returnOp = dyn_cast<TestReturnOp>(op);
453 if (!returnOp)
454 return;
455
456 // Replace the values directly with the return operands. Skip if the
457 // number of operands doesn't match (e.g., when inlining into a call
458 // with a different result arity due to invalid IR mixing dialects).
459 if (returnOp.getNumOperands() != valuesToRepl.size())
460 return;
461 for (const auto &it : llvm::enumerate(returnOp.getOperands()))
462 valuesToRepl[it.index()].replaceAllUsesWith(it.value());
463 }
464
465 /// Attempt to materialize a conversion for a type mismatch between a call
466 /// from this dialect, and a callable region. This method should generate an
467 /// operation that takes 'input' as the only operand, and produces a single
468 /// result of 'resultType'. If a conversion can not be generated, nullptr
469 /// should be returned.
470 Operation *materializeCallConversion(OpBuilder &builder, Value input,
471 Type resultType,
472 Location conversionLoc) const final {
473 // Only allow conversion for i16/i32 types.
474 if (!(resultType.isSignlessInteger(width: 16) ||
475 resultType.isSignlessInteger(width: 32)) ||
476 !(input.getType().isSignlessInteger(width: 16) ||
477 input.getType().isSignlessInteger(width: 32)))
478 return nullptr;
479 return TestCastOp::create(builder, conversionLoc, resultType, input);
480 }
481
482 Value handleArgument(OpBuilder &builder, Operation *call, Operation *callable,
483 Value argument,
484 DictionaryAttr argumentAttrs) const final {
485 if (!argumentAttrs.contains(name: "test.handle_argument"))
486 return argument;
487 return TestTypeChangerOp::create(builder, call->getLoc(),
488 argument.getType(), argument);
489 }
490
491 Value handleResult(OpBuilder &builder, Operation *call, Operation *callable,
492 Value result, DictionaryAttr resultAttrs) const final {
493 if (!resultAttrs.contains(name: "test.handle_result"))
494 return result;
495 return TestTypeChangerOp::create(builder, call->getLoc(), result.getType(),
496 result);
497 }
498
499 void processInlinedCallBlocks(
500 Operation *call,
501 iterator_range<Region::iterator> inlinedBlocks) const final {
502 if (!isa<ConversionCallOp>(call))
503 return;
504
505 // Set attributed on all ops in the inlined blocks.
506 for (Block &block : inlinedBlocks) {
507 block.walk(callback: [&](Operation *op) {
508 op->setDiscardableAttr(name: "inlined_conversion",
509 value: UnitAttr::get(context: call->getContext()));
510 });
511 }
512 }
513};
514
515struct TestReductionPatternInterface : public DialectReductionPatternInterface {
516public:
517 TestReductionPatternInterface(Dialect *dialect)
518 : DialectReductionPatternInterface(dialect) {}
519
520 void populateReductionPatterns(RewritePatternSet &patterns) const final {
521 populateTestReductionPatterns(patterns);
522 }
523};
524
525struct TestToEmitCDialectInterface : public ConvertToEmitCPatternInterface {
526 explicit TestToEmitCDialectInterface(Dialect *dialect)
527 : ConvertToEmitCPatternInterface(dialect) {}
528
529 void populateConvertToEmitCConversionPatterns(
530 ConversionTarget &target, TypeConverter &typeConverter,
531 RewritePatternSet &patterns,
532 ::std::optional<bool> lowerToCpp) const final {
533 typeConverter.addConversion([](test::TestMemRefElementTypeType type) {
534 return emitc::OpaqueType::get(type.getContext(), "TestElementT");
535 });
536 }
537};
538
539} // namespace
540
541void TestDialect::registerInterfaces() {
542 auto &blobInterface = addInterface<TestResourceBlobManagerInterface>();
543 addInterface<TestOpAsmInterface>(blobInterface);
544
545 addInterfaces<TestDialectFoldInterface, TestInlinerInterface,
546 TestReductionPatternInterface, TestBytecodeDialectInterface>();
547 addInterface<TestToEmitCDialectInterface>();
548}
549