Algorithm Search⌘K

Algorithmcore

Cytron SSA construction

Also called Cytron et al. SSA construction.

Builds minimal SSA form by placing phi-functions at the iterated dominance frontiers of each variable's definitions and renaming over the dominator tree.

Time
O(I + V (n + m + D)) worst · averageΘ(I + n + m + D) best
Space
O(I + V m + D) extra
Where
D = the total size of the dominance frontiers; I = the number of instructions; V = the number of variables; m = the number of edges; n = the number of blocks
Properties
deterministicofflinerecursive

The Cytron SSA construction is the standard way to build static single assignment form. It works in two passes over a control flow graph whose dominator tree and dominance frontiers are known. The first pass decides where phi-functions go: for each variable, at the iterated dominance frontier of the blocks that assign it. The second pass walks the dominator tree from the root and gives every definition a new name, with one stack of names per variable, so that each use gets the name of the nearest definition above it. Cytron, Ferrante, Rosen, Wegman and Zadeck published it in 1991 and proved that it places the fewest phi-functions that any correct placement needs. Almost every textbook teaches it.

In plain words

First decide where merges are needed. A variable assigned in some block can meet other values of itself only at the edge of the region that block controls, so put a merge there. A merge is itself an assignment, so repeat from each new merge until nothing changes. Then walk the blocks from the top of the dominator tree down. Keep, for each variable, a stack of the names in force. A new assignment gets a fresh name, which goes on the stack. A read takes the name on top. At the end of each block, fill in the merges of the next blocks with the names in force. After a block and everything below it in the tree are done, pop the names it pushed, so its siblings see the old ones.

The problem

The input is a procedure in three-address code with no phi-functions, and its control flow graph G=(N,E,r)G = (N, E, r). Every block is reachable and the entry rr has no predecessors. The output is the same procedure in minimal, strict SSA form, as defined on the SSA construction page: a phi-function for each variable vv exactly at the blocks of the iterated join set J+(Sv)J^+(S_v), where SvS_v is the set of blocks that assign vv plus rr, each definition with a new name, and each use renamed so that it reads the same value as before.

The algorithm needs the immediate dominators and the dominance frontiers. The implementation computes the first with the Cooper-Harvey-Kennedy iteration and the second with the walk described on the dominance frontier computation page.

The algorithm

  1. CYTRON-SSA(G, r, idom, DF)
  2. // Part 1: where the phi-functions go
  3. 1for each variable v do Sites[v] <- {r}
  4. 2for each block b and each instruction in b that assigns v do add b to Sites[v]
  5. 3for each variable v do
  6. 4W <- Sites[v]
  7. 5while W is not empty do remove a block x from W
  8. 6for each y in DF[x] do
  9. 7if y has no phi-function for v then put "v = phi" at the top of y
  10. 8if y was never in W then add y to W
  11. // Part 2: renaming
  12. 9for each parameter p do push p on Stack[p]
  13. RENAME(r)
  14. 10RENAME(b)
  15. for each phi-function "v = phi" at the top of b do
  16. 11replace v by a new name v.k; push v.k on Stack[v]
  17. 12for each other instruction "v = ... u ..." of b, in order do
  18. replace each use u by Top(u)
  19. 13replace v by a new name v.k; push v.k on Stack[v]
  20. replace each use u in the terminator of b by Top(u)
  21. 14for each successor s of b do
  22. 15for each phi-function for v in s do set its operand for the edge (b, s) to Top(v)
  23. 16for each child c of b in the dominator tree do RENAME(c)
  24. 17pop every name that b pushed in lines L11 and L13

Top(v) is the name on top of the stack of vv. If the stack is empty, vv is a local variable read on a path where it has no value yet. Then Top(v) returns v.0, and the implementation puts v.0 = 0 at the top of the entry block. This keeps the result strict: every name has a definition that dominates all its uses. The parameters keep their own names for their values on entry.

Lines L1 and L2 put rr in every site set, because the entry holds each variable's first value. Lines L4 to L8 are the worklist that computes DF+(Sv)DF^+(S_v); the test in line L7 puts at most one phi-function for vv in each block, and the test in line L8 puts each block on the list at most once. Line L12 reads the uses before line L13 pushes the new name, so i = i + 1 reads the old name of i. Lines L14 and L15 run after the whole block, so a phi operand gets the name in force at the end of the predecessor.

The phi-functions of a block are read in parallel, as one copy on the edge. Line L15 takes all their operands from the state at the end of bb, not from the other phi-functions of ss, so the order in which the phi-functions are written does not matter.

Example

The program from the control flow graph page adds the odd numbers below nn:

# params: n
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

Part 1. The frontiers are DF(B2)=DF(B3)=DF(B5)={B2}DF(B2) = DF(B3) = DF(B5) = \{B2\}, DF(B4)={B5}DF(B4) = \{B5\}, and the others are empty. The sites are i: {B1, B5}, s: {B1, B4}, t1: {B1, B2}, t2: {B1, B3} and n: {B1}. For s, the worklist takes B4 and puts a phi-function at B5, takes B5 and puts one at B2, and takes B2, whose frontier B2 already has one. For i, t1 and t2 it puts one at B2. So B2 gets four phi-functions and B5 gets one.

Part 2. The dominator tree is B1 → B2 → {B3, B6}, B3 → {B4, B5}. The walk visits B1, B2, B3, B4, B5 and B6.

  • B1 pushes i.1 and s.1. At the edge to B2, the stacks of t1 and t2 are empty, so those operands become t1.0 and t2.0.
  • B2 pushes the phi names i.2, s.2, t1.1, t2.1, then t1.2 for t1 = i < n, which reads i.2.
  • B3 pushes t2.2. At the edge to B5, the operand of s becomes s.2.
  • B4 pushes s.3 for s = s + i, which reads s.2 and i.2. At the edge to B5, the operand becomes s.3. B4 pops s.3.
  • B5 pushes the phi name s.4 and i.3. At the edge to B2, the operands become i.3, s.4, t1.2 and t2.2. B5 pops its names.
  • B3 pops t2.2. B6 returns s.2, the name on top of the stack of s after B2.

The result is:

# params: n
B1:
  t1.0 = 0
  t2.0 = 0
  i.1 = 0
  s.1 = 0
  jump B2
B2:
  i.2 = phi [B1: i.1, B5: i.3]
  s.2 = phi [B1: s.1, B5: s.4]
  t1.1 = phi [B1: t1.0, B5: t1.2]
  t2.1 = phi [B1: t2.0, B5: t2.2]
  t1.2 = i.2 < n
  br t1.2 B3 B6
B3:
  t2.2 = i.2 % 2
  br t2.2 B4 B5
B4:
  s.3 = s.2 + i.2
  jump B5
B5:
  s.4 = phi [B3: s.2, B4: s.3]
  i.3 = i.2 + 1
  jump B2
B6:
  ret s.2

On n=6n = 6 it returns 9, and on n=10n = 10 it returns 25, the same as the input. The phi-functions for t1 and t2 are minimal but dead. Pruned SSA form would leave them out.

Correctness

The proof file gives the full proof in two parts.

Placement. A phi-function for vv is needed at yy when two definitions of vv reach yy along paths that meet first at yy; this set, closed under the new phi-functions, is J+(Sv)J^+(S_v). The proof shows J+(Sv)=DF+(Sv)J^+(S_v) = DF^+(S_v). One direction: if y∈DF(x)y \in DF(x), a path from xx that stays in the region xx dominates and a path from rr that avoids xx meet first at yy. The other direction: follow a path from a definition to yy and track the deepest definition block that dominates the current node. It changes only at blocks of DF+(Sv)DF^+(S_v), so if yy is not one of them, both paths into yy come from definitions that strictly dominate yy, and one of the two paths then avoids a node that dominates yy, which is impossible.

Renaming. For each point qq of the program, let dd(q)dd(q) be the nearest definition of vv, phi-functions included, that dominates qq. Along any path, crossing an edge into a block with no phi-function for vv does not change dddd, because a change would put the block in the dominance frontier of a definition block. So in every run, the last definition of vv executed before qq is dd(q)dd(q). The stacks hold exactly the definitions on the dominator tree path above qq, so Top(v) is dd(q)dd(q). Hence every use reads the value it read before, every name is defined once, and every definition dominates its uses. The same argument shows that two versions of one variable are never live at the same point, so the output is conventional SSA.

Proof: Phi-functions at the iterated dominance frontier give minimal SSA form, and renaming over the dominator tree is correctfull

Setting. G=(N,E,r)G = (N, E, r) is the control flow graph of the input program. Every block is reachable from rr, and rr has no predecessors (the toy IR gives the entry no predecessors; a compiler can add an empty entry block). xdom⁡yx \operatorname{dom} y means that every path from rr to yy contains xx, and sdom⁡\operatorname{sdom} is the strict version. The dominators of yy are the ancestors of yy in the dominator tree, yy included, so they form a chain. A path is a sequence of blocks joined by edges, and it is non-empty if it has at least one edge.

Fix a variable vv. Let SS be the set of blocks that assign vv, plus rr. The block rr counts as a definition because it holds the value of vv on entry: the parameter itself, or the name v.0v.0 when vv is not a parameter.

Lemma 1. If dsdom⁡yd \operatorname{sdom} y and (p,y)∈E(p, y) \in E, then ddom⁡pd \operatorname{dom} p.

Proof. A path from rr to pp that avoids dd, followed by the edge (p,y)(p, y), is a path from rr to yy that avoids dd, since d≠yd \ne y. □\square

Part 1. The placement is minimal

Join sets. y∈J(X)y \in J(X) if there are two non-empty paths P1P_1 from x1x_1 to yy and P2P_2 from x2x_2 to yy with x1≠x2x_1 \ne x_2 in XX, such that yy is the only node the two paths share. (So yy occurs in each path only at the end, except that P1P_1 may start at x1=yx_1 = y.)

What minimal means. After the construction, the definitions of vv are the blocks of SS and the blocks Φ\Phi that get a phi-function for vv. If two of them reach a block yy along paths that meet first at yy, a use at the top of yy would have two reaching definitions, so yy needs a phi-function. So a valid placement is a set Φ\Phi with J(S∪Φ)⊆ΦJ(S \cup \Phi) \subseteq \Phi. JJ is monotone and NN is finite, so the least such set exists. It is J+(S)J^+(S), the limit of J1=J(S)J_1 = J(S), Ji+1=J(S∪Ji)J_{i+1} = J(S \cup J_i): by induction each JiJ_i lies in every valid Φ\Phi, and the limit is valid. Minimal SSA form places phi-functions for vv exactly at J+(S)J^+(S). We show that this set is DF+(S)DF^+(S), the set that lines L3 to L8 compute.

Lemma 2. If x≠rx \ne r, then DF(x)⊆J({r,x})DF(x) \subseteq J(\{r, x\}).

Proof. Let y∈DF(x)y \in DF(x): there is an edge (p,y)(p, y) with xdom⁡px \operatorname{dom} p and not xsdom⁡yx \operatorname{sdom} y. As rr has no predecessors, y≠ry \ne r.

The first path. Take a path from rr to pp. It contains xx. Keep the part after the last xx, so we get a path from xx to pp in which xx occurs only at the start. Every node uu on it is dominated by xx: a path from rr to uu that avoids xx, followed by the rest of this path to pp, would avoid xx and contradict xdom⁡px \operatorname{dom} p. Add the edge (p,y)(p, y), and cut the path at the first yy after the start. The result P1P_1 is a non-empty path from xx to yy, and every node of P1P_1 except the last is dominated by xx.

The second path. Take a path from rr to yy and cut it at the first yy. If x≠yx \ne y, choose it to avoid xx, which is possible because xx does not dominate yy. The result P2P_2 is non-empty, because r≠yr \ne y. No node uu of P2P_2 before yy is dominated by xx: the part of P2P_2 from rr to uu avoids xx (if x=yx = y, because yy occurs only at the end).

So the only node the two paths share is yy, and they start at xx and rr, which differ. Hence y∈J({r,x})y \in J(\{r, x\}). □\square

Lemma 3. For every set XX with r∈Xr \in X, J(X)⊆DF+(X)J(X) \subseteq DF^+(X).

Proof. Let T=X∪DF+(X)T = X \cup DF^+(X). By the definition of DF+DF^+ as a limit, DF(T)=DF+(X)⊆TDF(T) = DF^+(X) \subseteq T. For each node ww, let d(w)d(w) be the deepest dominator of ww that is in TT, with ww itself allowed. It exists, since r∈Tr \in T dominates every node.

Claim. If (p,w)∈E(p, w) \in E and w∉Tw \notin T, then d(w)=d(p)d(w) = d(p). Let u=d(p)u = d(p), so u∈Tu \in T and udom⁡pu \operatorname{dom} p. If uu did not strictly dominate ww, then w∈DF(u)⊆Tw \in DF(u) \subseteq T, which is false. So usdom⁡wu \operatorname{sdom} w, and d(w)d(w) is uu or a node below uu. As w∉Tw \notin T, d(w)sdom⁡wd(w) \operatorname{sdom} w, so by Lemma 1 d(w)dom⁡pd(w) \operatorname{dom} p, and d(w)d(w) is uu or a node above uu. So d(w)=ud(w) = u.

Now let y∈J(X)y \in J(X) through P1=a0,…,akP_1 = a_0, \ldots, a_k and P2=b0,…,blP_2 = b_0, \ldots, b_l, with ak=bl=ya_k = b_l = y. Let aia_i be the last node of a0,…,ak−1a_0, \ldots, a_{k-1} that is in TT. It exists, as a0∈Xa_0 \in X. The nodes ai+1,…,ak−1a_{i+1}, \ldots, a_{k-1} are not in TT, so the claim gives d(ak−1)=d(ai)=aid(a_{k-1}) = d(a_i) = a_i. So aidom⁡ak−1a_i \operatorname{dom} a_{k-1}. If aia_i does not strictly dominate yy, then y∈DF(ai)⊆DF+(X)y \in DF(a_i) \subseteq DF^+(X) and we are done. In the same way, with bjb_j the last node of b0,…,bl−1b_0, \ldots, b_{l-1} in TT, either y∈DF+(X)y \in DF^+(X) or bjsdom⁡yb_j \operatorname{sdom} y.

Suppose aisdom⁡ya_i \operatorname{sdom} y and bjsdom⁡yb_j \operatorname{sdom} y. Both are on the dominator chain of yy, so one dominates the other; say bjdom⁡aib_j \operatorname{dom} a_i. They are not equal: they are nodes of P1P_1 and P2P_2 other than yy. So aia_i does not dominate bjb_j, and some path from rr to bjb_j avoids aia_i. Follow it with the part of P2P_2 from bjb_j to yy. The nodes of P2P_2 other than yy are not on P1P_1, and ai≠ya_i \ne y, so the whole path avoids aia_i. This contradicts aisdom⁡ya_i \operatorname{sdom} y. □\square

Lemma 4. DF+(S∪DF+(S))=DF+(S)DF^+(S \cup DF^+(S)) = DF^+(S).

Proof. Let X=S∪DF+(S)X = S \cup DF^+(S). Then DF(X)=DF+(S)DF(X) = DF^+(S), and DF(X∪DF+(S))=DF(X)=DF+(S)DF(X \cup DF^+(S)) = DF(X) = DF^+(S). So DF+(S)DF^+(S) contains DF(X)DF(X) and is closed, and DF+(X)DF^+(X) is the least such set, so DF+(X)⊆DF+(S)DF^+(X) \subseteq DF^+(S). The other inclusion holds because DF+DF^+ is monotone. □\square

Theorem 1. J+(S)=DF+(S)J^+(S) = DF^+(S). So lines L3 to L8 place a phi-function for vv at exactly the blocks where minimal SSA form needs one.

Proof. (⊇\supseteq) By induction on the sequence DF1=DF(S)DF_1 = DF(S), DFi+1=DF(S∪DFi)DF_{i+1} = DF(S \cup DF_i), each DFi⊆J+(S)DF_i \subseteq J^+(S). Every xx with x≠rx \ne r in S∪J+(S)S \cup J^+(S) has DF(x)⊆J({r,x})⊆J(S∪J+(S))=J+(S)DF(x) \subseteq J(\{r, x\}) \subseteq J(S \cup J^+(S)) = J^+(S), by Lemma 2 and monotonicity, and DF(r)=∅DF(r) = \emptyset because rr strictly dominates every other node and has no predecessors. So DF1⊆J+(S)DF_1 \subseteq J^+(S), and if DFi⊆J+(S)DF_i \subseteq J^+(S), then DFi+1=DF(S∪DFi)⊆J+(S)DF_{i+1} = DF(S \cup DF_i) \subseteq J^+(S).

(⊆\subseteq) Let Φ=DF+(S)\Phi = DF^+(S). By Lemmas 3 and 4, J(S∪Φ)⊆DF+(S∪Φ)=ΦJ(S \cup \Phi) \subseteq DF^+(S \cup \Phi) = \Phi. So Φ\Phi is a valid placement, and the least one, J+(S)J^+(S), lies inside it. □\square

Lines L4 to L8 compute DF+(S)DF^+(S) by the standard worklist, which returns the limit of the sequence (this is Lemma 4 of the dominance frontier computation proof). The flag has_phi puts at most one phi-function for vv in each block.

Part 2. Renaming is correct

Fix vv again. After line L8, the definition points of vv are: the entry definition at the top of rr, each phi-function for vv at the top of a block of Φ\Phi, and each instruction that assigns vv. A point is a position between two instructions of a block, or the end of a block (after the last instruction, before the terminator). A definition point DD in block cc dominates a point qq in block bb if csdom⁡bc \operatorname{sdom} b, or c=bc = b and DD comes before qq. For each point qq, the definition points that dominate it form a chain: those in strict dominators of bb, ordered by depth in the tree and then by position, followed by those above qq in bb. The entry definition is always in it. Let dd(q)dd(q) be the last one, the nearest dominating definition.

Lemma 5. Let (p,w)(p, w) be an edge and let ww have no phi-function for vv. Then dd(top of w)=dd(end of p)dd(\text{top of } w) = dd(\text{end of } p).

Proof. Let D=dd(end of p)D = dd(\text{end of } p), in block cc. Then cdom⁡pc \operatorname{dom} p, and c∈S∪Φc \in S \cup \Phi. If cc did not strictly dominate ww, then w∈DF(c)⊆DF+(S)=Φw \in DF(c) \subseteq DF^+(S) = \Phi (by Lemma 4, DF(S∪Φ)⊆ΦDF(S \cup \Phi) \subseteq \Phi), and ww would have a phi-function. So csdom⁡wc \operatorname{sdom} w, and DD dominates the top of ww.

Every definition point that dominates the top of ww lies in a block c′c' with c′sdom⁡wc' \operatorname{sdom} w, because ww has no definition point at its top. By Lemma 1, c′dom⁡pc' \operatorname{dom} p, so the point also dominates the end of pp. So the chain for the top of ww is part of the chain for the end of pp, and it contains DD, the last element of the larger chain. Hence DD is its last element too. □\square

Theorem 2 (the dynamic meaning). Along every path from rr, and so in every run, at every point qq, the last definition point of vv that was passed is dd(q)dd(q). Phi-functions count as passed when their block is entered.

Proof. Let EE be the last definition point passed before qq; it exists because the entry definition runs first. Right after EE, the nearest dominating definition is EE itself. Between EE and qq, the run executes no definition point of vv. Moving inside a block past instructions that do not define vv does not change dddd. Moving along an edge (p,w)(p, w) into a block that has no phi-function for vv does not change dddd, by Lemma 5. A block with a phi-function for vv cannot be entered in this stretch, because the phi-function would be executed. So dd(q)=Edd(q) = E. □\square

Theorem 3 (the walk). Lines L9 to L17 give each use of vv at a point qq the name of dd(q)dd(q). For a phi operand of vv in block ww that belongs to the edge (p,w)(p, w), the use is at the end of pp, and the walk gives it the name of dd(end of p)dd(\text{end of } p).

Proof. Invariant: when the walk is at a point qq of block bb, the stack of vv holds the names of the definition points of vv that dominate qq, in chain order, except that the entry definition of a variable that is not a parameter is left implicit. This holds at the top of rr: line L9 pushes each parameter, and the stacks of the other variables are empty. Lines L11 and L13 push a name exactly when the walk passes a definition point, which then dominates the following points of bb. When the walk enters a child cc of bb in the tree, at line L16, the points of bb above the end all dominate the top of cc, and no other definition points do except those in the strict dominators of bb, which are already on the stack below them. Line L17 pops what bb pushed, so the stacks are restored when the walk goes back up. So the top of the stack is dd(q)dd(q), or the stack is empty and dd(q)dd(q) is the entry definition v.0v.0, which the function top returns.

Lines L12 and L13 read the top before they push the new definition, so an instruction like x = x + 1 reads the old name. Lines L14 and L15 run after all instructions of bb, so they fill the operand of the edge (b,s)(b, s) with dd(end of b)dd(\text{end of } b). □\square

Corollary (correctness of the output). Take a run of the input program that never reads a variable before it has a value. In the matching run of the output, each instruction reads, at each use, the name of the last definition of that variable that was executed, by Theorems 2 and 3, and that name holds the value the input program would read. The branches go the same way, so the two runs follow the same blocks and return the same value. A phi operand v.0v.0 is read only on a path where the input program does not read vv, because v.0v.0 is never the last definition before a real use in such a run. Every use names the definition at dd(q)dd(q), which dominates qq, so the output is strict. Each name has one definition point, so each use has exactly one reaching definition.

Corollary (the output is conventional). At any point qq, the only version of vv that is live is the one defined at dd(q)dd(q). If v.kv.k is live at qq, there is a path from qq to a use of v.kv.k with no definition of v.kv.k on it. If that path had any definition point of vv, the last one before the use would be dddd of the use, which is the definition of v.kv.k, so the use would not see v.kv.k from qq. So the path has no definition point of vv, and by Theorem 2, applied to a run through qq along that path, dd(q)dd(q) is the definition of v.kv.k. So the versions of one variable never interfere, and mapping each v.kv.k back to vv and deleting the phi-functions, as strip_versions does, keeps the meaning.

Running time. Lines L1 and L2 read each instruction once. For one variable, the worklist of lines L4 to L8 takes each block of S∪ΦS \cup \Phi once and reads its frontier once, which costs O(∣S∣+∣Φ∣+∑x∈S∪Φ∣DF(x)∣)=O(n+D)O(|S| + |\Phi| + \sum_{x \in S \cup \Phi} |DF(x)|) = O(n + D), with DD the total size of the frontiers. Over VV variables this is O(V(n+D))O(V (n + D)), and the sum of ∣S∣|S| over all variables is at most the number of instructions plus VV. The walk visits each block once, each instruction once and each phi operand once, so it takes time linear in the size of the output, which is O(I+Vm)O(I + V m) for II instructions and mm edges.

Complexity

Let II be the number of instructions, VV the number of variables, nn and mm the numbers of blocks and edges, and DD the total size of the dominance frontiers.

  • Dominance. The immediate dominators take O(mlog⁡n)O(m \log n) time with the simple version of Lengauer-Tarjan, or O(m α(m,n))O(m\, \alpha(m, n)) with its sophisticated version, or a few passes of the Cooper-Harvey-Kennedy iteration in practice. The frontiers take Θ(n+m+D)\Theta(n + m + D).
  • Placement. For one variable, the worklist takes each block of Sv∪DF+(Sv)S_v \cup DF^+(S_v) once and reads its frontier once, which is O(n+D)O(n + D). Over all variables this is O(I+V(n+D))O(I + V(n + D)).
  • Renaming. Each instruction, each phi-function and each phi operand is handled once. The output has at most VV phi-functions per block, so this is O(I+Vm)O(I + V m).

The total after the dominator tree is O(I+V(n+m+D))O(I + V(n + m + D)). DD can be Θ(n2)\Theta(n^2), and the output itself can have Θ(n2)\Theta(n^2) phi-functions, as the nested repeat-until loops on the dominance frontier page show. Cytron et al. found both to grow about linearly on real programs. The extra space is the frontiers, the stacks and the output.

Properties

  • Minimal. It places phi-functions at exactly J+(Sv)J^+(S_v) for each variable, on any control flow graph, reducible or not.
  • Not pruned. It can place dead phi-functions, such as those for t1 and t2 in the example.
  • Strict and conventional. With the entry definitions, every definition dominates its uses, and the versions of one variable never interfere. So, before any optimization, out-of-SSA translation can just drop the version numbers.
  • Needs the whole graph. The graph must be complete before the dominator tree can be built.
  • Recursive. RENAME recurses on the dominator tree. A deep tree needs an explicit stack in production code.

Variants and improvements

  • Pruned SSA. Compute liveness first and skip a phi-function for vv at yy if vv is not live on entry to yy. See pruned SSA form.
  • Semi-pruned SSA. Briggs, Cooper, Harvey and Simpson (1998) skip the variables that are never live across a block boundary. It needs no full liveness pass and removes most of the dead phi-functions.
  • Linear-time placement. Sreedhar and Gao (1995) compute DF+(Sv)DF^+(S_v) on the DJ-graph in O(n+m)O(n + m) per variable, without the frontiers.
  • On-demand construction. Braun et al. (2013) build SSA form during translation from the syntax tree, with no dominance information.
  • Copy folding during renaming. For a copy x = y, push the name of y on the stack of x and drop the copy. This saves a pass, but the output is then no longer conventional, and out-of-SSA translation must handle the lost copy and swap problems.

When to use it

Use it when the whole control flow graph is available and the dominator tree is needed anyway, which is the case in most optimizing compilers. It is the reference method: it is easy to prove correct and it gives the minimal placement on any graph. If the graph is not built yet, or the compiler wants to avoid the dominance passes, Braun's method is simpler. If the frontiers may be large, use DJ-graphs for the placement.

Pitfalls

  • Missing entry definitions. A variable read on some path before it is assigned has no name on that path. Without v.0 at the entry, the phi operand is empty and the result is not strict.
  • Reading phi-functions one by one. All phi-functions of a block take their operands from the end of the predecessor. Filling an operand with the name of another phi-function of the same block is wrong.
  • Popping too early or too late. The names pushed by a block must stay on the stacks while its dominator subtree is renamed and must be gone before its siblings are. Popping at the end of the block body, before the children, gives the children wrong names.
  • Edges into the entry. If the entry has a predecessor, it may need phi-functions, and the first entry has no incoming edge to choose an operand. Add a new empty entry block first.
  • Unreachable blocks. They have no immediate dominator. Delete them first.
  • Assuming the output is pruned. It is minimal, not pruned. Later passes must expect dead phi-functions, or the compiler must prune.

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.

cytron_ssa_construction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cytron-ssa-construction/. The authors are listed in prov/BVFDF2.jsonl.
"""Minimal SSA form by the method of Cytron, Ferrante, Rosen, Wegman and
Zadeck: phi-functions at the iterated dominance frontier of the blocks that
assign each variable, then renaming by a walk of the dominator tree.

The input is a toy IR program without phi-functions, whose names contain no
dot. The output names the k-th definition of v as v.k. A parameter keeps its
own name for its value on entry. A variable that some path reads before any
assignment gets the name v.0, defined by v.0 = 0 at the top of the entry, so
the result is strict: every definition dominates its uses.
"""

import toyir
from toyir import Block, Program


# ------------------------------------------------- dominators and frontiers


def _postorder(succ, root):
    seen = {root}
    out = []
    stack = [(root, iter(succ[root]))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            stack.pop()
            out.append(v)
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(succ[w])))
    return out


def immediate_dominators(succ, root):
    """The Cooper-Harvey-Kennedy iteration. idom[root] is None, and only the
    nodes that root reaches are keys."""
    order = _postorder(succ, root)
    po = {v: i for i, v in enumerate(order)}
    pred = {v: [] for v in order}
    for v in order:
        for w in succ[v]:
            pred[w].append(v)
    doms = {root: root}

    def intersect(a, b):
        while a != b:
            while po[a] < po[b]:
                a = doms[a]
            while po[b] < po[a]:
                b = doms[b]
        return a

    changed = True
    while changed:
        changed = False
        for b in reversed(order):
            if b == root:
                continue
            new = None
            for p in pred[b]:
                if p in doms:
                    new = p if new is None else intersect(p, new)
            if doms.get(b) != new:
                doms[b] = new
                changed = True
    idom = dict(doms)
    idom[root] = None
    return idom


def dominance_frontiers(succ, root, idom):
    """The walk of Cooper, Harvey and Kennedy from each predecessor."""
    pred = {v: [] for v in idom}
    for v in idom:
        for w in succ[v]:
            pred[w].append(v)
    df = {v: set() for v in idom}
    for y in idom:
        for p in pred[y]:
            runner = p
            while runner != idom[y] and y not in df[runner]:
                df[runner].add(y)
                runner = idom[runner]
    return df


# ------------------------------------------------------------- construction


def variables(prog):
    """The parameters, then the assigned names, in order of first appearance."""
    out = list(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            x = toyir.defs(ins)
            if x is not None and x not in out:
                out.append(x)
    return out


def place_phis(prog, idom=None, df=None):
    """Dict from block to the variables that get a phi-function there."""
    succ = {label: toyir.succs(prog, label) for label in prog.blocks}
    root = prog.entry
    if idom is None:
        idom = immediate_dominators(succ, root)
    if df is None:
        df = dominance_frontiers(succ, root, idom)
    sites = {v: {root} for v in variables(prog)}  # @line L1
    for label in idom:
        for ins in prog.blocks[label].instrs:
            x = toyir.defs(ins)
            if x is not None:
                sites[x].add(label)  # @line L2
    phis = {label: [] for label in idom}
    for v, s in sites.items():  # @line L3
        has_phi = set()
        work = list(s)  # @line L4
        queued = set(s)
        while work:  # @line L5
            x = work.pop()
            for y in df[x]:  # @line L6
                if y not in has_phi:
                    has_phi.add(y)
                    phis[y].append(v)  # @line L7
                    if y not in queued:
                        queued.add(y)
                        work.append(y)  # @line L8
    return phis


def cytron_ssa(prog):
    """Return a new program in minimal, strict SSA form with the same behaviour."""
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] == "phi":
                raise ValueError("the input already has phi-functions")
            x = toyir.defs(ins)
            if x is not None and "." in x:
                raise ValueError("names must not contain a dot: %r" % x)
    succ = {label: toyir.succs(prog, label) for label in prog.blocks}
    root = prog.entry
    idom = immediate_dominators(succ, root)
    df = dominance_frontiers(succ, root, idom)
    phis = place_phis(prog, idom, df)

    children = {v: [] for v in idom}
    for v in idom:
        if idom[v] is not None:
            children[idom[v]].append(v)
    params = set(prog.params)
    counter = {v: 0 for v in variables(prog)}
    stacks = {v: [] for v in counter}
    undefined = []  # the variables that need v.0 = 0 at the entry

    def top(v):
        if stacks[v]:
            return stacks[v][-1]
        name = v + ".0"
        if name not in undefined:
            undefined.append(name)
        return name

    def fresh(v):
        counter[v] += 1
        name = "%s.%d" % (v, counter[v])
        stacks[v].append(name)
        return name

    def operand(a):
        return top(a) if isinstance(a, str) else a

    for p in prog.params:
        stacks[p].append(p)  # @line L9

    # The blocks of the result, filled in during the walk. The phi-functions
    # are created first, with no operands, and get one operand per edge.
    new_phis = {label: [("phi", None, {}) for _ in phis[label]] for label in idom}
    out = {label: None for label in prog.blocks if label in idom}

    def rename(b):  # @line L10
        pushed = []
        block_phis = []
        for v, (_, _, args) in zip(phis[b], new_phis[b]):
            block_phis.append(("phi", fresh(v), args))  # @line L11
            pushed.append(v)
        new_phis[b] = block_phis
        instrs = []
        for ins in prog.blocks[b].instrs:
            k = ins[0]
            if k == "const":
                ins2 = ("const", None, ins[2])
            elif k == "copy":
                ins2 = ("copy", None, operand(ins[2]))  # @line L12
            elif k == "op":
                ins2 = ("op", None, ins[2], operand(ins[3]), operand(ins[4]))
            else:
                raise ValueError("unsupported instruction: %r" % (ins,))
            name = fresh(ins[1])  # @line L13
            pushed.append(ins[1])
            instrs.append(ins2[:1] + (name,) + ins2[2:])
        t = prog.blocks[b].term
        if t[0] == "br":
            t = ("br", operand(t[1]), t[2], t[3])
        elif t[0] == "ret":
            t = ("ret", operand(t[1]))
        for s in succ[b]:  # @line L14
            for v, (_, _, args) in zip(phis[s], new_phis[s]):
                args[b] = top(v)  # @line L15
        out[b] = (instrs, t)
        for c in children[b]:  # @line L16
            rename(c)
        for v in pushed:  # @line L17
            stacks[v].pop()

    rename(root)

    preds = {label: [] for label in out}
    for a in out:
        for s in succ[a]:
            preds[s].append(a)
    blocks = {}
    for label, (instrs, t) in out.items():
        # Write the operands of each phi-function in predecessor order.
        head = [("phi", x, {p: args[p] for p in preds[label]}) for _, x, args in new_phis[label]]
        if label == root:
            head = [("const", name, 0) for name in undefined] + head
        blocks[label] = Block(head + instrs, t)
    return Program(list(prog.params), blocks)


def strip_versions(prog):
    """Out of SSA for the output of cytron_ssa: drop the phi-functions and
    map each name v.k back to v. This is correct because the construction
    keeps the program conventional: no two versions of one variable are live
    at the same point."""
    def base(a):
        return a.split(".")[0] if isinstance(a, str) else a

    blocks = {}
    for label, b in prog.blocks.items():
        instrs = []
        for ins in b.instrs:
            if ins[0] == "phi":
                continue
            if ins[0] == "const":
                instrs.append(("const", base(ins[1]), ins[2]))
            elif ins[0] == "copy":
                instrs.append(("copy", base(ins[1]), base(ins[2])))
            else:
                instrs.append(("op", base(ins[1]), ins[2], base(ins[3]), base(ins[4])))
        t = b.term
        if t[0] == "br":
            t = ("br", base(t[1]), t[2], t[3])
        elif t[0] == "ret":
            t = ("ret", base(t[1]))
        blocks[label] = Block(instrs, t)
    return Program(list(prog.params), blocks)
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_cytron_ssa_construction.py 332 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cytron-ssa-construction/. The authors are listed in prov/BVFDF2.jsonl.

import random

import toyir
from toyir import Block, Program
from cytron_ssa_construction import cytron_ssa, place_phis, strip_versions, variables

ODD_SUM = """
# params: n
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
"""

ODD_SUM_SSA = """# params: n
B1:
  t1.0 = 0
  t2.0 = 0
  i.1 = 0
  s.1 = 0
  jump B2
B2:
  i.2 = phi [B1: i.1, B5: i.3]
  s.2 = phi [B1: s.1, B5: s.4]
  t1.1 = phi [B1: t1.0, B5: t1.2]
  t2.1 = phi [B1: t2.0, B5: t2.2]
  t1.2 = i.2 < n
  br t1.2 B3 B6
B3:
  t2.2 = i.2 % 2
  br t2.2 B4 B5
B4:
  s.3 = s.2 + i.2
  jump B5
B5:
  s.4 = phi [B3: s.2, B4: s.3]
  i.3 = i.2 + 1
  jump B2
B6:
  ret s.2
"""


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


def graph(prog):
    return {label: toyir.succs(prog, label) for label in prog.blocks}


def _reach(succ, root, removed=None):
    if root == removed:
        return set()
    seen = {root}
    stack = [root]
    while stack:
        v = stack.pop()
        for w in succ[v]:
            if w != removed and w not in seen:
                seen.add(w)
                stack.append(w)
    return seen


def brute_dominators(succ, root):
    nodes = _reach(succ, root)
    dom = {v: set() for v in nodes}
    for d in nodes:
        left = _reach(succ, root, d)
        for v in nodes:
            if v not in left:
                dom[v].add(d)
    return dom


def brute_frontiers(succ, root):
    dom = brute_dominators(succ, root)
    df = {v: set() for v in dom}
    for p in dom:
        for y in succ[p]:
            for x in dom[p]:
                if not (x in dom[y] and x != y):
                    df[x].add(y)
    return df


def def_sites(prog):
    sites = {v: {prog.entry} for v in variables(prog)}
    for label, b in prog.blocks.items():
        for ins in b.instrs:
            sites[ins[1]].add(label)
    return sites


def brute_idf(df, s):
    cur = set()
    while True:
        nxt = set()
        for x in set(s) | cur:
            nxt |= df[x]
        if nxt == cur:
            return cur
        cur = nxt


def _paths_into(succ, x):
    """All non-empty paths from x that end at their first repeated node or
    earlier, as (end, set of nodes before the end). A path may end at x."""
    out = []

    def walk(v, seen):
        for w in succ[v]:
            out.append((w, frozenset(seen)))
            if w not in seen:
                seen.add(w)
                walk(w, seen)
                seen.remove(w)

    walk(x, {x})
    return out


def brute_join(succ, s):
    """J(S): nodes y with two non-empty paths from two different nodes of S
    that end at y and share no node but y."""
    ends = {x: {} for x in s}
    for x in s:
        for y, before in _paths_into(succ, x):
            if y in before and y != x:
                continue  # the path passed y before its end
            ends[x].setdefault(y, set()).add(before - {y})
    out = set()
    xs = sorted(s)
    for i, a in enumerate(xs):
        for b in xs[i + 1:]:
            for y in set(ends[a]) & set(ends[b]):
                if any(not (p & q) for p in ends[a][y] for q in ends[b][y]):
                    out.add(y)
    return out


def brute_iterated_join(succ, s):
    cur = set()
    while True:
        nxt = brute_join(succ, set(s) | cur)
        if nxt == cur:
            return cur
        cur = nxt


def trace(prog, args, skip=(), fuel=2000):
    """Run prog and record, for each executed non-phi instruction and
    terminator, the values of its operands. Instructions that define a name
    in skip are not recorded."""
    env = dict(zip(prog.params, args))
    label, prev, out = prog.entry, None, []
    while fuel > 0:
        fuel -= 1
        b = prog.blocks[label]
        phis = [ins for ins in b.instrs if ins[0] == "phi"]
        env.update([(ins[1], env[ins[2][prev]]) for ins in phis])
        k = 0
        for ins in b.instrs:
            if ins[0] == "phi":
                continue
            ops = [a if isinstance(a, int) else env[a] for a in toyir.uses(ins) + [x for x in ins[2:] if isinstance(x, int)]]
            if ins[1] not in skip:
                out.append((label, k, tuple(ops)))
                k += 1
            if ins[0] == "const":
                env[ins[1]] = ins[2]
            elif ins[0] == "copy":
                env[ins[1]] = ops[0]
            else:
                a = env[ins[3]] if isinstance(ins[3], str) else ins[3]
                c = env[ins[4]] if isinstance(ins[4], str) else ins[4]
                try:
                    env[ins[1]] = toyir._binop(ins[2], a, c)
                except toyir._Trap:
                    out.append(("trap",))
                    return out
        t = b.term
        if t[0] == "ret":
            out.append((label, "ret", env[t[1]] if isinstance(t[1], str) else t[1]))
            return out
        if t[0] == "jump":
            prev, label = label, t[1]
        else:
            c = env[t[1]] if isinstance(t[1], str) else t[1]
            out.append((label, "br", c))
            prev, label = label, (t[2] if c != 0 else t[3])
    out.append(("fuel",))
    return out


def check_ssa(ssa):
    """Single assignment, one operand per incoming edge, and strictness."""
    succ = graph(ssa)
    pred = toyir.preds(ssa)
    dom = brute_dominators(succ, ssa.entry)
    where = {p: (ssa.entry, -1) for p in ssa.params}
    for label, b in ssa.blocks.items():
        for k, ins in enumerate(b.instrs):
            assert ins[1] not in where, "two definitions of %s" % ins[1]
            where[ins[1]] = (label, k)

    def dominates(d, block, pos):
        b, k = d
        return (b in dom[block] and b != block) or (b == block and k < pos)

    for label, b in ssa.blocks.items():
        seen_other = False
        for k, ins in enumerate(b.instrs):
            if ins[0] == "phi":
                assert not seen_other
                assert set(ins[2]) == set(pred[label])
                for p, a in ins[2].items():
                    if isinstance(a, str):
                        assert dominates(where[a], p, len(ssa.blocks[p].instrs))
            else:
                seen_other = True
                for a in toyir.uses(ins):
                    assert dominates(where[a], label, k)
        for a in toyir.term_uses(b.term):
            assert dominates(where[a], label, len(b.instrs))


def programs(seed, count, nvars=6, nblocks=8):
    rng = random.Random(seed)
    for k in range(count):
        yield rng, toyir.random_program(rng, nvars, nblocks, acyclic=(k % 3 == 0))


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


def test_page_example():
    prog = toyir.parse(ODD_SUM)
    ssa = cytron_ssa(prog)
    assert toyir.show(ssa) == ODD_SUM_SSA
    for n in range(-2, 12):
        assert toyir.run(ssa, [n]) == toyir.run(prog, [n])


def test_phis_at_iterated_frontier():
    for _, prog in programs(1, 300):
        succ = graph(prog)
        df = brute_frontiers(succ, prog.entry)
        phis = place_phis(prog)
        for v, s in def_sites(prog).items():
            want = brute_idf(df, s)
            got = {b for b, vs in phis.items() if v in vs}
            assert got == want
            assert all(phis[b].count(v) <= 1 for b in phis)


def test_iterated_frontier_is_the_join_set():
    # Minimality: a phi-function goes exactly where two definitions converge.
    for _, prog in programs(2, 150, nvars=4, nblocks=6):
        succ = graph(prog)
        df = brute_frontiers(succ, prog.entry)
        for v, s in def_sites(prog).items():
            j = brute_join(succ, s)
            assert brute_idf(df, s) == j
            assert brute_iterated_join(succ, s) == j


def test_ssa_is_single_assignment_and_strict():
    for _, prog in programs(3, 300):
        check_ssa(cytron_ssa(prog))


def test_every_use_reads_the_original_value():
    for rng, prog in programs(4, 300):
        ssa = cytron_ssa(prog)
        skip = {ins[1] for ins in ssa.blocks[ssa.entry].instrs if ins[1].endswith(".0")}
        for _ in range(4):
            args = [rng.randint(-3, 6), rng.randint(-3, 6)]
            assert trace(ssa, args, skip) == trace(prog, args)


def test_round_trip_outputs():
    for rng, prog in programs(5, 400):
        ssa = cytron_ssa(prog)
        back = strip_versions(ssa)
        for _ in range(5):
            args = [rng.randint(-4, 8), rng.randint(-4, 8)]
            want = toyir.run(prog, args)
            assert toyir.run(ssa, args) == want
            assert toyir.run(back, args) == want


def test_quadratic_family():
    for n in range(1, 10):
        blocks = {"E": Block([], ("jump", "h1"))}
        for i in range(1, n + 1):
            blocks["h%d" % i] = Block([], ("jump", "h%d" % (i + 1) if i < n else "l%d" % n))
        for i in range(n, 0, -1):
            nxt = "l%d" % (i - 1) if i > 1 else "X"
            blocks["l%d" % i] = Block([("const", "v%d" % i, i)], ("br", "c", "h%d" % i, nxt))
        blocks["X"] = Block([], ("ret", 0))
        prog = Program(["c"], blocks)
        phis = place_phis(prog)
        assert sum(len(vs) for vs in phis.values()) == n * (n + 1) // 2
        check_ssa(cytron_ssa(prog))
        assert toyir.run(cytron_ssa(prog), [0]) == ("ret", 0)


def test_rejects_phi_input():
    prog = toyir.parse("B1:\n  jump B2\nB2:\n  x = phi [B1: 1]\n  ret x\n")
    try:
        cytron_ssa(prog)
    except ValueError:
        return
    assert False

History

Rosen, Wegman and Zadeck introduced phi-functions for global value numbering in 1988. Cytron, Ferrante, Rosen, Wegman and Zadeck gave the efficient construction through dominance frontiers at POPL 1989, and the full version with proofs and the control dependence graph in TOPLAS in 1991. The method made SSA form practical, and research and production compilers took it up; GCC, for example, places its phi-functions with dominance frontiers. Briggs et al. (1998) made it cheaper with semi-pruned SSA, and Sreedhar and Gao (1995) gave a linear-time placement.

References

  1. Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, pages 451-490, the placement of phi-functions with a worklist over the dominance frontiers, the renaming pass with one stack per variable over the dominator tree, the proofs that the result is minimal and correct, and the cost analysis
  2. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 19 (Static Single-Assignment Form), inserting phi-functions and renaming the variables
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), the section on static single-assignment form, with the placement of phi-functions and the renaming
  4. Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 3 (Standard Construction and Destruction Algorithms), phi-function insertion and variable renaming
  5. Preston Briggs, Keith D. Cooper, Timothy J. Harvey and L. Taylor Simpson, Practical improvements to the construction and destruction of static single assignment form, Software: Practice and Experience 28(8), 1998, pages 859-881, semi-pruned SSA form as a cheaper input to the same algorithm

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example