Algorithm Search⌘K

Algorithmadvanced

SSAPRE

Also called SSA-based partial redundancy elimination.

Performs PRE on SSA form one expression at a time by building a sparse SSA graph of the expression's occurrences.

Time
O((m + v)(n + d)) worst
Space
O(n v + d) extra
Where
d = the total size of the dominance frontiers; m = the number of distinct expressions; n = the number of instructions and blocks; v = the number of variables
Properties
deterministicofflineiterative

SSAPRE is an algorithm for partial redundancy elimination on static single assignment form, by Chow, Chan, Kennedy, Liu, Lo and Tu. It handles one expression at a time. For each expression it builds a small graph of the places that compute the expression and of the joins where different values of it meet, and it decides where to compute it on this graph alone. It needs no bit vectors and no dataflow over the whole flow graph, and it gets the same placement as lazy code motion.

In plain words

Take one expression, such as a + b. Mark every place that computes it. At each join where two paths can bring different values of it, put a marker that says "the value here comes from one of the paths".

Now walk the program from the top, branch by branch, and give each value of a + b a number. Two places get the same number when a and b did not change between them. The second of them is then redundant.

At each join marker, check two things. Will every path from here compute the expression again before a or b changes? And can the value be made ready on every path into the join? If both hold and the value is needed, compute it on the paths that lack it, just before the join, and let the later places read a temporary.

The problem

The input is a procedure of the toy IR with const, copy and op instructions and any control flow. An expression is the text a op b of an op instruction. The output is a program that gives the same result or trap on every input that ends, and in which no path from the entry to a ret evaluates an expression more often than before. Inserted computations must be at down-safe points: every path from there computes the expression again before an operand changes. Among such programs, SSAPRE wants the fewest evaluations on every path.

The paper works on a program that is already in SSA form. The toy IR lets a variable be assigned more than once, so this implementation computes the SSA versions of the variables on the side and does not rename the program.

The algorithm

A real occurrence of ee is an instruction x = e. A Φ for ee sits at the top of a join block. It is like a φ-function for a temporary hh that would hold the value of ee. Each Φ has one operand for each predecessor. An operand is ⊥ if no value of ee with the right operand versions reaches the end of that predecessor. It has a real use if the value comes from a real occurrence and not from another Φ.

  1. SSAPRE(P)
  2. 1remove unreachable blocks, give the entry no predecessor, and split every critical edge
  3. 2build the dominator tree and the dominance frontiers, and give each variable its SSA versions
  4. 3for each expression e = a op b, one at a time
  5. 4Φ-Insertion: put a Φ for e at DF+(blocks that compute e) and at each block with a φ for a or b
  6. 5Rename: walk the dominator tree with a stack of occurrences; an occurrence whose operand versions match the top takes its version, else it gets a new one; a Φ whose version is killed or reaches a ret before a real use is not down-safe
  7. 6DownSafety: if a Φ f is not down-safe, each Φ g that gives f an operand with no real use is not down-safe
  8. 7can_be_avail: reset each Φ that is not down-safe and has a ⊥ operand, and pass the reset to Φs that are not down-safe and use it with no real use
  9. 8later: start from can_be_avail; reset each Φ with an operand that has a real use, and pass the reset to every Φ that uses it
  10. 9will_be_avail(Φ) <- can_be_avail(Φ) and not later(Φ)
  11. 10Finalize: a real occurrence reloads t if its version comes from an earlier real occurrence, which then saves t, or from a will_be_avail Φ; mark each operand of a will_be_avail Φ that is ⊥, or has no real use and comes from a Φ that is not will_be_avail
  12. 11CodeMotion: insert t = e at the end of the predecessor of each marked operand, turn each save into t = e; x = t, and each reload into x = t
  13. 12return P
  • Φ-Insertion (line L4). A join needs a Φ where values from different occurrences can meet, which is the iterated dominance frontier of the occurrences, as in SSA construction. A φ for an operand also changes the value of ee, so its block gets a Φ too.
  • Rename (line L5). The walk keeps a stack of occurrences, like the renaming step of SSA construction. Two occurrences get the same version exactly when the versions of a and b agree. The walk also notes each Φ whose value dies or reaches a ret before a real occurrence uses it.
  • DownSafety (line L6). A Φ that only feeds another Φ, with no real occurrence in between, is down-safe only if that Φ is. This is the very busy expressions analysis on the sparse graph.
  • WillBeAvail (lines L7 to L9). can_be_avail says the value can be made ready at the Φ with safe insertions. later says that every insertion for the Φ could also go further down, because no operand has a real value yet. A Φ that is will_be_avail is a place where the value will be ready after the insertions.
  • Finalize and CodeMotion (lines L10 and L11). The paper gives the temporary SSA versions and keeps the Φs that are will_be_avail as real φs. Here the temporary is one plain name pre.k, which is what out-of-SSA translation would give.

Example

The parameters are a, b, c and n.

B0:
  i = 0
  br c B1 B2
B1:
  x = a + b
  jump B3
B2:
  x = 0
  jump B3
B3:
  y = a + b
  i = i + 1
  d = i < n
  br d B3 B4
B4:
  ret y

The edge from B3 to itself is critical, so line L1 adds a block B3_B3 that only jumps to B3. Each expression gets one Φ, at B3. For a + b, B3 is the dominance frontier of B1 and of B3. For i + 1 and i < n, B3 has a φ for i. In the notation of the paper, the factored graph of a + b is h1 = a + b in B1, then h2 = Φ(h1, ⊥, h2) at the top of B3 for the predecessors B1, B2 and B3_B3, then the occurrence in B3 with version h2.

Φ at B3 for operands from B1, B2, B3_B3 down-safe can_be_avail later will_be_avail
a + b real use, ⊥, real use yes yes no yes
i + 1 ⊥, ⊥, ⊥ yes yes yes no
i < n ⊥, ⊥, real use no no no no

For a + b, the Φ is down-safe, because B3 computes it first thing. Its operand from B2 is ⊥, so line L10 marks it, and the occurrence in B1 saves the temporary. For i + 1, the Φ is down-safe too, but no operand has a value yet, so it stays later: moving the addition would only make a temporary. For i < n, i changes before the comparison, so the Φ is not down-safe. The result is:

B1:
  pre.0 = a + b
  x = pre.0
  jump B3
B2:
  x = 0
  pre.0 = a + b
  jump B3
B3:
  y = pre.0
  i = i + 1
  d = i < n
  br d B3_B3 B4
B3_B3:
  jump B3
B4:
  ret y

With c=1c = 1 and n=3n = 3 the loop runs three times, and a + b runs once instead of four times. With c=0c = 0 it runs once instead of three times.

Correctness

The proof file has the full proof. It fixes one expression and uses one property of SSA form: the version of a variable at a point names the definition that is last on every path to the point.

  • Rename finds equal values. If an occurrence gets the version of an earlier one, the earlier one dominates it, and no path between them changes a or b.
  • Down-safety. A Φ that is still down-safe after line L6 is down-safe in the program. Every Φ with a marked operand is down-safe. The proof follows a chain of Φs that are not down-safe, can_be_avail and later back toward the entry, and shows that such a chain cannot exist.
  • Same outcome. At each reload and at each will_be_avail Φ, the temporary was computed after the last change of a and b. An inserted computation is down-safe, so if it traps, the old program would trap on the same values a little later.
  • Never more evaluations. Each insertion is matched with the first real occurrence after it on the path. That occurrence becomes a reload, and no two insertions share it.

Kennedy and colleagues also prove computational optimality: no safe placement does better on any path. The tests check it against busy code motion on every path of random acyclic programs.

Proof: SSAPRE keeps the outcome, inserts only at down-safe points, and never adds an evaluation on a pathfull

Setting. The program has const, copy and op instructions only. After line L1, every block is reachable from the entry block, the entry block has no predecessor, and no edge goes from a block with two successors to a block with two predecessors. We also assume that every block can reach a ret. A path is a sequence of blocks along edges, and a complete path starts at the entry and ends at a block with ret. We count positions on a path, because a path can visit a block more than once.

Fix one expression e=aopbe = a \mathbin{op} b. The steps for different expressions do not share anything, so this is no loss. A kill is an instruction that defines aa or bb. A real occurrence is an instruction x = e. It reads aa and bb before it defines xx, so a = a + b is a real occurrence followed by a kill.

Line L2 gives each variable its versions in minimal SSA form: the variable has a φ at each block of the iterated dominance frontier of the blocks that define it, the entry counted. We use the standard property of SSA form.

(V) If the version of aa at a point qq is dd, then the definition dd dominates qq, and on every path from the entry to qq the last definition of aa is dd. A φ counts as a definition at the top of its block.

Line L4 puts a Φ for ee at each block of Φ-blocks=DF+(blocks with a real occurrence)∪{blocks with a φ for a or b}\Phi\text{-blocks} = \mathrm{DF}^+(\text{blocks with a real occurrence}) \cup \{\text{blocks with a φ for } a \text{ or } b\}. Both parts are closed under the dominance frontier, so DF(Y)⊆Φ-blocks\mathrm{DF}(Y) \subseteq \Phi\text{-blocks} for each block YY that has a real occurrence or a Φ. The φ blocks of aa are closed because a φ is a definition of aa too.

A block in a dominance frontier has two or more predecessors. Since the critical edges are split, each predecessor of a Φ block has exactly one successor.

1. The rename walk

Line L5 walks the dominator tree in preorder. At a Φ block it pushes the Φ, and at each real occurrence it pushes the occurrence. When it leaves a block, it pops what the block and its subtree pushed. Each stack entry carries the versions of aa and bb at its own point. An occurrence whose versions equal those of the top of the stack gets the version of the top, and we call the top its definition. A Φ operand from a predecessor pp is the top at the end of pp if the versions match, and ⊥ if not. The operand has a real use if that top is a real occurrence.

Lemma 1. If an occurrence or a Φ operand at point qq has the definition DD, then DD dominates qq, and on every path from the entry to qq there is no kill after the last position of DD.

Proof. The stack holds only entries of blocks on the dominator tree path from the entry to the current block, and entries before qq in the current block. So DD dominates qq. Assume a path from the entry to qq has a definition of aa after the last position of DD. Let dd be the version of aa at qq. By (V) the last definition of aa before qq is dd, so dd is after the last DD, and the part of the path from that dd to qq does not pass DD. Any path from the entry to dd, followed by that part, is a path to qq. It passes DD, so the path to dd passes DD, and DD dominates dd. But DD sees the same version dd of aa, so by (V) dd dominates DD. Two different points cannot dominate each other, and dd before DD in one block is not possible either, because then the part from dd to qq would pass DD. The same holds for bb. □\square

Lemma 2. Let CC be a block with no Φ and let pp be a predecessor of CC. When the walk enters CC, the top of the stack and the versions of aa and bb are the same as at the end of pp.

Proof. CC has no φ for aa or bb, so by (V) their versions at the top of CC are the versions at the end of each predecessor. The walk enters CC with the stack it had after it finished the block idom(C)\mathrm{idom}(C). The immediate dominator of CC dominates pp. Let YY be a block on the dominator tree path strictly below idom(C)\mathrm{idom}(C) down to pp. Then YY dominates pp and does not strictly dominate CC, so C∈DF(Y)C \in \mathrm{DF}(Y). If YY had a real occurrence or a Φ, CC would be a Φ block. So the stack at the end of pp has nothing above what idom(C)\mathrm{idom}(C) left. □\square

Corollary 3. Let a path go from a point qq to a point rr and pass no real occurrence and no top of a Φ block, other than possibly the one at qq. Then the walk sees the same top of the stack at qq and at rr. The versions are also the same if the path has no kill.

Proof. Inside a block the walk pushes only at real occurrences. Between blocks, apply Lemma 2. □\square

2. Down-safety

A point is down-safe if every path from it reaches a real occurrence before a kill or the end of a ret block.

Lemma 4. If a Φ FF is still down-safe after line L6, then the top of its block is down-safe.

Proof. We show the other direction: if a path π\pi from the top of the block of FF reaches a kill or a ret before a real occurrence, then FF is marked. We use induction on the length of π\pi. Look at the first event on π\pi of these kinds: the walk reaches a real occurrence, the end of a ret block, or the end of a predecessor of a Φ block. Up to this event, Corollary 3 says that the top is FF.

  • If π\pi has a kill before the event, the versions now differ from those of FF. At a real occurrence with a different version, L5 marks the top FF. At the end of a predecessor of a Φ block, the operand is ⊥ and L5 marks FF. At a ret, L5 marks FF.
  • If π\pi has no kill before the event, the event is not a real occurrence, because π\pi has none before its kill or ret. If it is a ret, L5 marks FF. If it is the end of a predecessor of a Φ block GG, then the operand of GG is FF with no real use. The rest of π\pi from the top of GG is shorter and still bad, so by induction GG is marked. Then line L6 marks FF through this operand. □\square

3. Insertions are safe

Lemma 5. If line L10 marks an operand of a Φ ff for insertion, then ff is down-safe.

Proof. ff is will-be-avail, so it is can-be-avail. If the operand is ⊥ and ff is not down-safe, line L7 would reset ff. So let the operand come from a Φ gg with no real use, with gg not will-be-avail, and assume ff is not down-safe. By L6, gg is not down-safe. If gg were not can-be-avail, the reset of gg in L7 would reach ff. So gg is can-be-avail and later.

Let SS be the set of Φs that are not down-safe, can-be-avail and later. g∈Sg \in S. Take h∈Sh \in S. It has no ⊥ operand (L7), and no operand with a real use (L8). Each operand comes from a Φ h′h'. h′h' is later, or L8 would reset hh. h′h' is can-be-avail, or L7 would reset hh. h′h' is not down-safe, by L6. So h′∈Sh' \in S.

Take a path from the entry to the block of gg. The operand of gg from the predecessor on this path comes from some h′∈Sh' \in S, whose block dominates that predecessor by Lemma 1. So the path visits the block of h′h' at an earlier position. Repeat with h′h'. The positions decrease forever on a finite path, which is not possible. So ff is down-safe. □\square

Theorem A (safety). Each t = e that line L11 inserts is at a down-safe point.

Proof. The insertion is at the end of a predecessor pp of the block of ff, just before the terminator. pp has one successor, the block of ff, and a terminator does not kill. The top of the block of ff is down-safe by Lemmas 5 and 4. □\square

4. The outcome does not change

Line L11 keeps one plain name tt for ee, and writes it only with t = e. Say tt is good at a position of a run if the run executed t = e at an earlier position and no kill after it. Then tt holds the value of ee for the current aa and bb.

Lemma 6. In every run of the new program, tt is good at each reload and at the top of the block of each will-be-avail Φ.

Proof. Strong induction on the position in the run. The entry block has no Φ.

  • A reload RR has a definition DD, and by Lemma 1 there is no kill from the last DD to RR. If DD is a real occurrence that computes, L10 marked it to save, so the run executed t = e there. If DD is a reload, or a will-be-avail Φ, tt is good at the last DD by induction. In each case it stays good up to RR.
  • At the top of the block of a will-be-avail ff, entered from pp: if the operand is marked for insertion, t = e ran at the end of pp. Otherwise it is not ⊥. If it has a real use, its definition saves or reloads, and if not, it comes from a will-be-avail Φ. Lemma 1 and the induction finish the proof as before. □\square

Theorem B. On every input, the new program returns the same value as the original, or traps if the original traps.

Proof. Run both programs side by side. They take the same branches as long as the old names hold the same values. A kept instruction does the same thing. A reload gives xx the value of ee by Lemma 6, which is what the original computes, and a reload cannot trap. A save computes ee and copies it. An inserted t = e writes only tt.

If the original returns, every real occurrence on its run evaluates ee without a trap. An inserted evaluation is at a down-safe point (Theorem A), so the original later evaluates ee on the same operand values, and the inserted one does not trap either. If the original traps at an instruction that the new program keeps or saves, the new program traps there too, unless it trapped earlier. If it traps at a real occurrence that the new program reloads, then tt is good there, so the new program already evaluated ee on the same operand values and trapped. An earlier trap of the new program is at an inserted or saved evaluation of ee, and by down-safety or by the same values the original also traps. □\square

5. No path gets more evaluations

Lemma 7. Let FF be a Φ that is will-be-avail and down-safe after L6, and let a path go from the top of its block to a real occurrence RR with no real occurrence and no kill before RR. Then each Φ GG on the path is will-be-avail, the operand of GG on the path is not marked for insertion, and RR is a reload.

Proof. Let G0=F,G1,…,GkG_0 = F, G_1, \dots, G_k be the Φs at the tops of the blocks on the path, in order. By Corollary 3 the operand of Gi+1G_{i+1} on the path comes from GiG_i with no real use, and the definition of RR is GkG_k. If GiG_i is down-safe, then Gi+1G_{i+1} is down-safe, or L6 would mark GiG_i through this operand. A down-safe Φ is never reset by L7. GiG_i is not later, so the reset of GiG_i in L8 reached Gi+1G_{i+1}. So each GiG_i is will-be-avail, each operand on the path comes from a will-be-avail Φ and is not marked for insertion, and RR reloads from GkG_k. □\square

Theorem C. On every complete path, the new program evaluates ee at most as often as the original.

Proof. The new program evaluates ee at a computing occurrence, which the original also evaluates, and at insertions. Send each insertion at the end of pp, for the Φ ff, to the first real occurrence RR after it on the path. RR exists and the part before it has no kill, because the point is down-safe (Theorem A). ff is down-safe by Lemma 5, so by Lemma 7, RR is a reload, and it is not a computing occurrence. Two insertions cannot go to the same RR: the later one would be on an operand of a Φ on the path between the earlier one and RR, and Lemma 7 says that such an operand is not marked. So the map is one to one into the occurrences that the new program reloads. □\square

Computational optimality. Kennedy, Chan, Liu, Lo, Tu and Chow prove that the result is also computationally optimal: no safe placement evaluates ee fewer times on any path. We do not repeat that proof here. The tests compare the count on every path of random acyclic programs with busy code motion, which is computationally optimal, and the counts are equal.

Complexity

In this implementation, line L2 costs O(n+d)O(n + d) for the dominance frontiers and O(v(n+d))O(v (n + d)) for the φs and the versions of the variables. For each expression, line L4 costs O(n+d)O(n + d) and the walk of line L5 costs O(n)O(n). Lines L6 to L10 visit each Φ and each operand a fixed number of times, so they are linear in the size of the sparse graph, which is O(n)O(n). The total is O((m+v)(n+d))O((m + v)(n + d)).

Production versions find the occurrences of all expressions in one pass over the program and do the rest on the sparse graphs. Then the cost of the later steps for an expression depends on its own occurrences and Φs, not on the size of the procedure. Lazy code motion, in contrast, iterates bit vectors over every node of the flow graph.

Properties

  • Safe. Insertions are only at down-safe points.
  • Never more evaluations. No path evaluates an expression more often than before.
  • Computationally optimal. Proved by Kennedy and colleagues, and checked by the tests against busy code motion.
  • Sparse. Each expression is handled on a graph of its own occurrences and Φs.
  • Lexical. It works on the text a op b with the original variable names. Two different names with equal values are not seen as equal.
  • One expression at a time. Expressions do not interact, so a compiler can also restrict the work to the expressions it cares about.

Variants and improvements

  • Loads and stores. The same steps treat a load as an expression whose operand is a memory location, with stores and calls as kills. The dual problem sinks stores. Together they give register promotion of memory values.
  • Strength reduction. If an update such as i = i + 1 does not count as a kill of i * c but as a change that can be repaired, the same framework does strength reduction.
  • Value-based PRE. Working on the classes of global value numbering instead of on lexical expressions finds redundancy between different names.
  • Speculative PRE. With profile data, the down-safety rule can be relaxed on cold paths for expressions that cannot trap.

When to use it

Use SSAPRE in a compiler that keeps SSA form through its global optimizations. It needs no translation back to lexical expressions and no bit vectors, and the work for one expression stays near its occurrences. It also fits passes that only want PRE for a few expressions, such as loads in hot loops. In a compiler without SSA form, lazy code motion is the simpler choice. Use value-based PRE if much of the redundancy is hidden by copies.

Pitfalls

  • Critical edges. Insertions go at the end of the predecessor of a Φ block. That place is safe only if the predecessor has one successor, so the critical edges must be split first.
  • Kills before a real use. Rename must mark a Φ as not down-safe when the operands change before the next real occurrence, as for i < n in the example, and not only when the value reaches a ret. Missing this mark puts computations on paths that never needed them.
  • Loops that may not run. In a while loop whose test comes first, the Φ at the loop header is not down-safe for an expression in the body, so SSAPRE leaves it in the loop, like every safe PRE.
  • Runs that never end. Down-safety looks at paths that reach a ret. A run that passes an insertion and then loops forever can trap in the new program and not in the old one.
  • The temporary in SSA form. The paper's temporary has SSA versions and new φs at the will_be_avail Φs. These φs must go through out-of-SSA translation like any other, and the copies x = t need copy propagation afterwards.

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.

ssapre.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ssapre/. The authors are listed in prov/H6X0KK.jsonl.
"""SSAPRE (Chow, Chan, Kennedy, Liu, Lo and Tu) on the toy IR.

ssapre(prog) takes a program with const, copy and op instructions only. It
removes unreachable blocks, gives the entry no predecessor, and splits every
critical edge with a new block that only jumps. Then it gives each variable
SSA versions (minimal SSA, kept on the side; the program itself is not
rewritten into SSA form). An expression is the lexical triple (op, a, b) of
an op instruction. For each expression, the six steps of SSAPRE build a
sparse graph of its occurrences and decide where to compute it.

The output keeps one plain temporary t for each expression instead of the
SSA versions h1, h2, ... of the paper and their phis. The toy IR has
variables that can be assigned more than once, so this is the same program
that out-of-SSA translation would give, and t = e always stores the current
value of e.

plan(p) returns the occurrence graph of each expression of a normalized
program, so the tests and the page can look at the flags.
"""

import toyir


# ------------------------------------------------------------------- graph


def normalize(prog):
    """A copy of prog without unreachable blocks, with an entry that has no
    predecessor, and with every critical edge split. An edge A -> B is
    critical if A has two successors and B has two predecessors. The new
    block on the edge only jumps to B."""
    for blk in prog.blocks.values():
        for ins in blk.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("ssapre handles const, copy and op only: %r" % (ins,))
    reach = {prog.entry}
    stack = [prog.entry]
    while stack:
        b = stack.pop()
        for s in toyir.succs(prog, b):
            if s not in reach:
                reach.add(s)
                stack.append(s)
    taken = set(prog.blocks)

    def fresh(base):
        name = base
        while name in taken:
            name += "_"
        taken.add(name)
        return name

    blocks = {}
    if any(prog.entry in toyir.succs(prog, b) for b in reach):
        blocks[fresh("start")] = toyir.Block([], ("jump", prog.entry))
    for label, blk in prog.blocks.items():
        if label in reach:
            blocks[label] = toyir.Block(list(blk.instrs), blk.term)
    p = toyir.Program(list(prog.params), blocks)
    npred = {b: len(ps) for b, ps in toyir.preds(p).items()}
    out = {}
    for label, blk in p.blocks.items():
        out[label] = blk
        t = blk.term
        if t[0] == "br" and t[2] != t[3]:
            targets = []
            for s in (t[2], t[3]):
                if npred[s] > 1:
                    mid = fresh(label + "_" + s)
                    out[mid] = toyir.Block([], ("jump", s))
                    targets.append(mid)
                else:
                    targets.append(s)
            blk.term = ("br", t[1], targets[0], targets[1])
    return toyir.Program(list(prog.params), out)


def expression(ins):
    """The expression (op, a, b) that an instruction computes, or None."""
    if ins is not None and ins[0] == "op":
        return (ins[2], ins[3], ins[4])
    return None


def names_of(prog):
    out = set(prog.params)
    for blk in prog.blocks.values():
        for ins in blk.instrs:
            out.add(ins[1])
            out.update(toyir.uses(ins))
        out.update(toyir.term_uses(blk.term))
    return out


def reverse_postorder(prog):
    seen = {prog.entry}
    post = []
    stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            post.append(v)
            stack.pop()
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(toyir.succs(prog, w))))
    return post[::-1]


def dominators(prog):
    """The immediate dominator of each block and the children of each block
    in the dominator tree, by the iterative method of Cooper, Harvey and
    Kennedy. The entry is its own immediate dominator."""
    order = reverse_postorder(prog)
    num = {b: i for i, b in enumerate(order)}
    pred = toyir.preds(prog)
    idom = {order[0]: order[0]}

    def meet(x, y):
        while x != y:
            while num[x] > num[y]:
                x = idom[x]
            while num[y] > num[x]:
                y = idom[y]
        return x

    changed = True
    while changed:
        changed = False
        for b in order[1:]:
            new = None
            for p in pred[b]:
                if p in idom:
                    new = p if new is None else meet(p, new)
            if idom.get(b) != new:
                idom[b] = new
                changed = True
    children = {b: [] for b in order}
    for b in order[1:]:
        children[idom[b]].append(b)
    return idom, children


def frontiers(prog, idom):
    df = {b: set() for b in prog.blocks}
    for b, ps in toyir.preds(prog).items():
        if len(ps) >= 2:
            for p in ps:
                r = p
                while r != idom[b]:
                    df[r].add(b)
                    r = idom[r]
    return df


def iterated(df, start):
    """DF+ of a set of blocks."""
    out = set()
    work = list(start)
    while work:
        b = work.pop()
        for y in df[b]:
            if y not in out:
                out.add(y)
                work.append(y)
    return out


def variable_versions(prog, idom, children, df):
    """Minimal SSA for the variables, kept on the side. Returns phis, a dict
    from each variable to the set of blocks with a phi for it, and ver_in, a
    dict from each block to the version of every variable at its top, after
    its phis. A version is ("entry", v), ("phi", block, v) or
    ("def", block, i)."""
    names = sorted(names_of(prog))
    defs = {v: {prog.entry} for v in names}
    for b, blk in prog.blocks.items():
        for ins in blk.instrs:
            defs[ins[1]].add(b)
    phis = {v: iterated(df, defs[v]) for v in names}
    at = {b: [v for v in names if b in phis[v]] for b in prog.blocks}
    ver_in = {}
    todo = [(prog.entry, {v: ("entry", v) for v in names})]
    while todo:
        b, cur = todo.pop()
        cur = dict(cur)
        for v in at[b]:
            cur[v] = ("phi", b, v)
        ver_in[b] = dict(cur)
        for i, ins in enumerate(prog.blocks[b].instrs):
            cur[ins[1]] = ("def", b, i)
        for c in children[b]:
            todo.append((c, cur))
    return phis, ver_in


# ------------------------------------------------------- occurrence graph


class Phi:
    """A Φ for the expression at the top of a block."""

    def __init__(self, block, vers):
        self.block = block
        self.vers = vers  # the versions of the operands at the top of the block
        self.version = None
        self.ops = {}  # predecessor label -> Operand
        self.down_safe = True
        self.can_be_avail = True
        self.later = True

    @property
    def will_be_avail(self):
        return self.can_be_avail and not self.later  # @line L9


class Real:
    """A real occurrence x = a op b at node (block, index)."""

    def __init__(self, node, vers, version, defn):
        self.node = node
        self.vers = vers
        self.version = version
        self.defn = defn  # the occurrence on top of the stack with the same version, or None
        self.src = None  # the occurrence whose value this one uses
        self.save = False


class Operand:
    """The operand of a Φ that comes from one predecessor."""

    def __init__(self, defn, real):
        self.defn = defn  # None is ⊥
        self.real = real  # has_real_use
        self.insert = False


def rename(prog, e, phi_blocks, ver_in, children):
    """Give versions to the occurrences of e by a preorder walk of the
    dominator tree with a stack of occurrences. Returns the Φs (by block) and
    the real occurrences (in preorder)."""
    names = [x for x in e[1:]]
    tracked = {x for x in names if isinstance(x, str)}

    def key(cur):
        return tuple(cur[x] if isinstance(x, str) else x for x in names)

    phis = {b: Phi(b, key(ver_in[b])) for b in prog.blocks if b in phi_blocks}
    reals = []
    stack = []
    count = 0
    todo = [("enter", prog.entry)]
    while todo:
        item = todo.pop()
        if item[0] == "exit":
            del stack[item[1]:]
            continue
        b = item[1]
        todo.append(("exit", len(stack)))
        for c in reversed(children[b]):
            todo.append(("enter", c))
        cur = {x: ver_in[b][x] for x in tracked}
        if b in phis:
            f = phis[b]
            f.version = count
            count += 1
            stack.append(f)
        blk = prog.blocks[b]
        for i, ins in enumerate(blk.instrs):
            if expression(ins) == e:
                vs = key(cur)
                top = stack[-1] if stack else None
                if top is not None and top.vers == vs:
                    r = Real((b, i), vs, top.version, top)
                else:
                    if isinstance(top, Phi):
                        top.down_safe = False  # killed before a real use
                    r = Real((b, i), vs, count, None)
                    count += 1
                reals.append(r)
                stack.append(r)
            if ins[1] in tracked:
                cur[ins[1]] = ("def", b, i)
        vs = key(cur)
        top = stack[-1] if stack else None
        live = top is not None and top.vers == vs
        for s in toyir.succs(prog, b):
            if s in phis:
                if live:
                    phis[s].ops[b] = Operand(top, isinstance(top, Real))
                else:
                    phis[s].ops[b] = Operand(None, False)
                    if isinstance(top, Phi):
                        top.down_safe = False
        if blk.term[0] == "ret" and isinstance(top, Phi):
            top.down_safe = False  # reaches the exit without a real use
    return phis, reals


def users(phis):
    out = {id(f): [] for f in phis.values()}
    for f in phis.values():
        for o in f.ops.values():
            if isinstance(o.defn, Phi):
                out[id(o.defn)].append((f, o))
    return out


def down_safety(phis):
    work = [f for f in phis.values() if not f.down_safe]
    while work:
        f = work.pop()
        for o in f.ops.values():
            g = o.defn
            if isinstance(g, Phi) and not o.real and g.down_safe:
                g.down_safe = False
                work.append(g)


def can_be_avail(phis, use):
    def reset(g):
        g.can_be_avail = False
        for f, o in use[id(g)]:
            if not o.real and not f.down_safe and f.can_be_avail:
                reset(f)

    for f in phis.values():
        if not f.down_safe and f.can_be_avail and any(o.defn is None for o in f.ops.values()):
            reset(f)


def later(phis, use):
    def reset(g):
        g.later = False
        for f, _ in use[id(g)]:
            if f.later:
                reset(f)

    for f in phis.values():
        f.later = f.can_be_avail
    for f in phis.values():
        if f.later and any(o.defn is not None and o.real for o in f.ops.values()):
            reset(f)


def finalize(phis, reals):
    """Decide which real occurrences reload t, which save it, and which Φ
    operands need an insertion."""
    for r in reals:
        d = r.defn
        if d is None or (isinstance(d, Phi) and not d.will_be_avail):
            r.src = r
        elif isinstance(d, Real):
            r.src = d.src
        else:
            r.src = d
        if r.src is not r and isinstance(r.src, Real):
            r.src.save = True
    for f in phis.values():
        if not f.will_be_avail:
            continue
        for o in f.ops.values():
            if o.defn is None or (not o.real and not o.defn.will_be_avail):
                o.insert = True
            elif isinstance(o.defn, Real) and isinstance(o.defn.src, Real):
                o.defn.src.save = True


def plan(p):
    """The occurrence graph of each expression of a normalized program, as a
    list of (e, phis, reals) in the order of first occurrence."""
    idom, children = dominators(p)  # @line L2
    df = frontiers(p, idom)
    var_phis, ver_in = variable_versions(p, idom, children, df)
    exprs = []
    where = {}
    for b, blk in p.blocks.items():
        for ins in blk.instrs:
            e = expression(ins)
            if e is not None:
                if e not in where:
                    exprs.append(e)
                    where[e] = set()
                where[e].add(b)
    out = []
    for e in exprs:  # @line L3
        phi_blocks = iterated(df, where[e])  # @line L4
        for x in e[1:]:
            if isinstance(x, str):
                phi_blocks |= var_phis[x]
        phis, reals = rename(p, e, phi_blocks, ver_in, children)  # @line L5
        down_safety(phis)  # @line L6
        use = users(phis)
        can_be_avail(phis, use)  # @line L7
        later(phis, use)  # @line L8
        finalize(phis, reals)  # @line L10
        out.append((e, phis, reals))
    return out


# -------------------------------------------------------------- transform


def code_motion(p, plans):
    taken = names_of(p)
    action = {}
    insert = {b: [] for b in p.blocks}
    for k, (e, phis, reals) in enumerate(plans):  # @line L11
        name = "pre.%d" % k
        while name in taken:
            name += "_"
        taken.add(name)
        for r in reals:
            if r.src is not r:
                action[r.node] = ("reload", name)
            elif r.save:
                action[r.node] = ("save", name)
        for f in phis.values():
            for pred, o in f.ops.items():
                if o.insert:
                    insert[pred].append(("op", name, e[0], e[1], e[2]))
    blocks = {}
    for b, blk in p.blocks.items():
        instrs = []
        for i, ins in enumerate(blk.instrs):
            act = action.get((b, i))
            if act is None:
                instrs.append(ins)
            elif act[0] == "reload":
                instrs.append(("copy", ins[1], act[1]))
            else:
                instrs.append(("op", act[1], ins[2], ins[3], ins[4]))
                instrs.append(("copy", ins[1], act[1]))
        blocks[b] = toyir.Block(instrs + insert[b], blk.term)
    return toyir.Program(list(p.params), blocks)


def ssapre(prog):
    """SSAPRE. Returns the new program. Its blocks are the blocks of
    normalize(prog), with the same terminators."""
    p = normalize(prog)  # @line L1
    plans = plan(p)
    return code_motion(p, plans)  # @line L12
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_ssapre.py 272 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ssapre/. The authors are listed in prov/H6X0KK.jsonl.
import random
from collections import Counter

import toyir
import ssapre as S

PAGE_BEFORE = """# params: a, b, c, n
B0:
  i = 0
  br c B1 B2
B1:
  x = a + b
  jump B3
B2:
  x = 0
  jump B3
B3:
  y = a + b
  i = i + 1
  d = i < n
  br d B3 B4
B4:
  ret y
"""

PAGE_AFTER = """# params: a, b, c, n
B0:
  i = 0
  br c B1 B2
B1:
  pre.0 = a + b
  x = pre.0
  jump B3
B2:
  x = 0
  pre.0 = a + b
  jump B3
B3:
  y = pre.0
  i = i + 1
  d = i < n
  br d B3_B3 B4
B3_B3:
  jump B3
B4:
  ret y
"""

FUEL = 100000


def counts(prog, path):
    c = Counter()
    for b in path:
        for ins in prog.blocks[b].instrs:
            e = S.expression(ins)
            if e is not None:
                c[e] += 1
    return c


VARS = ("x0", "x1", "x2")


def dense_instr(rng):
    r = rng.random()
    if r < 0.2:
        x = rng.choice(VARS)
        return ("op", x, "+", x, 1)
    if r < 0.3:
        return ("copy", rng.choice(VARS), rng.choice(VARS))
    x = rng.choice(VARS + ("y0", "y1"))
    return ("op", x, rng.choice(("+", "/")), rng.choice(VARS), rng.choice(VARS + (2,)))


def dense(rng, nblocks, acyclic, most=3):
    """A random program over few names and two operators, so the same
    expression is often computed on several paths. Division by a variable
    can trap. The control flow and the loop counters come from
    toyir.random_program."""
    prog = toyir.random_program(rng, 3, nblocks, acyclic)
    for blk in prog.blocks.values():
        new = []
        for ins in blk.instrs:
            if ins[0] in ("op", "copy") and ins[1] in VARS:
                for _ in range(rng.randint(1, most)):
                    new.append(dense_instr(rng))
            else:
                new.append(ins)
        blk.instrs = new
    return prog


def programs(seed, n):
    rng = random.Random(seed)
    for k in range(n):
        acyclic = k % 2 == 0
        if k % 3 == 0:
            yield toyir.random_program(rng, rng.randint(2, 4), rng.randint(2, 7), acyclic)
        else:
            yield dense(rng, rng.randint(2, 8), acyclic)


ARGS = [(0, 0), (1, 0), (0, 1), (2, 3), (-2, 2), (3, -1), (2, 2), (-1, -1)]


def busy_points(p, e):
    """The oracle: the earliest safe points of e, on the graph with one node
    for each instruction and terminator. Busy code motion computes e exactly
    there, and it is computationally optimal (Knoop, Ruthing and Steffen).
    Also returns the down-safe nodes."""
    nodes, succ = [], {}
    for b, blk in p.blocks.items():
        k = len(blk.instrs)
        for i in range(k + 1):
            nodes.append((b, i))
            succ[(b, i)] = [(b, i + 1)] if i < k else [(s, 0) for s in toyir.succs(p, b)]
    pred = {n: [] for n in nodes}
    for n in nodes:
        for s in succ[n]:
            pred[s].append(n)

    def instr(n):
        blk = p.blocks[n[0]]
        return blk.instrs[n[1]] if n[1] < len(blk.instrs) else None

    comp = {n: S.expression(instr(n)) == e for n in nodes}
    kill = {n: instr(n) is not None and instr(n)[1] in e[1:] for n in nodes}
    ant = {n: True for n in nodes}
    changed = True
    while changed:
        changed = False
        for n in reversed(nodes):
            out = bool(succ[n]) and all(ant[s] for s in succ[n])
            new = comp[n] or (out and not kill[n])
            if new != ant[n]:
                ant[n] = new
                changed = True
    av_out = {n: True for n in nodes}
    av_in = {}
    changed = True
    while changed:
        changed = False
        for n in nodes:
            av_in[n] = bool(pred[n]) and all(av_out[q] for q in pred[n])
            new = (ant[n] or av_in[n]) and not kill[n]
            if new != av_out[n]:
                av_out[n] = new
                changed = True
    return {n for n in nodes if ant[n] and not av_in[n]}, ant


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


def test_page_example():
    p = toyir.parse(PAGE_BEFORE)
    q = S.ssapre(p)
    assert toyir.show(q) == PAGE_AFTER
    for args in [(2, 3, 1, 3), (2, 3, 0, 3), (0, 0, 1, 0), (5, -1, 0, 1)]:
        assert toyir.run(q, args) == toyir.run(p, args)
    e = ("+", "a", "b")
    path = ["B0", "B1", "B3", "B3_B3", "B3", "B3_B3", "B3", "B4"]
    assert counts(S.normalize(p), path)[e] == 4 and counts(q, path)[e] == 1
    plans = {e: (phis, reals) for e, phis, reals in S.plan(S.normalize(p))}
    f = plans[e][0]["B3"]
    assert (f.down_safe, f.can_be_avail, f.later, f.will_be_avail) == (True, True, False, True)
    assert sorted((b, o.defn is None, o.real, o.insert) for b, o in f.ops.items()) == [
        ("B1", False, True, False), ("B2", True, False, True), ("B3_B3", False, True, False)]
    # i + 1: the Φ at B3 is down-safe, but no operand is available, so it
    # stays "later" and the addition is not moved.
    g = plans[("+", "i", 1)][0]["B3"]
    assert (g.down_safe, g.can_be_avail, g.later) == (True, True, True)
    # i < n: i changes before the comparison, so the Φ is not down-safe.
    h = plans[("<", "i", "n")][0]["B3"]
    assert (h.down_safe, h.can_be_avail) == (False, False)


def test_same_outcome_on_random_programs():
    for prog in programs(1, 400):
        q = S.ssapre(prog)
        for args in ARGS:
            want = toyir.run(prog, args, FUEL)
            assert want != ("fuel",)
            assert toyir.run(q, args, FUEL) == want


def test_never_more_evaluations_and_optimal_on_every_path():
    better = 0
    for prog in programs(2, 600):
        if not toyir.is_acyclic(prog):
            continue
        p = S.normalize(prog)
        q = S.ssapre(prog)
        assert list(q.blocks) == list(p.blocks)
        exprs = {S.expression(ins) for blk in p.blocks.values() for ins in blk.instrs} - {None}
        best = {e: busy_points(p, e)[0] for e in exprs}
        for path in toyir.paths(p):
            old, new = counts(p, path), counts(q, path)
            assert set(new) <= set(old)
            for e in old:
                opt = sum(1 for (b, _) in best[e] if b in path)
                assert new[e] <= old[e]
                assert new[e] == opt
                better += new[e] < old[e]
    assert better > 50


def test_insertions_are_down_safe():
    inserted = 0
    for prog in programs(3, 400):
        p = S.normalize(prog)
        for e, phis, reals in S.plan(p):
            _, ant = busy_points(p, e)
            for f in phis.values():
                for pred, o in f.ops.items():
                    if o.insert:
                        assert f.down_safe and f.will_be_avail
                        assert ant[(pred, len(p.blocks[pred].instrs))]
                        inserted += 1
    assert inserted > 100


DO_WHILE = """# params: a, b, n
B0:
  i = 0
  jump B1
B1:
  x = a / b
  i = i + 1
  c = i < n
  br c B1 B2
B2:
  ret x
"""

ZERO_TRIP = """# params: a, b, n
B0:
  i = 0
  jump B1
B1:
  c = i < n
  br c B2 B3
B2:
  x = a / b
  i = i + 1
  jump B1
B3:
  ret i
"""


def test_loop_invariant_leaves_a_loop_that_runs_once():
    p = toyir.parse(DO_WHILE)
    q = S.ssapre(p)
    assert q.blocks["B0"].instrs[-1] == ("op", "pre.0", "/", "a", "b")
    assert q.blocks["B1"].instrs[0] == ("copy", "x", "pre.0")
    assert toyir.run(q, (7, 2, 3)) == toyir.run(p, (7, 2, 3)) == ("ret", 3)
    assert toyir.run(q, (7, 0, 3)) == ("trap",)


def test_no_hoisting_out_of_a_loop_that_may_not_run():
    p = toyir.parse(ZERO_TRIP)
    q = S.ssapre(p)
    for b, blk in q.blocks.items():
        for ins in blk.instrs:
            if S.expression(ins) == ("/", "a", "b"):
                assert b == "B2"
    assert toyir.run(q, (1, 0, 0)) == ("ret", 0)
    assert toyir.run(q, (1, 0, 2)) == ("trap",)

History

Chow, Chan, Kennedy, Liu, Lo and Tu presented SSAPRE at PLDI 1997. Earlier PRE methods, from Morel and Renvoise in 1979 to the lazy code motion of Knoop, Rüthing and Steffen in 1992, worked with bit vectors over the whole flow graph. SSAPRE showed that the same safe and optimal placement can be computed on SSA form, one expression at a time, by steps that look like SSA construction. Kennedy and the same coauthors gave the full algorithm, the proofs and the extensions to memory operations and strength reduction in TOPLAS in 1999.

References

  1. Fred Chow, Sun Chan, Robert Kennedy, Shin-Ming Liu, Raymond Lo and Peng Tu, A new algorithm for partial redundancy elimination based on SSA form, Proceedings of the ACM SIGPLAN 1997 Conference on Programming Language Design and Implementation (PLDI 1997), 273-286, the whole paper (the six steps Φ-Insertion, Rename, DownSafety, WillBeAvail, Finalize and CodeMotion)
  2. Robert Kennedy, Sun Chan, Shin-Ming Liu, Raymond Lo, Peng Tu and Fred Chow, Partial redundancy elimination in SSA form, ACM Transactions on Programming Languages and Systems 21(3), 1999, 627-676, the whole paper (the full algorithm, the proofs of correctness and optimality, and the extensions to loads, stores and strength reduction)
  3. Jens Knoop, Oliver Rüthing and Bernhard Steffen, Optimal code motion: theory and practice, ACM Transactions on Programming Languages and Systems 16(4), 1994, 1117-1155, the definitions of down-safety, computational optimality and lifetime optimality that SSAPRE reaches

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.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