1# Defining Dialects
2
3This document describes how to define [Dialects](LangRef.md/#dialects).
4
5[TOC]
6
7## LangRef Refresher
8
9Before diving into how to define these constructs, below is a quick refresher
10from the [MLIR LangRef](LangRef.md).
11
12Dialects are the mechanism by which to engage with and extend the MLIR
13ecosystem. They allow for defining new [attributes](LangRef.md#attributes),
14[operations](LangRef.md#operations), and [types](LangRef.md#type-system).
15Dialects are used to model a variety of different abstractions; from traditional
16[arithmetic](Dialects/ArithmeticOps.md) to
17[pattern rewrites](Dialects/PDLOps.md); and is one of the most fundamental
18aspects of MLIR.
19
20## Defining a Dialect
21
22At the most fundamental level, defining a dialect in MLIR is as simple as
23specializing the
24[C++ `Dialect` class](https://github.com/llvm/llvm-project/blob/main/mlir/include/mlir/IR/Dialect.h).
25That being said, MLIR provides a powerful declaratively specification mechanism via
26[TableGen](https://llvm.org/docs/TableGen/index.html); a generic language with
27tooling to maintain records of domain-specific information; that simplifies the
28definition process by automatically generating all of the necessary boilerplate
29C++ code, significantly reduces maintainence burden when changing aspects of dialect
30definitions, and also provides additional tools on top (such as
31documentation generation). Given the above, the declarative specification is the
32expected mechanism for defining new dialects, and is the method detailed within
33this document. Before continuing, it is highly recommended that users review the
34[TableGen Programmer's Reference](https://llvm.org/docs/TableGen/ProgRef.html)
35for an introduction to its syntax and constructs.
36
37Below showcases an example simple Dialect definition. We generally recommend defining
38the Dialect class in a different `.td` file from the attributes, operations, types,
39and other sub-components of the dialect to establish a proper layering between
40the various different dialect components. It also prevents situations where you may
41inadvertantly generate multiple definitions for some constructs. This recommendation
42extends to all of the MLIR constructs, including [Interfaces](Interfaces.md) for example.
43
44```tablegen
45// Include the definition of the necessary tablegen constructs for defining
46// our dialect.
47include "mlir/IR/DialectBase.td"
48
49// Here is a simple definition of a dialect.
50def MyDialect : Dialect {
51  let summary = "A short one line description of my dialect.";
52  let description = [{
53    My dialect is a very important dialect. This section contains a much more
54    detailed description that documents all of the important pieces of information
55    to know about the document.
56  }];
57
58  /// This is the namespace of the dialect. It is used to encapsulate the sub-components
59  /// of the dialect, such as operations ("my_dialect.foo").
60  let name = "my_dialect";
61
62  /// The C++ namespace that the dialect, and its sub-components, get placed in.
63  let cppNamespace = "::my_dialect";
64}
65```
66
67The above showcases a very simple description of a dialect, but dialects have lots
68of other capabilities that you may or may not need to utilize.
69
70### Initialization
71
72Every dialect must implement an initialization hook to add attributes, operations, types,
73attach any desired interfaces, or perform any other necessary initialization for the
74dialect that should happen on construction. This hook is declared for every dialect to
75define, and has the form:
76
77```c++
78void MyDialect::initialize() {
79  // Dialect initialization logic should be defined in here.
80}
81```
82
83### Documentation
84
85The `summary` and `description` fields allow for providing user documentation
86for the dialect. The `summary` field expects a simple single-line string, with the
87`description` field used for long and extensive documentation. This documentation can be
88used to generate markdown documentation for the dialect and is used by upstream
89[MLIR dialects](https://mlir.llvm.org/docs/Dialects/).
90
91### Class Name
92
93The name of the C++ class which gets generated is the same as the name of our TableGen
94dialect definition, but with any `_` characters stripped out. This means that if you name
95your dialect `Foo_Dialect`, the generated C++ class would be `FooDialect`. In the example
96above, we would get a C++ dialect named `MyDialect`.
97
98### C++ Namespace
99
100The namespace that the C++ class for our dialect, and all of its sub-components, is placed
101under is specified by the `cppNamespace` field. By default, uses the name of the dialect as
102the only namespace. To avoid placing in any namespace, use `""`. To specify nested namespaces,
103use `"::"` as the delimiter between namespace, e.g., given `"A::B"`, C++ classes will be placed
104within: `namespace A { namespace B { <classes> } }`.
105
106Note that this works in conjunction with the dialect's C++ code. Depending on how the generated files
107are included, you may want to specify a full namespace path or a partial one. In general, it's best
108to use full namespaces whenever you can. This makes it easier for dialects within different namespaces,
109and projects, to interact with each other.
110
111### Dependent Dialects
112
113MLIR has a very large ecosystem, and contains dialects that server many different purposes. It
114is quite common, given the above, that dialects may want to reuse certain components from other
115dialects. This may mean generating operations from those dialects during canonicalization, reusing
116attributes or types, etc. When a dialect has a dependency on another, i.e. when it constructs and/or
117generally relies on the components of another dialect, a dialect dependency should be explicitly
118recorded. An explicitly dependency ensures that dependent dialects are loaded alongside the
119dialect. Dialect dependencies can be recorded using the `dependentDialects` dialects field:
120
121```tablegen
122def MyDialect : Dialect {
123  // Here we register the Arithmetic and Func dialect as dependencies of our `MyDialect`.
124  let dependentDialects = [
125    "arith::ArithmeticDialect",
126    "func::FuncDialect"
127  ];
128}
129```
130
131### Extra declarations
132
133The declarative Dialect definitions try to auto-generate as much logic and methods
134as possible. With that said, there will always be long-tail cases that won't be covered.
135For such cases, `extraClassDeclaration` can be used. Code within the `extraClassDeclaration`
136field will be copied literally to the generated C++ Dialect class.
137
138Note that `extraClassDeclaration` is a mechanism intended for long-tail cases by
139power users; for not-yet-implemented widely-applicable cases, improving the
140infrastructure is preferable.
141
142### `hasConstantMaterializer`: Materializing Constants from Attributes
143
144This field is utilized to materialize a constant operation from an `Attribute` value and
145a `Type`. This is generally used when an operation within this dialect has been folded,
146and a constant operation should be generated. `hasConstantMaterializer` is used to enable
147materialization, and the `materializeConstant` hook is declared on the dialect. This
148hook takes in an `Attribute` value, generally returned by `fold`, and produces a
149"constant-like" operation that materializes that value. See the
150[documentation for canonicalization](Canonicalization.md) for a more in-depth
151introduction to `folding` in MLIR.
152
153Constant materialization logic can then be defined in the source file:
154
155```c++
156/// Hook to materialize a single constant operation from a given attribute value
157/// with the desired resultant type. This method should use the provided builder
158/// to create the operation without changing the insertion position. The
159/// generated operation is expected to be constant-like. On success, this hook
160/// should return the operation generated to represent the constant value.
161/// Otherwise, it should return nullptr on failure.
162Operation *MyDialect::materializeConstant(OpBuilder &builder, Attribute value,
163                                          Type type, Location loc) {
164  ...
165}
166```
167
168### `hasNonDefaultDestructor`: Providing a custom destructor
169
170This field should be used when the Dialect class has a custom destructor, i.e.
171when the dialect has some special logic to be run in the `~MyDialect`. In this case,
172only the declaration of the destructor is generated for the Dialect class.
173
174### Discardable Attribute Verification
175
176As described by the [MLIR Language Reference](LangRef.md#attributes),
177*discardable attribute* are a type of attribute that has its semantics defined
178by the dialect whose name prefixes that of the attribute. For example, if an
179operation has an attribute named `gpu.contained_module`, the `gpu` dialect
180defines the semantics and invariants, such as when and where it is valid to use,
181of that attribute. To hook into this verification for attributes that are prefixed
182by our dialect, several hooks on the Dialect may be used:
183
184#### `hasOperationAttrVerify`
185
186This field generates the hook for verifying when a discardable attribute of this dialect
187has been used within the attribute dictionary of an operation. This hook has the form:
188
189```c++
190/// Verify the use of the given attribute, whose name is prefixed by the namespace of this
191/// dialect, that was used in `op`s dictionary.
192LogicalResult MyDialect::verifyOperationAttribute(Operation *op, NamedAttribute attribute);
193```
194
195#### `hasRegionArgAttrVerify`
196
197This field generates the hook for verifying when a discardable attribute of this dialect
198has been used within the attribute dictionary of a region entry block argument. Note that
199the block arguments of a region entry block do not themselves have attribute dictionaries,
200but some operations may provide special dictionary attributes that correspond to the arguments
201of a region. For example, operations that implement `FunctionOpInterface` may have attribute
202dictionaries on the operation that correspond to the arguments of entry block of the function.
203In these cases, those operations will invoke this hook on the dialect to ensure the attribute
204is verified. The hook necessary for the dialect to implement has the form:
205
206```c++
207/// Verify the use of the given attribute, whose name is prefixed by the namespace of this
208/// dialect, that was used on the attribute dictionary of a region entry block argument.
209/// Note: As described above, when a region entry block has a dictionary is up to the individual
210/// operation to define.
211LogicalResult MyDialect::verifyRegionArgAttribute(Operation *op, unsigned regionIndex,
212                                                  unsigned argIndex, NamedAttribute attribute);
213```
214
215#### `hasRegionResultAttrVerify`
216
217This field generates the hook for verifying when a discardable attribute of this dialect
218has been used within the attribute dictionary of a region result. Note that the results of a
219region do not themselves have attribute dictionaries, but some operations may provide special
220dictionary attributes that correspond to the results of a region. For example, operations that
221implement `FunctionOpInterface` may have attribute dictionaries on the operation that correspond
222to the results of the function. In these cases, those operations will invoke this hook on the
223dialect to ensure the attribute is verified. The hook necessary for the dialect to implement
224has the form:
225
226```c++
227/// Generate verification for the given attribute, whose name is prefixed by the namespace
228/// of this dialect, that was used on the attribute dictionary of a region result.
229/// Note: As described above, when a region entry block has a dictionary is up to the individual
230/// operation to define.
231LogicalResult MyDialect::verifyRegionResultAttribute(Operation *op, unsigned regionIndex,
232                                                     unsigned argIndex, NamedAttribute attribute);
233```
234
235### Operation Interface Fallback
236
237Some dialects have an open ecosystem and don't register all of the possible operations. In such
238cases it is still possible to provide support for implementing an `OpInterface` for these
239operations. When an operation isn't registered or does not provide an implementation for an
240interface, the query will fallback to the dialect itself. The `hasOperationInterfaceFallback`
241field may be used to declare this fallback for operations:
242
243```c++
244/// Return an interface model for the interface with the given `typeId` for the operation
245/// with the given name.
246void *MyDialect::getRegisteredInterfaceForOp(TypeID typeID, StringAttr opName);
247```
248
249For a more detail description of the expected usages of this hook, view the detailed
250[interface documentation](Interfaces.md#dialect-fallback-for-opinterface).
251
252### Default Attribute/Type Parsers and Printers
253
254When a dialect registers an Attribute or Type, it must also override the respective
255`Dialect::parseAttribute`/`Dialect::printAttribute` or
256`Dialect::parseType`/`Dialect::printType` methods. In these cases, the dialect must
257explicitly handle the parsing and printing of each individual attribute or type within
258the dialect. If all of the attributes and types of the dialect provide a mnemonic,
259however, these methods may be autogenerated by using the
260`useDefaultAttributePrinterParser` and `useDefaultTypePrinterParser` fields. By default,
261these fields are set to `1`(enabled), meaning that if a dialect needs to explicitly handle the
262parser and printer of its Attributes and Types it should set these to `0` as necessary.
263
264### Dialect-wide Canonicalization Patterns
265
266Generally, [canonicalization](Canonicalization.md) patterns are specific to individual
267operations within a dialect. There are some cases, however, that prompt canonicalization
268patterns to be added to the dialect-level. For example, if a dialect defines a canonicalization
269pattern that operates on an interface or trait, it can be beneficial to only add this pattern
270once, instead of duplicating per-operation that implements that interface. To enable the
271generation of this hook, the `hasCanonicalizer` field may be used. This will declare
272the `getCanonicalizationPatterns` method on the dialect, which has the form:
273
274```c++
275/// Return the canonicalization patterns for this dialect:
276void MyDialect::getCanonicalizationPatterns(RewritePatternSet &results) const;
277```
278
279See the documentation for [Canonicalization in MLIR](Canonicalization.md) for a much more
280detailed description about canonicalization patterns.
281
282### C++ Accessor Prefix
283
284Historically, MLIR has generated accessors for operation components (such as attribute, operands,
285results) using the tablegen definition name verbatim. This means that if an operation was defined
286as:
287
288```tablegen
289def MyOp : MyDialect<"op"> {
290  let arguments = (ins StrAttr:$value, StrAttr:$other_value);
291}
292```
293
294It would have accessors generated for the `value` and `other_value` attributes as follows:
295
296```c++
297StringAttr MyOp::value();
298void MyOp::value(StringAttr newValue);
299
300StringAttr MyOp::other_value();
301void MyOp::other_value(StringAttr newValue);
302```
303
304Since then, we have decided to move accessors over to a style that matches the rest of the
305code base. More specifically, this means that we prefix accessors with `get` and `set`
306respectively, and transform `snake_style` names to camel case (`UpperCamel` when prefixed,
307and `lowerCamel` for individual variable names). If we look at the same example as above, this
308would produce:
309
310```c++
311StringAttr MyOp::getValue();
312void MyOp::setValue(StringAttr newValue);
313
314StringAttr MyOp::getOtherValue();
315void MyOp::setOtherValue(StringAttr newValue);
316```
317
318The form in which accessors are generated is controlled by the `emitAccessorPrefix` field.
319This field may any of the following values:
320
321* `kEmitAccessorPrefix_Raw`
322  - Don't emit any `get`/`set` prefix.
323
324* `kEmitAccessorPrefix_Prefixed`
325  - Only emit with `get`/`set` prefix.
326
327* `kEmitAccessorPrefix_Both`
328  - Emit with **and** without prefix.
329
330All new dialects are strongly encouraged to use the `kEmitAccessorPrefix_Prefixed` value, as
331the `Raw` form is deprecated and in the process of being removed.
332
333Note: Remove this section when all dialects have been switched to the new accessor form.
334