1# Defining Dialect Attributes and Types
2
3This document describes how to define dialect
4[attributes](LangRef.md/#attributes) and [types](LangRef.md/#type-system).
5
6[TOC]
7
8## LangRef Refresher
9
10Before diving into how to define these constructs, below is a quick refresher
11from the [MLIR LangRef](LangRef.md).
12
13### Attributes
14
15Attributes are the mechanism for specifying constant data on operations in
16places where a variable is never allowed - e.g. the comparison predicate of a
17[`arith.cmpi` operation](Dialects/ArithmeticOps.md#arithcmpi-mlirarithcmpiop), or
18the underlying value of a [`arith.constant` operation](Dialects/ArithmeticOps.md#arithconstant-mlirarithconstantop).
19Each operation has an attribute dictionary, which associates a set of attribute
20names to attribute values.
21
22### Types
23
24Every SSA value, such as operation results or block arguments, in MLIR has a type
25defined by the type system. MLIR has an open type system with no fixed list of types,
26and there are no restrictions on the abstractions they represent. For example, take
27the following [Arithmetic AddI operation](Dialects/ArithmeticOps.md#arithaddi-mlirarithaddiop):
28
29```mlir
30  %result = arith.addi %lhs, %rhs : i64
31```
32
33It takes two input SSA values (`%lhs` and `%rhs`), and returns a single SSA
34value (`%result`). The inputs and outputs of this operation are of type `i64`,
35which is an instance of the [Builtin IntegerType](Dialects/Builtin.md#integertype).
36
37## Attributes and Types
38
39The C++ Attribute and Type classes in MLIR (like Ops, and many other things) are
40value-typed. This means that instances of `Attribute` or `Type` are passed
41around by-value, as opposed to by-pointer or by-reference. The `Attribute` and
42`Type` classes act as wrappers around internal storage objects that are uniqued
43within an instance of an `MLIRContext`.
44
45The structure for defining Attributes and Types is nearly identical, with only a
46few differences depending on the context. As such, a majority of this document
47describes the process for defining both Attributes and Types side-by-side with
48examples for both. If necessary, a section will explicitly call out any
49distinct differences.
50
51### Adding a new Attribute or Type definition
52
53As described above, C++ Attribute and Type objects in MLIR are value-typed and
54essentially function as helpful wrappers around an internal storage object that
55holds the actual data for the type. Similarly to Operations, Attributes and Types
56are defined declaratively via [TableGen](https://llvm.org/docs/TableGen/index.html);
57a generic language with tooling to maintain records of domain-specific information.
58It is highly recommended that users review the
59[TableGen Programmer's Reference](https://llvm.org/docs/TableGen/ProgRef.html)
60for an introduction to its syntax and constructs.
61
62Starting the definition of a new attribute or type simply requires adding a
63specialization for either the `AttrDef` or `TypeDef` class respectively. Instances
64of the classes correspond to unqiue Attribute or Type classes.
65
66Below show cases an example Attribute and Type definition. We generally recommend
67defining Attribute and Type classes in different `.td` files to better encapsulate
68the different constructs, and define a proper layering between them. This
69recommendation extends to all of the MLIR constructs, including [Interfaces](Interfaces.md),
70Operations, etc.
71
72```tablegen
73// Include the definition of the necessary tablegen constructs for defining
74// our types.
75include "mlir/IR/AttrTypeBase.td"
76
77// It's common to define a base classes for types in the same dialect. This
78// removes the need to pass in the dialect for each type, and can also be used
79// to define a few fields ahead of time.
80class MyDialect_Type<string name, string typeMnemonic, list<Trait> traits = []>
81    : TypeDef<My_Dialect, name, traits> {
82  let mnemonic = typeMnemonic;
83}
84
85// Here is a simple definition of an "integer" type, with a width parameter.
86def My_IntegerType : MyDialect_Type<"Integer", "int"> {
87  let summary = "Integer type with arbitrary precision up to a fixed limit";
88  let description = [{
89    Integer types have a designated bit width.
90  }];
91  /// Here we defined a single parameter for the type, which is the bitwidth.
92  let parameters = (ins "unsigned":$width);
93
94  /// Here we define the textual format of the type declaratively, which will
95  /// automatically generate parser and printer logic. This will allow for
96  /// instances of the type to be output as, for example:
97  ///
98  ///    !my.int<10> // a 10-bit integer.
99  ///
100  let assemblyFormat = "`<` $width `>`";
101
102  /// Indicate that our type will add additional verification to the parameters.
103  let genVerifyDecl = 1;
104}
105```
106
107Below is an example of an Attribute:
108
109```tablegen
110// Include the definition of the necessary tablegen constructs for defining
111// our attributes.
112include "mlir/IR/AttrTypeBase.td"
113
114// It's common to define a base classes for attributes in the same dialect. This
115// removes the need to pass in the dialect for each attribute, and can also be used
116// to define a few fields ahead of time.
117class MyDialect_Attr<string name, string attrMnemonic, list<Trait> traits = []>
118    : AttrDef<My_Dialect, name, traits> {
119  let mnemonic = attrMnemonic;
120}
121
122// Here is a simple definition of an "integer" attribute, with a type and value parameter.
123def My_IntegerAttr : MyDialect_Attr<"Integer", "int"> {
124  let summary = "An Attribute containing a integer value";
125  let description = [{
126    An integer attribute is a literal attribute that represents an integral
127    value of the specified integer type.
128  }];
129  /// Here we've defined two parameters, one is the `self` type of the attribute
130  /// (i.e. the type of the Attribute itself), and the other is the integer value
131  /// of the attribute.
132  let parameters = (ins AttributeSelfTypeParameter<"">:$type, "APInt":$value);
133
134  /// Here we've defined a custom builder for the type, that removes the need to pass
135  /// in an MLIRContext instance; as it can be infered from the `type`.
136  let builders = [
137    AttrBuilderWithInferredContext<(ins "Type":$type,
138                                        "const APInt &":$value), [{
139      return $_get(type.getContext(), type, value);
140    }]>
141  ];
142
143  /// Here we define the textual format of the attribute declaratively, which will
144  /// automatically generate parser and printer logic. This will allow for
145  /// instances of the attribute to be output as, for example:
146  ///
147  ///    #my.int<50> : !my.int<32> // a 32-bit integer of value 50.
148  ///
149  let assemblyFormat = "`<` $value `>`";
150
151  /// Indicate that our attribute will add additional verification to the parameters.
152  let genVerifyDecl = 1;
153
154  /// Indicate to the ODS generator that we do not want the default builders,
155  /// as we have defined our own simpler ones.
156  let skipDefaultBuilders = 1;
157}
158```
159
160### Class Name
161
162The name of the C++ class which gets generated defaults to
163`<classParamName>Attr` or `<classParamName>Type` for attributes and types
164respectively. In the examples above, this was the `name` template parameter that
165was provided to `MyDialect_Attr` and `MyDialect_Type`. For the definitions we
166added above, we would get C++ classes named `IntegerType` and `IntegerAttr`
167respectively. This can be explicitly overridden via the `cppClassName` field.
168
169### Documentation
170
171The `summary` and `description` fields allow for providing user documentation
172for the attribute or type. The `summary` field expects a simple single-line
173string, with the `description` field used for long and extensive documentation.
174This documentation can be used to generate markdown documentation for the
175dialect and is used by upstream
176[MLIR dialects](https://mlir.llvm.org/docs/Dialects/).
177
178### Mnemonic
179
180The `mnemonic` field, i.e. the template parameters `attrMnemonic` and
181`typeMnemonic` we specified above, are used to specify a name for use during
182parsing. This allows for more easily dispatching to the current attribute or
183type class when parsing IR. This field is generally optional, and custom
184parsing/printing logic can be added without defining it, though most classes
185will want to take advantage of the convenience it provides. This is why we
186added it as a template parameter in the examples above.
187
188### Parameters
189
190The `parameters` field is a variable length list containing the attribute or
191type's parameters. If no parameters are specified (the default), this type is
192considered a singleton type (meaning there is only one possible instance).
193Parameters in this list take the form: `"c++Type":$paramName`. Parameter types
194with a C++ type that requires allocation when constructing the storage instance
195in the context require one of the following:
196
197- Utilize the `AttrParameter` or `TypeParameter` classes instead of the raw
198  "c++Type" string. This allows for providing custom allocation code when using
199  that parameter. `StringRefParameter` and `ArrayRefParameter` are examples of
200  common parameter types that require allocation.
201- Set the `genAccessors` field to 1 (the default) to generate accessor methods
202  for each parameter (e.g. `int getWidth() const` in the Type example above).
203- Set the `hasCustomStorageConstructor` field to `1` to generate a storage class
204  that only declares the constructor, allowing for you to specialize it with
205  whatever allocation code necessary.
206
207#### AttrParameter, TypeParameter, and AttrOrTypeParameter
208
209As hinted at above, these classes allow for specifying parameter types with
210additional functionality. This is generally useful for complex parameters, or those
211with additional invariants that prevent using the raw C++ class. Examples
212include documentation (e.g. the `summary` and `syntax` field), the C++ type, a
213custom allocator to use in the storage constructor method, a custom comparator
214to decide if two instances of the parameter type are equal, etc. As the names
215may suggest, `AttrParameter` is intended for parameters on Attributes,
216`TypeParameter` for Type parameters, and `AttrOrTypeParameters` for either.
217
218Below is an easy parameter pitfall, and highlights when to use these parameter
219classes.
220
221```tablegen
222let parameters = (ins "ArrayRef<int>":$dims);
223```
224
225The above seems innocuous, but it is often a bug! The default storage
226constructor blindly copies parameters by value. It does not know anything about
227the types, meaning that the data of this ArrayRef will be copied as-is and is
228likely to lead to use-after-free errors when using the created Attribute or
229Type if the underlying does not have a lifetime exceeding that of the MLIRContext.
230If the lifetime of the data can't be guaranteed, the `ArrayRef<int>` requires
231allocation to ensure that its elements reside within the MLIRContext, e.g. with
232`dims = allocator.copyInto(dims)`.
233
234Here is a simple example for the exact situation above:
235
236```tablegen
237def ArrayRefIntParam : TypeParameter<"::llvm::ArrayRef<int>", "Array of int"> {
238  let allocator = "$_dst = $_allocator.copyInto($_self);";
239}
240
241The parameter can then be used as so:
242
243...
244let parameters = (ins ArrayRefIntParam:$dims);
245```
246
247Below contains descriptions for other various available fields:
248
249The `allocator` code block has the following substitutions:
250
251- `$_allocator` is the TypeStorageAllocator in which to allocate objects.
252- `$_dst` is the variable in which to place the allocated data.
253
254The `comparator` code block has the following substitutions:
255
256- `$_lhs` is an instance of the parameter type.
257- `$_rhs` is an instance of the parameter type.
258
259MLIR includes several specialized classes for common situations:
260
261- `APFloatParameter` for APFloats.
262
263- `StringRefParameter<descriptionOfParam>` for StringRefs.
264
265- `ArrayRefParameter<arrayOf, descriptionOfParam>` for ArrayRefs of value types.
266
267- `SelfAllocationParameter<descriptionOfParam>` for C++ classes which contain a
268  method called `allocateInto(StorageAllocator &allocator)` to allocate itself
269  into `allocator`.
270
271- `ArrayRefOfSelfAllocationParameter<arrayOf, descriptionOfParam>` for arrays of
272  objects which self-allocate as per the last specialization.
273
274- `AttributeSelfTypeParameter` is a special AttrParameter that corresponds to
275  the `Type` of the attribute. Only one parameter of the attribute may be of
276  this parameter type.
277
278### Traits
279
280Similarly to operations, Attribute and Type classes may attach `Traits` that
281provide additional mixin methods and other data. `Trait`s may be attached via
282the trailing template argument, i.e. the `traits` list parameter in the example
283above. See the main [`Trait`](Traits.md) documentation for more information
284on defining and using traits.
285
286### Interfaces
287
288Attribute and Type classes may attach `Interfaces` to provide an virtual
289interface into the Attribute or Type. `Interfaces` are added in the same way as
290[Traits](#Traits), by using the `traits` list template parameter of the
291`AttrDef` or `TypeDef`. See the main [`Interface`](Interfaces.md)
292documentation for more information on defining and using interfaces.
293
294### Builders
295
296For each attribute or type, there are a few builders(`get`/`getChecked`)
297automatically generated based on the parameters of the type. These are used to
298construct instances of the corresponding attribute or type. For example, given
299the following definition:
300
301```tablegen
302def MyAttrOrType : ... {
303  let parameters = (ins "int":$intParam);
304}
305```
306
307The following builders are generated:
308
309```c++
310// Builders are named `get`, and return a new instance for a given set of parameters.
311static MyAttrOrType get(MLIRContext *context, int intParam);
312
313// If `genVerifyDecl` is set to 1, the following method is also generated. This method
314// is similar to `get`, but is failable and on error will return nullptr.
315static MyAttrOrType getChecked(function_ref<InFlightDiagnostic()> emitError,
316                               MLIRContext *context, int intParam);
317```
318
319If these autogenerated methods are not desired, such as when they conflict with
320a custom builder method, the `skipDefaultBuilders` field may be set to 1 to
321signal that the default builders should not be generated.
322
323#### Custom builder methods
324
325The default builder methods may cover a majority of the simple cases related to
326construction, but when they cannot satisfy all of an attribute or type's needs,
327additional builders may be defined via the `builders` field. The `builders`
328field is a list of custom builders, either using `TypeBuilder` for types or
329`AttrBuilder` for attributes, that are added to the attribute or type class. The
330following will showcase several examples for defining builders for a custom type
331`MyType`, the process is the same for attributes except that attributes use
332`AttrBuilder` instead of `TypeBuilder`.
333
334```tablegen
335def MyType : ... {
336  let parameters = (ins "int":$intParam);
337
338  let builders = [
339    TypeBuilder<(ins "int":$intParam)>,
340    TypeBuilder<(ins CArg<"int", "0">:$intParam)>,
341    TypeBuilder<(ins CArg<"int", "0">:$intParam), [{
342      // Write the body of the `get` builder inline here.
343      return Base::get($_ctxt, intParam);
344    }]>,
345    TypeBuilderWithInferredContext<(ins "Type":$typeParam), [{
346      // This builder states that it can infer an MLIRContext instance from
347      // its arguments.
348      return Base::get(typeParam.getContext(), ...);
349    }]>,
350  ];
351}
352```
353
354In this example, we provide several different convenience builders that are
355useful in different scenarios. The `ins` prefix is common to many function
356declarations in ODS, which use a TableGen [`dag`](#tablegen-syntax). What
357follows is a comma-separated list of types (quoted string or `CArg`) and names
358prefixed with the `$` sign. The use of `CArg` allows for providing a default
359value to that argument. Let's take a look at each of these builders individually
360
361The first builder will generate the declaration of a builder method that looks
362like:
363
364```tablegen
365  let builders = [
366    TypeBuilder<(ins "int":$intParam)>,
367  ];
368```
369
370```c++
371class MyType : /*...*/ {
372  /*...*/
373  static MyType get(::mlir::MLIRContext *context, int intParam);
374};
375```
376
377This builder is identical to the one that will be automatically generated for
378`MyType`. The `context` parameter is implicitly added by the generator, and is
379used when building the Type instance (with `Base::get`). The distinction here is
380that we can provide the implementation of this `get` method. With this style of
381builder definition only the declaration is generated, the implementor of
382`MyType` will need to provide a definition of `MyType::get`.
383
384The second builder will generate the declaration of a builder method that looks
385like:
386
387```tablegen
388  let builders = [
389    TypeBuilder<(ins CArg<"int", "0">:$intParam)>,
390  ];
391```
392
393```c++
394class MyType : /*...*/ {
395  /*...*/
396  static MyType get(::mlir::MLIRContext *context, int intParam = 0);
397};
398```
399
400The constraints here are identical to the first builder example except for the
401fact that `intParam` now has a default value attached.
402
403The third builder will generate the declaration of a builder method that looks
404like:
405
406```tablegen
407  let builders = [
408    TypeBuilder<(ins CArg<"int", "0">:$intParam), [{
409      // Write the body of the `get` builder inline here.
410      return Base::get($_ctxt, intParam);
411    }]>,
412  ];
413```
414
415```c++
416class MyType : /*...*/ {
417  /*...*/
418  static MyType get(::mlir::MLIRContext *context, int intParam = 0);
419};
420
421MyType MyType::get(::mlir::MLIRContext *context, int intParam) {
422  // Write the body of the `get` builder inline here.
423  return Base::get(context, intParam);
424}
425```
426
427This is identical to the second builder example. The difference is that now, a
428definition for the builder method will be generated automatically using the
429provided code block as the body. When specifying the body inline, `$_ctxt` may
430be used to access the `MLIRContext *` parameter.
431
432The fourth builder will generate the declaration of a builder method that looks
433like:
434
435```tablegen
436  let builders = [
437    TypeBuilderWithInferredContext<(ins "Type":$typeParam), [{
438      // This builder states that it can infer an MLIRContext instance from
439      // its arguments.
440      return Base::get(typeParam.getContext(), ...);
441    }]>,
442  ];
443```
444
445```c++
446class MyType : /*...*/ {
447  /*...*/
448  static MyType get(Type typeParam);
449};
450
451MyType MyType::get(Type typeParam) {
452  // This builder states that it can infer an MLIRContext instance from its
453  // arguments.
454  return Base::get(typeParam.getContext(), ...);
455}
456```
457
458In this builder example, the main difference from the third builder example
459there is that the `MLIRContext` parameter is no longer added. This is because
460the builder used `TypeBuilderWithInferredContext` implies that the context
461parameter is not necessary as it can be inferred from the arguments to the
462builder.
463
464### Parsing and Printing
465
466If a mnemonic was specified, the `hasCustomAssemblyFormat` and `assemblyFormat`
467fields may be used to specify the assembly format of an attribute or type. Attributes
468and Types with no parameters need not use either of these fields, in which case
469the syntax for the Attribute or Type is simply the mnemonic.
470
471For each dialect, two "dispatch" functions will be created: one for parsing and
472one for printing. These static functions placed alongside the class definitions
473and have the following function signatures:
474
475```c++
476static ParseResult generatedAttributeParser(DialectAsmParser& parser, StringRef *mnemonic, Type attrType, Attribute &result);
477static LogicalResult generatedAttributePrinter(Attribute attr, DialectAsmPrinter& printer);
478
479static ParseResult generatedTypeParser(DialectAsmParser& parser, StringRef *mnemonic, Type &result);
480static LogicalResult generatedTypePrinter(Type type, DialectAsmPrinter& printer);
481```
482
483The above functions should be added to the respective in your
484`Dialect::printType` and `Dialect::parseType` methods, or consider using the
485`useDefaultAttributePrinterParser` and `useDefaultTypePrinterParser` ODS Dialect
486options if all attributes or types define a mnemonic.
487
488The mnemonic, hasCustomAssemblyFormat, and assemblyFormat fields are optional.
489If none are defined, the generated code will not include any parsing or printing
490code and omit the attribute or type from the dispatch functions above. In this
491case, the dialect author is responsible for parsing/printing in the respective
492`Dialect::parseAttribute`/`Dialect::printAttribute` and
493`Dialect::parseType`/`Dialect::printType` methods.
494
495#### Using `hasCustomAssemblyFormat`
496
497Attributes and types defined in ODS with a mnemonic can define an
498`hasCustomAssemblyFormat` to specify custom parsers and printers defined in C++.
499When set to `1` a corresponding `parse` and `print` method will be declared on
500the Attribute or Type class to be defined by the user.
501
502For Types, these methods will have the form:
503
504- `static Type MyType::parse(AsmParser &parser)`
505
506- `Type MyType::print(AsmPrinter &p) const`
507
508For Attributes, these methods will have the form:
509
510- `static Attribute MyAttr::parse(AsmParser &parser, Type attrType)`
511
512- `Attribute MyAttr::print(AsmPrinter &p) const`
513
514#### Using `assemblyFormat`
515
516Attributes and types defined in ODS with a mnemonic can define an
517`assemblyFormat` to declaratively describe custom parsers and printers. The
518assembly format consists of literals, variables, and directives.
519
520- A literal is a keyword or valid punctuation enclosed in backticks, e.g.
521  `` `keyword` `` or `` `<` ``.
522- A variable is a parameter name preceded by a dollar sign, e.g. `$param0`,
523  which captures one attribute or type parameter.
524- A directive is a keyword followed by an optional argument list that defines
525  special parser and printer behaviour.
526
527```tablegen
528// An example type with an assembly format.
529def MyType : TypeDef<My_Dialect, "MyType"> {
530  // Define a mnemonic to allow the dialect's parser hook to call into the
531  // generated parser.
532  let mnemonic = "my_type";
533
534  // Define two parameters whose C++ types are indicated in string literals.
535  let parameters = (ins "int":$count, "AffineMap":$map);
536
537  // Define the assembly format. Surround the format with less `<` and greater
538  // `>` so that MLIR's printer uses the pretty format.
539  let assemblyFormat = "`<` $count `,` `map` `=` $map `>`";
540}
541```
542
543The declarative assembly format for `MyType` results in the following format in
544the IR:
545
546```mlir
547!my_dialect.my_type<42, map = affine_map<(i, j) -> (j, i)>>
548```
549
550##### Parameter Parsing and Printing
551
552For many basic parameter types, no additional work is needed to define how these
553parameters are parsed or printed.
554
555- The default printer for any parameter is `$_printer << $_self`, where `$_self`
556  is the C++ value of the parameter and `$_printer` is an `AsmPrinter`.
557- The default parser for a parameter is
558  `FieldParser<$cppClass>::parse($_parser)`, where `$cppClass` is the C++ type
559  of the parameter and `$_parser` is an `AsmParser`.
560
561Printing and parsing behaviour can be added to additional C++ types by
562overloading these functions or by defining a `parser` and `printer` in an ODS
563parameter class.
564
565Example of overloading:
566
567```c++
568using MyParameter = std::pair<int, int>;
569
570AsmPrinter &operator<<(AsmPrinter &printer, MyParameter param) {
571  printer << param.first << " * " << param.second;
572}
573
574template <> struct FieldParser<MyParameter> {
575  static FailureOr<MyParameter> parse(AsmParser &parser) {
576    int a, b;
577    if (parser.parseInteger(a) || parser.parseStar() ||
578        parser.parseInteger(b))
579      return failure();
580    return MyParameter(a, b);
581  }
582};
583```
584
585Example of using ODS parameter classes:
586
587```tablegen
588def MyParameter : TypeParameter<"std::pair<int, int>", "pair of ints"> {
589  let printer = [{ $_printer << $_self.first << " * " << $_self.second }];
590  let parser = [{ [&] -> FailureOr<std::pair<int, int>> {
591    int a, b;
592    if ($_parser.parseInteger(a) || $_parser.parseStar() ||
593        $_parser.parseInteger(b))
594      return failure();
595    return std::make_pair(a, b);
596  }() }];
597}
598```
599
600A type using this parameter with the assembly format `` `<` $myParam `>` `` will
601look as follows in the IR:
602
603```mlir
604!my_dialect.my_type<42 * 24>
605```
606
607###### Non-POD Parameters
608
609Parameters that aren't plain-old-data (e.g. references) may need to define a
610`cppStorageType` to contain the data until it is copied into the allocator. For
611example, `StringRefParameter` uses `std::string` as its storage type, whereas
612`ArrayRefParameter` uses `SmallVector` as its storage type. The parsers for
613these parameters are expected to return `FailureOr<$cppStorageType>`.
614
615To add a custom conversion between the `cppStorageType` and the C++ type of the
616parameter, parameters can override `convertFromStorage`, which by default is
617`"$_self"` (i.e., it attempts an implicit conversion from `cppStorageType`).
618
619###### Optional Parameters
620
621Optional parameters in the assembly format can be indicated by setting
622`isOptional`. The C++ type of an optional parameter is required to satisfy the
623following requirements:
624
625- is default-constructible
626- is contextually convertible to `bool`
627- only the default-constructed value is `false`
628
629The parameter parser should return the default-constructed value to indicate "no
630value present". The printer will guard on the presence of a value to print the
631parameter.
632
633If a value was not parsed for an optional parameter, then the parameter will be
634set to its default-constructed C++ value. For example, `Optional<int>` will be
635set to `llvm::None` and `Attribute` will be set to `nullptr`.
636
637Only optional parameters or directives that only capture optional parameters can
638be used in optional groups. An optional group is a set of elements optionally
639printed based on the presence of an anchor. Suppose parameter `a` is an
640`IntegerAttr`.
641
642```
643( `(` $a^ `)` ) : (`x`)?
644```
645
646In the above assembly format, if `a` is present (non-null), then it will be
647printed as `(5 : i32)`. If it is not present, it will be `x`. Directives that
648are used inside optional groups are allowed only if all captured parameters are
649also optional.
650
651###### Default-Valued Parameters
652
653Optional parameters can be given default values by setting `defaultValue`, a
654string of the C++ default value, or by using `DefaultValuedParameter`. If a
655value for the parameter was not encountered during parsing, it is set to this
656default value. If a parameter is equal to its default value, it is not printed.
657The `comparator` field of the parameter is used, but if one is not specified,
658the equality operator is used.
659
660For example:
661
662```tablegen
663let parameters = (ins DefaultValuedParameter<"Optional<int>", "5">:$a)
664let mnemonic = "default_valued";
665let assemblyFormat = "(`<` $a^ `>`)?";
666```
667
668Which will look like:
669
670```mlir
671!test.default_valued     // a = 5
672!test.default_valued<10> // a = 10
673```
674
675For optional `Attribute` or `Type` parameters, the current MLIR context is
676available through `$_ctxt`. E.g.
677
678```tablegen
679DefaultValuedParameter<"IntegerType", "IntegerType::get($_ctxt, 32)">
680```
681
682##### Assembly Format Directives
683
684Attribute and type assembly formats have the following directives:
685
686- `params`: capture all parameters of an attribute or type.
687- `qualified`: mark a parameter to be printed with its leading dialect and
688  mnemonic.
689- `struct`: generate a "struct-like" parser and printer for a list of key-value
690  pairs.
691- `custom`: dispatch a call to user-define parser and printer functions
692- `ref`: in a custom directive, references a previously bound variable
693
694###### `params` Directive
695
696This directive is used to refer to all parameters of an attribute or type. When
697used as a top-level directive, `params` generates a parser and printer for a
698comma-separated list of the parameters. For example:
699
700```tablegen
701def MyPairType : TypeDef<My_Dialect, "MyPairType"> {
702  let parameters = (ins "int":$a, "int":$b);
703  let mnemonic = "pair";
704  let assemblyFormat = "`<` params `>`";
705}
706```
707
708In the IR, this type will appear as:
709
710```mlir
711!my_dialect.pair<42, 24>
712```
713
714The `params` directive can also be passed to other directives, such as `struct`,
715as an argument that refers to all parameters in place of explicitly listing all
716parameters as variables.
717
718###### `qualified` Directive
719
720This directive can be used to wrap attribute or type parameters such that they
721are printed in a fully qualified form, i.e., they include the dialect name and
722mnemonic prefix.
723
724For example:
725
726```tablegen
727def OuterType : TypeDef<My_Dialect, "MyOuterType"> {
728  let parameters = (ins MyPairType:$inner);
729  let mnemonic = "outer";
730  let assemblyFormat = "`<` pair `:` $inner `>`";
731}
732def OuterQualifiedType : TypeDef<My_Dialect, "MyOuterQualifiedType"> {
733  let parameters = (ins MyPairType:$inner);
734  let mnemonic = "outer_qual";
735  let assemblyFormat = "`<` pair `:` qualified($inner) `>`";
736}
737```
738
739In the IR, the types will appear as:
740
741```mlir
742!my_dialect.outer<pair : <42, 24>>
743!my_dialect.outer_qual<pair : !mydialect.pair<42, 24>>
744```
745
746If optional parameters are present, they are not printed in the parameter list
747if they are not present.
748
749###### `struct` Directive
750
751The `struct` directive accepts a list of variables to capture and will generate
752a parser and printer for a comma-separated list of key-value pairs. If an
753optional parameter is included in the `struct`, it can be elided. The variables
754are printed in the order they are specified in the argument list **but can be
755parsed in any order**. For example:
756
757```tablegen
758def MyStructType : TypeDef<My_Dialect, "MyStructType"> {
759  let parameters = (ins StringRefParameter<>:$sym_name,
760                        "int":$a, "int":$b, "int":$c);
761  let mnemonic = "struct";
762  let assemblyFormat = "`<` $sym_name `->` struct($a, $b, $c) `>`";
763}
764```
765
766In the IR, this type can appear with any permutation of the order of the
767parameters captured in the directive.
768
769```mlir
770!my_dialect.struct<"foo" -> a = 1, b = 2, c = 3>
771!my_dialect.struct<"foo" -> b = 2, c = 3, a = 1>
772```
773
774Passing `params` as the only argument to `struct` makes the directive capture
775all the parameters of the attribute or type. For the same type above, an
776assembly format of `` `<` struct(params) `>` `` will result in:
777
778```mlir
779!my_dialect.struct<b = 2, sym_name = "foo", c = 3, a = 1>
780```
781
782The order in which the parameters are printed is the order in which they are
783declared in the attribute's or type's `parameter` list.
784
785###### `custom` and `ref` directive
786
787The `custom` directive is used to dispatch calls to user-defined printer and
788parser functions. For example, suppose we had the following type:
789
790```tablegen
791let parameters = (ins "int":$foo, "int":$bar);
792let assemblyFormat = "custom<Foo>($foo) custom<Bar>($bar, ref($foo))";
793```
794
795The `custom` directive `custom<Foo>($foo)` will in the parser and printer
796respectively generate calls to:
797
798```c++
799LogicalResult parseFoo(AsmParser &parser, FailureOr<int> &foo);
800void printFoo(AsmPrinter &printer, int foo);
801```
802
803A previously bound variable can be passed as a parameter to a `custom` directive
804by wrapping it in a `ref` directive. In the previous example, `$foo` is bound by
805the first directive. The second directive references it and expects the
806following printer and parser signatures:
807
808```c++
809LogicalResult parseBar(AsmParser &parser, FailureOr<int> &bar, int foo);
810void printBar(AsmPrinter &printer, int bar, int foo);
811```
812
813More complex C++ types can be used with the `custom` directive. The only caveat
814is that the parameter for the parser must use the storage type of the parameter.
815For example, `StringRefParameter` expects the parser and printer signatures as:
816
817```c++
818LogicalResult parseStringParam(AsmParser &parser,
819                               FailureOr<std::string> &value);
820void printStringParam(AsmPrinter &printer, StringRef value);
821```
822
823The custom parser is considered to have failed if it returns failure or if any
824bound parameters have failure values afterwards.
825
826### Verification
827
828If the `genVerifyDecl` field is set, additional verification methods are
829generated on the class.
830
831- `static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError, parameters...)`
832
833These methods are used to verify the parameters provided to the attribute or
834type class on construction, and emit any necessary diagnostics. This method is
835automatically invoked from the builders of the attribute or type class.
836
837- `AttrOrType getChecked(function_ref<InFlightDiagnostic()> emitError, parameters...)`
838
839As noted in the [Builders](#Builders) section, these methods are companions to
840`get` builders that are failable. If the `verify` invocation fails when these
841methods are called, they return nullptr instead of asserting.
842
843### Storage Classes
844
845Somewhat alluded to in the sections above is the concept of a "storage class"
846(often abbreviated to "storage"). Storage classes contain all of the data
847necessary to construct and unique a attribute or type instance. These classes
848are the "immortal" objects that get uniqued within an MLIRContext and get
849wrapped by the `Attribute` and `Type` classes. Every Attribute or Type class has
850a corresponding storage class, that can be accessed via the protected
851`getImpl()` method.
852
853In most cases the storage class is auto generated, but if necessary it can be
854manually defined by setting the `genStorageClass` field to 0. The name and
855namespace (defaults to `detail`) can additionally be controlled via the The
856`storageClass` and `storageNamespace` fields.
857
858#### Defining a storage class
859
860User defined storage classes must adhere to the following:
861
862- Inherit from the base type storage class of `AttributeStorage` or
863  `TypeStorage` respectively.
864- Define a type alias, `KeyTy`, that maps to a type that uniquely identifies an
865  instance of the derived type. For example, this could be a `std::tuple` of all
866  of the storage parameters.
867- Provide a construction method that is used to allocate a new instance of the
868  storage class.
869  - `static Storage *construct(StorageAllocator &allocator, const KeyTy &key)`
870- Provide a comparison method between an instance of the storage and the
871  `KeyTy`.
872  - `bool operator==(const KeyTy &) const`
873- Provide a method to generate the `KeyTy` from a list of arguments passed to
874  the uniquer when building an Attribute or Type. (Note: This is only necessary
875  if the `KeyTy` cannot be default constructed from these arguments).
876  - `static KeyTy getKey(Args...&& args)`
877- Provide a method to hash an instance of the `KeyTy`. (Note: This is not
878  necessary if an `llvm::DenseMapInfo<KeyTy>` specialization exists)
879  - `static llvm::hash_code hashKey(const KeyTy &)`
880
881Let's look at an example:
882
883```c++
884/// Here we define a storage class for a ComplexType, that holds a non-zero
885/// integer and an integer type.
886struct ComplexTypeStorage : public TypeStorage {
887  ComplexTypeStorage(unsigned nonZeroParam, Type integerType)
888      : nonZeroParam(nonZeroParam), integerType(integerType) {}
889
890  /// The hash key for this storage is a pair of the integer and type params.
891  using KeyTy = std::pair<unsigned, Type>;
892
893  /// Define the comparison function for the key type.
894  bool operator==(const KeyTy &key) const {
895    return key == KeyTy(nonZeroParam, integerType);
896  }
897
898  /// Define a hash function for the key type.
899  /// Note: This isn't necessary because std::pair, unsigned, and Type all have
900  /// hash functions already available.
901  static llvm::hash_code hashKey(const KeyTy &key) {
902    return llvm::hash_combine(key.first, key.second);
903  }
904
905  /// Define a construction function for the key type.
906  /// Note: This isn't necessary because KeyTy can be directly constructed with
907  /// the given parameters.
908  static KeyTy getKey(unsigned nonZeroParam, Type integerType) {
909    return KeyTy(nonZeroParam, integerType);
910  }
911
912  /// Define a construction method for creating a new instance of this storage.
913  static ComplexTypeStorage *construct(StorageAllocator &allocator, const KeyTy &key) {
914    return new (allocator.allocate<ComplexTypeStorage>())
915        ComplexTypeStorage(key.first, key.second);
916  }
917
918  /// The parametric data held by the storage class.
919  unsigned nonZeroParam;
920  Type integerType;
921};
922```
923
924### Mutable attributes and types
925
926Attributes and Types are immutable objects uniqued within an MLIRContext. That
927being said, some parameters may be treated as "mutable" and modified after
928construction. Mutable parameters should be reserved for parameters that can not
929be reasonably initialized during construction time. Given the mutable component,
930these parameters do not take part in the uniquing of the Attribute or Type.
931
932TODO: Mutable parameters are currently not supported in the declarative
933specification of attributes and types, and thus requires defining the Attribute
934or Type class in C++.
935
936#### Defining a mutable storage
937
938In addition to the base requirements for a storage class, instances with a
939mutable component must additionally adhere to the following:
940
941- The mutable component must not participate in the storage `KeyTy`.
942- Provide a mutation method that is used to modify an existing instance of the
943  storage. This method modifies the mutable component based on arguments, using
944  `allocator` for any newly dynamically-allocated storage, and indicates whether
945  the modification was successful.
946  - `LogicalResult mutate(StorageAllocator &allocator, Args ...&& args)`
947
948Let's define a simple storage for recursive types, where a type is identified by
949its name and may contain another type including itself.
950
951```c++
952/// Here we define a storage class for a RecursiveType that is identified by its
953/// name and contains another type.
954struct RecursiveTypeStorage : public TypeStorage {
955  /// The type is uniquely identified by its name. Note that the contained type
956  /// is _not_ a part of the key.
957  using KeyTy = StringRef;
958
959  /// Construct the storage from the type name. Explicitly initialize the
960  /// containedType to nullptr, which is used as marker for the mutable
961  /// component being not yet initialized.
962  RecursiveTypeStorage(StringRef name) : name(name), containedType(nullptr) {}
963
964  /// Define the comparison function.
965  bool operator==(const KeyTy &key) const { return key == name; }
966
967  /// Define a construction method for creating a new instance of the storage.
968  static RecursiveTypeStorage *construct(StorageAllocator &allocator,
969                                         const KeyTy &key) {
970    // Note that the key string is copied into the allocator to ensure it
971    // remains live as long as the storage itself.
972    return new (allocator.allocate<RecursiveTypeStorage>())
973        RecursiveTypeStorage(allocator.copyInto(key));
974  }
975
976  /// Define a mutation method for changing the type after it is created. In
977  /// many cases, we only want to set the mutable component once and reject
978  /// any further modification, which can be achieved by returning failure from
979  /// this function.
980  LogicalResult mutate(StorageAllocator &, Type body) {
981    // If the contained type has been initialized already, and the call tries
982    // to change it, reject the change.
983    if (containedType && containedType != body)
984      return failure();
985
986    // Change the body successfully.
987    containedType = body;
988    return success();
989  }
990
991  StringRef name;
992  Type containedType;
993};
994```
995
996#### Type class definition
997
998Having defined the storage class, we can define the type class itself.
999`Type::TypeBase` provides a `mutate` method that forwards its arguments to the
1000`mutate` method of the storage and ensures the mutation happens safely.
1001
1002```c++
1003class RecursiveType : public Type::TypeBase<RecursiveType, Type,
1004                                            RecursiveTypeStorage> {
1005public:
1006  /// Inherit parent constructors.
1007  using Base::Base;
1008
1009  /// Creates an instance of the Recursive type. This only takes the type name
1010  /// and returns the type with uninitialized body.
1011  static RecursiveType get(MLIRContext *ctx, StringRef name) {
1012    // Call into the base to get a uniqued instance of this type. The parameter
1013    // (name) is passed after the context.
1014    return Base::get(ctx, name);
1015  }
1016
1017  /// Now we can change the mutable component of the type. This is an instance
1018  /// method callable on an already existing RecursiveType.
1019  void setBody(Type body) {
1020    // Call into the base to mutate the type.
1021    LogicalResult result = Base::mutate(body);
1022
1023    // Most types expect the mutation to always succeed, but types can implement
1024    // custom logic for handling mutation failures.
1025    assert(succeeded(result) &&
1026           "attempting to change the body of an already-initialized type");
1027
1028    // Avoid unused-variable warning when building without assertions.
1029    (void) result;
1030  }
1031
1032  /// Returns the contained type, which may be null if it has not been
1033  /// initialized yet.
1034  Type getBody() { return getImpl()->containedType; }
1035
1036  /// Returns the name.
1037  StringRef getName() { return getImpl()->name; }
1038};
1039```
1040
1041### Extra declarations
1042
1043The declarative Attribute and Type definitions try to auto-generate as much
1044logic and methods as possible. With that said, there will always be long-tail
1045cases that won't be covered. For such cases, `extraClassDeclaration` can be
1046used. Code within the `extraClassDeclaration` field will be copied literally to
1047the generated C++ Attribute or Type class.
1048
1049Note that `extraClassDeclaration` is a mechanism intended for long-tail cases by
1050power users; for not-yet-implemented widely-applicable cases, improving the
1051infrastructure is preferable.
1052
1053### Registering with the Dialect
1054
1055Once the attributes and types have been defined, they must then be registered
1056with the parent `Dialect`. This is done via the `addAttributes` and `addTypes`
1057methods. Note that when registering, the full definition of the storage classes
1058must be visible.
1059
1060```c++
1061void MyDialect::initialize() {
1062    /// Add the defined attributes to the dialect.
1063  addAttributes<
1064#define GET_ATTRDEF_LIST
1065#include "MyDialect/Attributes.cpp.inc"
1066  >();
1067
1068    /// Add the defined types to the dialect.
1069  addTypes<
1070#define GET_TYPEDEF_LIST
1071#include "MyDialect/Types.cpp.inc"
1072  >();
1073}
1074```
1075