1# Operation Definition Specification (ODS) 2 3In addition to specializing the `mlir::Op` C++ template, MLIR also supports 4defining operations and data types in a table-driven manner. This is achieved 5via [TableGen][TableGen], which is both a generic language and its tooling to 6maintain records of domain-specific information. Facts regarding an operation 7are specified concisely into a TableGen record, which will be expanded into 8an equivalent `mlir::Op` C++ template specialization at compiler build time. 9 10This manual explains in detail all the available mechanisms for defining 11operations in such a table-driven manner. It aims to be a specification instead 12of a tutorial. Please refer to [Quickstart tutorial to adding MLIR graph 13rewrite](Tutorials/QuickstartRewrites.md) for the latter. 14 15In addition to detailing each mechanism, this manual also tries to capture 16best practices. They are rendered as quoted bullet points. 17 18## Motivation 19 20MLIR allows pluggable dialects, and dialects contain, among others, a list of 21operations. This open and extensible ecosystem leads to the "stringly" type IR 22problem, e.g., repetitive string comparisons during optimization and analysis 23passes, unintuitive accessor methods (e.g., generic/error prone `getOperand(3)` 24vs self-documenting `getStride()`) with more generic return types, verbose and 25generic constructors without default arguments, verbose textual IR dump, and 26so on. Furthermore, operation verification is: 27 281. best case: a central string-to-verification-function map, 291. middle case: duplication of verification across the code base, or 301. worst case: no verification functions. 31 32The fix is to support defining ops in a table-driven manner. Then for each 33dialect, we can have a central place that contains everything you need to know 34about each op, including its constraints, custom assembly form, etc. This 35description is also used to generate helper functions and classes to allow 36building, verification, parsing, printing, analysis, and many more. 37 38## Benefits 39 40Compared to the C++ template, this table-driven approach has several benefits 41including but not limited to: 42 43* **Single source of truth**: We strive to encode all facts regarding an 44 operation into the record, so that readers don't need to jump among code 45 snippets to fully understand an operation. 46* **Removing boilerplate**: We can automatically generate 47 operand/attribute/result getter methods, operation build methods, operation 48 verify methods, and many more utilities from the record. This greatly reduces 49 the boilerplate needed for defining a new op. 50* **Facilitating auto-generation**: The usage of these operation information 51 records are by no means limited to op definition itself. We can use them to 52 drive the auto-generation of many other components, like computation graph 53 serialization. 54 55## TableGen Syntax 56 57We use TableGen as the language for specifying operation information. TableGen 58itself just provides syntax for writing records; the syntax and constructs 59allowed in a TableGen file (typically with filename suffix `.td`) can be found 60[here][TableGenProgRef]. 61 62* TableGen `class` is similar to C++ class; it can be templated and 63 subclassed. 64* TableGen `def` is similar to C++ object; it can be declared by specializing 65 a TableGen `class` (e.g., `def MyDef : MyClass<...>;`) or completely 66 independently (e.g., `def MyDef;`). It cannot be further templated or 67 subclassed. 68* TableGen `dag` is a dedicated type for directed acyclic graph of elements. A 69 `dag` has one operator and zero or more arguments. Its syntax is `(operator 70 arg0, arg1, argN)`. The operator can be any TableGen `def`; an argument can 71 be anything, including `dag` itself. We can have names attached to both the 72 operator and the arguments like `(MyOp:$op_name MyArg:$arg_name)`. 73 74Please see the [language reference][TableGenProgRef] to learn about all the 75types and expressions supported by TableGen. 76 77## Operation Definition 78 79MLIR defines several common constructs to help operation definition and provide 80their semantics via a special [TableGen backend][TableGenBackend]: 81[`OpDefinitionsGen`][OpDefinitionsGen]. These constructs are defined in 82[`OpBase.td`][OpBase]. The main ones are 83 84* The `Op` class: It is the main construct for defining operations. All facts 85 regarding the operation are specified when specializing this class, with the 86 help of the following constructs. 87* The `Dialect` class: Operations belonging to one logical group are placed in 88 the same dialect. The `Dialect` class contains dialect-level information. 89* The `OpTrait` class hierarchy: They are used to specify special properties 90 and constraints of the operation, including whether the operation has side 91 effect or whether its output has the same shape as the input. 92* The `ins`/`outs` marker: These are two special makers builtin to the 93 `OpDefinitionsGen` backend. They lead the definitions of operands/attributes 94 and results respectively. 95* The `TypeConstraint` class hierarchy: They are used to specify the 96 constraints over operands or results. A notable subclass hierarchy is 97 `Type`, which stands for constraints for common C++ types. 98* The `AttrConstraint` class hierarchy: They are used to specify the 99 constraints over attributes. A notable subclass hierarchy is `Attr`, which 100 stands for constraints for attributes whose values are of common types. 101 102An operation is defined by specializing the `Op` class with concrete contents 103for all the fields it requires. For example, `tf.AvgPool` is defined as 104 105```tablegen 106def TF_AvgPoolOp : TF_Op<"AvgPool", [NoSideEffect]> { 107 let summary = "Performs average pooling on the input."; 108 109 let description = [{ 110Each entry in `output` is the mean of the corresponding size `ksize` 111window in `value`. 112 }]; 113 114 let arguments = (ins 115 TF_FpTensor:$value, 116 117 Confined<I64ArrayAttr, [ArrayMinCount<4>]>:$ksize, 118 Confined<I64ArrayAttr, [ArrayMinCount<4>]>:$strides, 119 TF_AnyStrAttrOf<["SAME", "VALID"]>:$padding, 120 DefaultValuedAttr<TF_ConvertDataFormatAttr, "NHWC">:$data_format 121 ); 122 123 let results = (outs 124 TF_FpTensor:$output 125 ); 126 127 TF_DerivedOperandTypeAttr T = TF_DerivedOperandTypeAttr<0>; 128} 129``` 130 131In the following we describe all the fields needed. Please see the definition 132of the `Op` class for the complete list of fields supported. 133 134### Operation name 135 136The operation name is a unique identifier of the operation within MLIR, e.g., 137`tf.Add` for addition operation in the TensorFlow dialect. This is the 138equivalent of the mnemonic in assembly language. It is used for parsing and 139printing in the textual format. It is also used for pattern matching in graph 140rewrites. 141 142The full operation name is composed of the dialect name and the op name, with 143the former provided via the dialect and the latter provided as the second 144template parameter to the `Op` class. 145 146### Operation documentation 147 148This includes both a one-line `summary` and a longer human-readable 149`description`. They will be used to drive automatic generation of dialect 150documentation. They need to be provided in the operation's definition body: 151 152```tablegen 153let summary = "..."; 154 155let description = [{ 156... 157}]; 158``` 159 160`description` should be written in Markdown syntax. 161 162Placing the documentation at the beginning is recommended since 163it helps in understanding the operation. 164 165> * Place documentation at the beginning of the operation definition 166> * The summary should be short and concise. It should be a one-liner without 167> trailing punctuation. Put expanded explanation in description. 168 169### Operation arguments 170 171There are two kinds of arguments: operands and attributes. Operands are runtime 172values produced by other ops; while attributes are compile-time known constant 173values, including two categories: 174 1751. Natural attributes: these attributes affect the behavior of the operations 176 (e.g., padding for convolution); 1771. Derived attributes: these attributes are not needed to define the operation 178 but are instead derived from information of the operation. E.g., the output 179 shape of type. This is mostly used for convenience interface generation or 180 interaction with other frameworks/translation. 181 182 All derived attributes should be materializable as an Attribute. That is, 183 even though they are not materialized, it should be possible to store as 184 an attribute. 185 186Both operands and attributes are specified inside the `dag`-typed `arguments`, 187led by `ins`: 188 189```tablegen 190let arguments = (ins 191 <type-constraint>:$<operand-name>, 192 ... 193 <attr-constraint>:$<attr-name>, 194 ... 195); 196``` 197 198Here `<type-constraint>` is a TableGen `def` from the `TypeConstraint` class 199hierarchy. Similarly, `<attr-constraint>` is a TableGen `def` from the 200`AttrConstraint` class hierarchy. See [Constraints](#constraints) for more 201information. 202 203There is no requirements on the relative order of operands and attributes; they 204can mix freely. The relative order of operands themselves matters. From each 205named argument a named getter will be generated that returns the argument with 206the return type (in the case of attributes the return type will be 207constructed from the storage type, while for operands it will be `Value`). Each 208attribute's raw value (e.g., as stored) can also be accessed via generated 209`<name>Attr` getters for use in transformation passes where the more user 210friendly return type is less suitable. 211 212All the arguments should be named to 1) provide documentation, 2) drive 213auto-generation of getter methods, 3) provide a handle to reference for other 214places like constraints. 215 216#### Variadic operands 217 218To declare a variadic operand, wrap the `TypeConstraint` for the operand with 219`Variadic<...>`. 220 221Normally operations have no variadic operands or just one variadic operand. For 222the latter case, it is easy to deduce which dynamic operands are for the static 223variadic operand definition. Though, if an operation has more than one variable 224length operands (either optional or variadic), it would be impossible to 225attribute dynamic operands to the corresponding static variadic operand 226definitions without further information from the operation. Therefore, either 227the `SameVariadicOperandSize` or `AttrSizedOperandSegments` trait is needed to 228indicate that all variable length operands have the same number of dynamic 229values. 230 231#### Optional operands 232 233To declare an optional operand, wrap the `TypeConstraint` for the operand with 234`Optional<...>`. 235 236Normally operations have no optional operands or just one optional operand. For 237the latter case, it is easy to deduce which dynamic operands are for the static 238operand definition. Though, if an operation has more than one variable length 239operands (either optional or variadic), it would be impossible to attribute 240dynamic operands to the corresponding static variadic operand definitions 241without further information from the operation. Therefore, either the 242`SameVariadicOperandSize` or `AttrSizedOperandSegments` trait is needed to 243indicate that all variable length operands have the same number of dynamic 244values. 245 246#### Optional attributes 247 248To declare an optional attribute, wrap the `AttrConstraint` for the attribute 249with `OptionalAttr<...>`. 250 251#### Attributes with default values 252 253To declare an attribute with a default value, wrap the `AttrConstraint` for the 254attribute with `DefaultValuedAttr<..., "...">`. 255 256The second parameter to `DefaultValuedAttr` should be a string containing the 257C++ default value. For example, a float default value should be specified as 258like `"0.5f"`, and an integer array default value should be specified as like 259`"{1, 2, 3}"`. 260 261#### Confining attributes 262 263`Confined` is provided as a general mechanism to help modelling further 264constraints on attributes beyond the ones brought by value types. You can use 265`Confined` to compose complex constraints out of more primitive ones. For 266example, a 32-bit integer attribute whose minimum value must be 10 can be 267expressed as `Confined<I32Attr, [IntMinValue<10>]>`. 268 269Right now, the following primitive constraints are supported: 270 271* `IntMinValue<N>`: Specifying an integer attribute to be greater than or 272 equal to `N` 273* `IntMaxValue<N>`: Specifying an integer attribute to be less than or equal 274 to `N` 275* `ArrayMinCount<N>`: Specifying an array attribute to have at least `N` 276 elements 277* `IntArrayNthElemEq<I, N>`: Specifying an integer array attribute's `I`-th 278 element to be equal to `N` 279* `IntArrayNthElemMinValue<I, N>`: Specifying an integer array attribute's 280 `I`-th element to be greater than or equal to `N` 281 282TODO: Design and implement more primitive constraints 283 284### Operation regions 285 286The regions of an operation are specified inside of the `dag`-typed `regions`, 287led by `region`: 288 289```tablegen 290let regions = (region 291 <region-constraint>:$<region-name>, 292 ... 293); 294``` 295 296#### Variadic regions 297 298Similar to the `Variadic` class used for variadic operands and results, 299`VariadicRegion<...>` can be used for regions. Variadic regions can currently 300only be specified as the last region in the regions list. 301 302### Operation results 303 304Similar to operands, results are specified inside the `dag`-typed `results`, led 305by `outs`: 306 307```tablegen 308let results = (outs 309 <type-constraint>:$<result-name>, 310 ... 311); 312``` 313 314#### Variadic results 315 316Similar to variadic operands, `Variadic<...>` can also be used for results. 317And similarly, `SameVariadicResultSize` for multiple variadic results in the 318same operation. 319 320### Operation successors 321 322For terminator operations, the successors are specified inside of the 323`dag`-typed `successors`, led by `successor`: 324 325```tablegen 326let successors = (successor 327 <successor-constraint>:$<successor-name>, 328 ... 329); 330``` 331 332#### Variadic successors 333 334Similar to the `Variadic` class used for variadic operands and results, 335`VariadicSuccessor<...>` can be used for successors. Variadic successors can 336currently only be specified as the last successor in the successor list. 337 338### Operation traits and constraints 339 340Traits are operation properties that affect syntax or semantics. MLIR C++ 341models various traits in the `mlir::OpTrait` namespace. 342 343Both operation traits, [interfaces](#operation-interfaces), and constraints 344involving multiple operands/attributes/results are provided as the second 345template parameter to the `Op` class. They should be deriving from the `OpTrait` 346class. See [Constraints](#constraints) for more information. 347 348### Interfaces 349 350[Interfaces](Interfaces.md#attribute-operation-type-interfaces) allow for 351attributes, operations, and types to expose method calls without the caller 352needing to know the derived type. Operation interfaces defined in C++ can be 353accessed in the ODS framework via the `OpInterfaceTrait` class. Aside from using 354pre-existing interfaces in the C++ API, the ODS framework also provides a 355simplified mechanism for defining such interfaces which removes much of the 356boilerplate necessary. 357 358Providing a definition of the `AttrInterface`, `OpInterface`, or `TypeInterface` 359class will auto-generate the C++ classes for the interface. An interface 360includes a name, for the C++ class, a description, and a list of interface 361methods. 362 363```tablegen 364def MyInterface : OpInterface<"MyInterface"> { 365 let description = ...; 366 let methods = [...]; 367} 368``` 369 370There are two types of methods that can be used with an interface, 371`InterfaceMethod` and `StaticInterfaceMethod`. They are both comprised of the 372same core components, with the distinction that `StaticInterfaceMethod` models a 373static method on the derived operation. 374 375An `InterfaceMethod` is comprised of the following components: 376 377* Description 378 - A string description of what this method does and its invariants. 379* ReturnType 380 - A string corresponding to the C++ return type of the method. 381* MethodName 382 - A string corresponding to the desired name of the method. 383* Arguments (Optional) 384 - A dag of strings that correspond to a C++ type and variable name 385 respectively. 386* MethodBody (Optional) 387 - An optional explicit implementation of the interface method. 388 - `ConcreteOp` is an implicitly defined typename that can be used to refer 389 to the type of the derived operation currently being operated on. 390 - In non-static methods, a variable 'ConcreteOp op' is defined and may be 391 used to refer to an instance of the derived operation. 392* DefaultImplementation (Optional) 393 - An optional explicit default implementation of the interface method. 394 - This method is placed within the `Trait` class that is attached to the 395 operation. As such, this method has the same characteristics as any 396 other [`Trait`](Traits.md) method. 397 - `ConcreteOp` is an implicitly defined typename that can be used to refer 398 to the type of the derived operation currently being operated on. 399 400ODS also allows generating the declarations for the `InterfaceMethod` of the op 401if one specifies the interface with `DeclareOpInterfaceMethods` (see example 402below). 403 404Examples: 405 406```tablegen 407def MyInterface : OpInterface<"MyInterface"> { 408 let description = [{ 409 My interface is very interesting. ... 410 }]; 411 412 let methods = [ 413 // A simple non-static method with no inputs. 414 InterfaceMethod<"'foo' is a non-static method with no inputs.", 415 "unsigned", "foo" 416 >, 417 418 // A new non-static method accepting an input argument. 419 InterfaceMethod<"/*insert doc here*/", 420 "Value ", "bar", (ins "unsigned":$i) 421 >, 422 423 // Query a static property of the derived operation. 424 StaticInterfaceMethod<"'fooStatic' is a static method with no inputs.", 425 "unsigned", "fooStatic" 426 >, 427 428 // Provide the definition of a static interface method. 429 // Note: `ConcreteOp` corresponds to the derived operation typename. 430 StaticInterfaceMethod<"/*insert doc here*/", 431 "Operation *", "create", (ins "OpBuilder &":$builder, "Location":$loc), [{ 432 return builder.create<ConcreteOp>(loc); 433 }]>, 434 435 // Provide a definition of the non-static method. 436 // Note: `op` corresponds to the derived operation variable. 437 InterfaceMethod<"/*insert doc here*/", 438 "unsigned", "getNumInputsAndOutputs", (ins), [{ 439 return op.getNumInputs() + op.getNumOutputs(); 440 }]>, 441 442 // Provide only a default definition of the method. 443 // Note: `ConcreteOp` corresponds to the derived operation typename. 444 InterfaceMethod<"/*insert doc here*/", 445 "unsigned", "getNumWithDefault", (ins), /*methodBody=*/[{}], [{ 446 ConcreteOp op = cast<ConcreteOp>(this->getOperation()); 447 return op.getNumInputs() + op.getNumOutputs(); 448 }]>, 449 ]; 450} 451 452// Operation interfaces can optionally be wrapped inside 453// DeclareOpInterfaceMethods. This would result in autogenerating declarations 454// for members `foo`, `bar` and `fooStatic`. Methods with bodies are not 455// declared inside the op declaration but instead handled by the op interface 456// trait directly. 457def OpWithInferTypeInterfaceOp : Op<... 458 [DeclareOpInterfaceMethods<MyInterface>]> { ... } 459 460// Methods that have a default implementation do not have declarations 461// generated. If an operation wishes to override the default behavior, it can 462// explicitly specify the method that it wishes to override. This will force 463// the generation of a declaration for those methods. 464def OpWithOverrideInferTypeInterfaceOp : Op<... 465 [DeclareOpInterfaceMethods<MyInterface, ["getNumWithDefault"]>]> { ... } 466``` 467 468Operation interfaces may also provide a verification method on `OpInterface` by 469setting `verify`. Setting `verify` results in the generated trait having a 470`verifyTrait` method that is applied to all operations implementing the trait. 471 472### Builder methods 473 474For each operation, there are a few builders automatically generated based on 475the arguments and returns types. For example, given the following op definition: 476 477```tablegen 478def MyOp : ... { 479 let arguments = (ins 480 I32:$i32_operand, 481 F32:$f32_operand, 482 ..., 483 484 I32Attr:$i32_attr, 485 F32Attr:$f32_attr, 486 ... 487 ); 488 489 let results = (outs 490 I32:$i32_result, 491 F32:$f32_result, 492 ... 493 ); 494} 495``` 496 497The following builders are generated: 498 499```c++ 500// All result-types/operands/attributes have one aggregate parameter. 501static void build(OpBuilder &odsBuilder, OperationState &odsState, 502 ArrayRef<Type> resultTypes, 503 ValueRange operands, 504 ArrayRef<NamedAttribute> attributes); 505 506// Each result-type/operand/attribute has a separate parameter. The parameters 507// for attributes are of mlir::Attribute types. 508static void build(OpBuilder &odsBuilder, OperationState &odsState, 509 Type i32_result, Type f32_result, ..., 510 Value i32_operand, Value f32_operand, ..., 511 IntegerAttr i32_attr, FloatAttr f32_attr, ...); 512 513// Each result-type/operand/attribute has a separate parameter. The parameters 514// for attributes are raw values unwrapped with mlir::Attribute instances. 515// (Note that this builder will not always be generated. See the following 516// explanation for more details.) 517static void build(OpBuilder &odsBuilder, OperationState &odsState, 518 Type i32_result, Type f32_result, ..., 519 Value i32_operand, Value f32_operand, ..., 520 APInt i32_attr, StringRef f32_attr, ...); 521 522// Each operand/attribute has a separate parameter but result type is aggregate. 523static void build(OpBuilder &odsBuilder, OperationState &odsState, 524 ArrayRef<Type> resultTypes, 525 Value i32_operand, Value f32_operand, ..., 526 IntegerAttr i32_attr, FloatAttr f32_attr, ...); 527 528// All operands/attributes have aggregate parameters. 529// Generated if return type can be inferred. 530static void build(OpBuilder &odsBuilder, OperationState &odsState, 531 ValueRange operands, ArrayRef<NamedAttribute> attributes); 532 533// (And manually specified builders depending on the specific op.) 534``` 535 536The first form provides basic uniformity so that we can create ops using the 537same form regardless of the exact op. This is particularly useful for 538implementing declarative pattern rewrites. 539 540The second and third forms are good for use in manually written code given that 541they provide better guarantee via signatures. 542 543The third form will be generated if any of the op's attribute has different 544`Attr.returnType` from `Attr.storageType` and we know how to build an attribute 545from an unwrapped value (i.e., `Attr.constBuilderCall` is defined.) 546Additionally, for the third form, if an attribute appearing later in the 547`arguments` list has a default value, the default value will be supplied in the 548declaration. This works for `BoolAttr`, `StrAttr`, `EnumAttr` for now and the 549list can grow in the future. So if possible, default valued attribute should be 550placed at the end of the `arguments` list to leverage this feature. (This 551behavior is essentially due to C++ function parameter default value placement 552restrictions.) Otherwise, the builder of the third form will still be generated 553but default values for the attributes not at the end of the `arguments` list 554will not be supplied in the builder's signature. 555 556ODS will generate a builder that doesn't require return type specified if 557 558* Op implements InferTypeOpInterface interface; 559* All return types are either buildable types or are the same as a given 560 operand (e.g., `AllTypesMatch` constraint between operand and result); 561 562And there may potentially exist other builders depending on the specific op; 563please refer to the 564[generated C++ file](#run-mlir-tblgen-to-see-the-generated-content) for the 565complete list. 566 567#### Custom builder methods 568 569However, if the above cases cannot satisfy all needs, you can define additional 570convenience build methods with `OpBuilder`. 571 572`OpBuilder` is a class that takes the parameter list and the optional `build()` 573method body. They are separated because we need to generate op declaration and 574definition into separate files. The parameter list should not include `OpBuilder 575&builder, OperationState &state` as they will be inserted automatically and the 576placeholders `$_builder` and `$_state` used. For legacy/to be deprecated reason 577if the `OpBuilder` parameter starts with `OpBuilder` param, then the parameter 578is used. If the `body` is not provided, only the builder declaration will be 579generated; this provides a way to define complicated builders entirely in C++ 580files. 581 582For example, for the following op: 583 584```tablegen 585def MyOp : Op<"my_op", []> { 586 let arguments = (ins F32Attr:$attr); 587 588 let results = (outs); 589} 590``` 591 592If we want to define a builder with a default value for the only attribute, we 593can add into `MyOp`: 594 595```tablegen 596def MyOp : ... { 597 ... 598 599 let builders = [ 600 OpBuilder<"float val = 0.5f", [{ 601 $_state.addAttribute("attr", $_builder.getF32FloatAttr(val)); 602 }]> 603 ]; 604} 605``` 606 607The generated builder will look like: 608 609```c++ 610static void build(OpBuilder &builder, OperationState &state, float val = 0.5f) { 611 state.addAttribute("attr", builder.getF32FloatAttr(val)); 612} 613``` 614 615### Custom parser and printer methods 616 617Functions to parse and print the operation's custom assembly form. 618 619### Custom verifier code 620 621Verification code will be automatically generated for 622[constraints](#constraints) specified on various entities of the op. To 623perform _additional_ verification, you can use 624 625```tablegen 626let verifier = [{ 627 ... 628}]; 629``` 630 631Code placed in `verifier` will be called after the auto-generated verification 632code. The order of trait verification excluding those of `verifier` should not 633be relied upon. 634 635### Declarative Assembly Format 636 637The custom assembly form of the operation may be specified in a declarative 638string that matches the operations operands, attributes, etc. With the ability 639to express additional information that needs to be parsed to build the 640operation: 641 642```tablegen 643def CallOp : Std_Op<"call", ...> { 644 let arguments = (ins FlatSymbolRefAttr:$callee, Variadic<AnyType>:$args); 645 let results = (outs Variadic<AnyType>); 646 647 let assemblyFormat = [{ 648 $callee `(` $args `)` attr-dict `:` functional-type($args, results) 649 }]; 650} 651``` 652 653The format is comprised of three components: 654 655#### Directives 656 657A directive is a type of builtin function, with an optional set of arguments. 658The available directives are as follows: 659 660* `attr-dict` 661 662 - Represents the attribute dictionary of the operation. 663 664* `attr-dict-with-keyword` 665 666 - Represents the attribute dictionary of the operation, but prefixes the 667 dictionary with an `attributes` keyword. 668 669* `custom` < UserDirective > ( Params ) 670 671 - Represents a custom directive implemented by the user in C++. 672 - See the [Custom Directives](#custom-directives) section below for more 673 details. 674 675* `functional-type` ( inputs , results ) 676 677 - Formats the `inputs` and `results` arguments as a 678 [function type](LangRef.md#function-type). 679 - The constraints on `inputs` and `results` are the same as the `input` of 680 the `type` directive. 681 682* `operands` 683 684 - Represents all of the operands of an operation. 685 686* `regions` 687 688 - Represents all of the regions of an operation. 689 690* `results` 691 692 - Represents all of the results of an operation. 693 694* `successors` 695 696 - Represents all of the successors of an operation. 697 698* `type` ( input ) 699 700 - Represents the type of the given input. 701 - `input` must be either an operand or result [variable](#variables), the 702 `operands` directive, or the `results` directive. 703 704* `type_ref` ( input ) 705 706 - Represents a reference to the type of the given input that must have 707 already been resolved. 708 - `input` must be either an operand or result [variable](#variables), the 709 `operands` directive, or the `results` directive. 710 - Used to pass previously parsed types to custom directives. 711 712#### Literals 713 714A literal is either a keyword or punctuation surrounded by \`\`. 715 716The following are the set of valid punctuation: 717 718`:`, `,`, `=`, `<`, `>`, `(`, `)`, `{`, `}`, `[`, `]`, `->` 719 720#### Variables 721 722A variable is an entity that has been registered on the operation itself, i.e. 723an argument(attribute or operand), region, result, successor, etc. In the 724`CallOp` example above, the variables would be `$callee` and `$args`. 725 726Attribute variables are printed with their respective value type, unless that 727value type is buildable. In those cases, the type of the attribute is elided. 728 729#### Custom Directives 730 731The declarative assembly format specification allows for handling a large 732majority of the common cases when formatting an operation. For the operations 733that require or desire specifying parts of the operation in a form not supported 734by the declarative syntax, custom directives may be specified. A custom 735directive essentially allows for users to use C++ for printing and parsing 736subsections of an otherwise declaratively specified format. Looking at the 737specification of a custom directive above: 738 739``` 740custom-directive ::= `custom` `<` UserDirective `>` `(` Params `)` 741``` 742 743A custom directive has two main parts: The `UserDirective` and the `Params`. A 744custom directive is transformed into a call to a `print*` and a `parse*` method 745when generating the C++ code for the format. The `UserDirective` is an 746identifier used as a suffix to these two calls, i.e., `custom<MyDirective>(...)` 747would result in calls to `parseMyDirective` and `printMyDirective` wihtin the 748parser and printer respectively. `Params` may be any combination of variables 749(i.e. Attribute, Operand, Successor, etc.) and type directives. The type 750directives must refer to a variable, but that variable need not also be a 751parameter to the custom directive. 752 753The arguments to the `parse<UserDirective>` method is firstly a reference to the 754`OpAsmParser`(`OpAsmParser &`), and secondly a set of output parameters 755corresponding to the parameters specified in the format. The mapping of 756declarative parameter to `parse` method argument is detailed below: 757 758* Attribute Variables 759 - Single: `<Attribute-Storage-Type>(e.g. Attribute) &` 760 - Optional: `<Attribute-Storage-Type>(e.g. Attribute) &` 761* Operand Variables 762 - Single: `OpAsmParser::OperandType &` 763 - Optional: `Optional<OpAsmParser::OperandType> &` 764 - Variadic: `SmallVectorImpl<OpAsmParser::OperandType> &` 765* Region Variables 766 - Single: `Region &` 767 - Variadic: `SmallVectorImpl<std::unique_ptr<Region>> &` 768* Successor Variables 769 - Single: `Block *&` 770 - Variadic: `SmallVectorImpl<Block *> &` 771* Type Directives 772 - Single: `Type &` 773 - Optional: `Type &` 774 - Variadic: `SmallVectorImpl<Type> &` 775* TypeRef Directives 776 - Single: `Type` 777 - Optional: `Type` 778 - Variadic: `const SmallVectorImpl<Type> &` 779 780When a variable is optional, the value should only be specified if the variable 781is present. Otherwise, the value should remain `None` or null. 782 783The arguments to the `print<UserDirective>` method is firstly a reference to the 784`OpAsmPrinter`(`OpAsmPrinter &`), and secondly a set of output parameters 785corresponding to the parameters specified in the format. The mapping of 786declarative parameter to `print` method argument is detailed below: 787 788* Attribute Variables 789 - Single: `<Attribute-Storage-Type>(e.g. Attribute)` 790 - Optional: `<Attribute-Storage-Type>(e.g. Attribute)` 791* Operand Variables 792 - Single: `Value` 793 - Optional: `Value` 794 - Variadic: `OperandRange` 795* Region Variables 796 - Single: `Region &` 797 - Variadic: `MutableArrayRef<Region>` 798* Successor Variables 799 - Single: `Block *` 800 - Variadic: `SuccessorRange` 801* Type Directives 802 - Single: `Type` 803 - Optional: `Type` 804 - Variadic: `TypeRange` 805* TypeRef Directives 806 - Single: `Type` 807 - Optional: `Type` 808 - Variadic: `TypeRange` 809 810When a variable is optional, the provided value may be null. 811 812#### Optional Groups 813 814In certain situations operations may have "optional" information, e.g. 815attributes or an empty set of variadic operands. In these situations a section 816of the assembly format can be marked as `optional` based on the presence of this 817information. An optional group is defined by wrapping a set of elements within 818`()` followed by a `?` and has the following requirements: 819 820* The first element of the group must either be a attribute, literal, operand, 821 or region. 822 - This is because the first element must be optionally parsable. 823* Exactly one argument variable within the group must be marked as the anchor 824 of the group. 825 - The anchor is the element whose presence controls whether the group 826 should be printed/parsed. 827 - An element is marked as the anchor by adding a trailing `^`. 828 - The first element is *not* required to be the anchor of the group. 829 - When a non-variadic region anchors a group, the detector for printing 830 the group is if the region is empty. 831* Literals, variables, custom directives, and type directives are the only 832 valid elements within the group. 833 - Any attribute variable may be used, but only optional attributes can be 834 marked as the anchor. 835 - Only variadic or optional operand arguments can be used. 836 - All region variables can be used. When a non-variable length region is 837 used, if the group is not present the region is empty. 838 - The operands to a type directive must be defined within the optional 839 group. 840 841An example of an operation with an optional group is `std.return`, which has a 842variadic number of operands. 843 844```tablegen 845def ReturnOp : ... { 846 let arguments = (ins Variadic<AnyType>:$operands); 847 848 // We only print the operands and types if there are a non-zero number 849 // of operands. 850 let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?"; 851} 852``` 853 854##### Unit Attributes 855 856In MLIR, the [`unit` Attribute](LangRef.md#unit-attribute) is special in that it 857only has one possible value, i.e. it derives meaning from its existence. When a 858unit attribute is used to anchor an optional group and is not the first element 859of the group, the presence of the unit attribute can be directly correlated with 860the presence of the optional group itself. As such, in these situations the unit 861attribute will not be printed or present in the output and will be automatically 862inferred when parsing by the presence of the optional group itself. 863 864For example, the following operation: 865 866```tablegen 867def FooOp : ... { 868 let arguments = (ins UnitAttr:$is_read_only); 869 870 let assemblyFormat = "attr-dict (`is_read_only` $is_read_only^)?"; 871} 872``` 873 874would be formatted as such: 875 876```mlir 877// When the unit attribute is present: 878foo.op is_read_only 879 880// When the unit attribute is not present: 881foo.op 882``` 883 884#### Requirements 885 886The format specification has a certain set of requirements that must be adhered 887to: 888 8891. The output and operation name are never shown as they are fixed and cannot 890 be altered. 8911. All operands within the operation must appear within the format, either 892 individually or with the `operands` directive. 8931. All regions within the operation must appear within the format, either 894 individually or with the `regions` directive. 8951. All successors within the operation must appear within the format, either 896 individually or with the `successors` directive. 8971. All operand and result types must appear within the format using the various 898 `type` directives, either individually or with the `operands` or `results` 899 directives. 9001. The `attr-dict` directive must always be present. 9011. Must not contain overlapping information; e.g. multiple instances of 902 'attr-dict', types, operands, etc. 903 - Note that `attr-dict` does not overlap with individual attributes. These 904 attributes will simply be elided when printing the attribute dictionary. 905 906##### Type Inference 907 908One requirement of the format is that the types of operands and results must 909always be present. In certain instances, the type of a variable may be deduced 910via type constraints or other information available. In these cases, the type of 911that variable may be elided from the format. 912 913* Buildable Types 914 915Some type constraints may only have one representation, allowing for them to 916be directly buildable; for example the `I32` or `Index` types. Types in `ODS` 917may mark themselves as buildable by setting the `builderCall` field or 918inheriting from the `BuildableType` class. 919 920* Trait Equality Constraints 921 922There are many operations that have known type equality constraints registered 923as traits on the operation; for example the true, false, and result values of a 924`select` operation often have the same type. The assembly format may inspect 925these equal constraints to discern the types of missing variables. The currently 926supported traits are: `AllTypesMatch`, `TypesMatchWith`, `SameTypeOperands`, 927and `SameOperandsAndResultType`. 928 929### `hasCanonicalizer` 930 931This boolean field indicate whether canonicalization patterns have been defined 932for this operation. If it is `1`, then `::getCanonicalizationPatterns()` should 933be defined. 934 935### `hasFolder` 936 937This boolean field indicate whether general folding rules have been defined 938for this operation. If it is `1`, then `::fold()` should be defined. 939 940### Extra declarations 941 942One of the goals of table-driven op definition is to auto-generate as much logic 943and methods needed for each op as possible. With that said, there will always be 944long-tail cases that won't be covered. For such cases, you can use 945`extraClassDeclaration`. Code in `extraClassDeclaration` will be copied 946literally to the generated C++ op class. 947 948Note that `extraClassDeclaration` is a mechanism intended for long-tail cases 949by power users; for not-yet-implemented widely-applicable cases, improving the 950infrastructure is preferable. 951 952### Generated C++ code 953 954[OpDefinitionsGen][OpDefinitionsGen] processes the op definition spec file and 955generates two files containing the corresponding C++ code: one for declarations, 956the other for definitions. The former is generated via the `-gen-op-decls` 957command-line option, while the latter is via the `-gen-op-defs` option. 958 959The definition file contains all the op method definitions, which can be 960included and enabled by defining `GET_OP_CLASSES`. For each operation, 961OpDefinitionsGen generates an operation class and an 962[operand adaptor](#operand-adaptors) class. Besides, it also contains a 963comma-separated list of all defined ops, which can be included and enabled by 964defining `GET_OP_LIST`. 965 966#### Class name and namespaces 967 968For each operation, its generated C++ class name is the symbol `def`ed with 969TableGen with dialect prefix removed. The first `_` serves as the delimiter. 970For example, for `def TF_AddOp`, the C++ class name would be `AddOp`. 971We remove the `TF` prefix because it is for scoping ops; other dialects 972may as well define their own `AddOp`s. 973 974The namespaces of the generated C++ class will come from the dialect's 975`cppNamespace` field. For example, if a dialect's `cppNamespace` is `A::B`, 976then an op of that dialect will be placed in 977`namespace A { namespace B { ... } }`. If a dialect does not specify a 978`cppNamespace`, we then use the dialect's name as the namespace. 979 980This means the qualified name of the generated C++ class does not necessarily 981match exactly with the operation name as explained in 982[Operation name](#operation-name). This is to allow flexible naming to satisfy 983coding style requirements. 984 985#### Operand adaptors 986 987For each operation, we automatically generate an _operand adaptor_. This class 988solves the problem of accessing operands provided as a list of `Value`s without 989using "magic" constants. The operand adaptor takes a reference to an array of 990`Value` and provides methods with the same names as those in the operation class 991to access them. For example, for a binary arithmetic operation, it may provide 992`.lhs()` to access the first operand and `.rhs()` to access the second operand. 993 994The operand adaptor class lives in the same namespace as the operation class, 995and has the name of the operation followed by `Adaptor` as well as an alias 996`Adaptor` inside the op class. 997 998Operand adaptors can be used in function templates that also process operations: 999 1000```c++ 1001template <typename BinaryOpTy> 1002std::pair<Value, Value> zip(BinaryOpTy &&op) { 1003 return std::make_pair(op.lhs(), op.rhs());; 1004} 1005 1006void process(AddOp op, ArrayRef<Value> newOperands) { 1007 zip(op); 1008 zip(Adaptor<AddOp>(newOperands)); 1009 /*...*/ 1010} 1011``` 1012 1013## Constraints 1014 1015Constraint is a core concept in table-driven operation definition: operation 1016verification and graph operation matching are all based on satisfying 1017constraints. So both the operation definition and rewrite rules specification 1018significantly involve writing constraints. We have the `Constraint` class in 1019[`OpBase.td`][OpBase] has the common base class for all constraints. 1020 1021An operation's constraint can cover different range; it may 1022 1023* Only concern a single attribute (e.g. being a 32-bit integer greater than 5), 1024* Multiple operands and results (e.g., the 1st result's shape must be the same 1025 as the 1st operand), or 1026* Intrinsic to the operation itself (e.g., having no side effect). 1027 1028We call them as single-entity constraint, multi-entity constraint, and traits, 1029respectively. 1030 1031### Single-entity constraint 1032 1033Constraints scoped to a single operand, attribute, or result are specified at 1034the entity's declaration place as described in 1035[Operation arguments](#operation-arguments) and 1036[Operation results](#operation-results). 1037 1038To help modelling constraints of common types, a set of `TypeConstraint`s are 1039created; they are the `Type` subclass hierarchy. It includes `F32` for the 1040constraints of being a float, `TensorOf<[F32]>` for the constraints of being 1041a float tensor, and so on. 1042 1043Similarly, a set of `AttrConstraint`s are created for helping modelling 1044constraints of common attribute kinds. They are the `Attr` subclass hierarchy. 1045It includes `F32Attr` for the constraints of being a float attribute, 1046`F32ArrayAttr` for the constraints of being a float array attribute, and so on. 1047 1048### Multi-entity constraint 1049 1050Constraints involving more than one operand/attribute/result are quite common 1051on operations, like the element type and shape relation between operands and 1052results. These constraints should be specified as the `Op` class template 1053parameter as described in 1054[Operation traits and constraints](#operation-traits-and-constraints). 1055 1056Multi-entity constraints are modeled as `PredOpTrait` (a subclass of `OpTrait`) 1057in [`OpBase.td`][OpBase].A bunch of constraint primitives are provided to help 1058specification. See [`OpBase.td`][OpBase] for the complete list. 1059 1060### Trait 1061 1062Traits are intrinsic properties of the operation like having side effect or not, 1063commutative or not, whether is a terminator, etc. These constraints should be 1064specified as the `Op` class template parameter as described in 1065[Operation traits and constraints](#operation-traits-and-constraints). 1066 1067Traits are modeled as `NativeOpTrait` (a subclass of `OpTrait`) in 1068[`OpBase.td`][OpBase]. They are backed and will be translated into the 1069corresponding C++ `mlir::OpTrait` classes. 1070 1071### How to specify new constraint 1072 1073To write a constraint, you need to provide its predicates and give it a 1074descriptive name. Predicates, modeled with the `Pred` class, are the workhorse 1075for composing constraints. The predicate for a constraint is typically built up 1076in a nested manner, using the two categories of predicates: 1077 10781. `CPred`: the primitive leaf predicate. 10792. Compound predicate: a predicate composed from child predicates using 1080 predicate combiners (conjunction: `And`, disjunction: `Or`, negation: `Neg`, 1081 substitution: `SubstLeaves`, concatenation: `Concat`). 1082 1083`CPred` is the basis for composing more complex predicates. It is the "atom" 1084predicate from the perspective of TableGen and the "interface" between 1085TableGen and C++. What is inside is already C++ code, which will be treated 1086as opaque strings with special placeholders to be substituted. 1087 1088You can put any C++ code that returns a boolean value inside a `CPred`, 1089including evaluating expressions, calling functions, calling class methods, 1090and so on. 1091 1092To help interaction with the C++ environment, there are a few special 1093placeholders provided to refer to entities in the context where this predicate 1094is used. They serve as "hooks" to the enclosing environment. This includes 1095`$_builder`, `$_op`, and `$_self`: 1096 1097* `$_builder` will be replaced by a `mlir::Builder` instance so that you can 1098 access common build methods. 1099* `$_op` will be replaced by the current operation so that you can access 1100 information of the current operation. 1101* `$_self` will be replaced with the entity this predicate is attached to. 1102 E.g., `BoolAttr` is an attribute constraint that wraps a 1103 `CPred<"$_self.isa<BoolAttr>()">`. Then for `F32:$attr`,`$_self` will be 1104 replaced by `$attr`. For type constraints, it's a little bit special since 1105 we want the constraints on each type definition reads naturally and we want 1106 to attach type constraints directly to an operand/result, `$_self` will be 1107 replaced by the operand/result's type. E.g., for `F32` in `F32:$operand`, its 1108 `$_self` will be expanded as `getOperand(...).getType()`. 1109 1110TODO: Reconsider the leading symbol for special placeholders. Eventually we want 1111to allow referencing operand/result $-names; such $-names can start with 1112underscore. 1113 1114For example, to write an attribute `attr` is an `IntegerAttr`, in C++ you can 1115just call `attr.isa<IntegerAttr>()`. The code can be wrapped in a `CPred` as 1116`$_self.isa<IntegerAttr>()`, with `$_self` as the special placeholder to be 1117replaced by the current attribute `attr` at expansion time. 1118 1119For more complicated predicates, you can wrap it in a single `CPred`, or you 1120can use predicate combiners to combine them. For example, to write the 1121constraint that an attribute `attr` is a 32-bit or 64-bit integer, you can 1122write it as 1123 1124```tablegen 1125And<[ 1126 CPred<"$_self.isa<IntegerAttr>()">, 1127 Or<[ 1128 CPred<"$_self.cast<IntegerAttr>().getType().isInteger(32)">, 1129 CPred<"$_self.cast<IntegerAttr>().getType().isInteger(64)"> 1130 ]> 1131]> 1132``` 1133 1134(Note that the above is just to show with a familiar example how you can use 1135`CPred` and predicate combiners to write complicated predicates. For integer 1136attributes specifically, [`OpBase.td`][OpBase] already defines `I32Attr` and 1137`I64Attr`. So you can actually reuse them to write it as `Or<[I32Attr.predicate, 1138I64Attr.predicate]>`.) 1139 1140TODO: Build up a library of reusable primitive constraints 1141 1142If the predicate is very complex to write with `CPred` together with predicate 1143combiners, you can also write it as a normal C++ function and use the `CPred` 1144as a way to "invoke" the function. For example, to verify an attribute `attr` 1145has some property, you can write a C++ function like 1146 1147```cpp 1148bool HasSomeProperty(Attribute attr) { ... } 1149``` 1150 1151and then define the op as: 1152 1153```tablegen 1154def HasSomeProperty : AttrConstraint<CPred<"HasSomeProperty($_self)">, 1155 "has some property">; 1156 1157def MyOp : Op<...> { 1158 let arguments = (ins 1159 ... 1160 HasSomeProperty:$attr 1161 ); 1162} 1163``` 1164 1165As to whether we should define the predicate using a single `CPred` wrapping 1166the whole expression, multiple `CPred`s with predicate combiners, or a single 1167`CPred` "invoking" a function, there are no clear-cut criteria. Defining using 1168`CPred` and predicate combiners is preferable since it exposes more information 1169(instead hiding all the logic behind a C++ function) into the op definition spec 1170so that it can potentially drive more auto-generation cases. But it will 1171require a nice library of common predicates as the building blocks to avoid the 1172duplication, which is being worked on right now. 1173 1174## Attribute Definition 1175 1176An attribute is a compile-time known constant of an operation. 1177 1178ODS provides attribute wrappers over C++ attribute classes. There are a few 1179common C++ [attribute classes][AttrClasses] defined in MLIR's core IR library 1180and one is free to define dialect-specific attribute classes. ODS allows one 1181to use these attributes in TableGen to define operations, potentially with 1182more fine-grained constraints. For example, `StrAttr` directly maps to 1183`StringAttr`; `F32Attr`/`F64Attr` requires the `FloatAttr` to additionally 1184be of a certain bitwidth. 1185 1186ODS attributes are defined as having a storage type (corresponding to a backing 1187`mlir::Attribute` that _stores_ the attribute), a return type (corresponding to 1188the C++ _return_ type of the generated of the helper getters) as well as method 1189to convert between the internal storage and the helper method. 1190 1191### Attribute decorators 1192 1193There are a few important attribute adapters/decorators/modifiers that can be 1194applied to ODS attributes to specify common additional properties like 1195optionality, default values, etc.: 1196 1197* `DefaultValuedAttr`: specifies the 1198 [default value](#attributes-with-default-values) for an attribute. 1199* `OptionalAttr`: specifies an attribute as [optional](#optional-attributes). 1200* `Confined`: adapts an attribute with 1201 [further constraints](#confining-attributes). 1202 1203### Enum attributes 1204 1205Some attributes can only take values from a predefined enum, e.g., the 1206comparison kind of a comparison op. To define such attributes, ODS provides 1207several mechanisms: `StrEnumAttr`, `IntEnumAttr`, and `BitEnumAttr`. 1208 1209* `StrEnumAttr`: each enum case is a string, the attribute is stored as a 1210 [`StringAttr`][StringAttr] in the op. 1211* `IntEnumAttr`: each enum case is an integer, the attribute is stored as a 1212 [`IntegerAttr`][IntegerAttr] in the op. 1213* `BitEnumAttr`: each enum case is a bit, the attribute is stored as a 1214 [`IntegerAttr`][IntegerAttr] in the op. 1215 1216All these `*EnumAttr` attributes require fully specifying all of the allowed 1217cases via their corresponding `*EnumAttrCase`. With this, ODS is able to 1218generate additional verification to only accept allowed cases. To facilitate the 1219interaction between `*EnumAttr`s and their C++ consumers, the 1220[`EnumsGen`][EnumsGen] TableGen backend can generate a few common utilities: a 1221C++ enum class, `llvm::DenseMapInfo` for the enum class, conversion functions 1222from/to strings. This is controlled via the `-gen-enum-decls` and 1223`-gen-enum-defs` command-line options of `mlir-tblgen`. 1224 1225For example, given the following `EnumAttr`: 1226 1227```tablegen 1228def Case15: I32EnumAttrCase<"Case15", 15>; 1229def Case20: I32EnumAttrCase<"Case20", 20>; 1230 1231def MyIntEnum: I32EnumAttr<"MyIntEnum", "An example int enum", 1232 [Case15, Case20]> { 1233 let cppNamespace = "Outer::Inner"; 1234 let stringToSymbolFnName = "ConvertToEnum"; 1235 let symbolToStringFnName = "ConvertToString"; 1236} 1237``` 1238 1239The following will be generated via `mlir-tblgen -gen-enum-decls`: 1240 1241```c++ 1242namespace Outer { 1243namespace Inner { 1244// An example int enum 1245enum class MyIntEnum : uint32_t { 1246 Case15 = 15, 1247 Case20 = 20, 1248}; 1249 1250llvm::Optional<MyIntEnum> symbolizeMyIntEnum(uint32_t); 1251llvm::StringRef ConvertToString(MyIntEnum); 1252llvm::Optional<MyIntEnum> ConvertToEnum(llvm::StringRef); 1253inline constexpr unsigned getMaxEnumValForMyIntEnum() { 1254 return 20; 1255} 1256 1257} // namespace Inner 1258} // namespace Outer 1259 1260namespace llvm { 1261template<> struct DenseMapInfo<Outer::Inner::MyIntEnum> { 1262 using StorageInfo = llvm::DenseMapInfo<uint32_t>; 1263 1264 static inline Outer::Inner::MyIntEnum getEmptyKey() { 1265 return static_cast<Outer::Inner::MyIntEnum>(StorageInfo::getEmptyKey()); 1266 } 1267 1268 static inline Outer::Inner::MyIntEnum getTombstoneKey() { 1269 return static_cast<Outer::Inner::MyIntEnum>(StorageInfo::getTombstoneKey()); 1270 } 1271 1272 static unsigned getHashValue(const Outer::Inner::MyIntEnum &val) { 1273 return StorageInfo::getHashValue(static_cast<uint32_t>(val)); 1274 } 1275 1276 static bool isEqual(const Outer::Inner::MyIntEnum &lhs, const Outer::Inner::MyIntEnum &rhs) { 1277 return lhs == rhs; 1278 } 1279}; 1280} 1281``` 1282 1283The following will be generated via `mlir-tblgen -gen-enum-defs`: 1284 1285```c++ 1286namespace Outer { 1287namespace Inner { 1288llvm::StringRef ConvertToString(MyIntEnum val) { 1289 switch (val) { 1290 case MyIntEnum::Case15: return "Case15"; 1291 case MyIntEnum::Case20: return "Case20"; 1292 } 1293 return ""; 1294} 1295 1296llvm::Optional<MyIntEnum> ConvertToEnum(llvm::StringRef str) { 1297 return llvm::StringSwitch<llvm::Optional<MyIntEnum>>(str) 1298 .Case("Case15", MyIntEnum::Case15) 1299 .Case("Case20", MyIntEnum::Case20) 1300 .Default(llvm::None); 1301} 1302llvm::Optional<MyIntEnum> symbolizeMyIntEnum(uint32_t value) { 1303 switch (value) { 1304 case 15: return MyIntEnum::Case15; 1305 case 20: return MyIntEnum::Case20; 1306 default: return llvm::None; 1307 } 1308} 1309 1310} // namespace Inner 1311} // namespace Outer 1312``` 1313 1314Similarly for the following `BitEnumAttr` definition: 1315 1316```tablegen 1317def None: BitEnumAttrCase<"None", 0x0000>; 1318def Bit1: BitEnumAttrCase<"Bit1", 0x0001>; 1319def Bit2: BitEnumAttrCase<"Bit2", 0x0002>; 1320def Bit3: BitEnumAttrCase<"Bit3", 0x0004>; 1321 1322def MyBitEnum: BitEnumAttr<"MyBitEnum", "An example bit enum", 1323 [None, Bit1, Bit2, Bit3]>; 1324``` 1325 1326We can have: 1327 1328```c++ 1329// An example bit enum 1330enum class MyBitEnum : uint32_t { 1331 None = 0, 1332 Bit1 = 1, 1333 Bit2 = 2, 1334 Bit3 = 4, 1335}; 1336 1337llvm::Optional<MyBitEnum> symbolizeMyBitEnum(uint32_t); 1338std::string stringifyMyBitEnum(MyBitEnum); 1339llvm::Optional<MyBitEnum> symbolizeMyBitEnum(llvm::StringRef); 1340inline MyBitEnum operator|(MyBitEnum lhs, MyBitEnum rhs) { 1341 return static_cast<MyBitEnum>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs)); 1342} 1343inline MyBitEnum operator&(MyBitEnum lhs, MyBitEnum rhs) { 1344 return static_cast<MyBitEnum>(static_cast<uint32_t>(lhs) & static_cast<uint32_t>(rhs)); 1345} 1346inline bool bitEnumContains(MyBitEnum bits, MyBitEnum bit) { 1347 return (static_cast<uint32_t>(bits) & static_cast<uint32_t>(bit)) != 0; 1348} 1349 1350namespace llvm { 1351template<> struct DenseMapInfo<::MyBitEnum> { 1352 using StorageInfo = llvm::DenseMapInfo<uint32_t>; 1353 1354 static inline ::MyBitEnum getEmptyKey() { 1355 return static_cast<::MyBitEnum>(StorageInfo::getEmptyKey()); 1356 } 1357 1358 static inline ::MyBitEnum getTombstoneKey() { 1359 return static_cast<::MyBitEnum>(StorageInfo::getTombstoneKey()); 1360 } 1361 1362 static unsigned getHashValue(const ::MyBitEnum &val) { 1363 return StorageInfo::getHashValue(static_cast<uint32_t>(val)); 1364 } 1365 1366 static bool isEqual(const ::MyBitEnum &lhs, const ::MyBitEnum &rhs) { 1367 return lhs == rhs; 1368 } 1369}; 1370``` 1371 1372```c++ 1373std::string stringifyMyBitEnum(MyBitEnum symbol) { 1374 auto val = static_cast<uint32_t>(symbol); 1375 // Special case for all bits unset. 1376 if (val == 0) return "None"; 1377 1378 llvm::SmallVector<llvm::StringRef, 2> strs; 1379 if (1u & val) { strs.push_back("Bit1"); val &= ~1u; } 1380 if (2u & val) { strs.push_back("Bit2"); val &= ~2u; } 1381 if (4u & val) { strs.push_back("Bit3"); val &= ~4u; } 1382 1383 if (val) return ""; 1384 return llvm::join(strs, "|"); 1385} 1386 1387llvm::Optional<MyBitEnum> symbolizeMyBitEnum(llvm::StringRef str) { 1388 // Special case for all bits unset. 1389 if (str == "None") return MyBitEnum::None; 1390 1391 llvm::SmallVector<llvm::StringRef, 2> symbols; 1392 str.split(symbols, "|"); 1393 1394 uint32_t val = 0; 1395 for (auto symbol : symbols) { 1396 auto bit = llvm::StringSwitch<llvm::Optional<uint32_t>>(symbol) 1397 .Case("Bit1", 1) 1398 .Case("Bit2", 2) 1399 .Case("Bit3", 4) 1400 .Default(llvm::None); 1401 if (bit) { val |= *bit; } else { return llvm::None; } 1402 } 1403 return static_cast<MyBitEnum>(val); 1404} 1405 1406llvm::Optional<MyBitEnum> symbolizeMyBitEnum(uint32_t value) { 1407 // Special case for all bits unset. 1408 if (value == 0) return MyBitEnum::None; 1409 1410 if (value & ~(1u | 2u | 4u)) return llvm::None; 1411 return static_cast<MyBitEnum>(value); 1412} 1413``` 1414 1415## Type Definitions 1416 1417MLIR defines the TypeDef class hierarchy to enable generation of data types 1418from their specifications. A type is defined by specializing the TypeDef 1419class with concrete contents for all the fields it requires. For example, an 1420integer type could be defined as: 1421 1422```tablegen 1423// All of the types will extend this class. 1424class Test_Type<string name> : TypeDef<Test_Dialect, name> { } 1425 1426// An alternate int type. 1427def IntegerType : Test_Type<"TestInteger"> { 1428 let mnemonic = "int"; 1429 1430 let summary = "An integer type with special semantics"; 1431 1432 let description = [{ 1433 An alternate integer type. This type differentiates itself from the 1434 standard integer type by not having a SignednessSemantics parameter, just 1435 a width. 1436 }]; 1437 1438 let parameters = (ins "unsigned":$width); 1439 1440 // We define the printer inline. 1441 let printer = [{ 1442 $_printer << "int<" << getImpl()->width << ">"; 1443 }]; 1444 1445 // The parser is defined here also. 1446 let parser = [{ 1447 if (parser.parseLess()) 1448 return Type(); 1449 int width; 1450 if ($_parser.parseInteger(width)) 1451 return Type(); 1452 if ($_parser.parseGreater()) 1453 return Type(); 1454 return get(ctxt, width); 1455 }]; 1456``` 1457 1458### Type name 1459 1460The name of the C++ class which gets generated defaults to 1461`<classParamName>Type` (e.g. `TestIntegerType` in the above example). This 1462can be overridden via the the `cppClassName` field. The field `mnemonic` is 1463to specify the asm name for parsing. It is optional and not specifying it 1464will imply that no parser or printer methods are attached to this class. 1465 1466### Type documentation 1467 1468The `summary` and `description` fields exist and are to be used the same way 1469as in Operations. Namely, the summary should be a one-liner and `description` 1470should be a longer explanation. 1471 1472### Type parameters 1473 1474The `parameters` field is a list of the types parameters. If no parameters 1475are specified (the default), this type is considered a singleton type. 1476Parameters are in the `"c++Type":$paramName` format. 1477To use C++ types as parameters which need allocation in the storage 1478constructor, there are two options: 1479 1480- Set `hasCustomStorageConstructor` to generate the TypeStorage class with 1481a constructor which is just declared -- no definition -- so you can write it 1482yourself. 1483- Use the `TypeParameter` tablegen class instead of the "c++Type" string. 1484 1485### TypeParameter tablegen class 1486 1487This is used to further specify attributes about each of the types 1488parameters. It includes documentation (`description` and `syntax`), the C++ 1489type to use, and a custom allocator to use in the storage constructor method. 1490 1491```tablegen 1492// DO NOT DO THIS! 1493let parameters = (ins 1494 "ArrayRef<int>":$dims); 1495``` 1496 1497The default storage constructor blindly copies fields by value. It does not 1498know anything about the types. In this case, the ArrayRef<int> requires 1499allocation with `dims = allocator.copyInto(dims)`. 1500 1501You can specify the necessary constuctor by specializing the `TypeParameter` 1502tblgen class: 1503 1504```tablegen 1505class ArrayRefIntParam : 1506 TypeParameter<"::llvm::ArrayRef<int>", "Array of ints"> { 1507 let allocator = [{$_dst = $_allocator.copyInto($_self);}]; 1508} 1509 1510... 1511 1512let parameters = (ins 1513 ArrayRefIntParam:$dims); 1514``` 1515 1516The `allocator` code block has the following substitutions: 1517- `$_allocator` is the TypeStorageAllocator in which to allocate objects. 1518- `$_dst` is the variable in which to place the allocated data. 1519 1520MLIR includes several specialized classes for common situations: 1521- `StringRefParameter<descriptionOfParam>` for StringRefs. 1522- `ArrayRefParameter<arrayOf, descriptionOfParam>` for ArrayRefs of value 1523types 1524- `SelfAllocationParameter<descriptionOfParam>` for C++ classes which contain 1525a method called `allocateInto(StorageAllocator &allocator)` to allocate 1526itself into `allocator`. 1527- `ArrayRefOfSelfAllocationParameter<arrayOf, descriptionOfParam>` for arrays 1528of objects which self-allocate as per the last specialization. 1529 1530If we were to use one of these included specializations: 1531 1532```tablegen 1533let parameters = (ins 1534 ArrayRefParameter<"int", "The dimensions">:$dims 1535); 1536``` 1537 1538### Parsing and printing 1539 1540If a mnemonic is specified, the `printer` and `parser` code fields are active. 1541The rules for both are: 1542- If null, generate just the declaration. 1543- If non-null and non-empty, use the code in the definition. The `$_printer` 1544or `$_parser` substitutions are valid and should be used. 1545- It is an error to have an empty code block. 1546 1547For each dialect, two "dispatch" functions will be created: one for parsing 1548and one for printing. You should add calls to these in your 1549`Dialect::printType` and `Dialect::parseType` methods. They are created in 1550the dialect's namespace and their function signatures are: 1551```c++ 1552Type generatedTypeParser(MLIRContext* ctxt, DialectAsmParser& parser, 1553 StringRef mnemonic); 1554LogicalResult generatedTypePrinter(Type type, DialectAsmPrinter& printer); 1555``` 1556 1557The mnemonic, parser, and printer fields are optional. If they're not 1558defined, the generated code will not include any parsing or printing code and 1559omit the type from the dispatch functions above. In this case, the dialect 1560author is responsible for parsing/printing the types in `Dialect::printType` 1561and `Dialect::parseType`. 1562 1563### Other fields 1564 1565- If the `genStorageClass` field is set to 1 (the default) a storage class is 1566generated with member variables corresponding to each of the specified 1567`parameters`. 1568- If the `genAccessors` field is 1 (the default) accessor methods will be 1569generated on the Type class (e.g. `int getWidth() const` in the example 1570above). 1571- If the `genVerifyInvariantsDecl` field is set, a declaration for a method 1572`static LogicalResult verifyConstructionInvariants(Location, parameters...)` 1573is added to the class as well as a `getChecked(Location, parameters...)` 1574method which gets the result of `verifyConstructionInvariants` before calling 1575`get`. 1576- The `storageClass` field can be used to set the name of the storage class. 1577- The `storageNamespace` field is used to set the namespace where the storage 1578class should sit. Defaults to "detail". 1579- The `extraClassDeclaration` field is used to include extra code in the 1580class declaration. 1581 1582## Debugging Tips 1583 1584### Run `mlir-tblgen` to see the generated content 1585 1586TableGen syntax sometimes can be obscure; reading the generated content can be 1587a very helpful way to understand and debug issues. To build `mlir-tblgen`, run 1588`cmake --build . --target mlir-tblgen` in your build directory and find the 1589`mlir-tblgen` binary in the `bin/` subdirectory. All the supported generators 1590can be found via `mlir-tblgen --help`. For example, `--gen-op-decls` and 1591`--gen-op-defs` as explained in [Generated C++ code](#generated-c++-code). 1592 1593To see the generated code, invoke `mlir-tblgen` with a specific generator by 1594providing include paths via `-I`. For example, 1595 1596```sh 1597# To see op C++ class declaration 1598mlir-tblgen --gen-op-decls -I /path/to/mlir/include /path/to/input/td/file 1599# To see op C++ class definition 1600mlir-tblgen --gen-op-defs -I /path/to/mlir/include /path/to/input/td/file 1601# To see op documentation 1602mlir-tblgen --gen-dialect-doc -I /path/to/mlir/include /path/to/input/td/file 1603 1604# To see op interface C++ class declaration 1605mlir-tblgen --gen-op-interface-decls -I /path/to/mlir/include /path/to/input/td/file 1606# To see op interface C++ class definition 1607mlir-tblgen --gen-op-interface-defs -I /path/to/mlir/include /path/to/input/td/file 1608# To see op interface documentation 1609mlir-tblgen --gen-op-interface-doc -I /path/to/mlir/include /path/to/input/td/file 1610``` 1611 1612## Appendix 1613 1614### Requirements and existing mechanisms analysis 1615 1616The op description should as declarative as possible to allow a wide range of 1617tools to work with them and query methods generated from them. In particular 1618this means specifying traits, constraints and shape inference information in 1619a way that is easily analyzable (e.g., avoid opaque calls to C++ functions where 1620possible). 1621 1622We considered the approaches of several contemporary systems and focused on 1623requirements that were desirable: 1624 1625* Ops registered using a registry separate from C++ code. 1626 * Unknown ops are allowed in MLIR, so ops need not be registered. The 1627 ability of the compiler to optimize those ops or graphs containing those 1628 ops is constrained but correct. 1629 * The current proposal does not include a runtime op description, but it 1630 does not preclude such description, it can be added later. 1631 * The op registry is essential for generating C++ classes that make 1632 manipulating ops, verifying correct construction etc. in C++ easier by 1633 providing a typed representation and accessors. 1634* The op registry will be defined in 1635 [TableGen](https://llvm.org/docs/TableGen/index.html) and be used to 1636 generate C++ classes and utility functions 1637 (builder/verifier/parser/printer). 1638 * TableGen is a modelling specification language used by LLVM's backends 1639 and fits in well with trait-based modelling. This is an implementation 1640 decision and there are alternative ways of doing this. But the 1641 specification language is good for the requirements of modelling the 1642 traits (as seen from usage in LLVM processor backend modelling) and easy 1643 to extend, so a practical choice. If another good option comes up, we 1644 will consider it. 1645* MLIR allows both defined and undefined ops. 1646 * Defined ops should have fixed semantics and could have a corresponding 1647 reference implementation defined using, for example, EDSC. 1648 * Dialects are under full control of the dialect owner and normally live 1649 with the framework of the dialect. 1650* The op's traits (e.g., commutative) are modelled along with the op in the 1651 registry. 1652* The op's operand/return type constraints are modelled along with the op in 1653 the registry (see [Shape inference](ShapeInference.md) discussion below), 1654 this allows (e.g.) optimized concise syntax in textual dumps. 1655* Behavior of the op is documented along with the op with a summary and a 1656 description. The description is written in markdown and extracted for 1657 inclusion in the generated LangRef section of the dialect. 1658* The generic assembly form of printing and parsing is available as normal, 1659 but a custom parser and printer can either be specified or automatically 1660 generated from an optional string representation showing the mapping of the 1661 "assembly" string to operands/type. 1662 * Parser-level remappings (e.g., `eq` to enum) will be supported as part 1663 of the parser generation. 1664* Matching patterns are specified separately from the op description. 1665 * Contrasted with LLVM there is no "base" set of ops that every backend 1666 needs to be aware of. Instead there are many different dialects and the 1667 transformations/legalizations between these dialects form a graph of 1668 transformations. 1669* Reference implementation may be provided along with the op definition. 1670 1671 * The reference implementation may be in terms of either standard ops or 1672 other reference implementations. 1673 1674 TODO: document expectation if the dependent op's definition changes. 1675 1676[TableGen]: https://llvm.org/docs/TableGen/index.html 1677[TableGenProgRef]: https://llvm.org/docs/TableGen/ProgRef.html 1678[TableGenBackend]: https://llvm.org/docs/TableGen/BackEnds.html#introduction 1679[OpBase]: https://github.com/llvm/llvm-project/blob/master/mlir/include/mlir/IR/OpBase.td 1680[OpDefinitionsGen]: https://github.com/llvm/llvm-project/blob/master/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp 1681[EnumsGen]: https://github.com/llvm/llvm-project/blob/master/mlir/tools/mlir-tblgen/EnumsGen.cpp 1682[StringAttr]: LangRef.md#string-attribute 1683[IntegerAttr]: LangRef.md#integer-attribute 1684[AttrClasses]: https://github.com/llvm/llvm-project/blob/master/mlir/include/mlir/IR/Attributes.h 1685