Skip to content

Lesson 12.1 — Pass-manager architectures: legacy and new LLVM, GCC, MLIR

Techniques: LLVM's legacy pass manager (declared AnalysisUsage, a static schedule); LLVM's new pass manager (lazy analysis caching, PreservedAnalyses, invalidation with dependencies, proxies and adaptors for module ↔ CGSCC ↔ function ↔ loop, instrumentation callbacks, optional and required passes); GCC's pass manager (passes.def, IR properties, TODO flags); MLIR's nested, operation-anchored pass manager (multithreading, dynamic pipelines) · Pebble implements: the analysis pebble-stats and its printer (E1), which the new pass manager caches and invalidates · Drill: pm-invalidation · Prerequisites: Ch 9 (LLVM IR), Ch 10 (the C++ API) · Time: 5–7 hours

A compiler optimizer is a sequence of passes, each a function from programs to programs, plus analyses that passes consult: dominator trees, loop nests, alias information. A pass manager decides when each analysis is computed, how long its result may be reused, in what order passes visit functions and loops, and how a user observes all this. The answer changes compile time by integer factors and, when it is wrong, silently miscompiles programs: a stale dominator tree used after a pass changed the CFG is a wrong-code bug that no test of the pass alone catches. This lesson compares four designs that production compilers use today and proves the property they all rely on: a cached result is only reused while it is still equal to what recomputing it would give.

1. Problem and motivation

The problem. Given a pipeline \(p_1, \dots, p_k\) of passes and a set of analyses, run every pass on the IR units it is written for (modules, functions, loops, strongly connected components of the call graph) so that each pass sees the analysis results it asks for, those results are coherent with the current IR, and no analysis is computed more often than necessary.

LLVM legacy pass manager

LLVM's original pass manager, documented in "Writing an LLVM Pass" [LLVM-WLP], asks every pass to declare up front, in getAnalysisUsage, which analyses it requires and which it preserves. A scheduler inserts the required analyses before each pass, frees the ones a pass does not preserve, and pipelines function passes so that all of them run on one function before the next function is touched. The declaration is static: a pass must say whether it preserves the CFG before it knows whether it will change anything. It survives in LLVM 23 only in the code generator (llc), which is being ported ([LLVM-NPM]).

LLVM new pass manager

Chandler Carruth's redesign (developed in tree from 2014 on, the default for the optimization pipeline since LLVM 13, and the only optimizer pipeline in LLVM 23) inverts the protocol: analyses are computed lazily when a pass calls getResult, results are cached per IR unit, and after running, a pass returns a PreservedAnalyses value saying what it actually preserved on this run [LLVM-NPM, LLVM-WNPM]. Analyses may depend on other analyses and decide their own invalidation. IR units nest (module ⊃ CGSCC ⊃ function ⊃ loop) through adaptors and proxies. Every pass execution goes through instrumentation callbacks, which is how -print-after, -print-changed, -time-passes, -opt-bisect-limit and optnone are implemented. This is the pass manager the course's plugin PebblePasses uses.

GCC pass manager

GCC organizes its middle end as one static tree of passes written down in gcc/passes.def [GCC-PassesDef]. Instead of analyses with dependencies, GCC tracks IR properties ("the function is in SSA form", "there is a CFG", "loops are up to date") that each pass requires, provides and destroys, and TODO flags that ask the manager to clean up after a pass (update SSA, clean up the CFG, verify) ("Pass manager" in [GCC-Int]). Gates decide per function whether a pass runs.

MLIR pass manager

MLIR's IR is a nest of operations with regions, not a fixed module/function/loop hierarchy, so its pass manager anchors each pipeline on an operation type and nests pipelines along the IR structure [MLIR-PM]. Because operations marked IsolatedFromAbove cannot see values defined outside them, passes on sibling isolated operations can run on different threads; passes may also build and run pipelines dynamically.

2. Definitions and algorithms

Throughout the lesson, let \(\mathcal{P}\) be the set of programs (LLVM modules, in this chapter), let \(\mathrm{Analyses}\) be the finite set of analyses a compiler registers, and let \(\mathrm{Sets}\) be the finite set of names of analysis sets (in LLVM 23: CFGAnalyses, the analyses that depend only on the CFG, and AllAnalysesOn<Function>, every function analysis), each name \(s \in \mathrm{Sets}\) standing for a subset \(\mathrm{members}(s) \subseteq \mathrm{Analyses}\). Every numbered box restates the objects it uses.

Definition 12.1.1 (IR units, passes)

Let \(\mathcal{P}\) be the set of programs. An IR unit is a module, a call-graph SCC, a function or a loop; units nest: a module contains SCCs and functions, an SCC contains functions, a function contains loops. For one of these four kinds, let \(U\) be the set of units of that kind. A pass on units of kind \(U\) is a function \(p : \mathcal{P} \times U \to \mathcal{P}\) such that \(p(P, u)\) differs from \(P \in \mathcal{P}\) only inside the unit \(u \in U\) (for a module pass, \(u\) is the whole module). A pipeline on \(U\) is a finite sequence of passes \(\pi = p_1 \cdots p_k\) with \(k \ge 0\). Running \(\pi\) on a unit \(u \in U\) of a program \(P\) produces \(\pi(P, u) \triangleq p_k(\dots p_2(p_1(P, u), u) \dots, u)\); running \(\pi\) on a program runs it on every unit of kind \(U\) of that program, in an order the manager chooses.

Definition 12.1.2 (Analysis, result, cache)

Let \(\mathcal{P}\) be the set of programs and \(U\) the set of units of one kind (Definition 12.1.1). An analysis \(A\) on \(U\) is a function \(A : \mathcal{P} \times U \to R_A\) into a set \(R_A\) of results; let \(\mathrm{Analyses}\) be the finite set of analyses. An analysis manager holds a partial map, the cache, \(\mathrm{cache} : \mathrm{Analyses} \times U \rightharpoonup \bigcup_{A \in \mathrm{Analyses}} R_A\) with \(\mathrm{cache}[A, u] \in R_A\) for every \((A, u) \in \mathrm{dom}(\mathrm{cache})\). For analyses \(A, B \in \mathrm{Analyses}\), a program \(P \in \mathcal{P}\) and a unit \(u \in U\): \(A\) requests \(B\) if computing \(A(P, u)\) asks the manager for \(B(P, u)\), or for \(B\) on a unit enclosing \(u\). \(A\) depends on \(B\), written \(A \to B\), if \(A\) requests \(B\) and, for every program \(P' \in \mathcal{P}\), \(A(P', u) = A(P, u)\) holds only when \(B(P', u) = B(P, u)\) (in an implementation: the result of \(A\) keeps a reference to the result of \(B\)). Both relations are required to be acyclic; \(\to^{+}\) is the transitive closure of \(\to\).

An analysis may request another only to build its result and not depend on it afterwards: in LLVM 23, LoopInfo requests the dominator tree but, once built, is correct as long as the CFG is unchanged, so it does not depend on it in the sense of Definition 12.1.2.

Definition 12.1.3 (PreservedAnalyses)

Let \(\mathrm{Analyses}\) be the set of analyses and \(\mathrm{Sets}\) the set of analysis-set names, each \(s \in \mathrm{Sets}\) standing for \(\mathrm{members}(s) \subseteq \mathrm{Analyses}\); let \(\ast \notin \mathrm{Analyses}\) be a distinguished symbol. A preservation report is a triple \(\mathrm{PA} = (K, S, X)\) with \(K \subseteq \mathrm{Analyses} \cup \{\ast\}\) the analyses reported preserved, \(S \subseteq \mathrm{Sets}\) the analysis sets reported preserved, and \(X \subseteq \mathrm{Analyses}\) the abandoned analyses. The special reports are \(\mathrm{all} \triangleq (\{\ast\}, \emptyset, \emptyset)\) and \(\mathrm{none} \triangleq (\emptyset, \emptyset, \emptyset)\). For an analysis \(A \in \mathrm{Analyses}\) and a set name \(s \in \mathrm{Sets}\), the checker of \(\mathrm{PA}\) answers

\[ \begin{aligned} \mathrm{preserved}_{\mathrm{PA}}(A) &\iff A \notin X \land (\ast \in K \lor A \in K), \\ \mathrm{preservedSet}_{\mathrm{PA}}(A, s) &\iff A \notin X \land (\ast \in K \lor s \in S). \end{aligned} \]

\(A\) is covered by \(\mathrm{PA}\) if \(\mathrm{preserved}_{\mathrm{PA}}(A)\) or \(\mathrm{preservedSet}_{\mathrm{PA}}(A, s)\) for some \(s \in \mathrm{Sets}\) with \(A \in \mathrm{members}(s)\). A run of a pass on a unit \(u\) that turns a program \(P\) into \(P'\) and returns the report \(\mathrm{PA}\) is truthful if \(A(P', u) = A(P, u)\) for every analysis \(A\) covered by \(\mathrm{PA}\).

Definition 12.1.4 (Invalidation predicate)

Let \(\mathrm{Analyses}\) be the set of analyses with the dependency relation \(\to\) (Definition 12.1.2) and let \(\mathrm{PA}\) be a preservation report (Definition 12.1.3). An invalidator is a function \(\mathrm{Inv} : \mathrm{Analyses} \to \{\mathsf{true}, \mathsf{false}\}\), read "\(\mathrm{Inv}(B)\) holds iff the cached result of \(B\) on the current unit is invalidated". Every analysis \(A \in \mathrm{Analyses}\) supplies an invalidation predicate \(\mathrm{inv}_A\), which maps a report \(\mathrm{PA}\) and an invalidator \(\mathrm{Inv}\) to a value \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) \in \{\mathsf{true}, \mathsf{false}\}\). \(A\) is stateless if \(A(P, u)\) is determined by the results \(B(P, u)\) of the analyses \(B\) with \(A \to B\), for every program \(P\) and every unit \(u\). The predicate \(\mathrm{inv}_A\) is sound if, whenever \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) = \mathsf{false}\), (i) \(A\) is covered by \(\mathrm{PA}\) or \(A\) is stateless, and (ii) \(\mathrm{Inv}(B) = \mathsf{false}\) for every \(B\) with \(A \to B\). The default predicate on units of kind \(U\) is \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) \triangleq \neg(\mathrm{preserved}_{\mathrm{PA}}(A) \lor \mathrm{preservedSet}_{\mathrm{PA}}(A, \mathrm{all}_U))\), where \(\mathrm{all}_U \in \mathrm{Sets}\) names the set of all analyses on \(U\); it is sound for an analysis without dependencies, and an analysis with dependencies must override it.

The default predicate is AnalysisResultModel::invalidate in llvm/IR/PassManagerInternal.h (LLVM 23.1.2): !PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<IRUnitT>>(). In the example below, write \(\mathrm{DT}\), \(\mathrm{PDT}\), \(\mathrm{LI}\), \(\mathrm{SE}\), \(\mathrm{AC}\) and \(\mathrm{TLI}\) for the analyses DominatorTreeAnalysis, PostDominatorTreeAnalysis, LoopAnalysis, ScalarEvolutionAnalysis, AssumptionAnalysis and TargetLibraryAnalysis, and \(\mathrm{CFG}\) and \(\mathrm{AllF}\) for the set names CFGAnalyses and AllAnalysesOn<Function>; \(\mathrm{preserved}\) and \(\mathrm{preservedSet}\) are the checker of the report the pass just returned.

The invalidation predicates of LLVM 23

Reading the invalidate methods of LLVM 23.1.2 [LLVM-Dominators, LLVM-SCEV, LLVM-BasicAA, LLVM-MSSA], for each analysis \(A\) among DominatorTree, PostDominatorTree and LoopInfo the method returns \(\neg(\mathrm{preserved}(A) \lor \mathrm{preservedSet}(A, \mathrm{AllF}) \lor \mathrm{preservedSet}(A, \mathrm{CFG}))\), so a pass that keeps the CFG keeps them without naming them. ScalarEvolution returns \(\neg \mathrm{preserved}(\mathrm{SE}) \lor \mathrm{Inv}(\mathrm{AC}) \lor \mathrm{Inv}(\mathrm{DT}) \lor \mathrm{Inv}(\mathrm{LI})\). BasicAA is stateless: it returns \(\mathrm{Inv}(\mathrm{AC}) \lor \mathrm{Inv}(\mathrm{DT}) \lor \mathrm{Inv}(\mathrm{TLI})\) and ignores its own preservation. AssumptionCache and TargetLibraryInfo return \(\mathsf{false}\) always. LoopInfo does not consult the dominator tree, although computing it requests one: it requests \(\mathrm{DT}\) but does not depend on it (Definition 12.1.2), so its predicate is sound without a dependency check.

LLVM legacy pass manager

Definition 12.1.5 (AnalysisUsage)

Let \(\mathrm{Analyses}\) be the set of analyses and \(\mathrm{CFGonly} \subseteq \mathrm{Analyses}\) the analyses whose result depends only on the control-flow graph of a unit. In the legacy manager each pass \(p\) declares, before it ever runs, its analysis usage: a set \(\mathrm{Req}(p) \subseteq \mathrm{Analyses}\) of analyses that must be available when \(p\) runs, and a set \(\mathrm{Pres}(p) \subseteq \mathrm{Analyses}\) of analyses whose cached results stay valid after every run of \(p\). Two shorthands enlarge \(\mathrm{Pres}(p)\): preserves CFG adds \(\mathrm{CFGonly}\), and preserves all adds \(\mathrm{Analyses}\). An analysis is itself a pass, with \(\mathrm{Pres}(A) = \mathrm{Analyses}\), whose result stays in the pass object.

In LLVM 23.1.2 the declaration is the method getAnalysisUsage with addRequired, addPreserved, setPreservesCFG() and setPreservesAll() (llvm/include/llvm/PassAnalysisSupport.h).

Algorithm 12.1.6 (Legacy scheduling, PMTopLevelManager::schedulePass)

  • Input: a pipeline \(\pi = p_1 \cdots p_k\) of passes, each with its analysis usage \(\mathrm{Req}(p_i)\) and \(\mathrm{Pres}(p_i)\) (Definition 12.1.5), over a set \(\mathrm{Analyses}\) of analyses.
  • Output: a schedule \(s\): a finite sequence over \(\mathrm{Analyses} \cup \{p_1, \dots, p_k\}\) in which every \(p_i\) occurs once, in order, and analyses occur where they are to be computed.
  • State: the schedule built so far, \(s\); the set \(\mathrm{avail} \subseteq \mathrm{Analyses}\) of analyses whose most recent occurrence in \(s\) is not followed in \(s\) by a pass that does not preserve them. Appending \(x\) to \(s\) sets \(s \triangleq s \cdot \langle x \rangle\).
  • Precondition: the relation "\(A \in \mathrm{Req}(B)\)" on \(\mathrm{Analyses}\) is acyclic; every required analysis is registered.
  • Postcondition: for every \(i \in \{1, \dots, k\}\) and every \(A \in \mathrm{Req}(p_i)\), \(A\) occurs in \(s\) before \(p_i\), with no element \(q\) between that occurrence and \(p_i\) such that \(A \notin \mathrm{Pres}(q)\).
  • Invariant: after every call of Add, \(\mathrm{avail}\) is exactly the set of analyses whose most recent occurrence in \(s\) is not followed by a non-preserving pass.
function Schedule(p_1 .. p_k):
    s ← ⟨⟩; avail ← ∅
    for i ← 1 to k:
        Add(p_i)
    return s

function Add(p):                           # p: a pass or an analysis
    for A in Req(p):                      # in declaration order
        if A ∉ avail:
            Add(A)                        # analyses are passes too; recursion is finite (acyclic)
    s ← s · ⟨p⟩                           # append p
    if p is an analysis:
        avail ← avail ∪ {p}
    else:
        avail ← { A ∈ avail | A ∈ Pres(p) }   # Pres(p) includes CFGonly / Analyses for the shorthands

At run time, FPPassManager::runOnFunction runs the whole function-level part of \(s\) on one function before the next, and PMDataManager::removeNotPreservedAnalysis implements the last line.

LLVM new pass manager

Algorithm 12.1.7 (Lazy analysis cache, AnalysisManager::getResult and invalidate)

  • Input: a set \(\mathrm{Analyses}\) of analyses on units of kind \(U\), each \(A \in \mathrm{Analyses}\) with its invalidation predicate \(\mathrm{inv}_A\) (Definition 12.1.4); the current program \(P \in \mathcal{P}\); a stream of requests \((A, u)\) with \(A \in \mathrm{Analyses}\), \(u \in U\), issued by passes, and, after each pass run on a unit \(u\), that run's report \(\mathrm{PA}\) (Definition 12.1.3).
  • Output: for each request \((A, u)\), the result \(A(P, u)\) for the program \(P\) current at the time of the request.
  • State: the cache \(\mathrm{cache} : \mathrm{Analyses} \times U \rightharpoonup \bigcup_{A \in \mathrm{Analyses}} R_A\) (Definition 12.1.2), where \(R_A\) is the result set of \(A\), initially empty; during one call of Invalidate, a partial map \(\mathrm{memo} : \mathrm{Analyses} \rightharpoonup \{\mathsf{true}, \mathsf{false}\}\), initially empty. Caching a result \(r \in R_A\) for \((A, u)\) sets \(\mathrm{cache}[A, u] \triangleq r\); deleting \((A, u)\) removes it from \(\mathrm{dom}(\mathrm{cache})\).
  • Precondition: every \(\mathrm{inv}_A\) is sound (Definition 12.1.4); every pass run is truthful (Definition 12.1.3).
  • Postcondition: every returned result equals \(A(P, u)\) for the current program \(P\) (Theorem 12.1.17).
  • Invariant: cache coherence (Definition 12.1.16): \(\mathrm{cache}[A, u] = A(P, u)\) for every \((A, u) \in \mathrm{dom}(\mathrm{cache})\).
function GetResult(A, u):                  # A ∈ Analyses, u ∈ U
    if (A, u) ∈ dom(cache): return cache[A, u]
    r ← A(P, u)                            # run the analysis; may call GetResult(B, u) for B requested by A
    cache[A, u] ← r                        # cache r for (A, u)
    return r

function Invalidate(u, PA):                # called by the pass manager after each pass on u
    memo ← ∅
    for (A, u) ∈ dom(cache), in any order:
        if Inv(A):
            delete cache[A, u]

function Inv(A):                           # the invalidator handed to inv_A (Definition 12.1.4)
    if A ∈ dom(memo): return memo[A]
    memo[A] ← inv_A(PA, Inv)               # may call Inv(B) for cached B with A → B
    return memo[A]

Algorithm 12.1.8 (Pass-manager run with instrumentation)

  • Input: a pipeline \(\pi = p_1 \cdots p_k\) on units of kind \(U\), with \(k \ge 0\) passes (Definition 12.1.1); a unit \(u \in U\) of the current program \(P\); an analysis manager \(\mathrm{AM}\) running Algorithm 12.1.7; a finite set \(\mathcal{C}\) of instrumentation callbacks, each a quadruple \(c = (\mathrm{shouldRun}, \mathrm{beforeSkipped}, \mathrm{before}, \mathrm{after})\) of a predicate \(\mathrm{shouldRun}(p, u) \in \{\mathsf{true}, \mathsf{false}\}\) on a pass \(p\) and a unit \(u\) and three procedures that observe a run and change nothing; we write \(c.\mathrm{shouldRun}\) for the first component of \(c\), and so on; a partition of \(\{p_1, \dots, p_k\}\) into required and optional passes.
  • Output: the transformed program \(\pi'(P, u)\), where \(\pi'\) is the subsequence of \(\pi\) that ran, and the combined report \(\mathrm{PA}_\pi\) (Definition 12.1.3).
  • State: the combined report \(\mathrm{PA}_\pi\), initially \(\mathrm{all}\). For reports \(\mathrm{PA}_1 = (K_1, S_1, X_1)\) and \(\mathrm{PA}_2 = (K_2, S_2, X_2)\), their intersection is \(\mathrm{PA}_1 \sqcap \mathrm{PA}_2 \triangleq (K_1 \cap K_2,\ S_1 \cap S_2,\ X_1 \cup X_2)\), where \(\ast \in K_1\) makes \(K_1 \cap K_2 \triangleq K_2\) and \(S_1 \cap S_2 \triangleq S_2\) (and symmetrically): an analysis is reported preserved by \(\mathrm{PA}_1 \sqcap \mathrm{PA}_2\) iff both reports preserve it.
  • Precondition: as Algorithm 12.1.7.
  • Postcondition: each required pass ran; each optional pass \(p_i\) ran iff \(c.\mathrm{shouldRun}(p_i, u)\) for every \(c \in \mathcal{C}\); the cache of \(\mathrm{AM}\) is coherent (Definition 12.1.16).
  • Invariant: after iteration \(i \in \{1, \dots, k\}\), \(\mathrm{PA}_\pi\) is the intersection of the reports returned by the passes among \(p_1, \dots, p_i\) that ran.
function Run(p_1 .. p_k, u):
    PA_π ← all
    for i ← 1 to k:
        if p_i is optional and not every c ∈ 𝒞 has c.shouldRun(p_i, u):
            for c in 𝒞: c.beforeSkipped(p_i, u)
            continue
        for c in 𝒞: c.before(p_i, u)
        PA ← p_i.run(u, AM)                # the pass transforms u and returns its report
        for c in 𝒞: c.after(p_i, u, PA)
        AM.Invalidate(u, PA)               # Algorithm 12.1.7
        PA_π ← PA_π ⊓ PA                   # keep only what every pass preserved
    return PA_π

In LLVM 23.1.2 the callbacks are shouldRunOptionalPass, beforeSkippedPass, beforeNonSkippedPass and afterPass of PassInstrumentation; optnone and -opt-bisect-limit are two such callbacks (OptNoneInstrumentation::shouldRun, OptPassGateInstrumentation::shouldRun in StandardInstrumentations.cpp [LLVM-SI]); a pass derived from RequiredPassInfoMixin is required, one derived from OptionalPassInfoMixin is optional. PreservedAnalyses::intersect is \(\sqcap\).

Definition 12.1.9 (Adaptors and proxies)

Let \(U_{\mathrm{out}}\) and \(U_{\mathrm{in}}\) be the sets of units of two kinds such that every unit of kind \(U_{\mathrm{in}}\) is contained in a unit of kind \(U_{\mathrm{out}}\) (Definition 12.1.1), and for \(u \in U_{\mathrm{out}}\) let \(\mathrm{children}(u) \subseteq U_{\mathrm{in}}\) be the inner units it contains. An adaptor turns a pipeline \(\pi\) on \(U_{\mathrm{in}}\) into a pass \(\mathrm{adapt}(\pi)\) on \(U_{\mathrm{out}}\) that runs \(\pi\) on every \(v \in \mathrm{children}(u)\) in a fixed order. A proxy is an analysis on one kind of unit whose result is the analysis manager of the other kind: an inner proxy is an analysis on \(U_{\mathrm{out}}\) whose result on \(u\) is the manager for the units in \(\mathrm{children}(u)\); an outer proxy is an analysis on \(U_{\mathrm{in}}\) whose result on \(v\) gives read-only access to the cached results on the unit of kind \(U_{\mathrm{out}}\) containing \(v\).

In LLVM 23.1.2 the adaptors are ModuleToFunctionPassAdaptor (every function definition, in module order), ModuleToPostOrderCGSCCPassAdaptor (every SCC of the call graph in post-order, callees first), CGSCCToFunctionPassAdaptor (each function of an SCC) and FunctionToLoopPassAdaptor (every loop, innermost first); the proxies are InnerAnalysisManagerProxy<FAM, Module>, a module analysis whose result is the function analysis manager (its invalidation walks the inner caches), and OuterAnalysisManagerProxy<MAM, Function>, which gives a function pass read-only access to cached module analyses.

Algorithm 12.1.10 (Module-to-function adaptor)

  • Input: a module \(M\), a function pipeline \(\pi\) (Definition 12.1.1), the module analysis manager \(\mathrm{MAM}\) and, through the inner proxy \(\mathrm{InnerProxy}\) (Definition 12.1.9), the function analysis manager \(\mathrm{FAM}\); write \(\mathrm{functions}(M)\) for the sequence of functions of \(M\) in module order, and let \(\mathrm{AllF} \in \mathrm{Sets}\) name the set of all function analyses.
  • Output: the transformed module and its report \(\mathrm{PA}_M\) (Definition 12.1.3).
  • State: the report \(\mathrm{PA}_M\), initially \(\mathrm{all}\), combined with \(\sqcap\) (Algorithm 12.1.8). Adding an analysis \(A\) (a set name \(s\)) to a report \(\mathrm{PA} = (K, S, X)\) yields \((K \cup \{A\}, S, X \setminus \{A\})\) (resp. \((K, S \cup \{s\}, X)\)).
  • Precondition: \(\pi\) changes only the function it runs on.
  • Postcondition: \(\pi\) ran on every function definition of \(M\), in module order; the cache of \(\mathrm{FAM}\) is coherent; \(\mathrm{PA}_M\) reports \(\mathrm{InnerProxy}\) and \(\mathrm{AllF}\) preserved, and a module analysis preserved only if every run of \(\pi\) reported it preserved.
  • Invariant: before processing a function \(f\), every function before \(f\) in \(\mathrm{functions}(M)\) has been processed and the cache of \(\mathrm{FAM}\) is coherent.
function ModuleToFunction(M, π):
    FAM ← MAM.GetResult(InnerProxy, M)
    PA_M ← all
    for f in functions(M), in order:
        if f is a declaration: continue
        PA_f ← Run(π, f)                   # Algorithm 12.1.8 on FAM
        PA_M ← PA_M ⊓ PA_f
    add AllF to PA_M                       # FAM was kept up to date function by function
    add InnerProxy to PA_M
    return PA_M

Definition 12.1.11 (CGSCC walk)

Let \(\mathrm{CG} = (F, C)\) be the call graph of a module: \(F\) its set of functions and \(C \subseteq F \times F\) its edges, with \((f, g) \in C\) iff \(f\) contains a call to \(g\). Its SCCs are the strongly connected components of \(\mathrm{CG}\); the SCC post-order is any linear order of the SCCs in which every SCC comes after every SCC it has an edge into. The CGSCC adaptor visits the SCCs in SCC post-order, so that a function is simplified before it is inlined into its callers. A CGSCC pass may mutate \(\mathrm{CG}\) (inlining adds and removes edges, deleting a function removes a node); it records the changes in an update record, and the adaptor re-runs the pipeline on SCCs that the changes split or merged. For an integer \(n \ge 1\), the devirtualization wrapper \(\mathrm{devirt}_n\) repeats the pipeline on an SCC up to \(n\) times while indirect calls become direct.

In LLVM 23.1.2 the call graph is LazyCallGraph, the update record is CGSCCUpdateResult, and \(\mathrm{devirt}_n\) is written devirt<n> in pipeline text.

GCC pass manager

Definition 12.1.12 (GCC pass data)

Let \(\mathrm{Prop}\) be a finite set of IR properties and \(\mathrm{Todo}\) a finite set of cleanup actions. A GCC pass \(p\) consists of a kind (GIMPLE, RTL, simple IPA or IPA), a name, three property sets \(\mathrm{required}(p), \mathrm{provided}(p), \mathrm{destroyed}(p) \subseteq \mathrm{Prop}\), two action sets \(\mathrm{todoStart}(p), \mathrm{todoFinish}(p) \subseteq \mathrm{Todo}\), a gate \(\mathrm{gate}_p(f) \in \{\mathsf{true}, \mathsf{false}\}\) on a function \(f\), and an execution \(\mathrm{execute}_p\) that transforms \(f\) and returns a further action set \(\subseteq \mathrm{Todo}\). A property set \(\Phi \subseteq \mathrm{Prop}\) describes a function if every property in \(\Phi\) holds of its IR. Running an action set \(T \subseteq \mathrm{Todo}\) performs each action in \(T\) (each is a transformation of the IR).

In GCC 15 (gcc/tree-pass.h [GCC-TreePass]) a pass is an opt_pass whose pass_data gives the type (GIMPLE_PASS, RTL_PASS, SIMPLE_IPA_PASS, IPA_PASS), properties_required, properties_provided and properties_destroyed over bits such as PROP_cfg, PROP_ssa, PROP_loops, and todo_flags_start, todo_flags_finish over bits such as TODO_update_ssa, TODO_cleanup_cfg, TODO_verify_il; gate(fun) decides whether the pass and its sub-passes run on fun, and execute(fun) returns further TODO flags.

Algorithm 12.1.13 (GCC execute_one_pass, simplified from gcc/passes.cc)

  • Input: a pass \(p\) (Definition 12.1.12) and the current function \(f\) with its property set \(\Phi \subseteq \mathrm{Prop}\); a distinguished action \(\mathrm{verify} \in \mathrm{Todo}\) that checks the IR.
  • Output: the updated function and property set \(\Phi'\); \(\mathsf{true}\) iff the pass ran.
  • State: the property set \(\Phi\) of the current function. Updating \(\Phi\) by \(p\) sets \(\Phi \triangleq (\Phi \setminus \mathrm{destroyed}(p)) \cup \mathrm{provided}(p)\).
  • Precondition: \(\mathrm{required}(p) \subseteq \Phi\) (checked when flag_checking).
  • Postcondition: if the pass ran, \(\Phi' = (\Phi \setminus \mathrm{destroyed}(p)) \cup \mathrm{provided}(p)\) and the finishing actions ran; otherwise \(\Phi' = \Phi\) and \(f\) is unchanged.
  • Invariant: \(\Phi\) describes \(f\).
function ExecuteOnePass(p, f):
    if not gate_p(f): return false
    run todoStart(p)
    assert required(p) ⊆ Φ                 # verify_curr_properties
    todo ← execute_p(f)
    Φ ← (Φ \ destroyed(p)) ∪ provided(p)   # update Φ by p
    run todo ∪ todoFinish(p) ∪ {verify}
    return true

function ExecutePassList(p, f):            # the passes.def tree: p.sub is the first child, p.next the sibling
    while p ≠ null:
        if ExecuteOnePass(p, f) and p.sub ≠ null:
            ExecutePassList(p.sub, f)
        p ← p.next

MLIR pass manager

Definition 12.1.14 (Operation-anchored pass managers)

Let \(\mathrm{Ops}\) be the set of operations of an MLIR program; each operation \(o \in \mathrm{Ops}\) has a type \(\mathrm{type}(o)\) (its operation name) and a finite sequence of regions, each a sequence of blocks of operations, so that \(\mathrm{Ops}\) is a forest with \(\mathrm{children}(o)\) the operations directly inside the regions of \(o\). An operation \(o\) is isolated from above if no operation inside its regions uses a value defined outside \(o\). An operation-anchored pass manager is a pipeline \(\pi_T\) anchored on an operation type \(T\): every pass of \(\pi_T\) runs on operations \(o\) with \(\mathrm{type}(o) = T\) and may modify only \(o\) and the operations inside its regions. A pass manager is op-agnostic if it is anchored on every type at once. Pass managers nest: a pipeline anchored on \(T\) may contain a pass manager anchored on \(T'\), which runs on the children of type \(T'\) of each operation of type \(T\). Every anchor type must be isolated from above.

In MLIR 23.1.2 the anchored manager is OpPassManager, anchor types are names such as func.func and builtin.module, isolation is the trait IsolatedFromAbove, and the textual pipeline builtin.module(func.func(cse,canonicalize)) runs cse then canonicalize on each function in the module.

Algorithm 12.1.15 (Nested adaptor, OpToOpPassAdaptor)

  • Input: an operation \(o \in \mathrm{Ops}\) and a family of nested pipelines \(\pi_T\) indexed by anchor types \(T\) (Definition 12.1.14).
  • Output: success, or failure if some pass signalled failure.
  • State: per child \(c \in \mathrm{children}(o)\), its own analysis manager (Algorithm 12.1.7 on the unit \(c\)).
  • Precondition: every anchor type \(T\) with a pipeline \(\pi_T\) is isolated from above.
  • Postcondition: for every child \(c \in \mathrm{children}(o)\) with \(\mathrm{type}(c) = T\) for some anchor type \(T\), \(\pi_T\) ran to completion on \(c\).
  • Invariant: children processed concurrently are disjoint subtrees of \(\mathrm{Ops}\).
function RunNested(o, pipelines):
    jobs ← [ (c, π_T) | c ∈ children(o), π_T matches type(c) ]
    if multithreading enabled:
        parallelForEach(jobs, (c, π) ↦ RunPipeline(π, c))   # one analysis manager per child
    else:
        for (c, π) in jobs: RunPipeline(π, c)
    return all succeeded

function RunPipeline(π, c):
    for p in π:
        if p.runOnOperation(c) signalled failure: return failure
        invalidate the cached analyses of c not reported preserved by p   # Algorithm 12.1.7, Invalidate
    return success

A pass may also call runPipeline(dynamicPM, op) on an operation it owns: a dynamic pipeline, scheduled at run time, instrumented and analysis-managed like a static one.

3. Worked example

The running example of this chapter is a function with a loop, @count, and five passes P1–P5 that request analyses and report preservation as a drill instance would state them. The new pass manager starts with an empty cache.

step pass requests returns computed (Alg. 12.1.7) invalidated cache after
1 P1 {LI} all DT, LI (LI requests DT) {} {DT, LI}
2 P2 {PDT, SE} all PDT, TLI, AC, SE (SE requests TLI, AC, DT, LI; DT, LI cached) {} {AC, DT, LI, PDT, SE, TLI}
3 P3 {SE} {CFG, AA} {} (SE cached) SE (not preserved by name; CFG does not cover it) {AC, DT, LI, PDT, TLI}
4 P4 {LI, PDT} {CFG, AA} {} {} (DT, PDT, LI kept by the CFG set) {AC, DT, LI, PDT, TLI}
5 P5 {LI, PDT} all {} {} {AC, DT, LI, PDT, TLI}
  • Step 2: the dependencies are computed by the request, not the pass; DT and LI are reused.
  • Step 3: preserving AA preserves nothing here (it is not cached); SE is dropped because it is not named, although its dependencies survive.
  • Step 4: the CFG set is enough for DT, PDT and LI (Definition 12.1.4, the example).

The legacy schedule for the same pipeline, if every pass declared its most common behavior (P1, P2, P5 setPreservesAll; P3, P4 setPreservesCFG), is DT LI P1 PDT TLI AC SE P2 P3 P4 P5 with SE freed after P3 — the same work, but only because the declarations happened to match what the passes did. A pass that sometimes changes the CFG must declare that it never preserves it, and then every CFG analysis is recomputed after it on every function, even the functions it left untouched.

Caching and invalidation in LLVM's new pass manager

Reproduce (opt 23.1.2):

cat > inv.ll <<'EOF'
define i32 @f(i32 %x, i1 %c) {
entry:
  %m = mul i32 %x, 8
  br i1 %c, label %a, label %b
a:
  br label %b
b:
  %p = phi i32 [ %m, %entry ], [ 0, %a ]
  ret i32 %p
}
EOF
opt -passes='function(require<domtree>,instcombine,require<domtree>,simplifycfg,require<domtree>)' \
    -debug-pass-manager -disable-output inv.ll

Output (complete):

Running analysis: InnerAnalysisManagerProxy<AnalysisManager<Function>, Module> on [module]
Running pass: RequireAnalysisPass<DominatorTreeAnalysis, Function> on f (5 instructions)
Running analysis: DominatorTreeAnalysis on f
Running pass: InstCombinePass on f (5 instructions)
Running analysis: LastRunTrackingAnalysis on f
Running analysis: AssumptionAnalysis on f
Running analysis: TargetIRAnalysis on f
Running analysis: TargetLibraryAnalysis on f
Running analysis: OptimizationRemarkEmitterAnalysis on f
Running analysis: AAManager on f
Running analysis: BasicAA on f
Running analysis: ScopedNoAliasAA on f
Running analysis: TypeBasedAA on f
Running analysis: OuterAnalysisManagerProxy<AnalysisManager<Module>, Function> on f
Running pass: RequireAnalysisPass<DominatorTreeAnalysis, Function> on f (5 instructions)
Running pass: SimplifyCFGPass on f (5 instructions)
Invalidating analysis: DominatorTreeAnalysis on f
Invalidating analysis: LastRunTrackingAnalysis on f
Invalidating analysis: BasicAA on f
Invalidating analysis: AAManager on f
Running pass: RequireAnalysisPass<DominatorTreeAnalysis, Function> on f (3 instructions)
Running analysis: DominatorTreeAnalysis on f
Running pass: VerifierPass on [module]
Running analysis: VerifierAnalysis on [module]

What to notice: InstCombine rewrote mul %x, 8 into shl %x, 3 but reported the CFG set preserved, so the second require<domtree> reuses the cached tree (no "Running analysis" line). SimplifyCFG removed block a; the dominator tree is invalidated, and with it BasicAA (which depends on it) and AAManager (which depends on BasicAA) — the cascade of Definition 12.1.4 — while AssumptionAnalysis and TargetLibraryAnalysis are never invalidated. The dependencies were computed on demand by InstCombine's requests (Algorithm 12.1.7).

Try it

./course drill pm-invalidation --seed 4 --difficulty hard --solution reproduces the table above; other seeds give new pipelines.

4. Invariants and correctness

Definition 12.1.16 (Cache coherence)

Let \(\mathrm{Analyses}\) be the set of analyses on units of kind \(U\), \(\mathrm{cache}\) a cache (Definition 12.1.2) and \(P \in \mathcal{P}\) a program. For an analysis \(A\) with result set \(R_A\) and results \(r, r' \in R_A\), write \(r \equiv_A r'\) for the analysis's own notion of equivalence of results: equality, or, for a stateless \(A\) (Definition 12.1.4), equality of the results of the analyses \(A\) depends on. The cache is coherent for \(P\) if \(\mathrm{cache}[A, u] \equiv_A A(P, u)\) for every \((A, u) \in \mathrm{dom}(\mathrm{cache})\).

Theorem 12.1.17 (Invalidation soundness)

Let \(\mathrm{Analyses}\) be the set of analyses on units of kind \(U\), with an acyclic dependency relation \(\to\) (Definition 12.1.2). Suppose that the invalidation predicate \(\mathrm{inv}_A\) of every \(A \in \mathrm{Analyses}\) is sound (Definition 12.1.4) and that every pass run is truthful (Definition 12.1.3). Then the cache of Algorithm 12.1.7 is coherent (Definition 12.1.16) after every step of Algorithm 12.1.8, and for every analysis \(A \in \mathrm{Analyses}\) and unit \(u \in U\), GetResult\((A, u)\) returns a result \(\equiv_A A(P, u)\) for the program \(P\) current at the call.

Proof

By induction on the number of GetResult calls and pass runs performed so far, with the statement "the cache is coherent for the current program" as the induction hypothesis. Base: the cache is empty, hence coherent. A GetResult\((A, u)\) call: on a hit, the induction hypothesis gives \(\mathrm{cache}[A, u] \equiv_A A(P, u)\); on a miss the result is computed by running \(A\) on the current \(P\), reading only results that GetResult returned (coherent by the induction hypothesis), so the cached value is \(A(P, u)\) and coherence is kept. A pass run on a unit \(u\) changes \(P\) into \(P'\) and reports \(\mathrm{PA}\); Invalidate then deletes every cached \((A, u)\) with \(\mathrm{Inv}(A) = \mathsf{true}\), and by the memo \(\mathrm{Inv}(A) = \mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv})\). Let \((A, u)\) survive, so \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) = \mathsf{false}\). By soundness (Definition 12.1.4), (i) \(A\) is covered by \(\mathrm{PA}\) or stateless, and (ii) \(\mathrm{Inv}(B) = \mathsf{false}\), so \((B, u)\) survives, for every \(B\) with \(A \to B\). We show \(\mathrm{cache}[A, u] \equiv_A A(P', u)\) by an inner induction along \(\to\), which is acyclic on a finite set and therefore well-founded. If \(A\) is covered, truthfulness (Definition 12.1.3) gives \(A(P', u) = A(P, u) \equiv_A \mathrm{cache}[A, u]\). If \(A\) is stateless, \(A(P', u)\) is determined by the results \(B(P', u)\) of its dependencies; each \((B, u)\) survives by (ii) and, by the inner induction hypothesis, \(\mathrm{cache}[B, u] \equiv_B B(P', u)\); so \(\mathrm{cache}[A, u] \equiv_A A(P', u)\) by the definition of \(\equiv_A\) for stateless analyses (Definition 12.1.16). Hence the cache is coherent for \(P'\) on \(u\). Cached results on units \(u' \neq u\) are untouched and stay coherent, because the pass changes \(P\) only inside \(u\) (Definition 12.1.1). ∎

Lemma 12.1.18 (Invalidation is closed under dependencies)

Let \(\mathrm{Analyses}\) be a set of analyses with acyclic dependency relation \(\to\) (Definition 12.1.2) and sound invalidation predicates (Definition 12.1.4), and let \(A, B \in \mathrm{Analyses}\) be cached on the same unit when Invalidate (Algorithm 12.1.7) runs after a pass. If \(B\) is invalidated and \(A \to^{+} B\), then \(A\) is invalidated too.

Proof

By induction on the length \(\ell \ge 1\) of a dependency path \(A = A_0 \to A_1 \to \dots \to A_\ell = B\). For \(\ell = 1\), \(A \to B\) directly: soundness (Definition 12.1.4, clause (ii)) requires \(\mathrm{Inv}(B) = \mathsf{false}\) whenever \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) = \mathsf{false}\); contrapositively \(\mathrm{Inv}(B) = \mathsf{true}\) forces \(\mathrm{inv}_A(\mathrm{PA}, \mathrm{Inv}) = \mathsf{true}\), and Invalidate deletes \(A\). For \(\ell > 1\), \(A_1 \to^{+} B\) with a path of length \(\ell - 1\), so \(A_1\) is invalidated by the induction hypothesis, and the case \(\ell = 1\) applies to \(A \to A_1\). ∎

Theorem 12.1.19 (Outer analyses are read-only for inner passes)

Let \(M\) be a module analysis whose cached result on a module is read by a function pass \(p\) through the outer proxy (Definition 12.1.9) while the module-to-function adaptor (Algorithm 12.1.10) runs a pipeline \(\pi\) containing \(p\). Suppose a run of \(p\) on a function \(f\) changes \(f\) so that \(M\)'s result on the module changes. Then no function-level Invalidate (Algorithm 12.1.7 on the function analysis manager) deletes the cached result of \(M\); it is deleted by the module-level Invalidate after the adaptor returns \(\mathrm{PA}_M\) iff \(\mathrm{inv}_M(\mathrm{PA}_M, \mathrm{Inv}) = \mathsf{true}\), which holds when some run of a pass of \(\pi\) did not report \(M\) preserved and \(\mathrm{inv}_M\) is sound; otherwise it is deleted only if \(M\) registered a module-level invalidation that function-level invalidation triggers.

Proof

Function-level Invalidate (Algorithm 12.1.7) iterates only over the domain of the function manager's cache, which contains pairs \((A, f)\) with \(A\) a function analysis, so the pair \((M, \text{module})\) is never inspected there. The only other invalidation of \(M\) happens at module level after the adaptor returns \(\mathrm{PA}_M\) (Algorithm 12.1.10): \(M\) is deleted iff \(\mathrm{inv}_M(\mathrm{PA}_M, \mathrm{Inv}) = \mathsf{true}\). By the postcondition of Algorithm 12.1.10, \(\mathrm{PA}_M\) reports \(M\) preserved only if every run of \(\pi\) reported it preserved; if some run did not, \(M\) is not covered by \(\mathrm{PA}_M\), and a sound \(\mathrm{inv}_M\) (Definition 12.1.4) must then return \(\mathsf{true}\) unless \(M\) is stateless. Between two inner passes, however, the cached \(M\) is stale; that is why the outer proxy returns only cached outer results (getCachedResult in LLVM 23.1.2), never computes them, and why LLVM requires outer analyses used by inner passes to be immutable in practice, or to register invalidation dependencies (registerOuterAnalysisInvalidation). ∎

Proposition 12.1.20 (GCC property invariant)

Let \(p\) be a GCC pass (Definition 12.1.12), \(f\) a function and \(\Phi \subseteq \mathrm{Prop}\) a property set that describes \(f\) before ExecuteOnePass\((p, f)\) (Algorithm 12.1.13). Suppose \(p\)'s declared property sets are correct: after \(\mathrm{execute}_p(f)\) and the finishing actions, every property in \(\mathrm{provided}(p)\) holds of \(f\), and every property that held before and is not in \(\mathrm{destroyed}(p)\) still holds. Then the property set \(\Phi'\) returned by ExecuteOnePass\((p, f)\) describes \(f\) after it.

Proof

If the gate rejects \(f\), ExecuteOnePass changes nothing and \(\Phi' = \Phi\) describes \(f\) by hypothesis. Otherwise let \(\phi \in \Phi' = (\Phi \setminus \mathrm{destroyed}(p)) \cup \mathrm{provided}(p)\). If \(\phi \in \mathrm{provided}(p)\), it holds by correctness of \(\mathrm{provided}(p)\). Otherwise \(\phi \in \Phi\) and \(\phi \notin \mathrm{destroyed}(p)\): it held before, because \(\Phi\) describes \(f\), and it is kept by correctness of \(\mathrm{destroyed}(p)\), possibly after a finishing action such as TODO_update_ssa repaired it — which is why the finishing actions run before the next pass. ∎

Proposition 12.1.21 (MLIR parallel execution is deterministic)

Let \(o \in \mathrm{Ops}\) be an operation and \(T\) an anchor type with pipeline \(\pi_T\) (Definition 12.1.14). Suppose every pass of \(\pi_T\) reads and writes only the operation it runs on and the operations inside its regions, and every operation of type \(T\) is isolated from above. Then running \(\pi_T\) on the children of \(o\) of type \(T\) in parallel (Algorithm 12.1.15) gives the same IR as running it on them sequentially, in any order.

Proof

Let \(c_1 \neq c_2\) be two children of \(o\) of type \(T\); they are disjoint subtrees of \(\mathrm{Ops}\) (Definition 12.1.14). By isolation, no operation inside \(c_1\) uses a value defined in \(c_2\) or outside \(c_1\), so no use-list is shared between \(c_1\) and \(c_2\) and no use-list of an operation outside \(c_1\) can be changed by a pass on \(c_1\); by the hypothesis on the passes, nothing outside \(c_1\) is written. Hence the write sets of the two jobs are disjoint and neither reads what the other writes: every interleaving of the two jobs is equivalent to a sequential order, and all sequential orders give the same result because the jobs commute. Shared uniqued state (types and attributes in the MLIRContext) is protected by locks and is insertion-only, so its contents do not affect results. ∎

A lying PreservedAnalyses is a miscompile waiting to happen

If a pass changes code but returns PreservedAnalyses::all(), the stale result survives (the hypothesis of Theorem 12.1.17 fails). The course's test tests/ch12/lit/stats-cache.ll catches exactly this for pebble-strength: print<pebble-stats> would print the old opcode counts. The converse mistake — returning none() when nothing changed — is only slow.

5. Complexity

Let \(k\) be the number of passes, \(n\) the number of units (functions), \(a\) the number of analyses, \(c_A\) the cost of computing analysis \(A\) on one unit, and \(d\) the number of dependency edges.

Technique Cost of analyses (worst) Cost of analyses (typical) Bookkeeping per pass Space
Legacy PM \(k \cdot n \cdot \sum_A c_A\) analyses recomputed only after non-preserving passes, as declared \(O(a)\) set operations per scheduled pass, once, at schedule time one result per analysis, freed when not preserved
New PM \(k \cdot n \cdot \sum_A c_A\) results recomputed only after a run that really changed them \(O(\lvert \mathrm{cache}_u \rvert + d)\) per pass per unit (memoized Inv) cache per (analysis, unit) pair
GCC PM \(k \cdot n \cdot\) (cost of TODOs) TODO work only where requested \(O(1)\) bit operations one IR, properties as a bit mask
MLIR PM as new PM as new PM, divided by up to \(\min(\#\text{threads}, \#\text{children})\) in wall time analysis map per operation one analysis manager per anchored operation

Justification. Invalidate visits each cached result once and, thanks to the memo, each dependency edge once: \(O(\lvert \mathrm{cache}_u \rvert + d)\). The worst case of both LLVM managers is the pathological family \(\pi_k = (\text{require}\langle A \rangle, q)^k\) where \(q\) always returns none: every one of the \(k\) requests misses, costing \(k \cdot n \cdot c_A\) — and for \(A = \mathrm{SE}\) also \(k \cdot n \cdot (c_{\mathrm{DT}} + c_{\mathrm{LI}})\) through dependencies. Real scale: LLVM 23's default<O2> pipeline has 119 top-level elements (opt -passes='default<O2>' -print-pipeline-passes, Lesson 12.2); CGSCC iteration is bounded by devirt<4> (at most 4 repetitions per SCC) in that pipeline. For MLIR, Proposition 12.1.21 bounds the achievable parallelism by the number of isolated children, e.g. functions in a module.

6. Variants and refinements

LLVM legacy pass manager

  • LoopPass / CallGraphSCCPass managers nested inside the function and module managers (LPPassManager, CGPassManager): the same declaration scheme per unit kind [LLVM-WLP]. Trade-off: nesting is implicit in the pass type, so a pipeline's structure is hard to see.
  • Immutable passes (ImmutablePass, e.g. TargetLibraryInfoWrapperPass) are never freed. Trade-off: correct only for information that cannot change.

LLVM new pass manager

  • Eager invalidation (function<eager-inv> in the O-pipelines): drop all function analyses after the function pipeline, to save memory [LLVM-PBP]. Trade-off: recomputation if a later pipeline wants them.
  • abandon<A>() and analysis sets: finer statements than "preserved"; preservedWhenStateless lets stateless analyses survive unless explicitly abandoned.
  • Loop pipelines with LPMUpdater let loop passes add or delete loops while the adaptor walks them (LoopPassManager.h [LLVM-LPM]).

GCC pass manager

  • IPA passes in three stages (summary generation, propagation, transformation) so that LTO can stream summaries ("Inter-procedural optimization passes" in [GCC-Int]). Trade-off: every IPA pass must be written three times.
  • Pass instances and set_pass_param (NEXT_PASS (pass_ccp, true)): one pass runs several times with parameters. Trade-off: dump files are numbered per instance.

MLIR pass manager

  • Dynamic pipelines (Pass::runPipeline) for passes such as the inliner that simplify callees while they run ("Dynamic Pass Pipelines" in [MLIR-PM]). Trade-off: less static checking of the pipeline.
  • Op-agnostic pipelines (nestAny, any(...)): one pipeline for every isolated operation type. Trade-off: passes must use interfaces instead of concrete op types.
  • Crash reproducers (--mlir-pass-pipeline-crash-reproducer): the manager records the pipeline and the input that crashed — built-in test-case reduction support (Lesson 12.7).

7. In real compilers

LLVM legacy pass manager

llvm/lib/IR/LegacyPassManager.cpp — PMTopLevelManager::schedulePass, FPPassManager::runOnFunction, PMDataManager::removeNotPreservedAnalysis [LLVM-LegacyPM] (LLVM 23.1.2). opt 23.1.2 no longer accepts -enable-new-pm=0; llc still builds its code-generation pipeline with the legacy manager by default and has a partial -enable-new-pm port.

The legacy schedule of llc: analyses inserted and re-inserted

Reproduce (llc 23.1.2, opt 23.1.2):

printf 'define i32 @f(i32 %%x) {\n  %%r = sdiv i32 %%x, 4\n  ret i32 %%r\n}\n' > sd.ll
opt -enable-new-pm=0 -O2 sd.ll -o /dev/null 2>&1
llc -O2 -mtriple=x86_64-linux-gnu -debug-pass=Structure sd.ll -o /dev/null 2>&1 | sed -n '2,20p'

Output (the opt error, then the first lines of the structure):

opt: Unknown command line argument '-enable-new-pm=0'.  Try: 'opt --help'
opt: Did you mean '--enable-newgvn=0'?
Target Library Information
Runtime Library Function Analysis
Target Pass Configuration
Machine Module Information
Target Transform Information
Assumption Cache Tracker
Library Function Lowering Analysis
Type-Based Alias Analysis
Scoped NoAlias Alias Analysis
Create Garbage Collector Module Metadata
Profile summary info
Machine Branch Probability Analysis
Default Regalloc Eviction Advisor
Default Regalloc Priority Advisor
  ModulePass Manager
    FunctionPass Manager
      Dominator Tree Construction
      Basic Alias Analysis (stateless AA impl)
      Function Alias Analysis Results

What to notice: the schedule (Algorithm 12.1.6) is flat and precomputed; immutable passes come first; within the function pass manager, Dominator Tree Construction appears again and again (the full listing has 216 lines) because a declared non-preserving pass freed it — declared, not observed. The optimizer (opt) has no legacy mode left.

LLVM new pass manager

llvm/include/llvm/IR/PassManager.h — AnalysisManager, InnerAnalysisManagerProxy, OuterAnalysisManagerProxy, ModuleToFunctionPassAdaptor, RequiredPassInfoMixin, OptionalPassInfoMixin; llvm/include/llvm/IR/Analysis.h — PreservedAnalyses, CFGAnalyses [LLVM-PMH]; llvm/include/llvm/IR/PassManagerImpl.h — AnalysisManager::invalidate; llvm/include/llvm/Analysis/CGSCCPassManager.h — ModuleToPostOrderCGSCCPassAdaptor, DevirtSCCRepeatedPass [LLVM-CGSCC]; llvm/include/llvm/IR/PassInstrumentation.h — PassInstrumentationCallbacks [LLVM-PI]; llvm/lib/Passes/StandardInstrumentations.cpp — OptNoneInstrumentation::shouldRun [LLVM-SI] (LLVM 23.1.2).

An invalidation cascade, and an analysis that survives it

Reproduce (opt 23.1.2):

cat > cascade.ll <<'EOF'
define i32 @f(ptr %p, i32 %n) {
entry:
  br label %loop
loop:
  %i = phi i32 [ 0, %entry ], [ %i.next, %loop ]
  %v = load i32, ptr %p
  %i.next = add i32 %i, %v
  %c = icmp slt i32 %i.next, %n
  br i1 %c, label %loop, label %exit
exit:
  ret i32 %i
}
EOF
opt -passes='function(require<scalar-evolution>,require<memoryssa>,invalidate<domtree>,require<loops>)' \
    -debug-pass-manager -disable-output cascade.ll 2>&1 | grep -v VerifierPass

Output (complete, minus the verifier line):

Running analysis: InnerAnalysisManagerProxy<AnalysisManager<Function>, Module> on [module]
Running pass: RequireAnalysisPass<ScalarEvolutionAnalysis, Function> on f (7 instructions)
Running analysis: ScalarEvolutionAnalysis on f
Running analysis: TargetLibraryAnalysis on f
Running analysis: AssumptionAnalysis on f
Running analysis: TargetIRAnalysis on f
Running analysis: DominatorTreeAnalysis on f
Running analysis: LoopAnalysis on f
Running pass: RequireAnalysisPass<MemorySSAAnalysis, Function> on f (7 instructions)
Running analysis: MemorySSAAnalysis on f
Running analysis: AAManager on f
Running analysis: BasicAA on f
Running analysis: ScopedNoAliasAA on f
Running analysis: TypeBasedAA on f
Running analysis: OuterAnalysisManagerProxy<AnalysisManager<Module>, Function> on f
Running pass: InvalidateAnalysisPass<DominatorTreeAnalysis> on f (7 instructions)
Invalidating analysis: DominatorTreeAnalysis on f
Invalidating analysis: ScalarEvolutionAnalysis on f
Invalidating analysis: BasicAA on f
Invalidating analysis: AAManager on f
Invalidating analysis: MemorySSAAnalysis on f
Running pass: RequireAnalysisPass<LoopAnalysis, Function> on f (7 instructions)
Running analysis: VerifierAnalysis on [module]

What to notice: invalidate<domtree> returns "everything but DT preserved"; Lemma 12.1.18 then drops SE, BasicAA, AAManager and MemorySSA, which depend on DT. LoopAnalysis was computed from the dominator tree but survives — it requests DT without depending on it, and its invalidate checks only the CFG (Definition 12.1.2 and the example after Definition 12.1.4) — and require<loops> finds it cached. The drill pm-invalidation uses exactly these rules.

Required and optional passes: optnone and the pass gate

Reproduce (opt 23.1.2, the course plugin built by ./course test 12 --solution; $SOL is that build: SOL=$PWD/build/ci-solutions-linux from the repository root, ci-solutions-macos on macOS):

cat > on.ll <<'EOF'
define i32 @opt_me(i32 %x) {
  %r = mul i32 %x, 8
  ret i32 %r
}
define i32 @leave_me(i32 %x) #0 {
  %r = mul i32 %x, 8
  ret i32 %r
}
attributes #0 = { noinline optnone }
EOF
opt -load-pass-plugin=$SOL/lib/PebblePasses.so \
    -passes='function(pebble-strength,print<pebble-stats>)' -debug-pass-manager -disable-output on.ll 2>&1 \
  | grep -E 'Skipping|Running pass|opcodes'

Output:

Running pass: (anonymous namespace)::StrengthPass on opt_me (2 instructions)
Running pass: (anonymous namespace)::StatsPrinter on opt_me (2 instructions)
  opcodes: ret=1 shl=1
Skipping pass (anonymous namespace)::StrengthPass on leave_me due to optnone attribute
Skipping pass: (anonymous namespace)::StrengthPass on leave_me
Running pass: (anonymous namespace)::StatsPrinter on leave_me (2 instructions)
  opcodes: mul=1 ret=1
Running pass: VerifierPass on [module]

What to notice: OptNoneInstrumentation answered shouldRunOptionalPass with false for the optional pebble-strength (an OptionalPassInfoMixin), which Algorithm 12.1.8 turns into a beforeSkippedPass; the printer is a RequiredPassInfoMixin and runs on both functions. The class names are the reference solution's: plugin passes are printed by C++ name, not by pipeline name.

The CGSCC adaptor visits callees first

Reproduce (opt 23.1.2):

cat > cg.ll <<'EOF'
define internal i32 @leaf(i32 %x) {
  %r = mul i32 %x, 4
  ret i32 %r
}
define i32 @root(i32 %x) {
  %a = call i32 @leaf(i32 %x)
  %b = add i32 %a, 1
  ret i32 %b
}
EOF
opt -passes='cgscc(inline,function(instcombine))' -debug-pass-manager -S cg.ll 2>&1 \
  | grep -E '^Running pass|^define|^  %|ret i32'

Output:

Running pass: InlinerPass on (leaf) (1 node)
Running pass: InstCombinePass on leaf (2 instructions)
Running pass: InlinerPass on (root) (1 node)
Running pass: InstCombinePass on root (3 instructions)
Running pass: VerifierPass on [module]
Running pass: PrintModulePass on [module]
define i32 @root(i32 %x) {
  %r.i = shl i32 %x, 2
  %b = or disjoint i32 %r.i, 1
  ret i32 %b

What to notice: Definition 12.1.11's post-order: the SCC (leaf) is simplified (mul → shl) before the inliner visits (root) and copies the simplified body (%r.i); the dead internal @leaf is then deleted. (The unfiltered output also shows eight "Invalidating analysis" lines on root after inlining changed its CFG-free body: the inliner reports nothing preserved.)

GCC pass manager

gcc/passes.def — the pass tree (INSERT_PASSES_AFTER (all_passes), PUSH_INSERT_PASSES_WITHIN (pass_all_optimizations), NEXT_PASS (pass_ccp, true)) [GCC-PassesDef]; gcc/tree-pass.h — pass_data, opt_pass, the PROP_* and TODO_* bits [GCC-TreePass]; gcc/passes.cc — execute_one_pass, execute_todo [GCC-Passes]; gcc/tree-ssa-ccp.cc — pass_data_ccp requires PROP_cfg | PROP_ssa and finishes with TODO_update_address_taken (gcc-15 branch).

GCC's pass tree with its gates evaluated

Reproduce (gcc 14.2.0 on x86-64 Linux — Ubuntu 24.04: sudo apt install gcc-14; macOS: brew install gcc@14, whose driver is also gcc-14; other GCC versions and targets print other pass lists and line counts):

printf 'int check(int x) { return x + 1 > x; }\n' > ub.c
gcc-14 -O2 -fdump-passes -c ub.c -o /dev/null 2>&1 | sed -n '17,40p'
gcc-14 -O2 -fdump-passes -c ub.c -o /dev/null 2>&1 | wc -l

Output:

   ipa-visibility                                      :  ON
   ipa-strubm                                          :  OFF
   ipa-build_ssa_passes                                :  ON
      tree-fixup_cfg1                                  :  ON
      tree-ssa                                         :  ON
      tree-walloca1                                    :  ON
      tree-warn-printf                                 :  OFF
      *nonnullcmp                                      :  OFF
      tree-early_uninit                                :  OFF
      tree-waccess1                                    :  ON
      tree-ubsan                                       :  OFF
      tree-nothrow                                     :  ON
      *rebuild_cgraph_edges                            :  ON
   ipa-opt_local_passes                                :  ON
      tree-fixup_cfg2                                  :  ON
      *rebuild_cgraph_edges                            :  ON
      tree-local-fnsummary1                            :  ON
      tree-einline                                     :  ON
      *infinite-recursion                              :  OFF
      tree-early_optimizations                         :  ON
         *remove_cgraph_callee_edges                   :  ON
         tree-early_objsz                              :  ON
         tree-ccp1                                     :  ON
         tree-forwprop1                                :  ON
378

What to notice: the nesting is the sub/next tree of Algorithm 12.1.13 (tree-early_optimizations has sub-passes); ON/OFF is each pass's gate at -O2; numbered names (ccp1, fixup_cfg2) are instances of one pass class (Section 6). A star marks passes without dump files. 378 lines for one function: GCC runs the same static tree for every function.

MLIR pass manager

mlir/lib/Pass/Pass.cpp — OpToOpPassAdaptor::runOnOperation, OpToOpPassAdaptor::runPipeline [MLIR-Pass]; mlir/include/mlir/Pass/Pass.h — Pass::runPipeline (inline; the dynamic-pipeline entry point); the documentation [MLIR-PM] (LLVM 23.1.2).

MLIR runs a nested pipeline one function at a time

Reproduce (mlir-opt 23.1.2 — macOS: Homebrew's llvm ships it in $(brew --prefix llvm)/bin; Linux: see the chapter's tools outside the course toolchain; this output came from the conda-forge mlir 23.1.2 package):

cat > m.mlir <<'EOF'
func.func @f(%x: i32) -> i32 {
  %c8 = arith.constant 8 : i32
  %a = arith.muli %x, %c8 : i32
  %b = arith.muli %x, %c8 : i32
  %s = arith.addi %a, %b : i32
  return %s : i32
}
func.func @g(%x: i32) -> i32 {
  %c0 = arith.constant 0 : i32
  %a = arith.addi %x, %c0 : i32
  return %a : i32
}
EOF
mlir-opt m.mlir -pass-pipeline='builtin.module(func.func(cse,canonicalize))' \
  -mlir-print-ir-after-all -mlir-disable-threading -o /dev/null 2>&1 | grep -E '^// -----|^func.func'

Output:

// -----// IR Dump After CSEPass: cse //----- //
func.func @f(%arg0: i32) -> i32 {
// -----// IR Dump After CanonicalizerPass: canonicalize{cse-between-iterations=false    max-iterations=10 max-num-rewrites=-1 region-simplify=normal test-convergence=false top-down=true} //----- //
func.func @f(%arg0: i32) -> i32 {
// -----// IR Dump After CSEPass: cse //----- //
func.func @g(%arg0: i32) -> i32 {
// -----// IR Dump After CanonicalizerPass: canonicalize{cse-between-iterations=false    max-iterations=10 max-num-rewrites=-1 region-simplify=normal test-convergence=false top-down=true} //----- //
func.func @g(%arg0: i32) -> i32 {

What to notice: the whole func.func pipeline runs on @f, then on @g (Algorithm 12.1.15), and each dump shows only the anchored function — passes cannot see outside it. Without -mlir-disable-threading the two functions are processed on different threads; Proposition 12.1.21 is why the result is the same. (Between the two dumps of @f, cse merged the two mulis.)

8. Comparison

Technique Power / precision Speed Output / error quality Implementation effort Typical use
LLVM legacy PM Static, declared preservation: must assume the worst case per pass Recomputes after every declared non-preserving pass, even when nothing changed -debug-pass=Structure shows the whole schedule up front Low per pass (declare usage); complex manager LLVM codegen (llc) in LLVM 23; LLVM optimizer before LLVM 13
LLVM new PM Dynamic, per-run PreservedAnalyses; dependency-aware invalidation (Theorem 12.1.17) Lazy; recomputes only what a run invalidated; \(O(\lvert \mathrm{cache} \rvert + d)\) bookkeeping per pass -debug-pass-manager, -print-changed, pass instrumentation Moderate per pass (truthful reports, invalidate for dependent analyses) LLVM 23 optimizer, opt, clang, the course plugin
GCC PM Coarse: IR properties and TODO flags instead of per-analysis caching Static tree; repairs (update SSA, cleanup CFG) on request -fdump-passes, per-pass dumps -fdump-tree-<pass> Low per pass (fill in pass_data) GCC's GIMPLE, RTL and IPA pipelines
MLIR PM Per-operation analysis managers; nesting follows the IR; op-agnostic pipelines Parallel over isolated operations (Proposition 12.1.21) -mlir-print-ir-after-all, -mlir-timing, crash reproducers Moderate: declare anchors, keep passes local MLIR-based compilers (Flang, CIRCT, IREE, Triton)

Choose the legacy PM when you maintain LLVM code-generation passes today; nothing new should target it. Choose the new PM when you write any LLVM optimization or analysis: it is the only optimizer pipeline, and its per-run preservation makes cheap passes cheap. Choose GCC's model when the compiler has few analyses and many IR-form invariants (SSA or not, CFG or not): properties are simple and checkable. Choose MLIR's model when the IR is a nest of isolated regions and compile time matters on many cores: anchoring gives parallelism for free.

9. Assessment

  • Quiz (./course quiz 12): pm-cache-trace (mapping), pm-cascade (set), pm-legacy-vs-new, pm-optional-required, pm-legacy-declare, pm-gcc-properties, pm-mlir-anchor, pm-cgscc-order (sequence), llvm-where-optnone (find it in LLVM), llvm-where-invalidate-scev.
  • Drill: ./course drill pm-invalidation (all difficulties; hard includes MemorySSA and PDT).
  • Flashcards: tags legacy-pm, new-pm, gcc-pm, mlir-pm.
  • Exercise: E1 (pebble-stats, cached and invalidated by the new pass manager; exercises.md).
  • Find where LLVM does it: open llvm/lib/Analysis/ScalarEvolution.cpp at llvmorg-23.1.2 and find ScalarEvolution::invalidate: which three analyses does it consult? Then open llvm/lib/Passes/StandardInstrumentations.cpp: which callback does OptNoneInstrumentation register?

References

See the chapter references.