Algorithm Search⌘K

Algorithmresearch

Lazy and hybrid cycle detection

Also called Hardekopf-Lin cycle detection.

Looks for constraint cycles only when an edge brings no new points-to facts, plus an offline pass, making Andersen's analysis scale.

Time
O(n^4 + n^2 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)
Properties
not context sensitivedeterministicnot flow sensitiveonlineiterative
Origin
Ben Hardekopf, Calvin Lin, 2007

Lazy and hybrid cycle detection are two ways to find the cycles of the constraint graph of Andersen's analysis at a low cost, so that the nodes of each cycle can be merged. All nodes on a cycle must end with the same points-to set, and merging them saves the solver from moving each fact around the cycle. Online cycle elimination searches for a cycle at each new edge, which costs much. Lazy cycle detection (LCD) searches only when an edge would carry a set that is already equal to the set at its target, since that is what a cycle looks like once the facts have gone around it. Hybrid cycle detection (HCD) looks at the statements before solving and finds cycles that go through loads and stores. It records which merges to do once the targets of the pointers are known, and then does them with no search. Hardekopf and Lin (2007) gave both and used them to analyse C programs of over a million lines.

In plain words

Andersen's analysis passes lists of addresses along arrows from pointer to pointer. When arrows go around a circle, every pointer on it ends with the same list, so the circle can become one pointer. Looking for circles after every new arrow is slow. The lazy method waits for a sign: an arrow whose two ends already have the same list. Only then does it look for a circle through that arrow, and it looks only once per arrow. The hybrid method reads the program first. A circle that passes through a read or write via a pointer only appears once that pointer gets a target. The method notes in advance which merges such targets will cause, and it does them as soon as the targets appear. The final lists are those of Andersen's analysis.

The problem

The input is a set of statements in the four basic forms p = &a, p = q, p = *q and *p = q over nn variables, and the output is the least solution LL of the subset constraints of Andersen's analysis, as on the page of the points-to analysis problem. The order is the subset order on each set, with the empty sets at the bottom, in the direction of Cousot. The analysis is flow-insensitive: it ignores the order of the statements, not the statements that the control flow gives.

If the solver's graph has a path from uu to vv, then L(u)⊆L(v)L(u) \subseteq L(v), so LL is the same on a cycle. Many cycles only appear while the solver runs: a load p = *q gives the edge a→pa \to p only when aa enters the set of qq. The offline graph shows them in advance. It has a node vv and a ref node ∗v*v for each variable, which stands for every target of vv, and the edges

statement offline edge
p = q q→pq \to p
p = *q ∗q→p*q \to p
*p = q q→∗pq \to *p

A cycle of the offline graph through ∗a*a and a variable bb becomes a real cycle through xx and bb for each target xx of aa, once the other ref nodes on the cycle have targets too.

The algorithm

The offline part is lines L1 to L4. The solver is the worklist solver of Andersen's analysis over the roots of a union-find forest, with the hybrid merges in lines L8 and L9 and the lazy check in lines L12 to L14.

  1. HYBRID(S)
  2. 1G <- the offline graph of S; find its strongly connected components
  3. 2merge the variables of each strongly connected component of the copy edges alone
  4. 3for each component C of G with a ref node and a variable node b do
  5. 4for each *a in C do add (b, the pointers of the other ref nodes of C) to H[a]
  6. 5set up the sets, edges, loads and stores as in Andersen's analysis; W <- the roots with a non-empty set
  7. 6while W is not empty do
  8. 7take n from W; if FIND(n) is not n then go to the next n
  9. 8for each (b, R) in H[n] such that pts[FIND(c)] is not empty for every c in R do
  10. 9for each x in pts[n] do MERGE(x, b)
  11. 10for each x in pts[n] do add the edges of the loads and stores of n for x
  12. 11for each w in succ[n] do
  13. 12if pts[w] = pts[n] and the edge n -> w was never checked then
  14. 13mark it checked; C <- the roots on some path from w to n
  15. 14if C is not empty then MERGE all of C; go to the next w
  16. 15copy pts[n] into pts[w]; if it grew, add w to W
  17. 16return pts[FIND(v)] for each variable v

MERGE joins the classes in the union-find forest, takes the union of their sets, edges, loads, stores and table entries, and puts the new root on the worklist. Line L2 merges only cycles of copies; the variable nodes of a component with ref nodes are not merged offline, since their cycle may need a pointer that never gets a target. The lazy check runs at most once per edge, so a cycle that it misses at one time is not searched for again on that edge.

Example

The program, in the toy IR:

entry:
  a = &x
  a = &y
  b = *a
  c = b
  *a = c
  y = &z
  ret 0

The offline graph has the edges ∗a→b*a \to b (from the load), b→cb \to c (from the copy) and c→∗ac \to *a (from the store). They form the component {∗a,b,c}\{*a, b, c\}, so line L4 records H[a]={(b,∅)}H[a] = \{(b, \emptyset)\}: every target of aa will be on a cycle with bb. There is no cycle of copies alone.

step lines what happens
1 L5 pts(a)={x,y}pts(a) = \{x, y\}, pts(y)={z}pts(y) = \{z\}, the copy edge b→cb \to c; the worklist is a,ya, y
2 L8, L9 take aa: the entry (b,∅)(b, \emptyset) applies, so xx and then yy merge into bb; pts(b)={z}pts(b) = \{z\}, from yy
3 L10 the load adds x→bx \to b and y→by \to b, which are now inside one node; the store *a = c adds c→bc \to b
4 L7 take yy: not a root, so skip it
5 L15 take bb: along b→cb \to c, pts(c)={z}pts(c) = \{z\}
6 L12 to L14 take cc: the edge c→bc \to b carries {z}\{z\} and pts(b)={z}pts(b) = \{z\} already, so search from bb for cc; the path b→cb \to c closes a cycle, and cc merges into bb
7 L11 take bb: no edges are left

The result is pts(a)={x,y}pts(a) = \{x, y\} and pts(b)=pts(c)=pts(x)=pts(y)={z}pts(b) = pts(c) = pts(x) = pts(y) = \{z\}, which is Andersen's least solution. The run made two hybrid merges, one lazy merge, and one search. The hybrid merges put xx and yy into one node before any fact went around the cycle.

Correctness

The full proof is in the proof file. Its steps:

  1. An offline path gives inclusions. Replace each ref node ∗c*c on a path of the offline graph by a location in L(c)L(c). Then each edge becomes a true inclusion of least sets: a copy, a load from that location, or a store into it.
  2. Every merge joins nodes with one least set. Copy cycles share their set. A hybrid merge of x∈pts(a)x \in pts(a) with bb happens only when every other ref node of the component has a target; then the two paths between bb and ∗a*a in the component, with xx for ∗a*a, give L(b)⊆L(x)⊆L(b)L(b) \subseteq L(x) \subseteq L(b). A lazy merge joins nodes on a cycle of the solver's edges, which are true inclusions.
  3. What is done stays done. A root that is not on the worklist has all the edges for its loads and stores, and its set is inside the set of each successor.
  4. At the end, the sets are LL. They form a solution, so they contain LL, and every set stays inside LL by step 2.

The proof never needs a merge to happen. So the lazy check can miss cycles, and the result is still exact.

Proof: Lazy and hybrid cycle detection merge only nodes with equal least sets, so the result is Andersen's least solutionfull

Setting. The program is a set of mm statements in the four forms over nn variables, each variable also a location. LL is the least solution of the subset constraints of Andersen's analysis: p = &a gives a∈L(p)a \in L(p), p = q gives L(q)⊆L(p)L(q) \subseteq L(p), p = *q gives L(a)⊆L(p)L(a) \subseteq L(p) for a∈L(q)a \in L(q), and *p = q gives L(q)⊆L(a)L(q) \subseteq L(a) for a∈L(p)a \in L(p). LL lies inside every solution. The solver keeps a union-find forest over the variables; [v][v] is the root of the class of vv, and each root rr has a set pts(r)pts(r), successors succ(r)succ(r), the loads and stores of its members, and the table entries HH of its members. The result is S(v)=pts([v])S(v) = pts([v]).

The offline graph has a node vv and a ref node ∗v*v for each variable vv, and the edges q→pq \to p for p = q, ∗q→p*q \to p for p = *q, and q→∗pq \to *p for *p = q. For each strongly connected component CC of it with a ref node ∗a*a and a variable node bb, line L4 adds the entry (b,R)(b, R) to H(a)H(a), where RR is the set of the pointers c≠ac \ne a with ∗c∈C*c \in C.

Lemma 1 (a walk of the offline graph gives inclusions). Let σ\sigma map each variable node vv of the offline graph to vv, and each ref node ∗c*c to some location σ(∗c)∈L(c)\sigma(*c) \in L(c). Then for every offline edge u→wu \to w, L(σ(u))⊆L(σ(w))L(\sigma(u)) \subseteq L(\sigma(w)).

Proof. For a copy edge q→pq \to p, this is the copy constraint. For a load edge ∗q→p*q \to p, σ(∗q)∈L(q)\sigma(*q) \in L(q), so the load constraint gives L(σ(∗q))⊆L(p)L(\sigma(*q)) \subseteq L(p). For a store edge q→∗pq \to *p, σ(∗p)∈L(p)\sigma(*p) \in L(p), so the store constraint gives L(q)⊆L(σ(∗p))L(q) \subseteq L(\sigma(*p)). □\square

Lemma 2 (every merge joins nodes with one least set). At every moment, all members of a class have the same LL, pts(r)⊆L(r)pts(r) \subseteq L(r) for every root rr, and every edge r→wr \to w of the solver has L(r)⊆L(w)L(r) \subseteq L(w).

Proof. The edges and the growth of the sets are those of Andersen's solver, with the loads and stores of a class read on its root, and they keep the last two parts as in the proof for online cycle elimination. It remains to check the three kinds of merge.

  • Offline merges (line L2). The members of a strongly connected component of the copy graph lie on cycles of copy constraints, so their LL is the same.
  • Hybrid merges (line L9). Line L8 runs only when pts([c])≠∅pts([c]) \ne \emptyset for every c∈Rc \in R, and line L9 merges bb with an x∈pts(n)x \in pts(n), where aa is a member of the class nn. Since the sets are inside LL and LL is the same on the class, x∈L(a)x \in L(a) and L(c)≠∅L(c) \ne \emptyset for every c∈Rc \in R. Let σ(∗a)=x\sigma(*a) = x and let σ(∗c)\sigma(*c) be any element of L(c)L(c) for c∈Rc \in R. The component CC has a path from bb to ∗a*a and one from ∗a*a back to bb, and all their nodes are in CC, so every ref node on them is ∗a*a or ∗c*c with c∈Rc \in R. By Lemma 1, LL does not shrink along either path under σ\sigma, so L(b)⊆L(x)⊆L(b)L(b) \subseteq L(x) \subseteq L(b).
  • Lazy merges (line L14). The set CC holds the roots on some path from ww to nn in the solver's graph, and the edge n→wn \to w is in the graph. So every member of CC lies on a cycle of solver edges, and by the third part LL is the same on all of it. □\square

The condition of line L8 is needed. In the statements a = &x, b = &w, b = *a, *c = b, q = *c and *a = q, the component {∗a,b,∗c,q}\{*a, b, *c, q\} gives the entry (b,{c})(b, \{c\}) for aa, but cc has no target, so L(x)=∅L(x) = \emptyset and L(b)={w}L(b) = \{w\}.

Lemma 3 (what is done stays done). Every root that is not on the worklist has, for every a∈pts(r)a \in pts(r), the edges for the loads and stores of its class, and pts(r)⊆pts(w)pts(r) \subseteq pts(w) for every edge r→wr \to w.

Proof. As for online cycle elimination: a root whose set grows is pushed, a root made by a merge is pushed, and an edge from a root that is not on the worklist is added with its set (in ADD-EDGE) or lies inside a merge. When a root is taken from the worklist, lines L10 to L15 add the edges for all its elements and send its set along all its edges, except along an edge whose ends line L14 merges, and that merged root is pushed again. □\square

Theorem 1 (correctness). The algorithm stops, and S=LS = L.

Proof. Each push comes from a set that grew or from a merge; there are at most nn growths per root and at most n−1n - 1 merges, so the loop stops. Line L12 starts at most one search per ordered pair of variables, since it marks the pair. When the loop stops, every root meets Lemma 3, and as for Andersen's analysis this makes SS a solution, so L⊆SL \subseteq S. By Lemma 2, S(v)=pts([v])⊆L([v])=L(v)S(v) = pts([v]) \subseteq L([v]) = L(v). □\square

The hybrid and lazy merges are only ways to store fewer sets. Missing one costs time, not precision: the proof does not need any merge to happen.

Theorem 2 (time). The offline part (lines L1 to L4) takes O(n+m)O(n + m) time. With each find counted as one step, the solver takes O(n4+n2m)O(n^4 + n^2 m) time in the worst case and O(n2+m)O(n^2 + m) space.

Proof. The offline graph has 2n2n nodes and mm edges, and Tarjan's algorithm takes O(n+m)O(n + m) time; the table has at most one entry per ref node and component. Each root is processed O(n)O(n) times, as in the proof for online cycle elimination, which gives O(n2m+n4)O(n^2 m + n^4) for the edges and the transfers of sets. A class has at most nn table entries, each with at most nn pointers, so lines L8 and L9 cost O(n2)O(n^2) per processing, plus the cost of the real merges, of which there are at most n−1n - 1 in all. With O(n2)O(n^2) processings, this is O(n4)O(n^4). There are at most n2n^2 lazy searches, each in O(n+n2)O(n + n^2) time. □\square

The worst case is not the point of the method. Its gain is that it searches far less often than online cycle elimination, only on edges that already carry equal sets, and that the hybrid merges need no search at all.

Complexity

Proved. The offline part takes O(n+m)O(n + m) time, with Tarjan's algorithm on a graph of 2n2n nodes and mm edges. The solver takes O(n4+n2m)O(n^4 + n^2 m) time in the worst case, with each find counted as one step: each root goes back on the worklist O(n)O(n) times, there are at most n2n^2 lazy searches of O(n2)O(n^2) time each, and the table costs O(n2)O(n^2) per visit of a root. The space is O(n2+m)O(n^2 + m). The method does not lower the worst case of Andersen's analysis, which is O(n3)O(n^3) with difference propagation.

Stated in the paper, not proved here. Hardekopf and Lin report that LCD and HCD together, with offline variable substitution and difference propagation, analyse C programs of over a million lines, and that they are faster than the earlier cycle detection methods that they compare with, including online cycle elimination and the methods of Heintze and Tardieu and of Pearce, Kelly and Hankin. They also report that HCD costs little and can be added to other solvers, including solvers based on BDDs.

Measured, not proved. On the 300 seeded random programs of the test file, of up to 12 variables and 30 statements, with 1809 variables in all, the solver made 158 offline merges, 101 hybrid merges and 320 lazy merges, with 292 searches. The result equals Andersen's least solution in each of the four modes, with or without the lazy and the offline parts. With the condition of line L8 dropped, 2 of 1000 random programs got sets larger than Andersen's.

Properties

  • Same result as Andersen's analysis. Every merge joins nodes with equal least sets.
  • Few searches. A search runs only on an edge that carries no new facts, and at most once per edge.
  • Merges with no search. The hybrid merges need only the table lookup of line L8.
  • Incomplete. Neither part finds every cycle. The proof does not need them to.
  • Works with other methods. It adds to offline variable substitution, to difference propagation, and to BDD-based solvers.

Variants and improvements

  • Online cycle elimination. Online cycle elimination searches at every new edge; it finds more cycles earlier, at a much higher cost per edge.
  • Hash-based value numbering. Hardekopf and Lin (SAS 2007) extended offline substitution so that it also finds pointers that are equal through loads, which shrinks the graph before LCD and HCD run.
  • Wave and deep propagation. Later solvers by Pereira and Berlin (2009) propagate in topological order of the collapsed graph and run cycle detection between waves.
  • Field-sensitive analysis. With field sensitivity, a load or store may add a field offset to each target. A cycle whose edges add offsets does not make the sets equal, so such edges must be left out of the cycle search or handled apart.

When to use it

Use it in an inclusion-based points-to solver that must handle large programs, together with offline variable substitution and difference propagation. For a small program, or a one-off analysis, plain Andersen's analysis is simpler and fast enough. When near-linear time matters more than precision, use Steensgaard's analysis.

Pitfalls

  • Merging too early. A component of the offline graph can pass through several ref nodes. The cycle through ∗a*a and bb exists only when the other pointers have targets too. In the statements a = &x, b = &w, b = *a, *c = b, q = *c, *a = q, with no target for cc, the least set of xx is empty and that of bb is {w}\{w\}. Merging xx with bb at once is sound but less precise than Andersen's analysis.
  • Merging the variable nodes of a mixed component offline. A cycle that passes through a ref node needs a target for that pointer. Merge offline only the cycles of plain copies.
  • Equal sets are only a hint. Two nodes can have equal sets without a cycle. The lazy check must still search, and must not merge on the hint alone.
  • Checking an edge again and again. Without the mark of line L13, an edge between two nodes with equal sets and no cycle starts a search on every visit.
  • Merging locations. Only the pointer sets are joined. The addresses in the sets stay the original locations.

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.

hybrid_cycle_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-cycle-detection/. The authors are listed in prov/NC36D7.jsonl.
"""Andersen's analysis with lazy and hybrid cycle detection.

hybrid(stmts, lazy=True, offline=True) returns (pts, stats), where pts is
the least solution of the subset constraints, the result of Andersen's
analysis. Nodes whose sets must be equal are merged in a union-find forest.

Offline part (hybrid cycle detection, HCD). Before solving, build a graph
with a node v and a ref node *v for each variable v, and the edges q -> p
for p = q, *q -> p for p = *q, and q -> *p for *p = q. The cycles of copies
are merged at once. For each strongly connected component C with a ref node
*a and a variable node b, record (b, R) for a, where R holds the pointers
of the other ref nodes of C. While solving, once every pointer in R has a
non-empty set, each x in the set of a is merged with b: the offline cycle
then exists in the real graph, with x in place of *a.

Online part (lazy cycle detection, LCD). When an edge n -> w is about to
carry the set of n and the set of w is already equal to it, which is a hint
of a cycle, search once for a path from w back to n and merge its nodes.

stats counts the merges of each kind and the searches.
"""

from collections import deque

import ptsgen


def sccs(nodes, succ):
    """Tarjan's algorithm, without recursion. Returns the strongly
    connected components in reverse topological order."""
    index, low, on_stack = {}, {}, set()
    stack, out = [], []
    counter = 0
    for root in nodes:
        if root in index:
            continue
        work = [(root, iter(succ.get(root, ())))]
        index[root] = low[root] = counter
        counter += 1
        stack.append(root)
        on_stack.add(root)
        while work:
            v, it = work[-1]
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter
                    counter += 1
                    stack.append(w)
                    on_stack.add(w)
                    work.append((w, iter(succ.get(w, ()))))
                    break
                if w in on_stack:
                    low[v] = min(low[v], index[w])
            else:
                work.pop()
                if work:
                    u = work[-1][0]
                    low[u] = min(low[u], low[v])
                if low[v] == index[v]:
                    comp = []
                    while True:
                        w = stack.pop()
                        on_stack.discard(w)
                        comp.append(w)
                        if w == v:
                            break
                    out.append(comp)
    return out


def offline_plan(stmts):
    """The copy cycles to merge at once, and the table H of HCD."""
    names = ptsgen.variables(stmts)
    copies, graph = {}, {}
    for kind, x, y in stmts:
        if kind == "copy":
            copies.setdefault(y, []).append(x)
            graph.setdefault(("v", y), []).append(("v", x))
        elif kind == "load":
            graph.setdefault(("r", y), []).append(("v", x))
        elif kind == "store":
            graph.setdefault(("v", y), []).append(("r", x))
    groups = [c for c in sccs(names, copies) if len(c) > 1]
    nodes = [("v", v) for v in names] + [("r", v) for v in names]
    table = {}
    for comp in sccs(nodes, graph):  # @line L3
        refs = sorted(x for k, x in comp if k == "r")
        plain = sorted(x for k, x in comp if k == "v")
        if refs and plain:
            for a in refs:
                rest = tuple(c for c in refs if c != a)
                table.setdefault(a, []).append((plain[0], rest))
    return groups, table


def hybrid(stmts, lazy=True, offline=True):
    names = ptsgen.variables(stmts)
    parent = {v: v for v in names}
    pts = {v: set() for v in names}
    succ = {v: set() for v in names}
    loads = {v: set() for v in names}
    stores = {v: set() for v in names}
    table = {v: [] for v in names}
    checked = set()
    stats = {"offline": 0, "hcd": 0, "lcd": 0, "searches": 0}
    work = deque()
    queued = set()

    def find(x):
        root = x
        while parent[root] != root:
            root = parent[root]
        while parent[x] != root:
            parent[x], x = root, parent[x]
        return root

    def push(v):
        if v not in queued:
            queued.add(v)
            work.append(v)

    def merge(nodes, kind):
        roots = sorted({find(x) for x in nodes})
        if len(roots) < 2:
            return
        r = roots[0]
        for x in roots[1:]:
            parent[x] = r
            pts[r] |= pts[x]
            succ[r] |= succ[x]
            loads[r] |= loads[x]
            stores[r] |= stores[x]
            table[r] += table[x]
            stats[kind] += 1
        succ[r] = {find(w) for w in succ[r]} - {r}
        push(r)

    def on_paths(src, dst):
        """The roots on some path from src to dst, or an empty set."""
        stats["searches"] += 1
        seen, stack = {src}, [src]
        while stack:
            x = stack.pop()
            for w in succ[x]:
                w = find(w)
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        if dst not in seen:
            return set()
        pred = {x: [] for x in seen}
        for x in seen:
            for w in succ[x]:
                pred[find(w)].append(x)
        back, stack = {dst}, [dst]
        while stack:
            x = stack.pop()
            for w in pred[x]:
                if w not in back:
                    back.add(w)
                    stack.append(w)
        return back

    def add_edge(u, v):
        u, v = find(u), find(v)
        if u != v and v not in succ[u]:
            succ[u].add(v)
            if not pts[u] <= pts[v]:
                pts[v] |= pts[u]
                push(v)

    for kind, x, y in stmts:
        if kind == "addr":
            pts[x].add(y)
        elif kind == "copy":
            succ[y].add(x)
        elif kind == "load":
            loads[y].add(x)
        else:
            stores[x].add(y)
    if offline:
        groups, plan = offline_plan(stmts)  # @line L1
        for a, entries in plan.items():
            table[a] += entries  # @line L4
        for group in groups:
            merge(group, "offline")  # @line L2
    for v in names:
        if find(v) == v and pts[v]:
            push(v)  # @line L5
    while work:  # @line L6
        n = work.popleft()
        queued.discard(n)
        if find(n) != n:  # @line L7
            continue
        for b, rest in list(table[n]):
            if all(pts[find(c)] for c in rest):  # @line L8
                for a in list(pts[n]):
                    merge([a, b], "hcd")  # @line L9
        n = find(n)
        for a in list(pts[n]):  # @line L10
            for p in list(loads[n]):
                add_edge(a, p)
            for q in list(stores[n]):
                add_edge(q, a)
        n = find(n)
        for w in list(succ[n]):  # @line L11
            w, n = find(w), find(n)
            if w == n:
                continue
            if lazy and pts[w] == pts[n] and (n, w) not in checked:  # @line L12
                checked.add((n, w))
                cycle = on_paths(w, n)  # @line L13
                if cycle:
                    merge(cycle, "lcd")  # @line L14
                    continue
            if not pts[n] <= pts[w]:  # @line L15
                pts[w] |= pts[n]
                push(w)
    return {v: set(pts[find(v)]) for v in names}, stats  # @line L16


def points_to(text):
    return hybrid(ptsgen.parse(text))[0]
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_hybrid_cycle_detection.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-cycle-detection/. The authors are listed in prov/NC36D7.jsonl.

import random

import ptsgen
from hybrid_cycle_detection import hybrid, offline_plan, points_to

PAGE = """
entry:
  a = &x
  a = &y
  b = *a
  c = b
  *a = c
  y = &z
  ret 0
"""

MODES = [(True, True), (True, False), (False, True), (False, False)]


def test_page_example():
    stmts = ptsgen.parse(PAGE)
    groups, table = offline_plan(stmts)
    assert groups == [] and table == {"a": [("b", ())]}
    pts, stats = hybrid(stmts)
    assert pts == ptsgen.least_solution(stmts)
    assert pts["a"] == {"x", "y"}
    assert pts["b"] == pts["c"] == pts["x"] == pts["y"] == {"z"}
    assert stats == {"offline": 0, "hcd": 2, "lcd": 1, "searches": 1}


def test_offline_copy_cycle():
    stmts = ptsgen.parse("p = &a\nq = p\nr = q\np = r")
    pts, stats = hybrid(stmts)
    assert stats["offline"] == 2 and stats["searches"] == 0
    assert pts["p"] == pts["q"] == pts["r"] == {"a"}


def test_hcd_waits_for_other_ref_nodes():
    # The offline cycle *a -> b -> *c -> q -> *a needs a target for c too.
    # While c points nowhere, x and b do not have equal least sets.
    stmts = ptsgen.parse("a = &x\nb = &w\nb = *a\n*c = b\nq = *c\n*a = q")
    groups, table = offline_plan(stmts)
    assert table["a"] == [("b", ("c",))]
    pts, stats = hybrid(stmts)
    assert stats["hcd"] == 0
    assert pts["x"] == set() and pts["b"] == {"w"}
    assert pts == ptsgen.least_solution(stmts)
    # Once c has a target, the cycle is real and the merge is safe.
    more = stmts + [("addr", "c", "y")]
    pts, stats = hybrid(more)
    assert stats["hcd"] >= 1
    assert pts == ptsgen.least_solution(more)
    assert pts["x"] == pts["b"]


def test_equals_andersen_on_random_programs():
    rng = random.Random(6100)
    total = {"offline": 0, "hcd": 0, "lcd": 0}
    for trial in range(300):
        stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
        least = ptsgen.least_solution(stmts)
        for lazy, offline in MODES:
            pts, stats = hybrid(stmts, lazy, offline)
            assert pts == least, (lazy, offline, ptsgen.show(stmts))
            if lazy and offline:
                for k in total:
                    total[k] += stats[k]
    assert all(total[k] > 20 for k in total)  # every kind of merge happens


def test_merged_nodes_have_equal_least_sets():
    rng = random.Random(6200)
    for trial in range(300):
        stmts = ptsgen.random_program(rng, rng.randint(2, 12), 30, (2, 4, 3, 3))
        assert hybrid(stmts)[0] == ptsgen.least_solution(stmts), ptsgen.show(stmts)


def test_sound_against_concrete_runs():
    rng = random.Random(6300)
    for trial in range(150):
        stmts = ptsgen.random_program(rng, rng.randint(3, 10), 30)
        pts = points_to(ptsgen.show(stmts))
        for p, a in ptsgen.concrete_facts(stmts, rng, runs=10, steps=150):
            assert a in pts[p]


def test_long_cycles():
    n = 2000
    text = "\n".join(["v0 = &a"] + ["v%d = v%d" % ((i + 1) % n, i) for i in range(n)])
    pts, stats = hybrid(ptsgen.parse(text))
    assert all(pts["v%d" % i] == {"a"} for i in range(n))
    assert stats["offline"] == n - 1
    # The same cycle, found online by the lazy check alone.
    pts, stats = hybrid(ptsgen.parse(text), lazy=True, offline=False)
    assert all(pts["v%d" % i] == {"a"} for i in range(n))
    assert stats["lcd"] == n - 1 and stats["searches"] == 1

History

Fähndrich, Foster, Su and Aiken (1998) merged cycles online with a partial search, and Rountev and Chandra (2000) merged equal variables before solving. Heintze and Tardieu (2001) and Pearce, Kelly and Hankin (2003) gave other online methods. Hardekopf and Lin (2007) observed that most searches of the online methods find nothing, and proposed to search only when an edge brings no new facts, which is lazy cycle detection, and to plan merges through loads and stores in an offline pass, which is hybrid cycle detection. Together with offline substitution, the methods made the inclusion-based analysis of C programs of millions of lines practical.

References

  1. Ben Hardekopf and Calvin Lin, The ant and the grasshopper, fast and accurate pointer analysis for millions of lines of code, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '07), 290 to 299, 2007, whole paper (lazy cycle detection, hybrid cycle detection with its offline graph of ref nodes, and the measurements on large C programs)
  2. Manuel Fähndrich, Jeffrey S. Foster, Zhendong Su and Alexander Aiken, Partial online cycle elimination in inclusion constraint graphs, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '98), 85 to 96, 1998, whole paper (online cycle elimination, the method that lazy detection makes cheaper)
  3. Atanas Rountev and Satish Chandra, Off-line variable substitution for scaling points-to analysis, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2000), 47 to 56, 2000, the offline pass over the copy graph, used before the solver

About this page

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

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