Algorithm Search⌘K

Problemcore

Register allocation

Also called global register allocation.

Assign the values of a program to a fixed number of machine registers, storing the rest in memory at least cost.

Register allocation decides where each value of a program lives while the program runs: in one of the kk registers of the machine, or in a memory slot. A value that does not get a register is spilled, and the compiler adds stores and loads that move it between memory and a register. The goal is a program that uses only kk registers, gives the same results, and runs as few added loads, stores and copies as possible. This page states the problem and its forms; register-allocation-np-completeness gives the hardness of one form, and the allocator pages give the methods.

In plain words

A processor computes only on values in its registers, and it has few of them, often 16 or 32. A program can have thousands of temporary values. Most of them are needed only for a short time, so the registers can be shared: two values can use the same register when they are never needed at the same moment. When too many values are needed at the same moment, some of them must wait in memory. The compiler writes each such value to memory and reads it back just before it is needed again. Memory is slow, so these extra reads and writes cost time. Register allocation chooses which values stay in registers, which register each one gets, and which values go to memory, so that the program stays correct and the extra work is small.

Definition

The input is a program PP in the toy IR (three-address code in basic blocks, a control flow graph), a number k≥2k \ge 2 of registers, and a weight f(B)≥0f(B) \ge 0 for each block BB, an estimate of how often BB runs. The memory slot of a name xx is written as the name mem.x; t = mem.x is a load and mem.x = t is a store. A slot is not a register.

A name xx is live at a point of PP if some path from that point reaches a use of xx with no definition of xx before it, as computed by live variable analysis. The live range of xx is the set of points where xx is live. MaxLive\mathrm{MaxLive} is the largest number of names live at one point. Two names interfere if one of them is live just after a definition of the other, unless that definition is a copy from the other name; the interference graph has the names as vertices and an edge for each interfering pair.

The output is a program P′P' with these properties:

  1. Every operand and result of an instruction is a register r0,…,rk−1r_0, \ldots, r_{k-1}, except the slot of a load or a store.
  2. P′P' is PP with each name renamed to a register at each point, plus added loads, stores and copies, and possibly added blocks on split edges.
  3. For every input, P′P' has the same outcome as PP (the same return value, the same trap, or no end).

The cost of P′P' is the sum, over the added instructions ii, of f(Bi)⋅c(i)f(B_i) \cdot c(i), where BiB_i is the block of ii and cc gives a cost to a load, a store and a copy. The problem is to find P′P' of least cost.

Four forms of the problem are studied on their own:

  • Coloring without splitting. Each name gets one register for its whole live range, and no code is added. This is possible if and only if the interference graph has a k-coloring: a register is a color, and two interfering names must not share a register.
  • Spilling. Choose the names to keep in memory, and where to put the loads and stores, so that the rest fits in kk registers at least cost (spill code placement).
  • Splitting. A name can move from one register to another through copies, so different parts of its live range can get different registers (live range splitting).
  • Coalescing. Give the source and the target of a copy the same register, so that the copy can be deleted (register coalescing problem).

Variants

  • Local allocation works on one basic block at a time and keeps no value in a register across blocks (local register allocation). With equal reload costs and no stores, it is the paging problem, and Belady's algorithm is optimal for it.
  • Global allocation works on a whole procedure. This is the form of this page, and the alias "global register allocation" names it.
  • Allocation on SSA form first spills until MaxLive≤k\mathrm{MaxLive} \le k, then colors the chordal interference graph with at most kk colors, and coalesces last (SSA-based register allocation).
  • Linear scan gives up the interference graph and assigns registers to live intervals in one sweep, for fast compilers such as JIT compilers (linear scan register allocation).
  • Real machines add constraints: some values must be in a fixed register (arguments and results of calls), some registers are destroyed by a call, and some instructions need register pairs or a register class. An allocator models a fixed register as a precolored vertex.

Examples

One block. The program below has one parameter p.

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

The live names just after each instruction are {p,a}\{p, a\}, {a,b}\{a, b\}, {a,b,c}\{a, b, c\}, {b,d}\{b, d\} and {e}\{e\}, and {p}\{p\} is live at the start, so MaxLive=3\mathrm{MaxLive} = 3. The interference edges are pp-aa, aa-bb, aa-cc, bb-cc and bb-dd; ee interferes with nothing. The triangle a,b,ca, b, c needs three colors, and three colors suffice. With k=3k = 3 and the parameter loaded from its slot, the allocator of Chaitin gives this program, with no added code apart from the parameter load:

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 some value must go to memory. Just after c = a + b, the three values aa, bb and cc are all used later, and only two fit in registers. In the toy IR every result is written to a register, so the value that waits in memory needs one store and one load. One store and one load also suffice: store b after its definition and load it just before e = b * d. So the least cost is one store and one load. A script ran this program and the two-register version on the inputs −50-50 to 4949 and found the same outcomes.

Coloring is not the whole problem. The program built on the page register-allocation-np-completeness for the triangle has three names u, v and w that interfere in a triangle, so no two-register assignment without splitting exists. But at most two names are live at any point, and one copy on one split edge gives a correct program with two registers. The interference graph answers only the first of the four forms above.

Known algorithms

AlgorithmTimeSpacePropertiesCode
Optimistic coloringO(r (l + s n + n^2)) worstO(n + m + s) extradeterministicofflineiterative1 language
Chaitin register allocationO(r (l + s n + n^2)) worstO(n + m + s) extradeterministicofflineiterative1 language
Iterated register coalescingO(r (l + s n + n^2 (c + 1))) worstO(n + m + s + c) extradeterministicofflineiterative1 language
Linear scan register allocationO(l + s n + n log n) worstO(s n) extradeterministicofflineiterative1 language
Local register allocationO(n k) worstΘ(n) extradeterministicofflineiterative1 language
Sethi-Ullman algorithmΘ(n) worstΘ(n) extradeterministicofflinerecursive1 language
SSA-based register allocationO(l + s n^2 + b^2) worstO(s n) extradeterministicofflineiterative1 language
Linear scan register allocation on SSA formO(s + b^2 + n^2 b) worstO(s + n b) extradeterministicofflineiterative1 language

Bounds

  • Lower bound. In a strict program (every use is reached only by paths that define the name) with no copies, the names live at one point interfere in pairs. Take two such names xx and yy and a path from the entry to the point. If the last definition of yy on the path comes after the last definition of xx, then xx is live just after that definition of yy. So these names form a clique, and χ(G)≥ω(G)≥MaxLive\chi(G) \ge \omega(G) \ge \mathrm{MaxLive}, where χ\chi is the chromatic number and ω\omega the size of the largest clique.
  • The gap can be large. Every graph, with one isolated vertex added, is the interference graph of a program with MaxLive≤2\mathrm{MaxLive} \le 2 (the construction on register-allocation-np-completeness). A Mycielski graph has no triangle and an arbitrarily large chromatic number, so the coloring form can need many more registers than MaxLive\mathrm{MaxLive}.
  • Upper bound with splitting. Bouchez, Darte, Guillon and Rastello (LCPC 2006) show that a strict program can be allocated with MaxLive\mathrm{MaxLive} registers and no spill when critical edges can be split (critical edge splitting) and moves and swaps can be inserted. So under these assumptions the question "are kk registers enough without spilling?" is answered by the test MaxLive≤k\mathrm{MaxLive} \le k, in polynomial time.
  • SSA form. In strict SSA form the interference graph is chordal and χ=ω=MaxLive\chi = \omega = \mathrm{MaxLive} (Hack, Grund and Goos 2006), so a perfect elimination ordering colors it optimally.
  • Hardness. The coloring form is NP-complete for every fixed k≥3k \ge 3 (register-allocation-np-completeness); for k=2k = 2 it is a bipartiteness test, in linear time. The choice of the values to spill everywhere stays NP-complete under SSA form in general (Bouchez, Darte and Rastello, LCTES 2007), and so does coalescing (register coalescing problem).

Reductions

  • The coloring form and k-coloring reduce to each other in polynomial time. One direction builds the interference graph. The other builds, for a graph GG, a program whose interference graph is GG plus one isolated vertex. A reduction from 3-colorability gives NP-hardness for three registers.
  • Local allocation with clean values and unit reload costs is the paging problem with a cache of kk pages.
  • In high-level synthesis, register binding maps the values of a schedule to hardware registers; for a straight schedule the live ranges are intervals, and the same coloring view applies.

Applications

Every optimizing compiler for a real processor has a register allocator, because operands of arithmetic instructions must be in registers. The allocator matters most in loops: a spill inside a loop runs on every iteration, which is why the block weights f(B)f(B) usually grow with the loop depth. JIT compilers use linear scan or a local allocator to keep compile time low. The same problem appears in the allocation of registers in hardware synthesis and of scratchpad memory on accelerators.

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, the formulation of global allocation as the coloring of the interference graph, and the proof that every graph is the interference graph of some program
  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 build, simplify, spill and select phases, and the spill cost estimate
  3. Florent Bouchez, Alain Darte, Christophe Guillon and Fabrice Rastello, Register allocation: what does the NP-completeness proof of Chaitin et al. really prove? Or revisiting register allocation: why and how, Languages and Compilers for Parallel Computing (LCPC 2006), LNCS 4382, Springer, 2007, the analysis of the reduction of Chaitin et al., the role of critical edges, and the result that MaxLive registers suffice for a strict program when critical edges can be split and moves and swaps can be inserted
  4. Sebastian Hack, Daniel Grund and Gerhard Goos, Register allocation for programs in SSA-form, Compiler Construction (CC 2006), LNCS 3923, Springer, 2006, 247-262, the interference graph of a strict SSA program is chordal, so it can be colored with MaxLive colors in polynomial time
  5. Florent Bouchez, Alain Darte and Fabrice Rastello, On the complexity of spill everywhere under SSA form, Proceedings of LCTES 2007, ACM, 2007, the complexity of choosing the values to spill, which stays NP-complete under SSA form in general
  6. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 13 (Register Allocation), local and global allocation, live ranges, interference and spill costs
  7. Andrew W. Appel with Jens Palsberg, Modern Compiler Implementation in Java, second edition, Cambridge University Press, 2002, Chapter 11 (Register Allocation)
  8. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 16 (Register Allocation)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a contract.yaml