Algorithm Search⌘K

Algorithmintro

Local value numbering

Also called LVN.

Gives each value in a basic block a number by hashing operator and operand numbers, so equal expressions get the same number.

Time
Θ(n) expected
Space
Θ(n) extra
Where
n = the number of instructions in the basic block
Properties
deterministiconlineiterative

Local value numbering (LVN) finds the operations in a basic block that compute a value the block has already computed, and replaces them by a copy. It gives every value a number. Two operations get the same number when they apply the same operator to operands with the same numbers, and a hash table keyed by (operator, number, number) finds this in expected constant time. With a few extra rules the same pass also does constant folding and safe algebraic identities. It is the local, one-block form of common subexpression elimination, and the base of global value numbering.

In plain words

Read the block from top to bottom and give each value a ticket number. A variable read for the first time gets a new ticket. When an instruction adds two values, look up "plus, with these two tickets" in a table. If the table already has an answer, the block computed this sum before, so the instruction can copy that earlier result instead of adding again. If not, the sum gets a new ticket and goes into the table. The ticket belongs to the value, not to the variable, so a copy or a different variable name does not hide a repeat. When a variable gets a new value, it gets a new ticket, and the old result can no longer be copied from it.

The problem

The input is one basic block of the toy IR of three-address code: a list of nn instructions with no jump into or out of the middle. The output is a block of the same length in which some op instructions are replaced by a constant or by a copy x = y, such that from every state on entry the new block traps exactly when the old one does and otherwise leaves the same state. The goal is to replace as many operations as possible whose value the block already holds in some name.

Two operations compute the same value if their operands hold the same values. This is undecidable in general (see the full employment theorem), and LVN finds a decidable part of it: equal operators applied to operands that are equal by construction in the block, plus constant folding and a fixed list of identities. It does not know facts that come from other blocks or from algebra beyond that list.

The algorithm

VN maps names to value numbers, CONST maps a number to its constant, KEY maps an expression key to a number, and HOLDERS maps a number to the names that were given it, oldest first.

  1. LVN(B)
  2. 1VN, CONST, KEY, HOLDERS <- empty maps
  3. 2for each instruction I of B, in order, do
  4. 3if I is a store then keep I and continue with the next instruction
  5. 4if I is x = k then v <- NUMBER(k)
  6. 5else if I is x = a then v <- NUMBER(a)
  7. 6else if I is x = a op b then
  8. 7va <- NUMBER(a); vb <- NUMBER(b)
  9. 8if CONST has va and vb and op does not trap on CONST[va], CONST[vb] then
  10. 9r <- CONST[va] op CONST[vb]; replace I by x = r; v <- NUMBER(r)
  11. 10else if a safe identity turns a op b into a constant or an operand c then
  12. 11replace I by x = c; v <- NUMBER(c)
  13. 12else key <- (op, va, vb), with va and vb sorted if op is commutative
  14. 13if key is in KEY then v <- KEY[key]
  15. 14if some n in HOLDERS[v] has VN[n] = v then replace I by x = n
  16. 15else v <- a new number
  17. 16KEY[key] <- v
  18. 17else v <- a new number (phi, load, call, alloc, addr)
  19. 18VN[x] <- v; append x to HOLDERS[v]
  20. 19return B
  21. NUMBER(a)
  22. 20if a is an integer k then
  23. 21if k has no number, give it a new number u and set CONST[u] <- k
  24. 22return the number of k
  25. 23if a is not in VN then VN[a] <- a new number; append a to HOLDERS[VN[a]]
  26. 24return VN[a]

Line L8 computes with the semantics of the target: in the toy IR / truncates toward zero, and /, % trap on a zero divisor and the shifts on a count outside 0 to 63. The identities of line L10 are a+0a + 0, a−0a - 0, a⋅1a \cdot 1, a/1a / 1, a≪0a \ll 0, a≫0a \gg 0, a∣0a \mathbin{|} 0, a⊕0a \oplus 0 and a&aa \mathbin{\&} a (to aa), a⋅0a \cdot 0, a&0a \mathbin{\&} 0, a−aa - a, a⊕aa \oplus a, a%1a \% 1, a%(−1)a \% (-1) (to 0), and a=aa = a, a≤aa \le a (to 1) and a<aa < a, a≠aa \ne a (to 0), where a−aa - a means two operands with the same number. None of them removes a trap: a/a→1a / a \to 1 and 0/a→00 / a \to 0 are not in the list, because they are wrong for a=0a = 0. The commutative operators are ++, ⋅\cdot, &\&, ∣|, ⊕\oplus, == and ≠\ne.

Line L14 is the subtle step. The table remembers that a value was computed, but the name that held it may have been overwritten since. HOLDERS keeps all names that were given the number, and the check VN[n]=v\mathrm{VN}[n] = v skips the ones that now hold something else. If no name holds the value any more, the instruction is kept, and its destination gets the old number, because it computes the same value. Line L17 gives a fresh number to every value that LVN cannot describe by a key: a phi (its operands come from other blocks), a load (memory may have changed), a call, alloc and addr. A store and a call keep their place and are never removed or merged.

The implementation keeps each holder list as a queue and drops stale names from its front, so that each name is passed over at most once.

Example

The parameters are x, y and d. The table lists the numbers that the implementation gives, in order: x is 1, y is 2, and so on.

instruction numbers result
a = x + y key (+,1,2)(+, 1, 2) is new, gets 3 kept, a is 3
b = y + x commutative, key (+,1,2)(+, 1, 2), number 3, holder a b = a
a = 17 constant 17 is 4 kept, a is now 4
c = x + y key (+,1,2)(+, 1, 2), number 3; holder a is stale, b holds 3 c = b
e = c * 1 identity a⋅1a \cdot 1 e = c
f = a * 2 both constant: 17⋅2=3417 \cdot 2 = 34 f = 34
g = x / d d is 8, key (/,1,8)(/, 1, 8) is new, gets 9 kept
h = x / d key (/,1,8)(/, 1, 8), number 9, holder g h = g
k = d / d no identity for a/aa / a; key (/,8,8)(/, 8, 8) is new kept
r = g - h both operands have number 9: a−aa - a r = 0
t = c + f, t = t + h, t = t + k three new keys kept
t = t + r r has the number of 0: a+0a + 0 t = t

The block ends with ret t. Before LVN a run executes 13 operations; after it, 6: a, g, k and the three sums. For x=7x = 7, y=2y = 2, d=3d = 3 both blocks return 9+34+2+1+0=469 + 34 + 2 + 1 + 0 = 46. For d=0d = 0 both trap at g = x / d: the replaced division h = x / d could not trap on its own, because g = x / d ran before it with the same values. The copy t = t and the unused names are left for copy propagation and dead code elimination.

The classic block of Cooper and Torczon shows why the key holds numbers, not names:

a = b + c
b = a - d
c = b + c
d = a - d

d = a - d becomes d = b, because a and d still hold the values they had when b = a - d ran. But c = b + c is not the same as a = b + c: b got a new number in between, so the key differs.

Correctness

The full proof is in the proof file. It gives each value number vv a value val(v)\mathrm{val}(v) in the run that it describes: the entry value of a name, a constant, the result of the instruction that created a key, or the value written by a phi, load or call. Two invariants hold after each instruction: every name in VN holds val\mathrm{val} of its number, and every key in KEY was created by an instruction that ran without a trap. From them, each case of the algorithm writes the same value as the original instruction, and traps exactly when it does:

  • a folded instruction does not trap and writes the value that the target computes from the same constants;
  • an identity holds for all integers and never has a trap on one side only;
  • a key that is already in KEY was computed by an earlier instruction from operands with the same values, without a trap. So the current instruction cannot trap either, and a current holder has its value.

So the two blocks move through the same states. This is the simulation argument used for every local rewrite: each changed name holds the same value at every use.

Proof: Local value numbering keeps the outcome of every runfull

Setting. The proof is about one basic block BB with instructions I1,…,InI_1, \ldots, I_n, and the block B′B' with instructions I1′,…,In′I'_1, \ldots, I'_n that LVN returns. The algorithm keeps instruction ii at position ii: Ii′I'_i is IiI_i, or it is a const or a copy with the same destination as IiI_i, and only an op instruction is ever replaced. The terminator does not change. We assume, as the toy IR does for its test programs, that no run reads a name before it is defined. A state is the environment of names, the memory, and the input of the calls; in the toy IR a run of a block is a function of its state on entry.

Fix any state σ0\sigma_0 on entry to BB, and run BB from σ0\sigma_0. Let σi\sigma_i be the state after I1,…,IiI_1, \ldots, I_i, if none of them traps. We show:

Theorem. Run BB and B′B' from the same entry state σ0\sigma_0. For each ii, IiI_i traps if and only if Ii′I'_i traps, and if neither traps, both programs are in the same state σi\sigma_i after position ii. Hence BB and B′B' trap at the same position or reach the terminator in the same state. Because each block maps every entry state to the same result, the programs before and after LVN make the same sequence of blocks and have the same outcome on every input: the same return value, the same trap, or no end.

The meaning of a value number. The algorithm creates each value number vv at most once, at one position of BB. Give it a value val(v)\mathrm{val}(v) in the run from σ0\sigma_0, by the way it was created:

  • a number created by NUMBER for a name aa that the block has not defined before: val(v)=σ0(a)\mathrm{val}(v) = \sigma_0(a);
  • a number created for an integer kk: val(v)=k\mathrm{val}(v) = k, and CONST maps vv to kk;
  • a number created at line L15 for the key (op,va,vb)(op, v_a, v_b): val(v)=val(va)opval(vb)\mathrm{val}(v) = \mathrm{val}(v_a) \mathbin{op} \mathrm{val}(v_b), the value that the instruction at that position computes in the run, if it does not trap;
  • a number created for a phi, load, call, alloc or addr at position ii: the value that IiI_i writes in the run.

Each val(v)\mathrm{val}(v) is fixed for the run, because a block is straight-line code and each position runs once.

Invariant. After the algorithm has handled position ii, and in a run that reaches position i+1i + 1 (no trap so far):

(I1) for every name nn in VN, σi(n)=val(VN[n])\sigma_i(n) = \mathrm{val}(\mathrm{VN}[n]);

(I2) for every key (op,va,vb)(op, v_a, v_b) in KEY, the instruction that created it ran without a trap, so val(va)opval(vb)\mathrm{val}(v_a) \mathbin{op} \mathrm{val}(v_b) is defined and equals val(KEY[op,va,vb])\mathrm{val}(\mathrm{KEY}[op, v_a, v_b]).

Both hold before position 1, where the maps are empty. NUMBER keeps (I1) when it adds a name aa that the block has not defined: aa still holds σ0(a)\sigma_0(a), which is val\mathrm{val} of its new number. A name that the block has defined is in VN already, because line L18 binds every destination.

Step. Assume the invariant and the theorem up to position i−1i - 1, so both programs are in state σi−1\sigma_{i-1}. Look at IiI_i.

  1. Not an op. Then Ii′=IiI'_i = I_i. Both programs run the same instruction from the same state, so they trap together or reach the same σi\sigma_i. For a phi, load, call, alloc or addr, xx gets a fresh number whose value is, by definition, what IiI_i wrote. For x = k the number is the one of kk, and xx holds kk. For x = a the number is the one of aa, and by (I1) xx now holds σi−1(a)=val(VN[a])\sigma_{i-1}(a) = \mathrm{val}(\mathrm{VN}[a]). A store defines no name. Every other name keeps its value and its number, so (I1) holds after line L18. KEY does not change, so (I2) holds.

  2. An op x = a op b, with va=VN[a]v_a = \mathrm{VN}[a] and vb=VN[b]v_b = \mathrm{VN}[b] after line L7. By (I1), σi−1(a)=val(va)\sigma_{i-1}(a) = \mathrm{val}(v_a) and σi−1(b)=val(vb)\sigma_{i-1}(b) = \mathrm{val}(v_b).

    a. Folding (L8, L9). CONST gives val(va)=c1\mathrm{val}(v_a) = c_1 and val(vb)=c2\mathrm{val}(v_b) = c_2, and the operation does not trap on (c1,c2)(c_1, c_2) under the semantics of the toy IR, which is the target. So IiI_i does not trap and writes r=c1opc2r = c_1 \mathbin{op} c_2. Ii′I'_i is x = r, which does not trap and writes the same value. The number of xx is the number of rr, whose value is rr.

    b. An identity (L10, L11). Each identity in the list is an equation that holds for all integers on which its left side is defined, and none of them has an operation that can trap on the left side and not on the right side, except where the divisor or the shift count is the constant that the identity requires (x/1x / 1, x%1x \% 1, x%−1x \% {-1}, x≪0x \ll 0, x≫0x \gg 0), and those never trap. So IiI_i does not trap and writes the value that Ii′I'_i writes: the constant of the identity or the current value of the operand it copies. The number of xx is the number of that constant or operand, and by (I1) its value is the value written.

    c. A key that is in KEY (L13, L14). Let v=KEY[key]v = \mathrm{KEY}[key]. The key is (op,va,vb)(op, v_a, v_b), with the operands swapped only for a commutative operator, for which val(va)opval(vb)=val(vb)opval(va)\mathrm{val}(v_a) \mathbin{op} \mathrm{val}(v_b) = \mathrm{val}(v_b) \mathbin{op} \mathrm{val}(v_a) for all integers. By (I2) the value val(va)opval(vb)\mathrm{val}(v_a) \mathbin{op} \mathrm{val}(v_b) is defined, so IiI_i, whose operands hold exactly these values, does not trap, and it writes val(v)\mathrm{val}(v). If a holder nn with VN[n]=v\mathrm{VN}[n] = v exists, Ii′I'_i is x = n; it reads a defined name, does not trap, and by (I1) writes σi−1(n)=val(v)\sigma_{i-1}(n) = \mathrm{val}(v). Otherwise Ii′=IiI'_i = I_i. In both cases xx gets the number vv and holds val(v)\mathrm{val}(v).

    d. A new key (L15, L16). Ii′=IiI'_i = I_i. If it traps, both programs trap here. Otherwise it writes val(va)opval(vb)\mathrm{val}(v_a) \mathbin{op} \mathrm{val}(v_b), which is by definition val\mathrm{val} of the fresh number vv, and the new entry of KEY was created by an instruction that ran without a trap, so (I2) holds.

    In each case the two programs trap together or write the same value to xx and nothing else, so both are in the same state σi\sigma_i. Only xx changed its number, and it holds the value of its new number, so (I1) holds. A holder list may still contain xx under its old number; line L14 checks VN[n]=v\mathrm{VN}[n] = v, so a stale holder is never used. □\square

Undefined names. Ii′I'_i reads only names that IiI_i reads or that are in VN. A name enters VN when the block defines it or when an earlier instruction reads it, so by the assumption it is defined in the run. So B′B' reads no undefined name.

The number of operations. An op instruction at position ii of B′B' is the op instruction IiI_i of BB, so every run of the program after LVN executes at most as many op instructions as the same run before it. This bound is about the count of operations; the total number of instructions is the same, because LVN replaces and never deletes.

Cost. Each instruction does a constant number of map lookups and inserts, plus the search for a holder at line L14. A name enters a holder list once per definition, at most nn entries in all for a block of nn instructions. The search drops stale names from the front of the list until it finds a current one, so each entry is dropped at most once, and each search costs O(1)O(1) plus the entries it drops. The whole block takes O(n)O(n) map operations, which is O(n)O(n) expected time with hash maps.

Complexity

Each instruction does a constant number of hash map lookups and inserts and one holder search. Each name enters a holder list once per definition, and each stale entry is dropped at most once, so the holder searches cost O(n)O(n) in total. With hashing the expected time is Θ(n)\Theta(n) for a block of nn instructions, and the maps take Θ(n)\Theta(n) space. A unit step here is one map operation on a key of three small integers.

Properties

  • One pass, in order. LVN reads the block once and decides each instruction from what came before it, so it can run while a front end emits the block.
  • Never more operations. The result has the same instructions in the same places, and an operation is only ever replaced by a constant or a copy. So every run executes at most as many operations as before, with the same total number of instructions.
  • Deterministic. The numbering depends only on the order of the instructions. Sorting the operands of commutative operators by number makes x + y and y + x meet.
  • Local. The maps are empty at the top of every block, so the result for one block does not depend on the others.

Variants and improvements

  • Superlocal value numbering. Run LVN along each path of an extended basic block, a tree of blocks in which every block but the root has one predecessor, and keep the maps of a block for its successors in the tree. Cooper and Torczon use scoped hash tables to undo the maps when they move back up the tree.
  • Dominator-based value numbering. On static single assignment form, the maps of a block can be passed to every block it dominates. No name is redefined in SSA, so the holder problem of line L14 disappears.
  • Global value numbering. Global value numbering proves equalities across blocks and through phi-functions, for example by the optimistic partitioning of Alpern, Wegman and Zadeck.
  • The DAG of a block. The same table builds the expression DAG of a block, in which each node is a key; this is hash consing of the expressions.
  • Loads. A load can get a key (load, number of the address) if every store, and every call, removes the load keys that may alias it. This needs alias analysis for any store through a pointer.

When to use it

Use LVN as an early, cheap cleanup inside each block, right after the front end and after inlining or unrolling, which create repeats. It is linear, needs no dataflow analysis, and does constant folding and simple identities in the same pass. It finds nothing across blocks, so a compiler that wants more runs it inside a superlocal or dominator-based scheme, or uses global value numbering and partial redundancy elimination.

Pitfalls

  • Copying from an overwritten name. After a = x + y; a = 17, the value of x + y is no longer in a. An implementation that keeps one name per number and does not check it replaces a later x + y by a, which gives 17.
  • Identities that remove traps. a/a→1a / a \to 1 and 0/a→00 / a \to 0 are false for a=0a = 0; the toy IR traps there. Only identities with a constant divisor or shift count that cannot trap are safe.
  • Folding with the host arithmetic. In Python -7 // 2 is −4-4, while the target gives −3-3. The folder must use the target rules.
  • Treating loads and calls as pure. Two loads from the same pointer can differ if a store or a call ran in between; two calls to the same function with the same arguments can return different values. LVN gives each of them a fresh number.
  • Longer live ranges. Replacing c = x + y by c = b keeps b alive longer. On a machine with few registers this can cause a spill that costs more than the addition.
  • Floating point. a+b=b+aa + b = b + a holds in IEEE arithmetic, but (a+b)+c=a+(b+c)(a + b) + c = a + (b + c) does not, and a−a=0a - a = 0 fails for infinities and NaN. Use only the rules that hold in the target arithmetic.

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.

local_value_numbering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-value-numbering/. The authors are listed in prov/CJTBEP.jsonl.
"""Local value numbering on the toy IR.

lvn_block(instrs) rewrites the instructions of one basic block and returns a
new list of the same length: the i-th instruction of the result replaces the
i-th instruction of the input. An operation becomes a constant when both
operands are known constants and it cannot trap, a copy or a constant when a
safe algebraic identity applies, and a copy of a name that still holds the
value when the same operation on the same value numbers was computed before
in the block. Every other instruction is kept. lvn(prog) applies lvn_block
to every block and returns a new program.
"""

from collections import deque

import toyir

COMMUTATIVE = ("+", "*", "&", "|", "^", "==", "!=")


def evaluate(op, a, b):
    """The value of a op b in the toy IR, or None if the operation traps.
    Division truncates toward zero, as on the target; Python's // does not."""
    if op in ("/", "%"):
        if b == 0:
            return None
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op in ("<<", ">>"):
        if b < 0 or b > 63:
            return None
        return a << b if op == "<<" else a >> b
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return 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)


def _identity(op, a, b, va, vb, ka, kb):
    """A safe algebraic identity for a op b. Returns ("name", a), ("name", b),
    ("const", k) or None. ka and kb are the known constants of the operands,
    or None. No identity removes a trap: x / x and 0 / x are not touched."""
    same = va == vb
    if op == "+":
        if kb == 0:
            return ("name", a)
        if ka == 0:
            return ("name", b)
    elif op == "-":
        if kb == 0:
            return ("name", a)
        if same:
            return ("const", 0)
    elif op == "*":
        if kb == 0 or ka == 0:
            return ("const", 0)
        if kb == 1:
            return ("name", a)
        if ka == 1:
            return ("name", b)
    elif op == "/":
        if kb == 1:
            return ("name", a)
    elif op == "%":
        if kb == 1 or kb == -1:
            return ("const", 0)
    elif op in ("<<", ">>"):
        if kb == 0:
            return ("name", a)
    elif op == "&":
        if kb == 0 or ka == 0:
            return ("const", 0)
        if same or kb == -1:
            return ("name", a)
        if ka == -1:
            return ("name", b)
    elif op == "|":
        if same or kb == 0:
            return ("name", a)
        if ka == 0:
            return ("name", b)
    elif op == "^":
        if same:
            return ("const", 0)
        if kb == 0:
            return ("name", a)
        if ka == 0:
            return ("name", b)
    elif op in ("==", "<="):
        if same:
            return ("const", 1)
    elif op in ("!=", "<"):
        if same:
            return ("const", 0)
    return None


class _Numbering:
    """The maps of one block: name -> VN, constant -> VN, VN -> constant,
    expression key -> VN, and VN -> the names that were given it."""

    def __init__(self):
        self.vn = {}
        self.const_vn = {}
        self.vn_const = {}
        self.table = {}
        self.holders = {}
        self.count = 0

    def fresh(self):
        self.count += 1
        return self.count

    def of_const(self, k):
        if k not in self.const_vn:  # @line L21
            v = self.fresh()
            self.const_vn[k] = v
            self.vn_const[v] = k
        return self.const_vn[k]  # @line L22

    def of(self, a):
        if isinstance(a, int):  # @line L20
            return self.of_const(a)
        if a not in self.vn:  # @line L23
            # First read in the block: the value the name has on entry.
            self.bind(a, self.fresh())
        return self.vn[a]  # @line L24

    def bind(self, x, v):
        self.vn[x] = v
        if v not in self.holders:
            self.holders[v] = deque()
        self.holders[v].append(x)

    def holder(self, v):
        """A name that holds value number v now, or None. Names that were
        redefined since they got v are dropped from the front of the list,
        so each name is passed over at most once per definition."""
        hs = self.holders.get(v)
        while hs and self.vn.get(hs[0]) != v:
            hs.popleft()
        return hs[0] if hs else None


def lvn_block(instrs):
    num = _Numbering()  # @line L1
    out = []
    for ins in instrs:  # @line L2
        kind = ins[0]
        new = ins
        if kind == "store":  # @line L3
            out.append(ins)
            continue
        if kind == "const":  # @line L4
            v = num.of_const(ins[2])
        elif kind == "copy":  # @line L5
            v = num.of(ins[2])
        elif kind == "op":  # @line L6
            x, op, a, b = ins[1], ins[2], ins[3], ins[4]
            va, vb = num.of(a), num.of(b)  # @line L7
            ka, kb = num.vn_const.get(va), num.vn_const.get(vb)
            r = None
            if ka is not None and kb is not None:  # @line L8
                r = evaluate(op, ka, kb)
            if r is not None:
                new = ("const", x, r)  # @line L9
                v = num.of_const(r)
            else:
                ident = _identity(op, a, b, va, vb, ka, kb)  # @line L10
                if ident is not None and isinstance(ident[1], int):
                    ident = ("const", ident[1])
                if ident is not None and ident[0] == "const":  # @line L11
                    new = ("const", x, ident[1])
                    v = num.of_const(ident[1])
                elif ident is not None:
                    new = ("copy", x, ident[1])
                    v = num.of(ident[1])
                else:
                    if op in COMMUTATIVE and vb < va:  # @line L12
                        va, vb = vb, va
                    key = (op, va, vb)
                    if key in num.table:  # @line L13
                        v = num.table[key]
                        h = num.holder(v)  # @line L14
                        if h is not None:
                            new = ("copy", x, h)
                    else:
                        v = num.fresh()  # @line L15
                        num.table[key] = v  # @line L16
        else:
            # phi, load, call, alloc, addr: a value this pass cannot name.
            v = num.fresh()  # @line L17
        out.append(new)
        num.bind(ins[1], v)  # @line L18
    return out  # @line L19


def lvn(prog):
    blocks = {}
    for label, blk in prog.blocks.items():
        blocks[label] = toyir.Block(lvn_block(blk.instrs), blk.term)
    return toyir.Program(list(prog.params), blocks)
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_local_value_numbering.py 280 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-value-numbering/. The authors are listed in prov/CJTBEP.jsonl.

import random

import toyir
from local_value_numbering import evaluate, lvn, lvn_block

PAGE = """
# params: x, y, d
entry:
  a = x + y
  b = y + x
  a = 17
  c = x + y
  e = c * 1
  f = a * 2
  g = x / d
  h = x / d
  k = d / d
  r = g - h
  t = c + f
  t = t + h
  t = t + k
  t = t + r
  ret t
"""

PAGE_AFTER = """
# params: x, y, d
entry:
  a = x + y
  b = a
  a = 17
  c = b
  e = c
  f = 34
  g = x / d
  h = g
  k = d / d
  r = 0
  t = c + f
  t = t + h
  t = t + k
  t = t
  ret t
"""

# The classic block of Cooper and Torczon: d = a - d is redundant, but
# c = b + c is not, because b was redefined in between.
CLASSIC = """
# params: b, c, d
entry:
  a = b + c
  b = a - d
  c = b + c
  d = a - d
  ret d
"""

# f adds its second argument to the cell p and returns the new value, so two
# equal calls give different results.
FUNC_F = toyir.parse(
    """
# params: p, a
entry:
  v = *p
  v = v + a
  *p = v
  ret v
"""
)

MEMORY = """
# params: x
entry:
  p = alloc
  *p = x
  u = *p
  *p = 5
  v = *p
  s = call f(p, x)
  t = call f(p, x)
  w = u + v
  w = w + s
  w = w + t
  ret w
"""


def count_ops(prog, args, fuel=10000):
    """Run a program without memory, phis or calls, and count the executed
    op instructions. Returns (outcome, count) with the outcome of toyir.run."""
    env = dict(zip(prog.params, args))
    label = prog.entry
    count = 0
    steps = 0

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

    while True:
        blk = prog.blocks[label]
        for ins in blk.instrs:
            steps += 1
            if steps > fuel:
                return ("fuel",), count
            if ins[0] == "const":
                env[ins[1]] = ins[2]
            elif ins[0] == "copy":
                env[ins[1]] = val(ins[2])
            else:
                count += 1
                r = evaluate(ins[2], val(ins[3]), val(ins[4]))
                if r is None:
                    return ("trap",), count
                env[ins[1]] = r
        steps += 1
        if steps > fuel:
            return ("fuel",), count
        t = blk.term
        if t[0] == "ret":
            return ("ret", val(t[1])), count
        if t[0] == "jump":
            label = t[1]
        else:
            label = t[2] if val(t[1]) != 0 else t[3]


def add_redundancy(rng, prog):
    """Insert, some instructions after an op instruction, a recomputation of
    the same operation into a variable x_i, sometimes with the operands
    swapped. The loop counters are never written."""
    names = ["x%d" % i for i in range(5)]
    for blk in prog.blocks.values():
        out = []
        pending = []
        for ins in blk.instrs:
            out.append(ins)
            if pending and rng.random() < 0.5:
                out.append(pending.pop(0))
            if ins[0] == "op" and rng.random() < 0.6:
                op, a, b = ins[2], ins[3], ins[4]
                if op in ("+", "*", "&", "|", "^", "==", "!=") and rng.random() < 0.5:
                    a, b = b, a
                pending.append(("op", rng.choice(names), op, a, b))
        blk.instrs = out + pending
    return prog


def same_shape(p, q):
    """The i-th instruction keeps its kind or becomes a const or a copy, and
    the destination and the terminators do not change."""
    assert list(p.blocks) == list(q.blocks)
    for label in p.blocks:
        a, b = p.blocks[label], q.blocks[label]
        assert a.term == b.term
        assert len(a.instrs) == len(b.instrs)
        for i, j in zip(a.instrs, b.instrs):
            if i[0] in ("op",):
                assert j == i or j[0] in ("const", "copy")
                assert j[1] == i[1]
            else:
                assert j == i


def test_page_example():
    p = toyir.parse(PAGE)
    q = lvn(p)
    assert toyir.show(q) == toyir.show(toyir.parse(PAGE_AFTER))
    for x in range(-6, 7):
        for y in range(-3, 4):
            for d in range(-3, 4):
                assert toyir.run(p, [x, y, d]) == toyir.run(q, [x, y, d])
    out, before = count_ops(p, [7, 2, 3])
    out2, after = count_ops(q, [7, 2, 3])
    assert out == out2 == ("ret", 9 + 34 + 2 + 1 + 0)
    assert (before, after) == (13, 6)
    # A zero divisor still traps at the first division.
    assert toyir.run(q, [7, 2, 0]) == ("trap",)


def test_classic_block():
    q = lvn(toyir.parse(CLASSIC))
    instrs = q.blocks["entry"].instrs
    assert instrs[2] == ("op", "c", "+", "b", "c")
    assert instrs[3] == ("copy", "d", "b")


def test_traps_are_kept():
    src = """
# params: x, y
entry:
  a = 0 / y
  b = y / y
  c = y % y
  e = x << y
  f = 7 / 0
  g = 1 << 64
  ret a
"""
    p = toyir.parse(src)
    q = lvn(p)
    assert q.blocks["entry"].instrs == p.blocks["entry"].instrs
    assert toyir.run(q, [3, 0]) == ("trap",)


def test_safe_identities():
    src = """
# params: x
entry:
  a = x * 0
  b = x % 1
  c = x - x
  e = x / 1
  f = x << 0
  g = x ^ x
  h = x <= x
  ret a
"""
    q = lvn(toyir.parse(src))
    kinds = [ins[0] for ins in q.blocks["entry"].instrs]
    assert kinds == ["const", "const", "const", "copy", "copy", "const", "const"]


def test_memory_and_calls_are_kept():
    p = toyir.parse(MEMORY)
    q = lvn(p)
    assert q.blocks["entry"].instrs == p.blocks["entry"].instrs
    for x in range(-4, 5):
        out = toyir.run(p, [x], funcs={"f": FUNC_F})
        assert out == toyir.run(q, [x], funcs={"f": FUNC_F})
    # u = x, v = 5, s = 5 + x, t = 5 + 2x
    assert toyir.run(q, [3], funcs={"f": FUNC_F}) == ("ret", 3 + 5 + 8 + 11)


def test_folding_uses_truncating_division():
    q = lvn(toyir.parse("# params: x\nentry:\n  a = -7 / 2\n  b = -7 % 2\n  c = 42 / -5\n  ret a\n"))
    assert q.blocks["entry"].instrs == [("const", "a", -3), ("const", "b", -1), ("const", "c", -8)]


def test_redefined_holder():
    src = """
# params: x, y
entry:
  a = x + y
  a = 0
  b = x + y
  ret b
"""
    q = lvn(toyir.parse(src))
    # No name holds x + y any more, so the operation is kept.
    assert q.blocks["entry"].instrs[2] == ("op", "b", "+", "x", "y")


def test_random_programs():
    rng = random.Random(20261115)
    hits = 0
    for trial in range(300):
        p = toyir.random_program(rng, 5, rng.randint(2, 8), acyclic=trial % 2 == 0)
        if trial % 3:
            add_redundancy(rng, p)
        q = lvn(p)
        same_shape(p, q)
        for _ in range(12):
            args = [rng.randint(-6, 6), rng.randint(-6, 6)]
            a, n1 = count_ops(p, args)
            b, n2 = count_ops(q, args)
            assert a == toyir.run(p, args)
            assert a == b
            assert n2 <= n1
            hits += n2 < n1
    assert hits > 100


def test_block_function_matches():
    rng = random.Random(7)
    p = add_redundancy(rng, toyir.random_program(rng, 4, 3, acyclic=True))
    for label, blk in p.blocks.items():
        assert lvn(p).blocks[label].instrs == lvn_block(blk.instrs)

History

Ershov described in 1958 how the BESM programming program numbered the operations of a formula and kept them in a table, so that a repeated operation was programmed once. Cocke and Schwartz gave a fuller description of value numbering in their 1970 Courant Institute notes on programming languages and their compilers. The dragon book builds the DAG of a basic block by the same value-number method. Cooper and Torczon present LVN with the extensions for commutative operators, constants and identities, and use it as the first step towards superlocal and dominator-based value numbering.

References

  1. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Section 8.4.1 (Local Value Numbering, with the extensions for commutative operations, constant folding and algebraic identities, and the problem of a name that is redefined) and Section 8.5.1 (Superlocal Value Numbering)
  2. Andrei P. Ershov, On programming of arithmetic operations, Communications of the ACM 1(8), 1958, 3-6, the numbering of the operations of a formula, so that an operation that is already programmed is found in a table and not programmed again
  3. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 12 (Early Optimizations), the section on value numbering, and Section 13.1 (Common-Subexpression Elimination)
  4. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 6.1.2 (The Value-Number Method for Constructing DAGs) and Section 8.5 (Optimization of Basic Blocks, the DAG of a block and local common subexpressions)

Where this leads

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