Algorithm Search⌘K

Algorithmresearch

SSA-based register allocation

Also called decoupled register allocation.

Spills until register pressure is at most k everywhere, then colors the chordal SSA interference graph with no further spills.

Time
O(l + s n^2 + b^2) worst
Space
O(s n) extra
Where
b = the number of blocks; l = the time of one liveness analysis; n = the number of names; s = the number of nodes
Properties
deterministicofflineiterative
Origin
Sebastian Hack, Daniel Grund, Gerhard Goos, 2006

SSA-based register allocation gives registers to the names of a program while it is still in static single assignment form. It works in two separate phases. The spill phase keeps names in memory until, at every point, at most kk names that are not spilled hold a value. The coloring phase then walks the blocks in the order of the dominator tree and gives each definition a free register, and it never fails, because the SSA chordal interference theorem says that the register pressure is the number of colors needed. Only after that are the phis replaced by copies. This split is why it is also called decoupled register allocation. In Chaitin's allocator, spilling and coloring must loop, because a graph can need more colors than its pressure.

In plain words

First decide which values will live in memory. Count, at every instruction, how many values must be held at once. Where the count is above the number of registers, pick a value that is cheap to keep in memory and move it out of the count. Repeat until every count fits. Then visit the code from the top, so that each value is seen where it is made before any place where it is used. Give each new value the lowest register that no live value holds. The first step promised that one is free. Last, where two paths join and a value takes different names on the two paths, add copies at the end of each path. If two values must swap registers, use a spare register.

The problem

The input is a program PP in the toy IR in strict SSA form, with const, copy, op and phi instructions, and a number k≥1k \ge 1 of registers. Strict means that each name has one definition and that the definition dominates every use. A phi operand from the predecessor QQ counts as used at the end of QQ. The output is a program with no phi that uses only the registers r0,…,rk−1r_0, \ldots, r_{k-1}, two scratch registers s0s_0 and s1s_1 kept apart for spill code and copies, and memory slots mem.x, and that has the same outcome as PP on every input.

A node is the group of all phis of one block, one other instruction, or one terminator. For a node vv, D(v)D(v) is the set of names that vv defines and O(v)O(v) is the set of names live just after vv. The register pressure at vv is ∣D(v)∪O(v)∣|D(v) \cup O(v)|, without the spilled names. MaxLive is the largest pressure when nothing is spilled.

The algorithm

  1. SSA-ALLOCATE(P, k)
  2. 1P <- P with a start block that loads the parameters, and with each edge into a block with phis split when its source ends in br
  3. 2compute liveness; for each node v (a phi group, an instruction or a terminator) let D(v) be its definitions and O(v) its live-out set
  4. 3spilled <- empty
  5. 4while some node v has more than k names of D(v) ∪ O(v) not in spilled do
  6. 5x <- the name of D(v) ∪ O(v) not in spilled with the least cost
  7. 6spilled <- spilled + {x}
  8. 7for each block B in preorder of the dominator tree do
  9. 8for each node v of B in order do
  10. 9busy <- the colors of the names of O(v) \ D(v) not in spilled
  11. 10for each name y of D(v) not in spilled do
  12. 11color[y] <- the color of a copy or phi partner of y if it is not busy, else the lowest color not busy
  13. 12busy <- busy + {color[y]}
  14. 13for each edge (Q, B) with B having phis do
  15. 14put at the end of Q the parallel copy loc(y) <- loc(a) for each phi y = phi[..., Q: a, ...] of B
  16. 15sequentialize it, breaking cycles with s0 and moving memory to memory through s1
  17. 16return P without phis, names replaced by registers or slots, loads into s0/s1 before uses of spilled names and stores after their definitions

Here loc(x)\mathrm{loc}(x) is rcr_c for a kept name of color cc and mem.x for a spilled name. The cost at line L5 is the number of definitions and uses of the name, phi operands included. Ties go to the name that is in the most nodes with too much pressure, then to the name order. A partner at line L11 is the source of a copy y = a or an operand of a phi y. Choosing a partner's color when it is free makes the copy or the phi move vanish, a cheap form of coalescing.

Line L1 needs a word. The parallel copy for an edge (Q,B)(Q, B) goes at the end of QQ. If QQ ends in br, the copy would also run on the other edge, so line L1 puts an empty block on such an edge, the usual critical edge splitting. The start block gives each parameter a definition, which keeps the program strict.

The spill rule here is a simple heuristic, chosen so the code is short. Real compilers use the spiller of Braun and Hack, which applies the furthest next use rule of Belady along each block and splits live ranges instead of spilling whole names, and they replace the partner bias with the recoloring of Hack and Goos.

Example

The program sums the squares 02+12+⋯+(n−1)20^2 + 1^2 + \cdots + (n-1)^2:

entry:
  i0 = 0
  a0 = 0
  jump head
head:
  i1 = phi [entry: i0, body: i2]
  a1 = phi [entry: a0, body: a2]
  t = i1 < n
  br t body done
body:
  u = i1 * i1
  a2 = a1 + u
  i2 = i1 + 1
  jump head
done:
  ret a1

Line L1 adds start: n = mem.n; jump entry. No edge needs a split block: the two edges into head come from entry and body, which end in jump. The nodes, with their pressure, are:

block node D(v)D(v) O(v)O(v) pressure
start n = mem.n nn nn 1
entry i0 = 0 i0i_0 i0,ni_0, n 2
entry a0 = 0 a0a_0 a0,i0,na_0, i_0, n 3
head phis i1,a1i_1, a_1 a1,i1,na_1, i_1, n 3
head t = i1 < n tt a1,i1,n,ta_1, i_1, n, t 4
body u = i1 * i1 uu a1,i1,n,ua_1, i_1, n, u 4
body a2 = a1 + u a2a_2 a2,i1,na_2, i_1, n 3
body i2 = i1 + 1 i2i_2 a2,i2,na_2, i_2, n 3

The terminators define nothing and have at most 3 names live after them. So MaxLive is 4.

With k=4k = 4. Nothing is spilled. The dominator tree has start, entry and head in a chain, with body and done below head. The coloring goes:

node busy color
n = mem.n none n→0n \to 0
i0 = 0 0 i0→1i_0 \to 1
a0 = 0 0, 1 a0→2a_0 \to 2
phis of head 0 i1→1i_1 \to 1 (partner i0i_0), a1→2a_1 \to 2 (partner a0a_0)
t = i1 < n 0, 1, 2 t→3t \to 3
u = i1 * i1 0, 1, 2 u→3u \to 3
a2 = a1 + u 0, 1 a2→2a_2 \to 2
i2 = i1 + 1 0, 2 i2→1i_2 \to 1

Four colors, exactly MaxLive. Each phi has the color of both of its operands: for i1i_1 and a1a_1 by the partner rule, for a2a_2 and i2i_2 because the lowest free color happens to match. So every parallel copy is empty and the output has no move at all except the load of the parameter:

start:
  r0 = mem.n
  jump entry
entry:
  r1 = 0
  r2 = 0
  jump head
head:
  r3 = r1 < r0
  br r3 body done
body:
  r3 = r1 * r1
  r2 = r2 + r3
  r1 = r1 + 1
  jump head
done:
  ret r2

With k=3k = 3. The nodes of tt and uu have pressure 4. Line L5 looks at the first, {a1,i1,n,t}\{a_1, i_1, n, t\}. The costs are a1a_1: 3, i1i_1: 5, nn: 2 and tt: 2, and nn wins the tie with tt because it is in both nodes with too much pressure. After that every pressure is at most 3, and head becomes s0 = mem.n; r2 = r0 < s0; br r2 body done. The loop reloads nn once per round, and the other names keep a register each, now r0r_0 to r2r_2.

With k=2k = 2. The rule spills nn, then tt, then uu. The output stores tt and uu and loads them back at once, which is the price of spilling whole names: a spiller that splits live ranges would keep tt and uu in a register for their one instruction. All three outputs return 0, 0, 1, 5, 14, 30 for n=0,…,5n = 0, \ldots, 5, the same as the input.

Correctness

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

  • Spilling. Each round of lines L4 to L6 adds one name, so the loop stops after at most nn rounds, and then no node has more than kk kept names in D(v)∪O(v)D(v) \cup O(v).
  • Coloring. In a strict SSA program the definition of a live name dominates the point where it is live. So when line L9 runs at vv, every kept name of O(v)∖D(v)O(v) \setminus D(v) is already colored, because its definition is earlier in the block or in a dominating block. busy then has at most k−1k - 1 colors, so line L11 finds a color below kk. Two names that interfere meet at the definition of one of them, where the other is in busy, so they get different colors.
  • Optimal without spills. If k≥k \ge MaxLive, nothing is spilled and the same bound gives at most MaxLive colors. The names of D(v)∪O(v)D(v) \cup O(v) at a node of largest pressure all interfere, so no allocation uses fewer. This is the chordal theorem in action: the greedy order is the reverse of a perfect elimination ordering.
  • Parallel copies. The destinations of one copy are distinct, since the phis of one block form one node. Moving a value whose destination no other move reads, and saving one destination in s0s_0 when only cycles are left, gives the effect of the parallel copy.
  • Same outcome. Along a run, each live name holds its value in its register or slot. A definition writes a register that no other live name holds, and the parallel copy at the end of a predecessor writes only the locations of the phis.

The number of spills is not minimal when kk is below MaxLive. Bouchez, Darte and Rastello showed that the spill problem stays NP-complete in SSA form, so some heuristic is needed there.

Proof: SSA-based allocation gives a correct program and uses exactly MaxLive registers when nothing is spilledfull

We prove five facts about SSA-ALLOCATE. Lemma 1 is about the spill phase: it stops, and after it each node has at most kk names that are not spilled. Lemma 2 shows that the coloring phase gives two interfering names different colors, all below kk. Lemma 3 shows that, with no spill, the number of colors is exactly MaxLive, the least possible. Lemma 4 shows that the sequential form of a parallel copy does what the parallel copy does. Lemma 5 shows that the output has the same outcome as the input.

Setup

The input PP is a program in strict SSA form: each name has one definition, and each use of a name is dominated by its definition. A phi operand from the predecessor QQ counts as a use at the end of QQ. Line L1 makes the program WW. It adds a block start, the new entry, that copies each parameter pp live at the old entry from its slot mem.p, and it puts a new empty block on each edge from a block that ends in br to a block with phis. Both changes keep the outcome and keep strict SSA form: the copies of the parameters are the only definitions of those names and they dominate every block, and an empty block on an edge only moves the end of the predecessor.

A node is the group of all phis of one block, one other instruction, or one terminator. The nodes of a block come in the order phi group, instructions, terminator. For a node vv, D(v)D(v) is the set of names it defines and O(v)O(v) is the set of names live just after it. Liveness counts a phi operand as read by the terminator of its predecessor, so O(t)O(t) for the terminator tt of a block QQ is the live-out set of QQ, phi operands included. Two names x≠yx \ne y interfere when some node vv has x∈D(v)x \in D(v) and y∈D(v)∪O(v)y \in D(v) \cup O(v). For a set SS of spilled names, the pressure of vv is ∣(D(v)∪O(v))∖S∣|(D(v) \cup O(v)) \setminus S|, and MaxLive is the largest pressure with SS empty.

We use one fact from the SSA chordal interference theorem: in a strict SSA program, the definition of a name zz dominates every point where zz is live. So if z∈O(v)∖D(v)z \in O(v) \setminus D(v), then the node that defines zz comes before vv in its block, or lies in a block that strictly dominates the block of vv.

The spill phase

Lemma 1. Lines L3 to L6 stop after at most nn rounds, where nn is the number of names. When they stop, each node has pressure at most kk for the set spilled.

Proof. Each round runs only if some node vv has pressure above kk. Then (D(v)∪O(v))∖spilled(D(v) \cup O(v)) \setminus \mathit{spilled} has more than k≥1k \ge 1 names, so line L5 can pick one, and line L6 adds a name that was not in spilled. So spilled grows by one name in each round, and there are at most nn rounds. The loop stops only when the test of line L4 fails, that is, when no node has pressure above kk. □\square

The choice at line L5 does not matter for correctness. It only changes how many loads and stores the output has.

The coloring phase

Line L7 visits the blocks in a preorder of the dominator tree, so a block comes after every block that strictly dominates it. Line L8 visits the nodes of a block in order. Call a name kept if it is not spilled.

Lemma 2. When line L9 runs at a node vv, every kept name of O(v)∖D(v)O(v) \setminus D(v) has a color. Each kept name gets one color, every color is below kk, and two kept names that interfere get different colors.

Proof. Take a kept z∈O(v)∖D(v)z \in O(v) \setminus D(v). By the fact from the setup, the node that defines zz is earlier in the same block or in a block that strictly dominates the block of vv. In both cases lines L7 and L8 visit it before vv, and lines L10 and L11 gave zz its color there. Each name has one definition, so each kept name is colored once.

Now the bound. At line L11 for a name y∈D(v)y \in D(v), busy holds the colors of the kept names of O(v)∖D(v)O(v) \setminus D(v) and the colors given so far to the kept names of D(v)D(v) before yy. All of these names are in (D(v)∪O(v))∖spilled(D(v) \cup O(v)) \setminus \mathit{spilled} and are not yy, so by Lemma 1, ∣busy∣≤k−1|\mathit{busy}| \le k - 1. The lowest color not in busy is at most ∣busy∣|\mathit{busy}|, so it is below kk. A partner color is the color of a name colored before, so by induction on the order of the coloring it is below kk too.

Last, take kept names x≠yx \ne y that interfere at the node vv with x∈D(v)x \in D(v). If y∈D(v)y \in D(v) too, the one of them colored second sees the color of the first in busy, because line L12 adds each new color. If y∈O(v)∖D(v)y \in O(v) \setminus D(v), its color is in busy from line L9 when xx is colored. In both cases line L11 picks a color not in busy, and a partner color is used only when it is not in busy. So xx and yy get different colors. □\square

Lemma 3. Let mm be MaxLive. If k≥mk \ge m, nothing is spilled and the coloring uses exactly mm colors. No valid assignment of registers to the names of WW uses fewer.

Proof. With k≥mk \ge m, no node has pressure above kk with spilled empty, so the loop of line L4 stops at once. Repeat the bound of Lemma 2 with mm in place of kk: at each node ∣busy∣≤m−1|\mathit{busy}| \le m - 1, so a lowest free color is below mm, and by induction every partner color is below mm too. So at most mm colors are used.

For the lower bound, take a node vv with ∣D(v)∪O(v)∣=m|D(v) \cup O(v)| = m. Every x∈D(v)x \in D(v) interferes with every other name of D(v)∪O(v)D(v) \cup O(v) by the definition. Two names y,z∈O(v)∖D(v)y, z \in O(v) \setminus D(v) are both live just after vv, and neither is defined at vv, so both were live just before vv too; the theorem shows that two names live at one point interfere (one of their definitions dominates the other, and the other name is live just after the later definition). So D(v)∪O(v)D(v) \cup O(v) is a clique of mm names, and any valid assignment uses at least mm registers. □\square

This is where chordality shows: the interference graph of WW has chromatic number equal to its largest clique, and a greedy pass in dominance order finds such a coloring without building the graph.

Leaving SSA form

Let loc(x)\mathrm{loc}(x) be the register rcr_c for a kept name of color cc, and the slot mem.x for a spilled name. Lines L13 and L14 put at the end of each predecessor QQ of a block BB with phis the parallel copy {loc(y)←loc(a)}\{\mathrm{loc}(y) \leftarrow \mathrm{loc}(a)\} over the phis y=ϕ[…,Q: a,…]y = \phi[\ldots, Q{:}\ a, \ldots] of BB. Its destinations are distinct: the phis of BB form one node, so two kept phis of BB get different colors by Lemma 2, and two spilled phis have different slots. The source QQ ends in jump, since line L1 split every edge from a br into a block with phis, so the copy can go just before the jump.

Lemma 4. Let MM be a list of moves (d,s)(d, s) with distinct destinations, where each dd is a register or a slot and each ss is a register, a slot or a constant, and none of them is s0s_0 or s1s_1. The instructions that SEQUENTIALIZE returns leave each dd with the old value of its ss, leave every other register and slot unchanged, and may change only s0s_0 and s1s_1 besides.

Proof. Moves with d=sd = s are dropped; they change nothing. Call a move pending if it is not yet emitted. We keep this invariant: each pending move reads, from its source, the value that its original source had at the start, and every location that is not s0s_0 and not the destination of an emitted move still has its value from the start.

A move is emitted only when its destination is not the source of any pending move. Emitting it writes dd, which no pending move still has to read, and it reads its source, which still has the right value by the invariant. A move from a slot to a slot goes through s1s_1, which no pending move reads. So the invariant holds after the emit.

If no move can be emitted, every pending destination is the source of some pending move. There are as many pending moves as pending destinations, and each move has one source, so the sources of the pending moves are exactly the pending destinations. In particular, no pending move reads s0s_0. Line L15 copies the destination dd of the first pending move into s0s_0 and makes every pending move that reads dd read s0s_0 instead. The invariant holds, and now dd is no longer read, so the next round emits a move. Each round either emits a move or is followed by an emit, so the loop stops after at most 2∣M∣2|M| rounds with all moves emitted. Then, by the invariant, each destination holds the start value of its source. □\square

The same outcome

Lemma 5. On every input, the output of SSA-ALLOCATE has the same outcome as PP.

Proof. WW has the same outcome as PP, as shown in the setup. Line L16 turns each node of WW into a short list of instructions: a phi group into nothing (its work is done by the parallel copies at the ends of the predecessors), an instruction into the same operation on locations, with loads into s0s_0 and s1s_1 before a read of a slot and a store from s0s_0 after a write of a slot, and a terminator into the same terminator after the parallel copy of its block, if any. So a run of the output follows a run of WW node by node. We show by induction along the run this invariant:

(I) Just after each node of WW, every name z∈O(v)z \in O(v) that has a value holds that value in loc(z)\mathrm{loc}(z).

Just before the entry, nothing is live except the slots of the parameters, which hold the arguments. Now take a node vv and assume (I) for the node before it in the run.

  • An instruction y=f(a,b)y = f(a, b). The names aa and bb are live before vv, so they are in the live-out set of the previous node, and by (I) they are in loc(a)\mathrm{loc}(a) and loc(b)\mathrm{loc}(b). The loads into s0s_0 and s1s_1 change no location of a name. The result goes to loc(y)\mathrm{loc}(y). Every other z∈O(v)z \in O(v) is in O(v)∖D(v)O(v) \setminus D(v), so it was live before vv and held its value. If yy is kept, zz kept, then yy and zz interfere and Lemma 2 gives them different registers. If either is spilled, their locations differ because slots are named after names and registers are not slots. So only loc(y)\mathrm{loc}(y) changed, and (I) holds after vv.
  • A terminator. It writes no location, and a br or ret reads its operand from its location, through s0s_0 if it is a slot. If the block ends in jump to a block BB with phis, the parallel copy runs first. Its sources are phi operands, which are in OO of the terminator, so by (I) they hold the right values. By Lemma 4 the copy writes exactly the locations of the phis of BB and changes nothing else but s0s_0 and s1s_1.
  • The phi group of BB, reached from QQ. After the copy at the end of QQ, loc(y)\mathrm{loc}(y) holds the value that the phi yy takes. The other names live after the phi group are in O∖DO \setminus D of the phi group, so they were live at the end of QQ, and by Lemma 2 none of them shares a location with a phi of BB. So they kept their values, and (I) holds after the phi group.

Each read of the output therefore sees the value that WW reads, and so each branch goes the same way and ret returns the same value. A run of WW that traps or runs out of fuel does the same in the output after at most a constant factor more steps; the tests use enough fuel for both. □\square

Together, Lemmas 1 to 5 show that SSA-ALLOCATE gives a program with the same outcome that uses only r0,…,rk−1r_0, \ldots, r_{k-1}, s0s_0, s1s_1 and slots, and that when k≥k \ge MaxLive it spills nothing and uses exactly MaxLive registers, which no allocation can beat. The number of spills when k<k < MaxLive is not minimal: choosing the fewest names to spill is NP-hard even in SSA form.

Complexity

With nn names, ss nodes, bb blocks and ll the time of liveness:

  • Liveness and nodes. One fixed point of live variable analysis on the blocks, then one backward walk per block gives O(v)O(v) for each node in O(sn)O(s n) time and space.
  • Spill phase. Each round scans all nodes in O(sn)O(s n), and there are at most nn rounds, so O(sn2)O(s n^2) in the worst case. A real spiller works block by block in near-linear time.
  • Dominator tree. The iterative method of Cooper, Harvey and Kennedy takes O(b2)O(b^2) in the worst case and is close to linear in practice.
  • Coloring. One pass over the nodes with a set of busy colors, O(sn)O(s n).
  • Phi removal. A parallel copy of mm moves takes O(m2)O(m^2) with the simple scan; the sum over all edges is at most the total size of the phis squared per block, small in practice.

The total is O(l+sn2+b2)O(l + s n^2 + b^2). No interference graph is built: the coloring needs only the live sets, which is what makes the method fast.

Properties

  • Exact when the pressure fits. With k≥k \ge MaxLive it uses exactly MaxLive registers and no spill, the best possible. In the Chaitin approach, deciding kk-colorability of a general interference graph is NP-complete, so no such promise is possible there.
  • Spill and color are separate. Once the pressure is at most kk, coloring cannot fail. There is no loop back from coloring to spilling.
  • Strict SSA is required. The dominance argument needs each use to be dominated by its definition. For a non-strict program, the interference graph need not be chordal.
  • Whole names in this version. A spilled name is in memory everywhere, with a load before each use and a store after its definition, through s0s_0 and s1s_1.
  • Copies are left after coloring. The phis turn into moves unless partners share a register. The partner bias removes many moves, but not all, and finding the fewest moves is NP-hard (see register coalescing).

Variants and improvements

  • Belady-based spilling (Braun and Hack, 2009) walks each block, keeps the kk values whose next use is nearest, and places reloads and splits, with loop-aware next-use distances. It lowers the pressure to kk with far fewer loads than spilling whole names.
  • Recoloring for coalescing (Hack and Goos, 2008) changes the colors after the coloring phase so that names joined by copies share a register, while the coloring stays valid. Bouchez, Darte and Rastello studied other coalescing rules that keep the graph colorable.
  • Register constraints. Calling conventions and two-address instructions fix some names to registers, which breaks chordality. Hack splits the live ranges just before such an instruction with a parallel copy, so that the constraint is met inside one node.
  • SSA linear scan (Wimmer and Franz, 2010) keeps the interval model of linear scan but builds the intervals from SSA form. It is faster to write into a JIT, and it does not have the optimality of the coloring here.
  • Use in compilers. The libFirm compiler uses this method as its main allocator, and the approach is taught in the SSA book of Rastello and Bouchez Tichadou.

When to use it

Use it in an optimizing compiler that keeps SSA form until code generation, where code quality matters and the machine has a regular register file. It gives the best number of registers whenever no spill is needed, and its two phases can be built and tuned on their own. For a fast JIT tier, linear scan or SSA linear scan is simpler. For a program that has already left SSA form, use graph coloring, since the chordal property is gone.

Pitfalls

  • Leaving SSA first. If the phis are replaced by copies before allocation, a name gets several definitions and the interference graph may stop being chordal: the loop on the interference graph page has a chordless cycle of length 4 after out-of-SSA translation. Color first, then remove the phis.
  • Copies on a branch edge. A copy for the edge (Q,B)(Q, B) placed before a br of QQ also runs on the other edge and can overwrite a live value. Split such edges.
  • Swaps. Two phis whose operands swap registers form a cycle in the parallel copy. Copying them one by one loses a value. Break each cycle with a scratch register, or use an exchange instruction.
  • Dead definitions. A name that is defined and never used still needs a register at its definition. Count D(v)D(v) in the pressure, not only the live names.
  • Pressure is not the whole story for spill code. The output needs registers for the loads and stores of spilled names. Here s0s_0 and s1s_1 are kept apart for that. Without spare registers, the spill phase must lower the pressure further at instructions that read spilled names.
  • Non-strict input. A name read on a path where it has no definition breaks the dominance argument. Give the parameters a definition in a start block and build strict SSA form.

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.

ssa_based_register_allocation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ssa-based-register-allocation/. The authors are listed in prov/C6A8K4.jsonl.
"""SSA-based register allocation in the style of Hack, Grund and Goos.

allocate(prog, k) takes a toy IR program in strict SSA form, with const,
copy, op and phi instructions, and k >= 1 registers. It works in three
phases:

1. spill: keep whole names in memory slots until at most k names that are
   not spilled hold a value at each node;
2. color: walk the blocks in a preorder of the dominator tree and give each
   definition the lowest register that no live name holds (or the register
   of its copy or phi partner, when that one is free);
3. leave SSA: replace the phis of each block by a parallel copy at the end
   of each predecessor, made sequential with the scratch register s0 for
   cycles and s1 for moves from memory to memory.

It returns (out, color, spilled). out has no phis, and its names are the
registers r0 .. r(k-1), the scratch registers s0 and s1, and memory slots
whose names start with "mem.". Its parameters are the slots of the
parameters of prog.

A node is a group of phis of one block, an ordinary instruction or a
terminator. nodes(prog) lists, for each block, its nodes as (defs, out),
where out is the set of names live just after the node. The names of a phi
operand count as read at the end of the predecessor.
"""

import toyir

MEM = "mem."


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


# ------------------------------------------------------------ preparation


def _fresh(prog, base):
    label = base
    while label in prog.blocks:
        label += "_"
    return label


def prepare(prog):
    """Add a start block that loads each live parameter from its slot, and
    split each edge into a block with phis whose source ends in a branch,
    so that every parallel copy can go just before a jump."""
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] not in ("const", "copy", "op", "phi"):
                raise ValueError("only const, copy, op and phi: %r" % (ins,))
            for a in [ins[1]] + toyir.uses(ins):
                if is_mem(a):
                    raise ValueError("names that start with %r are reserved" % MEM)
    if any(ins[0] == "phi" for ins in prog.blocks[prog.entry].instrs):
        raise ValueError("the entry block must not have phis")
    blocks = {lab: toyir.Block(list(b.instrs), b.term) for lab, b in prog.blocks.items()}
    work = toyir.Program(list(prog.params), blocks)
    for lab in list(blocks):
        term = blocks[lab].term
        if term[0] != "br":
            continue
        for target in toyir.succs(work, lab):
            if not any(ins[0] == "phi" for ins in blocks[target].instrs):
                continue
            mid = _fresh(work, "%s_%s" % (lab, target))
            blocks[mid] = toyir.Block([], ("jump", target))
            term = (term[0], term[1]) + tuple(mid if t == target else t for t in term[2:])
            blocks[target].instrs = [
                ("phi", ins[1], {(mid if p == lab else p): a for p, a in ins[2].items()}) if ins[0] == "phi" else ins
                for ins in blocks[target].instrs
            ]
        blocks[lab].term = term
    live_in, _ = liveness(work)
    start = _fresh(work, "start")
    pro = [("copy", p, MEM + p) for p in prog.params if p in live_in[work.entry]]
    out = {start: toyir.Block(pro, ("jump", work.entry))}
    out.update(blocks)
    return toyir.Program([MEM + p for p in prog.params], out)


# --------------------------------------------------------------- liveness


def _phis(b):
    return [ins for ins in b.instrs if ins[0] == "phi"]


def _body(b):
    return [ins for ins in b.instrs if ins[0] != "phi"]


def liveness(prog):
    """live_in and live_out of each block for SSA form: live_in excludes the
    phis of the block, and live_out includes the phi operands that the block
    sends to its successors."""
    use, kill, phiuse, phidef = {}, {}, {}, {}
    for label, b in prog.blocks.items():
        u, d = set(), set()
        for ins in _body(b):
            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
        phidef[label] = {ins[1] for ins in _phis(b)}
        phiuse[label] = set()
    for label, b in prog.blocks.items():
        for ins in _phis(b):
            for p, a in ins[2].items():
                if isinstance(a, str):
                    phiuse[p].add(a)
    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(phiuse[label])
            for s in toyir.succs(prog, label):
                out |= live_in[s]
            new_in = (use[label] | (out - kill[label])) - phidef[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 nodes(prog):
    """For each block, its nodes in order as (defs, out). The phi group comes
    first (when the block has phis), then the instructions, then the
    terminator."""
    _, live_out = liveness(prog)
    result = {}
    for label, b in prog.blocks.items():
        live = set(live_out[label])
        rev = [((), frozenset(live))]
        live |= set(toyir.term_uses(b.term))
        for ins in reversed(_body(b)):
            rev.append(((ins[1],), frozenset(live)))
            live.discard(ins[1])
            live.update(toyir.uses(ins))
        phis = _phis(b)
        if phis:
            rev.append((tuple(ins[1] for ins in phis), frozenset(live)))
        result[label] = list(reversed(rev))
    return result


def max_live(prog, spilled=()):
    """The largest number of names that are not spilled in defs | out of one
    node."""
    best = 0
    for ns in nodes(prog).values():
        for defs, out in ns:
            best = max(best, len((set(defs) | out) - set(spilled)))
    return best


# ------------------------------------------------------------- dominators


def dominator_preorder(prog):
    """The blocks in a preorder of the dominator tree (iterative dominators
    of Cooper, Harvey and Kennedy on the reverse postorder)."""
    entry = prog.entry
    order, seen = [], {entry}
    stack = [(entry, iter(toyir.succs(prog, entry)))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            order.append(v)
            stack.pop()
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(toyir.succs(prog, w))))
    rpo = list(reversed(order))
    index = {v: i for i, v in enumerate(rpo)}
    pred = toyir.preds(prog)
    idom = {entry: entry}

    def meet(a, b):
        while a != b:
            while index[a] > index[b]:
                a = idom[a]
            while index[b] > index[a]:
                b = idom[b]
        return a

    changed = True
    while changed:
        changed = False
        for v in rpo[1:]:
            ps = [p for p in pred[v] if p in idom]
            new = ps[0]
            for p in ps[1:]:
                new = meet(p, new)
            if idom.get(v) != new:
                idom[v] = new
                changed = True
    children = {v: [] for v in rpo}
    for v in rpo[1:]:
        children[idom[v]].append(v)
    out, stack = [], [entry]
    while stack:
        v = stack.pop()
        out.append(v)
        stack.extend(reversed(children[v]))
    return out


# ----------------------------------------------------------------- phases


def spill_costs(prog):
    """The number of definitions and uses of each name, phi operands included."""
    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
    return cost


def spill(prog, k):
    """Spill whole names until each node has at most k names that are not
    spilled in defs | out. The name chosen at an overfull node is the one
    with the least cost; ties go to the one that is overfull at the most
    nodes, then to the name order."""
    ns = [(set(d) | out) - {a for a in set(d) | out if is_mem(a)} for v in nodes(prog).values() for d, out in v]  # @line L2
    cost = spill_costs(prog)
    spilled = set()  # @line L3
    while True:
        over = [s - spilled for s in ns if len(s - spilled) > k]  # @line L4
        if not over:
            return spilled
        count = {}
        for s in over:
            for x in s:
                count[x] = count.get(x, 0) + 1
        x = min(over[0], key=lambda a: (cost[a], -count[a], a))  # @line L5
        spilled.add(x)  # @line L6


def color(prog, spilled):
    """Color the names that are not spilled, in a preorder of the dominator
    tree. Returns the color of each such name."""
    color = {}
    ns = nodes(prog)
    partner = {}
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] == "copy" and isinstance(ins[2], str):
                partner[ins[1]] = [ins[2]]
            elif ins[0] == "phi":
                partner[ins[1]] = [a for a in ins[2].values() if isinstance(a, str)]
    for label in dominator_preorder(prog):  # @line L7
        for defs, out in ns[label]:  # @line L8
            busy = {color[z] for z in out if z not in defs and z not in spilled and not is_mem(z)}  # @line L9
            for y in defs:  # @line L10
                if y in spilled or is_mem(y):
                    continue
                pref = [color[a] for a in partner.get(y, []) if a in color and color[a] not in busy]
                c = pref[0] if pref else min(set(range(len(busy) + 1)) - busy)  # @line L11
                color[y] = c
                busy.add(c)  # @line L12
    return color


def sequentialize(moves):
    """Turn a parallel copy, a list of (dst, src) with distinct dst, into a
    list of instructions. A cycle is broken by saving one destination in s0;
    a move from memory to memory goes through s1."""
    moves = [(d, s) for d, s in moves if d != s]
    out = []

    def emit(d, s):
        if isinstance(s, int):
            out.append(("const", d, s))
        elif is_mem(d) and is_mem(s):
            out.extend([("copy", "s1", s), ("copy", d, "s1")])
        else:
            out.append(("copy", d, s))

    while moves:
        srcs = {s for _, s in moves if isinstance(s, str)}
        for i, (d, s) in enumerate(moves):
            if d not in srcs:
                emit(d, s)
                moves.pop(i)
                break
        else:
            # Every destination is still read, so only cycles are left.
            d = moves[0][0]  # @line L15
            out.append(("copy", "s0", d))
            moves = [(dd, "s0" if ss == d else ss) for dd, ss in moves]
    return out


def _rewrite_body(instrs, loc):
    out = []
    for ins in instrs:
        x = loc(ins[1])
        if ins[0] == "const":
            out.append(("const", x, ins[2]))
            continue
        locs = [loc(a) for a in ([ins[2]] if ins[0] == "copy" else [ins[3], ins[4]])]
        if ins[0] == "copy":
            if locs[0] != x:
                if is_mem(locs[0]) and is_mem(x):
                    out += [("copy", "s0", locs[0]), ("copy", x, "s0")]
                else:
                    out.append(("copy", x, locs[0]))
            continue
        loaded = {}
        for a in locs:
            if is_mem(a) and a not in loaded:
                loaded[a] = ("s0", "s1")[len(loaded)]
                out.append(("copy", loaded[a], a))
        a, c = (loaded.get(v, v) for v in locs)
        if is_mem(x):
            out += [("op", "s0", ins[2], a, c), ("copy", x, "s0")]
        else:
            out.append(("op", x, ins[2], a, c))
    return out


def allocate(prog, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    work = prepare(prog)  # @line L1
    spilled = spill(work, k)
    col = color(work, spilled)

    def loc(a):
        if not isinstance(a, str) or is_mem(a):
            return a
        return MEM + a if a in spilled else "r%d" % col[a]

    copies = {label: [] for label in work.blocks}
    for label, b in work.blocks.items():  # @line L13
        for ins in _phis(b):
            for p, a in ins[2].items():
                copies[p].append((loc(ins[1]), loc(a)))  # @line L14
    blocks = {}
    for label, b in work.blocks.items():
        body = _rewrite_body(_body(b), loc)
        term = b.term
        if copies[label]:
            if term[0] != "jump":
                raise AssertionError("prepare split this edge")
            body += sequentialize(copies[label])
        if term[0] in ("br", "ret"):
            a = loc(term[1])
            if is_mem(a):
                body.append(("copy", "s0", a))
                a = "s0"
            term = (term[0], a) + term[2:]
        blocks[label] = toyir.Block(body, term)
    return toyir.Program(list(work.params), blocks), col, spilled  # @line L16
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_ssa_based_register_allocation.py 420 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ssa-based-register-allocation/. The authors are listed in prov/C6A8K4.jsonl.

import random

import toyir
from ssa_based_register_allocation import allocate, is_mem, max_live, prepare, sequentialize

LOOP = """# params: n
entry:
  i0 = 0
  a0 = 0
  jump head
head:
  i1 = phi [entry: i0, body: i2]
  a1 = phi [entry: a0, body: a2]
  t = i1 < n
  br t body done
body:
  u = i1 * i1
  a2 = a1 + u
  i2 = i1 + 1
  jump head
done:
  ret a1
"""


# ------------------------------------------------- SSA construction (Cytron)


def dominators(prog):
    """Dominator sets by the plain fixed point: Dom(v) = {v} + meet of Dom(p)."""
    labels = list(prog.blocks)
    pred = toyir.preds(prog)
    dom = {v: set(labels) for v in labels}
    dom[prog.entry] = {prog.entry}
    changed = True
    while changed:
        changed = False
        for v in labels:
            if v == prog.entry:
                continue
            ps = [dom[p] for p in pred[v]]
            new = {v} | (set.intersection(*ps) if ps else set())
            if new != dom[v]:
                dom[v], changed = new, True
    idom = {}
    for v in labels:
        strict = dom[v] - {v}
        for d in strict:
            if strict <= dom[d]:
                idom[v] = d
    return dom, idom


def block_live_in(prog):
    """Live-in names of each block of a program without phis."""
    live = {lab: set() for lab in prog.blocks}
    changed = True
    while changed:
        changed = False
        for lab in reversed(list(prog.blocks)):
            b = prog.blocks[lab]
            cur = set(toyir.term_uses(b.term))
            for s in toyir.succs(prog, lab):
                cur |= live[s]
            for ins in reversed(b.instrs):
                cur.discard(ins[1])
                cur |= set(toyir.uses(ins))
            if cur != live[lab]:
                live[lab], changed = cur, True
    return live


def to_ssa(prog):
    """Pruned SSA form (phis at the iterated dominance frontier where the
    name is live, then renaming along the dominator tree). The parameters
    keep their names."""
    dom, idom = dominators(prog)
    pred = toyir.preds(prog)
    live = block_live_in(prog)
    df = {v: set() for v in prog.blocks}
    for v in prog.blocks:
        if len(pred[v]) >= 2:
            for p in pred[v]:
                r = p
                while r != idom.get(v):
                    df[r].add(v)
                    r = idom[r]
    defsites = {}
    for p in prog.params:
        defsites.setdefault(p, set()).add(prog.entry)
    for lab, b in prog.blocks.items():
        for ins in b.instrs:
            defsites.setdefault(ins[1], set()).add(lab)
    phis = {lab: [] for lab in prog.blocks}
    for x, sites in sorted(defsites.items()):
        work, placed = list(sites), set()
        while work:
            v = work.pop()
            for w in df[v]:
                if w not in placed:
                    placed.add(w)
                    if x in live[w]:
                        phis[w].append(x)
                    if w not in sites:
                        work.append(w)
    children = {v: [] for v in prog.blocks}
    for v, d in idom.items():
        children[d].append(v)
    count = {}
    stacks = {p: [p] for p in prog.params}
    blocks = {}
    phi_args = {lab: {x: {} for x in phis[lab]} for lab in prog.blocks}
    phi_name = {}

    def new(x):
        count[x] = count.get(x, 0) + 1
        name = "%s.%d" % (x, count[x])
        stacks.setdefault(x, []).append(name)
        return name

    def top(a):
        return stacks[a][-1] if isinstance(a, str) else a

    def walk(v):
        pushed = []
        for x in phis[v]:
            phi_name[(v, x)] = new(x)
            pushed.append(x)
        body = []
        for ins in prog.blocks[v].instrs:
            if ins[0] == "const":
                body.append(("const", None, ins[2]))
            elif ins[0] == "copy":
                body.append(("copy", None, top(ins[2])))
            else:
                body.append(("op", None, ins[2], top(ins[3]), top(ins[4])))
            body[-1] = (body[-1][0], new(ins[1])) + body[-1][2:]
            pushed.append(ins[1])
        t = prog.blocks[v].term
        if t[0] in ("br", "ret"):
            t = (t[0], top(t[1])) + t[2:]
        blocks[v] = (body, t)
        for s in toyir.succs(prog, v):
            for x in phis[s]:
                phi_args[s][x][v] = top(x)
        for c in sorted(children[v], key=list(prog.blocks).index):
            walk(c)
        for x in pushed:
            stacks[x].pop()

    walk(prog.entry)
    out = {}
    for lab in prog.blocks:
        body, t = blocks[lab]
        ph = [("phi", phi_name[(lab, x)], phi_args[lab][x]) for x in phis[lab]]
        out[lab] = toyir.Block(ph + body, t)
    return toyir.Program(list(prog.params), out)


def random_ssa(rng, nvars, nblocks, acyclic):
    prog = toyir.random_program(rng, nvars, nblocks, acyclic)
    return prog, to_ssa(prog)


# --------------------------------------------- independent checks on output


def item_graph(prog):
    """Nodes: one phi group per block with phis, each instruction, each
    terminator. A phi operand is read by the terminator of its predecessor."""
    items, first = [], {}
    for lab, b in prog.blocks.items():
        first[lab] = len(items)
        ph = [ins for ins in b.instrs if ins[0] == "phi"]
        if ph:
            items.append((lab, "phi", set(i[1] for i in ph), set()))
        for ins in b.instrs:
            if ins[0] != "phi":
                items.append((lab, "ins", {ins[1]}, set(toyir.uses(ins))))
        reads = set(toyir.term_uses(b.term))
        for s in toyir.succs(prog, lab):
            for ins in prog.blocks[s].instrs:
                if ins[0] == "phi" and isinstance(ins[2][lab], str):
                    reads.add(ins[2][lab])
        items.append((lab, "term", set(), reads))
    nxt = []
    for n, (lab, kind, _, _) in enumerate(items):
        nxt.append([first[s] for s in toyir.succs(prog, lab)] if kind == "term" else [n + 1])
    return items, nxt


def brute_live_out(prog):
    items, nxt = item_graph(prog)
    prv = [[] for _ in items]
    for n, ss in enumerate(nxt):
        for s in ss:
            prv[s].append(n)
    names = set().union(*(u for _, _, _, u in items))
    live_in = [set() for _ in items]
    for x in names:
        work = [n for n, it in enumerate(items) if x in it[3]]
        seen = set(work)
        while work:
            v = work.pop()
            for p in prv[v]:
                if p not in seen and x not in items[p][2]:
                    seen.add(p)
                    work.append(p)
        for n in seen:
            live_in[n].add(x)
    out = [set().union(*(live_in[s] for s in nxt[n])) for n in range(len(items))]
    return items, out


def interference(prog):
    items, out = brute_live_out(prog)
    adj = {}
    for _, _, d, _ in items:
        for x in d:
            adj.setdefault(x, set())
    points = []
    for n, (_, _, d, _) in enumerate(items):
        here = {x for x in d | out[n] if not is_mem(x)}
        points.append(here)
        for x in d:
            for y in here:
                if x != y and not is_mem(x):
                    adj.setdefault(x, set()).add(y)
                    adj.setdefault(y, set()).add(x)
    return {x: v for x, v in adj.items() if not is_mem(x)}, points


def is_chordal(adj):
    """Maximum cardinality search, then a check that its reverse order is a
    perfect elimination ordering."""
    weight = {v: 0 for v in adj}
    order, done = [], set()
    while len(order) < len(adj):
        v = max((u for u in adj if u not in done), key=lambda u: (weight[u], u))
        order.append(v)
        done.add(v)
        for w in adj[v]:
            if w not in done:
                weight[w] += 1
    pos = {v: i for i, v in enumerate(order)}
    for v in adj:
        earlier = [w for w in adj[v] if pos[w] < pos[v]]
        if earlier:
            parent = max(earlier, key=pos.__getitem__)
            if any(w != parent and w not in adj[parent] for w in earlier):
                return False
    return True


def chromatic(adj):
    nodes = sorted(adj, key=lambda v: -len(adj[v]))
    for k in range(len(nodes) + 1):
        col = {}

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

        if go(0):
            return k
    return len(nodes)


def clique_number(adj):
    best = 0

    def grow(clique, cand):
        nonlocal best
        best = max(best, len(clique))
        for v in sorted(cand):
            grow(clique | {v}, {w for w in cand if w > v and w in adj[v]})

    grow(set(), set(adj))
    return best


# ------------------------------------------------------------------- tests


def check(orig, ssa, k, rng):
    work = prepare(ssa)
    out, col, spilled = allocate(ssa, k)
    adj, points = interference(work)
    for x in adj:
        assert (x in col) != (x in spilled), x
    for x in col:
        assert 0 <= col[x] < k
        for y in adj[x]:
            if y in col:
                assert col[x] != col[y], (x, y)
    for here in points:
        assert len(here - spilled) <= k
    for b in out.blocks.values():
        assert all(ins[0] != "phi" for ins in b.instrs)
    for _ in range(4):
        args = [rng.randint(-6, 6), rng.randint(-6, 6)]
        assert toyir.run(out, args, fuel=200000) == toyir.run(orig, args, fuel=200000)
    return adj, points, col, spilled


def test_random_programs_keep_their_outputs():
    rng = random.Random(7)
    spills = 0
    for trial in range(150):
        orig, ssa = random_ssa(rng, rng.randint(2, 6), rng.randint(1, 7), acyclic=trial % 2 == 0)
        for k in (1, 2, 3, 4):
            _, _, _, spilled = check(orig, ssa, k, rng)
            spills += len(spilled)
    assert spills > 0


def test_max_live_colors_when_pressure_fits():
    rng = random.Random(21)
    tested = 0
    for trial in range(150):
        orig, ssa = random_ssa(rng, rng.randint(2, 5), rng.randint(1, 6), acyclic=trial % 2 == 1)
        work = prepare(ssa)
        adj, points = interference(work)
        m = max(len(p) for p in points)
        assert m == max_live(work)
        assert is_chordal(adj)
        for k in range(m, m + 2):
            _, _, col, spilled = check(orig, ssa, k, rng)
            assert not spilled
            assert len(set(col.values())) == m
        if len(adj) <= 14:
            assert clique_number(adj) == chromatic(adj) == m
            tested += 1
    assert tested > 50


def test_not_chordal_after_leaving_ssa():
    # The loop of the interference graph page: several definitions of d.
    text = """# params: n
L0:
  d = n
  jump L1
L1:
  a = d + 1
  b = a + d
  c = a + 1
  d = b - c
  d = d % c
  br d L1 L2
L2:
  ret d
"""
    prog = toyir.parse(text)
    items, out = brute_live_out(prog)
    adj = {}
    for n, (_, _, d, _) in enumerate(items):
        for x in d:
            for y in out[n]:
                src = None
                if items[n][1] == "ins":
                    ins = [i for i in prog.blocks[items[n][0]].instrs if i[1] == x]
                    src = ins[0][2] if ins and ins[0][0] == "copy" else None
                if x != y and y != src:
                    adj.setdefault(x, set()).add(y)
                    adj.setdefault(y, set()).add(x)
    assert {x: adj[x] for x in "abcd"} == {"a": {"b", "d"}, "b": {"a", "c"}, "c": {"b", "d"}, "d": {"a", "c"}}
    assert not is_chordal({x: adj[x] for x in "abcd"})


def test_loop_example():
    prog = toyir.parse(LOOP)
    work = prepare(prog)
    assert max_live(work) == 4
    out, col, spilled = allocate(prog, 4)
    assert not spilled
    assert col == {"n": 0, "i0": 1, "a0": 2, "i1": 1, "a1": 2, "t": 3, "u": 3, "a2": 2, "i2": 1}
    # The bias puts each phi and its operands in one register, so no copy is left.
    assert [ins for b in out.blocks.values() for ins in b.instrs if ins[0] == "copy"] == [("copy", "r0", "mem.n")]
    out3, _, spilled3 = allocate(prog, 3)
    assert spilled3 == {"n"}
    out2, _, spilled2 = allocate(prog, 2)
    assert spilled2 == {"n", "t", "u"}
    for n in range(-2, 8):
        expect = toyir.run(prog, [n])
        assert toyir.run(out, [n]) == toyir.run(out3, [n]) == toyir.run(out2, [n]) == expect
        assert expect == ("ret", sum(i * i for i in range(max(n, 0))))


def test_sequentialize_parallel_copies():
    rng = random.Random(4)
    locs = ["r0", "r1", "r2", "r3", "mem.a", "mem.b"]
    for _ in range(3000):
        dsts = rng.sample(locs, rng.randint(1, len(locs)))
        moves = [(d, rng.choice(locs + [rng.randint(0, 9)])) for d in dsts]
        state = {x: i + 100 for i, x in enumerate(locs)}
        expect = dict(state)
        for d, s in moves:
            expect[d] = s if isinstance(s, int) else state[s]
        for ins in sequentialize(moves):
            state[ins[1]] = ins[2] if ins[0] == "const" else state[ins[2]]
        assert all(state[x] == expect[x] for x in locs)


def test_swap_needs_s0():
    seq = sequentialize([("r0", "r1"), ("r1", "r0")])
    assert seq == [("copy", "s0", "r0"), ("copy", "r0", "r1"), ("copy", "r1", "s0")]
    # A chain needs no scratch register: r2 is read before it is written.
    assert sequentialize([("r1", "r2"), ("r2", "r3")]) == [("copy", "r1", "r2"), ("copy", "r2", "r3")]

History

Pereira and Palsberg (2005) saw that most interference graphs from the Java programs they studied were chordal and colored them with a chordal coloring method. In 2005 three groups proved that strict SSA programs always give chordal interference graphs: Hack, Grund and Goos in a Karlsruhe report, published at CC 2006 and in a short proof with Goos in Information Processing Letters; Brisk, Dabiri, Macbeth and Sarrafzadeh at IWLS 2005; and Bouchez, Darte, Guillon and Rastello, whose paper appeared at LCPC 2006. Hack, Grund and Goos turned the result into the decoupled allocator. Bouchez, Darte and Rastello (2007) showed that spilling stays hard in SSA form, Hack and Goos (2008) added recoloring for coalescing, and Braun and Hack (2009) gave the spiller used in libFirm.

References

  1. Sebastian Hack, Daniel Grund and Gerhard Goos, Register allocation for programs in SSA-form, Compiler Construction (CC 2006), LNCS 3923, 247-262, the split of allocation into a spill phase that lowers the register pressure to k and a coloring phase in a dominance order that needs no further spill, and the removal of the phis by permutations of registers
  2. Sebastian Hack and Gerhard Goos, Optimal register allocation for SSA-form programs in polynomial time, Information Processing Letters 98(4), 2006, 150-155, the proof that the interference graph of a strict SSA program is chordal, and that its chromatic number is the largest register pressure
  3. Florent Bouchez, Alain Darte and Fabrice Rastello, On the complexity of spill everywhere under SSA form, LCTES 2007, 103-112, the proof that choosing the cheapest set of names to spill everywhere is NP-complete even for SSA programs, and the cases that are polynomial
  4. Sebastian Hack and Gerhard Goos, Copy coalescing by graph recoloring, PLDI 2008, 227-237, copy coalescing after the coloring, by recoloring chunks of names connected by copies while the coloring stays valid
  5. Matthias Braun and Sebastian Hack, Register spilling and live-range splitting for SSA-form programs, Compiler Construction (CC 2009), LNCS 5501, 174-189, the spill phase based on the furthest next use rule of Belady, applied per block with loop-aware distances, which inserts reloads and splits live ranges
  6. Fabrice Rastello and Florent Bouchez Tichadou, Register allocation, chapter 22 of SSA-based Compiler Design, Springer, 2022, 303-328, the overview of the decoupled approach, the spill phase, the coloring along the dominance tree, and the coalescing and phi removal after coloring

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