Algorithmcore
T1-T2 reduction
Also called Hecht-Ullman transformations.
Tests reducibility by removing self-loops and merging nodes with a single predecessor; the graph is reducible if one node remains.
- Time
- O(n^2 + m) worstΘ(n + m) best
- Space
- Θ(n + m) extra
- Where
- m = the number of edges; n = the number of vertices
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The T1-T2 reduction tests whether a control flow graph is a reducible flow graph. It uses two rules, the Hecht-Ullman transformations. T1 deletes a self-loop. T2 takes a node other than the entry that has exactly one predecessor and merges it into that predecessor. Apply the rules until neither applies. The graph is reducible if and only if one node is left, and the order of the steps does not change the answer. With a worklist the test takes time. The list of steps also tells in which order the regions of the graph collapse, which is what elimination data-flow methods use.
In plain words
Think of the flow graph as a map of rooms joined by one-way doors. Two moves are allowed. If a door leads from a room back into the same room, remove it. If a room other than the entrance can be entered from only one other room, knock down the wall between them, so they become one room; its doors out now leave from the bigger room. Keep making moves until none is possible. If only the entrance room is left, every loop in the program had one way in, and the graph is reducible. If several rooms are left, each of them can be entered from two or more places, and some loop has more than one way in. It does not matter which move you make first. You always end with the same answer.
The problem
Input. A flow graph : a directed graph with vertices, edges and an entry vertex . Vertices that does not reach are ignored, and parallel edges count as one edge.
Output. The limit graph, which is the graph left when neither T1 nor T2 applies, and the list of steps. is reducible exactly when the limit graph has one vertex.
The rules. T1 deletes an edge . T2 applies to a vertex whose only predecessor is . It deletes and the edge , and it replaces each edge by . An edge becomes a self-loop on , which a later T1 removes. Reducibility itself is defined on the reducible flow graph page: the graph without its back edges, the edges where dominates , has no cycle.
The algorithm
A worklist holds the vertices that may need a step. A vertex whose sets change goes back on the list.
T1-T2-REDUCE(G, r)- 1
keep the vertices that r reaches; succ[v], pred[v] <- sets of successors and predecessors - 2
W <- all kept vertices - 3
while W is not empty do - 4
v <- pop(W); if v was merged before, skip it - 5
if v is in succ[v] then - 6
T1: remove v from succ[v] and from pred[v] - 7
if v != r and pred[v] = {u} for one vertex u then - 8
T2: remove v from succ[u] - 9
for each w in succ[v] do - 10
replace v by u in pred[w]; add w to succ[u] - 11
delete v; push u and every w in succ[v] on W - 12
return the remaining graph; G is reducible if it has one vertex
Line L6 runs before line L7, so a vertex with a self-loop gets the loop removed and can then be merged in the same visit. Line L11 pushes exactly the vertices whose sets changed: lost an edge and gained others, and each moved successor has a new predecessor set, which may now have one element. A T1 changes only the sets of , and line L7 tests again at once.
In the implementation, the sets are Python sets, the steps are returned as tuples ("T1", v) and ("T2", v, u), and cfg_is_reducible runs the test on the blocks of a toy IR program.
Example
Take the nested loops of the natural loop page:
B0:
i = 0
s = 0
jump B1
B1:
t = i < n
br t B2 B6
B2:
j = 0
jump B3
B3:
u = j < i
br u B4 B5
B4:
s = s + j
j = j + 1
jump B3
B5:
i = i + 1
jump B1
B6:
ret s
The edges are , , , , , , , . The worklist starts with B0 to B6 and pops the smallest first.
| step | rule | what happens | edges after the step |
|---|---|---|---|
| 1 | T2 | B2 has only B1 before it; merge B2 into B1 | replaces |
| 2 | T2 | B4 has only B3; merge B4 into B3 | becomes the self-loop |
| 3 | T1 | remove | now B3 has only B1 before it |
| 4 | T2 | merge B3 into B1 | , |
| 5 | T2 | B5 has only B1; merge B5 into B1 | becomes the self-loop |
| 6 | T1 | remove | now B1 has only B0 before it |
| 7 | T2 | merge B1 into B0 | |
| 8 | T2 | merge B6 into B0 | no edges |
One vertex is left, so the graph is reducible. The inner loop collapsed in steps 2 and 3, and the outer loop in steps 4 to 6. Each T1 marks the moment a whole loop has become one node.
Now take the smallest irreducible graph from the reducible flow graph page: , , , , , . There is no self-loop, is the entry, and , and have two predecessors each. No step applies, and the limit graph is the whole graph with 4 vertices. The cycle can be entered at both and .
Correctness
The proof file proves the whole claim. Its steps:
- T1 changes nothing that matters. A self-loop lies on no path and is always a back edge, so dominance and the graph without back edges stay the same.
- T2 keeps reducibility in both directions. When merges into , the dominance relation among the other vertices does not change, and is a back edge exactly when is one. The edge is never a back edge. So the graph without back edges after the step is the graph before it with the edge contracted, and one has a cycle if and only if the other does.
- A reducible graph always allows a step. If the graph is reducible, has at least two vertices and has no self-loop, some vertex other than has one predecessor. Take the first vertex after in a topological order of the graph without back edges. Either is its only predecessor, or the vertices that dominates form a smaller reducible flow graph with root , and induction finds the vertex inside it.
- The theorem. From 1 to 3: is reducible if and only if every maximal sequence of steps ends in one vertex, if and only if some sequence does. So the order does not matter.
- The worklist. Each vertex that may allow a step is on , so when is empty no step applies, and the algorithm has made a maximal sequence.
Hecht and Ullman proved more: the limit graph is the same, up to names, for every order of the steps. The proof file cites this and does not prove it; the test does not need it.
Proof: T1 and T2 reduce a flow graph to one vertex exactly when it is reducible, and the worklist finds a maximal sequencefull
Setting. A flow graph is , where is a set of ordered pairs (self-loops are allowed, parallel edges are not) and reaches every vertex. Line L1 of the algorithm keeps only the vertices that reaches, and an edge from a vertex that does not reach lies on no path from , so this changes neither the dominators nor the answer; from here on every vertex is reachable. dominates , written , if every path from to contains . An edge is a back edge if , is the set of back edges, and . is reducible if has no cycle; call this condition (C). This is the definition on the page of the reducible flow graph.
T1 deletes a self-loop . T2 applies to a vertex whose set of predecessors is for one vertex . It deletes and the edge and replaces each edge by ; an edge that is already there is not added again. Since is reachable and is its only predecessor, , so has no self-loop. An edge becomes the self-loop . Let and for . Then the new graph is with and , because the only edge into is .
Two facts are used many times. A walk from to that avoids a vertex contains a path from to that avoids . Dominance is antisymmetric: if and , then . Indeed, let and take a path from to . It contains , and is not its last vertex, so the part of up to is a path from to that does not contain , because appears on only at the end. So does not dominate .
Lemma 1 (T1 keeps everything). T1 does not change reachability, dominance or .
Proof. A self-loop is on no path, since a path does not repeat a vertex. So the paths from are the same, and reachability and dominance are the same. The self-loop is a back edge because , so it is not in , and the other back edges stay back edges.
Lemma 2 (paths through a T2 step). Let T2 merge into .
(a) Every vertex of is reachable from .
(b) For : in if and only if in .
(c) For : in if and only if in .
(d) is not a back edge of .
Proof. Every occurrence of on a walk from comes right after an occurrence of , because and is its only predecessor.
Down. Map a walk of from by and drop each step , which becomes . A step becomes , which is in . The result is a walk of from with the vertex set . If , then also , so is that vertex set in all cases.
Up. An edge is the image of some edge other than . Then , so , and , or and . Replace the step by in the first case and by in the second. A walk of from becomes a walk of from whose vertex set is the old vertex set, perhaps with added.
(a) follows from the down map, applied to a path from to .
(b) If a path of from to avoids , its lift is a walk of from to that avoids , since the only new vertex is . If a path of from to avoids , its image has the vertex set , which does not contain . So "some path avoids " is true in exactly when it is true in .
(c) Each path from to ends with the step , so its part up to is a path from to . If every path to contains , so does every path to . If a path to avoids , then adding the step gives a path to that avoids , because and the path to does not contain (it would contain before it).
(d) , since every path to passes through . If also , then by antisymmetry, which is false. So does not dominate , and is not a back edge.
Lemma 3 (T2 keeps (C)). If T2 turns into , then satisfies (C) if and only if does.
Proof. First, an edge of is a back edge of exactly when its image is a back edge of . If this is Lemma 2(b). The case does not occur. If and , then is a back edge iff in , iff in by Lemma 2(c), iff in by Lemma 2(b), iff is a back edge of . Two edges with the same image, and , are therefore both back edges or both not.
So the edges of are the images of the edges of other than , and is an edge of by Lemma 2(d). In other words, is with the edge contracted, where is the only edge of into .
A graph has a cycle exactly when it has a closed walk with at least one edge. Let be a cycle of . If avoids , it is a cycle of . Otherwise contains the steps , and replacing them by gives a closed walk of with at least one edge; if is , the result is the self-loop . Conversely, a closed walk of with at least one edge lifts as in the proof of Lemma 2, by putting before every step that comes from an edge , to a closed walk of with at least one edge.
Lemma 4 (progress). If satisfies (C), has at least 2 vertices and has no self-loop, then some vertex has exactly one predecessor.
Proof. By strong induction on . Every edge is a back edge, because dominates every vertex. The edges of a depth-first search tree from are not back edges: for a tree edge , the tree path from to does not contain , so does not dominate . So contains a spanning tree from , every vertex has a predecessor in , and has none. is acyclic by (C), so it has a topological order, and comes first because it is the only vertex without a predecessor in and all others are reachable from it in . Let be the second vertex in this order. Its predecessors in come before it, so they are . Every other predecessor of in is the tail of a back edge , so , and because there is no self-loop. The edge is not a back edge, since does not dominate .
Case 1. has no predecessor other than . Then works.
Case 2. Some predecessor has . Let . Then , , so .
(i) Every edge into starts in . Let with , . If , a path from to that avoids , followed by the step to , is a path to that avoids ; this contradicts .
(ii) reaches every vertex of inside . Take a path from to and its part after the last . A vertex of is in : if a path from to avoided , then followed by the rest of would be a walk to that avoids .
So is a flow graph with root , fewer vertices than , at least 2 vertices and no self-loop.
(iii) satisfies (C). Let with in . We show in . If this holds, because is the root of . Let . Take a path from to and cut it at its first ; call this part . does not contain : otherwise its part up to would avoid , and would fail. So if a path of from to avoided , then followed by it would be a walk of from to that avoids , which is false. Hence every back edge of inside is a back edge of , and the graph of is a subgraph of . A subgraph of an acyclic graph is acyclic.
By induction, some , , has exactly one predecessor in . By (i), all predecessors of in lie in , so has exactly one predecessor in , and because .
Theorem 1 (the T1-T2 characterization). A sequence of T1 and T2 steps is maximal if neither applies to its last graph. Every sequence is finite, because each step removes an edge or a vertex. For a flow graph , these are equivalent:
- is reducible.
- Every maximal sequence of T1 and T2 steps ends in a graph with one vertex.
- Some maximal sequence ends in a graph with one vertex.
Proof. (1) ⇒ (2): by Lemmas 1 and 3, every graph of the sequence satisfies (C) and is a flow graph. The last graph has no self-loop, since T1 does not apply, and no vertex with exactly one predecessor, since T2 does not apply. By Lemma 4 it has one vertex. (2) ⇒ (3): a maximal sequence exists, since any sequence can be extended until it stops. (3) ⇒ (1): the last graph has one vertex and no self-loop, so it has no edge and satisfies (C). Lemmas 1 and 3 hold in both directions, so going back along the sequence, every graph satisfies (C), and so does .
So the verdict does not depend on the order of the steps. Hecht and Ullman (1972) proved more: the last graph of a maximal sequence is the same, up to the names of the vertices, for every order. This file does not prove that stronger claim, and the algorithm does not need it.
Lemma 5 (the worklist finds a maximal sequence). Each T1 in line L6 and each T2 in lines L8 to L11 is a step on the current graph, and when line L3 finds empty, neither T1 nor T2 applies to any vertex.
Proof. Lines L5 and L7 test exactly the conditions of T1 and T2 on the current sets, and lines L8 to L11 update and as T2 says, with sets, so a repeated edge is stored once. Whether T1 or T2 applies to a vertex depends only on , and whether . Invariant: each vertex to which T1 or T2 applies is in when line L3 tests it. At the start every vertex is in . When is popped, line L6 removes a self-loop if there is one, and then line L7 tests T2 on the new sets of . If T2 is not done, then neither step applies to any more, and no other set has changed. If T2 is done, is gone. The sets that change are , the sets for , and when ; line L11 pushes and every such . A T1 changes only the sets of . So the invariant holds after each iteration, and when is empty no step applies.
Termination and cost. Let and be the numbers of vertices and edges. There are at most T2 steps, because each removes a vertex and the root is never removed, and at most T1 steps, because a self-loop is either an edge of the input or made by a T2 step from an edge , at most one per T2. Line L2 pushes vertices and each T2 pushes vertices, so there are at most pushes, and the loop runs times. Line L1 takes steps. Each T2 step does set operations. With a hash table per set, each set operation takes expected constant time, and the total is expected; with an bit table for edge membership and lists for iteration the same bound holds in the worst case. The space is for the sets.
What is proved and what is measured. Theorem 1, Lemma 5 and the bound are proved here. The uniqueness of the limit graph is cited from Hecht and Ullman. The tests check, on seeded random graphs, that the result agrees with the definition of reducibility computed by brute force, and that a naive applier that picks T1 and T2 steps in random orders always reaches the same verdict; these are measurements and do not replace the proof.
Complexity
Proved. Line L1 takes time. Each T2 removes a vertex, so there are at most of them, and each pushes at most vertices, so the loop runs times. Each T2 does set operations, one per moved successor. The total is , in expectation with hash sets and in the worst case with an bit table for edge membership. The extra space is for the sets. On a star, where points to every other vertex, each vertex is merged with no successors to move, and the time is .
Measured, not proved. In the tests, 1,500 seeded random digraphs with 1 to 8 vertices give the same verdict as the definition computed by brute force, and on 400 graphs a naive applier that picks steps in random orders always reaches the verdict of the worklist. A chain of 20,000 vertices with edges in both directions takes a few hundredths of a second in Python on a laptop.
Properties
- Deterministic. The step list depends on the order of the worklist; the verdict does not.
- Non-recursive. The search of line L1 and the main loop use explicit lists.
- Order-independent. Any order of T1 and T2 steps gives the same answer, by the theorem of the proof file.
- A parse of the graph. On a reducible graph the steps form a hierarchy of regions: each T2 attaches a region to its single entry, and each T1 closes a loop.
- Offline. The whole graph is needed; after an edge change the test runs again.
Variants and improvements
- Tarjan's test. Tarjan (1974) tests reducibility in almost linear time with one depth-first search and disjoint set forests, which keep track of the vertices that have been collapsed together.
- Test with one search. Run one depth-first search, compute dominators, for example with the Cooper-Harvey-Kennedy algorithm, and check that each retreating edge goes to a dominator of its source. This is form 5 on the reducible flow graph page.
- Intervals. Allen and Cocke's interval analysis collapses a whole single-entry region at a time, instead of one node. A graph is reducible exactly when the sequence of interval graphs ends in one node.
- Elimination data-flow analysis. The step list orders the work of elimination methods: at a T2 step the transfer function of is composed into , and at a T1 step the effect of the loop is closed. Then the results are spread back in reverse order.
- Node splitting. When the reduction gets stuck, copy a vertex with predecessors into vertices, one per predecessor. Each copy then allows a T2 step. Repeating this makes any flow graph reducible, but the graph can grow very large.
When to use it
Use it when you need a simple and clearly correct reducibility test for the control flow graphs of single procedures, which are small, or when you also need the order in which the regions collapse. For large graphs, use Tarjan's test or a single search with dominators. If you need the loops themselves, compute natural loops or a loop nesting forest instead.
Pitfalls
- Unreachable vertices. An edge from a vertex that does not reach still counts as a predecessor, so T2 cannot fire and a reducible graph looks irreducible. Delete unreachable vertices first, as line L1 does.
- Parallel edges. A branch
br c L Lgives two edges toL. Counted twice, they block T2 onL. Keep the edges as sets. - The self-loop as a predecessor. A vertex with a self-loop has itself as a predecessor. Do T1 before testing T2, or the test fails on every loop header.
- Merging the entry. T2 must never merge , even if has exactly one predecessor, for example the latch of a loop that starts at the entry. Merging it would remove the entry of the graph.
- A worklist that forgets vertices. After a T2, both and the moved successors must go back on the list. If they do not, the loop can stop while a step still applies, and the answer is wrong.
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/t1-t2-reduction/. The authors are listed in prov/VPKTQX.jsonl.
"""The T1-T2 reduction of Hecht and Ullman.
t1_t2_reduce(n, edges, root) applies T1 (delete a self-loop) and T2 (merge a
vertex other than the root that has exactly one predecessor into that
predecessor) until neither applies. It returns (left, left_edges, steps):
the vertices and edges of the limit graph and the list of steps taken, each
("T1", v) or ("T2", v, u) for "v merged into u". Only the vertices that the
root reaches take part. The graph is reducible exactly when one vertex is
left; is_reducible says so, and cfg_is_reducible does it for a toy IR
program.
"""
import toyir
def t1_t2_reduce(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")
out = [[] 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")
out[a].append(b)
# Keep the vertices that root reaches, with successor and predecessor sets.
seen = [False] * n # @line L1
seen[root] = True
stack = [root]
while stack:
v = stack.pop()
for w in out[v]:
if not seen[w]:
seen[w] = True
stack.append(w)
succ = {v: set() for v in range(n) if seen[v]}
pred = {v: set() for v in succ}
for a, b in edges:
if seen[a]:
succ[a].add(b)
pred[b].add(a)
steps = []
work = sorted(succ, reverse=True) # @line L2
while work: # @line L3
v = work.pop() # @line L4
if v not in succ:
continue
if v in succ[v]: # @line L5
succ[v].discard(v) # @line L6
pred[v].discard(v)
steps.append(("T1", v))
if v != root and len(pred[v]) == 1: # @line L7
(u,) = pred[v]
moved = succ[v]
succ[u].discard(v) # @line L8
for w in moved: # @line L9
pred[w].discard(v) # @line L10
pred[w].add(u)
succ[u].add(w)
del succ[v], pred[v] # @line L11
steps.append(("T2", v, u))
work.append(u)
work.extend(moved)
left = sorted(succ) # @line L12
left_edges = sorted((a, b) for a in succ for b in succ[a])
return left, left_edges, steps
def is_reducible(n, edges, root):
"""True if T1 and T2 reduce the part that root reaches to one vertex."""
return len(t1_t2_reduce(n, edges, root)[0]) == 1
def cfg_is_reducible(prog):
"""Reducibility of the control flow graph of a toy IR program."""
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)]
return is_reducible(len(labels), edges, 0)
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_t1_t2_reduction.py 282 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/t1-t2-reduction/. The authors are listed in prov/VPKTQX.jsonl.
import random
import pytest
import toyir
from t1_t2_reduction import cfg_is_reducible, is_reducible, t1_t2_reduce
NESTED = """
B0:
i = 0
s = 0
jump B1
B1:
t = i < n
br t B2 B6
B2:
j = 0
jump B3
B3:
u = j < i
br u B4 B5
B4:
s = s + j
j = j + 1
jump B3
B5:
i = i + 1
jump B1
B6:
ret s
"""
STUCK = """
r:
br p A B
A:
x = x + 1
br q B C
B:
x = x * 2
br q A C
C:
ret x
"""
ODD_SUM = """
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
def graph(prog):
labels = list(prog.blocks)
index = {lab: i for i, lab in enumerate(labels)}
return labels, [(index[a], index[b]) for a, b in toyir.edges(prog)]
def reach(n, succ, root, banned):
"""The vertices that root reaches without passing through banned."""
if banned == root:
return set()
seen = {root}
stack = [root]
while stack:
v = stack.pop()
for w in succ[v]:
if w != banned and w not in seen:
seen.add(w)
stack.append(w)
return seen
def brute_reducible(n, edges, root):
"""Reducibility by the definition: compute the dominators by deleting
each vertex in turn, drop the back edges (t, h) with h dominating t, and
check that what is left has no cycle."""
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
full = reach(n, succ, root, -1)
dom = {v: {v} for v in full}
for d in full:
r = reach(n, succ, root, d)
for v in full:
if v not in r:
dom[v].add(d)
fwd = {v: set() for v in full}
for a, b in edges:
if a in full and b not in dom[a]:
fwd[a].add(b)
indeg = {v: 0 for v in full}
for a in fwd:
for b in fwd[a]:
indeg[b] += 1
queue = [v for v in full if indeg[v] == 0]
count = 0
while queue:
v = queue.pop()
count += 1
for w in fwd[v]:
indeg[w] -= 1
if indeg[w] == 0:
queue.append(w)
return count == len(full)
def naive_reduce(n, edges, root, rng):
"""Apply T1 and T2 in a random order until neither applies. Returns the
number of vertices left."""
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
full = reach(n, succ, root, -1)
s = {v: set() for v in full}
for a, b in edges:
if a in full:
s[a].add(b)
while True:
moves = []
for v in s:
if v in s[v]:
moves.append(("T1", v))
preds = [u for u in s if v in s[u]]
if v != root and len(preds) == 1 and preds[0] != v:
moves.append(("T2", v, preds[0]))
if not moves:
return len(s)
move = rng.choice(moves)
if move[0] == "T1":
s[move[1]].discard(move[1])
else:
v, u = move[1], move[2]
s[u].discard(v)
s[u] |= s[v]
del s[v]
def random_graph(rng):
n = rng.randint(1, 8)
m = rng.randint(n, 3 * n)
return n, [(rng.randrange(n), rng.randrange(n)) for _ in range(m)]
def test_nested_loops_reduce_to_one_node():
labels, edges = graph(toyir.parse(NESTED))
left, left_edges, steps = t1_t2_reduce(len(labels), edges, 0)
assert left == [0] and left_edges == []
named = [(s[0],) + tuple(labels[x] for x in s[1:]) for s in steps]
assert named == [
("T2", "B2", "B1"),
("T2", "B4", "B3"),
("T1", "B3"),
("T2", "B3", "B1"),
("T2", "B5", "B1"),
("T1", "B1"),
("T2", "B1", "B0"),
("T2", "B6", "B0"),
]
def test_smallest_irreducible_graph_is_stuck():
prog = toyir.parse(STUCK)
labels, edges = graph(prog)
left, left_edges, steps = t1_t2_reduce(len(labels), edges, 0)
assert steps == []
assert left == [0, 1, 2, 3]
assert left_edges == [(0, 1), (0, 2), (1, 2), (1, 3), (2, 1), (2, 3)]
assert not cfg_is_reducible(prog)
assert not brute_reducible(len(labels), edges, 0)
def test_odd_sum_program():
prog = toyir.parse(ODD_SUM)
assert cfg_is_reducible(prog)
assert toyir.run(prog, [6]) == ("ret", 9)
def test_small_cases():
assert t1_t2_reduce(1, [], 0) == ([0], [], [])
assert t1_t2_reduce(1, [(0, 0)], 0) == ([0], [], [("T1", 0)])
# Parallel edges count as one edge.
assert t1_t2_reduce(2, [(0, 1), (0, 1)], 0) == ([0], [], [("T2", 1, 0)])
# A cycle through the root is reducible.
assert is_reducible(3, [(0, 1), (1, 2), (2, 0)], 0)
# The root keeps its in-edges until a T1 removes them.
assert t1_t2_reduce(2, [(0, 1), (1, 0)], 0) == ([0], [], [("T2", 1, 0), ("T1", 0)])
def test_unreachable_part_is_ignored():
# 3, 4 and 5 form an irreducible pattern that the root 0 does not reach.
edges = [(0, 1), (1, 2), (3, 4), (3, 5), (4, 5), (5, 4), (4, 1)]
left, left_edges, _ = t1_t2_reduce(6, edges, 0)
assert left == [0] and left_edges == []
# With root 3 the same graph is irreducible.
assert not is_reducible(6, edges, 3)
def test_bad_input():
with pytest.raises(ValueError):
t1_t2_reduce(0, [], 0)
with pytest.raises(ValueError):
t1_t2_reduce(2, [], 2)
with pytest.raises(ValueError):
t1_t2_reduce(2, [(0, 2)], 0)
def test_random_graphs_match_the_definition():
rng = random.Random(53)
seen = [0, 0]
for _ in range(1500):
n, edges = random_graph(rng)
root = rng.randrange(n)
want = brute_reducible(n, edges, root)
assert is_reducible(n, edges, root) == want
seen[want] += 1
assert min(seen) > 100
def test_every_order_gives_the_same_answer():
rng = random.Random(59)
for _ in range(400):
n, edges = random_graph(rng)
want = is_reducible(n, edges, 0)
for _ in range(4):
assert (naive_reduce(n, edges, 0, rng) == 1) == want
def test_limit_graph_is_stuck_and_counts_match():
rng = random.Random(61)
for _ in range(800):
n, edges = random_graph(rng)
left, left_edges, steps = t1_t2_reduce(n, edges, 0)
succ = [[] for _ in range(n)]
for a, b in edges:
succ[a].append(b)
size = len(reach(n, succ, 0, -1))
assert sum(1 for s in steps if s[0] == "T2") == size - len(left)
assert 0 in left
assert all(a != b for a, b in left_edges)
for v in left:
if v != 0:
assert sum(1 for a, b in left_edges if b == v) >= 2
def test_random_toy_programs():
rng = random.Random(67)
seen = [0, 0]
for _ in range(300):
prog = toyir.random_program(rng, 3, rng.randint(2, 9), rng.random() < 0.3)
labels, edges = graph(prog)
want = brute_reducible(len(labels), edges, 0)
assert cfg_is_reducible(prog) == want
seen[want] += 1
assert seen[1] > 100
def test_long_graphs():
n = 20000
chain = [(i, i + 1) for i in range(n - 1)]
assert is_reducible(n, chain + [(i + 1, i) for i in range(n - 1)], 0)
assert is_reducible(n, chain + [(n - 1, 0)], 0)
# Two entries into one long cycle: irreducible.
assert not is_reducible(n, chain + [(n - 1, 1), (0, n // 2)], 0)
History
Hecht and Ullman introduced the transformations T1 and T2 in 1972 and defined a flow graph to be reducible when they reduce it to one node; they also proved that the limit graph does not depend on the order of the steps. Their 1974 paper in the Journal of the ACM gave further equivalent forms, among them the forbidden subgraph. In the same year Tarjan gave an almost-linear test. The rules became the standard way to explain reducibility in textbooks, and the order of collapse that they define is the basis of T1-T2 elimination methods for data-flow analysis.
References
- Matthew S. Hecht and Jeffrey D. Ullman, Flow graph reducibility, SIAM Journal on Computing 1(2) (1972), 188-202, the transformations T1 and T2, the definition of reducibility as reduction to one node, and the uniqueness of the limit graph
- Matthew S. Hecht and Jeffrey D. Ullman, Characterizations of reducible flow graphs, Journal of the ACM 21(3), 1974, the equivalent forms of reducibility, among them the forbidden (*) subgraph and the uniqueness of the acyclic graph of forward edges
- Robert Endre Tarjan, Testing flow graph reducibility, Journal of Computer and System Sciences 9(3), 1974, pages 355-365, the almost-linear test for reducibility with depth-first search and disjoint set union
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.6.4 (back edges and reducibility) and Section 9.7 (region-based analysis)
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 7 (Control-Flow Analysis), reducibility and the analyses that collapse regions of a flow graph
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 VPKTQX Edit this page History Report an error Markdown