Algorithmcore
Andersen's analysis
Also called inclusion-based points-to analysis, subset-based pointer analysis.
Flow-insensitive points-to analysis that turns each assignment into a subset constraint and solves the constraint graph in cubic time.
- Solves
- Points-to analysis
- Time
- O(n^3 + m) worst
- Space
- O(n^2 + m) extra
- Where
- m = the number of pointer statements; n = the number of variables (each variable is also a location)
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Lars Ole Andersen, 1994
Andersen's analysis solves the points-to analysis problem for a whole program, without regard to the order of its statements. Each pointer assignment becomes one subset constraint between points-to sets: after p = q, the set of p must contain the set of q. The analysis finds the least sets that meet all the constraints. It keeps a constraint graph with an edge for each subset constraint and moves new facts along the edges with a worklist. Loads and stores add new edges while it runs, because the target of *p is known only when the set of p is known. On variables it runs in time in the worst case, and much faster on real programs.
In plain words
Each pointer in a program holds the address of some memory cell. We want to know, for each pointer, all the cells it could ever hold, for any run of the program. Andersen's analysis reads each assignment as a rule. If one pointer is copied into another, then everything the first could hold, the second could hold too. Copies through a pointer give rules that depend on what that pointer holds, so new rules appear as the answer grows. The analysis draws an arrow from each source to each target and pushes facts along the arrows until nothing new arrives. The result is the smallest answer that obeys every rule. It never misses a cell that a real run can use. It can list a cell that no real run uses, because it ignores the order of the statements.
The problem
The input is a set of statements in the four basic forms over a set of variables, and the output is a points-to set for each variable. Every variable is also a memory location, so it can be a target. In the toy IR, p = alloc at site is treated as p = &h_k, with one location per site. Each statement gives one constraint:
| statement | constraint |
|---|---|
p = &a |
|
p = q |
|
p = *q |
for every |
*p = q |
for every |
The result is the least solution of these constraints, in the order of on each set, with union as the join. This is the order of abstract interpretation in the direction of Cousot: bottom is the most precise answer, where every set is empty, and larger answers are less precise. The least solution exists because the solutions are closed under intersection. The analysis in the terms of a data-flow framework:
| item | value |
|---|---|
| direction | none: the analysis is flow-insensitive and has one answer for the whole program |
| may or must | may |
| domain | maps from to subsets of |
| order | on each set (bottom is precise) |
| join | union on each set |
| bottom and top | all sets empty, and all sets equal to |
| boundary value | none, there is no entry or exit point |
| initial value | all sets empty |
| transfer | monotone, not distributive: the load and store rules combine two facts, and |
Flow-insensitive means that the order of the statements is ignored: the answer covers every run that executes the statements in any order, any number of times. It does not mean that control flow is ignored entirely. Every real path is one of those orders, so the answer is sound for the program, and statements that the program never reaches can still be dropped first. Two expressions *p and *q may alias if , which gives an alias analysis.
The algorithm
The constraint graph has a node for each variable and an edge for each known constraint . Copies give edges at the start. A load p = *q gives the edge for each that enters , and a store *q = r gives . Each node keeps , the part of its set that it has not yet sent on. This is difference propagation: each fact moves along each edge once.
ANDERSEN(S)- 1
for each variable v do pts[v] <- {}; succ[v] <- {}; delta[v] <- {} - 2
W <- an empty worklist - 3
for each p = &a in S do add a to pts[p] and to delta[p]; add p to W - 4
for each p = q in S do ADD-EDGE(q, p) - 5
while W is not empty do - 6
take n from W; d <- delta[n]; delta[n] <- {} - 7
for each a in d do - 8
for each p = *n in S do ADD-EDGE(a, p) - 9
for each *n = r in S do ADD-EDGE(r, a) - 10
for each w in succ[n] do PROPAGATE(d, w) - 11
return pts ADD-EDGE(u, v)- 12
if v is not in succ[u] then - 13
add v to succ[u]; PROPAGATE(pts[u], v) PROPAGATE(s, v)- 14
new <- s minus pts[v] - 15
if new is not empty then - 16
add new to pts[v] and to delta[v]; add v to W if it is not there
A new edge must carry the whole set of its source at once (line L13), since the facts that the source already sent on did not go along this edge. After that, only the differences move (line L10). The implementation keeps the loads and stores of each node in tables, so lines L8 and L9 look only at the statements of , and it uses a first-in first-out worklist. The order of the worklist changes the running time, not the result.
Example
The program, in the toy IR:
entry:
p = &a
q = &b
r = &p
s = q
*r = s
t = *r
ret 0
Lines L3 and L4 give , , , the edge and . The worklist is .
| step | node | what happens | |
|---|---|---|---|
| 1 | has no edges, loads or stores yet | ||
| 2 | is already in | ||
| 3 | load t = *r: edge , ; store *r = s: edge , |
||
| 4 | is already in | ||
| 5 | no edges | ||
| 6 | along : | ||
| 7 | no edges; the worklist is empty |
The result is , , , , , and . The fact comes from the store *r = s, which writes into because points to . The set of stays : the edge goes one way only. The Steensgaard analysis of the same program unifies the targets of and with those of and gives .
Correctness
The full proof is in the proof file. Its steps:
- The least solution exists. The intersection of solutions is a solution, and the assignment where every set is is one. So the intersection of all solutions is the least one. It is also the least fixed point of a monotone map, by the Knaster-Tarski theorem.
- Every fact is forced. By induction over the steps, , and every edge has : each new edge comes from a statement and from a fact that is already in .
- What is sent stays sent. With minus , every edge has , and the edges for loads and stores exist for every element of . A node with a non-empty is on the worklist.
- At the end, the sets are a solution. When the worklist is empty, , so all four constraints hold. With step 2, .
- Soundness for the program. In any run that executes the statements in any order, the cell that points to is always in . Each statement keeps this true because meets its constraint.
Proof: Andersen's worklist algorithm computes the least solution of the subset constraints in O(n^3 + m) timefull
Setting. The program is a set of statements over a set of variables. Every variable is also a location, so a points-to assignment is a map . The statements give the constraints
- : ;
- : ;
- : for every ;
- : for every .
A solution is an assignment that meets all of them. Assignments are ordered pointwise by , with the pointwise union as join and the empty sets as bottom. This is the order of abstract interpretation in the direction of Cousot: a larger assignment says more pointers may point to more places, so it is less precise and safer. "Least" below means least in this order.
Lemma 1 (the least solution exists). The pointwise intersection of any family of solutions is a solution. So there is a least solution , the intersection of all solutions.
Proof. Let be solutions and . For , is in every . For , for each . For and , , so for each . The store case is the same. The full assignment is a solution, so the family is not empty.
The same is the least fixed point of the monotone map that adds to every fact one rule forces from , by the Knaster-Tarski theorem; Lemma 1 is the direct form of this.
The algorithm. Write for the set of edges, and for the arrays of the pseudocode and for the worklist. An edge stands for . Line L3 puts the addresses in, line L4 adds the copy edges, and lines L8 and L9 add the edges that a load or a store needs for each new element of the set of its pointer. PROPAGATE adds to the part of a set that is new and records it in .
Lemma 2 (every fact is forced). At all times, for every , and for every edge .
Proof. Both hold at the start, when all sets and are empty. Line L3 adds to only for a statement , and . Line L4 adds for a statement , and . Line L8 adds for a statement and an , so because is a solution. Line L9 is the same for a store. PROPAGATE along an edge adds only elements of . In line L10, and the edges are those of .
Lemma 3 (what is done is done). Call . The following hold each time line L5 tests the loop condition:
- If , then .
- Every statement has , and every statement has the edge .
- For every edge , .
- For every statement and every , the edge is in ; for every statement and every , the edge is in .
Proof. Parts 1 and 2 are clear: every write to comes with , leaves only in line L6 where is emptied, and lines L3 and L4 run before the loop. Before the loop, for every : line L3 puts into both and , and PROPAGATE does the same with the new elements. So parts 3 and 4 hold then. Consider one pass of lines L6 to L10 at node , with . Sets only grow, and an element enters only when and it is in , because elsewhere new elements go into and together. So in this pass the new part of is empty if and is if . Part 3 for an edge : if the edge was added in this pass, ADD-EDGE sent all of to at that moment, and that set already held the old and . If the edge was there before, the old was already in , and for line L10 sends along every edge of . Part 4: the new part of is , and lines L8 and L9 add the needed edges for each element of . For , does not grow.
Theorem 1 (correctness). The loop stops, and then .
Proof. Each pass of the loop body takes a node out of , and a node is put back only when some grows. By Lemma 2, , so there are at most pushes after line L4, plus at most before, and the loop stops. Then is empty, so every is empty by part 1 of Lemma 3, and . Parts 2 to 4 now say that meets every constraint: for and the edge is in , so by part 3, and the other forms are the same. So is a solution, by Lemma 1, and by Lemma 2.
Soundness for the program. A flow-insensitive analysis must cover every run that executes the statements of in any order, any number of times. Let be the location whose address holds in such a run, or none. Then whenever is defined, at every moment. This holds at the start, when nothing is defined. A step sets . A step sets . A step with sets , since . A step with sets . Every path through a control flow graph made of these statements is such a run, so the result holds for the program under any control flow.
Theorem 2 (time). With hash sets, the algorithm takes expected time and space. With an bit matrix for and bit vectors for the sets, the same bound holds in the worst case, counting word operations on vectors of bits as .
Proof. Reading the statements and filling the tables of loads and stores, without repeats, costs ; after that there are at most distinct loads and distinct stores. Count the rest.
- Edges. There are at most distinct edges. Each one is added once, and its call of PROPAGATE costs . Total .
- Elements taken from delta. An element enters once, so it is in the of line L6 for at most once. The pairs each cost, in lines L8 and L9, one test of ADD-EDGE per load and per store of . The distinct loads and stores of all nodes number at most in total, and each is met at most times, once per , so these tests cost .
- Line L10. The pass at sends along at most edges at cost each. Since each element is in the of at most once, the total over all passes at is , and over all it is .
- Worklist. At most pushes and pops, each.
The space is the edges and set elements plus the statements.
The bound is for the worklist with difference propagation. A plain round-robin iteration, which applies every constraint in each round until no set changes, also reaches , but each of up to rounds can cost .
Complexity
Proved. Each of the at most edges is added once, and its first PROPAGATE costs . Each element enters each set once, so it is in some once per node; for that pair, lines L8 and L9 touch the loads and stores of the node, and line L10 touches at most edges. After the statements are read and their repeats dropped in time, there are at most loads and stores, and the total is time with space. With hash sets the bound is in expectation; with an bit matrix for the edges and bit vectors for the sets it is a worst-case bound.
Stated in the literature, not proved here. Heintze and McAllester (1997) relate the cubic time of inclusion-based flow analysis to the reachability problem of two-way nondeterministic pushdown automata (2NPDA), for which no subcubic algorithm is known; this is the "cubic bottleneck". Sridharan and Fink (2009) show that the worklist algorithm runs in time on k-sparse programs, where, roughly, each variable and each location gets its values from at most a constant number of statements, and they argue that real programs are close to this case.
Measured, not proved. On random programs of 30 statements, the result of the implementation equals that of a plain round-robin iteration of the four rules in all 400 seeded trials of its test file.
Properties
- Least solution. The result does not depend on the worklist order or on the order of the statements.
- Directional. An edge moves facts only from to . This is the source of its precision over unification.
- Not distributive. The load and store rules join two facts, so the analysis is not a bit-vector problem, and the solver must add edges while it runs.
- Whole program. The answer for one variable can depend on any statement. Demand-driven methods answer one query with less work.
- One location per name. Every variable and allocation site is one location. A loop that allocates many objects at one site gives one location for all of them.
Variants and improvements
- Cycle elimination. All nodes on a cycle of edges have the same final set, so they can be merged into one. Online cycle elimination looks for a cycle when an edge is added; lazy and hybrid cycle detection look less often or plan the merges offline.
- Offline variable substitution. Offline variable substitution finds, before solving, variables that must have equal sets and solves for one of each group.
- Unification. Steensgaard's analysis replaces each subset constraint by an equality and runs in almost linear time, with larger sets. One-level flow keeps subsets only at the top level.
- Fields and contexts. Field sensitivity gives each field of a structure its own location. Context sensitivity analyses each call of a function apart, and object sensitivity uses the receiver object as the context.
- Datalog and BDDs. The four rules are a Datalog program; semi-naive evaluation is the same difference propagation. Large analyses store the relations as binary decision diagrams.
- Demand-driven. Demand-driven points-to analysis answers one query by a search in the constraint graph, with matched load and store edges, a form of CFL-reachability.
When to use it
Use it when a flow-insensitive answer is enough and the program is up to a few million lines, as in most whole-program analyses of C and Java. It is the usual base for call graph construction, for mod-ref analysis and for alias queries in an optimizer. With cycle elimination and difference propagation, it handles programs of millions of lines. When time must be near linear and precision can drop, use Steensgaard's analysis. When the order of the statements matters, such as for strong updates of a pointer that is assigned twice, use a flow-sensitive analysis.
Pitfalls
- New edges need the full set. If ADD-EDGE sends only the current of the source, the facts the source sent earlier never reach the new target, and the result misses facts.
- Stores write into the target, not the pointer. The store
*p = qadds edges for . Adding instead is a common mistake that gives wrong sets for both and its targets. - The order of statements. Flow-insensitive answers include facts that no single order makes true together. The answer is not "what points to at this line".
- Precision of the abstraction. All objects from one allocation site are one location, so a store into one of them is a store into all. Do not use the result to prove that two objects from one site are different.
- Self-loops and repeats. Edges and repeated statements are harmless, but without a test for repeated edges, ADD-EDGE can run PROPAGATE over the full set many times.
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/andersen-analysis/. The authors are listed in prov/MBB0JP.jsonl.
"""Andersen's inclusion-based points-to analysis.
andersen(stmts) takes statements in the four forms of ptsgen
(("addr", p, a), ("copy", p, q), ("load", p, q) for p = *q and
("store", p, q) for *p = q) and returns the least solution of the subset
constraints, as a dict from each variable to the set of variables it may
point to. It keeps a constraint graph with an edge u -> v for each
inclusion pts(u) <= pts(v), and a worklist of nodes whose sets have grown.
Each node also keeps delta, the part of its set that it has not yet sent
along its edges or used for its loads and stores (difference propagation).
may_alias(pts, p, q) tells if *p and *q may be the same location.
"""
from collections import deque
import ptsgen
def andersen(stmts):
names = ptsgen.variables(stmts)
pts = {v: set() for v in names} # @line L1
succ = {v: set() for v in names}
delta = {v: set() for v in names}
loads = {v: set() for v in names} # loads[q]: the p with p = *q
stores = {v: set() for v in names} # stores[p]: the q with *p = q
work = deque() # @line L2
queued = set()
def push(v):
if v not in queued:
queued.add(v)
work.append(v)
def propagate(s, v):
new = s - pts[v] # @line L14
if new: # @line L15
pts[v] |= new # @line L16
delta[v] |= new
push(v)
def add_edge(u, v):
if v not in succ[u]: # @line L12
succ[u].add(v) # @line L13
propagate(pts[u], v)
for kind, x, y in stmts:
if kind == "addr":
pts[x].add(y) # @line L3
delta[x].add(y)
push(x)
elif kind == "load":
loads[y].add(x)
elif kind == "store":
stores[x].add(y)
for kind, x, y in stmts:
if kind == "copy":
add_edge(y, x) # @line L4
while work: # @line L5
n = work.popleft() # @line L6
queued.discard(n)
d = delta[n]
delta[n] = set()
for a in d: # @line L7
for p in loads[n]:
add_edge(a, p) # @line L8
for q in stores[n]:
add_edge(q, a) # @line L9
for w in list(succ[n]):
propagate(d, w) # @line L10
return pts # @line L11
def may_alias(pts, p, q):
"""True if the locations *p and *q may be the same."""
return bool(pts.get(p, set()) & pts.get(q, set()))
def points_to(text):
"""Run the analysis on a program written in toy IR notation."""
return andersen(ptsgen.parse(text))
ptsgen.py 177 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/.
"""Points-to constraints in the four basic forms, for the pointer analysis pages.
A program is a list of statements. Each statement is a tuple with the same
shape as the pointer instructions of the toy IR (toyir.py):
("addr", p, a) p = &a
("copy", p, q) p = q
("load", p, q) p = *q
("store", p, q) *p = q
Every name is a pointer variable, and every variable is also a memory
location whose address the program may take. A points-to solution is a dict
from each variable to a set of variables. The order of the statements does
not matter to a flow-insensitive analysis.
parse(text) and show(stmts) convert to and from the toy IR notation.
random_program(rng, nvars, nstmts) builds a random program.
least_solution(stmts) is a slow reference: it applies the four rules to
every statement, round after round, until nothing changes.
is_solution(stmts, pts) checks that pts meets every constraint.
concrete_facts(stmts, rng, runs, steps) runs the program concretely, with
the statements in random order, and returns the facts (p, a) that some run
saw: p held the address of a.
"""
import re
_NAME = r"[A-Za-z_][A-Za-z0-9_]*"
_FORMS = [
("addr", re.compile(r"(%s) = &(%s)" % (_NAME, _NAME))),
("load", re.compile(r"(%s) = \*(%s)" % (_NAME, _NAME))),
("store", re.compile(r"\*(%s) = (%s)" % (_NAME, _NAME))),
("copy", re.compile(r"(%s) = (%s)" % (_NAME, _NAME))),
]
def parse(text):
"""Parse lines such as "p = &a", "p = q", "p = *q" and "*p = q".
The k-th "p = alloc" becomes "p = &hk", one location per allocation
site. Blank lines, lines that start with #, block labels and the
terminators jump, br and ret are skipped, so a toy IR program with only
pointer instructions can be read as it is. A flow-insensitive analysis
ignores the order of the statements, so the blocks do not matter."""
stmts = []
sites = 0
for raw in text.splitlines():
line = " ".join(raw.split())
if not line or line.startswith("#") or line.endswith(":"):
continue
if line.split()[0] in ("jump", "br", "ret"):
continue
m = re.fullmatch(r"(%s) = alloc" % _NAME, line)
if m:
sites += 1
stmts.append(("addr", m.group(1), "h%d" % sites))
continue
for kind, rx in _FORMS:
m = rx.fullmatch(line)
if m:
stmts.append((kind, m.group(1), m.group(2)))
break
else:
raise ValueError("not a pointer statement: %r" % raw)
return stmts
def show(stmts):
out = []
for kind, x, y in stmts:
if kind == "addr":
out.append("%s = &%s" % (x, y))
elif kind == "copy":
out.append("%s = %s" % (x, y))
elif kind == "load":
out.append("%s = *%s" % (x, y))
else:
out.append("*%s = %s" % (x, y))
return "\n".join(out)
def variables(stmts):
"""All names, in the order of their first use."""
seen = {}
for _, x, y in stmts:
seen.setdefault(x, None)
seen.setdefault(y, None)
return list(seen)
def random_program(rng, nvars=8, nstmts=30, weights=(3, 4, 2, 2)):
"""A random list of nstmts statements over the names v0 .. v(nvars-1).
weights gives the relative number of addr, copy, load and store forms."""
names = ["v%d" % i for i in range(nvars)]
kinds = ["addr", "copy", "load", "store"]
return [
(rng.choices(kinds, weights)[0], rng.choice(names), rng.choice(names))
for _ in range(nstmts)
]
def least_solution(stmts):
"""The least solution of the inclusion constraints, by plain iteration."""
pts = {v: set() for v in variables(stmts)}
changed = True
while changed:
changed = False
for kind, x, y in stmts:
if kind == "addr":
new = {y}
targets = [x]
elif kind == "copy":
new = pts[y]
targets = [x]
elif kind == "load":
new = set()
for a in pts[y]:
new |= pts[a]
targets = [x]
else:
new = pts[y]
targets = list(pts[x])
for t in targets:
if not new <= pts[t]:
pts[t] |= new
changed = True
return pts
def is_solution(stmts, pts):
"""True if pts satisfies every constraint of stmts."""
for kind, x, y in stmts:
if kind == "addr" and y not in pts[x]:
return False
if kind == "copy" and not pts[y] <= pts[x]:
return False
if kind == "load" and any(not pts[a] <= pts[x] for a in pts[y]):
return False
if kind == "store" and any(not pts[y] <= pts[a] for a in pts[x]):
return False
return True
def concrete_facts(stmts, rng, runs=20, steps=120):
"""Run the program concretely. Each variable holds no value at the start.
A run is a sequence of statements in any order, with repeats, which is the
semantics that a flow-insensitive analysis must cover; every path of a
real control flow graph over these statements is such a sequence. A
statement that reads a variable with no value, or goes through one,
cannot run, so the run picks another. Returns the set of pairs (p, a)
such that p held the address of a at some moment of some run."""
seen = set()
for _ in range(runs):
val = {v: None for v in variables(stmts)}
for _ in range(steps):
kind, x, y = stmts[rng.randrange(len(stmts))]
if kind == "addr":
val[x] = y
dst = x
elif kind == "copy":
if val[y] is None:
continue
val[x] = val[y]
dst = x
elif kind == "load":
if val[y] is None or val[val[y]] is None:
continue
val[x] = val[val[y]]
dst = x
else:
if val[x] is None or val[y] is None:
continue
dst = val[x]
val[dst] = val[y]
seen.add((dst, val[dst]))
return seen
test_andersen_analysis.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/andersen-analysis/. The authors are listed in prov/MBB0JP.jsonl.
import random
import ptsgen
from andersen_analysis import andersen, may_alias, points_to
PAGE = """
entry:
p = &a
q = &b
r = &p
s = q
*r = s
t = *r
ret 0
"""
def test_page_example():
pts = points_to(PAGE)
assert pts == {
"p": {"a", "b"},
"a": set(),
"q": {"b"},
"b": set(),
"r": {"p"},
"s": {"b"},
"t": {"a", "b"},
}
assert may_alias(pts, "p", "t")
assert may_alias(pts, "q", "s")
assert may_alias(pts, "p", "q")
assert not may_alias(pts, "r", "p")
def test_parse_and_show():
stmts = ptsgen.parse(PAGE)
assert [k for k, _, _ in stmts] == ["addr", "addr", "addr", "copy", "store", "load"]
assert ptsgen.parse(ptsgen.show(stmts)) == stmts
def test_allocation_sites():
# Each alloc instruction is one abstract location.
pts = points_to("p = alloc\nq = alloc\nr = p\n*r = q\ns = *p")
assert pts["p"] == {"h1"} and pts["q"] == {"h2"}
assert pts["h1"] == {"h2"} and pts["s"] == {"h2"}
def test_empty_and_trivial():
assert andersen([]) == {}
assert points_to("p = p") == {"p": set()}
assert points_to("p = &p\nq = *p") == {"p": {"p"}, "q": {"p"}}
def test_store_through_self():
# *p = p with p = &a writes the address of a into a.
assert points_to("p = &a\n*p = p") == {"p": {"a"}, "a": {"a"}}
def test_same_as_least_solution_on_random_programs():
rng = random.Random(1994)
for trial in range(400):
nvars = rng.randint(2, 12)
stmts = ptsgen.random_program(rng, nvars, rng.randint(1, 30))
pts = andersen(stmts)
assert pts == ptsgen.least_solution(stmts), ptsgen.show(stmts)
assert ptsgen.is_solution(stmts, pts)
def test_every_fact_is_needed():
# The result is the least solution, so no smaller assignment is a
# solution: removing any one fact breaks some constraint.
rng = random.Random(7)
for trial in range(100):
stmts = ptsgen.random_program(rng, 6, 20)
pts = andersen(stmts)
for v in pts:
for a in pts[v]:
smaller = {w: set(s) for w, s in pts.items()}
smaller[v].discard(a)
assert not ptsgen.is_solution(stmts, smaller)
def test_sound_against_concrete_runs():
rng = random.Random(2024)
for trial in range(150):
stmts = ptsgen.random_program(rng, rng.randint(3, 10), 30)
pts = andersen(stmts)
facts = ptsgen.concrete_facts(stmts, rng, runs=10, steps=150)
for p, a in facts:
assert a in pts[p], (p, a, ptsgen.show(stmts))
def test_concrete_runs_reach_most_facts():
# The analysis is the least solution, and with enough runs the concrete
# program shows nearly every fact of it. The check uses programs without
# loads and stores, where every fact must show up.
rng = random.Random(5)
for trial in range(50):
stmts = ptsgen.random_program(rng, 6, 15, weights=(1, 2, 0, 0))
pts = andersen(stmts)
facts = ptsgen.concrete_facts(stmts, rng, runs=40, steps=200)
assert facts == {(p, a) for p in pts for a in pts[p]}
History
Lars Ole Andersen defined the inclusion-based analysis in his 1994 PhD thesis at DIKU, as part of a partial evaluator for C. Steensgaard's 1996 unification analysis was a faster and less precise answer to its cubic cost. Heintze and McAllester (1997) placed the cubic time among the problems equivalent to 2NPDA reachability. Fähndrich, Foster, Su and Aiken (1998) made the solver much faster by merging cycles online, Rountev and Chandra (2000) by finding equal variables offline, and Hardekopf and Lin (2007) by lazy and hybrid cycle detection, which made Andersen's analysis of millions of lines of C practical. Hind (2001) surveyed the field and its open questions. Sridharan and Fink (2009) explained its speed on real code with the k-sparse bound. Many current tools write the analysis as Datalog rules; Smaragdakis and Balatsouras (2015) survey this style.
References
- Lars Ole Andersen, Program Analysis and Specialization for the C Programming Language, PhD thesis, DIKU, University of Copenhagen, 1994 (DIKU report 94/19), the chapter on pointer analysis, with the inclusion constraints for the assignments of C and their solution
- Nevin Heintze and David McAllester, On the cubic bottleneck in subtyping and flow analysis, Proceedings of the 12th IEEE Symposium on Logic in Computer Science (LICS), 342 to 351, 1997, whole paper (the cubic bound of inclusion-based flow analysis and its relation to 2NPDA reachability)
- Manu Sridharan and Stephen J. Fink, The complexity of Andersen's analysis in practice, Static Analysis Symposium (SAS 2009), LNCS 5673, 205 to 221, whole paper (a quadratic bound for k-sparse programs, which explains why the analysis is fast on real code)
- Michael Hind, Pointer analysis, haven't we solved this problem yet?, Proceedings of the ACM SIGPLAN-SIGSOFT Workshop on Program Analysis for Software Tools and Engineering (PASTE '01), 54 to 61, 2001, the survey of flow-insensitive analyses and their scalability
- Yannis Smaragdakis and George Balatsouras, Pointer Analysis, Foundations and Trends in Programming Languages 2(1), 1 to 69, 2015, the inclusion-based model of the analysis, written as rules over input relations
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 12.4 (a simple pointer-analysis algorithm, flow-insensitive, written in Datalog)
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 MBB0JP Edit this page History Report an error Markdown