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.
- Solves
- Call graph construction
- Time
- O(n^3) worst
- Space
- O(n^2) extra
- Where
- n = the number of nodes of the program
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- 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 time. The answer is sound for every run, it is the base of closure optimizations, and it is the 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 , and each variable occurrence knows its binder . is the set of function nodes. The output is the least triple of a set of reachable labels, a cache for each label and an environment for each binder, such that for every :
- a function has ;
- a variable with binder has ;
let x = t1 in t2has and ;if t1 then t2 else t3has ;t1 t2has, for each : , , , and forfix f x -> ealso ;
and the root and the direct subterms of every reachable node other than a function are in . The call graph is the set of pairs with = t1 t2 in and .
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | triples 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 |
| boundary value | the root is reachable |
| initial value | everything empty |
| transfer | the inclusions above; monotone, and not distributive, since rule 5 needs both reachable and |
The algorithm
ZERO-CFA(e)- 1
label the nodes of e and link each variable to its binder - 2
for each set node n (C[t] for a label, R[b] for a binder): V[n] <- {}; D[n] <- {}; succ[n] <- {} - 3
W <- []; REACH(root) - 4
while W is not empty do - 5
take n from W; d <- D[n]; D[n] <- {} - 6
for each application t that watches n and each λ in d do CALL(t, λ) - 7
for each m in succ[n] do PROPAGATE(m, d) - 8
return the sets V REACH(t)- 9
if t is marked then return; mark t - 10
if t is a function then PROPAGATE(C[t], {t}); stop here, the body waits for a call - 11
if t is a variable with binder b then ADD-EDGE(R[b], C[t]) - 12
if t is let x = t1 in t2 then ADD-EDGE(C[t1], R[x]); ADD-EDGE(C[t2], C[t]) - 13
if t is if t1 then t2 else t3 then ADD-EDGE(C[t2], C[t]); ADD-EDGE(C[t3], C[t]) - 14
if t is t1 t2 then make t watch C[t1] and CALL(t, λ) for each λ in V[C[t1]] then REACH each direct subterm of tCALL(t, λ) -- t is t1 t2- 15
if λ is fix f x -> body then PROPAGATE(R[f], {λ}) - 16
ADD-EDGE(C[t2], R[param(λ)]) - 17
ADD-EDGE(C[body(λ)], C[t]) - 18
REACH(body(λ)) ADD-EDGE(a, b)- 19
if b is not in succ[a] then add b to succ[a]; PROPAGATE(b, V[a]) PROPAGATE(n, d)- 20
d <- d \ V[n]; if d is empty then return - 21
V[n] <- V[n] ∪ d; D[n] <- D[n] ∪ d; if n is not in W then add n to W
The sets form a graph with an edge for each inclusion . 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. holds the elements that 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 , and for the three functions.
| step | what the algorithm finds |
|---|---|
| 1 | REACH from the root: , and the edge to gives |
| 2 | the operator id of both calls gets ; each call runs CALL with |
| 3 | the first call: flows into ; the second call: flows into ; so |
| 4 | the body x of gets and sends it back to both calls; so |
| 5 | the call a 3 gets and in its operator, CALL reaches both bodies, and the integer 3 adds no function to or |
The call graph has 4 edges: both calls of id go to , and a 3 goes to and . The run only calls at a 3. The edge to is spurious, because both calls of id share the one set . 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 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 . Call an environment good if the closure of each variable has its function in 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 . At a call, the operator gives , rule 5 puts the argument into and makes the body reachable, so the body runs in a good environment and its result is in . 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 , 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 is the set of functions. For a function , is the binder of its argument and its body. An analysis is a triple : a set of labels, a set for each label and a set for each binder. It is closed if:
- the root is in ;
- for a function : ;
- for a variable with binder : ;
- for =
let x = t1 in t2in : , and ; - for =
if t1 then t2 else t3in : and ; - for =
t1 op t2in : ; - for =
t1 t2in : , and for every : , , , and if isfix f x -> e, then .
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 and , is the current set of node , is the part of that has not yet been sent along the edges of , and is in exactly when . is the set of labels marked by line L9.
Lemma 1 (the edge invariant). At each test of line L4: for every edge , ; and for every application that watches the node and every , has run.
Proof. Line L19 creates an edge and sends all of to at once. Line L14 makes watch and runs CALL for all of at once. After that, an element enters only in line L21, which puts it into too. It leaves only in line L5, and lines L6 and L7 then send it along every edge of and to every watcher of . Sets only grow, so an element once in stays there.
Lemma 2 (termination). The algorithm stops.
Proof. There are finitely many set nodes, and each is a subset of the finite set . Every pass of the loop of line L4 removes a node with . A node returns to only when line L21 adds a new element to . So the number of passes is at most the number of nodes plus , which is finite. Each REACH marks each label at most once (line L9), so each call of REACH stops.
Lemma 3 (the result is closed). When the algorithm stops, is closed.
Proof. At the end is empty, so every is empty, and Lemma 1 gives for every edge, and for every watcher of and every . Line L3 puts the root in . For each label that line L9 marks, the lines after it give the rule of : line L10 gives rule 2; line L11 gives the edge of rule 3; line L12 gives the two edges of rule 4; line L13 gives the edges of rule 5; and line L14 makes watch . 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 had , and lines L15 to L18 give exactly the four parts of the rule for .
Lemma 4 (every fact is forced). Let be any closed analysis. At all times, every label marked by line L9 is in , and .
Proof. By induction over the steps. Line L3 marks the root, which is in by rule 1. REACH marks the direct subterms of a marked let, if, op or application node, which are in by rules 4 to 7, and line L18 marks for an application and a , which is in by rule 7. Line L10 adds to for a marked function , which rule 2 allows. Every edge 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 in ; so sending along it keeps . Line L15 adds to , which rule 7 requires.
Theorem 1 (least closed analysis). The algorithm stops and returns the least closed analysis.
Proof. Lemma 2, Lemma 3 and Lemma 4.
The semantics. A value is a constant or a closure of a function and an environment. An environment maps names to values. The judgement is the usual call-by-value big-step evaluation. For an application, and , and then runs in extended with the argument, and for a fix also with bound to . 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 fits a set if is a constant, or with and good for . An environment is good for a node if each variable in scope at , with binder at , has fitting . Good for means good for itself.
Lemma 5 (the evaluation invariant). If , is good for , and , then fits . Moreover, every evaluation that the derivation contains has and good for . Every binding it makes, of to a binder , has fitting , and every call it makes, at an application to a function , has .
Proof. By induction on the height of the derivation. A constant fits any set. A variable with binder gives , which fits by rule 3. A function gives , with by rule 2, and is good for . For let x = t1 in t2, rule 4 puts and in . By induction the value of fits , so the extended environment is good for , whose value fits . 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 . By induction gives with and good for , which is the call fact. gives fitting , by rule 7. For a fix, fits , since by rule 7. So the environment of the body is good for , which is in by rule 7. By induction its value fits . The facts about the inner evaluations come from the induction hypothesis for each premise.
Theorem 2 (soundness). Let the root be closed, and let be the result. In every run of the program, finished or not, every evaluation of a node to a closure has , every binding of a closure to a binder has , and every call at an application to a function has .
Proof. The root is in , 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 and have finished, so it is covered too.
Theorem 3 (cost). For a term of nodes, the algorithm runs in time with hash sets, in expectation, or with bit vectors in the worst case.
Proof. There are at most cache nodes and at most binder nodes, and each set has at most elements. Lines L11 to L13 make edges. Lines L16 and L17 make two edges per pair of an application and a function, so edges in all. Each element enters each at most once, because line L20 removes the elements already in . So line L7 sends each element along each edge at most once, which costs . CALL runs for a pair at most twice: once in line L14 and once when is in the delta of the operator in line L6. That is calls. Each call does work besides line L19, which may send a whole set of elements, so the calls cost . REACH marks each label once and does work per label besides its edges and calls. The total is .
Complexity
Proved. There are set nodes and each set has at most functions. The edges are from the text and two per pair of an application and a function, so in all. Each element crosses each edge at most once, which costs . CALL runs at most twice per pair of an application and a function, and each run may send a set of size , which is again. So the time is and the space is 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
ifboth 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 call sites as a context for each binding (k-CFA). It is more precise and EXPTIME-complete for (the k-CFA theorem).
- Abstract values for constants. Track integers and booleans by sign or by constant to prune
ifbranches. 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)insidefix f x -> ...finds no function in , and the recursive edge is missing. Line L15 must put the fix itself into . - Sending only the new elements on a new edge. If line L19 sent only the current delta, the elements that received before the edge existed would never cross it. Line L19 must send all of .
- Calling 0-CFA context-sensitive. The name 0-CFA means zero call sites of context. Call strings of length 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JG6AT6 Edit this page History Report an error Markdown