1# Interfaces 2 3MLIR is a generic and extensible framework, representing different dialects with 4their own attributes, operations, types, and so on. MLIR Dialects can express 5operations with a wide variety of semantics and different levels of abstraction. 6The downside to this is that MLIR transformations and analyses need to be able 7to account for the semantics of every operation, or be overly conservative. 8Without care, this can result in code with special-cases for each supported 9operation type. To combat this, MLIR provides a concept of `interfaces`. 10 11[TOC] 12 13## Motivation 14 15Interfaces provide a generic way of interacting with the IR. The goal is to be 16able to express transformations/analyses in terms of these interfaces without 17encoding specific knowledge about the exact operation or dialect involved. This 18makes the compiler more easily extensible by allowing the addition of new 19dialects and operations in a decoupled way with respect to the implementation of 20transformations/analyses. 21 22### Dialect Interfaces 23 24Dialect interfaces are generally useful for transformation passes or analyses 25that want to operate generically on a set of attributes/operations/types, which 26may be defined in different dialects. These interfaces generally involve wide 27coverage over an entire dialect and are only used for a handful of analyses or 28transformations. In these cases, registering the interface directly on each 29operation is overly complex and cumbersome. The interface is not core to the 30operation, just to the specific transformation. An example of where this type of 31interface would be used is inlining. Inlining generally queries high-level 32information about the operations within a dialect, like cost modeling and 33legality, that often is not specific to one operation. 34 35A dialect interface can be defined by inheriting from the 36[CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) base 37class `DialectInterfaceBase::Base<>`. This class provides the necessary 38utilities for registering an interface with a dialect so that it can be 39referenced later. Once the interface has been defined, dialects can override it 40using dialect-specific information. The interfaces defined by a dialect are 41registered via `addInterfaces<>`, a similar mechanism to Attributes, Operations, 42Types, etc. 43 44```c++ 45/// Define a base inlining interface class to allow for dialects to opt-in to 46/// the inliner. 47class DialectInlinerInterface : 48 public DialectInterface::Base<DialectInlinerInterface> { 49public: 50 /// Returns true if the given region 'src' can be inlined into the region 51 /// 'dest' that is attached to an operation registered to the current dialect. 52 /// 'valueMapping' contains any remapped values from within the 'src' region. 53 /// This can be used to examine what values will replace entry arguments into 54 /// the 'src' region, for example. 55 virtual bool isLegalToInline(Region *dest, Region *src, 56 IRMapping &valueMapping) const { 57 return false; 58 } 59}; 60 61/// Override the inliner interface to add support for the AffineDialect to 62/// enable inlining affine operations. 63struct AffineInlinerInterface : public DialectInlinerInterface { 64 /// Affine structures have specific inlining constraints. 65 bool isLegalToInline(Region *dest, Region *src, 66 IRMapping &valueMapping) const final { 67 ... 68 } 69}; 70 71/// Register the interface with the dialect. 72AffineDialect::AffineDialect(MLIRContext *context) ... { 73 addInterfaces<AffineInlinerInterface>(); 74} 75``` 76 77Once registered, these interfaces can be queried from the dialect by an analysis 78or transformation without the need to determine the specific dialect subclass: 79 80```c++ 81Dialect *dialect = ...; 82if (DialectInlinerInterface *interface = dyn_cast<DialectInlinerInterface>(dialect)) { 83 // The dialect has provided an implementation of this interface. 84 ... 85} 86``` 87 88#### DialectInterfaceCollection 89 90An additional utility is provided via `DialectInterfaceCollection`. This class 91allows collecting all of the dialects that have registered a given interface 92within an instance of the `MLIRContext`. This can be useful to hide and optimize 93the lookup of a registered dialect interface. 94 95```c++ 96class InlinerInterface : public 97 DialectInterfaceCollection<DialectInlinerInterface> { 98 /// The hooks for this class mirror the hooks for the DialectInlinerInterface, 99 /// with default implementations that call the hook on the interface for a 100 /// given dialect. 101 virtual bool isLegalToInline(Region *dest, Region *src, 102 IRMapping &valueMapping) const { 103 auto *handler = getInterfaceFor(dest->getContainingOp()); 104 return handler ? handler->isLegalToInline(dest, src, valueMapping) : false; 105 } 106}; 107 108MLIRContext *ctx = ...; 109InlinerInterface interface(ctx); 110if(!interface.isLegalToInline(...)) 111 ... 112``` 113 114### Attribute/Operation/Type Interfaces 115 116Attribute/Operation/Type interfaces, as the names suggest, are those registered 117at the level of a specific attribute/operation/type. These interfaces provide 118access to derived objects by providing a virtual interface that must be 119implemented. As an example, many analyses and transformations want to reason 120about the side effects of an operation to improve performance and correctness. 121The side effects of an operation are generally tied to the semantics of a 122specific operation, for example an `affine.load` operation has a `read` effect 123(as the name may suggest). 124 125These interfaces are defined by overriding the 126[CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) class 127for the specific IR entity; `AttrInterface`, `OpInterface`, or `TypeInterface` 128respectively. These classes take, as a template parameter, a `Traits` class that 129defines a `Concept` and a `Model` class. These classes provide an implementation 130of concept-based polymorphism, where the `Concept` defines a set of virtual 131methods that are overridden by the `Model` that is templated on the concrete 132entity type. It is important to note that these classes should be pure, and 133should not contain non-static data members or other mutable data. To attach an 134interface to an object, the base interface classes provide a 135[`Trait`](Traits) class that can be appended to the trait list of that 136object. 137 138```c++ 139struct ExampleOpInterfaceTraits { 140 /// Define a base concept class that specifies the virtual interface to be 141 /// implemented. 142 struct Concept { 143 virtual ~Concept(); 144 145 /// This is an example of a non-static hook to an operation. 146 virtual unsigned exampleInterfaceHook(Operation *op) const = 0; 147 148 /// This is an example of a static hook to an operation. A static hook does 149 /// not require a concrete instance of the operation. The implementation is 150 /// a virtual hook, the same as the non-static case, because the 151 /// implementation of the hook itself still requires indirection. 152 virtual unsigned exampleStaticInterfaceHook() const = 0; 153 }; 154 155 /// Define a model class that specializes a concept on a given operation type. 156 template <typename ConcreteOp> 157 struct Model : public Concept { 158 /// Override the method to dispatch on the concrete operation. 159 unsigned exampleInterfaceHook(Operation *op) const final { 160 return llvm::cast<ConcreteOp>(op).exampleInterfaceHook(); 161 } 162 163 /// Override the static method to dispatch to the concrete operation type. 164 unsigned exampleStaticInterfaceHook() const final { 165 return ConcreteOp::exampleStaticInterfaceHook(); 166 } 167 }; 168}; 169 170/// Define the main interface class that analyses and transformations will 171/// interface with. 172class ExampleOpInterface : public OpInterface<ExampleOpInterface, 173 ExampleOpInterfaceTraits> { 174public: 175 /// Inherit the base class constructor to support LLVM-style casting. 176 using OpInterface<ExampleOpInterface, ExampleOpInterfaceTraits>::OpInterface; 177 178 /// The interface dispatches to 'getImpl()', a method provided by the base 179 /// `OpInterface` class that returns an instance of the concept. 180 unsigned exampleInterfaceHook() const { 181 return getImpl()->exampleInterfaceHook(getOperation()); 182 } 183 unsigned exampleStaticInterfaceHook() const { 184 return getImpl()->exampleStaticInterfaceHook(getOperation()->getName()); 185 } 186}; 187 188``` 189 190Once the interface has been defined, it is registered to an operation by adding 191the provided trait `ExampleOpInterface::Trait` as described earlier. Using this 192interface is just like using any other derived operation type, i.e. casting: 193 194```c++ 195/// When defining the operation, the interface is registered via the nested 196/// 'Trait' class provided by the 'OpInterface<>' base class. 197class MyOp : public Op<MyOp, ExampleOpInterface::Trait> { 198public: 199 /// The definition of the interface method on the derived operation. 200 unsigned exampleInterfaceHook() { return ...; } 201 static unsigned exampleStaticInterfaceHook() { return ...; } 202}; 203 204/// Later, we can query if a specific operation(like 'MyOp') overrides the given 205/// interface. 206Operation *op = ...; 207if (ExampleOpInterface example = dyn_cast<ExampleOpInterface>(op)) 208 llvm::errs() << "hook returned = " << example.exampleInterfaceHook() << "\n"; 209``` 210 211#### External Models for Attribute, Operation and Type Interfaces 212 213It may be desirable to provide an interface implementation for an IR object 214without modifying the definition of said object. Notably, this allows to 215implement interfaces for attributes, operations and types outside of the dialect 216that defines them, for example, to provide interfaces for built-in types. 217 218This is achieved by extending the concept-based polymorphism model with two more 219classes derived from `Concept` as follows. 220 221```c++ 222struct ExampleTypeInterfaceTraits { 223 struct Concept { 224 virtual unsigned exampleInterfaceHook(Type type) const = 0; 225 virtual unsigned exampleStaticInterfaceHook() const = 0; 226 }; 227 228 template <typename ConcreteType> 229 struct Model : public Concept { /*...*/ }; 230 231 /// Unlike `Model`, `FallbackModel` passes the type object through to the 232 /// hook, making it accessible in the method body even if the method is not 233 /// defined in the class itself and thus has no `this` access. ODS 234 /// automatically generates this class for all interfaces. 235 template <typename ConcreteType> 236 struct FallbackModel : public Concept { 237 unsigned exampleInterfaceHook(Type type) const override { 238 getImpl()->exampleInterfaceHook(type); 239 } 240 unsigned exampleStaticInterfaceHook() const override { 241 ConcreteType::exampleStaticInterfaceHook(); 242 } 243 }; 244 245 /// `ExternalModel` provides a place for default implementations of interface 246 /// methods by explicitly separating the model class, which implements the 247 /// interface, from the type class, for which the interface is being 248 /// implemented. Default implementations can be then defined generically 249 /// making use of `cast<ConcreteType>`. If `ConcreteType` does not provide 250 /// the APIs required by the default implementation, custom implementations 251 /// may use `FallbackModel` directly to override the default implementation. 252 /// Being located in a class template, it never gets instantiated and does not 253 /// lead to compilation errors. ODS automatically generates this class and 254 /// places default method implementations in it. 255 template <typename ConcreteModel, typename ConcreteType> 256 struct ExternalModel : public FallbackModel<ConcreteModel> { 257 unsigned exampleInterfaceHook(Type type) const override { 258 // Default implementation can be provided here. 259 return type.cast<ConcreteType>().callSomeTypeSpecificMethod(); 260 } 261 }; 262}; 263``` 264 265External models can be provided for attribute, operation and type interfaces by 266deriving either `FallbackModel` or `ExternalModel` and by registering the model 267class with the relevant class in a given context. Other contexts will not see 268the interface unless registered. 269 270```c++ 271/// External interface implementation for a concrete class. This does not 272/// require modifying the definition of the type class itself. 273struct ExternalModelExample 274 : public ExampleTypeInterface::ExternalModel<ExternalModelExample, 275 IntegerType> { 276 static unsigned exampleStaticInterfaceHook() { 277 // Implementation is provided here. 278 return IntegerType::someStaticMethod(); 279 } 280 281 // No need to define `exampleInterfaceHook` that has a default implementation 282 // in `ExternalModel`. But it can be overridden if desired. 283} 284 285int main() { 286 MLIRContext context; 287 /* ... */; 288 289 // Attach the interface model to the type in the given context before 290 // using it. The dialect containing the type is expected to have been loaded 291 // at this point. 292 IntegerType::attachInterface<ExternalModelExample>(context); 293} 294``` 295 296Note: It is strongly encouraged to only use this mechanism if you "own" the 297interface being externally applied. This prevents a situation where neither the 298owner of the dialect containing the object nor the owner of the interface are 299aware of an interface implementation, which can lead to duplicate or 300diverging implementations. 301 302Forgetting to register an external model can lead to bugs which are hard to 303track down. The `declarePromisedInterface` function can be used to declare that 304an external model implementation for an operation must eventually be provided. 305 306``` 307 void MyDialect::initialize() { 308 declarePromisedInterface<SomeInterface, SomeOp>(); 309 ... 310 } 311``` 312 313Now attempting to use the interface, e.g in a cast, without a prior registration 314of the external model will lead to a runtime error that will look similar to 315this: 316 317``` 318LLVM ERROR: checking for an interface (`SomeInterface`) that was promised by dialect 'mydialect' but never implemented. This is generally an indication that the dialect extension implementing the interface was never registered. 319``` 320 321If you encounter this error for a dialect and an interface provided by MLIR, you 322may look for a method that will be named like 323`register<Dialect><Interface>ExternalModels(DialectRegistry ®istry);` ; try 324to find it with `git grep 'register.*SomeInterface.*Model' mlir`. 325 326#### Dialect Fallback for OpInterface 327 328Some dialects have an open ecosystem and don't register all of the possible 329operations. In such cases it is still possible to provide support for 330implementing an `OpInterface` for these operation. When an operation isn't 331registered or does not provide an implementation for an interface, the query 332will fallback to the dialect itself. 333 334A second model is used for such cases and automatically generated when using ODS 335(see below) with the name `FallbackModel`. This model can be implemented for a 336particular dialect: 337 338```c++ 339// This is the implementation of a dialect fallback for `ExampleOpInterface`. 340struct FallbackExampleOpInterface 341 : public ExampleOpInterface::FallbackModel< 342 FallbackExampleOpInterface> { 343 static bool classof(Operation *op) { return true; } 344 345 unsigned exampleInterfaceHook(Operation *op) const; 346 unsigned exampleStaticInterfaceHook() const; 347}; 348``` 349 350A dialect can then instantiate this implementation and returns it on specific 351operations by overriding the `getRegisteredInterfaceForOp` method : 352 353```c++ 354void *TestDialect::getRegisteredInterfaceForOp(TypeID typeID, 355 StringAttr opName) { 356 if (typeID == TypeID::get<ExampleOpInterface>()) { 357 if (isSupported(opName)) 358 return fallbackExampleOpInterface; 359 return nullptr; 360 } 361 return nullptr; 362} 363``` 364 365#### Utilizing the ODS Framework 366 367Note: Before reading this section, the reader should have some familiarity with 368the concepts described in the 369[`Operation Definition Specification`](DefiningDialects/Operations.md) documentation. 370 371As detailed above, [Interfaces](#attributeoperationtype-interfaces) allow for 372attributes, operations, and types to expose method calls without requiring that 373the caller know the specific derived type. The downside to this infrastructure, 374is that it requires a bit of boiler plate to connect all of the pieces together. 375MLIR provides a mechanism with which to defines interfaces declaratively in ODS, 376and have the C++ definitions auto-generated. 377 378As an example, using the ODS framework would allow for defining the example 379interface above as: 380 381```tablegen 382def ExampleOpInterface : OpInterface<"ExampleOpInterface"> { 383 let description = [{ 384 This is an example interface definition. 385 }]; 386 387 let methods = [ 388 InterfaceMethod< 389 "This is an example of a non-static hook to an operation.", 390 "unsigned", "exampleInterfaceHook" 391 >, 392 StaticInterfaceMethod< 393 "This is an example of a static hook to an operation.", 394 "unsigned", "exampleStaticInterfaceHook" 395 >, 396 ]; 397} 398``` 399 400Providing a definition of the `AttrInterface`, `OpInterface`, or `TypeInterface` 401class will auto-generate the C++ classes for the interface. Interfaces are 402comprised of the following components: 403 404* C++ Class Name (Provided via template parameter) 405 - The name of the C++ interface class. 406* Interface Base Classes 407 - A set of interfaces that the interface class should derived from. See 408 [Interface Inheritance](#interface-inheritance) below for more details. 409* Description (`description`) 410 - A string description of the interface, its invariants, example usages, 411 etc. 412* C++ Namespace (`cppNamespace`) 413 - The C++ namespace that the interface class should be generated in. 414* Methods (`methods`) 415 - The list of interface hook methods that are defined by the IR object. 416 - The structure of these methods is defined below. 417* Extra Class Declarations (Optional: `extraClassDeclaration`) 418 - Additional C++ code that is generated in the declaration of the 419 interface class. This allows for defining methods and more on the user 420 facing interface class, that do not need to hook into the IR entity. 421 These declarations are _not_ implicitly visible in default 422 implementations of interface methods, but static declarations may be 423 accessed with full name qualification. 424* Extra Shared Class Declarations (Optional: `extraSharedClassDeclaration`) 425 - Additional C++ code that is injected into the declarations of both the 426 interface and the trait class. This allows for defining methods and more 427 that are exposed on both the interface and the trait class, e.g. to inject 428 utilities on both the interface and the derived entity implementing the 429 interface (e.g. attribute, operation, etc.). 430 - In non-static methods, `$_attr`/`$_op`/`$_type` 431 (depending on the type of interface) may be used to refer to an 432 instance of the IR entity. In the interface declaration, the type of 433 the instance is the interface class. In the trait declaration, the 434 type of the instance is the concrete entity class 435 (e.g. `IntegerAttr`, `FuncOp`, etc.). 436* Extra Trait Class Declarations (Optional: `extraTraitClassDeclaration`) 437 - Additional C++ code that is injected into the interface trait 438 declaration. 439 - Allows the same replacements as extra shared class declarations. 440 441`OpInterface` classes may additionally contain the following: 442 443* Verifier (`verify`) 444 - A C++ code block containing additional verification applied to the 445 operation that the interface is attached to. 446 - The structure of this code block corresponds 1-1 with the structure of a 447 [`Trait::verifyTrait`](Traits) method. 448 449##### Interface Methods 450 451There are two types of methods that can be used with an interface, 452`InterfaceMethod` and `StaticInterfaceMethod`. They are both comprised of the 453same core components, with the distinction that `StaticInterfaceMethod` models a 454static method on the derived IR object. 455 456Interface methods are comprised of the following components: 457 458* Description 459 - A string description of this method, its invariants, example usages, 460 etc. 461* ReturnType 462 - A string corresponding to the C++ return type of the method. 463* MethodName 464 - A string corresponding to the C++ name of the method. 465* Arguments (Optional) 466 - A dag of strings that correspond to a C++ type and variable name 467 respectively. 468* MethodBody (Optional) 469 - An optional explicit implementation of the interface method. 470 - This implementation is placed within the method defined on the `Model` 471 traits class, and is not defined by the `Trait` class that is attached 472 to the IR entity. More concretely, this body is only visible by the 473 interface class and does not affect the derived IR entity. 474 - `ConcreteAttr`/`ConcreteOp`/`ConcreteType` is an implicitly defined 475 `typename` that can be used to refer to the type of the derived IR 476 entity currently being operated on. 477 - In non-static methods, `$_op` and `$_self` may be used to refer to an 478 instance of the derived IR entity. 479* DefaultImplementation (Optional) 480 - An optional explicit default implementation of the interface method. 481 - This implementation is placed within the `Trait` class that is attached 482 to the IR entity, and does not directly affect any of the interface 483 classes. As such, this method has the same characteristics as any other 484 [`Trait`](Traits) method. 485 - `ConcreteAttr`/`ConcreteOp`/`ConcreteType` is an implicitly defined 486 `typename` that can be used to refer to the type of the derived IR 487 entity currently being operated on. 488 - This may refer to static fields of the interface class using the 489 qualified name, e.g., `TestOpInterface::staticMethod()`. 490 491ODS also allows for generating declarations for the `InterfaceMethod`s of an 492operation if the operation specifies the interface with 493`DeclareOpInterfaceMethods` (see an example below). 494 495Examples: 496 497```tablegen 498def MyInterface : OpInterface<"MyInterface"> { 499 let description = [{ 500 This is the description of the interface. It provides concrete information 501 on the semantics of the interface, and how it may be used by the compiler. 502 }]; 503 504 let methods = [ 505 InterfaceMethod<[{ 506 This method represents a simple non-static interface method with no 507 inputs, and a void return type. This method is required to be implemented 508 by all operations implementing this interface. This method roughly 509 correlates to the following on an operation implementing this interface: 510 511 ```c++ 512 class ConcreteOp ... { 513 public: 514 void nonStaticMethod(); 515 }; 516 ``` 517 }], "void", "nonStaticMethod" 518 >, 519 520 InterfaceMethod<[{ 521 This method represents a non-static interface method with a non-void 522 return value, as well as an `unsigned` input named `i`. This method is 523 required to be implemented by all operations implementing this interface. 524 This method roughly correlates to the following on an operation 525 implementing this interface: 526 527 ```c++ 528 class ConcreteOp ... { 529 public: 530 Value nonStaticMethod(unsigned i); 531 }; 532 ``` 533 }], "Value", "nonStaticMethodWithParams", (ins "unsigned":$i) 534 >, 535 536 StaticInterfaceMethod<[{ 537 This method represents a static interface method with no inputs, and a 538 void return type. This method is required to be implemented by all 539 operations implementing this interface. This method roughly correlates 540 to the following on an operation implementing this interface: 541 542 ```c++ 543 class ConcreteOp ... { 544 public: 545 static void staticMethod(); 546 }; 547 ``` 548 }], "void", "staticMethod" 549 >, 550 551 StaticInterfaceMethod<[{ 552 This method corresponds to a static interface method that has an explicit 553 implementation of the method body. Given that the method body has been 554 explicitly implemented, this method should not be defined by the operation 555 implementing this method. This method merely takes advantage of properties 556 already available on the operation, in this case its `build` methods. This 557 method roughly correlates to the following on the interface `Model` class: 558 559 ```c++ 560 struct InterfaceTraits { 561 /// ... The `Concept` class is elided here ... 562 563 template <typename ConcreteOp> 564 struct Model : public Concept { 565 Operation *create(OpBuilder &builder, Location loc) const override { 566 return builder.create<ConcreteOp>(loc); 567 } 568 } 569 }; 570 ``` 571 572 Note above how no modification is required for operations implementing an 573 interface with this method. 574 }], 575 "Operation *", "create", (ins "OpBuilder &":$builder, "Location":$loc), 576 /*methodBody=*/[{ 577 return builder.create<ConcreteOp>(loc); 578 }]>, 579 580 InterfaceMethod<[{ 581 This method represents a non-static method that has an explicit 582 implementation of the method body. Given that the method body has been 583 explicitly implemented, this method should not be defined by the operation 584 implementing this method. This method merely takes advantage of properties 585 already available on the operation, in this case its `build` methods. This 586 method roughly correlates to the following on the interface `Model` class: 587 588 ```c++ 589 struct InterfaceTraits { 590 /// ... The `Concept` class is elided here ... 591 592 template <typename ConcreteOp> 593 struct Model : public Concept { 594 unsigned getNumInputsAndOutputs(Operation *opaqueOp) const override { 595 ConcreteOp op = cast<ConcreteOp>(opaqueOp); 596 return op.getNumInputs() + op.getNumOutputs(); 597 } 598 } 599 }; 600 ``` 601 602 Note above how no modification is required for operations implementing an 603 interface with this method. 604 }], 605 "unsigned", "getNumInputsAndOutputs", (ins), /*methodBody=*/[{ 606 return $_op.getNumInputs() + $_op.getNumOutputs(); 607 }]>, 608 609 InterfaceMethod<[{ 610 This method represents a non-static method that has a default 611 implementation of the method body. This means that the implementation 612 defined here will be placed in the trait class that is attached to every 613 operation that implements this interface. This has no effect on the 614 generated `Concept` and `Model` class. This method roughly correlates to 615 the following on the interface `Trait` class: 616 617 ```c++ 618 template <typename ConcreteOp> 619 class MyTrait : public OpTrait::TraitBase<ConcreteType, MyTrait> { 620 public: 621 bool isSafeToTransform() { 622 ConcreteOp op = cast<ConcreteOp>(this->getOperation()); 623 return op.getProperties().hasFlag; 624 } 625 }; 626 ``` 627 628 As detailed in [Traits](Traits), given that each operation implementing 629 this interface will also add the interface trait, the methods on this 630 interface are inherited by the derived operation. This allows for 631 injecting a default implementation of this method into each operation that 632 implements this interface, without changing the interface class itself. If 633 an operation wants to override this default implementation, it merely 634 needs to implement the method and the derived implementation will be 635 picked up transparently by the interface class. 636 637 ```c++ 638 class ConcreteOp ... { 639 public: 640 bool isSafeToTransform() { 641 // Here we can override the default implementation of the hook 642 // provided by the trait. 643 } 644 }; 645 ``` 646 }], 647 "bool", "isSafeToTransform", (ins), /*methodBody=*/[{}], 648 /*defaultImplementation=*/[{ 649 return $_op.getProperties().hasFlag; 650 }]>, 651 ]; 652} 653 654// Operation interfaces can optionally be wrapped inside 655// `DeclareOpInterfaceMethods`. This would result in autogenerating declarations 656// for members `foo`, `bar` and `fooStatic`. Methods with bodies are not 657// declared inside the op declaration but instead handled by the op interface 658// trait directly. 659def OpWithInferTypeInterfaceOp : Op<... 660 [DeclareOpInterfaceMethods<MyInterface>]> { ... } 661 662// Methods that have a default implementation do not have declarations 663// generated. If an operation wishes to override the default behavior, it can 664// explicitly specify the method that it wishes to override. This will force 665// the generation of a declaration for those methods. 666def OpWithOverrideInferTypeInterfaceOp : Op<... 667 [DeclareOpInterfaceMethods<MyInterface, ["getNumWithDefault"]>]> { ... } 668``` 669 670##### Interface Inheritance 671 672Interfaces also support a limited form of inheritance, which allows for 673building upon pre-existing interfaces in a way similar to that of classes in 674programming languages like C++. This more easily allows for building modular 675interfaces, without suffering from the pain of lots of explicit casting. To 676enable inheritance, an interface simply needs to provide the desired set of 677base classes in its definition. For example: 678 679```tablegen 680def MyBaseInterface : OpInterface<"MyBaseInterface"> { 681 ... 682} 683 684def MyInterface : OpInterface<"MyInterface", [MyBaseInterface]> { 685 ... 686} 687``` 688 689This will result in `MyInterface` inheriting various components from 690`MyBaseInterface`, namely its interface methods and extra class declarations. 691Given that these inherited components are comprised of opaque C++ blobs, we 692cannot properly sandbox the names. As such, it's important to ensure that inherited 693components do not create name overlaps, as these will result in errors during 694interface generation. 695 696`MyInterface` will also implicitly inherit any base classes defined on 697`MyBaseInterface` as well. It's important to note, however, that there is only 698ever one instance of each interface for a given attribute, operation, or type. 699Inherited interface methods simplify forward to base interface implementation. 700This produces a simpler system overall, and also removes any potential problems 701surrounding "diamond inheritance". The interfaces on an attribute/op/type can be 702thought of as comprising a set, with each interface (including base interfaces) 703uniqued within this set and referenced elsewhere as necessary. 704 705When adding an interface with inheritance to an attribute, operation, or type, 706all of the base interfaces are also implicitly added as well. The user may still 707manually specify the base interfaces if they desire, such as for use with the 708`Declare<Attr|Op|Type>InterfaceMethods` helper classes. 709 710If our interface were to be specified as: 711 712```tablegen 713def MyBaseInterface : OpInterface<"MyBaseInterface"> { 714 ... 715} 716 717def MyOtherBaseInterface : OpInterface<MyOtherBaseInterface, [MyBaseInterface]> { 718 ... 719} 720 721def MyInterface : OpInterface<"MyInterface", [MyBaseInterface, MyOtherBaseInterface]> { 722 ... 723} 724``` 725 726An operation with `MyInterface` attached, would have the following interfaces added: 727 728* MyBaseInterface, MyOtherBaseInterface, MyInterface 729 730The methods from `MyBaseInterface` in both `MyInterface` and `MyOtherBaseInterface` would 731forward to a single unique implementation for the operation. 732 733##### Generation 734 735Once the interfaces have been defined, the C++ header and source files can be 736generated using the `--gen-<attr|op|type>-interface-decls` and 737`--gen-<attr|op|type>-interface-defs` options with mlir-tblgen. Note that when 738generating interfaces, mlir-tblgen will only generate interfaces defined in 739the top-level input `.td` file. This means that any interfaces that are 740defined within include files will not be considered for generation. 741 742Note: Existing operation interfaces defined in C++ can be accessed in the ODS 743framework via the `OpInterfaceTrait` class. 744 745#### Operation Interface List 746 747MLIR includes standard interfaces providing functionality that is likely to be 748common across many different operations. Below is a list of some key interfaces 749that may be used directly by any dialect. The format of the header for each 750interface section goes as follows: 751 752* `Interface class name` 753 - (`C++ class` -- `ODS class`(if applicable)) 754 755##### CallInterfaces 756 757* `CallOpInterface` - Used to represent operations like 'call' 758 - `CallInterfaceCallable getCallableForCallee()` 759 - `void setCalleeFromCallable(CallInterfaceCallable)` 760* `CallableOpInterface` - Used to represent the target callee of call. 761 - `Region * getCallableRegion()` 762 - `ArrayRef<Type> getArgumentTypes()` 763 - `ArrayRef<Type> getResultsTypes()` 764 - `ArrayAttr getArgAttrsAttr()` 765 - `ArrayAttr getResAttrsAttr()` 766 - `void setArgAttrsAttr(ArrayAttr)` 767 - `void setResAttrsAttr(ArrayAttr)` 768 - `Attribute removeArgAttrsAttr()` 769 - `Attribute removeResAttrsAttr()` 770 771##### RegionKindInterfaces 772 773* `RegionKindInterface` - Used to describe the abstract semantics of regions. 774 - `RegionKind getRegionKind(unsigned index)` - Return the kind of the 775 region with the given index inside this operation. 776 - RegionKind::Graph - represents a graph region without control flow 777 semantics 778 - RegionKind::SSACFG - represents an 779 [SSA-style control flow](LangRef.md/#control-flow-and-ssacfg-regions) region 780 with basic blocks and reachability 781 - `hasSSADominance(unsigned index)` - Return true if the region with the 782 given index inside this operation requires dominance. 783 784##### SymbolInterfaces 785 786* `SymbolOpInterface` - Used to represent 787 [`Symbol`](SymbolsAndSymbolTables.md/#symbol) operations which reside 788 immediately within a region that defines a 789 [`SymbolTable`](SymbolsAndSymbolTables.md/#symbol-table). 790 791* `SymbolUserOpInterface` - Used to represent operations that reference 792 [`Symbol`](SymbolsAndSymbolTables.md/#symbol) operations. This provides the 793 ability to perform safe and efficient verification of symbol uses, as well 794 as additional functionality. 795