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
615###### Optional Parameters
616
617Optional parameters in the assembly format can be indicated by setting
618`isOptional`. The C++ type of an optional parameter is required to satisfy the
619following requirements:
620
621- is default-constructible
622- is contextually convertible to `bool`
623- only the default-constructed value is `false`
624
625The parameter parser should return the default-constructed value to indicate "no
626value present". The printer will guard on the presence of a value to print the
627parameter.
628
629If a value was not parsed for an optional parameter, then the parameter will be
630set to its default-constructed C++ value. For example, `Optional<int>` will be
631set to `llvm::None` and `Attribute` will be set to `nullptr`.
632
633Only optional parameters or directives that only capture optional parameters can
634be used in optional groups. An optional group is a set of elements optionally
635printed based on the presence of an anchor. Suppose parameter `a` is an
636`IntegerAttr`.
637
638```
639( `(` $a^ `)` ) : (`x`)?
640```
641
642In the above assembly format, if `a` is present (non-null), then it will be
643printed as `(5 : i32)`. If it is not present, it will be `x`. Directives that
644are used inside optional groups are allowed only if all captured parameters are
645also optional.
646
647###### Default-Valued Parameters
648
649Optional parameters can be given default values by setting `defaultValue`, a
650string of the C++ default value, or by using `DefaultValuedParameter`. If a
651value for the parameter was not encountered during parsing, it is set to this
652default value. If a parameter is equal to its default value, it is not printed.
653The `comparator` field of the parameter is used, but if one is not specified,
654the equality operator is used.
655
656For example:
657
658```tablegen
659let parameters = (ins DefaultValuedParameter<"Optional<int>", "5">:$a)
660let mnemonic = "default_valued";
661let assemblyFormat = "(`<` $a^ `>`)?";
662```
663
664Which will look like:
665
666```mlir
667!test.default_valued     // a = 5
668!test.default_valued<10> // a = 10
669```
670
671For optional `Attribute` or `Type` parameters, the current MLIR context is
672available through `$_ctx`. E.g.
673
674```tablegen
675DefaultValuedParameter<"IntegerType", "IntegerType::get($_ctx, 32)">
676```
677
678##### Assembly Format Directives
679
680Attribute and type assembly formats have the following directives:
681
682- `params`: capture all parameters of an attribute or type.
683- `qualified`: mark a parameter to be printed with its leading dialect and
684  mnemonic.
685- `struct`: generate a "struct-like" parser and printer for a list of key-value
686  pairs.
687- `custom`: dispatch a call to user-define parser and printer functions
688- `ref`: in a custom directive, references a previously bound variable
689
690###### `params` Directive
691
692This directive is used to refer to all parameters of an attribute or type. When
693used as a top-level directive, `params` generates a parser and printer for a
694comma-separated list of the parameters. For example:
695
696```tablegen
697def MyPairType : TypeDef<My_Dialect, "MyPairType"> {
698  let parameters = (ins "int":$a, "int":$b);
699  let mnemonic = "pair";
700  let assemblyFormat = "`<` params `>`";
701}
702```
703
704In the IR, this type will appear as:
705
706```mlir
707!my_dialect.pair<42, 24>
708```
709
710The `params` directive can also be passed to other directives, such as `struct`,
711as an argument that refers to all parameters in place of explicitly listing all
712parameters as variables.
713
714###### `qualified` Directive
715
716This directive can be used to wrap attribute or type parameters such that they
717are printed in a fully qualified form, i.e., they include the dialect name and
718mnemonic prefix.
719
720For example:
721
722```tablegen
723def OuterType : TypeDef<My_Dialect, "MyOuterType"> {
724  let parameters = (ins MyPairType:$inner);
725  let mnemonic = "outer";
726  let assemblyFormat = "`<` pair `:` $inner `>`";
727}
728def OuterQualifiedType : TypeDef<My_Dialect, "MyOuterQualifiedType"> {
729  let parameters = (ins MyPairType:$inner);
730  let mnemonic = "outer_qual";
731  let assemblyFormat = "`<` pair `:` qualified($inner) `>`";
732}
733```
734
735In the IR, the types will appear as:
736
737```mlir
738!my_dialect.outer<pair : <42, 24>>
739!my_dialect.outer_qual<pair : !mydialect.pair<42, 24>>
740```
741
742If optional parameters are present, they are not printed in the parameter list
743if they are not present.
744
745###### `struct` Directive
746
747The `struct` directive accepts a list of variables to capture and will generate
748a parser and printer for a comma-separated list of key-value pairs. If an
749optional parameter is included in the `struct`, it can be elided. The variables
750are printed in the order they are specified in the argument list **but can be
751parsed in any order**. For example:
752
753```tablegen
754def MyStructType : TypeDef<My_Dialect, "MyStructType"> {
755  let parameters = (ins StringRefParameter<>:$sym_name,
756                        "int":$a, "int":$b, "int":$c);
757  let mnemonic = "struct";
758  let assemblyFormat = "`<` $sym_name `->` struct($a, $b, $c) `>`";
759}
760```
761
762In the IR, this type can appear with any permutation of the order of the
763parameters captured in the directive.
764
765```mlir
766!my_dialect.struct<"foo" -> a = 1, b = 2, c = 3>
767!my_dialect.struct<"foo" -> b = 2, c = 3, a = 1>
768```
769
770Passing `params` as the only argument to `struct` makes the directive capture
771all the parameters of the attribute or type. For the same type above, an
772assembly format of `` `<` struct(params) `>` `` will result in:
773
774```mlir
775!my_dialect.struct<b = 2, sym_name = "foo", c = 3, a = 1>
776```
777
778The order in which the parameters are printed is the order in which they are
779declared in the attribute's or type's `parameter` list.
780
781###### `custom` and `ref` directive
782
783The `custom` directive is used to dispatch calls to user-defined printer and
784parser functions. For example, suppose we had the following type:
785
786```tablegen
787let parameters = (ins "int":$foo, "int":$bar);
788let assemblyFormat = "custom<Foo>($foo) custom<Bar>($bar, ref($foo))";
789```
790
791The `custom` directive `custom<Foo>($foo)` will in the parser and printer
792respectively generate calls to:
793
794```c++
795LogicalResult parseFoo(AsmParser &parser, FailureOr<int> &foo);
796void printFoo(AsmPrinter &printer, int foo);
797```
798
799A previously bound variable can be passed as a parameter to a `custom` directive
800by wrapping it in a `ref` directive. In the previous example, `$foo` is bound by
801the first directive. The second directive references it and expects the
802following printer and parser signatures:
803
804```c++
805LogicalResult parseBar(AsmParser &parser, FailureOr<int> &bar, int foo);
806void printBar(AsmPrinter &printer, int bar, int foo);
807```
808
809More complex C++ types can be used with the `custom` directive. The only caveat
810is that the parameter for the parser must use the storage type of the parameter.
811For example, `StringRefParameter` expects the parser and printer signatures as:
812
813```c++
814LogicalResult parseStringParam(AsmParser &parser,
815                               FailureOr<std::string> &value);
816void printStringParam(AsmPrinter &printer, StringRef value);
817```
818
819The custom parser is considered to have failed if it returns failure or if any
820bound parameters have failure values afterwards.
821
822### Verification
823
824If the `genVerifyDecl` field is set, additional verification methods are
825generated on the class.
826
827- `static LogicalResult verify(function_ref<InFlightDiagnostic()> emitError, parameters...)`
828
829These methods are used to verify the parameters provided to the attribute or
830type class on construction, and emit any necessary diagnostics. This method is
831automatically invoked from the builders of the attribute or type class.
832
833- `AttrOrType getChecked(function_ref<InFlightDiagnostic()> emitError, parameters...)`
834
835As noted in the [Builders](#Builders) section, these methods are companions to
836`get` builders that are failable. If the `verify` invocation fails when these
837methods are called, they return nullptr instead of asserting.
838
839### Storage Classes
840
841Somewhat alluded to in the sections above is the concept of a "storage class"
842(often abbreviated to "storage"). Storage classes contain all of the data
843necessary to construct and unique a attribute or type instance. These classes
844are the "immortal" objects that get uniqued within an MLIRContext and get
845wrapped by the `Attribute` and `Type` classes. Every Attribute or Type class has
846a corresponding storage class, that can be accessed via the protected
847`getImpl()` method.
848
849In most cases the storage class is auto generated, but if necessary it can be
850manually defined by setting the `genStorageClass` field to 0. The name and
851namespace (defaults to `detail`) can additionally be controlled via the The
852`storageClass` and `storageNamespace` fields.
853
854#### Defining a storage class
855
856User defined storage classes must adhere to the following:
857
858- Inherit from the base type storage class of `AttributeStorage` or
859  `TypeStorage` respectively.
860- Define a type alias, `KeyTy`, that maps to a type that uniquely identifies an
861  instance of the derived type. For example, this could be a `std::tuple` of all
862  of the storage parameters.
863- Provide a construction method that is used to allocate a new instance of the
864  storage class.
865  - `static Storage *construct(StorageAllocator &allocator, const KeyTy &key)`
866- Provide a comparison method between an instance of the storage and the
867  `KeyTy`.
868  - `bool operator==(const KeyTy &) const`
869- Provide a method to generate the `KeyTy` from a list of arguments passed to
870  the uniquer when building an Attribute or Type. (Note: This is only necessary
871  if the `KeyTy` cannot be default constructed from these arguments).
872  - `static KeyTy getKey(Args...&& args)`
873- Provide a method to hash an instance of the `KeyTy`. (Note: This is not
874  necessary if an `llvm::DenseMapInfo<KeyTy>` specialization exists)
875  - `static llvm::hash_code hashKey(const KeyTy &)`
876
877Let's look at an example:
878
879```c++
880/// Here we define a storage class for a ComplexType, that holds a non-zero
881/// integer and an integer type.
882struct ComplexTypeStorage : public TypeStorage {
883  ComplexTypeStorage(unsigned nonZeroParam, Type integerType)
884      : nonZeroParam(nonZeroParam), integerType(integerType) {}
885
886  /// The hash key for this storage is a pair of the integer and type params.
887  using KeyTy = std::pair<unsigned, Type>;
888
889  /// Define the comparison function for the key type.
890  bool operator==(const KeyTy &key) const {
891    return key == KeyTy(nonZeroParam, integerType);
892  }
893
894  /// Define a hash function for the key type.
895  /// Note: This isn't necessary because std::pair, unsigned, and Type all have
896  /// hash functions already available.
897  static llvm::hash_code hashKey(const KeyTy &key) {
898    return llvm::hash_combine(key.first, key.second);
899  }
900
901  /// Define a construction function for the key type.
902  /// Note: This isn't necessary because KeyTy can be directly constructed with
903  /// the given parameters.
904  static KeyTy getKey(unsigned nonZeroParam, Type integerType) {
905    return KeyTy(nonZeroParam, integerType);
906  }
907
908  /// Define a construction method for creating a new instance of this storage.
909  static ComplexTypeStorage *construct(StorageAllocator &allocator, const KeyTy &key) {
910    return new (allocator.allocate<ComplexTypeStorage>())
911        ComplexTypeStorage(key.first, key.second);
912  }
913
914  /// The parametric data held by the storage class.
915  unsigned nonZeroParam;
916  Type integerType;
917};
918```
919
920### Mutable attributes and types
921
922Attributes and Types are immutable objects uniqued within an MLIRContext. That
923being said, some parameters may be treated as "mutable" and modified after
924construction. Mutable parameters should be reserved for parameters that can not
925be reasonably initialized during construction time. Given the mutable component,
926these parameters do not take part in the uniquing of the Attribute or Type.
927
928TODO: Mutable parameters are currently not supported in the declarative
929specification of attributes and types, and thus requires defining the Attribute
930or Type class in C++.
931
932#### Defining a mutable storage
933
934In addition to the base requirements for a storage class, instances with a
935mutable component must additionally adhere to the following:
936
937- The mutable component must not participate in the storage `KeyTy`.
938- Provide a mutation method that is used to modify an existing instance of the
939  storage. This method modifies the mutable component based on arguments, using
940  `allocator` for any newly dynamically-allocated storage, and indicates whether
941  the modification was successful.
942  - `LogicalResult mutate(StorageAllocator &allocator, Args ...&& args)`
943
944Let's define a simple storage for recursive types, where a type is identified by
945its name and may contain another type including itself.
946
947```c++
948/// Here we define a storage class for a RecursiveType that is identified by its
949/// name and contains another type.
950struct RecursiveTypeStorage : public TypeStorage {
951  /// The type is uniquely identified by its name. Note that the contained type
952  /// is _not_ a part of the key.
953  using KeyTy = StringRef;
954
955  /// Construct the storage from the type name. Explicitly initialize the
956  /// containedType to nullptr, which is used as marker for the mutable
957  /// component being not yet initialized.
958  RecursiveTypeStorage(StringRef name) : name(name), containedType(nullptr) {}
959
960  /// Define the comparison function.
961  bool operator==(const KeyTy &key) const { return key == name; }
962
963  /// Define a construction method for creating a new instance of the storage.
964  static RecursiveTypeStorage *construct(StorageAllocator &allocator,
965                                         const KeyTy &key) {
966    // Note that the key string is copied into the allocator to ensure it
967    // remains live as long as the storage itself.
968    return new (allocator.allocate<RecursiveTypeStorage>())
969        RecursiveTypeStorage(allocator.copyInto(key));
970  }
971
972  /// Define a mutation method for changing the type after it is created. In
973  /// many cases, we only want to set the mutable component once and reject
974  /// any further modification, which can be achieved by returning failure from
975  /// this function.
976  LogicalResult mutate(StorageAllocator &, Type body) {
977    // If the contained type has been initialized already, and the call tries
978    // to change it, reject the change.
979    if (containedType && containedType != body)
980      return failure();
981
982    // Change the body successfully.
983    containedType = body;
984    return success();
985  }
986
987  StringRef name;
988  Type containedType;
989};
990```
991
992#### Type class definition
993
994Having defined the storage class, we can define the type class itself.
995`Type::TypeBase` provides a `mutate` method that forwards its arguments to the
996`mutate` method of the storage and ensures the mutation happens safely.
997
998```c++
999class RecursiveType : public Type::TypeBase<RecursiveType, Type,
1000                                            RecursiveTypeStorage> {
1001public:
1002  /// Inherit parent constructors.
1003  using Base::Base;
1004
1005  /// Creates an instance of the Recursive type. This only takes the type name
1006  /// and returns the type with uninitialized body.
1007  static RecursiveType get(MLIRContext *ctx, StringRef name) {
1008    // Call into the base to get a uniqued instance of this type. The parameter
1009    // (name) is passed after the context.
1010    return Base::get(ctx, name);
1011  }
1012
1013  /// Now we can change the mutable component of the type. This is an instance
1014  /// method callable on an already existing RecursiveType.
1015  void setBody(Type body) {
1016    // Call into the base to mutate the type.
1017    LogicalResult result = Base::mutate(body);
1018
1019    // Most types expect the mutation to always succeed, but types can implement
1020    // custom logic for handling mutation failures.
1021    assert(succeeded(result) &&
1022           "attempting to change the body of an already-initialized type");
1023
1024    // Avoid unused-variable warning when building without assertions.
1025    (void) result;
1026  }
1027
1028  /// Returns the contained type, which may be null if it has not been
1029  /// initialized yet.
1030  Type getBody() { return getImpl()->containedType; }
1031
1032  /// Returns the name.
1033  StringRef getName() { return getImpl()->name; }
1034};
1035```
1036
1037### Extra declarations
1038
1039The declarative Attribute and Type definitions try to auto-generate as much
1040logic and methods as possible. With that said, there will always be long-tail
1041cases that won't be covered. For such cases, `extraClassDeclaration` can be
1042used. Code within the `extraClassDeclaration` field will be copied literally to
1043the generated C++ Attribute or Type class.
1044
1045Note that `extraClassDeclaration` is a mechanism intended for long-tail cases by
1046power users; for not-yet-implemented widely-applicable cases, improving the
1047infrastructure is preferable.
1048
1049### Registering with the Dialect
1050
1051Once the attributes and types have been defined, they must then be registered
1052with the parent `Dialect`. This is done via the `addAttributes` and `addTypes`
1053methods. Note that when registering, the full definition of the storage classes
1054must be visible.
1055
1056```c++
1057void MyDialect::initialize() {
1058    /// Add the defined attributes to the dialect.
1059  addAttributes<
1060#define GET_ATTRDEF_LIST
1061#include "MyDialect/Attributes.cpp.inc"
1062  >();
1063
1064    /// Add the defined types to the dialect.
1065  addTypes<
1066#define GET_TYPEDEF_LIST
1067#include "MyDialect/Types.cpp.inc"
1068  >();
1069}
1070```
1071