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
223Asking for a cached and immutable outer level IR analysis works via
224``getCachedResult()``, but getting direct access to an outer level IR analysis
225manager to compute an outer level IR analysis is not allowed. This is for a
226couple reasons.
227
228The first reason is that running analyses across outer level IR in inner level
229IR passes can result in quadratic compile time behavior. For example, a module
230analysis often scans every function and allowing function passes to run a module
231analysis may cause us to scan functions a quadratic number of times. If passes
232could keep outer level analyses up to date rather than computing them on demand
233this wouldn't be an issue, but that would be a lot of work to ensure every pass
234updates all outer level analyses, and so far this hasn't been necessary and
235there isn't infrastructure for this (aside from function analyses in loop passes
236as described below). Self-updating analyses that gracefully degrade also handle
237this problem (e.g. GlobalsAA), but they run into the issue of having to be
238manually recomputed somewhere in the optimization pipeline if we want precision,
239and they block potential future concurrency.
240
241The second reason is to keep in mind potential future pass concurrency, for
242example parallelizing function passes over different functions in a CGSCC or
243module. Since passes can ask for a cached analysis result, allowing passes to
244trigger outer level analysis computation could result in non-determinism if
245concurrency was supported. A related limitation is that outer level IR analyses
246that are used must be immutable, or else they could be invalidated by changes to
247inner level IR. Outer analyses unused by inner passes can and often will be
248invalidated by changes to inner level IR. These invalidations happen after the
249inner pass manager finishes, so accessing mutable analyses would give invalid
250results.
251
252The exception to not being able to access outer level analyses is accessing
253function analyses in loop passes. Loop passes often use function analyses such
254as the dominator tree. Loop passes inherently require modifying the function the
255loop is in, and that includes some function analyses the loop analyses depend
256on. This discounts future concurrency over separate loops in a function, but
257that's a tradeoff due to how tightly a loop and its function are coupled. To
258make sure the function analyses that loop passes use are valid, they are
259manually updated in the loop passes to ensure that invalidation is not
260necessary. There is a set of common function analyses that loop passes and
261analyses have access to which is passed into loop passes as a
262``LoopStandardAnalysisResults`` parameter. Other mutable function analyses are
263not accessible from loop passes.
264
265As with any caching mechanism, we need some way to tell analysis managers
266when results are no longer valid. Much of the analysis manager complexity
267comes from trying to invalidate as few analysis results as possible to keep
268compile times as low as possible.
269
270There are two ways to deal with potentially invalid analysis results. One is
271to simply force clear the results. This should generally only be used when
272the IR that the result is keyed on becomes invalid. For example, a function
273is deleted, or a CGSCC has become invalid due to call graph changes.
274
275The typical way to invalidate analysis results is for a pass to declare what
276types of analyses it preserves and what types it does not. When transforming
277IR, a pass either has the option to update analyses alongside the IR
278transformation, or tell the analysis manager that analyses are no longer
279valid and should be invalidated. If a pass wants to keep some specific
280analysis up to date, such as when updating it would be faster than
281invalidating and recalculating it, the analysis itself may have methods to
282update it for specific transformations, or there may be helper updaters like
283``DomTreeUpdater`` for a ``DominatorTree``. Otherwise to mark some analysis
284as no longer valid, the pass can return a ``PreservedAnalyses`` with the
285proper analyses invalidated.
286
287.. code-block:: c++
288
289  // We've made no transformations that can affect any analyses.
290  return PreservedAnalyses::all();
291
292  // We've made transformations and don't want to bother to update any analyses.
293  return PreservedAnalyses::none();
294
295  // We've specifically updated the dominator tree alongside any transformations, but other analysis results may be invalid.
296  PreservedAnalyses PA;
297  PA.preserve<DominatorAnalysis>();
298  return PA;
299
300  // We haven't made any control flow changes, any analyses that only care about the control flow are still valid.
301  PreservedAnalyses PA;
302  PA.preserveSet<CFGAnalyses>();
303  return PA;
304
305The pass manager will call the analysis manager's ``invalidate()`` method
306with the pass's returned ``PreservedAnalyses``. This can be also done
307manually within the pass:
308
309.. code-block:: c++
310
311  FooModulePass::run(Module& M, ModuleAnalysisManager& AM) {
312    auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
313
314    // Invalidate all analysis results for function F1.
315    FAM.invalidate(F1, PreservedAnalyses::none());
316
317    // Invalidate all analysis results across the entire module.
318    AM.invalidate(M, PreservedAnalyses::none());
319
320    // Clear the entry in the analysis manager for function F2 if we've completely removed it from the module.
321    FAM.clear(F2);
322
323    ...
324  }
325
326One thing to note when accessing inner level IR analyses is cached results for
327deleted IR. If a function is deleted in a module pass, its address is still used
328as the key for cached analyses. Take care in the pass to either clear the
329results for that function or not use inner analyses at all.
330
331``AM.invalidate(M, PreservedAnalyses::none());`` will invalidate the inner
332analysis manager proxy which will clear all cached analyses, conservatively
333assuming that there are invalid addresses used as keys for cached analyses.
334However, if you'd like to be more selective about which analyses are
335cached/invalidated, you can mark the analysis manager proxy as preserved,
336essentially saying that all deleted entries have been taken care of manually.
337This should only be done with measurable compile time gains as it can be tricky
338to make sure all the right analyses are invalidated.
339
340Implementing Analysis Invalidation
341==================================
342
343By default, an analysis is invalidated if ``PreservedAnalyses`` says that
344analyses on the IR unit it runs on are not preserved (see
345``AnalysisResultModel::invalidate()``). An analysis can implement
346``invalidate()`` to be more conservative when it comes to invalidation. For
347example,
348
349.. code-block:: c++
350
351  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
352                                     FunctionAnalysisManager::Invalidator &) {
353    auto PAC = PA.getChecker<FooAnalysis>();
354    // the default would be:
355    // return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>());
356    return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()
357        || PAC.preservedSet<CFGAnalyses>());
358  }
359
360says that if the ``PreservedAnalyses`` specifically preserves
361``FooAnalysis``, or if ``PreservedAnalyses`` preserves all analyses (implicit
362in ``PAC.preserved()``), or if ``PreservedAnalyses`` preserves all function
363analyses, or ``PreservedAnalyses`` preserves all analyses that only care
364about the CFG, the ``FooAnalysisResult`` should not be invalidated.
365
366If an analysis is stateless and generally shouldn't be invalidated, use the
367following:
368
369.. code-block:: c++
370
371  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
372                                     FunctionAnalysisManager::Invalidator &) {
373    // Check whether the analysis has been explicitly invalidated. Otherwise, it's
374    // stateless and remains preserved.
375    auto PAC = PA.getChecker<FooAnalysis>();
376    return !PAC.preservedWhenStateless();
377  }
378
379If an analysis depends on other analyses, those analyses also need to be
380checked if they are invalidated:
381
382.. code-block:: c++
383
384  bool FooAnalysisResult::invalidate(Function &F, const PreservedAnalyses &PA,
385                                     FunctionAnalysisManager::Invalidator &) {
386    auto PAC = PA.getChecker<FooAnalysis>();
387    if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
388      return true;
389
390    // Check transitive dependencies.
391    return Inv.invalidate<BarAnalysis>(F, PA) ||
392          Inv.invalidate<BazAnalysis>(F, PA);
393  }
394
395Combining invalidation and analysis manager proxies results in some
396complexity. For example, when we invalidate all analyses in a module pass,
397we have to make sure that we also invalidate function analyses accessible via
398any existing inner proxies. The inner proxy's ``invalidate()`` first checks
399if the proxy itself should be invalidated. If so, that means the proxy may
400contain pointers to IR that is no longer valid, meaning that the inner proxy
401needs to completely clear all relevant analysis results. Otherwise the proxy
402simply forwards the invalidation to the inner analysis manager.
403
404Generally for outer proxies, analysis results from the outer analysis manager
405should be immutable, so invalidation shouldn't be a concern. However, it is
406possible for some inner analysis to depend on some outer analysis, and when
407the outer analysis is invalidated, we need to make sure that dependent inner
408analyses are also invalidated. This actually happens with alias analysis
409results. Alias analysis is a function-level analysis, but there are
410module-level implementations of specific types of alias analysis. Currently
411``GlobalsAA`` is the only module-level alias analysis and it generally is not
412invalidated so this is not so much of a concern. See
413``OuterAnalysisManagerProxy::Result::registerOuterAnalysisInvalidation()``
414for more details.
415
416Invoking ``opt``
417================
418
419To use the legacy pass manager:
420
421.. code-block:: shell
422
423  $ opt -enable-new-pm=0 -pass1 -pass2 /tmp/a.ll -S
424
425This will be removed once the legacy pass manager is deprecated and removed for
426the optimization pipeline.
427
428To use the new PM:
429
430.. code-block:: shell
431
432  $ opt -passes='pass1,pass2' /tmp/a.ll -S
433
434The new PM typically requires explicit pass nesting. For example, to run a
435function pass, then a module pass, we need to wrap the function pass in a module
436adaptor:
437
438.. code-block:: shell
439
440  $ opt -passes='function(no-op-function),no-op-module' /tmp/a.ll -S
441
442A more complete example, and ``-debug-pass-manager`` to show the execution
443order:
444
445.. code-block:: shell
446
447  $ 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
448
449Improper nesting can lead to error messages such as
450
451.. code-block:: shell
452
453  $ opt -passes='no-op-function,no-op-module' /tmp/a.ll -S
454  opt: unknown function pass 'no-op-module'
455
456The nesting is: module (-> cgscc) -> function -> loop, where the CGSCC nesting is optional.
457
458There are a couple of special cases for easier typing:
459
460* If the first pass is not a module pass, a pass manager of the first pass is
461  implicitly created
462
463  * For example, the following are equivalent
464
465.. code-block:: shell
466
467  $ opt -passes='no-op-function,no-op-function' /tmp/a.ll -S
468  $ opt -passes='function(no-op-function,no-op-function)' /tmp/a.ll -S
469
470* If there is an adaptor for a pass that lets it fit in the previous pass
471  manager, that is implicitly created
472
473  * For example, the following are equivalent
474
475.. code-block:: shell
476
477  $ opt -passes='no-op-function,no-op-loop' /tmp/a.ll -S
478  $ opt -passes='no-op-function,loop(no-op-loop)' /tmp/a.ll -S
479
480For a list of available passes and analyses, including the IR unit (module,
481CGSCC, function, loop) they operate on, run
482
483.. code-block:: shell
484
485  $ opt --print-passes
486
487or take a look at ``PassRegistry.def``.
488
489To make sure an analysis named ``foo`` is available before a pass, add
490``require<foo>`` to the pass pipeline. This adds a pass that simply requests
491that the analysis is run. This pass is also subject to proper nesting.  For
492example, to make sure some function analysis is already computed for all
493functions before a module pass:
494
495.. code-block:: shell
496
497  $ opt -passes='function(require<my-function-analysis>),my-module-pass' /tmp/a.ll -S
498
499Status of the New and Legacy Pass Managers
500==========================================
501
502LLVM currently contains two pass managers, the legacy PM and the new PM. The
503optimization pipeline (aka the middle-end) works with both the legacy PM and
504the new PM, whereas the backend target-dependent code generation only works
505with the legacy PM.
506
507For the optimization pipeline, the new PM is the default PM. Using the legacy PM
508for the optimization pipeline is deprecated and there are ongoing efforts to
509remove its usage.
510
511Some IR passes are considered part of the backend codegen pipeline even if
512they are LLVM IR passes (whereas all MIR passes are codegen passes). This
513includes anything added via ``TargetPassConfig`` hooks, e.g.
514``TargetPassConfig::addCodeGenPrepare()``. As mentioned before, passes added
515in ``TargetMachine::adjustPassManager()`` are part of the optimization
516pipeline, and should have a corresponding line in
517``TargetMachine::registerPassBuilderCallbacks()``.
518
519Currently there are efforts to make the codegen pipeline work with the new
520PM.
521