Algorithmintro
Maximal munch instruction selection
Also called maximal munch tiling.
Tiles an expression tree top-down by always choosing the largest pattern that matches at the root, then tiling the subtrees.
- Solves
- Instruction selection
- Time
- O(n P m) worst
- Space
- O(n) extra
- Where
- P = the number of patterns; m = the number of nodes of the largest pattern; n = the number of nodes of the tree
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Roderic G. G. Cattell, 1980
Maximal munch is the simplest way to choose machine instructions for an expression tree. It solves the instruction selection problem for trees with a greedy rule. At the root, it takes the largest instruction pattern that matches, and then it tiles each operand subtree in the same way. The result is always a valid cover, and no two adjacent tiles can be joined into one tile. Appel calls such a tiling optimal. It is not always optimum: the total cost can be higher than the least cost that the Aho-Johnson dynamic program or BURS finds.
In plain words
Each machine instruction does a small piece of the expression tree, so choosing instructions is like covering the tree with tiles. Some tiles are big, for example one load instruction that also adds an offset to the address.
Maximal munch starts at the top of the tree. It looks at all tiles that fit there and takes the one that covers the most nodes. The parts of the tree under the tile are still open, and the algorithm does the same thing on each of them. When the work comes back up, it writes the instructions, so each instruction comes after the instructions for its operands.
The rule is fast and easy to write by hand. A big tile is usually a good choice, but not always. A big tile at the top can take away a node that a cheaper tile below needs.
The problem
The input is an expression tree with nodes and a table of instruction patterns. The nodes on this page are CONST , VAR (a variable in memory), MEM (load the word at address ), ADD and MUL. In a pattern, reg is a hole: an operand that an earlier instruction leaves in a register. CONST in a pattern is an immediate constant, and VAR is a memory operand.
| name | pattern | cost | size |
|---|---|---|---|
| LI | CONST | 1 | 1 |
| LD | VAR | 3 | 1 |
| ADD | ADD(reg, reg) | 1 | 1 |
| ADDI | ADD(reg, CONST) | 1 | 2 |
| ADDM | ADD(reg, VAR) | 3 | 2 |
| MUL | MUL(reg, reg) | 3 | 1 |
| LDR | MEM(reg) | 3 | 1 |
| LDO | MEM(ADD(reg, CONST)) | 3 | 3 |
| LDX | MEM(ADD(reg, reg)) | 3 | 2 |
| MADD | ADD(MUL(reg, reg), reg) | 2 | 2 |
The size of a pattern is the number of tree nodes that it covers, so the holes do not count. A tiling puts one pattern on each part of the tree, so that each node is covered exactly once and each hole is the root of another tile. The output is a tiling and the code that it gives, with one new virtual register for each tile. Maximal munch does not handle a register limit.
The algorithm
MUNCH(v)- 1
best ← none - 2
for each pattern p of the table, in table order do - 3
if p matches at v and (best = none or size(p) > size(best)) then best ← p - 4
for each hole h of best, from left to right do - 5
x_h ← MUNCH(h) - 6
t ← a new register; emit best into t, with the registers x_h and the constants and variables that best covers - 7
return t
The choice goes top-down, at lines L2 and L3. The code comes out bottom-up, at line L6, after the code of the operands. A tie in size goes to the first pattern of the table, so the order of the table is part of the algorithm. Appel's version emits the code in the same order.
Example
Take , where , and are variables.
| step | node | patterns that match | choice |
|---|---|---|---|
| 1 | MEM | LDR (size 1), LDX (size 2) | LDX, which also covers the ADD |
| 2 | MUL | MUL | MUL |
| 3 | LD | LD | |
| 4 | LD | LD | |
| 5 | LD | LD |
LDO does not match at the root, because the right operand of the ADD is not a constant. The code is:
| instruction | cost |
|---|---|
| 3 | |
| 3 | |
| 3 | |
| 3 | |
| 3 |
The total is 15. The tiling LDR, MADD and three LD costs , and it is the cheapest tiling of this tree. The big tile LDX at the root took the ADD node, so the cheap MADD could not cover it. The munch tiling is still optimal in Appel's sense: LDX and MUL do not join into any pattern of the table.
On , munch takes LDO at the root and LD for , for a cost of 6. That is the cheapest tiling, and it is the case that the rule is made for.
Correctness
MUNCH always stops, because each call covers at least the node and then works only on smaller subtrees. If the table has a pattern of size 1 for each kind of node, some pattern matches at every node, so the result is a tiling of the whole tree, and each node is covered exactly once. The code computes the value of the tree, because each instruction runs after the instructions of its holes.
The tiling is optimal in the sense of Appel: no two adjacent tiles can be replaced by one tile of lower cost. In fact a stronger claim holds. Let be the tile at and the tile at a hole of . If a pattern covered exactly the nodes of and , it would match at and have size , so line L3 would have chosen it, or a pattern at least as large, instead of . So no two adjacent tiles join into any tile at all, cheap or not. The example shows that this local property does not give the least total cost. The proof file gives the details.
Proof: Maximal munch gives a valid tiling with no two tiles that combinefull
We use the pseudocode of the page. A pattern is a tree whose leaves can be holes. A hole stands for an operand in a register, and every other node of the pattern is an operator, an immediate constant or a variable in memory. When a pattern matches at a node of the tree , it covers the nodes of that sit under the non-hole nodes of , and its holes sit on nodes . The size is the number of nodes that covers. A tiling of is a pattern that matches at and a tiling of for each hole .
We assume that the table is complete: for each kind of node there is a pattern of size 1 that matches it, with a hole for each child. The table of the page has LI, LD, ADD, MUL and LDR, so it is complete.
Lemma 1 (termination and validity). For each node , MUNCH stops and emits a tiling of . Each node of is covered by exactly one tile of it, and each tile comes after the tiles of its holes in the code.
Proof. By induction on the size of . By completeness, at least one pattern matches at , so line L3 chooses a pattern with . The pattern covers and the nodes under its non-hole nodes. Its holes are proper descendants of , and their subtrees are disjoint and disjoint from the nodes that covers. Each node of is either covered by or lies in exactly one subtree . Line L5 calls MUNCH on each , which is smaller than . By induction, each call stops and covers each node of exactly once. Line L6 emits after these calls, so its operands are in registers when it runs.
Lemma 1 also shows that the code computes the value of : the instruction of a tile computes the value of the covered part of the tree from the values of its holes, and by induction these values are in the registers that line L5 returns.
Lemma 2 (no two tiles combine). Let be the tile at a node , and let be the tile at one of its holes . No pattern of the table matches at and covers exactly the nodes that and cover together.
Proof. Suppose that a pattern matches at and covers the union. The two sets are disjoint and , so . When MUNCH ran line L3, also matched at , and line L3 keeps a pattern of the largest size. So the size of the chosen pattern is at least . This contradicts the choice of .
Theorem. Maximal munch emits a valid tiling of . In this tiling, no two adjacent tiles can be replaced by one tile of the table, so in particular by one tile of lower cost. So the tiling is optimal in the sense of Appel.
Proof. Lemma 1 and Lemma 2. Two tiles are adjacent when one sits on a hole of the other, and this is the case of Lemma 2.
The tiling need not be optimum. Take with the table of the page. At the root, LDR has size 1, LDO does not match, and LDX has size 2, so MUNCH picks LDX. Then it tiles MUL with MUL and the three variables with LD. The cost is . The tiling LDR, MADD and three LD costs . The tiles LDX and MUL of the munch tiling do not combine into any pattern, so Lemma 2 is not violated. The local property does not give the least total cost.
Time. Line L2 tries each pattern at each node where MUNCH runs, and a match takes time proportional to the size of the pattern. MUNCH runs once for each tile, and each tile covers at least one node. So the time is for nodes, patterns and patterns of at most nodes. For a fixed table this is linear in .
Complexity
MUNCH runs once for each tile, and each tile covers at least one node, so it runs at most times. Each run tries all patterns, and a match takes time proportional to the size of the pattern, at most . The time is , which is linear in for a fixed table. A real code generator sorts the patterns by size and indexes them by the operator at the root, so a run tries only a few patterns. The recursion is as deep as the tree, so the extra space is .
Properties
- Valid. With a complete table, the result covers each node exactly once.
- Optimal, not optimum. No two adjacent tiles join into one tile, but the total cost can be higher than the least cost.
- Cost-blind. The choice uses the sizes of the patterns, not their costs. A cost changes the result only through the order of the table.
- Greedy and top-down. It is a greedy algorithm: a choice at a node is never taken back.
- No register limit. It uses a new virtual register for each tile. A register allocator runs later.
Variants and improvements
- Cost as the key. Choose the pattern with the best ratio of cost to size, or the most expensive one. Such a rule is still greedy, and it can still miss the least cost, because a choice at the root cannot see the costs below.
- Optimum tiling. The Aho-Johnson dynamic program and BURS find the least cost with the same table, in time that is also linear for a fixed table.
- Munch and peephole. Some compilers first select simple instructions and then combine them with a peephole optimizer. The two methods find many of the same big instructions.
When to use it
Use it for a first code generator, a simple compiler or a JIT that must be fast and short. It also works well on machines whose cost model is close to "fewer instructions is better", where big tiles are almost always good, such as many RISC machines. When the table has many overlapping patterns with different costs, as on CISC machines or in DSP code, use a dynamic program or BURS instead.
Pitfalls
- "Optimal" is not "optimum". In Appel's words an optimal tiling is only locally best. Do not claim that munch gives the cheapest code.
- An incomplete table. If some node kind has no pattern of size 1, munch can reach a node where nothing matches, even though a tiling of the whole tree exists.
- The order of the table. Two patterns of the same size can both match, for example ADDM and MADD on . The first one in the table wins, so a change in the order changes the code and its cost.
- Shared nodes. On a DAG, munch tiles a shared node once for each parent, so the code computes it more than once.
- Another maximal munch. In lexical analysis, "maximal munch" is the longest-match rule for tokens. It is a different algorithm with the same idea.
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/maximal-munch/. The authors are listed in prov/FV9S4Q.jsonl.
"""Maximal munch instruction selection for expression trees.
A tree is written with tuples: ("CONST", k), ("VAR", x), ("MEM", a),
("ADD", a, b) or ("MUL", a, b). VAR is a variable in memory and MEM(a)
loads the word at the address a. Each instruction is a tree pattern with a
cost. 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, ...
"""
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),
]
def size(pat: object) -> int:
"""The number of tree nodes that the pattern covers."""
if pat == "reg":
return 0
return 1 + sum(size(q) for q in pat[1:])
def match(pat: object, n: tuple) -> list | None:
"""Match pat at n. Return the leaves of the pattern, left to right, as
(kind, node) pairs with kind "reg", "const" or "var", or None."""
if pat == "reg":
return [("reg", n)]
if pat == ("CONST",):
return [("const", n)] if n[0] == "CONST" else None
if pat == ("VAR",):
return [("var", n)] if n[0] == "VAR" else None
if n[0] != pat[0]:
return None
out: list = []
for p, child in zip(pat[1:], n[1:]):
m = match(p, child)
if m is None:
return None
out += m
return out
def choose(n: tuple) -> tuple[int, list]:
"""The largest pattern that matches at n. A tie goes to the first one in the table."""
best, leaves = -1, None
for idx, (_, pat, _) in enumerate(RULES): # @line L2
m = match(pat, n)
if m is not None and (best < 0 or size(pat) > size(RULES[best][1])): # @line L3
best, leaves = idx, m
if best < 0:
raise ValueError("no pattern matches at %r" % (n[0],))
return best, leaves
def munch(n: tuple, code: list) -> str:
"""Append the code for n to code and return the register that holds n."""
idx, leaves = choose(n) # @line L1
args = []
for kind, h in leaves: # @line L4
if kind == "reg":
args.append(munch(h, code)) # @line L5
else:
args.append(h[1])
dst = "v%d" % len(code)
code.append((idx, dst, args)) # @line L6
return dst # @line L7
def select(tree: tuple) -> tuple[list, int]:
"""Return (code, cost) of the maximal munch tiling of the tree."""
code: list = []
munch(tree, code)
return code, sum(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]) -> 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_maximal_munch.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-munch/. The authors are listed in prov/FV9S4Q.jsonl.
import random
from maximal_munch import RULES, choose, evaluate, run, select
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 paths(t: tuple, p: tuple = ()) -> list[tuple]:
"""The path of every node: the list of child positions from the root."""
out = [p]
if t[0] not in ("CONST", "VAR"):
for i, c in enumerate(t[1:]):
out += paths(c, p + (i,))
return out
def node_at(t: tuple, p: tuple) -> tuple:
for i in p:
t = t[1 + i]
return t
def cover(pat: object, t: tuple, p: tuple) -> tuple[set, list] | None:
"""The paths that the pattern covers at path p, and the paths of its register holes."""
n = node_at(t, p)
if pat == "reg":
return set(), [p]
if pat == ("CONST",) or pat == ("VAR",):
return ({p}, []) if n[0] == pat[0] else None
if n[0] != pat[0]:
return None
covered, holes = {p}, []
for i, q in enumerate(pat[1:]):
m = cover(q, t, p + (i,))
if m is None:
return None
covered |= m[0]
holes += m[1]
return covered, holes
def munch_tiles(t: tuple) -> dict[tuple, tuple]:
"""The tiles that munch chooses: root path -> (rule, covered paths, hole paths)."""
tiles: dict[tuple, tuple] = {}
def go(p: tuple) -> None:
idx, _ = choose(node_at(t, p))
covered, holes = cover(RULES[idx][1], t, p)
tiles[p] = (idx, covered, holes)
for h in holes:
go(h)
go(())
return tiles
def tilings(t: tuple) -> list[int]:
"""The cost of every tiling of t."""
res = []
for _, pat, cost in RULES:
m = cover(pat, t, ())
if m is None:
continue
partial = [cost]
for h in m[1]:
partial = [x + y for x in partial for y in tilings(node_at(t, h))]
res += partial
return res
def test_munch_is_not_optimum() -> None:
t = ("MEM", ("ADD", ("MUL", ("VAR", "a"), ("VAR", "b")), ("VAR", "c")))
code, cost = select(t)
assert [RULES[ins[0]][0] for ins in code] == ["ld", "ld", "mul", "ld", "ldx"]
assert cost == 15
assert min(tilings(t)) == 14
env = {"a": 4, "b": 5, "c": 6}
assert run(code, env) == evaluate(t, env) == 37
def test_cover_is_valid_and_locally_optimal() -> None:
rng = random.Random(1978)
worse = 0
for _ in range(400):
t = random_tree(rng, rng.randint(1, 8))
tiles = munch_tiles(t)
# each node is covered by exactly one tile
seen: list = []
for _, covered, _ in tiles.values():
seen += covered
assert sorted(seen) == sorted(paths(t))
# a parent tile and a child tile never form one tile of the table
for v, (_, cv, holes) in tiles.items():
for h in holes:
union = cv | tiles[h][1]
for _, pat, _ in RULES:
m = cover(pat, t, v)
assert m is None or m[0] != union
code, cost = select(t)
assert cost == sum(RULES[idx][2] for idx, _, _ in tiles.values())
assert cost >= min(tilings(t))
worse += cost > min(tilings(t))
for _ in range(3):
env = {x: rng.randint(-20, 20) for x in "abc"}
assert run(code, env) == evaluate(t, env)
assert worse > 0
def test_each_tree_has_a_cover() -> None:
rng = random.Random(9)
for _ in range(200):
t = random_tree(rng, rng.randint(1, 30))
code, _ = select(t)
env = {x: rng.randint(-9, 9) for x in "abc"}
assert run(code, env) == evaluate(t, env)
History
Cattell used the largest-pattern-first rule in the code generator generator of his 1978 thesis at Carnegie Mellon, and he described the method in TOPLAS in 1980. The 1980 paper does not use the words "maximal munch"; Hjort Blindell traces the term to the thesis. Appel used the name for the algorithm in his textbooks of the late 1990s, where he also set the terms optimal and optimum tilings apart. Optimum tree tiling is older: Aho and Johnson gave a dynamic program in 1976.
References
- Roderic G. G. Cattell, Automatic derivation of code generators from machine descriptions, ACM Transactions on Programming Languages and Systems 2(2), 1980, 173-190, the code generator that matches the largest instruction pattern first at the root of the tree and then works on the subtrees
- Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 9 (Instruction Selection), Section 9.1, the Maximal Munch algorithm and the definitions of optimal and optimum tilings
- Gabriel Hjort Blindell, Survey on instruction selection, an extensive and modern literature review, arXiv:1306.4898, 2013, the section on macro expansion and tree covering, where the term maximal munch is traced to the thesis of Cattell
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 FV9S4Q Edit this page History Report an error Markdown