1//===- TestTypes.cpp - MLIR Test Dialect Types ------------------*- C++ -*-===//
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// This file contains types defined by the TestDialect for testing various
10// features of MLIR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TestTypes.h"
15#include "TestDialect.h"
16#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
17#include "mlir/IR/BuiltinAttributes.h"
18#include "mlir/IR/DialectImplementation.h"
19#include "mlir/IR/ExtensibleDialect.h"
20#include "mlir/IR/TypeUtilities.h"
21#include "mlir/IR/Types.h"
22#include "llvm/ADT/Hashing.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/Support/TypeSize.h"
25#include <cstring>
26#include <optional>
27
28using namespace mlir;
29using namespace test;
30
31// Custom parser for SignednessSemantics.
32static ParseResult
33parseSignedness(AsmParser &parser,
34 TestIntegerType::SignednessSemantics &result) {
35 StringRef signStr;
36 auto loc = parser.getCurrentLocation();
37 if (parser.parseKeyword(keyword: &signStr))
38 return failure();
39 if (signStr.equals_insensitive(RHS: "u") || signStr.equals_insensitive(RHS: "unsigned"))
40 result = TestIntegerType::SignednessSemantics::Unsigned;
41 else if (signStr.equals_insensitive(RHS: "s") ||
42 signStr.equals_insensitive(RHS: "signed"))
43 result = TestIntegerType::SignednessSemantics::Signed;
44 else if (signStr.equals_insensitive(RHS: "n") ||
45 signStr.equals_insensitive(RHS: "none"))
46 result = TestIntegerType::SignednessSemantics::Signless;
47 else
48 return parser.emitError(loc, message: "expected signed, unsigned, or none");
49 return success();
50}
51
52// Custom printer for SignednessSemantics.
53static void printSignedness(AsmPrinter &printer,
54 const TestIntegerType::SignednessSemantics &ss) {
55 switch (ss) {
56 case TestIntegerType::SignednessSemantics::Unsigned:
57 printer << "unsigned";
58 break;
59 case TestIntegerType::SignednessSemantics::Signed:
60 printer << "signed";
61 break;
62 case TestIntegerType::SignednessSemantics::Signless:
63 printer << "none";
64 break;
65 }
66}
67
68// The functions don't need to be in the header file, but need to be in the mlir
69// namespace. Declare them here, then define them immediately below. Separating
70// the declaration and definition adheres to the LLVM coding standards.
71namespace test {
72// FieldInfo is used as part of a parameter, so equality comparison is
73// compulsory.
74static bool operator==(const FieldInfo &a, const FieldInfo &b);
75// FieldInfo is used as part of a parameter, so a hash will be computed.
76static llvm::hash_code hash_value(const FieldInfo &fi); // NOLINT
77} // namespace test
78
79// FieldInfo is used as part of a parameter, so equality comparison is
80// compulsory.
81static bool test::operator==(const FieldInfo &a, const FieldInfo &b) {
82 return a.name == b.name && a.type == b.type;
83}
84
85// FieldInfo is used as part of a parameter, so a hash will be computed.
86static llvm::hash_code test::hash_value(const FieldInfo &fi) { // NOLINT
87 return llvm::hash_combine(args: fi.name, args: fi.type);
88}
89
90//===----------------------------------------------------------------------===//
91// TestCustomType
92//===----------------------------------------------------------------------===//
93
94static ParseResult parseCustomTypeA(AsmParser &parser, int &aResult) {
95 return parser.parseInteger(result&: aResult);
96}
97
98static void printCustomTypeA(AsmPrinter &printer, int a) { printer << a; }
99
100static ParseResult parseCustomTypeB(AsmParser &parser, int a,
101 std::optional<int> &bResult) {
102 if (a < 0)
103 return success();
104 for (int i : llvm::seq(Begin: 0, End: a))
105 if (failed(Result: parser.parseInteger(result&: i)))
106 return failure();
107 bResult.emplace(args: 0);
108 return parser.parseInteger(result&: *bResult);
109}
110
111static void printCustomTypeB(AsmPrinter &printer, int a, std::optional<int> b) {
112 if (a < 0)
113 return;
114 printer << ' ';
115 for (int i : llvm::seq(Begin: 0, End: a))
116 printer << i << ' ';
117 printer << *b;
118}
119
120static ParseResult parseFooString(AsmParser &parser, std::string &foo) {
121 std::string result;
122 if (parser.parseString(string: &result))
123 return failure();
124 foo = std::move(result);
125 return success();
126}
127
128static void printFooString(AsmPrinter &printer, StringRef foo) {
129 printer << '"' << foo << '"';
130}
131
132static ParseResult parseBarString(AsmParser &parser, StringRef foo) {
133 return parser.parseKeyword(keyword: foo);
134}
135
136static void printBarString(AsmPrinter &printer, StringRef foo) {
137 printer << foo;
138}
139//===----------------------------------------------------------------------===//
140// Tablegen Generated Definitions
141//===----------------------------------------------------------------------===//
142
143#include "TestTypeInterfaces.cpp.inc"
144#define GET_TYPEDEF_CLASSES
145#include "TestTypeDefs.cpp.inc"
146
147//===----------------------------------------------------------------------===//
148// CompoundAType
149//===----------------------------------------------------------------------===//
150
151Type CompoundAType::parse(AsmParser &parser) {
152 int widthOfSomething;
153 Type oneType;
154 SmallVector<int, 4> arrayOfInts;
155 if (parser.parseLess() || parser.parseInteger(widthOfSomething) ||
156 parser.parseComma() || parser.parseType(oneType) || parser.parseComma() ||
157 parser.parseLSquare())
158 return Type();
159
160 int i;
161 while (!*parser.parseOptionalInteger(i)) {
162 arrayOfInts.push_back(i);
163 if (parser.parseOptionalComma())
164 break;
165 }
166
167 if (parser.parseRSquare() || parser.parseGreater())
168 return Type();
169
170 return get(parser.getContext(), widthOfSomething, oneType, arrayOfInts);
171}
172void CompoundAType::print(AsmPrinter &printer) const {
173 printer << "<" << getWidthOfSomething() << ", " << getOneType() << ", [";
174 auto intArray = getArrayOfInts();
175 llvm::interleaveComma(intArray, printer);
176 printer << "]>";
177}
178
179//===----------------------------------------------------------------------===//
180// TestIntegerType
181//===----------------------------------------------------------------------===//
182
183// Example type validity checker.
184LogicalResult
185TestIntegerType::verify(function_ref<InFlightDiagnostic()> emitError,
186 unsigned width,
187 TestIntegerType::SignednessSemantics ss) {
188 if (width > 8)
189 return failure();
190 return success();
191}
192
193Type TestIntegerType::parse(AsmParser &parser) {
194 SignednessSemantics signedness;
195 int width;
196 if (parser.parseLess() || parseSignedness(parser, result&: signedness) ||
197 parser.parseComma() || parser.parseInteger(result&: width) ||
198 parser.parseGreater())
199 return Type();
200 Location loc = parser.getEncodedSourceLoc(loc: parser.getNameLoc());
201 return getChecked(loc, args: loc.getContext(), args&: width, args&: signedness);
202}
203
204void TestIntegerType::print(AsmPrinter &p) const {
205 p << "<";
206 printSignedness(printer&: p, ss: getSignedness());
207 p << ", " << getWidth() << ">";
208}
209
210//===----------------------------------------------------------------------===//
211// TestStructType
212//===----------------------------------------------------------------------===//
213
214Type StructType::parse(AsmParser &p) {
215 SmallVector<FieldInfo, 4> parameters;
216 if (p.parseLess())
217 return Type();
218 while (succeeded(p.parseOptionalLBrace())) {
219 Type type;
220 StringRef name;
221 if (p.parseKeyword(&name) || p.parseComma() || p.parseType(type) ||
222 p.parseRBrace())
223 return Type();
224 parameters.push_back(FieldInfo{name, type});
225 if (p.parseOptionalComma())
226 break;
227 }
228 if (p.parseGreater())
229 return Type();
230 return get(p.getContext(), parameters);
231}
232
233void StructType::print(AsmPrinter &p) const {
234 p << "<";
235 llvm::interleaveComma(getFields(), p, [&](const FieldInfo &field) {
236 p << "{" << field.name << "," << field.type << "}";
237 });
238 p << ">";
239}
240
241//===----------------------------------------------------------------------===//
242// TestType
243//===----------------------------------------------------------------------===//
244
245void TestType::printTypeC(Location loc) const {
246 emitRemark(loc) << *this << " - TestC";
247}
248
249void TestType::printTypeC(Location loc, int value) const {
250 emitRemark(loc) << *this << " - " << value << " - Int TestC";
251}
252
253//===----------------------------------------------------------------------===//
254// TestTypeWithLayout
255//===----------------------------------------------------------------------===//
256
257Type TestTypeWithLayoutType::parse(AsmParser &parser) {
258 unsigned val;
259 if (parser.parseLess() || parser.parseInteger(val) || parser.parseGreater())
260 return Type();
261 return TestTypeWithLayoutType::get(parser.getContext(), val);
262}
263
264void TestTypeWithLayoutType::print(AsmPrinter &printer) const {
265 printer << "<" << getKey() << ">";
266}
267
268llvm::TypeSize
269TestTypeWithLayoutType::getTypeSizeInBits(const DataLayout &dataLayout,
270 DataLayoutEntryListRef params) const {
271 return llvm::TypeSize::getFixed(extractKind(params, "size"));
272}
273
274uint64_t
275TestTypeWithLayoutType::getABIAlignment(const DataLayout &dataLayout,
276 DataLayoutEntryListRef params) const {
277 return extractKind(params, "alignment");
278}
279
280uint64_t TestTypeWithLayoutType::getPreferredAlignment(
281 const DataLayout &dataLayout, DataLayoutEntryListRef params) const {
282 return extractKind(params, "preferred");
283}
284
285std::optional<uint64_t>
286TestTypeWithLayoutType::getIndexBitwidth(const DataLayout &dataLayout,
287 DataLayoutEntryListRef params) const {
288 return extractKind(params, "index");
289}
290
291bool TestTypeWithLayoutType::areCompatible(
292 DataLayoutEntryListRef oldLayout, DataLayoutEntryListRef newLayout,
293 DataLayoutSpecInterface newSpec,
294 const DataLayoutIdentifiedEntryMap &map) const {
295 unsigned old = extractKind(oldLayout, "alignment");
296 return old == 1 || extractKind(newLayout, "alignment") <= old;
297}
298
299LogicalResult
300TestTypeWithLayoutType::verifyEntries(DataLayoutEntryListRef params,
301 Location loc) const {
302 for (DataLayoutEntryInterface entry : params) {
303 // This is for testing purposes only, so assert well-formedness.
304 assert(entry.isTypeEntry() && "unexpected identifier entry");
305 assert(
306 llvm::isa<TestTypeWithLayoutType>(llvm::cast<Type>(entry.getKey())) &&
307 "wrong type passed in");
308 auto array = llvm::dyn_cast<ArrayAttr>(entry.getValue());
309 assert(array && array.getValue().size() == 2 &&
310 "expected array of two elements");
311 auto kind = llvm::dyn_cast<StringAttr>(array.getValue().front());
312 (void)kind;
313 assert(kind &&
314 (kind.getValue() == "size" || kind.getValue() == "alignment" ||
315 kind.getValue() == "preferred" || kind.getValue() == "index") &&
316 "unexpected kind");
317 assert(llvm::isa<IntegerAttr>(array.getValue().back()));
318 }
319 return success();
320}
321
322uint64_t TestTypeWithLayoutType::extractKind(DataLayoutEntryListRef params,
323 StringRef expectedKind) const {
324 for (DataLayoutEntryInterface entry : params) {
325 ArrayRef<Attribute> pair =
326 llvm::cast<ArrayAttr>(entry.getValue()).getValue();
327 StringRef kind = llvm::cast<StringAttr>(pair.front()).getValue();
328 if (kind == expectedKind)
329 return llvm::cast<IntegerAttr>(pair.back()).getValue().getZExtValue();
330 }
331 return 1;
332}
333
334//===----------------------------------------------------------------------===//
335// Dynamic Types
336//===----------------------------------------------------------------------===//
337
338/// Define a singleton dynamic type.
339static std::unique_ptr<DynamicTypeDefinition>
340getSingletonDynamicType(TestDialect *testDialect) {
341 return DynamicTypeDefinition::get(
342 "dynamic_singleton", testDialect,
343 [](function_ref<InFlightDiagnostic()> emitError,
344 ArrayRef<Attribute> args) {
345 if (!args.empty()) {
346 emitError() << "expected 0 type arguments, but had " << args.size();
347 return failure();
348 }
349 return success();
350 });
351}
352
353/// Define a dynamic type representing a pair.
354static std::unique_ptr<DynamicTypeDefinition>
355getPairDynamicType(TestDialect *testDialect) {
356 return DynamicTypeDefinition::get(
357 "dynamic_pair", testDialect,
358 [](function_ref<InFlightDiagnostic()> emitError,
359 ArrayRef<Attribute> args) {
360 if (args.size() != 2) {
361 emitError() << "expected 2 type arguments, but had " << args.size();
362 return failure();
363 }
364 return success();
365 });
366}
367
368static std::unique_ptr<DynamicTypeDefinition>
369getCustomAssemblyFormatDynamicType(TestDialect *testDialect) {
370 auto verifier = [](function_ref<InFlightDiagnostic()> emitError,
371 ArrayRef<Attribute> args) {
372 if (args.size() != 2) {
373 emitError() << "expected 2 type arguments, but had " << args.size();
374 return failure();
375 }
376 return success();
377 };
378
379 auto parser = [](AsmParser &parser,
380 llvm::SmallVectorImpl<Attribute> &parsedParams) {
381 Attribute leftAttr, rightAttr;
382 if (parser.parseLess() || parser.parseAttribute(result&: leftAttr) ||
383 parser.parseColon() || parser.parseAttribute(result&: rightAttr) ||
384 parser.parseGreater())
385 return failure();
386 parsedParams.push_back(Elt: leftAttr);
387 parsedParams.push_back(Elt: rightAttr);
388 return success();
389 };
390
391 auto printer = [](AsmPrinter &printer, ArrayRef<Attribute> params) {
392 printer << "<" << params[0] << ":" << params[1] << ">";
393 };
394
395 return DynamicTypeDefinition::get("dynamic_custom_assembly_format",
396 testDialect, std::move(verifier),
397 std::move(parser), std::move(printer));
398}
399
400test::detail::TestCustomStorageCtorTypeStorage *
401test::detail::TestCustomStorageCtorTypeStorage::construct(
402 mlir::StorageUniquer::StorageAllocator &, std::tuple<int> &&) {
403 // Note: this tests linker error ("undefined symbol"), the actual
404 // implementation is not important.
405 return nullptr;
406}
407
408//===----------------------------------------------------------------------===//
409// TestDialect
410//===----------------------------------------------------------------------===//
411
412namespace {
413
414struct PtrElementModel
415 : public LLVM::PointerElementTypeInterface::ExternalModel<PtrElementModel,
416 SimpleAType> {};
417} // namespace
418
419void TestDialect::registerTypes() {
420 addTypes<TestRecursiveType,
421#define GET_TYPEDEF_LIST
422#include "TestTypeDefs.cpp.inc"
423 >();
424 SimpleAType::attachInterface<PtrElementModel>(*getContext());
425
426 registerDynamicType(getSingletonDynamicType(this));
427 registerDynamicType(getPairDynamicType(this));
428 registerDynamicType(getCustomAssemblyFormatDynamicType(this));
429}
430
431Type TestDialect::parseType(DialectAsmParser &parser) const {
432 StringRef typeTag;
433 {
434 Type genType;
435 auto parseResult = generatedTypeParser(parser, &typeTag, genType);
436 if (parseResult.has_value())
437 return genType;
438 }
439
440 {
441 Type dynType;
442 auto parseResult = parseOptionalDynamicType(typeTag, parser, dynType);
443 if (parseResult.has_value()) {
444 if (succeeded(parseResult.value()))
445 return dynType;
446 return Type();
447 }
448 }
449
450 if (typeTag != "test_rec") {
451 parser.emitError(parser.getNameLoc()) << "unknown type!";
452 return Type();
453 }
454
455 StringRef name;
456 if (parser.parseLess() || parser.parseKeyword(&name))
457 return Type();
458 auto rec = TestRecursiveType::get(parser.getContext(), name);
459
460 FailureOr<AsmParser::CyclicParseReset> cyclicParse =
461 parser.tryStartCyclicParse(rec);
462
463 // If this type already has been parsed above in the stack, expect just the
464 // name.
465 if (failed(cyclicParse)) {
466 if (failed(parser.parseGreater()))
467 return Type();
468 return rec;
469 }
470
471 // Otherwise, parse the body and update the type.
472 if (failed(parser.parseComma()))
473 return Type();
474 Type subtype = parseType(parser);
475 if (!subtype || failed(parser.parseGreater()) || failed(rec.setBody(subtype)))
476 return Type();
477
478 return rec;
479}
480
481void TestDialect::printType(Type type, DialectAsmPrinter &printer) const {
482 if (succeeded(generatedTypePrinter(type, printer)))
483 return;
484
485 if (succeeded(printIfDynamicType(type, printer)))
486 return;
487
488 auto rec = llvm::cast<TestRecursiveType>(type);
489
490 FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrint =
491 printer.tryStartCyclicPrint(rec);
492
493 printer << "test_rec<" << rec.getName();
494 if (succeeded(cyclicPrint)) {
495 printer << ", ";
496 printType(rec.getBody(), printer);
497 }
498 printer << ">";
499}
500
501Type TestRecursiveAliasType::getBody() const { return getImpl()->body; }
502
503void TestRecursiveAliasType::setBody(Type type) { (void)Base::mutate(type); }
504
505StringRef TestRecursiveAliasType::getName() const { return getImpl()->name; }
506
507Type TestRecursiveAliasType::parse(AsmParser &parser) {
508 StringRef name;
509 if (parser.parseLess() || parser.parseKeyword(&name))
510 return Type();
511 auto rec = TestRecursiveAliasType::get(parser.getContext(), name);
512
513 FailureOr<AsmParser::CyclicParseReset> cyclicParse =
514 parser.tryStartCyclicParse(rec);
515
516 // If this type already has been parsed above in the stack, expect just the
517 // name.
518 if (failed(cyclicParse)) {
519 if (failed(parser.parseGreater()))
520 return Type();
521 return rec;
522 }
523
524 // Otherwise, parse the body and update the type.
525 if (failed(parser.parseComma()))
526 return Type();
527 Type subtype;
528 if (parser.parseType(subtype))
529 return nullptr;
530 if (!subtype || failed(parser.parseGreater()))
531 return Type();
532
533 rec.setBody(subtype);
534
535 return rec;
536}
537
538void TestRecursiveAliasType::print(AsmPrinter &printer) const {
539
540 FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrint =
541 printer.tryStartCyclicPrint(*this);
542
543 printer << "<" << getName();
544 if (succeeded(cyclicPrint)) {
545 printer << ", ";
546 printer << getBody();
547 }
548 printer << ">";
549}
550
551void TestTypeOpAsmTypeInterfaceType::getAsmName(
552 OpAsmSetNameFn setNameFn) const {
553 setNameFn("op_asm_type_interface");
554}
555
556::mlir::OpAsmDialectInterface::AliasResult
557TestTypeOpAsmTypeInterfaceType::getAlias(::llvm::raw_ostream &os) const {
558 os << "op_asm_type_interface_type";
559 return ::mlir::OpAsmDialectInterface::AliasResult::FinalAlias;
560}
561
562::mlir::LogicalResult TestTensorType::verifyCompatibleBufferType(
563 ::mlir::bufferization::BufferLikeType bufferType,
564 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) const {
565 if (auto testMemref = dyn_cast<TestMemrefType>(bufferType)) {
566 const bool valid = getShape() == testMemref.getShape() &&
567 getElementType() == testMemref.getElementType();
568 return mlir::success(valid);
569 }
570
571 // A builtin memref may leave an extent of the tensor dynamic.
572 if (auto builtinMemref = dyn_cast<MemRefType>(bufferType)) {
573 const bool valid = succeeded(verifyCompatibleShape(
574 getShape(), builtinMemref.getShape())) &&
575 getElementType() == builtinMemref.getElementType();
576 return mlir::success(valid);
577 }
578
579 return emitError() << "expected MemRefType or TestMemrefType";
580}
581
582::mlir::LogicalResult TestUnshapedType::verifyCompatibleBufferType(
583 ::mlir::bufferization::BufferLikeType bufferType,
584 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) const {
585 auto memref = dyn_cast<MemRefType>(bufferType);
586 if (!memref)
587 return emitError() << "expected MemRefType";
588 return mlir::success(getElementType() == memref.getElementType());
589}
590
591bool TestTensorLikeWrapperType::isTensorLike() const {
592 return isa<::mlir::bufferization::TensorLikeType>(getInner());
593}
594
595::mlir::LogicalResult TestTensorLikeWrapperType::verifyCompatibleBufferType(
596 ::mlir::bufferization::BufferLikeType bufferType,
597 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) const {
598 return cast<::mlir::bufferization::TensorLikeType>(getInner())
599 .verifyCompatibleBufferType(bufferType, emitError);
600}
601
602//===----------------------------------------------------------------------===//
603// TestTypeNewlineAndIndent
604//===----------------------------------------------------------------------===//
605
606Type TestTypeNewlineAndIndentType::parse(::mlir::AsmParser &parser) {
607 if (parser.parseLess() || parser.parseKeyword("indented_content") ||
608 parser.parseGreater()) {
609 return Type();
610 }
611 return get(parser.getContext());
612}
613
614void TestTypeNewlineAndIndentType::print(::mlir::AsmPrinter &printer) const {
615 printer << "<";
616 printer.increaseIndent();
617 printer.printNewline();
618 printer << "indented_content";
619 printer.decreaseIndent();
620 printer.printNewline();
621 printer << ">";
622}
623
624//===----------------------------------------------------------------------===//
625// TestDenseElementType - DenseElementTypeInterface Implementation
626//===----------------------------------------------------------------------===//
627
628// Elements are stored as 32-bit integers.
629size_t TestDenseElementType::getDenseElementBitSize() const { return 32; }
630
631Attribute
632TestDenseElementType::convertToAttribute(ArrayRef<char> rawData) const {
633 assert(rawData.size() == 4 && "expected 4 bytes for TestDenseElement");
634 int32_t value;
635 std::memcpy(&value, rawData.data(), sizeof(value));
636 return IntegerAttr::get(IntegerType::get(getContext(), 32), value);
637}
638
639LogicalResult TestDenseElementType::convertFromAttribute(
640 Attribute attr, SmallVectorImpl<char> &result) const {
641 auto intAttr = dyn_cast<IntegerAttr>(attr);
642 if (!intAttr || intAttr.getType().getIntOrFloatBitWidth() != 32)
643 return failure();
644 int32_t value = intAttr.getValue().getSExtValue();
645 result.append(reinterpret_cast<const char *>(&value),
646 reinterpret_cast<const char *>(&value) + sizeof(value));
647 return success();
648}
649