Algorithmadvanced
k-CFA
Also called Shivers k-CFA, k-limited control flow analysis.
Control flow analysis of higher-order programs that keeps a separate binding of each variable for each string of the last k call sites.
- Solves
- Call graph construction
- Time
- 2^O((k+1) n log n) worst
- Space
- 2^O((k+1) n log n) extra
- Where
- k = the length of the call strings; n = the number of nodes of the program
- Model
- Word RAM
- Properties
- context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Olin Shivers, 1991
k-CFA is a family of control flow analyses for higher-order programs, one for each . Like 0-CFA, it finds the functions that each expression may evaluate to, which gives a call graph. Unlike 0-CFA, it binds each variable separately for each contour, the string of the last call sites that led to the binding. A closure records the contour of each of its free variables. For there is one contour, and k-CFA is 0-CFA. For the answers are more precise, but the number of abstract closures can be exponential, and deciding k-CFA is EXPTIME-complete (the k-CFA theorem).
In plain words
0-CFA gives each variable one bag of functions for the whole program. If a helper such as id is called in two places, both arguments land in the same bag, and both callers get both back. k-CFA gives each variable one bag per context. The context of a binding is the list of the last k call sites on the way to it. With k = 1, the call id f at one place and id g at another use different bags, so each caller only gets its own function back. A function value also remembers the context of each variable it uses. More contexts mean more precise answers, but the number of these remembered contexts can explode.
The problem
The input is a closed term of the toy language of the 0-CFA page and a number . A contour is a sequence of at most application labels. A call at application in contour runs the body in the contour , the last elements of followed by . A let binds in the current contour. An abstract environment maps the free variables of a node to contours, and an abstract closure is a pair .
The output is the least analysis where is a set of tasks (the ways node may be evaluated), is a set of abstract closures for each node and contour, and is one for each binder and contour, closed under the rules of lines L6 to L15. The call graph forgets the contours: is an edge when some closure of is in for the operator of .
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | tasks, and maps from (node, contour) and (binder, contour) to sets of abstract closures |
| order | inclusion in all parts (bottom is precise) |
| join | union in all parts |
| bottom and top | everything empty, and every task with every set full |
| boundary value | the task of the root, with the empty environment and the empty contour |
| initial value | the root task only |
| transfer | the rules below; monotone, and not distributive, since a call needs both a closure and its task |
The algorithm
K-CFA(e, k)- 1
label e; T <- {(root, {}, ())} - 2
repeat - 3
for each task (t, ce, d) in T do RULE(t, ce, d) - 4
until the last pass added no task and no set element - 5
return C and R RULE(t, ce, d)- 6
if t is a variable x with binder b then add R[(b, ce(x))] to C[(t, d)] - 7
if t is a function then add the closure (t, ce) to C[(t, d)] - 8
if t is let x = t1 in t2 then TASK(t1, ce, d); add C[(t1, d)] to R[(x, d)]; TASK(t2, ce[x -> d], d); add C[(t2, d)] to C[(t, d)] - 9
if t is if or an operator then TASK each subterm with (ce, d); for if, add C[(t2, d)] and C[(t3, d)] to C[(t, d)] - 10
if t is t1 t2 then TASK(t1, ce, d); TASK(t2, ce, d) - 11
for each closure (λ, ce') in C[(t1, d)] do - 12
d' <- the last k labels of d followed by t - 13
add C[(t2, d)] to R[(param(λ), d')]; for fix f x -> body, add (λ, ce') to R[(f, d')] - 14
TASK(body(λ), ce' with the parameters mapped to d', d') - 15
add C[(body(λ), d')] to C[(t, d)] TASK(t, ce, d)- 16
add (t, ce restricted to the free variables of t, d) to T
A task is one way that a node may be evaluated: with which contours for its free variables and in which current contour. Line L16 restricts the environment to the free variables, so two tasks that differ only in variables the node does not use are one task. Line L6 looks up the contour of in the environment, not the current contour, because may have been bound by an outer function in an older call. The loop of lines L2 to L4 applies every rule again until nothing changes. A worklist with dependencies, as on the 0-CFA page, gives the same result faster.
Example
The program of the 0-CFA page:
let id = fun x -> x in
let a = id (fun y -> y + 1) in // call site s1
let b = id (fun z -> z * 2) in // call site s2
a 3 // call site s3
With , the two calls of id run its body in different contours.
| fact | 1-CFA | 0-CFA |
|---|---|---|
| in contour : ; in contour : | ||
body x of id |
in : ; in : | |
| targets of s3 |
1-CFA finds exactly the calls of the run. Now wrap id in another function:
let id = fun x -> x in
let g = fun w -> id w in // call site s0 inside g
let a = g (fun y -> y + 1) in // s1
let b = g (fun z -> z * 2) in // s2
a 3
With , is split by and , but both calls of id happen at , so has the single contour and gets both functions back. a 3 again has two targets. With , the contours of are and , and the spurious target goes away. Every extra layer of wrappers needs one more unit of .
Correctness
Least solution. Every task and every element that a pass adds is the conclusion of one of the rules, applied to facts that are already forced. So by induction the result is inside every closed analysis. The loop stops only after a pass in which every rule held, so the result is closed. Termination holds because there are finitely many contours, abstract closures and tasks.
Soundness. Instrument the run with contours: a call at in contour runs the body in , and each binding stores the contour in which it was made. The abstraction of a closure keeps its function and the contours of its free variables. By induction on the evaluation, if node is evaluated in contour with environment , then its task is in , and the abstraction of its value is in . The step for a call uses that the concrete and the abstract contour of the callee are both . So every call of the run is in the call graph. The full proofs are in the proof file.
Proof: The round-robin k-CFA stops with the least closed analysis, which is sound for call-by-value runs with contoursfull
Setting. The program is a closed term of the toy language of the 0-CFA page, with labels, binders, functions , and as there, and the free names of node . Fix . A contour is a sequence of at most application labels. For a contour and an application , is the last elements of followed by (the empty sequence when ). An abstract environment maps names to contours, and is its restriction to . An abstract closure is a pair with defined exactly on .
An analysis is a triple : a set of tasks with defined on , a set of abstract closures for each label and contour, and a set for each binder and contour. It is closed if is in and every task satisfies the rule of lines L6 to L15:
- a variable with binder : ;
- a function: ;
let x = t1 in t2: , , and ;ifand operators: each direct subterm has , and forif t1 then t2 else t3, ;t1 t2: , and for every , with and equal to with the parameters of mapped to : ; if isfix f x -> e, ; ; and .
Each rule keeps holding when the sets on its right side grow, so the intersection of closed analyses is closed and a least closed analysis exists.
Lemma 1 (finiteness). There are finitely many tasks, keys and abstract closures. With nodes, the number of contours is , the number of abstract closures is at most , and the number of tasks is at most .
Proof. A contour is a sequence of at most labels. An abstract closure is a function label and a map from at most names to contours. A task is a label, a map from at most names to contours and a contour.
Lemma 2 (termination). The loop of lines L2 to L4 stops.
Proof. Every pass that does not stop the loop adds a task or an element to some set. Sets and tasks never shrink, and by Lemma 1 they live in finite sets. So the number of passes is at most the number of possible tasks plus the number of possible pairs of a key and a closure, plus one.
Lemma 3 (every fact is forced). Let be any closed analysis. At all times , and .
Proof. By induction over the steps. Line L1 adds the root task, which is in . Every other addition is made by the rule of a task , and it is the conclusion of rule 1 to 5 for this task, with premises (the sets read and the closures picked in line L11) inside and by induction. Since is closed, the same conclusion holds there.
Theorem 1 (least closed analysis). The algorithm stops and returns the least closed analysis.
Proof. It stops by Lemma 2. In the last pass, the rule of every task ran and changed nothing, so every task satisfies its rule with the final sets, and the result is closed. By Lemma 3 it is inside every closed analysis.
The semantics with contours. A value is a constant or a closure , where an environment maps each name to a pair of a contour and a value. Evaluation is call-by-value with a current contour . A let binds to and stays in . A call at application of a closure binds the parameters of to , with the argument and, for a fix, the closure itself, and runs the body in the contour . The contours do not change the values: dropping them gives the plain environment semantics. The abstraction of an environment is $|\rho|(x) = $ the contour of , and of a closure is .
An environment is good if, for each name in it, with binder at the place where is used and , either is a constant or with and good.
Lemma 4 (the evaluation invariant). Let be closed. If , is good, and , then is a constant or with a good environment. Every evaluation inside the derivation, , has its task in and good; every binding of a closure to a binder in contour has ; and every call at of a closure of has among the functions of for the contour of the call.
Proof. By induction on the height of the derivation. A variable with binder and : , and by rule 1. A function gives , whose abstraction is , in by rule 2. A let: rule 3 gives the task of with , so by induction is in . The new environment binds to , so it is good, its abstraction is , and rule 3 gives the task of . By induction the value is in . if and operators are the same with rule 4. An application t1 t2: rule 5 gives the tasks of and , so by induction gives with , which is the call fact, and the argument is a constant or in . Let , the same in both semantics. By rule 5, , and for a fix, . So the environment of the body is good, its abstraction is with the parameters mapped to , and rule 5 gives the task of the body. By induction its value is in . The facts about inner evaluations come from the induction hypothesis on each premise.
Theorem 2 (soundness). Let be the result. In every run of the closed program, finished or not, every evaluation of a node in contour to a closure has , every binding of a closure to binder in contour has , and every call at application runs a function that appears in . Dropping the contours, the result contains the 0-CFA facts of the run.
Proof. The root task is in with the empty environment, which is good. Every finished evaluation of the run is a sub-derivation of the run from the root, so Lemma 4 applies to it. A call is made only after its operator and argument have finished.
Theorem 3 (cost). The algorithm runs in time polynomial in , , and the number of tasks, so in time for fixed , and in time polynomial in for .
Proof. By Lemma 2 there are at most (number of tasks) passes, since there are at most cache keys and binder keys. Each pass runs the rule of every task once. A rule makes unions per closure of the operator, and each union of sets of at most elements costs with hashing. With , and the number of tasks are at most for fixed , so the number of passes and the cost of a pass are both , and so is their product. For there is one contour, every abstract environment maps all names to the empty contour, so , there are at most tasks, and the time is polynomial. The exponential bound cannot be improved to a polynomial, since P is not EXPTIME by the time hierarchy theorem and Van Horn and Mairson prove that deciding a k-CFA fact is EXPTIME-complete for every (see the theorem page).
Complexity
Proved. With nodes there are at most contours. An abstract closure maps up to free variables to contours, so there are at most of them, and as many tasks times . Each pass of the loop adds at least one fact, and each pass costs a polynomial in these numbers. So the time is , which is for fixed . For every closure has the one empty contour, and the time is polynomial.
Stated in the literature. Van Horn and Mairson (2008) prove that deciding whether a closure flows to an expression under k-CFA is EXPTIME-complete for every . Since P is not EXPTIME, by the time hierarchy theorem, no polynomial algorithm exists. Might, Smaragdakis and Van Horn (2010) show that the same idea is polynomial for object-oriented programs, where a closure (an object) copies its free values into fields instead of capturing an environment, and they define m-CFA, a polynomial analysis for functional programs with flat environments.
Measured, not proved. On 400 random closed terms (seed 1991), gives exactly the result of a plain 0-CFA. On 300 random terms (seed 2007), forgetting the contours, 2-CFA is inside 1-CFA and 1-CFA is inside 0-CFA. On 1500 random terms (seed 1988), every closure, binding and call of a concrete run with contours is in the result for and .
Properties
- Polyvariant. One variable has many abstract bindings, one per contour.
- The environment problem. A closure keeps one contour per free variable, and these can differ. This is the source of the exponential number of abstract closures, and of the EXPTIME hardness.
- Not distributive. A call rule fires only for closures that reach the operator in the same contour.
- More precise as grows, in practice. In the tests, larger never gave a larger projected result. With the "last " truncation, the contours of map onto those of by dropping the oldest site, which is why this holds.
- Call strings are functional k-CFA only here. In a first-order or object-oriented setting, a call-string analysis of length has no environment problem and is polynomial. Calling that "k-CFA" hides the difference.
Variants and improvements
- Uniform k-CFA. Nielson, Nielson and Hankin index both the cache and the environment by the same contour of the current call. It is the form used on this page.
- m-CFA. Might, Smaragdakis and Van Horn keep only the top stack frames and use flat environments, where all free variables of a closure share one contour. It is polynomial for fixed .
- Object sensitivity. In object-oriented analysis, contexts made of receiver allocation sites often work better than call sites (object sensitivity).
- Pushdown analyses. CFA2 and related analyses match calls with returns, like a pushdown system, so a return never goes to the wrong caller, even with .
- Abstract machines. Van Horn and Might derive k-CFA by bounding the store of an abstract machine, which gives the same analysis for richer languages.
When to use it
Use 1-CFA, or 2-CFA at most, when 0-CFA mixes the uses of small higher-order helpers and the extra precision pays off, for example to inline or specialize closures in a compiler for a functional language. Large rarely pays. For big programs, prefer a polynomial analysis: m-CFA, a pushdown analysis, or, in object-oriented code, call-site or object-sensitive points-to analysis, which are polynomial for fixed .
Pitfalls
- Looking up a variable in the current contour. A version of line L6 that reads instead of is unsound. In
let f = fun x -> fun y -> x in (f 1) 2, the inner body runs in the contour of the call(f 1) 2, but was bound in the contour off 1. Line L6 must use the contour that the closure environment records. - Dropping the environment of closures. If line L7 stores only the function , line L14 has no contours for the free variables of the body. Keep the restricted environment in the closure.
- Keeping the first call sites. A version of line L12 that keeps the oldest labels makes all deep calls share one contour. Line L12 must keep the most recent labels.
- Expecting polynomial time for fixed . For the problem is EXPTIME-complete, and real programs can show the blow-up. Bound the time, or use m-CFA.
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
# Part of https://algorithm.tamnd.com/k-cfa/. The authors are listed in prov/WSCAQ1.jsonl.
"""k-CFA: control flow analysis of a higher-order program with the last k
call sites as the context of each binding.
label(term) numbers the nodes of a toylam term in preorder, as on the 0-CFA
page, and links each variable to its binder (label, name).
k_cfa(term, k) returns (nodes, C, R). A contour is a tuple of at most k
application labels, the most recent last. An abstract closure is (lam, ce)
where ce is a sorted tuple of (name, contour) pairs for the free variables of
the function lam. C[(t, d)] is the set of closures that node t may evaluate
to in contour d, and R[(b, d)] the set of closures bound to binder b in
contour d. The solver keeps a set of tasks (t, ce, d), one for each way in
which node t may be evaluated, and applies the rule of every task, round
after round, until nothing changes. The number of contours is at most n^k,
and the number of closures can be exponential in n, so k >= 1 is exponential
in the worst case.
"""
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)
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 free_names(nodes):
"""The free variable names of each node. Children have larger labels."""
fv = [frozenset()] * len(nodes)
for t in range(len(nodes) - 1, -1, -1):
node = nodes[t]
tag = node[0]
if tag == "var":
fv[t] = frozenset([node[1]])
elif tag == "lam":
fv[t] = fv[node[2]] - {node[1]}
elif tag == "fix":
fv[t] = fv[node[3]] - {node[1], node[2]}
elif tag == "let":
fv[t] = fv[node[2]] | (fv[node[3]] - {node[1]})
elif tag == "app":
fv[t] = fv[node[1]] | fv[node[2]]
elif tag == "if":
fv[t] = fv[node[1]] | fv[node[2]] | fv[node[3]]
elif tag == "prim":
fv[t] = fv[node[2]] | fv[node[3]]
return fv
def k_cfa(term, k):
nodes = label(term)
fv = free_names(nodes)
C, R = {}, {}
tasks = {} # an ordered set of (t, ce, d)
changed = [False]
def task(t, ce, d):
key = (t, tuple(sorted((x, c) for x, c in ce.items() if x in fv[t])), d) # @line L16
if key not in tasks:
tasks[key] = None
changed[0] = True
def add(table, key, items):
s = table.setdefault(key, set())
if not items <= s:
s |= items
changed[0] = True
def rule(t, ce, d):
node = nodes[t]
tag = node[0]
if tag == "var":
if node[2] is not None:
add(C, (t, d), R.get((node[2], ce[node[1]]), set())) # @line L6
elif tag in ("lam", "fix"):
add(C, (t, d), {(t, tuple(sorted(ce.items())))}) # @line L7
elif tag == "let":
t1, t2 = node[2], node[3]
task(t1, ce, d) # @line L8
add(R, ((t, node[1]), d), C.get((t1, d), set()))
task(t2, {**ce, node[1]: d}, d)
add(C, (t, d), C.get((t2, d), set()))
elif tag in ("if", "prim"):
kids = node[1:] if tag == "if" else node[2:]
for u in kids:
task(u, ce, d) # @line L9
if tag == "if":
add(C, (t, d), C.get((node[2], d), set()) | C.get((node[3], d), set()))
elif tag == "app":
t1, t2 = node[1], node[2]
task(t1, ce, d) # @line L10
task(t2, ce, d)
for lam, ce2 in list(C.get((t1, d), ())): # @line L11
d2 = (d + (t,))[-k:] if k > 0 else () # @line L12
fun = nodes[lam]
inner = dict(ce2)
if fun[0] == "lam":
x, body = fun[1], fun[2]
else:
x, body = fun[2], fun[3]
add(R, ((lam, fun[1]), d2), {(lam, ce2)}) # @line L13
inner[fun[1]] = d2
add(R, ((lam, x), d2), C.get((t2, d), set()))
inner[x] = d2
task(body, inner, d2) # @line L14
add(C, (t, d), C.get((body, d2), set())) # @line L15
task(0, {}, ()) # @line L1
while changed[0]: # @line L2 @line L4
changed[0] = False
for t, ce, d in list(tasks): # @line L3
rule(t, dict(ce), d)
return nodes, C, R # @line L5
def project(table):
"""Forget the contours and environments: a dict from each label or binder
to the set of function labels."""
out = {}
for (key, _), closures in table.items():
if closures:
out.setdefault(key, set()).update(lam for lam, _ in closures)
return out
def call_graph(nodes, C):
"""The pairs (application label, function label) of the result."""
flat = project(C)
return {(t, lam) for t, node in enumerate(nodes) if node[0] == "app" for lam in flat.get(node[1], ())}
toylam.py 285 lines
# 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])}"
test_k_cfa.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-cfa/. The authors are listed in prov/WSCAQ1.jsonl.
import random
import toylam
from k_cfa import call_graph, free_names, k_cfa, label, project
class Halt(Exception):
pass
def run(nodes, k, fuel=3000, max_depth=150):
"""An environment-based call-by-value interpreter that keeps, for each
binding, the contour in which it was made: the last k call sites. Records
every closure that a node produces in a contour, every binding and every
call, with the closures cut down to (function, contours of its free
variables)."""
fv = free_names(nodes)
seen, binds, calls = [], [], []
budget = [fuel]
def abstract(v):
lam, env = v[1], v[2]
return (lam, tuple(sorted((x, env[x][0]) for x in fv[lam])))
def ev(t, env, d, 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]][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, d, depth + 1)
a = ev(node[2], env, d, depth + 1)
if f[0] != "clo":
raise Halt("stuck")
lam = f[1]
fun = nodes[lam]
d2 = (d + (t,))[-k:] if k > 0 else ()
calls.append((t, lam))
inner = dict(f[2])
if fun[0] == "fix":
inner[fun[1]] = (d2, f)
binds.append((((lam, fun[1]), d2), f))
x, body = fun[2], fun[3]
else:
x, body = fun[1], fun[2]
inner[x] = (d2, a)
binds.append((((lam, x), d2), a))
v = ev(body, inner, d2, depth + 1)
elif tag == "let":
a = ev(node[2], env, d, depth + 1)
binds.append((((t, node[1]), d), a))
v = ev(node[3], {**env, node[1]: (d, a)}, d, depth + 1)
elif tag == "if":
c = ev(node[1], env, d, depth + 1)
if c[0] != "bool":
raise Halt("stuck")
v = ev(node[2] if c[1] else node[3], env, d, depth + 1)
else:
a = ev(node[2], env, d, depth + 1)
b = ev(node[3], env, d, 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, d), v))
return v
try:
ev(0, {}, (), 0)
except Halt:
pass
seen = [(key, abstract(v)) for key, v in seen if v[0] == "clo"]
binds = [(key, abstract(v)) for key, v in binds if v[0] == "clo"]
return seen, binds, calls
def plain_zero_cfa(nodes):
"""The 0-CFA rules of the 0-CFA page applied 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]]):
fun = nodes[lam]
if fun[0] == "fix":
changed |= put(R.setdefault((lam, fun[1]), set()), {lam})
binder, body = (lam, fun[2]), fun[3]
else:
binder, body = (lam, fun[1]), fun[2]
changed |= put(R.setdefault(binder, set()), C[node[2]])
changed |= put(C[t], C[body])
kids.append(body)
for u in kids:
if u not in reached:
reached.add(u)
changed = True
return {t: s for t, s in C.items() if s}, {b: s for b, s in R.items() if s}
def find(nodes, tag, name):
return next(t for t, n in enumerate(nodes) if n[0] == tag and n[1] == name)
def last_app(nodes):
return max(t for t, n in enumerate(nodes) if n[0] == "app")
def fun(x, body):
return ("lam", x, body)
ID_EXAMPLE = (
"let", "id", fun("x", ("var", "x")),
("let", "a", ("app", ("var", "id"), fun("y", ("prim", "+", ("var", "y"), ("int", 1)))),
("let", "b", ("app", ("var", "id"), fun("z", ("prim", "*", ("var", "z"), ("int", 2)))),
("app", ("var", "a"), ("int", 3)))),
)
WRAPPED = (
"let", "id", fun("x", ("var", "x")),
("let", "g", fun("w", ("app", ("var", "id"), ("var", "w"))),
("let", "a", ("app", ("var", "g"), fun("y", ("prim", "+", ("var", "y"), ("int", 1)))),
("let", "b", ("app", ("var", "g"), fun("z", ("prim", "*", ("var", "z"), ("int", 2)))),
("app", ("var", "a"), ("int", 3))))),
)
def targets_of_last_call(term, k):
nodes, C, R = k_cfa(term, k)
last = last_app(nodes)
return {lam for t, lam in call_graph(nodes, C) if t == last}, nodes
def test_page_example_one_cfa_splits_the_calls_of_id():
zero, nodes = targets_of_last_call(ID_EXAMPLE, 0)
one, _ = targets_of_last_call(ID_EXAMPLE, 1)
ly, lz = find(nodes, "lam", "y"), find(nodes, "lam", "z")
assert zero == {ly, lz}
assert one == {ly}
nodes, C, R = k_cfa(ID_EXAMPLE, 1)
lx = find(nodes, "lam", "x")
assert {d for (b, d) in R if b == (lx, "x")} == {(t,) for t, n in enumerate(nodes) if n[0] == "app"} - {(last_app(nodes),)}
def test_a_wrapper_needs_two_call_sites():
one, nodes = targets_of_last_call(WRAPPED, 1)
two, _ = targets_of_last_call(WRAPPED, 2)
ly, lz = find(nodes, "lam", "y"), find(nodes, "lam", "z")
assert one == {ly, lz}
assert two == {ly}
assert toylam.evaluate(WRAPPED) == ("value", ("int", 4))
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_zero_contours_is_zero_cfa():
for term in terms(1991, 400):
nodes, C, R = k_cfa(term, 0)
assert (project(C), project(R)) == plain_zero_cfa(nodes), toylam.show(term)
def test_more_contours_never_lose_precision():
for term in terms(2007, 300):
flat = [k_cfa(term, k) for k in (0, 1, 2)]
for small, big in ((1, 0), (2, 1)):
cs, cb = project(flat[small][1]), project(flat[big][1])
assert all(s <= cb.get(t, set()) for t, s in cs.items()), toylam.show(term)
rs, rb = project(flat[small][2]), project(flat[big][2])
assert all(s <= rb.get(b, set()) for b, s in rs.items()), toylam.show(term)
def test_sound_against_concrete_runs():
with_calls = 0
for term in terms(1988, 1500, depth=7):
nodes = label(term)
for k in (1, 2):
_, C, R = k_cfa(term, k)
seen, binds, calls = run(nodes, k)
with_calls += bool(calls)
for key, clo in seen:
assert clo in C.get(key, ()), toylam.show(term)
for key, clo in binds:
assert clo in R.get(key, ()), toylam.show(term)
assert set(calls) <= call_graph(nodes, C)
assert with_calls > 100
History
Shivers introduced control flow analysis for Scheme in 1988, with 0-CFA and 1-CFA, and defined the k-CFA hierarchy in his 1991 thesis by abstract interpretation of a continuation-passing semantics. Nielson, Nielson and Hankin (1999) gave a constraint-based uniform form in their textbook. For years it was believed that k-CFA was polynomial for fixed . Van Horn and Mairson (2008) proved that it is EXPTIME-complete for every , by encoding a Turing machine with exponential time in the closures of a program. Might, Smaragdakis and Van Horn (2010) explained why the same idea is polynomial for object-oriented programs and used it to define m-CFA.
References
- Olin Shivers, Control-flow analysis of higher-order languages, PhD thesis, Carnegie Mellon University, CMU-CS-91-145, 1991, the definition of the k-CFA hierarchy by abstract interpretation of a CPS semantics with contours of the last k call sites
- Olin Shivers, Control flow analysis in Scheme, Proceedings of PLDI '88, 164 to 174, 1988, the first control flow analyses, 0-CFA and 1-CFA, for Scheme
- David Van Horn and Harry G. Mairson, Deciding kCFA is complete for EXPTIME, Proceedings of ICFP 2008, 275 to 282, the EXPTIME-completeness of k-CFA for every k at least 1
- Matthew Might, Yannis Smaragdakis and David Van Horn, Resolving and exploiting the k-CFA paradox, Proceedings of PLDI 2010, 305 to 315, why k-CFA is polynomial for object-oriented programs, and m-CFA, a polynomial hierarchy for functional programs
- Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Principles of Program Analysis, Springer, 1999, chapter 3, constraint-based analysis, with the section on adding context information (uniform k-CFA)
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 WSCAQ1 Edit this page History Report an error Markdown