Algorithm Search⌘K

Data structureadvanced

Loop nesting forest

Also called loop tree.

A forest whose nodes are the loops of a flow graph, with each loop below the loops that contain it, defined for irreducible graphs too.

A loop nesting forest describes the loops of a control flow graph and how they nest. Each node of the forest is a loop, a set of blocks, with a set of headers, and each loop lies below the smallest loop that contains it. On a reducible flow graph the loops are the natural loops merged by header, and the forest is the usual loop tree of a compiler. The forest is also defined when the graph is irreducible: a loop that can be entered at several blocks gets several headers. This page builds the forest of Steensgaard. The outer loops are the nontrivial strongly connected components of the graph. The headers of a loop are its blocks with a predecessor outside the loop, and the inner loops are found again in the loop with its headers removed. Removing the edges from each loop into its headers leaves a graph with no cycle.

In plain words

A program often has loops inside loops. A compiler wants a map of them: which blocks belong to each loop, where each loop starts, and which loop is inside which. The loop nesting forest is that map. To build it, find each group of blocks in which every block can get to every other block. Each such group is a loop. The blocks where control can come into the group from outside are its headers, the doors of the loop. Take the doors away, and look for groups again inside what is left. These are the inner loops. Go on until no group is left. In a well-structured program every loop has one door, at its top. In other programs a loop can have two or more doors, and the map shows all of them.

The abstract type

The input is a flow graph G=(V,E,r)G = (V, E, r) with a root rr. Only the part that rr reaches counts. The structure holds a family of loops. Each loop LL is a set of vertices with a nonempty set H(L)⊆LH(L) \subseteq L of headers and a parent loop or none. The operations are:

  • loop_forest(G, r): build the structure.
  • headers(L), parent(L), children(L): read the forest.
  • innermost(v): the smallest loop that contains vv, or none.
  • depth(L): the number of loops from LL up to its root, with LL counted.

The laws:

  • Nesting. Two loops are disjoint or one contains the other, and the loops that contain LL are LL and its ancestors.
  • Children avoid the headers. A child of LL lies in L∖H(L)L \setminus H(L).
  • Loops are cycles. Each loop is strongly connected and holds a cycle, and every cycle of the graph lies in some loop.
  • The headers break the cycles. If the edges from inside each loop LL into H(L)H(L) are removed, the graph has no cycle.
  • Reducible graphs. If GG is reducible, each loop has one header hh. hh dominates the loop, and the loop is the union of the natural loops of the back edges into hh. There is one loop for each vertex that is the target of a back edge.

Representation

The Python code returns a list of loops. Each loop is a dict with the sorted list nodes, the sorted list headers and the index parent, which is −1-1 at a root of the forest. A parent comes before its children in the list. innermost(n, loops) gives each vertex its innermost loop, and depth(loops, i) follows the parent indices. cfg_loops(prog) does the same for a program in the toy IR and uses block labels.

A compiler does not store the full vertex set of every loop, because a vertex at depth dd would be stored dd times. It keeps one record per loop with its headers, its parent and its children, and one pointer per block to the innermost loop. Then the loops of a block are found by following parents, and the blocks of a loop by walking its subtree. This uses O(n)O(n) space for nn blocks.

Operations

  1. LOOP-NESTING-FOREST(G, r)
  2. 1R0 <- the vertices that r reaches; T <- the stack [(R0, none)]
  3. 2while T is not empty do
  4. 3(R, p) <- pop(T)
  5. 4for each strongly connected component S of G[R] do
  6. 5skip S if it has one vertex and no self-loop
  7. 6H <- {v in S : v = r or v has a predecessor in R0 outside S}
  8. 7record the loop S with headers H and parent p
  9. 8push (S \ H, the new loop) on T
  10. 9return the loops

Line L1 drops the unreachable part, and line L6 looks only at predecessors that rr reaches, so dead code cannot create a header. The root has no predecessor, so line L6 counts it as an entry, as if control came into it from outside. A loop always has a header: if it does not hold rr, a path from rr into the loop must enter it somewhere. So each region on the stack is smaller than the loop above it, and the loop stops. The code finds the components with Tarjan's algorithm, with an explicit stack, so deep nesting does not use Python recursion.

innermost walks the list once and keeps, for each vertex, the last loop that contains it. This is the innermost one, because the loops that contain a vertex form a chain and a parent comes before its children.

Example

Take the blocks B0 to B6 with the edges B0→B1, B1→B2, B2→B1, B2→B3, B3→B4, B4→B3, B4→B5, B5→B1 and B5→B6. This is a loop at B1 with a loop at B3 inside it.

step region components loop found headers
1 B0 to B6 {B0}, {B1, B2, B3, B4, B5}, {B6} {B1, B2, B3, B4, B5} B1, entered from B0
2 {B2, B3, B4, B5} {B2}, {B3, B4}, {B5} {B3, B4}, parent 0 B3, entered from B2
3 {B4} {B4} none, B4 has no self-loop

The innermost loops are: B0 none, B1 loop 0, B2 loop 0, B3 loop 1, B4 loop 1, B5 loop 0, B6 none. The edges into headers from inside their loops are B2→B1, B5→B1 and B4→B3. Without them the graph has no cycle. The graph is reducible, and loop 0 is the union of the natural loops of B2→B1 and B5→B1.

Now take an irreducible graph: r→A, r→B, A→B, B→A and A→C. The only nontrivial component is {A, B}. Both blocks have the predecessor r outside it, so the loop {A, B} has the headers A and B, and nothing is left inside. No block of the cycle dominates the other, so the graph has no back edge at all, and no natural loop finds this cycle. The forest still shows it.

Correctness

The proof file shows four things. First, every loop has a header, so the regions shrink and the construction stops, with at most nn loops and depth at most nn. Second, the loops nest: loops made from one region are disjoint, and everything below a loop lies in it. Third, a cycle that avoids all the removed edges would lie in one component of some region, would have to avoid its headers, and so would lie in a smaller region, which gives a contradiction by induction. Fourth, for a reducible graph, take the first vertex hh of a top loop in a topological order of the graph without back edges. Every edge into hh from the loop is then a back edge, hh dominates the loop and is its only header, and the loop is the union of the natural loops into hh. Inside the loop, delete the edges into hh and make hh the root. This smaller graph is reducible, has the same dominators and natural loops, and gives the same inner loops with the same headers, so induction on the number of edges finishes the proof. The component step is Tarjan's algorithm and is cited.

Proof: The loops of repeated strongly connected components form a forest that breaks every cycle, and on a reducible graph they are the natural loopsfull

Setting. A flow graph is G=(V,E,r)G = (V, E, r) with a root r∈Vr \in V. Let VrV_r be the set of vertices that rr reaches, and keep only the edges whose source is in VrV_r; their targets are then in VrV_r too. All paths, cycles and predecessors below are in this graph. A path may have length 0. For R⊆VrR \subseteq V_r, G[R]G[R] is the subgraph induced by RR. A strongly connected component SS of G[R]G[R] is nontrivial if ∣S∣>1|S| > 1 or S={v}S = \{v\} with a self-loop (v,v)(v, v). Note that a set is nontrivial exactly when it holds a cycle.

Definition. The forest is built by SPLIT(Vr,⊥)\mathrm{SPLIT}(V_r, \bot), where SPLIT(R,p)\mathrm{SPLIT}(R, p) does this for each nontrivial strongly connected component SS of G[R]G[R]: it makes SS a loop with parent pp and header set

H(S)={v∈S:v=r or some predecessor of v lies outside S},H(S) = \{v \in S : v = r \text{ or some predecessor of } v \text{ lies outside } S\},

and then calls SPLIT(S∖H(S),S)\mathrm{SPLIT}(S \setminus H(S), S). Lines L1 to L9 of the code do exactly this, with a stack of pending regions in place of the recursion. The regions are handled one at a time and the result for one region does not depend on the others, so the order of the stack does not matter. The components come from Tarjan's algorithm, which is cited, not proved here; the tests check them against mutual reachability.

Lemma 1 (termination and size). Every loop SS has H(S)≠∅H(S) \neq \emptyset. So every call works on a smaller region than its parent call, the recursion stops, and the depth of the forest is at most ∣Vr∣|V_r|. Each vertex is a header of at most one loop, so there are at most ∣Vr∣|V_r| loops.

Proof. If r∈Sr \in S then r∈H(S)r \in H(S). Otherwise take v∈Sv \in S and a path from rr to vv. It starts outside SS and ends in SS, so it has an edge (u,w)(u, w) with u∉Su \notin S and w∈Sw \in S, and w∈H(S)w \in H(S). So ∣S∖H(S)∣<∣S∣≤∣R∣|S \setminus H(S)| < |S| \le |R|. A header hh of SS is not in S∖H(S)S \setminus H(S), so no loop below SS contains it, and loops made in the same call are disjoint, as components are. □\square

Lemma 2 (laminar family). Any two loops are disjoint or one contains the other. The loops that contain a loop LL are exactly LL and its ancestors, so the parent of LL is the smallest loop that strictly contains it. A child of LL lies in L∖H(L)L \setminus H(L).

Proof. By the definition, every loop below SS lies in S∖H(S)S \setminus H(S). Take two loops A≠BA \ne B. If one is an ancestor of the other, it contains the other. Otherwise take the deepest call that lies on both of their paths from the top call. AA lies in (or is) one component of that call and BB in another, so they are disjoint. Now let L′⊇LL' \supseteq L with L′≠LL' \ne L. L′L' is not disjoint from LL, so it is an ancestor or a descendant of LL, and a descendant lies in L∖H(L)L \setminus H(L), which is strictly smaller than LL. So L′L' is an ancestor. □\square

Theorem 1 (the forest breaks every cycle). Let CC be the set of edges (u,h)(u, h) such that u∈Lu \in L and h∈H(L)h \in H(L) for some loop LL. Then the graph (Vr,E∖C)(V_r, E \setminus C) has no cycle. Each loop also holds a cycle through each of its headers, so every loop is used.

Proof. We show, by induction on ∣R∣|R|, that for every region RR on which SPLIT\mathrm{SPLIT} is called, G[R]G[R] without the edges of CC has no cycle. With R=VrR = V_r this is the theorem. Let ZZ be a cycle in G[R]∖CG[R] \setminus C. Its vertices reach each other inside RR, so they lie in one component SS of G[R]G[R], and SS is nontrivial because it holds a cycle. So SS is a loop. If ZZ passes a header h∈H(S)h \in H(S), the edge of ZZ into hh comes from a vertex of Z⊆SZ \subseteq S, so it is in CC, which is false. So ZZ lies in S∖H(S)S \setminus H(S), and SPLIT\mathrm{SPLIT} is called on this smaller region, where by induction no such cycle exists. For the last claim: SS is strongly connected and nontrivial, so each h∈Sh \in S lies on a cycle inside SS. □\square

Reducible graphs. An edge (u,v)(u, v) is a back edge if vv dominates uu; let BB be the set of back edges. GG is reducible if (Vr,E∖B)(V_r, E \setminus B) has no cycle. A self-loop is a back edge. The natural loop of a back edge (u,h)(u, h) is N(u,h)={h}∪{w:some path from w to u avoids h}N(u, h) = \{h\} \cup \{w : \text{some path from } w \text{ to } u \text{ avoids } h\}.

Lemma 3 (the top loops of a reducible graph). Let GG be reducible and let SS be a nontrivial component of G[Vr]G[V_r]. Let hh be the first vertex of SS in a topological order of (Vr,E∖B)(V_r, E \setminus B). Then:

(a) every edge (u,h)(u, h) with u∈Su \in S is a back edge; (b) hh dominates every vertex of SS; (c) H(S)={h}H(S) = \{h\}; (d) every back edge (u,h)(u, h) has u∈Su \in S, and SS is the union of N(u,h)N(u, h) over these back edges.

Proof. (a) If (u,h)(u, h) were not a back edge, uu would come before hh in the order, but hh is the first vertex of SS. (A self-loop is a back edge anyway.)

(b) Let w∈Sw \in S, w≠hw \ne h, and suppose a path PP from rr to ww avoids hh. Take a path QQ from ww to hh inside SS and let uu be the vertex just before the first hh on QQ. Then u∈Su \in S, and PP followed by the part of QQ up to uu is a path from rr to uu that avoids hh. But (u,h)(u, h) is a back edge by (a), so hh dominates uu, which is false.

(c) First, H(S)H(S) is not empty by Lemma 1. Let x∈H(S)x \in H(S). If x=rx = r, then rr dominates hh and hh dominates rr by (b), so x=r=hx = r = h. Otherwise xx has a predecessor y∉Sy \notin S. Suppose x≠hx \ne h. A path from rr to yy, followed by the edge (y,x)(y, x), passes hh by (b), and h≠xh \ne x, so hh lies on the part up to yy. Then hh reaches yy, yy reaches xx, and xx reaches hh inside SS, so y∈Sy \in S, which is false. So x=hx = h.

(d) Let (u,h)(u, h) be a back edge. Every path from rr to uu passes hh, so hh reaches uu, and uu reaches hh by the edge, so u∈Su \in S. Let w∈N(u,h)w \in N(u, h) with w≠hw \ne h, and let PP be a path from ww to uu that avoids hh. If a path from rr to ww avoided hh, then with PP it would give a path from rr to uu that avoids hh; so hh dominates ww, hh reaches ww, and ww reaches hh through uu. So w∈Sw \in S. Conversely, let w∈Sw \in S, w≠hw \ne h, take a path from ww to hh inside SS, and let uu be the vertex just before its first hh. Then (u,h)(u, h) is a back edge by (a), and the path up to uu avoids hh, so w∈N(u,h)w \in N(u, h). □\square

Lemma 4 (the graph inside a top loop). In the setting of Lemma 3, let G′G' have the vertices SS, the edges of G[S]G[S] except those that end at hh, and the root hh. Then:

(a) hh reaches every vertex of SS in G′G'; (b) for a,b∈Sa, b \in S, aa dominates bb in G′G' if and only if aa dominates bb in GG; (c) G′G' is reducible, its back edges are the back edges of GG inside SS that do not end at hh, and for such a back edge (u,y)(u, y) the natural loop in G′G' equals the natural loop in GG; (d) the loops of G′G' are exactly the loops of GG below SS, with the same header sets.

Proof. (a) Let w∈Sw \in S. A path from rr to ww passes hh by Lemma 3(b). Its part after the last hh does not return to hh, and each of its vertices zz is reached from hh and reaches ww, which reaches hh, so z∈Sz \in S. So this part is a path of G′G'.

(b) Suppose aa dominates bb in G′G', and let PP be a path in GG from rr to bb. As in (a), the part of PP after its last hh is a path of G′G' from hh to bb, so it passes aa, and so does PP. Conversely, suppose aa dominates bb in GG, and let QQ be a path in G′G' from hh to bb. If a=ha = h, QQ passes aa. Otherwise take a path P0P_0 in GG from rr to the first hh it meets. P0P_0 followed by QQ is a path of GG to bb, so it passes aa. If aa were on P0P_0, it would be before hh, and the part of P0P_0 up to aa would reach a∈Sa \in S without passing hh, against Lemma 3(b). So aa is on QQ.

(c) By (b), an edge of G′G' is a back edge of G′G' exactly when it is a back edge of GG. By Lemma 3(a), all the removed edges are back edges, so the edges of G′G' that are not back edges are edges of (Vr,E∖B)(V_r, E \setminus B), and they have no cycle. So G′G' is reducible. Every back edge (u,y)(u, y) of GG with y∈Sy \in S has u∈Su \in S, because yy dominates uu and so reaches it, and uu reaches yy. Now let y≠hy \ne h. A path of G′G' is a path of GG, so the natural loop in G′G' lies in the one in GG. Conversely, let PP be a path in GG from ww to uu that avoids yy. Each vertex zz of PP is dominated by yy, since a path from rr to zz that avoids yy would, with the rest of PP, reach uu without yy. So yy reaches zz, and zz reaches yy through uu, so z∈Sz \in S. If PP passed hh, then yy would dominate hh, while hh dominates yy by Lemma 3(b), so y=hy = h, which is false. So PP is a path of G′G'.

(d) In G′G' no edge ends at hh, so {h}\{h\} is a trivial component, and the other components of G′G' are the components of G′[S∖{h}]=G[S∖{h}]G'[S \setminus \{h\}] = G[S \setminus \{h\}], the region of the call SPLIT(S∖H(S),S)\mathrm{SPLIT}(S \setminus H(S), S) in GG. So both build the same loops at their top level. For the headers, let S2S_2 be such a loop and x∈S2x \in S_2. The root of G′G' is h∉S2h \notin S_2, and the root rr of GG is not in S2S_2 either, since r∈Sr \in S would mean r=hr = h by Lemma 3(c). A predecessor yy of xx in GG lies in SS, since otherwise x≠hx \ne h would be in H(S)H(S), against Lemma 3(c). So xx has the same predecessors in GG and in G′G', and H(S2)H(S_2) is the same in both. The calls below S2S_2 then see the same regions and the same predecessors, so the whole subtree is the same. □\square

Theorem 2 (reducible graphs). Let GG be reducible. Then every loop LL of the forest has exactly one header hh, hh dominates every vertex of LL, and LL is the union of the natural loops of all the back edges that end at hh. The map from a loop to its header is a one-to-one map from the loops onto the targets of the back edges.

Proof. By induction on the number of edges. The loops at the top level satisfy the claims by Lemma 3. A loop LL below a top loop SS is a loop of G′G' with the same headers (Lemma 4(d)). G′G' is reducible and has fewer edges, since SS holds an edge into hh by Lemma 3(a) and the nontriviality of SS. So by induction LL has one header h2h_2, h2h_2 dominates LL in G′G', and LL is the union of the natural loops in G′G' of the back edges of G′G' into h2h_2. By Lemma 4(b) and (c), the same holds in GG, and since h2≠hh_2 \ne h, the back edges of G′G' into h2h_2 are all the back edges of GG into h2h_2.

For the map: each loop LL with header hh holds an edge from LL into hh, which is a back edge (Lemma 3(a), in GG or in G′G'), so hh is a back edge target. Different loops have different headers by Lemma 1. Let yy be the target of a back edge (u,y)(u, y). Then uu and yy lie on a cycle, so yy is in a top loop SS. If yy is the header of SS we are done. Otherwise (u,y)(u, y) is a back edge of G′G' by Lemma 4(c), and by induction yy is the header of a loop of G′G', which is a loop of GG by Lemma 4(d). □\square

Cost. Let n=∣V∣n = |V|, m=∣E∣m = |E| and let dd be the depth of the forest. The regions of the calls at one depth are disjoint, so all the calls at one depth cost O(n+m)O(n + m) for the components, the header sets and the new regions, counting each edge from its source and from its target. There are at most d+1d + 1 depths, so the total is O((d+1)(n+m))O((d + 1)(n + m)), which is O(n(n+m))O(n (n + m)) in the worst case by Lemma 1. The Python code also sorts each region and each loop for a fixed output order, which adds O(nlog⁡n)O(n \log n) per depth. The bound is reached: the path 0,1,…,2k0, 1, \ldots, 2k with the back edges (2k−i,i)(2k - i, i) for i<ki < k has kk nested loops, and the call at depth ii works on about 2k−2i2k - 2i vertices, so the work is Θ(k2)\Theta(k^2) for a graph with Θ(k)\Theta(k) edges.

What is proved and what is measured. Lemmas 1 to 4 and Theorems 1 and 2 are proved here, given that the component step is correct. The almost-linear algorithms of Ramalingam for other forests are cited, not proved. The tests compare the code with a direct reading of the definition that finds components by mutual reachability, with the merged natural loops of brute-force dominators on reducible graphs, and with the properties of Lemma 2 and Theorem 1. The running times in the tests and on the page are measurements.

Complexity

Let nn be the number of vertices, mm the number of edges and dd the depth of the forest.

operation time space
build (lines L1 to L9) O((d+1)(n+m))O((d + 1)(n + m)), so O(n(n+m))O(n (n + m)) in the worst case O(n+m)O(n + m) working space
the loops as vertex lists Θ(∑vdepth(v))\Theta(\sum_v \mathrm{depth}(v)), at most O(nd)O(n d)
innermost for all vertices O(∑vdepth(v))O(\sum_v \mathrm{depth}(v)) O(n)O(n)
parent, headers O(1)O(1)
depth(L) O(depth(L))O(\mathrm{depth}(L))

Proved. The regions at one depth of the forest are disjoint, so one depth costs O(n+m)O(n + m), and there are at most d+1d + 1 depths. The bound is tight: the path 0,1,…,2k0, 1, \ldots, 2k with the back edges 2k−i→i2k - i \to i for i<ki < k has kk nested loops, and the work is Θ(k2)\Theta(k^2) for Θ(k)\Theta(k) edges. The Python code also sorts each region and each loop for a fixed output, which adds O(nlog⁡n)O(n \log n) per depth.

Cited, not proved. Ramalingam showed that Havlak's algorithm is quadratic in the worst case, not almost linear as first stated, and gave almost-linear versions of it and of the algorithm of Sreedhar, Gao and Lee. He later defined the reduced Havlak forest, which a bottom-up algorithm builds in almost linear time. Those algorithms build other forests, not the one of this page.

Measured, not proved. On the nested path above, the Python code took about 0.04 s for k=250k = 250, 0.17 s for k=500k = 500, 0.71 s for k=1000k = 1000 and 3.0 s for k=2000k = 2000 on one laptop, about four times as long for each doubling. Over 2,000 seeded random graphs with up to 9 vertices, 1,749 were reducible, and the loops had 1 header in 2,140 cases, 2 in 223, 3 in 49 and 4 in 14.

Variants

  • Havlak's forest. Do a depth-first search and give each loop one header, its first vertex in the search. On an irreducible graph the result can depend on the order of the search.
  • Sreedhar, Gao and Lee. Find the loops with the dominator tree and the join edges of the flow graph, the DJ graph.
  • Reduced Havlak forest. Ramalingam's forest, built bottom-up in almost linear time.
  • The loop tree of a reducible graph. Find the back edges with dominators, build each natural loop by a backward search from the tail, and merge the loops that share a header. On a reducible graph this gives the forest of this page, as the proof file shows.
  • A virtual root. Many compilers add one more node above the forest for the whole function, so the forest becomes a tree.

When to use it

Use the forest when an optimization needs the loop structure: loop invariant code motion, induction variable analysis, unrolling and other loop transformations, block placement, and register allocation that weights spill costs by loop depth. It is also a good order for iterative data-flow analysis, since an inner loop can settle before its outer loop. Use this construction when the input can be irreducible, for example code from a goto, from a decompiler or from a JIT that enters a loop in the middle. If the graph is known to be reducible, the natural loops from a dominator tree give the same forest and often come for free.

Pitfalls

  • One header is not always true. An irreducible loop has two or more headers. An optimization that puts a preheader before "the" header must skip such a loop or first make it reducible, for example by node splitting.
  • The forests differ. On an irreducible graph, Steensgaard's, Havlak's and other forests can give different headers and different inner loops. Do not mix results from two of them.
  • The root. The entry block has no predecessor. If it lies on a cycle, it must still count as a header, or the loop through it gets no header and the construction does not stop.
  • Unreachable code. An edge from a block that the entry cannot reach must be ignored. Otherwise it can turn a block of a real loop into a header.
  • Self-loops. A block with an edge to itself is a loop with one vertex. A block on no cycle is not a loop.
  • Recursion depth. Loop nests from generated code can be hundreds deep. Use explicit stacks for the components and for the regions.
  • Stale forests. A transformation that adds or removes blocks or edges can change the loops. Rebuild the forest or update it.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

loop_nesting_forest.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loop-nesting-forest/. The authors are listed in prov/EMNP01.jsonl.
"""A loop nesting forest by repeated strongly connected components.

loop_forest(n, edges, root) returns a list of loops. Each loop is a dict
with "nodes" (the sorted vertices of the loop, inner loops included),
"headers" (its entry vertices, sorted) and "parent" (the index of the
smallest loop that contains it, or -1). The loops are the nontrivial
strongly connected components of the part that root reaches; inside each
loop, the headers are removed and the rest is split again. The headers of a
loop are its vertices with a predecessor outside the loop, and root, if the
loop contains it. This choice of headers is the one of Steensgaard; on a
reducible graph each loop then has one header and is the union of the
natural loops of that header.

innermost(n, loops) gives, for each vertex, the index of the innermost loop
that contains it, or -1. cfg_loops(prog) works on the blocks of a toy IR
program and uses labels.
"""

import toyir


def _sccs(nodes, succ):
    """Tarjan's algorithm with an explicit stack, on the subgraph induced by
    the set nodes. Returns the components as lists."""
    index = {}
    low = {}
    on = set()
    stack = []
    out = []
    counter = 0
    for s in sorted(nodes):
        if s in index:
            continue
        index[s] = low[s] = counter
        counter += 1
        stack.append(s)
        on.add(s)
        work = [(s, iter(succ[s]))]
        while work:
            v, it = work[-1]
            advanced = False
            for w in it:
                if w not in nodes:
                    continue
                if w not in index:
                    index[w] = low[w] = counter
                    counter += 1
                    stack.append(w)
                    on.add(w)
                    work.append((w, iter(succ[w])))
                    advanced = True
                    break
                if w in on and index[w] < low[v]:
                    low[v] = index[w]
            if advanced:
                continue
            work.pop()
            if work:
                u = work[-1][0]
                if low[v] < low[u]:
                    low[u] = low[v]
            if low[v] == index[v]:
                comp = []
                while True:
                    w = stack.pop()
                    on.discard(w)
                    comp.append(w)
                    if w == v:
                        break
                out.append(comp)
    return out


def loop_forest(n, edges, root):
    if n < 1 or not 0 <= root < n:
        raise ValueError("a flow graph needs n >= 1 vertices and a root in range")
    succ = [[] for _ in range(n)]
    for a, b in edges:
        if not (0 <= a < n and 0 <= b < n):
            raise ValueError("edge endpoint out of range")
        succ[a].append(b)
    seen = {root}  # @line L1
    stack = [root]
    while stack:
        v = stack.pop()
        for w in succ[v]:
            if w not in seen:
                seen.add(w)
                stack.append(w)
    pred = [[] for _ in range(n)]
    for a, b in edges:
        if a in seen:
            pred[b].append(a)

    loops = []
    regions = [(seen, -1)]
    while regions:  # @line L2
        region, parent = regions.pop()  # @line L3
        for comp in _sccs(region, succ):  # @line L4
            body = set(comp)
            v = comp[0]
            if len(comp) == 1 and v not in succ[v]:  # @line L5
                continue
            heads = {x for x in body if x == root or any(p not in body for p in pred[x])}  # @line L6
            loops.append({"nodes": sorted(body), "headers": sorted(heads), "parent": parent})  # @line L7
            regions.append((body - heads, len(loops) - 1))  # @line L8
    return loops  # @line L9


def innermost(n, loops):
    """The innermost loop of each vertex, or -1. A loop comes after its
    parent in the list, so the last loop that contains a vertex is the
    innermost one."""
    out = [-1] * n
    for i, loop in enumerate(loops):
        for v in loop["nodes"]:
            out[v] = i
    return out


def depth(loops, i):
    """The number of loops on the path from loop i up to its root."""
    d = 0
    while i != -1:
        d += 1
        i = loops[i]["parent"]
    return d


def cfg_loops(prog):
    """The loops of a toy IR program, with block labels instead of numbers."""
    labels = list(prog.blocks)
    index = {lab: i for i, lab in enumerate(labels)}
    edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
    loops = loop_forest(len(labels), edges, 0)
    return [
        {
            "nodes": [labels[v] for v in loop["nodes"]],
            "headers": [labels[v] for v in loop["headers"]],
            "parent": loop["parent"],
        }
        for loop in loops
    ]
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

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

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

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

from dataclasses import dataclass, field
import re

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


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


@dataclass
class Program:
    params: list
    blocks: dict

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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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

    walk([prog.entry])
    return out


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


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


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


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

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

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


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

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

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


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


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

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


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

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

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

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

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

import pytest

import toyir
from loop_nesting_forest import cfg_loops, depth, innermost, loop_forest


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


def reach_in(allowed, succ, s):
    """The vertices of allowed that s reaches inside allowed (s included)."""
    seen = {s}
    stack = [s]
    while stack:
        v = stack.pop()
        for w in succ[v]:
            if w in allowed and w not in seen:
                seen.add(w)
                stack.append(w)
    return seen


def adjacency(n, edges):
    succ = [[] for _ in range(n)]
    for a, b in edges:
        succ[a].append(b)
    return succ


def by_definition(n, edges, root):
    """The forest from its recursive definition, with mutual reachability in
    place of a strongly connected components algorithm."""
    succ = adjacency(n, edges)
    reach = reach_in(set(range(n)), succ, root)
    pred = [[] for _ in range(n)]
    for a, b in edges:
        if a in reach:
            pred[b].append(a)
    out = set()

    def split(region):
        r = {v: reach_in(region, succ, v) for v in region}
        done = set()
        for v in sorted(region):
            if v in done:
                continue
            comp = {w for w in r[v] if v in r[w]}
            done |= comp
            if len(comp) == 1 and v not in succ[v]:
                continue
            heads = {x for x in comp if x == root or any(p not in comp for p in pred[x])}
            out.add((frozenset(comp), frozenset(heads)))
            split(comp - heads)

    split(reach)
    return out


def natural_loops(n, edges, root):
    """(reducible, loops) where loops are the natural loops, merged by
    header, with dominators from their definition: d dominates v when v
    cannot be reached from root once d is removed."""
    succ = adjacency(n, edges)
    reach = reach_in(set(range(n)), succ, root)

    def dominates(d, v):
        if d == v or d == root:
            return True
        return v not in reach_in(reach - {d}, succ, root)

    pred = [[] for _ in range(n)]
    for a, b in edges:
        if a in reach:
            pred[b].append(a)
    live = [(a, b) for a, b in edges if a in reach]
    back = [(a, b) for a, b in live if dominates(b, a)]
    forward = adjacency(n, [(a, b) for a, b in live if not dominates(b, a)])
    reducible = not has_cycle(reach, forward)
    loops = {}
    for a, h in back:
        body = loops.setdefault(h, {h})
        if a in body:
            continue
        body.add(a)
        stack = [a]
        while stack:
            v = stack.pop()
            for p in pred[v]:
                if p not in body:
                    body.add(p)
                    stack.append(p)
    return reducible, {(frozenset(b), frozenset([h])) for h, b in loops.items()}


def has_cycle(vertices, succ):
    indeg = {v: 0 for v in vertices}
    for v in vertices:
        for w in succ[v]:
            if w in indeg:
                indeg[w] += 1
    ready = [v for v in vertices if indeg[v] == 0]
    count = 0
    while ready:
        v = ready.pop()
        count += 1
        for w in succ[v]:
            if w in indeg:
                indeg[w] -= 1
                if indeg[w] == 0:
                    ready.append(w)
    return count != len(vertices)


def as_set(loops):
    return {(frozenset(x["nodes"]), frozenset(x["headers"])) for x in loops}


def random_graph(rng):
    n = rng.randint(1, 9)
    m = rng.randint(0, 3 * n)
    edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]
    return n, edges, rng.randrange(n)


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


def test_nested_loops_example():
    # B0 -> B1 -> B2 -> B3 -> B4 -> B5 -> B6, with back edges B2 -> B1,
    # B4 -> B3 and B5 -> B1.
    edges = [(0, 1), (1, 2), (2, 1), (2, 3), (3, 4), (4, 3), (4, 5), (5, 1), (5, 6)]
    loops = loop_forest(7, edges, 0)
    assert loops == [
        {"nodes": [1, 2, 3, 4, 5], "headers": [1], "parent": -1},
        {"nodes": [3, 4], "headers": [3], "parent": 0},
    ]
    assert innermost(7, loops) == [-1, 0, 0, 1, 1, 0, -1]
    assert [depth(loops, i) for i in range(2)] == [1, 2]


def test_irreducible_loop_has_two_headers():
    # r -> A, r -> B, A <-> B, A -> C. The cycle can be entered at A or at B.
    loops = loop_forest(4, [(0, 1), (0, 2), (1, 2), (2, 1), (1, 3)], 0)
    assert loops == [{"nodes": [1, 2], "headers": [1, 2], "parent": -1}]


def test_small_cases():
    assert loop_forest(1, [], 0) == []
    assert loop_forest(1, [(0, 0)], 0) == [{"nodes": [0], "headers": [0], "parent": -1}]
    assert loop_forest(2, [(0, 1), (1, 1)], 0) == [{"nodes": [1], "headers": [1], "parent": -1}]
    # A loop through the root has the root as a header.
    assert loop_forest(2, [(0, 1), (1, 0)], 0) == [{"nodes": [0, 1], "headers": [0], "parent": -1}]
    assert loop_forest(3, [(0, 1), (1, 0), (1, 2), (2, 1)], 0) == [
        {"nodes": [0, 1, 2], "headers": [0], "parent": -1},
        {"nodes": [1, 2], "headers": [1], "parent": 0},
    ]
    # Repeated edges change nothing.
    assert loop_forest(2, [(0, 1), (1, 1), (1, 1), (0, 1)], 0) == [{"nodes": [1], "headers": [1], "parent": -1}]


def test_unreachable_part_is_ignored():
    # 2 <-> 3 is a cycle that 0 cannot reach, and 3 -> 1 is an edge from it
    # into the loop 1 <-> 4; that edge must not make 1 or 4 a header.
    edges = [(0, 1), (1, 4), (4, 1), (2, 3), (3, 2), (3, 4)]
    assert loop_forest(5, edges, 0) == [{"nodes": [1, 4], "headers": [1], "parent": -1}]


def test_bad_input():
    with pytest.raises(ValueError):
        loop_forest(0, [], 0)
    with pytest.raises(ValueError):
        loop_forest(2, [], 2)
    with pytest.raises(ValueError):
        loop_forest(2, [(0, 2)], 0)


def test_random_graphs_match_the_definition():
    rng = random.Random(97)
    multi = 0
    for _ in range(2000):
        n, edges, root = random_graph(rng)
        got = loop_forest(n, edges, root)
        assert as_set(got) == by_definition(n, edges, root), (n, edges, root)
        multi += sum(1 for x in got if len(x["headers"]) > 1)
    assert multi > 100


def test_reducible_graphs_give_merged_natural_loops():
    rng = random.Random(101)
    seen = [0, 0]
    for _ in range(2000):
        n, edges, root = random_graph(rng)
        reducible, nat = natural_loops(n, edges, root)
        seen[reducible] += 1
        if reducible:
            assert as_set(loop_forest(n, edges, root)) == nat, (n, edges, root)
    assert min(seen) > 100


def test_forest_properties():
    rng = random.Random(103)
    for _ in range(1500):
        n, edges, root = random_graph(rng)
        loops = loop_forest(n, edges, root)
        succ = adjacency(n, edges)
        reach = reach_in(set(range(n)), succ, root)
        sets = [set(x["nodes"]) for x in loops]
        for i, x in enumerate(loops):
            assert x["headers"] and set(x["headers"]) <= sets[i] <= reach
            p = x["parent"]
            assert p < i
            if p != -1:
                assert sets[i] <= sets[p] - set(loops[p]["headers"])
            for j in range(i):
                assert sets[i] <= sets[j] or not (sets[i] & sets[j])
                if sets[i] <= sets[j]:
                    # The parent is the smallest loop above.
                    assert p != -1 and sets[p] <= sets[j]
        inner = innermost(n, loops)
        for v in range(n):
            holding = [i for i in range(len(loops)) if v in sets[i]]
            assert inner[v] == (max(holding, key=lambda i: depth(loops, i)) if holding else -1)
        # Remove the edges from inside each loop to its headers: no cycle is left.
        cut = set()
        for x, s in zip(loops, sets):
            cut |= {(a, b) for a, b in edges if a in s and b in x["headers"]}
        rest = adjacency(n, [(a, b) for a, b in edges if (a, b) not in cut])
        assert not has_cycle(reach, rest)


def test_toy_programs():
    rng = random.Random(107)
    multi = 0
    for _ in range(300):
        prog = toyir.random_program(rng, 4, rng.randint(1, 14), rng.random() < 0.2)
        labels = list(prog.blocks)
        index = {lab: i for i, lab in enumerate(labels)}
        edges = [(index[a], index[b]) for a, b in toyir.edges(prog)]
        got = cfg_loops(prog)
        want = by_definition(len(labels), edges, 0)
        named = {(frozenset(index[v] for v in x["nodes"]), frozenset(index[v] for v in x["headers"])) for x in got}
        assert named == want
        multi += sum(1 for x in got if len(x["headers"]) > 1)
        if toyir.is_acyclic(prog):
            assert got == []
    assert multi > 0


def test_deep_nesting():
    # The path 0 .. 2k with the back edges 2k - i -> i gives k nested loops.
    k = 500
    n = 2 * k + 1
    edges = [(i, i + 1) for i in range(2 * k)] + [(2 * k - i, i) for i in range(k)]
    start = time.perf_counter()
    loops = loop_forest(n, edges, 0)
    assert time.perf_counter() - start < 5
    assert len(loops) == k
    for i, x in enumerate(loops):
        assert x["headers"] == [i] and x["nodes"] == list(range(i, 2 * k - i + 1))
        assert x["parent"] == i - 1
    assert depth(loops, k - 1) == k
    assert innermost(n, loops)[k] == k - 1

History

Early optimizing compilers found loops through intervals and dominators, in the work of Allen and Cocke around 1970, and the natural loops of a reducible graph give the loop tree that textbooks describe. Irreducible graphs needed more. Steensgaard's technical report of 1993 defined loops as nested strongly connected components with entry nodes, for program dependence graphs of irreducible programs. Sreedhar, Gao and Lee found loops with DJ graphs in 1996, and Havlak described a forest from a depth-first search in 1997. Ramalingam showed in 1999 that Havlak's algorithm can take quadratic time and gave almost-linear versions, and in 2002 he described a common frame for these forests and the reduced Havlak forest.

References

  1. G. Ramalingam, On loops, dominators, and dominance frontiers, ACM Transactions on Programming Languages and Systems 24(5), 2002, pages 455-490, loop nesting forests in general, the construction that finds strongly connected components, picks headers, removes the edges into the headers and repeats, the forests of Steensgaard, Havlak and Sreedhar, Gao and Lee as cases of it, and the reduced Havlak forest
  2. G. Ramalingam, Identifying loops in almost linear time, ACM Transactions on Programming Languages and Systems 21(2), 1999, pages 175-188, Steensgaard's top-down algorithm with generalized entry nodes and generalized back edges, the quadratic worst case of Havlak's algorithm, and almost-linear versions of the Havlak and Sreedhar, Gao and Lee algorithms
  3. Paul Havlak, Nesting of reducible and irreducible loops, ACM Transactions on Programming Languages and Systems 19(4), 1997, pages 557-567, a loop nesting forest for reducible and irreducible loops built from a depth-first search
  4. Vugranam C. Sreedhar, Guang R. Gao and Yong-Fong Lee, Identifying loops using DJ graphs, ACM Transactions on Programming Languages and Systems 18(6), 1996, pages 649-658, reducible and irreducible loops found with the dominator tree and the join edges of the flow graph
  5. Bjarne Steensgaard, Sequentializing program dependence graphs for irreducible programs, Technical Report MSR-TR-93-14, Microsoft Research, 1993, the loops of irreducible programs as nested strongly connected components with entry nodes

About this page

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/EMNP01/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EMNP01/text.yaml