Algorithm Search⌘K

Algorithmadvanced

Alpern-Wegman-Zadeck value numbering

Also called partition-based value numbering.

Finds congruent SSA values by refining a partition of the value graph until operands of congruent values are congruent, as in DFA minimization.

Time
O((n + e) log n) worst
Space
Θ(n + e) extra
Where
e = the number of edges of the value graph; n = the number of nodes of the value graph
Properties
deterministicofflineiterative

The Alpern-Wegman-Zadeck algorithm (AWZ) solves global value numbering on SSA form. It builds the value graph of the procedure, in which each SSA name is a node labeled with its operator and pointing to its operands. Then it finds the coarsest partition of the nodes in which equal labels and congruent operands are the only reason to share a class. It starts from the hopeful guess that all nodes with the same label are equal, and splits classes only when operands prove two nodes different. This is the partition refinement of Hopcroft's DFA minimization, and it runs in O((n+e)log⁡n)O((n + e) \log n) time. Because it starts hopeful, it finds equal values that depend on themselves through loops, which a one-pass hashing method like local value numbering cannot.

In plain words

Put every value of the program into a group with all the values of the same kind: all additions together, all multiplications together, and all merges at the same join together. Now check each group. Two values in a group must have their first operands in one group and their second operands in one group. If they do not, split the group. Repeat until no group needs a split.

At the end, two values in one group are equal on every run, wherever both are available. A value whose group was already computed higher up in the program is replaced by a copy of the earlier one.

The hopeful start is the point. Two loop counters that both start at 1 and both add 1 are in one group from the start, and nothing ever splits them.

The problem

The input is a procedure of the toy IR with const, copy and op instructions and any control flow. The output is a program with the same behavior on every input in which some operations are replaced by copies of equal values computed earlier. The algorithm is meant to remove every operation that is congruent to an operation that dominates it. Congruence is defined on the value graph in the definition of the problem: a partition that refines the labels and in which nodes of one class have their jj-th operands in one class, for every jj.

AWZ does not find all equal values. That problem is undecidable, and even Herbrand equivalence, which treats operators as unknown functions, is more than congruence, because AWZ treats each phi as an unknown function of its block.

The algorithm

The value graph has a node for each parameter, SSA name and constant. The label of an op is its operator, the label of a phi is its block, a parameter has a label of its own, and a constant is labeled by its value. The children of an op are its operands, and the children of a phi are its operands in the order of the predecessors of the block.

  1. AWZ(P)
  2. 1S <- SSA form of P, with copies and constants folded into the operands
  3. 2G <- the value graph of S
  4. 3B <- the partition of the nodes of G by label and number of children
  5. 4W <- all classes of B
  6. 5while W is not empty do
  7. 6take a class C out of W
  8. 7for each position j do
  9. 8for each class D that has nodes whose j-th child is in C and nodes whose j-th child is not
  10. 9split D into those two parts; the larger part keeps the name D
  11. 10put the smaller part into W
  12. 11walk the dominator tree of S from the entry, with a scoped map REP from classes to names
  13. 12for each definition x of the block, phis first
  14. 13if REP has the class of x then replace the definition by x = REP[class of x]
  15. 14else REP[class of x] <- x
  16. 15return S

Line L8 uses the members of CC as they were at line L6. The worklist holds classes, and line L10 is Hopcroft's rule: a part that splits off goes into the worklist, and the larger part, which keeps the name, needs no new entry. If DD was waiting in WW, both parts are waiting now. If DD was not, the partition is already stable for DD, and stability for the smaller part implies stability for the larger one.

Lines L11 to L14 are the elimination. A replaced phi becomes a copy placed right after the phis of its block. The representative of a phi is another phi of the same block, since only those share its label. The SSA builder places phis at the dominance frontiers of the definitions, only where the variable is live, as in SSA construction.

Example

The parameter is n.

entry:
  i = 1
  j = 1
  s = 0
  jump loop
loop:
  a = i * 4
  b = j * 4
  s = s + a
  s = s + b
  i = i + 1
  j = j + 1
  c = i <= n
  br c loop exit
exit:
  ret s

In SSA form, with the constants folded, the loop block starts with i.1 = phi [entry: 1, loop: i.2], s.1 = phi [entry: 0, loop: s.3] and j.1 = phi [entry: 1, loop: j.2]. The value graph has 14 nodes: n, the constants 0, 1 and 4, three phis and seven ops.

step classes with more than one node
L3, by label phis of loop: {i.1, j.1, s.1}; *: {a.1, b.1}; +: {s.2, s.3, i.2, j.2}
first operand of a phi is 0, not 1 {i.1, j.1}, s.1 alone
first operand of a + is a phi, not a + {s.2, i.2, j.2}, s.3 alone
second operand of a + is a *, not a constant {i.2, j.2}, s.2 alone
no more splits {i.1, j.1}, {a.1, b.1}, {i.2, j.2}

The order of the splits depends on the worklist, but the final partition does not. The elimination meets i.1 before j.1, a.1 before b.1 and i.2 before j.2, so it gives:

loop:
  i.1 = phi [entry: 1, loop: i.2]
  s.1 = phi [entry: 0, loop: s.3]
  j.1 = i.1
  a.1 = i.1 * 4
  b.1 = a.1
  s.2 = s.1 + a.1
  s.3 = s.2 + b.1
  i.2 = i.1 + 1
  j.2 = i.2
  c.1 = i.2 <= n
  br c.1 loop exit

For n=3n = 3 both programs return 2⋅(4+8+12)=482 \cdot (4 + 8 + 12) = 48, and the operations run drop from 21 to 15. A pessimistic hashing method that visits loop first meets i.1 and j.1 before their back-edge operands have numbers, so it must give them different numbers, and it finds none of these three equalities.

Correctness

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

  • The partition is the coarsest congruence. Every congruence refines the current partition, because a split separates two nodes whose jj-th children lie on different sides of a union of classes, and no congruence relates such nodes. When the worklist is empty, the partition is stable for each of its classes, which is the definition of a congruence. The second part needs an invariant: every class is in the worklist, or the partition is stable for the union of the class with some classes that are in the worklist.
  • Congruent names hold equal values. In every run, if xx and yy are congruent and both definitions dominate the current point, they hold equal values. The proof goes by induction on the steps of the run. Its key lemma says that the latest execution of an operand comes before the latest execution of a value that uses it, when the value dominates the point. Strict SSA form gives this.
  • The elimination keeps every outcome. A replaced op is congruent to a dominating one that was computed from equal operands without a trap, so the copy writes the value that the op would write, and the op could not have trapped. A replaced phi gets the value of a congruent phi of the same block. The two programs run in lockstep with the same environments, so they return the same value, trap at the same step or run out of fuel at the same step.
Proof: AWZ finds the coarsest congruence, and congruent values are equalfull

Setting. SS is a strict SSA program in the toy IR with only phis and op instructions: every operand is a constant, a parameter or a name whose definition dominates the use, and the use of a phi operand for predecessor PP is at the end of PP. The SSA builder of the implementation gives such a program, because it folds copies and constants into the operands and reads 0 where no definition reaches. A point is a position between two instructions; a definition dd dominates a point pp if every path from the entry to pp runs through dd before it reaches pp. The phis of a block run as one group when the block is entered, so the first point of a block is after its phis.

The value graph GG has a node for each parameter, each SSA name and each constant. Its label is ("param", pp), ("op", op\mathit{op}), ("phi", BB) or ("const", kk). The children of an op are its two operands, and the children of a phi in block BB are its operands in the order of the predecessors of BB. A congruence is an equivalence relation RR on the nodes such that uRvu \mathrel{R} v implies that uu and vv have the same label and the same number of children, and chj(u)Rchj(v)\mathrm{ch}_j(u) \mathrel{R} \mathrm{ch}_j(v) for every position jj. A partition is a congruence if the relation "same class" is one.

1. The coarsest congruence exists

Let R∗R^* be the transitive closure of the union of all congruences. The identity is a congruence, so R∗R^* is reflexive, and it is symmetric and transitive. If uR∗vu \mathrel{R^*} v, there is a chain u=w0,w1,…,wm=vu = w_0, w_1, \ldots, w_m = v in which each step is in some congruence. Each step keeps the label and the number of children and relates the jj-th children, so the chain of jj-th children shows chj(u)R∗chj(v)\mathrm{ch}_j(u) \mathrel{R^*} \mathrm{ch}_j(v). So R∗R^* is a congruence, and every congruence refines it. It is the coarsest congruence.

2. The partition step finds it

The partition step keeps a partition π\pi and a worklist WW of classes. For a set CC and a position jj, write prej(C)\mathrm{pre}_j(C) for the nodes whose jj-th child is in CC. Say that π\pi is stable for CC if every class DD of π\pi is inside prej(C)\mathrm{pre}_j(C) or disjoint from it, for every jj.

Two facts hold because each node has at most one jj-th child.

(F1) If π\pi is stable for S1S_1 and for S2⊆S1S_2 \subseteq S_1, then it is stable for S1∖S2S_1 \setminus S_2, since prej(S1∖S2)=prej(S1)∖prej(S2)\mathrm{pre}_j(S_1 \setminus S_2) = \mathrm{pre}_j(S_1) \setminus \mathrm{pre}_j(S_2).

(F2) If π\pi is stable for SS, every refinement of π\pi is stable for SS.

Invariant (I1). Every congruence refines π\pi. At the start π\pi is the partition by label and number of children, and every congruence refines it. A split of a class DD by X=prej(C)X = \mathrm{pre}_j(C), where CC is a union of classes of π\pi, separates u∈D∩Xu \in D \cap X from v∈D∖Xv \in D \setminus X. Nodes of DD have the same number of children, so vv has a jj-th child, and it is outside CC, while the jj-th child of uu is in CC. If a congruence RR had uRvu \mathrel{R} v, then chj(u)Rchj(v)\mathrm{ch}_j(u) \mathrel{R} \mathrm{ch}_j(v), and by (I1) the two children would be in one class of π\pi, so both in CC or both outside it. This is false, so no congruence relates uu and vv, and (I1) holds after the split.

Invariant (I2). For every class CC of π\pi, either C∈WC \in W, or there is a set UU that is a union of classes in WW (possibly empty) such that π\pi is stable for C∪UC \cup U.

At the start every class is in WW. Look at the two steps of the loop.

  • A split. A class DD splits into a larger part, which keeps the name DD, and a smaller part D′D', which goes into WW. If D∈WD \in W, both parts are in WW. If π\pi was stable for D∪UD \cup U, it is now stable for D∪(D′∪U)D \cup (D' \cup U) by (F2), and D′∪UD' \cup U is a union of classes in WW. For any other class EE with a set U∋DU \ni D, UU is still a union of classes in WW after the split, because both parts are in WW. Stability for a fixed set survives the split by (F2).
  • Taking CC out of WW. The step keeps SS, the members of CC at that time, and splits every class by prej(S)\mathrm{pre}_j(S) for every jj. After that, π\pi is stable for SS. The classes inside SS are the class that keeps the name CC, which is not in WW, and the parts split off from it, which are in WW. So CC satisfies (I2) with U=S∖CU = S \setminus C. Another class EE with a set UU that contains SS is stable for E∪UE \cup U and for SS, so by (F1) it is stable for E∪(U∖S)E \cup (U \setminus S), and U∖SU \setminus S is a union of classes in WW.

End. Each split adds a class, and there are at most NN classes for NN nodes, so there are at most N−1N - 1 splits and at most 2N−12N - 1 classes ever enter WW. When WW is empty, (I2) says that π\pi is stable for each of its classes. Then two nodes u,vu, v in one class have their jj-th children in the same class for every jj: if chj(u)∈C\mathrm{ch}_j(u) \in C, the class of uu meets prej(C)\mathrm{pre}_j(C), so it lies inside it. The classes also refine the labels, so π\pi is a congruence. By (I1) every congruence refines it. So π\pi is the coarsest congruence R∗R^*.

Cost. Taking CC out of WW costs O(∣C∣)O(|C|) plus the edges that enter CC. Splitting a class DD by a part PP of size ∣D∩X∣|D \cap X| costs O(∣P∣)O(|P|): if PP is at most half of DD, the code moves PP out, and otherwise it builds D∖PD \setminus P, which is smaller than PP. Fix a node mm. Classes only shrink. A class that contains mm enters WW once at the start, and later only as a smaller part, which has at most half the size of the class of mm before the split. So at most 1+log⁡2N1 + \log_2 N classes that contain mm ever enter WW, and mm and the edges into mm are scanned at most that often. The total is O((N+E)log⁡N)O((N + E) \log N) for EE edges.

3. Congruent names hold equal values

Fix a run of SS. For a name xx and a time tt, let valt(x)\mathrm{val}_t(x) be the value that the latest execution of the definition of xx before tt wrote, and let ptp_t be the point of the run at time tt. A constant kk has the value kk at all times.

Lemma. If the definition of cc dominates the definition of yy, and the definition of yy dominates ptp_t, then the latest execution of cc before tt came before the latest execution of yy before tt.

Proof. Both have run, because their definitions dominate ptp_t. Suppose the latest cc came after the latest yy. Dominance is antisymmetric and the two definitions differ, so yy does not dominate cc, and there is a path from the entry to the definition of cc that avoids the definition of yy. Continue it with the part of the run from the latest cc to ptp_t, which has no execution of yy. This path reaches ptp_t without the definition of yy, which contradicts the dominance. □\square

So when the definition of yy dominates ptp_t, the latest instance of yy was computed from the current values of its operands.

Theorem. Let RR be any congruence of GG. At every time tt of the run, if xRyx \mathrel{R} y and the definitions of xx and yy both dominate ptp_t, then valt(x)=valt(y)\mathrm{val}_t(x) = \mathrm{val}_t(y).

Proof. By induction on tt. At the start only the parameters are defined, and a parameter is congruent only to itself, because its label is unique. A step moves from ptp_t to pt+1p_{t+1} in one of two ways.

An op x=aopbx = a \mathbin{op} b runs. A definition other than xx that dominates pt+1p_{t+1} also dominates ptp_t, because ptp_t is the only point before pt+1p_{t+1}. So pairs that do not contain xx keep their values and the claim holds for them by induction. Now take y≠xy \ne x with xRyx \mathrel{R} y whose definition dominates pt+1p_{t+1}. Then y=copdy = c \mathbin{op} d with aRca \mathrel{R} c and bRdb \mathrel{R} d. First, c≠xc \ne x: otherwise the definition of xx dominates the definition of yy, and the definition of yy dominates the point just before xx, so by antisymmetry they are equal, which they are not. In the same way d≠xd \ne x. By the lemma, the latest yy computed valt(c)opvalt(d)\mathrm{val}_t(c) \mathbin{op} \mathrm{val}_t(d) without a trap. The definitions of cc and dd dominate the definition of yy, which dominates ptp_t, and the definitions of aa and bb dominate ptp_t by strictness. By induction at ptp_t, valt(a)=valt(c)\mathrm{val}_t(a) = \mathrm{val}_t(c) and valt(b)=valt(d)\mathrm{val}_t(b) = \mathrm{val}_t(d), where a constant operand has its own value and is congruent only to the same constant. So xx computes the same operation on the same values. It does not trap, and it writes valt(y)\mathrm{val}_t(y).

The run enters block BB from PP and runs the phis of BB. A definition that dominates the first point of BB and is not a phi of BB is in a block that strictly dominates BB. That block dominates PP, so the definition dominates ptp_t, the end of PP, and old pairs keep their values. A phi of BB is congruent only to phis of BB, because the label names the block. If xx and yy are phis of BB with xRyx \mathrel{R} y, their operands aPa_P and cPc_P for PP are the children at the same position, so aPRcPa_P \mathrel{R} c_P. Their definitions dominate the end of PP by strictness. By induction valt(aP)=valt(cP)\mathrm{val}_t(a_P) = \mathrm{val}_t(c_P), and both phis write this value. □\square

The proof of the op case shows more: when yy is about to run and a congruent xx dominates it, the latest xx was computed from operands equal to those of yy without a trap. So yy does not trap either, and it would write valt(x)\mathrm{val}_t(x).

4. The elimination keeps every outcome

The elimination walks the dominator tree and keeps, for each class, the first definition it meets on the current branch of the tree. A definition yy whose class already has a representative xx in scope becomes y = x. The definition of xx dominates the definition of yy: it is in a block that dominates the block of yy, or earlier in the same block, or, when yy is a phi, it is a phi of the same block, since only phis of the block share its label. A representative is always a definition that was kept.

Run SS and the new program S′S' on the same input, step by step. Both programs have the same blocks, terminators and number of instructions, so we show that they hold the same environment at every point. Assume it up to ptp_t.

  • A kept instruction runs the same way in both.
  • A replaced op yy: by the remark after the theorem, yy in SS does not trap and writes valt(x)\mathrm{val}_t(x), and the copy in S′S' writes the same value.
  • A replaced phi yy of BB becomes a copy after the phis of BB. In SS, yy and xx are congruent phis of BB, so by the theorem they get the same value on entry to BB. In S′S', xx is kept and gets that value, and the copy writes it into yy before any other instruction of BB reads yy. A phi of BB that reads yy reads it at the end of a predecessor, where both programs agree by induction.

So the two runs return the same value, trap at the same step, or run out of fuel at the same step. The SSA builder keeps the outcome of the original program (by the usual argument for SSA construction, with copies folded), so the whole transformation does. Each op of S′S' is an op of SS at the same place, so every run executes at most as many operations as before.

Complexity

The value graph has nn nodes and ee edges, with nn and ee linear in the size of the SSA form. Taking a class CC from the worklist costs O(∣C∣)O(|C|) plus the edges into CC, and a split costs time linear in the part that is moved. A class that contains a fixed node enters the worklist at most 1+log⁡2n1 + \log_2 n times, since each later entry is at most half of the class of the node before the split. So the refinement takes O((n+e)log⁡n)O((n + e) \log n) time, which Alpern, Wegman and Zadeck state as O(Elog⁡E)O(E \log E). The partition and the lists of users take Θ(n+e)\Theta(n + e) space. SSA construction and the dominator tree are near linear, and the elimination is one walk of the tree with a hash map, so the whole pass is dominated by the refinement.

Properties

  • Optimistic. It assumes equality and refutes it, so it finds the greatest fixed point: the coarsest congruence. A pessimistic method finds a congruence too, but it can be finer.
  • The result does not depend on the order. The coarsest congruence is unique, so any worklist order gives the same partition as naive round-by-round refinement.
  • Never more operations. Each operation is kept or replaced by a copy, so no run executes more operations than before.
  • No algebra. Operators are uninterpreted: x+yx + y and y+xy + x are different unless the operands are sorted first, and a⋅2a \cdot 2 and a+aa + a are never merged.
  • Phis are local to their block. Two phis are congruent only if they are in the same block, so equalities that move an operation through a phi are missed.

Variants and improvements

  • Commutative operators. Sort the two operands of a commutative operator by a fixed key before the refinement, or give such a node an unordered pair of children. The first is cheap and finds the common cases.
  • Constants and conditions. Click and Cooper combine optimistic value numbering with conditional constant propagation, in the style of sparse conditional constant propagation, so that a known constant can merge classes and an unreachable edge drops a phi operand.
  • Rewrite rules for phis. Rüthing, Knoop and Steffen alternate the AWZ partition with rules that move an operation through a phi, which finds more Herbrand equalities while staying polynomial.
  • Redundancy beyond dominance. Congruent values that do not dominate each other can be removed by partial redundancy elimination on value classes, which inserts computations where needed.

When to use it

Use AWZ when the program is in SSA form and loops carry values that step together, such as induction variables after unrolling or inlining. It finds what pessimistic hashing misses, in O((n+e)log⁡n)O((n + e) \log n) time. When most redundancy is in straight-line code, or when algebraic rules matter more than loops, dominator-based hashing with folding is simpler and almost as good. When a redundant value is computed on only some paths, use partial redundancy elimination.

Pitfalls

  • Congruent but not available. Congruent values in two branches of an if are equal where both are defined, but neither dominates the other. Replacing one by the other reads an undefined name on the other path.
  • Merging phis of different blocks. A phi label must name its block. Two phis phi [L: a, R: b] at two different joins can choose by different conditions, so they can differ on the same run.
  • Ignoring the operand order of a phi. The children of a phi follow the order of the predecessors of its block. Comparing them as a set merges phi [L: a, R: b] with phi [L: b, R: a].
  • Algebra that removes traps. AWZ itself never removes a trap, because it only replaces an op by a dominating congruent op that ran without a trap on equal operands. An added rule such as a/a=1a / a = 1 breaks this for a=0a = 0.
  • Non-strict SSA. The proof needs every use to be dominated by its definition. If a variable is read before it is defined on some path, the builder must give that path an explicit value, as the implementation does with 0.
  • Longer live ranges. A copy of a value defined far above keeps that value live, which can cost a register in a loop.

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.

alpern_wegman_zadeck_value_numbering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpern-wegman-zadeck-value-numbering/. The authors are listed in prov/1FT49Y.jsonl.
"""Alpern-Wegman-Zadeck value numbering on the toy IR.

awz(prog) takes a program without phis and without memory operations, puts it
in SSA form, finds the coarsest congruence of its value graph by Hopcroft
partition refinement, and replaces each definition that has a congruent
definition above it in the dominator tree by a copy. It returns the new
program and the partition.

The parts can be used alone: to_ssa builds SSA form with copies and constants
folded into the operands, value_graph builds the labeled graph, congruence
refines a partition, and eliminate does the replacement.
"""

import toyir


# ------------------------------------------------------------------ graphs


def normalize(prog):
    """A copy of prog without unreachable blocks and with an entry block that
    has no predecessor (a new block "start" is added if needed)."""
    seen = []
    stack = [prog.entry]
    reach = {prog.entry}
    while stack:
        b = stack.pop()
        seen.append(b)
        for s in toyir.succs(prog, b):
            if s not in reach:
                reach.add(s)
                stack.append(s)
    blocks = {}
    if any(prog.entry in toyir.succs(prog, b) for b in reach):
        name = "start"
        while name in prog.blocks:
            name += "_"
        blocks[name] = 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)
    return toyir.Program(list(prog.params), blocks)


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


def dominators(prog):
    """Immediate dominators by the iterative method of Cooper, Harvey and
    Kennedy. The entry maps to itself. Every block must be reachable."""
    rpo = reverse_postorder(prog)
    index = {b: i for i, b in enumerate(rpo)}
    preds = toyir.preds(prog)
    idom = {rpo[0]: rpo[0]}

    def meet(a, b):
        while a != b:
            while index[a] > index[b]:
                a = idom[a]
            while index[b] > index[a]:
                b = idom[b]
        return a

    changed = True
    while changed:
        changed = False
        for b in rpo[1:]:
            new = None
            for p in preds[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
    return idom


def dom_children(prog, idom):
    kids = {b: [] for b in prog.blocks}
    for b in prog.blocks:
        if b != prog.entry:
            kids[idom[b]].append(b)
    return kids


def dominates(idom, a, b):
    """True if block a dominates block b."""
    while True:
        if a == b:
            return True
        if idom[b] == b:
            return False
        b = idom[b]


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


# --------------------------------------------------------------------- SSA


def live_in(prog):
    """The names that are live on entry to each block of a program without
    phis."""
    gen, kill = {}, {}
    for b, blk in prog.blocks.items():
        g, k = set(), set()
        for ins in blk.instrs:
            g |= set(toyir.uses(ins)) - k
            k.add(toyir.defs(ins))
        g |= set(toyir.term_uses(blk.term)) - k
        gen[b], kill[b] = g, k
    live = {b: set() for b in prog.blocks}
    changed = True
    while changed:
        changed = False
        for b in reversed(list(prog.blocks)):
            out = set()
            for s in toyir.succs(prog, b):
                out |= live[s]
            new = gen[b] | (out - kill[b])
            if new != live[b]:
                live[b] = new
                changed = True
    return live


def to_ssa(prog):
    """SSA form of a program with only const, copy and op instructions.
    Copies and constants are folded into the operands that read them, so
    the result has only phis and ops. Version 0 of a parameter is the
    parameter itself, and the other versions are named base.k. A read of a
    name with no reaching definition reads 0; the programs we transform never
    do such a read. Phis are placed at the iterated dominance frontier of the
    definitions (minimal SSA, not pruned)."""
    prog = normalize(prog)
    for blk in prog.blocks.values():
        for ins in blk.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("awz handles const, copy and op only: %r" % (ins,))
    idom = dominators(prog)
    df = frontiers(prog, idom)
    kids = dom_children(prog, idom)
    preds = toyir.preds(prog)

    sites = {}
    for p in prog.params:
        sites.setdefault(p, set()).add(prog.entry)
    for label, blk in prog.blocks.items():
        for ins in blk.instrs:
            sites.setdefault(ins[1], set()).add(label)
    live = live_in(prog)
    phis = {b: [] for b in prog.blocks}
    for v in sites:
        work = list(sites[v])
        placed = set()
        while work:
            b = work.pop()
            for f in df[b]:
                if f not in placed:
                    placed.add(f)
                    if v in live[f]:
                        phis[f].append(v)
                    if f not in sites[v]:
                        work.append(f)
    for b in phis:
        phis[b].sort()

    taken = set(sites) | set(prog.params)
    counter = {}

    def fresh(v):
        while True:
            counter[v] = counter.get(v, 0) + 1
            name = "%s.%d" % (v, counter[v])
            if name not in taken:
                taken.add(name)
                return name

    stack = {v: [] for v in sites}
    for p in prog.params:
        stack[p].append(p)

    def cur(a):
        if isinstance(a, int):
            return a
        s = stack.get(a)
        return s[-1] if s else 0

    phi_name = {}
    phi_args = {}
    body = {}
    terms = {}

    def rename(b):
        pushed = []
        for v in phis[b]:
            name = fresh(v)
            phi_name[(b, v)] = name
            stack[v].append(name)
            pushed.append(v)
        out = []
        for ins in prog.blocks[b].instrs:
            x = ins[1]
            if ins[0] == "const":
                val = ins[2]
            elif ins[0] == "copy":
                val = cur(ins[2])
            else:
                val = fresh(x)
                out.append(("op", val, ins[2], cur(ins[3]), cur(ins[4])))
            stack[x].append(val)
            pushed.append(x)
        body[b] = out
        t = prog.blocks[b].term
        if t[0] == "br":
            terms[b] = ("br", cur(t[1]), t[2], t[3])
        elif t[0] == "ret":
            terms[b] = ("ret", cur(t[1]))
        else:
            terms[b] = t
        for s in toyir.succs(prog, b):
            for v in phis[s]:
                phi_args.setdefault((s, v), {})[b] = cur(v)
        for c in kids[b]:
            rename(c)
        for v in pushed:
            stack[v].pop()

    rename(prog.entry)
    blocks = {}
    for b in prog.blocks:
        instrs = []
        for v in phis[b]:
            args = phi_args[(b, v)]
            instrs.append(("phi", phi_name[(b, v)], {p: args[p] for p in preds[b]}))
        blocks[b] = toyir.Block(instrs + body[b], terms[b])
    return toyir.Program(list(prog.params), blocks)


# ------------------------------------------------------------ value graph


def value_graph(ssa):
    """The value graph of an SSA program: (nodes, label, children). A node
    is an SSA name or an integer constant. The label of an op is ("op", op),
    of a phi ("phi", block), of a parameter ("param", name) and of a
    constant ("const", k). The children of a phi follow the order of the
    predecessors of its block."""
    label = {}
    children = {}

    def leaf(a):
        if isinstance(a, int) and a not in label:
            label[a] = ("const", a)
            children[a] = ()
        return a

    for p in ssa.params:
        label[p] = ("param", p)
        children[p] = ()
    for b, blk in ssa.blocks.items():
        for ins in blk.instrs:
            if ins[0] == "phi":
                label[ins[1]] = ("phi", b)
                children[ins[1]] = tuple(leaf(a) for a in ins[2].values())
            else:
                label[ins[1]] = ("op", ins[2])
                children[ins[1]] = (leaf(ins[3]), leaf(ins[4]))
        t = blk.term
        if t[0] in ("br", "ret"):
            leaf(t[1])
    nodes = list(label)
    return nodes, label, children


# --------------------------------------------------- partition refinement


def congruence(nodes, label, children):
    """The coarsest partition of the nodes that refines the partition by
    label and in which nodes of one class have children in the same
    classes, position by position. Returns a dict node -> class number.
    Hopcroft's rule: after a split, only the smaller part goes into the
    worklist. The time is O((N + E) log N) for N nodes and E edges."""
    users = {}
    for n in nodes:
        for j, c in enumerate(children[n]):
            users.setdefault(c, []).append((j, n))
    members = []
    cls = {}
    first = {}
    for n in nodes:  # @line L3
        key = (label[n], len(children[n]))
        if key not in first:
            first[key] = len(members)
            members.append(set())
        cls[n] = first[key]
        members[first[key]].add(n)
    work = list(range(len(members)))  # @line L4
    while work:  # @line L5
        c = work.pop()  # @line L6
        pre = {}
        for m in list(members[c]):
            for j, u in users.get(m, ()):
                pre.setdefault(j, []).append(u)
        for j in sorted(pre):  # @line L7
            hit = {}
            for u in pre[j]:
                hit.setdefault(cls[u], set()).add(u)
            for d, part in hit.items():  # @line L8
                if len(part) == len(members[d]):
                    continue
                # Split in time O(|part|): move out the smaller side.
                if 2 * len(part) <= len(members[d]):  # @line L9
                    small = part
                    members[d] -= part
                else:
                    small = members[d] - part
                    members[d] = part
                new = len(members)
                members.append(small)
                for u in small:
                    cls[u] = new
                work.append(new)  # @line L10
    return cls


# -------------------------------------------------------------- elimination


def eliminate(ssa, cls):
    """Replace each phi or op whose class has a definition higher in the
    dominator tree, or earlier in the same block, by a copy of that
    definition. A replaced phi becomes a copy placed after the phis of its
    block. Returns a new program."""
    idom = dominators(ssa)
    kids = dom_children(ssa, idom)
    rep = {}
    for p in ssa.params:
        rep.setdefault(cls[p], p)
    blocks = {}

    def walk(b):  # @line L11
        added = []
        blk = ssa.blocks[b]
        phis, copies, rest = [], [], []
        for ins in blk.instrs:  # @line L12
            x = ins[1]
            c = cls[x]
            if c in rep:  # @line L13
                (copies if ins[0] == "phi" else rest).append(("copy", x, rep[c]))
            else:
                rep[c] = x  # @line L14
                added.append(c)
                (phis if ins[0] == "phi" else rest).append(ins)
        blocks[b] = toyir.Block(phis + copies + rest, blk.term)
        for k in kids[b]:
            walk(k)
        for c in added:
            del rep[c]

    walk(ssa.entry)
    return toyir.Program(list(ssa.params), {b: blocks[b] for b in ssa.blocks})  # @line L15


def awz(prog):
    """Returns (new program, partition) for a program with const, copy and
    op instructions only. The partition maps each node of the value graph
    of to_ssa(prog) to its class number."""
    ssa = to_ssa(prog)  # @line L1
    nodes, label, children = value_graph(ssa)  # @line L2
    cls = congruence(nodes, label, children)
    return eliminate(ssa, cls), cls
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_alpern_wegman_zadeck_value_numbering.py 412 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpern-wegman-zadeck-value-numbering/. The authors are listed in prov/1FT49Y.jsonl.

import itertools
import random

import toyir
from alpern_wegman_zadeck_value_numbering import (
    awz,
    congruence,
    dominates,
    dominators,
    to_ssa,
    value_graph,
)

# The example of the page: i and j step together, so a and b are equal.
PAGE = """
# params: n
entry:
  i = 1
  j = 1
  s = 0
  jump loop
loop:
  a = i * 4
  b = j * 4
  s = s + a
  s = s + b
  i = i + 1
  j = j + 1
  c = i <= n
  br c loop exit
exit:
  ret s
"""

PAGE_AFTER = """# params: n
entry:
  jump loop
loop:
  i.1 = phi [entry: 1, loop: i.2]
  s.1 = phi [entry: 0, loop: s.3]
  j.1 = i.1
  a.1 = i.1 * 4
  b.1 = a.1
  s.2 = s.1 + a.1
  s.3 = s.2 + b.1
  i.2 = i.1 + 1
  j.2 = i.2
  c.1 = i.2 <= n
  br c.1 loop exit
exit:
  ret s.3
"""

# Two branches compute the same sum, and the phis that merge them are
# congruent. The two divisions are congruent, but neither dominates the
# other, so both stay.
DIAMOND = """
# params: x, y, p
entry:
  br p left right
left:
  u = x + y
  v = x + y
  q = x / y
  jump join
right:
  u = y
  v = y
  jump join
join:
  w = u - v
  r = x / y
  ret w
"""


# ------------------------------------------------------------------ helpers


def trace(prog, args, fuel=20000):
    """Run prog like toyir.run and also return the number of op
    instructions run and the environment at the end of each block, as a
    list of (label, env). Programs here have no memory operations."""
    env = dict(zip(prog.params, args))
    label, prev, ops, ends = prog.entry, None, 0, []
    while True:
        blk = prog.blocks[label]
        incoming = []
        rest = []
        for ins in blk.instrs:
            if ins[0] == "phi":
                incoming.append((ins[1], val(env, ins[2][prev])))
                fuel -= 1
            else:
                rest.append(ins)
        for x, v in incoming:
            env[x] = v
        for ins in rest:
            fuel -= 1
            if fuel < 0:
                return ("fuel",), ops, ends
            if ins[0] == "const":
                env[ins[1]] = ins[2]
            elif ins[0] == "copy":
                env[ins[1]] = val(env, ins[2])
            else:
                ops += 1
                try:
                    env[ins[1]] = toyir._binop(ins[2], val(env, ins[3]), val(env, ins[4]))
                except toyir._Trap:
                    return ("trap",), ops, ends
        fuel -= 1
        if fuel < 0:
            return ("fuel",), ops, ends
        ends.append((label, dict(env)))
        t = blk.term
        if t[0] == "ret":
            return ("ret", val(env, t[1])), ops, ends
        if t[0] == "jump":
            prev, label = label, t[1]
        else:
            prev, label = label, (t[2] if val(env, t[1]) != 0 else t[3])


def val(env, a):
    return a if isinstance(a, int) else env[a]


def shadowed(prog):
    """Add a shadow v_s of every variable v that is computed by the same
    instructions, so that v_s and v always hold the same value."""
    def sh(a):
        return a if isinstance(a, int) else a + "_s"

    blocks = {}
    for label, blk in prog.blocks.items():
        out = []
        if label == prog.entry:
            out += [("copy", sh(p), p) for p in prog.params]
        for ins in blk.instrs:
            out.append(ins)
            if ins[0] == "const":
                out.append(("const", sh(ins[1]), ins[2]))
            elif ins[0] == "copy":
                out.append(("copy", sh(ins[1]), sh(ins[2])))
            else:
                out.append(("op", sh(ins[1]), ins[2], sh(ins[3]), sh(ins[4])))
        blocks[label] = toyir.Block(out, blk.term)
    return toyir.Program(list(prog.params), blocks)


def programs(seed, count):
    rng = random.Random(seed)
    for k in range(count):
        p = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 7), k % 2 == 0)
        yield rng, (shadowed(p) if k % 3 == 0 else p)


def def_blocks(ssa):
    where = {p: ssa.entry for p in ssa.params}
    for b, blk in ssa.blocks.items():
        for ins in blk.instrs:
            where[ins[1]] = b
    return where


def classes(cls):
    out = {}
    for n, c in cls.items():
        out.setdefault(c, set()).add(n)
    return {frozenset(s) for s in out.values()}


def moore(nodes, label, children):
    """The naive refinement: split by (class, classes of the children)
    until nothing changes."""
    cls = {n: (label[n], len(children[n])) for n in nodes}
    while True:
        sig = {n: (cls[n], tuple(cls[c] for c in children[n])) for n in nodes}
        if len(set(sig.values())) == len(set(cls.values())):
            return cls
        cls = sig


def set_partitions(items):
    if not items:
        yield []
        return
    first, rest = items[0], items[1:]
    for part in set_partitions(rest):
        for i in range(len(part)):
            yield part[:i] + [[first] + part[i]] + part[i + 1:]
        yield [[first]] + part


def random_graph(rng, n):
    nodes = list(range(n))
    label, children = {}, {}
    for v in nodes:
        k = rng.randint(0, 2)
        label[v] = rng.choice("ab") if k else rng.choice("xy")
        children[v] = tuple(rng.randrange(n) for _ in range(k))
    return nodes, label, children


def hash_numbering(ssa):
    """Pessimistic value numbering: visit the blocks in reverse postorder
    and give a phi a known number only if all its operands are numbered."""
    from alpern_wegman_zadeck_value_numbering import reverse_postorder

    num, table = {}, {}

    def of(a):
        if isinstance(a, int):
            return ("const", a)
        return num.get(a, ("fresh", a))

    for p in ssa.params:
        num[p] = ("param", p)
    for b in reverse_postorder(ssa):
        for ins in ssa.blocks[b].instrs:
            if ins[0] == "phi":
                if any(isinstance(a, str) and a not in num for a in ins[2].values()):
                    num[ins[1]] = ("fresh", ins[1])
                    continue
                key = ("phi", b) + tuple(of(a) for a in ins[2].values())
            else:
                key = ("op", ins[2], of(ins[3]), of(ins[4]))
            num[ins[1]] = table.setdefault(key, ("v", len(table)))
    return num


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


def test_page_example():
    prog = toyir.parse(PAGE)
    out, cls = awz(prog)
    assert toyir.show(out) == PAGE_AFTER
    for n in (0, 1, 2, 5):
        assert toyir.run(out, [n]) == toyir.run(prog, [n])
    assert toyir.run(out, [3]) == ("ret", 48)
    _, before, _ = trace(to_ssa(prog), [3])
    _, after, _ = trace(out, [3])
    assert (before, after) == (21, 15)


def test_optimistic_finds_what_hashing_misses():
    ssa = to_ssa(toyir.parse(PAGE))
    _, cls = awz(toyir.parse(PAGE))
    assert cls["i.1"] == cls["j.1"] and cls["a.1"] == cls["b.1"]
    num = hash_numbering(ssa)
    assert num["i.1"] != num["j.1"] and num["a.1"] != num["b.1"]


def test_diamond():
    prog = toyir.parse(DIAMOND)
    ssa = to_ssa(prog)
    out, cls = awz(prog)
    assert cls["u.1"] == cls["v.1"] and cls["u.2"] == cls["v.2"]
    assert cls["q.1"] == cls["r.1"]
    assert cls["w.1"] != cls["u.2"]
    text = toyir.show(out)
    assert "v.1 = u.1" in text and "v.2 = u.2" in text
    assert "r.1 = x / y" in text
    for args in ([3, 4, 0], [3, 4, 1], [3, 0, 0], [3, 0, 1]):
        assert toyir.run(out, args) == toyir.run(prog, args) == toyir.run(ssa, args)


def test_same_outcome_on_random_programs():
    for rng, prog in programs(11, 300):
        out, _ = awz(prog)
        ssa = to_ssa(prog)
        for _ in range(8):
            args = [rng.randint(-4, 9), rng.randint(-4, 9)]
            want = toyir.run(prog, args)
            assert want[0] != "fuel"
            assert toyir.run(ssa, args) == want
            assert toyir.run(out, args) == want


def test_never_more_operations():
    for rng, prog in programs(12, 200):
        out, _ = awz(prog)
        for _ in range(6):
            args = [rng.randint(-4, 9), rng.randint(-4, 9)]
            r0, n0, _ = trace(prog, args)
            r1, n1, _ = trace(out, args)
            assert r0 == r1 == toyir.run(prog, args)
            assert n1 <= n0


def test_shadows_are_found():
    rng = random.Random(13)
    checked = 0
    for k in range(150):
        p = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 7), k % 2 == 0)
        ssa = to_ssa(shadowed(p))
        _, cls = awz(shadowed(p))
        for blk in ssa.blocks.values():
            phi_of = {ins[1].partition(".")[0]: ins[1] for ins in blk.instrs if ins[0] == "phi"}
            for i, ins in enumerate(blk.instrs):
                base = ins[1].partition(".")[0]
                if not base.endswith("_s"):
                    continue
                # A shadow phi has the phi of its variable in the same block,
                # and a shadow op follows the op it copies.
                twin = phi_of[base[:-2]] if ins[0] == "phi" else blk.instrs[i - 1][1]
                assert cls[ins[1]] == cls[twin]
                checked += 1
    assert checked > 300


def test_congruent_names_hold_equal_values():
    for rng, prog in programs(14, 200):
        ssa = to_ssa(prog)
        nodes, label, children = value_graph(ssa)
        cls = congruence(nodes, label, children)
        idom = dominators(ssa)
        where = def_blocks(ssa)
        by = {}
        for n in where:
            by.setdefault(cls[n], []).append(n)
        for _ in range(6):
            args = [rng.randint(-4, 9), rng.randint(-4, 9)]
            _, _, ends = trace(ssa, args)
            for label_, env in ends:
                for names in by.values():
                    live = [n for n in names if dominates(idom, where[n], label_)]
                    assert len({env[n] for n in live}) <= 1


def herbrand_terms(ssa, path):
    """The Herbrand term of every name at the end of each block of a path:
    parameters are atoms, constants are integers, an op is a tuple."""
    env = {p: ("param", p) for p in ssa.params}
    out = []
    prev = None
    for label in path:
        blk = ssa.blocks[label]
        new = {}
        for ins in blk.instrs:
            if ins[0] == "phi":
                a = ins[2][prev]
                new[ins[1]] = a if isinstance(a, int) else env[a]
        env.update(new)
        for ins in blk.instrs:
            if ins[0] == "op":
                a, b = ins[3], ins[4]
                ta = a if isinstance(a, int) else env[a]
                tb = b if isinstance(b, int) else env[b]
                env[ins[1]] = (ins[2], ta, tb)
        out.append((label, dict(env)))
        prev = label
    return out


def test_congruence_implies_herbrand_equivalence():
    rng = random.Random(15)
    for k in range(150):
        p = toyir.random_program(rng, rng.randint(2, 4), rng.randint(2, 6), True)
        if k % 2 == 0:
            p = shadowed(p)
        ssa = to_ssa(p)
        nodes, label, children = value_graph(ssa)
        cls = congruence(nodes, label, children)
        idom = dominators(ssa)
        where = def_blocks(ssa)
        for path in toyir.paths(ssa):
            for lab, env in herbrand_terms(ssa, path):
                for x, y in itertools.combinations(sorted(where), 2):
                    if cls[x] == cls[y] and dominates(idom, where[x], lab) and dominates(idom, where[y], lab):
                        assert env[x] == env[y]


def test_hopcroft_equals_naive_refinement():
    rng = random.Random(16)
    for k in range(300):
        if k % 2:
            nodes, label, children = random_graph(rng, rng.randint(1, 30))
        else:
            p = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 7), k % 4 == 0)
            nodes, label, children = value_graph(to_ssa(shadowed(p)))
        assert classes(congruence(nodes, label, children)) == classes(moore(nodes, label, children))


def test_coarsest_by_brute_force():
    rng = random.Random(17)
    for _ in range(60):
        nodes, label, children = random_graph(rng, rng.randint(1, 7))
        best = classes(congruence(nodes, label, children))
        found = False
        for part in set_partitions(nodes):
            c = {v: i for i, block in enumerate(part) for v in block}
            if any(label[u] != label[v] or len(children[u]) != len(children[v]) for block in part for u in block for v in block):
                continue
            ok = all(
                c[children[u][j]] == c[children[v][j]]
                for block in part
                for u in block
                for v in block
                for j in range(len(children[u]))
            )
            if not ok:
                continue
            # Every congruence refines the one AWZ finds.
            assert all(any(set(block) <= b for b in best) for block in part)
            found = found or {frozenset(block) for block in part} == best
        assert found

History

Alpern, Wegman and Zadeck presented the algorithm at POPL 1988, together with the companion paper of Rosen, Wegman and Zadeck on global value numbers and redundant computations, which also uses SSA form. AWZ took the partition refinement of Hopcroft's 1971 DFA minimization and applied it to the value graph, which made the optimistic assumption cheap. Muchnick presents it as the global value numbering of his textbook. Later work measured what it misses: Rüthing, Knoop and Steffen added rules for phis in 1999, and Gulwani and Necula gave a polynomial algorithm for Herbrand equivalence in 2004 and noted that AWZ is incomplete because it treats phis as uninterpreted.

References

  1. Bowen Alpern, Mark N. Wegman and F. Kenneth Zadeck, Detecting equality of variables in programs, Proceedings of the 15th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL 1988), 1-11, the whole paper (the value graph of SSA form, congruence, the optimistic partition by the method of Hopcroft in O(E log E) time, and the proof that congruent variables are equal where both are defined)
  2. Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Global value numbers and redundant computations, Proceedings of the 15th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL 1988), 12-27, the whole paper (the companion paper on removing redundant computations with global value numbers)
  3. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Section 12.4.2 (Global Value Numbering, the value graph and the partitioning algorithm)
  4. Cliff Click and Keith D. Cooper, Combining analyses, combining optimizations, ACM Transactions on Programming Languages and Systems 17(2), 1995, 181-196, the whole paper (conditional constant propagation and value numbering combined in one optimistic analysis)
  5. Oliver Rüthing, Jens Knoop and Bernhard Steffen, Detecting equalities of variables, combining efficiency with precision, Static Analysis Symposium (SAS 1999), LNCS 1694, 232-247, the whole paper (rewrite rules for phis, alternated with the AWZ partition, to find more equalities)
  6. Sumit Gulwani and George C. Necula, A polynomial-time algorithm for global value numbering, Static Analysis Symposium (SAS 2004), LNCS 3148, 212-227, Section 1 (AWZ is incomplete because it treats phi functions as uninterpreted)

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