Algorithm Search⌘K

Algorithmresearch

Sparse flow-sensitive pointer analysis

Also called staged flow-sensitive pointer analysis.

Makes flow-sensitive points-to analysis scale by propagating facts only along def-use chains found by a cheaper pre-analysis.

Time
O(n^3 m^4) worst
Space
O(n^2 m + n m^2) extra
Where
m = the number of names; n = the number of nodes and edges of the control flow graph
Properties
not context sensitivedeterministicflow sensitiveofflineiterative
Origin
Ben Hardekopf, Calvin Lin, 2011

A sparse flow-sensitive pointer analysis computes a points-to set for each variable at each program point, like the dense flow-sensitive analysis, but it moves a set only from the node that defines it to the nodes that use it. For top-level variables these def-use chains are easy to find. For memory reached through pointers they depend on the result being computed. The staged analysis of Hardekopf and Lin (2011) breaks this cycle with a cheap first stage: Andersen's analysis gives a sound over-approximation of what each store may write and each load may read, and that gives def-use chains that are safe to use. The second stage then runs the flow-sensitive transfer functions, with strong updates, along those chains only. The result is exactly the dense result at every place where a variable is used.

In plain words

A flow-sensitive analysis knows that a pointer pointed to one thing before a line and to another thing after it. The plain way to do this keeps a full table of every pointer at every line and copies the table from line to line. Most entries never change on the way, so most of that copying is wasted. The sparse way sends each new fact straight from the line that makes it to the lines that read it. The hard part is knowing which lines read a fact written through a pointer. A fast first pass that ignores the order of statements answers that safely, because it can only say "maybe" too often, never too rarely. The second pass then follows those links and gets the same answers as the full table.

The problem

The input is a control flow graph whose nodes hold statements of four forms: x=&ax = \&a, x=yx = y, x=∗yx = {*}y and ∗x=y{*}x = y, with node 00 as the entry. A name of the form h1,h2,…h_1, h_2, \ldots is a heap location that stands for every object made at one allocation site. The output is, for each reachable node uu and each name ww that uu may read, the set INu(w)IN_u(w) of names that ww may point to just before uu, and the set OUTd(v)OUT_d(v) just after each node dd for each name vv that dd may define. Here AA is Andersen's result, and DEF(n)DEF(n) and USE(n)USE(n) are the names that nn may define and read according to AA.

item value
direction forward
may or must may
domain maps from pairs (node, name) on def-use edges to subsets of the names, each inside the Andersen set of the name
order pointwise inclusion (bottom is precise)
join union over the def-use edges into a node
bottom and top every set empty, and every name mapped to its Andersen set
boundary value at the entry no name points to anything
initial value every out(d,v)out(d, v) is empty
transfer x=&ax = \&a gives {a}\{a\}, a copy and a load give the usual sets, and a store gives a strong update to a single target that is not a heap name and a weak update otherwise

The algorithm

  1. SPARSE-FS(S, G)
  2. 1A = ANDERSEN(S)
  3. 2for each node n reachable from the entry, compute DEF(n) and USE(n) with A
  4. 3for each reachable node d and each v in DEF(d) do
  5. 4add an edge d -v-> u for each node u with v in USE(u) that some path reaches from d with no node strictly between them that may define v
  6. 5set every out(d, v) to the empty set and put every reachable node on the worklist W
  7. 6while W is not empty do
  8. 7take a node n from W
  9. 8for each w in USE(n), in(w) = the union of out(d, w) over the edges d -w-> n
  10. 9for each v in DEF(n), new = TRANSFER(n, v, in)
  11. 10if new differs from out(n, v) then out(n, v) = new and put every u with an edge n -v-> u on W
  12. 11return out, and in(w) at each node for each w in USE of the node
  13. TRANSFER(n, v, in)
  14. 12x = &a gives {a}; x = y gives in(y); x = *y gives the union of in(b) for b in in(y)
  15. for a store *x = y:
  16. 13if in(x) is empty then return the empty set
  17. 14if in(x) = {v} and v is not a heap name then return in(y)
  18. 15if v is in in(x) then return in(v) ∪ in(y) else return in(v)

For a node nn, DEF(n)DEF(n) is {x}\{x\} for the first three forms and A(x)A(x) for a store ∗x=y{*}x = y. USE(n)USE(n) is empty for x=&ax = \&a, {y}\{y\} for a copy, {y}∪A(y)\{y\} \cup A(y) for a load and {x,y}∪A(x)\{x, y\} \cup A(x) for a store. The search of line L4 is a depth-first search from the successors of dd that records each node using vv and stops at each node that may define vv. A store defines every name that its pointer may point to by Andersen's result, so a weak update at a store passes the old value on through line L15.

Line L14 is the strong update. When the pointer points to exactly one name, and that name is one concrete location, the store overwrites it, so the old value is dropped. Line L13 handles a store whose pointer points to nothing yet. Such a store cannot run, so its output is empty. This keeps TRANSFER monotone: if line L13 kept the old value, a later strong update could make the output smaller, and the result would depend on the order of the worklist.

Example

0: p = &a
1: x = &p
2: t = *x
3: q = &b
4: *x = q
5: r = *x
6: s = p

The nodes form one straight path. Andersen's analysis gives A(x)={p}A(x) = \{p\}, A(p)=A(t)=A(r)=A(s)={a,b}A(p) = A(t) = A(r) = A(s) = \{a, b\} and A(q)={b}A(q) = \{b\}. So the store at node 4 may define only pp, and the loads at nodes 2 and 5 may read xx and pp.

def-use edge why
0→p20 \xrightarrow{p} 2, 0→p40 \xrightarrow{p} 4 node 4 may define pp, so the search stops there
1→x21 \xrightarrow{x} 2, 1→x41 \xrightarrow{x} 4, 1→x51 \xrightarrow{x} 5 no other node defines xx
3→q43 \xrightarrow{q} 4 the store reads qq
4→p54 \xrightarrow{p} 5, 4→p64 \xrightarrow{p} 6 the store gives the new value of pp

The worklist gives out(0,p)={a}out(0, p) = \{a\} and out(1,x)={p}out(1, x) = \{p\}, so node 2 gets t={a}t = \{a\}. At node 4, in(x)={p}in(x) = \{p\} is one name and not a heap name, so line L14 gives out(4,p)=in(q)={b}out(4, p) = in(q) = \{b\}. Node 5 reads pp through the edge from node 4 and gets r={b}r = \{b\}, and node 6 gets s={b}s = \{b\}. Andersen's analysis alone gives {a,b}\{a, b\} for tt, rr and ss. If xx pointed to a heap name h1h_1 instead, line L15 would keep the old value, and a later load would see both the old and the new value.

Correctness

The proof file shows four facts. First, TRANSFER keeps every set inside the Andersen set of its name and is monotone, because a store with an empty pointer set gives the empty set. Second, a node changes only names in its DEF set and reads only names in its USE set, both computed from the sound Andersen result. Third, the least solution of the sparse equations is equal to the dense flow-sensitive least solution on every def-use pair. One direction restricts the dense solution to the def-use pairs and shows that it satisfies the sparse equations. The other direction extends the sparse solution to every node by the reaching definitions and shows that it satisfies the dense equations. Fourth, every concrete run is covered: a strong update is applied only when the pointer can hold one location, and a heap name, which stands for many objects, gets only weak updates.

Proof: The sparse analysis computes exactly the sets of the dense flow-sensitive analysis on its def-use pairs, and both are inside Andersen's resultfull

Setting. The program is a control flow graph whose nodes NN are the nodes reachable from the entry 00. Each node nn holds one statement x=&ax = \&a, x=yx = y, x=∗yx = {*}y or ∗x=y{*}x = y. Names\mathit{Names} is the set of all names, and a name that matches h<digits> is a heap name. AA is Andersen's least solution of the four inclusion rules for all statements (the Andersen page). A state SS maps every name to a set of names. LAL_A is the set of states with S(w)⊆A(w)S(w) \subseteq A(w) for every ww. Ordered by pointwise inclusion, LAL_A is a finite complete lattice.

The dense analysis. For a node nn and a state SS, Fn(S)F_n(S) is SS with these changes:

  1. x=&ax = \&a: x↦{a}x \mapsto \{a\};
  2. x=yx = y: x↦S(y)x \mapsto S(y);
  3. x=∗yx = {*}y: x↦⋃b∈S(y)S(b)x \mapsto \bigcup_{b \in S(y)} S(b);
  4. ∗x=y{*}x = y, with X=S(x)X = S(x): if X=∅X = \emptyset, every b∈A(x)b \in A(x) maps to ∅\emptyset; if X={b}X = \{b\} and bb is not a heap name, b↦S(y)b \mapsto S(y); otherwise every b∈Xb \in X maps to S(b)∪S(y)S(b) \cup S(y).

The dense equations are IN0⊇⊥IN_0 \supseteq \bot, INn=⋃p∈pred(n)OUTpIN_n = \bigcup_{p \in pred(n)} OUT_p and OUTn=Fn(INn)OUT_n = F_n(IN_n), where ⊥\bot maps every name to ∅\emptyset. The dense result DD is their least solution in LAL_A.

DEF, USE and def-use edges. DEF(n)DEF(n) is {x}\{x\} for the first three forms and A(x)A(x) for a store. USE(n)USE(n) is ∅\emptyset, {y}\{y\}, {y}∪A(y)\{y\} \cup A(y) and {x,y}∪A(x)\{x, y\} \cup A(x) for the four forms. A node dd reaches uu for ww if there is a path d=m0→m1→⋯→mk=ud = m_0 \to m_1 \to \cdots \to m_k = u with k≥1k \ge 1 and w∉DEF(mi)w \notin DEF(m_i) for 0<i<k0 < i < k. The edge d→wud \xrightarrow{w} u exists when w∈DEF(d)w \in DEF(d), w∈USE(u)w \in USE(u) and dd reaches uu for ww. The search of lines L3 and L4 finds exactly these: it starts at the successors of dd, records a visited uu when w∈USE(u)w \in USE(u), and goes on past uu only when w∉DEF(u)w \notin DEF(u).

The sparse analysis. Its unknowns are out(d,v)out(d, v) for d∈Nd \in N and v∈DEF(d)v \in DEF(d). For a node uu and w∈USE(u)w \in USE(u), inu(w)=⋃{out(d,w):d→wu}in_u(w) = \bigcup \{ out(d, w) : d \xrightarrow{w} u \}. The sparse equations are out(d,v)=Fd(ind)(v)out(d, v) = F_d(in_d)(v), where indin_d is extended to a state by ∅\emptyset outside USE(d)USE(d). The sparse result PP is their least solution with every out(d,v)⊆A(v)out(d, v) \subseteq A(v).

Lemma 1 (closure and monotonicity). Each FnF_n maps LAL_A into LAL_A and is monotone on LAL_A.

Proof. Let S∈LAS \in L_A. Rule 1 gives {a}⊆A(x)\{a\} \subseteq A(x). Rule 2 gives S(y)⊆A(y)⊆A(x)S(y) \subseteq A(y) \subseteq A(x). In rule 3, b∈S(y)⊆A(y)b \in S(y) \subseteq A(y), so S(b)⊆A(b)⊆A(x)S(b) \subseteq A(b) \subseteq A(x) by Andersen's load rule. In rule 4, X⊆A(x)X \subseteq A(x), so every written bb is in A(x)A(x), and S(y)⊆A(y)⊆A(b)S(y) \subseteq A(y) \subseteq A(b) by Andersen's store rule. So Fn(S)∈LAF_n(S) \in L_A.

For monotonicity, only rule 4 needs care. Let S⊆S′S \subseteq S' in LAL_A, with X=S(x)⊆X′=S′(x)X = S(x) \subseteq X' = S'(x), and fix a name bb. If b∉A(x)b \notin A(x), then b∉X′b \notin X' and bb is unchanged in both. Let b∈A(x)b \in A(x). The value of bb is ∅\emptyset if X=∅X = \emptyset, S(y)S(y) if X={b}X = \{b\} with bb not a heap name, S(b)∪S(y)S(b) \cup S(y) if b∈Xb \in X otherwise, and S(b)S(b) if b∉X≠∅b \notin X \neq \emptyset. Going from XX to the larger X′X' moves only from the empty case to any case, from the second case to the third, or from the fourth case to the third, and each of these moves gives a superset. With S⊆S′S \subseteq S' the sets S(y)S(y) and S(b)S(b) only grow. □\square

Lemma 2 (locality). For S∈LAS \in L_A, Fn(S)(w)=S(w)F_n(S)(w) = S(w) for w∉DEF(n)w \notin DEF(n), and Fn(S)(v)F_n(S)(v) for v∈DEF(n)v \in DEF(n) depends only on SS restricted to USE(n)USE(n).

Proof. The first three rules change only xx. They read yy, and rule 3 also reads b∈S(y)⊆A(y)b \in S(y) \subseteq A(y). Rule 4 changes only names in X⊆A(x)X \subseteq A(x) or in A(x)A(x), and it reads xx, yy and b∈A(x)b \in A(x). All of these are in USE(n)USE(n). □\square

Lemma 3 (both results exist and are computed). DD and PP exist. The round-robin iteration of the dense equations from ⊥\bot reaches DD, and the worklist of lines L5 to L10 stops with PP.

Proof. By Lemma 1 the dense equations define a monotone map on the finite lattice LAN×LANL_A^{N} \times L_A^{N}, so its least fixed point exists and is the limit of the iteration from the bottom (Kleene). The sparse map is monotone by Lemma 1 and keeps every out(d,v)⊆A(v)out(d, v) \subseteq A(v), so the same holds for it. The worklist starts with every node, so each equation is evaluated at least once. A value only changes to a larger set, by induction with monotonicity, so there are finitely many changes, and each change puts every user of that value on the worklist. When the worklist is empty, each node was last evaluated after its last input changed, so every equation holds. Every value it computes is inside every solution, by induction over the steps, so the result is the least one. □\square

Lemma 4 (paths carry values). If dd reaches uu for ww and w∈DEF(d)w \in DEF(d), then OUTd(w)⊆INu(w)OUT_d(w) \subseteq IN_u(w) in DD.

Proof. Along the path d=m0→⋯→mk=ud = m_0 \to \cdots \to m_k = u, OUTmi(w)⊆INmi+1(w)OUT_{m_{i}}(w) \subseteq IN_{m_{i+1}}(w) by the join, and OUTmi(w)=INmi(w)OUT_{m_i}(w) = IN_{m_i}(w) for 0<i<k0 < i < k by Lemma 2, since w∉DEF(mi)w \notin DEF(m_i). □\square

Theorem 1 (sparse equals dense). For every d∈Nd \in N and v∈DEF(d)v \in DEF(d), P(d,v)=OUTd(v)P(d, v) = OUT_d(v) in DD. For every u∈Nu \in N and w∈USE(u)w \in USE(u), inu(w)in_u(w) computed from PP equals INu(w)IN_u(w) in DD.

Proof. Sparse inside dense. Let R(d,v)=OUTd(v)R(d, v) = OUT_d(v) from DD. Then for w∈USE(d)w \in USE(d), indR(w)=⋃e→wdOUTe(w)⊆INd(w)in^R_d(w) = \bigcup_{e \xrightarrow{w} d} OUT_e(w) \subseteq IN_d(w) by Lemma 4. By Lemmas 1 and 2, Fd(indR)(v)⊆Fd(INd)(v)=OUTd(v)=R(d,v)F_d(in^R_d)(v) \subseteq F_d(IN_d)(v) = OUT_d(v) = R(d, v). So RR satisfies every sparse equation with ⊆\subseteq, and since the least fixed point of a monotone map is below every such point (Knaster and Tarski), P⊆RP \subseteq R.

Dense inside sparse. Build the state EE from PP: INuE(w)IN^E_u(w) is the union of P(d,w)P(d, w) over all dd that reach uu for ww with w∈DEF(d)w \in DEF(d), and OUTnE(w)OUT^E_n(w) is P(n,w)P(n, w) for w∈DEF(n)w \in DEF(n) and INnE(w)IN^E_n(w) otherwise. All its sets are inside AA. Check the dense equations with ⊇\supseteq. For the join at uu, take a predecessor pp. If w∈DEF(p)w \in DEF(p), then pp reaches uu for ww by the path p→up \to u, so OUTpE(w)⊆INuE(w)OUT^E_p(w) \subseteq IN^E_u(w). If not, OUTpE(w)=INpE(w)OUT^E_p(w) = IN^E_p(w), and every dd that reaches pp for ww also reaches uu for ww, through pp. For the transfer at nn and w∉DEF(n)w \notin DEF(n), Fn(INnE)(w)=INnE(w)=OUTnE(w)F_n(IN^E_n)(w) = IN^E_n(w) = OUT^E_n(w) by Lemma 2. For v∈DEF(n)v \in DEF(n), INnEIN^E_n agrees with innPin^P_n on USE(n)USE(n), because the edges into nn are exactly the reaching definitions of the names in USE(n)USE(n). So by Lemma 2, Fn(INnE)(v)=Fn(innP)(v)=P(n,v)=OUTnE(v)F_n(IN^E_n)(v) = F_n(in^P_n)(v) = P(n, v) = OUT^E_n(v). So EE satisfies the dense equations with ⊇\supseteq, and D⊆ED \subseteq E.

Now for v∈DEF(d)v \in DEF(d): OUTd(v)⊆OUTdE(v)=P(d,v)⊆R(d,v)=OUTd(v)OUT_d(v) \subseteq OUT^E_d(v) = P(d, v) \subseteq R(d, v) = OUT_d(v). For w∈USE(u)w \in USE(u): INu(w)⊆INuE(w)=inuP(w)IN_u(w) \subseteq IN^E_u(w) = in^P_u(w), and inuP(w)=⋃OUTe(w)⊆INu(w)in^P_u(w) = \bigcup OUT_e(w) \subseteq IN_u(w) by the first part and Lemma 4. □\square

Theorem 2 (inside Andersen, and sound). Every set of DD, and so every set of PP, is inside Andersen's set for the same name. For every run that starts at the entry with no values and follows the graph, the state before each node is covered by ININ: if location ℓ\ell holds a pointer to ℓ′\ell', then the name of ℓ′\ell' is in INn(name of ℓ)IN_n(\text{name of } \ell).

Proof. The first part is D∈LAD \in L_A. For soundness, use induction on the length of the run. At the entry nothing holds a value. For one step through node nn, the cases of rules 1 to 3 follow the concrete step. For a store ∗x=y{*}x = y that runs, xx holds a location whose name bb is in X=INn(x)X = IN_n(x), so X≠∅X \neq \emptyset. If X={b}X = \{b\} and bb is not a heap name, then bb is the only location with that name, the store overwrites it, and the new value is covered by INn(y)IN_n(y). Otherwise the written location keeps a value covered by INn(b)∪INn(y)IN_n(b) \cup IN_n(y). Other locations do not change. The empty case never runs, so its value does not matter for soundness. A heap name stands for every object created at its allocation statement, so it only gets weak updates. □\square

Theorem 3 (cost). Let nn be the number of nodes and edges of the graph and mm the number of names. Building the def-use edges takes O(n2m)O(n^2 m) time after Andersen's analysis, there are at most n2mn^2 m of them, and the worklist runs in O(n3m4)O(n^3 m^4) time. The space is O(n2m+nm2)O(n^2 m + n m^2).

Proof. There are at most nmn m pairs (d,v)(d, v), and each search visits each node and edge once, so the edges cost O(n2m)O(n^2 m) and number at most n⋅n⋅mn \cdot n \cdot m. Each out(d,v)out(d, v) is a subset of A(v)A(v) and only grows, so it changes at most mm times, and each change queues at most nn users. So there are at most n+n2m2n + n^2 m^2 visits. A visit computes at most mm values, and each reads at most mm inputs, each a union over at most nn sources of sets of size at most mm, so it costs O(nm2)O(n m^2). The product is O(n3m4)O(n^3 m^4). The space holds the edges and at most nmn m sets of size at most mm. ■\blacksquare

Complexity

Proved. Let nn be the number of nodes and edges and mm the number of names. After Andersen's analysis, building the def-use edges takes O(n2m)O(n^2 m) time, with at most n2mn^2 m edges. Each value out(d,v)out(d, v) only grows inside A(v)A(v), so it changes at most mm times, and the worklist makes at most n+n2m2n + n^2 m^2 visits of O(nm2)O(n m^2) each. That gives O(n3m4)O(n^3 m^4) time and O(n2m+nm2)O(n^2 m + n m^2) space. This bound is loose. The point of the method is that real programs have far fewer def-use edges than the worst case.

Stated in the literature. Hardekopf and Lin report that the staged analysis handles C programs of up to millions of lines of code, as the title of their paper says, and that it is much faster and uses much less memory than their earlier semi-sparse analysis.

Measured, not proved. On 400 random programs with up to 25 nodes and 8 names (seed 2011), the sparse result equals the dense result at every def-use pair. The sparse analysis stored 7936 points-to facts where the dense tables stored 33568, which is 24%. Of the 525 reachable stores, 81 got a strong update. On 300 programs (seed 2004), every dense set is inside the Andersen set, and some are strictly smaller. On 300 programs (seed 2003), every fact of a random concrete run is in the result.

Properties

  • Exact with respect to the dense analysis. The sparse result is not an approximation of the dense flow-sensitive result: at each use the sets are the same.
  • As precise as its strong updates allow. It is more precise than Andersen's analysis only because of the order of statements and the strong updates of line L14.
  • The first stage limits the cost, not the result. A less precise first stage gives larger DEF and USE sets and more def-use edges, so more work, but the answers stay the same as long as the first stage is sound.
  • Flow-sensitive, not context-sensitive. Calls are handled through the call graph, with one set per variable and node for all contexts.

Variants and improvements

  • Semi-sparse analysis. Hardekopf and Lin's earlier analysis (2009) puts only the top-level variables, whose address is never taken, in SSA form and still propagates the address-taken variables densely.
  • Memory SSA. The def-use edges of line L4 for address-taken variables are usually built by putting the program in SSA form for memory, with a may-definition at each store and a may-use at each load for the names that Andersen's result gives. This gives fewer edges than one edge from each definition to each use.
  • Access equivalence. Names whose def-use chains are the same can share one set of edges, which saves memory on large programs.
  • A cheaper first stage. Steensgaard's analysis can replace Andersen's analysis as the first stage. It is faster but gives more def-use edges.
  • Fields and contexts. The same staging works with field-sensitive names and with a context-sensitive first stage.

When to use it

Use it when a client needs flow-sensitive precision, for example strong updates for a bug checker or for proving that a pointer is not null at a point, on a program that is too large for the dense analysis. When flow-insensitive precision is enough, Andersen's analysis alone is cheaper. When only a few variables matter, a demand-driven analysis may be cheaper still.

Pitfalls

  • Strong updates on heap names. A version of line L14 without the test "v is not a heap name" overwrites a heap location that stands for many objects. For q0=&aq_0 = \&a, x=&h1x = \&h_1, ∗x=q0{*}x = q_0, q=&bq = \&b, ∗x=q{*}x = q, r=∗xr = {*}x it gives r={b}r = \{b\} instead of {a,b}\{a, b\}, which misses a real value. The right line L14 updates strongly only a name for one concrete location.
  • Keeping the old value at a store that cannot run. A version of line L13 that returns in(v)in(v) when in(x)in(x) is empty makes TRANSFER non-monotone, because a later strong update gives a smaller set. The result then depends on the order of the worklist. The right line L13 returns the empty set.
  • Stopping the search at a use. A version of line L4 that stops at the first node that uses vv misses later uses on the same path. The right search records a node that uses vv and goes on past it, and stops only at a node that may define vv.
  • An unsound first stage. If the first stage misses a target of a store, the store does not appear in DEF for that name and the def-use edges skip it. The first stage must be sound for every statement of the program.
  • Calling it sound with reflection or native code. Like every whole-program pointer analysis, it covers only the statements it sees. Code loaded, generated or called through native interfaces needs a model.

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
sparse_flow_sensitive_pointer_analysis.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-flow-sensitive-pointer-analysis/. The authors are listed in prov/9J9RX5.jsonl.
"""Staged sparse flow-sensitive points-to analysis, after Hardekopf and Lin.

A program is (stmts, succ): stmts[i] is the statement of node i 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 succ[i] lists the successors of node i
in the control flow graph. Node 0 is the entry. A name that matches h<digits>
is a heap location that stands for many objects, so it never gets a strong
update. At the entry every pointer points to nothing.

sparse_fs(stmts, succ) runs three stages:
1. andersen(stmts), the flow-insensitive auxiliary analysis;
2. DEF and USE sets for each node, computed with the auxiliary result, and
   the def-use edges: d -v-> u when d may define v, u may use v, and some
   path of the graph goes from d to u with no node strictly between them
   that may define v;
3. a worklist that recomputes a node only when one of its inputs changed,
   and sends a changed value along the def-use edges of that variable only.

It returns (ins, outs, users): ins[(u, v)] is the points-to set of v just
before node u, for every reachable u and v in USE(u); outs[(d, v)] is the set
of v just after node d, for v in DEF(d); users[(d, v)] lists the nodes u of
the def-use edges d -v-> u.
"""

import re
from collections import deque

HEAP = re.compile(r"h\d+")


def is_heap(a):
    return HEAP.fullmatch(a) is not None


def andersen(stmts):
    """Andersen's analysis by a constraint graph with difference propagation,
    the solver of the Andersen page."""
    names = {}
    for _, x, y in stmts:
        names.setdefault(x, None)
        names.setdefault(y, None)
    pts = {v: set() for v in names}
    succ = {v: set() for v in names}
    delta = {v: set() for v in names}
    loads = {v: set() for v in names}
    stores = {v: set() for v in names}
    work = deque()
    queued = set()

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

    def propagate(s, v):
        new = s - pts[v]
        if new:
            pts[v] |= new
            delta[v] |= new
            push(v)

    def add_edge(u, v):
        if v not in succ[u]:
            succ[u].add(v)
            propagate(pts[u], v)

    for kind, x, y in stmts:
        if kind == "addr":
            pts[x].add(y)
            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)
    while work:
        n = work.popleft()
        queued.discard(n)
        d = delta[n]
        delta[n] = set()
        for a in d:
            for p in loads[n]:
                add_edge(a, p)
            for q in stores[n]:
                add_edge(q, a)
        for w in list(succ[n]):
            propagate(d, w)
    return pts


def reachable(succ):
    seen = {0}
    stack = [0]
    while stack:
        n = stack.pop()
        for m in succ[n]:
            if m not in seen:
                seen.add(m)
                stack.append(m)
    return sorted(seen)


def def_use(stmt, aux):
    """The locations that the statement may define and may read."""
    kind, x, y = stmt
    if kind == "addr":
        return {x}, set()
    if kind == "copy":
        return {x}, {y}
    if kind == "load":
        return {x}, {y} | aux.get(y, set())
    return set(aux.get(x, ())), {x, y} | aux.get(x, set())


def transfer(stmt, v, get):
    """The new set of v after the statement, for v in DEF; get(w) gives the
    set of w before it."""
    kind, x, y = stmt
    if kind == "addr":
        return frozenset([y])  # @line L12
    if kind == "copy":
        return get(y)
    if kind == "load":
        out = set()
        for b in get(y):
            out |= get(b)
        return frozenset(out)
    targets = get(x)
    if not targets:
        return frozenset()  # @line L13
    if targets == {v} and not is_heap(v):
        return get(y)  # @line L14
    if v in targets:
        return get(v) | get(y)  # @line L15
    return get(v)


def sparse_fs(stmts, succ):
    aux = andersen(stmts)  # @line L1
    nodes = reachable(succ)
    defs, uses = {}, {}
    for n in nodes:
        defs[n], uses[n] = def_use(stmts[n], aux)  # @line L2
    users, sources = {}, {}
    for d in nodes:
        for v in defs[d]:  # @line L3
            found = []
            seen = set()
            stack = list(succ[d])
            while stack:
                u = stack.pop()
                if u in seen:
                    continue
                seen.add(u)
                if v in uses[u]:
                    found.append(u)  # @line L4
                if v not in defs[u]:
                    stack.extend(succ[u])
            users[(d, v)] = sorted(found)
            for u in found:
                sources.setdefault((u, v), []).append(d)
    outs = {(d, v): frozenset() for d in nodes for v in defs[d]}

    def read(n):
        def get(w):
            s = set()
            for d in sources.get((n, w), ()):
                s |= outs[(d, w)]
            return frozenset(s)

        return get

    work = deque(nodes)  # @line L5
    queued = set(nodes)
    while work:  # @line L6
        n = work.popleft()  # @line L7
        queued.discard(n)
        get = read(n)  # @line L8
        for v in sorted(defs[n]):
            new = transfer(stmts[n], v, get)  # @line L9
            if new != outs[(n, v)]:
                outs[(n, v)] = new  # @line L10
                for u in users[(n, v)]:
                    if u not in queued:
                        queued.add(u)
                        work.append(u)
    ins = {(u, w): read(u)(w) for u in nodes for w in uses[u]}
    return ins, outs, users  # @line L11
test_sparse_flow_sensitive_pointer_analysis.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-flow-sensitive-pointer-analysis/. The authors are listed in prov/9J9RX5.jsonl.

import random

import ptsgen
from sparse_flow_sensitive_pointer_analysis import andersen, is_heap, reachable, sparse_fs

EMPTY = frozenset()


def dense(stmts, succ, aux):
    """The dense flow-sensitive reference: a full map from every name to its
    set before and after every reachable node, by round-robin iteration. A
    store writes the locations that its pointer may point to here, with a
    strong update for one location that is not a heap name. A store whose
    pointer points to nothing cannot run; it gives the empty set to the
    locations it may write by the auxiliary analysis aux."""
    nodes = reachable(succ)
    names = ptsgen.variables(stmts)
    preds = {n: [] for n in nodes}
    for n in nodes:
        for m in succ[n]:
            preds[m].append(n)
    IN = {n: {v: EMPTY for v in names} for n in nodes}
    OUT = {n: {v: EMPTY for v in names} for n in nodes}
    changed = True
    while changed:
        changed = False
        for n in nodes:
            inn = {v: frozenset().union(*(OUT[p][v] for p in preds[n])) for v in names}
            out = dict(inn)
            kind, x, y = stmts[n]
            if kind == "addr":
                out[x] = frozenset([y])
            elif kind == "copy":
                out[x] = inn[y]
            elif kind == "load":
                out[x] = frozenset().union(*(inn[b] for b in inn[y]))
            elif not inn[x]:
                for b in aux[x]:
                    out[b] = EMPTY
            elif len(inn[x]) == 1 and not is_heap(next(iter(inn[x]))):
                out[next(iter(inn[x]))] = inn[y]
            else:
                for b in inn[x]:
                    out[b] = inn[b] | inn[y]
            if inn != IN[n] or out != OUT[n]:
                IN[n], OUT[n] = inn, out
                changed = True
    return IN, OUT


def line(succ_count):
    return [[i + 1] for i in range(succ_count - 1)] + [[]]


PAGE = [
    ("addr", "p", "a"),
    ("addr", "x", "p"),
    ("load", "t", "x"),
    ("addr", "q", "b"),
    ("store", "x", "q"),
    ("load", "r", "x"),
    ("copy", "s", "p"),
]


def test_page_example_strong_update():
    succ = line(len(PAGE))
    ins, outs, users = sparse_fs(PAGE, succ)
    assert outs[(2, "t")] == {"a"}
    assert outs[(4, "p")] == {"b"}
    assert outs[(5, "r")] == {"b"}
    assert outs[(6, "s")] == {"b"}
    assert users[(0, "p")] == [2, 4]
    assert users[(4, "p")] == [5, 6]
    aux = andersen(PAGE)
    assert aux["t"] == aux["r"] == {"a", "b"}


def test_heap_location_gets_a_weak_update():
    stmts = [("addr", "q0", "a"), ("addr", "x", "h1"), ("store", "x", "q0"), ("addr", "q", "b"), ("store", "x", "q"), ("load", "r", "x")]
    _, outs, _ = sparse_fs(stmts, line(len(stmts)))
    assert outs[(5, "r")] == {"a", "b"}


def test_branches_join():
    stmts = [("addr", "x", "p"), ("addr", "q", "a"), ("addr", "q", "b"), ("store", "x", "q"), ("load", "r", "x")]
    succ = [[1, 2], [3], [3], [4], []]
    ins, outs, _ = sparse_fs(stmts, succ)
    assert ins[(3, "q")] == {"a", "b"}
    assert outs[(4, "r")] == {"a", "b"}


def test_unreachable_nodes_are_ignored():
    stmts = [("addr", "p", "a"), ("addr", "p", "b"), ("copy", "r", "p")]
    succ = [[2], [2], []]
    ins, outs, _ = sparse_fs(stmts, succ)
    assert ins[(2, "p")] == {"a"}
    assert (1, "p") not in outs


def random_cfg(rng, nvars, nnodes):
    stmts = []
    for kind, x, y in ptsgen.random_program(rng, nvars, nnodes):
        if kind == "addr" and rng.random() < 0.35:
            y = "h%d" % rng.randint(1, 2)
        stmts.append((kind, x, y))
    succ = []
    for i in range(nnodes):
        out = []
        if i + 1 < nnodes and rng.random() < 0.85:
            out.append(i + 1)
        if rng.random() < 0.3:
            out.append(rng.randrange(nnodes))
        succ.append(sorted(set(out)))
    return stmts, succ


def programs(seed, count, nvars=(2, 8), nnodes=(1, 25)):
    rng = random.Random(seed)
    for _ in range(count):
        yield rng, random_cfg(rng, rng.randint(*nvars), rng.randint(*nnodes))


def test_sparse_equals_dense():
    for _, (stmts, succ) in programs(2011, 400):
        aux = andersen(stmts)
        IN, OUT = dense(stmts, succ, aux)
        ins, outs, _ = sparse_fs(stmts, succ)
        for (u, w), s in ins.items():
            assert s == IN[u][w], (ptsgen.show(stmts), succ, u, w)
        for (d, v), s in outs.items():
            assert s == OUT[d][v], (ptsgen.show(stmts), succ, d, v)


def test_dense_is_inside_andersen():
    strict = 0
    for _, (stmts, succ) in programs(2004, 300):
        aux = andersen(stmts)
        assert aux == ptsgen.least_solution(stmts)
        IN, OUT = dense(stmts, succ, aux)
        for n in IN:
            for w, s in IN[n].items():
                assert s <= aux[w]
                strict += s < aux[w]
    assert strict > 0


def run(stmts, succ, rng, steps=60):
    """One random walk from the entry. Each execution of x = &h with a heap
    name h makes a fresh object (h, k). Yields (node, memory) before each
    node. A load or store through a pointer with no value stops the walk."""
    mem = {}
    n, fresh = 0, 0
    for _ in range(steps):
        yield n, dict(mem)
        kind, x, y = stmts[n]
        if kind == "addr":
            if is_heap(y):
                fresh += 1
                mem[x] = (y, fresh)
            else:
                mem[x] = y
        elif kind == "copy":
            mem[x] = mem.get(y)
        elif kind == "load":
            if mem.get(y) is None:
                return
            mem[x] = mem.get(mem[y])
        else:
            if mem.get(x) is None:
                return
            mem[mem[x]] = mem.get(y)
        if not succ[n]:
            return
        n = rng.choice(succ[n])


def name(loc):
    return loc if isinstance(loc, str) else loc[0]


def test_sound_against_concrete_runs():
    checked = 0
    for rng, (stmts, succ) in programs(2003, 300):
        aux = andersen(stmts)
        IN, _ = dense(stmts, succ, aux)
        ins, _, _ = sparse_fs(stmts, succ)
        for _ in range(5):
            for n, mem in run(stmts, succ, rng):
                for loc, val in mem.items():
                    if val is not None:
                        assert name(val) in IN[n][name(loc)], (ptsgen.show(stmts), succ)
                        if (n, name(loc)) in ins:
                            assert name(val) in ins[(n, name(loc))]
                            checked += 1
    assert checked > 500

History

Sparse evaluation of dataflow problems along def-use chains is older than pointer analysis on SSA form. For pointer analysis the difficulty was that the def-use chains of memory depend on the points-to result itself. Hardekopf and Lin (2009) first made the top-level variables sparse in a semi-sparse analysis. In 2011 they added the staging: a flow-insensitive analysis first gives safe def-use chains for memory, and the flow-sensitive analysis then runs only along them. Later frameworks for LLVM build a sparse value-flow graph in the same way.

References

  1. Ben Hardekopf and Calvin Lin, Flow-sensitive pointer analysis for millions of lines of code, Proceedings of CGO 2011, the staged analysis with an auxiliary flow-insensitive analysis, def-use chains for address-taken variables and strong updates on singleton targets

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/9J9RX5/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
  • at least three sources
  • a scene preset for the example