Algorithm Search⌘K

Algorithmadvanced

Bottom-up rewrite system

Also called BURS, BURG.

Precomputes the dynamic programming of optimal tree tiling into tables, so a code generator labels each node by table lookup.

Time
Θ(n) worst
Space
Θ(n) extra
Where
n = the number of nodes of the tree
Properties
deterministicofflinerecursive
Origin
Eduardo Pelegrí Llopart, Susan L. Graham, 1988

A bottom-up rewrite system, or BURS, is a way to build an optimum tree tiler ahead of time. It solves the instruction selection problem for trees with the same answer as the tiling dynamic program of Aho and Johnson, but it does the dynamic program when the code generator is built, not when it runs. Each node then gets a state by one table lookup from its operator and the states of its children, and the states hold all the information needed to read off a least-cost tiling. BURG, by Fraser, Henry and Proebsting, is the best known generator of such tables. The method works only if the number of states is finite, which holds for most machine grammars but not for all.

In plain words

The tiling dynamic program does the same arithmetic again and again. At every node it adds up costs from the children and keeps the cheapest tile for each kind of result.

BURS notices that only the differences between these costs matter for the choice. A subtree can be very big, but the cost to get it into a register is often just "the cost to get it into an address, plus one". So the algorithm keeps only the differences. Then the possible cost lists are few, and each one gets a number.

Before any program is compiled, the generator works out all these lists and builds a table: for an operator and the numbers of its children, the table gives the number of the node. At compile time, the code generator only looks up the table, from the leaves up. Then it walks down and writes the chosen instructions.

The problem

The input is an expression tree TT with nn nodes and a tree grammar that describes the machine. A grammar has nonterminals, such as reg for a value in a register, and two kinds of rules, each with a cost:

  • a base rule X→op(Y1,…,Yk)X \to \mathrm{op}(Y_1, \ldots, Y_k): a node with operator op can be derived from XX if its children can be derived from Y1,…,YkY_1, \ldots, Y_k;
  • a chain rule X→YX \to Y: a value of kind YY can be turned into a value of kind XX.

A pattern of the instruction table becomes rules of this form. Each inner node of a big pattern gets a fresh helper nonterminal with a rule of cost 0. With the table of maximal munch and the Aho-Johnson page, the rules are:

rule cost from
con →\to CONST, var →\to VAR 0 the leaves
reg →\to con 1 LI
reg →\to var 3 LD
reg →\to ADD(reg, reg) 1 ADD
reg →\to ADD(reg, con) 1 ADDI
reg →\to ADD(reg, var) 3 ADDM
reg →\to MUL(reg, reg) 3 MUL
reg →\to MEM(reg) 3 LDR
h1→h_1 \to ADD(reg, con), reg →\to MEM(h1h_1) 0, 3 LDO
h2→h_2 \to ADD(reg, reg), reg →\to MEM(h2h_2) 0, 3 LDX
h3→h_3 \to MUL(reg, reg), reg →\to ADD(h3h_3, reg) 0, 2 MADD

A derivation of the tree from reg is exactly a tiling, and it has the same cost. The output is a least-cost derivation, and the code that it gives. Registers are virtual, so there is no register limit.

The algorithm

A state is a set of entries (X,δX,ρX)(X, \delta_X, \rho_X): a nonterminal, its cost relative to the cheapest nonterminal of the node, and the rule that reaches this cost.

  1. BUILD(grammar) ▷ when the code generator is built
  2. 1for each leaf operator a do table[a] ← STATE(a, ())
  3. STATE(op, s_1, ..., s_k):
  4. 2for each base rule X → op(Y_1, ..., Y_k) with each Y_i in s_i do
  5. 3total ← cost of the rule + sum over i of δ_{Y_i} in s_i; keep the least total for X, with its rule
  6. 4repeat: for each chain rule X → Y, if δ_Y + its cost < δ_X then lower δ_X and keep the rule; until nothing changes
  7. 5subtract the least δ from every entry, and return the set of entries
  8. 6repeat: for each operator op and each tuple of known states, table[op, s...] ← STATE(op, s...); until no new state appears
  9. LABEL(v) ▷ when a program is compiled
  10. 7for each child u of v do LABEL(u)
  11. 8state(v) ← table[op(v), state of each child]
  12. REDUCE(v, X)
  13. 9ρ ← the rule of X in state(v)
  14. 10if ρ is a chain rule X → Y then REDUCE(v, Y) and emit the instruction of ρ
  15. 11else ρ is X → op(Y_1, ..., Y_k):
  16. 12for each child u_i of v do REDUCE(u_i, Y_i); emit the instruction of ρ, unless X is a helper

The code generator calls LABEL(root) and then REDUCE(root, reg). A helper passes the operands of its node up to the rule above it, so one instruction such as LDX gets the operands of both the MEM and the ADD.

Example

BUILD on the grammar of the page finds 11 states. Here is the labeling of T=MEM(ADD(MUL(a,b),c))T = \mathrm{MEM}(\mathrm{ADD}(\mathrm{MUL}(a, b), c)):

node state entries (XX: δX\delta_X, rule)
aa, bb, cc 1 var: 0, var →\to VAR; reg: 3, LD
MUL(a,b)(a, b) 5 h3h_3: 0; reg: 3, MUL
ADD(…,c)(\ldots, c) 9 reg: 0, MADD; h2h_2: 1
MEM 2 reg: 0, LDR

At the MUL node, h3→MUL(reg,reg)h_3 \to \mathrm{MUL}(\mathrm{reg}, \mathrm{reg}) costs 0+3+3=60 + 3 + 3 = 6 and MUL costs 3+3+3=93 + 3 + 3 = 9, so the relative costs are 0 and 3. At the ADD node, MADD gives 2+0+3=52 + 0 + 3 = 5, ADD gives 1+3+3=71 + 3 + 3 = 7, ADDM gives 3+3+0=63 + 3 + 0 = 6, and h2h_2 gives 0+3+3=60 + 3 + 3 = 6. The best for reg is MADD, and h2h_2 is 1 more. At the root, LDR gives 3+0=33 + 0 = 3, and LDX gives 3+1=43 + 1 = 4, so LDR wins.

REDUCE(root, reg) emits LD aa, LD bb, LD cc, MADD, LDR, for a cost of 14. That is the least tiling cost; maximal munch picks LDX at the root and pays 15. The absolute cost never appears at compile time. The numbers in the states are the same for any tree, however big, that reaches the same state.

Correctness

The key fact is shift invariance. At a node, every base rule adds the costs of the children, so if each child cost is changed by a constant, every candidate total changes by the same sum of constants. The best rule for each nonterminal stays the same, and so do the differences between the totals. The chain rules, at line L4, are a shortest path problem on the nonterminals, solved by the Bellman-Ford method, and a shift does not change it either. So the state of a node, with costs taken relative to the cheapest entry, depends only on its operator and the states of its children. That is what makes a table possible.

By induction on the tree, the state of each node holds, for each nonterminal XX, the true least cost of deriving the subtree from XX, minus the least cost over all nonterminals, and a rule that starts such a least derivation. REDUCE follows these rules from the root down and emits a least-cost derivation from reg, which is a least-cost tiling. The proof file gives the details.

Proof: BURS states hold the relative least costs, and the reduction gives a least-cost tilingfull

We use the grammar and the pseudocode of the page. The grammar has nonterminals, base rules X→op(Y1,…,Yk)X \to \mathrm{op}(Y_1, \ldots, Y_k) and chain rules X→YX \to Y, each with a cost c≥0c \ge 0. A derivation of a tree TvT_v from XX is a base rule X→op(Y1,…,Yk)X \to \mathrm{op}(Y_1, \ldots, Y_k) with op=op(v)\mathrm{op} = \mathrm{op}(v) and a derivation of the ii-th child of vv from YiY_i for each ii, or a chain rule X→YX \to Y and a derivation of TvT_v from YY. Its cost is the sum of the costs of its rules. Let LX(v)L_X(v) be the least cost of a derivation of TvT_v from XX, or ∞\infty if there is none.

The grammar and the tilings

The normalizer gives each pattern of size more than 1 a fresh helper nonterminal for each inner node, with a base rule of cost 0. A pattern that is a single leaf becomes a chain rule from the nonterminal of that leaf to reg.

Lemma 1. The least cost of a tiling of TT is Lreg(root)L_{\mathrm{reg}}(\mathrm{root}), and each derivation from reg gives a tiling of the same cost.

Proof. A helper nonterminal appears in the right side of exactly one rule, and it has exactly one rule. So a derivation that uses a helper at a node must use the whole chain of helpers of one pattern, which is one match of that pattern, and its cost is the cost of the pattern. A derivation from reg is therefore a choice of a pattern at the node, and derivations from reg of the holes, or from con or var of the constant and variable leaves, which cost 0. This is exactly a tiling, with the same cost. □\square

The states

A state is a finite set of entries (X,δX,ρX)(X, \delta_X, \rho_X): a nonterminal, a number and a rule. For a node vv let m(v)=min⁡XLX(v)m(v) = \min_X L_X(v).

Lemma 2 (invariant). Let ss be the state that LABEL gives to vv. Then XX has an entry in ss exactly when LX(v)<∞L_X(v) < \infty, and then δX=LX(v)−m(v)\delta_X = L_X(v) - m(v), and the rule ρX\rho_X starts a derivation of TvT_v from XX of cost LX(v)L_X(v) whose other parts are least-cost derivations.

Proof. By induction on the height of vv. Let vv have operator op and children u1,…,uku_1, \ldots, u_k with states s1,…,sks_1, \ldots, s_k. By the induction hypothesis, LY(ui)=δY(i)+m(ui)L_Y(u_i) = \delta^{(i)}_Y + m(u_i) for each YY in sis_i.

Base rules (lines L2 and L3). A derivation that starts with a base rule X→op(Y1,…,Yk)X \to \mathrm{op}(Y_1, \ldots, Y_k) of cost cc has least cost

c+∑iLYi(ui)=(c+∑iδYi(i))+M,M=∑im(ui),c + \sum_i L_{Y_i}(u_i) = \Big(c + \sum_i \delta^{(i)}_{Y_i}\Big) + M, \qquad M = \sum_i m(u_i),

because the parts are independent. Line L3 computes the term in brackets. The constant MM is the same for every base rule at vv. So for each XX, the rule with the least computed value is also the rule with the least true value, and the computed value is the true one minus MM. Let bXb_X be the least true cost of a derivation from XX that starts with a base rule. After line L3, the entry of XX is bX−Mb_X - M, with its rule.

Chain rules (line L4). We have LX(v)=min⁡(bX,min⁡X→Y(c+LY(v)))L_X(v) = \min\big(b_X, \min_{X \to Y} (c + L_Y(v))\big). This is a shortest path problem: LX(v)L_X(v) is the least cost of a path from XX along chain rules to some YY, plus bYb_Y. The costs are not negative, so a least path never repeats a nonterminal. Line L4 relaxes the chain rules until no value falls, which is the Bellman-Ford method. Each value is always the cost of some path, so it never falls below LX(v)−ML_X(v) - M. After pp passes, each value is at most the cost of each path with at most pp chain rules, so after one pass for each nonterminal all values are exact, and the next pass changes nothing. So the loop stops, and each value is LX(v)−ML_X(v) - M. The rules that line L4 keeps form least paths. The whole computation subtracts the same MM from every value, so it does not change any choice.

Normalizing (line L5). The least value after line L4 is m(v)−Mm(v) - M. Line L5 subtracts it, so δX=LX(v)−m(v)\delta_X = L_X(v) - m(v). □\square

The values in a state depend only on op and the states of the children, not on MM. So a state of a node is a function of op and the child states, and BUILD can compute this function once for each operator and each tuple of states. This is the reason why the shift by the minimum is needed: the absolute costs LX(v)L_X(v) grow with the tree and take infinitely many values, but the relative costs often take only a few.

Lemma 3 (the tables are complete). If BUILD stops, then for each tree, each lookup of LABEL finds an entry, and the state it finds is the state of Lemma 2.

Proof. By induction on the height of the tree. The state of a leaf is in the table by line L1. For an inner node, the child states are in the set of states by induction. BUILD stops only when every operator and every tuple of known states has an entry (line L6). That entry was computed with lines L2 to L5, so by Lemma 2 it is the right state. □\square

Theorem. If BUILD stops and the root state has reg, then REDUCE(root, reg) emits a tiling of least cost.

Proof. REDUCE(v,X)(v, X) uses the rule ρX\rho_X of the state of vv (line L9). By Lemma 2 this rule starts a derivation of cost LX(v)L_X(v), provided that the parts below it are least-cost derivations. REDUCE then calls itself on the same node with the right side of a chain rule (line L10), or on each child with the nonterminal of the base rule (line L12), and by induction each call emits a least-cost derivation. The chain calls on one node follow a least path, so they never loop. So REDUCE emits a derivation of cost Lreg(root)L_{\mathrm{reg}}(\mathrm{root}), and Lemma 1 turns it into a tiling of the same least cost. ■\blacksquare

When BUILD stops. The set of states is finite exactly when the relative costs δX\delta_X that occur are bounded, because the costs are integers. Then the worklist of line L6 adds only finitely many states and stops. Some grammars give unbounded relative costs. For example, with the rules x→ax \to a and y→ay \to a of cost 0, and x→f(x)x \to f(x) of cost 1 and y→f(y)y \to f(y) of cost 2, the tree f(f(⋯f(a)))f(f(\cdots f(a))) with kk copies of ff has Lx=kL_x = k and Ly=2kL_y = 2k, so its state has δy=k\delta_y = k, and the states never repeat. For such a grammar the tables are infinite, and a generator must stop with an error or fall back to the dynamic program at compile time.

Time. LABEL does one table lookup for each node, and REDUCE visits each node once for each nonterminal that the derivation uses there, which is a constant for a fixed grammar. So labeling and reducing take Θ(n)\Theta(n) time for a tree with nn nodes. The cost of BUILD depends only on the grammar.

Complexity

LABEL does one table lookup for each node, and REDUCE visits each node a constant number of times for a fixed grammar. So compiling a tree takes Θ(n)\Theta(n) time and Θ(n)\Theta(n) space for the labels. The dynamic program has moved to BUILD, whose cost depends only on the grammar. For a binary operator, the table has one entry for each pair of states, so it has size O(S2)O(S^2) for SS states. Real generators compress it, for example by mapping the states of each operand position to a few classes. For the grammar of the page, the tables have 2+11+2⋅112=2552 + 11 + 2 \cdot 11^2 = 255 entries.

Properties

  • Optimum. For a fixed grammar with a finite set of states, the result is a least-cost tiling, the same cost as the dynamic program.
  • No arithmetic at compile time. The code generator does no cost sums and no comparisons, only lookups.
  • A tree automaton. The states and the table form a deterministic bottom-up tree automaton, much like a DFA on strings, and BUILD is close to the subset construction with costs attached.
  • Fixed costs. The costs must be known when the tables are built. A cost that depends on the tree, such as "free if the constant is small", needs a different tool.

Variants and improvements

  • iburg. Fraser, Hanson and Proebsting take the same grammar but run the dynamic program at compile time. The generator is much simpler and the costs can be dynamic, at the price of some speed.
  • Table trimming. Proebsting removes entries of a state that can never be part of a least derivation, so that fewer states are distinct. This makes the tables smaller and BUILD faster.
  • On-demand tables. A code generator can compute the states lazily, the first time it needs each one, and cache them. This avoids building states that no program reaches.
  • Rewrites. In the theory of Pelegrí-Llopart and Graham, rules can also rewrite the tree, for example by commutativity, before it is tiled. BURG and most later tools keep only the tree grammar.
  • Matching without costs. Hoffmann-O'Donnell matching builds the same kind of bottom-up tables for tree pattern matching without costs.

When to use it

Use it for a production code generator with a fixed machine description, where compile speed matters and the grammar is large. The tables give a least-cost tiling at the speed of a lookup. When the grammar changes often, or the costs depend on the operands, use iburg or the plain dynamic program. When the input is a DAG, split it into trees first, since tiling a DAG is NP-complete (the DAG theorem).

Pitfalls

  • Infinite states. BUILD stops only if the relative costs are bounded. With x→ax \to a and y→ay \to a of cost 0, x→f(x)x \to f(x) of cost 1 and y→f(y)y \to f(y) of cost 2, a chain of kk copies of ff has δy=k\delta_y = k, and BUILD never stops. A generator must detect this and give an error.
  • Absolute costs in states. If the states store absolute costs, every tree has new states and the table is useless. Always subtract the minimum.
  • Ties. Two rules can have the same cost. Break ties in a fixed order, or two equal states can look different and the table grows.
  • Unreachable goals. If the root state has no entry for reg, the grammar cannot derive the tree. Check this before REDUCE.
  • No register limit. BURS ignores the number of registers. The Aho-Johnson cost vectors add it, at the cost of larger states.

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.

burs.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/burs/. The authors are listed in prov/VPX7R8.jsonl.

"""A bottom-up rewrite system (BURS) code generator.

A tree is written with tuples: ("CONST", k), ("VAR", x), ("MEM", a),
("ADD", a, b) or ("MUL", a, b). The machine is a list of tree patterns
with costs. In a pattern, "reg" is an operand in a register, ("CONST",) an
immediate constant and ("VAR",) a variable in memory. Registers are
unbounded virtual registers v0, v1, ...

The patterns become a tree grammar with rules of depth one. All dynamic
programming happens when the tables are built. Labeling a tree is then one
table lookup per node.
"""

RULES = [
    ("li", ("CONST",), 1),
    ("ld", ("VAR",), 3),
    ("add", ("ADD", "reg", "reg"), 1),
    ("addi", ("ADD", "reg", ("CONST",)), 1),
    ("addm", ("ADD", "reg", ("VAR",)), 3),
    ("mul", ("MUL", "reg", "reg"), 3),
    ("ldr", ("MEM", "reg"), 3),
    ("ldo", ("MEM", ("ADD", "reg", ("CONST",))), 3),
    ("ldx", ("MEM", ("ADD", "reg", "reg")), 3),
    ("madd", ("ADD", ("MUL", "reg", "reg"), "reg"), 2),
]
ARITY = {"CONST": 0, "VAR": 0, "MEM": 1, "ADD": 2, "MUL": 2}


def normalize(rules: list) -> tuple[list, list]:
    """Turn the patterns into base rules (lhs, op, kids, cost, pattern) and
    chain rules (lhs, rhs, cost, pattern). A helper nonterminal stands for
    each inner node of a pattern; its rule costs 0."""
    base = [("con", "CONST", (), 0, None), ("var", "VAR", (), 0, None)]
    chain = []
    count = [0]

    def nt(p: object) -> str:
        if p == "reg":
            return "reg"
        if p == ("CONST",):
            return "con"
        if p == ("VAR",):
            return "var"
        count[0] += 1
        name = "h%d" % count[0]
        base.append((name, p[0], tuple(nt(q) for q in p[1:]), 0, None))
        return name

    for idx, (_, pat, cost) in enumerate(rules):
        if pat == ("CONST",):
            chain.append(("reg", "con", cost, idx))
        elif pat == ("VAR",):
            chain.append(("reg", "var", cost, idx))
        else:
            base.append(("reg", pat[0], tuple(nt(q) for q in pat[1:]), cost, idx))
    return base, chain


class Burs:
    """The tables of a BURS code generator for one set of patterns."""

    def __init__(self, rules: list = RULES) -> None:
        self.rules = rules
        self.base, self.chain = normalize(rules)
        self.states: list[tuple] = []
        self.index: dict[tuple, int] = {}
        self.table: dict[tuple, int] = {}
        self.build()

    def close(self, cost: dict[str, tuple]) -> tuple:
        # Apply chain rules until no cost falls, then subtract the minimum.
        changed = True
        while changed:  # @line L4
            changed = False
            for k, (lhs, rhs, c, _) in enumerate(self.chain):
                if rhs in cost and (lhs not in cost or cost[rhs][0] + c < cost[lhs][0]):
                    cost[lhs] = (cost[rhs][0] + c, ("chain", k))
                    changed = True
        low = min(c for c, _ in cost.values())  # @line L5
        return tuple(sorted((x, c - low, r) for x, (c, r) in cost.items()))

    def transition(self, op: str, kids: tuple) -> tuple:
        # The state of a node with this operator and these child states.
        cost: dict[str, tuple] = {}
        kid_cost = [{x: c for x, c, _ in self.states[s]} for s in kids]
        for k, (lhs, bop, nts, c, _) in enumerate(self.base):  # @line L2
            if bop != op or any(x not in kc for x, kc in zip(nts, kid_cost)):
                continue
            total = c + sum(kc[x] for x, kc in zip(nts, kid_cost))  # @line L3
            if lhs not in cost or total < cost[lhs][0]:
                cost[lhs] = (total, ("base", k))
        return self.close(cost)

    def add_state(self, s: tuple) -> int:
        if s not in self.index:
            self.index[s] = len(self.states)
            self.states.append(s)
        return self.index[s]

    def build(self) -> None:
        # The worklist: compute every transition from known states until no new state appears.
        for op, a in ARITY.items():  # @line L1
            if a == 0:
                self.table[(op,)] = self.add_state(self.transition(op, ()))
        done = 0
        while done < len(self.states):  # @line L6
            done = len(self.states)
            for op, a in ARITY.items():
                if a == 1:
                    for s in range(done):
                        if (op, s) not in self.table:
                            self.table[(op, s)] = self.add_state(self.transition(op, (s,)))
                elif a == 2:
                    for s in range(done):
                        for t in range(done):
                            if (op, s, t) not in self.table:
                                self.table[(op, s, t)] = self.add_state(self.transition(op, (s, t)))

    def label(self, t: tuple) -> tuple:
        """Return the tree with a state number on each node: (op, value, state, kids)."""
        if t[0] in ("CONST", "VAR"):
            return (t[0], t[1], self.table[(t[0],)], [])
        kids = [self.label(c) for c in t[1:]]  # @line L7
        return (t[0], None, self.table[(t[0],) + tuple(k[2] for k in kids)], kids)  # @line L8

    def reduce(self, n: tuple, goal: str, code: list, names: list) -> object:
        """Emit the code for n derived from the nonterminal goal. Return the
        virtual register, constant or variable that holds the result."""
        entry = {x: r for x, _, r in self.states[n[2]]}[goal]  # @line L9
        kind, k = entry
        if kind == "chain":
            lhs, rhs, cost, idx = self.chain[k]  # @line L10
            arg = self.reduce(n, rhs, code, names)
            return self.emit(idx, [arg], code, names)
        lhs, op, nts, cost, idx = self.base[k]  # @line L11
        if op in ("CONST", "VAR"):
            return n[1]
        args: list = []
        for child, x in zip(n[3], nts):  # @line L12
            sub = self.reduce(child, x, code, names)
            args += sub if isinstance(sub, list) else [sub]
        if idx is None:
            return args  # a helper: its operands go to the instruction above
        return self.emit(idx, args, code, names)

    def emit(self, idx: int, args: list, code: list, names: list) -> str:
        dst = "v%d" % len(names)
        names.append(dst)
        code.append((idx, dst, args))
        return dst

    def generate(self, t: tuple) -> tuple[list, int]:
        """Return (code, cost). The cost is the least cost of a tiling."""
        n = self.label(t)
        code: list = []
        self.reduce(n, "reg", code, [])
        return code, sum(self.rules[ins[0]][2] for ins in code)


def heap(a: int) -> int:
    """The word at address a."""
    return (31 * a + 7) % 97


def evaluate(t: tuple, env: dict[str, int]) -> int:
    """The value of the tree, computed directly."""
    op = t[0]
    if op == "CONST":
        return t[1]
    if op == "VAR":
        return env[t[1]]
    if op == "MEM":
        return heap(evaluate(t[1], env))
    a, b = evaluate(t[1], env), evaluate(t[2], env)
    return a + b if op == "ADD" else a * b


def run(code: list, env: dict[str, int], rules: list = RULES) -> int:
    """Run the code and return the value of the last instruction."""
    reg: dict[str, int] = {}
    for idx, dst, args in code:
        it = iter(args)

        def ev(p: object) -> int:
            if p == "reg":
                return reg[next(it)]
            if p == ("CONST",):
                return next(it)
            if p == ("VAR",):
                return env[next(it)]
            vals = [ev(q) for q in p[1:]]
            if p[0] == "MEM":
                return heap(vals[0])
            return vals[0] + vals[1] if p[0] == "ADD" else vals[0] * vals[1]

        reg[dst] = ev(rules[idx][1])
    return reg[code[-1][1]]
test_burs.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/burs/. The authors are listed in prov/VPX7R8.jsonl.

import random

from burs import RULES, Burs, evaluate, run


def random_tree(rng: random.Random, size: int) -> tuple:
    """A random tree with exactly size nodes."""
    if size == 1:
        if rng.random() < 0.5:
            return ("CONST", rng.randint(0, 9))
        return ("VAR", rng.choice("abc"))
    if size == 2 or rng.random() < 0.25:
        return ("MEM", random_tree(rng, size - 1))
    left = rng.randint(1, size - 2)
    return (rng.choice(["ADD", "ADD", "MUL"]), random_tree(rng, left), random_tree(rng, size - 1 - left))


def holes(p: object, n: tuple) -> list | None:
    """The subtrees under the register holes of p at n, or None."""
    if p == "reg":
        return [n]
    if p == ("CONST",) or p == ("VAR",):
        return [] if n[0] == p[0] else None
    if n[0] != p[0]:
        return None
    out: list = []
    for q, c in zip(p[1:], n[1:]):
        m = holes(q, c)
        if m is None:
            return None
        out += m
    return out


def tilings(t: tuple, rules: list) -> list[int]:
    """The cost of every tiling of t."""
    res = []
    for _, p, cost in rules:
        hs = holes(p, t)
        if hs is None:
            continue
        partial = [cost]
        for h in hs:
            partial = [x + y for x in partial for y in tilings(h, rules)]
        res += partial
    return res


def dp(t: tuple, rules: list) -> int:
    """The least tiling cost, by dynamic programming at compile time."""
    best = None
    for _, p, cost in rules:
        hs = holes(p, t)
        if hs is not None:
            c = cost + sum(dp(h, rules) for h in hs)
            best = c if best is None else min(best, c)
    return best


def test_example() -> None:
    b = Burs()
    t = ("MEM", ("ADD", ("MUL", ("VAR", "a"), ("VAR", "b")), ("VAR", "c")))
    code, cost = b.generate(t)
    assert cost == 14 == min(tilings(t, RULES))
    assert [RULES[ins[0]][0] for ins in code] == ["ld", "ld", "ld", "madd", "ldr"]
    env = {"a": 4, "b": 5, "c": 6}
    assert run(code, env) == evaluate(t, env) == 37


def test_tables() -> None:
    b = Burs()
    assert len(b.states) == 11
    for s in b.states:
        assert min(c for _, c, _ in s) == 0
    # every operator has an entry for every state or pair of states
    k = len(b.states)
    assert len(b.table) == 2 + k + 2 * k * k


def test_least_cost_on_small_trees() -> None:
    rng = random.Random(1988)
    b = Burs()
    for _ in range(400):
        t = random_tree(rng, rng.randint(1, 8))
        code, cost = b.generate(t)
        assert cost == min(tilings(t, RULES)) == dp(t, RULES)
        for _ in range(3):
            env = {x: rng.randint(-20, 20) for x in "abc"}
            assert run(code, env) == evaluate(t, env)


def test_large_trees_and_other_tables() -> None:
    rng = random.Random(1992)
    for rules in (RULES, RULES[:9], [r for r in RULES if r[0] != "ldx"]):
        b = Burs(rules)
        for _ in range(100):
            t = random_tree(rng, rng.randint(1, 40))
            code, cost = b.generate(t)
            assert cost == dp(t, rules)
            env = {x: rng.randint(-9, 9) for x in "abc"}
            assert run(code, env, rules) == evaluate(t, env)

History

Pelegrí-Llopart and Graham introduced bottom-up rewrite systems in 1988. They showed that a code generator can find optimum tilings with tables computed ahead of time, with the costs in each state taken relative to the cheapest entry. Balachandran, Dhamdhere and Biswas gave a simpler table construction in 1990. In 1992, Proebsting described a fast worklist construction with trimming, and Fraser, Henry and Proebsting released BURG, a generator that reads a tree grammar and writes the tables in C. In the same year, Fraser, Hanson and Proebsting wrote iburg, which reads the same grammars and does the work at compile time; the lcc compiler uses it.

References

  1. Eduardo Pelegrí-Llopart and Susan L. Graham, Optimal code generation for expression trees, an application of BURS theory, Proceedings of the 15th ACM Symposium on Principles of Programming Languages, 1988, 294-308, the bottom-up rewrite systems, the states with costs relative to the least cost, and the tables computed when the code generator is built
  2. Christopher W. Fraser, Robert R. Henry and Todd A. Proebsting, BURG, fast optimal instruction selection and tree parsing, ACM SIGPLAN Notices 27(4), 1992, 68-76, the tree grammar with costs and chain rules, the labeler driven by tables, and the reducer
  3. Christopher W. Fraser, David R. Hanson and Todd A. Proebsting, Engineering a simple, efficient code-generator generator, ACM Letters on Programming Languages and Systems 1(3), 1992, 213-226, iburg, which uses the same grammars but runs the dynamic program while it compiles
  4. Todd A. Proebsting, Simple and efficient BURS table generation, Proceedings of the ACM SIGPLAN 1992 Conference on Programming Language Design and Implementation, 331-340, the worklist construction of the states and the trimming of entries that can never be used
  5. A. Balachandran, D. M. Dhamdhere and S. Biswas, Efficient retargetable code generation using bottom-up tree pattern matching, Computer Languages 15(3), 1990, 127-140, the states with normalized costs and the construction of the transition tables
  6. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 9 (Instruction Selection), the section on tree grammars and code generator generators

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
  • a scene preset for the example