1# Pass Infrastructure 2 3[TOC] 4 5Passes represent the basic infrastructure for transformation and optimization. 6This document provides an overview of the pass infrastructure in MLIR and how to 7use it. 8 9See [MLIR specification](LangRef.md) for more information about MLIR and its 10core aspects, such as the IR structure and operations. 11 12See [MLIR Rewrites](Tutorials/QuickstartRewrites.md) for a quick start on graph 13rewriting in MLIR. If a transformation involves pattern matching operation DAGs, 14this is a great place to start. 15 16## Operation Pass 17 18In MLIR, the main unit of abstraction and transformation is an 19[operation](LangRef.md#operations). As such, the pass manager is designed to 20work on instances of operations at different levels of nesting. The structure of 21the [pass manager](#pass-manager), and the concept of nesting, is detailed 22further below. All passes in MLIR derive from `OperationPass` and adhere to the 23following restrictions; any noncompliance will lead to problematic behavior in 24multithreaded and other advanced scenarios: 25 26* Modify any state referenced or relied upon outside the current being 27 operated on. This includes adding or removing operations from the parent 28 block, changing the attributes(depending on the contract of the current 29 operation)/operands/results/successors of the current operation. 30* Modify the state of another operation not nested within the current 31 operation being operated on. 32 * Other threads may be operating on these operations simultaneously. 33* Inspect the state of sibling operations. 34 * Other threads may be modifying these operations in parallel. 35 * Inspecting the state of ancestor/parent operations is permitted. 36* Maintain mutable pass state across invocations of `runOnOperation`. A pass 37 may be run on many different operations with no guarantee of execution 38 order. 39 * When multithreading, a specific pass instance may not even execute on 40 all operations within the IR. As such, a pass should not rely on running 41 on all operations. 42* Maintain any global mutable state, e.g. static variables within the source 43 file. All mutable state should be maintained by an instance of the pass. 44* Must be copy-constructible 45 * Multiple instances of the pass may be created by the pass manager to 46 process operations in parallel. 47 48When creating an operation pass, there are two different types to choose from 49depending on the usage scenario: 50 51### OperationPass : Op-Specific 52 53An `op-specific` operation pass operates explicitly on a given operation type. 54This operation type must adhere to the restrictions set by the pass manager for 55pass execution. 56 57To define an op-specific operation pass, a derived class must adhere to the 58following: 59 60* Inherit from the CRTP class `OperationPass` and provide the operation type 61 as an additional template parameter. 62* Override the virtual `void runOnOperation()` method. 63 64A simple pass may look like: 65 66```c++ 67namespace { 68/// Here we utilize the CRTP `PassWrapper` utility class to provide some 69/// necessary utility hooks. This is only necessary for passes defined directly 70/// in C++. Passes defined declaratively use a cleaner mechanism for providing 71/// these utilities. 72struct MyFunctionPass : public PassWrapper<OperationPass<FuncOp>, 73 MyFunctionPass> { 74 void runOnOperation() override { 75 // Get the current FuncOp operation being operated on. 76 FuncOp f = getOperation(); 77 78 // Walk the operations within the function. 79 f.walk([](Operation *inst) { 80 .... 81 }); 82 } 83}; 84} // end anonymous namespace 85 86/// Register this pass so that it can be built via from a textual pass pipeline. 87/// (Pass registration is discussed more below) 88void registerMyPass() { 89 PassRegistration<MyFunctionPass>( 90 "flag-name-to-invoke-pass-via-mlir-opt", "Pass description here"); 91} 92``` 93 94### OperationPass : Op-Agnostic 95 96An `op-agnostic` pass operates on the operation type of the pass manager that it 97is added to. This means that passes of this type may operate on several 98different operation types. Passes of this type are generally written generically 99using operation [interfaces](Interfaces.md) and [traits](Traits.md). Examples of 100this type of pass are 101[Common Sub-Expression Elimination](Passes.md#-cse-eliminate-common-sub-expressions) 102and [Inlining](Passes.md#-inline-inline-function-calls). 103 104To create an operation pass, a derived class must adhere to the following: 105 106* Inherit from the CRTP class `OperationPass`. 107* Override the virtual `void runOnOperation()` method. 108 109A simple pass may look like: 110 111```c++ 112/// Here we utilize the CRTP `PassWrapper` utility class to provide some 113/// necessary utility hooks. This is only necessary for passes defined directly 114/// in C++. Passes defined declaratively use a cleaner mechanism for providing 115/// these utilities. 116struct MyOperationPass : public PassWrapper<OperationPass<>, MyOperationPass> { 117 void runOnOperation() override { 118 // Get the current operation being operated on. 119 Operation *op = getOperation(); 120 ... 121 } 122}; 123``` 124 125### Dependent Dialects 126 127Dialects must be loaded in the MLIRContext before entities from these dialects 128(operations, types, attributes, ...) can be created. Dialects must also be 129loaded before starting the execution of a multi-threaded pass pipeline. To this 130end, a pass that may create an entity from a dialect that isn't guaranteed to 131already ne loaded must express this by overriding the `getDependentDialects()` 132method and declare this list of Dialects explicitly. 133 134### Initialization 135 136In certain situations, a Pass may contain state that is constructed dynamically, 137but is potentially expensive to recompute in successive runs of the Pass. One 138such example is when using [`PDL`-based](Dialects/PDLOps.md) 139[patterns](PatternRewriter.md), which are compiled into a bytecode during 140runtime. In these situations, a pass may override the following hook to 141initialize this heavy state: 142 143* `void initialize(MLIRContext *context)` 144 145This hook is executed once per run of a full pass pipeline, meaning that it does 146not have access to the state available during a `runOnOperation` call. More 147concretely, all necessary accesses to an `MLIRContext` should be driven via the 148provided `context` parameter, and methods that utilize "per-run" state such as 149`getContext`/`getOperation`/`getAnalysis`/etc. must not be used. 150 151## Analysis Management 152 153An important concept, along with transformation passes, are analyses. These are 154conceptually similar to transformation passes, except that they compute 155information on a specific operation without modifying it. In MLIR, analyses are 156not passes but free-standing classes that are computed lazily on-demand and 157cached to avoid unnecessary recomputation. An analysis in MLIR must adhere to 158the following: 159 160* Provide a valid constructor taking an `Operation*`. 161* Must not modify the given operation. 162 163An analysis may provide additional hooks to control various behavior: 164 165* `bool isInvalidated(const AnalysisManager::PreservedAnalyses &)` 166 167Given a preserved analysis set, the analysis returns true if it should truly be 168invalidated. This allows for more fine-tuned invalidation in cases where an 169analysis wasn't explicitly marked preserved, but may be preserved (or 170invalidated) based upon other properties such as analyses sets. 171 172### Querying Analyses 173 174The base `OperationPass` class provides utilities for querying and preserving 175analyses for the current operation being processed. 176 177* OperationPass automatically provides the following utilities for querying 178 analyses: 179 * `getAnalysis<>` 180 - Get an analysis for the current operation, constructing it if 181 necessary. 182 * `getCachedAnalysis<>` 183 - Get an analysis for the current operation, if it already exists. 184 * `getCachedParentAnalysis<>` 185 - Get an analysis for a given parent operation, if it exists. 186 * `getCachedChildAnalysis<>` 187 - Get an analysis for a given child operation, if it exists. 188 * `getChildAnalysis<>` 189 - Get an analysis for a given child operation, constructing it if 190 necessary. 191 192Using the example passes defined above, let's see some examples: 193 194```c++ 195/// An interesting analysis. 196struct MyOperationAnalysis { 197 // Compute this analysis with the provided operation. 198 MyOperationAnalysis(Operation *op); 199}; 200 201void MyOperationPass::runOnOperation() { 202 // Query MyOperationAnalysis for the current operation. 203 MyOperationAnalysis &myAnalysis = getAnalysis<MyOperationAnalysis>(); 204 205 // Query a cached instance of MyOperationAnalysis for the current operation. 206 // It will not be computed if it doesn't exist. 207 auto optionalAnalysis = getCachedAnalysis<MyOperationAnalysis>(); 208 if (optionalAnalysis) 209 ... 210 211 // Query a cached instance of MyOperationAnalysis for the parent operation of 212 // the current operation. It will not be computed if it doesn't exist. 213 auto optionalAnalysis = getCachedParentAnalysis<MyOperationAnalysis>(); 214 if (optionalAnalysis) 215 ... 216} 217``` 218 219### Preserving Analyses 220 221Analyses that are constructed after being queried by a pass are cached to avoid 222unnecessary computation if they are requested again later. To avoid stale 223analyses, all analyses are assumed to be invalidated by a pass. To avoid 224invalidation, a pass must specifically mark analyses that are known to be 225preserved. 226 227* All Pass classes automatically provide the following utilities for 228 preserving analyses: 229 * `markAllAnalysesPreserved` 230 * `markAnalysesPreserved<>` 231 232```c++ 233void MyOperationPass::runOnOperation() { 234 // Mark all analyses as preserved. This is useful if a pass can guarantee 235 // that no transformation was performed. 236 markAllAnalysesPreserved(); 237 238 // Mark specific analyses as preserved. This is used if some transformation 239 // was performed, but some analyses were either unaffected or explicitly 240 // preserved. 241 markAnalysesPreserved<MyAnalysis, MyAnalyses...>(); 242} 243``` 244 245## Pass Failure 246 247Passes in MLIR are allowed to gracefully fail. This may happen if some invariant 248of the pass was broken, potentially leaving the IR in some invalid state. If 249such a situation occurs, the pass can directly signal a failure to the pass 250manager via the `signalPassFailure` method. If a pass signaled a failure when 251executing, no other passes in the pipeline will execute and the top-level call 252to `PassManager::run` will return `failure`. 253 254```c++ 255void MyOperationPass::runOnOperation() { 256 // Signal failure on a broken invariant. 257 if (some_broken_invariant) 258 return signalPassFailure(); 259} 260``` 261 262## Pass Manager 263 264The above sections introduced the different types of passes and their 265invariants. This section introduces the concept of a PassManager, and how it can 266be used to configure and schedule a pass pipeline. There are two main classes 267related to pass management, the `PassManager` and the `OpPassManager`. The 268`PassManager` class acts as the top-level entry point, and contains various 269configurations used for the entire pass pipeline. The `OpPassManager` class is 270used to schedule passes to run at a specific level of nesting. The top-level 271`PassManager` also functions as an `OpPassManager`. 272 273### OpPassManager 274 275An `OpPassManager` is essentially a collection of passes to execute on an 276operation of a specific type. This operation type must adhere to the following 277requirement: 278 279* Must be registered and marked 280 [`IsolatedFromAbove`](Traits.md#isolatedfromabove). 281 282 * Passes are expected to not modify operations at or above the current 283 operation being processed. If the operation is not isolated, it may 284 inadvertently modify or traverse the SSA use-list of an operation it is 285 not supposed to. 286 287Passes can be added to a pass manager via `addPass`. The pass must either be an 288`op-specific` pass operating on the same operation type as `OpPassManager`, or 289an `op-agnostic` pass. 290 291An `OpPassManager` is generally created by explicitly nesting a pipeline within 292another existing `OpPassManager` via the `nest<>` method. This method takes the 293operation type that the nested pass manager will operate on. At the top-level, a 294`PassManager` acts as an `OpPassManager`. Nesting in this sense, corresponds to 295the [structural](Tutorials/UnderstandingTheIRStructure.md) nesting within 296[Regions](LangRef.md#regions) of the IR. 297 298For example, the following `.mlir`: 299 300``` 301module { 302 spv.module "Logical" "GLSL450" { 303 func @foo() { 304 ... 305 } 306 } 307} 308``` 309 310Has the nesting structure of: 311 312``` 313`module` 314 `spv.module` 315 `function` 316``` 317 318Below is an example of constructing a pipeline that operates on the above 319structure: 320 321```c++ 322// Create a top-level `PassManager` class. If an operation type is not 323// explicitly specific, the default is the builtin `module` operation. 324PassManager pm(ctx); 325// Note: We could also create the above `PassManager` this way. 326PassManager pm(ctx, /*operationName=*/"module"); 327 328// Add a pass on the top-level module operation. 329pm.addPass(std::make_unique<MyModulePass>()); 330 331// Nest a pass manager that operates on `spirv.module` operations nested 332// directly under the top-level module. 333OpPassManager &nestedModulePM = pm.nest<spirv::ModuleOp>(); 334nestedModulePM.addPass(std::make_unique<MySPIRVModulePass>()); 335 336// Nest a pass manager that operates on functions within the nested SPIRV 337// module. 338OpPassManager &nestedFunctionPM = nestedModulePM.nest<FuncOp>(); 339nestedFunctionPM.addPass(std::make_unique<MyFunctionPass>()); 340 341// Run the pass manager on the top-level module. 342ModuleOp m = ...; 343if (failed(pm.run(m))) 344 ... // One of the passes signaled a failure. 345``` 346 347The above pass manager contains the following pipeline structure: 348 349``` 350OpPassManager<ModuleOp> 351 MyModulePass 352 OpPassManager<spirv::ModuleOp> 353 MySPIRVModulePass 354 OpPassManager<FuncOp> 355 MyFunctionPass 356``` 357 358These pipelines are then run over a single operation at a time. This means that, 359for example, given a series of consecutive passes on FuncOp, it will execute all 360on the first function, then all on the second function, etc. until the entire 361program has been run through the passes. This provides several benefits: 362 363* This improves the cache behavior of the compiler, because it is only 364 touching a single function at a time, instead of traversing the entire 365 program. 366* This improves multi-threading performance by reducing the number of jobs 367 that need to be scheduled, as well as increasing the efficiency of each job. 368 An entire function pipeline can be run on each function asynchronously. 369 370## Dynamic Pass Pipelines 371 372In some situations it may be useful to run a pass pipeline within another pass, 373to allow configuring or filtering based on some invariants of the current 374operation being operated on. For example, the 375[Inliner Pass](Passes.md#-inline-inline-function-calls) may want to run 376intraprocedural simplification passes while it is inlining to produce a better 377cost model, and provide more optimal inlining. To enable this, passes may run an 378arbitrary `OpPassManager` on the current operation being operated on or any 379operation nested within the current operation via the `LogicalResult 380Pass::runPipeline(OpPassManager &, Operation *)` method. This method returns 381whether the dynamic pipeline succeeded or failed, similarly to the result of the 382top-level `PassManager::run` method. A simple example is shown below: 383 384```c++ 385void MyModulePass::runOnOperation() { 386 ModuleOp module = getOperation(); 387 if (hasSomeSpecificProperty(module)) { 388 OpPassManager dynamicPM("module"); 389 ...; // Build the dynamic pipeline. 390 if (failed(runPipeline(dynamicPM, module))) 391 return signalPassFailure(); 392 } 393} 394``` 395 396Note: though above the dynamic pipeline was constructed within the 397`runOnOperation` method, this is not necessary and pipelines should be cached 398when possible as the `OpPassManager` class can be safely copy constructed. 399 400The mechanism described in this section should be used whenever a pass pipeline 401should run in a nested fashion, i.e. when the nested pipeline cannot be 402scheduled statically along with the rest of the main pass pipeline. More 403specifically, a `PassManager` should generally never need to be constructed 404within a `Pass`. Using `runPipeline` also ensures that all analyses, 405[instrumentations](#pass-instrumentation), and other pass manager related 406components are integrated with the dynamic pipeline being executed. 407 408## Instance Specific Pass Options 409 410MLIR provides a builtin mechanism for passes to specify options that configure 411its behavior. These options are parsed at pass construction time independently 412for each instance of the pass. Options are defined using the `Option<>` and 413`ListOption<>` classes, and follow the 414[LLVM command line](https://llvm.org/docs/CommandLine.html) flag definition 415rules. See below for a few examples: 416 417```c++ 418struct MyPass ... { 419 /// Make sure that we have a valid default constructor and copy constructor to 420 /// ensure that the options are initialized properly. 421 MyPass() = default; 422 MyPass(const MyPass& pass) {} 423 424 /// Any parameters after the description are forwarded to llvm::cl::list and 425 /// llvm::cl::opt respectively. 426 Option<int> exampleOption{*this, "flag-name", llvm::cl::desc("...")}; 427 ListOption<int> exampleListOption{*this, "list-flag-name", 428 llvm::cl::desc("...")}; 429}; 430``` 431 432For pass pipelines, the `PassPipelineRegistration` templates take an additional 433template parameter for an optional `Option` struct definition. This struct 434should inherit from `mlir::PassPipelineOptions` and contain the desired pipeline 435options. When using `PassPipelineRegistration`, the constructor now takes a 436function with the signature `void (OpPassManager &pm, const MyPipelineOptions&)` 437which should construct the passes from the options and pass them to the pm: 438 439```c++ 440struct MyPipelineOptions : public PassPipelineOptions { 441 // The structure of these options is the same as those for pass options. 442 Option<int> exampleOption{*this, "flag-name", llvm::cl::desc("...")}; 443 ListOption<int> exampleListOption{*this, "list-flag-name", 444 llvm::cl::desc("...")}; 445}; 446 447void registerMyPasses() { 448 PassPipelineRegistration<MyPipelineOptions>( 449 "example-pipeline", "Run an example pipeline.", 450 [](OpPassManager &pm, const MyPipelineOptions &pipelineOptions) { 451 // Initialize the pass manager. 452 }); 453} 454``` 455 456## Pass Statistics 457 458Statistics are a way to keep track of what the compiler is doing and how 459effective various transformations are. It is often useful to see what effect 460specific transformations have on a particular input, and how often they trigger. 461Pass statistics are specific to each pass instance, which allow for seeing the 462effect of placing a particular transformation at specific places within the pass 463pipeline. For example, they help answer questions like "What happens if I run 464CSE again here?". 465 466Statistics can be added to a pass by using the 'Pass::Statistic' class. This 467class takes as a constructor arguments: the parent pass, a name, and a 468description. This class acts like an atomic unsigned integer, and may be 469incremented and updated accordingly. These statistics rely on the same 470infrastructure as 471[`llvm::Statistic`](http://llvm.org/docs/ProgrammersManual.html#the-statistic-class-stats-option) 472and thus have similar usage constraints. Collected statistics can be dumped by 473the [pass manager](#pass-manager) programmatically via 474`PassManager::enableStatistics`; or via `-pass-statistics` and 475`-pass-statistics-display` on the command line. 476 477An example is shown below: 478 479```c++ 480struct MyPass ... { 481 /// Make sure that we have a valid default constructor and copy constructor to 482 /// ensure that the options are initialized properly. 483 MyPass() = default; 484 MyPass(const MyPass& pass) {} 485 486 /// Define the statistic to track during the execution of MyPass. 487 Statistic exampleStat{this, "exampleStat", "An example statistic"}; 488 489 void runOnOperation() { 490 ... 491 492 // Update the statistic after some invariant was hit. 493 ++exampleStat; 494 495 ... 496 } 497}; 498``` 499 500The collected statistics may be aggregated in two types of views: 501 502A pipeline view that models the structure of the pass manager, this is the 503default view: 504 505```shell 506$ mlir-opt -pass-pipeline='func(my-pass,my-pass)' foo.mlir -pass-statistics 507 508===-------------------------------------------------------------------------=== 509 ... Pass statistics report ... 510===-------------------------------------------------------------------------=== 511'func' Pipeline 512 MyPass 513 (S) 15 exampleStat - An example statistic 514 VerifierPass 515 MyPass 516 (S) 6 exampleStat - An example statistic 517 VerifierPass 518VerifierPass 519``` 520 521A list view that aggregates the statistics of all instances of a specific pass 522together: 523 524```shell 525$ mlir-opt -pass-pipeline='func(my-pass, my-pass)' foo.mlir -pass-statistics -pass-statistics-display=list 526 527===-------------------------------------------------------------------------=== 528 ... Pass statistics report ... 529===-------------------------------------------------------------------------=== 530MyPass 531 (S) 21 exampleStat - An example statistic 532``` 533 534## Pass Registration 535 536Briefly shown in the example definitions of the various pass types is the 537`PassRegistration` class. This mechanism allows for registering pass classes so 538that they may be created within a 539[textual pass pipeline description](#textual-pass-pipeline-specification). An 540example registration is shown below: 541 542```c++ 543void registerMyPass() { 544 PassRegistration<MyPass>("argument", "description"); 545} 546``` 547 548* `MyPass` is the name of the derived pass class. 549* "argument" is the argument used to refer to the pass in the textual format. 550* "description" is a brief description of the pass. 551 552For passes that cannot be default-constructed, `PassRegistration` accepts an 553optional third argument that takes a callback to create the pass: 554 555```c++ 556void registerMyPass() { 557 PassRegistration<MyParametricPass>( 558 "argument", "description", 559 []() -> std::unique_ptr<Pass> { 560 std::unique_ptr<Pass> p = std::make_unique<MyParametricPass>(/*options*/); 561 /*... non-trivial-logic to configure the pass ...*/; 562 return p; 563 }); 564} 565``` 566 567This variant of registration can be used, for example, to accept the 568configuration of a pass from command-line arguments and pass it to the pass 569constructor. 570 571Note: Make sure that the pass is copy-constructible in a way that does not share 572data as the [pass manager](#pass-manager) may create copies of the pass to run 573in parallel. 574 575### Pass Pipeline Registration 576 577Described above is the mechanism used for registering a specific derived pass 578class. On top of that, MLIR allows for registering custom pass pipelines in a 579similar fashion. This allows for custom pipelines to be available to tools like 580mlir-opt in the same way that passes are, which is useful for encapsulating 581common pipelines like the "-O1" series of passes. Pipelines are registered via a 582similar mechanism to passes in the form of `PassPipelineRegistration`. Compared 583to `PassRegistration`, this class takes an additional parameter in the form of a 584pipeline builder that modifies a provided `OpPassManager`. 585 586```c++ 587void pipelineBuilder(OpPassManager &pm) { 588 pm.addPass(std::make_unique<MyPass>()); 589 pm.addPass(std::make_unique<MyOtherPass>()); 590} 591 592void registerMyPasses() { 593 // Register an existing pipeline builder function. 594 PassPipelineRegistration<>( 595 "argument", "description", pipelineBuilder); 596 597 // Register an inline pipeline builder. 598 PassPipelineRegistration<>( 599 "argument", "description", [](OpPassManager &pm) { 600 pm.addPass(std::make_unique<MyPass>()); 601 pm.addPass(std::make_unique<MyOtherPass>()); 602 }); 603} 604``` 605 606### Textual Pass Pipeline Specification 607 608The previous sections detailed how to register passes and pass pipelines with a 609specific argument and description. Once registered, these can be used to 610configure a pass manager from a string description. This is especially useful 611for tools like `mlir-opt`, that configure pass managers from the command line, 612or as options to passes that utilize 613[dynamic pass pipelines](#dynamic-pass-pipelines). 614 615To support the ability to describe the full structure of pass pipelines, MLIR 616supports a custom textual description of pass pipelines. The textual description 617includes the nesting structure, the arguments of the passes and pass pipelines 618to run, and any options for those passes and pipelines. A textual pipeline is 619defined as a series of names, each of which may in itself recursively contain a 620nested pipeline description. The syntax for this specification is as follows: 621 622```ebnf 623pipeline ::= op-name `(` pipeline-element (`,` pipeline-element)* `)` 624pipeline-element ::= pipeline | (pass-name | pass-pipeline-name) options? 625options ::= '{' (key ('=' value)?)+ '}' 626``` 627 628* `op-name` 629 * This corresponds to the mnemonic name of an operation to run passes on, 630 e.g. `func` or `module`. 631* `pass-name` | `pass-pipeline-name` 632 * This corresponds to the argument of a registered pass or pass pipeline, 633 e.g. `cse` or `canonicalize`. 634* `options` 635 * Options are specific key value pairs representing options defined by a 636 pass or pass pipeline, as described in the 637 ["Instance Specific Pass Options"](#instance-specific-pass-options) 638 section. See this section for an example usage in a textual pipeline. 639 640For example, the following pipeline: 641 642```shell 643$ mlir-opt foo.mlir -cse -canonicalize -convert-std-to-llvm='use-bare-ptr-memref-call-conv=1' 644``` 645 646Can also be specified as (via the `-pass-pipeline` flag): 647 648```shell 649$ mlir-opt foo.mlir -pass-pipeline='func(cse,canonicalize),convert-std-to-llvm{use-bare-ptr-memref-call-conv=1}' 650``` 651 652In order to support round-tripping a pass to the textual representation using 653`OpPassManager::printAsTextualPipeline(raw_ostream&)`, override `StringRef 654Pass::getArgument()` to specify the argument used when registering a pass. 655 656## Declarative Pass Specification 657 658Some aspects of a Pass may be specified declaratively, in a form similar to 659[operations](OpDefinitions.md). This specification simplifies several mechanisms 660used when defining passes. It can be used for generating pass registration 661calls, defining boilerplate pass utilities, and generating pass documentation. 662 663Consider the following pass specified in C++: 664 665```c++ 666struct MyPass : PassWrapper<MyPass, OperationPass<ModuleOp>> { 667 MyPass() = default; 668 MyPass(const MyPass &) {} 669 670 ... 671 672 // Specify any options. 673 Option<bool> option{ 674 *this, "example-option", 675 llvm::cl::desc("An example option"), llvm::cl::init(true)}; 676 ListOption<int64_t> listOption{ 677 *this, "example-list", 678 llvm::cl::desc("An example list option"), llvm::cl::ZeroOrMore, 679 llvm::cl::MiscFlags::CommaSeparated}; 680 681 // Specify any statistics. 682 Statistic statistic{this, "example-statistic", "An example statistic"}; 683}; 684 685/// Expose this pass to the outside world. 686std::unique_ptr<Pass> foo::createMyPass() { 687 return std::make_unique<MyPass>(); 688} 689 690/// Register this pass. 691void foo::registerMyPass() { 692 PassRegistration<MyPass>("my-pass", "My pass summary"); 693} 694``` 695 696This pass may be specified declaratively as so: 697 698```tablegen 699def MyPass : Pass<"my-pass", "ModuleOp"> { 700 let summary = "My Pass Summary"; 701 let description = [{ 702 Here we can now give a much larger description of `MyPass`, including all of 703 its various constraints and behavior. 704 }]; 705 706 // A constructor must be provided to specify how to create a default instance 707 // of MyPass. 708 let constructor = "foo::createMyPass()"; 709 710 // Specify any options. 711 let options = [ 712 Option<"option", "example-option", "bool", /*default=*/"true", 713 "An example option">, 714 ListOption<"listOption", "example-list", "int64_t", 715 "An example list option", 716 "llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated"> 717 ]; 718 719 // Specify any statistics. 720 let statistics = [ 721 Statistic<"statistic", "example-statistic", "An example statistic"> 722 ]; 723} 724``` 725 726Using the `gen-pass-decls` generator, we can generate most of the boilerplate 727above automatically. This generator takes as an input a `-name` parameter, that 728provides a tag for the group of passes that are being generated. This generator 729produces two chunks of output: 730 731The first is a code block for registering the declarative passes with the global 732registry. For each pass, the generator produces a `registerFooPass` where `Foo` 733is the name of the definition specified in tablegen. It also generates a 734`registerGroupPasses`, where `Group` is the tag provided via the `-name` input 735parameter, that registers all of the passes present. 736 737```c++ 738// gen-pass-decls -name="Example" 739 740#define GEN_PASS_REGISTRATION 741#include "Passes.h.inc" 742 743void registerMyPasses() { 744 // Register all of the passes. 745 registerExamplePasses(); 746 747 // Register `MyPass` specifically. 748 registerMyPassPass(); 749} 750``` 751 752The second is a base class for each of the passes, containing most of the boiler 753plate related to pass definitions. These classes are named in the form of 754`MyPassBase`, where `MyPass` is the name of the pass definition in tablegen. We 755can update the original C++ pass definition as so: 756 757```c++ 758/// Include the generated base pass class definitions. 759#define GEN_PASS_CLASSES 760#include "Passes.h.inc" 761 762/// Define the main class as deriving from the generated base class. 763struct MyPass : MyPassBase<MyPass> { 764 /// The explicit constructor is no longer explicitly necessary when defining 765 /// pass options and statistics, the base class takes care of that 766 /// automatically. 767 ... 768 769 /// The definitions of the options and statistics are now generated within 770 /// the base class, but are accessible in the same way. 771}; 772 773/// Expose this pass to the outside world. 774std::unique_ptr<Pass> foo::createMyPass() { 775 return std::make_unique<MyPass>(); 776} 777``` 778 779Using the `gen-pass-doc` generator, markdown documentation for each of the 780passes can be generated. See [Passes.md](Passes.md) for example output of real 781MLIR passes. 782 783### Tablegen Specification 784 785The `Pass` class is used to begin a new pass definition. This class takes as an 786argument the registry argument to attribute to the pass, as well as an optional 787string corresponding to the operation type that the pass operates on. The class 788contains the following fields: 789 790* `summary` 791 - A short one line summary of the pass, used as the description when 792 registering the pass. 793* `description` 794 - A longer, more detailed description of the pass. This is used when 795 generating pass documentation. 796* `dependentDialects` 797 - A list of strings representing the `Dialect` classes this pass may 798 introduce entities, Attributes/Operations/Types/etc., of. 799* `constructor` 800 - A code block used to create a default instance of the pass. 801* `options` 802 - A list of pass options used by the pass. 803* `statistics` 804 - A list of pass statistics used by the pass. 805 806#### Options 807 808Options may be specified via the `Option` and `ListOption` classes. The `Option` 809class takes the following template parameters: 810 811* C++ variable name 812 - A name to use for the generated option variable. 813* argument 814 - The argument name of the option. 815* type 816 - The C++ type of the option. 817* default value 818 - The default option value. 819* description 820 - A one line description of the option. 821* additional option flags 822 - A string containing any additional options necessary to construct the 823 option. 824 825```tablegen 826def MyPass : Pass<"my-pass"> { 827 let options = [ 828 Option<"option", "example-option", "bool", /*default=*/"true", 829 "An example option">, 830 ]; 831} 832``` 833 834The `ListOption` class takes the following fields: 835 836* C++ variable name 837 - A name to use for the generated option variable. 838* argument 839 - The argument name of the option. 840* element type 841 - The C++ type of the list element. 842* description 843 - A one line description of the option. 844* additional option flags 845 - A string containing any additional options necessary to construct the 846 option. 847 848```tablegen 849def MyPass : Pass<"my-pass"> { 850 let options = [ 851 ListOption<"listOption", "example-list", "int64_t", 852 "An example list option", 853 "llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated"> 854 ]; 855} 856``` 857 858#### Statistic 859 860Statistics may be specified via the `Statistic`, which takes the following 861template parameters: 862 863* C++ variable name 864 - A name to use for the generated statistic variable. 865* display name 866 - The name used when displaying the statistic. 867* description 868 - A one line description of the statistic. 869 870```tablegen 871def MyPass : Pass<"my-pass"> { 872 let statistics = [ 873 Statistic<"statistic", "example-statistic", "An example statistic"> 874 ]; 875} 876``` 877 878## Pass Instrumentation 879 880MLIR provides a customizable framework to instrument pass execution and analysis 881computation, via the `PassInstrumentation` class. This class provides hooks into 882the PassManager that observe various events: 883 884* `runBeforePipeline` 885 * This callback is run just before a pass pipeline, i.e. pass manager, is 886 executed. 887* `runAfterPipeline` 888 * This callback is run right after a pass pipeline has been executed, 889 successfully or not. 890* `runBeforePass` 891 * This callback is run just before a pass is executed. 892* `runAfterPass` 893 * This callback is run right after a pass has been successfully executed. 894 If this hook is executed, `runAfterPassFailed` will *not* be. 895* `runAfterPassFailed` 896 * This callback is run right after a pass execution fails. If this hook is 897 executed, `runAfterPass` will *not* be. 898* `runBeforeAnalysis` 899 * This callback is run just before an analysis is computed. 900* `runAfterAnalysis` 901 * This callback is run right after an analysis is computed. 902 903PassInstrumentation instances may be registered directly with a 904[PassManager](#pass-manager) instance via the `addInstrumentation` method. 905Instrumentations added to the PassManager are run in a stack like fashion, i.e. 906the last instrumentation to execute a `runBefore*` hook will be the first to 907execute the respective `runAfter*` hook. The hooks of a `PassInstrumentation` 908class are guaranteed to be executed in a thread safe fashion, so additional 909synchronization is not necessary. Below in an example instrumentation that 910counts the number of times the `DominanceInfo` analysis is computed: 911 912```c++ 913struct DominanceCounterInstrumentation : public PassInstrumentation { 914 /// The cumulative count of how many times dominance has been calculated. 915 unsigned &count; 916 917 DominanceCounterInstrumentation(unsigned &count) : count(count) {} 918 void runAfterAnalysis(llvm::StringRef, TypeID id, Operation *) override { 919 if (id == TypeID::get<DominanceInfo>()) 920 ++count; 921 } 922}; 923 924MLIRContext *ctx = ...; 925PassManager pm(ctx); 926 927// Add the instrumentation to the pass manager. 928unsigned domInfoCount; 929pm.addInstrumentation( 930 std::make_unique<DominanceCounterInstrumentation>(domInfoCount)); 931 932// Run the pass manager on a module operation. 933ModuleOp m = ...; 934if (failed(pm.run(m))) 935 ... 936 937llvm::errs() << "DominanceInfo was computed " << domInfoCount << " times!\n"; 938``` 939 940### Standard Instrumentations 941 942MLIR utilizes the pass instrumentation framework to provide a few useful 943developer tools and utilities. Each of these instrumentations are directly 944available to all users of the MLIR pass framework. 945 946#### Pass Timing 947 948The PassTiming instrumentation provides timing information about the execution 949of passes and computation of analyses. This provides a quick glimpse into what 950passes are taking the most time to execute, as well as how much of an effect a 951pass has on the total execution time of the pipeline. Users can enable this 952instrumentation directly on the PassManager via `enableTiming`. This 953instrumentation is also made available in mlir-opt via the `-pass-timing` flag. 954The PassTiming instrumentation provides several different display modes for the 955timing results, each of which is described below: 956 957##### List Display Mode 958 959In this mode, the results are displayed in a list sorted by total time with each 960pass/analysis instance aggregated into one unique result. This view is useful 961for getting an overview of what analyses/passes are taking the most time in a 962pipeline. This display mode is available in mlir-opt via 963`-pass-timing-display=list`. 964 965```shell 966$ mlir-opt foo.mlir -mlir-disable-threading -pass-pipeline='func(cse,canonicalize)' -convert-std-to-llvm -pass-timing -pass-timing-display=list 967 968===-------------------------------------------------------------------------=== 969 ... Pass execution timing report ... 970===-------------------------------------------------------------------------=== 971 Total Execution Time: 0.0203 seconds 972 973 ---Wall Time--- --- Name --- 974 0.0047 ( 55.9%) Canonicalizer 975 0.0019 ( 22.2%) VerifierPass 976 0.0016 ( 18.5%) LLVMLoweringPass 977 0.0003 ( 3.4%) CSE 978 0.0002 ( 1.9%) (A) DominanceInfo 979 0.0084 (100.0%) Total 980``` 981 982##### Pipeline Display Mode 983 984In this mode, the results are displayed in a nested pipeline view that mirrors 985the internal pass pipeline that is being executed in the pass manager. This view 986is useful for understanding specifically which parts of the pipeline are taking 987the most time, and can also be used to identify when analyses are being 988invalidated and recomputed. This is the default display mode. 989 990```shell 991$ mlir-opt foo.mlir -mlir-disable-threading -pass-pipeline='func(cse,canonicalize)' -convert-std-to-llvm -pass-timing 992 993===-------------------------------------------------------------------------=== 994 ... Pass execution timing report ... 995===-------------------------------------------------------------------------=== 996 Total Execution Time: 0.0249 seconds 997 998 ---Wall Time--- --- Name --- 999 0.0058 ( 70.8%) 'func' Pipeline 1000 0.0004 ( 4.3%) CSE 1001 0.0002 ( 2.6%) (A) DominanceInfo 1002 0.0004 ( 4.8%) VerifierPass 1003 0.0046 ( 55.4%) Canonicalizer 1004 0.0005 ( 6.2%) VerifierPass 1005 0.0005 ( 5.8%) VerifierPass 1006 0.0014 ( 17.2%) LLVMLoweringPass 1007 0.0005 ( 6.2%) VerifierPass 1008 0.0082 (100.0%) Total 1009``` 1010 1011##### Multi-threaded Pass Timing 1012 1013When multi-threading is enabled in the pass manager the meaning of the display 1014slightly changes. First, a new timing column is added, `User Time`, that 1015displays the total time spent across all threads. Secondly, the `Wall Time` 1016column displays the longest individual time spent amongst all of the threads. 1017This means that the `Wall Time` column will continue to give an indicator on the 1018perceived time, or clock time, whereas the `User Time` will display the total 1019cpu time. 1020 1021```shell 1022$ mlir-opt foo.mlir -pass-pipeline='func(cse,canonicalize)' -convert-std-to-llvm -pass-timing 1023 1024===-------------------------------------------------------------------------=== 1025 ... Pass execution timing report ... 1026===-------------------------------------------------------------------------=== 1027 Total Execution Time: 0.0078 seconds 1028 1029 ---User Time--- ---Wall Time--- --- Name --- 1030 0.0177 ( 88.5%) 0.0057 ( 71.3%) 'func' Pipeline 1031 0.0044 ( 22.0%) 0.0015 ( 18.9%) CSE 1032 0.0029 ( 14.5%) 0.0012 ( 15.2%) (A) DominanceInfo 1033 0.0038 ( 18.9%) 0.0015 ( 18.7%) VerifierPass 1034 0.0089 ( 44.6%) 0.0025 ( 31.1%) Canonicalizer 1035 0.0006 ( 3.0%) 0.0002 ( 2.6%) VerifierPass 1036 0.0004 ( 2.2%) 0.0004 ( 5.4%) VerifierPass 1037 0.0013 ( 6.5%) 0.0013 ( 16.3%) LLVMLoweringPass 1038 0.0006 ( 2.8%) 0.0006 ( 7.0%) VerifierPass 1039 0.0200 (100.0%) 0.0081 (100.0%) Total 1040``` 1041 1042#### IR Printing 1043 1044When debugging it is often useful to dump the IR at various stages of a pass 1045pipeline. This is where the IR printing instrumentation comes into play. This 1046instrumentation allows for conditionally printing the IR before and after pass 1047execution by optionally filtering on the pass being executed. This 1048instrumentation can be added directly to the PassManager via the 1049`enableIRPrinting` method. `mlir-opt` provides a few useful flags for utilizing 1050this instrumentation: 1051 1052* `print-ir-before=(comma-separated-pass-list)` 1053 * Print the IR before each of the passes provided within the pass list. 1054* `print-ir-before-all` 1055 * Print the IR before every pass in the pipeline. 1056 1057```shell 1058$ mlir-opt foo.mlir -pass-pipeline='func(cse)' -print-ir-before=cse 1059 1060*** IR Dump Before CSE *** 1061func @simple_constant() -> (i32, i32) { 1062 %c1_i32 = constant 1 : i32 1063 %c1_i32_0 = constant 1 : i32 1064 return %c1_i32, %c1_i32_0 : i32, i32 1065} 1066``` 1067 1068* `print-ir-after=(comma-separated-pass-list)` 1069 * Print the IR after each of the passes provided within the pass list. 1070* `print-ir-after-all` 1071 * Print the IR after every pass in the pipeline. 1072 1073```shell 1074$ mlir-opt foo.mlir -pass-pipeline='func(cse)' -print-ir-after=cse 1075 1076*** IR Dump After CSE *** 1077func @simple_constant() -> (i32, i32) { 1078 %c1_i32 = constant 1 : i32 1079 return %c1_i32, %c1_i32 : i32, i32 1080} 1081``` 1082 1083* `print-ir-after-change` 1084 * Only print the IR after a pass if the pass mutated the IR. This helps to 1085 reduce the number of IR dumps for "uninteresting" passes. 1086 * Note: Changes are detected by comparing a hash of the operation before 1087 and after the pass. This adds additional run-time to compute the hash of 1088 the IR, and in some rare cases may result in false-positives depending 1089 on the collision rate of the hash algorithm used. 1090 * Note: This option should be used in unison with one of the other 1091 'print-ir-after' options above, as this option alone does not enable 1092 printing. 1093 1094```shell 1095$ mlir-opt foo.mlir -pass-pipeline='func(cse,cse)' -print-ir-after=cse -print-ir-after-change 1096 1097*** IR Dump After CSE *** 1098func @simple_constant() -> (i32, i32) { 1099 %c1_i32 = constant 1 : i32 1100 return %c1_i32, %c1_i32 : i32, i32 1101} 1102``` 1103 1104* `print-ir-module-scope` 1105 * Always print the top-level module operation, regardless of pass type or 1106 operation nesting level. 1107 * Note: Printing at module scope should only be used when multi-threading 1108 is disabled(`-mlir-disable-threading`) 1109 1110```shell 1111$ mlir-opt foo.mlir -mlir-disable-threading -pass-pipeline='func(cse)' -print-ir-after=cse -print-ir-module-scope 1112 1113*** IR Dump After CSE *** ('func' operation: @bar) 1114func @bar(%arg0: f32, %arg1: f32) -> f32 { 1115 ... 1116} 1117 1118func @simple_constant() -> (i32, i32) { 1119 %c1_i32 = constant 1 : i32 1120 %c1_i32_0 = constant 1 : i32 1121 return %c1_i32, %c1_i32_0 : i32, i32 1122} 1123 1124*** IR Dump After CSE *** ('func' operation: @simple_constant) 1125func @bar(%arg0: f32, %arg1: f32) -> f32 { 1126 ... 1127} 1128 1129func @simple_constant() -> (i32, i32) { 1130 %c1_i32 = constant 1 : i32 1131 return %c1_i32, %c1_i32 : i32, i32 1132} 1133``` 1134 1135## Crash and Failure Reproduction 1136 1137The [pass manager](#pass-manager) in MLIR contains a builtin mechanism to 1138generate reproducibles in the even of a crash, or a 1139[pass failure](#pass-failure). This functionality can be enabled via 1140`PassManager::enableCrashReproducerGeneration` or via the command line flag 1141`pass-pipeline-crash-reproducer`. In either case, an argument is provided that 1142corresponds to the output `.mlir` file name that the reproducible should be 1143written to. The reproducible contains the configuration of the pass manager that 1144was executing, as well as the initial IR before any passes were run. A potential 1145reproducible may have the form: 1146 1147```mlir 1148// configuration: -pass-pipeline='func(cse,canonicalize),inline' -verify-each 1149 1150module { 1151 func @foo() { 1152 ... 1153 } 1154} 1155``` 1156 1157The configuration dumped can be passed to `mlir-opt` by specifying 1158`-run-reproducer` flag. This will result in parsing the first line configuration 1159of the reproducer and adding those to the command line options. 1160 1161Beyond specifying a filename, one can also register a `ReproducerStreamFactory` 1162function that would be invoked in the case of a crash and the reproducer written 1163to its stream. 1164 1165### Local Reproducer Generation 1166 1167An additional flag may be passed to 1168`PassManager::enableCrashReproducerGeneration`, and specified via 1169`pass-pipeline-local-reproducer` on the command line, that signals that the pass 1170manager should attempt to generate a "local" reproducer. This will attempt to 1171generate a reproducer containing IR right before the pass that fails. This is 1172useful for situations where the crash is known to be within a specific pass, or 1173when the original input relies on components (like dialects or passes) that may 1174not always be available. 1175 1176For example, if the failure in the previous example came from `canonicalize`, 1177the following reproducer will be generated: 1178 1179```mlir 1180// configuration: -pass-pipeline='func(canonicalize)' 1181// note: verifyPasses=false 1182 1183module { 1184 func @foo() { 1185 ... 1186 } 1187} 1188``` 1189