Algorithm Search⌘K

Algorithmcore

Local register allocation

Also called bottom-up local allocation.

Allocates registers in one basic block in order, and when none is free spills the value whose next use is farthest away.

Time
O(n k) worst
Space
Θ(n) extra
Where
k = the number of registers; n = the number of instructions of the block
Properties
deterministicofflineiterative
Origin
Laszlo A. Belady, 1966

Local register allocation assigns machine registers to the values of one basic block. The bottom-up allocator walks the block from the first instruction to the last. It gives each operand and each result a register, and when no register is free, it frees the register whose value is needed again furthest in the future. This is Belady's rule for paging, applied to registers. When every value has a copy in memory, the rule gives the least number of loads, by the optimality of Belady's rule. When some values are dirty, so that freeing them costs a store, the rule can lose, and the exact problem is NP-hard.

In plain words

A block of code uses more values than the machine has registers. The allocator walks through the block in order. Before an instruction runs, its operands must be in registers. If an operand is not there, the allocator loads it from memory. The result of the instruction also needs a register.

When all registers are full, one value must go. The allocator looks ahead in the block and chooses the value that will be needed again last. That value would stay unused for the longest time, so a register spent on it is the most wasted.

If the value that goes has no copy in memory yet, the allocator must save it first. This extra store is the weak spot of the rule. A value with a copy in memory is cheaper to throw out, and the rule does not look at that.

The problem

The input is one block of the toy IR and a number k≥2k \ge 2 of registers r0,…,rk−1r_0, \ldots, r_{k-1}. The block has const, copy and op instructions and ends with ret. Each name xx has a memory slot mem.x. The parameters start in memory. An op instruction reads its operands from registers and writes its result to a register.

A value in a register is clean if memory holds the same value, and dirty if not. A parameter that was loaded is clean. A value that an instruction computes is dirty until it is stored. A load costs 1, and a store costs 1. In the clean model, a store costs 0, which is the same as saying that every value is clean.

The output is a block that uses only the registers and the memory slots, computes the same result, and has the least number of loads and stores. The allocation is on demand: it loads a value only when an instruction needs it, and frees a register only when it needs one.

The algorithm

The block is first read backwards to find, for each value and each point, the next use of the value. A value with no later use is dead.

  1. ALLOCATE(block, k)
  2. 1for each instruction x ← a op b of the block, in order do
  3. 2for each operand u that is not in a register do
  4. 3r ← GETREG(pinned = the operands of this instruction that are already in registers); emit r ← mem.u; u is clean
  5. 4for each operand u that is dead after this instruction do free the register of u
  6. 5r ← GETREG(pinned = none); emit r ← the operation, with the registers of the operands
  7. 6put x in r; x is dirty; if x is dead, free r
  8. GETREG(pinned)
  9. 7if some register is free then return it
  10. 8v ← the value in a register, not pinned, whose next use is furthest away
  11. 9if v is dirty then emit mem.v ← the register of v ▷ a store
  12. 10free the register of v and return it

The ret is an instruction with one operand and no result. Line L5 may reuse the register of an operand, even of a live one, because the instruction reads its operands before it writes its result. A pinned operand is never freed at line L3, so both operands of an instruction are in registers at the same time.

Example

Take this block and k=2k = 2:

# params: a, b, c, d
entry:
  t = a + b
  u = c + d
  v = t * u
  w = v - a
  ret w

The allocator emits:

# params: mem.a, mem.b, mem.c, mem.d
entry:
  r0 = mem.a
  r1 = mem.b
  r1 = r0 + r1
  r0 = mem.c
  mem.t = r1
  r1 = mem.d
  r0 = r0 + r1
  r1 = mem.t
  r0 = r1 * r0
  r1 = mem.a
  r0 = r0 - r1
  ret r0

After the first instruction, bb is dead, so tt takes its register, and r0r_0 still holds aa. To load cc, the allocator compares aa, needed at the fourth instruction, with tt, needed at the third, and frees aa. It is clean, so this costs nothing now. To load dd, the only register that is not pinned holds tt, which is dirty, so it is stored first. The cost is six loads and one store, 7 in total. A brute force search over all choices also finds 7. With k=3k = 3, the allocator frees the clean aa to load dd, and the cost is 5 loads.

For a=1a = 1, b=2b = 2, c=3c = 3 and d=4d = 4, both blocks return 20.

Correctness

The output computes the same values as the block. Each instruction reads its operands from the registers that hold them, a pinned operand is never freed before its instruction runs, and a value is loaded only from a memory slot that holds it, because a dirty value is stored before its register is freed.

The clean model is a case of demand paging. The values are pages, the registers are the cache, and each use of a value is a request. A pinned operand gets one more request just after the request for the other operand, so the furthest-next-request rule never evicts it, and each definition is a request for a new page, which every schedule must load. Under this map the allocator is exactly LFD, and its cost is the cost of LFD minus the number of definitions, the same constant for every allocation. So the optimality of Belady's rule gives the least number of loads.

With dirty values, the rule can lose. With k=3k = 3 and the block t = b + 1, u = b + t, u = u * a, t = b * t, v = t * u, ret v, the allocator must free a register for aa while uu is pinned. The next uses of bb and tt are the two operands of the fourth instruction, and tt comes second, so the rule frees the dirty tt: a store and a load later, for a total of 4. Freeing the clean bb costs one load, for a total of 3. The proof file gives both proofs.

Proof: Belady's rule is optimal for local allocation with clean values, and only thenfull

We use the model and the pseudocode of the page. A block is turned into a list of steps. A value is a definition of a name, or a parameter. For each instruction, there is a step USE uu for each distinct operand uu, in order, where the earlier operands of the same instruction are pinned. Then there is a step DROP uu for each operand with no later use, and then a step DEF xx for the result. The ret is an instruction with one operand and no result. There are k≥2k \ge 2 registers.

An allocation answers each step. At USE uu with uu not in a register, it loads uu into a free register, or, if there is none, it frees the register of some value that is not pinned, and then loads uu. At DEF xx, it puts xx into a free register, or frees the register of some value first. A value that is freed while it is dirty costs a store. A load costs 1. The clean model is the model in which stores cost 0, which is the same as saying that each value always has a copy in memory.

Validity

Lemma 1. The code that ALLOCATE emits computes the same result as the block, and it never uses more than kk registers.

Proof. The allocator keeps the map from registers to values exact: a register holds a value only after the load or the instruction that writes it, and the map drops a value when its register is freed or reused. Only registers r0,…,rk−1r_0, \ldots, r_{k-1} exist. A load reads the memory slot of a value. That slot holds the value: a parameter starts there, and a computed value is loaded only after the store that line L9 emits when it frees the register of the dirty value. The slot of a name is not written again while the value is live, because a later definition of the same name comes after the last use of the old value. An instruction reads its operands from the registers that the USE steps recorded. A pinned operand is never freed before the instruction runs, so these registers still hold the operands. Freeing the register of an operand at DEF is safe, because the instruction reads its operands before it writes its result. By induction over the steps, each instruction computes the value of the original one, so the ret returns the same value. □\square

The clean model

Theorem 1. In the clean model, ALLOCATE with Belady's rule (lines L7 and L8) has the least cost of all allocations of the block.

Proof. We map the block to a request sequence σ\sigma for demand paging with a cache of size kk and an empty initial cache. The pages are the values. Each USE uu gives a request for uu. If the USE step of uu has pinned values, it is followed by one more request for each pinned value. Each DEF xx gives a request for xx. DROP steps give no request.

From allocations to paging. Take any allocation AA. It gives a paging schedule PAP_A: keep the same values in the cache as AA keeps in registers, except that a dropped value stays in the cache until AA reuses its register. The repeated requests of pinned values are hits, since AA never frees a pinned value. The request for a defined value xx is a fault in every schedule, because xx was never requested before. So PAP_A loads exactly cost(A)+D\mathrm{cost}(A) + D pages, where DD is the number of DEF steps.

From LFD to Belady. By the optimality of Belady's rule, the schedule LFD, which evicts the page whose next request is furthest away, loads at most as many pages on σ\sigma as any paging algorithm. We show that LFD on σ\sigma makes the same choices as ALLOCATE.

  • A dropped value has no later request, so LFD evicts it before any live value. This is the same as using the free register at line L7.
  • At a fault on the USE of uu, each pinned value pp has its next request just after the request for uu. The cache is full and has k≥2k \ge 2 pages, so it holds a page other than pp whose next request is later. So LFD never evicts a pinned value, and the repeated requests are hits.
  • The repeated requests only add requests for a pinned value right after the USE step. So among values that are not pinned, the order of the next requests in σ\sigma is the order of the next USE steps, which is the order that line L8 uses.

So LFD on σ\sigma is PBP_B for the allocation BB that ALLOCATE makes, and it loads cost(B)+D\mathrm{cost}(B) + D pages. For each allocation AA,

cost(B)+D=LFD(σ)≤PA(σ)=cost(A)+D.\mathrm{cost}(B) + D = \mathrm{LFD}(\sigma) \le P_A(\sigma) = \mathrm{cost}(A) + D.

So cost(B)≤cost(A)\mathrm{cost}(B) \le \mathrm{cost}(A). ■\blacksquare

Two values never have the same next request in σ\sigma, unless they have none, so the ties of line L8 do not matter for the cost.

Dirty values

Claim 2. When a store costs 1, Belady's rule is not always optimal.

Proof. Take k=3k = 3 and the block

t = b + 1
u = b + t
u = u * a
t = b * t
v = t * u
ret v

with the parameters aa and bb in memory. ALLOCATE loads bb, computes tt and uu, and then needs a register for aa at the third instruction, where uu is pinned. The next uses of bb and tt are the first and the second operand of the fourth instruction, so line L8 frees the register of tt. The value tt is dirty, so this costs a store, and tt is loaded again at the fourth instruction. The total is three loads (bb, aa, tt) and one store: 4. The allocation that frees bb instead pays no store, and it loads bb again at the fourth instruction: three loads (bb, aa, bb), a total of 3. □\square

In this case, the value with the furthest next use is only one step further than a clean value, but it costs twice as much to free. Belady's rule does not see the difference. The test file checks Theorem 1 and Claim 2 by brute force over all choices of the register to free.

Complexity

Reading the block backwards gives, for each use, the position of the next use of the same value, in O(n)O(n) time. Then each step of ALLOCATE tests at most kk registers at lines L7 and L8, so the time is O(nk)O(n k) in the worst case. A priority queue of the registers by next use brings this to O(nlog⁡k)O(n \log k), but kk is small, so a scan is the usual choice. The next-use table takes Θ(n)\Theta(n) space. The reference code keeps a copy of the table for each step, for clarity.

Properties

  • Optimal for clean values. In the clean model, with equal load costs, no allocation of the block has fewer loads.
  • Not optimal with stores. With dirty values the exact problem is NP-hard (Farach-Colton and Liberatore), and the rule is only a heuristic.
  • Offline. The rule looks at future uses, which is fine in a compiler, because the whole block is known.
  • Local. It knows nothing about other blocks. At the end of a block, the values that are live out must go back to memory or to agreed registers.

Variants and improvements

  • Clean first. Among the values whose next use is far away, prefer a clean one. This fixes the counterexample, but it can lose in other blocks. Farach-Colton and Liberatore give an algorithm whose cost is within a constant factor of the optimum.
  • Top-down allocation. Count the uses of each value in the block, give registers to the most used values for the whole block, and keep a few registers free for the rest. It is simpler and often worse.
  • Rematerialization. A constant or a value that is cheap to compute again is always clean: instead of a reload, the allocator can recompute it.
  • Global allocators. Linear scan uses a similar furthest-end rule over a whole function, and graph coloring works on the interference of live ranges.
  • Expression trees. For a single tree without shared values, the Sethi-Ullman numbering chooses an evaluation order that needs the fewest registers.

When to use it

Use it in a fast compiler or a JIT, where a global allocator is too slow, and in the back end of a simple code generator for straight-line code. It is also the inner step of some global allocators, which first fix the values that live across blocks and then allocate each block on its own. For code with many dirty values and expensive stores, add the clean-first rule or a cost-aware search.

Pitfalls

  • Freeing a pinned operand. If the load of the second operand frees the register of the first, the instruction cannot run. Pin the operands of the current instruction.
  • Forgetting the store. A dirty value must be stored before its register is reused, or a later reload reads an old value.
  • Reusing a slot too early. If two values of the same name share one memory slot, the slot of the old value must not be needed after the new one is stored. In the toy IR this holds, because the new definition comes after the last use of the old value.
  • Dead values. A value with no later use should free its register at once. Belady's rule evicts it first anyway, but code that keeps dead values can store them for nothing.
  • "Optimal" for the wrong model. The optimality theorem counts loads with clean values. With stores, or with loads of different costs, it no longer holds.

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_register_allocation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-register-allocation/. The authors are listed in prov/A84DF7.jsonl.

"""Bottom-up local register allocation for one basic block of the toy IR.

The block has const, copy and op instructions and ends with ret. The machine
has k registers r0 .. r(k-1). Each name x also has a memory slot mem.x. The
parameters start in memory, so they are clean: memory has their value. A
value that an instruction computes is dirty until it is stored. A load
mem.x -> r costs LOAD_COST, and a store r -> mem.x costs store_cost.

The output is a toy IR program whose parameters are the memory slots of the
original parameters, and which uses only registers and memory slots.
"""

from toyir import Block, Program

LOAD_COST = 1
NEVER = float("inf")


def operands(ins: tuple, term: tuple) -> list:
    """The operands that an instruction reads; ins is None for the ret."""
    if ins is None:
        return [term[1]]
    if ins[0] == "op":
        return [ins[3], ins[4]]
    if ins[0] == "copy":
        return [ins[2]]
    if ins[0] == "const":
        return []
    raise ValueError("a local block has only const, copy and op: %r" % (ins,))


def steps(block: Block) -> list[tuple]:
    """The block as a list of register requests. A value is a pair (name,
    i): the name and the index of its definition, with i = -1 for a
    parameter. The steps are:
      ("use", u, pinned)  u must be in a register; pinned values must stay
      ("drop", u)         u has no later use, so its register is free
      ("def", x)          x needs a register; it is dirty
    """
    instrs = list(block.instrs) + [None]
    cur: dict[str, tuple] = {}
    reads: list[list] = []
    for i, ins in enumerate(instrs):
        vals: list = []
        for a in operands(ins, block.term):
            if isinstance(a, str) and cur.get(a, (a, -1)) not in vals:
                vals.append(cur.get(a, (a, -1)))
        reads.append(vals)
        if ins is not None:
            cur[ins[1]] = (ins[1], i)
    last: dict[tuple, int] = {}
    for i, vals in enumerate(reads):
        for v in vals:
            last[v] = i
    out: list[tuple] = []
    for i, vals in enumerate(reads):
        for t, v in enumerate(vals):
            out.append(("use", v, tuple(vals[:t])))
        for v in vals:
            if last[v] == i:
                out.append(("drop", v))
        if instrs[i] is not None:
            x = (instrs[i][1], i)
            out.append(("def", x))
            if x not in last:
                out.append(("drop", x))
    return out


def next_uses(st: list[tuple]) -> list[dict]:
    """For each step s, the step of the next use after s of each value."""
    res: list[dict] = [{} for _ in st]
    nxt: dict[tuple, int] = {}
    for s in range(len(st) - 1, -1, -1):
        res[s] = dict(nxt)
        if st[s][0] == "use":
            nxt[st[s][1]] = s
    return res


class Allocator:
    """Belady's rule: evict the value whose next use is furthest away."""

    def __init__(self, k: int, store_cost: int = 1) -> None:
        if k < 2:
            raise ValueError("an instruction can need two registers")
        self.k = k
        self.store_cost = store_cost

    def victim(self, reg: list, pinned: tuple, nxt: dict) -> int:
        """The register to free. A subclass can try another rule."""
        cand = [r for r in range(self.k) if reg[r] not in pinned]
        return max(cand, key=lambda r: (nxt.get(reg[r], NEVER), -r))  # @line L8

    def getreg(self, pinned: tuple, nxt: dict) -> int:
        if None in self.reg:  # @line L7
            return self.reg.index(None)
        r = self.victim(self.reg, pinned, nxt)
        v = self.reg[r]
        if v in self.dirty:  # @line L9
            self.code.append(("copy", "mem." + v[0], "r%d" % r))
            self.cost += self.store_cost
            self.dirty.discard(v)
        self.reg[r] = None  # @line L10
        return r

    def allocate(self, prog: Program) -> tuple[Program, int]:
        """Return the allocated program and its cost in loads and stores."""
        ((label, block),) = prog.blocks.items()
        st = steps(block)
        nu = next_uses(st)
        self.reg: list = [None] * self.k
        self.dirty: set = set()
        self.code: list = []
        self.cost = 0
        cur: dict[str, tuple] = {}
        where: dict[tuple, str] = {}  # the register of each operand of the current instruction
        for s, step in enumerate(st):  # @line L1
            if step[0] == "use":
                u = step[1]
                if u not in self.reg:  # @line L2
                    r = self.getreg(step[2], nu[s])  # @line L3
                    self.code.append(("copy", "r%d" % r, "mem." + u[0]))
                    self.cost += LOAD_COST
                    self.reg[r] = u
                where[u] = "r%d" % self.reg.index(u)
            elif step[0] == "drop":  # @line L4
                if step[1] in self.reg:
                    self.reg[self.reg.index(step[1])] = None
            else:
                x = step[1]
                ins = block.instrs[x[1]]

                def loc(a: object) -> object:
                    return where[cur.get(a, (a, -1))] if isinstance(a, str) else a

                r = self.getreg((), nu[s])  # @line L5
                dst = "r%d" % r
                if ins[0] == "const":
                    self.code.append(("const", dst, ins[2]))
                elif ins[0] == "copy":
                    self.code.append(("copy", dst, loc(ins[2])))
                else:
                    self.code.append(("op", dst, ins[2], loc(ins[3]), loc(ins[4])))
                self.reg[r] = x  # @line L6
                self.dirty.add(x)
                cur[x[0]] = x
                where = {}
        ret = block.term[1]
        if isinstance(ret, str):
            ret = where[cur.get(ret, (ret, -1))]
        params = ["mem." + p for p in prog.params]
        return Program(params, {label: Block(self.code, ("ret", ret))}), self.cost


def allocate(prog: Program, k: int, store_cost: int = 1) -> tuple[Program, int]:
    """Allocate the one block of prog to k registers with Belady's rule."""
    return Allocator(k, store_cost).allocate(prog)
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_register_allocation.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-register-allocation/. The authors are listed in prov/A84DF7.jsonl.

import random
from functools import lru_cache

from local_register_allocation import LOAD_COST, allocate, steps
from toyir import Block, Program, parse, run


def random_block(rng: random.Random, n: int) -> Program:
    """A block of n instructions over the parameters a, b, c and the names x0 .. x3."""
    names = ["a", "b", "c"]
    instrs = []
    for _ in range(n):
        x = "x%d" % rng.randrange(4)
        r = rng.random()
        if r < 0.1:
            instrs.append(("const", x, rng.randint(0, 9)))
        elif r < 0.2:
            instrs.append(("copy", x, rng.choice(names)))
        else:
            b = rng.choice(names) if rng.random() < 0.85 else rng.randint(1, 5)
            instrs.append(("op", x, rng.choice("+-*"), rng.choice(names), b))
        if x not in names:
            names.append(x)
    return Program(["a", "b", "c"], {"entry": Block(instrs, ("ret", rng.choice(names)))})


def best_cost(prog: Program, k: int, store_cost: int) -> int:
    """Brute force over every choice of the register to free, at every step
    where no register is free."""
    (block,) = prog.blocks.values()
    st = steps(block)

    @lru_cache(maxsize=None)
    def go(s: int, regs: frozenset, dirty: frozenset) -> int:
        if s == len(st):
            return 0
        kind, v = st[s][0], st[s][1]
        if kind == "drop":
            return go(s + 1, regs - {v}, dirty - {v})
        if kind == "use" and v in regs:
            return go(s + 1, regs, dirty)
        here = LOAD_COST if kind == "use" else 0
        new_dirty = dirty | {v} if kind == "def" else dirty
        if len(regs) < k:
            return here + go(s + 1, regs | {v}, new_dirty)
        pinned = st[s][2] if kind == "use" else ()
        best = None
        for w in regs:
            if w in pinned:
                continue
            c = here + (store_cost if w in dirty else 0)
            c += go(s + 1, (regs - {w}) | {v}, (new_dirty - {w}))
            best = c if best is None else min(best, c)
        return best

    return go(0, frozenset(), frozenset())


def check_runs(prog: Program, out: Program, k: int, rng: random.Random) -> None:
    (code,) = out.blocks.values()
    for ins in code.instrs:
        for a in ins[1:]:
            if isinstance(a, str) and a not in ("+", "-", "*"):
                assert a.startswith("mem.") or int(a[1:]) < k
    for _ in range(3):
        args = [rng.randint(-9, 9) for _ in prog.params]
        assert run(out, args) == run(prog, args)


def test_example() -> None:
    prog = parse(
        """
        # params: a, b, c, d
        entry:
          t = a + b
          u = c + d
          v = t * u
          w = v - a
          ret w
        """
    )
    out, cost = allocate(prog, 2)
    assert cost == best_cost(prog, 2, 1) == 7
    (code,) = out.blocks.values()
    assert sum(1 for ins in code.instrs if ins[0] == "copy" and ins[1] == "mem.t") == 1
    assert run(out, [1, 2, 3, 4]) == run(prog, [1, 2, 3, 4]) == ("ret", 20)
    out, cost = allocate(prog, 3)
    assert cost == best_cost(prog, 3, 1) == 5


def test_belady_is_optimal_when_stores_are_free() -> None:
    rng = random.Random(1966)
    for _ in range(300):
        prog = random_block(rng, rng.randint(1, 8))
        for k in (2, 3):
            out, cost = allocate(prog, k, store_cost=0)
            assert cost == best_cost(prog, k, 0)
            check_runs(prog, out, k, rng)


def test_dirty_values() -> None:
    rng = random.Random(2000)
    worse = 0
    for _ in range(300):
        prog = random_block(rng, rng.randint(1, 8))
        for k in (2, 3):
            out, cost = allocate(prog, k)
            best = best_cost(prog, k, 1)
            assert cost >= best
            worse += cost > best
            check_runs(prog, out, k, rng)
    assert worse > 0


def test_belady_is_not_optimal_with_dirty_values() -> None:
    prog = parse(
        """
        # params: a, b
        entry:
          t = b + 1
          u = b + t
          u = u * a
          t = b * t
          v = t * u
          ret v
        """
    )
    out, cost = allocate(prog, 3)
    assert run(out, [3, 5]) == run(prog, [3, 5])
    # Belady frees the register of t, which is dirty: one store and one load.
    # Freeing b, which is clean, costs one load.
    assert cost == 4
    assert best_cost(prog, 3, 1) == 3
    assert allocate(prog, 3, store_cost=0)[1] == best_cost(prog, 3, 0) == 3

History

Belady studied replacement algorithms for virtual memory in 1966 and gave the rule that evicts the page whose next use is furthest in the future. Compiler textbooks use the same rule for the bottom-up local allocator. Its optimality for paging was proved later; the optimality page gives the history. Farach-Colton and Liberatore studied local register allocation with clean and dirty values in 2000. They proved that the problem with store costs is NP-hard and gave an approximation algorithm.

References

  1. L. A. Belady, A study of replacement algorithms for a virtual-storage computer, IBM Systems Journal 5(2), 1966, 78-101, the replacement rule that evicts the page whose next reference is furthest in the future
  2. Martin Farach-Colton and Vincenzo Liberatore, On local register allocation, Journal of Algorithms 37(1), 2000, 37-65, the model with clean and dirty values, the NP-hardness of the problem with store costs, and the approximation algorithm
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 13 (Register Allocation), local register allocation, the top-down and the bottom-up local allocators, and the remark on clean and dirty values
  4. 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), the simple code generator for a basic block and its function getReg

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