Algorithm Search⌘K

Algorithmadvanced

Sreedhar out-of-SSA translation

Also called conventional SSA translation.

Converts SSA into conventional SSA, where phi-related names do not interfere, by inserting copies, and then drops all phi-functions.

Time
O(F B N V + N^2 V^2) worst · averageΘ(N) best
Space
O(N + V^2) extra
Where
B = the number of blocks; F = the number of phi-functions; N = the size of the program (each phi operand counts); V = the number of names
Properties
deterministicofflineiterative

Sreedhar's out-of-SSA translation removes the phi-functions of a program in static single assignment form without splitting edges. It works in two steps. First it adds copies until the program is in conventional SSA form: no two names joined by phi-functions are live at the same time. Then it gives all the names of each such group one variable and deletes the phi-functions. Sreedhar, Ju, Gillies and Santhanam published it in 1999 with three ways to choose the copies. Method I copies every resource of every phi-function. Method III uses liveness and interference to copy only where it is needed. It solves the lost copy and swap problems, which break the older translation after copy folding.

In plain words

A phi-function joins several names into one value. If none of these names is ever needed while another one holds a different value, they can all share one variable, and the phi-function becomes nothing. Optimizations break this. For example, a loop may still read the old value of a counter after the new value is made. The fix is to add a copy that gives one of the names a short private life: just before the jump in the block that feeds the phi-function, or just after the phi-functions at the top of the block. A careful choice of copies leaves only a few. When no group has a conflict left, rename the group to one variable and drop the phi-functions.

The problem

The input is a strict SSA program. Phi-functions come first in each block and have one operand for each predecessor. An operand is a name or a constant. The output is an equivalent program with no phi-functions, as on the out-of-SSA translation page. The method must not split edges or add blocks.

Most of the terms below come from Sreedhar et al. The resources of the phi-function x0=ϕ(x1,…,xn)x_0 = \phi(x_1, \ldots, x_n) are its target x0x_0 and its operands xix_i, where xix_i comes from the predecessor LiL_i of the block L0L_0. The phi congruence classes are the classes of the smallest equivalence relation that relates each target to its operands. A name is live at a point if some path from there reads it before it is defined again. An operand xix_i is read at the end of LiL_i. Two names interfere if one is live just after the definition of the other. A program is conventional if no two names in one class interfere. Otherwise it is transformed. SSA form straight after construction is conventional. Copy propagation and the removal of trivial phi-functions can make it transformed.

The algorithm

For a resource ii of the current phi-function, LIVE(i)\mathrm{LIVE}(i) is the set of names that a new copy name for ii would interfere with. For an operand from LiL_i it is LiveOut(Li)\mathrm{LiveOut}(L_i) plus the names read by the terminator of LiL_i, because the copy goes just before the terminator. For the target it is the set of names live just after the phi-functions of L0L_0, plus the other phi targets of L0L_0 and the targets of the copies already placed after them, without x0x_0 itself.

  1. SREEDHAR-METHOD-III(P)
  2. 1make each name its own phi congruence class
  3. 2for each phi-function x0 = phi(x1 from L1, ..., xn from Ln) of P do
  4. 3compute liveness and the interference graph of P
  5. 4chosen <- the resources that are constants
  6. 5for each pair i < j of named resources with xi != xj do
  7. 6if no name in class(xi) interferes with a name in class(xj) then go to the next pair
  8. 7needI <- class(xi) ∩ LIVE(j) != {}; needJ <- class(xj) ∩ LIVE(i) != {}
  9. 8if needI then add i to chosen
  10. 9if needJ then add j to chosen
  11. 10if not needI and not needJ then record i and j as deferred neighbours
  12. 11for each deferred resource i, the one with most deferred neighbours first do
  13. 12if i is not in chosen and some neighbour of i is not in chosen then add i to chosen
  14. 13while some i in chosen and j not in chosen have class(xj) ∩ LIVE(i) != {} do
  15. 14add j to chosen
  16. 15for each chosen resource, add a copy and use the new name in the phi-function
  17. 16merge the classes of x0, x1, ..., xn
  18. 17give each class one variable, delete the phi-functions and the copies v <- v

Line L15 puts the copy for an operand xix_i as xi' = xi at the end of LiL_i, before its terminator. A constant operand gets xi' = k. The copy for the target puts x0 = x0' just after the phi-functions of L0L_0, and x0′x_0' becomes the target. The new names are fresh, so the program stays in SSA form. Method I skips lines L3 to L14 and chooses every resource. Lines L5 to L12 are the four cases of the paper: copy xix_i if its class is live where xjx_j is defined or read, copy xjx_j in the opposite case, copy both if both hold, and defer the pair if neither holds. Lines L13 and L14 are a closing step added in this implementation; Pitfalls explains why it is needed.

Line L17 picks the parameter of the class as its variable if there is one, otherwise the smallest name. The implementation computes liveness and interference again for each phi-function. The paper updates them in place.

Example

The lost copy. After copy propagation, the loop returns the old value of x from the last pass:

# params: n
B1:
  x.1 = 1
  jump B2
B2:
  x.2 = phi [B1: x.1, B2: x.3]
  x.3 = x.2 + 1
  t.1 = x.3 < n
  br t.1 B2 B3
B3:
  ret x.2

The one class is {x.2,x.1,x.3}\{x.2, x.1, x.3\}. For n=3n = 3 the program returns 2. If x.1, x.2 and x.3 simply become one variable, the add overwrites the value that B3 returns, and the result is 3.

  1. The resources are the target x.2, x.1 from B1, and x.3 from B2. x.2 and x.3 interfere: x.2 is live where x.3 is defined, because B3 reads it. x.1 interferes with neither.
  2. For the pair (x.2, x.3): LiveOut(B2)={x.2,x.3,n}\mathrm{LiveOut}(B2) = \{x.2, x.3, n\}, so the class of x.2 meets LIVE\mathrm{LIVE} of the operand from B2, and the target needs a copy. Just after the phi-function only n is live, so x.3 needs no copy.
  3. The closing step finds nothing. One copy goes in. The new target is x.2_1, and the class becomes {x.2_1,x.1,x.3}\{x.2\_1, x.1, x.3\}, while x.2 is now in no class.

The conventional program and the result of renaming the class to x.1:

B2:                                    B2:
  x.2_1 = phi [B1: x.1, B2: x.3]         x.2 = x.1
  x.2 = x.2_1                            x.1 = x.2 + 1
  x.3 = x.2 + 1                          t.1 = x.1 < n
  t.1 = x.3 < n                          br t.1 B2 B3
  br t.1 B2 B3                         B3:
                                         ret x.2

Cytron's translation would put the copy x.2 = x.3 at the end of B2, where it also runs when the loop exits. Here the copy sits at the top of B2, so the exit edge leaves x.2 alone. No edge was split.

The swap. In this loop the two phi-functions exchange a and b on each pass:

# params: n
B1:
  a.1 = 1
  b.1 = 2
  i.1 = 1
  jump B2
B2:
  a.2 = phi [B1: a.1, B2: b.2]
  b.2 = phi [B1: b.1, B2: a.2]
  i.2 = phi [B1: i.1, B2: i.3]
  i.3 = i.2 + 1
  t.1 = i.2 < n
  br t.1 B2 B3
B3:
  r.1 = a.2 * 10
  r.2 = r.1 + b.2
  ret r.2

For n=1,2,3n = 1, 2, 3 it returns 12, 21, 12. Naive renaming gives 22 for n=2n = 2.

  1. First phi-function: a.2 and b.2 are both phi targets of B2, and both are live in B3, so they interfere. a.2 is live out of B2, and b.2 is live just after the phi-functions. Both needs hold, so both the target a.2 and the operand b.2 from B2 are copied.
  2. Second phi-function: the same holds for b.2 and a.2. Two more copies.
  3. Third phi-function: i.2 interferes with i.3, because t.1 reads i.2 after i.3 is defined. But i.2 is not live out of B2, and i.3 is not live just after the phi-functions. So the pair is deferred, and line L12 copies the target i.2.

Method III adds 5 copies. Method I adds 9: one for each of the 6 operands and one for each of the 3 targets. After renaming, B2 is:

B2:
  a.2 = a.1
  b.2 = a.2_4
  i.2 = i.1
  i.1 = i.2 + 1
  t.1 = i.2 < n
  a.1 = b.2
  a.2_4 = a.2
  br t.1 B2 B3

The class of b.1 was named a.2_4, the smallest of its names, and B1 now sets a.2_4 = 2. The swap is correct because the top copies save the two values in a.2 and b.2 before the bottom copies overwrite the loop variables. No temporary is needed, and no edge is split.

Correctness

The full proof is in the proof file. It has three parts.

  • Renaming a conventional program is correct. By induction over a run, every live name has its value in the variable of its class. A write to the variable of a class cannot destroy the value of another live name of the same class, because that name would be live just after the definition, so the two would interfere. On an edge, each phi target already has the value of its operand in the shared variable.
  • Copies keep the meaning. An operand copy reads the operand at the same point the phi-function did. A target copy passes the value on before any old instruction of the block. Copies never make two old names interfere, because they only move a use earlier or a definition later past other copies.
  • The merged class is free of interference. A new name for an operand lives only from its copy to the end of LiL_i, and a new name for a target only from the phi-functions to its copy. So it interferes only with names in LIVE(i)\mathrm{LIVE}(i). Two old classes that interfered are split by lines L8 to L12. A new name against a class that was not copied is handled by lines L13 and L14. Two new names never overlap.
Proof: Correctness of Sreedhar's out-of-SSA translationfull

We prove that the translation in impl/python/sreedhar_cssa_translation.py is correct. There are two parts. First, renaming the phi congruence classes of a program in conventional SSA form keeps its meaning. Second, Methods I and III add copies that keep the meaning and make the program conventional. Together they show that sreedhar_out_of_ssa returns a program without phi-functions that follows the same blocks and gives the same result as its input on every run.

Setting

The input PP is in strict SSA form. Each name has one definition: a parameter is defined at the top of the entry rr, a phi target at the phi point of its block (just after all phi-functions), and any other name at its instruction. The phi-functions of a block bb have one operand for each predecessor. On the edge (p,b)(p, b), all of them read their operand for pp at the end of pp, and then all of them write their targets at the phi point of bb.

A name xx is live at a point qq if some path from qq reaches a use of xx without passing the definition of xx. The operand of a phi-function for the predecessor pp is used at the end of pp. Two names u≠wu \ne w interfere if uu is live just after the definition of ww, or ww just after the definition of uu. Note that a dead definition still interferes with the names live at it, because it writes its variable.

The phi congruence classes are the classes of the smallest equivalence relation in which each phi target is related to each of its name operands. PP is conventional if no two names in one class interfere and every phi operand is a name.

Fact 0. If xx is live at a point qq of a run of a strict program, then the definition of xx ran before qq, and xx has been live at every point since its last run.

Proof. Take a path from qq to a use of xx that avoids the definition. Joined to the run up to qq, it is a path from rr to the use. The definition dominates the use, so it lies on the run up to qq. From its last run to qq, the run followed by the same path reaches the use without the definition, so xx is live at each point between. □\square

Part 1: renaming a conventional program

rename_classes maps every name xx to a representative rep(x)\mathrm{rep}(x) of its class: the smallest parameter in the class if there is one, otherwise the smallest name. Names in no class keep their names. It deletes the phi-functions and the copies that become y = y. Call the result QQ.

Theorem 1. If PP is conventional, then on every input QQ follows the same sequence of blocks as PP, and it returns the same value, traps at the same instruction, or runs forever when PP does.

Proof. We show by induction over the steps of the two runs that they are in the same block and that this invariant holds:

(I) for every name xx live at the current point of PP, the variable rep(x)\mathrm{rep}(x) in QQ holds the value of xx in PP.

Start. Only parameters are live at the top of rr, by Fact 0. Let xx be a live parameter. Every other parameter yy is defined at the same point, and xx is live just after it, so xx and yy interfere. As PP is conventional, yy is not in the class of xx, so rep(x)=x\mathrm{rep}(x) = x. QQ binds xx to the same argument.

An instruction d=f(a,b)d = f(a, b). Its operands are live just before it, so by (I) QQ reads the same values, and computes the same value or traps in the same way. QQ writes rep(d)\mathrm{rep}(d). Let x≠dx \ne d be live just after the instruction. If rep(x)=rep(d)\mathrm{rep}(x) = \mathrm{rep}(d), then xx and dd are in one class, and xx is live just after the definition of dd, so they interfere; that is impossible. So the write clobbers no live name, and (I) holds after the step. A copy d=sd = s with rep(d)=rep(s)\mathrm{rep}(d) = \mathrm{rep}(s) is deleted in QQ; then rep(d)\mathrm{rep}(d) already holds the value of ss, which is the value of dd.

A terminator. Its operand is live just before it, so by (I) both runs take the same branch or return the same value.

An edge (p,b)(p, b). Let x1,…,xmx_1, \ldots, x_m be the phi targets of bb, and aia_i the operand of xix_i for pp. In PP, each xix_i gets the value that aia_i has at the end of pp. QQ does nothing on the edge. Let yy be live at the phi point of bb. If yy is a target xix_i, then rep(xi)=rep(ai)\mathrm{rep}(x_i) = \mathrm{rep}(a_i), as they are in one class, and aia_i is live at the end of pp, so by (I) that variable holds the right value. If yy is not a target, then yy is live on entry to bb and so at the end of pp, its value does not change on the edge, and by (I) rep(y)\mathrm{rep}(y) holds it already. A dead target needs no value. As QQ writes no variable on the edge, (I) holds at the phi point.

So the invariant holds at every step, and the runs agree. □\square

Part 2: the copies

to_cssa handles the phi-functions one at a time. For the kk-th phi-function of block L0L_0, with target x0x_0 and operand xix_i from predecessor LiL_i, a copy on the target replaces x0x_0 by a new name x0′x_0' in the phi-function and puts x0 = x0' after the phi-functions of L0L_0 and after the copies already there. A copy on the operand xix_i puts xi' = xi (or xi' = k for a constant) at the end of LiL_i, before its terminator, and makes xi′x_i' the operand. Then the classes of all resources of the phi-function are merged (line L16).

Lemma 2 (meaning). Each copy keeps the program in strict SSA form and keeps its meaning.

Proof. The new name xi′x_i' is defined at the end of LiL_i and read there by the phi-function, with no definition of xix_i in between, so the phi-function gets the same value. The new name x0′x_0' gets the value x0x_0 used to get, and x0 = x0' passes it on before any instruction of L0L_0 that came from PP. Every use of x0x_0 was dominated by the phi point of L0L_0, so it comes after this copy or in a block dominated by L0L_0; the program stays strict. Each new name has one definition. □\square

Lemma 3 (old names). Adding a copy never makes two old names interfere that did not interfere before.

Proof. The copy xi' = xi at the end of LiL_i moves the use of xix_i from the end of LiL_i to just before the terminator. Live ranges of old names can only shrink, and no old name gets a new definition. The copy x0 = x0' moves the definition of x0x_0 from the phi point to a later point of L0L_0, with only copies to new names or to other targets in between. The old names live just after the new definition of x0x_0 are the old names that were live just after the phi point, other than x0x_0. So x0x_0 interferes with no new old name, and its own live range only shrinks. □\square

Lemma 4 (new names). At the moment it is added:

  • the new name xi′x_i' of an operand from LiL_i interferes exactly with the names live just before the terminator of LiL_i, that is LiveOut(Li)\mathrm{LiveOut}(L_i) plus the operand of the terminator;
  • the new name x0′x_0' of a target interferes only with names that are live just after the phi-functions of L0L_0, are phi targets of L0L_0, or are targets of the copies already placed after them.

Later, a new name can interfere only with a name defined later between its definition and its last use, and that is again a copy at the end of LiL_i or after the phi-functions of L0L_0. Lemma 4 for that later copy covers the pair.

Proof. xi′x_i' is live from its definition to the end of LiL_i, where only the terminator follows. x0′x_0' is live from the phi point to its copy; the definitions in between are the other phi targets and the earlier copies. □\square

These sets are exactly the sets near[i] in _choose: LIVE(i)\mathrm{LIVE}(i) in the pseudocode.

Invariant J. After each phi-function is handled, no two names in one class of the union-find interfere.

Theorem 5. Invariant J holds for Method I and for Method III.

Proof. Before the first phi-function every class is a single name. Assume J before the kk-th phi-function. By Lemma 3 the copies add no interference between old names, so the classes not touched by the merge stay free of interference; the new names are only in the merged class MM. It remains to show that MM has no interfering pair.

Method I. Every resource is copied, so M={x0′,x1′,…,xn′}M = \{x_0', x_1', \ldots, x_n'\}. Two operand names xi′x_i' and xj′x_j' live only at the ends of two different predecessors. x0′x_0' dies at the top of L0L_0 and every xi′x_i' is born at the end of a block, after that point when Li=L0L_i = L_0. So no two of them are live at the same point, and none interferes with another.

Method III. Let CC be the set of copied resources when line L14 ends. MM is the union of the classes of the resources not in CC and the new names of the resources in CC. Take two names in MM.

  1. Both in the class of one resource j∉Cj \notin C: no interference, by J and Lemma 3.
  2. In the classes of two resources j,l∉Cj, l \notin C that are different: if the classes interfered before the copies, line L6 saw the pair. Then lines L8 and L9 copy at least one of them, or the pair is deferred at line L10. For a deferred pair, line L12 copies the first of the two in its order if neither is copied yet. Either way jj or ll is in CC, which is false. So the classes did not interfere before, and by Lemma 3 they do not interfere now.
  3. The new name of i∈Ci \in C and a name ww in the class of j∉Cj \notin C: by Lemma 4, they interfere only if w∈LIVE(i)w \in \mathrm{LIVE}(i). But then lines L13 and L14 put jj into CC, which is false.
  4. The new names of i,i′∈Ci, i' \in C: they do not interfere, as for Method I.

So MM has no interfering pair, and J holds after the merge. □\square

Each phi-function is handled once, and later steps change only their own phi-function. So at the end the classes of the union-find hold the phi congruence classes of the result, and every constant operand has been replaced by a copy. By Theorem 5, the result of to_cssa is conventional.

The whole translation

Theorem 6. For a strict SSA program PP and either method, sreedhar_out_of_ssa(P) returns a program with no phi-functions that follows the same blocks as PP on every input and returns the same value, traps at the same point, or runs forever when PP does.

Proof. By Lemma 2 the program after to_cssa has the meaning of PP and is strict. By Theorem 5 it is conventional. By Theorem 1, rename_classes keeps its meaning. □\square

Corollary 7. If PP is conventional and has no constant phi operands, Method III adds no copies.

Proof. Each class built during the run is part of a phi congruence class of PP, by induction, so no two classes that line L6 compares ever interfere. No resource is copied at lines L4 to L12, so CC is empty and line L14 adds nothing. □\square

Counting

Method I adds one copy per phi operand and one per phi-function. Method III copies a subset of the same resources, so it never adds more. The tests compare both counts on random programs, and check the result with a brute-force interference test that follows paths.

Running time

The implementation computes liveness and the interference graph again for each phi-function. Liveness by round-robin iteration takes O(n⋅(I+V))O(n \cdot (I + V)) set operations per pass for nn blocks, II instructions and VV names, and the interference graph has O(V2)O(V^2) edges. Sreedhar et al. update both in place as copies are added, which is what makes the method practical on large procedures.

Complexity

Let NN be the size of the program, counting each phi operand, VV the number of names, BB the number of blocks and FF the number of phi-functions.

  • Method I adds one copy for each phi operand and one for each phi-function, in Θ(N)\Theta(N) time, with no analysis.
  • Liveness. The implementation runs the round-robin live variable analysis once per phi-function. With sets of names, this is O(BNV)O(BNV) per run in the worst case, so O(FBNV)O(FBNV) in total. The interference graph adds O(NV)O(NV) per run.
  • Choosing copies. A phi-function with kk resources checks O(k2)O(k^2) pairs, and each check compares two classes in O(V2)O(V^2) time. Summed over all phi-functions, ∑k2≤N2\sum k^2 \le N^2.
  • Space. The interference graph takes O(V2)O(V^2).

The paper builds liveness and the interference graph once, and updates both as each copy is added. That makes the method practical for large procedures.

Properties

  • No edge splitting. All copies go into existing blocks, so it also works on edges that cannot be split.
  • Method III never adds more copies than Method I. It copies a subset of the same resources.
  • No copies on conventional input. If the program is conventional and has no constant operands, no pair passes line L6, and Method III adds nothing.
  • Order dependent. The copies chosen depend on the order of the phi-functions and on the deferred choice at line L11.
  • Copies in sequence are enough. The copies of one edge go into different places, at the end of LiL_i or at the top of L0L_0, and each writes a fresh name. So there is no parallel copy to order, and no swap cycle that needs a temporary.

Variants and improvements

  • Method I. Copy every resource. It is simple and always correct, and it leaves the removal of copies to a later coalescing pass.
  • Method II. The paper's second method uses the interference graph to choose the copies, without the liveness tests of Method III.
  • Coalescing on classes. The paper also removes copies after the translation by merging phi congruence classes that do not interfere. See the register coalescing problem.
  • Boissinot et al. (2009). They start from Method I with parallel copies, then coalesce with an interference test that uses the values of names and the dominance order of definitions, in place of a full interference graph.
  • Register allocation on SSA. An SSA-based register allocator assigns registers before leaving SSA form. The phi-functions then become parallel copies between registers.

When to use it

Use it when the program is in transformed SSA form after copy propagation or value numbering, and edge splitting is costly or not possible. Method I with a strong coalescer is the simplest correct choice. Method III gives few copies from the start, at the cost of liveness and an interference graph. If edges can be split freely, splitting critical edges and ordering the copies of each edge as a parallel copy is the simpler way.

Pitfalls

  • The four cases alone are not enough. They look only at pairs whose classes already interfere. A copy gives a resource a new name, and that new name can interfere with the class of a resource that was not copied. For example, a constant operand always gets a copy, and its new name is live at the end of its block together with whatever is live there. Lines L13 and L14 add copies until no new name is live where a class that was not copied is.
  • The wrong live set for the target. The new target is live from the phi-functions to its copy. Every other phi target of the block and every earlier copy at the top is defined there. A dead phi target still writes its variable, so it counts too.
  • Uses in the terminator. An operand copy goes before the terminator, so the names that the terminator reads are live where the new name is born. LiveOut(Li)\mathrm{LiveOut}(L_i) alone misses them.
  • Stale liveness. Each copy changes liveness. Either compute it again, as the implementation does, or update it, as the paper does.
  • Constant operands. A constant has no variable. It must become a copy into a new name before the class can be renamed.
  • Choosing the class variable. If a class has a parameter, the parameter must be its variable, because the entry block already holds the value there.

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.

sreedhar_cssa_translation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sreedhar-cssa-translation/. The authors are listed in prov/N0QEY1.jsonl.
"""Translation out of SSA form by Sreedhar, Ju, Gillies and Santhanam (1999).

The input is a strict SSA program in the toy IR. Phi-functions come first in
each block and have one operand for each predecessor. Method I puts a copy on
every resource of every phi-function. Method III uses liveness and
interference to copy only the resources that need it. Both give conventional
SSA form: no two names in one phi congruence class interfere. Then each class
gets one variable and the phi-functions are dropped. No edge is split.

A phi-function reads its operand for the predecessor p at the end of p, so
that operand is live out of p. A copy for the operand from p goes at the end
of p, before the terminator. A copy for the target goes right after the
phi-functions of its block. Two names interfere when one is live just after
the definition of the other. Liveness and interference are computed again
for each phi-function; the paper updates them in place instead.

The four cases of Method III look only at pairs of resources whose classes
interfere already. A copy gives a resource a new name, and that name can
interfere with the class of a resource that was left alone. So a closing
step also copies every resource whose class is live where a copied resource
gets its new name. Constant operands always get a copy.
"""

import toyir
from toyir import Block, Program


class Classes:
    """Union-find over names. The sets are the phi congruence classes."""

    def __init__(self):
        self.parent = {}
        self.members = {}

    def find(self, x):
        if x not in self.parent:
            self.parent[x] = x
            self.members[x] = {x}
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:
            self.parent[x], x = root, self.parent[x]
        return root

    def of(self, x):
        return self.members[self.find(x)]

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[rb] = ra
            self.members[ra] |= self.members.pop(rb)


class _State:
    """The program while copies go in: phi-functions, body and terminator
    of each block, kept apart."""

    def __init__(self, prog):
        pred = toyir.preds(prog)
        self.params = list(prog.params)
        self.order = list(prog.blocks)
        self.phis, self.body, self.top, self.term, self.succ = {}, {}, {}, {}, {}
        self.names = set(prog.params)
        for label, b in prog.blocks.items():
            k = 0
            while k < len(b.instrs) and b.instrs[k][0] == "phi":
                k += 1
            for ins in b.instrs:
                if ins[0] not in ("phi", "const", "copy", "op"):
                    raise ValueError("unsupported instruction %r" % (ins,))
                self.names.add(ins[1])
            if any(ins[0] == "phi" for ins in b.instrs[k:]):
                raise ValueError("phi after a non-phi instruction in %s" % label)
            for ins in b.instrs[:k]:
                if set(ins[2]) != set(pred[label]):
                    raise ValueError("phi %s needs one operand per predecessor" % ins[1])
            self.phis[label] = [[ins[1], dict(ins[2])] for ins in b.instrs[:k]]
            self.body[label] = list(b.instrs[k:])
            self.top[label] = 0  # copies for targets placed so far
            self.term[label] = b.term
            self.succ[label] = toyir.succs(prog, label)
        self.serial = 0
        self.copies = 0

    def fresh(self, base):
        while True:
            self.serial += 1
            name = "%s_%d" % (base, self.serial)
            if name not in self.names:
                self.names.add(name)
                return name

    def slots(self, label, k):
        """The resources of the k-th phi of label: (None, target) first, then
        (pred, operand) for each predecessor."""
        dest, ops = self.phis[label][k]
        return [(None, dest)] + list(ops.items())

    def program(self):
        blocks = {}
        for label in self.order:
            phis = [("phi", d, dict(ops)) for d, ops in self.phis[label]]
            blocks[label] = Block(phis + list(self.body[label]), self.term[label])
        return Program(list(self.params), blocks)


def liveness(st):
    """live_out[b], and after[b]: the names live just after the phis of b."""
    up, kill = {}, {}
    for b in st.order:
        u, d = set(), set()
        for ins in st.body[b]:
            u |= {a for a in toyir.uses(ins) if a not in d}
            d.add(ins[1])
        u |= {a for a in toyir.term_uses(st.term[b]) if a not in d}
        up[b], kill[b] = u, d
    live_in = {b: set() for b in st.order}
    live_out = {b: set() for b in st.order}
    after = {b: set() for b in st.order}
    changed = True
    while changed:
        changed = False
        for b in reversed(st.order):
            out = set()
            for s in st.succ[b]:
                out |= live_in[s]
                out |= {ops[b] for _, ops in st.phis[s] if isinstance(ops[b], str)}
            aft = up[b] | (out - kill[b])
            inn = aft - {d for d, _ in st.phis[b]}
            if out != live_out[b] or inn != live_in[b]:
                changed = True
            live_out[b], after[b], live_in[b] = out, aft, inn
    return live_out, after


def interference(st, live_out, after):
    """Name -> the names that interfere with it."""
    g = {}

    def add(a, b):
        if a != b:
            g.setdefault(a, set()).add(b)
            g.setdefault(b, set()).add(a)

    for b in st.order:
        live = set(live_out[b]) | set(toyir.term_uses(st.term[b]))
        for ins in reversed(st.body[b]):
            for x in live:
                add(ins[1], x)
            live.discard(ins[1])
            live |= set(toyir.uses(ins))
        for d, _ in st.phis[b]:
            for x in live:
                add(d, x)
    for p in st.params:
        for x in after[st.order[0]]:
            add(p, x)
    return g


def _classes_interfere(a, b, g):
    return any(g.get(u, set()) & b for u in a)


def _insert(st, label, k, chosen):
    """Put a copy on each chosen resource of the k-th phi of label."""
    phi = st.phis[label][k]
    for i, (p, r) in enumerate(st.slots(label, k)):
        if i not in chosen:
            continue
        if p is None:
            new = st.fresh(r)
            st.body[label].insert(st.top[label], ("copy", r, new))
            st.top[label] += 1
            phi[0] = new
        else:
            new = st.fresh(r if isinstance(r, str) else "k")
            st.body[p].append(("const", new, r) if isinstance(r, int) else ("copy", new, r))
            phi[1][p] = new
        st.copies += 1


def _choose(st, label, k, classes):
    """Method III: the resources of one phi-function that need a copy."""
    live_out, after = liveness(st)  # @line L3
    g = interference(st, live_out, after)
    slots = st.slots(label, k)
    n = len(slots)
    # The names that a new copy name for slot i would interfere with. For an
    # operand from p: the names live just before the terminator of p. For
    # the target: the names live just after the phis, the other phi targets
    # (a dead one still writes its variable), and the targets of the copies
    # already placed after the phis.
    top = set(after[label]) | {d for d, _ in st.phis[label]}
    top |= {ins[1] for ins in st.body[label][: st.top[label]]}
    top.discard(slots[0][1])
    near = [top] + [live_out[p] | set(toyir.term_uses(st.term[p])) for p, _ in slots[1:]]

    def live_at(i):
        return near[i]

    chosen = {i for i in range(n) if not isinstance(slots[i][1], str)}  # @line L4
    deferred = {}
    for i in range(n):  # @line L5
        for j in range(i + 1, n):
            xi, xj = slots[i][1], slots[j][1]
            if not isinstance(xi, str) or not isinstance(xj, str) or xi == xj:
                continue
            ci, cj = classes.of(xi), classes.of(xj)
            if not _classes_interfere(ci, cj, g):  # @line L6
                continue
            need_i = bool(ci & live_at(j))  # @line L7
            need_j = bool(cj & live_at(i))
            if need_i:
                chosen.add(i)  # @line L8
            if need_j:
                chosen.add(j)  # @line L9
            if not need_i and not need_j:
                deferred.setdefault(i, set()).add(j)  # @line L10
                deferred.setdefault(j, set()).add(i)
    for i in sorted(deferred, key=lambda i: (-len(deferred[i]), i)):  # @line L11
        if i not in chosen and any(j not in chosen for j in deferred[i]):
            chosen.add(i)  # @line L12
    grown = True
    while grown:  # @line L13
        grown = False
        for i in sorted(chosen):
            for j in range(n):
                if j not in chosen and classes.of(slots[j][1]) & live_at(i):
                    chosen.add(j)  # @line L14
                    grown = True
    return chosen


def to_cssa(prog, method=3):
    """Copies that make prog conventional. Returns (program, number of copies)."""
    if method not in (1, 3):
        raise ValueError("method must be 1 or 3")
    st = _State(prog)
    classes = Classes()  # @line L1
    for label in st.order:
        for k in range(len(st.phis[label])):  # @line L2
            if method == 1:
                chosen = set(range(len(st.slots(label, k))))
            else:
                chosen = _choose(st, label, k, classes)
            _insert(st, label, k, chosen)  # @line L15
            names = [r for _, r in st.slots(label, k)]
            for r in names[1:]:
                classes.union(names[0], r)  # @line L16
    return st.program(), st.copies


def phi_classes(prog):
    """The phi congruence classes of prog, as a Classes object."""
    classes = Classes()
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] == "phi":
                for a in ins[2].values():
                    if isinstance(a, str):
                        classes.union(ins[1], a)
    return classes


def rename_classes(cssa):
    """Give each phi congruence class one variable and drop the phi-functions
    and the copies x = x. Correct when cssa is conventional."""
    classes = phi_classes(cssa)  # @line L17
    params = set(cssa.params)
    rep = {}
    for root, members in classes.members.items():
        named = sorted(members & params) or sorted(members)
        for x in members:
            rep[x] = named[0]

    def m(a):
        return rep.get(a, a) if isinstance(a, str) else a

    blocks = {}
    for label, b in cssa.blocks.items():
        out = []
        for ins in b.instrs:
            if ins[0] == "phi":
                continue
            if ins[0] == "const":
                out.append(("const", m(ins[1]), ins[2]))
            elif ins[0] == "copy":
                if m(ins[1]) != m(ins[2]):
                    out.append(("copy", m(ins[1]), m(ins[2])))
            else:
                out.append(("op", m(ins[1]), ins[2], m(ins[3]), m(ins[4])))
        t = b.term
        if t[0] in ("br", "ret"):
            t = (t[0], m(t[1])) + tuple(t[2:])
        blocks[label] = Block(out, t)
    return Program(list(cssa.params), blocks)


def sreedhar_out_of_ssa(prog, method=3):
    """Translate prog out of SSA form. Returns (program, copies inserted)."""
    cssa, copies = to_cssa(prog, method)
    return rename_classes(cssa), copies
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_sreedhar_cssa_translation.py 370 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sreedhar-cssa-translation/. The authors are listed in prov/N0QEY1.jsonl.

import random

import toyir
from sreedhar_cssa_translation import rename_classes, sreedhar_out_of_ssa, to_cssa

LOST_COPY = """
# params: n
B1:
  x.1 = 1
  jump B2
B2:
  x.2 = phi [B1: x.1, B2: x.3]
  x.3 = x.2 + 1
  t.1 = x.3 < n
  br t.1 B2 B3
B3:
  ret x.2
"""

SWAP = """
# params: n
B1:
  a.1 = 1
  b.1 = 2
  i.1 = 1
  jump B2
B2:
  a.2 = phi [B1: a.1, B2: b.2]
  b.2 = phi [B1: b.1, B2: a.2]
  i.2 = phi [B1: i.1, B2: i.3]
  i.3 = i.2 + 1
  t.1 = i.2 < n
  br t.1 B2 B3
B3:
  r.1 = a.2 * 10
  r.2 = r.1 + b.2
  ret r.2
"""

DIAMOND = """
# params: c
B1:
  br c B2 B3
B2:
  x.1 = 1
  jump B4
B3:
  x.2 = 2
  jump B4
B4:
  x.3 = phi [B2: x.1, B3: x.2]
  ret x.3
"""


# ------------------------------------------------------- building TSSA input


def _rename(ins, m, d):
    if ins[0] == "const":
        return ("const", d, ins[2])
    if ins[0] == "copy":
        return ("copy", d, m(ins[2]))
    return ("op", d, ins[2], m(ins[3]), m(ins[4]))


def _rename_term(t, m):
    return (t[0], m(t[1])) + tuple(t[2:]) if t[0] in ("br", "ret") else t


def maximal_ssa(prog):
    """SSA form with a phi-function for every variable at the top of every
    block but the entry. A variable that is not a parameter starts as v.0 = 0
    at the top of the entry. This form is conventional."""
    pred = toyir.preds(prog)
    names = set(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            names.add(ins[1])
            names.update(toyir.uses(ins))
        names.update(toyir.term_uses(b.term))
    names = sorted(names)
    count = {}
    end = {}
    blocks = {}
    for label, b in prog.blocks.items():
        instrs = []
        if label == prog.entry:
            cur = {}
            for v in names:
                if v in prog.params:
                    cur[v] = v
                else:
                    cur[v] = v + ".0"
                    instrs.append(("const", v + ".0", 0))
        else:
            cur = {v: "%s.%s" % (v, label) for v in names}
        for ins in b.instrs:
            v = ins[1]
            count[v] = count.get(v, 0) + 1
            d = "%s.%d" % (v, count[v])
            instrs.append(_rename(ins, lambda a: cur[a] if isinstance(a, str) else a, d))
            cur[v] = d
        end[label] = cur
        blocks[label] = toyir.Block(instrs, _rename_term(b.term, lambda a: cur[a] if isinstance(a, str) else a))
    for label, b in blocks.items():
        if label != prog.entry:
            phis = [("phi", "%s.%s" % (v, label), {p: end[p][v] for p in pred[label]}) for v in names]
            b.instrs[0:0] = phis
    return toyir.Program(list(prog.params), blocks)


def fold(ssa, constants=False):
    """Copy folding and removal of trivial phi-functions, until nothing
    changes. This is what makes SSA form transformed. With constants=True,
    phi operands defined by a constant become that constant."""
    blocks = {label: toyir.Block(list(b.instrs), b.term) for label, b in ssa.blocks.items()}
    repl = {}

    def r(a):
        while isinstance(a, str) and a in repl:
            a = repl[a]
        return a

    changed = True
    while changed:
        changed = False
        for b in blocks.values():
            out = []
            for ins in b.instrs:
                if ins[0] == "copy":
                    repl[ins[1]] = r(ins[2])
                    changed = True
                    continue
                if ins[0] == "phi":
                    ops = {p: r(a) for p, a in ins[2].items()}
                    others = set(ops.values()) - {ins[1]}
                    if len(others) == 1:
                        repl[ins[1]] = others.pop()
                        changed = True
                        continue
                    ins = ("phi", ins[1], ops)
                out.append(ins)
            b.instrs = out
    const = {ins[1]: ins[2] for b in blocks.values() for ins in b.instrs if ins[0] == "const"}
    for b in blocks.values():
        out = []
        for ins in b.instrs:
            if ins[0] == "phi":
                ops = {p: r(a) for p, a in ins[2].items()}
                if constants:
                    ops = {p: const.get(a, a) for p, a in ops.items()}
                out.append(("phi", ins[1], ops))
            else:
                out.append(_rename(ins, r, ins[1]))
        b.instrs = out
        b.term = _rename_term(b.term, r)
    return toyir.Program(list(ssa.params), blocks)


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


def _live_from(prog, succ, label, start, name):
    """Is name read on some path that starts at instruction start of label,
    before it is defined again? A phi operand is read at the end of its
    predecessor."""
    stack, seen = [(label, start)], set()
    while stack:
        b, i = stack.pop()
        if (b, i) in seen:
            continue
        seen.add((b, i))
        blk = prog.blocks[b]
        killed = False
        for ins in blk.instrs[i:]:
            if name in toyir.uses(ins):
                return True
            if ins[1] == name:
                killed = True
                break
        if killed:
            continue
        if name in toyir.term_uses(blk.term):
            return True
        for s in succ[b]:
            phis = [ins for ins in prog.blocks[s].instrs if ins[0] == "phi"]
            if any(ins[2][b] == name for ins in phis):
                return True
            if not any(ins[1] == name for ins in phis):
                stack.append((s, len(phis)))
    return False


def brute_interferes(prog):
    """A function telling whether two names interfere: one is live just after
    the definition of the other."""
    succ = {label: toyir.succs(prog, label) for label in prog.blocks}
    site = {p: (prog.entry, 0) for p in prog.params}
    for label, b in prog.blocks.items():
        nphi = sum(1 for ins in b.instrs if ins[0] == "phi")
        for k, ins in enumerate(b.instrs):
            site[ins[1]] = (label, nphi if ins[0] == "phi" else k + 1)

    def interferes(u, w):
        if u == w:
            return False
        return _live_from(prog, succ, *site[w], u) or _live_from(prog, succ, *site[u], w)

    return interferes


def brute_classes(prog):
    parent = {}

    def find(x):
        parent.setdefault(x, x)
        while parent[x] != x:
            x = parent[x]
        return x

    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] == "phi":
                for a in ins[2].values():
                    if isinstance(a, str):
                        parent[find(a)] = find(ins[1])
    out = {}
    for x in parent:
        out.setdefault(find(x), []).append(x)
    return list(out.values())


def is_conventional(prog):
    interferes = brute_interferes(prog)
    for cls in brute_classes(prog):
        for i, u in enumerate(cls):
            for w in cls[i + 1 :]:
                if interferes(u, w):
                    return False
    return all(isinstance(a, str) for b in prog.blocks.values() for ins in b.instrs if ins[0] == "phi" for a in ins[2].values())


def single_assignment(prog):
    seen = set(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[1] in seen:
                return False
            seen.add(ins[1])
    return True


def tssa_programs(seed, count):
    rng = random.Random(seed)
    for k in range(count):
        prog = toyir.random_program(rng, 4, rng.randint(3, 7), acyclic=(k % 4 == 0))
        yield rng, prog, fold(maximal_ssa(prog), constants=(k % 2 == 1))


def phi_operands(prog):
    return sum(len(ins[2]) + 1 for b in prog.blocks.values() for ins in b.instrs if ins[0] == "phi")


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


def test_lost_copy():
    ssa = toyir.parse(LOST_COPY)
    assert not is_conventional(ssa)
    # Renaming without copies loses the old value of x: 3 instead of 2.
    assert toyir.run(ssa, [3]) == ("ret", 2)
    assert toyir.run(rename_classes(ssa), [3]) == ("ret", 3)
    cssa, copies = to_cssa(ssa)
    assert copies == 1
    assert is_conventional(cssa)
    out = rename_classes(cssa)
    assert toyir.show(out) == (
        "# params: n\nB1:\n  x.1 = 1\n  jump B2\nB2:\n  x.2 = x.1\n  x.1 = x.2 + 1\n"
        "  t.1 = x.1 < n\n  br t.1 B2 B3\nB3:\n  ret x.2\n"
    )
    for n in range(-1, 8):
        assert toyir.run(out, [n]) == toyir.run(ssa, [n])


def test_swap():
    ssa = toyir.parse(SWAP)
    assert not is_conventional(ssa)
    assert toyir.run(rename_classes(ssa), [2]) == ("ret", 22)
    out, copies = sreedhar_out_of_ssa(ssa)
    assert copies == 5
    _, copies1 = sreedhar_out_of_ssa(ssa, method=1)
    assert copies1 == 9
    assert [toyir.run(out, [n])[1] for n in range(1, 6)] == [12, 21, 12, 21, 12]
    for n in range(-1, 8):
        assert toyir.run(out, [n]) == toyir.run(ssa, [n])


def test_conventional_input_needs_no_copies():
    ssa = toyir.parse(DIAMOND)
    out, copies = sreedhar_out_of_ssa(ssa)
    assert copies == 0
    assert toyir.show(out) == "# params: c\nB1:\n  br c B2 B3\nB2:\n  x.1 = 1\n  jump B4\nB3:\n  x.1 = 2\n  jump B4\nB4:\n  ret x.1\n"
    rng = random.Random(11)
    for k in range(40):
        prog = toyir.random_program(rng, 4, rng.randint(3, 6), acyclic=(k % 3 == 0))
        ssa = maximal_ssa(prog)
        assert is_conventional(ssa)
        out, copies = sreedhar_out_of_ssa(ssa)
        assert copies == 0
        for _ in range(3):
            args = [rng.randint(-3, 6), rng.randint(-3, 6)]
            assert toyir.run(out, args) == toyir.run(prog, args)


def test_result_is_conventional():
    transformed = 0
    for _, prog, ssa in tssa_programs(1, 60):
        transformed += not is_conventional(ssa)
        for method in (1, 3):
            cssa, _ = to_cssa(ssa, method)
            assert single_assignment(cssa)
            assert is_conventional(cssa)
    assert transformed > 20


def test_same_results_as_the_original_program():
    for rng, prog, ssa in tssa_programs(2, 80):
        out1, _ = sreedhar_out_of_ssa(ssa, method=1)
        out3, _ = sreedhar_out_of_ssa(ssa, method=3)
        for out in (out1, out3):
            assert not any(ins[0] == "phi" for b in out.blocks.values() for ins in b.instrs)
        for _ in range(4):
            args = [rng.randint(-3, 6), rng.randint(-3, 6)]
            want = toyir.run(prog, args)
            assert toyir.run(ssa, args) == want
            assert toyir.run(out1, args) == want
            assert toyir.run(out3, args) == want


def test_method_three_copies_at_most_method_one():
    fewer = 0
    for _, _, ssa in tssa_programs(3, 60):
        _, c1 = to_cssa(ssa, method=1)
        _, c3 = to_cssa(ssa, method=3)
        assert c1 == phi_operands(ssa)
        assert c3 <= c1
        fewer += c3 < c1
    assert fewer > 30


def test_rejects_bad_input():
    bad = [
        "B1:\n  jump B2\nB2:\n  y = 1\n  x = phi [B1: 1]\n  ret x\n",
        "# params: c\nB1:\n  br c B2 B3\nB2:\n  jump B3\nB3:\n  x = phi [B2: 1]\n  ret x\n",
    ]
    for text in bad:
        try:
            to_cssa(toyir.parse(text))
        except ValueError:
            continue
        assert False, text
    try:
        to_cssa(toyir.parse(DIAMOND), method=2)
    except ValueError:
        return
    assert False

History

Cytron, Ferrante, Rosen, Wegman and Zadeck (1991) translated out of SSA form with copies at the ends of the predecessors. Briggs, Cooper, Harvey and Simpson (1998) showed that this fails after copy folding, with the lost copy and swap problems, and fixed it with liveness and ordered copies. Sreedhar, Ju, Gillies and Santhanam (SAS 1999) gave the terms conventional and transformed SSA and phi congruence class. They showed that renaming is enough for conventional SSA, and gave three methods that reach it with copies alone. Boissinot, Darte, Rastello, Dupont de Dinechin and Guillon (CGO 2009) revisited the approach. They made Method I with parallel copies the starting point and moved the work to a fast coalescer. The SSA book edited by Rastello and Bouchez Tichadou (2022) presents both.

References

  1. Vugranam C. Sreedhar, Roy Dz-Ching Ju, David M. Gillies and Vatsa Santhanam, Translating out of static single assignment form, Static Analysis Symposium (SAS 1999), LNCS 1694, conventional and transformed SSA form, phi congruence classes, Method I (copies for every resource), Method II (guided by the interference graph), Method III (guided by liveness and the interference graph, with four cases and deferred pairs), and copy coalescing on phi congruence classes
  2. 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, the lost copy and swap problems, which the method solves without splitting edges
  3. Benoit Boissinot, Alain Darte, Fabrice Rastello, Benoît Dupont de Dinechin and Christophe Guillon, Revisiting out-of-SSA translation for correctness, code quality, and efficiency, International Symposium on Code Generation and Optimization (CGO 2009), pages 114-125, Method I with parallel copies as the starting point, followed by coalescing with value-based interference
  4. Fabrice Rastello and Florent Bouchez Tichadou (editors), SSA-based Compiler Design, Springer, 2022, Chapter 3 (Standard Construction and Destruction Algorithms), conventional SSA and its destruction with copies; Chapter 21 (SSA Destruction for Machine Code)

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