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
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 time, where 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 , given by the successor lists , and a root . In program analysis is a control flow graph and is its entry block. Let be the set of vertices reachable from .
A hierarchical ordering of is a sequence of the vertices of , each once, with matched parentheses, where every opening parenthesis is followed at once by a vertex, the head of that component. For a vertex , is the set of heads of the components that contain ; a head belongs to its own component. Write when comes before in the sequence. The ordering is a weak topological ordering when every edge with satisfies
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 , one for each vertex, over an abstract domain with a widening , and to return values with at every vertex.
The algorithm
WTO uses a counter , a stack and a depth-first number , which is 0 for a vertex not yet visited, a positive number for a vertex on the stack, and for a vertex that is already placed. A partition is a list of elements; an element is a vertex or a component , whose body is a partition. ITERATE is the recursive iteration strategy; every value is at the start.
WTO(G, r)- 1
for each v in V do DFN[v] ← 0 - 2
num ← 0, S ← empty stack, P ← empty list - 3
VISIT(r, P) - 4
return P VISIT(v, P) ▷ returns the least DFN reached from v- 5
push v on S, num ← num + 1, DFN[v] ← num - 6
head ← DFN[v], loop ← false - 7
for each w in succ(v) do - 8
if DFN[w] = 0 then min ← VISIT(w, P) else min ← DFN[w] - 9
if min ≤ head then head ← min, loop ← true - 10
if head = DFN[v] then ▷ v is the root of a strongly connected part - 11
DFN[v] ← +∞, e ← pop S - 12
if loop then - 13
while e ≠ v do DFN[e] ← 0, e ← pop S - 14
add COMPONENT(v) to the front of P - 15
else add v to the front of P - 16
return head COMPONENT(v)- 17
C ← empty list - 18
for each w in succ(v) do - 19
if DFN[w] = 0 then VISIT(w, C) - 20
return (v, C) ITERATE(P)- 21
for each element e of P, in order do - 22
if e is a vertex v then x[v] ← F_v(x) - 23
else let (h, C) = e - 24
x[h] ← x[h] ∇ F_h(x) - 25
repeat - 26
ITERATE(C) - 27
t ← F_h(x) - 28
if t ⊑ x[h] then leave the repeat loop - 29
x[h] ← x[h] ∇ t
VISIT is Tarjan's algorithm with one change. Line L9 computes the least depth-first number that reaches, as Tarjan's low value does, and also records in whether reaches a vertex numbered at most itself, that is, whether lies on a cycle of its part. A vertex placed earlier has , so it never lowers . When line L10 finds the root of a strongly connected part, either the part is 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 : now has , 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 .
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 outer, outer init, outer exit, init inner, inner body, inner next, body inner and next 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: = [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 ; a root with no loop: = [next] |
| inside: VISIT(body) | 12 | 12 | called by COMPONENT(inner); inner has DFN : = [body] |
| inside: VISIT(inner) | 9 | 9 | a root with a loop: = [(inner body), next] |
| inside: VISIT(init) | 8 | 8 | a root with no loop: = [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; . The back edges body inner and next 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 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 | note | ||
|---|---|---|---|---|---|
| 1 | entry | L22 | |||
| 2 | outer | L24 | |||
| 3 | init | L22 | |||
| 4 | inner | L24 | |||
| 5 | body | L22 | the guard fails | ||
| 6 | inner | L28 | stable: leave the inner loop | ||
| 7 | next | L22 | |||
| 8 | outer | L29 | gives ; widen | ||
| 9 | init | L22 | |||
| 10 | inner | L24 | gives ; the widening with the old jumps | ||
| 11 | body | L22 | |||
| 12 | inner | L29 | gives ; widen | ||
| 13 | body | L22 | |||
| 14 | inner | L28 | stable: leave the inner loop | ||
| 15 | next | L22 | |||
| 16 | outer | L28 | stable: leave the outer loop | ||
| 17 | exit | L22 |
The run makes 17 evaluations of some , 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 of the inner head makes the widening jump to . A narrowing pass does not repair this, because the cycle inner body inner keeps the bound alive. The restart variant below keeps at inner, and a narrowing pass after it gives at exit.
Correctness
There are three claims; the full proofs are in the proof file.
- WTO builds a weak topological ordering of . 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.
- Every cycle passes through a head. Take a cycle and its last vertex in the order. The next vertex on the cycle has , so the edge condition puts in : is a head. So the vertices without the heads form a graph with no cycle, and the heads are enough as widening points.
- ITERATE stops with at every vertex, if each is monotone and 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 , 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 . For a list of elements and a vertex in it, is the set of heads of the components of (at any depth) that contain . For the full WTO this is . If is an element of and is in , then
The vertices of one element are next to each other in the flattened order, with the head first.
Part 1. The searches
A search is a run of VISIT for in turn, on one list , where the call for is skipped if at that time. WTO is the search . COMPONENT is the search for the set named in Lemma 2. We say that a search starts in a clean state when
- (C1) every vertex of has DFN 0,
- (C2) every edge from a vertex of goes to a vertex of 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 only grows. Let be the set of vertices of that the start vertices reach by paths inside .
Lemma 1 (Tarjan). In a search from a clean state, VISIT behaves as Tarjan's algorithm on the graph , with the edges to done vertices left out. In particular, as shown on the Tarjan page:
- (T1) VISIT returns if and only if is the first vertex of its strongly connected component (SCC) of that the search reaches;
- (T2) at that time the vertices on the stack from upward are exactly the SCC of ;
- (T3) if an edge of goes from the SCC to another SCC , then the root of reaches line L10 before the root of ;
- (T4) VISIT returns the least of and the numbers of the vertices on the stack that an edge of the search tree below reaches.
Proof. Line L8 uses the returned value of a tree child and the DFN of any other successor. A successor that is on the stack has a finite DFN, which is Tarjan's rule. A done successor gives , 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 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.
Lemma 2. Let a search start in a clean state. When it ends:
- (a) every vertex of is done, every other vertex has its old DFN, and the stack is as at the start;
- (b) the elements of correspond one to one to the SCCs of , in an order such that every edge of goes from an element to the same element or to a later one;
- (c) the element of an SCC is the vertex if and is not an edge; otherwise it is a component , where is the first vertex of that the search reaches, and is the result of the search , which starts in a clean state.
Proof. By strong induction on . Assume the claim for all smaller sets.
The loop flag. Let be a root, so VISIT reaches line L10 with . The variable only goes down, so no successor gave a value below , and is true if and only if some successor gave exactly . Let be the SCC of . If is an edge, line L8 gives for it. If , some edge has and . All of lies in the search tree below , so lies below some tree child of , and is on the stack when the edge is examined. By (T4) VISIT returns at most , so it returns exactly . In the other direction, if a successor gives , then either , or by (T4) the tree below has an edge to , so is on a cycle. So is true if and only if is not a single vertex without a self-loop.
The elements. By (T1) line L10 holds once per SCC, at its first vertex . By (T2) the vertices above on the stack are . If is false, , line L11 makes done, and line L15 adds the vertex . If is true, line L11 makes done, and line L13 pops and sets their DFN to 0. So the search of line L14 starts with (C1). For (C2), let be an edge with . If , then , which is done, or . If , then is not on the stack: a vertex on the stack below reaches (Tarjan's stack invariant), so it would be in . And has a nonzero DFN, because the search tree below has examined the edge . So is done. Thus the inner search starts in a clean state, and , so the claim holds for it.
Every vertex of is reached by the inner search. Take and a shortest path from to in . It visits only at its start, so its second vertex is in and the rest of the path stays in . So by (a) for the inner search, all of 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 . This is what Lemma 1 needs.
The order. Each element goes to the front of when its root reaches line L14 or L15. By (T3), if an edge goes from SCC to SCC , the element of is added first, so it ends up after the element of . This is (b).
Part (a). Every vertex of is in some SCC, so it is either a root made done at line L11 or a vertex of some 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 , because by (C2) it only reaches vertices of or done vertices.
Theorem 1. WTO returns a weak topological ordering of the set of vertices reachable from .
Proof. WTO is the search , which starts in a clean state, and its set is . We show by strong induction on that the list of any search from a clean state has two properties.
It is a hierarchical ordering of . By (b) and (c), the elements cover the SCCs of , which partition . A vertex element holds one vertex. A component element of holds and, by induction, each vertex of once.
Every edge with satisfies the WTO condition with . Let and be the elements of that contain and .
- . By (b) comes before , so . The heads in lie in , and does not, so . The edge is forward.
- is a vertex. Then and is a self-loop, which (c) rules out. This case does not occur.
- and . The head comes first in its element, so , and by (1). The edge is backward. This includes the self-loop .
- , and . Then is in , so , and does not hold . The edge is forward.
- and . Both are in , the edge lies in , and the inner search reaches both. By induction the edge satisfies the condition in . The order of restricted to is the order of , and by (1) with . So a forward edge of (, ) is forward in , and a backward edge of (, ) is backward in .
For the top level, every edge out of a vertex of ends in , so every such edge is covered.
Theorem 2. Every cycle of through a vertex of contains a head of the WTO.
Proof. All the vertices of the cycle are in . Let be the last of them in the order, and let be the vertex after on the cycle. Then , so the edge is not forward, and by Theorem 1 it is backward: . So is a head.
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 is monotone and reads only for the predecessors of . Assume that is a widening: and , and for every increasing chain the sequence , is constant from some index on. All values start at . A vertex outside is never assigned, so its value stays .
Lemma 3 (values only grow). No assignment of ITERATE makes a value smaller: after each assignment the new value is the old one.
Proof. By induction on the number of assignments. At lines L24 and L29, . At line L22, the old value of is or for the state of the last assignment to . By induction at every vertex, so by monotonicity .
Lemma 4 (finitely many changes at a head). Over any run, the value of a head changes only finitely many times.
Proof. Only lines L24 and L29 for the component of assign . Let be the values of used by these assignments, in time order. By Lemma 3 the states grow, so by monotonicity. The values of are and , the widened sequence of the chain . If the chain is infinite, the sequence is constant from some index on. Either way it changes finitely often.
Theorem 3 (termination). ITERATE stops for every WTO .
Proof. By induction on the depth of nesting of . If has no component, it makes one assignment per element. Otherwise take a component of . By induction every call ITERATE stops. Consider one run of the loop of lines L25 to L29. Each round that does not leave the loop has at line L28. Then line L29 gives , which differs from the old , so the value of changes. If the loop never ended, would change infinitely often, against Lemma 4. So each element of is processed in finite time, and has finitely many elements.
Lemma 5 (who comes after whom). Let be an edge with .
- (i) If is not a head, then every assignment to is followed later by an evaluation of at line L22.
- (ii) If is the head of the component and is not in , then every assignment to is followed later by a test of line L28 for .
Proof. In both cases the edge is forward by Theorem 1. For (i), because is not a head, and would need . For (ii), a backward edge to needs , which means is in . So and .
Let be the body of the innermost component that contains both and , or the whole WTO if there is none. Write for its head, if it has one.
If , then is in the body . Every assignment to is at line L24 or L29, and both are followed by a call ITERATE, which processes the element of that contains .
Otherwise and are in , in elements and of . These differ: a component element holding both would contradict the choice of , and a vertex element holding both would mean with a self-loop, so would be a head with in its component. Since , comes before . Every assignment to happens while ITERATE processes in some pass over , and that pass then processes , by Theorem 3 to its end.
It remains to see what processing does. A component is processed by at least one pass over its body, and each pass processes every element of the body. So processing reaches line L22 for in case (i), since is not a head and so is a vertex element at some depth. In case (ii), is or lies inside , and every processing of ends with a test of line L28 that passes, by Theorem 3.
Theorem 4 (post-fixed point). When ITERATE ends, the final values satisfy for every .
Proof. Let be a vertex that is not a head, and let be the time of its last evaluation at line L22, with state . By Lemma 5 (i), no predecessor of in is assigned after , and predecessors outside never change. reads only the predecessors, so .
Let be the head of the component , and let be the time of the last test of line L28 for . That test passed, since the run ended: . After , is never processed again, since each processing ends with such a test. Every assignment to a vertex of happens while is processed, so no vertex of , included, changes after . A predecessor of outside is not assigned after by Lemma 5 (ii). Hence .
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 with , which the Cousots call a post-fixed point and the Knaster-Tarski page calls a pre-fixed point. When each 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.
Complexity
Building the WTO. A unit step is one look at an edge or one push or pop. VISIT looks at each successor of once. A vertex is visited once at the top level, and once more by COMPONENT of each component that contains and has a head other than . COMPONENT looks at the successors of once more. So the successor list of is read exactly times, and the total time is
With no cycle, and the time is . In the worst case : on the chain the WTO is , vertex is read times for , and the total is , which is for this graph. The stack, the DFN array and the output take space.
Iterating. ITERATE evaluates 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 names, a head can change at most 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 , , the WTO is 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 , , , gives
0 (1 2). The edge 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 , 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 , and
bodygets and . 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 in place of 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 < headin place ofmin ≤ head, the flag stays false at the root of every part, because every cycle through the root returns exactly . 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 isentry 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 . - 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 for every vertex still stops, but it loses bounds that a guard has just set. In the example,
inithas after the first pass, and in the second pass gives , so the widening sets and the guardi < 3is 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 levels deep, and ITERATE 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag X5B201 Edit this page History Report an error Markdown