[llvm-branch-commits] [llvm] [mlir] [mlir][ODS] Add partitions for attributes and types (PR #241935)
Markus Böck via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Wed Nov 18 02:57:24 PST 2026
https://github.com/zero9178 updated https://github.com/llvm/llvm-project/pull/241935
>From a03b6f2548725923f7af2a4a53ff185736cdf7d8 Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Tue, 17 Nov 2026 11:05:33 +0000
Subject: [PATCH 1/5] [mlir][ODS] Add partitions for attributes and types
Allow attributes and types to be grouped into named partitions, like
ops. Each def can set `partition` to a `Partition` record. Passing
`-attrdefs-partition=<name>` or `-typedefs-partition=<name>` to the
attrdef/typedef decls and defs generators then emits only the defs of
that partition. A large dialect can thus split its attributes and types
over several compilation units with narrower headers.
The implementation mirrors the approach used in op partitioning
with a `register<DialectClass>Attributes` function (or Types) is used to register every attribute (or type) of the dialect and dispatches to partition specific functions.
The `generated{Parser,Printer}` function saw the biggest change.
It is not generated as `generated<DialectClass>{Attribute,Type}{Parser,Printer}` which is a method with public linkage.
This method is also generated for non-partitioned dialects and the old `generated{Parser,Printer}` function soft-deprecated (but for now retained for migration purposes).
The additional testing, the test dialect's attributes and types are split into the
partitions `Core` and `Syntax`.
This roughly halves the compile time (15.1s -> 6.7s + 6.9s) and peak memory (721 MiB -> 385 and
376 MiB) of the largest test dialect attribute compilation unit.
Co-authored-by: Claude <noreply at anthropic.com>
---
.../DefiningDialects/AttributesAndTypes.md | 57 ++-
mlir/include/mlir/IR/AttrTypeBase.td | 6 +
mlir/include/mlir/IR/DialectBase.td | 3 +-
.../FuncToLLVM/TestConvertCallOp.cpp | 2 +-
.../FuncToLLVM/TestConvertFuncOp.cpp | 2 +-
.../TestOneShotModuleBufferize.cpp | 3 +-
mlir/test/lib/Dialect/Test/CMakeLists.txt | 23 +-
mlir/test/lib/Dialect/Test/TestAttrDefs.td | 83 ++--
...tAttributes.cpp => TestAttributesCore.cpp} | 246 +-----------
...{TestAttributes.h => TestAttributesCore.h} | 15 +-
.../lib/Dialect/Test/TestAttributesSyntax.cpp | 260 ++++++++++++
.../lib/Dialect/Test/TestAttributesSyntax.h | 18 +
mlir/test/lib/Dialect/Test/TestDialect.cpp | 73 +++-
mlir/test/lib/Dialect/Test/TestDialect.h | 15 +-
mlir/test/lib/Dialect/Test/TestDialectBase.h | 26 ++
.../Dialect/Test/TestDialectInterfaces.cpp | 2 +-
mlir/test/lib/Dialect/Test/TestInterfaces.td | 20 +-
mlir/test/lib/Dialect/Test/TestOpDefs.cpp | 1 +
mlir/test/lib/Dialect/Test/TestOps.td | 5 +
.../lib/Dialect/Test/TestOpsAttributes.cpp | 4 +
.../test/lib/Dialect/Test/TestOpsPatterns.cpp | 2 +
.../test/lib/Dialect/Test/TestOpsProperties.h | 1 +
mlir/test/lib/Dialect/Test/TestOpsSyntax.h | 4 +-
mlir/test/lib/Dialect/Test/TestOpsTraits.cpp | 2 +
mlir/test/lib/Dialect/Test/TestPatterns.cpp | 2 +-
mlir/test/lib/Dialect/Test/TestTypeDefs.td | 66 ++--
.../Test/{TestTypes.cpp => TestTypesCore.cpp} | 154 +-------
.../Test/{TestTypes.h => TestTypesCore.h} | 69 +---
.../test/lib/Dialect/Test/TestTypesSyntax.cpp | 99 +++++
mlir/test/lib/Dialect/Test/TestTypesSyntax.h | 72 ++++
.../lib/IR/TestBuiltinAttributeInterfaces.cpp | 2 -
mlir/test/lib/IR/TestBytecodeRoundtrip.cpp | 1 +
mlir/test/lib/IR/TestInterfaces.cpp | 2 +-
mlir/test/lib/IR/TestTypes.cpp | 2 +-
.../mlir-tblgen/attr-type-partitions-error.td | 44 +++
mlir/test/mlir-tblgen/attr-type-partitions.td | 151 +++++++
mlir/test/mlir-tblgen/attrdefs.td | 13 +-
.../default-type-attr-print-parser.td | 8 +-
mlir/test/mlir-tblgen/op-partitions-error.td | 2 +-
mlir/test/mlir-tblgen/typedefs.td | 5 +-
mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp | 374 ++++++++++++++----
mlir/tools/mlir-tblgen/CMakeLists.txt | 1 +
mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp | 10 +-
mlir/tools/mlir-tblgen/OpGenHelpers.cpp | 57 +--
mlir/tools/mlir-tblgen/OpGenHelpers.h | 4 -
mlir/tools/mlir-tblgen/PartitionHelpers.cpp | 63 +++
mlir/tools/mlir-tblgen/PartitionHelpers.h | 65 +++
mlir/unittests/IR/InterfaceAttachmentTest.cpp | 4 +-
mlir/unittests/IR/InterfaceTest.cpp | 3 +-
mlir/unittests/Parser/ResourceTest.cpp | 1 -
50 files changed, 1439 insertions(+), 708 deletions(-)
rename mlir/test/lib/Dialect/Test/{TestAttributes.cpp => TestAttributesCore.cpp} (63%)
rename mlir/test/lib/Dialect/Test/{TestAttributes.h => TestAttributesCore.h} (78%)
create mode 100644 mlir/test/lib/Dialect/Test/TestAttributesSyntax.cpp
create mode 100644 mlir/test/lib/Dialect/Test/TestAttributesSyntax.h
create mode 100644 mlir/test/lib/Dialect/Test/TestDialectBase.h
rename mlir/test/lib/Dialect/Test/{TestTypes.cpp => TestTypesCore.cpp} (80%)
rename mlir/test/lib/Dialect/Test/{TestTypes.h => TestTypesCore.h} (63%)
create mode 100644 mlir/test/lib/Dialect/Test/TestTypesSyntax.cpp
create mode 100644 mlir/test/lib/Dialect/Test/TestTypesSyntax.h
create mode 100644 mlir/test/mlir-tblgen/attr-type-partitions-error.td
create mode 100644 mlir/test/mlir-tblgen/attr-type-partitions.td
create mode 100644 mlir/tools/mlir-tblgen/PartitionHelpers.cpp
create mode 100644 mlir/tools/mlir-tblgen/PartitionHelpers.h
diff --git a/mlir/docs/DefiningDialects/AttributesAndTypes.md b/mlir/docs/DefiningDialects/AttributesAndTypes.md
index 44abe29de9a916..621454b7a7ef73 100644
--- a/mlir/docs/DefiningDialects/AttributesAndTypes.md
+++ b/mlir/docs/DefiningDialects/AttributesAndTypes.md
@@ -524,17 +524,19 @@ the syntax for the Attribute or Type is simply the mnemonic.
For each dialect, two "dispatch" functions will be created: one for parsing and
one for printing. These static functions are placed alongside the class
-definitions and have the following function signatures:
+definitions in the C++ namespace of the dialect and have the following function
+signatures, where `<DialectClass>` is the C++ class name of the dialect:
```c++
-static OptionalParseResult generatedAttributeParser(
+static OptionalParseResult generated<DialectClass>AttributeParser(
AsmParser &parser, StringRef *mnemonic, Type type, Attribute &value);
-static LogicalResult generatedAttributePrinter(Attribute def,
- AsmPrinter &printer);
+static LogicalResult generated<DialectClass>AttributePrinter(
+ Attribute def, AsmPrinter &printer);
-static OptionalParseResult generatedTypeParser(
+static OptionalParseResult generated<DialectClass>TypeParser(
AsmParser &parser, StringRef *mnemonic, Type &value);
-static LogicalResult generatedTypePrinter(Type def, AsmPrinter &printer);
+static LogicalResult generated<DialectClass>TypePrinter(
+ Type def, AsmPrinter &printer);
```
If `*mnemonic` is empty, the parsers first parse the mnemonic. Otherwise, they
@@ -1252,3 +1254,46 @@ void MyDialect::initialize() {
registerMyDialectTypes(this);
}
```
+
+#### Logical Sharding with Partitions
+
+Like [ops](Operations.md/#logical-sharding-with-op-partitions), attributes and
+types can be grouped into named partitions by setting their `partition` to a
+`Partition` record, so that each partition is generated into its own
+declaration and definition files:
+
+```tablegen
+def MyDialect_CoreAttrs : Partition<"Core">;
+def MyDialect_LayoutAttrs : Partition<"Layout">;
+
+class MyDialect_Attr<string name, string attrMnemonic>
+ : AttrDef<MyDialect, name> {
+ let mnemonic = attrMnemonic;
+ // Attributes are in partition `Core`, unless they set another partition.
+ let partition = MyDialect_CoreAttrs;
+}
+
+def MyIntAttr : MyDialect_Attr<"MyInt", "int"> { ... }
+
+let partition = MyDialect_LayoutAttrs in
+def MyLayoutAttr : MyDialect_Attr<"MyLayout", "layout"> { ... }
+```
+
+Passing `-attrdefs-partition=<partition>` (or `-typedefs-partition=<partition>`)
+with a partition name to `-gen-attrdef-decls` and `-gen-attrdef-defs` (or
+`-gen-typedef-decls` and `-gen-typedef-defs`) generates only the attributes (or
+types) of that partition. Every generated attribute or type must then be in a
+partition, and the specified partition must have attributes or types. Without
+the option, `partition` is ignored.
+
+The dialect calls the same functions with and without partitions:
+`register<DialectClass>Attributes` (or `register<DialectClass>Types`) to
+register the attributes (or types), and, if it implements its own parser and
+printer, `generated<DialectClass>AttributeParser` and
+`generated<DialectClass>AttributePrinter` (or `...Type...`).
+
+Without partitions, these are `static` functions of the definitions, which can
+only be called in the compilation unit that includes the definitions. With
+partitions, they are declared by the declarations of every partition, so they
+can be called in any compilation unit that includes the declarations of a
+partition.
diff --git a/mlir/include/mlir/IR/AttrTypeBase.td b/mlir/include/mlir/IR/AttrTypeBase.td
index c478c281ac4602..b70774f447608b 100644
--- a/mlir/include/mlir/IR/AttrTypeBase.td
+++ b/mlir/include/mlir/IR/AttrTypeBase.td
@@ -254,6 +254,12 @@ class AttrOrTypeDef<string valueType, string name, list<Trait> defTraits,
// Generate a default 'getAlias' method for OpAsm{Type,Attr}Interface.
bit genMnemonicAlias = 0;
+
+ // Optional. The partition of this def. `-gen-{attr,type}def-{decls,defs}`
+ // generate the defs of one partition at a time with
+ // `-{attr,type}defs-partition=...`, which requires every generated def to be
+ // in a partition. Ignored without `-{attr,type}defs-partition`.
+ Partition partition = ?;
}
// Define a new attribute, named `name`, belonging to `dialect` that inherits
diff --git a/mlir/include/mlir/IR/DialectBase.td b/mlir/include/mlir/IR/DialectBase.td
index 046aaf13c6a11a..f9bb130c6f3857 100644
--- a/mlir/include/mlir/IR/DialectBase.td
+++ b/mlir/include/mlir/IR/DialectBase.td
@@ -102,7 +102,8 @@ class Dialect {
}
// A partition of the definitions of a dialect, for "logical sharding" of their
-// generated declarations and definitions. See `Op::partition`.
+// generated declarations and definitions. See `Op::partition` and
+// `AttrOrTypeDef::partition`.
class Partition<string name> {
// The name of the partition, a C++ identifier. Generators select a partition
// by this name, e.g. `-gen-op-decls` and `-gen-op-defs` with
diff --git a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
index 89e02814950fd8..2035c7a2e81c2f 100644
--- a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
+++ b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
@@ -7,7 +7,7 @@
//===----------------------------------------------------------------------===//
#include "TestOpsConversion.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
diff --git a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertFuncOp.cpp b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertFuncOp.cpp
index 75168dde93130f..64155d87aaee8b 100644
--- a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertFuncOp.cpp
+++ b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertFuncOp.cpp
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
-#include "TestDialect.h"
+#include "TestTypesCore.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
diff --git a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
index fc50be654a04df..cb60b63ad35d98 100644
--- a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
+++ b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
@@ -14,8 +14,9 @@
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Pass/Pass.h"
-#include "TestAttributes.h" // TestTensorEncodingAttr, TestMemRefLayoutAttr
+#include "TestAttributesCore.h" // TestTensorEncodingAttr, TestMemRefLayoutAttr
#include "TestOpsInterfaces.h"
+#include "TestTypesCore.h" // TestTensorType, TestMemrefType
#include "llvm/ADT/TypeSwitch.h"
diff --git a/mlir/test/lib/Dialect/Test/CMakeLists.txt b/mlir/test/lib/Dialect/Test/CMakeLists.txt
index 5b6b54bc75350a..85ffc745383d70 100644
--- a/mlir/test/lib/Dialect/Test/CMakeLists.txt
+++ b/mlir/test/lib/Dialect/Test/CMakeLists.txt
@@ -15,14 +15,23 @@ mlir_tablegen(TestOpInterfaces.h.inc -gen-op-interface-decls)
mlir_tablegen(TestOpInterfaces.cpp.inc -gen-op-interface-defs)
add_public_tablegen_target(MLIRTestInterfaceIncGen)
+# The attribute and type partitions, each with its own header and source file.
set(LLVM_TARGET_DEFINITIONS TestOps.td)
-mlir_tablegen(TestAttrDefs.h.inc -gen-attrdef-decls -attrdefs-dialect=test)
-mlir_tablegen(TestAttrDefs.cpp.inc -gen-attrdef-defs -attrdefs-dialect=test)
+foreach(partition Core Syntax)
+ mlir_tablegen(TestAttributes${partition}.h.inc -gen-attrdef-decls
+ -attrdefs-dialect=test -attrdefs-partition=${partition})
+ mlir_tablegen(TestAttributes${partition}.cpp.inc -gen-attrdef-defs
+ -attrdefs-dialect=test -attrdefs-partition=${partition})
+endforeach()
add_public_tablegen_target(MLIRTestAttrDefIncGen)
set(LLVM_TARGET_DEFINITIONS TestTypeDefs.td)
-mlir_tablegen(TestTypeDefs.h.inc -gen-typedef-decls -typedefs-dialect=test)
-mlir_tablegen(TestTypeDefs.cpp.inc -gen-typedef-defs -typedefs-dialect=test)
+foreach(partition Core Syntax)
+ mlir_tablegen(TestTypes${partition}.h.inc -gen-typedef-decls
+ -typedefs-dialect=test -typedefs-partition=${partition})
+ mlir_tablegen(TestTypes${partition}.cpp.inc -gen-typedef-defs
+ -typedefs-dialect=test -typedefs-partition=${partition})
+endforeach()
add_public_tablegen_target(MLIRTestTypeDefIncGen)
set(LLVM_TARGET_DEFINITIONS TestEnumDefs.td)
@@ -48,7 +57,8 @@ add_public_tablegen_target(MLIRTestOpsSyntaxIncGen)
# Exclude tests from libMLIR.so
add_mlir_library(MLIRTestDialect
- TestAttributes.cpp
+ TestAttributesCore.cpp
+ TestAttributesSyntax.cpp
TestDialect.cpp
TestFormatUtils.cpp
TestInterfaces.cpp
@@ -62,7 +72,8 @@ add_mlir_library(MLIRTestDialect
TestOpsTraits.cpp
TestPatterns.cpp
TestTraits.cpp
- TestTypes.cpp
+ TestTypesCore.cpp
+ TestTypesSyntax.cpp
TestOpsSyntax.cpp
TestDialectInterfaces.cpp
diff --git a/mlir/test/lib/Dialect/Test/TestAttrDefs.td b/mlir/test/lib/Dialect/Test/TestAttrDefs.td
index be1fbe556cb3c4..942ae6a431c7a5 100644
--- a/mlir/test/lib/Dialect/Test/TestAttrDefs.td
+++ b/mlir/test/lib/Dialect/Test/TestAttrDefs.td
@@ -25,11 +25,28 @@ include "mlir/IR/OpAsmInterface.td"
include "mlir/IR/SymbolInterfaces.td"
include "mlir/IR/TensorEncoding.td"
+// The attributes and types of the test dialect are in two partitions, each
+// generated and compiled separately: `Syntax` for those that exercise custom
+// and declarative assembly formats, and `Core` for all others. Since `Core` is
+// compiled without the declarations of `Syntax`, attributes and types in
+// `Core` must not refer to those in `Syntax`.
+def Test_AttrTypeCorePartition : Partition<"Core">;
+def Test_AttrTypeSyntaxPartition : Partition<"Syntax">;
+
// All of the attributes will extend this class.
class Test_Attr<string name, list<Trait> traits = []>
- : AttrDef<Test_Dialect, name, traits>;
+ : AttrDef<Test_Dialect, name, traits> {
+ let partition = Test_AttrTypeCorePartition;
+}
-class Test_LocAttr<string name> : LocationAttrDef<Test_Dialect, name, []>;
+class Test_SyntaxAttr<string name, list<Trait> traits = []>
+ : Test_Attr<name, traits> {
+ let partition = Test_AttrTypeSyntaxPartition;
+}
+
+class Test_LocAttr<string name> : LocationAttrDef<Test_Dialect, name, []> {
+ let partition = Test_AttrTypeCorePartition;
+}
def SimpleAttrA : Test_Attr<"SimpleA"> {
let mnemonic = "smpla";
@@ -53,7 +70,7 @@ def CompoundAttrA : Test_Attr<"CompoundA"> {
);
let hasCustomAssemblyFormat = 1;
}
-def CompoundAttrNested : Test_Attr<"CompoundAttrNested"> {
+def CompoundAttrNested : Test_SyntaxAttr<"CompoundAttrNested"> {
let mnemonic = "cmpnd_nested";
let parameters = (ins CompoundAttrA : $nested );
let assemblyFormat = "`<` `nested` `=` $nested `>`";
@@ -61,7 +78,7 @@ def CompoundAttrNested : Test_Attr<"CompoundAttrNested"> {
// An attribute testing AttributeSelfTypeParameter.
def AttrWithSelfTypeParam
- : Test_Attr<"AttrWithSelfTypeParam", [TypedAttrInterface]> {
+ : Test_SyntaxAttr<"AttrWithSelfTypeParam", [TypedAttrInterface]> {
let mnemonic = "attr_with_self_type_param";
let parameters = (ins AttributeSelfTypeParameter<"">:$type);
let assemblyFormat = "";
@@ -69,7 +86,7 @@ def AttrWithSelfTypeParam
// An attribute testing AttributeSelfTypeParameter.
def AttrWithTypeBuilder
- : Test_Attr<"AttrWithTypeBuilder", [TypedAttrInterface]> {
+ : Test_SyntaxAttr<"AttrWithTypeBuilder", [TypedAttrInterface]> {
let mnemonic = "attr_with_type_builder";
let parameters = (ins
"::mlir::IntegerAttr":$attr,
@@ -88,7 +105,7 @@ def AttrWithTrait : Test_Attr<"AttrWithTrait", [TestAttrTrait]> {
}
// An attribute of a list of decimal formatted integers in similar format to shapes.
-def TestDecimalShapeAttr : Test_Attr<"TestDecimalShape"> {
+def TestDecimalShapeAttr : Test_SyntaxAttr<"TestDecimalShape"> {
let mnemonic = "decimal_shape";
let parameters = (ins ArrayRefParameter<"int64_t">:$shape);
@@ -145,7 +162,7 @@ def TestSubElementsAccessAttr : Test_Attr<"TestSubElementsAccess"> {
}
// A more complex parameterized attribute with multiple level of nesting.
-def CompoundNestedInner : Test_Attr<"CompoundNestedInner"> {
+def CompoundNestedInner : Test_SyntaxAttr<"CompoundNestedInner"> {
let mnemonic = "cmpnd_nested_inner";
// List of type parameters.
let parameters = (
@@ -156,7 +173,7 @@ def CompoundNestedInner : Test_Attr<"CompoundNestedInner"> {
let assemblyFormat = "`<` $some_int $cmpdA `>`";
}
-def CompoundNestedOuter : Test_Attr<"CompoundNestedOuter"> {
+def CompoundNestedOuter : Test_SyntaxAttr<"CompoundNestedOuter"> {
let mnemonic = "cmpnd_nested_outer";
// List of type parameters.
@@ -167,7 +184,7 @@ def CompoundNestedOuter : Test_Attr<"CompoundNestedOuter"> {
let assemblyFormat = "`<` `i` $inner `>`";
}
-def CompoundNestedOuterQual : Test_Attr<"CompoundNestedOuterQual"> {
+def CompoundNestedOuterQual : Test_SyntaxAttr<"CompoundNestedOuterQual"> {
let mnemonic = "cmpnd_nested_outer_qual";
// List of type parameters.
@@ -194,7 +211,7 @@ def TestParamVector : ArrayRefParameter<"int", ""> {
def TestParamUnsigned : AttrParameter<"uint64_t", ""> {}
-def TestAttrWithFormat : Test_Attr<"TestAttrWithFormat"> {
+def TestAttrWithFormat : Test_SyntaxAttr<"TestAttrWithFormat"> {
let parameters = (
ins
TestParamOne:$one,
@@ -218,32 +235,32 @@ def TestAttrWithFormat : Test_Attr<"TestAttrWithFormat"> {
let genVerifyDecl = 1;
}
-def TestAttrWithOptionalSigned : Test_Attr<"TestAttrWithOptionalSigned"> {
+def TestAttrWithOptionalSigned : Test_SyntaxAttr<"TestAttrWithOptionalSigned"> {
let parameters = (ins OptionalParameter<"std::optional<int64_t>">:$value);
let assemblyFormat = "`<` $value `>`";
let mnemonic = "attr_with_optional_signed";
}
-def TestAttrWithOptionalUnsigned : Test_Attr<"TestAttrWithOptionalUnsigned"> {
+def TestAttrWithOptionalUnsigned : Test_SyntaxAttr<"TestAttrWithOptionalUnsigned"> {
let parameters = (ins OptionalParameter<"std::optional<uint64_t>">:$value);
let assemblyFormat = "`<` $value `>`";
let mnemonic = "attr_with_optional_unsigned";
}
-def TestAttrWithOptionalEnum : Test_Attr<"TestAttrWithOptionalEnum"> {
+def TestAttrWithOptionalEnum : Test_SyntaxAttr<"TestAttrWithOptionalEnum"> {
let parameters = (ins OptionalParameter<"std::optional<SimpleEnum>">:$value);
let assemblyFormat = "`<` $value `>`";
let mnemonic = "attr_with_optional_enum";
}
-def TestAttrUgly : Test_Attr<"TestAttrUgly"> {
+def TestAttrUgly : Test_SyntaxAttr<"TestAttrUgly"> {
let parameters = (ins "::mlir::Attribute":$attr);
let mnemonic = "attr_ugly";
let assemblyFormat = "`begin` $attr `end`";
}
-def TestAttrParams: Test_Attr<"TestAttrParams"> {
+def TestAttrParams: Test_SyntaxAttr<"TestAttrParams"> {
let parameters = (ins "int":$v0, "int":$v1);
let mnemonic = "attr_params";
@@ -253,7 +270,7 @@ def TestAttrParams: Test_Attr<"TestAttrParams"> {
// Test roundtrip of ArrayRefParameter in struct format (issue #156623).
// An ArrayRefParameter without a custom printer in a non-last struct position
// must be wrapped in `[...]` to be parseable.
-def TestAttrArrayRefStruct : Test_Attr<"TestAttrArrayRefStruct"> {
+def TestAttrArrayRefStruct : Test_SyntaxAttr<"TestAttrArrayRefStruct"> {
let parameters = (ins
ArrayRefParameter<"int64_t">:$elements,
"int64_t":$count
@@ -264,7 +281,7 @@ def TestAttrArrayRefStruct : Test_Attr<"TestAttrArrayRefStruct"> {
// Test that ArrayRefParameter in the LAST struct position is NOT wrapped:
// no ambiguity exists because there is no following comma separator.
-def TestAttrArrayRefStructLast : Test_Attr<"TestAttrArrayRefStructLast"> {
+def TestAttrArrayRefStructLast : Test_SyntaxAttr<"TestAttrArrayRefStructLast"> {
let parameters = (ins
"int64_t":$count,
ArrayRefParameter<"int64_t">:$elements
@@ -274,7 +291,7 @@ def TestAttrArrayRefStructLast : Test_Attr<"TestAttrArrayRefStructLast"> {
}
// Test roundtrip of OptionalArrayRefParameter in non-last struct position.
-def TestAttrOptArrayRefStruct : Test_Attr<"TestAttrOptArrayRefStruct"> {
+def TestAttrOptArrayRefStruct : Test_SyntaxAttr<"TestAttrOptArrayRefStruct"> {
let parameters = (ins
OptionalArrayRefParameter<"int64_t">:$elements,
"int64_t":$count
@@ -284,7 +301,7 @@ def TestAttrOptArrayRefStruct : Test_Attr<"TestAttrOptArrayRefStruct"> {
}
// Test types can be parsed/printed.
-def TestAttrWithTypeParam : Test_Attr<"TestAttrWithTypeParam"> {
+def TestAttrWithTypeParam : Test_SyntaxAttr<"TestAttrWithTypeParam"> {
let parameters = (ins "::mlir::IntegerType":$int_type,
"::mlir::Type":$any_type);
let mnemonic = "attr_with_type";
@@ -293,7 +310,7 @@ def TestAttrWithTypeParam : Test_Attr<"TestAttrWithTypeParam"> {
// Test self type parameter with assembly format.
def TestAttrSelfTypeParameterFormat
- : Test_Attr<"TestAttrSelfTypeParameterFormat", [TypedAttrInterface]> {
+ : Test_SyntaxAttr<"TestAttrSelfTypeParameterFormat", [TypedAttrInterface]> {
let parameters = (ins "int":$a, AttributeSelfTypeParameter<"">:$type);
let mnemonic = "attr_self_type_format";
@@ -301,7 +318,7 @@ def TestAttrSelfTypeParameterFormat
}
def TestAttrSelfTypeParameterStructFormat
- : Test_Attr<"TestAttrSelfTypeParameterStructFormat", [TypedAttrInterface]> {
+ : Test_SyntaxAttr<"TestAttrSelfTypeParameterStructFormat", [TypedAttrInterface]> {
let parameters = (ins "int":$a, AttributeSelfTypeParameter<"">:$type);
let mnemonic = "attr_self_type_struct_format";
@@ -345,12 +362,14 @@ def TestExtern1DI64ElementsAttr : Test_Attr<"TestExtern1DI64Elements", [Elements
}
// An array of nested attributes.
+let partition = Test_AttrTypeSyntaxPartition in
def TestArrayOfUglyAttrs : ArrayOfAttr<Test_Dialect, "ArrayOfUglyAttrs",
"array_of_ugly", "TestAttrUglyAttr"> {
let assemblyFormat = "`[` (`]`) : ($value^ ` ` `]`)?";
}
// An array of integers.
+let partition = Test_AttrTypeCorePartition in {
def TestArrayOfInts : ArrayOfAttr<Test_Dialect, "ArrayOfInts",
"array_of_ints", "int32_t">;
@@ -364,11 +383,13 @@ def TestSimpleEnumAttr
: EnumAttr<Test_Dialect, TestSimpleEnum, "simple_enum">;
def TestArrayOfEnums : ArrayOfAttr<Test_Dialect, "ArrayOfEnums",
"array_of_enums", "SimpleEnumAttr">;
+} // let partition = Test_AttrTypeCorePartition
+let partition = Test_AttrTypeSyntaxPartition in
def TestStructEnumAttr
: EnumAttr<Test_Dialect, TestStructEnum, "struct_enum_value">;
-def TestAttrEnumAttrStruct : Test_Attr<"TestAttrEnumAttrStruct"> {
+def TestAttrEnumAttrStruct : Test_SyntaxAttr<"TestAttrEnumAttrStruct"> {
let parameters = (ins
EnumAttrParameter<TestStructEnumAttr>:$required,
OptionalEnumAttrParameter<TestStructEnumAttr>:$optional,
@@ -380,10 +401,11 @@ def TestAttrEnumAttrStruct : Test_Attr<"TestAttrEnumAttrStruct"> {
let assemblyFormat = "`<` struct(params) `>`";
}
+let partition = Test_AttrTypeSyntaxPartition in
def TestStructBitEnumAttr
: EnumAttr<Test_Dialect, TestStructBitEnum, "struct_bit_enum_value">;
-def TestAttrBitEnumAttrStruct : Test_Attr<"TestAttrBitEnumAttrStruct"> {
+def TestAttrBitEnumAttrStruct : Test_SyntaxAttr<"TestAttrBitEnumAttrStruct"> {
let parameters = (ins
EnumAttrParameter<TestStructBitEnumAttr>:$flags,
"int64_t":$count
@@ -393,12 +415,13 @@ def TestAttrBitEnumAttrStruct : Test_Attr<"TestAttrBitEnumAttrStruct"> {
}
// Test custom directive as optional group anchor.
-def TestCustomAnchor : Test_Attr<"TestCustomAnchor"> {
+def TestCustomAnchor : Test_SyntaxAttr<"TestCustomAnchor"> {
let parameters = (ins "int":$a, OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "custom_anchor";
let assemblyFormat = "`<` $a (`>`) : (`,` custom<TrueFalse>($b)^ `>`)?";
}
+let partition = Test_AttrTypeCorePartition in
def Test_IteratorTypeEnum
: EnumAttr<Test_Dialect, IteratorType, "iterator_type">;
@@ -416,7 +439,7 @@ def TestCopyCount : Test_Attr<"TestCopyCount"> {
let genVerifyDecl = 1;
}
-def TestConditionalAliasAttr : Test_Attr<"TestConditionalAlias"> {
+def TestConditionalAliasAttr : Test_SyntaxAttr<"TestConditionalAlias"> {
let mnemonic = "conditional_alias";
let parameters = (ins "mlir::StringAttr":$value);
let assemblyFormat = [{
@@ -424,7 +447,7 @@ def TestConditionalAliasAttr : Test_Attr<"TestConditionalAlias"> {
}];
}
-def TestNestedAliasAttr : Test_Attr<"TestNestedAlias"> {
+def TestNestedAliasAttr : Test_SyntaxAttr<"TestNestedAlias"> {
let mnemonic = "nested_alias";
let parameters = (ins "mlir::StringAttr":$value, OptionalParameter<"TestNestedAliasAttr">:$nested);
let assemblyFormat = [{
@@ -434,7 +457,7 @@ def TestNestedAliasAttr : Test_Attr<"TestNestedAlias"> {
// Test AsmParser::parseFloat(const fltSemnatics&, APFloat&) API through the
// custom parser and printer.
-def TestCustomFloatAttr : Test_Attr<"TestCustomFloat"> {
+def TestCustomFloatAttr : Test_SyntaxAttr<"TestCustomFloat"> {
let mnemonic = "custom_float";
let parameters = (ins "mlir::StringAttr":$type_str, APFloatParameter<"">:$value);
@@ -444,7 +467,7 @@ def TestCustomFloatAttr : Test_Attr<"TestCustomFloat"> {
}
// Test `struct` with nested `custom` assembly format.
-def TestCustomStructAttr : Test_Attr<"TestCustomStruct"> {
+def TestCustomStructAttr : Test_SyntaxAttr<"TestCustomStruct"> {
let mnemonic = "custom_struct";
let parameters = (ins "mlir::StringAttr":$type_str, "int64_t":$value,
OptionalParameter<"mlir::ArrayAttr">:$opt_value);
@@ -494,7 +517,7 @@ def TestOpAsmAttrInterfaceTablegenDefaultAttr : Test_Attr<"TestOpAsmAttrInterfac
}
// Test attribute containing a slash token
-def SlashAttr: Test_Attr<"Slash">{
+def SlashAttr: Test_SyntaxAttr<"Slash">{
let mnemonic = "slash_attr";
let parameters = (
@@ -542,7 +565,7 @@ def TestSymbolRefAttr : Test_Attr<"TestSymbolRef",
let assemblyFormat = "`<` $symbol `>`";
}
-def TestAttrNewlineAndIndent : Test_Attr<"TestAttrNewlineAndIndent"> {
+def TestAttrNewlineAndIndent : Test_SyntaxAttr<"TestAttrNewlineAndIndent"> {
let mnemonic = "newline_and_indent";
let parameters = (ins "::mlir::Type":$indentType);
let hasCustomAssemblyFormat = 1;
diff --git a/mlir/test/lib/Dialect/Test/TestAttributes.cpp b/mlir/test/lib/Dialect/Test/TestAttributesCore.cpp
similarity index 63%
rename from mlir/test/lib/Dialect/Test/TestAttributes.cpp
rename to mlir/test/lib/Dialect/Test/TestAttributesCore.cpp
index d86a32af6c39a7..e7fc915c5f7188 100644
--- a/mlir/test/lib/Dialect/Test/TestAttributes.cpp
+++ b/mlir/test/lib/Dialect/Test/TestAttributesCore.cpp
@@ -1,4 +1,4 @@
-//===- TestAttributes.cpp - MLIR Test Dialect Attributes --------*- C++ -*-===//
+//===- TestAttributesCore.cpp - Test attributes in `Core` -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -6,23 +6,18 @@
//
//===----------------------------------------------------------------------===//
//
-// This file contains attributes defined by the TestDialect for testing various
-// features of MLIR.
+// This file contains the attributes of the test dialect in partition `Core`.
//
//===----------------------------------------------------------------------===//
-#include "TestAttributes.h"
-#include "TestDialect.h"
-#include "TestTypes.h"
+#include "TestAttributesCore.h"
+#include "TestDialectBase.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/ExtensibleDialect.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/Types.h"
-#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/bit.h"
-#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace mlir;
@@ -59,43 +54,6 @@ void CompoundAAttr::print(AsmPrinter &printer) const {
printer << "]>";
}
-//===----------------------------------------------------------------------===//
-// CompoundAAttr
-//===----------------------------------------------------------------------===//
-
-Attribute TestDecimalShapeAttr::parse(AsmParser &parser, Type type) {
- if (parser.parseLess()) {
- return Attribute();
- }
- SmallVector<int64_t> shape;
- if (parser.parseOptionalGreater()) {
- auto parseDecimal = [&]() {
- shape.emplace_back();
- auto parseResult = parser.parseOptionalDecimalInteger(shape.back());
- if (!parseResult.has_value() || failed(*parseResult)) {
- parser.emitError(parser.getCurrentLocation()) << "expected an integer";
- return failure();
- }
- return success();
- };
- if (failed(parseDecimal())) {
- return Attribute();
- }
- while (failed(parser.parseOptionalGreater())) {
- if (failed(parser.parseXInDimensionList()) || failed(parseDecimal())) {
- return Attribute();
- }
- }
- }
- return get(parser.getContext(), shape);
-}
-
-void TestDecimalShapeAttr::print(AsmPrinter &printer) const {
- printer << "<";
- llvm::interleave(getShape(), printer, "x");
- printer << ">";
-}
-
Attribute TestI64ElementsAttr::parse(AsmParser &parser, Type type) {
SmallVector<uint64_t> elements;
if (parser.parseLess() || parser.parseLSquare())
@@ -133,36 +91,6 @@ TestI64ElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError,
return success();
}
-LogicalResult TestAttrWithFormatAttr::verify(
- function_ref<InFlightDiagnostic()> emitError, int64_t one, std::string two,
- IntegerAttr three, ArrayRef<int> four, uint64_t five, ArrayRef<int> six,
- ArrayRef<AttrWithTypeBuilderAttr> arrayOfAttrs) {
- if (four.size() != static_cast<unsigned>(one))
- return emitError() << "expected 'one' to equal 'four.size()'";
- return success();
-}
-
-//===----------------------------------------------------------------------===//
-// Utility Functions for Generated Attributes
-//===----------------------------------------------------------------------===//
-
-static FailureOr<SmallVector<int>> parseIntArray(AsmParser &parser) {
- SmallVector<int> ints;
- if (parser.parseLSquare() || parser.parseCommaSeparatedList([&]() {
- ints.push_back(0);
- return parser.parseInteger(ints.back());
- }) ||
- parser.parseRSquare())
- return failure();
- return ints;
-}
-
-static void printIntArray(AsmPrinter &printer, ArrayRef<int> ints) {
- printer << '[';
- llvm::interleaveComma(ints, printer);
- printer << ']';
-}
-
//===----------------------------------------------------------------------===//
// TestSubElementsAccessAttr
//===----------------------------------------------------------------------===//
@@ -194,22 +122,6 @@ ArrayRef<uint64_t> TestExtern1DI64ElementsAttr::getElements() const {
return {};
}
-//===----------------------------------------------------------------------===//
-// TestCustomAnchorAttr
-//===----------------------------------------------------------------------===//
-
-static ParseResult parseTrueFalse(AsmParser &p, std::optional<int> &result) {
- bool b;
- if (p.parseInteger(b))
- return failure();
- result = b;
- return success();
-}
-
-static void printTrueFalse(AsmPrinter &p, std::optional<int> result) {
- p << (*result ? "true" : "false");
-}
-
//===----------------------------------------------------------------------===//
// TestCopyCountAttr Implementation
//===----------------------------------------------------------------------===//
@@ -279,112 +191,6 @@ static llvm::hash_code hash_value(const test::CopyCount ©Count) {
}
} // namespace test
-//===----------------------------------------------------------------------===//
-// TestConditionalAliasAttr
-//===----------------------------------------------------------------------===//
-
-/// Attempt to parse the conditionally-aliased string attribute as a keyword or
-/// string, else try to parse an alias.
-static ParseResult parseConditionalAlias(AsmParser &p, StringAttr &value) {
- std::string str;
- if (succeeded(p.parseOptionalKeywordOrString(&str))) {
- value = StringAttr::get(p.getContext(), str);
- return success();
- }
- return p.parseAttribute(value);
-}
-
-/// Print the string attribute as an alias if it has one, otherwise print it as
-/// a keyword if possible.
-static void printConditionalAlias(AsmPrinter &p, StringAttr value) {
- if (succeeded(p.printAlias(value)))
- return;
- p.printKeywordOrString(value);
-}
-
-//===----------------------------------------------------------------------===//
-// Custom Float Attribute
-//===----------------------------------------------------------------------===//
-
-static void printCustomFloatAttr(AsmPrinter &p, StringAttr typeStrAttr,
- APFloat value) {
- p << typeStrAttr << " : " << value;
-}
-
-static ParseResult parseCustomFloatAttr(AsmParser &p, StringAttr &typeStrAttr,
- FailureOr<APFloat> &value) {
-
- std::string str;
- if (p.parseString(&str))
- return failure();
-
- typeStrAttr = StringAttr::get(p.getContext(), str);
-
- if (p.parseColon())
- return failure();
-
- const llvm::fltSemantics *semantics;
- if (str == "float")
- semantics = &llvm::APFloat::IEEEsingle();
- else if (str == "double")
- semantics = &llvm::APFloat::IEEEdouble();
- else if (str == "fp80")
- semantics = &llvm::APFloat::x87DoubleExtended();
- else
- return p.emitError(p.getCurrentLocation(), "unknown float type, expected "
- "'float', 'double' or 'fp80'");
-
- APFloat parsedValue(0.0);
- if (p.parseFloat(*semantics, parsedValue))
- return failure();
-
- value.emplace(parsedValue);
- return success();
-}
-
-//===----------------------------------------------------------------------===//
-// TestCustomStructAttr
-//===----------------------------------------------------------------------===//
-
-static void printCustomStructAttr(AsmPrinter &p, int64_t value) {
- if (ShapedType::isDynamic(value)) {
- p << "?";
- } else {
- p.printStrippedAttrOrType(value);
- }
-}
-
-static ParseResult parseCustomStructAttr(AsmParser &p, int64_t &value) {
- if (succeeded(p.parseOptionalQuestion())) {
- value = ShapedType::kDynamic;
- return success();
- }
- return p.parseInteger(value);
-}
-
-static void printCustomOptStructFieldAttr(AsmPrinter &p, ArrayAttr attr) {
- if (attr && attr.size() == 1 && isa<IntegerAttr>(attr[0])) {
- p << cast<IntegerAttr>(attr[0]).getInt();
- } else {
- p.printStrippedAttrOrType(attr);
- }
-}
-
-static ParseResult parseCustomOptStructFieldAttr(AsmParser &p,
- ArrayAttr &attr) {
- int64_t value;
- OptionalParseResult result = p.parseOptionalInteger(value);
- if (result.has_value()) {
- if (failed(result.value()))
- return failure();
- attr = ArrayAttr::get(
- p.getContext(),
- {IntegerAttr::get(IntegerType::get(p.getContext(), 64), value)});
- return success();
- }
- return p.parseAttribute(attr);
-}
-
//===----------------------------------------------------------------------===//
// TestOpAsmAttrInterfaceAttr
//===----------------------------------------------------------------------===//
@@ -450,30 +256,6 @@ bool TestConstMemorySpaceAttr::isValidPtrIntCast(
return false;
}
-//===----------------------------------------------------------------------===//
-// TestAttrNewlineAndIndent
-//===----------------------------------------------------------------------===//
-
-Attribute TestAttrNewlineAndIndentAttr::parse(::mlir::AsmParser &parser,
- ::mlir::Type type) {
- Type indentType;
- if (parser.parseLess() || parser.parseType(indentType) ||
- parser.parseGreater()) {
- return Attribute();
- }
- return get(parser.getContext(), indentType);
-}
-
-void TestAttrNewlineAndIndentAttr::print(::mlir::AsmPrinter &printer) const {
- printer << "<";
- printer.increaseIndent();
- printer.printNewline();
- printer << getIndentType();
- printer.decreaseIndent();
- printer.printNewline();
- printer << ">";
-}
-
//===----------------------------------------------------------------------===//
// Tablegen Generated Definitions
//===----------------------------------------------------------------------===//
@@ -481,7 +263,7 @@ void TestAttrNewlineAndIndentAttr::print(::mlir::AsmPrinter &printer) const {
#include "TestAttrInterfaces.cpp.inc"
#include "TestOpEnums.cpp.inc"
#define GET_ATTRDEF_CLASSES
-#include "TestAttrDefs.cpp.inc"
+#include "TestAttributesCore.cpp.inc"
//===----------------------------------------------------------------------===//
// Dynamic Attributes
@@ -551,24 +333,6 @@ getDynamicCustomAssemblyFormatAttr(TestDialect *testDialect) {
std::move(parser), std::move(printer));
}
-//===----------------------------------------------------------------------===//
-// SlashAttr
-//===----------------------------------------------------------------------===//
-
-Attribute SlashAttr::parse(AsmParser &parser, Type type) {
- int lhs, rhs;
-
- if (parser.parseLess() || parser.parseInteger(lhs) || parser.parseSlash() ||
- parser.parseInteger(rhs) || parser.parseGreater())
- return Attribute();
-
- return SlashAttr::get(parser.getContext(), lhs, rhs);
-}
-
-void SlashAttr::print(AsmPrinter &printer) const {
- printer << "<" << getLhs() << " / " << getRhs() << ">";
-}
-
//===----------------------------------------------------------------------===//
// TestCustomStorageCtorAttr
//===----------------------------------------------------------------------===//
diff --git a/mlir/test/lib/Dialect/Test/TestAttributes.h b/mlir/test/lib/Dialect/Test/TestAttributesCore.h
similarity index 78%
rename from mlir/test/lib/Dialect/Test/TestAttributes.h
rename to mlir/test/lib/Dialect/Test/TestAttributesCore.h
index e4c0eb1f01089f..05b908615fbbd0 100644
--- a/mlir/test/lib/Dialect/Test/TestAttributes.h
+++ b/mlir/test/lib/Dialect/Test/TestAttributesCore.h
@@ -1,18 +1,13 @@
-//===- TestTypes.h - MLIR Test Dialect Types --------------------*- C++ -*-===//
+//===- TestAttributesCore.h - Test attributes in `Core` ---------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-//
-// This file contains types defined by the TestDialect for testing various
-// features of MLIR.
-//
-//===----------------------------------------------------------------------===//
-#ifndef MLIR_TESTATTRIBUTES_H
-#define MLIR_TESTATTRIBUTES_H
+#ifndef MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESCORE_H
+#define MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESCORE_H
#include <tuple>
@@ -48,6 +43,6 @@ using TestDialectResourceBlobHandle =
} // namespace test
#define GET_ATTRDEF_CLASSES
-#include "TestAttrDefs.h.inc"
+#include "TestAttributesCore.h.inc"
-#endif // MLIR_TESTATTRIBUTES_H
+#endif // MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESCORE_H
diff --git a/mlir/test/lib/Dialect/Test/TestAttributesSyntax.cpp b/mlir/test/lib/Dialect/Test/TestAttributesSyntax.cpp
new file mode 100644
index 00000000000000..82cd3a3e9dfdb7
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestAttributesSyntax.cpp
@@ -0,0 +1,260 @@
+//===- TestAttributesSyntax.cpp - Test attributes in `Syntax` -------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the attributes of the test dialect in partition `Syntax`,
+// which exercise custom and declarative assembly formats.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestAttributesSyntax.h"
+#include "TestDialectBase.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/DialectImplementation.h"
+#include "mlir/IR/OpImplementation.h"
+#include "llvm/ADT/APFloat.h"
+
+using namespace mlir;
+using namespace test;
+
+//===----------------------------------------------------------------------===//
+// TestDecimalShapeAttr
+//===----------------------------------------------------------------------===//
+
+Attribute TestDecimalShapeAttr::parse(AsmParser &parser, Type type) {
+ if (parser.parseLess()) {
+ return Attribute();
+ }
+ SmallVector<int64_t> shape;
+ if (parser.parseOptionalGreater()) {
+ auto parseDecimal = [&]() {
+ shape.emplace_back();
+ auto parseResult = parser.parseOptionalDecimalInteger(shape.back());
+ if (!parseResult.has_value() || failed(*parseResult)) {
+ parser.emitError(parser.getCurrentLocation()) << "expected an integer";
+ return failure();
+ }
+ return success();
+ };
+ if (failed(parseDecimal())) {
+ return Attribute();
+ }
+ while (failed(parser.parseOptionalGreater())) {
+ if (failed(parser.parseXInDimensionList()) || failed(parseDecimal())) {
+ return Attribute();
+ }
+ }
+ }
+ return get(parser.getContext(), shape);
+}
+
+void TestDecimalShapeAttr::print(AsmPrinter &printer) const {
+ printer << "<";
+ llvm::interleave(getShape(), printer, "x");
+ printer << ">";
+}
+
+LogicalResult TestAttrWithFormatAttr::verify(
+ function_ref<InFlightDiagnostic()> emitError, int64_t one, std::string two,
+ IntegerAttr three, ArrayRef<int> four, uint64_t five, ArrayRef<int> six,
+ ArrayRef<AttrWithTypeBuilderAttr> arrayOfAttrs) {
+ if (four.size() != static_cast<unsigned>(one))
+ return emitError() << "expected 'one' to equal 'four.size()'";
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// Utility Functions for Generated Attributes
+//===----------------------------------------------------------------------===//
+
+static FailureOr<SmallVector<int>> parseIntArray(AsmParser &parser) {
+ SmallVector<int> ints;
+ if (parser.parseLSquare() || parser.parseCommaSeparatedList([&]() {
+ ints.push_back(0);
+ return parser.parseInteger(ints.back());
+ }) ||
+ parser.parseRSquare())
+ return failure();
+ return ints;
+}
+
+static void printIntArray(AsmPrinter &printer, ArrayRef<int> ints) {
+ printer << '[';
+ llvm::interleaveComma(ints, printer);
+ printer << ']';
+}
+
+//===----------------------------------------------------------------------===//
+// TestCustomAnchorAttr
+//===----------------------------------------------------------------------===//
+
+static ParseResult parseTrueFalse(AsmParser &p, std::optional<int> &result) {
+ bool b;
+ if (p.parseInteger(b))
+ return failure();
+ result = b;
+ return success();
+}
+
+static void printTrueFalse(AsmPrinter &p, std::optional<int> result) {
+ p << (*result ? "true" : "false");
+}
+
+//===----------------------------------------------------------------------===//
+// TestConditionalAliasAttr
+//===----------------------------------------------------------------------===//
+
+/// Attempt to parse the conditionally-aliased string attribute as a keyword or
+/// string, else try to parse an alias.
+static ParseResult parseConditionalAlias(AsmParser &p, StringAttr &value) {
+ std::string str;
+ if (succeeded(p.parseOptionalKeywordOrString(&str))) {
+ value = StringAttr::get(p.getContext(), str);
+ return success();
+ }
+ return p.parseAttribute(value);
+}
+
+/// Print the string attribute as an alias if it has one, otherwise print it as
+/// a keyword if possible.
+static void printConditionalAlias(AsmPrinter &p, StringAttr value) {
+ if (succeeded(p.printAlias(value)))
+ return;
+ p.printKeywordOrString(value);
+}
+
+//===----------------------------------------------------------------------===//
+// Custom Float Attribute
+//===----------------------------------------------------------------------===//
+
+static void printCustomFloatAttr(AsmPrinter &p, StringAttr typeStrAttr,
+ APFloat value) {
+ p << typeStrAttr << " : " << value;
+}
+
+static ParseResult parseCustomFloatAttr(AsmParser &p, StringAttr &typeStrAttr,
+ FailureOr<APFloat> &value) {
+
+ std::string str;
+ if (p.parseString(&str))
+ return failure();
+
+ typeStrAttr = StringAttr::get(p.getContext(), str);
+
+ if (p.parseColon())
+ return failure();
+
+ const llvm::fltSemantics *semantics;
+ if (str == "float")
+ semantics = &llvm::APFloat::IEEEsingle();
+ else if (str == "double")
+ semantics = &llvm::APFloat::IEEEdouble();
+ else if (str == "fp80")
+ semantics = &llvm::APFloat::x87DoubleExtended();
+ else
+ return p.emitError(p.getCurrentLocation(), "unknown float type, expected "
+ "'float', 'double' or 'fp80'");
+
+ APFloat parsedValue(0.0);
+ if (p.parseFloat(*semantics, parsedValue))
+ return failure();
+
+ value.emplace(parsedValue);
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// TestCustomStructAttr
+//===----------------------------------------------------------------------===//
+
+static void printCustomStructAttr(AsmPrinter &p, int64_t value) {
+ if (ShapedType::isDynamic(value)) {
+ p << "?";
+ } else {
+ p.printStrippedAttrOrType(value);
+ }
+}
+
+static ParseResult parseCustomStructAttr(AsmParser &p, int64_t &value) {
+ if (succeeded(p.parseOptionalQuestion())) {
+ value = ShapedType::kDynamic;
+ return success();
+ }
+ return p.parseInteger(value);
+}
+
+static void printCustomOptStructFieldAttr(AsmPrinter &p, ArrayAttr attr) {
+ if (attr && attr.size() == 1 && isa<IntegerAttr>(attr[0])) {
+ p << cast<IntegerAttr>(attr[0]).getInt();
+ } else {
+ p.printStrippedAttrOrType(attr);
+ }
+}
+
+static ParseResult parseCustomOptStructFieldAttr(AsmParser &p,
+ ArrayAttr &attr) {
+ int64_t value;
+ OptionalParseResult result = p.parseOptionalInteger(value);
+ if (result.has_value()) {
+ if (failed(result.value()))
+ return failure();
+ attr = ArrayAttr::get(
+ p.getContext(),
+ {IntegerAttr::get(IntegerType::get(p.getContext(), 64), value)});
+ return success();
+ }
+ return p.parseAttribute(attr);
+}
+
+//===----------------------------------------------------------------------===//
+// TestAttrNewlineAndIndent
+//===----------------------------------------------------------------------===//
+
+Attribute TestAttrNewlineAndIndentAttr::parse(::mlir::AsmParser &parser,
+ ::mlir::Type type) {
+ Type indentType;
+ if (parser.parseLess() || parser.parseType(indentType) ||
+ parser.parseGreater()) {
+ return Attribute();
+ }
+ return get(parser.getContext(), indentType);
+}
+
+void TestAttrNewlineAndIndentAttr::print(::mlir::AsmPrinter &printer) const {
+ printer << "<";
+ printer.increaseIndent();
+ printer.printNewline();
+ printer << getIndentType();
+ printer.decreaseIndent();
+ printer.printNewline();
+ printer << ">";
+}
+
+//===----------------------------------------------------------------------===//
+// Tablegen Generated Definitions
+//===----------------------------------------------------------------------===//
+
+#define GET_ATTRDEF_CLASSES
+#include "TestAttributesSyntax.cpp.inc"
+
+//===----------------------------------------------------------------------===//
+// SlashAttr
+//===----------------------------------------------------------------------===//
+
+Attribute SlashAttr::parse(AsmParser &parser, Type type) {
+ int lhs, rhs;
+
+ if (parser.parseLess() || parser.parseInteger(lhs) || parser.parseSlash() ||
+ parser.parseInteger(rhs) || parser.parseGreater())
+ return Attribute();
+
+ return SlashAttr::get(parser.getContext(), lhs, rhs);
+}
+
+void SlashAttr::print(AsmPrinter &printer) const {
+ printer << "<" << getLhs() << " / " << getRhs() << ">";
+}
diff --git a/mlir/test/lib/Dialect/Test/TestAttributesSyntax.h b/mlir/test/lib/Dialect/Test/TestAttributesSyntax.h
new file mode 100644
index 00000000000000..3849be121b2e62
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestAttributesSyntax.h
@@ -0,0 +1,18 @@
+//===- TestAttributesSyntax.h - Test attributes in `Syntax` -----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESSYNTAX_H
+#define MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESSYNTAX_H
+
+// The attributes in `Syntax` use the enums and attributes in `Core`.
+#include "TestAttributesCore.h"
+
+#define GET_ATTRDEF_CLASSES
+#include "TestAttributesSyntax.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTATTRIBUTESSYNTAX_H
diff --git a/mlir/test/lib/Dialect/Test/TestDialect.cpp b/mlir/test/lib/Dialect/Test/TestDialect.cpp
index 57bba2e5749a86..b7fafe8e023814 100644
--- a/mlir/test/lib/Dialect/Test/TestDialect.cpp
+++ b/mlir/test/lib/Dialect/Test/TestDialect.cpp
@@ -8,7 +8,7 @@
#include "TestDialect.h"
#include "TestOps.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/Bytecode/BytecodeImplementation.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
@@ -454,6 +454,77 @@ void TestDialect::getCanonicalizationPatterns(
results.add(&dialectCanonicalizationPattern);
}
+Type TestDialect::parseType(DialectAsmParser &parser) const {
+ StringRef typeTag;
+ {
+ Type genType;
+ auto parseResult =
+ generatedTestDialectTypeParser(parser, &typeTag, genType);
+ if (parseResult.has_value())
+ return genType;
+ }
+
+ {
+ Type dynType;
+ auto parseResult = parseOptionalDynamicType(typeTag, parser, dynType);
+ if (parseResult.has_value()) {
+ if (succeeded(parseResult.value()))
+ return dynType;
+ return Type();
+ }
+ }
+
+ if (typeTag != "test_rec") {
+ parser.emitError(parser.getNameLoc()) << "unknown type!";
+ return Type();
+ }
+
+ StringRef name;
+ if (parser.parseLess() || parser.parseKeyword(&name))
+ return Type();
+ auto rec = TestRecursiveType::get(parser.getContext(), name);
+
+ FailureOr<AsmParser::CyclicParseReset> cyclicParse =
+ parser.tryStartCyclicParse(rec);
+
+ // If this type already has been parsed above in the stack, expect just the
+ // name.
+ if (failed(cyclicParse)) {
+ if (failed(parser.parseGreater()))
+ return Type();
+ return rec;
+ }
+
+ // Otherwise, parse the body and update the type.
+ if (failed(parser.parseComma()))
+ return Type();
+ Type subtype = parseType(parser);
+ if (!subtype || failed(parser.parseGreater()) || failed(rec.setBody(subtype)))
+ return Type();
+
+ return rec;
+}
+
+void TestDialect::printType(Type type, DialectAsmPrinter &printer) const {
+ if (succeeded(generatedTestDialectTypePrinter(type, printer)))
+ return;
+
+ if (succeeded(printIfDynamicType(type, printer)))
+ return;
+
+ auto rec = llvm::cast<TestRecursiveType>(type);
+
+ FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrint =
+ printer.tryStartCyclicPrint(rec);
+
+ printer << "test_rec<" << rec.getName();
+ if (succeeded(cyclicPrint)) {
+ printer << ", ";
+ printType(rec.getBody(), printer);
+ }
+ printer << ">";
+}
+
//===----------------------------------------------------------------------===//
// TestCallWithSegmentsOp
//===----------------------------------------------------------------------===//
diff --git a/mlir/test/lib/Dialect/Test/TestDialect.h b/mlir/test/lib/Dialect/Test/TestDialect.h
index d37272f17e547c..7dd79e0af94a08 100644
--- a/mlir/test/lib/Dialect/Test/TestDialect.h
+++ b/mlir/test/lib/Dialect/Test/TestDialect.h
@@ -14,9 +14,10 @@
#ifndef MLIR_TESTDIALECT_H
#define MLIR_TESTDIALECT_H
-#include "TestAttributes.h"
+// The ops of all partitions use the attributes in `Core` and `Syntax`.
+#include "TestAttributesSyntax.h"
+#include "TestDialectBase.h"
#include "TestInterfaces.h"
-#include "TestTypes.h"
#include "mlir/Bytecode/BytecodeImplementation.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/DLTI/DLTI.h"
@@ -46,16 +47,6 @@
#include <memory>
-namespace mlir {
-class RewritePatternSet;
-} // end namespace mlir
-
-//===----------------------------------------------------------------------===//
-// TestDialect
-//===----------------------------------------------------------------------===//
-
-#include "TestOpsDialect.h.inc"
-
namespace test {
//===----------------------------------------------------------------------===//
diff --git a/mlir/test/lib/Dialect/Test/TestDialectBase.h b/mlir/test/lib/Dialect/Test/TestDialectBase.h
new file mode 100644
index 00000000000000..39402329a086a9
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestDialectBase.h
@@ -0,0 +1,26 @@
+//===- TestDialectBase.h - The test dialect class ---------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Declares only the test dialect class, without its ops and the headers they
+// need, for the compilation units of the attributes and types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTDIALECTBASE_H
+#define MLIR_TEST_DIALECT_TEST_TESTDIALECTBASE_H
+
+// The dialect declares a helper for the discardable attribute `SimpleAAttr`.
+#include "TestAttributesCore.h"
+
+namespace mlir {
+class RewritePatternSet;
+} // namespace mlir
+
+#include "TestOpsDialect.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTDIALECTBASE_H
diff --git a/mlir/test/lib/Dialect/Test/TestDialectInterfaces.cpp b/mlir/test/lib/Dialect/Test/TestDialectInterfaces.cpp
index 2d5b1314d9f198..5196655008532e 100644
--- a/mlir/test/lib/Dialect/Test/TestDialectInterfaces.cpp
+++ b/mlir/test/lib/Dialect/Test/TestDialectInterfaces.cpp
@@ -8,7 +8,7 @@
#include "TestDialect.h"
#include "TestOps.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/Bytecode/Encoding.h"
#include "mlir/Conversion/ConvertToEmitC/ToEmitCInterface.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
diff --git a/mlir/test/lib/Dialect/Test/TestInterfaces.td b/mlir/test/lib/Dialect/Test/TestInterfaces.td
index 46cb57fd8f9b22..25cd671246e3d3 100644
--- a/mlir/test/lib/Dialect/Test/TestInterfaces.td
+++ b/mlir/test/lib/Dialect/Test/TestInterfaces.td
@@ -15,7 +15,7 @@ include "mlir/Interfaces/SideEffectInterfaceBase.td"
// A set of type interfaces used to test interface inheritance.
def TestBaseTypeInterfacePrintTypeA : TypeInterface<"TestBaseTypeInterfacePrintTypeA"> {
let cppNamespace = "::test";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"Prints the type name.",
"void", "printTypeA", (ins "::mlir::Location":$loc), [{
@@ -27,7 +27,7 @@ def TestBaseTypeInterfacePrintTypeA : TypeInterface<"TestBaseTypeInterfacePrintT
def TestBaseTypeInterfacePrintTypeB
: TypeInterface<"TestBaseTypeInterfacePrintTypeB", [TestBaseTypeInterfacePrintTypeA]> {
let cppNamespace = "::test";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"Prints the type name.",
"void", "printTypeB", (ins "::mlir::Location":$loc),
@@ -42,7 +42,7 @@ def TestBaseTypeInterfacePrintTypeB
def TestTypeInterface
: TypeInterface<"TestTypeInterface", [TestBaseTypeInterfacePrintTypeB]> {
let cppNamespace = "::test";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"Prints the type name.",
"void", "printTypeC", (ins "::mlir::Location":$loc)
@@ -83,7 +83,7 @@ def TestTypeInterface
def TestExternalTypeInterface : TypeInterface<"TestExternalTypeInterface"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"Returns the bitwidth of the type plus 'arg'.",
"unsigned", "getBitwidthPlusArg", (ins "unsigned":$arg)>,
@@ -113,7 +113,7 @@ def TestExternalTypeInterface : TypeInterface<"TestExternalTypeInterface"> {
def TestExternalFallbackTypeInterface
: TypeInterface<"TestExternalFallbackTypeInterface"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"Returns the bitwidth of the given integer type.",
"unsigned", "getBitwidth", (ins), "", "return $_type.getWidth();">,
@@ -122,7 +122,7 @@ def TestExternalFallbackTypeInterface
def TestExternalAttrInterface : AttrInterface<"TestExternalAttrInterface"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestAttributes.h"];
+ let cppIncludes = ["TestAttributesCore.h"];
let methods = [
InterfaceMethod<"Gets the dialect pointer.", "const ::mlir::Dialect *",
"getDialectPtr">,
@@ -182,7 +182,7 @@ def TestOptionallyImplementedOpInterface
def TestOptionallyImplementedAttrInterface
: AttrInterface<"TestOptionallyImplementedAttrInterface"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestAttributes.h"];
+ let cppIncludes = ["TestAttributesCore.h"];
let methods = [
InterfaceMethod<"", "bool", "getImplementsInterface", (ins)>,
@@ -196,7 +196,7 @@ def TestOptionallyImplementedAttrInterface
def TestOptionallyImplementedTypeInterface
: TypeInterface<"TestOptionallyImplementedTypeInterface"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"", "bool", "getImplementsInterface", (ins)>,
@@ -210,7 +210,7 @@ def TestOptionallyImplementedTypeInterface
// Dummy type interface "A" that requires type interface "B" to be complete.
def TestCyclicTypeInterfaceA : TypeInterface<"TestCyclicTypeInterfaceA"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"",
"::mlir::FailureOr<::mlir::TestCyclicTypeInterfaceB>",
@@ -225,7 +225,7 @@ def TestCyclicTypeInterfaceA : TypeInterface<"TestCyclicTypeInterfaceA"> {
// Dummy type interface "B" that requires type interface "A" to be complete.
def TestCyclicTypeInterfaceB : TypeInterface<"TestCyclicTypeInterfaceB"> {
let cppNamespace = "::mlir";
- let cppIncludes = ["TestTypes.h"];
+ let cppIncludes = ["TestTypesCore.h"];
let methods = [
InterfaceMethod<"",
"::mlir::FailureOr<::mlir::TestCyclicTypeInterfaceA>",
diff --git a/mlir/test/lib/Dialect/Test/TestOpDefs.cpp b/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
index 7f2edc20c27d87..0b98a20a38e8a4 100644
--- a/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
@@ -8,6 +8,7 @@
#include "TestDialect.h"
#include "TestOps.h"
+#include "TestTypesCore.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/Verifier.h"
diff --git a/mlir/test/lib/Dialect/Test/TestOps.td b/mlir/test/lib/Dialect/Test/TestOps.td
index 958d1984c0e56e..bbc223ae01da88 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.td
+++ b/mlir/test/lib/Dialect/Test/TestOps.td
@@ -516,8 +516,10 @@ def PromisedInterfacesOp : TEST_AttrOp<"promised_interfaces"> {
//===----------------------------------------------------------------------===//
// Define the enum attribute.
+let partition = Test_AttrTypeCorePartition in
def TestEnumAttr : EnumAttr<Test_Dialect, TestEnum, "enum">;
+let partition = Test_AttrTypeCorePartition in
def TestPrettyEnumAttr
: EnumAttr<Test_Dialect, TestPrettyEnum, "pretty_enum">;
@@ -611,6 +613,7 @@ def OpWithSimpleEnum16Prop : TEST_AttrOp<"op_with_simple_enum_16_prop"> {
//===----------------------------------------------------------------------===//
// Define the enum attribute.
+let partition = Test_AttrTypeCorePartition in
def TestBitEnumAttr : EnumAttr<Test_Dialect, TestBitEnum, "bit_enum">;
// Define an op that contains the enum attribute.
@@ -619,6 +622,7 @@ def OpWithBitEnum : TEST_AttrOp<"op_with_bit_enum"> {
let assemblyFormat = "$value (`tag` $tag^)? attr-dict";
}
+let partition = Test_AttrTypeCorePartition in
def TestBitEnumVerticalBarAttr
: EnumAttr<Test_Dialect, TestBitEnumVerticalBar, "bit_enum_vbar">;
@@ -640,6 +644,7 @@ def OpWithBitEnumVerticalBarDirective
let assemblyFormat = "enum($value) attr-dict";
}
+let partition = Test_AttrTypeCorePartition in
def TestBitEnumSpaceAttr
: EnumAttr<Test_Dialect, TestBitEnumSpace, "bit_enum_space">;
diff --git a/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp b/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
index b0bbf1b053ac0a..444829e6435fcf 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
@@ -8,6 +8,10 @@
#include "TestOpsAttributes.h"
#include "TestFormatUtils.h"
+// The definitions of `Attributes` ops use the type interfaces of `Core`.
+#include "TestTypesCore.h"
+// The generated op definitions parse prop-dicts with `FieldParser`.
+#include "mlir/IR/DialectImplementation.h"
using namespace mlir;
using namespace test;
diff --git a/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp b/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
index a3423bda38a02d..19463d3c9a8846 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
@@ -7,6 +7,8 @@
//===----------------------------------------------------------------------===//
#include "TestOpsPatterns.h"
+// The definitions of `Patterns` ops use the types in `Core`.
+#include "TestTypesCore.h"
using namespace mlir;
using namespace test;
diff --git a/mlir/test/lib/Dialect/Test/TestOpsProperties.h b/mlir/test/lib/Dialect/Test/TestOpsProperties.h
index d597a3f725f875..4417b40b4a228e 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsProperties.h
+++ b/mlir/test/lib/Dialect/Test/TestOpsProperties.h
@@ -10,6 +10,7 @@
#define MLIR_TEST_DIALECT_TEST_TESTOPSPROPERTIES_H
#include "TestDialect.h"
+#include "mlir/IR/DialectImplementation.h"
#include "llvm/ADT/SmallVector.h"
#include <optional>
diff --git a/mlir/test/lib/Dialect/Test/TestOpsSyntax.h b/mlir/test/lib/Dialect/Test/TestOpsSyntax.h
index bb4adf2911c961..704199cac8a028 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsSyntax.h
+++ b/mlir/test/lib/Dialect/Test/TestOpsSyntax.h
@@ -9,8 +9,8 @@
#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSSYNTAX_H
#define MLIR_TEST_DIALECT_TEST_TESTOPSSYNTAX_H
-#include "TestAttributes.h"
-#include "TestTypes.h"
+#include "TestAttributesSyntax.h"
+#include "TestTypesSyntax.h"
namespace test {
class TestReturnOp;
diff --git a/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp b/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
index 41ce5043d261f3..0a4a1b10107b4e 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
@@ -7,6 +7,8 @@
//===----------------------------------------------------------------------===//
#include "TestOpsTraits.h"
+// The generated op definitions parse prop-dicts with `FieldParser`.
+#include "mlir/IR/DialectImplementation.h"
using namespace mlir;
using namespace test;
diff --git a/mlir/test/lib/Dialect/Test/TestPatterns.cpp b/mlir/test/lib/Dialect/Test/TestPatterns.cpp
index 0417d6662814e0..76cc53775064fc 100644
--- a/mlir/test/lib/Dialect/Test/TestPatterns.cpp
+++ b/mlir/test/lib/Dialect/Test/TestPatterns.cpp
@@ -9,7 +9,7 @@
#include "../../IR/DumpNotifications.h"
#include "TestDialect.h"
#include "TestOps.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/CommonFolders.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
diff --git a/mlir/test/lib/Dialect/Test/TestTypeDefs.td b/mlir/test/lib/Dialect/Test/TestTypeDefs.td
index 70214c9271734b..bec5e5903b95e9 100644
--- a/mlir/test/lib/Dialect/Test/TestTypeDefs.td
+++ b/mlir/test/lib/Dialect/Test/TestTypeDefs.td
@@ -22,9 +22,17 @@ include "mlir/IR/BuiltinTypeInterfaces.td"
include "mlir/Interfaces/DataLayoutInterfaces.td"
include "mlir/Dialect/Bufferization/IR/BufferizationTypeInterfaces.td"
-// All of the types will extend this class.
+// All of the types will extend this class. See TestAttrDefs.td for the
+// partitions.
class Test_Type<string name, list<Trait> traits = []>
- : TypeDef<Test_Dialect, name, traits>;
+ : TypeDef<Test_Dialect, name, traits> {
+ let partition = Test_AttrTypeCorePartition;
+}
+
+class Test_SyntaxType<string name, list<Trait> traits = []>
+ : Test_Type<name, traits> {
+ let partition = Test_AttrTypeSyntaxPartition;
+}
def SimpleTypeA : Test_Type<"SimpleA"> {
let mnemonic = "smpla";
@@ -54,7 +62,7 @@ def CompoundTypeA : Test_Type<"CompoundA"> {
}
// A more complex and nested parameterized type.
-def CompoundNestedInnerType : Test_Type<"CompoundNestedInner"> {
+def CompoundNestedInnerType : Test_SyntaxType<"CompoundNestedInner"> {
let mnemonic = "cmpnd_inner";
// List of type parameters.
let parameters = (
@@ -65,7 +73,7 @@ def CompoundNestedInnerType : Test_Type<"CompoundNestedInner"> {
let assemblyFormat = "`<` $some_int $cmpdA `>`";
}
-def CompoundNestedOuterType : Test_Type<"CompoundNestedOuter"> {
+def CompoundNestedOuterType : Test_SyntaxType<"CompoundNestedOuter"> {
let mnemonic = "cmpnd_nested_outer";
// List of type parameters.
@@ -73,7 +81,7 @@ def CompoundNestedOuterType : Test_Type<"CompoundNestedOuter"> {
let assemblyFormat = "`<` `i` $inner `>`";
}
-def CompoundNestedOuterTypeQual : Test_Type<"CompoundNestedOuterQual"> {
+def CompoundNestedOuterTypeQual : Test_SyntaxType<"CompoundNestedOuterQual"> {
let mnemonic = "cmpnd_nested_outer_qual";
// List of type parameters.
@@ -133,7 +141,7 @@ class FieldInfo_Type<string name> : Test_Type<name> {
// An ArrayRef of something which requires allocation in the storage
// constructor.
ArrayRefOfSelfAllocationParameter<
- "::test::FieldInfo", // FieldInfo is defined/declared in TestTypes.h.
+ "::test::FieldInfo", // FieldInfo is defined/declared in TestTypesCore.h.
"Models struct fields">: $fields
);
let hasCustomAssemblyFormat = 1;
@@ -183,7 +191,7 @@ def TestTypeWithTrait : Test_Type<"TestTypeWithTrait", [TestTypeTrait]> {
}
// Type with assembly format.
-def TestTypeWithFormat : Test_Type<"TestTypeWithFormat"> {
+def TestTypeWithFormat : Test_SyntaxType<"TestTypeWithFormat"> {
let parameters = (
ins
TestParamOne:$one,
@@ -196,7 +204,7 @@ def TestTypeWithFormat : Test_Type<"TestTypeWithFormat"> {
}
// Test dispatch to parseField
-def TestTypeNoParser : Test_Type<"TestTypeNoParser"> {
+def TestTypeNoParser : Test_SyntaxType<"TestTypeNoParser"> {
let parameters = (
ins
"uint32_t":$one,
@@ -209,7 +217,7 @@ def TestTypeNoParser : Test_Type<"TestTypeNoParser"> {
let assemblyFormat = "`<` $one `,` `[` $two `]` `,` $three `,` $four `>`";
}
-def TestTypeStructCaptureAll : Test_Type<"TestStructTypeCaptureAll"> {
+def TestTypeStructCaptureAll : Test_SyntaxType<"TestStructTypeCaptureAll"> {
let parameters = (
ins
"int":$v0,
@@ -222,7 +230,7 @@ def TestTypeStructCaptureAll : Test_Type<"TestStructTypeCaptureAll"> {
let assemblyFormat = "`<` struct(params) `>`";
}
-def TestTypeOptionalParam : Test_Type<"TestTypeOptionalParam"> {
+def TestTypeOptionalParam : Test_SyntaxType<"TestTypeOptionalParam"> {
let parameters = (ins
OptionalParameter<"std::optional<int>">:$a,
"int":$b,
@@ -233,7 +241,7 @@ def TestTypeOptionalParam : Test_Type<"TestTypeOptionalParam"> {
let assemblyFormat = "`<` $a `,` $b ( `,` $c^)? `>`";
}
-def TestTypeOptionalParams : Test_Type<"TestTypeOptionalParams"> {
+def TestTypeOptionalParams : Test_SyntaxType<"TestTypeOptionalParams"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
StringRefParameter<>:$b);
let mnemonic = "optional_params";
@@ -241,55 +249,55 @@ def TestTypeOptionalParams : Test_Type<"TestTypeOptionalParams"> {
}
def TestTypeOptionalParamsAfterRequired
- : Test_Type<"TestTypeOptionalParamsAfterRequired"> {
+ : Test_SyntaxType<"TestTypeOptionalParamsAfterRequired"> {
let parameters = (ins StringRefParameter<>:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "optional_params_after";
let assemblyFormat = "`<` params `>`";
}
-def TestTypeOptionalStruct : Test_Type<"TestTypeOptionalStruct"> {
+def TestTypeOptionalStruct : Test_SyntaxType<"TestTypeOptionalStruct"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
StringRefParameter<>:$b);
let mnemonic = "optional_struct";
let assemblyFormat = "`<` struct(params) `>`";
}
-def TestTypeAllOptionalParams : Test_Type<"TestTypeAllOptionalParams"> {
+def TestTypeAllOptionalParams : Test_SyntaxType<"TestTypeAllOptionalParams"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "all_optional_params";
let assemblyFormat = "`<` params `>`";
}
-def TestTypeAllOptionalStruct : Test_Type<"TestTypeAllOptionalStruct"> {
+def TestTypeAllOptionalStruct : Test_SyntaxType<"TestTypeAllOptionalStruct"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "all_optional_struct";
let assemblyFormat = "`<` struct(params) `>`";
}
-def TestTypeOptionalGroup : Test_Type<"TestTypeOptionalGroup"> {
+def TestTypeOptionalGroup : Test_SyntaxType<"TestTypeOptionalGroup"> {
let parameters = (ins "int":$a, OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "optional_group";
let assemblyFormat = "`<` (`(` $b^ `)`) : (`x`)? $a `>`";
}
-def TestTypeOptionalGroupParams : Test_Type<"TestTypeOptionalGroupParams"> {
+def TestTypeOptionalGroupParams : Test_SyntaxType<"TestTypeOptionalGroupParams"> {
let parameters = (ins DefaultValuedParameter<"std::optional<int>", "10">:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "optional_group_params";
let assemblyFormat = "`<` (`(` params^ `)`) : (`x`)? `>`";
}
-def TestTypeOptionalGroupStruct : Test_Type<"TestTypeOptionalGroupStruct"> {
+def TestTypeOptionalGroupStruct : Test_SyntaxType<"TestTypeOptionalGroupStruct"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "optional_group_struct";
let assemblyFormat = "`<` (`(` struct(params)^ `)`) : (`x`)? `>`";
}
-def TestTypeSpaces : Test_Type<"TestTypeSpaceS"> {
+def TestTypeSpaces : Test_SyntaxType<"TestTypeSpaceS"> {
let parameters = (ins "int":$a, "int":$b);
let mnemonic = "spaces";
let assemblyFormat = "`<` ` ` $a `\\n` `(` `)` `` `(` `)` $b `>`";
@@ -309,7 +317,7 @@ class DefaultValuedAPFloat<string value>
}() }];
}
-def TestTypeAPFloat : Test_Type<"TestTypeAPFloat"> {
+def TestTypeAPFloat : Test_SyntaxType<"TestTypeAPFloat"> {
let parameters = (ins
DefaultValuedAPFloat<"APFloat::getZero(APFloat::IEEEdouble())">:$a
);
@@ -317,7 +325,7 @@ def TestTypeAPFloat : Test_Type<"TestTypeAPFloat"> {
let assemblyFormat = "`<` $a `>`";
}
-def TestTypeOptionalValueType : Test_Type<"TestTypeOptionalValueType"> {
+def TestTypeOptionalValueType : Test_SyntaxType<"TestTypeOptionalValueType"> {
let parameters = (ins
OptionalParameter<"std::optional<int>">:$value
);
@@ -325,7 +333,7 @@ def TestTypeOptionalValueType : Test_Type<"TestTypeOptionalValueType"> {
let assemblyFormat = "(`<` $value^ `>`)?";
}
-def TestTypeDefaultValuedType : Test_Type<"TestTypeDefaultValuedType"> {
+def TestTypeDefaultValuedType : Test_SyntaxType<"TestTypeDefaultValuedType"> {
let parameters = (ins
DefaultValuedParameter<"mlir::IntegerType",
"mlir::IntegerType::get($_ctxt, 32)">:$type
@@ -334,21 +342,21 @@ def TestTypeDefaultValuedType : Test_Type<"TestTypeDefaultValuedType"> {
let assemblyFormat = "`<` (`(` $type^ `)`)? `>`";
}
-def TestTypeCustom : Test_Type<"TestTypeCustom"> {
+def TestTypeCustom : Test_SyntaxType<"TestTypeCustom"> {
let parameters = (ins "int":$a, OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "custom_type";
let assemblyFormat = [{ `<` custom<CustomTypeA>($a) ``
custom<CustomTypeB>(ref($a), $b) `>` }];
}
-def TestTypeCustomSpacing : Test_Type<"TestTypeCustomSpacing"> {
+def TestTypeCustomSpacing : Test_SyntaxType<"TestTypeCustomSpacing"> {
let parameters = (ins "int":$a, "int":$b);
let mnemonic = "custom_type_spacing";
let assemblyFormat = [{ `<` custom<CustomTypeA>($a)
custom<CustomTypeA>($b) `>` }];
}
-def TestTypeCustomString : Test_Type<"TestTypeCustomString"> {
+def TestTypeCustomString : Test_SyntaxType<"TestTypeCustomString"> {
let parameters = (ins StringRefParameter<>:$foo);
let mnemonic = "custom_type_string";
let assemblyFormat = [{ `<` custom<FooString>($foo)
@@ -362,19 +370,19 @@ def TestCustomStorageCtor : Test_Type<"TestCustomStorageCtor"> {
let hasStorageCustomConstructor = 1;
}
-def TestTypeOptionalString : Test_Type<"TestTypeOptionalString"> {
+def TestTypeOptionalString : Test_SyntaxType<"TestTypeOptionalString"> {
let parameters = (ins StringRefParameter<"description", [{"default"}]>:$str);
let mnemonic = "optional_type_string";
let assemblyFormat = [{ (`<` $str^ `>`)? }];
}
-def TestTypeElseAnchor : Test_Type<"TestTypeElseAnchor"> {
+def TestTypeElseAnchor : Test_SyntaxType<"TestTypeElseAnchor"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a);
let mnemonic = "else_anchor";
let assemblyFormat = "`<` (`?`) : ($a^)? `>`";
}
-def TestTypeElseAnchorStruct : Test_Type<"TestTypeElseAnchorStruct"> {
+def TestTypeElseAnchorStruct : Test_SyntaxType<"TestTypeElseAnchorStruct"> {
let parameters = (ins OptionalParameter<"std::optional<int>">:$a,
OptionalParameter<"std::optional<int>">:$b);
let mnemonic = "else_anchor_struct";
@@ -524,7 +532,7 @@ def TestBaseBody : Test_Type<"TestBaseBody",
let mnemonic = "test_base_body";
}
-def TestTypeNewlineAndIndent : Test_Type<"TestTypeNewlineAndIndent"> {
+def TestTypeNewlineAndIndent : Test_SyntaxType<"TestTypeNewlineAndIndent"> {
let mnemonic = "newline_and_indent";
let hasCustomAssemblyFormat = 1;
}
diff --git a/mlir/test/lib/Dialect/Test/TestTypes.cpp b/mlir/test/lib/Dialect/Test/TestTypesCore.cpp
similarity index 80%
rename from mlir/test/lib/Dialect/Test/TestTypes.cpp
rename to mlir/test/lib/Dialect/Test/TestTypesCore.cpp
index 9410d5e2aa9226..68b6ce487aa1d2 100644
--- a/mlir/test/lib/Dialect/Test/TestTypes.cpp
+++ b/mlir/test/lib/Dialect/Test/TestTypesCore.cpp
@@ -1,4 +1,4 @@
-//===- TestTypes.cpp - MLIR Test Dialect Types ------------------*- C++ -*-===//
+//===- TestTypesCore.cpp - Test types in `Core` ---------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -6,13 +6,12 @@
//
//===----------------------------------------------------------------------===//
//
-// This file contains types defined by the TestDialect for testing various
-// features of MLIR.
+// This file contains the types of the test dialect in partition `Core`.
//
//===----------------------------------------------------------------------===//
-#include "TestTypes.h"
-#include "TestDialect.h"
+#include "TestTypesCore.h"
+#include "TestDialectBase.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/DialectImplementation.h"
@@ -20,7 +19,6 @@
#include "mlir/IR/TypeUtilities.h"
#include "mlir/IR/Types.h"
#include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/SetVector.h"
#include "llvm/Support/TypeSize.h"
#include <cstring>
#include <optional>
@@ -87,62 +85,13 @@ static llvm::hash_code test::hash_value(const FieldInfo &fi) { // NOLINT
return llvm::hash_combine(fi.name, fi.type);
}
-//===----------------------------------------------------------------------===//
-// TestCustomType
-//===----------------------------------------------------------------------===//
-
-static ParseResult parseCustomTypeA(AsmParser &parser, int &aResult) {
- return parser.parseInteger(aResult);
-}
-
-static void printCustomTypeA(AsmPrinter &printer, int a) { printer << a; }
-
-static ParseResult parseCustomTypeB(AsmParser &parser, int a,
- std::optional<int> &bResult) {
- if (a < 0)
- return success();
- for (int i : llvm::seq(0, a))
- if (failed(parser.parseInteger(i)))
- return failure();
- bResult.emplace(0);
- return parser.parseInteger(*bResult);
-}
-
-static void printCustomTypeB(AsmPrinter &printer, int a, std::optional<int> b) {
- if (a < 0)
- return;
- printer << ' ';
- for (int i : llvm::seq(0, a))
- printer << i << ' ';
- printer << *b;
-}
-
-static ParseResult parseFooString(AsmParser &parser, std::string &foo) {
- std::string result;
- if (parser.parseString(&result))
- return failure();
- foo = std::move(result);
- return success();
-}
-
-static void printFooString(AsmPrinter &printer, StringRef foo) {
- printer << '"' << foo << '"';
-}
-
-static ParseResult parseBarString(AsmParser &parser, StringRef foo) {
- return parser.parseKeyword(foo);
-}
-
-static void printBarString(AsmPrinter &printer, StringRef foo) {
- printer << foo;
-}
//===----------------------------------------------------------------------===//
// Tablegen Generated Definitions
//===----------------------------------------------------------------------===//
#include "TestTypeInterfaces.cpp.inc"
#define GET_TYPEDEF_CLASSES
-#include "TestTypeDefs.cpp.inc"
+#include "TestTypesCore.cpp.inc"
//===----------------------------------------------------------------------===//
// CompoundAType
@@ -410,7 +359,6 @@ test::detail::TestCustomStorageCtorTypeStorage::construct(
//===----------------------------------------------------------------------===//
namespace {
-
struct PtrElementModel
: public LLVM::PointerElementTypeInterface::ExternalModel<PtrElementModel,
SimpleAType> {};
@@ -426,76 +374,6 @@ void TestDialect::registerTypes() {
registerDynamicType(getCustomAssemblyFormatDynamicType(this));
}
-Type TestDialect::parseType(DialectAsmParser &parser) const {
- StringRef typeTag;
- {
- Type genType;
- auto parseResult = generatedTypeParser(parser, &typeTag, genType);
- if (parseResult.has_value())
- return genType;
- }
-
- {
- Type dynType;
- auto parseResult = parseOptionalDynamicType(typeTag, parser, dynType);
- if (parseResult.has_value()) {
- if (succeeded(parseResult.value()))
- return dynType;
- return Type();
- }
- }
-
- if (typeTag != "test_rec") {
- parser.emitError(parser.getNameLoc()) << "unknown type!";
- return Type();
- }
-
- StringRef name;
- if (parser.parseLess() || parser.parseKeyword(&name))
- return Type();
- auto rec = TestRecursiveType::get(parser.getContext(), name);
-
- FailureOr<AsmParser::CyclicParseReset> cyclicParse =
- parser.tryStartCyclicParse(rec);
-
- // If this type already has been parsed above in the stack, expect just the
- // name.
- if (failed(cyclicParse)) {
- if (failed(parser.parseGreater()))
- return Type();
- return rec;
- }
-
- // Otherwise, parse the body and update the type.
- if (failed(parser.parseComma()))
- return Type();
- Type subtype = parseType(parser);
- if (!subtype || failed(parser.parseGreater()) || failed(rec.setBody(subtype)))
- return Type();
-
- return rec;
-}
-
-void TestDialect::printType(Type type, DialectAsmPrinter &printer) const {
- if (succeeded(generatedTypePrinter(type, printer)))
- return;
-
- if (succeeded(printIfDynamicType(type, printer)))
- return;
-
- auto rec = llvm::cast<TestRecursiveType>(type);
-
- FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrint =
- printer.tryStartCyclicPrint(rec);
-
- printer << "test_rec<" << rec.getName();
- if (succeeded(cyclicPrint)) {
- printer << ", ";
- printType(rec.getBody(), printer);
- }
- printer << ">";
-}
-
Type TestRecursiveAliasType::getBody() const { return getImpl()->body; }
void TestRecursiveAliasType::setBody(Type type) { (void)Base::mutate(type); }
@@ -597,28 +475,6 @@ ::mlir::LogicalResult TestTensorLikeWrapperType::verifyCompatibleBufferType(
.verifyCompatibleBufferType(bufferType, emitError);
}
-//===----------------------------------------------------------------------===//
-// TestTypeNewlineAndIndent
-//===----------------------------------------------------------------------===//
-
-Type TestTypeNewlineAndIndentType::parse(::mlir::AsmParser &parser) {
- if (parser.parseLess() || parser.parseKeyword("indented_content") ||
- parser.parseGreater()) {
- return Type();
- }
- return get(parser.getContext());
-}
-
-void TestTypeNewlineAndIndentType::print(::mlir::AsmPrinter &printer) const {
- printer << "<";
- printer.increaseIndent();
- printer.printNewline();
- printer << "indented_content";
- printer.decreaseIndent();
- printer.printNewline();
- printer << ">";
-}
-
//===----------------------------------------------------------------------===//
// TestDenseElementType - DenseElementTypeInterface Implementation
//===----------------------------------------------------------------------===//
diff --git a/mlir/test/lib/Dialect/Test/TestTypes.h b/mlir/test/lib/Dialect/Test/TestTypesCore.h
similarity index 63%
rename from mlir/test/lib/Dialect/Test/TestTypes.h
rename to mlir/test/lib/Dialect/Test/TestTypesCore.h
index b447e699ee7d4e..79c8a1fabc0800 100644
--- a/mlir/test/lib/Dialect/Test/TestTypes.h
+++ b/mlir/test/lib/Dialect/Test/TestTypesCore.h
@@ -1,32 +1,23 @@
-//===- TestTypes.h - MLIR Test Dialect Types --------------------*- C++ -*-===//
+//===- TestTypesCore.h - Test types in `Core` -------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-//
-// This file contains types defined by the TestDialect for testing various
-// features of MLIR.
-//
-//===----------------------------------------------------------------------===//
-#ifndef MLIR_TESTTYPES_H
-#define MLIR_TESTTYPES_H
+#ifndef MLIR_TEST_DIALECT_TEST_TESTTYPESCORE_H
+#define MLIR_TEST_DIALECT_TEST_TESTTYPESCORE_H
-#include <optional>
#include <tuple>
#include "mlir/Dialect/Bufferization/IR/BufferizationTypeInterfaces.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/Dialect.h"
-#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Types.h"
namespace test {
-class TestAttrWithFormatAttr;
-
/// FieldInfo represents a field in the StructType data type. It is used as a
/// parameter in TestTypeDefs.td.
struct FieldInfo {
@@ -38,60 +29,11 @@ struct FieldInfo {
return FieldInfo{alloc.copyInto(name), type};
}
};
-
-/// A custom type for a test type parameter.
-struct CustomParam {
- int value;
-
- bool operator==(const CustomParam &other) const {
- return other.value == value;
- }
-};
-
-inline llvm::hash_code hash_value(const test::CustomParam ¶m) {
- return llvm::hash_value(param.value);
-}
-
} // namespace test
-namespace mlir {
-template <>
-struct FieldParser<test::CustomParam> {
- static FailureOr<test::CustomParam> parse(AsmParser &parser) {
- auto value = FieldParser<int>::parse(parser);
- if (failed(value))
- return failure();
- return test::CustomParam{*value};
- }
-};
-
-inline mlir::AsmPrinter &operator<<(mlir::AsmPrinter &printer,
- test::CustomParam param) {
- return printer << param.value;
-}
-
-/// Overload the attribute parameter parser for optional integers.
-template <>
-struct FieldParser<std::optional<int>> {
- static FailureOr<std::optional<int>> parse(AsmParser &parser) {
- std::optional<int> value;
- value.emplace();
- OptionalParseResult result = parser.parseOptionalInteger(*value);
- if (result.has_value()) {
- if (succeeded(*result))
- return value;
- return failure();
- }
- value.reset();
- return value;
- }
-};
-} // namespace mlir
-
#include "TestTypeInterfaces.h.inc"
namespace test {
-
/// Storage for simple named recursive types, where the type is identified by
/// its name and can "contain" another type, including itself.
struct TestRecursiveTypeStorage : public ::mlir::TypeStorage {
@@ -145,10 +87,9 @@ class TestRecursiveType
/// Name/key getter.
::llvm::StringRef getName() { return getImpl()->name; }
};
-
} // namespace test
#define GET_TYPEDEF_CLASSES
-#include "TestTypeDefs.h.inc"
+#include "TestTypesCore.h.inc"
-#endif // MLIR_TESTTYPES_H
+#endif // MLIR_TEST_DIALECT_TEST_TESTTYPESCORE_H
diff --git a/mlir/test/lib/Dialect/Test/TestTypesSyntax.cpp b/mlir/test/lib/Dialect/Test/TestTypesSyntax.cpp
new file mode 100644
index 00000000000000..585230a5e64dc1
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestTypesSyntax.cpp
@@ -0,0 +1,99 @@
+//===- TestTypesSyntax.cpp - Test types in `Syntax` -----------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the types of the test dialect in partition `Syntax`, which
+// exercise custom and declarative assembly formats.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestTypesSyntax.h"
+#include "TestDialectBase.h"
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/DialectImplementation.h"
+
+using namespace mlir;
+using namespace test;
+
+//===----------------------------------------------------------------------===//
+// TestCustomType
+//===----------------------------------------------------------------------===//
+
+static ParseResult parseCustomTypeA(AsmParser &parser, int &aResult) {
+ return parser.parseInteger(aResult);
+}
+
+static void printCustomTypeA(AsmPrinter &printer, int a) { printer << a; }
+
+static ParseResult parseCustomTypeB(AsmParser &parser, int a,
+ std::optional<int> &bResult) {
+ if (a < 0)
+ return success();
+ for (int i : llvm::seq(0, a))
+ if (failed(parser.parseInteger(i)))
+ return failure();
+ bResult.emplace(0);
+ return parser.parseInteger(*bResult);
+}
+
+static void printCustomTypeB(AsmPrinter &printer, int a, std::optional<int> b) {
+ if (a < 0)
+ return;
+ printer << ' ';
+ for (int i : llvm::seq(0, a))
+ printer << i << ' ';
+ printer << *b;
+}
+
+static ParseResult parseFooString(AsmParser &parser, std::string &foo) {
+ std::string result;
+ if (parser.parseString(&result))
+ return failure();
+ foo = std::move(result);
+ return success();
+}
+
+static void printFooString(AsmPrinter &printer, StringRef foo) {
+ printer << '"' << foo << '"';
+}
+
+static ParseResult parseBarString(AsmParser &parser, StringRef foo) {
+ return parser.parseKeyword(foo);
+}
+
+static void printBarString(AsmPrinter &printer, StringRef foo) {
+ printer << foo;
+}
+//===----------------------------------------------------------------------===//
+// Tablegen Generated Definitions
+//===----------------------------------------------------------------------===//
+
+#define GET_TYPEDEF_CLASSES
+#include "TestTypesSyntax.cpp.inc"
+
+//===----------------------------------------------------------------------===//
+// TestTypeNewlineAndIndent
+//===----------------------------------------------------------------------===//
+
+Type TestTypeNewlineAndIndentType::parse(::mlir::AsmParser &parser) {
+ if (parser.parseLess() || parser.parseKeyword("indented_content") ||
+ parser.parseGreater()) {
+ return Type();
+ }
+ return get(parser.getContext());
+}
+
+void TestTypeNewlineAndIndentType::print(::mlir::AsmPrinter &printer) const {
+ printer << "<";
+ printer.increaseIndent();
+ printer.printNewline();
+ printer << "indented_content";
+ printer.decreaseIndent();
+ printer.printNewline();
+ printer << ">";
+}
diff --git a/mlir/test/lib/Dialect/Test/TestTypesSyntax.h b/mlir/test/lib/Dialect/Test/TestTypesSyntax.h
new file mode 100644
index 00000000000000..b81fc2d0b326c3
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestTypesSyntax.h
@@ -0,0 +1,72 @@
+//===- TestTypesSyntax.h - Test types in `Syntax` ---------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTTYPESSYNTAX_H
+#define MLIR_TEST_DIALECT_TEST_TESTTYPESSYNTAX_H
+
+#include <optional>
+
+#include "mlir/IR/DialectImplementation.h"
+#include "mlir/IR/Types.h"
+
+// The types in `Syntax` use the types in `Core`.
+#include "TestTypesCore.h"
+
+namespace test {
+/// A custom type for a test type parameter.
+struct CustomParam {
+ int value;
+
+ bool operator==(const CustomParam &other) const {
+ return other.value == value;
+ }
+};
+
+inline llvm::hash_code hash_value(const test::CustomParam ¶m) {
+ return llvm::hash_value(param.value);
+}
+} // namespace test
+
+namespace mlir {
+template <>
+struct FieldParser<test::CustomParam> {
+ static FailureOr<test::CustomParam> parse(AsmParser &parser) {
+ auto value = FieldParser<int>::parse(parser);
+ if (failed(value))
+ return failure();
+ return test::CustomParam{*value};
+ }
+};
+
+inline mlir::AsmPrinter &operator<<(mlir::AsmPrinter &printer,
+ test::CustomParam param) {
+ return printer << param.value;
+}
+
+/// Overload the attribute parameter parser for optional integers.
+template <>
+struct FieldParser<std::optional<int>> {
+ static FailureOr<std::optional<int>> parse(AsmParser &parser) {
+ std::optional<int> value;
+ value.emplace();
+ OptionalParseResult result = parser.parseOptionalInteger(*value);
+ if (result.has_value()) {
+ if (succeeded(*result))
+ return value;
+ return failure();
+ }
+ value.reset();
+ return value;
+ }
+};
+} // namespace mlir
+
+#define GET_TYPEDEF_CLASSES
+#include "TestTypesSyntax.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTTYPESSYNTAX_H
diff --git a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
index d055642bc550af..e314ed176a36cd 100644
--- a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
+++ b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
@@ -8,14 +8,12 @@
#include <utility>
-#include "TestAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Pass/Pass.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
using namespace mlir;
-using namespace test;
// Helper to print one scalar value, force int8_t to print as integer instead of
// char.
diff --git a/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp b/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
index e5db4c94452e2e..7482c9f085eac6 100644
--- a/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
+++ b/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
@@ -7,6 +7,7 @@
//===----------------------------------------------------------------------===//
#include "TestOpsCore.h"
+#include "TestTypesCore.h"
#include "mlir/Bytecode/BytecodeReader.h"
#include "mlir/Bytecode/BytecodeWriter.h"
#include "mlir/IR/BuiltinOps.h"
diff --git a/mlir/test/lib/IR/TestInterfaces.cpp b/mlir/test/lib/IR/TestInterfaces.cpp
index 881019dbfd50d6..a26db49864f3c3 100644
--- a/mlir/test/lib/IR/TestInterfaces.cpp
+++ b/mlir/test/lib/IR/TestInterfaces.cpp
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Pass/Pass.h"
diff --git a/mlir/test/lib/IR/TestTypes.cpp b/mlir/test/lib/IR/TestTypes.cpp
index ce0f799d517a68..f2fb9c18107033 100644
--- a/mlir/test/lib/IR/TestTypes.cpp
+++ b/mlir/test/lib/IR/TestTypes.cpp
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Pass/Pass.h"
diff --git a/mlir/test/mlir-tblgen/attr-type-partitions-error.td b/mlir/test/mlir-tblgen/attr-type-partitions-error.td
new file mode 100644
index 00000000000000..d5c61530f85f46
--- /dev/null
+++ b/mlir/test/mlir-tblgen/attr-type-partitions-error.td
@@ -0,0 +1,44 @@
+// RUN: not mlir-tblgen -gen-attrdef-decls -attrdefs-partition=Memory -I %S/../../include -DERROR1 %s 2>&1 | FileCheck --check-prefix=ERROR1 %s
+// RUN: not mlir-tblgen -gen-typedef-defs -typedefs-partition=Memroy -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
+// RUN: not mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Memory -I %S/../../include -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
+
+include "mlir/IR/AttrTypeBase.td"
+
+def MemoryPartition : Partition<"Memory">;
+
+def Test_Dialect : Dialect {
+ let name = "test";
+}
+
+def AddressAttr : AttrDef<Test_Dialect, "Address"> {
+ let mnemonic = "address";
+ let partition = MemoryPartition;
+}
+
+def PointerType : TypeDef<Test_Dialect, "Pointer"> {
+ let mnemonic = "ptr";
+ let partition = MemoryPartition;
+}
+
+#ifdef ERROR1
+// ERROR1: error: attribute 'NoPartitionAttr' is in no partition, but its attributes are generated by partition with -attrdefs-partition
+def NoPartitionAttr : AttrDef<Test_Dialect, "NoPartition"> {
+ let mnemonic = "no_partition";
+}
+#endif
+
+#ifdef ERROR3
+def SnakeCasePartition : Partition<"control_flow">;
+def CamelCasePartition : Partition<"ControlFlow">;
+def BranchAttr : AttrDef<Test_Dialect, "Branch"> {
+ let mnemonic = "br";
+ let partition = SnakeCasePartition;
+}
+// ERROR3: error: attribute partitions 'control_flow' and 'ControlFlow' have the same name 'ControlFlow' in generated functions
+def CondBranchAttr : AttrDef<Test_Dialect, "CondBranch"> {
+ let mnemonic = "cond_br";
+ let partition = CamelCasePartition;
+}
+#endif
+
+// ERROR2: error: no type is in the specified type partition 'Memroy'
diff --git a/mlir/test/mlir-tblgen/attr-type-partitions.td b/mlir/test/mlir-tblgen/attr-type-partitions.td
new file mode 100644
index 00000000000000..cb6f5a8375ad30
--- /dev/null
+++ b/mlir/test/mlir-tblgen/attr-type-partitions.td
@@ -0,0 +1,151 @@
+// RUN: mlir-tblgen -gen-attrdef-decls -attrdefs-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DECLS
+// RUN: mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DEFS
+// RUN: mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=FIRST
+// RUN: mlir-tblgen -gen-typedef-defs -typedefs-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=TYPES
+// RUN: mlir-tblgen -gen-attrdef-defs -I %S/../../include %s | FileCheck %s --check-prefix=ALL
+
+include "mlir/IR/AttrTypeBase.td"
+
+def Test_ArithPartition : Partition<"Arith">;
+def Test_MemoryPartition : Partition<"Memory">;
+
+def Test_Dialect : Dialect {
+ let name = "test";
+ let cppNamespace = "test";
+ let useDefaultAttributePrinterParser = 1;
+}
+
+class Test_Attr<string name, string attrMnemonic> : AttrDef<Test_Dialect, name> {
+ let mnemonic = attrMnemonic;
+ let partition = Test_ArithPartition;
+}
+
+def IntAttr : Test_Attr<"Int", "int"> {
+ let parameters = (ins "int":$value);
+ let assemblyFormat = "`<` $value `>`";
+}
+
+let partition = Test_MemoryPartition in {
+def AddressAttr : Test_Attr<"Address", "address"> {
+ let parameters = (ins "IntAttr":$offset);
+ let assemblyFormat = "`<` $offset `>`";
+}
+def AlignmentAttr : Test_Attr<"Alignment", "alignment">;
+}
+
+def IndexType : TypeDef<Test_Dialect, "Index"> {
+ let mnemonic = "index";
+ let partition = Test_ArithPartition;
+}
+
+// Only the defs of the specified partition are declared. The defs of the other
+// partitions are forward declared, so that declarations can refer to them. The
+// parse and print dispatch functions and the registration hook of the dialect
+// are declared, as well as those of all partitions in the `detail` namespace,
+// which they dispatch to and register the defs of all partitions with.
+// DECLS: namespace mlir {
+// DECLS-NEXT: class AsmParser;
+// DECLS-NEXT: class AsmPrinter;
+// DECLS-NEXT: class OptionalParseResult;
+// DECLS-NEXT: } // namespace mlir
+// DECLS: class AddressAttr;
+// DECLS-NEXT: class AlignmentAttr;
+// DECLS-NEXT: class IntAttr;
+// DECLS-NOT: class IntAttr :
+// DECLS: class AddressAttr : public
+// DECLS-NOT: class IntAttr :
+// DECLS: class TestDialect;
+// DECLS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value);
+// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
+// DECLS-NEXT: void registerTestDialectAttributes(TestDialect *dialect);
+// DECLS-NEXT: namespace detail {
+// DECLS-EMPTY:
+// DECLS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParserArith(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value);
+// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinterArith(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
+// DECLS-NEXT: void registerTestDialectAttributesArith(TestDialect *dialect);
+// DECLS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParserMemory(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value);
+// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinterMemory(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
+// DECLS-NEXT: void registerTestDialectAttributesMemory(TestDialect *dialect);
+// DECLS-EMPTY:
+// DECLS-NEXT: } // namespace detail
+// DECLS-NOT: IntAttr
+
+// The dispatch functions of a partition continue with the mnemonic that the
+// dispatch functions of previous partitions parsed.
+// DEFS-LABEL: #ifdef GET_ATTRDEF_LIST
+// DEFS-NEXT: #undef GET_ATTRDEF_LIST
+// DEFS-EMPTY:
+// DEFS-NEXT: test::AddressAttr,
+// DEFS-NEXT: test::AlignmentAttr
+// DEFS-EMPTY:
+// DEFS-NEXT: #endif
+// DEFS: namespace detail {
+// DEFS-EMPTY:
+// DEFS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParserMemory(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) {
+// DEFS-NEXT: return ::mlir::AsmParser::KeywordSwitch<::mlir::OptionalParseResult>(parser, mnemonic)
+// DEFS: ::llvm::LogicalResult generatedTestDialectAttributePrinterMemory(::mlir::Attribute def, ::mlir::AsmPrinter &printer) {
+// DEFS: } // namespace detail
+// DEFS-NOT: registerTestDialectAttributes(
+// DEFS: void registerTestDialectAttributesMemory(TestDialect *dialect) {
+// DEFS-NEXT: ::mlir::AbstractAttribute::insert<AddressAttr>(*dialect);
+// DEFS-NEXT: ::mlir::AbstractAttribute::insert<AlignmentAttr>(*dialect);
+// DEFS-NEXT: }
+// DEFS-EMPTY:
+// DEFS-NEXT: } // namespace detail
+// DEFS-NOT: generatedTestDialectAttributeParser(
+// DEFS-NOT: IntAttr::
+// DEFS-NOT: TestDialect::parseAttribute
+
+// The first partition by name also defines the dispatch functions and the
+// registration hook of the dialect, which call those of all partitions. The
+// default parser and printer of the dialect call its dispatch functions.
+// FIRST: ::mlir::OptionalParseResult generatedTestDialectAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) {
+// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectAttributeParserArith(parser, mnemonic, type, value); result.has_value())
+// FIRST-NEXT: return result;
+// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectAttributeParserMemory(parser, mnemonic, type, value); result.has_value())
+// FIRST-NEXT: return result;
+// FIRST-NEXT: return std::nullopt;
+// FIRST-NEXT: }
+// FIRST: ::llvm::LogicalResult generatedTestDialectAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer) {
+// FIRST-NEXT: if (::mlir::succeeded(test::detail::generatedTestDialectAttributePrinterArith(def, printer)))
+// FIRST-NEXT: return ::mlir::success();
+// FIRST-NEXT: if (::mlir::succeeded(test::detail::generatedTestDialectAttributePrinterMemory(def, printer)))
+// FIRST-NEXT: return ::mlir::success();
+// FIRST-NEXT: return ::mlir::failure();
+// FIRST-NEXT: }
+// FIRST: void registerTestDialectAttributes(TestDialect *dialect) {
+// FIRST-NEXT: test::detail::registerTestDialectAttributesArith(dialect);
+// FIRST-NEXT: test::detail::registerTestDialectAttributesMemory(dialect);
+// FIRST-NEXT: }
+// FIRST-NEXT: namespace detail {
+// FIRST-EMPTY:
+// FIRST-NEXT: void registerTestDialectAttributesArith(TestDialect *dialect) {
+// FIRST-NEXT: ::mlir::AbstractAttribute::insert<IntAttr>(*dialect);
+// FIRST-NEXT: }
+// FIRST: ::mlir::Attribute TestDialect::parseAttribute(
+// FIRST: auto parseResult = generatedTestDialectAttributeParser(parser, &attrTag, type, attr);
+// FIRST: if (::mlir::succeeded(generatedTestDialectAttributePrinter(attr, printer)))
+
+// TYPES: ::mlir::OptionalParseResult generatedTestDialectTypeParserArith(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
+// TYPES: ::mlir::OptionalParseResult generatedTestDialectTypeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
+// TYPES-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectTypeParserArith(parser, mnemonic, value); result.has_value())
+// TYPES: void registerTestDialectTypesArith(TestDialect *dialect) {
+// TYPES-NEXT: ::mlir::AbstractType::insert<IndexType>(*dialect);
+
+// Without -attrdefs-partition, partitions are ignored. The dispatch functions
+// and the hook that registers all defs are local to the definitions, since a
+// dialect may generate its attributes from several files. The dispatch
+// functions are also available under their former names.
+// ALL-NOT: generatedTestDialectAttributeParserArith
+// ALL: static ::mlir::OptionalParseResult generatedTestDialectAttributeParser(
+// ALL-NEXT: return ::mlir::AsmParser::KeywordSwitch<::mlir::OptionalParseResult>(parser, mnemonic)
+// ALL: static ::mlir::OptionalParseResult generatedAttributeParser(
+// ALL-NEXT: return test::generatedTestDialectAttributeParser(parser, mnemonic, type, value);
+// ALL-NOT: generatedTestDialectAttributeParserArith
+// ALL: class TestDialect;
+// ALL-NEXT: {{\[\[}}maybe_unused{{\]\]}} static void registerTestDialectAttributes(TestDialect *dialect) {
+// ALL-NEXT: ::mlir::AbstractAttribute::insert<IntAttr>(*dialect);
+// ALL-NEXT: ::mlir::AbstractAttribute::insert<AddressAttr>(*dialect);
+// ALL-NEXT: ::mlir::AbstractAttribute::insert<AlignmentAttr>(*dialect);
+// ALL-NEXT: }
+// ALL-NOT: generatedTestDialectAttributeParserArith
diff --git a/mlir/test/mlir-tblgen/attrdefs.td b/mlir/test/mlir-tblgen/attrdefs.td
index 69baa712b5bafc..f890f5dde0677f 100644
--- a/mlir/test/mlir-tblgen/attrdefs.td
+++ b/mlir/test/mlir-tblgen/attrdefs.td
@@ -19,7 +19,7 @@ include "mlir/IR/OpBase.td"
// DEF: ::test::CompoundAAttr,
// DEF: ::test::SingleParameterAttr
-// DEF-LABEL: ::mlir::OptionalParseResult generatedAttributeParser(
+// DEF-LABEL: ::mlir::OptionalParseResult generatedTestDialectAttributeParser(
// DEF-SAME: ::mlir::AsmParser &parser,
// DEF-SAME: ::llvm::StringRef *mnemonic, ::mlir::Type type,
// DEF-SAME: ::mlir::Attribute &value) {
@@ -34,6 +34,17 @@ include "mlir/IR/OpBase.td"
// DEF: .Default([&](llvm::StringRef keyword,
// DEF-NEXT: *mnemonic = keyword;
// DEF-NEXT: return std::nullopt;
+// DEF: ::llvm::LogicalResult generatedTestDialectAttributePrinter(
+
+// Without partitions, the dispatch functions are also available under their
+// former names.
+// DEF: /// Kept for compatibility, use `generatedTestDialectAttributeParser` and `generatedTestDialectAttributePrinter` instead.
+// DEF-NEXT: {{\[\[}}maybe_unused{{\]\]}} static ::mlir::OptionalParseResult generatedAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) {
+// DEF-NEXT: return ::test::generatedTestDialectAttributeParser(parser, mnemonic, type, value);
+// DEF-NEXT: }
+// DEF: {{\[\[}}maybe_unused{{\]\]}} static ::llvm::LogicalResult generatedAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer) {
+// DEF-NEXT: return ::test::generatedTestDialectAttributePrinter(def, printer);
+// DEF-NEXT: }
def Test_Dialect: Dialect {
// DECL-NOT: TestDialect
diff --git a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
index c0eedb879bcda4..a1d448c7532af6 100644
--- a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
+++ b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
@@ -29,7 +29,7 @@ def AttrA : TestAttr<"AttrA"> {
// ATTR: ::llvm::StringRef attrTag;
// ATTR: {
// ATTR: ::mlir::Attribute attr;
-// ATTR: auto parseResult = generatedAttributeParser(parser, &attrTag, type, attr);
+// ATTR: auto parseResult = generatedTestDialectAttributeParser(parser, &attrTag, type, attr);
// ATTR: if (parseResult.has_value())
// ATTR: return attr;
// ATTR: }
@@ -40,7 +40,7 @@ def AttrA : TestAttr<"AttrA"> {
// ATTR: void TestDialect::printAttribute(::mlir::Attribute attr,
// ATTR: ::mlir::DialectAsmPrinter &printer) const {
-// ATTR: if (::mlir::succeeded(generatedAttributePrinter(attr, printer)))
+// ATTR: if (::mlir::succeeded(generatedTestDialectAttributePrinter(attr, printer)))
// ATTR: return;
// ATTR: }
@@ -56,7 +56,7 @@ def TypeA : TestType<"TypeA"> {
// TYPE: ::llvm::SMLoc typeLoc = parser.getCurrentLocation();
// TYPE: ::llvm::StringRef mnemonic;
// TYPE: ::mlir::Type genType;
-// TYPE: auto parseResult = generatedTypeParser(parser, &mnemonic, genType);
+// TYPE: auto parseResult = generatedTestDialectTypeParser(parser, &mnemonic, genType);
// TYPE: if (parseResult.has_value())
// TYPE: return genType;
// TYPE: parser.emitError(typeLoc) << "unknown type `"
@@ -66,7 +66,7 @@ def TypeA : TestType<"TypeA"> {
// TYPE: void TestDialect::printType(::mlir::Type type,
// TYPE: ::mlir::DialectAsmPrinter &printer) const {
-// TYPE: if (::mlir::succeeded(generatedTypePrinter(type, printer)))
+// TYPE: if (::mlir::succeeded(generatedTestDialectTypePrinter(type, printer)))
// TYPE: return;
// TYPE: }
diff --git a/mlir/test/mlir-tblgen/op-partitions-error.td b/mlir/test/mlir-tblgen/op-partitions-error.td
index 0019ae1974c97b..2bd5a9d636bba5 100644
--- a/mlir/test/mlir-tblgen/op-partitions-error.td
+++ b/mlir/test/mlir-tblgen/op-partitions-error.td
@@ -33,7 +33,7 @@ def CamelCasePartition : Partition<"ControlFlow">;
def BranchOp : Op<Test_Dialect, "br"> {
let partition = SnakeCasePartition;
}
-// ERROR2: error: op partitions 'control_flow' and 'ControlFlow' have the same registration hook 'registerTestDialectOperationsControlFlow'
+// ERROR2: error: op partitions 'control_flow' and 'ControlFlow' have the same name 'ControlFlow' in generated functions
def CondBranchOp : Op<Test_Dialect, "cond_br"> {
let partition = CamelCasePartition;
}
diff --git a/mlir/test/mlir-tblgen/typedefs.td b/mlir/test/mlir-tblgen/typedefs.td
index 30bded77d24085..6c7ef329f25bcb 100644
--- a/mlir/test/mlir-tblgen/typedefs.td
+++ b/mlir/test/mlir-tblgen/typedefs.td
@@ -20,7 +20,7 @@ include "mlir/IR/OpBase.td"
// DEF: ::test::SingleParameterType,
// DEF: ::test::IntegerType
-// DEF-LABEL: ::mlir::OptionalParseResult generatedTypeParser(
+// DEF-LABEL: ::mlir::OptionalParseResult generatedTestDialectTypeParser(
// DEF-SAME: ::mlir::AsmParser &parser,
// DEF-SAME: ::llvm::StringRef *mnemonic,
// DEF-SAME: ::mlir::Type &value) {
@@ -34,6 +34,9 @@ include "mlir/IR/OpBase.td"
// DEF: .Default([&](llvm::StringRef keyword,
// DEF-NEXT: *mnemonic = keyword;
// DEF-NEXT: return std::nullopt;
+// DEF: /// Kept for compatibility, use `generatedTestDialectTypeParser` and `generatedTestDialectTypePrinter` instead.
+// DEF-NEXT: {{\[\[}}maybe_unused{{\]\]}} static ::mlir::OptionalParseResult generatedTypeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
+// DEF-NEXT: return ::test::generatedTestDialectTypeParser(parser, mnemonic, value);
def Test_Dialect: Dialect {
// DECL-NOT: TestDialect
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index 97f95a1c0aafdc..e3a3a7abe1352e 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -8,6 +8,7 @@
#include "AttrOrTypeFormatGen.h"
#include "CppGenUtilities.h"
+#include "PartitionHelpers.h"
#include "mlir/TableGen/AttrOrTypeDef.h"
#include "mlir/TableGen/Class.h"
#include "mlir/TableGen/Format.h"
@@ -848,8 +849,10 @@ namespace {
/// This struct is the base generator used when processing tablegen interfaces.
class DefGenerator {
public:
- bool emitDecls(StringRef selectedDialect);
- bool emitDefs(StringRef selectedDialect);
+ /// Emit the declarations or definitions of the defs of `selectedDialect`, or
+ /// only those in partition `selectedPartition` if set.
+ bool emitDecls(StringRef selectedDialect, StringRef selectedPartition);
+ bool emitDefs(StringRef selectedDialect, StringRef selectedPartition);
protected:
DefGenerator(ArrayRef<const Record *> defs, raw_ostream &os,
@@ -862,16 +865,54 @@ class DefGenerator {
});
}
+ /// If `selectedPartition` is set, removes the defs of other partitions from
+ /// `defs`, assigning them to `otherPartitionDefs` if non-null, and returns
+ /// the names of all partitions, sorted by name.
+ SmallVector<StringRef>
+ selectPartition(StringRef selectedPartition,
+ SmallVectorImpl<AttrOrTypeDef> &defs,
+ SmallVectorImpl<AttrOrTypeDef> *otherPartitionDefs = nullptr);
+
/// Emit the list of def type names.
void emitTypeDefList(ArrayRef<AttrOrTypeDef> defs);
- /// Emit the code to dispatch between different defs during parsing/printing.
- void emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs);
- /// Returns the name of the function that registers the defs of `dialect`.
- std::string getRegistrationHookName(const Dialect &dialect) const;
-
- /// Emit the definition of the hook that registers `defs` with their dialect.
- void emitRegistrationHook(ArrayRef<AttrOrTypeDef> defs);
+ /// Emit the code to dispatch between different defs during parsing/printing.
+ ///
+ /// When partitioning only the `selectedPartition` dispatch functions are
+ /// emitted.
+ /// The partition that comes lexicographically first is additionally elected
+ /// to define the top-level parsing/printing dispatcher that delegates to
+ /// every partitions' dispatcher.
+ void emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs,
+ StringRef selectedPartition,
+ ArrayRef<StringRef> partitions);
+
+ /// Emit the dispatch functions under their legacy names, which forward to
+ /// the dispatch functions of `dialect`. Only used without partitions.
+ void emitLegacyParsePrintDispatch(const Dialect &dialect);
+
+ /// Create the functions `parserName` and `printerName` that dispatch parsing
+ /// and printing to the defs.
+ std::pair<Method, Method>
+ createParsePrintDispatch(StringRef parserName, StringRef printerName,
+ Method::Properties properties) const;
+
+ /// Returns the name of the function that dispatches parsing (`kind` is
+ /// "Parser") or printing (`kind` is "Printer") to the defs of `dialect` in
+ /// `partition`, or to all defs of `dialect` if `partition` is empty.
+ std::string getDispatchName(const Dialect &dialect, StringRef kind,
+ StringRef partition = "") const;
+
+ /// Returns the name of the function that registers the defs of `dialect` in
+ /// `partition`, or all defs of `dialect` if `partition` is empty.
+ std::string getRegistrationHookName(const Dialect &dialect,
+ StringRef partition) const;
+
+ /// Emit the definitions of the registration hooks of `defs`. See
+ /// `emitDefs`.
+ void emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
+ StringRef selectedPartition,
+ ArrayRef<StringRef> partitions);
/// The set of def records to emit.
std::vector<const Record *> defRecords;
@@ -911,15 +952,19 @@ static const char *const typeDefDeclHeader = R"(
namespace mlir {
class AsmParser;
class AsmPrinter;
+class OptionalParseResult;
} // namespace mlir
)";
-bool DefGenerator::emitDecls(StringRef selectedDialect) {
+bool DefGenerator::emitDecls(StringRef selectedDialect,
+ StringRef selectedPartition) {
emitSourceFileHeader((defType + "Def Declarations").str(), os);
llvm::IfDefEmitter scope(os, "GET_" + defType.upper() + "DEF_CLASSES");
- SmallVector<AttrOrTypeDef, 16> defs;
+ SmallVector<AttrOrTypeDef, 16> defs, otherPartitionDefs;
collectAllDefs(selectedDialect, defRecords, defs);
+ SmallVector<StringRef> partitions =
+ selectPartition(selectedPartition, defs, &otherPartitionDefs);
// The required includes are only known once all declarations were
// generated, so buffer the declarations until the includes are emitted.
@@ -937,6 +982,10 @@ bool DefGenerator::emitDecls(StringRef selectedDialect) {
def.getDescription());
declOs << "class " << def.getCppClassName() << ";\n";
}
+ // Forward declare the defs of the other partitions, so that the
+ // declarations can refer to defs of any partition.
+ for (const AttrOrTypeDef &def : otherPartitionDefs)
+ declOs << "class " << def.getCppClassName() << ";\n";
// Emit the declarations.
for (const AttrOrTypeDef &def : defs) {
@@ -944,6 +993,30 @@ bool DefGenerator::emitDecls(StringRef selectedDialect) {
gen.emitDecl(declOs);
llvm::append_range(includes, gen.getRequiredIncludes());
}
+
+ // When generating by partition, declare the parse and print dispatch
+ // functions and the registration hook of the dialect, as well as those of
+ // all partitions, which they call, in the `detail` namespace.
+ if (!partitions.empty()) {
+ raw_indented_ostream indentedOs(declOs);
+ Dialect dialect = defs.front().getDialect();
+ const char *const hookDecl = "void {0}({1} *dialect);\n";
+ auto declareFunctions = [&](StringRef partition) {
+ auto [parser, printer] = createParsePrintDispatch(
+ getDispatchName(dialect, "Parser", partition),
+ getDispatchName(dialect, "Printer", partition), Method::None);
+ parser.writeDeclTo(indentedOs);
+ printer.writeDeclTo(indentedOs);
+ declOs << llvm::formatv(hookDecl,
+ getRegistrationHookName(dialect, partition),
+ dialect.getCppClassName());
+ };
+ declOs << "class " << dialect.getCppClassName() << ";\n";
+ declareFunctions("");
+ llvm::NamespaceEmitter detailNs(declOs, "detail");
+ for (StringRef partition : partitions)
+ declareFunctions(partition);
+ }
}
tblgen::emitIncludes(os, includes);
@@ -983,6 +1056,8 @@ void DefGenerator::emitTypeDefList(ArrayRef<AttrOrTypeDef> defs) {
/// {0}: the dialect fully qualified class name.
/// {1}: the optional code for the dynamic attribute parser dispatch.
/// {2}: the optional code for the dynamic attribute printer dispatch.
+/// {3}: the name of the function dispatching to the attribute parsers.
+/// {4}: the name of the function dispatching to the attribute printers.
static const char *const dialectDefaultAttrPrinterParserDispatch = R"(
/// Parse an attribute registered to this dialect.
::mlir::Attribute {0}::parseAttribute(::mlir::DialectAsmParser &parser,
@@ -991,7 +1066,7 @@ ::mlir::Attribute {0}::parseAttribute(::mlir::DialectAsmParser &parser,
::llvm::StringRef attrTag;
{{
::mlir::Attribute attr;
- auto parseResult = generatedAttributeParser(parser, &attrTag, type, attr);
+ auto parseResult = {3}(parser, &attrTag, type, attr);
if (parseResult.has_value())
return attr;
}
@@ -1003,7 +1078,7 @@ ::mlir::Attribute {0}::parseAttribute(::mlir::DialectAsmParser &parser,
/// Print an attribute registered to this dialect.
void {0}::printAttribute(::mlir::Attribute attr,
::mlir::DialectAsmPrinter &printer) const {{
- if (::mlir::succeeded(generatedAttributePrinter(attr, printer)))
+ if (::mlir::succeeded({4}(attr, printer)))
return;
{2}
}
@@ -1032,13 +1107,15 @@ static const char *const dialectDynamicAttrPrinterDispatch = R"(
/// {0}: the dialect fully qualified class name.
/// {1}: the optional code for the dynamic type parser dispatch.
/// {2}: the optional code for the dynamic type printer dispatch.
+/// {3}: the name of the function dispatching to the type parsers.
+/// {4}: the name of the function dispatching to the type printers.
static const char *const dialectDefaultTypePrinterParserDispatch = R"(
/// Parse a type registered to this dialect.
::mlir::Type {0}::parseType(::mlir::DialectAsmParser &parser) const {{
::llvm::SMLoc typeLoc = parser.getCurrentLocation();
::llvm::StringRef mnemonic;
::mlir::Type genType;
- auto parseResult = generatedTypeParser(parser, &mnemonic, genType);
+ auto parseResult = {3}(parser, &mnemonic, genType);
if (parseResult.has_value())
return genType;
{1}
@@ -1049,7 +1126,7 @@ ::mlir::Type {0}::parseType(::mlir::DialectAsmParser &parser) const {{
/// Print a type registered to this dialect.
void {0}::printType(::mlir::Type type,
::mlir::DialectAsmPrinter &printer) const {{
- if (::mlir::succeeded(generatedTypePrinter(type, printer)))
+ if (::mlir::succeeded({4}(type, printer)))
return;
{2}
}
@@ -1105,28 +1182,78 @@ static bool needsLeadingSpace(const AttrOrTypeDef &def) {
return !llvm::is_contained("<{([`", fmtStr[1]);
}
-/// Emit the dialect printer/parser dispatcher. User's code should call these
-/// functions from their dialect's print/parse methods.
-void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs) {
- if (llvm::none_of(defs, [](const AttrOrTypeDef &def) {
- return def.getMnemonic().has_value();
- })) {
- return;
- }
- // Declare the parser.
+std::pair<Method, Method>
+DefGenerator::createParsePrintDispatch(StringRef parserName,
+ StringRef printerName,
+ Method::Properties properties) const {
SmallVector<MethodParameter> params = {{"::mlir::AsmParser &", "parser"},
{"::llvm::StringRef *", "mnemonic"}};
if (isAttrGenerator)
params.emplace_back("::mlir::Type", "type");
params.emplace_back(strfmt("::mlir::{0} &", valueType), "value");
- Method parse("::mlir::OptionalParseResult",
- strfmt("generated{0}Parser", valueType), Method::StaticInline,
+ Method parse("::mlir::OptionalParseResult", parserName, properties,
std::move(params));
- // Declare the printer.
- Method printer("::llvm::LogicalResult",
- strfmt("generated{0}Printer", valueType), Method::StaticInline,
+ Method printer("::llvm::LogicalResult", printerName, properties,
{{strfmt("::mlir::{0}", valueType), "def"},
{"::mlir::AsmPrinter &", "printer"}});
+ return {std::move(parse), std::move(printer)};
+}
+
+std::string DefGenerator::getDispatchName(const Dialect &dialect,
+ StringRef kind,
+ StringRef partition) const {
+ return strfmt("generated{0}{1}{2}{3}", dialect.getCppClassName(), valueType,
+ kind, getPartitionFunctionSuffix(partition));
+}
+
+std::string DefGenerator::getRegistrationHookName(const Dialect &dialect,
+ StringRef partition) const {
+ return strfmt("register{0}{1}s{2}", dialect.getCppClassName(), valueType,
+ getPartitionFunctionSuffix(partition));
+}
+
+SmallVector<StringRef> DefGenerator::selectPartition(
+ StringRef selectedPartition, SmallVectorImpl<AttrOrTypeDef> &defs,
+ SmallVectorImpl<AttrOrTypeDef> *otherPartitionDefs) {
+ if (selectedPartition.empty())
+ return {};
+
+ SmallVector<const Record *> records = llvm::map_to_vector(
+ defs, [](const AttrOrTypeDef &def) { return def.getDef(); });
+ verifyPartitions(
+ records, selectedPartition, isAttrGenerator ? "attribute" : "type",
+ isAttrGenerator ? "-attrdefs-partition" : "-typedefs-partition");
+
+ SmallVector<StringRef> partitions = getPartitionNames(records);
+ tblgen::selectPartition(
+ selectedPartition, defs, otherPartitionDefs,
+ [](const AttrOrTypeDef &def) { return def.getDef(); });
+ return partitions;
+}
+
+/// Emit the dialect printer/parser dispatcher. User's code should call these
+/// functions from their dialect's print/parse methods.
+void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs,
+ StringRef selectedPartition,
+ ArrayRef<StringRef> partitions) {
+ // The dispatch functions of all partitions are declared, so they are always
+ // emitted when generating by partition.
+ if (selectedPartition.empty() &&
+ llvm::none_of(defs, [](const AttrOrTypeDef &def) {
+ return def.getMnemonic().has_value();
+ })) {
+ return;
+ }
+
+ Dialect dialect = defs.front().getDialect();
+ // Without partitions, the dispatch functions are local to the definitions.
+ // With partitions, they are declared by every partition, so that the
+ // top-level dispatch function of the dialect can call them.
+ bool byPartition = !selectedPartition.empty();
+ auto [parse, printer] = createParsePrintDispatch(
+ getDispatchName(dialect, "Parser", selectedPartition),
+ getDispatchName(dialect, "Printer", selectedPartition),
+ byPartition ? Method::None : Method::StaticInline);
// The parser dispatch uses a KeywordSwitch, matching on the mnemonic and
// calling the def's parse function. The KeywordSwitch only parses the
@@ -1195,34 +1322,126 @@ void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs) {
printer.body() << " .Default([](auto) { return ::mlir::failure(); });";
raw_indented_ostream indentedOs(os);
- parse.writeDeclTo(indentedOs);
- printer.writeDeclTo(indentedOs);
+ if (!byPartition) {
+ {
+ DialectNamespaceEmitter ns(os, dialect);
+ // Note: The functions are inline, therefore only the declarations need
+ // to be emitted.
+ parse.writeDeclTo(indentedOs);
+ printer.writeDeclTo(indentedOs);
+ }
+ emitLegacyParsePrintDispatch(dialect);
+ return;
+ }
+
+ DialectNamespaceEmitter ns(os, dialect);
+ {
+ llvm::NamespaceEmitter detailNs(os, "detail");
+ parse.writeDefTo(indentedOs, "");
+ printer.writeDefTo(indentedOs, "");
+ }
+
+ // The first partition by name also emits the dispatch functions of the
+ // dialect, which try the dispatch functions of every partition in turn.
+ if (partitions.front() != selectedPartition)
+ return;
+
+ auto [parseAll, printAll] = createParsePrintDispatch(
+ getDispatchName(dialect, "Parser"), getDispatchName(dialect, "Printer"),
+ Method::None);
+ for (StringRef partition : partitions) {
+ parseAll.body() << llvm::formatv(
+ " if (::mlir::OptionalParseResult result = {0}::detail::{1}(parser, "
+ "mnemonic, {2}value); result.has_value())\n"
+ " return result;\n",
+ dialect.getCppNamespace(),
+ getDispatchName(dialect, "Parser", partition),
+ isAttrGenerator ? "type, " : "");
+ printAll.body() << llvm::formatv(
+ " if (::mlir::succeeded({0}::detail::{1}(def, printer)))\n"
+ " return ::mlir::success();\n",
+ dialect.getCppNamespace(),
+ getDispatchName(dialect, "Printer", partition));
+ }
+ parseAll.body() << " return std::nullopt;";
+ printAll.body() << " return ::mlir::failure();";
+ parseAll.writeDefTo(indentedOs, "");
+ printAll.writeDefTo(indentedOs, "");
}
-std::string
-DefGenerator::getRegistrationHookName(const Dialect &dialect) const {
- return strfmt("register{0}{1}s", dialect.getCppClassName(), valueType);
+/// Emit `generatedAttributeParser` and `generatedAttributePrinter` (or
+/// `...Type...`), the former names of the dispatch functions of the dialect
+/// when not generating by partition, which forward to them.
+// TODO: Mark these functions `[[deprecated]]` once all in-tree users call the
+// dispatch functions of the dialect instead, and remove them later.
+void DefGenerator::emitLegacyParsePrintDispatch(const Dialect &dialect) {
+ auto [parse, printer] = createParsePrintDispatch(
+ strfmt("generated{0}Parser", valueType),
+ strfmt("generated{0}Printer", valueType), Method::StaticInline);
+ parse.body() << llvm::formatv(
+ " return {0}::{1}(parser, mnemonic, {2}value);",
+ dialect.getCppNamespace(), getDispatchName(dialect, "Parser"),
+ isAttrGenerator ? "type, " : "");
+ printer.body() << llvm::formatv(" return {0}::{1}(def, printer);",
+ dialect.getCppNamespace(),
+ getDispatchName(dialect, "Printer"));
+ // Unlike the dispatch functions of the dialect, which these functions use,
+ // these functions are unused unless called by the dialect.
+ raw_indented_ostream indentedOs(os);
+ os << "/// Kept for compatibility, use `"
+ << getDispatchName(dialect, "Parser") << "` and `"
+ << getDispatchName(dialect, "Printer") << "` instead.\n"
+ << "[[maybe_unused]] ";
+ parse.writeDeclTo(indentedOs);
+ os << "[[maybe_unused]] ";
+ printer.writeDeclTo(indentedOs);
}
-/// Emit the hook that registers the defs with their dialect. Since registering
-/// requires the definitions of the storage classes, the hook is a static
-/// function.
-void DefGenerator::emitRegistrationHook(ArrayRef<AttrOrTypeDef> defs) {
+/// Emit the hooks that register the defs with their dialect. When generating
+/// by partition, the hook of the partition is emitted in the `detail`
+/// namespace, and the first partition by name also emits the hook that calls
+/// the hooks of all partitions, all of which are declared by every partition.
+/// Otherwise, the hook registering all defs is a static function.
+void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
+ StringRef selectedPartition,
+ ArrayRef<StringRef> partitions) {
Dialect dialect = defs.front().getDialect();
std::string dialectClass = dialect.getCppClassName();
DialectNamespaceEmitter ns(os, dialect);
- // TODO: Ideally, the hook would be non-static, so that callers do not have to
- // be in the same TU as the registration function. This is currently blocked
- // by dialects defining their attributes and types across multiple TUs (e.g.
- // the transform dialect and its extensions), whose hooks would cause
- // multiple definition errors.
- os << "class " << dialectClass << ";\n"
- << llvm::formatv("[[maybe_unused]] static void {0}({1} *dialect) {{\n",
- getRegistrationHookName(dialect), dialectClass);
- for (const AttrOrTypeDef &def : defs)
- os << llvm::formatv(" ::mlir::Abstract{0}::insert<{1}>(*dialect);\n",
- valueType, def.getCppClassName());
- os << "}\n";
+ const char *const hookDef = "{0}void {1}({2} *dialect) {{\n";
+ auto emitInserts = [&] {
+ for (const AttrOrTypeDef &def : defs)
+ os << llvm::formatv(" ::mlir::Abstract{0}::insert<{1}>(*dialect);\n",
+ valueType, def.getCppClassName());
+ os << "}\n";
+ };
+ if (selectedPartition.empty()) {
+ // TODO: Ideally, the hook would be non-static, so that callers do not have
+ // to be in the same TU as the registration function. This is currently
+ // blocked by dialects defining their attributes and types across multiple
+ // TUs (e.g. the transform dialect and its extensions), whose hooks would
+ // cause multiple definition errors.
+ os << "class " << dialectClass << ";\n"
+ << llvm::formatv(hookDef, "[[maybe_unused]] static ",
+ getRegistrationHookName(dialect, ""), dialectClass);
+ emitInserts();
+ return;
+ }
+
+ if (partitions.front() == selectedPartition) {
+ os << llvm::formatv(hookDef, "", getRegistrationHookName(dialect, ""),
+ dialectClass);
+ for (StringRef partition : partitions)
+ os << " " << dialect.getCppNamespace()
+ << "::detail::" << getRegistrationHookName(dialect, partition)
+ << "(dialect);\n";
+ os << "}\n";
+ }
+ llvm::NamespaceEmitter detailNs(os, "detail");
+ os << llvm::formatv(hookDef, "",
+ getRegistrationHookName(dialect, selectedPartition),
+ dialectClass);
+ emitInserts();
}
/// Headers declaring the C++ constructs used by every generated attribute or
@@ -1240,18 +1459,20 @@ static constexpr StringRef attrOrTypeDefIncludes[] = {
"mlir/IR/OpImplementation.h",
};
-bool DefGenerator::emitDefs(StringRef selectedDialect) {
+bool DefGenerator::emitDefs(StringRef selectedDialect,
+ StringRef selectedPartition) {
emitSourceFileHeader((defType + "Def Definitions").str(), os);
SmallVector<AttrOrTypeDef, 16> defs;
collectAllDefs(selectedDialect, defRecords, defs);
+ SmallVector<StringRef> partitions = selectPartition(selectedPartition, defs);
if (defs.empty())
return false;
emitTypeDefList(defs);
llvm::IfDefEmitter scope(os, "GET_" + defType.upper() + "DEF_CLASSES");
tblgen::emitIncludes(os, attrOrTypeDefIncludes);
- emitParsePrintDispatch(defs);
+ emitParsePrintDispatch(defs, selectedPartition, partitions);
for (const AttrOrTypeDef &def : defs) {
{
DialectNamespaceEmitter ns(os, def.getDialect());
@@ -1264,21 +1485,29 @@ bool DefGenerator::emitDefs(StringRef selectedDialect) {
<< def.getDialect().getCppNamespace() << "::" << def.getCppClassName()
<< ")\n";
}
- emitRegistrationHook(defs);
+ emitRegistrationHooks(defs, selectedPartition, partitions);
+
+ // Only the first partition by name defines the parser/printer of the
+ // dialect.
+ if (!partitions.empty() && partitions.front() != selectedPartition)
+ return false;
Dialect firstDialect = defs.front().getDialect();
+ std::string parserName = getDispatchName(firstDialect, "Parser");
+ std::string printerName = getDispatchName(firstDialect, "Printer");
// Emit the default parser/printer for Attributes if the dialect asked for it.
if (isAttrGenerator && firstDialect.useDefaultAttributePrinterParser()) {
DialectNamespaceEmitter nsEmitter(os, firstDialect);
if (firstDialect.isExtensible()) {
- os << llvm::formatv(dialectDefaultAttrPrinterParserDispatch,
- firstDialect.getCppClassName(),
- dialectDynamicAttrParserDispatch,
- dialectDynamicAttrPrinterDispatch);
+ os << llvm::formatv(
+ dialectDefaultAttrPrinterParserDispatch,
+ firstDialect.getCppClassName(), dialectDynamicAttrParserDispatch,
+ dialectDynamicAttrPrinterDispatch, parserName, printerName);
} else {
os << llvm::formatv(dialectDefaultAttrPrinterParserDispatch,
- firstDialect.getCppClassName(), "", "");
+ firstDialect.getCppClassName(), "", "", parserName,
+ printerName);
}
}
@@ -1286,13 +1515,14 @@ bool DefGenerator::emitDefs(StringRef selectedDialect) {
if (!isAttrGenerator && firstDialect.useDefaultTypePrinterParser()) {
DialectNamespaceEmitter nsEmitter(os, firstDialect);
if (firstDialect.isExtensible()) {
- os << llvm::formatv(dialectDefaultTypePrinterParserDispatch,
- firstDialect.getCppClassName(),
- dialectDynamicTypeParserDispatch,
- dialectDynamicTypePrinterDispatch);
+ os << llvm::formatv(
+ dialectDefaultTypePrinterParserDispatch,
+ firstDialect.getCppClassName(), dialectDynamicTypeParserDispatch,
+ dialectDynamicTypePrinterDispatch, parserName, printerName);
} else {
os << llvm::formatv(dialectDefaultTypePrinterParserDispatch,
- firstDialect.getCppClassName(), "", "");
+ firstDialect.getCppClassName(), "", "", parserName,
+ printerName);
}
}
@@ -1403,18 +1633,23 @@ static llvm::cl::opt<std::string>
attrDialect("attrdefs-dialect",
llvm::cl::desc("Generate attributes for this dialect"),
llvm::cl::cat(attrdefGenCat), llvm::cl::CommaSeparated);
+static llvm::cl::opt<std::string> attrPartition(
+ "attrdefs-partition",
+ llvm::cl::desc("Only generate the attributes in this partition (see "
+ "`AttrOrTypeDef::partition`)"),
+ llvm::cl::cat(attrdefGenCat));
static mlir::GenRegistration
genAttrDefs("gen-attrdef-defs", "Generate AttrDef definitions",
[](const RecordKeeper &records, raw_ostream &os) {
AttrDefGenerator generator(records, os);
- return generator.emitDefs(attrDialect);
+ return generator.emitDefs(attrDialect, attrPartition);
});
static mlir::GenRegistration
genAttrDecls("gen-attrdef-decls", "Generate AttrDef declarations",
[](const RecordKeeper &records, raw_ostream &os) {
AttrDefGenerator generator(records, os);
- return generator.emitDecls(attrDialect);
+ return generator.emitDecls(attrDialect, attrPartition);
});
static mlir::GenRegistration
@@ -1441,18 +1676,23 @@ static llvm::cl::opt<std::string>
typeDialect("typedefs-dialect",
llvm::cl::desc("Generate types for this dialect"),
llvm::cl::cat(typedefGenCat), llvm::cl::CommaSeparated);
+static llvm::cl::opt<std::string> typePartition(
+ "typedefs-partition",
+ llvm::cl::desc("Only generate the types in this partition (see "
+ "`AttrOrTypeDef::partition`)"),
+ llvm::cl::cat(typedefGenCat));
static mlir::GenRegistration
genTypeDefs("gen-typedef-defs", "Generate TypeDef definitions",
[](const RecordKeeper &records, raw_ostream &os) {
TypeDefGenerator generator(records, os);
- return generator.emitDefs(typeDialect);
+ return generator.emitDefs(typeDialect, typePartition);
});
static mlir::GenRegistration
genTypeDecls("gen-typedef-decls", "Generate TypeDef declarations",
[](const RecordKeeper &records, raw_ostream &os) {
TypeDefGenerator generator(records, os);
- return generator.emitDecls(typeDialect);
+ return generator.emitDecls(typeDialect, typePartition);
});
static mlir::GenRegistration
diff --git a/mlir/tools/mlir-tblgen/CMakeLists.txt b/mlir/tools/mlir-tblgen/CMakeLists.txt
index 936c84ef58b2b1..e25cdbaf45852e 100644
--- a/mlir/tools/mlir-tblgen/CMakeLists.txt
+++ b/mlir/tools/mlir-tblgen/CMakeLists.txt
@@ -28,6 +28,7 @@ add_tablegen(mlir-tblgen MLIR
OpGenHelpers.cpp
OpInterfacesGen.cpp
OpPythonBindingGen.cpp
+ PartitionHelpers.cpp
PassCAPIGen.cpp
PassDocGen.cpp
PassGen.cpp
diff --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
index 4255ab15d58909..96fd1ae6a2830d 100644
--- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
@@ -15,6 +15,7 @@
#include "OpClass.h"
#include "OpFormatGen.h"
#include "OpGenHelpers.h"
+#include "PartitionHelpers.h"
#include "mlir/TableGen/Argument.h"
#include "mlir/TableGen/Attribute.h"
#include "mlir/TableGen/Builder.h"
@@ -4783,15 +4784,12 @@ static SmallVector<Dialect> getOpDialects(ArrayRef<const Record *> defs) {
static SmallVector<StringRef>
getAllOpPartitions(const Dialect &dialect, ArrayRef<const Record *> defs,
ArrayRef<const Record *> otherPartitionDefs) {
- llvm::SetVector<StringRef> partitions;
+ SmallVector<const Record *> dialectDefs;
for (const Record *def :
concat<const Record *const>(defs, otherPartitionDefs))
if (def->getValueAsDef("opDialect") == dialect.getDef())
- partitions.insert(getOpPartitionName(*def));
-
- SmallVector<StringRef> result = partitions.takeVector();
- llvm::sort(result);
- return result;
+ dialectDefs.push_back(def);
+ return getPartitionNames(dialectDefs);
}
/// Emit the declarations of the op registration hooks of every dialect with
diff --git a/mlir/tools/mlir-tblgen/OpGenHelpers.cpp b/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
index 6ff151dbdba46e..0839be84045b50 100644
--- a/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
+++ b/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
#include "OpGenHelpers.h"
-#include "llvm/ADT/StringExtras.h"
+#include "PartitionHelpers.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatVariadic.h"
@@ -50,49 +50,10 @@ static std::string getOperationName(const Record &def) {
return std::string(formatv("{0}.{1}", prefix, opName));
}
-StringRef mlir::tblgen::getOpPartitionName(const Record &def) {
- const Record *partition = def.getValueAsOptionalDef("partition");
- return partition ? partition->getValueAsString("partitionName") : "";
-}
-
std::string mlir::tblgen::getOpRegistrationHookName(const Dialect &dialect,
StringRef partition) {
return "register" + dialect.getCppClassName() + "Operations" +
- convertToCamelFromSnakeCase(partition, /*capitalizeFirst=*/true);
-}
-
-/// Verifies the op partitions of `defs`, the ops requested by the filters other
-/// than "op-partition": every op must be in a partition, the specified
-/// partition must have ops and the registration hooks of different partitions
-/// must have different names.
-static void verifyOpPartitions(ArrayRef<const Record *> defs) {
- // Index sharding does not emit the registration hooks of partitions.
- if (opShardCount > 1)
- PrintFatalError("-op-partition cannot be combined with -op-shard-count");
-
- bool hasSpecifiedPartition = false;
- StringMap<StringRef> partitionsByHookName;
- for (const Record *def : defs) {
- StringRef partition = getOpPartitionName(*def);
- // An op without a partition would not be generated by any partition.
- if (partition.empty())
- PrintFatalError(def, "op '" + def->getName() +
- "' is in no partition, but its ops are "
- "generated by partition with -op-partition");
- hasSpecifiedPartition |= partition == opPartition;
-
- std::string hookName = getOpRegistrationHookName(
- Dialect(def->getValueAsDef("opDialect")), partition);
- auto [it, inserted] = partitionsByHookName.try_emplace(hookName, partition);
- if (!inserted && it->second != partition)
- PrintFatalError(
- def, "op partitions '" + it->second + "' and '" + partition +
- "' have the same registration hook '" + hookName + "'");
- }
-
- if (!hasSpecifiedPartition)
- PrintFatalError("no op is in the specified op partition '" + opPartition +
- "'");
+ getPartitionFunctionSuffix(partition);
}
std::vector<const Record *> mlir::tblgen::getRequestedOpDefinitions(
@@ -119,15 +80,13 @@ std::vector<const Record *> mlir::tblgen::getRequestedOpDefinitions(
if (opPartition.empty())
return defs;
+ // Index sharding does not emit the registration hooks of partitions.
+ if (opShardCount > 1)
+ PrintFatalError("-op-partition cannot be combined with -op-shard-count");
+
// Only include ops of the specified partition.
- verifyOpPartitions(defs);
- auto otherPartitionsBegin =
- std::stable_partition(defs.begin(), defs.end(), [](const Record *def) {
- return getOpPartitionName(*def) == opPartition;
- });
- if (otherPartitionDefs)
- otherPartitionDefs->assign(otherPartitionsBegin, defs.end());
- defs.erase(otherPartitionsBegin, defs.end());
+ verifyPartitions(defs, opPartition, "op", "-op-partition");
+ selectPartition(opPartition, defs, otherPartitionDefs);
return defs;
}
diff --git a/mlir/tools/mlir-tblgen/OpGenHelpers.h b/mlir/tools/mlir-tblgen/OpGenHelpers.h
index 87ea8edf010224..0542ffe01f191f 100644
--- a/mlir/tools/mlir-tblgen/OpGenHelpers.h
+++ b/mlir/tools/mlir-tblgen/OpGenHelpers.h
@@ -43,10 +43,6 @@ void shardOpDefinitions(
/// are not generated by partition.
StringRef getSpecifiedOpPartition();
-/// Returns the name of the partition of op `def`, or an empty string if the op
-/// is in no partition.
-StringRef getOpPartitionName(const llvm::Record &def);
-
/// Returns the name of the function that registers the ops of `dialect` in op
/// partition `partition`, or the ops of all its partitions if `partition` is
/// empty.
diff --git a/mlir/tools/mlir-tblgen/PartitionHelpers.cpp b/mlir/tools/mlir-tblgen/PartitionHelpers.cpp
new file mode 100644
index 00000000000000..cb9b520bb53532
--- /dev/null
+++ b/mlir/tools/mlir-tblgen/PartitionHelpers.cpp
@@ -0,0 +1,63 @@
+//===- PartitionHelpers.cpp - Helpers for generating by partition ---------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "PartitionHelpers.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVectorExtras.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/TableGen/Error.h"
+
+using namespace mlir;
+using namespace mlir::tblgen;
+using llvm::Record;
+
+StringRef mlir::tblgen::getPartitionName(const Record &def) {
+ const Record *partition = def.getValueAsOptionalDef("partition");
+ return partition ? partition->getValueAsString("partitionName") : "";
+}
+
+std::string mlir::tblgen::getPartitionFunctionSuffix(StringRef partition) {
+ return llvm::convertToCamelFromSnakeCase(partition, /*capitalizeFirst=*/true);
+}
+
+void mlir::tblgen::verifyPartitions(ArrayRef<const Record *> defs,
+ StringRef selectedPartition, StringRef kind,
+ StringRef option) {
+ bool hasSelectedPartition = false;
+ llvm::StringMap<StringRef> partitionsBySuffix;
+ for (const Record *def : defs) {
+ StringRef partition = getPartitionName(*def);
+ // A def without a partition would not be generated by any partition.
+ if (partition.empty())
+ llvm::PrintFatalError(
+ def, kind + " '" + def->getName() + "' is in no partition, but its " +
+ kind + "s are generated by partition with " + option);
+ hasSelectedPartition |= partition == selectedPartition;
+
+ std::string suffix = getPartitionFunctionSuffix(partition);
+ auto [it, inserted] = partitionsBySuffix.try_emplace(suffix, partition);
+ if (!inserted && it->second != partition)
+ llvm::PrintFatalError(def, kind + " partitions '" + it->second +
+ "' and '" + partition +
+ "' have the same name '" + suffix +
+ "' in generated functions");
+ }
+ if (!hasSelectedPartition)
+ llvm::PrintFatalError("no " + kind + " is in the specified " + kind +
+ " partition '" + selectedPartition + "'");
+}
+
+SmallVector<StringRef>
+mlir::tblgen::getPartitionNames(ArrayRef<const Record *> defs) {
+ SmallVector<StringRef> partitions = llvm::map_to_vector(
+ defs, [](const Record *def) { return getPartitionName(*def); });
+ llvm::sort(partitions);
+ partitions.erase(llvm::unique(partitions), partitions.end());
+ return partitions;
+}
diff --git a/mlir/tools/mlir-tblgen/PartitionHelpers.h b/mlir/tools/mlir-tblgen/PartitionHelpers.h
new file mode 100644
index 00000000000000..0c072e004a92bb
--- /dev/null
+++ b/mlir/tools/mlir-tblgen/PartitionHelpers.h
@@ -0,0 +1,65 @@
+//===- PartitionHelpers.h - Helpers for generating by partition -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines helpers for the generators that generate the definitions
+// of a dialect one partition (see `Partition` in DialectBase.td) at a time,
+// such as its ops, attributes or types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TOOLS_MLIRTBLGEN_PARTITIONHELPERS_H_
+#define MLIR_TOOLS_MLIRTBLGEN_PARTITIONHELPERS_H_
+
+#include "mlir/Support/LLVM.h"
+#include "llvm/ADT/STLForwardCompat.h"
+#include "llvm/TableGen/Record.h"
+#include <algorithm>
+#include <string>
+
+namespace mlir {
+namespace tblgen {
+/// Returns the name of the partition of `def`, or an empty string if it is in
+/// no partition. `def` must have a field `partition` of type `Partition` (see
+/// DialectBase.td), which may be unset.
+StringRef getPartitionName(const llvm::Record &def);
+
+/// Returns the suffix of the names of the generated functions of `partition`,
+/// such as its registration hook.
+std::string getPartitionFunctionSuffix(StringRef partition);
+
+/// Verifies the partitions of `defs`: every def must be in a partition,
+/// `selectedPartition` must have defs and different partitions must not map to
+/// the same suffix (see `getPartitionFunctionSuffix`). `kind` (e.g. "op") and
+/// `option` (e.g. "-op-partition") are used in diagnostics.
+void verifyPartitions(ArrayRef<const llvm::Record *> defs,
+ StringRef selectedPartition, StringRef kind,
+ StringRef option);
+
+/// Removes the defs of partitions other than `selectedPartition` from `defs`,
+/// assigning them to `otherPartitionDefs` if non-null. `getRecord(def)` returns
+/// the record of a def.
+template <typename ContainerT, typename GetRecordFn = llvm::identity>
+void selectPartition(
+ StringRef selectedPartition, ContainerT &defs,
+ llvm::type_identity_t<ContainerT> *otherPartitionDefs = nullptr,
+ GetRecordFn getRecord = {}) {
+ auto otherPartitionsBegin =
+ std::stable_partition(defs.begin(), defs.end(), [&](const auto &def) {
+ return getPartitionName(*getRecord(def)) == selectedPartition;
+ });
+ if (otherPartitionDefs)
+ otherPartitionDefs->assign(otherPartitionsBegin, defs.end());
+ defs.erase(otherPartitionsBegin, defs.end());
+}
+
+/// Returns the names of the partitions of `defs`, sorted by name.
+SmallVector<StringRef> getPartitionNames(ArrayRef<const llvm::Record *> defs);
+} // namespace tblgen
+} // namespace mlir
+
+#endif // MLIR_TOOLS_MLIRTBLGEN_PARTITIONHELPERS_H_
diff --git a/mlir/unittests/IR/InterfaceAttachmentTest.cpp b/mlir/unittests/IR/InterfaceAttachmentTest.cpp
index a107c40774a578..5da50393efe623 100644
--- a/mlir/unittests/IR/InterfaceAttachmentTest.cpp
+++ b/mlir/unittests/IR/InterfaceAttachmentTest.cpp
@@ -17,9 +17,9 @@
#include "mlir/IR/BuiltinTypes.h"
#include "gtest/gtest.h"
-#include "TestAttributes.h"
+#include "TestAttributesCore.h"
#include "TestOpsPatterns.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
#include "mlir/IR/OwningOpRef.h"
using namespace mlir;
diff --git a/mlir/unittests/IR/InterfaceTest.cpp b/mlir/unittests/IR/InterfaceTest.cpp
index d7554e7bceaa86..7c279ef6807f2a 100644
--- a/mlir/unittests/IR/InterfaceTest.cpp
+++ b/mlir/unittests/IR/InterfaceTest.cpp
@@ -13,9 +13,8 @@
#include "mlir/IR/OwningOpRef.h"
#include "gtest/gtest.h"
-#include "TestAttributes.h"
#include "TestOpsInterfaces.h"
-#include "TestTypes.h"
+#include "TestTypesCore.h"
using namespace mlir;
using namespace test;
diff --git a/mlir/unittests/Parser/ResourceTest.cpp b/mlir/unittests/Parser/ResourceTest.cpp
index f29c144bcd66fc..9c74133e156c23 100644
--- a/mlir/unittests/Parser/ResourceTest.cpp
+++ b/mlir/unittests/Parser/ResourceTest.cpp
@@ -6,7 +6,6 @@
//
//===----------------------------------------------------------------------===//
-#include "TestAttributes.h"
#include "TestDialect.h"
#include "mlir/Parser/Parser.h"
>From 24657974c7ed68f4aa690242c9f6c4cd12252d7a Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Tue, 17 Nov 2026 14:17:34 +0000
Subject: [PATCH 2/5] Address review comments
Co-authored-by: Claude <noreply at anthropic.com>
---
.../DefiningDialects/AttributesAndTypes.md | 2 +-
mlir/include/mlir/IR/AttrTypeBase.td | 4 +--
mlir/test/lib/Dialect/Test/CMakeLists.txt | 8 ++---
.../mlir-tblgen/attr-type-partitions-error.td | 8 ++---
mlir/test/mlir-tblgen/attr-type-partitions.td | 10 +++---
mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp | 33 ++++++++++---------
6 files changed, 34 insertions(+), 31 deletions(-)
diff --git a/mlir/docs/DefiningDialects/AttributesAndTypes.md b/mlir/docs/DefiningDialects/AttributesAndTypes.md
index 621454b7a7ef73..96e49f3434fd79 100644
--- a/mlir/docs/DefiningDialects/AttributesAndTypes.md
+++ b/mlir/docs/DefiningDialects/AttributesAndTypes.md
@@ -1279,7 +1279,7 @@ let partition = MyDialect_LayoutAttrs in
def MyLayoutAttr : MyDialect_Attr<"MyLayout", "layout"> { ... }
```
-Passing `-attrdefs-partition=<partition>` (or `-typedefs-partition=<partition>`)
+Passing `-attrdef-partition=<partition>` (or `-typedef-partition=<partition>`)
with a partition name to `-gen-attrdef-decls` and `-gen-attrdef-defs` (or
`-gen-typedef-decls` and `-gen-typedef-defs`) generates only the attributes (or
types) of that partition. Every generated attribute or type must then be in a
diff --git a/mlir/include/mlir/IR/AttrTypeBase.td b/mlir/include/mlir/IR/AttrTypeBase.td
index b70774f447608b..c9539c523e01e8 100644
--- a/mlir/include/mlir/IR/AttrTypeBase.td
+++ b/mlir/include/mlir/IR/AttrTypeBase.td
@@ -257,8 +257,8 @@ class AttrOrTypeDef<string valueType, string name, list<Trait> defTraits,
// Optional. The partition of this def. `-gen-{attr,type}def-{decls,defs}`
// generate the defs of one partition at a time with
- // `-{attr,type}defs-partition=...`, which requires every generated def to be
- // in a partition. Ignored without `-{attr,type}defs-partition`.
+ // `-{attr,type}def-partition=...`, which requires every generated def to be
+ // in a partition. Ignored without `-{attr,type}def-partition`.
Partition partition = ?;
}
diff --git a/mlir/test/lib/Dialect/Test/CMakeLists.txt b/mlir/test/lib/Dialect/Test/CMakeLists.txt
index 85ffc745383d70..37252bf9d8b1e6 100644
--- a/mlir/test/lib/Dialect/Test/CMakeLists.txt
+++ b/mlir/test/lib/Dialect/Test/CMakeLists.txt
@@ -19,18 +19,18 @@ add_public_tablegen_target(MLIRTestInterfaceIncGen)
set(LLVM_TARGET_DEFINITIONS TestOps.td)
foreach(partition Core Syntax)
mlir_tablegen(TestAttributes${partition}.h.inc -gen-attrdef-decls
- -attrdefs-dialect=test -attrdefs-partition=${partition})
+ -attrdefs-dialect=test -attrdef-partition=${partition})
mlir_tablegen(TestAttributes${partition}.cpp.inc -gen-attrdef-defs
- -attrdefs-dialect=test -attrdefs-partition=${partition})
+ -attrdefs-dialect=test -attrdef-partition=${partition})
endforeach()
add_public_tablegen_target(MLIRTestAttrDefIncGen)
set(LLVM_TARGET_DEFINITIONS TestTypeDefs.td)
foreach(partition Core Syntax)
mlir_tablegen(TestTypes${partition}.h.inc -gen-typedef-decls
- -typedefs-dialect=test -typedefs-partition=${partition})
+ -typedefs-dialect=test -typedef-partition=${partition})
mlir_tablegen(TestTypes${partition}.cpp.inc -gen-typedef-defs
- -typedefs-dialect=test -typedefs-partition=${partition})
+ -typedefs-dialect=test -typedef-partition=${partition})
endforeach()
add_public_tablegen_target(MLIRTestTypeDefIncGen)
diff --git a/mlir/test/mlir-tblgen/attr-type-partitions-error.td b/mlir/test/mlir-tblgen/attr-type-partitions-error.td
index d5c61530f85f46..bb1842869df2a1 100644
--- a/mlir/test/mlir-tblgen/attr-type-partitions-error.td
+++ b/mlir/test/mlir-tblgen/attr-type-partitions-error.td
@@ -1,6 +1,6 @@
-// RUN: not mlir-tblgen -gen-attrdef-decls -attrdefs-partition=Memory -I %S/../../include -DERROR1 %s 2>&1 | FileCheck --check-prefix=ERROR1 %s
-// RUN: not mlir-tblgen -gen-typedef-defs -typedefs-partition=Memroy -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
-// RUN: not mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Memory -I %S/../../include -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
+// RUN: not mlir-tblgen -gen-attrdef-decls -attrdef-partition=Memory -I %S/../../include -DERROR1 %s 2>&1 | FileCheck --check-prefix=ERROR1 %s
+// RUN: not mlir-tblgen -gen-typedef-defs -typedef-partition=Memroy -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
+// RUN: not mlir-tblgen -gen-attrdef-defs -attrdef-partition=Memory -I %S/../../include -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
include "mlir/IR/AttrTypeBase.td"
@@ -21,7 +21,7 @@ def PointerType : TypeDef<Test_Dialect, "Pointer"> {
}
#ifdef ERROR1
-// ERROR1: error: attribute 'NoPartitionAttr' is in no partition, but its attributes are generated by partition with -attrdefs-partition
+// ERROR1: error: attribute 'NoPartitionAttr' is in no partition, but its attributes are generated by partition with -attrdef-partition
def NoPartitionAttr : AttrDef<Test_Dialect, "NoPartition"> {
let mnemonic = "no_partition";
}
diff --git a/mlir/test/mlir-tblgen/attr-type-partitions.td b/mlir/test/mlir-tblgen/attr-type-partitions.td
index cb6f5a8375ad30..59088b34eb0bc2 100644
--- a/mlir/test/mlir-tblgen/attr-type-partitions.td
+++ b/mlir/test/mlir-tblgen/attr-type-partitions.td
@@ -1,7 +1,7 @@
-// RUN: mlir-tblgen -gen-attrdef-decls -attrdefs-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DECLS
-// RUN: mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DEFS
-// RUN: mlir-tblgen -gen-attrdef-defs -attrdefs-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=FIRST
-// RUN: mlir-tblgen -gen-typedef-defs -typedefs-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=TYPES
+// RUN: mlir-tblgen -gen-attrdef-decls -attrdef-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DECLS
+// RUN: mlir-tblgen -gen-attrdef-defs -attrdef-partition=Memory -I %S/../../include %s | FileCheck %s --check-prefix=DEFS
+// RUN: mlir-tblgen -gen-attrdef-defs -attrdef-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=FIRST
+// RUN: mlir-tblgen -gen-typedef-defs -typedef-partition=Arith -I %S/../../include %s | FileCheck %s --check-prefix=TYPES
// RUN: mlir-tblgen -gen-attrdef-defs -I %S/../../include %s | FileCheck %s --check-prefix=ALL
include "mlir/IR/AttrTypeBase.td"
@@ -132,7 +132,7 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// TYPES: void registerTestDialectTypesArith(TestDialect *dialect) {
// TYPES-NEXT: ::mlir::AbstractType::insert<IndexType>(*dialect);
-// Without -attrdefs-partition, partitions are ignored. The dispatch functions
+// Without -attrdef-partition, partitions are ignored. The dispatch functions
// and the hook that registers all defs are local to the definitions, since a
// dialect may generate its attributes from several files. The dispatch
// functions are also available under their former names.
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index e3a3a7abe1352e..1c2205049d6bba 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -1000,18 +1000,20 @@ bool DefGenerator::emitDecls(StringRef selectedDialect,
if (!partitions.empty()) {
raw_indented_ostream indentedOs(declOs);
Dialect dialect = defs.front().getDialect();
- const char *const hookDecl = "void {0}({1} *dialect);\n";
+ static constexpr StringLiteral hookDecl = "void {0}({1} *dialect);\n";
auto declareFunctions = [&](StringRef partition) {
auto [parser, printer] = createParsePrintDispatch(
getDispatchName(dialect, "Parser", partition),
getDispatchName(dialect, "Printer", partition), Method::None);
parser.writeDeclTo(indentedOs);
printer.writeDeclTo(indentedOs);
- declOs << llvm::formatv(hookDecl,
+ declOs << llvm::formatv(hookDecl.data(),
getRegistrationHookName(dialect, partition),
dialect.getCppClassName());
};
declOs << "class " << dialect.getCppClassName() << ";\n";
+ // An empty partition name declares the functions of the dialect, which
+ // dispatch to (or register the defs of) every partition.
declareFunctions("");
llvm::NamespaceEmitter detailNs(declOs, "detail");
for (StringRef partition : partitions)
@@ -1222,7 +1224,7 @@ SmallVector<StringRef> DefGenerator::selectPartition(
defs, [](const AttrOrTypeDef &def) { return def.getDef(); });
verifyPartitions(
records, selectedPartition, isAttrGenerator ? "attribute" : "type",
- isAttrGenerator ? "-attrdefs-partition" : "-typedefs-partition");
+ isAttrGenerator ? "-attrdef-partition" : "-typedef-partition");
SmallVector<StringRef> partitions = getPartitionNames(records);
tblgen::selectPartition(
@@ -1351,15 +1353,16 @@ void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs,
Method::None);
for (StringRef partition : partitions) {
parseAll.body() << llvm::formatv(
- " if (::mlir::OptionalParseResult result = {0}::detail::{1}(parser, "
- "mnemonic, {2}value); result.has_value())\n"
- " return result;\n",
+ R"( if (::mlir::OptionalParseResult result = {0}::detail::{1}(parser, mnemonic, {2}value); result.has_value())
+ return result;
+)",
dialect.getCppNamespace(),
getDispatchName(dialect, "Parser", partition),
isAttrGenerator ? "type, " : "");
printAll.body() << llvm::formatv(
- " if (::mlir::succeeded({0}::detail::{1}(def, printer)))\n"
- " return ::mlir::success();\n",
+ R"( if (::mlir::succeeded({0}::detail::{1}(def, printer)))
+ return ::mlir::success();
+)",
dialect.getCppNamespace(),
getDispatchName(dialect, "Printer", partition));
}
@@ -1408,7 +1411,7 @@ void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
Dialect dialect = defs.front().getDialect();
std::string dialectClass = dialect.getCppClassName();
DialectNamespaceEmitter ns(os, dialect);
- const char *const hookDef = "{0}void {1}({2} *dialect) {{\n";
+ static constexpr StringLiteral hookDef = "{0}void {1}({2} *dialect) {{\n";
auto emitInserts = [&] {
for (const AttrOrTypeDef &def : defs)
os << llvm::formatv(" ::mlir::Abstract{0}::insert<{1}>(*dialect);\n",
@@ -1422,15 +1425,15 @@ void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
// TUs (e.g. the transform dialect and its extensions), whose hooks would
// cause multiple definition errors.
os << "class " << dialectClass << ";\n"
- << llvm::formatv(hookDef, "[[maybe_unused]] static ",
+ << llvm::formatv(hookDef.data(), "[[maybe_unused]] static ",
getRegistrationHookName(dialect, ""), dialectClass);
emitInserts();
return;
}
if (partitions.front() == selectedPartition) {
- os << llvm::formatv(hookDef, "", getRegistrationHookName(dialect, ""),
- dialectClass);
+ os << llvm::formatv(hookDef.data(), "",
+ getRegistrationHookName(dialect, ""), dialectClass);
for (StringRef partition : partitions)
os << " " << dialect.getCppNamespace()
<< "::detail::" << getRegistrationHookName(dialect, partition)
@@ -1438,7 +1441,7 @@ void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
os << "}\n";
}
llvm::NamespaceEmitter detailNs(os, "detail");
- os << llvm::formatv(hookDef, "",
+ os << llvm::formatv(hookDef.data(), "",
getRegistrationHookName(dialect, selectedPartition),
dialectClass);
emitInserts();
@@ -1634,7 +1637,7 @@ static llvm::cl::opt<std::string>
llvm::cl::desc("Generate attributes for this dialect"),
llvm::cl::cat(attrdefGenCat), llvm::cl::CommaSeparated);
static llvm::cl::opt<std::string> attrPartition(
- "attrdefs-partition",
+ "attrdef-partition",
llvm::cl::desc("Only generate the attributes in this partition (see "
"`AttrOrTypeDef::partition`)"),
llvm::cl::cat(attrdefGenCat));
@@ -1677,7 +1680,7 @@ static llvm::cl::opt<std::string>
llvm::cl::desc("Generate types for this dialect"),
llvm::cl::cat(typedefGenCat), llvm::cl::CommaSeparated);
static llvm::cl::opt<std::string> typePartition(
- "typedefs-partition",
+ "typedef-partition",
llvm::cl::desc("Only generate the types in this partition (see "
"`AttrOrTypeDef::partition`)"),
llvm::cl::cat(typedefGenCat));
>From 4905bedddc80a7171ce719e7dc2a95d1ea27933c Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Tue, 17 Nov 2026 14:28:38 +0000
Subject: [PATCH 3/5] remove useless docs
---
mlir/docs/DefiningDialects/AttributesAndTypes.md | 12 ------------
1 file changed, 12 deletions(-)
diff --git a/mlir/docs/DefiningDialects/AttributesAndTypes.md b/mlir/docs/DefiningDialects/AttributesAndTypes.md
index 96e49f3434fd79..91a654fc1a214e 100644
--- a/mlir/docs/DefiningDialects/AttributesAndTypes.md
+++ b/mlir/docs/DefiningDialects/AttributesAndTypes.md
@@ -1285,15 +1285,3 @@ with a partition name to `-gen-attrdef-decls` and `-gen-attrdef-defs` (or
types) of that partition. Every generated attribute or type must then be in a
partition, and the specified partition must have attributes or types. Without
the option, `partition` is ignored.
-
-The dialect calls the same functions with and without partitions:
-`register<DialectClass>Attributes` (or `register<DialectClass>Types`) to
-register the attributes (or types), and, if it implements its own parser and
-printer, `generated<DialectClass>AttributeParser` and
-`generated<DialectClass>AttributePrinter` (or `...Type...`).
-
-Without partitions, these are `static` functions of the definitions, which can
-only be called in the compilation unit that includes the definitions. With
-partitions, they are declared by the declarations of every partition, so they
-can be called in any compilation unit that includes the declarations of a
-partition.
>From 2eb41e54dc2c3392497d2c3a225c90806f5ac2dd Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Tue, 17 Nov 2026 14:44:36 +0000
Subject: [PATCH 4/5] Emit partition functions in the dialect namespace like
ops
Co-authored-by: Claude <noreply at anthropic.com>
---
mlir/test/mlir-tblgen/attr-type-partitions.td | 29 ++++++++-----------
mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp | 23 ++++++---------
2 files changed, 21 insertions(+), 31 deletions(-)
diff --git a/mlir/test/mlir-tblgen/attr-type-partitions.td b/mlir/test/mlir-tblgen/attr-type-partitions.td
index 59088b34eb0bc2..7dc70d91d2cf37 100644
--- a/mlir/test/mlir-tblgen/attr-type-partitions.td
+++ b/mlir/test/mlir-tblgen/attr-type-partitions.td
@@ -41,8 +41,8 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// Only the defs of the specified partition are declared. The defs of the other
// partitions are forward declared, so that declarations can refer to them. The
// parse and print dispatch functions and the registration hook of the dialect
-// are declared, as well as those of all partitions in the `detail` namespace,
-// which they dispatch to and register the defs of all partitions with.
+// are declared, as well as those of all partitions, which they dispatch to and
+// register the defs of all partitions with.
// DECLS: namespace mlir {
// DECLS-NEXT: class AsmParser;
// DECLS-NEXT: class AsmPrinter;
@@ -58,8 +58,6 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// DECLS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value);
// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
// DECLS-NEXT: void registerTestDialectAttributes(TestDialect *dialect);
-// DECLS-NEXT: namespace detail {
-// DECLS-EMPTY:
// DECLS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParserArith(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value);
// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinterArith(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
// DECLS-NEXT: void registerTestDialectAttributesArith(TestDialect *dialect);
@@ -67,7 +65,7 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// DECLS-NEXT: ::llvm::LogicalResult generatedTestDialectAttributePrinterMemory(::mlir::Attribute def, ::mlir::AsmPrinter &printer);
// DECLS-NEXT: void registerTestDialectAttributesMemory(TestDialect *dialect);
// DECLS-EMPTY:
-// DECLS-NEXT: } // namespace detail
+// DECLS-NEXT: } // namespace test
// DECLS-NOT: IntAttr
// The dispatch functions of a partition continue with the mnemonic that the
@@ -79,19 +77,18 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// DEFS-NEXT: test::AlignmentAttr
// DEFS-EMPTY:
// DEFS-NEXT: #endif
-// DEFS: namespace detail {
+// DEFS: namespace test {
// DEFS-EMPTY:
// DEFS-NEXT: ::mlir::OptionalParseResult generatedTestDialectAttributeParserMemory(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) {
// DEFS-NEXT: return ::mlir::AsmParser::KeywordSwitch<::mlir::OptionalParseResult>(parser, mnemonic)
// DEFS: ::llvm::LogicalResult generatedTestDialectAttributePrinterMemory(::mlir::Attribute def, ::mlir::AsmPrinter &printer) {
-// DEFS: } // namespace detail
// DEFS-NOT: registerTestDialectAttributes(
// DEFS: void registerTestDialectAttributesMemory(TestDialect *dialect) {
// DEFS-NEXT: ::mlir::AbstractAttribute::insert<AddressAttr>(*dialect);
// DEFS-NEXT: ::mlir::AbstractAttribute::insert<AlignmentAttr>(*dialect);
// DEFS-NEXT: }
// DEFS-EMPTY:
-// DEFS-NEXT: } // namespace detail
+// DEFS-NEXT: } // namespace test
// DEFS-NOT: generatedTestDialectAttributeParser(
// DEFS-NOT: IntAttr::
// DEFS-NOT: TestDialect::parseAttribute
@@ -100,25 +97,23 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// registration hook of the dialect, which call those of all partitions. The
// default parser and printer of the dialect call its dispatch functions.
// FIRST: ::mlir::OptionalParseResult generatedTestDialectAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) {
-// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectAttributeParserArith(parser, mnemonic, type, value); result.has_value())
+// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::generatedTestDialectAttributeParserArith(parser, mnemonic, type, value); result.has_value())
// FIRST-NEXT: return result;
-// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectAttributeParserMemory(parser, mnemonic, type, value); result.has_value())
+// FIRST-NEXT: if (::mlir::OptionalParseResult result = test::generatedTestDialectAttributeParserMemory(parser, mnemonic, type, value); result.has_value())
// FIRST-NEXT: return result;
// FIRST-NEXT: return std::nullopt;
// FIRST-NEXT: }
// FIRST: ::llvm::LogicalResult generatedTestDialectAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer) {
-// FIRST-NEXT: if (::mlir::succeeded(test::detail::generatedTestDialectAttributePrinterArith(def, printer)))
+// FIRST-NEXT: if (::mlir::succeeded(test::generatedTestDialectAttributePrinterArith(def, printer)))
// FIRST-NEXT: return ::mlir::success();
-// FIRST-NEXT: if (::mlir::succeeded(test::detail::generatedTestDialectAttributePrinterMemory(def, printer)))
+// FIRST-NEXT: if (::mlir::succeeded(test::generatedTestDialectAttributePrinterMemory(def, printer)))
// FIRST-NEXT: return ::mlir::success();
// FIRST-NEXT: return ::mlir::failure();
// FIRST-NEXT: }
// FIRST: void registerTestDialectAttributes(TestDialect *dialect) {
-// FIRST-NEXT: test::detail::registerTestDialectAttributesArith(dialect);
-// FIRST-NEXT: test::detail::registerTestDialectAttributesMemory(dialect);
+// FIRST-NEXT: test::registerTestDialectAttributesArith(dialect);
+// FIRST-NEXT: test::registerTestDialectAttributesMemory(dialect);
// FIRST-NEXT: }
-// FIRST-NEXT: namespace detail {
-// FIRST-EMPTY:
// FIRST-NEXT: void registerTestDialectAttributesArith(TestDialect *dialect) {
// FIRST-NEXT: ::mlir::AbstractAttribute::insert<IntAttr>(*dialect);
// FIRST-NEXT: }
@@ -128,7 +123,7 @@ def IndexType : TypeDef<Test_Dialect, "Index"> {
// TYPES: ::mlir::OptionalParseResult generatedTestDialectTypeParserArith(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
// TYPES: ::mlir::OptionalParseResult generatedTestDialectTypeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type &value) {
-// TYPES-NEXT: if (::mlir::OptionalParseResult result = test::detail::generatedTestDialectTypeParserArith(parser, mnemonic, value); result.has_value())
+// TYPES-NEXT: if (::mlir::OptionalParseResult result = test::generatedTestDialectTypeParserArith(parser, mnemonic, value); result.has_value())
// TYPES: void registerTestDialectTypesArith(TestDialect *dialect) {
// TYPES-NEXT: ::mlir::AbstractType::insert<IndexType>(*dialect);
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index 1c2205049d6bba..a1ba95b3cfe22c 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -996,7 +996,7 @@ bool DefGenerator::emitDecls(StringRef selectedDialect,
// When generating by partition, declare the parse and print dispatch
// functions and the registration hook of the dialect, as well as those of
- // all partitions, which they call, in the `detail` namespace.
+ // all partitions, which they call.
if (!partitions.empty()) {
raw_indented_ostream indentedOs(declOs);
Dialect dialect = defs.front().getDialect();
@@ -1015,7 +1015,6 @@ bool DefGenerator::emitDecls(StringRef selectedDialect,
// An empty partition name declares the functions of the dialect, which
// dispatch to (or register the defs of) every partition.
declareFunctions("");
- llvm::NamespaceEmitter detailNs(declOs, "detail");
for (StringRef partition : partitions)
declareFunctions(partition);
}
@@ -1337,11 +1336,8 @@ void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs,
}
DialectNamespaceEmitter ns(os, dialect);
- {
- llvm::NamespaceEmitter detailNs(os, "detail");
- parse.writeDefTo(indentedOs, "");
- printer.writeDefTo(indentedOs, "");
- }
+ parse.writeDefTo(indentedOs, "");
+ printer.writeDefTo(indentedOs, "");
// The first partition by name also emits the dispatch functions of the
// dialect, which try the dispatch functions of every partition in turn.
@@ -1353,14 +1349,14 @@ void DefGenerator::emitParsePrintDispatch(ArrayRef<AttrOrTypeDef> defs,
Method::None);
for (StringRef partition : partitions) {
parseAll.body() << llvm::formatv(
- R"( if (::mlir::OptionalParseResult result = {0}::detail::{1}(parser, mnemonic, {2}value); result.has_value())
+ R"( if (::mlir::OptionalParseResult result = {0}::{1}(parser, mnemonic, {2}value); result.has_value())
return result;
)",
dialect.getCppNamespace(),
getDispatchName(dialect, "Parser", partition),
isAttrGenerator ? "type, " : "");
printAll.body() << llvm::formatv(
- R"( if (::mlir::succeeded({0}::detail::{1}(def, printer)))
+ R"( if (::mlir::succeeded({0}::{1}(def, printer)))
return ::mlir::success();
)",
dialect.getCppNamespace(),
@@ -1401,9 +1397,9 @@ void DefGenerator::emitLegacyParsePrintDispatch(const Dialect &dialect) {
}
/// Emit the hooks that register the defs with their dialect. When generating
-/// by partition, the hook of the partition is emitted in the `detail`
-/// namespace, and the first partition by name also emits the hook that calls
-/// the hooks of all partitions, all of which are declared by every partition.
+/// by partition, the hook of the partition is emitted, and the first partition
+/// by name also emits the hook that calls the hooks of all partitions, all of
+/// which are declared by every partition.
/// Otherwise, the hook registering all defs is a static function.
void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
StringRef selectedPartition,
@@ -1436,11 +1432,10 @@ void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
getRegistrationHookName(dialect, ""), dialectClass);
for (StringRef partition : partitions)
os << " " << dialect.getCppNamespace()
- << "::detail::" << getRegistrationHookName(dialect, partition)
+ << "::" << getRegistrationHookName(dialect, partition)
<< "(dialect);\n";
os << "}\n";
}
- llvm::NamespaceEmitter detailNs(os, "detail");
os << llvm::formatv(hookDef.data(), "",
getRegistrationHookName(dialect, selectedPartition),
dialectClass);
>From 2b736fc110428a43fadb9819f20051f850a1b135 Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Tue, 17 Nov 2026 15:11:24 +0000
Subject: [PATCH 5/5] add `StringLiteral` overload to `formatv`
---
llvm/include/llvm/Support/FormatVariadic.h | 4 ++++
mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp | 10 +++++-----
2 files changed, 9 insertions(+), 5 deletions(-)
diff --git a/llvm/include/llvm/Support/FormatVariadic.h b/llvm/include/llvm/Support/FormatVariadic.h
index 4c92d45c2f5b95..dd101e36dc36f0 100644
--- a/llvm/include/llvm/Support/FormatVariadic.h
+++ b/llvm/include/llvm/Support/FormatVariadic.h
@@ -255,6 +255,10 @@ template <typename... Ts> inline auto formatv(const char *Fmt, Ts &&...Vals) {
return formatv<Ts...>(true, Fmt, std::forward<Ts>(Vals)...);
}
+template <typename... Ts> inline auto formatv(StringLiteral Fmt, Ts &&...Vals) {
+ return formatv<Ts...>(Fmt.data(), std::forward<Ts>(Vals)...);
+}
+
} // end namespace llvm
#endif // LLVM_SUPPORT_FORMATVARIADIC_H
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index a1ba95b3cfe22c..886ba88845e230 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -1007,7 +1007,7 @@ bool DefGenerator::emitDecls(StringRef selectedDialect,
getDispatchName(dialect, "Printer", partition), Method::None);
parser.writeDeclTo(indentedOs);
printer.writeDeclTo(indentedOs);
- declOs << llvm::formatv(hookDecl.data(),
+ declOs << llvm::formatv(hookDecl,
getRegistrationHookName(dialect, partition),
dialect.getCppClassName());
};
@@ -1421,22 +1421,22 @@ void DefGenerator::emitRegistrationHooks(ArrayRef<AttrOrTypeDef> defs,
// TUs (e.g. the transform dialect and its extensions), whose hooks would
// cause multiple definition errors.
os << "class " << dialectClass << ";\n"
- << llvm::formatv(hookDef.data(), "[[maybe_unused]] static ",
+ << llvm::formatv(hookDef, "[[maybe_unused]] static ",
getRegistrationHookName(dialect, ""), dialectClass);
emitInserts();
return;
}
if (partitions.front() == selectedPartition) {
- os << llvm::formatv(hookDef.data(), "",
- getRegistrationHookName(dialect, ""), dialectClass);
+ os << llvm::formatv(hookDef, "", getRegistrationHookName(dialect, ""),
+ dialectClass);
for (StringRef partition : partitions)
os << " " << dialect.getCppNamespace()
<< "::" << getRegistrationHookName(dialect, partition)
<< "(dialect);\n";
os << "}\n";
}
- os << llvm::formatv(hookDef.data(), "",
+ os << llvm::formatv(hookDef, "",
getRegistrationHookName(dialect, selectedPartition),
dialectClass);
emitInserts();
More information about the llvm-branch-commits
mailing list