Algorithm Search⌘K

Algorithmcore

Chaitin register allocation

Also called graph coloring register allocation, Chaitin allocator.

Simplifies the interference graph by removing nodes of degree less than k, spills when none is left, and colors in reverse order.

Time
O(r (l + s n + n^2)) worst
Space
O(n + m + s) extra
Where
l = the time of one liveness analysis; m = the number of interference edges; n = the number of names; r = the number of rounds (at most n + 1); s = the number of instructions
Properties
deterministicofflineiterative
Origin
Gregory J. Chaitin, Marc A. Auslander, Ashok K. Chandra, John Cocke, Martin E. Hopkins, Peter W. Markstein, 1981

Chaitin's allocator gives registers to the names of a program by coloring its interference graph with kk colors, one per register. It removes vertices of degree less than kk one by one, because such a vertex can always be colored after its neighbors. When every vertex left has degree kk or more, it chooses one to spill by the ratio of its spill cost to its degree, keeps that name in memory, adds loads and stores, and starts again with a new graph. When nothing is spilled, it colors the vertices in the reverse order of their removal. It solves the register allocation problem as a heuristic: it always gives a correct program, but it may spill a name although the graph has a kk-coloring, and the full problem is NP-hard (register-allocation-np-completeness).

In plain words

Each value of the program is a dot, and a line joins two values that are needed at the same time. We want to color the dots with kk colors so that no line joins two dots of one color. Look for a dot with fewer than kk lines. Whatever colors its neighbors get, at least one color is left for it. So put it aside and forget it. Its removal may give other dots fewer lines, so repeat. If every dot gets put aside, give colors in the reverse order: each dot, when its turn comes, still has a free color. If at some moment every dot left has kk lines or more, pick the one that is cheapest to keep in memory, move it to memory in the program, and start again.

The problem

The input is a program PP in the toy IR with const, copy and op instructions, and a number k≥2k \ge 2 of registers. The output is a program P′P' that uses only the registers r0,…,rk−1r_0, \ldots, r_{k-1} and memory slots mem.x, and that has the same outcome as PP on every input. The goal is few loads and stores, but the allocator gives no bound on their number.

The algorithm works on the interference graph G=(V,E)G = (V, E): two names are joined when one is live just after a definition of the other, except at a copy between them. A kk-coloring is a map c:V→{0,…,k−1}c: V \to \{0, \ldots, k-1\} with c(x)≠c(y)c(x) \ne c(y) on every edge. The kk-core of GG is the largest induced subgraph in which every vertex has degree at least kk (it may be empty); see degeneracy. The spill cost of a name is here the number of its definitions and uses; a real compiler weights each one by an estimate of how often its block runs.

The algorithm

  1. CHAITIN-ALLOCATE(P, k)
  2. 1P <- P with a new entry block that loads each live parameter p from mem.p
  3. 2T <- the empty set // spill temporaries
  4. 3loop
  5. 4G <- the interference graph of P // build
  6. 5cost[x] <- the number of definitions and uses of x in P, or infinity if x is in T
  7. 6stack <- empty; spill <- the empty set
  8. 7while G has a vertex do // simplify
  9. 8if some vertex v of G has degree < k then
  10. 9push v on stack; remove v from G
  11. 10else
  12. 11v <- a vertex of G with the least cost[v] / degree(v)
  13. 12spill <- spill + {v}; remove v from G
  14. 13if spill is empty then
  15. 14for each v on stack, from the top down do // select
  16. 15color[v] <- the least color in 0 .. k-1 not used by a colored neighbor of v
  17. 16return P with each name x renamed to r[color[x]] and each copy r = r deleted
  18. 17P <- P with each x in spill kept in mem.x: a load into a new temporary before
  19. each use of x and a store from a new temporary after each definition of x
  20. 18T <- T + the new temporaries

Line L8 picks the vertices of degree less than kk in the order in which they reach that degree; the vertices that start below kk come first, in the order of the names in the program. The implementation keeps them in a queue. Line L11 breaks ties by the same order.

Line L15 always finds a color: when vv was pushed, it had fewer than kk neighbors left in GG, and the neighbors colored before it are exactly those. The spill code of line L17 is spill everywhere: every use of a spilled name reads a fresh temporary loaded just before it, and every definition writes a fresh temporary stored just after it. A temporary lives across at most one instruction, so it gets an infinite cost and is never spilled again.

Example

Take the program with one parameter p:

L0:
  a = p + 1
  b = p + 2
  c = a + b
  d = a * c
  e = b * d
  ret e

Line L1 adds the block start with p = mem.p and jump L0. The edges of GG are pp-aa, aa-bb, aa-cc, bb-cc and bb-dd; ee is isolated. The names in program order are p,a,b,c,d,ep, a, b, c, d, e, and the costs are 3, 3, 3, 2, 2 and 2.

With k=3k = 3. The degrees are p:1p{:}1, a:3a{:}3, b:3b{:}3, c:2c{:}2, d:1d{:}1 and e:0e{:}0, so the queue starts as p,c,d,ep, c, d, e.

step removed degrees that change queue after
1 pp aa: 3 to 2 c,d,e,ac, d, e, a
2 cc aa: 2 to 1, bb: 3 to 2 d,e,a,bd, e, a, b
3 dd bb: 2 to 1 e,a,be, a, b
4 ee none a,ba, b
5 aa bb: 1 to 0 bb
6 bb none empty

No spill. Line L14 pops b,a,e,d,c,pb, a, e, d, c, p and line L15 gives b→0b \to 0, a→1a \to 1, e→0e \to 0, d→1d \to 1 (its neighbor bb has 0), c→2c \to 2 (aa has 1 and bb has 0), and p→0p \to 0. The result is:

start:
  r0 = mem.p
  jump L0
L0:
  r1 = r0 + 1
  r0 = r0 + 2
  r2 = r1 + r0
  r1 = r1 * r2
  r0 = r0 * r1
  ret r0

With k=2k = 2. The queue starts as p,d,ep, d, e. Removing them lowers aa and bb to degree 2, and then aa, bb and cc all have degree 2. Line L11 compares 3/23/2, 3/23/2 and 2/22/2 and spills cc. Line L17 rewrites c = a + b and d = a * c as

  c.1 = a + b
  mem.c = c.1
  c.2 = mem.c
  d = a * c.2

The store and the load are next to each other, so the pressure does not drop: in round 2, aa, bb and the temporary c.2 still form a triangle. Round 2 spills aa (cost 3 over degree 4, tied with bb and first in order), round 3 spills bb, and round 4 colors the graph. The final program has 3 stores and 5 loads besides the parameter load. One store and one load are enough, by keeping only bb in memory between its definition and e = b * d, as the page register allocation problem shows. So the allocator is far from optimal on this program, mainly because of spill everywhere.

A graph that is 2-colorable but spilled. In a cycle of length 4 every vertex has degree 2. With k=2k = 2, line L8 never applies, so line L11 spills a vertex, although two colors suffice. Optimistic coloring colors this cycle.

Correctness

The full proof is in the proof file. Its parts are:

  • Simplify rule. If deg⁡(v)<k\deg(v) < k, then GG is kk-colorable if and only if G−vG - v is. So removing vv at line L9 loses no coloring.
  • Select. When no spill happens, line L15 gives each vertex a color below kk that differs from all its neighbors, so the coloring is proper.
  • When it spills. Chaitin's allocator chooses a spill in a round if and only if the kk-core of GG is not empty. So it colors without spilling exactly the graphs of degeneracy less than kk.
  • Renaming. If cc is a proper coloring of GG, renaming each name xx to rc(x)r_{c(x)} keeps the outcome of every run. The proof is an invariant: at each point of a run, each live name that has a value is held by its register.
  • Spill everywhere. After line L17, mem.x holds the value of xx at each point after a definition of xx, so each load reads the right value.
  • Termination. Each round spills at least one name of the original program, and such a name never comes back, so there are at most n+1n + 1 rounds for nn names.
Proof: Chaitin's allocator gives a correct program with k registers and stopsfull

We prove six facts about CHAITIN-ALLOCATE. Lemmas 1 to 3 are about one round on a graph. Lemmas 4 and 5 show that renaming and spill code keep the outcome of every run. Lemma 6 shows that the loop stops.

Throughout, G=(V,E)G = (V, E) is a finite simple graph and k≥1k \ge 1. For U⊆VU \subseteq V, G[U]G[U] is the subgraph induced by UU, and G−v=G[V∖{v}]G - v = G[V \setminus \{v\}]. A kk-coloring is a map c:V→{0,…,k−1}c: V \to \{0, \ldots, k-1\} with c(x)≠c(y)c(x) \ne c(y) for every edge {x,y}\{x, y\}.

One round on the graph

Lemma 1 (simplify rule). If deg⁡G(v)<k\deg_G(v) < k, then GG has a kk-coloring if and only if G−vG - v has one.

Proof. If cc is a kk-coloring of GG, its restriction to V∖{v}V \setminus \{v\} is a kk-coloring of G−vG - v. Conversely, let c′c' be a kk-coloring of G−vG - v. The neighbors of vv use at most deg⁡G(v)<k\deg_G(v) < k colors, so some color j∈{0,…,k−1}j \in \{0, \ldots, k-1\} is used by no neighbor of vv. Set c(v)=jc(v) = j and c(x)=c′(x)c(x) = c'(x) for x≠vx \ne v. Each edge at vv joins vv to a neighbor of another color, and each other edge is an edge of G−vG - v, so cc is a kk-coloring of GG. □\square

Lemma 2 (select). If a round ends with an empty set spill, then line L15 gives each vertex a color in {0,…,k−1}\{0, \ldots, k-1\}, and the result is a kk-coloring of GG.

Proof. With no spill, every vertex was pushed at line L9. Let v1,…,vnv_1, \ldots, v_n be the push order and Gi=G[{vi,…,vn}]G_i = G[\{v_i, \ldots, v_n\}], the graph just before viv_i was removed. Line L8 gives deg⁡Gi(vi)<k\deg_{G_i}(v_i) < k. Line L14 visits vn,vn−1,…,v1v_n, v_{n-1}, \ldots, v_1. When it reaches viv_i, the colored vertices are exactly vi+1,…,vnv_{i+1}, \ldots, v_n, so the colored neighbors of viv_i are its neighbors in GiG_i. There are fewer than kk of them, so they use fewer than kk colors, and line L15 finds a color below kk. For an edge {vi,vj}\{v_i, v_j\} with i<ji < j, the vertex vjv_j is colored first, and line L15 gives viv_i a color different from c(vj)c(v_j). So no edge has two equal colors. □\square

Lemma 2 is the step-by-step form of Lemma 1: the vertices go back in the reverse order, and each one finds a free color.

The kk-core of GG is C=G[K]C = G[K], where KK is the union of all sets U⊆VU \subseteq V such that every vertex of G[U]G[U] has degree at least kk in G[U]G[U]. If every vertex of G[U1]G[U_1] and of G[U2]G[U_2] has degree at least kk, then so does every vertex of G[U1∪U2]G[U_1 \cup U_2], because adding vertices never lowers a degree. So CC itself has minimum degree at least kk when it is not empty, and it contains every induced subgraph with that property.

Lemma 3 (when a round spills). A round chooses a spill at line L12 if and only if the kk-core of GG is not empty.

Proof. Suppose K≠∅K \ne \emptyset. The loop of line L7 removes every vertex, so it removes some vertex of KK; let vv be the first one. When vv is removed, all of KK is still in the graph, so vv has degree at least deg⁡C(v)≥k\deg_C(v) \ge k. Line L8 does not apply to vv, and line L11 removes vv only if line L8 applies to no vertex at all. So vv is removed at line L12, and the round spills.

Suppose the round spills, and look at the first time line L12 runs. Let UU be the set of vertices still in the graph then. Line L8 did not apply, so every vertex of G[U]G[U] has degree at least kk in G[U]G[U], and U≠∅U \ne \emptyset. So U⊆KU \subseteq K and the kk-core is not empty. □\square

So a round colors GG with no spill exactly when GG has degeneracy less than kk: every nonempty induced subgraph has a vertex of degree less than kk. A kk-colorable graph with a nonempty kk-core, such as the cycle of length 4 for k=2k = 2, is spilled.

Renaming and spill code keep the outcome

A program here is a toy IR program with const, copy and op instructions. Its names are of two kinds: the memory slots, whose names start with mem., and the other names, which are the vertices of the interference graph. We assume that no run of the program reads a name before it writes it; the toy IR interpreter stops with an error otherwise. Line L1 makes this true for the parameters: it reads each live parameter from its slot at the start, and the new program has the slots as its parameters.

The outcome of a run is its return value, a trap, or no end. Two runs correspond when they visit the same blocks in the same order and run the same instructions there, apart from instructions that one of them adds or deletes as stated.

We use one fact about liveness. Let instruction ii define xx and read the names in use(i)\mathrm{use}(i). Then the names live just before ii are use(i)∪(out(i)∖{x})\mathrm{use}(i) \cup (\mathrm{out}(i) \setminus \{x\}), where out(i)\mathrm{out}(i) is the set live just after ii. At the end of a block BB, the names live before the terminator are liveout(B)\mathrm{liveout}(B) plus the name the terminator reads, and liveout(B)\mathrm{liveout}(B) contains the live-in set of each successor.

Lemma 4 (renaming). Let QQ be a program with interference graph GG, and let cc be a kk-coloring of GG. Let Q′Q' be QQ with each non-slot name xx renamed to rc(x)r_{c(x)} and each copy that becomes r = r deleted. Then for every input, QQ and Q′Q' have the same outcome.

Proof. Run QQ and Q′Q' on the same input. Write σ\sigma and σ′\sigma' for their stores. We show that the runs correspond, with Q′Q' skipping the deleted copies, and that this invariant holds at every point between two instructions:

(R) For each non-slot name xx that is live at the point and has been written on the run, σ′(rc(x))=σ(x)\sigma'(r_{c(x)}) = \sigma(x). For each slot mm, σ′(m)=σ(m)\sigma'(m) = \sigma(m).

At the start, no non-slot name has been written, and both programs got the same arguments in the same slots. So (R) holds.

Take an instruction ii that defines xx, with (R) true just before it. Each non-slot operand aa is in use(i)\mathrm{use}(i), so it is live just before ii, and it has been written by our assumption. By (R), the register of aa in Q′Q' holds σ(a)\sigma(a), and slot operands agree too. So both programs compute the same value ww, or both trap on the same operands. After the step, σ(x)=w\sigma(x) = w. We check (R) just after ii.

  • If xx is a slot (a store), Q′Q' writes ww to the same slot, and no register changes.
  • If ii is a deleted copy x = a with c(x)=c(a)c(x) = c(a), the register rc(x)r_{c(x)} already holds σ(a)=w\sigma(a) = w.
  • Otherwise Q′Q' writes ww to rc(x)r_{c(x)}, so the claim holds for xx.

Now let y≠xy \ne x be a non-slot name in out(i)\mathrm{out}(i) that has been written. Then yy was live just before ii and σ(y)\sigma(y) did not change, so before the step σ′(rc(y))=σ(y)\sigma'(r_{c(y)}) = \sigma(y). If c(y)≠c(x)c(y) \ne c(x), the step did not touch rc(y)r_{c(y)}. If c(y)=c(x)c(y) = c(x), then {x,y}\{x, y\} is not an edge of GG. Since y∈out(i)y \in \mathrm{out}(i) and y≠xy \ne x, the definition rule of the interference graph adds this edge unless ii is the copy x = y. So ii is that copy, and the value written to rc(x)=rc(y)r_{c(x)} = r_{c(y)} is σ(y)\sigma(y) itself. In each case σ′(rc(y))=σ(y)\sigma'(r_{c(y)}) = \sigma(y) after the step.

A terminator reads a name that is live before it, so by (R) both programs take the same branch or return the same value. The names live at the start of the next block are live before the terminator, so (R) holds there. By induction over the steps of the run, the runs correspond, and they end in the same way: with the same return value, with the same trap, or not at all. □\square

Lemma 5 (spill everywhere). Let SS be a set of non-slot names of QQ, and let Q2Q_2 be the result of line L17: for each x∈Sx \in S, each instruction that reads xx is preceded by a load t = mem.x into a new name tt and reads tt instead, and each instruction that defines xx defines a new name tt instead and is followed by the store mem.x = t. Then QQ and Q2Q_2 have the same outcome on every input, and Q2Q_2 reads no name before it writes it.

Proof. The new names appear nowhere else, so the other names keep their meaning. For x∈Sx \in S, QQ never writes mem.x itself: a slot of a non-slot name is written only by a store added when that name is spilled, and a spilled name no longer occurs in the program. QQ may read mem.x only in the entry block, when xx is a parameter loaded there. We show that the runs correspond, Q2Q_2 running the added loads and stores, with this invariant at the points of QQ:

(S) For each non-slot name y∉Sy \notin S written so far, σ2(y)=σ(y)\sigma_2(y) = \sigma(y). For each x∈Sx \in S written so far, σ2(mem.x)=σ(x)\sigma_2(\mathtt{mem.}x) = \sigma(x). Each slot that no added store has written so far has the same value in both runs.

It holds at the start. Take an instruction ii of QQ. For each operand x∈Sx \in S, the name xx was written before ii on this run, so the added load reads σ2(mem.x)=σ(x)\sigma_2(\mathtt{mem.}x) = \sigma(x). The other operands agree by (S). So Q2Q_2 computes the same value ww, or traps in the same way. If ii defines y∉Sy \notin S, then σ2(y)=w\sigma_2(y) = w. If ii defines x∈Sx \in S, the new name gets ww and the store sets mem.x\mathtt{mem.}x to w=σ(x)w = \sigma(x). Terminators are handled in the same way. Each new name is written just before its only read, so Q2Q_2 reads nothing before it writes it. □\square

By Lemmas 4 and 5, every program that CHAITIN-ALLOCATE returns has the outcome of the program after line L1, and line L1 keeps the outcome because it only moves the parameters through their slots. The returned program uses only the registers r0,…,rk−1r_0, \ldots, r_{k-1} by Lemma 2.

Termination

Call the non-slot names of the program after line L1 the original names, and the names made by line L17 the temporaries.

The only loads that write original names are the parameter loads of the entry block made by line L1. The instructions of that block read only slots and, after a parameter is spilled, the store temporary of that parameter. By (O) below for the earlier rounds, temporaries are never spilled, so line L17 never adds a load in that block.

We prove three statements together, by induction on the rounds.

  • (T) Shape. Each temporary tt is written once and read once. Either tt is a load temporary: its write is a load, and its read is the first instruction after the write that is not a load. Or tt is a store temporary: its read is the store just after its write.
  • (U) Few temporary edges. In the interference graph of the round, each temporary has at most one neighbor that is a temporary.
  • (O) Original spills. Each time line L11 runs, it chooses an original name.

(T) holds in round 1, which has no temporary, and it carries over from a round to the next if (O) holds in that round. Line L17 creates temporaries of the two shapes. By (O) it spills only original names. It adds loads just before an instruction jj that reads a spilled name; jj is not a store of a temporary, which reads only a temporary, and not a load, which reads only a slot. If jj is the reader of an old load temporary, only loads now lie between that temporary's write and jj, so its shape holds. Line L17 adds stores just after an instruction that writes a spilled original name; that instruction is not the write of an old temporary, so no old store temporary is separated from its store.

(T) implies (U) in the same round. An edge between temporaries tt and uu needs, say, uu live just after the write of tt. If uu is a store temporary, it is live only just after its own write, so t=ut = u, which is not an edge. If uu is a load temporary, it is live from just after its load to its reader jj, and dead after jj. The writes inside that stretch are loads, and none of them is in the entry block. So tt is a load temporary whose first following instruction that is not a load is also jj: tt and uu have the same reader. An instruction reads at most two names, and each spilled name read by it gets one load, so at most two load temporaries share a reader. So each temporary has at most one temporary neighbor.

(U) implies (O) in the same round. When line L11 runs, every vertex left has degree at least k≥2k \ge 2 in the current graph. If all of them were temporaries, the current graph would be induced by temporaries, and by (U) each of its vertices would have degree at most 1. So some original name is left. Its cost is finite and its degree is positive, so its ratio is finite, while every temporary has ratio infinity. So line L11 chooses an original name.

Lemma 6 (termination). Let n0n_0 be the number of original names. CHAITIN-ALLOCATE with k≥2k \ge 2 returns after at most n0+1n_0 + 1 rounds.

Proof. By (O), each round that spills spills at least one original name, because line L12 runs only after line L11. Line L17 replaces every occurrence of a spilled name by temporaries, and later rounds create only temporaries, so a spilled original name never appears again and is never spilled again. There are n0n_0 original names, so at most n0n_0 rounds spill, and the next round returns. □\square

Together, Lemmas 2, 4, 5 and 6 prove that CHAITIN-ALLOCATE stops and returns a program that uses only kk registers and has the same outcome as its input on every input. Lemma 3 tells exactly when a round spills.

Complexity

One round has three parts:

  • Build. Liveness costs ll. The walk over the instructions adds one edge per name live after each definition, so it takes O(sn)O(s n) time, and the graph takes O(n+m)O(n + m) space as adjacency sets.
  • Simplify. With a queue, each removal at line L9 updates the degrees of the neighbors, so all removals cost O(n+m)O(n + m). A spill choice at line L11 scans the vertices left, O(n)O(n) each, so at most O(n2)O(n^2) in a round. A heap keyed by cost over degree gives O((n+m)log⁡n)O((n + m) \log n) instead.
  • Select. Each vertex scans its neighbors once: O(n+m)O(n + m).

Each round spills at least one original name, so r≤n+1r \le n + 1, and the total is O(r(l+sn+n2))O(r (l + s n + n^2)). Over all rounds, the spill code adds one load or store per occurrence of an original name, and temporaries are never spilled, so the program keeps O(s)O(s) instructions. The example above needed 4 rounds for 6 names.

Properties

  • Guarantee. If the kk-core of the interference graph is empty, the allocator colors it with at most kk colors and adds no spill code. Such a graph has degeneracy at most k−1k - 1, and in the simplify order each vertex has fewer than kk neighbors that come later, as in a degeneracy ordering.
  • No optimality. It may spill when a kk-coloring exists (the cycle of length 4 with k=2k = 2), and when it spills, the amount of spill code can be far from the least (the example above). The problem it attacks is NP-complete for k≥3k \ge 3, so no polynomial-time allocator is exact unless P = NP.
  • Deterministic. The result depends on the order of the names and the tie-breaking rule.
  • Copies. The allocator does not coalesce. A copy x = y is deleted only when xx and yy get the same color by chance.

Variants and improvements

  • Optimistic coloring (Briggs, Cooper and Torczon) pushes the spill choice of line L11 on the stack like any other vertex and spills it only if line L15 finds no free color. It spills a subset of what Chaitin's allocator spills.
  • Iterated register coalescing (George and Appel) adds conservative coalescing of copies to the simplify loop.
  • Better spill code. Spill code placement loads a value once for several close uses, live range splitting spills a name only where the pressure is high, and rematerialization recomputes a constant instead of loading it.
  • Spill cost. A real allocator weights each definition and use by an estimate of how often its block runs, so that names used in loops are spilled last. Other ratios than cost over degree are used too.
  • Precolored vertices. Machine registers fixed by calling conventions are vertices with a fixed color that are never removed or spilled.

When to use it

Use it in an optimizing compiler that can afford to build the interference graph, when the target has a fixed set of uniform registers. It is the basis of most graph-coloring allocators, but production compilers use the optimistic form, usually with coalescing. For a JIT compiler or for huge functions, linear scan is cheaper. On SSA form, SSA-based allocation colors optimally once the pressure is at most kk.

Pitfalls

  • A copy is not an interference. Adding an edge between x and y at x = y blocks coalescing and wastes a register. The rule skips the copy source.
  • A dead definition still writes a register. The definition must interfere with the names live after it, or the write can destroy a live value.
  • Rebuild after spilling. Spill code changes liveness. In the example, spilling cc left its reload c.2 in the same triangle. Coloring the old graph minus the spilled names is wrong.
  • Spill temporaries must not be spilled. A temporary of spill everywhere has the shortest possible life; spilling it again creates new temporaries with the same life and the loop never ends. The infinite cost of line L5 prevents this.
  • k≥2k \ge 2. An instruction such as x = a + b with both operands spilled reads two temporaries at once, so one register is not enough in this model.
  • Parameters. A parameter live on entry needs a definition, or it interferes with nothing and may share a register with another live parameter. Line L1 adds the loads that define them.

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.

chaitin_register_allocation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chaitin-register-allocation/. The authors are listed in prov/D7BWHP.jsonl.
"""Chaitin's graph coloring register allocator.

chaitin_color(adj, k, cost) works on a graph: adj maps each node to the set
of its neighbors. It returns (color, spilled). When spilled is empty, color
maps every node to a color in 0 .. k-1 and no edge has two equal colors.
Otherwise color is empty and spilled is the set of nodes that the simplify
phase chose to spill.

allocate(prog, k) works on a toy IR program with const, copy and op
instructions only (no phi). It builds the interference graph, colors it,
spills the chosen names everywhere and repeats. It returns
(out, rounds, spilled): out runs like prog, its register names are
r0 .. r(k-1), and its memory slots have names that start with "mem.".
The parameters of out are the memory slots of the parameters of prog.
"""

from collections import deque
import math

import toyir

MEM = "mem."


def is_mem(name):
    return isinstance(name, str) and name.startswith(MEM)


# ------------------------------------------------------------- graph level


def simplify(adj, k, cost):
    """The simplify phase. Returns the stack as a list of (node, chosen),
    in the order of removal; chosen is True for a spill choice."""
    order = list(adj)
    index = {v: i for i, v in enumerate(order)}
    deg = {v: len(adj[v]) for v in order}
    removed = set()
    low = deque(v for v in order if deg[v] < k)
    queued = set(low)
    stack = []  # @line L6
    while len(stack) < len(order):  # @line L7
        if low:  # @line L8
            v, chosen = low.popleft(), False  # @line L9
        else:  # @line L10
            # Every node left has degree >= k: choose the cheapest per edge.
            v = min((u for u in order if u not in removed), key=lambda u: (cost[u] / deg[u], index[u]))  # @line L11
            chosen = True  # @line L12
        removed.add(v)
        stack.append((v, chosen))
        for w in sorted(adj[v], key=index.__getitem__):
            if w not in removed:
                deg[w] -= 1
                if deg[w] < k and w not in queued:
                    queued.add(w)
                    low.append(w)
    return stack


def chaitin_color(adj, k, cost=None):
    if k < 1:
        raise ValueError("k must be at least 1")
    if cost is None:
        cost = {v: 1 for v in adj}
    stack = simplify(adj, k, cost)
    spilled = {v for v, chosen in stack if chosen}
    if spilled:  # @line L13
        return {}, spilled
    color = {}
    for v, _ in reversed(stack):  # @line L14
        used = {color[w] for w in adj[v] if w in color}
        c = 0
        while c in used:
            c += 1
        color[v] = c  # @line L15 (c < k: v had fewer than k neighbors left when it was removed)
    return color, set()


# ----------------------------------------------------------- program level


def _check(prog):
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("only const, copy and op instructions: %r" % (ins,))


def liveness(prog):
    """live_in and live_out of each block, by the backward fixed point."""
    use, kill = {}, {}
    for label, b in prog.blocks.items():
        u, d = set(), set()
        for ins in b.instrs:
            u.update(a for a in toyir.uses(ins) if a not in d)
            d.add(ins[1])
        u.update(a for a in toyir.term_uses(b.term) if a not in d)
        use[label], kill[label] = u, d
    live_in = {label: set() for label in prog.blocks}
    live_out = {label: set() for label in prog.blocks}
    changed = True
    while changed:
        changed = False
        for label in reversed(list(prog.blocks)):
            out = set()
            for s in toyir.succs(prog, label):
                out |= live_in[s]
            new_in = use[label] | (out - kill[label])
            if out != live_out[label] or new_in != live_in[label]:
                live_out[label], live_in[label] = out, new_in
                changed = True
    return live_in, live_out


def interference(prog):
    """The interference graph of the names that are not memory slots, and
    the list of copies (x, y) for x = y between two such names. At each
    definition of x, x interferes with each name live after it, except the
    source of a copy x = y."""
    _check(prog)
    _, live_out = liveness(prog)
    adj = {}
    moves = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in [ins[1]] + toyir.uses(ins):
                if not is_mem(a):
                    adj.setdefault(a, set())
        for a in toyir.term_uses(b.term):
            if not is_mem(a):
                adj.setdefault(a, set())
    for label, b in prog.blocks.items():
        live = set(live_out[label]) | set(toyir.term_uses(b.term))
        for ins in reversed(b.instrs):
            x = ins[1]
            src = ins[2] if ins[0] == "copy" and isinstance(ins[2], str) else None
            if not is_mem(x):
                for y in live:
                    if y != x and y != src and not is_mem(y):
                        adj[x].add(y)
                        adj[y].add(x)
                if src is not None and src != x and not is_mem(src):
                    moves.append((x, src))
            live.discard(x)
            live.update(toyir.uses(ins))
    return adj, moves


def spill_costs(prog, infinite=()):
    """The number of definitions and uses of each name; a name in infinite
    (a spill temporary) gets an infinite cost, so it is never chosen."""
    cost = {}
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in [ins[1]] + toyir.uses(ins):
                cost[a] = cost.get(a, 0) + 1
        for a in toyir.term_uses(b.term):
            cost[a] = cost.get(a, 0) + 1
    for a in infinite:
        cost[a] = math.inf
    return cost


def _names(prog):
    out = set(prog.params)
    for b in prog.blocks.values():
        for ins in b.instrs:
            out.add(ins[1])
            out.update(toyir.uses(ins))
        out.update(toyir.term_uses(b.term))
    return out


def _sub(a, m):
    return m.get(a, a) if isinstance(a, str) else a


def spill_everywhere(prog, spilled):
    """Keep each name x of spilled in the memory slot mem.x. Each use reads a
    new temporary loaded just before it; each definition writes a new
    temporary stored just after it. Returns (program, temporaries)."""
    taken = _names(prog)
    temps = set()
    count = [0]

    def temp(x):
        while True:
            count[0] += 1
            t = "%s.%d" % (x, count[0])
            if t not in taken:
                taken.add(t)
                temps.add(t)
                return t

    blocks = {}
    for label, b in prog.blocks.items():
        out = []
        for ins in b.instrs:
            loads = {}
            for a in toyir.uses(ins):
                if a in spilled and a not in loads:
                    loads[a] = temp(a)
                    out.append(("copy", loads[a], MEM + a))
            if ins[0] == "copy":
                ins = ("copy", ins[1], _sub(ins[2], loads))
            elif ins[0] == "op":
                ins = ("op", ins[1], ins[2], _sub(ins[3], loads), _sub(ins[4], loads))
            x = ins[1]
            if x in spilled:
                t = temp(x)
                out.append((ins[0], t) + ins[2:])
                out.append(("copy", MEM + x, t))
            else:
                out.append(ins)
        term = b.term
        if term[0] in ("br", "ret") and term[1] in spilled:
            t = temp(term[1])
            out.append(("copy", t, MEM + term[1]))
            term = (term[0], t) + term[2:]
        blocks[label] = toyir.Block(out, term)
    return toyir.Program(list(prog.params), blocks), temps


def prepare(prog):
    """A copy of prog whose arguments arrive in memory slots. A new entry
    block loads each parameter that is live on entry, then jumps to the old
    entry."""
    _check(prog)
    if any(is_mem(a) for a in _names(prog)):
        raise ValueError("names that start with %r are reserved" % MEM)
    live_in, _ = liveness(prog)
    label = "start"
    while label in prog.blocks:
        label += "_"
    pro = [("copy", p, MEM + p) for p in prog.params if p in live_in[prog.entry]]
    blocks = {label: toyir.Block(pro, ("jump", prog.entry))}
    for lab, b in prog.blocks.items():
        blocks[lab] = toyir.Block(list(b.instrs), b.term)
    return toyir.Program([MEM + p for p in prog.params], blocks)


def assign(prog, color):
    """Rename each name to its register; drop copies that become r = r."""

    def reg(a):
        if not isinstance(a, str) or is_mem(a):
            return a
        return "r%d" % color[a]

    blocks = {}
    for label, b in prog.blocks.items():
        out = []
        for ins in b.instrs:
            if ins[0] == "const":
                out.append(("const", reg(ins[1]), ins[2]))
            elif ins[0] == "copy":
                x, a = reg(ins[1]), reg(ins[2])
                if x != a:
                    out.append(("copy", x, a))
            else:
                out.append(("op", reg(ins[1]), ins[2], reg(ins[3]), reg(ins[4])))
        term = b.term
        if term[0] in ("br", "ret"):
            term = (term[0], reg(term[1])) + term[2:]
        blocks[label] = toyir.Block(out, term)
    return toyir.Program(list(prog.params), blocks)


def allocate(prog, k):
    """Build, simplify, spill and repeat until the graph is k-colorable by
    simplify alone. Each round spills at least one name that is not a spill
    temporary, so the number of rounds is at most the number of names + 1."""
    if k < 2:
        raise ValueError("k must be at least 2: one instruction can read two spilled names")
    work = prepare(prog)  # @line L1
    infinite = set()  # @line L2
    spilled_all = []
    rounds = 0
    while True:  # @line L3
        rounds += 1
        adj, _ = interference(work)  # @line L4
        cost = spill_costs(work, infinite)  # @line L5
        color, spilled = chaitin_color(adj, k, cost)
        if not spilled:
            return assign(work, color), rounds, spilled_all  # @line L16
        work, temps = spill_everywhere(work, spilled)  # @line L17
        infinite |= temps  # @line L18
        spilled_all.extend(sorted(spilled))
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_chaitin_register_allocation.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chaitin-register-allocation/. The authors are listed in prov/D7BWHP.jsonl.

import itertools
import random

import toyir
from chaitin_register_allocation import allocate, chaitin_color, interference, is_mem


def graph(n, edges):
    adj = {v: set() for v in range(n)}
    for a, b in edges:
        adj[a].add(b)
        adj[b].add(a)
    return adj


def k_colorable(adj, k):
    """Exhaustive search: True when some map to 0 .. k-1 has no equal edge."""
    nodes = sorted(adj, key=lambda v: -len(adj[v]))
    color = {}

    def go(i):
        if i == len(nodes):
            return True
        v = nodes[i]
        used = {color[w] for w in adj[v] if w in color}
        for c in range(k):
            if c not in used:
                color[v] = c
                if go(i + 1):
                    return True
                del color[v]
        return False

    return go(0)


def k_core(adj, k):
    """Delete nodes of degree < k until none is left; what stays is the k-core."""
    left = set(adj)
    changed = True
    while changed:
        changed = False
        for v in sorted(left):
            if len(adj[v] & left) < k:
                left.discard(v)
                changed = True
    return left


def check(adj, k):
    color, spilled = chaitin_color(adj, k)
    if spilled:
        assert color == {}
    else:
        assert set(color) == set(adj)
        assert all(0 <= c < k for c in color.values())
        assert all(color[a] != color[b] for a in adj for b in adj[a])
    # Chaitin spills exactly when the k-core is not empty.
    assert bool(spilled) == bool(k_core(adj, k))
    # A graph that simplify colors is k-colorable; the converse fails.
    if not spilled:
        assert k_colorable(adj, k)
    return bool(spilled)


def test_every_graph_up_to_5_nodes():
    missed = 0
    for n in range(1, 6):
        pairs = list(itertools.combinations(range(n), 2))
        for mask in range(1 << len(pairs)):
            adj = graph(n, [p for i, p in enumerate(pairs) if mask >> i & 1])
            for k in (1, 2, 3):
                if check(adj, k) and k_colorable(adj, k):
                    missed += 1
    assert missed > 0


def test_random_graphs_up_to_10_nodes():
    rng = random.Random(1981)
    for _ in range(400):
        n = rng.randint(6, 10)
        p = rng.choice((0.2, 0.35, 0.5))
        adj = graph(n, [e for e in itertools.combinations(range(n), 2) if rng.random() < p])
        for k in (2, 3, 4):
            check(adj, k)


def test_cycle_of_four_spills_with_two_colors():
    c4 = graph(4, [(0, 1), (1, 2), (2, 3), (3, 0)])
    color, spilled = chaitin_color(c4, 2)
    assert spilled and k_colorable(c4, 2)
    color, spilled = chaitin_color(c4, 3)
    assert not spilled and len(set(color.values())) == 2


def test_spill_choice_uses_cost_per_degree():
    # K4 with k = 3: node 3 is the cheapest per edge.
    k4 = graph(4, list(itertools.combinations(range(4), 2)))
    _, spilled = chaitin_color(k4, 3, {0: 9, 1: 9, 2: 9, 3: 2})
    assert spilled == {3}


def test_copy_does_not_interfere():
    prog = toyir.parse("# params: a\nL:\n  b = a\n  c = a + b\n  ret c\n")
    adj, moves = interference(prog)
    assert "b" not in adj["a"]
    assert moves == [("b", "a")]


def test_dead_definition_interferes():
    prog = toyir.parse("# params: a\nL:\n  d = 5\n  ret a\n")
    adj, _ = interference(prog)
    assert adj["d"] == {"a"}


PAGE = """
# params: p
L0:
  a = p + 1
  b = p + 2
  c = a + b
  d = a * c
  e = b * d
  ret e
"""


def test_page_example():
    prog = toyir.parse(PAGE)
    adj, _ = interference(prog)
    assert adj == {
        "p": {"a"},
        "a": {"p", "b", "c"},
        "b": {"a", "c", "d"},
        "c": {"a", "b"},
        "d": {"b"},
        "e": set(),
    }
    out, rounds, spilled = allocate(prog, 3)
    assert rounds == 1 and spilled == []
    out, rounds, spilled = allocate(prog, 2)
    # Spilling c does not break the triangle: the reload of c still meets a and b.
    assert rounds == 4 and spilled == ["c", "a", "b"]
    for p in range(-3, 4):
        assert toyir.run(out, [p]) == toyir.run(prog, [p])


def registers(prog):
    names = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            names.add(ins[1])
            names.update(toyir.uses(ins))
        names.update(toyir.term_uses(b.term))
    return {a for a in names if not is_mem(a)}


def test_random_programs_keep_their_outcome():
    rng = random.Random(82)
    for trial in range(150):
        prog = toyir.random_program(rng, rng.randint(2, 7), rng.randint(1, 6), trial % 2 == 0)
        for k in (2, 3, 4, 5):
            out, rounds, spilled = allocate(prog, k)
            assert registers(out) <= {"r%d" % i for i in range(k)}
            for _ in range(4):
                args = [rng.randint(-4, 6), rng.randint(-4, 6)]
                assert toyir.run(out, args, fuel=100000) == toyir.run(prog, args, fuel=100000)

History

Chaitin, Auslander, Chandra, Cocke, Hopkins and Markstein (1981) made graph coloring work for global register allocation in the PL.8 compiler at IBM. The same paper showed that every graph is an interference graph, so exact coloring is NP-complete. Chaitin (1982) described the simplify rule, the cost over degree heuristic and the build-simplify-spill loop that this page follows. Briggs, Cooper, Kennedy and Torczon (1989) and Briggs, Cooper and Torczon (1994) made the coloring optimistic, and George and Appel (1996) added iterated coalescing.

References

  1. Gregory J. Chaitin, Marc A. Auslander, Ashok K. Chandra, John Cocke, Martin E. Hopkins and Peter W. Markstein, Register allocation via coloring, Computer Languages 6(1), 1981, 47-57, global allocation as coloring of the interference graph, the build and color phases, and spilling with a rebuild of the graph
  2. Gregory J. Chaitin, Register allocation and spilling via graph coloring, Proceedings of the SIGPLAN '82 Symposium on Compiler Construction, SIGPLAN Notices 17(6), 1982, 98-105, the simplify rule (a node of degree less than k can always be colored last), the choice of a spill by cost divided by degree, and the loop of build, simplify, spill
  3. Preston Briggs, Keith D. Cooper and Linda Torczon, Improvements to graph coloring register allocation, ACM Transactions on Programming Languages and Systems 16(3), 1994, 428-455, the description of Chaitin's allocator as the baseline, and the example graphs that are k-colorable but that Chaitin's allocator spills
  4. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation), coloring by simplification, and spilling
  5. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 13 (Register Allocation), global allocation by graph coloring, the top-down and bottom-up coloring schemes, and spill costs
  6. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 16 (Register Allocation), graph coloring with webs, spill costs and the pruning of the graph by degree

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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