1==========================
2Using the New Pass Manager
3==========================
4
5.. contents::
6    :local:
7
8Overview
9========
10
11For an overview of the new pass manager, see the `blog post
12<https://blog.llvm.org/posts/2021-03-26-the-new-pass-manager/>`_.
13
14Just Tell Me How To Run The Default Optimization Pipeline With The New Pass Manager
15===================================================================================
16
17.. code-block:: c++
18
19  // Create the analysis managers.
20  LoopAnalysisManager LAM;
21  FunctionAnalysisManager FAM;
22  CGSCCAnalysisManager CGAM;
23  ModuleAnalysisManager MAM;
24
25  // Create the new pass manager builder.
26  // Take a look at the PassBuilder constructor parameters for more
27  // customization, e.g. specifying a TargetMachine or various debugging
28  // options.
29  PassBuilder PB;
30
31  // Register all the basic analyses with the managers.
32  PB.registerModuleAnalyses(MAM);
33  PB.registerCGSCCAnalyses(CGAM);
34  PB.registerFunctionAnalyses(FAM);
35  PB.registerLoopAnalyses(LAM);
36  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
37
38  // Create the pass manager.
39  // This one corresponds to a typical -O2 optimization pipeline.
40  ModulePassManager MPM = PB.buildPerModuleDefaultPipeline(OptimizationLevel::O2);
41
42  // Optimize the IR!
43  MPM.run(MyModule, MAM);
44
45The C API also supports most of this, see ``llvm-c/Transforms/PassBuilder.h``.
46
47Adding Passes to a Pass Manager
48===============================
49
50For how to write a new PM pass, see :doc:`this page <WritingAnLLVMNewPMPass>`.
51
52To add a pass to a new PM pass manager, the important thing is to match the
53pass type and the pass manager type. For example, a ``FunctionPassManager``
54can only contain function passes:
55
56.. code-block:: c++
57
58  FunctionPassManager FPM;
59  // InstSimplifyPass is a function pass
60  FPM.addPass(InstSimplifyPass());
61
62If you want to add a loop pass that runs on all loops in a function to a
63``FunctionPassManager``, the loop pass must be wrapped in a function pass
64adaptor that goes through all the loops in the function and runs the loop
65pass on each one.
66
67.. code-block:: c++
68
69  FunctionPassManager FPM;
70  // LoopRotatePass is a loop pass
71  FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
72
73The IR hierarchy in terms of the new PM is Module -> (CGSCC ->) Function ->
74Loop, where going through a CGSCC is optional.
75
76.. code-block:: c++
77
78  FunctionPassManager FPM;
79  // loop -> function
80  FPM.addPass(createFunctionToLoopPassAdaptor(LoopFooPass()));
81
82  CGSCCPassManager CGPM;
83  // loop -> function -> cgscc
84  CGPM.addPass(createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass())));
85  // function -> cgscc
86  CGPM.addPass(createCGSCCToFunctionPassAdaptor(FunctionFooPass()));
87
88  ModulePassManager MPM;
89  // loop -> function -> module
90  MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass())));
91  // function -> module
92  MPM.addPass(createModuleToFunctionPassAdaptor(FunctionFooPass()));
93
94  // loop -> function -> cgscc -> module
95  MPM.addPass(createModuleToCGSCCPassAdaptor(createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass()))));
96  // function -> cgscc -> module
97  MPM.addPass(createModuleToCGSCCPassAdaptor(createCGSCCToFunctionPassAdaptor(FunctionFooPass())));
98
99
100A pass manager of a specific IR unit is also a pass of that kind. For
101example, a ``FunctionPassManager`` is a function pass, meaning it can be
102added to a ``ModulePassManager``:
103
104.. code-block:: c++
105
106  ModulePassManager MPM;
107
108  FunctionPassManager FPM;
109  // InstSimplifyPass is a function pass
110  FPM.addPass(InstSimplifyPass());
111
112  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
113
114Generally you want to group CGSCC/function/loop passes together in a pass
115manager, as opposed to adding adaptors for each pass to the containing upper
116level pass manager. For example,
117
118.. code-block:: c++
119
120  ModulePassManager MPM;
121  MPM.addPass(createModuleToFunctionPassAdaptor(FunctionPass1()));
122  MPM.addPass(createModuleToFunctionPassAdaptor(FunctionPass2()));
123  MPM.run();
124
125will run ``FunctionPass1`` on each function in a module, then run
126``FunctionPass2`` on each function in the module. In contrast,
127
128.. code-block:: c++
129
130  ModulePassManager MPM;
131
132  FunctionPassManager FPM;
133  FPM.addPass(FunctionPass1());
134  FPM.addPass(FunctionPass2());
135
136  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
137
138will run ``FunctionPass1`` and ``FunctionPass2`` on the first function in a
139module, then run both passes on the second function in the module, and so on.
140This is better for cache locality around LLVM data structures. This similarly
141applies for the other IR types, and in some cases can even affect the quality
142of optimization. For example, running all loop passes on a loop may cause a
143later loop to be able to be optimized more than if each loop pass were run
144separately.
145
146Inserting Passes into Default Pipelines
147=======================================
148
149Rather than manually adding passes to a pass manager, the typical way of
150creating a pass manager is to use a ``PassBuilder`` and call something like
151``PassBuilder::buildPerModuleDefaultPipeline()`` which creates a typical
152pipeline for a given optimization level.
153
154Sometimes either frontends or backends will want to inject passes into the
155pipeline. For example, frontends may want to add instrumentation, and target
156backends may want to add passes that lower custom intrinsics. For these
157cases, ``PassBuilder`` exposes callbacks that allow injecting passes into
158certain parts of the pipeline. For example,
159
160.. code-block:: c++
161
162  PassBuilder PB;
163  PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM,
164                                         PassBuilder::OptimizationLevel Level) {
165      MPM.addPass(FooPass());
166  };
167
168will add ``FooPass`` near the very beginning of the pipeline for pass
169managers created by that ``PassBuilder``. See the documentation for
170``PassBuilder`` for the various places that passes can be added.
171
172If a ``PassBuilder`` has a corresponding ``TargetMachine`` for a backend, it
173will call ``TargetMachine::registerPassBuilderCallbacks()`` to allow the
174backend to inject passes into the pipeline. This is equivalent to the legacy
175PM's ``TargetMachine::adjustPassManager()``.
176
177Clang's ``BackendUtil.cpp`` shows examples of a frontend adding (mostly
178sanitizer) passes to various parts of the pipeline.
179``AMDGPUTargetMachine::registerPassBuilderCallbacks()`` is an example of a
180backend adding passes to various parts of the pipeline.
181
182Using Analyses
183==============
184
185LLVM provides many analyses that passes can use, such as a dominator tree.
186Calculating these can be expensive, so the new pass manager has
187infrastructure to cache analyses and reuse them when possible.
188
189When a pass runs on some IR, it also receives an analysis manager which it can
190query for analyses. Querying for an analysis will cause the manager to check if
191it has already computed the result for the requested IR. If it already has and
192the result is still valid, it will return that. Otherwise it will construct a
193new result by calling the analysis's ``run()`` method, cache it, and return it.
194You can also ask the analysis manager to only return an analysis if it's
195already cached.
196
197The analysis manager only provides analysis results for the same IR type as
198what the pass runs on. For example, a function pass receives an analysis
199manager that only provides function-level analyses. This works for many
200passes which work on a fixed scope. However, some passes want to peek up or
201down the IR hierarchy. For example, an SCC pass may want to look at function
202analyses for the functions inside the SCC. Or it may want to look at some
203immutable global analysis. In these cases, the analysis manager can provide a
204proxy to an outer or inner level analysis manager. For example, to get a
205``FunctionAnalysisManager`` from a ``CGSCCAnalysisManager``, you can call
206
207.. code-block:: c++
208
209  FunctionAnalysisManager &FAM =
210      AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)
211          .getManager();
212
213and use ``FAM`` as a typical ``FunctionAnalysisManager`` that a function pass
214would have access to. To get access to an outer level IR analysis, you can
215call
216
217.. code-block:: c++
218
219  const auto &MAMProxy =
220      AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG);
221  FooAnalysisResult *AR = MAMProxy.getCachedResult<FooAnalysis>(M);
222
223Getting direct access to an outer level IR analysis manager is not allowed.
224This is to keep in mind potential future pass concurrency, for example
225parallelizing function passes over different functions in a CGSCC or module.
226Since passes can ask for a cached analysis result, allowing passes to trigger
227outer level analysis computation could result in non-determinism if
228concurrency was supported. Therefore a pass running on inner level IR cannot
229change the state of outer level IR analyses. Another limitation is that outer
230level IR analyses that are used must be immutable, or else they could be
231invalidated by changes to inner level IR. Outer analyses unused by inner
232passes can and often will be invalidated by changes to inner level IR. These
233invalidations happen after the inner pass manager finishes, so accessing
234mutable analyses would give invalid results.
235
236The exception to the above is accessing function analyses in loop passes.
237Loop passes inherently require modifying the function the loop is in, and
238that includes some function analyses the loop analyses depend on. This
239discounts future concurrency over separate loops in a function, but that's a
240tradeoff due to how tightly a loop and its function are coupled. To make sure
241the function analyses loop passes use are valid, they are manually updated in
242the loop passes to ensure that invalidation is not necessary. There is a set
243of common function analyses that loop passes and analyses have access to
244which is passed into loop passes as a ``LoopStandardAnalysisResults``
245parameter. Other function analyses are not accessible from loop passes.
246
247As with any caching mechanism, we need some way to tell analysis managers
248when results are no longer valid. Much of the analysis manager complexity
249comes from trying to invalidate as few analysis results as possible to keep
250compile times as low as possible.
251
252There are two ways to deal with potentially invalid analysis results. One is
253to simply force clear the results. This should generally only be used when
254the IR that the result is keyed on becomes invalid. For example, a function
255is deleted, or a CGSCC has become invalid due to call graph changes.
256
257The typical way to invalidate analysis results is for a pass to declare what
258types of analyses it preserves and what types it does not. When transforming
259IR, a pass either has the option to update analyses alongside the IR
260transformation, or tell the analysis manager that analyses are no longer
261valid and should be invalidated. If a pass wants to keep some specific
262analysis up to date, such as when updating it would be faster than
263invalidating and recalculating it, the analysis itself may have methods to
264update it for specific transformations, or there may be helper updaters like
265``DomTreeUpdater`` for a ``DominatorTree``. Otherwise to mark some analysis
266as no longer valid, the pass can return a ``PreservedAnalyses`` with the
267proper analyses invalidated.
268
269.. code-block:: c++
270
271  // We've made no transformations that can affect any analyses.
272  return PreservedAnalyses::all();
273
274  // We've made transformations and don't want to bother to update any analyses.
275  return PreservedAnalyses::none();
276
277  // We've specifically updated the dominator tree alongside any transformations, but other analysis results may be invalid.
278  PreservedAnalyses PA;
279  PA.preserve<DominatorAnalysis>();
280  return PA;
281
282  // We haven't made any control flow changes, any analyses that only care about the control flow are still valid.
283  PreservedAnalyses PA;
284  PA.preserveSet<CFGAnalyses>();
285  return PA;
286
287The pass manager will call the analysis manager's ``invalidate()`` method
288with the pass's returned ``PreservedAnalyses``. This can be also done
289manually within the pass:
290
291.. code-block:: c++
292
293  FooModulePass::run(Module& M, ModuleAnalysisManager& AM) {
294    auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
295
296    // Invalidate all analysis results for function F
297    FAM.invalidate(F, PreservedAnalyses::none());
298
299    // Invalidate all analysis results
300    AM.invalidate(M, PreservedAnalyses::none());
301
302    ...
303  }
304
305This is especially important when a pass removes then adds a function. The
306analysis manager may store a pointer to a function that has been deleted, and
307if the pass creates a new function before invalidating analysis results, the
308new function may be at the same address as the old one, causing invalid
309cached results. This is also useful for being more precise about
310invalidation. Selectively invalidating analysis results only for functions
311modified in an SCC pass can allow more analysis results to remain. But except
312for complex fine-grain invalidation with inner proxies, passes should
313typically just return a proper ``PreservedAnalyses`` and let the pass manager
314deal with proper invalidation.
315
316Implementing Analysis Invalidation
317==================================
318
319By default, an analysis is invalidated if ``PreservedAnalyses`` says that
320analyses on the IR unit it runs on are not preserved (see
321``AnalysisResultModel::invalidate()``). An analysis can implement
322``invalidate()`` to be more conservative when it comes to invalidation. For
323example,
324
325.. code-block:: c++
326
327  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
328                                     FunctionAnalysisManager::Invalidator &) {
329    auto PAC = PA.getChecker<FooAnalysis>();
330    // the default would be:
331    // return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>());
332    return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()
333        || PAC.preservedSet<CFGAnalyses>());
334  }
335
336says that if the ``PreservedAnalyses`` specifically preserves
337``FooAnalysis``, or if ``PreservedAnalyses`` preserves all analyses (implicit
338in ``PAC.preserved()``), or if ``PreservedAnalyses`` preserves all function
339analyses, or ``PreservedAnalyses`` preserves all analyses that only care
340about the CFG, the ``FooAnalysisResult`` should not be invalidated.
341
342If an analysis is stateless and generally shouldn't be invalidated, use the
343following:
344
345.. code-block:: c++
346
347  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
348                                     FunctionAnalysisManager::Invalidator &) {
349    // Check whether the analysis has been explicitly invalidated. Otherwise, it's
350    // stateless and remains preserved.
351    auto PAC = PA.getChecker<FooAnalysis>();
352    return !PAC.preservedWhenStateless();
353  }
354
355If an analysis depends on other analyses, those analyses also need to be
356checked if they are invalidated:
357
358.. code-block:: c++
359
360  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
361                                     FunctionAnalysisManager::Invalidator &) {
362    auto PAC = PA.getChecker<FooAnalysis>();
363    if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
364      return true;
365
366    // Check transitive dependencies.
367    return Inv.invalidate<BarAnalysis>(F, PA) ||
368          Inv.invalidate<BazAnalysis>(F, PA);
369  }
370
371Combining invalidation and analysis manager proxies results in some
372complexity. For example, when we invalidate all analyses in a module pass,
373we have to make sure that we also invalidate function analyses accessible via
374any existing inner proxies. The inner proxy's ``invalidate()`` first checks
375if the proxy itself should be invalidated. If so, that means the proxy may
376contain pointers to IR that is no longer valid, meaning that the inner proxy
377needs to completely clear all relevant analysis results. Otherwise the proxy
378simply forwards the invalidation to the inner analysis manager.
379
380Generally for outer proxies, analysis results from the outer analysis manager
381should be immutable, so invalidation shouldn't be a concern. However, it is
382possible for some inner analysis to depend on some outer analysis, and when
383the outer analysis is invalidated, we need to make sure that dependent inner
384analyses are also invalidated. This actually happens with alias analysis
385results. Alias analysis is a function-level analysis, but there are
386module-level implementations of specific types of alias analysis. Currently
387``GlobalsAA`` is the only module-level alias analysis and it generally is not
388invalidated so this is not so much of a concern. See
389``OuterAnalysisManagerProxy::Result::registerOuterAnalysisInvalidation()``
390for more details.
391
392Invoking ``opt``
393================
394
395To use the legacy pass manager:
396
397.. code-block:: shell
398
399  $ opt -enable-new-pm=0 -pass1 -pass2 /tmp/a.ll -S
400
401This will be removed once the legacy pass manager is deprecated and removed for
402the optimization pipeline.
403
404To use the new PM:
405
406.. code-block:: shell
407
408  $ opt -passes='pass1,pass2' /tmp/a.ll -S
409
410The new PM typically requires explicit pass nesting. For example, to run a
411function pass, then a module pass, we need to wrap the function pass in a module
412adaptor:
413
414.. code-block:: shell
415
416  $ opt -passes='function(no-op-function),no-op-module' /tmp/a.ll -S
417
418A more complete example, and ``-debug-pass-manager`` to show the execution
419order:
420
421.. code-block:: shell
422
423  $ opt -passes='no-op-module,cgscc(no-op-cgscc,function(no-op-function,loop(no-op-loop))),function(no-op-function,loop(no-op-loop))' /tmp/a.ll -S -debug-pass-manager
424
425Improper nesting can lead to error messages such as
426
427.. code-block:: shell
428
429  $ opt -passes='no-op-function,no-op-module' /tmp/a.ll -S
430  opt: unknown function pass 'no-op-module'
431
432The nesting is: module (-> cgscc) -> function -> loop, where the CGSCC nesting is optional.
433
434There are a couple of special cases for easier typing:
435
436* If the first pass is not a module pass, a pass manager of the first pass is
437  implicitly created
438
439  * For example, the following are equivalent
440
441.. code-block:: shell
442
443  $ opt -passes='no-op-function,no-op-function' /tmp/a.ll -S
444  $ opt -passes='function(no-op-function,no-op-function)' /tmp/a.ll -S
445
446* If there is an adaptor for a pass that lets it fit in the previous pass
447  manager, that is implicitly created
448
449  * For example, the following are equivalent
450
451.. code-block:: shell
452
453  $ opt -passes='no-op-function,no-op-loop' /tmp/a.ll -S
454  $ opt -passes='no-op-function,loop(no-op-loop)' /tmp/a.ll -S
455
456For a list of available passes and analyses, including the IR unit (module,
457CGSCC, function, loop) they operate on, run
458
459.. code-block:: shell
460
461  $ opt --print-passes
462
463or take a look at ``PassRegistry.def``.
464
465To make sure an analysis named ``foo`` is available before a pass, add
466``require<foo>`` to the pass pipeline. This adds a pass that simply requests
467that the analysis is run. This pass is also subject to proper nesting.  For
468example, to make sure some function analysis is already computed for all
469functions before a module pass:
470
471.. code-block:: shell
472
473  $ opt -passes='function(require<my-function-analysis>),my-module-pass' /tmp/a.ll -S
474
475Status of the New and Legacy Pass Managers
476==========================================
477
478LLVM currently contains two pass managers, the legacy PM and the new PM. The
479optimization pipeline (aka the middle-end) works with both the legacy PM and
480the new PM, whereas the backend target-dependent code generation only works
481with the legacy PM.
482
483For the optimization pipeline, the new PM is the default PM. Using the legacy PM
484for the optimization pipeline is deprecated and there are ongoing efforts to
485remove its usage.
486
487Some IR passes are considered part of the backend codegen pipeline even if
488they are LLVM IR passes (whereas all MIR passes are codegen passes). This
489includes anything added via ``TargetPassConfig`` hooks, e.g.
490``TargetPassConfig::addCodeGenPrepare()``. As mentioned before, passes added
491in ``TargetMachine::adjustPassManager()`` are part of the optimization
492pipeline, and should have a corresponding line in
493``TargetMachine::registerPassBuilderCallbacks()``.
494
495Currently there are efforts to make the codegen pipeline work with the new
496PM.
497