Algorithm Search⌘K

Algorithmcore

0-CFA

Also called zeroth-order control flow analysis, monovariant control flow analysis.

Find the functions that each expression of a higher-order program may evaluate to, with one abstract binding per variable, in cubic time.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the number of nodes of the program
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
Olin Shivers, 1988

0-CFA is the simplest control flow analysis for higher-order programs. In a language where functions are values, the function that a call f x runs depends on the value of f, so call graph construction needs to know which functions can flow into which expressions. 0-CFA answers this with one set of functions for each expression and one for each variable, the same for all calls of the enclosing function. It writes the flow as inclusions between sets and solves them with a worklist in O(n3)O(n^3) time. The answer is sound for every run, it is the base of closure optimizations, and it is the k=0k = 0 case of k-CFA.

In plain words

In a functional program, f x may call any function that ends up in f. To find out which, 0-CFA gives every expression and every variable a set of functions. A function written in the code goes into the set of its own expression. A variable gets everything that was bound to it. When a call may call a function, the argument flows into the parameter of that function, and the result of its body flows back into the call. The analysis only looks inside a function once some call can call it. It repeats this until nothing new appears. Every variable has one set for the whole program, so two calls of the same function mix their arguments. That is what the 0 in the name means.

The problem

The input is a closed term of a call-by-value language with variables, fun x -> e, fix f x -> e (a recursive function), application e1 e2, let x = e1 in e2, if e1 then e2 else e3, operators on integers and constants. Each node has a label tt, and each variable occurrence knows its binder bb. Λ\Lambda is the set of function nodes. The output is the least triple of a set ReRe of reachable labels, a cache C[t]⊆ΛC[t] \subseteq \Lambda for each label and an environment R[b]⊆ΛR[b] \subseteq \Lambda for each binder, such that for every t∈Ret \in Re:

  1. a function tt has t∈C[t]t \in C[t];
  2. a variable with binder bb has R[b]⊆C[t]R[b] \subseteq C[t];
  3. let x = t1 in t2 has C[t1]⊆R[x]C[t_1] \subseteq R[x] and C[t2]⊆C[t]C[t_2] \subseteq C[t];
  4. if t1 then t2 else t3 has C[t2]∪C[t3]⊆C[t]C[t_2] \cup C[t_3] \subseteq C[t];
  5. t1 t2 has, for each λ∈C[t1]\lambda \in C[t_1]: body(λ)∈Re\mathrm{body}(\lambda) \in Re, C[t2]⊆R[param(λ)]C[t_2] \subseteq R[\mathrm{param}(\lambda)], C[body(λ)]⊆C[t]C[\mathrm{body}(\lambda)] \subseteq C[t], and for fix f x -> e also λ∈R[f]\lambda \in R[f];

and the root and the direct subterms of every reachable node other than a function are in ReRe. The call graph is the set of pairs (t,λ)(t, \lambda) with tt = t1 t2 in ReRe and λ∈C[t1]\lambda \in C[t_1].

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain triples (Re,C,R)(Re, C, R) of reachable labels and sets of functions
order inclusion in all parts (bottom is precise)
join union in all parts
bottom and top everything empty, and all labels reachable with all sets equal to Λ\Lambda
boundary value the root is reachable
initial value everything empty
transfer the inclusions above; monotone, and not distributive, since rule 5 needs both tt reachable and λ∈C[t1]\lambda \in C[t_1]

The algorithm

  1. ZERO-CFA(e)
  2. 1label the nodes of e and link each variable to its binder
  3. 2for each set node n (C[t] for a label, R[b] for a binder): V[n] <- {}; D[n] <- {}; succ[n] <- {}
  4. 3W <- []; REACH(root)
  5. 4while W is not empty do
  6. 5take n from W; d <- D[n]; D[n] <- {}
  7. 6for each application t that watches n and each λ in d do CALL(t, λ)
  8. 7for each m in succ[n] do PROPAGATE(m, d)
  9. 8return the sets V
  10. REACH(t)
  11. 9if t is marked then return; mark t
  12. 10if t is a function then PROPAGATE(C[t], {t}); stop here, the body waits for a call
  13. 11if t is a variable with binder b then ADD-EDGE(R[b], C[t])
  14. 12if t is let x = t1 in t2 then ADD-EDGE(C[t1], R[x]); ADD-EDGE(C[t2], C[t])
  15. 13if t is if t1 then t2 else t3 then ADD-EDGE(C[t2], C[t]); ADD-EDGE(C[t3], C[t])
  16. 14if t is t1 t2 then make t watch C[t1] and CALL(t, λ) for each λ in V[C[t1]]
  17. then REACH each direct subterm of t
  18. CALL(t, λ) -- t is t1 t2
  19. 15if λ is fix f x -> body then PROPAGATE(R[f], {λ})
  20. 16ADD-EDGE(C[t2], R[param(λ)])
  21. 17ADD-EDGE(C[body(λ)], C[t])
  22. 18REACH(body(λ))
  23. ADD-EDGE(a, b)
  24. 19if b is not in succ[a] then add b to succ[a]; PROPAGATE(b, V[a])
  25. PROPAGATE(n, d)
  26. 20d <- d \ V[n]; if d is empty then return
  27. 21V[n] <- V[n] ∪ d; D[n] <- D[n] ∪ d; if n is not in W then add n to W

The sets V[n]V[n] form a graph with an edge a→ba \to b for each inclusion V[a]⊆V[b]V[a] \subseteq V[b]. Most edges are known from the text (lines L11 to L13). The edges of a call (lines L16 and L17) appear only when a function reaches the operator, which is why each application watches the cache of its operator. D[n]D[n] holds the elements that nn has not yet sent on, so each element crosses each edge once. REACH skips the bodies of functions, and line L18 visits a body only when a call may run it.

Example

let id = fun x -> x in
let a = id (fun y -> y + 1) in
let b = id (fun z -> z * 2) in
a 3

The program evaluates to 4. Write λx\lambda_x, λy\lambda_y and λz\lambda_z for the three functions.

step what the algorithm finds
1 REACH from the root: λx∈C[fun x]\lambda_x \in C[\texttt{fun x}], and the edge to R[id]R[id] gives R[id]={λx}R[id] = \{\lambda_x\}
2 the operator id of both calls gets λx\lambda_x; each call runs CALL with λx\lambda_x
3 the first call: λy\lambda_y flows into R[x]R[x]; the second call: λz\lambda_z flows into R[x]R[x]; so R[x]={λy,λz}R[x] = \{\lambda_y, \lambda_z\}
4 the body x of λx\lambda_x gets {λy,λz}\{\lambda_y, \lambda_z\} and sends it back to both calls; so R[a]=R[b]={λy,λz}R[a] = R[b] = \{\lambda_y, \lambda_z\}
5 the call a 3 gets λy\lambda_y and λz\lambda_z in its operator, CALL reaches both bodies, and the integer 3 adds no function to R[y]R[y] or R[z]R[z]

The call graph has 4 edges: both calls of id go to λx\lambda_x, and a 3 goes to λy\lambda_y and λz\lambda_z. The run only calls λy\lambda_y at a 3. The edge to λz\lambda_z is spurious, because both calls of id share the one set R[x]R[x]. 1-CFA keeps one set of x per call site of id, and removes it.

Correctness

Least solution. Every edge and every element that the algorithm adds is required by one of the rules, for labels that the rules make reachable. So, by induction over the steps, the sets stay inside every solution. When WW is empty, every element of every set has crossed every edge and reached every watcher, so all rules hold. So the result is the least solution.

Soundness. Use an environment semantics with closures (λ,ρ)(\lambda, \rho). Call an environment good if the closure of each variable has its function in RR of the variable's binder, and its own environment good. By induction on the evaluation, a reachable node evaluated in a good environment gives a value whose function is in C[t]C[t]. At a call, the operator gives λ∈C[t1]\lambda \in C[t_1], rule 5 puts the argument into R[param(λ)]R[\mathrm{param}(\lambda)] and makes the body reachable, so the body runs in a good environment and its result is in C[t]C[t]. This covers runs that stop, get stuck or loop, since every finished part of a run is a finished evaluation. The full proofs are in the proof file.

Proof: The worklist 0-CFA computes the least closed analysis in cubic time, and the analysis is sound for call-by-value runsfull

Setting. The program is a term of the toy language with the nodes x, fun x -> e, fix f x -> e, e1 e2, let x = e1 in e2, if e1 then e2 else e3, e1 op e2 and integer and boolean constants. Line L1 gives every node a label tt, and gives every variable occurrence its binder: the lambda, fix or let node that binds it, paired with the name. A function is a lambda or a fix node, and Λ\Lambda is the set of functions. For a function λ\lambda, param(λ)\mathrm{param}(\lambda) is the binder of its argument and body(λ)\mathrm{body}(\lambda) its body. An analysis is a triple (Re,C,R)(Re, C, R): a set ReRe of labels, a set C[t]⊆ΛC[t] \subseteq \Lambda for each label and a set R[b]⊆ΛR[b] \subseteq \Lambda for each binder. It is closed if:

  1. the root is in ReRe;
  2. for a function t∈Ret \in Re: t∈C[t]t \in C[t];
  3. for a variable t∈Ret \in Re with binder bb: R[b]⊆C[t]R[b] \subseteq C[t];
  4. for tt = let x = t1 in t2 in ReRe: t1,t2∈Ret_1, t_2 \in Re, C[t1]⊆R[(t,x)]C[t_1] \subseteq R[(t, x)] and C[t2]⊆C[t]C[t_2] \subseteq C[t];
  5. for tt = if t1 then t2 else t3 in ReRe: t1,t2,t3∈Ret_1, t_2, t_3 \in Re and C[t2]∪C[t3]⊆C[t]C[t_2] \cup C[t_3] \subseteq C[t];
  6. for tt = t1 op t2 in ReRe: t1,t2∈Ret_1, t_2 \in Re;
  7. for tt = t1 t2 in ReRe: t1,t2∈Ret_1, t_2 \in Re, and for every λ∈C[t1]\lambda \in C[t_1]: body(λ)∈Re\mathrm{body}(\lambda) \in Re, C[t2]⊆R[param(λ)]C[t_2] \subseteq R[\mathrm{param}(\lambda)], C[body(λ)]⊆C[t]C[\mathrm{body}(\lambda)] \subseteq C[t], and if λ\lambda is fix f x -> e, then λ∈R[(λ,f)]\lambda \in R[(\lambda, f)].

Analyses are ordered by inclusion in all parts. Each rule keeps holding when the sets grow on its right side, so the intersection of closed analyses is closed, and there is a least closed analysis.

In the algorithm, the set nodes are C[t]C[t] and R[b]R[b], V[n]V[n] is the current set of node nn, D[n]D[n] is the part of V[n]V[n] that has not yet been sent along the edges of nn, and nn is in WW exactly when D[n]≠∅D[n] \ne \emptyset. ReRe is the set of labels marked by line L9.

Lemma 1 (the edge invariant). At each test of line L4: for every edge a→ba \to b, V[a]∖D[a]⊆V[b]V[a] \setminus D[a] \subseteq V[b]; and for every application tt that watches the node C[t1]C[t_1] and every λ∈V[C[t1]]∖D[C[t1]]\lambda \in V[C[t_1]] \setminus D[C[t_1]], CALL(t,λ)\mathrm{CALL}(t, \lambda) has run.

Proof. Line L19 creates an edge a→ba \to b and sends all of V[a]V[a] to bb at once. Line L14 makes tt watch C[t1]C[t_1] and runs CALL for all of V[C[t1]]V[C[t_1]] at once. After that, an element enters V[a]V[a] only in line L21, which puts it into D[a]D[a] too. It leaves D[a]D[a] only in line L5, and lines L6 and L7 then send it along every edge of aa and to every watcher of aa. Sets only grow, so an element once in V[b]V[b] stays there. □\square

Lemma 2 (termination). The algorithm stops.

Proof. There are finitely many set nodes, and each V[n]V[n] is a subset of the finite set Λ\Lambda. Every pass of the loop of line L4 removes a node nn with D[n]≠∅D[n] \ne \emptyset. A node returns to WW only when line L21 adds a new element to V[n]V[n]. So the number of passes is at most the number of nodes plus ∑n∣V[n]∣\sum_n |V[n]|, which is finite. Each REACH marks each label at most once (line L9), so each call of REACH stops. □\square

Lemma 3 (the result is closed). When the algorithm stops, (Re,V[C[⋅]],V[R[⋅]])(Re, V[C[\cdot]], V[R[\cdot]]) is closed.

Proof. At the end WW is empty, so every D[n]D[n] is empty, and Lemma 1 gives V[a]⊆V[b]V[a] \subseteq V[b] for every edge, and CALL(t,λ)\mathrm{CALL}(t, \lambda) for every watcher tt of C[t1]C[t_1] and every λ∈V[C[t1]]\lambda \in V[C[t_1]]. Line L3 puts the root in ReRe. For each label tt that line L9 marks, the lines after it give the rule of tt: line L10 gives rule 2; line L11 gives the edge R[b]→C[t]R[b] \to C[t] of rule 3; line L12 gives the two edges of rule 4; line L13 gives the edges of rule 5; and line L14 makes tt watch C[t1]C[t_1]. REACH visits the direct subterms of let, if, op and application nodes, which gives the membership parts of rules 4 to 7. For rule 7, each λ∈V[C[t1]]\lambda \in V[C[t_1]] had CALL(t,λ)\mathrm{CALL}(t, \lambda), and lines L15 to L18 give exactly the four parts of the rule for λ\lambda. □\square

Lemma 4 (every fact is forced). Let (Re∗,C∗,R∗)(Re^*, C^*, R^*) be any closed analysis. At all times, every label marked by line L9 is in Re∗Re^*, V[C[t]]⊆C∗[t]V[C[t]] \subseteq C^*[t] and V[R[b]]⊆R∗[b]V[R[b]] \subseteq R^*[b].

Proof. By induction over the steps. Line L3 marks the root, which is in Re∗Re^* by rule 1. REACH marks the direct subterms of a marked let, if, op or application node, which are in Re∗Re^* by rules 4 to 7, and line L18 marks body(λ)\mathrm{body}(\lambda) for an application tt and a λ∈V[C[t1]]⊆C∗[t1]\lambda \in V[C[t_1]] \subseteq C^*[t_1], which is in Re∗Re^* by rule 7. Line L10 adds tt to V[C[t]]V[C[t]] for a marked function tt, which rule 2 allows. Every edge a→ba \to b that lines L11 to L13, L16 and L17 create is an inclusion that rules 3 to 5 or 7 require of every closed analysis, for nodes marked or for a λ\lambda in C∗[t1]C^*[t_1]; so sending V[a]⊆a∗V[a] \subseteq a^* along it keeps V[b]⊆b∗V[b] \subseteq b^*. Line L15 adds λ\lambda to V[R[(λ,f)]]V[R[(\lambda, f)]], which rule 7 requires. □\square

Theorem 1 (least closed analysis). The algorithm stops and returns the least closed analysis.

Proof. Lemma 2, Lemma 3 and Lemma 4. □\square

The semantics. A value is a constant or a closure (λ,ρ)(\lambda, \rho) of a function and an environment. An environment maps names to values. The judgement ρ⊢t⇓v\rho \vdash t \Downarrow v is the usual call-by-value big-step evaluation. For an application, ρ⊢t1⇓(λ,ρ′)\rho \vdash t_1 \Downarrow (\lambda, \rho') and ρ⊢t2⇓a\rho \vdash t_2 \Downarrow a, and then body(λ)\mathrm{body}(\lambda) runs in ρ′\rho' extended with the argument, and for a fix also with ff bound to (λ,ρ′)(\lambda, \rho'). A run that does not stop, or gets stuck, is a tree of finished and unfinished evaluations. Every finished evaluation in it has a derivation.

Given a closed analysis, say that a value vv fits a set S⊆ΛS \subseteq \Lambda if vv is a constant, or v=(λ,ρ)v = (\lambda, \rho) with λ∈S\lambda \in S and ρ\rho good for λ\lambda. An environment ρ\rho is good for a node tt if each variable xx in scope at tt, with binder bb at tt, has ρ(x)\rho(x) fitting R[b]R[b]. Good for λ\lambda means good for λ\lambda itself.

Lemma 5 (the evaluation invariant). If t∈Ret \in Re, ρ\rho is good for tt, and ρ⊢t⇓v\rho \vdash t \Downarrow v, then vv fits C[t]C[t]. Moreover, every evaluation ρ1⊢t′⇓v′\rho_1 \vdash t' \Downarrow v' that the derivation contains has t′∈Ret' \in Re and ρ1\rho_1 good for t′t'. Every binding it makes, of v′v' to a binder bb, has v′v' fitting R[b]R[b], and every call it makes, at an application t′′t'' to a function λ\lambda, has λ∈C[t1′′]\lambda \in C[t_1''].

Proof. By induction on the height of the derivation. A constant fits any set. A variable xx with binder bb gives ρ(x)\rho(x), which fits R[b]⊆C[t]R[b] \subseteq C[t] by rule 3. A function tt gives (t,ρ)(t, \rho), with t∈C[t]t \in C[t] by rule 2, and ρ\rho is good for tt. For let x = t1 in t2, rule 4 puts t1t_1 and t2t_2 in ReRe. By induction the value aa of t1t_1 fits C[t1]⊆R[(t,x)]C[t_1] \subseteq R[(t, x)], so the extended environment is good for t2t_2, whose value fits C[t2]⊆C[t]C[t_2] \subseteq C[t]. The cases of if and of an operator are the same with rules 5 and 6; an operator gives a constant. For t1 t2, rule 7 puts t1,t2∈Ret_1, t_2 \in Re. By induction t1t_1 gives (λ,ρ′)(\lambda, \rho') with λ∈C[t1]\lambda \in C[t_1] and ρ′\rho' good for λ\lambda, which is the call fact. t2t_2 gives aa fitting C[t2]⊆R[param(λ)]C[t_2] \subseteq R[\mathrm{param}(\lambda)], by rule 7. For a fix, (λ,ρ′)(\lambda, \rho') fits R[(λ,f)]R[(\lambda, f)], since λ∈R[(λ,f)]\lambda \in R[(\lambda, f)] by rule 7. So the environment of the body is good for body(λ)\mathrm{body}(\lambda), which is in ReRe by rule 7. By induction its value fits C[body(λ)]⊆C[t]C[\mathrm{body}(\lambda)] \subseteq C[t]. The facts about the inner evaluations come from the induction hypothesis for each premise. □\square

Theorem 2 (soundness). Let the root be closed, and let (Re,C,R)(Re, C, R) be the result. In every run of the program, finished or not, every evaluation of a node tt to a closure (λ,ρ)(\lambda, \rho) has λ∈C[t]\lambda \in C[t], every binding of a closure (λ,ρ)(\lambda, \rho) to a binder bb has λ∈R[b]\lambda \in R[b], and every call at an application tt to a function λ\lambda has λ∈C[t1]\lambda \in C[t_1].

Proof. The root is in ReRe, and the empty environment is good for the closed root. Every finished evaluation in the run is a derivation inside the derivation tree of the run, which starts at the root with the empty environment. Apply Lemma 5 to the finished sub-derivations. A call is made only after both t1t_1 and t2t_2 have finished, so it is covered too. □\square

Theorem 3 (cost). For a term of nn nodes, the algorithm runs in O(n3)O(n^3) time with hash sets, in expectation, or with bit vectors in the worst case.

Proof. There are at most nn cache nodes and at most 2n2n binder nodes, and each set has at most ∣Λ∣≤n|\Lambda| \le n elements. Lines L11 to L13 make O(n)O(n) edges. Lines L16 and L17 make two edges per pair of an application and a function, so O(n2)O(n^2) edges in all. Each element enters each D[n]D[n] at most once, because line L20 removes the elements already in V[n]V[n]. So line L7 sends each element along each edge at most once, which costs O(n2)⋅O(n)=O(n3)O(n^2) \cdot O(n) = O(n^3). CALL runs for a pair (t,λ)(t, \lambda) at most twice: once in line L14 and once when λ\lambda is in the delta of the operator in line L6. That is O(n2)O(n^2) calls. Each call does O(1)O(1) work besides line L19, which may send a whole set of O(n)O(n) elements, so the calls cost O(n3)O(n^3). REACH marks each label once and does O(1)O(1) work per label besides its edges and calls. The total is O(n3)O(n^3). ■\blacksquare

Complexity

Proved. There are O(n)O(n) set nodes and each set has at most nn functions. The edges are O(n)O(n) from the text and two per pair of an application and a function, so O(n2)O(n^2) in all. Each element crosses each edge at most once, which costs O(n3)O(n^3). CALL runs at most twice per pair of an application and a function, and each run may send a set of size O(n)O(n), which is O(n3)O(n^3) again. So the time is O(n3)O(n^3) and the space is O(n2)O(n^2) for the sets and the edges.

Stated in the literature. Heintze and McAllester (1997) reduce the recognition problem of two-way nondeterministic pushdown automata (2NPDA) to flow analysis. No sub-cubic algorithm for that problem is known, so this is the "cubic bottleneck". Van Horn and Mairson (2008) prove that 0-CFA is complete for PTIME, so it is unlikely to have a fast parallel algorithm.

Measured, not proved. On 500 random closed terms (seed 1991), the result equals a plain round-robin iteration of the rules. On 2000 random terms (seed 1988), every closure, binding and call of a concrete run is in the result. The test interpreter agrees with the substitution semantics of the toy language on 500 random terms.

Properties

  • Monovariant. Each variable has one set for all calls of its function. This is the source of the spurious edge in the example.
  • Reachability-aware. A function body that no reachable call can run adds nothing. Plain constraint versions that scan all the code give a larger, still sound, result.
  • Flow-insensitive within a body. The branches of if both flow into the result, whatever the test.
  • Exact on linear programs. Van Horn and Mairson show that 0-CFA and evaluation agree when each bound variable is used at most once. This is the root of the PTIME hardness.
  • Equivalent to inclusion-based points-to analysis. Functions play the role of allocation sites, and application plays the role of a call through a pointer. The constraint graph is the one of Andersen's analysis.

Variants and improvements

  • k-CFA. Keep the last kk call sites as a context for each binding (k-CFA). It is more precise and EXPTIME-complete for k≥1k \ge 1 (the k-CFA theorem).
  • Abstract values for constants. Track integers and booleans by sign or by constant to prune if branches. This mixes control flow analysis with constant propagation.
  • Equality-based flow. Unify the sets of both sides instead of including one in the other, as in Steensgaard's analysis. It runs in almost linear time and loses precision.
  • Sub-transitive flow. Heintze and McAllester (PLDI 1997) answer some queries in linear time for typed programs of bounded type size by not building the transitive closure.
  • CFL reachability. The flow can also be written as reachability with matched parentheses (CFL reachability).

When to use it

Use 0-CFA when a compiler for a functional language needs to know which functions a call may run, for example to turn calls into direct calls, to choose a closure layout in closure conversion, or to do defunctionalization with one case per function that reaches a call. It is cubic in the worst case and usually much faster. When two uses of a helper such as map or compose mix their arguments and that costs too much precision, use 1-CFA or a polynomial context-sensitive variant.

Pitfalls

  • Analysing every body at once. A version of line L10 that also calls REACH on the body of every function gives a sound result with more edges, because dead functions add flows. Keep line L10 as it is and let line L18 reach a body only on a call.
  • Forgetting the self binding of fix. Without line L15, the recursive call f (x - 1) inside fix f x -> ... finds no function in R[f]R[f], and the recursive edge is missing. Line L15 must put the fix itself into R[f]R[f].
  • Sending only the new elements on a new edge. If line L19 sent only the current delta, the elements that aa received before the edge existed would never cross it. Line L19 must send all of V[a]V[a].
  • Calling 0-CFA context-sensitive. The name 0-CFA means zero call sites of context. Call strings of length kk give k-CFA only in this functional setting; in object-oriented programs, call-site contexts and k-CFA in the sense of Shivers differ.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

toylam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy lambda language: terms, types, call-by-value small steps.

Terms are tuples:
    ("var", x)              a variable, x is a str
    ("lam", x, e)           fun x -> e
    ("app", e1, e2)         e1 e2
    ("let", x, e1, e2)      let x = e1 in e2
    ("int", k)              an integer constant, k is a Python int
    ("bool", b)             true or false, b is a Python bool
    ("if", e1, e2, e3)      if e1 then e2 else e3
    ("prim", op, e1, e2)    e1 op e2, op is one of + - * < ==
    ("fix", f, x, e)        a recursive function: f is the function itself, x its argument

Types are tuples:
    ("int",)  ("bool",)  ("fun", t1, t2)  ("tv", n)   with n an int

Values are int and bool constants, lambdas and fix terms. The semantics is
call by value, left to right. step(e) returns the next term when e can step,
e itself when e is a value, and the marker "stuck" otherwise. A free
variable, an application of a non-function, a non-boolean condition and an
operator on non-integers are stuck. Substitution only ever puts closed values
into terms, because evaluation starts from closed terms, so no renaming is
needed.
"""

STUCK = "stuck"

PRIMS = ("+", "-", "*", "<", "==")


def is_value(e):
    return e[0] in ("int", "bool", "lam", "fix")


def free_vars(e):
    """The set of free term variables of e."""
    tag = e[0]
    if tag == "var":
        return {e[1]}
    if tag == "lam":
        return free_vars(e[2]) - {e[1]}
    if tag == "app":
        return free_vars(e[1]) | free_vars(e[2])
    if tag == "let":
        return free_vars(e[2]) | (free_vars(e[3]) - {e[1]})
    if tag in ("int", "bool"):
        return set()
    if tag == "if":
        return free_vars(e[1]) | free_vars(e[2]) | free_vars(e[3])
    if tag == "prim":
        return free_vars(e[2]) | free_vars(e[3])
    if tag == "fix":
        return free_vars(e[3]) - {e[1], e[2]}
    raise ValueError(f"not a term: {e!r}")


def subst(e, x, v):
    """Replace the free occurrences of x in e by the closed value v."""
    tag = e[0]
    if tag == "var":
        return v if e[1] == x else e
    if tag == "lam":
        return e if e[1] == x else ("lam", e[1], subst(e[2], x, v))
    if tag == "app":
        return ("app", subst(e[1], x, v), subst(e[2], x, v))
    if tag == "let":
        body = e[3] if e[1] == x else subst(e[3], x, v)
        return ("let", e[1], subst(e[2], x, v), body)
    if tag in ("int", "bool"):
        return e
    if tag == "if":
        return ("if", subst(e[1], x, v), subst(e[2], x, v), subst(e[3], x, v))
    if tag == "prim":
        return ("prim", e[1], subst(e[2], x, v), subst(e[3], x, v))
    if tag == "fix":
        if x in (e[1], e[2]):
            return e
        return ("fix", e[1], e[2], subst(e[3], x, v))
    raise ValueError(f"not a term: {e!r}")


def _prim(op, a, b):
    if op == "+":
        return ("int", a + b)
    if op == "-":
        return ("int", a - b)
    if op == "*":
        return ("int", a * b)
    if op == "<":
        return ("bool", a < b)
    if op == "==":
        return ("bool", a == b)
    raise ValueError(f"unknown operator {op!r}")


def step(e):
    """One call-by-value step: the next term, e itself if e is a value, or STUCK."""
    if is_value(e):
        return e
    tag = e[0]
    if tag == "var":
        return STUCK
    if tag == "app":
        f, a = e[1], e[2]
        if not is_value(f):
            f2 = step(f)
            return STUCK if f2 == STUCK else ("app", f2, a)
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("app", f, a2)
        if f[0] == "lam":
            return subst(f[2], f[1], a)
        if f[0] == "fix":
            return subst(subst(f[3], f[1], f), f[2], a)
        return STUCK
    if tag == "let":
        if not is_value(e[2]):
            e1 = step(e[2])
            return STUCK if e1 == STUCK else ("let", e[1], e1, e[3])
        return subst(e[3], e[1], e[2])
    if tag == "if":
        c = e[1]
        if not is_value(c):
            c2 = step(c)
            return STUCK if c2 == STUCK else ("if", c2, e[2], e[3])
        if c[0] == "bool":
            return e[2] if c[1] else e[3]
        return STUCK
    if tag == "prim":
        a, b = e[2], e[3]
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("prim", e[1], a2, b)
        if not is_value(b):
            b2 = step(b)
            return STUCK if b2 == STUCK else ("prim", e[1], a, b2)
        if a[0] == "int" and b[0] == "int":
            return _prim(e[1], a[1], b[1])
        return STUCK
    raise ValueError(f"not a term: {e!r}")


def evaluate(e, fuel=10000):
    """Run e. Returns ("value", v), ("stuck", t) with the stuck term t, or ("fuel",)."""
    for _ in range(fuel):
        if is_value(e):
            return ("value", e)
        nxt = step(e)
        if nxt == STUCK:
            return ("stuck", e)
        e = nxt
    return ("value", e) if is_value(e) else ("fuel",)


NAMES = ("x", "y", "z", "f", "g")


def random_term(rng, depth, scope=()):
    """A random term of height at most depth whose free variables are in scope.

    With the default empty scope the term is closed. rng is a random.Random.
    """
    scope = tuple(scope)
    if depth <= 0 or rng.random() < 0.15:
        r = rng.random()
        if scope and r < 0.6:
            return ("var", rng.choice(scope))
        if r < 0.8:
            return ("int", rng.randint(0, 3))
        return ("bool", rng.random() < 0.5)
    d = depth - 1
    kind = rng.choice(("var", "lam", "lam", "app", "app", "let", "let", "if", "prim", "fix"))
    if kind == "var" and scope:
        return ("var", rng.choice(scope))
    if kind == "lam" or kind == "var":
        x = rng.choice(NAMES)
        return ("lam", x, random_term(rng, d, scope + (x,)))
    if kind == "app":
        return ("app", random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "let":
        x = rng.choice(NAMES)
        return ("let", x, random_term(rng, d, scope), random_term(rng, d, scope + (x,)))
    if kind == "if":
        return ("if", random_term(rng, d, scope), random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "prim":
        return ("prim", rng.choice(PRIMS), random_term(rng, d, scope), random_term(rng, d, scope))
    f, x = rng.sample(NAMES, 2)
    return ("fix", f, x, random_term(rng, d, scope + (f, x)))


def size(e):
    """The number of nodes of the syntax tree of e."""
    tag = e[0]
    if tag in ("var", "int", "bool"):
        return 1
    if tag == "lam":
        return 1 + size(e[2])
    if tag == "app":
        return 1 + size(e[1]) + size(e[2])
    if tag == "let":
        return 1 + size(e[2]) + size(e[3])
    if tag == "if":
        return 1 + size(e[1]) + size(e[2]) + size(e[3])
    if tag == "prim":
        return 1 + size(e[2]) + size(e[3])
    if tag == "fix":
        return 1 + size(e[3])
    raise ValueError(f"not a term: {e!r}")


def show(e):
    """The surface syntax: fun x -> e, e1 e2, let x = e1 in e2."""
    tag = e[0]
    if tag == "var":
        return e[1]
    if tag == "int":
        return str(e[1])
    if tag == "bool":
        return "true" if e[1] else "false"
    if tag == "lam":
        return f"(fun {e[1]} -> {show(e[2])})"
    if tag == "app":
        return f"({show(e[1])} {show(e[2])})"
    if tag == "let":
        return f"(let {e[1]} = {show(e[2])} in {show(e[3])})"
    if tag == "if":
        return f"(if {show(e[1])} then {show(e[2])} else {show(e[3])})"
    if tag == "prim":
        return f"({show(e[2])} {e[1]} {show(e[3])})"
    if tag == "fix":
        return f"(fix {e[1]} {e[2]} -> {show(e[3])})"
    raise ValueError(f"not a term: {e!r}")


def type_vars(t):
    """The type variables of t, in order of first occurrence, left to right."""
    out = []

    def go(u):
        if u[0] == "tv":
            if u[1] not in out:
                out.append(u[1])
        elif u[0] == "fun":
            go(u[1])
            go(u[2])

    go(t)
    return out


def rename_type(t, mapping):
    if t[0] == "tv":
        return ("tv", mapping.get(t[1], t[1]))
    if t[0] == "fun":
        return ("fun", rename_type(t[1], mapping), rename_type(t[2], mapping))
    return t


def normalize_type(t):
    """Rename the type variables of t to 0, 1, 2, ... in order of first occurrence."""
    return rename_type(t, {v: i for i, v in enumerate(type_vars(t))})


def type_size(t):
    """The number of nodes of t as a tree."""
    if t[0] == "fun":
        return 1 + type_size(t[1]) + type_size(t[2])
    return 1


def show_type(t):
    """int, bool, a, b, ... with right-associative arrows."""
    if t[0] == "int":
        return "int"
    if t[0] == "bool":
        return "bool"
    if t[0] == "tv":
        n = t[1]
        return chr(ord("a") + n) if 0 <= n < 26 else f"t{n}"
    left = show_type(t[1])
    if t[1][0] == "fun":
        left = f"({left})"
    return f"{left} -> {show_type(t[2])}"
zero_cfa.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-cfa/. The authors are listed in prov/JG6AT6.jsonl.
"""0-CFA: the functions that each expression of a higher-order program may
evaluate to, with one abstract binding per variable.

label(term) numbers the nodes of a toylam term in preorder and links each
variable to its binder. A node is a tuple whose children are labels:

    ("var", x, b)        b is the binder (label, name), or None if x is free
    ("lam", x, body)     binds (label, x)
    ("fix", f, x, body)  binds (label, f) and (label, x)
    ("app", t1, t2)
    ("let", x, t1, t2)   binds (label, x)
    ("if", t1, t2, t3)   ("prim", op, t1, t2)   ("int", k)   ("bool", b)

zero_cfa(term) returns (nodes, C, R). C[l] is the set of labels of the lam
and fix nodes that node l may evaluate to, and R[b] the same for the binder
b. Only code that can run is analysed: the body of a function is visited
when some reachable call may call it. The solver is a worklist over the
sets C[l] and R[b] that sends only the new elements along each edge.
Cost: O(n^3) for a term of n nodes.
"""

from collections import deque


def label(term):
    nodes = []
    stack = [(term, {}, None, 0)]  # (term, scope, parent label, child slot)
    while stack:
        t, scope, parent, slot = stack.pop()
        here = len(nodes)
        tag = t[0]
        if tag == "var":
            nodes.append(("var", t[1], scope.get(t[1])))
        elif tag in ("int", "bool"):
            nodes.append(t)
        else:
            nodes.append(None)  # filled when the children have labels
        if parent is not None:
            node = list(nodes[parent])
            node[slot] = here
            nodes[parent] = tuple(node)
        if tag == "lam":
            nodes[here] = ("lam", t[1], None)
            stack.append((t[2], {**scope, t[1]: (here, t[1])}, here, 2))
        elif tag == "fix":
            nodes[here] = ("fix", t[1], t[2], None)
            inner = {**scope, t[1]: (here, t[1]), t[2]: (here, t[2])}
            stack.append((t[3], inner, here, 3))
        elif tag == "app":
            nodes[here] = ("app", None, None)
            stack.append((t[2], scope, here, 2))
            stack.append((t[1], scope, here, 1))
        elif tag == "let":
            nodes[here] = ("let", t[1], None, None)
            stack.append((t[3], {**scope, t[1]: (here, t[1])}, here, 3))
            stack.append((t[2], scope, here, 2))
        elif tag == "if":
            nodes[here] = ("if", None, None, None)
            for slot2 in (3, 2, 1):
                stack.append((t[slot2], scope, here, slot2))
        elif tag == "prim":
            nodes[here] = ("prim", t[1], None, None)
            stack.append((t[3], scope, here, 3))
            stack.append((t[2], scope, here, 2))
    return nodes


def param(node, lab):
    """The binder of the parameter and the body label of a lam or fix node."""
    if node[0] == "lam":
        return (lab, node[1]), node[2]
    return (lab, node[2]), node[3]


def zero_cfa(term):
    nodes = label(term)  # @line L1
    val, delta, succ = {}, {}, {}  # @line L2
    watch = {}  # ("C", t1) -> the applications whose operator is t1
    reached = set()
    work = deque()

    def propagate(n, d):
        d = d - val.setdefault(n, set())  # @line L20
        if d:
            val[n] |= d  # @line L21
            if n not in delta:  # n is in the worklist exactly when it has a delta
                delta[n] = set()
                work.append(n)
            delta[n] |= d

    def add_edge(a, b):
        if b not in succ.setdefault(a, set()):  # @line L19
            succ[a].add(b)
            propagate(b, val.get(a, set()))

    def call(t, lam):
        node = nodes[lam]
        if node[0] == "fix":
            propagate(("R", (lam, node[1])), {lam})  # @line L15
        binder, body = param(node, lam)
        add_edge(("C", nodes[t][2]), ("R", binder))  # @line L16
        add_edge(("C", body), ("C", t))  # @line L17
        reach(body)  # @line L18

    def reach(root):
        todo = [root]
        while todo:
            t = todo.pop()
            if t in reached:  # @line L9
                continue
            reached.add(t)
            node = nodes[t]
            tag = node[0]
            if tag in ("lam", "fix"):
                propagate(("C", t), {t})  # @line L10
            elif tag == "var":
                if node[2] is not None:
                    add_edge(("R", node[2]), ("C", t))  # @line L11
            elif tag == "let":
                add_edge(("C", node[2]), ("R", (t, node[1])))  # @line L12
                add_edge(("C", node[3]), ("C", t))
                todo += [node[2], node[3]]
            elif tag == "if":
                add_edge(("C", node[2]), ("C", t))  # @line L13
                add_edge(("C", node[3]), ("C", t))
                todo += [node[1], node[2], node[3]]
            elif tag == "prim":
                todo += [node[2], node[3]]
            elif tag == "app":
                op = ("C", node[1])
                watch.setdefault(op, []).append(t)  # @line L14
                for lam in list(val.get(op, ())):
                    call(t, lam)
                todo += [node[1], node[2]]

    reach(0)  # @line L3
    while work:  # @line L4
        n = work.popleft()
        d = delta.pop(n)  # @line L5
        for t in list(watch.get(n, ())):
            for lam in d:
                call(t, lam)  # @line L6
        for m in list(succ.get(n, ())):
            propagate(m, d)  # @line L7
    cache = {lab: val.get(("C", lab), set()) for lab in range(len(nodes))}
    env = {key[1]: s for key, s in val.items() if key[0] == "R" and s}
    return nodes, cache, env  # @line L8


def call_graph(nodes, cache):
    """The pairs (application label, function label) of the result."""
    return {(t, lam) for t, node in enumerate(nodes) if node[0] == "app" for lam in cache[node[1]]}
test_zero_cfa.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-cfa/. The authors are listed in prov/JG6AT6.jsonl.

import random

import toylam
from zero_cfa import call_graph, label, param, zero_cfa


class Halt(Exception):
    pass


def run(nodes, fuel=4000, max_depth=150):
    """An environment-based call-by-value interpreter over the labelled
    nodes. It records every value that a node produces and every binding.
    Returns (outcome, seen, binds, calls), where outcome is ("value", v),
    ("stuck",) or ("fuel",)."""
    seen, binds, calls = [], [], []
    budget = [fuel]

    def ev(t, env, depth):
        budget[0] -= 1
        if budget[0] < 0 or depth > max_depth:
            raise Halt("fuel")
        node = nodes[t]
        tag = node[0]
        if tag == "var":
            if node[1] not in env:
                raise Halt("stuck")
            v = env[node[1]]
        elif tag in ("int", "bool"):
            v = node
        elif tag in ("lam", "fix"):
            v = ("clo", t, env)
        elif tag == "app":
            f = ev(node[1], env, depth + 1)
            a = ev(node[2], env, depth + 1)
            if f[0] != "clo":
                raise Halt("stuck")
            lam = f[1]
            calls.append((t, lam))
            binder, body = param(nodes[lam], lam)
            inner = dict(f[2])
            if nodes[lam][0] == "fix":
                inner[nodes[lam][1]] = f
                binds.append(((lam, nodes[lam][1]), f))
            inner[binder[1]] = a
            binds.append((binder, a))
            v = ev(body, inner, depth + 1)
        elif tag == "let":
            a = ev(node[2], env, depth + 1)
            binds.append(((t, node[1]), a))
            v = ev(node[3], {**env, node[1]: a}, depth + 1)
        elif tag == "if":
            c = ev(node[1], env, depth + 1)
            if c[0] != "bool":
                raise Halt("stuck")
            v = ev(node[2] if c[1] else node[3], env, depth + 1)
        else:
            a = ev(node[2], env, depth + 1)
            b = ev(node[3], env, depth + 1)
            if a[0] != "int" or b[0] != "int":
                raise Halt("stuck")
            v = toylam._prim(node[1], a[1], b[1])
        seen.append((t, v))
        return v

    try:
        outcome = ("value", ev(0, {}, 0))
    except Halt as h:
        outcome = (str(h),)
    return outcome, seen, binds, calls


def plain_cfa(nodes):
    """The 0-CFA rules applied to every reached node, round after round."""
    C = {t: set() for t in range(len(nodes))}
    R = {}
    reached = {0}
    changed = True

    def put(s, items):
        if not items <= s:
            s |= items
            return True
        return False

    while changed:
        changed = False
        for t in sorted(reached):
            node = nodes[t]
            tag = node[0]
            kids = []
            if tag in ("lam", "fix"):
                changed |= put(C[t], {t})
            elif tag == "var" and node[2] is not None:
                changed |= put(C[t], R.setdefault(node[2], set()))
            elif tag == "let":
                changed |= put(R.setdefault((t, node[1]), set()), C[node[2]])
                changed |= put(C[t], C[node[3]])
                kids = [node[2], node[3]]
            elif tag == "if":
                changed |= put(C[t], C[node[2]] | C[node[3]])
                kids = [node[1], node[2], node[3]]
            elif tag == "prim":
                kids = [node[2], node[3]]
            elif tag == "app":
                kids = [node[1], node[2]]
                for lam in list(C[node[1]]):
                    binder, body = param(nodes[lam], lam)
                    if nodes[lam][0] == "fix":
                        changed |= put(R.setdefault((lam, nodes[lam][1]), set()), {lam})
                    changed |= put(R.setdefault(binder, set()), C[node[2]])
                    changed |= put(C[t], C[body])
                    kids.append(body)
            for k in kids:
                if k not in reached:
                    reached.add(k)
                    changed = True
    return C, {b: s for b, s in R.items() if s}


def same_outcome(mine, theirs, nodes):
    if mine[0] == "fuel" or theirs[0] == "fuel":
        return True
    if mine[0] != theirs[0]:
        return False
    if mine[0] == "stuck":
        return True
    v, w = mine[1], theirs[1]
    if v[0] == "clo":
        return nodes[v[1]][0] == w[0]
    return v == w


def find(nodes, tag, name):
    return next(t for t, n in enumerate(nodes) if n[0] == tag and n[1] == name)


ID_EXAMPLE = (
    "let", "id", ("lam", "x", ("var", "x")),
    ("let", "a", ("app", ("var", "id"), ("lam", "y", ("prim", "+", ("var", "y"), ("int", 1)))),
     ("let", "b", ("app", ("var", "id"), ("lam", "z", ("prim", "*", ("var", "z"), ("int", 2)))),
      ("app", ("var", "a"), ("int", 3)))),
)


def test_page_example_merges_the_two_calls_of_id():
    nodes, C, R = zero_cfa(ID_EXAMPLE)
    lx, ly, lz = find(nodes, "lam", "x"), find(nodes, "lam", "y"), find(nodes, "lam", "z")
    assert R[(lx, "x")] == {ly, lz}
    assert R[(find(nodes, "let", "a"), "a")] == {ly, lz}
    last = max(t for t, n in enumerate(nodes) if n[0] == "app")
    assert {lam for t, lam in call_graph(nodes, C) if t == last} == {ly, lz}
    assert toylam.evaluate(ID_EXAMPLE) == ("value", ("int", 4))


def test_body_of_an_uncalled_function_is_not_analysed():
    term = ("lam", "x", ("app", ("lam", "y", ("var", "y")), ("lam", "z", ("var", "z"))))
    nodes, C, R = zero_cfa(term)
    assert call_graph(nodes, C) == set()
    assert C[0] == {0}
    assert R == {}


def test_recursive_function():
    body = ("if", ("prim", "<", ("var", "x"), ("int", 1)), ("int", 0),
            ("app", ("var", "f"), ("prim", "-", ("var", "x"), ("int", 1))))
    term = ("app", ("fix", "f", "x", body), ("int", 3))
    nodes, C, R = zero_cfa(term)
    fix = find(nodes, "fix", "f")
    apps = [t for t, n in enumerate(nodes) if n[0] == "app"]
    assert len(apps) == 2 and apps[0] == 0
    assert call_graph(nodes, C) == {(0, fix), (apps[1], fix)}
    assert R[(fix, "f")] == {fix}


def test_labels_are_preorder():
    nodes = label(ID_EXAMPLE)
    assert nodes[0][0] == "let" and nodes[1] == ("lam", "x", 2) and nodes[2] == ("var", "x", (1, "x"))


def terms(seed, count, depth=6):
    rng = random.Random(seed)
    for _ in range(count):
        yield toylam.random_term(rng, rng.randint(1, depth))


def test_same_as_plain_iteration():
    for term in terms(1991, 500):
        nodes, C, R = zero_cfa(term)
        C2, R2 = plain_cfa(nodes)
        assert C == C2, toylam.show(term)
        assert R == R2, toylam.show(term)


def test_sound_against_concrete_runs():
    runs = 0
    for term in terms(1988, 2000, depth=7):
        nodes, C, R = zero_cfa(term)
        graph = call_graph(nodes, C)
        outcome, seen, binds, calls = run(nodes)
        runs += len(calls) > 0
        for t, v in seen:
            if v[0] == "clo":
                assert v[1] in C[t], toylam.show(term)
        for b, v in binds:
            if v[0] == "clo":
                assert v[1] in R.get(b, ()), toylam.show(term)
        assert set(calls) <= graph
    assert runs > 100


def test_interpreter_agrees_with_toylam():
    for term in terms(7, 500, depth=7):
        nodes = label(term)
        mine = run(nodes)[0]
        assert same_outcome(mine, toylam.evaluate(term, 4000), nodes), toylam.show(term)

History

Jones (1981) gave an early flow analysis for lambda expressions. Shivers named control flow analysis in 1988 and defined 0-CFA and 1-CFA for Scheme by abstract interpretation of a continuation-passing semantics, in a PLDI paper and in his 1991 thesis. Palsberg (1995) wrote 0-CFA as a system of set constraints and showed that it agrees with the abstract interpretation form. Heintze and McAllester (1997) explained why it has resisted sub-cubic algorithms, and Van Horn and Mairson (2008) proved it complete for PTIME.

References

  1. Olin Shivers, Control flow analysis in Scheme, Proceedings of PLDI '88, 164 to 174, 1988, the first statement of control flow analysis for higher-order programs
  2. Olin Shivers, Control-flow analysis of higher-order languages, PhD thesis, Carnegie Mellon University, CMU-CS-91-145, 1991, the definition of 0-CFA and 1-CFA by abstract interpretation of a CPS semantics
  3. Jens Palsberg, Closure analysis in constraint form, ACM Transactions on Programming Languages and Systems 17(1), 47 to 62, 1995, the constraint form of 0-CFA and its equivalence with the abstract interpretation form
  4. Nevin Heintze and David McAllester, On the cubic bottleneck in subtyping and flow analysis, Proceedings of LICS 1997, 342 to 351, the reduction from 2NPDA recognition to flow analysis, which explains why no sub-cubic algorithm is known
  5. David Van Horn and Harry G. Mairson, Flow analysis, linearity, and PTIME, Static Analysis Symposium 2008, LNCS 5079, 255 to 269, the proof that 0-CFA is complete for PTIME

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/JG6AT6/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example