Algorithm Search⌘K

Algorithmresearch

IDE framework

Also called interprocedural distributive environments.

Extends IFDS to environment problems, such as linear constant propagation, by labeling exploded edges with distributive value functions.

Time
O(E D^3) worst · averageΘ(N + E) best
Space
O(N D^2 + C D^2) extra
Where
C = the number of call sites; D = the largest number of facts of one procedure; E = the number of edges of the supergraph; N = the number of nodes of the supergraph
Properties
deterministiciterative

The IDE framework of Sagiv, Reps and Horwitz extends IFDS from sets of facts to environments. IDE stands for Interprocedural, Distributive, Environment. An environment maps each fact, usually a variable, to a value in a lattice, and every flow function must distribute over the meet of environments. Such a function is fixed by small functions on single values, one for each pair of facts. IDE puts these micro-functions on the edges of the exploded supergraph of IFDS. Phase I walks the graph like the tabulation algorithm, but each path edge carries the meet of the micro-functions along its paths. Phase II pushes actual values through these functions. The main example is linear constant propagation, where a variable may be a constant or ax+ba x + b of one other variable. The result is the meet over all valid paths, and the time is O(ED3)O(E D^3) when micro-functions are cheap and the value lattice has finite height.

In plain words

IFDS answers yes or no questions, such as "may this variable hold a secret". Many analyses need a value instead, such as "this variable is always 7". IDE handles these. It keeps the same big graph, with one copy of every program point for each variable. But each edge now carries a small rule that says how a value changes on the way, such as "add 1" or "times 3". First the algorithm builds, for each procedure, rules that go all the way from the entry to every point. It joins rules where paths meet. Then it feeds the real values in at the entry of the program and applies the rules. A procedure that adds 1 to its argument gives a constant at each call with a constant argument, even when the argument differs between callers.

The problem

An IDE instance is a supergraph G∗G^*, a finite set of facts DpD_p for each procedure pp, a value lattice LL of finite height, and for each edge an environment transformer t:(Dp→L)→(Dq→L)t : (D_p \to L) \to (D_q \to L) that distributes over the pointwise meet. The output is, for every node nn and fact dd, the meet over all valid paths

MVP(n)(d)=⊓{tπ(ρ0)(d):π a valid path from smain to n},\mathrm{MVP}(n)(d) = \mathop{\large\sqcap} \{ t_\pi(\rho_0)(d) : \pi \text{ a valid path from } s_{main} \text{ to } n \},

where ρ0\rho_0 is the start environment. This page uses the meet convention of Kildall: the start value is ⊤\top and the result is the greatest solution. In the join convention of Cousot the order flips and the same result is the least solution.

A distributive transformer is given by micro-functions. For each pair of facts d,d′d, d' there is a function fd,d′:L→Lf_{d,d'} : L \to L, and

t(ρ)(d′)=⊓d∈D∪{0}fd,d′(ρ(d)),t(\rho)(d') = \mathop{\large\sqcap}_{d \in D \cup \{\mathbf{0}\}} f_{d,d'}(\rho(d)),

where the extra fact 0\mathbf{0} always has the value ⊥\bot. The pair (0,d′)(\mathbf{0}, d') carries the part of tt that does not depend on any input, such as x = 5. A pair with fd,d′=λl.⊤f_{d,d'} = \lambda l.\top has no edge.

The implementation solves linear constant propagation on the toy IR. The values are ⊤\top, the integers and ⊥\bot. The micro-functions are:

form meaning
top λl.⊤\lambda l.\top, the function of no path
bot λl.⊥\lambda l.\bot
const k λl.k\lambda l.k
line a b λl. al+b\lambda l.\, a l + b with a≠0a \ne 0, and ⊥↦⊥\bot \mapsto \bot
point l0 v l0↦vl_0 \mapsto v, every other value ↦⊥\mapsto \bot

Every form maps ⊤\top to ⊤\top. The set is closed under meet and composition. The meet of two lines with different slopes agrees with both at one point at most, so it is a point function or bot. Each function has exactly one form, so two functions are equal exactly when their tuples are equal. A chain of strict meets from top has at most three steps.

statement edges and micro-functions
x = k 0→x\mathbf{0} \to x: const k; every other d→dd \to d: identity
x = a a→xa \to x: identity, plus the identity for every d≠xd \ne x
x = a + k, a - k, k - a, a * k a→xa \to x: a line. a * 0 gives 0→x\mathbf{0} \to x: const 0
x = k1 op k2 0→x\mathbf{0} \to x: const of the result, or bot on a trap
any other x = a op b 0→x\mathbf{0} \to x: bot
ret a a→RETa \to RET: identity, or 0→RET\mathbf{0} \to RET: const a for a constant
call edge of x = call q(a, b) each argument variable to its parameter: identity; a constant argument gives 0→\mathbf{0} \to parameter: const
call-to-return edge identity for every fact of the caller except x
return edge RET→xRET \to x: identity, 0→0\mathbf{0} \to \mathbf{0}: identity

The parameters of main are ⊥\bot unless a seed value is given.

The algorithm

Phase I computes a jump function J(n,d1,d2)J(n, d_1, d_2) for each pair of a node nn in procedure pp and facts d1,d2d_1, d_2. It is the meet of the micro-function compositions along all same-level paths from ⟨sp,d1⟩\langle s_p, d_1 \rangle to ⟨n,d2⟩\langle n, d_2 \rangle. It also computes a summary function S(c,d4,d5)S(c, d_4, d_5) for each call site, which goes from ⟨c,d4⟩\langle c, d_4 \rangle through the callee to ⟨r,d5⟩\langle r, d_5 \rangle. A key enters the worklist again each time its function goes down. Phase II computes values at start nodes and call nodes with a second worklist, then gets every other value with one application of a jump function.

  1. IDE(G*, F, seeds) F gives the labelled exploded edges; seeds gives values to the parameters of main
  2. 1Jump, Through, Summary ← λl.⊤ everywhere; WorkList ← []
  3. 2for each d in {0} ∪ params(main) do PROPAGATE(s_main, d, d, id)
  4. 3while WorkList is not empty do
  5. 4(n, d1, d2) ← remove the first item; f ← Jump(n, d1, d2) (n is in procedure p)
  6. 5if n is a call node c, with callee q and return site r then
  7. 6for each call edge <c,d2> → <s_q,d3> do PROPAGATE(s_q, d3, d3, id)
  8. 7for each edge <c,d2> → <r,d3> with label g, call-to-return or Summary(c, d2, d3), do PROPAGATE(r, d1, d3, g ∘ f)
  9. 8else if n is the exit node e_p then
  10. 9for each call node c of p, with return site r, and each return edge <e_p,d2> → <r,d5> with label g do
  11. 10t ← Through(c, d1, d5) ⊓ (g ∘ f); if t = Through(c, d1, d5) then skip it, else Through(c, d1, d5) ← t
  12. 11for each call edge <c,d4> → <s_p,d1> with label h do
  13. 12s ← Summary(c, d4, d5) ⊓ (t ∘ h); if s ≠ Summary(c, d4, d5) then Summary(c, d4, d5) ← s
  14. 13for each d3 with Jump(c, d3, d4) ≠ λl.⊤ do PROPAGATE(r, d3, d5, s ∘ Jump(c, d3, d4))
  15. 14else for each successor m of n and each edge <n,d2> → <m,d3> with label g do PROPAGATE(m, d1, d3, g ∘ f)
  16. 15val ← ⊤ everywhere; LOWER(s_main, 0, ⊥); for each parameter x of main do LOWER(s_main, x, seed of x, or ⊥)
  17. 16while WorkList2 is not empty do
  18. 17(n, d) ← remove the first item; v ← val(n, d) (n is in procedure p)
  19. 18if n = s_p then for each m in {s_p} ∪ calls(p) and each d2 with Jump(m, d, d2) ≠ λl.⊤ do LOWER(m, d2, Jump(m, d, d2)(v))
  20. 19if n is a call node with callee q then for each call edge <n,d> → <s_q,d3> with label h do LOWER(s_q, d3, h(v))
  21. 20for each other node n of p and each d2 do val(n, d2) ← ⊓ over d1 of Jump(n, d1, d2)(val(s_p, d1))
  22. 21return val without the fact 0
  23. PROPAGATE(n, d1, d2, f)
  24. 22j ← Jump(n, d1, d2) ⊓ f; if j ≠ Jump(n, d1, d2) then Jump(n, d1, d2) ← j and append (n, d1, d2) to WorkList unless it is there
  25. LOWER(n, d, v)
  26. 23w ← val(n, d) ⊓ v; if w ≠ val(n, d) then val(n, d) ← w and append (n, d) to WorkList2 unless it is there

Phase I has the shape of the IFDS tabulation. The differences are in L22 and in the exit case. A key is not done when it is first found. It goes back on the worklist each time its function goes down, and the finite height of the function space bounds how often this happens. At the exit (L9 to L13), Through(c,d1,d5)Through(c, d_1, d_5) collects the effect of the callee from the entry fact d1d_1 to the return fact d5d_5 at the site cc. Each call edge into d1d_1 then turns it into a summary function, and every path edge that already reaches the call is extended.

In Phase II, line L18 handles the start node of pp and the call nodes of pp only. These are the nodes where values must cross into other procedures, so they need the worklist. Every other node gets its value in L20, in one pass, from the values at the start of its procedure.

The implementation keeps, next to JumpJump, an index of sources for L13 and an index of targets for L18. It also builds, for each call site, the inverse of its call edges for L11.

Example

add(a, b):    t = a * 3
              u = t + 1
              ret u
main(n):      x = 2
              y = call add(x, n)        c1
              z = call add(n, x)        c2
              v = 4
              w = call add(v, y)        c3
              ret w

The parameter n of main is ⊥\bot. Phase I finds these jump functions in add: a→ta \to t is line 3 0, a→ua \to u is line 3 1, and at the exit a→RETa \to RET is line 3 1. The fact bb only reaches itself. At the exit, L10 to L12 give one summary function per call site from the argument variable to the target: x→yx \to y at c1c_1, n→zn \to z at c2c_2 and v→wv \to w at c3c_3, all line 3 1. Each site also gets 0→0\mathbf{0} \to \mathbf{0}, so there are six summary functions.

Back in main, L13 composes each summary function with the jump function at the call:

target composition jump function from the start of main
y line 3 1 after 0→x\mathbf{0} \to x: const 2 0→y\mathbf{0} \to y: const 7
z line 3 1 after n→nn \to n: identity n→zn \to z: line 3 1
w line 3 1 after 0→v\mathbf{0} \to v: const 4 0→w\mathbf{0} \to w: const 13

Phase II starts with 0=⊥\mathbf{0} = \bot and n=⊥n = \bot at the start of main. So y is 7, w is 13, and z is ⊥\bot. At the start of add, a gets 2, ⊥\bot and 4 from the three calls, so it is ⊥\bot. The same is true of b. A context-insensitive analysis of the same supergraph sees only a=⊥a = \bot at the entry of add, so it reports u as ⊥\bot and gets ⊥\bot for y and w too. IDE gets the constants because the summary keeps the relation RET=3a+1RET = 3a + 1, not the value of a.

The run finds 53 keys, with 53 changes of jump functions, 6 summary functions and 20 changes of values in Phase II.

Correctness

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

  1. The micro-functions. The forms are closed under meet and composition, every form is distributive and maps ⊤\top to ⊤\top, each function has one form, and a strictly falling chain has at most four elements.
  2. One path, many facts. For a path π\pi of the supergraph, tπ(ρ)(d′)t_\pi(\rho)(d') is the meet of the compositions of micro-functions along the exploded paths that follow π\pi and end at d′d', applied to the start values. So MVP is the meet over valid paths of the exploded graph.
  3. Phase I is sound. Every stored jump, through and summary function is a finite meet of the functions of real same-level paths. The proof is an induction on time, with distributivity to move compositions inside meets.
  4. Phase I is complete. Each key is taken off the worklist after its last change. This gives five local constraints at the end. The one at summary functions holds because L7 or L13 runs after both functions take their final values. An induction on the length of the path then shows that the jump function is at most the function of every same-level path.
  5. Phase II. The values at start nodes and call nodes are meets of real path values, and at the end they satisfy three local constraints. An induction on the number of calls that are still open gives the other direction. L20 then gives the right value at every other node.
  6. Termination and cost. Each function changes at most three times and each value at most twice. The cost counts the work at each kind of node, as for IFDS.
Proof: The IDE algorithm computes the meet over all valid paths for linear constant propagation in O(E D^3) timefull

Setting. G∗G^* is the supergraph of the program, as on the page. Every procedure pp has a start node sps_p and an exit node epe_p. A call site has a call node cc in some procedure, a return site rr and three edges: the call edge c→sqc \to s_q, the return edge eq→re_q \to r and the call-to-return edge c→rc \to r. The facts of pp form a finite set DpD_p, and D=max⁡p∣Dp∣D = \max_p |D_p|. 0\mathbf{0} is a new fact that is in no DpD_p.

The values form the flat lattice L={⊤}∪Z∪{⊥}L = \{\top\} \cup \mathbb{Z} \cup \{\bot\}, with ⊥⊑k⊑⊤\bot \sqsubseteq k \sqsubseteq \top for every integer kk and no order between two integers. The meet is ⊓\sqcap. This is the meet convention of Kildall: the start value is ⊤\top and the result is the greatest solution. In the join convention of Cousot the order flips and the same result is the least solution.

A micro-function is one of the forms of the page: λl.⊤\lambda l.\top, λl.⊥\lambda l.\bot, λl.k\lambda l.k, λl. al+b\lambda l.\, a l + b with a≠0a \ne 0, and the point function that maps l0l_0 to vv and every other value to ⊥\bot. All forms map ⊤\top to ⊤\top, the line maps ⊥\bot to ⊥\bot, and the constant maps ⊥\bot to kk. Let FF be the set of these functions. Three facts about FF are used below, and the tests of the implementation check each of them by brute force on sample points.

  • (F1) FF is closed under the pointwise meet and under composition, and meet_fn and compose compute them exactly. For example, the meet of λl.k\lambda l.k and λl. al+b\lambda l.\, a l + b agrees with both at l0=(k−b)/al_0 = (k - b)/a when this is an integer, and gives ⊥\bot at every other value. So it is the point function l0↦kl_0 \mapsto k, or λl.⊥\lambda l.\bot when l0l_0 is not an integer. The other cases are the same kind of algebra.
  • (F2) Every f∈Ff \in F is distributive: f(x⊓y)=f(x)⊓f(y)f(x \sqcap y) = f(x) \sqcap f(y). If one of x,yx, y is ⊤\top, this follows from f(⊤)=⊤f(\top) = \top. If x=yx = y, it is clear. Otherwise x⊓y=⊥x \sqcap y = \bot, and f(⊥)f(\bot) is ⊥\bot, or kk when ff is the constant kk, in which case f(x)=f(y)=kf(x) = f(y) = k. So ff is also monotone.
  • (F3) Each function has one form, and a strictly falling chain in FF has at most four elements: λl.⊤\lambda l.\top, then a constant or a line, then a point function, then λl.⊥\lambda l.\bot. The meet of two different constants, lines or points is lower in this list, and nothing is between λl.⊤\lambda l.\top and the constants and lines.

By (F3), the meet of any set of functions of FF, even an infinite set, is the meet of a finite subset, so it is in FF and it is the pointwise meet. The same holds in LL, which has height 2.

Every edge e=(n,m)e = (n, m) of G∗G^* and every pair d∈Dn∪{0}d \in D_n \cup \{\mathbf{0}\}, d′∈Dm∪{0}d' \in D_m \cup \{\mathbf{0}\} have a micro-function φe(d,d′)\varphi_e(d, d'). The function is λl.⊤\lambda l.\top when there is no exploded edge, and φe(0,0)\varphi_e(\mathbf{0}, \mathbf{0}) is the identity. An environment ρ\rho maps the facts of a procedure to LL, with ρ(0)=⊥\rho(\mathbf{0}) = \bot. The edge ee has the environment transformer

te(ρ)(d′)=⊓dφe(d,d′)(ρ(d)).t_e(\rho)(d') = \mathop{\large\sqcap}_{d} \varphi_e(d, d')(\rho(d)).

For a path π=e1…ek\pi = e_1 \dots e_k, tπ=tek∘⋯∘te1t_\pi = t_{e_k} \circ \dots \circ t_{e_1}. The start environment ρ0\rho_0 gives ⊥\bot to 0\mathbf{0}, the seed value or ⊥\bot to each parameter of main, and ⊤\top to the other variables of main. Valid and same-level paths are defined by matched brackets, as for IFDS. The meet over all valid paths is

MVP(n)(d)=⊓{tπ(ρ0)(d):π a valid path from smain to n}.\mathrm{MVP}(n)(d) = \mathop{\large\sqcap} \{ t_\pi(\rho_0)(d) : \pi \text{ a valid path from } s_{main} \text{ to } n \}.

The exploded supergraph G#G^\# has a node ⟨n,d⟩\langle n, d \rangle for every node nn and fact dd, and an edge ⟨n,d⟩→⟨m,d′⟩\langle n, d \rangle \to \langle m, d' \rangle labelled φe(d,d′)\varphi_e(d, d') for every edge e=(n,m)e = (n, m) with φe(d,d′)≠λl.⊤\varphi_e(d, d') \ne \lambda l.\top. For a path σ\sigma of G#G^\#, φσ\varphi_\sigma is the composition of its labels, and the identity for the empty path. No label is λl.⊤\lambda l.\top, and a composition is λl.⊤\lambda l.\top only if one of its parts is. So φσ≠λl.⊤\varphi_\sigma \ne \lambda l.\top.

We use the lines L1 to L23 of the pseudocode. J(n,d1,d2)J(n, d_1, d_2) is the jump function of (n,d1,d2)(n, d_1, d_2), T(c,d1,d5)T(c, d_1, d_5) is the function of line L10, S(c,d4,d5)S(c, d_4, d_5) is the summary function, and val(n,d)\mathrm{val}(n, d) is the value of Phase II. A missing function is λl.⊤\lambda l.\top, and a missing value is ⊤\top.

Lemma 1 (one path, many facts). For a path π\pi of G∗G^* from nn to mm, an environment ρ\rho and a fact d′d',

tπ(ρ)(d′)=⊓{φσ(ρ(d)):σ a path of G# that follows π from some ⟨n,d⟩ to ⟨m,d′⟩}.t_\pi(\rho)(d') = \mathop{\large\sqcap} \{ \varphi_\sigma(\rho(d)) : \sigma \text{ a path of } G^\# \text{ that follows } \pi \text{ from some } \langle n, d \rangle \text{ to } \langle m, d' \rangle \}.

Proof. Induction on the length of π\pi. For the empty path the only σ\sigma is the empty path from ⟨n,d′⟩\langle n, d' \rangle, and both sides are ρ(d′)\rho(d'). Let π=π′e\pi = \pi' e. By induction and by (F2),

tπ(ρ)(d′)=⊓dφe(d,d′)(⊓σ′φσ′(ρ(d0)))=⊓d⊓σ′φe(d,d′)(φσ′(ρ(d0))),t_\pi(\rho)(d') = \mathop{\large\sqcap}_d \varphi_e(d, d')\Big(\mathop{\large\sqcap}_{\sigma'} \varphi_{\sigma'}(\rho(d_0))\Big) = \mathop{\large\sqcap}_d \mathop{\large\sqcap}_{\sigma'} \varphi_e(d, d')(\varphi_{\sigma'}(\rho(d_0))),

where σ′\sigma' runs over the paths that follow π′\pi' and end at ⟨⋅,d⟩\langle \cdot, d \rangle. An empty meet is ⊤\top, and every micro-function maps ⊤\top to ⊤\top, so empty meets do no harm. A term with φe(d,d′)=λl.⊤\varphi_e(d, d') = \lambda l.\top is ⊤\top and drops out. The other terms are exactly the paths σ=σ′e\sigma = \sigma' e of G#G^\#. □\square

The brackets of a path of G#G^\# are those of its shadow in G∗G^*. So Lemma 1 gives:

Corollary 2. MVP(n)(d)\mathrm{MVP}(n)(d) is the meet of φρ(ρ0(d0))\varphi_\rho(\rho_0(d_0)) over all valid paths ρ\rho of G#G^\# from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle to ⟨n,d⟩\langle n, d \rangle.

A path that starts at ⟨smain,d0⟩\langle s_{main}, d_0 \rangle for a variable d0d_0 of main that is not a parameter has the value ⊤\top and drops out. So from now on d0d_0 is 0\mathbf{0} or a parameter of main.

Decomposition. Cut a valid path of G#G^\# from ⟨smain,d0⟩\langle s_{main}, d_0 \rangle at its last call edge that is never closed. This gives α⋅σ\alpha \cdot \sigma, where α\alpha is empty or ends with that call edge, and σ\sigma is a same-level path from some ⟨sp,d1⟩\langle s_p, d_1 \rangle. We call α\alpha an entry path to ⟨sp,d1⟩\langle s_p, d_1 \rangle and d1d_1 the entry fact. Let

SL(n,d1,d2)=⊓{φσ:σ same-level from ⟨sp,d1⟩ to ⟨n,d2⟩},EN(p,d1)=⊓{φα(ρ0(d0)):α an entry path to ⟨sp,d1⟩}.\mathrm{SL}(n, d_1, d_2) = \mathop{\large\sqcap} \{ \varphi_\sigma : \sigma \text{ same-level from } \langle s_p, d_1 \rangle \text{ to } \langle n, d_2 \rangle \}, \qquad \mathrm{EN}(p, d_1) = \mathop{\large\sqcap} \{ \varphi_\alpha(\rho_0(d_0)) : \alpha \text{ an entry path to } \langle s_p, d_1 \rangle \}.

By Corollary 2, (F2) and the remark after (F3),

MVP(n)(d2)=⊓d1SL(n,d1,d2)(EN(p,d1)).(∗)\mathrm{MVP}(n)(d_2) = \mathop{\large\sqcap}_{d_1} \mathrm{SL}(n, d_1, d_2)(\mathrm{EN}(p, d_1)). \qquad (\ast)

Phase I.

Lemma 3 (Phase I is sound). Every function that the algorithm stores as J(n,d1,d2)J(n, d_1, d_2) is a finite meet of φσ\varphi_\sigma over same-level paths σ\sigma from ⟨sp,d1⟩\langle s_p, d_1 \rangle to ⟨n,d2⟩\langle n, d_2 \rangle. Every T(c,d1,d5)T(c, d_1, d_5) is a finite meet of g∘φσg \circ \varphi_\sigma, where σ\sigma is same-level from ⟨sq,d1⟩\langle s_q, d_1 \rangle to some ⟨eq,d2⟩\langle e_q, d_2 \rangle and gg is the label of a return edge ⟨eq,d2⟩→⟨r,d5⟩\langle e_q, d_2 \rangle \to \langle r, d_5 \rangle of the site cc. Every S(c,d4,d5)S(c, d_4, d_5) is a finite meet of φτ\varphi_\tau over same-level paths τ\tau from ⟨c,d4⟩\langle c, d_4 \rangle to ⟨r,d5⟩\langle r, d_5 \rangle that start with the call edge of cc and end with its return edge. So, at every time, J⊒SLJ \sqsupseteq \mathrm{SL}.

Proof. Induction on time. A new value is the meet of the old value and one new term, so it is enough to look at the terms. By (F2) and the pointwise meet, g∘(f1⊓f2)=(g∘f1)⊓(g∘f2)g \circ (f_1 \sqcap f_2) = (g \circ f_1) \sqcap (g \circ f_2) and (f1⊓f2)∘h=(f1∘h)⊓(f2∘h)(f_1 \sqcap f_2) \circ h = (f_1 \circ h) \sqcap (f_2 \circ h), so a composition of finite meets of path functions is a finite meet of the functions of the joined paths.

  • L2 and L6 give the identity to (s,d,d)(s, d, d), the function of the empty path.
  • L7 and L14 give g∘J(n,d1,d2)g \circ J(n, d_1, d_2) for an exploded edge with label gg. The joined paths are same-level.
  • L7 also gives S(c,d2,d3)∘J(c,d1,d2)S(c, d_2, d_3) \circ J(c, d_1, d_2), and L13 gives S(c,d4,d5)∘J(c,d3,d4)S(c, d_4, d_5) \circ J(c, d_3, d_4). A same-level path followed by a call, a same-level path in the callee and the matching return is same-level.
  • L10 gives g∘J(eq,d1,d2)g \circ J(e_q, d_1, d_2) for a return edge of cc with label gg.
  • L12 gives T(c,d1,d5)∘hT(c, d_1, d_5) \circ h for a call edge ⟨c,d4⟩→⟨sq,d1⟩\langle c, d_4 \rangle \to \langle s_q, d_1 \rangle with label hh. □\square

A key (n,d1,d2)(n, d_1, d_2) exists once J(n,d1,d2)≠λl.⊤J(n, d_1, d_2) \ne \lambda l.\top. Every key is put on the worklist when its function changes, unless it is on the worklist already, and L4 reads the current function when it takes the key off. Also, L4 takes the key off the worklist before the key can be added again. So every key that exists at the end was taken off at least once after its last change, and at that time L5 to L14 saw its final function. Write JJ, TT, SS for the final functions. Since stored functions only go down, this gives the following constraints at the end.

  • (C1) For every exploded edge ⟨n,d2⟩→⟨m,d3⟩\langle n, d_2 \rangle \to \langle m, d_3 \rangle with label gg that is intraprocedural or a call-to-return edge, J(m,d1,d3)⊑g∘J(n,d1,d2)J(m, d_1, d_3) \sqsubseteq g \circ J(n, d_1, d_2) when (n,d1,d2)(n, d_1, d_2) exists.
  • (C2) If (c,d1,d2)(c, d_1, d_2) exists and the call edge of cc goes from ⟨c,d2⟩\langle c, d_2 \rangle to ⟨sq,d3⟩\langle s_q, d_3 \rangle, then J(sq,d3,d3)⊑idJ(s_q, d_3, d_3) \sqsubseteq \mathrm{id}.
  • (C3) If (eq,d1,d2)(e_q, d_1, d_2) exists, then T(c,d1,d5)⊑g∘J(eq,d1,d2)T(c, d_1, d_5) \sqsubseteq g \circ J(e_q, d_1, d_2) for every call site cc of qq and every return edge ⟨eq,d2⟩→⟨r,d5⟩\langle e_q, d_2 \rangle \to \langle r, d_5 \rangle of cc with label gg.
  • (C4) S(c,d4,d5)⊑T(c,d1,d5)∘hS(c, d_4, d_5) \sqsubseteq T(c, d_1, d_5) \circ h for every call edge ⟨c,d4⟩→⟨sq,d1⟩\langle c, d_4 \rangle \to \langle s_q, d_1 \rangle with label hh. When L10 lowers TT, L11 and L12 meet SS with the new T∘hT \circ h at once. When TT does not change, the old step still holds.
  • (C5) J(r,d3,d5)⊑S(c,d4,d5)∘J(c,d3,d4)J(r, d_3, d_5) \sqsubseteq S(c, d_4, d_5) \circ J(c, d_3, d_4) whenever (c,d3,d4)(c, d_3, d_4) exists.

Proof of (C5). Let tSt_S be the time when S(c,d4,d5)S(c, d_4, d_5) got its final value, tJt_J the time of the last change of J(c,d3,d4)J(c, d_3, d_4), and tP>tJt_P > t_J the time of the last removal of (c,d3,d4)(c, d_3, d_4) from the worklist. If tP>tSt_P > t_S, then L7 sees the final SS and the final JJ at tPt_P. If tP<tSt_P < t_S, then tJ<tSt_J < t_S, so at tSt_S the key already exists, d3d_3 is among the sources of ⟨c,d4⟩\langle c, d_4 \rangle, and L13 meets J(r,d3,d5)J(r, d_3, d_5) with S∘JS \circ J for the final SS and JJ. □\square

Lemma 4 (Phase I is complete). Let ασ\alpha \sigma be a valid path of G#G^\# from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle, where d0d_0 is 0\mathbf{0} or a parameter of main, cut as in the decomposition, with σ\sigma from ⟨sp,d1⟩\langle s_p, d_1 \rangle to ⟨n,d2⟩\langle n, d_2 \rangle. Then at the end J(n,d1,d2)⊑φσJ(n, d_1, d_2) \sqsubseteq \varphi_\sigma. In particular the key exists.

Proof. Strong induction on the length of ασ\alpha \sigma.

  • σ\sigma is empty. If α\alpha is empty, L2 gives the identity to (smain,d0,d0)(s_{main}, d_0, d_0). Otherwise α\alpha ends with a call edge from ⟨c,d4⟩\langle c, d_4 \rangle to ⟨sp,d1⟩\langle s_p, d_1 \rangle, and the path without this edge is shorter. By induction, the key of cc for this shorter path exists, and (C2) gives J(sp,d1,d1)⊑idJ(s_p, d_1, d_1) \sqsubseteq \mathrm{id}.

  • The last edge of σ\sigma is intraprocedural or a call-to-return edge with label gg, from ⟨m,d′⟩\langle m, d' \rangle. By induction J(m,d1,d′)⊑φσ′J(m, d_1, d') \sqsubseteq \varphi_{\sigma'}, where σ′\sigma' is σ\sigma without its last edge. By (C1) and (F2), J(n,d1,d2)⊑g∘J(m,d1,d′)⊑g∘φσ′=φσJ(n, d_1, d_2) \sqsubseteq g \circ J(m, d_1, d') \sqsubseteq g \circ \varphi_{\sigma'} = \varphi_\sigma.

  • The last edge of σ\sigma is a return edge. Then σ=σ1⋅call⋅σ2⋅ret\sigma = \sigma_1 \cdot \mathit{call} \cdot \sigma_2 \cdot \mathit{ret}, where the call edge goes from ⟨c,d4⟩\langle c, d_4 \rangle to ⟨sq,d1′⟩\langle s_q, d_1' \rangle with label hh, σ2\sigma_2 is same-level from ⟨sq,d1′⟩\langle s_q, d_1' \rangle to ⟨eq,d2′⟩\langle e_q, d_2' \rangle, and the return edge has label gg. The path ασ1⋅call⋅σ2\alpha \sigma_1 \cdot \mathit{call} \cdot \sigma_2 is shorter and has the entry fact d1′d_1', so J(eq,d1′,d2′)⊑φσ2J(e_q, d_1', d_2') \sqsubseteq \varphi_{\sigma_2}. The path ασ1\alpha \sigma_1 is shorter, so J(c,d1,d4)⊑φσ1J(c, d_1, d_4) \sqsubseteq \varphi_{\sigma_1}. By (C3), (C4) and (C5),

    J(n,d1,d2)⊑S(c,d4,d2)∘J(c,d1,d4)⊑g∘J(eq,d1′,d2′)∘h∘J(c,d1,d4)⊑g∘φσ2∘h∘φσ1=φσ.J(n, d_1, d_2) \sqsubseteq S(c, d_4, d_2) \circ J(c, d_1, d_4) \sqsubseteq g \circ J(e_q, d_1', d_2') \circ h \circ J(c, d_1, d_4) \sqsubseteq g \circ \varphi_{\sigma_2} \circ h \circ \varphi_{\sigma_1} = \varphi_\sigma.

    Each step uses that composition is monotone in both places, which holds by (F2). □\square

Corollary 5. If some entry path reaches ⟨sp,d1⟩\langle s_p, d_1 \rangle, then J(n,d1,d2)=SL(n,d1,d2)J(n, d_1, d_2) = \mathrm{SL}(n, d_1, d_2) at the end, for every nn in pp and every d2d_2. Otherwise no key (n,d1,d2)(n, d_1, d_2) exists.

Proof. The first part is Lemma 3 and Lemma 4, with the remark after (F3) for the infinite meet. For the second part, a key with the source d1d_1 is first made by L2 or L6, and both need an entry path to ⟨sp,d1⟩\langle s_p, d_1 \rangle, by Lemma 3 applied to the key of the call node. □\square

Phase II.

By Corollary 5, Phase II works with J=SLJ = \mathrm{SL}. Let K\mathcal{K} be the set of start nodes and call nodes.

Lemma 6 (Phase II is sound). Every value that L23 stores as val(n,d)\mathrm{val}(n, d) with n∈Kn \in \mathcal{K} is a finite meet of values φρ(ρ0(d0))\varphi_\rho(\rho_0(d_0)) of valid paths ρ\rho of G#G^\# to ⟨n,d⟩\langle n, d \rangle. So val(n,d)⊒MVP(n)(d)\mathrm{val}(n, d) \sqsupseteq \mathrm{MVP}(n)(d).

Proof. Induction on time. L15 uses the empty path. L18 applies J(m,d,d2)J(m, d, d_2), a finite meet of same-level path functions, to a finite meet of values of valid paths to ⟨sp,d⟩\langle s_p, d \rangle. By (F2) the result is a finite meet of values of the joined paths, and a valid path followed by a same-level path is valid. L19 appends a call edge to a valid path, and the result is valid. □\square

The Phase II worklist has the same property as the Phase I worklist: each pair is taken off after its last change. So at the end of L19 the values satisfy the following constraints.

  • (V1) val(smain,d0)⊑ρ0(d0)\mathrm{val}(s_{main}, d_0) \sqsubseteq \rho_0(d_0) for 0\mathbf{0} and the parameters of main.
  • (V2) val(m,d2)⊑J(m,d,d2)(val(sp,d))\mathrm{val}(m, d_2) \sqsubseteq J(m, d, d_2)(\mathrm{val}(s_p, d)) for every m∈{sp}∪calls(p)m \in \{s_p\} \cup \mathrm{calls}(p) and every key (m,d,d2)(m, d, d_2).
  • (V3) val(sq,d3)⊑h(val(c,d))\mathrm{val}(s_q, d_3) \sqsubseteq h(\mathrm{val}(c, d)) for every call edge ⟨c,d⟩→⟨sq,d3⟩\langle c, d \rangle \to \langle s_q, d_3 \rangle with label hh.

Lemma 7 (Phase II is complete on K\mathcal{K}). For every valid path ρ\rho of G#G^\# from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle to ⟨n,d⟩\langle n, d \rangle with n∈Kn \in \mathcal{K}, val(n,d)⊑φρ(ρ0(d0))\mathrm{val}(n, d) \sqsubseteq \varphi_\rho(\rho_0(d_0)).

Proof. Induction on the number kk of call edges of ρ\rho that are never closed. Cut ρ=ασ\rho = \alpha \sigma, with σ\sigma from ⟨sp,d1⟩\langle s_p, d_1 \rangle. First we show val(sp,d1)⊑φα(ρ0(d0))\mathrm{val}(s_p, d_1) \sqsubseteq \varphi_\alpha(\rho_0(d_0)). If k=0k = 0, then α\alpha is empty and (V1) gives it. If k>0k > 0, then α=α′⋅call\alpha = \alpha' \cdot \mathit{call}, where the call edge goes from ⟨c,d4⟩\langle c, d_4 \rangle to ⟨sp,d1⟩\langle s_p, d_1 \rangle with label hh. The path α′\alpha' ends at a call node and has k−1k - 1 open calls, so by induction val(c,d4)⊑φα′(ρ0(d0))\mathrm{val}(c, d_4) \sqsubseteq \varphi_{\alpha'}(\rho_0(d_0)), and (V3) with (F2) gives the claim. Now nn is sps_p or a call node of pp, so by (V2), Lemma 4 and (F2),

val(n,d)⊑J(n,d1,d)(val(sp,d1))⊑φσ(φα(ρ0(d0)))=φρ(ρ0(d0)).□\mathrm{val}(n, d) \sqsubseteq J(n, d_1, d)(\mathrm{val}(s_p, d_1)) \sqsubseteq \varphi_\sigma(\varphi_\alpha(\rho_0(d_0))) = \varphi_\rho(\rho_0(d_0)). \qquad \square

Theorem (correctness). At the end, val(n,d)=MVP(n)(d)\mathrm{val}(n, d) = \mathrm{MVP}(n)(d) for every node nn and every fact dd. So the result VV of line L21 is the meet over all valid paths.

Proof. For n∈Kn \in \mathcal{K}, this is Lemma 6, Lemma 7 and Corollary 2. For another node nn of pp, L20 sets

val(n,d2)=⊓d1J(n,d1,d2)(val(sp,d1))=⊓d1SL(n,d1,d2)(MVP(sp)(d1)).\mathrm{val}(n, d_2) = \mathop{\large\sqcap}_{d_1} J(n, d_1, d_2)(\mathrm{val}(s_p, d_1)) = \mathop{\large\sqcap}_{d_1} \mathrm{SL}(n, d_1, d_2)(\mathrm{MVP}(s_p)(d_1)).

Keys that do not exist give ⊤\top and drop out. We show that the right side is MVP(n)(d2)\mathrm{MVP}(n)(d_2). Every entry path to ⟨sp,d1⟩\langle s_p, d_1 \rangle is a valid path, so MVP(sp)(d1)⊑EN(p,d1)\mathrm{MVP}(s_p)(d_1) \sqsubseteq \mathrm{EN}(p, d_1), and by (∗)(\ast) and monotonicity the right side is at most MVP(n)(d2)\mathrm{MVP}(n)(d_2). For the other direction, (∗)(\ast) for sps_p gives MVP(sp)(d1)=⊓d1′SL(sp,d1′,d1)(EN(p,d1′))\mathrm{MVP}(s_p)(d_1) = \mathop{\large\sqcap}_{d_1'} \mathrm{SL}(s_p, d_1', d_1)(\mathrm{EN}(p, d_1')). A same-level path to ⟨sp,d1⟩\langle s_p, d_1 \rangle followed by one from ⟨sp,d1⟩\langle s_p, d_1 \rangle to ⟨n,d2⟩\langle n, d_2 \rangle is same-level, so SL(n,d1,d2)∘SL(sp,d1′,d1)⊒SL(n,d1′,d2)\mathrm{SL}(n, d_1, d_2) \circ \mathrm{SL}(s_p, d_1', d_1) \sqsupseteq \mathrm{SL}(n, d_1', d_2). With (F2), the right side is at least ⊓d1′SL(n,d1′,d2)(EN(p,d1′))=MVP(n)(d2)\mathop{\large\sqcap}_{d_1'} \mathrm{SL}(n, d_1', d_2)(\mathrm{EN}(p, d_1')) = \mathrm{MVP}(n)(d_2). □\square

Lemma 8 (termination). The algorithm stops.

Proof. By (F3), each JJ, TT and SS changes at most three times. There are finitely many keys, and each change puts at most one key on the worklist. So Phase I takes finitely many keys off the worklist, and each removal does a finite amount of work. In Phase II each value changes at most twice, from ⊤\top to an integer and from there to ⊥\bot. So each pair enters the worklist at most twice. L20 is one pass over the keys. □\square

Theorem (cost). Let NN be the number of nodes of G∗G^*, EE its number of edges and CC its number of call sites. Assume that the meet, the composition and the application of micro-functions take constant time, as they do with integers of bounded size, and use hash tables with constant expected cost per operation. Then the algorithm runs in O(ED3)O(E D^3) time and uses O(ND2+CD2)O(N D^2 + C D^2) space.

Proof. Write D′=D+1D' = D + 1. A node has at most D′2D'^2 keys, and each is taken off at most three times, once per change.

  • An ordinary node nn with deg⁡(n)\deg(n) successors gives at most deg⁡(n)D′\deg(n) D' calls of PROPAGATE per removal. In total 3D′3deg⁡(n)3 D'^3 \deg(n), and O(ED′3)O(E D'^3) over all nodes.
  • A call node gives at most 3D′3 D' calls per removal at L6 and L7, since a pair (c,d2)(c, d_2) has at most D′D' summary functions. In total 9D′39 D'^3 per call site.
  • An exit node gives at most D′D' meets at L10 per removal and per call site. In total 3D′33 D'^3 per call site, since each call site calls one procedure. Each T(c,d1,d5)T(c, d_1, d_5) changes at most three times, there are D′2D'^2 of them per site, and each change runs L11 over at most D′D' facts: 3D′33 D'^3 per site. Each S(c,d4,d5)S(c, d_4, d_5) changes at most three times, and each change runs L13 over at most D′D' sources: 3D′33 D'^3 per site.
  • Phase II takes each pair at a start node or a call node off at most twice. A start node of pp runs L18 over at most (1+calls(p))D′(1 + \mathrm{calls}(p)) D' keys per removal, which is O((N+C)D′2)O((N + C) D'^2) in total. A call node runs L19 over at most D′D' facts per removal, which is O(CD′2)O(C D'^2). L20 is one pass over at most ND′2N D'^2 keys.

A call site has three edges in EE, so C≤EC \le E, and the total is O(ED′3)=O(ED3)O(E D'^3) = O(E D^3). The keys, their functions and the source and target indexes take O(ND′2)O(N D'^2) space. The summary functions, the functions TT and the inverse call maps take O(D′2)O(D'^2) per call site, and the values take O(ND′)O(N D'). □\square

Without the functions TT, the exit case would compose every key of eqe_q with every call edge into ⟨sq,d1⟩\langle s_q, d_1 \rangle and with every source of the call node. That is D′4D'^4 steps per call site in the worst case. The functions TT keep this case at D′3D'^3.

Complexity

  • Phase I. A node has at most (D+1)2(D+1)^2 keys, and each is taken off the worklist at most three times, once per change. So the counts of IFDS grow by a constant factor: O(ED3)O(E D^3) for ordinary nodes and O(D3)O(D^3) per call site for call nodes and exit nodes.
  • Phase II. Each value at a start node or a call node changes at most twice. Each time a start value changes, L18 looks at the keys of that entry fact at the start node and at each call node of the procedure. L20 is one pass over the keys. This is O((N+C)D2)O((N + C) D^2).
  • Total. O(ED3)O(E D^3) time and O(ND2+CD2)O(N D^2 + C D^2) space, with hash tables and micro-functions of constant size. Each meet, composition and application is O(1)O(1) here when integers fit in a word.
  • Best case. Building the supergraph reads the program, Θ(N+E)\Theta(N + E).
  • Few targets per fact. In linear constant propagation a statement sends a variable to itself and to at most one other variable. So the flow steps stay near the number of keys, far below the D3D^3 factor per edge.

The tables below are measured, not proved. The first has random modules of the toy IR with loops and recursion. f0 calls f1, each fi calls f(i+1) and one random procedure, and some arguments are constants.

procedures variables NN EE DD keys jump changes summary changes value changes E(D+1)3E (D+1)^3 ms
4 4 133 155 15 1509 1688 16 122 634880 5.2
16 4 527 615 15 5756 6371 65 459 2519040 20.9
16 16 711 801 27 13567 14490 68 869 17583552 75.6
64 4 2061 2430 15 21926 24562 297 1773 9953280 248.4
64 16 2762 3127 27 50878 54734 304 3313 68643904 626.1

Most keys get one function and keep it. At most about one key in eight goes down after it is found. The second table is a worst case for the number of keys. A procedure g with kk parameters moves them around in a loop with linear steps, so every entry fact reaches every variable, and at the loop head the lines meet into points and then into bot. main calls g twice.

kk NN EE DD keys jump changes summary changes value changes E(D+1)3E (D+1)^3 ms
4 14 17 7 246 458 18 19 8704 1.7
8 18 21 11 1058 2054 34 35 36288 6.9
16 26 29 19 5946 11774 66 67 232000 85.6
32 42 45 35 39530 78830 130 131 2099520 435.8

Here the keys come close to N(D+1)2N (D+1)^2, and almost every key changes twice. The times were taken on a busy machine, so only the counts are reliable.

Properties

  • Exact. For a distributive problem whose micro-functions are closed under meet and composition, the result is the meet over all valid paths, with and without recursion.
  • Relations, not values. A summary function keeps how the result depends on the argument. One summary serves callers with different constant arguments.
  • IFDS as a special case. With the two-point lattice and the identity on every edge, Phase I finds exactly the path edges of IFDS, and a fact holds where its value is not ⊤\top.
  • Order free. The final jump functions and values do not depend on the order of the worklists.
  • Only what is reached. Keys exist only for entry facts that some valid path reaches.

Variants and improvements

  • Copy constant propagation. Without lines and points, only const, identity and bot remain. This is cheaper and finds constants that are only copied across calls.
  • Affine relations. Linear constant propagation follows one variable at a time. Relations between several variables, such as x+y=10x + y = 10, need weighted pushdown systems or other summary-based methods, which cost more.
  • Solvers. Heros (Bodden 2012) runs IDE problems on Soot for Java. PhASAR (Schubert, Hermann and Bodden 2019) runs them on LLVM IR. Both build the supergraph on demand.
  • Typestate. IDE is also used for typestate, with an object as the fact and the set of its possible states as the value.
  • Other forms. Like IFDS, IDE can be read as a functional approach where each procedure summary is stored one pair of facts at a time. It is also a weighted form of CFL-reachability and of pushdown reachability.

When to use it

Use IDE when the result at a point is a value per variable, the transformers are distributive, and you want precision across calls. Linear constant propagation, copy constants and typestate fit. If the facts have no values, IFDS is simpler. If one result depends on two variables at once, as in x = a + b with both unknown, the transformer is not distributive in this sense, and IDE gives bot. Then use an intraprocedural method such as sparse conditional constant propagation inside procedures, or a non-distributive functional approach.

Pitfalls

  • Forms must be unique. L22 stops when the new function equals the old one. If one function has two forms, the test can fail forever or miss a change. Keep every micro-function in one normal form, or compare the functions themselves.
  • Integer overflow. The meet of two lines solves a1l+b1=a2l+b2a_1 l + b_1 = a_2 l + b_2. With machine integers that wrap around, this equation can have several solutions, and the point form is wrong. Use exact integers, or treat a possible overflow as bot.
  • Infinite height. Full linear functions over the integers are fine here because each chain has at most three steps. A richer function space without a height bound may not stop.
  • Functions on ⊤\top. Every micro-function must map ⊤\top to ⊤\top, or a fact that no path reaches can give a value. This holds for const k too, although it ignores every other input.
  • Branches are ignored. The result is the meet over valid paths of the graph, so a branch that is never taken still counts. A recursive procedure is analysed at every depth, even when a test stops the recursion early.
  • Values at other nodes. Running the Phase II worklist over every node is correct but costs more. Only start nodes and call nodes need it.

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.

ide_framework.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ide-framework/. The authors are listed in prov/60PTYF.jsonl.
"""The IDE algorithm of Sagiv, Reps and Horwitz, with linear constant
propagation on the toy IR as the instance.

A module is a dict from procedure name to toyir.Program, as for IFDS. The
supergraph has a node (proc, label, i) for instruction i of a block, a node
for each terminator (i = len(instrs)) and an exit node (proc, EXIT, 0) per
procedure. The facts of a procedure are its variables and RET; ZERO is the
extra fact. Every exploded edge carries a micro-function on values.

Values: TOP (no value seen), an int, or BOT (not a constant).
Micro-functions, in a form that is unique for each function:

    ("top",)          l -> TOP for every l, the function of no path
    ("bot",)          l -> BOT
    ("const", k)      l -> k
    ("line", a, b)    l -> a*l + b for an int l, BOT -> BOT   (a != 0)
    ("point", l0, v)  l0 -> v, any other l -> BOT

Every function maps TOP to TOP. A value that some path reaches is never
TOP, so only the behaviour on ints and BOT matters, and there the forms
above are closed under meet and composition, with no loss.
"""

from collections import Counter, deque

import toyir

ZERO = "0"
RET = "RET"
EXIT = "$exit"
TOP = "top"
BOT = "bot"

TOPF = ("top",)
BOTF = ("bot",)
ID = ("line", 1, 0)


# ------------------------------------------------------------------ values


def meet_val(a, b):
    if a == TOP:
        return b
    if b == TOP or a == b:
        return a
    return BOT


def apply(f, l):
    """The value of the micro-function f at l."""
    if l == TOP or f[0] == "top":
        return TOP
    k = f[0]
    if k == "bot":
        return BOT
    if k == "const":
        return f[1]
    if l == BOT:
        return BOT
    if k == "line":
        return f[1] * l + f[2]
    return f[2] if l == f[1] else BOT


def _point_or_bot(num, den, value):
    """The point function at l0 = num / den with the given value, or BOT
    when l0 is not an int (or the value is BOT)."""
    if value == BOT or num % den != 0:
        return BOTF
    return ("point", num // den, value)


def meet_fn(f, g):
    """The pointwise meet of two micro-functions."""
    if f[0] == "top":
        return g
    if g[0] == "top" or f == g:
        return f
    if f[0] == "bot" or g[0] == "bot":
        return BOTF
    if f[0] > g[0]:
        f, g = g, f
    # Now f[0] <= g[0] in the order const < line < point.
    if f[0] == "const" and g[0] == "const":
        return BOTF
    if f[0] == "const" and g[0] == "line":
        k, a, b = f[1], g[1], g[2]
        return _point_or_bot(k - b, a, k)
    if f[0] == "const":  # g is a point
        return g if g[2] == f[1] else BOTF
    if f[0] == "line" and g[0] == "line":
        a1, b1, a2, b2 = f[1], f[2], g[1], g[2]
        if a1 == a2:
            return BOTF
        num, den = b2 - b1, a1 - a2
        if num % den != 0:
            return BOTF
        l0 = num // den
        return ("point", l0, a1 * l0 + b1)
    if f[0] == "line":  # g is a point
        return g if f[1] * g[1] + f[2] == g[2] else BOTF
    return BOTF  # two different points


def compose(g, f):
    """The micro-function g after f."""
    if f[0] == "top" or g[0] == "top":
        return TOPF
    if g[0] == "bot" or g[0] == "const":
        return g
    if f[0] == "bot":
        return BOTF
    if f[0] == "const":
        v = apply(g, f[1])
        return BOTF if v == BOT else ("const", v)
    if f[0] == "point":
        v = apply(g, f[2])
        return BOTF if v == BOT else ("point", f[1], v)
    a1, b1 = f[1], f[2]  # f is a line
    if g[0] == "line":
        return ("line", g[1] * a1, g[1] * b1 + g[2])
    return _point_or_bot(g[1] - b1, a1, g[2])  # g is a point


# ------------------------------------------------------------- supergraph


def _linear(op, a, b):
    """The micro-function of x = a op b, as (source, function): source is a
    variable, or ZERO for a function that ignores its input."""
    if isinstance(a, int) and isinstance(b, int):
        try:
            return ZERO, ("const", toyir._binop(op, a, b))
        except toyir._Trap:
            return ZERO, BOTF
    if isinstance(a, str) and isinstance(b, str):
        return ZERO, BOTF
    if op == "+":
        return (a, ("line", 1, b)) if isinstance(a, str) else (b, ("line", 1, a))
    if op == "-":
        return (a, ("line", 1, -b)) if isinstance(a, str) else (b, ("line", -1, a))
    if op == "*":
        var, k = (a, b) if isinstance(a, str) else (b, a)
        return (ZERO, ("const", 0)) if k == 0 else (var, ("line", k, 0))
    return ZERO, BOTF


class Supergraph:
    """The supergraph of a module and the exploded edges of linear constant
    propagation. Each flow method returns a list of (fact, micro-function)."""

    def __init__(self, module, main=None):
        self.module = module
        self.main = main if main is not None else next(iter(module))
        self.facts = {}
        self.start = {}
        self.exit = {}
        self.succ = {}
        self.callee = {}
        self.ret_site = {}
        self.callers = {p: [] for p in module}
        self.calls_in = {p: [] for p in module}
        self.nodes = []
        self.proc = {}
        for p, prog in module.items():
            names = set(prog.params)
            for label, blk in prog.blocks.items():
                for i, ins in enumerate(blk.instrs):
                    if ins[0] not in ("const", "copy", "op", "call"):
                        raise ValueError("unsupported instruction: %r" % (ins,))
                    names.add(ins[1])
                    names.update(toyir.uses(ins))
                    node = (p, label, i)
                    self.nodes.append(node)
                    if ins[0] == "call":
                        q = ins[2]
                        if q not in module:
                            raise ValueError("unknown procedure %r" % q)
                        if len(ins[3]) != len(module[q].params):
                            raise ValueError("wrong number of arguments for %r" % q)
                        self.callee[node] = q
                        self.ret_site[node] = (p, label, i + 1)
                        self.callers[q].append(node)
                        self.calls_in[p].append(node)
                    else:
                        self.succ[node] = [(p, label, i + 1)]
                names.update(toyir.term_uses(blk.term))
                tnode = (p, label, len(blk.instrs))
                self.nodes.append(tnode)
                if blk.term[0] == "ret":
                    self.succ[tnode] = [(p, EXIT, 0)]
                else:
                    self.succ[tnode] = [(p, s, 0) for s in toyir.succs(prog, label)]
            if RET in names or ZERO in names:
                raise ValueError("reserved name used as a variable")
            self.facts[p] = sorted(names) + [RET]
            self.start[p] = (p, prog.entry, 0)
            self.exit[p] = (p, EXIT, 0)
            self.nodes.append(self.exit[p])
            self.succ[self.exit[p]] = []
        for n in self.nodes:
            self.proc[n] = n[0]

    def num_edges(self):
        return sum(len(v) for v in self.succ.values()) + 3 * len(self.callee)

    def instr(self, n):
        p, label, i = n
        blk = self.module[p].blocks[label]
        return blk.instrs[i] if i < len(blk.instrs) else blk.term

    def normal_flow(self, n, m, d):
        ins = self.instr(n)
        k = ins[0]
        if k == "jump" or k == "br":
            return [(d, ID)]
        if k == "ret":
            a = ins[1]
            out = [(d, ID)]
            if d == ZERO and isinstance(a, int):
                out.append((RET, ("const", a)))
            elif d == a:
                out.append((RET, ID))
            return out
        x = ins[1]
        if k == "const":
            src, fn = ZERO, ("const", ins[2])
        elif k == "copy":
            src, fn = ins[2], ID
        else:
            src, fn = _linear(ins[2], ins[3], ins[4])
        out = []
        if d != x:
            out.append((d, ID))
        if d == src:
            out.append((x, fn))
        return out

    def call_flow(self, c, d):
        ins = self.instr(c)
        params = self.module[ins[2]].params
        if d == ZERO:
            out = [(ZERO, ID)]
            out += [(params[j], ("const", a)) for j, a in enumerate(ins[3]) if isinstance(a, int)]
            return out
        return [(params[j], ID) for j, a in enumerate(ins[3]) if a == d]

    def c2r_flow(self, c, d):
        return [] if d == self.instr(c)[1] else [(d, ID)]

    def ret_flow(self, c, d):
        if d == ZERO:
            return [(ZERO, ID)]
        return [(self.instr(c)[1], ID)] if d == RET else []


# -------------------------------------------------------------- the solver


def ide(sg, seeds=None):
    """Run IDE. seeds maps each parameter of main to its value at the start
    (an int or BOT); a missing parameter is BOT. Returns (V, stats), where
    V[n] maps each variable with a value other than TOP to that value."""
    seeds = dict(seeds or {})
    main = sg.main
    stats = Counter()
    jump = {}  # (n, d1, d2) -> the jump function from <s_p, d1> to <n, d2>
    sources = {}  # (n, d2) -> the d1 with a jump function to <n, d2>
    targets = {}  # (n, d1) -> the d2 with a jump function from <s_p, d1> to <n, d2>
    summary = {}  # (c, d4) -> {d5: the summary function from <c, d4> to <r, d5>}
    through = {}  # (c, d1, d5) -> meet of ret o jump(e_q, d1, d2) over d2
    inv_call = {}  # c -> d1 -> [(d4, h)] for the call edges <c, d4> -> <s_q, d1>
    for c in sg.callee:
        inv = {}
        for d4 in sg.facts[sg.proc[c]] + [ZERO]:
            for d1, h in sg.call_flow(c, d4):
                inv.setdefault(d1, []).append((d4, h))
        inv_call[c] = inv
    work = deque()
    queued = set()

    def propagate(n, d1, d2, f):
        key = (n, d1, d2)
        old = jump.get(key, TOPF)
        new = meet_fn(old, f)
        stats["meets"] += 1
        if new != old:  # @line L22
            if old == TOPF:
                stats["path_edges"] += 1
                sources.setdefault((n, d2), set()).add(d1)
                targets.setdefault((n, d1), set()).add(d2)
            jump[key] = new
            stats["jump_changes"] += 1
            if key not in queued:
                queued.add(key)
                work.append(key)

    # Phase I: jump functions and summary functions.
    s_main = sg.start[main]  # @line L1
    for d in [ZERO] + list(sg.module[main].params):  # @line L2
        propagate(s_main, d, d, ID)
    while work:  # @line L3
        key = work.popleft()  # @line L4
        queued.discard(key)
        n, d1, d2 = key
        f = jump[key]
        stats["pops"] += 1
        p = sg.proc[n]
        if n in sg.callee:  # @line L5
            c, q, r = n, sg.callee[n], sg.ret_site[n]
            for d3, _h in sg.call_flow(c, d2):  # @line L6
                propagate(sg.start[q], d3, d3, ID)
            for d3, g in sg.c2r_flow(c, d2):  # @line L7
                propagate(r, d1, d3, compose(g, f))
            for d3, s in list(summary.get((c, d2), {}).items()):
                propagate(r, d1, d3, compose(s, f))
        elif n == sg.exit[p]:  # @line L8
            for c in sg.callers[p]:  # @line L9
                r = sg.ret_site[c]
                for d5, g in sg.ret_flow(c, d2):
                    tkey = (c, d1, d5)
                    told = through.get(tkey, TOPF)
                    t = meet_fn(told, compose(g, f))  # @line L10
                    if t == told:
                        continue
                    through[tkey] = t
                    for d4, h in inv_call[c].get(d1, ()):  # @line L11
                        sums = summary.setdefault((c, d4), {})
                        sold = sums.get(d5, TOPF)
                        s = meet_fn(sold, compose(t, h))  # @line L12
                        if s == sold:
                            continue
                        sums[d5] = s
                        stats["summary_changes"] += 1
                        for d3 in list(sources.get((c, d4), ())):  # @line L13
                            propagate(r, d3, d5, compose(s, jump[(c, d3, d4)]))
        else:
            for m in sg.succ[n]:  # @line L14
                for d3, g in sg.normal_flow(n, m, d2):
                    propagate(m, d1, d3, compose(g, f))

    # Phase II: values.
    val = {}
    work2 = deque()
    in_work2 = set()

    def lower(n, d, v):
        old = val.get((n, d), TOP)
        new = meet_val(old, v)
        if new != old:  # @line L23
            val[(n, d)] = new
            stats["value_changes"] += 1
            if (n, d) not in in_work2:
                in_work2.add((n, d))
                work2.append((n, d))

    lower(s_main, ZERO, BOT)  # @line L15
    for x in sg.module[main].params:
        lower(s_main, x, seeds.get(x, BOT))
    while work2:  # @line L16
        n, d = work2.popleft()  # @line L17
        in_work2.discard((n, d))
        v = val[(n, d)]
        p = sg.proc[n]
        if n == sg.start[p]:  # @line L18
            for m in [n] + sg.calls_in[p]:
                for d2 in list(targets.get((m, d), ())):
                    lower(m, d2, apply(jump[(m, d, d2)], v))
        if n in sg.callee:  # @line L19
            q = sg.callee[n]
            for d3, h in sg.call_flow(n, d):
                lower(sg.start[q], d3, apply(h, v))
    for (n, d1, d2), f in jump.items():  # @line L20
        p = sg.proc[n]
        if n == sg.start[p] or n in sg.callee:
            continue
        v = val.get((sg.start[p], d1), TOP)
        if v != TOP:
            new = meet_val(val.get((n, d2), TOP), apply(f, v))
            if new != TOP:
                val[(n, d2)] = new
    V = {n: {} for n in sg.nodes}  # @line L21
    for (n, d), v in val.items():
        if d != ZERO and v != TOP:
            V[n][d] = v
    return V, stats


def ide_framework(module, main=None, seeds=None):
    """Convenience wrapper: the constants at every node of the module."""
    sg = Supergraph(module, main)
    V, _ = ide(sg, seeds)
    return V
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_ide_framework.py 431 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ide-framework/. The authors are listed in prov/60PTYF.jsonl.

import random

import toyir
from toyir import parse, random_program
from ide_framework import (
    BOT,
    BOTF,
    EXIT,
    ID,
    RET,
    TOP,
    TOPF,
    ZERO,
    Supergraph,
    apply,
    compose,
    ide,
    ide_framework,
    meet_fn,
    meet_val,
)

# The example of the page: add is linear in its first parameter, so each
# call with a constant first argument gives a constant, even though the
# first parameter is not a constant at the entry of add.
ADD = """
# params: a, b
B0:
  t = a * 3
  u = t + 1
  ret u
"""

MAIN = """
# params: n
B0:
  x = 2
  y = call add(x, n)
  z = call add(n, x)
  v = 4
  w = call add(v, y)
  ret w
"""


def add_module():
    return {"main": parse(MAIN), "add": parse(ADD)}


def leq(a, b):
    """a is below or equal to b in the value lattice."""
    return a == BOT or b == TOP or a == b


# ---------------------------------------------------- micro-function algebra

DOMAIN = list(range(-40, 41)) + [BOT]


def table(f):
    return [apply(f, l) for l in DOMAIN]


def random_fn(rng):
    r = rng.random()
    if r < 0.1:
        return BOTF
    if r < 0.3:
        return ("const", rng.randint(-10, 10))
    if r < 0.8:
        return ("line", rng.choice([-3, -2, -1, 1, 2, 3]), rng.randint(-6, 6))
    return ("point", rng.randint(-5, 5), rng.randint(-10, 10))


def canonical(f):
    if f[0] == "line":
        return f[1] != 0
    if f[0] == "point":
        return f[2] != BOT and f[2] != TOP
    return f[0] in ("top", "bot", "const")


def test_micro_functions() -> None:
    rng = random.Random(6001)
    for _ in range(800):
        f, g = random_fn(rng), random_fn(rng)
        m = meet_fn(f, g)
        assert canonical(m)
        assert table(m) == [meet_val(x, y) for x, y in zip(table(f), table(g))]
        assert meet_fn(g, f) == m
        c = compose(g, f)
        assert canonical(c)
        assert table(c) == [apply(g, apply(f, l)) for l in DOMAIN]
        # Distributive over the meet of two inputs.
        l1, l2 = rng.choice(DOMAIN), rng.choice(DOMAIN)
        assert apply(f, meet_val(l1, l2)) == meet_val(apply(f, l1), apply(f, l2))
        # The same table means the same tuple.
        if table(f) == table(g):
            assert f == g
    for f in [BOTF, ("const", 3), ("line", 2, 1), ("point", 1, 4)]:
        assert meet_fn(TOPF, f) == f and compose(f, TOPF) == TOPF and compose(TOPF, f) == TOPF
        assert compose(ID, f) == f and compose(f, ID) == f
        assert apply(f, TOP) == TOP
    # A chain of meets goes down at most three times from TOPF.
    for _ in range(400):
        f, steps = TOPF, 0
        for _ in range(8):
            g = meet_fn(f, random_fn(rng))
            if g != f:
                steps += 1
            f = g
        assert steps <= 3


# ------------------------------------------------------------ brute force


def step(env, flow):
    """Push an environment (fact -> value, TOP left out) over one edge."""
    out = {}
    for d, v in env.items():
        for d2, g in flow(d):
            out[d2] = meet_val(out.get(d2, TOP), apply(g, v))
    return out


def start_env(sg, seeds):
    env = {ZERO: BOT}
    for x in sg.module[sg.main].params:
        env[x] = (seeds or {}).get(x, BOT)
    return env


def mvp_by_paths(sg, seeds=None, cap=20000, max_depth=None):
    """The meet over all valid paths, by walking each valid path from the
    start of main with its own environment. At a call node the path either
    enters the callee or takes the call-to-return edge; at an exit it goes
    back to the call on top of its stack. Returns None after cap steps."""
    M = {n: {} for n in sg.nodes}
    todo = [(sg.start[sg.main], start_env(sg, seeds), ())]
    steps = 0
    while todo:
        n, env, stack = todo.pop()
        steps += 1
        if steps > cap:
            return None
        for d, v in env.items():
            M[n][d] = meet_val(M[n].get(d, TOP), v)
        if n in sg.callee:
            if max_depth is None or len(stack) < max_depth:
                todo.append((sg.start[sg.callee[n]], step(env, lambda d: sg.call_flow(n, d)), stack + (n,)))
            todo.append((sg.ret_site[n], step(env, lambda d: sg.c2r_flow(n, d)), stack))
        elif n[1] == EXIT:
            if stack:
                c = stack[-1]
                todo.append((sg.ret_site[c], step(env, lambda d: sg.ret_flow(c, d)), stack[:-1]))
        else:
            for m in sg.succ[n]:
                todo.append((m, step(env, lambda d: sg.normal_flow(n, m, d)), stack))
    for n in M:
        M[n].pop(ZERO, None)
    return M


def mfp_supergraph(sg, seeds=None):
    """Context-insensitive constant propagation on the supergraph: every
    exit flows back to every caller."""
    IN = {n: {} for n in sg.nodes}
    work, queued = [], set()

    def add(m, env):
        changed = False
        for d, v in env.items():
            new = meet_val(IN[m].get(d, TOP), v)
            if new != IN[m].get(d, TOP):
                IN[m][d] = new
                changed = True
        if changed and m not in queued:
            queued.add(m)
            work.append(m)

    add(sg.start[sg.main], start_env(sg, seeds))
    while work:
        n = work.pop()
        queued.discard(n)
        env = IN[n]
        if n in sg.callee:
            q = sg.callee[n]
            add(sg.start[q], step(env, lambda d: sg.call_flow(n, d)))
            add(sg.ret_site[n], step(env, lambda d: sg.c2r_flow(n, d)))
            add(sg.ret_site[n], step(IN[sg.exit[q]], lambda d: sg.ret_flow(n, d)))
        elif n[1] == EXIT:
            for c in sg.callers[n[0]]:
                if ZERO in IN[c]:
                    add(sg.ret_site[c], step(env, lambda d: sg.ret_flow(c, d)))
        else:
            for m in sg.succ[n]:
                add(m, step(env, lambda d: sg.normal_flow(n, m, d)))
    for n in IN:
        IN[n].pop(ZERO, None)
    return IN


def run_recorded(module, main, args, fuel=3000):
    """Run the module and record the variables before each node. Returns
    the outcome, in the form of toyir.run, and a list of (node, env)."""
    seen = []
    stack = []
    p = main
    prog = module[p]
    env = dict(zip(prog.params, args))
    label, pc, dest = prog.entry, 0, None

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise toyir._Fuel()
        fuel -= 1

    def val(a):
        return a if isinstance(a, int) else env[a]

    try:
        while True:
            blk = module[p].blocks[label]
            called = False
            while pc < len(blk.instrs):
                ins = blk.instrs[pc]
                seen.append(((p, label, pc), dict(env)))
                tick()
                k = ins[0]
                if k == "const":
                    env[ins[1]] = ins[2]
                elif k == "copy":
                    env[ins[1]] = val(ins[2])
                elif k == "op":
                    env[ins[1]] = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
                else:
                    q = module[ins[2]]
                    stack.append((p, label, pc + 1, ins[1], env))
                    env = dict(zip(q.params, [val(a) for a in ins[3]]))
                    p, label, pc = ins[2], q.entry, 0
                    called = True
                    break
                pc += 1
            if called:
                continue
            seen.append(((p, label, len(blk.instrs)), dict(env)))
            tick()
            t = blk.term
            if t[0] == "jump":
                label, pc = t[1], 0
                continue
            if t[0] == "br":
                label, pc = (t[2] if val(t[1]) != 0 else t[3]), 0
                continue
            v = val(t[1])
            seen.append(((p, EXIT, 0), dict(env, **{RET: v})))
            if not stack:
                return ("ret", v), seen
            p, label, pc, dest, env = stack.pop()
            env[dest] = v
    except toyir._Trap:
        return ("trap",), seen
    except toyir._Fuel:
        return ("fuel",), seen


# ---------------------------------------------------------- random modules


def random_module(rng, recursive=False):
    """Three procedures f0, f1 and f2 from random_program, with two to four
    calls x = call fj(a, b) added. Without recursion, fi only calls fj with
    j > i. A call in B0 goes after the constants that start B0."""
    names = ["f0", "f1", "f2"]
    module = {f: random_program(rng, 4, rng.randint(2, 4), True) for f in names}
    xs = ["x%d" % i for i in range(4)]
    for _ in range(rng.randint(2, 4)):
        i = rng.randrange(0, 3 if recursive else 2)
        j = rng.randrange(0, 3) if recursive else rng.randrange(i + 1, 3)
        prog = module[names[i]]
        label = rng.choice(list(prog.blocks))
        instrs = prog.blocks[label].instrs
        lo = 2 if label == prog.entry else 0
        pos = rng.randint(lo, len(instrs))
        args = [rng.choice(xs) if rng.random() < 0.6 else rng.randint(0, 5) for _ in range(2)]
        instrs.insert(pos, ("call", rng.choice(xs), names[j], args))
    return module


def bound_checks(sg, stats):
    D1 = max(len(f) for f in sg.facts.values()) + 1
    N = len(sg.nodes)
    assert stats["path_edges"] <= N * D1 * D1
    assert stats["jump_changes"] <= 3 * stats["path_edges"]
    assert stats["pops"] <= stats["jump_changes"]
    assert stats["summary_changes"] <= 3 * len(sg.callee) * D1 * D1
    assert stats["value_changes"] <= 2 * N * D1
    assert stats["meets"] <= 3 * sg.num_edges() * 3 * D1 ** 3


def check_sound(module, V, rng, fuel=3000):
    for _ in range(3):
        args = [rng.randint(-6, 9), rng.randint(-6, 9)]
        out, seen = run_recorded(module, "f0", args, fuel)
        assert out == toyir.run(module["f0"], args, fuel=fuel, funcs=module)
        for n, env in seen:
            for x, v in env.items():
                assert x in V[n], (n, x)
                assert V[n][x] == BOT or V[n][x] == v, (n, x, V[n][x], v)


# ------------------------------------------------------------------- tests


def test_add_example() -> None:
    module = add_module()
    sg = Supergraph(module, "main")
    V, stats = ide(sg)
    end = ("main", EXIT, 0)
    assert V[end] == {"n": BOT, "x": 2, "y": 7, "z": BOT, "v": 4, "w": 13, RET: 13}
    assert V[("add", "B0", 0)] == {"a": BOT, "b": BOT}
    # The summary of add maps a to RET by l -> 3l + 1. The first argument
    # is 2 at the first call and 4 at the third, so y = 7 and w = 13.
    M = mvp_by_paths(sg)
    assert M == V
    MFP = mfp_supergraph(sg)
    assert MFP[end]["y"] == BOT and MFP[end]["w"] == BOT
    bound_checks(sg, stats)
    assert run_recorded(module, "main", [5])[0] == ("ret", 13)


def test_seeded_main() -> None:
    module = add_module()
    sg = Supergraph(module, "main")
    V, _ = ide(sg, {"n": 5})
    end = ("main", EXIT, 0)
    assert V[end]["z"] == 16 and V[end]["w"] == 13
    assert V[("add", "B0", 0)]["a"] == BOT
    assert mvp_by_paths(sg, {"n": 5}) == V


def test_point_function() -> None:
    # Two branches give u = 3a + 1 and u = a + 5. The meet of the two
    # lines is the point function 2 -> 7, so a call with a = 2 gives 7 and
    # any other argument gives BOT.
    f = parse("# params: a, b\nB0:\n  br b L R\nL:\n  t = a * 3\n  u = t + 1\n  jump J\nR:\n  u = a + 5\n  jump J\nJ:\n  ret u\n")
    main = parse("# params: n\nB0:\n  x = 2\n  y = call f(x, n)\n  z = call f(3, n)\n  ret y\n")
    module = {"main": main, "f": f}
    sg = Supergraph(module, "main")
    V, _ = ide(sg)
    end = ("main", EXIT, 0)
    assert V[end]["y"] == 7 and V[end]["z"] == BOT
    assert mvp_by_paths(sg) == V


def test_recursion_keeps_linear_relation() -> None:
    # The analysis does not follow the branch, so it sees every depth d. At
    # depth d the base case returns k - d, and each of the d returns adds
    # 1, so down(k) returns k on every valid path. The summary of down is
    # the identity, and b = 3.
    down = parse("# params: k\nB0:\n  c = k < 1\n  br c done more\nmore:\n  j = k - 1\n  r = call down(j)\n  s = r + 1\n  ret s\ndone:\n  ret k\n")
    main = parse("# params: n\nB0:\n  a = 3\n  b = call down(a)\n  ret b\n")
    module = {"main": main, "down": down}
    V = ide_framework(module, "main")
    assert V[("main", EXIT, 0)]["b"] == 3
    MFP = mfp_supergraph(Supergraph(module, "main"))
    assert MFP[("main", EXIT, 0)]["b"] == BOT


def test_random_acyclic_modules() -> None:
    rng = random.Random(6101)
    srng = random.Random(6201)
    compared = strict = 0
    for _ in range(300):
        module = random_module(rng)
        sg = Supergraph(module, "f0")
        V, stats = ide(sg)
        bound_checks(sg, stats)
        M = mvp_by_paths(sg)
        if M is not None:
            compared += 1
            assert V == M
        MFP = mfp_supergraph(sg)
        for n in sg.nodes:
            assert set(MFP[n]) == set(V[n])
            assert all(leq(MFP[n][d], V[n][d]) for d in V[n])
        if any(MFP[n] != V[n] for n in sg.nodes):
            strict += 1
        check_sound(module, V, srng)
    assert compared >= 290
    assert strict >= 12


def test_random_recursive_modules() -> None:
    rng = random.Random(6102)
    srng = random.Random(6202)
    compared = 0
    for _ in range(100):
        module = random_module(rng, recursive=True)
        sg = Supergraph(module, "f0")
        V, stats = ide(sg)
        bound_checks(sg, stats)
        MFP = mfp_supergraph(sg)
        for n in sg.nodes:
            assert set(MFP[n]) == set(V[n])
            assert all(leq(MFP[n][d], V[n][d]) for d in V[n])
        # Paths with at most three open calls are some of the valid paths,
        # so their meet is above or equal to the result.
        M = mvp_by_paths(sg, cap=5000, max_depth=3)
        if M is not None:
            compared += 1
            for n in sg.nodes:
                assert set(M[n]) <= set(V[n])
                assert all(leq(V[n][d], M[n][d]) for d in M[n])
        check_sound(module, V, srng, fuel=400)
    assert compared >= 85


def test_bad_input() -> None:
    bad = {"main": parse("# params: a\nB0:\n  x = call nope(a)\n  ret x\n")}
    try:
        Supergraph(bad)
    except ValueError:
        pass
    else:
        raise AssertionError("unknown callee accepted")

History

Callahan, Cooper, Kennedy and Torczon (1986) introduced jump functions and return functions to carry constants across calls in a practical compiler. Sharir and Pnueli (1981) had defined the meet over valid paths and the functional approach, in which each procedure is summarized as a function. Reps, Horwitz and Sagiv (POPL 1995) turned the functional approach for finite distributive subset problems into reachability on the exploded supergraph. Sagiv, Reps and Horwitz then generalized it to environments. They presented IDE at TAPSOFT 1995, and the journal version appeared in Theoretical Computer Science in 1996. It gave the two phases, linear constant propagation as the main example, and the O(ED3)O(E D^3) bound. Later tools such as Heros (2012) and PhASAR (2019) made IDE available for Java and for C and C++.

References

  1. Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, Theoretical Computer Science 167(1-2), 131 to 170, 1996, the IDE problem, environment transformers, the exploded supergraph with micro-functions, the two-phase algorithm, linear constant propagation and its O(E D^3) bound
  2. Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, TAPSOFT '95: Theory and Practice of Software Development, Lecture Notes in Computer Science, 651 to 665, 1995, the conference version of the same work
  3. Thomas Reps, Susan Horwitz and Mooly Sagiv, Precise interprocedural dataflow analysis via graph reachability, Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '95), 49 to 61, 1995, the IFDS tabulation algorithm that Phase I generalizes
  4. David Callahan, Keith D. Cooper, Ken Kennedy and Linda Torczon, Interprocedural constant propagation, Proceedings of the 1986 SIGPLAN Symposium on Compiler Construction, 152 to 161, 1986, jump functions and return functions for constants across calls, the earlier practical approach
  5. Eric Bodden, Inter-procedural data-flow analysis with IFDS/IDE and Soot, Proceedings of the ACM SIGPLAN International Workshop on State of the Art in Java Program Analysis (SOAP '12), 3 to 8, 2012, the Heros solver for IFDS and IDE problems
  6. Philipp Dominik Schubert, Ben Hermann and Eric Bodden, PhASAR: an inter-procedural static analysis framework for C/C++, Tools and Algorithms for the Construction and Analysis of Systems (TACAS 2019), Lecture Notes in Computer Science, 393 to 410, 2019, an IFDS and IDE solver on LLVM IR
  7. Micha Sharir and Amir Pnueli, Two approaches to interprocedural data flow analysis, in Steven S. Muchnick and Neil D. Jones (eds.), Program Flow Analysis: Theory and Applications, Prentice-Hall, 1981, the meet over valid paths and the functional approach with procedure summaries

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 proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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
  • History with a source
  • a scene preset for the example