Algorithm Search⌘K

Algorithmcore

Steensgaard's analysis

Also called unification-based points-to analysis.

Flow-insensitive points-to analysis that unifies the targets of both sides of each assignment, with union-find, in almost linear time.

Time
O((n + m) α(n + m)) worst
Space
O(n + m) extra
Where
m = the number of pointer statements; n = the number of variables; α = the inverse Ackermann function
Properties
not context sensitivedeterministicnot flow sensitiveonlineiterative
Origin
Bjarne Steensgaard, 1996

Steensgaard's analysis solves the points-to analysis problem by unification. Where Andersen's analysis reads p = q as "the set of p contains the set of q", Steensgaard's analysis reads it as "p and q point into the same class of locations". The locations are kept in classes with union-find, each class points to at most one class, and every statement merges a few classes. One pass over the statements is enough, and the total time is almost linear in the size of the program. The sets are larger than Andersen's, and the proof file shows that they always contain them.

In plain words

Think of the memory cells of a program as grouped into boxes, where every box has at most one arrow to another box. A pointer in a box can point to any cell in the box at the end of the arrow. When the program copies one pointer into another, the analysis makes them use the same target box: if the two boxes they point to are different, it pours one into the other. Pouring two boxes together also pours together the boxes that they point to. Each statement is read once, and each pour is quick with the union-find structure. The answer is safe, because every cell a real run can use ends up in the right box. It is coarse, because cells that were only copied in one direction still share a box.

The problem

The input is a set of statements over nn variables in the forms p = &a, p = q, p = *q and *p = q; p = alloc at site kk is treated as p = &h_k. The output is a set S(v)S(v) for each variable vv that meets the subset constraints of Andersen's analysis. Steensgaard's analysis computes more: a partition of the locations into classes and, for each class, at most one target class, such that:

  • for p = &a, the class of aa is the target of the class of pp;
  • for p = q, if the class of qq has a target, the class of pp has the same target;
  • for p = *q and *p = q, the same rule applies between pp and the target class of qq, or between the target class of pp and qq.

Then S(v)S(v) is the set of variables in the target class of the class of vv. Steensgaard wrote these rules as a type system: the type of a location is a reference to the class of its targets, and the analysis is type inference. The analysis in the terms of a data-flow framework:

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain partitions of the locations, with at most one target class per class
order the partition is coarser and the target map follows it (bottom is precise)
join merging classes (union-find)
bottom and top all classes single, with no targets; one class that points to itself
boundary value none
initial value each location in its own class, with no target
transfer monotone, not distributive

The algorithm

Each root of the union-find forest has a target ptpt, or none, and a list pendingpending. A copy p = q when qq has no target yet must not invent one: that would merge the classes of pp and qq for nothing. So ASSIGN puts pp on the pending list of qq, and the join happens only if qq gets a target later. Steensgaard calls this a conditional join. JOIN merges two classes and then their targets.

  1. STEENSGAARD(S)
  2. 1make a class for each variable, with no target and an empty pending list
  3. 2for each statement of S, in any order do
  4. 3p = &a: if class(p) has no target then SET-TARGET(class(p), class(a))
  5. 4else queue JOIN(pt(class(p)), class(a))
  6. 5p = q: ASSIGN(class(p), class(q))
  7. 6p = *q: ASSIGN(class(p), DEREF(class(q)))
  8. 7*p = q: ASSIGN(DEREF(class(p)), class(q))
  9. 8run the queued operations until the queue is empty
  10. 9return S(v) = the variables in the class pt(class(v)), for each v
  11. DEREF(c)
  12. 10if c has no target then SET-TARGET(c, a new class)
  13. 11return pt(c)
  14. ASSIGN(x, y) the targets of x must include those of y
  15. if x = y then return
  16. 12if y has no target then add x to pending(y)
  17. 13else if x has no target then SET-TARGET(x, pt(y))
  18. 14else queue JOIN(pt(x), pt(y))
  19. JOIN(c1, c2)
  20. if c1 = c2 then return
  21. 15c <- UNION(c1, c2)
  22. 16if neither had a target then pending(c) <- pending(c1) + pending(c2)
  23. 17else if one had no target then pt(c) <- the other target; queue ASSIGN(d, c) for each d pending on the one with no target
  24. 18else pt(c) <- pt(c1); queue JOIN(pt(c1), pt(c2))
  25. SET-TARGET(c, t)
  26. 19pt(c) <- t
  27. 20queue ASSIGN(d, c) for each d in pending(c); pending(c) <- empty

The paper writes JOIN and the conditional join as recursive procedures. The implementation uses one queue of operations instead, so long chains of joins do not use the call stack. The union-find forest uses union by rank and path compression, as in a disjoint-set forest.

Example

The same program as on the Andersen page:

entry:
  p = &a
  q = &b
  r = &p
  s = q
  *r = s
  t = *r
  ret 0
statement what happens classes and targets after it
p = &a pp had no target p→{a}p \to \{a\}
q = &b qq had no target q→{b}q \to \{b\}
r = &p rr had no target r→{p}r \to \{p\}
s = q ASSIGN: qq has a target, ss has none, so ss gets it s→{b}s \to \{b\}
*r = s DEREF(r)(r) is {p}\{p\}; ASSIGN: both {p}\{p\} and {s}\{s\} have targets, so JOIN({a},{b})(\{a\}, \{b\}) {a,b}\{a, b\} is one class; p,q,s→{a,b}p, q, s \to \{a, b\}
t = *r DEREF(r)(r) is {p}\{p\}; ASSIGN gives tt the target of {p}\{p\} t→{a,b}t \to \{a, b\}

The result is S(p)=S(q)=S(s)=S(t)={a,b}S(p) = S(q) = S(s) = S(t) = \{a, b\} and S(r)={p}S(r) = \{p\}. Andersen's analysis gives {b}\{b\} for qq and ss: here the store *r = s merged aa and bb, and since qq and ss already shared the class {b}\{b\}, the merge reached them too.

The pending lists matter for statements in the other order. In p = q followed by q = &b, the first statement finds that qq has no target and puts pp on its pending list; the second gives qq the target {b}\{b\}, and SET-TARGET then runs ASSIGN for pp, so S(p)={b}S(p) = \{b\}. A version without pending lists would make a placeholder target for qq at the first statement, which gives the same sets here, but in larger programs it merges classes that never needed to meet.

Correctness

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

  1. A target, once set, stays. A class with a target keeps one when it merges, and the old and the new targets end up in one class, because the JOIN of line L18 runs before the end.
  2. A pending copy is not lost. If ASSIGN(x,y)(x, y) runs and the class of yy has a target at the end, then the classes of xx and yy have the same target at the end. The pending entry moves with the class until the class gets a target, and then it becomes an ASSIGN again.
  3. The result is a solution. With steps 1 and 2, each of the four statement forms meets its subset constraint. For a load p = *q, every aa in S(q)S(q) is in the target class of qq, which is the class that DEREF returned, and its target is the target of pp.
  4. It contains Andersen's result. Andersen's sets are the least solution, so they are inside every solution, and in particular inside SS.

The sets have one more property: two sets are equal or disjoint, because each is a whole class.

Proof: Steensgaard's analysis gives a solution of the subset constraints, so its sets contain Andersen's, in almost linear timefull

Setting. The program is a set of mm statements in the four forms p = &a, p = q, p = *q and *p = q over nn variables, and each variable is also a location. The constraints of a statement are those of Andersen's analysis, and LL is their least solution in the order ⊆\subseteq on each set. The proof of the Andersen page shows that L⊆PL \subseteq P for every solution PP.

The algorithm keeps a union-find forest over the variables and the fresh classes made in line L10. For a root cc, pt(c)pt(c) is a class or none, and pending(c)pending(c) is a list of classes. At the end, cls(v)cls(v) is the root of vv, T(c)T(c) is the root of pt(c)pt(c) when pt(c)pt(c) is set, and

S(v)={a a variable:cls(a)=T(cls(v))},S(v) = \{a \text{ a variable} : cls(a) = T(cls(v))\},

or the empty set when cls(v)cls(v) has no target. All operations queued while a statement is read run in line L8 before the next statement, so no operation is left in the queue at the end. We write x∼yx \sim y if xx and yy are in the same class at the end. Classes only merge, so two elements in one class at some moment are in one class at the end.

Lemma 1 (a target, once set, stays). If at some moment the root of the class of xx has the target tt, then at the end cls(x)cls(x) has a target and T(cls(x))∼tT(cls(x)) \sim t.

Proof. A target is written only in line L19, which is called only for a root with no target, and in lines L17 and L18, when two roots merge. So a root with a target keeps it until its class merges with another. We use induction on the number of later merges of the class of xx. With none, the root of xx at the end still has tt. At the next merge, the class of xx, with target tt, merges with a class with target t2t_2 or with none. If the other class has none, line L17 gives the new root the target tt. If it has t2t_2, line L18 gives the new root one of tt and t2t_2 and queues JOIN(t,t2)(t, t_2), which runs before the end, so t∼t2t \sim t_2. In both cases the new root has a target t′t' with t′∼tt' \sim t, and the induction hypothesis for the remaining merges gives T(cls(x))∼t′∼tT(cls(x)) \sim t' \sim t. □\square

Lemma 2 (a pending copy is not lost). If ASSIGN(x,y)(x, y) runs, then at the end either cls(y)cls(y) has no target, or both cls(x)cls(x) and cls(y)cls(y) have targets and T(cls(x))=T(cls(y))T(cls(x)) = T(cls(y)).

Proof. Let xx and yy be the roots when ASSIGN runs. If x=yx = y, there is nothing to show. If pt(y)pt(y) is set and pt(x)pt(x) is not, line L13 sets the target of xx to pt(y)pt(y), and Lemma 1, used for xx and for yy, gives T(cls(x))∼pt(y)∼T(cls(y))T(cls(x)) \sim pt(y) \sim T(cls(y)). If both are set, line L14 queues JOIN(pt(x),pt(y))(pt(x), pt(y)), and Lemma 1 again gives the claim. If pt(y)pt(y) is not set, line L12 puts xx on pending(y)pending(y). As long as the class of yy has no target, a merge with another class with no target keeps the entry on the joined list (line L16). The class of yy gets a target only in line L19 or line L17, and both queue ASSIGN(d,c)(d, c) for every dd on its list, with cc the root of the class of yy. That ASSIGN runs with pt(c)pt(c) set, so it falls in one of the cases above. If the class of yy never gets a target, then cls(y)cls(y) has none at the end. □\square

Theorem 1 (the result is a solution). SS meets every constraint of the program.

Proof. Take each statement form.

  • p = &a. Line L3 sets the target of pp to the class of aa, or line L4 queues JOIN(pt(p),a)(pt(p), a). By Lemma 1, T(cls(p))∼aT(cls(p)) \sim a, so a∈S(p)a \in S(p).
  • p = q. Line L5 runs ASSIGN(p,q)(p, q). If cls(q)cls(q) has no target, S(q)=∅S(q) = \emptyset. Otherwise, by Lemma 2, T(cls(p))=T(cls(q))T(cls(p)) = T(cls(q)) and S(p)=S(q)S(p) = S(q).
  • p = *q. Line L6 gets t=pt(q)t = pt(q) from DEREF, so T(cls(q))∼tT(cls(q)) \sim t by Lemma 1, and then runs ASSIGN(p,t)(p, t). Let a∈S(q)a \in S(q). Then cls(a)=T(cls(q))=cls(t)cls(a) = T(cls(q)) = cls(t). If this class has no target, S(a)=∅S(a) = \emptyset. Otherwise Lemma 2 gives T(cls(p))=T(cls(t))=T(cls(a))T(cls(p)) = T(cls(t)) = T(cls(a)), so S(a)=S(p)S(a) = S(p).
  • *p = q. Line L7 gets t=pt(p)t = pt(p), with T(cls(p))∼tT(cls(p)) \sim t, and runs ASSIGN(t,q)(t, q). Let a∈S(p)a \in S(p), so cls(a)=cls(t)cls(a) = cls(t). If cls(q)cls(q) has no target, S(q)=∅S(q) = \emptyset. Otherwise Lemma 2 gives T(cls(a))=T(cls(t))=T(cls(q))T(cls(a)) = T(cls(t)) = T(cls(q)), so S(q)=S(a)S(q) = S(a). □\square

Corollary (containment). L(v)⊆S(v)L(v) \subseteq S(v) for every variable vv: Steensgaard's sets contain Andersen's. This is the least-solution property of LL applied to the solution SS. In particular SS is sound for every run that executes the statements in any order, by the soundness argument of the Andersen page.

Unification. For any uu and vv, S(u)S(u) and S(v)S(v) are equal or disjoint, since each is one whole class of variables or empty. So two pointers whose sets meet always have the same set. This is the loss of precision against Andersen.

Theorem 2 (time). With linked lists for the pending lists, and union by rank with path compression, the algorithm takes O((n+m) α(n+m))O((n + m)\,\alpha(n + m)) time and O(n+m)O(n + m) space to compute the classes and their targets. Listing the sets S(v)S(v) costs their total size more.

Proof. There are at most n+mn + m classes: one per variable, and at most one fresh class per load or store, made in line L10. Count the operations.

  • Each statement runs one of lines L3 to L7: at most one SET-TARGET, one queued JOIN, one ASSIGN and two DEREF.
  • An ASSIGN puts an entry on a pending list at most once, and an entry is taken off once, when its class gets a target, and then gives one ASSIGN that cannot add to a pending list again, because the class it reads now has a target. So there are at most 2m2m ASSIGN operations, and each queues at most one JOIN.
  • A JOIN that merges two classes lowers the number of classes by one, so at most n+m−1n + m - 1 JOINs merge. Each queues at most one more JOIN in line L18. A JOIN that finds both arguments in one class does nothing else.
  • So the number of JOINs is at most mm from line L4, plus 2m2m from line L14, plus n+mn + m from line L18. The ASSIGNs queued by lines L17 and L20 number at most the pending entries, at most mm.

Every operation does O(1)O(1) finds and unions plus O(1)O(1) other work, since joining two linked lists is O(1)O(1). In total there are O(n+m)O(n + m) operations on the union-find forest, which cost O((n+m) α(n+m))O((n + m)\,\alpha(n + m)) by the bound of Tarjan for union by rank with path compression. The space is one record per class and one per pending entry. □\square

The implementation joins two pending lists by appending the shorter Python list to the longer one. An entry then moves only when its list at least doubles, so it moves O(log⁡m)O(\log m) times, and this part costs O(mlog⁡m)O(m \log m) in the worst case instead of O(m)O(m).

Complexity

Proved. There are at most n+mn + m classes, one per variable and one fresh class per load or store at most. Each statement queues O(1)O(1) operations; each pending entry is added once and fired once; each JOIN that merges removes a class and queues at most one more JOIN. So there are O(n+m)O(n + m) operations, each with O(1)O(1) finds and unions. With union by rank and path compression the total time is O((n+m) α(n+m))O((n + m)\,\alpha(n + m)), where α\alpha is the inverse Ackermann function, and the space is O(n+m)O(n + m). This assumes pending lists that join in O(1)O(1), such as linked lists; the implementation appends the shorter list to the longer, which costs O(mlog⁡m)O(m \log m) for that part. Writing out all the sets S(v)S(v) costs their total size, up to Θ(n2)\Theta(n^2), so a client should query the classes instead.

Stated in the paper, not proved here. Steensgaard states the bound O(Nα(N,N))O(N \alpha(N, N)) in the size NN of the program, for full C with structures and function pointers, and reports that the analysis of a C program of about 75,000 lines took about 27 seconds on an SGI Indigo2 workstation of the time.

Measured, not proved. In the seeded tests of the implementation, on 400 random programs of up to 30 statements, the sets of every variable contained Andersen's sets, and on 200 programs, three random orders of the statements each gave the same result.

Properties

  • Online. Each statement is read once, in any order, and the classes after a prefix of the statements are already correct for that prefix. The analysis can run while a compiler reads the program.
  • Sets are equal or disjoint. Two pointers that may point to one common location have the same set. This is what makes the result so small to store: one target per class.
  • Bidirectional loss. A copy p = q makes the targets of qq visible to pp and also the targets of pp visible to qq.
  • Not recursive in the code. The queue replaces the recursion of JOIN.
  • Result independent of the order. The tests found no case where the order of the statements changed the result.

Variants and improvements

  • One-level flow. Das's one-level flow keeps the subset direction for top-level copies, which are most of the copies in C, and unifies below that. Its precision is close to Andersen's at a cost close to Steensgaard's.
  • Fields. Steensgaard's paper treats a structure as one location. Later work gives each field its own class; see field sensitivity.
  • Context sensitivity. Unification works well with context sensitivity by cloning: the classes of a function are copied at each call, as the type of a polymorphic function is copied at each use.
  • Andersen's analysis. Andersen's analysis keeps the subset direction everywhere, for more precision and up to cubic time.
  • Type inference. The same union-find method solves the unification problem for first-order terms and the type equations of the Hindley-Milner type system.

When to use it

Use it when the program is very large or the analysis must run in a compile pass, and coarse sets are acceptable. It is a good first pass that tells which pointers can never alias, and it can split a program into parts that a more precise analysis then studies apart. When the clients need precise sets, such as call graphs through function pointers or alias queries for an optimizer, use Andersen's analysis or one-level flow.

Pitfalls

  • Joining on copies from pointers with no target. If p = q merges the targets of pp and qq even when qq has none yet, a placeholder target is made and later joined with real targets; the result is still sound but coarser. The pending lists avoid this.
  • Forgetting to join targets. When two classes merge, their targets must merge too. Without line L18 the classes no longer have one target each, and the result misses facts.
  • Reading sets as precise. Equal sets do not mean the two pointers were copied into each other. Unification merges along the whole chain of statements, as in the example, where qq gets aa.
  • Recursion depth. A program with a long chain of pointers to pointers gives a long chain of JOINs. A recursive JOIN can overflow the stack on such input.

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.

ptsgen.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""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
steensgaard_analysis.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/steensgaard-analysis/. The authors are listed in prov/EFB787.jsonl.
"""Steensgaard's unification-based points-to analysis.

steensgaard(stmts) takes statements in the four forms of ptsgen and returns
a dict from each variable to the set of variables it may point to. The
locations are split into classes kept in a union-find forest. Each class
has at most one target class, pt, or none (bottom). A copy p = q is a
conditional join: if q has no target yet, p is put on the pending list of
q, and the join waits until q gets a target. Joining two classes also joins
their targets. All the work goes through one queue of operations, so the
code has no recursion.

classes(stmts) returns the classes of the program variables and the target
class of each, for display.
"""

from collections import deque

import ptsgen


def _solve(stmts):
    names = ptsgen.variables(stmts)
    parent = {}
    rank = {}
    pt = {}  # target class of a root, or None for bottom
    pending = {}  # roots waiting for this root to get a target
    ops = deque()

    def make(key):
        parent[key] = key
        rank[key] = 0
        pt[key] = None
        pending[key] = []
        return key

    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 set_target(c, t):
        pt[c] = t  # @line L19
        for d in pending[c]:
            ops.append(("assign", d, c))  # @line L20
        pending[c] = []

    def deref(c):
        """The target class of c; a fresh class if c has none."""
        c = find(c)
        if pt[c] is None:
            set_target(c, make(("fresh", len(parent))))  # @line L10
        return find(pt[c])  # @line L11

    def assign(cx, cy):
        """The targets of cx must include those of cy."""
        cx, cy = find(cx), find(cy)
        if cx == cy:
            return
        if pt[cy] is None:
            pending[cy].append(cx)  # @line L12
        elif pt[cx] is None:
            set_target(cx, pt[cy])  # @line L13
        else:
            ops.append(("join", pt[cx], pt[cy]))  # @line L14

    def join(c1, c2):
        c1, c2 = find(c1), find(c2)
        if c1 == c2:
            return
        t1, t2, p1, p2 = pt[c1], pt[c2], pending[c1], pending[c2]
        if rank[c1] < rank[c2]:
            c1, c2 = c2, c1
        parent[c2] = c1  # @line L15
        if rank[c1] == rank[c2]:
            rank[c1] += 1
        c = c1
        pt[c], pending[c] = None, []
        if t1 is None and t2 is None:  # @line L16
            # Append the shorter list to the longer one; a linked list
            # would do this in O(1).
            longer, shorter = (p1, p2) if len(p1) >= len(p2) else (p2, p1)
            longer.extend(shorter)
            pending[c] = longer
        elif t1 is None or t2 is None:  # @line L17
            set_target(c, t1 if t1 is not None else t2)
            for d in p1 if t1 is None else p2:
                ops.append(("assign", d, c))
        else:
            pt[c] = t1  # @line L18
            ops.append(("join", t1, t2))

    for v in names:
        make(v)  # @line L1
    for kind, x, y in stmts:  # @line L2
        if kind == "addr":
            cx = find(x)
            if pt[cx] is None:
                set_target(cx, find(y))  # @line L3
            else:
                ops.append(("join", pt[cx], y))  # @line L4
        elif kind == "copy":
            assign(x, y)  # @line L5
        elif kind == "load":
            assign(x, deref(y))  # @line L6
        else:
            assign(deref(x), y)  # @line L7
        while ops:  # @line L8
            op, a, b = ops.popleft()
            if op == "assign":
                assign(a, b)
            else:
                join(a, b)
    return names, find, pt


def steensgaard(stmts):
    names, find, pt = _solve(stmts)
    members = {}
    for a in names:
        members.setdefault(find(a), set()).add(a)
    pts = {}
    for v in names:
        t = pt[find(v)]
        pts[v] = set() if t is None else set(members.get(find(t), ()))  # @line L9
    return pts


def classes(stmts):
    """The classes of the program variables, each a sorted list, and a dict
    from the index of each class to the index of its target class, if the
    target holds a program variable."""
    names, find, pt = _solve(stmts)
    by_root = {}
    for v in names:
        by_root.setdefault(find(v), []).append(v)
    roots = sorted(by_root, key=lambda r: sorted(by_root[r]))
    groups = [sorted(by_root[r]) for r in roots]
    index = {r: i for i, r in enumerate(roots)}
    target = {}
    for r in roots:
        t = pt[r]
        if t is not None and find(t) in index:
            target[index[r]] = index[find(t)]
    return groups, target


def points_to(text):
    return steensgaard(ptsgen.parse(text))
test_steensgaard_analysis.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/steensgaard-analysis/. The authors are listed in prov/EFB787.jsonl.

import random

import ptsgen
from steensgaard_analysis import classes, points_to, steensgaard

PAGE = """
entry:
  p = &a
  q = &b
  r = &p
  s = q
  *r = s
  t = *r
  ret 0
"""


def test_page_example():
    pts = points_to(PAGE)
    ab = {"a", "b"}
    assert pts == {"p": ab, "a": set(), "q": ab, "b": set(), "r": {"p"}, "s": ab, "t": ab}
    groups, target = classes(ptsgen.parse(PAGE))
    assert groups == [["a", "b"], ["p"], ["q"], ["r"], ["s"], ["t"]]
    assert target == {1: 0, 2: 0, 3: 1, 4: 0, 5: 0}


def test_copy_from_a_pointer_with_no_target_waits():
    # q has no target when p = q is seen; the join waits on the pending list
    # and happens when q = &b arrives. No placeholder is joined with b.
    pts = points_to("p = q\nq = &b")
    assert pts == {"p": {"b"}, "q": {"b"}, "b": set()}
    # A copy between two pointers that never get targets merges nothing.
    assert points_to("p = q\nr = &a") == {"p": set(), "q": set(), "r": {"a"}, "a": set()}


def test_unification_merges_targets():
    # Two different targets of one pointer end up in one class.
    pts = points_to("p = &a\np = &b\nq = &a")
    assert pts["q"] == {"a", "b"}


def test_store_and_load_through_unknown_targets():
    # *p = q before p has a target makes a placeholder class; p = &a later
    # joins a with it, so a gets the target of q.
    pts = points_to("*p = q\nq = &x\np = &a\nr = *p")
    assert pts["a"] == {"x"} and pts["r"] == {"x"}


def is_unification(pts):
    # Two sets are equal or disjoint, as in a storage graph where each
    # class points to at most one class.
    sets = [frozenset(s) for s in pts.values() if s]
    return all(a == b or not (a & b) for a in sets for b in sets)


def test_contains_andersen_on_random_programs():
    rng = random.Random(1996)
    for trial in range(400):
        stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
        pts = steensgaard(stmts)
        least = ptsgen.least_solution(stmts)
        for v in least:
            assert least[v] <= pts[v], ptsgen.show(stmts)
        assert ptsgen.is_solution(stmts, pts)
        assert is_unification(pts)


def test_order_of_statements_does_not_change_the_result():
    rng = random.Random(11)
    for trial in range(200):
        stmts = ptsgen.random_program(rng, rng.randint(2, 10), 30)
        first = steensgaard(stmts)
        for _ in range(3):
            shuffled = stmts[:]
            rng.shuffle(shuffled)
            assert steensgaard(shuffled) == first, ptsgen.show(stmts)


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


def test_long_chain_needs_no_recursion():
    # p0 = &p1, p1 = &p2, ..., and a copy that joins the two ends of the
    # chain; the joins run through the queue, not the call stack.
    n = 3000
    lines = ["p%d = &p%d" % (i, i + 1) for i in range(n)]
    lines += ["q%d = &p%d" % (i, i) for i in range(1, n, 2)]
    lines += ["x = q1", "x = q%d" % (n - 1)]
    pts = points_to("\n".join(lines))
    assert pts["x"] == pts["q1"] and "p1" in pts["x"] and "p%d" % (n - 1) in pts["x"]

History

Bjarne Steensgaard presented the analysis at POPL 1996, as an answer to the cubic cost of Andersen's analysis. He described it as type inference with a non-standard type system for C and solved it with union-find, the method of type inference for ML-like languages. The conditional join with pending sets was his device to avoid merging classes for copies of pointers that never point anywhere. Das (2000) showed that keeping the direction at the top level gives most of Andersen's precision at almost the same cost. Unification remains the basis of fast analyses in compilers and of context-sensitive analyses by cloning.

References

  1. Bjarne Steensgaard, Points-to analysis in almost linear time, Proceedings of the 23rd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '96), 32 to 41, 1996, the non-standard type system for C, the equivalence class representatives with fast union-find, the conditional join with pending sets, the O(N α(N, N)) bound and the timings on C programs
  2. Manuvir Das, Unification-based pointer analysis with directional assignments, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2000), 35 to 46, the comparison of the precision of Steensgaard's analysis, one-level flow and Andersen's analysis on C programs
  3. 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 place of unification-based analyses among the flow-insensitive analyses
  4. Yannis Smaragdakis and George Balatsouras, Pointer Analysis, Foundations and Trends in Programming Languages 2(1), 1 to 69, 2015, the comparison of unification-based and inclusion-based analyses
  5. Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, fourth edition, Chapter 19 (data structures for disjoint sets, union by rank with path compression)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/EFB787/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