Algorithm Search⌘K

Algorithmadvanced

Weak topological ordering

Also called Bourdoncle iteration strategy.

Orders the nodes of a flow graph as nested components with heads, giving the points where to widen and a good order of iteration.

Time
O((k + 1)(n + m)) worst · averageΘ(n + m) best
Space
Θ(n) extra
Where
k = the largest number of components that contain one vertex; m = the number of edges between them; n = the number of vertices reachable from the root
Properties
deterministicrecursive
Origin
François Bourdoncle, 1993

A weak topological ordering (WTO) of a directed graph is a total order of its vertices with nested parentheses, such as entry (outer init (inner body) next) exit. Each parenthesized group is a strongly connected part of the graph, and its first vertex is its head. Bourdoncle's algorithm builds a WTO in O((k+1)(n+m))O((k + 1)(n + m)) time, where kk is the nesting depth, by applying Tarjan's SCC algorithm again inside each component. An abstract interpreter then iterates the equations in this order, stabilizes each inner component before the outer one, and applies the widening only at the heads. Every cycle of the graph passes through a head, so this is enough to make the iteration stop.

In plain words

An analyzer computes a value at each block of a program, and it must recompute the blocks of a loop until nothing changes. Two questions come up. In which order should it visit the blocks? And where must it widen, so that a loop with an unknown trip count does not keep it busy forever?

A WTO answers both. It lists the blocks so that, outside loops, every block comes after the blocks that feed it. A loop is written as a group in parentheses, with its entry block first. The analyzer runs through a group again and again until the entry block of the group stops changing. It widens only at the first block of each group. Inner loops are groups inside groups, and the analyzer settles an inner loop before it goes on with the outer one.

The problem

The input is a directed graph G=(V,E)G = (V, E), given by the successor lists succ(v)\mathit{succ}(v), and a root rr. In program analysis GG is a control flow graph and rr is its entry block. Let VrV_r be the set of vertices reachable from rr.

A hierarchical ordering of VrV_r is a sequence of the vertices of VrV_r, each once, with matched parentheses, where every opening parenthesis is followed at once by a vertex, the head of that component. For a vertex cc, ω(c)\omega(c) is the set of heads of the components that contain cc; a head belongs to its own component. Write u≺vu \prec v when uu comes before vv in the sequence. The ordering is a weak topological ordering when every edge u→vu \to v with u∈Vru \in V_r satisfies

(u≺v  and  v∉ω(u))or(v⪯u  and  v∈ω(u)).\bigl(u \prec v \ \text{ and } \ v \notin \omega(u)\bigr) \quad \text{or} \quad \bigl(v \preceq u \ \text{ and } \ v \in \omega(u)\bigr).

So an edge either goes forward, and does not enter a component through its head from inside, or it goes backward, to the head of a component that contains its source. A topological order of a graph without cycles is a WTO with no parentheses.

The second task is to solve equations xv=Fv(x)x_v = F_v(x), one for each vertex, over an abstract domain with a widening ∇\nabla, and to return values with Fv(x)⊑xvF_v(x) \sqsubseteq x_v at every vertex.

The algorithm

WTO uses a counter num\mathit{num}, a stack SS and a depth-first number DFN[v]\mathit{DFN}[v], which is 0 for a vertex not yet visited, a positive number for a vertex on the stack, and +∞+\infty for a vertex that is already placed. A partition PP is a list of elements; an element is a vertex or a component (h,C)(h, C), whose body CC is a partition. ITERATE is the recursive iteration strategy; every value x[v]x[v] is ⊥\bot at the start.

  1. WTO(G, r)
  2. 1for each v in V do DFN[v] ← 0
  3. 2num ← 0, S ← empty stack, P ← empty list
  4. 3VISIT(r, P)
  5. 4return P
  6. VISIT(v, P) ▷ returns the least DFN reached from v
  7. 5push v on S, num ← num + 1, DFN[v] ← num
  8. 6head ← DFN[v], loop ← false
  9. 7for each w in succ(v) do
  10. 8if DFN[w] = 0 then min ← VISIT(w, P) else min ← DFN[w]
  11. 9if min ≤ head then head ← min, loop ← true
  12. 10if head = DFN[v] then ▷ v is the root of a strongly connected part
  13. 11DFN[v] ← +∞, e ← pop S
  14. 12if loop then
  15. 13while e ≠ v do DFN[e] ← 0, e ← pop S
  16. 14add COMPONENT(v) to the front of P
  17. 15else add v to the front of P
  18. 16return head
  19. COMPONENT(v)
  20. 17C ← empty list
  21. 18for each w in succ(v) do
  22. 19if DFN[w] = 0 then VISIT(w, C)
  23. 20return (v, C)
  24. ITERATE(P)
  25. 21for each element e of P, in order do
  26. 22if e is a vertex v then x[v] ← F_v(x)
  27. 23else let (h, C) = e
  28. 24x[h] ← x[h] ∇ F_h(x)
  29. 25repeat
  30. 26ITERATE(C)
  31. 27t ← F_h(x)
  32. 28if t ⊑ x[h] then leave the repeat loop
  33. 29x[h] ← x[h] ∇ t

VISIT is Tarjan's algorithm with one change. Line L9 computes the least depth-first number that vv reaches, as Tarjan's low value does, and also records in loop\mathit{loop} whether vv reaches a vertex numbered at most vv itself, that is, whether vv lies on a cycle of its part. A vertex placed earlier has DFN=+∞\mathit{DFN} = +\infty, so it never lowers head\mathit{head}. When line L10 finds the root vv of a strongly connected part, either the part is vv alone with no self-loop (line L15), or line L13 takes the other vertices off the stack and marks them unvisited again. Line L14 then calls COMPONENT, which runs the same search on the part without vv: vv now has DFN=+∞\mathit{DFN} = +\infty, so every edge back to it is ignored, and the search splits the rest into smaller parts. Each finished element goes to the front of the list, so the elements come out in a topological order of the parts, as in Tarjan's algorithm.

ITERATE walks the WTO. A vertex outside every component is computed once (line L22). A component is computed again and again: the head is widened (lines L24 and L29), then the body is stabilized by a recursive call (line L26), and the loop ends when the head no longer grows (line L28). Only the head is tested. Only the heads are widened.

Example

The program has two nested loops. Its parameter is n; here n=3n = 3.

entry:
  i = 0
  jump outer
outer:
  t = i < 3
  br t init exit
init:
  j = 0
  jump inner
inner:
  u = j < i
  br u body next
body:
  j = j + 1
  jump inner
next:
  i = i + 1
  jump outer
exit:
  ret i

The edges are entry →\to outer, outer →\to init, outer →\to exit, init →\to inner, inner →\to body, inner →\to next, body →\to inner and next →\to outer, with the successors in this order. The table lists the calls of VISIT in the order in which they finish.

call DFN returns what happens
VISIT(body) 5 4 sees inner with DFN 4, so it is not a root
VISIT(next) 6 2 sees outer with DFN 2
VISIT(inner) 4 2 loop is true, but 2 < 4, so it is not a root
VISIT(init) 3 2 not a root
VISIT(exit) 7 7 a root with no loop: PP = [exit]
VISIT(outer) 2 2 a root with a loop: pop next, body, inner, init and set their DFN to 0; call COMPONENT(outer)
inside: VISIT(body) 10 9 sees inner with DFN 9, so it is not a root
inside: VISIT(next) 11 11 outer has DFN +∞+\infty; a root with no loop: CC = [next]
inside: VISIT(body) 12 12 called by COMPONENT(inner); inner has DFN +∞+\infty: C′C' = [body]
inside: VISIT(inner) 9 9 a root with a loop: CC = [(inner body), next]
inside: VISIT(init) 8 8 a root with no loop: CC = [init, (inner body), next]
VISIT(entry) 1 1 a root with no loop

The result is entry (outer init (inner body) next) exit. The heads are outer and inner; ω(body)={outer,inner}\omega(\mathit{body}) = \{\mathit{outer}, \mathit{inner}\}. The back edges body →\to inner and next →\to outer each go to a head that contains their source.

Now ITERATE runs an interval analysis on this WTO. The value of a block is the state at its start; j has no value before init, so it is ⊤\top there. The guard j < i on the edge to body refines j below the upper bound of i and i above the lower bound of j.

step vertex line ii jj note
1 entry L22 ⊤\top ⊤\top
2 outer L24 [0,0][0, 0] ⊤\top ⊥∇[0,0]\bot \nabla [0, 0]
3 init L22 [0,0][0, 0] ⊤\top
4 inner L24 [0,0][0, 0] [0,0][0, 0]
5 body L22 ⊥\bot ⊥\bot the guard j<ij < i fails
6 inner L28 [0,0][0, 0] [0,0][0, 0] stable: leave the inner loop
7 next L22 [0,0][0, 0] [0,0][0, 0]
8 outer L29 [0,+∞][0, +\infty] ⊤\top FF gives i∈[0,1]i \in [0, 1]; widen
9 init L22 [0,2][0, 2] ⊤\top
10 inner L24 [0,+∞][0, +\infty] [0,0][0, 0] FF gives i∈[0,2]i \in [0, 2]; the widening with the old [0,0][0, 0] jumps
11 body L22 [1,+∞][1, +\infty] [0,0][0, 0]
12 inner L29 [0,+∞][0, +\infty] [0,+∞][0, +\infty] FF gives j∈[0,1]j \in [0, 1]; widen
13 body L22 [1,+∞][1, +\infty] [0,+∞][0, +\infty]
14 inner L28 stable: leave the inner loop
15 next L22 [0,+∞][0, +\infty] [0,+∞][0, +\infty]
16 outer L28 stable: leave the outer loop
17 exit L22 [3,+∞][3, +\infty] ⊤\top

The run makes 17 evaluations of some FvF_v, with widening at two vertices only. The order of the evaluations is entry, outer, then init, inner, body, inner, next, outer, then the same pass with one more round of the inner loop, and last exit. Step 10 shows a weakness discussed under Pitfalls. Inside the inner loop i is at most 2, but the old value [0,0][0, 0] of the inner head makes the widening jump to +∞+\infty. A narrowing pass does not repair this, because the cycle inner →\to body →\to inner keeps the bound +∞+\infty alive. The restart variant below keeps i∈[0,2]i \in [0, 2] at inner, and a narrowing pass after it gives i∈[3,3]i \in [3, 3] at exit.

Correctness

There are three claims; the full proofs are in the proof file.

  1. WTO builds a weak topological ordering of VrV_r. VISIT finds the strongly connected parts of the graph as Tarjan's algorithm does, and it lists them in a topological order, because each part goes to the front of the list when it is finished. A part with a cycle becomes a component whose head is the first vertex of the part that the search reached, and whose body is, by induction on the number of vertices, a WTO of the part without its head. The edge condition follows by cases: an edge between two parts goes forward; an edge to the head of a part goes backward to a head that contains its source; any other edge inside a part is an edge of the smaller graph.
  2. Every cycle passes through a head. Take a cycle and its last vertex uu in the order. The next vertex vv on the cycle has v⪯uv \preceq u, so the edge condition puts vv in ω(u)\omega(u): vv is a head. So the vertices without the heads form a graph with no cycle, and the heads are enough as widening points.
  3. ITERATE stops with Fv(x)⊑x[v]F_v(x) \sqsubseteq x[v] at every vertex, if each FvF_v is monotone and ∇\nabla is a widening. Every assignment makes a value larger or keeps it, so the inputs of each head form an increasing chain over the whole run, and the widening makes the number of strict changes at each head finite. When the outer loop of a component ends, its head passes the test of line L28, and the edge condition shows that no value it depends on changes later. With sound FvF_v, the abstract domain claim then gives a sound result.
Proof: WTO builds a weak topological ordering, and the recursive strategy stops at a post-fixed pointfull

We use the names of the pseudocode on the main page. A vertex is done when its DFN is +∞+\infty. For a list LL of elements and a vertex uu in it, ωL(u)\omega_L(u) is the set of heads of the components of LL (at any depth) that contain uu. For the full WTO this is ω(u)\omega(u). If (h,C)(h, C) is an element of LL and uu is in CC, then

ωL(u)={h}∪ωC(u),ωL(h)={h}.(1)\omega_L(u) = \{h\} \cup \omega_C(u), \qquad \omega_L(h) = \{h\}. \tag{1}

The vertices of one element are next to each other in the flattened order, with the head first.

Part 1. The searches

A search Σ(W,s1,…,sq)\Sigma(W, s_1, \ldots, s_q) is a run of VISIT(si,P)(s_i, P) for i=1,…,qi = 1, \ldots, q in turn, on one list PP, where the call for sis_i is skipped if DFN[si]≠0\mathit{DFN}[s_i] \ne 0 at that time. WTO is the search Σ(V,r)\Sigma(V, r). COMPONENT(h)(h) is the search Σ(S∖{h},succ(h))\Sigma(S \setminus \{h\}, \mathit{succ}(h)) for the set SS named in Lemma 2. We say that a search starts in a clean state when

  • (C1) every vertex of WW has DFN 0,
  • (C2) every edge from a vertex of WW goes to a vertex of WW or to a done vertex,
  • (C3) every DFN already on the stack is smaller than every number that the search will give.

(C3) holds always, because num\mathit{num} only grows. Let RR be the set of vertices of WW that the start vertices reach by paths inside WW.

Lemma 1 (Tarjan). In a search from a clean state, VISIT behaves as Tarjan's algorithm on the graph G[W]G[W], with the edges to done vertices left out. In particular, as shown on the Tarjan page:

  • (T1) VISIT(v)(v) returns DFN[v]\mathit{DFN}[v] if and only if vv is the first vertex of its strongly connected component (SCC) of G[R]G[R] that the search reaches;
  • (T2) at that time the vertices on the stack from vv upward are exactly the SCC of vv;
  • (T3) if an edge of G[R]G[R] goes from the SCC AA to another SCC BB, then the root of BB reaches line L10 before the root of AA;
  • (T4) VISIT(v)(v) returns the least of DFN[v]\mathit{DFN}[v] and the numbers DFN[b]\mathit{DFN}[b] of the vertices bb on the stack that an edge a→ba \to b of the search tree below vv reaches.

Proof. Line L8 uses the returned value of a tree child and the DFN of any other successor. A successor ww that is on the stack has a finite DFN, which is Tarjan's rule. A done successor gives +∞+\infty, which never passes the test of line L9, so the edge has no effect. This is Tarjan's rule for a vertex of a finished component. An edge out of WW goes to a done vertex by (C2). Tarjan's algorithm uses the numbers only to compare them, so (C3) makes the numbers that are already on the stack harmless; the search never reaches those vertices anyway, by (C2). The only other difference is lines L13 and L14, and Lemma 2 shows that when line L14 ends, the vertices popped at line L13 are done and the stack is as Tarjan's algorithm leaves it. So the state that the rest of the search sees is the state of Tarjan's algorithm. □\square

Lemma 2. Let a search Σ(W,…)\Sigma(W, \ldots) start in a clean state. When it ends:

  • (a) every vertex of RR is done, every other vertex has its old DFN, and the stack is as at the start;
  • (b) the elements of PP correspond one to one to the SCCs of G[R]G[R], in an order such that every edge of G[R]G[R] goes from an element to the same element or to a later one;
  • (c) the element of an SCC SS is the vertex vv if S={v}S = \{v\} and v→vv \to v is not an edge; otherwise it is a component (h,C)(h, C), where hh is the first vertex of SS that the search reaches, and CC is the result of the search Σ(S∖{h},succ(h))\Sigma(S \setminus \{h\}, \mathit{succ}(h)), which starts in a clean state.

Proof. By strong induction on ∣W∣|W|. Assume the claim for all smaller sets.

The loop flag. Let vv be a root, so VISIT(v)(v) reaches line L10 with head=DFN[v]\mathit{head} = \mathit{DFN}[v]. The variable head\mathit{head} only goes down, so no successor gave a value below DFN[v]\mathit{DFN}[v], and loop\mathit{loop} is true if and only if some successor gave exactly DFN[v]\mathit{DFN}[v]. Let SS be the SCC of vv. If v→vv \to v is an edge, line L8 gives DFN[v]\mathit{DFN}[v] for it. If ∣S∣≥2|S| \ge 2, some edge u→vu \to v has u∈Su \in S and u≠vu \ne v. All of SS lies in the search tree below vv, so uu lies below some tree child ww of vv, and vv is on the stack when the edge u→vu \to v is examined. By (T4) VISIT(w)(w) returns at most DFN[v]\mathit{DFN}[v], so it returns exactly DFN[v]\mathit{DFN}[v]. In the other direction, if a successor ww gives DFN[v]\mathit{DFN}[v], then either w=vw = v, or by (T4) the tree below ww has an edge to vv, so vv is on a cycle. So loop\mathit{loop} is true if and only if SS is not a single vertex without a self-loop.

The elements. By (T1) line L10 holds once per SCC, at its first vertex hh. By (T2) the vertices above hh on the stack are S∖{h}S \setminus \{h\}. If loop\mathit{loop} is false, S={h}S = \{h\}, line L11 makes hh done, and line L15 adds the vertex hh. If loop\mathit{loop} is true, line L11 makes hh done, and line L13 pops S∖{h}S \setminus \{h\} and sets their DFN to 0. So the search Σ(S∖{h},succ(h))\Sigma(S \setminus \{h\}, \mathit{succ}(h)) of line L14 starts with (C1). For (C2), let a→ba \to b be an edge with a∈S∖{h}a \in S \setminus \{h\}. If b∈Sb \in S, then b=hb = h, which is done, or b∈S∖{h}b \in S \setminus \{h\}. If b∉Sb \notin S, then bb is not on the stack: a vertex on the stack below hh reaches hh (Tarjan's stack invariant), so it would be in SS. And bb has a nonzero DFN, because the search tree below hh has examined the edge a→ba \to b. So bb is done. Thus the inner search starts in a clean state, and ∣S∖{h}∣<∣S∣≤∣W∣|S \setminus \{h\}| < |S| \le |W|, so the claim holds for it.

Every vertex of S∖{h}S \setminus \{h\} is reached by the inner search. Take u∈S∖{h}u \in S \setminus \{h\} and a shortest path from hh to uu in G[S]G[S]. It visits hh only at its start, so its second vertex is in succ(h)\mathit{succ}(h) and the rest of the path stays in S∖{h}S \setminus \{h\}. So by (a) for the inner search, all of S∖{h}S \setminus \{h\} is done when line L14 ends, and the stack is back to its state after line L13, which is Tarjan's state after it pops SS. This is what Lemma 1 needs.

The order. Each element goes to the front of PP when its root reaches line L14 or L15. By (T3), if an edge goes from SCC AA to SCC B≠AB \ne A, the element of BB is added first, so it ends up after the element of AA. This is (b).

Part (a). Every vertex of RR is in some SCC, so it is either a root made done at line L11 or a vertex of some S∖{h}S \setminus \{h\} made done by the inner search. VISIT pushes and pops each vertex once per search, so the stack is restored. The search changes no DFN outside RR, because by (C2) it only reaches vertices of WW or done vertices. □\square

Theorem 1. WTO(G,r)(G, r) returns a weak topological ordering of the set VrV_r of vertices reachable from rr.

Proof. WTO is the search Σ(V,r)\Sigma(V, r), which starts in a clean state, and its set RR is VrV_r. We show by strong induction on ∣W∣|W| that the list PP of any search from a clean state has two properties.

It is a hierarchical ordering of RR. By (b) and (c), the elements cover the SCCs of G[R]G[R], which partition RR. A vertex element holds one vertex. A component element of SS holds hh and, by induction, each vertex of S∖{h}S \setminus \{h\} once.

Every edge u→vu \to v with u,v∈Ru, v \in R satisfies the WTO condition with ωP\omega_P. Let eue_u and eve_v be the elements of PP that contain uu and vv.

  1. eu≠eve_u \ne e_v. By (b) eue_u comes before eve_v, so u≺vu \prec v. The heads in ωP(u)\omega_P(u) lie in eue_u, and vv does not, so v∉ωP(u)v \notin \omega_P(u). The edge is forward.
  2. eu=eve_u = e_v is a vertex. Then u=vu = v and u→uu \to u is a self-loop, which (c) rules out. This case does not occur.
  3. eu=ev=(h,C)e_u = e_v = (h, C) and v=hv = h. The head comes first in its element, so h⪯uh \preceq u, and h∈ωP(u)h \in \omega_P(u) by (1). The edge is backward. This includes the self-loop h→hh \to h.
  4. eu=ev=(h,C)e_u = e_v = (h, C), u=hu = h and v≠hv \ne h. Then vv is in CC, so h≺vh \prec v, and ωP(h)={h}\omega_P(h) = \{h\} does not hold vv. The edge is forward.
  5. eu=ev=(h,C)e_u = e_v = (h, C) and u,v≠hu, v \ne h. Both are in CC, the edge lies in G[S∖{h}]G[S \setminus \{h\}], and the inner search reaches both. By induction the edge satisfies the condition in CC. The order of PP restricted to CC is the order of CC, and by (1) ωP(u)={h}∪ωC(u)\omega_P(u) = \{h\} \cup \omega_C(u) with v≠hv \ne h. So a forward edge of CC (u≺vu \prec v, v∉ωC(u)v \notin \omega_C(u)) is forward in PP, and a backward edge of CC (v⪯uv \preceq u, v∈ωC(u)v \in \omega_C(u)) is backward in PP.

For the top level, every edge out of a vertex of VrV_r ends in VrV_r, so every such edge is covered. □\square

Theorem 2. Every cycle of GG through a vertex of VrV_r contains a head of the WTO.

Proof. All the vertices of the cycle are in VrV_r. Let uu be the last of them in the order, and let vv be the vertex after uu on the cycle. Then v⪯uv \preceq u, so the edge u→vu \to v is not forward, and by Theorem 1 it is backward: v∈ω(u)v \in \omega(u). So vv is a head. □\square

So removing the heads leaves a graph without cycles. This is the first half of Bourdoncle's result: the heads are an admissible set of widening points.

Part 2. The recursive strategy

Assume that every FvF_v is monotone and reads only x[u]x[u] for the predecessors uu of vv. Assume that ∇\nabla is a widening: a⊑a∇ba \sqsubseteq a \nabla b and b⊑a∇bb \sqsubseteq a \nabla b, and for every increasing chain y0⊑y1⊑⋯y_0 \sqsubseteq y_1 \sqsubseteq \cdots the sequence z0=y0z_0 = y_0, zj+1=zj∇yj+1z_{j+1} = z_j \nabla y_{j+1} is constant from some index on. All values start at ⊥\bot. A vertex outside VrV_r is never assigned, so its value stays ⊥\bot.

Lemma 3 (values only grow). No assignment of ITERATE makes a value smaller: after each assignment the new value is ⊒\sqsupseteq the old one.

Proof. By induction on the number of assignments. At lines L24 and L29, x[h]⊑x[h]∇tx[h] \sqsubseteq x[h] \nabla t. At line L22, the old value of x[v]x[v] is ⊥\bot or Fv(x′)F_v(x') for the state x′x' of the last assignment to vv. By induction x′⊑xx' \sqsubseteq x at every vertex, so by monotonicity Fv(x′)⊑Fv(x)F_v(x') \sqsubseteq F_v(x). □\square

Lemma 4 (finitely many changes at a head). Over any run, the value of a head hh changes only finitely many times.

Proof. Only lines L24 and L29 for the component of hh assign x[h]x[h]. Let t1,t2,…t_1, t_2, \ldots be the values of Fh(x)F_h(x) used by these assignments, in time order. By Lemma 3 the states grow, so t1⊑t2⊑⋯t_1 \sqsubseteq t_2 \sqsubseteq \cdots by monotonicity. The values of x[h]x[h] are z0=⊥z_0 = \bot and zj=zj−1∇tjz_j = z_{j-1} \nabla t_j, the widened sequence of the chain ⊥⊑t1⊑t2⊑⋯\bot \sqsubseteq t_1 \sqsubseteq t_2 \sqsubseteq \cdots. If the chain is infinite, the sequence is constant from some index on. Either way it changes finitely often. □\square

Theorem 3 (termination). ITERATE(P)(P) stops for every WTO PP.

Proof. By induction on the depth of nesting of PP. If PP has no component, it makes one assignment per element. Otherwise take a component (h,C)(h, C) of PP. By induction every call ITERATE(C)(C) stops. Consider one run of the loop of lines L25 to L29. Each round that does not leave the loop has t⋢x[h]t \not\sqsubseteq x[h] at line L28. Then line L29 gives x[h]∇t⊒tx[h] \nabla t \sqsupseteq t, which differs from the old x[h]x[h], so the value of hh changes. If the loop never ended, hh would change infinitely often, against Lemma 4. So each element of PP is processed in finite time, and PP has finitely many elements. □\square

Lemma 5 (who comes after whom). Let u→vu \to v be an edge with u,v∈Vru, v \in V_r.

  • (i) If vv is not a head, then every assignment to uu is followed later by an evaluation of FvF_v at line L22.
  • (ii) If vv is the head of the component cc and uu is not in cc, then every assignment to uu is followed later by a test of line L28 for cc.

Proof. In both cases the edge is forward by Theorem 1. For (i), v∉ω(u)v \notin \omega(u) because vv is not a head, and v⪯uv \preceq u would need v∈ω(u)v \in \omega(u). For (ii), a backward edge to vv needs v∈ω(u)v \in \omega(u), which means uu is in cc. So u≺vu \prec v and v∉ω(u)v \notin \omega(u).

Let LL be the body of the innermost component that contains both uu and vv, or the whole WTO if there is none. Write gg for its head, if it has one.

If u=gu = g, then vv is in the body LL. Every assignment to gg is at line L24 or L29, and both are followed by a call ITERATE(L)(L), which processes the element of LL that contains vv.

Otherwise uu and vv are in LL, in elements eue_u and eve_v of LL. These differ: a component element holding both would contradict the choice of LL, and a vertex element holding both would mean u=vu = v with a self-loop, so vv would be a head with uu in its component. Since u≺vu \prec v, eue_u comes before eve_v. Every assignment to uu happens while ITERATE processes eue_u in some pass over LL, and that pass then processes eve_v, by Theorem 3 to its end.

It remains to see what processing eve_v does. A component is processed by at least one pass over its body, and each pass processes every element of the body. So processing eve_v reaches line L22 for vv in case (i), since vv is not a head and so is a vertex element at some depth. In case (ii), cc is eve_v or lies inside eve_v, and every processing of cc ends with a test of line L28 that passes, by Theorem 3. □\square

Theorem 4 (post-fixed point). When ITERATE ends, the final values xx satisfy Fv(x)⊑x[v]F_v(x) \sqsubseteq x[v] for every v∈Vrv \in V_r.

Proof. Let vv be a vertex that is not a head, and let TT be the time of its last evaluation at line L22, with state xTx_T. By Lemma 5 (i), no predecessor of vv in VrV_r is assigned after TT, and predecessors outside VrV_r never change. FvF_v reads only the predecessors, so Fv(x)=Fv(xT)=x[v]F_v(x) = F_v(x_T) = x[v].

Let v=hv = h be the head of the component cc, and let TT be the time of the last test of line L28 for cc. That test passed, since the run ended: Fh(xT)⊑xT[h]F_h(x_T) \sqsubseteq x_T[h]. After TT, cc is never processed again, since each processing ends with such a test. Every assignment to a vertex of cc happens while cc is processed, so no vertex of cc, hh included, changes after TT. A predecessor uu of hh outside cc is not assigned after TT by Lemma 5 (ii). Hence Fh(x)=Fh(xT)⊑xT[h]=x[h]F_h(x) = F_h(x_T) \sqsubseteq x_T[h] = x[h]. □\square

Theorems 2, 3 and 4 together are Bourdoncle's result: widening only at the heads of a WTO, with the recursive strategy, gives an iteration that stops, and that ends at an element xx with F(x)⊑xF(x) \sqsubseteq x, which the Cousots call a post-fixed point and the Knaster-Tarski page calls a pre-fixed point. When each FvF_v is a sound abstraction of the concrete step, such an element over-approximates the collecting semantics, by the local condition proved on the abstract domain page. ■\blacksquare

Complexity

Building the WTO. A unit step is one look at an edge or one push or pop. VISIT(v)(v) looks at each successor of vv once. A vertex vv is visited once at the top level, and once more by COMPONENT of each component that contains vv and has a head other than vv. COMPONENT(v)(v) looks at the successors of vv once more. So the successor list of vv is read exactly 1+∣ω(v)∣1 + |\omega(v)| times, and the total time is

∑v∈Vr(1+∣ω(v)∣)(1+outdeg(v))≤(k+1)(n+m).\sum_{v \in V_r} \bigl(1 + |\omega(v)|\bigr)\bigl(1 + \mathit{outdeg}(v)\bigr) \le (k + 1)(n + m).

With no cycle, k=0k = 0 and the time is Θ(n+m)\Theta(n + m). In the worst case k=n−1k = n - 1: on the chain 0⇄1⇄⋯⇄n−10 \rightleftarrows 1 \rightleftarrows \cdots \rightleftarrows n-1 the WTO is (0 (1 (2⋯(n−2 n−1)⋯ )))(0\ (1\ (2 \cdots (n-2\ n-1) \cdots))), vertex ii is read i+2i + 2 times for i≤n−2i \le n - 2, and the total is Θ(n2)\Theta(n^2), which is Θ(n(n+m))\Theta(n(n + m)) for this graph. The stack, the DFN array and the output take Θ(n)\Theta(n) space.

Iterating. ITERATE evaluates FvF_v once per assignment and once per stop test. The number of passes over a component depends on the domain and the widening, not on the graph alone. With the interval widening on vv names, a head can change at most 2v+12v + 1 times over the whole run, and each change starts at most one more pass over its body.

Properties

  • Deterministic. The WTO depends on the root and on the order of the successor lists. Another order can give other heads.
  • Not the fewest heads. Finding the fewest vertices that cut every cycle is the feedback vertex set problem, which is NP-hard. On the graph 0→10 \to 1, 1⇄21 \rightleftarrows 2, 2⇄32 \rightleftarrows 3 the WTO is 0 (1 (2 3))0\ (1\ (2\ 3)) with heads 1 and 2, but vertex 2 alone cuts both cycles.
  • Heads on reducible graphs. On a reducible flow graph each head is a loop header: the head is the entry of its part, so it dominates the part, and the edge into it from inside the part is a back edge. The components then follow the loops of a loop nesting forest.
  • Irreducible graphs work too. A cycle with two entries, such as 0→10 \to 1, 0→20 \to 2, 1⇄21 \rightleftarrows 2, gives 0 (1 2). The edge 0→20 \to 2 enters the component at a vertex that is not the head; it is a forward edge, and the iteration stays correct.
  • Order of the dataflow pages. The same WTO serves an analysis in the dual order of Kildall that the worklist algorithm uses; only the join, the stop test and the direction of the widening are turned around.

Variants and improvements

  • The iterative strategy. Bourdoncle also gives a strategy that runs through the whole component of the outermost head, in the flattened order, until that head is stable, without stabilizing inner components first. It is simpler, but the recursive strategy usually needs fewer evaluations, and it lets the analyzer test only the head.
  • Restart an inner loop on entry. Replace line L24 by x[h]←Fh(x)x[h] \leftarrow F_h(x), so that each new pass of an outer loop starts the inner head from its new entry value. In the example, step 10 then keeps i∈[0,2]i \in [0, 2], and body gets i∈[1,2]i \in [1, 2] and j∈[0,1]j \in [0, 1]. Values can then go down, so the termination proof above no longer applies; the iteration still stops if the widening makes every widened sequence stop, increasing or not, which the interval widening does.
  • A narrowing pass. After ITERATE, run it again with Δ\Delta in place of ∇\nabla at lines L24 and L29, and with the test of line L28 replaced by "no change".
  • A worklist on top of the WTO. Use the WTO order as the priority of a worklist, and put a vertex back only when an input changed. This skips blocks whose inputs did not change.
  • Plain topological order. On a graph without cycles the WTO is a topological sort. It is the reverse postorder of the depth-first search from the root, because each vertex goes to the front of the list when its visit ends.

When to use it

Use a WTO in an abstract interpreter over a domain of infinite height, such as intervals, octagons or polyhedra, where the widening points and the order of iteration decide both termination and precision. It also suits a worklist dataflow solver on a lattice of finite height, but there a reverse postorder is simpler and almost as fast. Widening at every block also stops, but it loses much more precision; widening at the targets of the back edges of a depth-first search also cuts every cycle, but it gives no order in which to stabilize nested loops.

Pitfalls

  • A strict test in line L9. With min < head in place of min ≤ head, the flag loop\mathit{loop} stays false at the root of every part, because every cycle through the root returns exactly DFN[v]\mathit{DFN}[v]. Then no loop gets a component: line L15 places the root alone, and the other vertices of its part stay on the stack and never enter the WTO. On the example above the result is entry outer exit. ITERATE never computes the dropped vertices, and the result is not a post-fixed point, so it is unsound. Line L9 must use ≤\le.
  • No reset in line L13. If the vertices taken off the stack keep their old DFN, COMPONENT in line L14 sees them as visited and returns an empty body, and the loop body is lost. Line L13 must set their DFN to 0.
  • Widening at every vertex in line L22. Writing x[v]←x[v]∇Fv(x)x[v] \leftarrow x[v] \nabla F_v(x) for every vertex still stops, but it loses bounds that a guard has just set. In the example, init has i∈[0,0]i \in [0, 0] after the first pass, and in the second pass FF gives [0,2][0, 2], so the widening sets i∈[0,+∞]i \in [0, +\infty] and the guard i < 3 is lost. Line L22 must assign, and only lines L24 and L29 widen.
  • Widening on re-entry in line L24. The old value of an inner head comes from the last pass of the outer loop. Widening with it can jump over a bound that the outer loop has just changed, as in step 10 of the example. Use the restart variant with a widening that stops on every sequence, or recover the bound with narrowing.
  • Deep recursion. VISIT can recurse nn levels deep, and ITERATE kk levels deep. The Python code keeps its own stack.

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.

weak_topological_ordering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-topological-ordering/. The authors are listed in prov/X5B201.jsonl.
"""Bourdoncle's weak topological ordering and the recursive iteration strategy.

A graph is given by a function succ(v) that returns the successors of v in a
fixed order, and a root. weak_topological_ordering returns a list of elements;
an element is a vertex or a Component(head, body), where body is again a list
of elements. iterate runs the recursive strategy over such a list.
"""

from __future__ import annotations

import math
from dataclasses import dataclass, field
from typing import Callable, Generator, Hashable, Iterable, TypeVar, Union

D = TypeVar("D")

INF = math.inf


@dataclass
class Component:
    """A component of a WTO: its head, then its body, which is a WTO itself."""

    head: Hashable
    body: list["Element"] = field(default_factory=list)


Element = Union[Hashable, Component]
Frame = Generator[tuple, object, object]


class _State:
    def __init__(self, succ: Callable[[Hashable], Iterable[Hashable]]) -> None:
        self.succ = succ
        self.dfn: dict[Hashable, float] = {}  # a missing key means DFN = 0
        self.num = 0
        self.stack: list[Hashable] = []


def _visit(v: Hashable, part: list[Element], st: _State) -> Frame:
    st.stack.append(v)  # @line L5
    st.num += 1  # @line L5
    st.dfn[v] = st.num  # @line L5
    head: float = st.dfn[v]  # @line L6
    loop = False  # @line L6
    for w in st.succ(v):  # @line L7
        if st.dfn.get(w, 0) == 0:  # @line L8
            low = yield ("visit", w, part)  # @line L8
        else:
            low = st.dfn[w]  # @line L8
        if low <= head:  # @line L9
            head = low  # @line L9
            loop = True  # @line L9
    if head == st.dfn[v]:  # @line L10
        st.dfn[v] = INF  # @line L11
        e = st.stack.pop()  # @line L11
        if loop:  # @line L12
            while e != v:  # @line L13
                st.dfn[e] = 0  # @line L13
                e = st.stack.pop()  # @line L13
            comp = yield ("component", v)  # @line L14
            part.append(comp)  # @line L14
        else:
            part.append(v)  # @line L15
    return head  # @line L16


def _component(v: Hashable, st: _State) -> Frame:
    body: list[Element] = []  # @line L17
    for w in st.succ(v):  # @line L18
        if st.dfn.get(w, 0) == 0:  # @line L19
            yield ("visit", w, body)  # @line L19
    body.reverse()  # elements were appended; one reversal equals adding each to the front
    return Component(v, body)  # @line L20


def weak_topological_ordering(
    succ: Callable[[Hashable], Iterable[Hashable]], root: Hashable
) -> list[Element]:
    """Return Bourdoncle's WTO of the vertices reachable from root.

    The WTO is a list of vertices and Components in a nested topological
    order: every cycle of the graph contains the head of a component that
    contains the whole cycle. Successors are explored in the order that succ
    gives. Precondition: succ(v) is defined for every vertex reachable from
    root. Cost: O((k + 1)(n + m)) time for n reachable vertices, m edges
    among them and nesting depth k, and O(n) extra space; no Python recursion.
    """
    st = _State(succ)  # @line L1
    part: list[Element] = []  # @line L2
    # Each generator frame plays the role of one recursive call. A frame
    # yields a request ("visit", w, partition) or ("component", v); the driver
    # starts a new frame for it and sends the frame's result back.
    frames: list[Frame] = [_visit(root, part, st)]  # @line L3
    value: object = None
    while frames:
        try:
            req = frames[-1].send(value)
        except StopIteration as stop:
            frames.pop()
            value = stop.value
            continue
        value = None
        if req[0] == "visit":
            frames.append(_visit(req[1], req[2], st))
        else:
            frames.append(_component(req[1], st))
    part.reverse()  # elements were appended; one reversal equals adding each to the front
    return part  # @line L4


class _Values(dict):
    """The current values; a vertex with no value yet has the value bottom."""

    def __init__(self, bottom: object) -> None:
        super().__init__()
        self.bottom = bottom

    def __missing__(self, key: Hashable) -> object:
        return self.bottom


@dataclass
class _Pass:
    elems: list[Element]
    i: int
    comp: Component | None


def iterate(
    wto: list[Element],
    f: Callable[[Hashable, dict], D],
    leq: Callable[[D, D], bool],
    widen: Callable[[D, D], D],
    bottom: D,
) -> dict:
    """Run Bourdoncle's recursive iteration strategy over a WTO.

    f(v, x) computes the right side F_v of the equation of v from the current
    values x, a dict in which a vertex with no value yet reads as bottom.
    Each head is widened, each other vertex is assigned. Precondition: every
    F_v is monotone and widen is a widening. Then the run ends, and the
    result has f(v, x) <= x[v] for every vertex of the WTO. Cost: one call of
    f per assignment and per stop test; the number of passes depends on the
    widening. No Python recursion.
    """
    x = _Values(bottom)
    stack = [_Pass(wto, 0, None)]
    while stack:
        p = stack[-1]
        if p.i == len(p.elems):  # the pass over this list is over
            stack.pop()
            if p.comp is None:
                continue
            h = p.comp.head
            t = f(h, x)  # @line L27
            if leq(t, x[h]):  # @line L28
                continue
            x[h] = widen(x[h], t)  # @line L29
            stack.append(_Pass(p.comp.body, 0, p.comp))  # @line L26
            continue
        e = p.elems[p.i]  # @line L21
        p.i += 1
        if not isinstance(e, Component):
            x[e] = f(e, x)  # @line L22
        else:
            h = e.head  # @line L23
            x[h] = widen(x[h], f(h, x))  # @line L24
            stack.append(_Pass(e.body, 0, e))  # @line L25 L26
    return dict(x)


def flatten(wto: list[Element]) -> list[Hashable]:
    """The vertices of a WTO in its total order: each head before its body."""
    out: list[Hashable] = []
    todo: list[Element] = list(reversed(wto))
    while todo:
        e = todo.pop()
        if isinstance(e, Component):
            out.append(e.head)
            todo.extend(reversed(e.body))
        else:
            out.append(e)
    return out


def heads_of(wto: list[Element]) -> dict[Hashable, list[Hashable]]:
    """Map each vertex v to omega(v), the heads of the components that contain v, outermost first."""
    out: dict[Hashable, list[Hashable]] = {}
    todo: list[tuple[Element, tuple]] = [(e, ()) for e in wto]
    while todo:
        e, hs = todo.pop()
        if isinstance(e, Component):
            inner = hs + (e.head,)
            out[e.head] = list(inner)
            todo.extend((b, inner) for b in e.body)
        else:
            out[e] = list(hs)
    return out


def show(wto: list[Element]) -> str:
    """Bourdoncle's notation, for example: a (b c (d e) f) g."""
    tokens: list[str] = []
    todo: list[object] = list(reversed(wto))
    while todo:
        e = todo.pop()
        if e == ")":
            tokens.append(")")
        elif isinstance(e, Component):
            tokens.append("(" + str(e.head))
            todo.append(")")
            todo.extend(reversed(e.body))
        else:
            tokens.append(str(e))
    return " ".join(tokens).replace(" )", ")")
test_weak_topological_ordering.py 317 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-topological-ordering/. The authors are listed in prov/X5B201.jsonl.

import math
import random
from collections import deque

from weak_topological_ordering import (
    Component,
    flatten,
    heads_of,
    iterate,
    show,
    weak_topological_ordering,
)

INF = math.inf

# The control flow graph of the nested loop on the page.
EXAMPLE = {
    "entry": ["outer"],
    "outer": ["init", "exit"],
    "init": ["inner"],
    "inner": ["body", "next"],
    "body": ["inner"],
    "next": ["outer"],
    "exit": [],
}


def wto_of(graph, root):
    return weak_topological_ordering(lambda v: graph[v], root)


# ---- brute force oracles, independent of the code under test ----


def reach(graph, start, allowed):
    """Vertices of allowed reachable from start by paths inside allowed (start included)."""
    seen = {start}
    todo = [start]
    while todo:
        u = todo.pop()
        for w in graph[u]:
            if w in allowed and w not in seen:
                seen.add(w)
                todo.append(w)
    return seen


def sccs(graph, allowed):
    """The strongly connected components of the subgraph induced by allowed, from reachability sets."""
    r = {u: reach(graph, u, allowed) for u in allowed}
    out = []
    done = set()
    for u in sorted(allowed, key=repr):
        if u in done:
            continue
        comp = frozenset(w for w in r[u] if u in r[w])
        done |= comp
        out.append(comp)
    return out


def has_cycle(graph, allowed):
    indeg = {u: 0 for u in allowed}
    for u in allowed:
        for w in graph[u]:
            if w in allowed:
                indeg[w] += 1
    q = deque(u for u in allowed if indeg[u] == 0)
    seen = 0
    while q:
        u = q.popleft()
        seen += 1
        for w in graph[u]:
            if w in allowed:
                indeg[w] -= 1
                if indeg[w] == 0:
                    q.append(w)
    return seen < len(allowed)


def vertices(e):
    if isinstance(e, Component):
        out = {e.head}
        for b in e.body:
            out |= vertices(b)
        return out
    return {e}


def check_level(graph, part, allowed, root_like):
    """The elements of part are the SCCs of graph[allowed], in topological order, recursively."""
    sets = [frozenset(vertices(e)) for e in part]
    assert sorted(sets, key=sorted_key) == sorted(sccs(graph, allowed), key=sorted_key)
    pos = {}
    for k, s in enumerate(sets):
        for u in s:
            pos[u] = k
    for u in allowed:
        for w in graph[u]:
            if w in allowed:
                assert pos[u] <= pos[w]  # no edge goes back to an earlier element
    for e, s in zip(part, sets):
        cyclic = len(s) > 1 or any(u in graph[u] for u in s)
        assert isinstance(e, Component) == cyclic
        if isinstance(e, Component):
            h = e.head
            assert h in reach(graph, h, s) and any(h in graph[u] for u in s)  # h is on a cycle in s
            outside = [u for u in graph if h in graph[u] and u not in s]
            assert h in root_like or outside  # h is entered from outside or is a start vertex
            check_level(graph, e.body, s - {h}, set(graph[h]))


def sorted_key(s):
    return sorted(map(repr, s))


def check_wto(graph, root):
    w = wto_of(graph, root)
    order = flatten(w)
    reachable = reach(graph, root, set(graph))
    assert len(order) == len(set(order)) and set(order) == reachable
    check_level(graph, w, reachable, {root})
    rank = {v: k for k, v in enumerate(order)}
    omega = heads_of(w)
    heads = {v for v in order if omega[v] and omega[v][-1] == v}
    for u in reachable:
        for v in graph[u]:
            forward = rank[u] < rank[v] and v not in omega[u]
            backward = rank[v] <= rank[u] and v in omega[u]
            assert forward or backward, (u, v)
    assert not has_cycle(graph, reachable - heads)
    return w


def random_graph(rng, n):
    graph = {u: [] for u in range(n)}
    p = rng.choice((0.15, 0.25, 0.4))
    for u in range(n):
        for v in range(n):
            if rng.random() < p:
                graph[u].append(v)
        rng.shuffle(graph[u])
    return graph


# ---- the tests ----


def test_example() -> None:
    w = check_wto(EXAMPLE, "entry")
    assert show(w) == "entry (outer init (inner body) next) exit"
    assert flatten(w) == ["entry", "outer", "init", "inner", "body", "next", "exit"]
    assert heads_of(w)["body"] == ["outer", "inner"]


def test_edges() -> None:
    assert wto_of({0: []}, 0) == [0]
    assert wto_of({0: [0]}, 0) == [Component(0, [])]
    assert show(wto_of({0: [1], 1: [0]}, 0)) == "(0 1)"
    assert show(wto_of({0: [1], 1: [1, 2], 2: []}, 0)) == "0 (1) 2"
    # vertex 3 is not reachable from the root and is left out
    assert flatten(wto_of({0: [1], 1: [], 3: [0]}, 0)) == [0, 1]
    # an irreducible loop: the cycle 1 <-> 2 is entered at 1 and at 2
    g = {0: [1, 2], 1: [2], 2: [1]}
    assert show(check_wto(g, 0)) == "0 (1 2)"


def test_nested_chain_is_quadratic() -> None:
    n = 40
    g = {i: [] for i in range(n)}
    for i in range(n - 1):
        g[i].append(i + 1)
        g[i + 1].append(i)
    calls = {v: 0 for v in g}

    def succ(v):
        calls[v] += 1
        return g[v]

    w = weak_topological_ordering(succ, 0)
    omega = heads_of(w)
    assert show(w).startswith("(0 (1 (2 ") and len(omega[n - 1]) == n - 1  # nesting depth n - 1
    for v in g:
        assert calls[v] == 1 + len(omega[v])
    assert sum(calls.values()) == sum(1 + len(omega[v]) for v in g) >= n * (n - 1) // 2


def test_random_wto() -> None:
    rng = random.Random(20241115)
    for _ in range(700):
        n = rng.randint(1, 8)
        g = random_graph(rng, n)
        root = rng.randrange(n)
        calls = {v: 0 for v in g}

        def succ(v, g=g, calls=calls):
            calls[v] += 1
            return g[v]

        weak_topological_ordering(succ, root)
        w = check_wto(g, root)
        omega = heads_of(w)
        for v in flatten(w):
            assert calls[v] == 1 + len(omega[v])


def random_equations(rng, g, root, size):
    """Random monotone edge functions S -> {(a + c) mod size : a in S and a in guard}."""
    edges = {}
    for u in g:
        for v in g[u]:
            guard = frozenset(a for a in range(size) if rng.random() < 0.7)
            edges[(u, v)] = (rng.randint(0, size - 1), guard)
    init = frozenset(rng.sample(range(size), rng.randint(1, 2)))
    preds = {v: [u for u in g if v in g[u]] for v in g}

    def f(v, x):
        out = set(init) if v == root else set()
        for u in preds[v]:
            c, guard = edges[(u, v)]
            out |= {(a + c) % size for a in x[u] if a in guard}
        return frozenset(out)

    return f


def test_iterate_finite_gives_least_fixed_point() -> None:
    rng = random.Random(7)
    for _ in range(500):
        n = rng.randint(1, 7)
        g = random_graph(rng, n)
        root = rng.randrange(n)
        f = random_equations(rng, g, root, 6)
        w = weak_topological_ordering(lambda v: g[v], root)
        got = iterate(w, f, lambda a, b: a <= b, lambda a, b: a | b, frozenset())
        # Kleene iteration from bottom, over the reachable vertices
        order = flatten(w)
        x = {v: frozenset() for v in g}
        while True:
            y = {v: (f(v, x) if v in order else frozenset()) for v in g}
            if y == x:
                break
            x = y
        assert {v: got.get(v, frozenset()) for v in order} == {v: x[v] for v in order}


def iv_leq(a, b):
    return a is None or (b is not None and b[0] <= a[0] and a[1] <= b[1])


def iv_join(a, b):
    if a is None:
        return b
    if b is None:
        return a
    return (min(a[0], b[0]), max(a[1], b[1]))


def iv_widen(a, b):
    if a is None:
        return b
    if b is None:
        return a
    return (-INF if b[0] < a[0] else a[0], INF if b[1] > a[1] else a[1])


def test_iterate_intervals_is_sound_and_stops() -> None:
    rng = random.Random(99)
    for _ in range(500):
        n = rng.randint(1, 7)
        g = random_graph(rng, n)
        root = rng.randrange(n)
        preds = {v: [u for u in g if v in g[u]] for v in g}
        edges = {}
        for u in g:
            for v in g[u]:
                lo, hi = sorted(rng.sample(range(-6, 7), 2))
                guard = rng.choice(((-INF, INF), (lo, INF), (-INF, hi), (lo, hi)))
                edges[(u, v)] = (rng.randint(-2, 3), guard)
        start = rng.randint(-3, 3)
        calls = [0]

        def f(v, x):
            calls[0] += 1
            assert calls[0] < 20000
            out = (start, start) if v == root else None
            for u in preds[v]:
                a = x[u]
                if a is None:
                    continue
                c, (gl, gu) = edges[(u, v)]
                lo, hi = max(a[0], gl), min(a[1], gu)
                if lo <= hi:
                    out = iv_join(out, (lo + c, hi + c))
            return out

        w = weak_topological_ordering(lambda v: g[v], root)
        x = iterate(w, f, iv_leq, iv_widen, None)
        full = {v: x.get(v) for v in g}
        for v in flatten(w):  # the result is a post-fixed point
            assert iv_leq(f(v, full), full[v])
        # every concrete state found by a bounded search is covered
        seen = {(root, start)}
        todo = [(root, start)]
        while todo and len(seen) < 3000:
            u, a = todo.pop()
            for v in g[u]:
                c, (gl, gu) = edges[(u, v)]
                if gl <= a <= gu and abs(a + c) <= 40 and (v, a + c) not in seen:
                    seen.add((v, a + c))
                    todo.append((v, a + c))
        for v, a in seen:
            box = x.get(v)
            assert box is not None and box[0] <= a <= box[1]

History

Cousot and Cousot (1977) showed that an upward iteration with widening stops when the widening is applied at a set of points that cuts every loop. François Bourdoncle (1993) asked which points and which order to use. He defined hierarchical and weak topological orderings, built them by applying Tarjan's 1972 algorithm for strongly connected components again inside each part, and gave the iterative and recursive strategies. He proved that the heads of a WTO are an admissible set of widening points and that, in the recursive strategy, stability of a component can be detected at its head alone. The method is the standard iteration order of abstract interpreters for imperative programs.

References

  1. François Bourdoncle, Efficient chaotic iteration strategies with widenings, Formal Methods in Programming and Their Applications (FMPA 1993), LNCS 735, pages 128 to 141, the definition of hierarchical and weak topological orderings, the algorithm built on Tarjan's algorithm, the iterative and recursive iteration strategies, and the result that the heads of the components are an admissible set of widening points
  2. Robert Tarjan, Depth-first search and linear graph algorithms, SIAM Journal on Computing 1(2), 1972, pages 146 to 160, the depth-first numbering and the low values that find the strongly connected components, which the visit procedure reuses
  3. Patrick Cousot and Radhia Cousot, Abstract interpretation: a unified lattice model for static analysis of programs by construction or approximation of fixpoints, POPL 1977, pages 238 to 252, the upward iteration with widening, applied at a set of points that cuts every loop of the program

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
  • a scene preset for the example