Computer Science · Book 5 · Bachelor Year 3

University Computer Science — Year 3

University Computer Science — Year 3 · Bachelor Year 3

8Program Analysis and Optimisation

The compiler of chapter 7 is correct and slow: every temporary lives in memory, every copy is executed, and a constant computed at compile time by a reader is computed at run time by the machine. This chapter makes it faster without making it wrong. Every optimisation rests on a fact about the program that holds on all its executions, such as “this temporary is never read again” or “this temporary always holds 42”, and such facts are computed by one method: a system of equations over the control-flow graph, solved as a fixed point. With them the chapter removes useless work from the three-address code, then gives the temporaries registers by colouring a graph, and counts on rv what each step saves.

8.1 Dataflow analysis as a fixed point

Take the question “which temporaries may still be read later?” at every point of a function. A temporary is needed before an instruction if the instruction reads it, or if it is needed after the instruction and the instruction does not overwrite it. After a block, it is needed if it is needed at the start of some successor. These are equations, one pair per block, and a loop makes them circular: what is needed at the end of the loop body depends on what is needed at its top, which depends on the body. The equations are solved by starting from “nothing is needed” and applying them until nothing changes. Why this ends, and why it ends at the right answer, is a theorem about ordered sets.

You already know

A partial order ⊑\sqsubseteq on a set is reflexive, antisymmetric and transitive. An upper bound of two elements is above both; their least upper bound, when it exists, is below every other upper bound.

Definition 8.1 (Dataflow lattice, height)

A dataflow lattice is a set of facts LL with a partial order ⊑\sqsubseteq, read “is at most as informative a claim as”, in which every two facts x,yx, y have a least upper bound x⊔yx \sqcup y, their join, and which has a least element ⊥\bot. Its height is the largest number of strict steps in a chain x0⊏x1⊏⋯⊏xhx_0 \sqsubset x_1 \sqsubset \dots \sqsubset x_h.

For liveness, the facts are sets of temporaries, ordered by inclusion, the join is union and ⊥\bot is the empty set; with mm temporaries the height is mm. For constants, the fact about one temporary is “not yet seen” (⊥\bot), “always the constant kk”, or “not a constant” (⊤\top), a lattice of height 2 however many constants there are (the figure below); for mm temporaries, take one such fact per temporary, height 2m2m.

Two dataflow lattices, smaller elements below. Left: the value of one temporary for constant propagation; two different constants join to , so the height is 2. Right: the sets of three temporaries ordered by inclusion, the lattice of liveness; its height is 3.
Two dataflow lattices, smaller elements below. Left: the value of one temporary for constant propagation; two different constants join to ⊤\top, so the height is 2. Right: the sets of three temporaries ordered by inclusion, the lattice of liveness; its height is 3.

Definition 8.2 (Transfer function, monotone framework)

A transfer function fB:L→Lf_B : L \to L gives the fact at one end of a block BB from the fact at the other: at the end from the start for a forward analysis, at the start from the end for a backward one. It is monotone if x⊑yx \sqsubseteq y implies fB(x)⊑fB(y)f_B(x) \sqsubseteq f_B(y). A monotone framework is a dataflow lattice, a direction, a monotone transfer function per block, and a fact at the boundary (the entry, or the exits). Its equations are in(B)=⨆Pout(P)⊔boundary\mathit{in}(B) = \bigsqcup_{P} \mathit{out}(P) \sqcup \mathit{boundary}, over the blocks PP the facts flow from, and out(B)=fB(in(B))\mathit{out}(B) = f_B(\mathit{in}(B)).

Put all the blocks’ facts in one vector X∈LnX \in L^n, ordered componentwise. The equations say X=F(X)X = F(X) for one function F:Ln→LnF : L^n \to L^n, monotone because joins and the fBf_B are. A solution is a fixed point of FF, and the useful one is the least.

Definition 8.3 (Least fixed point)

A fixed point of FF is an XX with F(X)=XF(X) = X. The least fixed point is a fixed point below every other.

Theorem 8.4 (Fixed points by iteration)

Let FF be monotone on a lattice of finite height hh with least element ⊥\bot. The sequence ⊥,F(⊥),F(F(⊥)),…\bot, F(\bot), F(F(\bot)), \dots is increasing, becomes constant after at most hh strict steps, and its final value is the least fixed point of FF.

Proof. ⊥⊑F(⊥)\bot \sqsubseteq F(\bot) since ⊥\bot is least, and if Fk−1(⊥)⊑Fk(⊥)F^{k-1}(\bot) \sqsubseteq F^{k}(\bot) then monotonicity gives Fk(⊥)⊑Fk+1(⊥)F^{k}(\bot) \sqsubseteq F^{k+1}(\bot): the sequence increases. A strictly increasing chain has at most hh steps, so after at most hh strict steps two consecutive terms are equal, F(X)=XF(X) = X, and the sequence stays there. For leastness, let YY be any fixed point. ⊥⊑Y\bot \sqsubseteq Y, and if Fk(⊥)⊑YF^k(\bot) \sqsubseteq Y then Fk+1(⊥)⊑F(Y)=YF^{k+1}(\bot) \sqsubseteq F(Y) = Y; so X⊑YX \sqsubseteq Y. ∎

Iterating FF on the whole vector recomputes every block when one has changed. The worklist algorithm recomputes only the blocks whose inputs changed: it keeps a queue of blocks, starts with all of them, and when a block’s output changes, it queues the blocks its facts flow to (Listing 8.2). It computes the same least fixed point, since each recomputation is one component of FF applied to a vector below the fixed point, and the values only grow; exercise 8.7 bounds its work. Listing 8.1 is the interface an analysis implements.

/// A monotone framework: a lattice of facts and a transfer function per block.
pub trait Analysis {
    type V: Clone + PartialEq;
    fn dir(&self) -> Dir;
    fn bottom(&self) -> Self::V; // the starting value of every block
    fn boundary(&self) -> Self::V; // the fact at the entry (forward) or an exit (backward)
    fn join(&self, a: &Self::V, b: &Self::V) -> Self::V;
    fn transfer(&self, block: usize, x: &Self::V) -> Self::V;
}
Listing 8.1. A monotone framework as a Rust trait: the lattice (its least element and join), the direction, the boundary and the transfer function. code/bachelor-3/08-program-optimisation/listings/dataflow.rs
pub fn solve<A: Analysis>(a: &A, g: &Cfg) -> Solution<A::V> {
    let (n, p, dir) = (g.blocks.len(), preds(g), a.dir());
    // inn: the side facts flow in from; out: the side the transfer produces
    let (mut inn, mut out) = (vec![a.bottom(); n], vec![a.bottom(); n]);
    let mut work: VecDeque<usize> = (0..n).collect();
    let mut queued = vec![true; n];
    let mut visits = 0;
    while let Some(b) = work.pop_front() {
        queued[b] = false;
        visits += 1;
        let (from, to) = match dir {
            Dir::Forward => (&p[b], &g.succ[b]),
            Dir::Backward => (&g.succ[b], &p[b]),
        };
        let at_boundary = if dir == Dir::Forward { b == 0 } else { g.succ[b].is_empty() };
        let mut x = if at_boundary { a.boundary() } else { a.bottom() };
        for &s in from {
            x = a.join(&x, &out[s]);
        }
        let y = a.transfer(b, &x);
        inn[b] = x;
        if y != out[b] {
            out[b] = y;
            for &m in to {
                if !queued[m] {
                    queued[m] = true;
                    work.push_back(m);
                }
            }
        }
    }
    match dir {
        Dir::Forward => Solution { before: inn, after: out, visits },
        Dir::Backward => Solution { before: out, after: inn, visits },
    }
}
Listing 8.2. The worklist algorithm, for both directions. A block is queued again only when a fact it reads has changed. code/bachelor-3/08-program-optimisation/listings/dataflow.rs

8.1.1 Liveness and reaching definitions

Definition 8.5 (Live temporary)

A temporary is live at a point if some path from that point reads it before writing it. Liveness is the backward analysis whose facts are sets of temporaries, joined by union, with the empty set at the exits, and livebefore(i)=uses(i)∪(liveafter(i)∖def(i))\mathit{live}_{\mathrm{before}}(i) = \mathit{uses}(i) \cup (\mathit{live}_{\mathrm{after}}(i) \setminus \mathit{def}(i)) for each instruction ii.

The transfer function of a block applies this rule to its instructions from the last to the first (Listing 8.3). It is monotone, since a larger set after gives a larger set before. Output 8.1 runs it on the function sumsq of loop.moor, a sum of squares; the solution took 12 visits for 6 blocks, two passes over a loop.

/// live before i = uses(i) + (live after i - def(i))
pub fn step(i: &Tac, after: &Set) -> Set {
    let mut s = after.clone();
    if let Some(d) = def(i) {
        s.remove(&d);
    }
    s.extend(uses(i));
    s
}

pub struct Liveness<'a> {
    pub code: &'a [Tac],
    pub g: &'a Cfg,
}

impl Analysis for Liveness<'_> {
    type V = Set;
    fn dir(&self) -> Dir { Dir::Backward }
    fn bottom(&self) -> Set { Set::new() }
    fn boundary(&self) -> Set { Set::new() } // nothing is live after a return
    fn join(&self, a: &Set, b: &Set) -> Set { a.union(b).copied().collect() }
    fn transfer(&self, b: usize, out: &Set) -> Set {
        let (s, e) = self.g.blocks[b];
        self.code[s..e].iter().rev().fold(out.clone(), |live, i| step(i, &live))
    }
}
Listing 8.3. Liveness: one instruction, then a block, read backwards. code/bachelor-3/08-program-optimisation/listings/liveness.rs
$ rustc --edition 2021 -O -o live_demo live_demo.rs && ./live_demo loop.moor
B0  live in {n}
        s = 0
        i = 0
    live out {n, s, i}
B1  live in {n, s, i}
        L1:
        if i < n goto L2
    live out {n, s, i}
B2  live in {s}
        goto L3
    live out {s}
B3  live in {n, s, i}
        L2:
        t3 = i * i
        sq = t3
        t5 = s + sq
        s = t5
        t6 = i + 1
        i = t6
        goto L1
    live out {n, s, i}
B4  live in {s}
        L3:
        return s
    live out {}
B5  live in {}
        return
    live out {}
6 blocks, 12 visits
Output 8.1. The temporaries live at the start and at the end of each block of sumsq. n, s and i stay live around the loop; inside the body, t3, sq, t5 and t6 each live for one instruction.
The control-flow graph of sumsq with the live sets of  in red, at the start of the function and after each block. The unreachable final return is not drawn.
The control-flow graph of sumsq with the live sets of Output 8.1 in red, at the start of the function and after each block. The unreachable final return is not drawn.

Definition 8.6 (Reaching definition)

A definition is an instruction that writes a temporary. It reaches a point if some path from it to that point writes the same temporary nowhere else. Reaching definitions are a forward analysis on sets of instructions, joined by union: an instruction that writes tt adds itself and removes the other definitions of tt.

reaching.rs implements it in twenty lines with the same trait. At the top of the loop of sumsq, the definitions that reach are s=0s = 0 and i=0i = 0 from the entry and the six of the loop body, which come round the back edge (test reaching_definitions_of_the_loop). Two definitions of i reach the test i < n: from the entry and from the body. The next section gives each of them its own name.

8.2 Static single assignment

Most temporaries of chapter 7 are written once, by construction. The exceptions are the variables, which every assignment writes again. An analysis about a variable must then ask which assignment it is talking about at each point, which is what reaching definitions answer, at the price of a set per point. A form in which every temporary has one definition makes the question vanish: the name tells the definition.

Definition 8.7 (Static single assignment, phi-function)

A function is in static single assignment form if every temporary has exactly one definition in its text. Where definitions of one variable from different paths meet, at the start of a block, a ϕ\phi-function x3=ϕ(B1: x1,B2: x2)x_3 = \phi(B_1{:}\,x_1, B_2{:}\,x_2) defines a new name whose value is x1x_1 if control came from B1B_1 and x2x_2 if it came from B2B_2.

The question is where to put the ϕ\phi-functions. Everywhere two paths join would do, and would put far too many. The right places are given by dominance.

Definition 8.8 (Dominator, dominance frontier)

A block dd dominates a block bb if every path from the entry to bb passes through dd; every block dominates itself, and dd strictly dominates bb if moreover d≠bd \ne b. The immediate dominator of b≠b \ne entry is the strict dominator of bb that every other strict dominator of bb dominates. The dominance frontier DF(x)\mathrm{DF}(x) is the set of blocks yy such that xx dominates a predecessor of yy but does not strictly dominate yy. For a set SS, DF+(S)\mathrm{DF}^{+}(S) is the limit of S1=DF(S)S_1 = \mathrm{DF}(S), Sk+1=DF(S∪Sk)S_{k+1} = \mathrm{DF}(S \cup S_k), the iterated frontier.

The dominators of bb are its own set plus those common to all its predecessors: Dom(b)={b}∪⋂pDom(p)\mathrm{Dom}(b) = \{b\} \cup \bigcap_{p} \mathrm{Dom}(p), with Dom(entry)={entry}\mathrm{Dom}(\mathrm{entry}) = \{\mathrm{entry}\}. This is again a fixed point, a forward analysis whose join is intersection, started from “all blocks” (Listing 8.4). The dominators of a block form a chain, each dominating the next, so they are a path in a tree, the dominator tree, in which each block’s parent is its immediate dominator. The frontiers are computed by walking up that tree from each predecessor of a join (Listing 8.5).

/// Dom(b): the blocks on every path from the entry to b. Iterate
/// Dom(b) = {b} + intersection of Dom(p) over the predecessors p, from "all".
pub fn dominators(g: &Cfg) -> Vec<BTreeSet<usize>> {
    let (n, p, live) = (g.blocks.len(), preds(g), reachable(g));
    let all: BTreeSet<usize> = (0..n).filter(|&b| live[b]).collect();
    let mut dom: Vec<BTreeSet<usize>> = (0..n)
        .map(|b| {
            if b == 0 {
                [0].into()
            } else if live[b] {
                all.clone()
            } else {
                [].into()
            }
        })
        .collect();
    let mut changed = true;
    while changed {
        changed = false;
        for b in 1..n {
            if !live[b] {
                continue;
            }
            let mut d = all.clone();
            for &q in p[b].iter().filter(|&&q| live[q]) {
                d = d.intersection(&dom[q]).copied().collect();
            }
            d.insert(b);
            if d != dom[b] {
                dom[b] = d;
                changed = true;
            }
        }
    }
    dom
}
Listing 8.4. Dominators by iteration. Unreachable blocks are left out: no path reaches them, so nothing dominates them. code/bachelor-3/08-program-optimisation/listings/ssa.rs
/// DF(x): the blocks y such that x dominates a predecessor of y but not y strictly.
pub fn frontiers(g: &Cfg, idom: &[Option<usize>]) -> Vec<BTreeSet<usize>> {
    let (p, live) = (preds(g), reachable(g));
    let mut df = vec![BTreeSet::new(); g.blocks.len()];
    for y in (0..g.blocks.len()).filter(|&y| live[y]) {
        for &q in p[y].iter().filter(|&&q| live[q]) {
            let mut runner = Some(q);
            while let Some(r) = runner {
                if Some(r) == idom[y] {
                    break;
                }
                df[r].insert(y);
                runner = idom[r];
            }
        }
    }
    df
}

/// Where phi-functions go: the iterated frontier of the blocks that define v.
pub fn phi_blocks(defs: &BTreeSet<usize>, df: &[BTreeSet<usize>]) -> BTreeSet<usize> {
    let (mut placed, mut work): (BTreeSet<usize>, Vec<usize>) =
        (BTreeSet::new(), defs.iter().copied().collect());
    while let Some(x) = work.pop() {
        for &y in &df[x] {
            if placed.insert(y) && !defs.contains(&y) {
                work.push(y);
            }
        }
    }
    placed
}
Listing 8.5. Dominance frontiers, and the iterated frontier of a set of blocks, where ϕ\phi-functions go. code/bachelor-3/08-program-optimisation/listings/ssa.rs

Lemma 8.9 (Leaving dominance)

Let x=u0,u1,…,uk=yx = u_0, u_1, \dots, u_k = y be a path. If xx does not strictly dominate yy, some uiu_i with i≥1i \ge 1 is in DF(x)\mathrm{DF}(x).

Proof. Let i≥1i \ge 1 be the least index such that xx does not strictly dominate uiu_i; it exists since uk=yu_k = y qualifies. Then xx dominates ui−1u_{i-1}: either i−1=0i - 1 = 0 and u0=xu_0 = x, or xx strictly dominates ui−1u_{i-1} by the choice of ii. So xx dominates a predecessor of uiu_i and does not strictly dominate uiu_i: ui∈DF(x)u_i \in \mathrm{DF}(x). ∎

Theorem 8.10 (Placing phi-functions)

Let SS be the blocks that define a variable vv, the entry included if vv is a parameter, and place a ϕ\phi-function for vv at the start of every block of DF+(S)\mathrm{DF}^{+}(S). Then (a) at every use of vv, the last definition of vv (an original one or a ϕ\phi) is the same on every path from the entry, and its block dominates the use. (b) Every ϕ\phi placed this way is at a block where two paths from different definitions of vv first meet: none is placed where only one definition can arrive. Some may still be placed where vv is dead, and those can be left out without losing (a); pruned SSA leaves them out (Exercise 8.9).

Proof. We prove (a); (b) is admitted. Let D=S∪DF+(S)D = S \cup \mathrm{DF}^{+}(S), the blocks where vv is defined once the ϕ\phi-functions are placed. DD is closed under frontiers: DF(D)⊆D\mathrm{DF}(D) \subseteq D, by the construction of the limit. Take a use of vv in block yy, after any definition of vv in yy (otherwise treat the start of yy the same way), and a path π\pi from the entry to yy. Let xx be the last block of DD on π\pi, yy included; it exists, since vv is defined before it is used. If x≠yx \ne y and xx did not strictly dominate yy, Lemma 8.9 applied to the part of π\pi from xx to yy would give a later block of DF(x)⊆D\mathrm{DF}(x) \subseteq D on π\pi, contradicting the choice of xx. So xx dominates yy.

Let x′x' be the last block of DD on another path π′\pi'. Both dominate yy, so one dominates the other; suppose xx strictly dominates x′x'. Since x′x' does not dominate xx, some path from the entry to xx avoids x′x'. Follow it, then the part of π\pi after its last visit to xx: that part contains no block of DD but xx, so it avoids x′x' too, and the whole is a path from the entry to yy that avoids x′x', which contradicts x′x' dominating yy. So x=x′x = x': every path reaches the use through the same last definition. ∎

Renaming then walks the dominator tree from the entry, with a stack of current names per variable: a definition pushes a fresh name, a use takes the name on top, and on the way out of a block the stacks are popped back. Before leaving a block, the walk fills in the arguments of the ϕ\phi-functions of its successors with the names current at its end. Output 8.2 shows the result for sumsq: s and i are each assigned twice, so each gets a ϕ\phi at the loop’s header, B1, which is the frontier of the body B3. The temporaries written once keep their names.

$ rustc --edition 2021 -O -o ssa_demo ssa_demo.rs && ./ssa_demo loop.moor
B0  dom {B0}  idom -  frontier {}
B1  dom {B0, B1}  idom B0  frontier {B1}
B2  dom {B0, B1, B2}  idom B1  frontier {}
B3  dom {B0, B1, B3}  idom B1  frontier {B1}
B4  dom {B0, B1, B2, B4}  idom B2  frontier {}
SSA form, 2 phi-functions:
B0
    s.0 = 0
    i.0 = 0
B1
    L1:
    s.1 = phi(B0: s.0, B3: s.2)
    i.1 = phi(B0: i.0, B3: i.2)
    if i.1 < n goto L2
B2
    goto L3
B3
    L2:
    t3 = i.1 * i.1
    sq = t3
    t5 = s.1 + sq
    s.2 = t5
    t6 = i.1 + 1
    i.2 = t6
    goto L1
B4
    L3:
    return s.1
Output 8.2. Dominators, immediate dominators and frontiers of sumsq, then its SSA form. Names are numbered from 0 per variable.
The dominator tree of sumsq (solid), each block below its immediate dominator, and the two non-empty frontiers (dashed). s and i are defined in B0 and B3; the iterated frontier of these blocks is B1, the loop’s header.
The dominator tree of sumsq (solid), each block below its immediate dominator, and the two non-empty frontiers (dashed). s and i are defined in B0 and B3; the iterated frontier of these blocks is B1, the loop’s header.

SSA is how optimising compilers hold a program between their passes: an analysis about a name is an analysis about one definition, and many of the analyses of the next section become a single pass. The program in this chapter stays in three-address code and uses the dataflow equations; the SSA form is computed and printed, and the exercises use it.

8.3 The classic optimisations

An optimisation is a transformation of the code that keeps its meaning, in the sense of chapter 7: on every input on which the original program terminates normally, the transformed one prints the same and exits with the same code. Each one below is justified by a fact computed by a dataflow analysis, and the fact is what the proof needs.

Definition 8.11 (Constant propagation)

Constant propagation is the forward analysis whose fact at each point maps each temporary to ⊥\bot, a constant kk, or ⊤\top, joined pointwise in the lattice of the figure above; the parameters are ⊤\top at the entry. Its transformation replaces a use of a temporary by kk where the fact says kk, computes at compile time an operation whose operands are constants (constant folding), and replaces a branch whose outcome is then known by a jump or by nothing.

/// The value lattice of one temporary: Undef < Const(k) < Nac (not a constant).
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Cv {
    Undef,
    Const(i32),
    Nac,
}

pub fn meet(a: Cv, b: Cv) -> Cv {
    match (a, b) {
        (Cv::Undef, x) | (x, Cv::Undef) => x,
        (Cv::Const(x), Cv::Const(y)) if x == y => a,
        _ => Cv::Nac,
    }
}
Listing 8.6. The lattice of one temporary, and its join, called meet by tradition. code/bachelor-3/08-program-optimisation/listings/opt.rs
/// Uses replaced by known constants, constant operations folded, and branches
/// whose outcome is known replaced by a jump or removed.
pub fn const_prop(f: &mut FuncTac) -> usize {
    let g = cfg::build(f);
    let sol = solve(&ConstProp { f, g: &g }, &g);
    let mut out: Vec<Tac> = vec![];
    for (b, &(s, e)) in g.blocks.iter().enumerate() {
        let mut env = sol.before[b].clone();
        for i in &f.code[s..e] {
            let mut known = |v: Val| match v {
                Val::T(t) => match env.get(&t) {
                    Some(Cv::Const(c)) => Val::K(*c),
                    _ => v,
                },
                k => k,
            };
            let new = match map_uses(i, &mut known) {
                Tac::Bin(d, op, Val::K(x), Val::K(y)) => {
                    Some(Tac::Copy(d, Val::K(fold(op, x, y))))
                }
                Tac::Neg(d, Val::K(x)) => Some(Tac::Copy(d, Val::K(x.wrapping_neg()))),
                Tac::Not(d, Val::K(x)) => Some(Tac::Copy(d, Val::K(1 - x))),
                Tac::Branch(op, Val::K(x), Val::K(y), l) => {
                    (fold(op, x, y) != 0).then_some(Tac::Jump(l))
                }
                other => Some(other),
            };
            env = cp_step(&env, i);
            out.extend(new);
        }
    }
    replace(f, out)
}
Listing 8.7. Constant propagation’s transformation: the facts are recomputed instruction by instruction from the start of each block. code/bachelor-3/08-program-optimisation/listings/opt.rs

Theorem 8.12 (Constant propagation is sound)

If the least fixed point maps tt to the constant kk at a point, then on every execution that reaches that point, tt holds kk there.

Proof. Say a concrete state, a value for each temporary, agrees with a fact if each temporary mapped to a constant holds that constant. By induction on the number of instructions executed, the state at each point agrees with the fact the solution gives there. At the entry, the fact maps only parameters, to ⊤\top, and every state agrees. One instruction: if the state before agrees with the fact before, the state after agrees with the transfer of that fact, because the transfer computes the same operation on the same constants, and gives ⊤\top whenever an operand is not known; folding uses Moor’s 32-bit arithmetic, the interpreter’s. Along an edge, the fact at the target is the join of the facts of its predecessors, so it is above the fact of the edge taken, and a state that agrees with a fact agrees with every fact above it. A temporary mapped to ⊥\bot at a reachable point has not been written on any path to it, and the front end does not let it be read. ∎

Replacing a use by its constant then changes no value, so no output. A branch on two constants always goes the same way, so replacing it by a jump or deleting it changes no path that runs.

Definition 8.13 (Copy propagation, value numbering, dead code)

Copy propagation replaces a use of xx by yy where the copy x=yx = y is available: on every path to the point, it was executed and neither xx nor yy was written since. Value numbering gives each computed value a number, such that two operations with the same operator on operands with the same numbers get the same number; a computation whose value already has a temporary is replaced by a copy of it. An instruction is dead code if it can never run, or if it has no effect but writing a temporary that is not live after it; dead-code elimination removes it.

Available copies are a forward analysis like the others, with one difference: a copy must hold on every path, so the join is intersection, and the least element is “every copy”. opt.rs numbers values within each block only, which is enough to find a * b computed twice in one expression. Listing 8.8 removes dead code, with the liveness of the previous section. Each is proved correct the way constant propagation was: the fact holds on every execution, and under the fact the transformation changes no value that is ever read.

/// Removes the blocks no path reaches, and every instruction without side
/// effect whose result is not live afterwards.
pub fn dead_code(f: &mut FuncTac) -> usize {
    let g = cfg::build(f);
    let live_blocks = reachable(&g);
    let sol = solve(&Liveness { code: &f.code, g: &g }, &g);
    let after = live_after(&f.code, &g, &sol.after);
    let mut out = vec![];
    for (b, &(s, e)) in g.blocks.iter().enumerate() {
        if !live_blocks[b] {
            continue; // unreachable: dropped whole
        }
        for k in s..e {
            let i = &f.code[k];
            let pure = matches!(i, Tac::Bin(..) | Tac::Neg(..) | Tac::Not(..) | Tac::Copy(..)
                                   | Tac::LoadG(..) | Tac::LoadA(..));
            let dead = pure && def(i).is_some_and(|d| !after[k].contains(&d));
            let self_copy = matches!(i, Tac::Copy(d, Val::T(s)) if d == s);
            let jump_to_next =
                matches!(i, Tac::Jump(l) if f.code.get(k + 1) == Some(&Tac::Label(*l)));
            if !(dead || self_copy || jump_to_next) {
                out.push(i.clone());
            }
        }
    }
    replace(f, out)
}
Listing 8.8. Dead-code elimination. A store, a call or a jump is never removed for being dead, since its effect is not a temporary. code/bachelor-3/08-program-optimisation/listings/opt.rs

The passes feed each other. Folding a * 7 with a known to be 6 gives 42; propagating it may decide a branch; the branch removed makes a block unreachable; the block removed makes some temporaries dead; their definitions removed make more temporaries dead. optimise therefore runs the four passes in turn until a round changes nothing, which happens since each pass only removes instructions or replaces operands by constants. Exercise 8.4 predicts the result on a program that folds entirely.

Remark 8.14

The fixed point that constant propagation computes is not the best possible fact. In if c > 0 { a = 2; b = 3; } else { a = 3; b = 2; } x = a + b;, xx is 5 on both paths, yet the join at the end of the if makes a and b both ⊤\top before the addition, and xx is found ⊤\top. Exercise 8.10 shows that this happens because the transfer functions of constant propagation do not distribute over joins.

One more transformation is told and left as exercise 8.12. In while i < 100 { s = s + a * b + i; i = i + 1; }, the product a * b is the same on every iteration, since nothing in the loop writes a or b. Loop-invariant code motion computes it once, before the loop. The dominators give the loops: an edge b→hb \to h such that hh dominates bb is a back edge, and the blocks that can reach bb without passing through hh form, with hh, the loop it closes.

8.4 Register allocation by graph colouring

Definition 8.15 (Register allocation, interference graph)

Register allocation decides, for each temporary, whether it lives in a register, and which, or in memory. Two temporaries interfere if one is written at a point where the other is live and may hold a different value; the interference graph has the temporaries as vertices and an edge between each pair that interferes.

Two temporaries that do not interfere can share a register: wherever one of them holds a value that will be read, the other holds nothing that will. The exception in the definition of interference is for copies: after x = y, the two hold the same value, and sharing a register is harmless, even useful (it makes the copy disappear). Listing 8.9 builds the graph from the live sets after each instruction. The parameters arrive together, in a0, a1, …, so they interfere with each other and with whatever is live at the entry.

/// Two temporaries interfere if one is written while the other is live and
/// holds a different value; the source of a copy does not interfere with its target.
pub fn interference(f: &FuncTac, g: &Cfg) -> Graph {
    let sol = solve(&Liveness { code: &f.code, g }, g);
    let after = live_after(&f.code, g, &sol.after);
    let mut gr = Graph::default();
    for (k, i) in f.code.iter().enumerate() {
        for t in uses(i) {
            gr.node(t);
        }
        if let Some(d) = def(i) {
            gr.node(d);
            for &t in &after[k] {
                if !matches!(i, Tac::Copy(_, Val::T(s)) if *s == t) {
                    gr.edge(d, t);
                }
            }
        }
    }
    let entry: BTreeSet<u32> = sol.before.first().cloned().unwrap_or_default();
    for (n, &p) in f.params.iter().enumerate() {
        // the parameters arrive together
        gr.node(p);
        for &q in f.params[..n].iter().chain(&entry) {
            gr.edge(p, q);
        }
    }
    gr
}
Listing 8.9. The interference graph: each definition against the temporaries live after it, except the source of a copy. code/bachelor-3/08-program-optimisation/listings/regalloc.rs

You already know

The Year 1 volume coloured graphs: a colouring with kk colours gives each vertex one of kk colours so that the two ends of every edge differ. It encoded the question “does a kk-colouring exist?” as a satisfiability problem.

A kk-colouring of the interference graph is an allocation with kk registers. Deciding whether a graph has one is NP-complete for every fixed k≥3k \ge 3, as chapter 17 proves for k=3k = 3; the fewest colours that suffice, the graph’s chromatic number, is as hard to compute. A compiler therefore uses a heuristic, built on one simple fact.

Proposition 8.16 (Simplify)

If a vertex vv of GG has fewer than kk neighbours, then GG is kk-colourable if and only if G−vG - v is.

Proof. A colouring of GG restricts to one of G−vG - v. Conversely, colour G−vG - v; the neighbours of vv use at most k−1k - 1 colours, so one of the kk is free for vv. ∎

Definition 8.17 (Spill)

A spilled temporary lives in a slot of the frame instead of a register, and is loaded before each use and stored after each definition. Its spill cost estimates the memory accesses this adds: here, each use or definition counts 10d10^{d}, with dd the depth of the loops around it.

The allocator (Listing 8.10) repeats the proposition: while some vertex has fewer than kk neighbours, it removes it and pushes it on a stack (simplify). When none has, it removes the vertex with the least spill cost per neighbour and marks it spilled (spill). Then it pops the stack and gives each vertex the lowest colour its already coloured neighbours do not use (select); by the proposition, one is always free. The registers are s0–s11, which a callee must preserve, so a value in one survives calls; each function saves the ones it uses.

pub fn colour(gr: &Graph, k: usize, cost: &BTreeMap<u32, f64>) -> Colouring {
    let mut left: BTreeMap<u32, BTreeSet<u32>> = gr.adj.clone();
    let (mut stack, mut spilled) = (vec![], BTreeSet::new());
    while !left.is_empty() {
        // simplify: a node of degree < k can always be coloured later
        let pick = left.iter().find(|(_, ns)| ns.len() < k).map(|(&t, _)| t);
        let t = pick.unwrap_or_else(|| {
            // spill: the cheapest per neighbour removed
            let weight = |t: &u32| cost.get(t).unwrap_or(&0.0) / left[t].len() as f64;
            let t = *left
                .keys()
                .min_by(|a, b| weight(a).total_cmp(&weight(b)))
                .unwrap();
            spilled.insert(t);
            t
        });
        for n in left.remove(&t).unwrap() {
            left.get_mut(&n).unwrap().remove(&t);
        }
        if pick.is_some() {
            stack.push(t);
        }
    }
    let mut colour = BTreeMap::new();
    while let Some(t) = stack.pop() {
        // select: the lowest colour no neighbour has
        let taken: BTreeSet<usize> = gr.adj[&t]
            .iter()
            .filter_map(|n| colour.get(n).copied())
            .collect();
        colour.insert(t, (0..).find(|c| !taken.contains(c)).unwrap());
    }
    Colouring { colour, spilled }
}
Listing 8.10. Simplify, spill and select. A spilled temporary is not coloured; it keeps a stack slot. code/bachelor-3/08-program-optimisation/listings/regalloc.rs

Output 8.3 optimises sumsq, builds its interference graph and colours it. n, s, i and t3 are all live after t3 = i * i, so they form a clique and need four registers; with three, one of them is spilled, and the cheapest per neighbour is n, read once per iteration and with five neighbours.

$ rustc --edition 2021 -O -o color_demo color_demo.rs && ./color_demo loop.moor
    s = 0
    i = 0
    L1:
    if i < n goto L2
    goto L3
    L2:
    t3 = i * i
    t5 = s + t3
    s = t5
    t6 = i + 1
    i = t6
    goto L1
    L3:
    return s
interference graph: 6 nodes, 10 edges
  n    cost   10  -- s i t3 t5 t6
  s    cost   22  -- n i t3 t6
  i    cost   51  -- n s t3 t5
  t3   cost   20  -- n s i
  t5   cost   20  -- n i
  t6   cost   20  -- n s
k = 3: s:2 i:1 t3:0 t5:0 t6:0   spilled: n
k = 4: n:2 s:3 i:1 t3:0 t5:0 t6:0   spilled: none
Output 8.3. sumsq optimised (the copy sq = t3 is gone), its interference graph with each temporary’s spill cost and neighbours, and colourings with three and four registers.
The interference graph of sumsq, 6 vertices and 10 edges as in , coloured with four colours. n, s, i and t3 form a clique, so three colours are not enough. The three short-lived temporaries share colour 0.
The interference graph of sumsq, 6 vertices and 10 edges as in Output 8.3, coloured with four colours. n, s, i and t3 form a clique, so three colours are not enough. The three short-lived temporaries share colour 0.

The selection of chapter 7 is adapted in one place: an operand in a register is used where it is, and only a spilled one is loaded into a scratch register (Listing 8.11). A result is computed straight into its register, and stored only if it is spilled.

    /// The register holding v, loading it into `scratch` if needed.
    fn get(&mut self, v: Val, scratch: &'static str) -> &'static str {
        match v {
            Val::K(0) => "zero",
            Val::K(n) => {
                self.i(format!("li {scratch}, {n}"));
                scratch
            }
            Val::T(t) => match self.loc[&t] {
                Loc::Reg(r) => r,
                Loc::Slot(o) => {
                    self.i(format!("lw {scratch}, {o}(sp)"));
                    scratch
                }
            },
        }
    }
    /// Where to compute t: its register, or t0 before a store.
    fn target(&self, t: u32) -> &'static str {
        match self.loc[&t] {
            Loc::Reg(r) => r,
            Loc::Slot(_) => "t0",
        }
    }
    fn finish(&mut self, t: u32, reg: &str) {
        if let Loc::Slot(o) = self.loc[&t] {
            self.i(format!("sw {reg}, {o}(sp)"));
        }
    }
Listing 8.11. Operands and results once temporaries have locations. The constant 0 is the register zero. code/bachelor-3/08-program-optimisation/listings/rvgen.rs

Definition 8.18 (Register coalescing)

Register coalescing merges the two vertices of a copy x = y that do not interfere into one, so that they get the same register and the copy becomes mv r, r, which is deleted.

Our allocator does not coalesce, and its output shows the cost: in the loop of sumsq, s = t5 and i = t6 become mv instructions executed on every iteration. Merging vertices raises degrees and can turn a colourable graph into one that is not, so coalescing is done only when it cannot cause a spill, for instance when the merged vertex has fewer than kk neighbours of degree kk or more.

8.5 Measured

moorc_opt compiles at three levels: -O0 is chapter 7’s compiler, -O1 runs the optimisations of this chapter and keeps every temporary on the stack, and -O2 adds the allocator. Output 8.4 runs three samples at each level on rv, which counts exactly; these are numbers of instructions, not times.

$ rustc --edition 2021 -O -o moorc_opt $CH/moorc_opt.rs
$ for p in fib sum_array primes; do for O in 0 1 2; do ./moorc_opt -O$O $p.moor > $p.$O.S; done; done
$ python measure.py fib:20 sum_array primes
program    level  instructions   loads  stores   output
fib          -O0        426887  131347   98511   6765
fib          -O1        426885  131346   98510   6765
fib          -O2        448781   87566   87566   6765
                 same output and exit code
sum_array    -O0           457     167      96   285
sum_array    -O1           457     167      96   285
sum_array    -O2           259      17      17   285
                 same output and exit code
primes       -O0          3041    1039     659   2 3 5 ...
primes       -O1          3041    1039     659   2 3 5 ...
primes       -O2          2113     256     256   2 3 5 ...
                 same output and exit code
Output 8.4. Three samples of chapter 7 compiled at the three levels: instructions executed, loads and stores. Every level prints the same and exits with the same code.

Three things stand out. First, -O1 hardly helps these samples: their copies are loop variables, live around the loop, which no pass here can remove. On straight-line code it helps a lot: expr.moor goes from 45 instructions to 13, because everything in it is a constant. Second, the allocator removes most memory accesses everywhere: sum_array from 263 to 34 loads and stores. Third, on fib, -O2 executes more instructions than -O1, 448,781 against 426,885, though it makes a quarter fewer memory accesses. Every call now saves and restores the s registers it uses, three of them and ra, and half of all calls are leaves that return at once: the leaf call went from 11 instructions to 16. A compiler that tests n<2n < 2 before saving anything, as gcc did in chapter 7, avoids this cost; the technique, which places the saves only on the paths that need them, is called shrink-wrapping.

In practice — Count before you time

rv’s counts are exact and the same on every run, so a change of one instruction per iteration is visible, which no timing on a laptop would show. They are not times: on a real processor, a load costs more or less depending on where the data is, and the Year 2 volume’s caches decide that. Counting tells whether an optimisation does what it means to; only timing on the target tells whether it matters.

History — Dataflow and colouring

Gary Kildall published a unified approach to global program optimisation in 1973, the analyses of this chapter as one algorithm over a lattice. John Kam and Jeffrey Ullman characterised monotone dataflow frameworks in 1977. Gregory Chaitin described register allocation and spilling via graph colouring in 1982. Ron Cytron, Jeanne Ferrante, Barry Rosen, Mark Wegman and Kenneth Zadeck published in 1991 how to compute static single assignment form efficiently, with dominance frontiers.

8.6 Exercises

Exercise 8.1 ★

In sumsq (Output 8.1), which temporaries are live after s = 0, after sq = t3 and after t6 = i + 1? Which is live at the entry, and why only that one?

Solution

Solution of Exercise 8.1.

After s = 0: {n,s}\{n, s\}; after sq = t3: {n,s,i,sq}\{n, s, i, sq\}; after t6 = i + 1: {n,s,t6}\{n, s, t6\}, since i is overwritten by the next instruction before any read. At the entry only n is live: s and i are written by the first two instructions before anything reads them (exercise_1_live_variables_of_the_loop).

Exercise 8.2 ★

Give the dominators and the immediate dominator of each block of the function f of chapter 7’s exercise 7.9, a while loop with a return inside.

Solution

Solution of Exercise 8.2.

With the blocks of that exercise’s solution: B0 (the loop’s test, also the entry) {0}\{0\}; B1 {0,1}\{0, 1\}; B2 {0,2}\{0, 2\}; B3 {0,2,3}\{0, 2, 3\}; B4 {0,2,4}\{0, 2, 4\}; B6 {0,2,3,6}\{0, 2, 3, 6\}; B7 {0,2,3,6,7}\{0, 2, 3, 6, 7\}; B8 {0,1,8}\{0, 1, 8\}. B5 and B9 are unreachable and have none. The immediate dominators are B0 for B1 and B2, B2 for B3 and B4, B3 for B6, B6 for B7 and B1 for B8: the dominator tree is the chain B0, B2, B3, B6, B7, with B4 hanging from B2, and B1, with B8 below it, from B0 (exercise_2_dominators).

Exercise 8.3 ★

Place the ϕ\phi-functions of fn f(n: int) -> int { var x = 0; var y = 1; if n > 0 { x = n; } else { y = n; } while x < 10 { x = x + y; } return x; }, and give their arguments.

Solution

Solution of Exercise 8.3.

x is defined in the entry B0, in the then part B2 and in the loop body B7; y in B0 and in the else part B3. The frontier of each branch of the if is the block where they join, B4; the frontier of the loop body B7 is the loop’s header B5; and the frontier of B4 is empty, since B4 dominates everything after it. So DF+({B0,B2,B7})={B4,B5}\mathrm{DF}^{+}(\{\mathrm{B0}, \mathrm{B2}, \mathrm{B7}\}) = \{\mathrm{B4}, \mathrm{B5}\} and DF+({B0,B3})={B4}\mathrm{DF}^{+}(\{\mathrm{B0}, \mathrm{B3}\}) = \{\mathrm{B4}\}: x gets ϕ\phi-functions at B4 and B5, y only at B4, since the loop does not assign it:

x2=ϕ(B3: x0,B2: x1),y2=ϕ(B3: y1,B2: y0),x3=ϕ(B4: x2,B7: x4)x_2 = \phi(\mathrm{B3}{:}\,x_0, \mathrm{B2}{:}\,x_1),\quad y_2 = \phi(\mathrm{B3}{:}\,y_1, \mathrm{B2}{:}\,y_0),\quad x_3 = \phi(\mathrm{B4}{:}\,x_2, \mathrm{B7}{:}\,x_4)

(exercise_3_phi_placement).

Exercise 8.4 ★

Predict the three-address code of var a = 6; var b = a * 7; var c = b - 40; if c > 1 { print(b); } else { print(a); } return c * a; after optimise, and the number of rounds it takes.

Solution

Solution of Exercise 8.4.

Round 1 propagates a=6a = 6, folds b=42b = 42 and c=2c = 2, decides the branch (2>12 > 1), removes the else block and the copies that became dead. Round 2 removes the jumps and labels’ instructions made pointless and the last dead temporaries, and round 3 changes nothing. What is left is L1:, call print(42), L3:, return 12: three rounds (exercise_4_folded_tac).

Exercise 8.5 ★★

exercises/ex5_wrong_way.rs is liveness with the direction set to forward and nothing else changed. On sumsq it says that nothing is live at the entry and that n, s and i are live after the final return. Explain both answers from the equations, and say what an allocator would do with them.

Solution

Solution of Exercise 8.5.

Forward, the fact at a block’s start is the join of the facts at the ends of its predecessors, and the entry gets the boundary, the empty set. The transfer, still the backward rule, then adds what the block reads to what flowed in. The result is “the temporaries read on some path from the entry to here”, a fact about the past: at the entry nothing has been read, so nothing is “live”, and after the final return everything read in the loop has been read, so n, s and i are (exercise_5_liveness_the_wrong_way). An allocator fed with these sets would see no interference at the entry and could give n’s register to s, overwriting the loop bound; the program would then loop a wrong number of times. Liveness depends on the future of a point, so its facts must flow from the successors.

Exercise 8.6 ★★

Write dead-store elimination for globals: a store g = v is removed if, later in the same block, g is stored again with no load of g and no call in between. Why must a call stop the search? Test it on g = 1; h = 2; g = 3; print(g); g = 4; h = g; g = 5; return g + h;.

Solution

Solution of Exercise 8.6.

exercises/ex6_dead_store.rs scans forward from each store within its block. A call stops the search because the callee may read the global, and then the first store’s value is needed; a load of the same global stops it for the same reason. On the test program it removes g = 1 only: h = 2 is followed by the call to print before h is stored again, and g = 3 and g = 4 are read before the next store. The program still prints 3 and exits with 5+4=95 + 4 = 9 (exercise_6_dead_stores).

Exercise 8.7 ★★

Prove that the worklist algorithm visits blocks at most n+h⋅en + h \cdot e times, for nn blocks, ee edges and a lattice of height hh per block.

Solution

Solution of Exercise 8.7.

Every value computed is at least the previous value of the same block: by induction, the facts flowing in only grow, and the transfer is monotone. So the output of a block changes at most hh times. Each change puts at most out(b)\mathrm{out}(b) blocks in the queue, its successors (or predecessors, backwards), and each visit is caused by the initial queue or by one such insertion. The visits number at most n+∑bh⋅out(b)=n+h⋅en + \sum_b h \cdot \mathrm{out}(b) = n + h \cdot e. For liveness on sumsq the bound is 6+7×5=416 + 7 \times 5 = 41, with h=7h = 7 temporaries (n, s, i, t3, sq, t5, t6) and e=5e = 5 edges; the actual count is 12.

Exercise 8.8 ★★

Colour the interference graph of Output 8.3 with three registers, or prove that a spill is needed.

Solution

Solution of Exercise 8.8.

A spill is needed. n, s, i and t3 are pairwise adjacent: all four are live just after t3 = i * i, as the edges listed show. Four vertices pairwise adjacent need four colours. With three registers the allocator spills n, whose cost per neighbour is 10/5=210/5 = 2, the smallest, and colours the rest (exercise_8_three_registers_are_not_enough).

Exercise 8.9 ★★

A nest of dd while loops, each with its own counter i0, …, initialised just before it, increments one accumulator s in the innermost body. How many ϕ\phi-functions does the placement of Theorem 8.10 put, as a function of dd? How many are useful?

Solution

Solution of Exercise 8.9.

d(d+3)/2d(d + 3)/2: 2, 5, 9, 14, 20 for d=1,…,5d = 1, \dots, 5 (exercise_9_phis_of_nested_loops). s is assigned in the innermost body, whose iterated frontier contains every header: dd ϕ\phi-functions. The counter of the loop at depth jj is assigned before its loop, in the body of the loop at depth j−1j - 1, and at the end of its own body; the iterated frontier of these blocks is its own header and the headers of the j−1j - 1 loops around it: jj ϕ\phi-functions, d(d+1)/2d(d+1)/2 in all. Only 2d2d are useful: s is live at every header, and each counter at its own header; at the headers of the outer loops the counter is dead, since it is reset before being read. Placing ϕ\phi-functions only where the variable is live gives the pruned SSA form, with 2d2d.

Exercise 8.10 ★★★

A framework is distributive if f(x⊔y)=f(x)⊔f(y)f(x \sqcup y) = f(x) \sqcup f(y) for every transfer function. Show that constant propagation is not, with the program of the remark in Section 8.3, and prove that for a distributive framework the least fixed point equals the join, over all paths to a point, of the facts computed along each path.

Solution

Solution of Exercise 8.10.

Let x1={a↦2,b↦3}x_1 = \{a \mapsto 2, b \mapsto 3\} and x2={a↦3,b↦2}x_2 = \{a \mapsto 3, b \mapsto 2\} be the facts at the end of the two branches, and ff the transfer of x = a + b. Then f(x1)⊔f(x2)f(x_1) \sqcup f(x_2) maps xx to 5⊔5=55 \sqcup 5 = 5, but f(x1⊔x2)=f({a↦⊤,b↦⊤})f(x_1 \sqcup x_2) = f(\{a \mapsto \top, b \mapsto \top\}) maps xx to ⊤\top (exercise_10_not_distributive).

For the theorem, let MOP(b)\mathrm{MOP}(b) be the join over all paths pp from the entry to bb of fp(boundary)f_p(\mathit{boundary}), fpf_p being the composition of the transfers along pp; the lattice has finite height, so this join is a finite one. First, MOP⊑\mathrm{MOP} \sqsubseteq the least fixed point XX in any monotone framework: by induction on the length of pp, fp(boundary)⊑X(b)f_p(\mathit{boundary}) \sqsubseteq X(b), since each step applies a monotone transfer and XX satisfies the equations. Second, if every fBf_B distributes over joins, MOP satisfies the equations: the join over the predecessors PP of fP(MOP(P))f_P(\mathrm{MOP}(P)) is the join over PP of the join over the paths to PP of fP(fp(boundary))f_P(f_p(\mathit{boundary})), which is the join over all paths to bb. So MOP is a fixed point, and the least fixed point is below it. The two are equal. For constant propagation the least fixed point can be strictly above MOP, as the example shows: the analysis loses facts that hold on every path, because it joins before applying the transfer.

Exercise 8.11 ★★★

A graph is chordal if every cycle of four or more vertices has a chord. Admit that the interference graph of a program in SSA form, with interference defined at definitions, is chordal. Prove that a chordal graph has a vertex whose neighbours form a clique, deduce that simplify never gets stuck when kk is at least the largest clique, and conclude that such a program needs exactly as many registers as the most temporaries live at one point.

Solution

Solution of Exercise 8.11.

A vertex is simplicial if its neighbours form a clique. Claim: a chordal graph that is not complete has two non-adjacent simplicial vertices, and a complete one has every vertex simplicial. By induction on the number of vertices: if GG is not complete, take non-adjacent a,ba, b and a minimal set SS separating them. SS is a clique: for u,v∈Su, v \in S, both have neighbours in the component AA of aa and in the component BB of bb of G−SG - S (otherwise SS would not be minimal), so there are shortest paths u…vu \dots v through AA and through BB; together they form a cycle of length at least 4 whose only possible chord is uvuv, since AA and BB are not joined. By induction, G[A∪S]G[A \cup S] has a simplicial vertex in AA (two non-adjacent ones if it is not complete, and they cannot both be in the clique SS; if it is complete, any vertex of AA), and its neighbours in GG are all in A∪SA \cup S, so it is simplicial in GG; the same in BB.

A simplicial vertex in a graph whose largest clique has ω\omega vertices has at most ω−1\omega - 1 neighbours. Removing a vertex leaves a chordal graph, an induced subgraph. So if k≥ωk \ge \omega, simplify always finds a vertex of degree less than kk, never spills, and colours the graph with ω\omega colours, which a clique of ω\omega vertices needs anyway. For an SSA program the vertices of a clique are temporaries live together at one point (the definition of the one defined last, which the others’ definitions dominate), so ω\omega is the largest number of temporaries live at one point, and that many registers are necessary and sufficient.

Exercise 8.12 ★★★

Write loop-invariant code motion: move an operation whose operands no instruction of the loop writes, into a temporary written nowhere else, to just before the loop’s header. Why is moving it safe even if the loop body might not run, given Moor’s division? Test it on while i < 100 { s = s + a * b + i; i = i + 1; } and count the instructions saved.

Solution

Solution of Exercise 8.12.

exercises/ex12_licm.rs finds the loops by their back edges, as in the text, and moves one candidate at a time until none is left. Moving the operation before the loop executes it even when the loop body would not run; this is safe because the operation has no effect but its result, and in Moor no arithmetic traps: division by zero gives −1-1, as on the processor. In a language where division by zero stops the program, only an operation that dominates the loop’s exits, or whose divisor is known to be non-zero, could be moved. On the test, t6 = t0 * t2 moves before L1:; with a=6a = 6 and b=7b = 7 both versions print ∑i<100(42+i)=9150\sum_{i < 100} (42 + i) = 9150, and the moved one executes 396 fewer instructions, 4 per iteration (two loads, the multiplication, a store) minus the 4 executed once before the loop (exercise_12_loop_invariant_code_motion).

8.7 Weekend problem

Problem 8.1

Weekend problem — A hot loop in the town’s billing

The library of the series’ invented town fines late returns: 10 cents a day for the first week, 25 cents a day after it, at most 500. billing.moor reads the days late of each returned loan, then fines and totals them in one loop. The data are the loans table of the town (data/town/loans.csv). Output 8.5 gives the interference graph of the program after -O1 and two colourings; Output 8.6 compiles it at each level, with fewer and fewer registers, and counts.

    i = 0;
    while i < n {
        var days = late[i];
        var fine = 0;
        if days > 0 {
            if days <= 7 { fine = day_rate * days; }
            else { fine = 7 * day_rate + week_rate * (days - 7); }
            if fine > cap { fine = cap; }
            count = count + 1;
        }
        total = total + fine;
        if fine > worst { worst = fine; }
        i = i + 1;
    }
Listing 8.12. The hot loop of billing.moor. The rates and the cap are variables set before it. code/bachelor-3/08-program-optimisation/listings/billing.moor
$ rustc --edition 2021 -O -o color_demo $CH/color_demo.rs
$ ./color_demo billing.moor 7 6 | sed -n '/^interference/,$p'
interference graph: 16 nodes, 58 edges
  t0   cost   21  -- i t3 t4 total count worst t11 fine t14 t16 t17 t18 t19 t20 t21
  i    cost   82  -- t0 t3 total count worst t11 fine t14 t16 t17 t18 t19 t20
  t3   cost   20  -- t0 i
  t4   cost   20  -- t0
  total cost   22  -- t0 i count worst t11 fine t14 t16 t17 t18 t19 t21
  count cost   22  -- t0 i total worst t11 fine t14 t16 t17 t18 t20 t21
  worst cost   22  -- t0 i total count t11 fine t14 t16 t17 t18 t19 t20 t21
  t11  cost   50  -- t0 i total count worst fine
  fine cost   80  -- t0 i total count worst t11 t19 t20
  t14  cost   20  -- t0 i total count worst
  t16  cost   20  -- t0 i total count worst
  t17  cost   20  -- t0 i total count worst
  t18  cost   20  -- t0 i total count worst
  t19  cost   20  -- t0 i total worst fine
  t20  cost   20  -- t0 i count worst fine
  t21  cost   20  -- t0 total count worst
k = 7: t0:5 i:6 t3:0 t4:0 total:4 count:3 worst:2 t11:0 fine:1 t14:0 t16:0 t17:0 t18:0 t19:0 t20:0 t21:0   spilled: none
k = 6: i:5 t3:0 t4:0 total:4 count:3 worst:2 t11:1 fine:0 t14:0 t16:0 t17:0 t18:0 t19:1 t20:1 t21:0   spilled: t0
Output 8.5. The interference graph of billing.moor after -O1, and colourings with seven and six registers. t0 is n: copy propagation replaced n by the temporary returned by read.
$ rustc --edition 2021 -O -o moorc_opt $CH/moorc_opt.rs
$ ./moorc_opt -O0 billing.moor > O0.S
$ ./moorc_opt -O1 billing.moor > O1.S
$ for k in 12 6 5 4 3 2 1; do ./moorc_opt -O2 -k $k billing.moor > k$k.S; done
$ python billing_counts.py loans.csv O0.S O1.S k12.S k6.S k5.S k4.S k3.S k2.S k1.S
378 returned loans, 87 late, at most 30 days
                           whole run           hot loop
program instructions   loads  stores    instr.   ld+st   output
O0.S           22528    8180    4743     15296    9125   87 24305 500
O1.S           21496    7473    4294     14272    7974   87 24305 500
k12.S          11815     385     385      7233     378   87 24305 500
k6.S           12484    1142     385      7525     757   87 24305 500
k5.S           12861    1520     763      7903    1513   87 24305 500
k4.S           13238    1898     768      8281    1896   87 24305 500
k3.S           13411    1985     855      8455    2070   87 24305 500
k2.S           15182    3001    1697     10228    3930   87 24305 500
k1.S           17452    5270    2454     11363    5443   87 24305 500
Output 8.6. The program at -O0, -O1, and -O2 with 12 down to 1 registers, run on the 378 returned loans: counts for the whole run, then for the hot loop alone. All print 87 late loans, 24,305 cents in fines, and a largest fine of 500.

Part I — Liveness.

  1. Which of n, i, days, fine, total, count, worst, day_rate, week_rate and cap are live at the top of the loop in the source, before any optimisation?
  2. After -O1, day_rate, week_rate and cap have disappeared from the graph. Which pass removed them, and what did it put in their place?
  3. Why is fine live across the test fine > cap, and days not after the computation of fine?
  4. Which temporaries are live at the point where most are, and how many are they?
  5. Why does t3, the value returned by read in the first loop, interfere with only two temporaries?
  6. What does the cost 82 of i count?

Part II — Colouring.

  1. Find a clique of seven vertices in the graph. What does it prove about the registers needed?
  2. Check that the colouring with seven registers is proper on the edges of fine.
  3. Why can the ten temporaries t3, t4, t11, t14, …, t21 all share colour 0?
  4. With 12 registers available, how many does the allocator use, and which s registers must the function save?
  5. Explain why total and count cannot share a register, and why t14 and t16 can.
  6. Simulate simplify by hand with k=7k = 7 for the first three vertices it removes.

Part III — Fewer registers.

  1. With six registers, which temporary is spilled, and why that one by the cost per neighbour?
  2. Count, from the program, the extra loads that spilling t0 adds per iteration of each loop, and check against the table.
  3. With five registers, which temporaries would you expect to be spilled next? Check the table’s loads and stores.
  4. Why do the counts with 12 and with 8 registers coincide, while 6 differ? (8 is not in the table; argue from the graph.)
  5. With one register, half the temporaries are spilled. Why is the count still well below -O1’s?
  6. Plot or tabulate the instructions against kk. Where is the largest step?

Part IV — The counts.

  1. In the hot loop, what fraction of -O0’s loads and stores does -O1 remove, and what fraction of its instructions?
  2. In the hot loop, what fraction of -O1’s loads and stores does the allocator remove with 12 registers, and what fraction of its instructions? Compare with the whole run.
  3. Where do the 385 loads that remain in the whole run with 12 registers come from? And the 385 stores?
  4. How many instructions does one iteration of the hot loop execute at -O1, and at -O2, on average?
  5. What would coalescing save on this loop? Count the mv instructions in it.
  6. Sum up: the percentage of loads and stores, and of all instructions, that graph-colouring allocation removes on the billing loop, and what limits it.
Solution

Solution of Problem 8.1.

1. n, i, total, count, worst, day_rate, week_rate and cap: each is read in the loop before being written, or after it. days and fine are written at the top of the body before any read.

2. Constant propagation: the three are 10, 25 and 500 on every path, so their uses became constants (7 * day_rate folded to 70), and dead-code elimination removed their now unread copies.

3. fine is read after the test: added to total and compared with worst. days (t11) is read only to compute fine; after the last such read no path reads it again.

4. Seven, for instance just after fine = 0: t0, i, total, count, worst, t11 and fine.

5. It is defined by read and read at once by the store into late[i]; between the two, only t0 and i are live.

6. Each use or definition of i weighted by 10depth10^{\text{depth}}: in each loop, the test, the index, the increment and the copy back, four times 10; two loops, 80; plus the two i = 0 outside any loop, 1 each: 82.

7. The seven of question 4: each pair is an edge in Output 8.5. Seven registers are needed to avoid spilling.

8. fine has colour 1; its neighbours t0, i, total, count, worst, t11, t19 and t20 have colours 5, 6, 4, 3, 2, 0, 0 and 0: none has 1.

9. No two of them interfere: each lives from its definition to its few uses, and none of the others is defined in between (the graph has no edge among them). Their neighbours are among the six long-lived temporaries t0, i, total, count, worst and fine, which select colours 5, 6, 4, 3, 2 and 1, so colour 0 is free for all ten.

10. Seven: s1 to s7, all saved in the prologue and restored in the epilogue. ra is not saved, since the function calls nothing: the built-ins are system calls.

11. total and count are both live throughout the loop: an edge. t14 and t16 are in different branches of the if; neither is live where the other is defined.

12. In the order of the temporaries’ numbers, the first vertex of degree less than 7 is t3 (degree 2), then t4 (degree 1), then t11, whose degree is 6.

13. t0. When simplify gets stuck, the remaining vertices all have six neighbours or more; t0 costs 21 for fifteen neighbours, the least cost per neighbour, since it is read only in the two loop tests: 21/15=1.421/15 = 1.4, against 22/1222/12 for total and 82/13 for i.

14. One load per evaluation of each loop’s test, 379 each: 758 more, minus the restore of the seventh s register, no longer used: 385+758−1=1142385 + 758 - 1 = 1142. In the hot loop, 378+379=757378 + 379 = 757 loads and stores. The spill’s store replaces that register’s save: the stores stay at 385.

15. total is spilled next (color_demo with k=5k = 5 confirms it): one load and one store per iteration, 378 each, which is the step from 1142 to 1520 loads and 385 to 763 stores; its store at total = 0 and its load for print replace the save and the restore of the register no longer used. With four registers worst follows, and with three count follows: 87 more loads and 87 more stores, one of each per late loan, for count = count + 1 (1898 to 1985 loads, 768 to 855 stores).

16. The largest clique has seven vertices and simplify finds a colouring with seven colours; with k≥7k \ge 7 it never gets stuck and select uses the lowest colours, so the allocation, and the code, are the same. With six, a spill is unavoidable.

17. The one register still holds fine and the short-lived temporaries that do not interfere with it, so part of the arithmetic of the loop stays in a register. A spilled temporary costs a load per use and a store per definition, as at -O1, but the operands in the register cost nothing, and the code generator of -O2 also uses zero for the constant 0, immediate forms, and computes a result straight into its location.

18. Instructions: 11,815 for 7 to 12 registers, then 12,484, 12,861, 13,238, 13,411, 15,182 and 17,452 for 6 down to 1. The largest step is from 2 registers to 1 (2,270), which spills the loop counter i, then from 3 to 2 (1,771), which spills days (t11) and two short-lived temporaries.

19. In the hot loop, loads and stores go from 9,125 to 7,974, 12.6 % fewer, and instructions from 15,296 to 14,272, 6.7 % fewer: the constants and some copies are gone, but every temporary still goes through memory.

20. From 7,974 loads and stores to 378, 95.3 % fewer; from 14,272 instructions to 7,233, 49.3 % fewer. Over the whole run, 11,767 to 770 (93.5 %) and 21,496 to 11,815 (45.0 %): the first loop’s read calls and stores are work the allocator cannot remove.

21. 378 loads of late[i] in the hot loop and 7 restores; 378 stores into late[i] in the first loop and 7 saves.

22. 14,272/378≈37.814{,}272/378 \approx 37.8 at -O1 and 7,233/378≈19.17{,}233/378 \approx 19.1 at -O2, the loop’s test counting 379 times in both.

23. The hot loop executes 935 mv instructions: the copies back into i and total on every iteration (378 each), into count and fine for late loans, and worst = fine five times. All but the last connect temporaries that do not interfere, so coalescing would remove about 930 of 7,233 instructions, 13 %. worst = fine must stay: both are live afterwards.

24. On the billing loop, graph-colouring allocation removes 95.3 % of the loads and stores and 49.3 % of all instructions executed (93.5 % and 45.0 % over the whole run). What is left is the essential memory traffic, one load of late[i] per loan, the arithmetic, the branches, and the copies that coalescing would remove. Seven registers suffice because at most seven temporaries are live at once; below that, each spilled temporary costs about one access per use in the loop.

Terms defined in this chapter

See all 1050 terms in the glossary