1 ==========================
2 Using the New Pass Manager
3 ==========================
11 For an overview of the new pass manager, see the `blog post
12 <https://blog.llvm.org/posts/2021-03-26-the-new-pass-manager/>`_.
14 Just Tell Me How To Run The Default Optimization Pipeline With The New Pass Manager
15 ===================================================================================
19 // Create the analysis managers.
20 LoopAnalysisManager LAM;
21 FunctionAnalysisManager FAM;
22 CGSCCAnalysisManager CGAM;
23 ModuleAnalysisManager MAM;
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
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);
38 // Create the pass manager.
39 // This one corresponds to a typical -O2 optimization pipeline.
40 ModulePassManager MPM = PB.buildPerModuleDefaultPipeline(OptimizationLevel::O2);
43 MPM.run(MyModule, MAM);
45 The C API also supports most of this, see ``llvm-c/Transforms/PassBuilder.h``.
47 Adding Passes to a Pass Manager
48 ===============================
50 For how to write a new PM pass, see :doc:`this page <WritingAnLLVMNewPMPass>`.
52 To add a pass to a new PM pass manager, the important thing is to match the
53 pass type and the pass manager type. For example, a ``FunctionPassManager``
54 can only contain function passes:
58 FunctionPassManager FPM;
59 // InstSimplifyPass is a function pass
60 FPM.addPass(InstSimplifyPass());
62 If 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
64 adaptor that goes through all the loops in the function and runs the loop
69 FunctionPassManager FPM;
70 // LoopRotatePass is a loop pass
71 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
73 The IR hierarchy in terms of the new PM is Module -> (CGSCC ->) Function ->
74 Loop, where going through a CGSCC is optional.
78 FunctionPassManager FPM;
80 FPM.addPass(createFunctionToLoopPassAdaptor(LoopFooPass()));
82 CGSCCPassManager CGPM;
83 // loop -> function -> cgscc
84 CGPM.addPass(createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass())));
86 CGPM.addPass(createCGSCCToFunctionPassAdaptor(FunctionFooPass()));
88 ModulePassManager MPM;
89 // loop -> function -> module
90 MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass())));
92 MPM.addPass(createModuleToFunctionPassAdaptor(FunctionFooPass()));
94 // loop -> function -> cgscc -> module
95 MPM.addPass(createModuleToCGSCCPassAdaptor(createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(LoopFooPass()))));
96 // function -> cgscc -> module
97 MPM.addPass(createModuleToCGSCCPassAdaptor(createCGSCCToFunctionPassAdaptor(FunctionFooPass())));
100 A pass manager of a specific IR unit is also a pass of that kind. For
101 example, a ``FunctionPassManager`` is a function pass, meaning it can be
102 added to a ``ModulePassManager``:
106 ModulePassManager MPM;
108 FunctionPassManager FPM;
109 // InstSimplifyPass is a function pass
110 FPM.addPass(InstSimplifyPass());
112 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
114 Generally you want to group CGSCC/function/loop passes together in a pass
115 manager, as opposed to adding adaptors for each pass to the containing upper
116 level pass manager. For example,
120 ModulePassManager MPM;
121 MPM.addPass(createModuleToFunctionPassAdaptor(FunctionPass1()));
122 MPM.addPass(createModuleToFunctionPassAdaptor(FunctionPass2()));
125 will run ``FunctionPass1`` on each function in a module, then run
126 ``FunctionPass2`` on each function in the module. In contrast,
130 ModulePassManager MPM;
132 FunctionPassManager FPM;
133 FPM.addPass(FunctionPass1());
134 FPM.addPass(FunctionPass2());
136 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
138 will run ``FunctionPass1`` and ``FunctionPass2`` on the first function in a
139 module, then run both passes on the second function in the module, and so on.
140 This is better for cache locality around LLVM data structures. This similarly
141 applies for the other IR types, and in some cases can even affect the quality
142 of optimization. For example, running all loop passes on a loop may cause a
143 later loop to be able to be optimized more than if each loop pass were run
146 Inserting Passes into Default Pipelines
147 =======================================
149 Rather than manually adding passes to a pass manager, the typical way of
150 creating a pass manager is to use a ``PassBuilder`` and call something like
151 ``PassBuilder::buildPerModuleDefaultPipeline()`` which creates a typical
152 pipeline for a given optimization level.
154 Sometimes either frontends or backends will want to inject passes into the
155 pipeline. For example, frontends may want to add instrumentation, and target
156 backends may want to add passes that lower custom intrinsics. For these
157 cases, ``PassBuilder`` exposes callbacks that allow injecting passes into
158 certain parts of the pipeline. For example,
163 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM,
164 PassBuilder::OptimizationLevel Level) {
165 MPM.addPass(FooPass());
168 will add ``FooPass`` near the very beginning of the pipeline for pass
169 managers created by that ``PassBuilder``. See the documentation for
170 ``PassBuilder`` for the various places that passes can be added.
172 If a ``PassBuilder`` has a corresponding ``TargetMachine`` for a backend, it
173 will call ``TargetMachine::registerPassBuilderCallbacks()`` to allow the
174 backend to inject passes into the pipeline. This is equivalent to the legacy
175 PM's ``TargetMachine::adjustPassManager()``.
177 Clang's ``BackendUtil.cpp`` shows examples of a frontend adding (mostly
178 sanitizer) passes to various parts of the pipeline.
179 ``AMDGPUTargetMachine::registerPassBuilderCallbacks()`` is an example of a
180 backend adding passes to various parts of the pipeline.
185 LLVM provides many analyses that passes can use, such as a dominator tree.
186 Calculating these can be expensive, so the new pass manager has
187 infrastructure to cache analyses and reuse them when possible.
189 When a pass runs on some IR, it also receives an analysis manager which it can
190 query for analyses. Querying for an analysis will cause the manager to check if
191 it has already computed the result for the requested IR. If it already has and
192 the result is still valid, it will return that. Otherwise it will construct a
193 new result by calling the analysis's ``run()`` method, cache it, and return it.
194 You can also ask the analysis manager to only return an analysis if it's
197 The analysis manager only provides analysis results for the same IR type as
198 what the pass runs on. For example, a function pass receives an analysis
199 manager that only provides function-level analyses. This works for many
200 passes which work on a fixed scope. However, some passes want to peek up or
201 down the IR hierarchy. For example, an SCC pass may want to look at function
202 analyses for the functions inside the SCC. Or it may want to look at some
203 immutable global analysis. In these cases, the analysis manager can provide a
204 proxy to an outer or inner level analysis manager. For example, to get a
205 ``FunctionAnalysisManager`` from a ``CGSCCAnalysisManager``, you can call
209 FunctionAnalysisManager &FAM =
210 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)
213 and use ``FAM`` as a typical ``FunctionAnalysisManager`` that a function pass
214 would have access to. To get access to an outer level IR analysis, you can
219 const auto &MAMProxy =
220 AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG);
221 FooAnalysisResult *AR = MAMProxy.getCachedResult<FooAnalysis>(M);
223 Asking for a cached and immutable outer level IR analysis works via
224 ``getCachedResult()``, but getting direct access to an outer level IR analysis
225 manager to compute an outer level IR analysis is not allowed. This is for a
228 The first reason is that running analyses across outer level IR in inner level
229 IR passes can result in quadratic compile time behavior. For example, a module
230 analysis often scans every function and allowing function passes to run a module
231 analysis may cause us to scan functions a quadratic number of times. If passes
232 could keep outer level analyses up to date rather than computing them on demand
233 this wouldn't be an issue, but that would be a lot of work to ensure every pass
234 updates all outer level analyses, and so far this hasn't been necessary and
235 there isn't infrastructure for this (aside from function analyses in loop passes
236 as described below). Self-updating analyses that gracefully degrade also handle
237 this problem (e.g. GlobalsAA), but they run into the issue of having to be
238 manually recomputed somewhere in the optimization pipeline if we want precision,
239 and they block potential future concurrency.
241 The second reason is to keep in mind potential future pass concurrency, for
242 example parallelizing function passes over different functions in a CGSCC or
243 module. Since passes can ask for a cached analysis result, allowing passes to
244 trigger outer level analysis computation could result in non-determinism if
245 concurrency was supported. A related limitation is that outer level IR analyses
246 that are used must be immutable, or else they could be invalidated by changes to
247 inner level IR. Outer analyses unused by inner passes can and often will be
248 invalidated by changes to inner level IR. These invalidations happen after the
249 inner pass manager finishes, so accessing mutable analyses would give invalid
252 The exception to not being able to access outer level analyses is accessing
253 function analyses in loop passes. Loop passes often use function analyses such
254 as the dominator tree. Loop passes inherently require modifying the function the
255 loop is in, and that includes some function analyses the loop analyses depend
256 on. This discounts future concurrency over separate loops in a function, but
257 that's a tradeoff due to how tightly a loop and its function are coupled. To
258 make sure the function analyses that loop passes use are valid, they are
259 manually updated in the loop passes to ensure that invalidation is not
260 necessary. There is a set of common function analyses that loop passes and
261 analyses have access to which is passed into loop passes as a
262 ``LoopStandardAnalysisResults`` parameter. Other mutable function analyses are
263 not accessible from loop passes.
265 As with any caching mechanism, we need some way to tell analysis managers
266 when results are no longer valid. Much of the analysis manager complexity
267 comes from trying to invalidate as few analysis results as possible to keep
268 compile times as low as possible.
270 There are two ways to deal with potentially invalid analysis results. One is
271 to simply force clear the results. This should generally only be used when
272 the IR that the result is keyed on becomes invalid. For example, a function
273 is deleted, or a CGSCC has become invalid due to call graph changes.
275 The typical way to invalidate analysis results is for a pass to declare what
276 types of analyses it preserves and what types it does not. When transforming
277 IR, a pass either has the option to update analyses alongside the IR
278 transformation, or tell the analysis manager that analyses are no longer
279 valid and should be invalidated. If a pass wants to keep some specific
280 analysis up to date, such as when updating it would be faster than
281 invalidating and recalculating it, the analysis itself may have methods to
282 update it for specific transformations, or there may be helper updaters like
283 ``DomTreeUpdater`` for a ``DominatorTree``. Otherwise to mark some analysis
284 as no longer valid, the pass can return a ``PreservedAnalyses`` with the
285 proper analyses invalidated.
289 // We've made no transformations that can affect any analyses.
290 return PreservedAnalyses::all();
292 // We've made transformations and don't want to bother to update any analyses.
293 return PreservedAnalyses::none();
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>();
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>();
305 The pass manager will call the analysis manager's ``invalidate()`` method
306 with the pass's returned ``PreservedAnalyses``. This can be also done
307 manually within the pass:
311 FooModulePass::run(Module& M, ModuleAnalysisManager& AM) {
312 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
314 // Invalidate all analysis results for function F1.
315 FAM.invalidate(F1, PreservedAnalyses::none());
317 // Invalidate all analysis results across the entire module.
318 AM.invalidate(M, PreservedAnalyses::none());
320 // Clear the entry in the analysis manager for function F2 if we've completely removed it from the module.
326 One thing to note when accessing inner level IR analyses is cached results for
327 deleted IR. If a function is deleted in a module pass, its address is still used
328 as the key for cached analyses. Take care in the pass to either clear the
329 results for that function or not use inner analyses at all.
331 ``AM.invalidate(M, PreservedAnalyses::none());`` will invalidate the inner
332 analysis manager proxy which will clear all cached analyses, conservatively
333 assuming that there are invalid addresses used as keys for cached analyses.
334 However, if you'd like to be more selective about which analyses are
335 cached/invalidated, you can mark the analysis manager proxy as preserved,
336 essentially saying that all deleted entries have been taken care of manually.
337 This should only be done with measurable compile time gains as it can be tricky
338 to make sure all the right analyses are invalidated.
340 Implementing Analysis Invalidation
341 ==================================
343 By default, an analysis is invalidated if ``PreservedAnalyses`` says that
344 analyses 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
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>());
360 says that if the ``PreservedAnalyses`` specifically preserves
361 ``FooAnalysis``, or if ``PreservedAnalyses`` preserves all analyses (implicit
362 in ``PAC.preserved()``), or if ``PreservedAnalyses`` preserves all function
363 analyses, or ``PreservedAnalyses`` preserves all analyses that only care
364 about the CFG, the ``FooAnalysisResult`` should not be invalidated.
366 If an analysis is stateless and generally shouldn't be invalidated, use the
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();
379 If an analysis depends on other analyses, those analyses also need to be
380 checked if they are invalidated:
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>>())
390 // Check transitive dependencies.
391 return Inv.invalidate<BarAnalysis>(F, PA) ||
392 Inv.invalidate<BazAnalysis>(F, PA);
395 Combining invalidation and analysis manager proxies results in some
396 complexity. For example, when we invalidate all analyses in a module pass,
397 we have to make sure that we also invalidate function analyses accessible via
398 any existing inner proxies. The inner proxy's ``invalidate()`` first checks
399 if the proxy itself should be invalidated. If so, that means the proxy may
400 contain pointers to IR that is no longer valid, meaning that the inner proxy
401 needs to completely clear all relevant analysis results. Otherwise the proxy
402 simply forwards the invalidation to the inner analysis manager.
404 Generally for outer proxies, analysis results from the outer analysis manager
405 should be immutable, so invalidation shouldn't be a concern. However, it is
406 possible for some inner analysis to depend on some outer analysis, and when
407 the outer analysis is invalidated, we need to make sure that dependent inner
408 analyses are also invalidated. This actually happens with alias analysis
409 results. Alias analysis is a function-level analysis, but there are
410 module-level implementations of specific types of alias analysis. Currently
411 ``GlobalsAA`` is the only module-level alias analysis and it generally is not
412 invalidated so this is not so much of a concern. See
413 ``OuterAnalysisManagerProxy::Result::registerOuterAnalysisInvalidation()``
419 To use the legacy pass manager:
421 .. code-block:: shell
423 $ opt -enable-new-pm=0 -pass1 -pass2 /tmp/a.ll -S
425 This will be removed once the legacy pass manager is deprecated and removed for
426 the optimization pipeline.
430 .. code-block:: shell
432 $ opt -passes='pass1,pass2' /tmp/a.ll -S
434 The new PM typically requires explicit pass nesting. For example, to run a
435 function pass, then a module pass, we need to wrap the function pass in a module
438 .. code-block:: shell
440 $ opt -passes='function(no-op-function),no-op-module' /tmp/a.ll -S
442 A more complete example, and ``-debug-pass-manager`` to show the execution
445 .. code-block:: shell
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
449 Improper nesting can lead to error messages such as
451 .. code-block:: shell
453 $ opt -passes='no-op-function,no-op-module' /tmp/a.ll -S
454 opt: unknown function pass 'no-op-module'
456 The nesting is: module (-> cgscc) -> function -> loop, where the CGSCC nesting is optional.
458 There are a couple of special cases for easier typing:
460 * If the first pass is not a module pass, a pass manager of the first pass is
463 * For example, the following are equivalent
465 .. code-block:: shell
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
470 * If there is an adaptor for a pass that lets it fit in the previous pass
471 manager, that is implicitly created
473 * For example, the following are equivalent
475 .. code-block:: shell
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
480 For a list of available passes and analyses, including the IR unit (module,
481 CGSCC, function, loop) they operate on, run
483 .. code-block:: shell
487 or take a look at ``PassRegistry.def``.
489 To 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
491 that the analysis is run. This pass is also subject to proper nesting. For
492 example, to make sure some function analysis is already computed for all
493 functions before a module pass:
495 .. code-block:: shell
497 $ opt -passes='function(require<my-function-analysis>),my-module-pass' /tmp/a.ll -S
499 Status of the New and Legacy Pass Managers
500 ==========================================
502 LLVM currently contains two pass managers, the legacy PM and the new PM. The
503 optimization pipeline (aka the middle-end) works with both the legacy PM and
504 the new PM, whereas the backend target-dependent code generation only works
507 For the optimization pipeline, the new PM is the default PM. Using the legacy PM
508 for the optimization pipeline is deprecated and there are ongoing efforts to
511 Some IR passes are considered part of the backend codegen pipeline even if
512 they are LLVM IR passes (whereas all MIR passes are codegen passes). This
513 includes anything added via ``TargetPassConfig`` hooks, e.g.
514 ``TargetPassConfig::addCodeGenPrepare()``. As mentioned before, passes added
515 in ``TargetMachine::adjustPassManager()`` are part of the optimization
516 pipeline, and should have a corresponding line in
517 ``TargetMachine::registerPassBuilderCallbacks()``.
519 Currently there are efforts to make the codegen pipeline work with the new