Algorithmcore
Sethi-Ullman algorithm
Also called Ershov numbers, Sethi-Ullman numbering.
Labels each node of an expression tree with the fewest registers that evaluate it, then emits code that evaluates the child with the larger label first and stores only when registers run out.
- Solves
- Register allocation
- Time
- Θ(n) worst
- Space
- Θ(n) extra
- Where
- k = the number of registers; n = the number of nodes of the tree
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ravi Sethi, Jeffrey D. Ullman, 1970
The Sethi-Ullman algorithm generates code for an expression tree on a machine with registers. It gives each node a label: the fewest registers that evaluate the subtree of the node without a store to memory. Then it walks the tree and evaluates the child with the larger label first. For a tree, the label of the root is exactly the minimum register count, and the code is as short as possible. The method needs a tree: for code with shared subexpressions the problem is NP-complete (see the DAG theorem). It also has a fixed instruction set with unit costs. Aho-Johnson code generation handles any set of instructions with costs.
In plain words
To compute a sum of two parts, you must keep the result of the first part in a register while you work on the second part. So the second part has one register less.
The algorithm first finds out how many registers each part needs. A single variable on the left needs one register. A variable on the right can stay in memory, because the machine can read it directly. When the two parts need different counts, the node needs the larger count: do the hungry part first, and the other part fits in what is left. When the two parts need the same count, the node needs one more register.
Then the algorithm writes the code in that order. When there are not enough registers, it computes the right part first, saves it in memory, and reads it back as the right operand at the end.
The problem
The input is a binary expression tree with nodes and a number . Each leaf is a variable in memory. Each inner node has an operator, a left child and a right child . No algebraic law is used: the operators need not be commutative or associative, and two nodes are different even when their subtrees are equal.
The machine has registers and four instructions, as in the model of Sethi and Ullman:
- load: , where is a variable or a temporary in memory,
- store: ,
- operation with a register: ,
- operation with memory: .
The left operand of an operation is always a register. The output is a program that leaves the value of the tree in . The goal is the fewest registers when no store is allowed, and the fewest instructions when the registers are fixed. This is register allocation and evaluation order together, for one tree.
The algorithm
LABEL computes the labels bottom-up. GEN emits the code. In GEN, is the number of free registers , and is the label of .
LABEL(v, left) ▷ left is true for the root and for each left child- 1
if v is a leaf and left then return 1 - 2
if v is a leaf then return 0 ▷ a right leaf is a memory operand - 3
la ← LABEL(a(v), true), lb ← LABEL(b(v), false) - 4
if la = lb then return la + 1 - 5
return max(la, lb) GEN(v, i) ▷ leave v in R_i, use only R_i .. R_(k-1)- 6
if v is a leaf then emit R_i ← v; return - 7
if b(v) is a leaf then GEN(a(v), i); emit R_i ← R_i op b(v); return - 8
if ℓ(a(v)) ≥ r and ℓ(b(v)) ≥ r then ▷ both children are too big: spill - 9
GEN(b(v), i); t ← a new temporary; emit t ← R_i - 10
GEN(a(v), i); emit R_i ← R_i op t - 11
else if ℓ(a(v)) ≥ ℓ(b(v)) then GEN(a(v), i); GEN(b(v), i + 1); emit R_i ← R_i op R_(i+1) - 12
else GEN(b(v), i); GEN(a(v), i + 1); emit R_i ← R_(i+1) op R_i
The first child keeps its result in while the second child runs in . Line L12 evaluates the right child first, but the operation still puts the left child on the left, so a non-commutative operator gives the right value. Line L8 is the only place with a store. There, the right child goes to a temporary , and line L10 reads directly as the right operand, so the algorithm never loads a temporary.
Example
Take with , , , and . Its value is . The labels are:
| node | position | label | label without memory operands |
|---|---|---|---|
| , , | left leaf | 1 | 1 |
| , | right leaf | 0 | 1 |
| left child | 1 | 2 | |
| right child | 1 | 2 | |
| right child | 2 (equal labels 1 and 1) | 2 | |
| root | root | 2 (labels 1 and 2) | 3 |
With , the right child has the larger label, so line L12 runs it first:
| step | instruction | value |
|---|---|---|
| 1 | 3 | |
| 2 | 10 | |
| 3 | 6 | |
| 4 | 9 | |
| 5 | 7 | |
| 6 | 5 | |
| 7 | 45 |
The code uses two registers and seven instructions, and no program for this tree does better. If you evaluate the left child first instead, holds while needs two more registers, so the peak is three.
With , each inner node with an inner right child goes through line L8. The code is , , , , , , , , . That is nine instructions with two stores, which is the minimum for one register.
Correctness
A store-free program is a game on the tree: a register holds the value of one node, a node can enter a register when its operands are there, and any register can be overwritten. The lower bound looks at the last time that each subtree of a node was empty before is computed. When the two children have the same label , the child whose subtree became non-empty last needs registers at some moment, and at that moment the other subtree still holds a register. So every program needs at least registers, even if it interleaves the two subtrees. The upper bound is an induction on GEN: GEN with stays inside . With fewer registers, GEN stays inside and still computes the right value. The full proof is in the proof file.
Proof: Sethi-Ullman labels are the minimum register count, and GEN reaches itfull
We use the machine and the pseudocode of the page. A tree has leaves and inner nodes, and each inner node has a left child and a right child . The label is the value that LABEL returns for (lines L1 to L5). We write for the subtree of .
The game of registers
A store-free program for is a sequence of instructions. Each instruction computes one node into a register . A load computes a leaf. An operation computes an inner node , and it reads the value of from a register and the value of from a register, or from memory when is a leaf. The register keeps the value until another instruction writes to it. The program ends with the value of the root in a register.
Let be the set of nodes whose value is in some register after instructions. One register holds the value of one node, so is at most the number of registers that the program uses. A step can add one node to when the operands of are in (a memory leaf needs nothing), and it can remove any node, because a register can be overwritten. So it is enough to bound from below.
Lemma 1 (lower bound). Let be a node, and let be times such that and . Then for some with .
Proof. By induction on the height of . If is a leaf, then , since .
Let be an inner node, with , , and . Let be the first time in with . The step computes , so , and unless is a leaf that is read from memory. The subtree is empty at time , so the induction hypothesis on gives a time with at least nodes of in . If , the same holds for . If is read from memory, then is a right leaf and . So some time in has at least nodes of in . This proves the lemma when , by line L5.
Now let . A left child has label at least 1 (line L1 and line L4 or L5), so . Then is not a right leaf of label 0, so . Let be the last time in with , and define in the same way. Both exist, because is such a time. By the choice of , the subtree is not empty at each time in , and the same holds for .
Assume . The induction hypothesis for on gives a time with . At time the subtree is empty, so . So is not empty at time , and and are disjoint. This gives , by line L4. If , swap the roles of and .
At time 0 no node is in a register, and at the end the root is in a register. So Lemma 1 with gives:
Theorem 1. Each store-free program for uses at least registers. This holds for every order of the instructions, including orders that interleave the two subtrees of a node, and for programs that compute a node more than once.
GEN reaches the bound
Lemma 2. Let and , and let be a node that is the root or a left child, or an inner node. Then GEN emits code that leaves the value of in , writes only and fresh temporaries, and reads only registers that it wrote before. If , the code has no store and writes only .
Proof. By induction on the height of . Let . A leaf that reaches line L6 is the root or a left child, so . The load writes only .
Let be an inner node with children and and labels and .
Line L7, is a leaf. Then and by line L5. By induction, GEN leaves in , and the operation reads from memory and writes . The bounds of carry over to .
Lines L8 to L10, and . GEN leaves in , and the store saves it in a fresh temporary . GEN then leaves in and does not write . The operation reads from and from . In this case : if then , and else . So the claim about is empty here.
Line L11, , not both at least . Then : either directly, or and . Since is an inner node, , so and . GEN leaves in . GEN leaves in , and it does not write . The operation reads both and writes . If : then , so GEN has no store and stays in . Also : if this follows from , and if from . So GEN has no store and stays in .
Line L12, . The same argument with and swapped. Here and not both at least give , and gives . The operation writes , so the left operand is still . If , then , GEN stays in , and GEN stays in with .
Theorem 2. For each , GEN leaves the value of the tree in and uses only . If , the code has no store and uses exactly the registers . With Theorem 1, is the minimum number of registers of a store-free program for .
Proof. Lemma 2 with and gives all claims except "exactly". Theorem 1 shows that the store-free code cannot use fewer than registers, and Lemma 2 shows that it uses no register outside the first .
The order. The proof of Lemma 2 shows why the child with the larger label goes first. While the second child runs, the first child holds one register. If the first child has the smaller label , the peak is at least when the order is not interleaved, which is more than .
Length. Each inner node gives one operation, each leaf that is the root or a left child gives one load, and each pass through line L8 gives one store. No instruction loads a temporary. Sethi and Ullman prove that their algorithm gives a program with the fewest instructions on their machine when no algebraic law is used. This file does not repeat that proof.
Complexity
LABEL visits each node once and does constant work there, so it takes time. GEN also visits each node once. It emits one operation for each inner node, one load for each leaf that is the root or a left child, and at most one store for each inner node. So the code has instructions, and GEN takes time. A unit step is the work at one node. The extra space is for the labels and the recursion stack, whose depth is the height of the tree.
Properties
- Exact for trees. The label of the root is the minimum register count over all store-free programs, in every evaluation order. The proof file proves this.
- Few registers suffice. A label in the variant without memory operands needs at least leaves, because a label goes up only when two children have the same label. Each label with memory operands is at most the label without them. So the label is at most , and a complete tree of 32 leaves needs only 5 registers with memory operands.
- A chain needs one register. A left-deep tree such as has label 1.
- Shortest code. On their machine and with no algebraic law, Sethi and Ullman prove that the program has the fewest instructions. The code also loads each variable once and never loads a temporary.
Variants and improvements
- Ershov numbers. On a machine with no memory operand, each leaf needs a register, so each leaf gets the label 1. These labels are the Horton-Strahler numbers of the tree. A spill then needs a store and a later load. The example tree has label 3 in this variant.
- Commutative and associative operators. Sethi and Ullman also reorder the operands of commutative operators, and regroup associative ones, to find an equal expression with the shortest code.
- Unary operators. A unary node gets the label of its child.
- Instruction costs. Aho-Johnson code generation replaces the fixed instructions by any set of tree patterns with costs and computes a cost for each number of free registers. The Sethi-Ullman algorithm is the special case with one pattern per operator.
When to use it
Use it to order the evaluation of expression trees in a simple compiler, or in the code generator of a tree-walking back end, when registers are few. Use the labels alone to decide which operand of a node to evaluate first. For straight-line code with named values, use local register allocation. For a machine with complex addressing modes and costs, use tree tiling by dynamic programming or a BURS generator.
Pitfalls
- Left to right. A fixed left-to-right order can use more registers. The example needs three registers in that order and two in the labeled order.
- Wrong operand order. In line L12 the right child is in , but it is still the right operand. Writing there computes for a subtraction.
- The wrong variant. Label 0 for a right leaf is right only when the machine can read that operand from memory. On a load-store machine it undercounts.
- Shared subtrees. On a DAG, a node with two parents keeps its register until both parents are done. The labels then give no bound, and the exact problem is NP-complete.
- Algebraic laws. The minimum is over programs that keep the tree as it is. With a commutative , the tree can become , which has label 1 instead of 2.
- Calls inside the tree. A call clobbers registers that the calling convention does not save, so a tree with calls needs more care than the labels show.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sethi-ullman-numbering/. The authors are listed in prov/HKPTPW.jsonl.
"""Sethi-Ullman labels and code generation for expression trees.
An expression is a variable name (a str) or a tuple (op, left, right) with
op in "+", "-", "*". The same variable can occur at many leaves, but each
leaf is a separate node of the tree.
The machine has registers R0 .. R(k-1) and four instructions:
("load", i, x) Ri <- x x is a variable or a temporary
("op", o, i, j, l) Ri <- Rj o Rl
("opm", o, i, j, x) Ri <- Rj o x the right operand is in memory
("store", t, i) t <- Ri
The left operand of an operation is always a register.
"""
from typing import Union
Expr = Union[str, tuple]
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}
def is_leaf(e: Expr) -> bool:
return isinstance(e, str)
def annotate(e: Expr, memory_operands: bool = True, is_left: bool = True) -> tuple:
"""Return a copy of e where each node carries its label.
A leaf becomes ("leaf", x, label). An inner node becomes
(op, left, right, label). With memory_operands=False each leaf gets 1,
which gives the Ershov numbers of a machine with no memory operands.
"""
if is_leaf(e):
if is_left or not memory_operands: # @line L1
return ("leaf", e, 1)
return ("leaf", e, 0) # @line L2
a = annotate(e[1], memory_operands, True) # @line L3
b = annotate(e[2], memory_operands, False)
la, lb = a[-1], b[-1]
if la == lb: # @line L4
return (e[0], a, b, la + 1)
return (e[0], a, b, max(la, lb)) # @line L5
def label(e: Expr, memory_operands: bool = True) -> int:
"""The label of the root: the fewest registers that evaluate e without stores."""
return annotate(e, memory_operands)[-1]
def generate(e: Expr, k: int) -> tuple[list[tuple], int]:
"""Return (code, number of stores) that leaves the value of e in R0.
The code uses only R0 .. R(k-1). It stores to temporaries only when the
label of e is larger than k.
"""
if k < 1:
raise ValueError("need at least one register")
code: list[tuple] = []
temps = [0]
def gen(n: tuple, i: int) -> None:
# Put the value of n in Ri. Use only Ri .. R(k-1).
r = k - i
if n[0] == "leaf":
code.append(("load", i, n[1])) # @line L6
return
op, a, b = n[0], n[1], n[2]
if b[0] == "leaf":
gen(a, i) # @line L7
code.append(("opm", op, i, i, b[1]))
elif a[-1] >= r and b[-1] >= r: # @line L8
gen(b, i) # @line L9
t = "t%d" % temps[0]
temps[0] += 1
code.append(("store", t, i))
gen(a, i) # @line L10
code.append(("opm", op, i, i, t))
elif a[-1] >= b[-1]:
gen(a, i) # @line L11
gen(b, i + 1)
code.append(("op", op, i, i, i + 1))
else:
gen(b, i) # @line L12
gen(a, i + 1)
code.append(("op", op, i, i + 1, i))
gen(annotate(e, True), 0)
return code, temps[0]
def evaluate(e: Expr, env: dict[str, int]) -> int:
"""Evaluate e directly."""
if is_leaf(e):
return env[e]
return OPS[e[0]](evaluate(e[1], env), evaluate(e[2], env))
def run(code: list[tuple], env: dict[str, int], k: int) -> int:
"""Run the code on a machine with k registers and return R0."""
reg: dict[int, int] = {}
mem = dict(env)
for ins in code:
if ins[0] == "load":
_, i, x = ins
assert 0 <= i < k
reg[i] = mem[x]
elif ins[0] == "op":
_, o, i, j, l = ins
assert 0 <= i < k
reg[i] = OPS[o](reg[j], reg[l])
elif ins[0] == "opm":
_, o, i, j, x = ins
assert 0 <= i < k
reg[i] = OPS[o](reg[j], mem[x])
else:
_, t, i = ins
assert t not in env
mem[t] = reg[i]
return reg[0]
test_sethi_ullman_numbering.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sethi-ullman-numbering/. The authors are listed in prov/HKPTPW.jsonl.
import random
from collections import deque
from functools import lru_cache
from sethi_ullman_numbering import evaluate, generate, label, run
def random_tree(rng: random.Random, inner: int) -> object:
"""A random expression tree with the given number of inner nodes."""
if inner == 0:
return rng.choice("abcd")
left = rng.randint(0, inner - 1)
return (rng.choice("+-*"), random_tree(rng, left), random_tree(rng, inner - 1 - left))
def flatten(e: object) -> tuple[list, list]:
"""Number the nodes. Return (kids, is_left) lists; node 0 is the root."""
kids: list = []
is_left: list = []
def walk(n: object, left: bool) -> int:
i = len(kids)
kids.append(None)
is_left.append(left)
if not isinstance(n, str):
kids[i] = (walk(n[1], True), walk(n[2], False))
return i
walk(e, True)
return kids, is_left
def min_registers(e: object, memory_operands: bool = True) -> int:
"""Brute force: the smallest peak of live register values over all
store-free evaluation orders, interleaved or not."""
kids, _ = flatten(e)
n = len(kids)
parent = [-1] * n
for i, ks in enumerate(kids):
if ks:
parent[ks[0]] = parent[ks[1]] = i
def live(done: int) -> int:
return sum(1 for u in range(n) if done >> u & 1 and (parent[u] < 0 or not done >> parent[u] & 1))
@lru_cache(maxsize=None)
def best(done: int) -> int:
if done >> 0 & 1:
return 0
res = 10**9
for v in range(n):
if done >> v & 1:
continue
if kids[v] is None:
nxt = done | 1 << v # load a leaf
else:
a, b = kids[v]
if not done >> a & 1:
continue
if done >> b & 1:
nxt = done | 1 << v
elif kids[b] is None and memory_operands:
nxt = done | 1 << v | 1 << b # b is a memory operand
else:
continue
res = min(res, max(live(nxt), best(nxt)))
return res
return best(0)
def min_instructions(e: object, k: int) -> int:
"""Brute force: the fewest instructions of any program for e with k registers.
Status of a node: 0 not computed, 1 in a register, 2 in memory,
3 in both, 4 used by its parent. Leaves start in memory. Loads, stores
and operations cost 1. Forgetting the register copy of a value that is
also in memory costs 0.
"""
kids, _ = flatten(e)
n = len(kids)
start = tuple(2 if ks is None else 0 for ks in kids)
dist = {start: 0}
dq = deque([start])
while dq:
s = dq.popleft()
d = dist[s]
if s[0] in (1, 3):
return d
regs = sum(1 for x in s if x in (1, 3))
moves = []
for v in range(n):
x = s[v]
if x == 2 and regs < k:
moves.append((v, 3, 1)) # load
if x == 1:
moves.append((v, 3, 1)) # store
if x == 3:
moves.append((v, 2, 0)) # forget the register copy
if x == 0 and kids[v] is not None:
a, b = kids[v]
if s[a] in (1, 3) and s[b] in (1, 2, 3):
t = list(s)
t[a] = t[b] = 4
t[v] = 1
moves.append((tuple(t), None, 1))
for v, x, c in moves:
if x is None:
t = v
else:
t = s[:v] + (x,) + s[v + 1:]
if t not in dist or dist[t] > d + c:
dist[t] = d + c
if c == 0:
dq.appendleft(t)
else:
dq.append(t)
raise AssertionError("no program")
def used_registers(code: list) -> int:
regs = set()
for ins in code:
if ins[0] == "load":
regs.add(ins[1])
elif ins[0] in ("op", "opm"):
regs.update(r for r in ins[2:5] if isinstance(r, int))
else:
regs.add(ins[2])
return len(regs)
def test_example() -> None:
# (a - b) * (c + (d - e)), the tree of the page.
e = ("*", ("-", "a", "b"), ("+", "c", ("-", "d", "e")))
assert label(e) == 2
assert label(e, memory_operands=False) == 3
code, stores = generate(e, 2)
assert stores == 0
assert code == [
("load", 0, "c"),
("load", 1, "d"),
("opm", "-", 1, 1, "e"),
("op", "+", 0, 0, 1),
("load", 1, "a"),
("opm", "-", 1, 1, "b"),
("op", "*", 0, 1, 0),
]
env = {"a": 7, "b": 2, "c": 3, "d": 10, "e": 4}
assert run(code, env, 2) == evaluate(e, env) == 45
code1, stores1 = generate(e, 1)
assert stores1 == 2 and len(code1) == 9 == min_instructions(e, 1)
assert run(code1, env, 1) == 45
assert len(code) == 7 == min_instructions(e, 2)
def test_leaf_and_chain() -> None:
assert label("x") == 1
chain = "a"
for v in "bcdefg":
chain = ("+", chain, v)
assert label(chain) == 1
code, stores = generate(chain, 1)
assert stores == 0 and len(code) == 7
def test_label_is_minimum_register_count() -> None:
rng = random.Random(1970)
for _ in range(300):
e = random_tree(rng, rng.randint(0, 5))
assert label(e) == min_registers(e)
assert label(e, False) == min_registers(e, False)
code, stores = generate(e, label(e))
assert stores == 0
assert used_registers(code) == label(e)
def test_complete_trees_need_more_registers() -> None:
e = "a"
for depth in range(1, 6):
e = ("+", e, e)
assert label(e) == depth
assert label(e, False) == depth + 1
def test_code_computes_the_value() -> None:
rng = random.Random(7)
for _ in range(400):
e = random_tree(rng, rng.randint(0, 12))
env = {v: rng.randint(-9, 9) for v in "abcd"}
for k in range(1, 5):
code, stores = generate(e, k)
assert run(code, env, k) == evaluate(e, env)
assert (stores == 0) == (label(e) <= k)
def test_fewest_instructions() -> None:
rng = random.Random(1976)
for _ in range(150):
e = random_tree(rng, rng.randint(1, 6))
for k in (1, 2, 3):
code, _ = generate(e, k)
assert len(code) == min_instructions(e, k)
History
Sethi and Ullman published the labels, the algorithm and the proofs in the Journal of the ACM in 1970. They prove that the code is shortest when no algebraic law applies, and they extend the method to commutative and associative operators. The dragon book calls the labels Ershov numbers, after a 1958 paper by A. P. Ershov on the programming of arithmetic operations.
References
- Ravi Sethi and J. D. Ullman, The generation of optimal code for arithmetic expressions, Journal of the ACM 17(4), 1970, 715-728, the labels of the nodes, the algorithm for a machine with N registers, and the proof that its programs are shortest when no algebraic law applies; the extension to commutative and associative operators
- A. P. Ershov, On programming of arithmetic operations, Communications of the ACM 1(8), 1958, 3-6, the whole paper, an English translation of a 1958 note in Doklady AN SSSR
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Chapter 8 (Code Generation), Section 8.10, Ershov numbers and the evaluation of expressions with too few registers
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation), the part on register allocation for trees
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HKPTPW Edit this page History Report an error Markdown