Discova
Back to cards
Programming19 min readWikipedia, updated 28 November 2026

Register allocation

Computer compiler optimization technique

In compiler optimization, register allocation is the process of assigning local automatic variables and expression results to a limited number of processor registers.

Register allocation can happen over a basic block (local register allocation), over a whole function/procedure (global register allocation), or across function boundaries traversed via call-graph (interprocedural register allocation). When done per function/procedure the calling convention may require insertion of save/restore around each call-site.

Context

Principle

In many programming languages, the programmer may use any number of variables. The computer can quickly read and write registers in the CPU, so the computer program runs faster when more variables can be in the CPU's registers. Also, sometimes code accessing registers is more compact, so the code is smaller, and can be fetched faster if it uses registers rather than memory. However, the number of registers is limited. Therefore, when the compiler is translating code to machine-language, it must decide how to allocate variables to the limited number of registers in the CPU.

Not all variables are in use (or "live") at the same time, so, over the lifetime of a program, a given register may be used to hold different variables. However, two variables in use at the same time cannot be assigned to the same register without corrupting one of the variables. If there are not enough registers to hold all the variables, some variables may be moved to and from RAM. This process is called "spilling" the registers. Over the lifetime of a program, a variable can be both spilled and stored in registers: this variable is then considered as "split". Accessing RAM is significantly slower than accessing registers and so a compiled program runs slower. Therefore, an optimizing compiler aims to assign as many variables to registers as possible. A high "Register pressure" is a technical term that means that more spills and reloads are needed; it is defined by Braun et al. as "the number of simultaneously live variables at an instruction".

In addition, some computer designs cache frequently-accessed registers. So, programs can be further optimized by assigning the same register to a source and destination of a move instruction whenever possible. This is especially important if the compiler is using an intermediate representation such as static single-assignment form (SSA). In particular, when SSA is not fully optimized it can artificially generate additional move instructions.

Components of register allocation

Register allocation consists therefore of choosing where to store the variables at runtime, i.e. inside or outside registers. If the variable is to be stored in registers, then the allocator needs to determine in which register(s) this variable will be stored. Eventually, another challenge is to determine the duration for which a variable should stay at the same location.

A register allocator, disregarding the chosen allocation strategy, can rely on a set of core actions to address these challenges. These actions can be gathered in several different categories:

Move insertion
This action consists of increasing the number of move instructions between registers, i.e. make a variable live in different registers during its lifetime, instead of one. This occurs in the split live range approach.
Spilling
This action consists of storing a variable into memory (primary storage like RAM) instead of registers.
Assignment
This action consists of assigning a register to a variable.
Coalescing
This action consists of limiting the number of moves between registers, thus limiting the total number of instructions. For instance, by identifying a variable live across different methods, and storing it into one register during its whole lifetime.

Many register allocation approaches optimize for one or more specific categories of actions.

Common problems raised in register allocation

Register allocation raises several problems that can be tackled (or avoided) by different register allocation approaches. Three of the most common problems are identified as follows:

Aliasing
In some architectures, assigning a value to one register can affect the value of another: this is called aliasing. For example, the x86 architecture has four general purpose 32-bit registers that can also be used as 16-bit or 8-bit registers. In this case, assigning a 32-bit value to the eax register will affect the value of the al register.
Pre-coloring
This problem is an act to force some variables to be assigned to particular registers. For example, in PowerPC calling conventions, parameters are commonly passed in R3-R10 and the return value is passed in R3.
NP-Problem
Chaitin et al. showed that optimal register allocation is an NP-complete problem. This NP-completeness is entirely dependent upon exactly how the problem is structured. It has been shown that for programs in SSA form, the graph coloring portion of the register allocation problem can be solved in linear time. What causes the general graph coloring problem to be NP-complete and what causes some versions of the register allocation problem to be NP-complete are distinct.

Register allocation techniques

Register allocation can happen over a basic block of code: it is said to be "local", and was first mentioned by Horwitz et al. As basic blocks do not contain branches, the allocation process is thought to be fast, because the management of control-flow graph merge points in register allocation reveals itself a time-consuming operation. However, this approach is thought not to produce as optimized code as the "global" approach, which operates over the whole compilation unit (a method or procedure for instance).

Graph-coloring allocation

Graph-coloring allocation is the predominant approach to solve register allocation. It was first proposed by Chaitin et al. In this approach, nodes in the graph represent live ranges (variables, temporaries, virtual/symbolic registers) that are candidates for register allocation. Edges connect live ranges that interfere, i.e., live ranges that are simultaneously live at at least one program point. Register allocation then reduces to the graph coloring problem in which colors (registers) are assigned to the nodes such that two nodes connected by an edge do not receive the same color.

Using liveness analysis, an interference graph can be built. The interference graph, which is an Interval graph where the nodes are the program's variables, is used to model which variables cannot be allocated to the same register.

Principle

The main phases in a Chaitin-style graph-coloring register allocator are:

  1. Renumber: discover live range information in the source program.
  2. Build: build the interference graph.
  3. Coalesce: merge the live ranges of non-interfering variables related by copy instructions.
  4. Spill cost: compute the spill cost of each variable. This assesses the impact of mapping a variable to memory on the speed of the final program.
  5. Simplify: construct an ordering of the nodes in the inferences graph
  6. Spill Code: insert spill instructions, i.e. loads and stores to commute values between registers and memory.
  7. Select: assign a register to each variable.

The Simplify step is particularly important. Let the number of available registers be . The simplify step notices that a node of degree strictly less than can always be colored, no matter the coloring of its neighbours. Therefore, the simplify step iteratively removes variables of degree less than . When none remain, a variable is chosen to be removed (making it a spill candidate) and hopefully increasing the number of variables with degree less than .

Drawbacks and further improvements

The graph-coloring allocation has three major drawbacks. First, it relies on graph-coloring, which is an NP-complete problem, to decide which variables are spilled. Although finding a minimal coloring for general graphs is indeed an NP-complete problem, minimal coloring of Interval graphs (including interference graphs) can be done in linear time (see Linear scan below); Therefore, this technique does not full utilize the problem's assumptions. Second, unless live-range splitting is used, evicted variables are spilled everywhere: store instructions are inserted as early as possible, i.e., just after variable definitions; load instructions are respectively inserted late, just before variable use. Third, a variable that is not spilled is kept in the same register throughout its whole lifetime.

On the other hand, a single register name may appear in multiple register classes, where a class is a set of register names that are interchangeable in a particular role. Then, multiple register names may be aliases for a single hardware register. Finally, graph coloring is an aggressive technique for allocating registers, but is computationally expensive due to its use of the interference graph, which can have a worst-case size that is quadratic in the number of live ranges. The traditional formulation of graph-coloring register allocation implicitly assumes a single bank of non-overlapping general-purpose registers and does not handle irregular architectural features like overlapping registers pairs, special purpose registers and multiple register banks.

One later improvement of Chaitin-style graph-coloring approach was found by Briggs et al.: it is called conservative coalescing. This improvement adds a criterion to decide when two live ranges can be merged. Mainly, in addition to the non-interfering requirements, two variables can only be coalesced if their merging will not cause further spilling. Briggs et al. introduces a second improvement to Chaitin's works which is biased coloring. Biased coloring tries to assign the same color in the graph-coloring to live range that are copy related.


Partitioned Boolean Quadratic Programming

The traditional formulation of graph coloring register allocation is best applied to orthogonal instruction set. Modern processors use highly non-orthogonal ISAs such as x86-64 or ARM, causing poor performance when using Chaitin-Briggs style register allocation. In response to this problem, Partitioned Boolean Quadratic Programming (PBQP) was developed. PBQP attempts to unify constraints imposed by non-orthogonal architectures under a unified representation, finding better allocations for non-orthogonal architectures. The major drawbacks of PBQP are its inability to cleanly encode live-range splitting, as well as its running time: Like Chaitin-Briggs allocation, it uses a graph which is worst-case quadratic in the number of virtual registers, and is also NP-hard in general.

Formulation

Similar to graph coloring register allocation, PBQP uses a graph to represent the input problem. It then associates cost matrices with every edge in the graph and cost vectors with every vertex in the graph. Assuming that registers are available in the ISA, the cost matrices have dimension (in practice different variables have different register domains, but we keep this assumption for simplicity) where represents the marginal cost of allocating virtual register to allocation option and virtual register to allocation option . The cost vectors have size , where represents the cost of allocating virtual register to allocation option . Note the dimension, which is due to the option of spilling. Together, these two cost representations are used to encode the constraints/costs imposed by a non-orthogonal ISA. Some examples of how to encode non-orthogonality using this representation follow:

Interference

Just like graph-coloring, PBQP also needs to disallow coloring two interfering virtual registers with the same, or overlapping, allocation options. ie if we take two virtual registers , which interfere, then , where and are the same register, or and are overlapping registers.

Class Constraints

Certain virtual registers may only be colorable with certain allocation options. For example, a 32-bit virtual register cannot go in r8b. This is accomplished by setting , where is an offending allocation option.

Copy Coalescing

Let , be two registers which have a mov instruction from one to the other. In this situation, it may be desirable to assign and to the same allocation option so that the move instruction can be elided. In this case where is some negative number determined by the loop nesting, and number of mov instructions between and .

Special Purpose Registers

Let be a virtual register. For ISA-specific reasons, it may be required to color with a specific allocation option (For example, may be used as a function parameter, function return value, or the rax argument to x64's single-operand IMUL instruction). Then we can set to require this allocation. A similar procedure can be followed when given allocations for are merely desirable.

All of the above factors should be summed into a single cost matrix for each edge, and a single cost vector for each vertex.

Solving PBQP Problems

Just like graph-coloring based allocation, PBQP solvers rely on the fact that in practice, many real programs generate PBQP graphs with low degree vertices. PBQP applies reduction rules to these low-degree vertices, removing them from the graph. This creates a cascading effect where previously high-degree vertices have their neighbours removed, and their degree decreased, resulting in them also being removed from the graph. If no low-degree vertices remain, PBQP solvers can apply heuristics to remove vertices. After many such reductions, every vertex will be disconnected, and the PBQP problem becomes trivial. The greedy solution is then selected, and the solution for the full problem can be reconstructed from the solution to the trivially reduced one. The description of the reduction rules and heuristics follows:

Degree-1 Reduction (RI)

Degree-1 reduction is applied to vertices which have exactly 1 outgoing edge. Take a vertex which has a single neighbour . Notice that for a given allocation of virtual register to allocation option , the optimal allocation of can be found via the following expression: . The procedure for Degree-1 reduction is then: loop over each possible choice of . Update . Delete vertex and its edge to vertex . Push vertex onto the stack for later reconstruction of the solution.

Degree-2 Reduction (RII)

This reduction applies to vertices with a degree of exactly two. Take a vertex with neighbours and . Notice that for a given allocation of virtual registers and to allocation options and respectively, there is an optimal allocation for given by . Degree-2 reduction is then performed by: Create a new edge between vertices and if it does not exist already. The new edge should have a cost matrix consisting of all 0 entries. loop over each of combinations of allocations to and . Set . Delete vertex . Delete the edges from vertex to vertices and . Push vertex onto the stack for later reconstruction.

Degree- Reduction (RN)

Lastly, if no vertices of degree one or two remain, then degree- reduction must be used. This reduction relies on heuristics, and breaks the optimality guarantee. In Degree- reduction, a vertex is chosen, and a heuristic is used to make a preliminary allocation for that vertex. This preliminary allocation is then used (with some further modifications) to update the cost vectors of adjacent vertices. Finally, the selected vertex is deleted along with its edges, and pushed on the stack. The heuristics used for ordering of RN reduction, and modification of cost have a significant effect on the resulting allocation.

An example set of heuristics is presented: First, the vertex with minimum spill cost/degree ratio is chosen to be reduced. Second, we estimate the cost for a given allocation option n of virtual register by assuming that we can optimally choose the cost of adjacent vertices. ie define . Because this is a preliminary selection, we do not want our allocation of to overconstrain neighbours, so we set relevant and select . Next, for a given define a modified and update . The intention of this modification is again to ensure that our preliminary choices for do not overconstrain adjacent vertices.

Reconstruction

After the PBQP problem has been reduced such that all vertices are of trivial degree, the solution can be reconstructed. First, allocate every remaining vertex to allocation option . Finally, iteratively pop vertices off the stack constructed during reduction. At each step, add the vertex back to the graph, along with its edges, and make a greedy choice for the new vertex's allocation. This greedy allocation uses the same method as outlined in the reduction rules above.

Branch and Bound

Even in the presence of tuned RN heuristics, it is useful to have a method which obtains optimal allocations on PBQP problems where RN reduction is required. To solve this problem, notice that the general optimization technique of Branch and bound can be applied to PBQP. Sub-problems of a PBQP are non-trivial subgraphs produced after only RI and RII reductions have been applied. The children of a subproblem represent the problems obtained after choosing a vertex to branch on, making different allocations to , and reducing the resulting problems. To find lower and upper bounds for a PBQP problem, note that exactly one element from each cost vector and cost matrix can contribute to the problem's final cost. Therefore, the upper bound . The lower bound is defined similarly. After this, the normal branch-and-bound procedure can be followed: Initialize a global upper bound to , and a priority queue of subproblems keyed on lower bound initially containing the reduced input problem. Iteratively dequeue the node with the smallest lower bound, compute its children (along with their bounds), update the global upper bound and current solution (if any of the children are trivial), insert the non-trivial children, and continue. If the dequeued node has a lower bound exceeding the upper bound, or if the queue is empty, then the algorithm can be terminated.

Linear scan

Linear scan is another global register allocation approach. It was first proposed by Poletto et al. in 1999. In this approach, the code is not turned into a graph. Instead, all the variables are linearly scanned to determine their live range, represented as an interval. Once the live ranges of all variables have been figured out, the intervals are traversed chronologically. Although this traversal could help identifying variables whose live ranges interfere, no interference graph is being built and the variables are allocated in a greedy way.

The motivation for this approach is speed; not in terms of execution time of the generated code, but in terms of time spent in code generation. Typically, the standard graph coloring approaches produce quality code, but have a significant overhead, the used graph coloring algorithm having a quadratic cost. Owing to this feature, linear scan is the approach currently used in several JIT compilers, like the Hotspot client compiler, V8, Jikes RVM, and the Android Runtime (ART). The Hotspot server compiler uses graph coloring for its superior code.

Pseudocode

This describes the algorithm as first proposed by Poletto et al., where:

  • R is the number of available registers.
  • active is the list, sorted in order of increasing end point, of live intervals overlapping the current point and placed in registers.
LinearScanRegisterAllocation
    active ← {}
    for each live interval i, in order of increasing start point do
        ExpireOldIntervals(i)
        if length(active) = R then
            SpillAtInterval(i)
        else
            register[i] ← a register removed from pool of free registers
            add i to active, sorted by increasing end point

ExpireOldIntervals(i)
    for each interval j in active, in order of increasing end point do
        if endpoint[j] ≥ startpoint[i] then
            return 
        remove j from active
        add register[j] to pool of free registers

SpillAtInterval(i)
    spill ← last interval in active
    if endpoint[spill] > endpoint[i] then
        register[i] ← register[spill]
        location[spill] ← new stack location
        remove spill from active
        add i to active, sorted by increasing end point
    else
        location[i] ← new stack location

Drawbacks and further improvements

However, the linear scan presents two major drawbacks. First, due to its greedy aspect, it does not take lifetime holes into account, i.e. "ranges where the value of the variable is not needed". Besides, a spilled variable will stay spilled for its entire lifetime.

Many other research works followed up on the Poletto's linear scan algorithm. Traub et al., for instance, proposed an algorithm called second-chance binpacking aiming at generating code of better quality. In this approach, spilled variables get the opportunity to be stored later in a register by using a different heuristic from the one used in the standard linear scan algorithm. Instead of using live intervals, the algorithm relies on live ranges, meaning that if a range needs to be spilled, it is not necessary to spill all the other ranges corresponding to this variable.

Linear scan allocation was also adapted to take advantage from the SSA form: the properties of this intermediate representation simplify the allocation algorithm and allow lifetime holes to be computed directly. First, the time spent in data-flow graph analysis, aimed at building the lifetime intervals, is reduced, namely because variables are unique. It consequently produces shorter live intervals, because each new assignment corresponds to a new live interval. To avoid modeling intervals and liveness holes, Rogers showed a simplification called future-active sets that successfully removed intervals for 80% of instructions.

Rematerialization

Coalescing

In the context of register allocation, coalescing is the act of merging variable-to-variable move operations by allocating those two variables to the same location. The coalescing operation takes place after the interference graph is built. Once two nodes have been coalesced, they must get the same color and be allocated to the same register, once the copy operation becomes unnecessary.

Doing coalescing might have both positive and negative impacts on the colorability of the interference graph. For example, one negative impact that coalescing could have on graph inference colorability is when two nodes are coalesced, as the result node will have a union of the edges of those being coalesced. A positive impact of coalescing on inference graph colorability is, for example, when a node interferes with both nodes being coalesced, the degree of the node is reduced by one which leads to improving the overall colorability of the interference graph.

There are several coalescing heuristics available:

Aggressive coalescing
It was first introduced in Chaitin's original register allocator. This heuristic aims at coalescing any non-interfering, copy-related nodes. From the perspective of copy elimination, this heuristic has the best results. On the other hand, aggressive coalescing could impact the colorability of the inference graph.
Conservative Coalescing
It mainly uses the same heuristic as aggressive coalescing but it merges moves if, and only if, it does not compromise the colorability of the interference graph.
Iterated coalescing
It removes one particular move at the time, while keeping the colorability of the graph.
Optimistic coalescing
It is based on aggressive coalescing, but if the inference graph colorability is compromised, then it gives up as few moves as possible.

Mixed approaches

Hybrid allocation

Some other register allocation approaches do not limit to one technique to optimize register's use. Cavazos et al., for instance, proposed a solution where it is possible to use both the linear scan and the graph coloring algorithms. In this approach, the choice between one or the other solution is determined dynamically: first, a machine learning algorithm is used "offline", that is to say not at runtime, to build a heuristic function that determines which allocation algorithm needs to be used. The heuristic function is then used at runtime; in light of the code behavior, the allocator can then choose between one of the two available algorithms.

Trace register allocation is a recent approach developed by Eisl et al. This technique handles the allocation locally: it relies on dynamic profiling data to determine which branches will be the most frequently used in a given control flow graph. It then infers a set of "traces" (i.e. code segments) in which the merge point is ignored in favor of the most used branch. Each trace is then independently processed by the allocator. This approach can be considered as hybrid because it is possible to use different register allocation algorithms between the different traces.

Split allocation

Split allocation is another register allocation technique that combines different approaches, usually considered as opposite. For instance, the hybrid allocation technique can be considered as split because the first heuristic building stage is performed offline, and the heuristic use is performed online. In the same fashion, B. Diouf et al. proposed an allocation technique relying both on offline and online behaviors, namely static and dynamic compilation. During the offline stage, an optimal spill set is first gathered using Integer Linear Programming. Then, live ranges are annotated using the compressAnnotation algorithm which relies on the previously identified optimal spill set. Register allocation is performed afterwards during the online stage, based on the data collected in the offline phase.

In 2007, Bouchez et al. suggested as well to split the register allocation in different stages, having one stage dedicated to spilling, and one dedicated to coloring and coalescing.

Comparison between the different techniques

Several metrics have been used to assess the performance of one register allocation technique against the other. Register allocation has typically to deal with a trade-off between code quality, i.e. code that executes quickly, and analysis overhead, i.e. the time spent determining analyzing the source code to generate code with optimized register allocation. From this perspective, execution time of the generated code and time spent in liveness analysis are relevant metrics to compare the different techniques.

Once relevant metrics have been chosen, the code on which the metrics will be applied should be available and relevant to the problem, either by reflecting the behavior of real-world application, or by being relevant to the particular problem the algorithm wants to address. The more recent articles about register allocation uses especially the Dacapo benchmark suite.

Adapted from the Wikipedia article, CC BY-SA 4.0. Continue on Wikipedia

Go deeper

Ideas this article links to.