Data structureadvanced
Sea of nodes
Also called Click graph IR.
A graph IR in SSA where data and control are both edges and most instructions float free of blocks until scheduling.
- Time
- O(n + b v) expected buildO(g b) schedule
- Space
- O(g) total
- Where
- b = the number of blocks; g = the number of nodes and edges of the graph; n = the number of instructions; v = the number of variables
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cliff Click, Michael Paleczny, 1995
The sea of nodes is a graph IR in static single assignment form in which control and data are both edges, and there are no basic blocks. Each value is one node, and its inputs are the nodes it reads. Branches, merges and returns are nodes too, joined by control edges. An arithmetic node that cannot trap has no control input at all: it floats, and the compiler decides only at the end which block computes it. Cliff Click and Michael Paleczny (1995) described it, sometimes called the Click graph IR, and it was the IR of the HotSpot server compiler and of the TurboFan compiler of V8. Because the graph keeps only real dependences, global value numbering is hash-consing of nodes, and loop-invariant code motion falls out of the final scheduling.
In plain words
A normal compiler keeps the program as a list of steps inside boxes, and each step has its place in a box. In the sea of nodes, the boxes are gone for most steps. A step only remembers which other steps it needs. Steps that decide which way the program goes, and steps that can fail, such as a division, keep a link to the decision above them. All other steps float. Two steps that compute the same thing from the same inputs become one step. At the end, the compiler puts every floating step back into a box: not earlier than its inputs allow, not later than its users need, and outside loops when it can.
The abstract type
The graph has nodes with an ordered list of inputs. The edges point from a node to its inputs, the reverse of data flow, as in Click and Paleczny. There are two classes of nodes.
Control nodes. START begins the procedure. A REGION node stands for a merge point, with one input for each incoming control edge. IF takes a control input and a condition, and its two projections IFTRUE and IFFALSE are the control on each outgoing edge. RETURN takes a control input and a value. The control nodes form the control flow graph, with REGION nodes as blocks.
Data nodes. PARAM and CONST are leaves. OP applies an operator to two inputs. PHI has a REGION as input 0 and one value for each input of that REGION, in the same order, as a phi-function. An OP that can trap, such as a division, has its REGION as an extra control input, so it is pinned to that block. Other OPs have no control input and float.
The operations are:
- BUILD(procedure): make the graph from a CFG or straight from the parser.
- New nodes with value numbering: making an OP that already exists returns the old node.
- Local rewrites on the graph, such as constant folding, by replacing a node with another in all its uses.
- SCHEDULE(): place every live floating node in a block and give back a CFG in SSA form.
Real compilers add a memory or effect input to loads, stores and calls, so that the order of memory operations is an edge as well. The toy version here has no memory.
Representation
A node is an object with a kind, a value (the operator, the constant or the parameter name) and an array of input nodes. Use lists, from a node to the nodes that read it, are kept as well, or rebuilt before scheduling. A hash table maps the key (kind, value, input ids) to the node with that key, for CONST and floating OP. The pinned nodes are never put in this table, since two divisions in different blocks are different events. A list of roots holds the nodes that must stay even with no use: RETURN, IF and the pinned OPs. A node is live if a root reaches it through input edges.
Operations
BUILD(P) ▷ P: blocks of const, copy, op; the entry has no predecessor- 1
START ← new node; for each block B: region[B] ← new REGION - 2
for each block B in reverse postorder do - 3
if B is the entry: map ← {each parameter p: PARAM(p), other names: UNDEF} - 4
else if B has one predecessor P: map ← a copy of out[P] - 5
else map ← {each name v: a new PHI(region[B])} - 6
for each instruction x = a op b of B do ▷ x = a and x = k only change map[x] - 7
if op can trap: n ← new OP(op, region[B], map[a], map[b]); add n to the roots - 8
else n ← HASHCONS(OP(op, map[a], map[b])) - 9
map[x] ← n - 10
end B with RETURN(region[B], map[a]), with IF(region[B], map[a]) and its two projections, or with nothing for a jump - 11
out[B] ← map - 12
for each block B except the entry do - 13
region[B].inputs ← the control of the edges P1 → B, ..., Pk → B - 14
for each PHI of v at B: its inputs ← region[B], out[P1][v], ..., out[Pk][v] - 15
replace each PHI whose inputs other than itself are one node w by w, until none is left SCHEDULE()- 16
dominator tree and loop depth of the blocks (the REGION nodes) - 17
for each live pinned node n: block[n] ← the block of its control input - 18
for each live floating node n, inputs first: early[n] ← the deepest block among the blocks of its inputs, or the entry - 19
for each live floating node n, uses first: - 20
lca ← none - 21
for each use u of n: lca ← LCA(lca, the block of u), where a PHI u that reads n through its input i counts in the i-th predecessor of its block - 22
best ← lca; walk x from lca up the dominator tree to early[n]: if depth(x) < depth(best) then best ← x - 23
block[n] ← best - 24
for each block: emit its PHIs, then its OPs with inputs first, then its terminator
BUILD (L1 to L15). This is the construction of Click and Paleczny with one simplification: every block with two or more predecessors gets a PHI for every name (line L5), and line L15 removes the PHIs that turn out to be copies, as in Braun et al.. A block with one predecessor needs no PHI, because its predecessor dominates it. The reverse postorder of line L2 visits that predecessor first, since a block whose only predecessor comes later would be unreachable. Line L8 is hash-consing: the second a + b returns the node of the first. This is global value numbering, done once at creation, with no data flow analysis. Copies and constants make no node of their own, so copy propagation is free.
SCHEDULE (L16 to L24). This is global code motion as Click (1995) gave it. Line L18 computes the earliest legal block: a node must come after its inputs, and the blocks of the inputs all lie on one path of the dominator tree, so the deepest of them is the earliest. Line L21 computes the latest legal block: it must dominate every use, so it is the lowest common ancestor of the use blocks. A PHI reads its -th input at the end of its -th predecessor, so that is where the use counts. Line L22 picks, on the dominator tree path from the latest block up to the earliest one, a block of least loop depth. Ties go to the lower block, which runs on fewer paths. Line L24 writes a CFG in SSA form, with the pinned nodes in their own blocks.
Example
Take this loop, where k = n * 4 does not change inside the loop:
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B4
B3:
k = n * 4
s = s + k
i = i + 1
jump B2
B4:
ret s
BUILD makes four REGIONs. B2 has two predecessors, so it gets a PHI for each of i, k, n, s and t1. The PHI of n has the inputs PARAM(n) and itself, so line L15 removes it and its uses read PARAM(n) directly. The PHIs of k and t1 stay in the graph, but no root reaches them, so they are dead. The live data nodes are:
| node | inputs | pinned? | early | latest (LCA of uses) | placed in |
|---|---|---|---|---|---|
| REGION(B2), 0, | yes | B2 | B2 | ||
| REGION(B2), 0, | yes | B2 | B2 | ||
| = < n | , PARAM(n) | no | B2 | B2 (the IF) | B2 |
| = n * 4 | PARAM(n), 4 | no | B1 | B3 | B1 |
| = + | , | no | B2 | B3 (PHI input from B3) | B3 |
| = + 1 | , 1 | no | B2 | B3 (PHI input from B3) | B3 |
The loop body is , with loop depth 1. For , the walk from B3 up to B1 passes B3 (depth 1), B2 (depth 1) and B1 (depth 0), so goes to B1: the multiply has left the loop, with no separate loop-invariant code motion pass. For and the walk stops at B2, of the same depth as B3, so they stay in B3. The output, with the node numbers as names, is:
B1:
v19 = n * 4
jump B2
B2:
v8 = phi [B1: 0, B3: v22]
v11 = phi [B1: 0, B3: v20]
v13 = v8 < n
br v13 B3 B4
B3:
v20 = v11 + v19
v22 = v8 + 1
jump B2
B4:
ret v11
The multiply now runs once even when the loop runs zero times. That is safe because it cannot trap. A division would be pinned to B3 and stay there.
Value numbering across branches. In B1: br c B2 B3, B2: x = a + b, B3: y = a + b; x = y * 2, B4: ret x, both additions become one node. Its uses are in B3 and in the PHI of B4 through the edge from B2, so the latest block is the common dominator B1, and the addition is computed once in B1. A CFG compiler would need partial redundancy elimination or code hoisting for the same result.
Correctness
There are two claims. First, BUILD keeps the meaning: for every run of the source program, and at every point of it, the value of each variable equals the value of the node that the map of line L3 to L9 assigns to it, where a PHI takes the value of its input for the last edge into its block. This holds by induction over the run, and the key point is that hash-consing only merges nodes with the same operator and the same inputs, which have the same value at every moment. Second, SCHEDULE keeps the meaning: every node is placed in a block that is dominated by the blocks of its inputs and that dominates its uses, so the output is in strict SSA form, and in strict SSA each read sees the latest computation of the node, which was made from the latest values of its inputs. Control and the pinned nodes keep their blocks, so the output takes the same branches and traps in the same blocks as the source. The full argument is in proofs/correctness.md.
Proof: BUILD followed by SCHEDULE keeps the outcome of every runfull
We use the notation of the page. is a toy IR procedure with const, copy and op instructions, every block is reachable, the entry has no predecessor, and no run of reads a name before it is defined. is the graph after line L14, the graph after line L15, and the program that SCHEDULE gives. We show that for all arguments, and return the same value, or both trap.
1. Values along a run
Fix the arguments and the run of . A time is a position in the run between two steps. Control enters blocks one after the other. For a block with predecessors and a time after the first entry into , let be the index of the edge of the last entry into at or before , and the time just before that entry, at the end of the predecessor. Define the value of a node of (or of ) by
- is the argument , , ;
- , which is undefined if traps on these values (a control input is ignored);
- at is , with and as above.
The recursion is well founded, because a PHI refers to an earlier time and the OP inputs of a node were made before it. Between two block entries no changes, and entering changes only the values of PHIs of and of nodes that depend on them.
Lemma 1 (BUILD is faithful on ). At every time in the run of , inside block before instruction , every name that is defined at that point has the value , where is the map of lines L3 to L9 at that point. A terminator br a or ret a reads , and an instruction with a trapping operator traps exactly when the value of its OP node is undefined.
Proof. By induction over the run. At the start, the parameters map to PARAM nodes. An instruction x = k or x = a changes the value of and in the same way. For x = a op b, the new value is , which is of the OP node of lines L7 and L8. When line L8 returns an older node from the hash table, that node has the same operator and the same inputs, so it has the same value. At an edge into a block with one predecessor, the map is copied and no value changes. At the -th edge into a block with two or more predecessors, every name maps to the PHI of at , whose new value is , the value of at the end of by induction.
2. Homes and freshness
Define the home of a node: the entry for PARAM, CONST and UNDEF, the block of a PHI or of a pinned OP, and for a floating OP the deepest home of its inputs in the dominator tree. This is the block early of line L18.
Lemma 2. In , the homes of the inputs of a floating OP lie on one path of the dominator tree, and the home of every node that appears in at a point of block , or in , dominates .
Proof. By induction over BUILD. The entry map holds nodes with home the entry. A block with one predecessor copies , and dominates it. A block with two or more predecessors maps every name to its own PHIs. A new OP in has inputs whose homes dominate . The dominators of form a path of the tree, so the deepest home is well defined and dominates . A node returned by the hash table has the same inputs and so the same home.
The cone of a node is the node with all nodes that it reaches through data inputs, without going through a PHI's inputs. A value depends only on the PHIs in the cone of , and on their last entries. Every PHI in the cone of has a home that dominates the home of , by the definition of home.
Lemma 3 (freshness). Let be a block that the home of every PHI in the cone of dominates. Let be a time in a visit of after its PHIs have been assigned, and a time in a block that dominates, such that the run does not enter between and . Then .
Proof. Suppose not. Then some PHI in the cone is at a block that is entered at a time with . , since is not entered again. dominates , so a path from the entry to the first visit of does not pass . Join it with the part of the run from to , which does not pass . This is a path from the entry to that avoids , which contradicts that dominates .
3. Removing trivial PHIs
Lemma 4. Let be a PHI at block whose inputs are all or , with . Then the home of strictly dominates , and at every time in a block that dominates.
Proof. By Lemma 2, an edge with input has in , so dominates . The first entry into on any path comes from a predecessor that does not dominate, so through an edge with input , whose predecessor the home of dominates. So every path to passes the home of . That home is not : otherwise would dominate the predecessor of that edge. So the home of strictly dominates .
Now fix . Following the last entries into backward, each through an edge with input , we reach a last entry through an edge with input at time , and . All entries into in come from predecessors that dominates. Suppose the run enters the home of at a time . The part of the run from to the next entry into ends with an entry from a predecessor that dominates, and before that entry it does not pass . Joined with a path from the entry to the first visit of , which avoids , it gives a path to that predecessor that avoids , a contradiction. If there is no entry into after , the same argument applies with in place of that entry, since dominates the block of . So is not entered in , and Lemma 3, with the home of , gives .
By Lemma 2, every place where is read, through a map or through the inputs of a node, is at a time in a block that dominates. So replacing by changes no value that is ever read, and Lemma 1 holds for as well. Repeating the step for each removed PHI gives the same for line L15.
4. SCHEDULE
Let be the placement of lines L17 to L23. For a pinned node it is its own block. For a floating node, line L22 picks a block on the dominator tree path from the LCA of its use blocks up to early. This path exists: by induction in the order of line L19, each use block is dominated by the block of the user, which the home of the user dominates, and the home of dominates the home of each user. So:
- (S1) the block of each input of dominates , and within one block line L24 puts the inputs first;
- (S2) dominates the block of every non-PHI use, and the predecessor through which every PHI use reads .
Lemma 5. The runs of and on the same arguments visit the same blocks through the same edges, up to the first trap or return. At every time at which reads the name of a node , the name holds .
Proof. By induction over the run. Suppose reads the name of at time in block , where is the use block of (S2). dominates , so it was visited, and its last visit at or before ran the instruction of at a time , before the read if both are in the same block visit (S1). By induction, the inputs read at held of the input nodes, so the name of got . The homes of the PHIs in the cone of dominate the home of , which dominates , and the run does not enter in . Lemma 3 with gives . A PHI instruction of at , entered through the edge , reads its -th input at the end of and so gets , which is the new of the PHI. A br reads of its condition node, the same value that reads by Lemma 1, so both runs take the same edge.
Theorem. and have the same outcome on all arguments.
Proof. By Lemma 5 both runs pass the same blocks. If returns in block , it returns of the RETURN input, and so does . If traps in a visit of , it traps at an instruction whose OP has an undefined value. That OP is pinned to , and runs every pinned OP of in that visit before the terminator, while floating OPs never trap. Values do not change inside a block visit, so traps in the same visit, at that instruction or at another one that also traps. If does not trap in a visit, no pinned OP of that block has an undefined value, so does not trap there either.
Complexity
The model is the word RAM, and the unit step is one node operation or one expected-constant-time hash table operation. Let be the number of instructions, the number of blocks, the number of variables and the number of nodes plus edges.
- BUILD. The maximal PHIs make nodes, and each instruction makes at most one node, so lines L1 to L14 take expected time. Building from the parser with PHIs only where needed, as production compilers do, makes far fewer PHIs. Line L15, done with use lists and a worklist of PHIs whose inputs changed, costs per round of removals.
- SCHEDULE. Dominators of the blocks cost with the Lengauer-Tarjan algorithm, for the control edges between them, and because a block ends with at most a two-way IF. Each LCA step and each step of the walk of line L22 moves up the dominator tree, so it is per edge in the worst case, and in total. With a constant-time LCA structure the LCA part drops to , and the walk of line L22 is short in practice.
- Space. , with .
Variants
- Effects as edges. Click and Paleczny thread memory and I/O as values: a store takes a memory state and gives a new one, and a load reads a memory state. This makes alias information part of the graph.
- Peephole at creation. The production graphs run constant folding, algebraic simplification and value numbering on each new node, so the parser already gives an optimized graph.
- Pinned versus floating loads. A load that can fault is pinned, or has a control input from the check that makes it safe. Moving a check makes the loads it guards move with it.
- Graphs with blocks. A CFG of SSA instructions, as in most compilers, is the other choice. V8 moved its JavaScript backend from the sea of nodes to Turboshaft, a CFG IR, and its blog post explains why.
- E-graphs. An e-graph also hash-conses nodes, but keeps many equal versions of a value at once to choose the best one later.
When to use it
The sea of nodes fits an optimizing compiler, often a just-in-time compiler, that runs many local rewrites and value numbering together and wants code motion as a by-product of scheduling. It is a poor fit when most operations have effects, because then most nodes sit on the effect chain and little floats. This is one of the reasons V8 gave for leaving it. It is also hard to read and debug, since the graph has no order to print, and some passes, such as those that need a fixed order of side effects, must rebuild a schedule first.
Pitfalls
- Floating a node that can trap. A division moved above its guarding test can fault on a path where the source never divided. Pin every operation that can trap or fault, or give it a control input from its guard.
- The PHI use in the wrong block. A PHI reads its input on the incoming edge, not in its own block. Counting the use in the PHI's block can place the value in a block that the incoming edge does not pass, so the PHI reads a value that was never computed on that path.
- Ties in loop depth. Choosing the higher block on a tie hoists code out of branches for no gain and makes it run on paths that did not need it. Prefer the lower block when the loop depth is equal.
- Dead PHIs and dead nodes. Maximal PHIs leave dead nodes. Schedule only nodes that a root reaches, or the output holds code for values that nobody reads.
- Value numbering pinned nodes. Two divisions with the same inputs in different blocks are not the same node, because each one traps on its own path.
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/sea-of-nodes/. The authors are listed in prov/Q4NRFR.jsonl.
"""A small sea-of-nodes graph for the toy IR, after Click and Paleczny (1995).
build(prog) turns a toy IR procedure with const, copy and op instructions
into a graph. Control is a chain of nodes: Start, one Region per block, If
with IfTrue and IfFalse projections, and Return. Data nodes are Param,
Const, Undef, Phi and Op. A Phi has its Region as input 0 and one value per
input of the Region. An Op that cannot trap floats: it has no control input,
and equal floating Ops are made once (hash-consing, which is global value
numbering at creation). An Op that can trap (/, %, <<, >>) is pinned to the
Region of its block and kept alive, because the trap is an effect.
schedule(graph) places every live floating node in a block by global code
motion (Click 1995): as early as its inputs allow, as late as its uses
allow, and then in the block of least loop depth between the two. It gives
back a toy IR program in SSA form with phi instructions.
"""
import toyir
TRAPPING = ("/", "%", "<<", ">>")
class Node:
__slots__ = ("id", "kind", "inputs", "val")
def __init__(self, nid, kind, inputs, val=None):
self.id = nid
self.kind = kind
self.inputs = inputs
self.val = val
def __repr__(self):
return "%s%d" % (self.kind, self.id)
class Graph:
"""The nodes, the region of each block and the roots."""
def __init__(self):
self.nodes = []
self.table = {} # hash-cons table for Const and floating Op
self.region = {} # block label -> Region node
self.term = {} # block label -> ("jump", L) / ("br", If, L1, L2) / ("ret", Return)
self.label_of = {} # Region id -> block label
self.params = []
self.entry = None
self.roots = []
def new(self, kind, inputs, val=None):
n = Node(len(self.nodes), kind, inputs, val)
self.nodes.append(n)
return n
def hashcons(self, kind, inputs, val):
key = (kind, val, tuple(i.id for i in inputs))
n = self.table.get(key)
if n is None:
n = self.new(kind, inputs, val)
self.table[key] = n
return n
def pinned(self, n):
return n.kind not in ("Const", "Undef", "Op") or (n.kind == "Op" and n.val in TRAPPING)
def _rpo(prog):
order, seen = [], {prog.entry}
stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
order.append(v)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(toyir.succs(prog, w))))
return order[::-1]
def build(prog):
"""The sea-of-nodes graph of prog. The entry block must have no
predecessor, every block must be reachable, and the instructions must be
const, copy and op."""
preds = toyir.preds(prog)
if preds[prog.entry]:
raise ValueError("the entry block must have no predecessor")
names = set(prog.params)
for b in prog.blocks.values():
for ins in b.instrs:
if ins[0] not in ("const", "copy", "op"):
raise ValueError("unsupported instruction: %r" % (ins,))
names.add(ins[1])
names = sorted(names)
g = Graph()
g.params, g.entry = list(prog.params), prog.entry
start = g.new("Start", [])
for label in prog.blocks: # @line L1
g.region[label] = g.new("Region", [])
g.label_of[g.region[label].id] = label
order = _rpo(prog)
if len(order) != len(prog.blocks):
raise ValueError("every block must be reachable from the entry")
out, phis, proj = {}, {}, {}
for label in order: # @line L2
reg = g.region[label]
if label == prog.entry: # @line L3
reg.inputs = [start]
env = {v: g.hashcons("Undef", [], None) for v in names}
for i, p in enumerate(prog.params):
env[p] = g.new("Param", [start], p)
elif len(preds[label]) == 1: # @line L4
env = dict(out[preds[label][0]])
else:
env = {v: g.new("Phi", [reg]) for v in names} # @line L5
phis[label] = dict(env)
def value(a):
return g.hashcons("Const", [], a) if isinstance(a, int) else env[a]
for ins in prog.blocks[label].instrs: # @line L6
if ins[0] == "const":
env[ins[1]] = value(ins[2])
elif ins[0] == "copy":
env[ins[1]] = value(ins[2])
elif ins[2] in TRAPPING:
n = g.new("Op", [reg, value(ins[3]), value(ins[4])], ins[2]) # @line L7
g.roots.append(n)
env[ins[1]] = n
else:
n = g.hashcons("Op", [value(ins[3]), value(ins[4])], ins[2]) # @line L8
env[ins[1]] = n # @line L9
t = prog.blocks[label].term # @line L10
if t[0] == "ret":
r = g.new("Return", [reg, value(t[1])])
g.roots.append(r)
g.term[label] = ("ret", r)
elif t[0] == "br" and t[2] != t[3]:
iff = g.new("If", [reg, value(t[1])])
g.roots.append(iff)
proj[(label, t[2])] = g.new("IfTrue", [iff])
proj[(label, t[3])] = g.new("IfFalse", [iff])
g.term[label] = ("br", iff, t[2], t[3])
else:
target = t[1] if t[0] == "jump" else t[2]
proj[(label, target)] = reg
g.term[label] = ("jump", target)
out[label] = env # @line L11
for label in prog.blocks: # @line L12
if label == prog.entry:
continue
ps = preds[label]
g.region[label].inputs = [proj[(p, label)] for p in ps] # @line L13
if label in phis:
for v, phi in phis[label].items():
phi.inputs = [g.region[label]] + [out[p][v] for p in ps] # @line L14
_remove_trivial_phis(g)
return g
def _remove_trivial_phis(g):
"""A phi whose inputs, other than itself, are all one node v is replaced
by v everywhere. Repeat until no such phi is left."""
changed = True
while changed:
changed = False
for n in g.nodes:
if n.kind != "Phi":
continue
vals = {i.id: i for i in n.inputs[1:] if i is not n}
if len(vals) == 1: # @line L15
v = next(iter(vals.values()))
n.kind, n.inputs = "Dead", []
for m in g.nodes:
m.inputs = [v if i is n else i for i in m.inputs]
g.roots = [v if r is n else r for r in g.roots]
changed = True
# ------------------------------------------------------------ scheduling
def _control_block(g, n):
"""The block of a control node or of a node pinned by a control input."""
while n.kind != "Region":
if n.kind == "Start":
return g.entry
n = n.inputs[0]
return g.label_of[n.id]
def _dominators(labels, succ, root):
"""idom and depth in the dominator tree, by the Cooper-Harvey-Kennedy
iteration."""
po, seen, stack = {}, {root}, [(root, iter(succ[root]))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
po[v] = len(po)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(succ[w])))
pred = {v: [] for v in labels}
for v in labels:
for w in succ[v]:
pred[w].append(v)
order = sorted(po, key=lambda v: -po[v])
idom = {root: root}
def intersect(a, b):
while a != b:
while po[a] < po[b]:
a = idom[a]
while po[b] < po[a]:
b = idom[b]
return a
changed = True
while changed:
changed = False
for b in order[1:]:
ps = [p for p in pred[b] if p in idom]
new = ps[0]
for p in ps[1:]:
new = intersect(p, new)
if idom.get(b) != new:
idom[b] = new
changed = True
depth = {root: 0}
for b in order[1:]:
depth[b] = depth[idom[b]] + 1
return idom, depth
def _loop_depth(labels, succ, idom, depth):
"""The number of natural loops that hold each block. A loop is the set of
blocks that reach the tail t of a back edge t -> h, where h dominates t,
without passing through h."""
pred = {v: [] for v in labels}
for v in labels:
for w in succ[v]:
pred[w].append(v)
def dominates(a, b):
while depth[b] > depth[a]:
b = idom[b]
return a == b
loops = {}
for t in labels:
for h in succ[t]:
if dominates(h, t):
body = loops.setdefault(h, {h})
stack = [t]
while stack:
v = stack.pop()
if v not in body:
body.add(v)
stack.extend(pred[v])
ld = {v: 0 for v in labels}
for body in loops.values():
for v in body:
ld[v] += 1
return ld
def schedule(g, prog_labels):
"""Place the live nodes and give back a toy IR program. prog_labels is the
list of block labels in the order to print them, the entry first."""
succ = {}
for label in prog_labels:
t = g.term[label]
succ[label] = [] if t[0] == "ret" else ([t[1]] if t[0] == "jump" else [t[2], t[3]])
idom, depth = _dominators(prog_labels, succ, g.entry) # @line L16
loop = _loop_depth(prog_labels, succ, idom, depth)
def lca(a, b):
if a is None:
return b
while depth[a] > depth[b]:
a = idom[a]
while depth[b] > depth[a]:
b = idom[b]
while a != b:
a, b = idom[a], idom[b]
return a
live, stack = set(), list(g.roots)
for n in stack:
live.add(n.id)
while stack:
n = stack.pop()
for i in n.inputs:
if i.id not in live:
live.add(i.id)
stack.append(i)
nodes = [n for n in g.nodes if n.id in live]
uses = {n.id: [] for n in nodes}
for n in nodes:
for k, i in enumerate(n.inputs):
uses[i.id].append((n, k))
block = {}
for n in nodes: # @line L17
if g.pinned(n):
block[n.id] = _control_block(g, n.inputs[0] if n.kind in ("Phi", "Op", "If", "Return", "Param") else n)
early = {}
def schedule_early(n): # @line L18
if n.id in early:
return early[n.id]
if n.id in block:
early[n.id] = block[n.id]
else:
best = g.entry
for i in n.inputs:
b = schedule_early(i)
if depth[b] > depth[best]:
best = b
early[n.id] = best
return early[n.id]
for n in nodes:
schedule_early(n)
def use_block(u, k):
if u.kind == "Phi" and k > 0:
region = u.inputs[0]
return _control_block(g, region.inputs[k - 1])
return schedule_late(u)
def schedule_late(n): # @line L19
if n.id in block:
return block[n.id]
here = None # @line L20
for u, k in uses[n.id]:
here = lca(here, use_block(u, k)) # @line L21
best, x = here, here
while True: # @line L22
if loop[x] < loop[best]:
best = x
if x == early[n.id]:
break
x = idom[x]
block[n.id] = best # @line L23
return best
for n in nodes:
schedule_late(n)
def name(n):
if n.kind == "Param":
return n.val
if n.kind == "Const":
return n.val
if n.kind == "Undef":
return 0
return "v%d" % n.id
for p in g.params:
if p.startswith("v") and p[1:].isdigit():
raise ValueError("parameter name %r clashes with node names" % p)
placed = {label: [] for label in prog_labels}
for n in nodes:
if n.kind in ("Phi", "Op"):
placed[block[n.id]].append(n)
blocks = {}
for label in prog_labels: # @line L24
instrs = []
region = g.region[label]
for n in placed[label]:
if n.kind == "Phi":
ops = {}
for k, c in enumerate(region.inputs):
ops[_control_block(g, c)] = name(n.inputs[k + 1])
instrs.append(("phi", name(n), ops))
done = set()
def emit(n):
if n.id in done or n.kind != "Op" or block[n.id] != label:
return
done.add(n.id)
ins = n.inputs[1:] if n.val in TRAPPING else n.inputs
for i in ins:
emit(i)
instrs.append(("op", name(n), n.val, name(ins[0]), name(ins[1])))
for n in placed[label]:
emit(n)
t = g.term[label]
if t[0] == "ret":
term = ("ret", name(t[1].inputs[1]))
elif t[0] == "br":
term = ("br", name(t[1].inputs[1]), t[2], t[3])
else:
term = ("jump", t[1])
blocks[label] = toyir.Block(instrs, term)
return toyir.Program(list(g.params), blocks), block
def roundtrip(prog):
"""Build the graph of prog and schedule it back."""
g = build(prog)
out, _ = schedule(g, list(prog.blocks))
return out
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_sea_of_nodes.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sea-of-nodes/. The authors are listed in prov/Q4NRFR.jsonl.
import random
import toyir
from sea_of_nodes import build, roundtrip, schedule
LOOP = """# params: n
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B4
B3:
k = n * 4
s = s + k
i = i + 1
jump B2
B4:
ret s
"""
DIAMOND = """# params: a, b, c
B1:
br c B2 B3
B2:
x = a + b
jump B4
B3:
y = a + b
x = y * 2
jump B4
B4:
ret x
"""
def ops_by_block(prog):
return {label: [i for i in b.instrs if i[0] == "op"] for label, b in prog.blocks.items()}
# ------------------------------------------------------------ brute force
def reaches(prog, a, b, banned):
if a == banned:
return False
seen, stack = {a}, [a]
while stack:
v = stack.pop()
if v == b:
return True
for w in toyir.succs(prog, v):
if w != banned and w not in seen:
seen.add(w)
stack.append(w)
return False
def dominates(prog, a, b):
"""a dominates b: b cannot be reached from the entry without a."""
return a == b or not reaches(prog, prog.entry, b, a)
def check_strict_ssa(prog):
"""Each name is defined once, and each definition dominates its uses; a
phi operand counts as a use at the end of its predecessor."""
where = {p: (prog.entry, -1) for p in prog.params}
for label, b in prog.blocks.items():
for i, ins in enumerate(b.instrs):
x = toyir.defs(ins)
assert x not in where, "two definitions of %s" % x
where[x] = (label, i)
def ok(name, label, i):
dl, di = where[name]
if dl == label:
return di < i
return dominates(prog, dl, label)
for label, b in prog.blocks.items():
for i, ins in enumerate(b.instrs):
if ins[0] == "phi":
for p, a in ins[2].items():
if isinstance(a, str):
assert ok(a, p, len(prog.blocks[p].instrs) + 1)
else:
for a in toyir.uses(ins):
assert ok(a, label, i)
for a in toyir.term_uses(b.term):
assert ok(a, label, len(b.instrs))
# ------------------------------------------------------------ page examples
def test_loop_invariant_value_leaves_the_loop():
out = roundtrip(toyir.parse(LOOP))
ops = ops_by_block(out)
assert [i[2:] for i in ops["B1"]] == [("*", "n", 4)]
assert sorted(i[2] for i in ops["B3"]) == ["+", "+"]
for n in range(-2, 8):
assert toyir.run(out, [n]) == toyir.run(toyir.parse(LOOP), [n])
assert toyir.run(out, [4]) == ("ret", 64)
def test_equal_values_are_made_once_and_hoisted():
out = roundtrip(toyir.parse(DIAMOND))
ops = ops_by_block(out)
assert [i[2:] for i in ops["B1"]] == [("+", "a", "b")]
assert ops["B2"] == []
assert [i[2] for i in ops["B3"]] == ["*"]
phis = [i for i in out.blocks["B4"].instrs if i[0] == "phi"]
assert len(phis) == 1
def test_a_division_stays_in_its_block():
prog = toyir.parse("# params: a, b, c\nB1:\n br c B2 B3\nB2:\n q = a / b\n jump B3\nB3:\n ret a\n")
out = roundtrip(prog)
assert [i[2] for i in ops_by_block(out)["B2"]] == ["/"]
assert ops_by_block(out)["B1"] == []
assert toyir.run(out, [1, 0, 0]) == ("ret", 1)
assert toyir.run(out, [1, 0, 1]) == ("trap",)
def test_graph_shape():
g = build(toyir.parse(LOOP))
kinds = [n.kind for n in g.nodes]
# B2 gets a phi for each of i, k, n, s and t1. The phi of n is trivial
# and removed; those of k and t1 have no use and are not scheduled.
assert kinds.count("Phi") == 4
out, _ = schedule(g, ["B1", "B2", "B3", "B4"])
assert sum(1 for i in out.blocks["B2"].instrs if i[0] == "phi") == 2
assert kinds.count("Region") == 4
assert kinds.count("If") == 1 and kinds.count("Return") == 1
# The floating multiply has no control input.
mul = [n for n in g.nodes if n.kind == "Op" and n.val == "*"]
assert len(mul) == 1 and [i.kind for i in mul[0].inputs] == ["Param", "Const"]
# ------------------------------------------------------------ random programs
def test_random_programs_keep_their_outcomes():
rng = random.Random(20261115)
compared = 0
for k in range(400):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 2 == 0))
out = roundtrip(prog)
for _ in range(6):
args = [rng.randint(-4, 7) for _ in prog.params]
want = toyir.run(prog, args)
if want == ("fuel",):
continue
assert toyir.run(out, args, fuel=200000) == want
compared += 1
assert compared > 2000
def test_random_programs_give_strict_ssa():
rng = random.Random(3)
for k in range(300):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 3 == 0))
check_strict_ssa(roundtrip(prog))
def test_no_more_operations_than_the_source():
rng = random.Random(5)
for k in range(300):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 2 == 0))
out = roundtrip(prog)
before = sum(1 for b in prog.blocks.values() for i in b.instrs if i[0] == "op")
after = sum(1 for b in out.blocks.values() for i in b.instrs if i[0] == "op")
assert after <= before
def test_trapping_operations_keep_their_block():
rng = random.Random(9)
for k in range(200):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 2 == 0))
g = build(prog)
out, block = schedule(g, list(prog.blocks))
for n in g.roots:
if n.kind == "Op":
region = n.inputs[0]
assert block[n.id] == g.label_of[region.id]
History
Click and Paleczny (1995) published the graph IR at the IR'95 workshop. It grew from Click's thesis work at Rice on combining analyses, and Click's PLDI paper of the same year gave global code motion and global value numbering on it. The HotSpot server compiler, called C2, was built on this IR. Paleczny, Vick and Click (2001) describe its SSA graph with RegionNode and PhiNode, and its global code motion on the sea of nodes. The TurboFan compiler of V8 also used a sea of nodes. In 2025 the V8 team reported that it had replaced it with the CFG-based Turboshaft in the JavaScript backend and for WebAssembly.
References
- Cliff Click and Michael Paleczny, A simple graph-based intermediate representation, ACM SIGPLAN Workshop on Intermediate Representations (IR'95), 1995, pages 35-49, the graph with control and data edges, Region, If and Phi nodes, projections, and the building of the graph from the parser with value numbering
- Cliff Click, Global code motion, global value numbering, PLDI 1995, pages 246-257, schedule early, schedule late at the lowest common ancestor of the uses, and the choice of the block of least loop depth between them
- Cliff Click, Combining analyses, combining optimizations, PhD thesis, Rice University, 1995, the intermediate representation used for the combined analyses
- Michael Paleczny, Christopher Vick and Cliff Click, The Java HotSpot server compiler, USENIX Java Virtual Machine Research and Technology Symposium (JVM'01), 2001, Section 3, the SSA graph IR with RegionNode and PhiNode based on Click and Paleczny; Section 10, global code motion on the sea of nodes
- V8 team, Land ahoy, leaving the Sea of Nodes, V8 blog, 2025, why TurboFan used the sea of nodes, the problems seen in practice, and its replacement by the CFG-based Turboshaft
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 | W4 complete |
|
Tag Q4NRFR Edit this page History Report an error Markdown