---
title: "Program Analysis and Optimisation"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 8
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/8-program-analysis-and-optimisation
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 8 — Program Analysis and Optimisation

The compiler of chapter [7](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation) is correct and slow: every temporary [lives](#def-b3-program-optimisation-liveness) 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](#def-b3-program-optimisation-lfp). With them the chapter removes useless work from the [three-address code](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#def-b3-code-generation-tac), 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 $L$ with a partial order $\sqsubseteq$, read “is at most as informative a claim as”, in which every two facts $x, y$ have a least upper bound $x \sqcup y$, their *join*, and which has a least element $\bot$. Its *height* is the largest number of strict steps in a chain $x_0 \sqsubset x_1 \sqsubset \dots \sqsubset x_h$.

For [liveness](#def-b3-program-optimisation-liveness), the facts are sets of temporaries, ordered by inclusion, the join is union and $\bot$ is the empty set; with $m$ temporaries the height is $m$. For constants, the fact about one temporary is “not yet seen” ($\bot$), “always the constant $k$”, or “not a constant” ($\top$), a lattice of height 2 however many constants there are (the figure below); for $m$ temporaries, take one such fact per temporary, height $2m$.

![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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-optimisation/fig-bff00684b07d.svg)

*Two [dataflow lattices](#def-b3-program-optimisation-lattice), smaller elements below. Left: the value of one temporary for [constant propagation](#def-b3-program-optimisation-constprop); two different constants join to $\top$, so the height is 2. Right: the sets of three temporaries ordered by inclusion, the lattice of [liveness](#def-b3-program-optimisation-liveness); its height is 3.*

**Definition 8.2 (Transfer function, monotone framework).**

A *transfer function* $f_B : L \to L$ gives the fact at one end of a block $B$ 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 \sqsubseteq y$ implies $f_B(x) \sqsubseteq f_B(y)$. A *monotone framework* is a [dataflow lattice](#def-b3-program-optimisation-lattice), a direction, a monotone transfer function per block, and a fact at the boundary (the entry, or the exits). Its equations are $\mathit{in}(B) = \bigsqcup_{P} \mathit{out}(P) \sqcup \mathit{boundary}$, over the blocks $P$ the facts flow from, and $\mathit{out}(B) = f_B(\mathit{in}(B))$.

Put all the blocks’ facts in one vector $X \in L^n$, ordered componentwise. The equations say $X = F(X)$ for one function $F : L^n \to L^n$, monotone because joins and the $f_B$ are. A solution is a [fixed point](#def-b3-program-optimisation-lfp) of $F$, and the useful one is the least.

**Definition 8.3 (Least fixed point).**

A *fixed point* of $F$ is an $X$ with $F(X) = X$. The *least fixed point* is a fixed point below every other.

**Theorem 8.4 (Fixed points by iteration).**

Let $F$ be monotone on a lattice of finite height $h$ with least element $\bot$. The sequence $\bot, F(\bot), F(F(\bot)), \dots$ is increasing, becomes constant after at most $h$ strict steps, and its final value is the [least fixed point](#def-b3-program-optimisation-lfp) of $F$.

**Proof.** $\bot \sqsubseteq F(\bot)$ since $\bot$ is least, and if $F^{k-1}(\bot) \sqsubseteq F^{k}(\bot)$ then monotonicity gives $F^{k}(\bot) \sqsubseteq F^{k+1}(\bot)$: the sequence increases. A strictly increasing chain has at most $h$ steps, so after at most $h$ strict steps two consecutive terms are equal, $F(X) = X$, and the sequence stays there. For leastness, let $Y$ be any [fixed point](#def-b3-program-optimisation-lfp). $\bot \sqsubseteq Y$, and if $F^k(\bot) \sqsubseteq Y$ then $F^{k+1}(\bot) \sqsubseteq F(Y) = Y$; so $X \sqsubseteq Y$. ∎

Iterating $F$ 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](#lst-b3-program-optimisation-solve)). It computes the same [least fixed point](#def-b3-program-optimisation-lfp), since each recomputation is one component of $F$ applied to a vector below the [fixed point](#def-b3-program-optimisation-lfp), and the values only grow; exercise [8.7](#exo-b3-program-optimisation-7) bounds its work. [Listing 8.1](#lst-b3-program-optimisation-trait) is the interface an analysis implements.

```rust
/// 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](#def-b3-program-optimisation-framework) as a Rust trait: the lattice (its least element and join), the direction, the boundary and the [transfer function](#def-b3-program-optimisation-framework). code/bachelor-3/08-program-optimisation/listings/dataflow.rs*

```rust
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](#thm-b3-program-optimisation-kleene), 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 $\mathit{live}_{\mathrm{before}}(i) = \mathit{uses}(i) \cup (\mathit{live}_{\mathrm{after}}(i) \setminus \mathit{def}(i))$ for each instruction $i$.

The [transfer function](#def-b3-program-optimisation-framework) of a block applies this rule to its instructions from the last to the first ([Listing 8.3](#lst-b3-program-optimisation-liveness)). It is monotone, since a larger set after gives a larger set before. [Output 8.1](#out-b3-program-optimisation-live) 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.

```rust
/// 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](#def-b3-program-optimisation-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](#def-b3-program-optimisation-liveness) at the start and at the end of each block of `sumsq`. `n`, `s` and `i` stay [live](#def-b3-program-optimisation-liveness) around the loop; inside the body, `t3`, `sq`, `t5` and `t6` each [live](#def-b3-program-optimisation-liveness) 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-optimisation/fig-0f7f330a9746.svg)

*The control-flow graph of `sumsq` with the [live](#def-b3-program-optimisation-liveness) sets of [Output 8.1](#out-b3-program-optimisation-live) 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 $t$ adds itself and removes the other definitions of $t$.

`reaching.rs` implements it in twenty lines with the same trait. At the top of the loop of `sumsq`, the [definitions](#def-b3-program-optimisation-reaching) that reach are $s = 0$ and $i = 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](#def-b3-program-optimisation-reaching) 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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation) 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](#def-b3-program-optimisation-reaching) answer, at the price of a set per point. A form in which every temporary has one [definition](#def-b3-program-optimisation-reaching) makes the question vanish: the name tells the [definition](#def-b3-program-optimisation-reaching).

**Definition 8.7 (Static single assignment, phi-function).**

A function is in *static single assignment form* if every temporary has exactly one [definition](#def-b3-program-optimisation-reaching) in its text. Where [definitions](#def-b3-program-optimisation-reaching) of one variable from different paths meet, at the start of a block, a *$\phi$-function* $x_3 = \phi(B_1{:}\,x_1, B_2{:}\,x_2)$ defines a new name whose value is $x_1$ if control came from $B_1$ and $x_2$ if it came from $B_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 $d$ *dominates* a block $b$ if every path from the entry to $b$ passes through $d$; every block dominates itself, and $d$ *strictly* dominates $b$ if moreover $d \ne b$. The *immediate dominator* of $b \ne$ entry is the strict dominator of $b$ that every other strict dominator of $b$ dominates. The *dominance frontier* $\mathrm{DF}(x)$ is the set of blocks $y$ such that $x$ dominates a predecessor of $y$ but does not strictly dominate $y$. For a set $S$, $\mathrm{DF}^{+}(S)$ is the limit of $S_1 = \mathrm{DF}(S)$, $S_{k+1} = \mathrm{DF}(S \cup S_k)$, the *iterated* frontier.

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

```rust
/// 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](#def-b3-program-optimisation-dominator) by iteration. Unreachable blocks are left out: no path reaches them, so nothing [dominates](#def-b3-program-optimisation-dominator) them. code/bachelor-3/08-program-optimisation/listings/ssa.rs*

```rust
/// 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](#def-b3-program-optimisation-dominator), 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 = u_0, u_1, \dots, u_k = y$ be a path. If $x$ does not strictly dominate $y$, some $u_i$ with $i \ge 1$ is in $\mathrm{DF}(x)$.

**Proof.** Let $i \ge 1$ be the least index such that $x$ does not strictly dominate $u_i$; it exists since $u_k = y$ qualifies. Then $x$ [dominates](#def-b3-program-optimisation-dominator) $u_{i-1}$: either $i - 1 = 0$ and $u_0 = x$, or $x$ strictly [dominates](#def-b3-program-optimisation-dominator) $u_{i-1}$ by the choice of $i$. So $x$ [dominates](#def-b3-program-optimisation-dominator) a predecessor of $u_i$ and does not strictly dominate $u_i$: $u_i \in \mathrm{DF}(x)$. ∎

**Theorem 8.10 (Placing phi-functions).**

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

**Proof.** We prove (a); (b) is admitted. Let $D = S \cup \mathrm{DF}^{+}(S)$, the blocks where $v$ is defined once the $\phi$-functions are placed. $D$ is closed under frontiers: $\mathrm{DF}(D) \subseteq D$, by the construction of the limit. Take a use of $v$ in block $y$, after any [definition](#def-b3-program-optimisation-reaching) of $v$ in $y$ (otherwise treat the start of $y$ the same way), and a path $\pi$ from the entry to $y$. Let $x$ be the last block of $D$ on $\pi$, $y$ included; it exists, since $v$ is defined before it is used. If $x \ne y$ and $x$ did not strictly dominate $y$, [Lemma 8.9](#lem-b3-program-optimisation-leave) applied to the part of $\pi$ from $x$ to $y$ would give a later block of $\mathrm{DF}(x) \subseteq D$ on $\pi$, contradicting the choice of $x$. So $x$ [dominates](#def-b3-program-optimisation-dominator) $y$.

Let $x'$ be the last block of $D$ on another path $\pi'$. Both dominate $y$, so one [dominates](#def-b3-program-optimisation-dominator) the other; suppose $x$ strictly [dominates](#def-b3-program-optimisation-dominator) $x'$. Since $x'$ does not dominate $x$, some path from the entry to $x$ avoids $x'$. Follow it, then the part of $\pi$ after its last visit to $x$: that part contains no block of $D$ but $x$, so it avoids $x'$ too, and the whole is a path from the entry to $y$ that avoids $x'$, which contradicts $x'$ dominating $y$. So $x = x'$: every path reaches the use through the same last [definition](#def-b3-program-optimisation-reaching). ∎

Renaming then walks the [dominator](#def-b3-program-optimisation-dominator) tree from the entry, with a stack of current names per variable: a [definition](#def-b3-program-optimisation-reaching) 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](#out-b3-program-optimisation-ssa) 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](#def-b3-program-optimisation-dominator), immediate [dominators](#def-b3-program-optimisation-dominator) 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-optimisation/fig-ecb315b9fcc5.svg)

*The [dominator](#def-b3-program-optimisation-dominator) tree of `sumsq` (solid), each block below its immediate [dominator](#def-b3-program-optimisation-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](#def-b3-program-optimisation-reaching), and many of the analyses of the next section become a single pass. The program in this chapter stays in [three-address code](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#def-b3-code-generation-tac) 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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation): 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 $k$, 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 $k$ where the fact says $k$, 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.

```rust
/// 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*

```rust
/// 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](#def-b3-program-optimisation-constprop)’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](#def-b3-program-optimisation-lfp) maps $t$ to the constant $k$ at a point, then on every execution that reaches that point, $t$ holds $k$ 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](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-phases) 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 $x$ by $y$ where the copy $x = y$ is *available*: on every path to the point, it was executed and neither $x$ nor $y$ 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](#def-b3-program-optimisation-liveness) 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](#lst-b3-program-optimisation-dce) removes [dead code](#def-b3-program-optimisation-others), with the [liveness](#def-b3-program-optimisation-liveness) of the previous section. Each is proved correct the way [constant propagation](#def-b3-program-optimisation-constprop) was: the fact holds on every execution, and under the fact the transformation changes no value that is ever read.

```rust
/// 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](#def-b3-program-optimisation-reaching) 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](#exo-b3-program-optimisation-4) predicts the result on a program that folds entirely.

**Remark 8.14.**

The [fixed point](#def-b3-program-optimisation-lfp) that [constant propagation](#def-b3-program-optimisation-constprop) computes is not the best possible fact. In `if c > 0 { a = 2; b = 3; } else { a = 3; b = 2; } x = a + b;`, $x$ is 5 on both paths, yet the join at the end of the `if` makes `a` and `b` both $\top$ before the addition, and $x$ is found $\top$. Exercise [8.10](#exo-b3-program-optimisation-10) shows that this happens because the [transfer functions](#def-b3-program-optimisation-framework) of [constant propagation](#def-b3-program-optimisation-constprop) do not distribute over joins.

One more transformation is told and left as exercise [8.12](#exo-b3-program-optimisation-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](#def-b3-program-optimisation-dominator) give the loops: an edge $b \to h$ such that $h$ [dominates](#def-b3-program-optimisation-dominator) $b$ is a *back edge*, and the blocks that can reach $b$ without passing through $h$ form, with $h$, 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](#def-b3-program-optimisation-liveness) in a register, and which, or in memory. Two temporaries *interfere* if one is written at a point where the other is [live](#def-b3-program-optimisation-liveness) 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](#lst-b3-program-optimisation-interference) builds the graph from the [live](#def-b3-program-optimisation-liveness) sets after each instruction. The parameters arrive together, in `a0`, `a1`, …, so they interfere with each other and with whatever is [live](#def-b3-program-optimisation-liveness) at the entry.

```rust
/// 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](#def-b3-program-optimisation-regalloc): each [definition](#def-b3-program-optimisation-reaching) against the temporaries [live](#def-b3-program-optimisation-liveness) 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 $k$ colours gives each vertex one of $k$ colours so that the two ends of every edge differ. It encoded the question “does a $k$-colouring exist?” as a satisfiability problem.

A $k$-colouring of the [interference graph](#def-b3-program-optimisation-regalloc) is an allocation with $k$ registers. Deciding whether a graph has one is NP-complete for every fixed $k \ge 3$, as chapter [17](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#ch-b3-np-completeness) proves for $k = 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 $v$ of $G$ has fewer than $k$ neighbours, then $G$ is $k$-colourable if and only if $G - v$ is.

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

**Definition 8.17 (Spill).**

A *spilled* temporary [lives](#def-b3-program-optimisation-liveness) in a slot of the frame instead of a register, and is loaded before each use and stored after each [definition](#def-b3-program-optimisation-reaching). Its *spill cost* estimates the memory accesses this adds: here, each use or [definition](#def-b3-program-optimisation-reaching) counts $10^{d}$, with $d$ the depth of the loops around it.

The allocator ([Listing 8.10](#lst-b3-program-optimisation-colour)) repeats the proposition: while some vertex has fewer than $k$ neighbours, it removes it and pushes it on a stack (*simplify*). When none has, it removes the vertex with the least [spill cost](#def-b3-program-optimisation-spill) per neighbour and marks it [spilled](#def-b3-program-optimisation-spill) (*[spill](#def-b3-program-optimisation-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.

```rust
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](#def-b3-program-optimisation-spill) and select. A [spilled](#def-b3-program-optimisation-spill) temporary is not coloured; it keeps a stack slot. code/bachelor-3/08-program-optimisation/listings/regalloc.rs*

[Output 8.3](#out-b3-program-optimisation-colour) optimises `sumsq`, builds its [interference graph](#def-b3-program-optimisation-regalloc) and colours it. `n`, `s`, `i` and `t3` are all [live](#def-b3-program-optimisation-liveness) after `t3 = i * i`, so they form a clique and need four registers; with three, one of them is [spilled](#def-b3-program-optimisation-spill), 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](#def-b3-program-optimisation-regalloc) with each temporary’s [spill cost](#def-b3-program-optimisation-spill) 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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-program-optimisation/fig-54ae54e8f2c5.svg)

*The [interference graph](#def-b3-program-optimisation-regalloc) of `sumsq`, 6 vertices and 10 edges as in [Output 8.3](#out-b3-program-optimisation-colour), 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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation) is adapted in one place: an operand in a register is used where it is, and only a [spilled](#def-b3-program-optimisation-spill) one is loaded into a scratch register ([Listing 8.11](#lst-b3-program-optimisation-get)). A result is computed straight into its register, and stored only if it is [spilled](#def-b3-program-optimisation-spill).

```rust
    /// 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](#def-b3-program-optimisation-spill), for instance when the merged vertex has fewer than $k$ neighbours of degree $k$ or more.

## 8.5 Measured

`moorc_opt` compiles at three levels: `-O0` is chapter [7](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation)’s compiler, `-O1` runs the optimisations of this chapter and keeps every temporary on the stack, and `-O2` adds the allocator. [Output 8.4](#out-b3-program-optimisation-measured) 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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation) 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](#def-b3-program-optimisation-liveness) 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 < 2$ before saving anything, as gcc did in chapter [7](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation), 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](#def-b3-program-optimisation-regalloc) 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](#def-b3-program-optimisation-ssa) efficiently, with [dominance frontiers](#def-b3-program-optimisation-dominator).

## 8.6 Exercises

**Exercise 8.1 ★.**

In `sumsq` ([Output 8.1](#out-b3-program-optimisation-live)), which temporaries are [live](#def-b3-program-optimisation-liveness) after `s = 0`, after `sq = t3` and after `t6 = i + 1`? Which is [live](#def-b3-program-optimisation-liveness) at the entry, and why only that one?

**Solution of Exercise 8.1.**

After `s = 0`: $\{n, s\}$; after `sq = t3`: $\{n, s, i, sq\}$; after `t6 = i + 1`: $\{n, s, t6\}$, since `i` is overwritten by the next instruction before any read. At the entry only `n` is [live](#def-b3-program-optimisation-liveness): `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](#def-b3-program-optimisation-dominator) and the immediate [dominator](#def-b3-program-optimisation-dominator) of each block of the function `f` of chapter [7](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#ch-b3-code-generation)’s exercise [7.9](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#exo-b3-code-generation-9), a `while` loop with a `return` inside.

**Solution of Exercise 8.2.**

With the blocks of that exercise’s solution: B0 (the loop’s test, also the entry) $\{0\}$; B1 $\{0, 1\}$; B2 $\{0, 2\}$; B3 $\{0, 2, 3\}$; B4 $\{0, 2, 4\}$; B6 $\{0, 2, 3, 6\}$; B7 $\{0, 2, 3, 6, 7\}$; B8 $\{0, 1, 8\}$. B5 and B9 are unreachable and have none. The immediate [dominators](#def-b3-program-optimisation-dominator) are B0 for B1 and B2, B2 for B3 and B4, B3 for B6, B6 for B7 and B1 for B8: the [dominator](#def-b3-program-optimisation-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 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](#def-b3-program-optimisation-dominator) everything after it. So $\mathrm{DF}^{+}(\{\mathrm{B0}, \mathrm{B2}, \mathrm{B7}\}) = \{\mathrm{B4}, \mathrm{B5}\}$ and $\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:

$$
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](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#def-b3-code-generation-tac) 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 of Exercise 8.4.**

Round 1 propagates $a = 6$, folds $b = 42$ and $c = 2$, decides the branch ($2 > 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](#def-b3-program-optimisation-liveness) with the direction set to forward and nothing else changed. On `sumsq` it says that nothing is [live](#def-b3-program-optimisation-liveness) at the entry and that `n`, `s` and `i` are [live](#def-b3-program-optimisation-liveness) after the final `return`. Explain both answers from the equations, and say what an allocator would do with them.

**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](#def-b3-program-optimisation-liveness)”, 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](#def-b3-program-optimisation-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 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 = 9$ (`exercise_6_dead_stores`).

**Exercise 8.7 ★★.**

Prove that the [worklist algorithm](#thm-b3-program-optimisation-kleene) visits blocks at most $n + h \cdot e$ times, for $n$ blocks, $e$ edges and a lattice of height $h$ per block.

**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 $h$ times. Each change puts at most $\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 + \sum_b h \cdot \mathrm{out}(b) = n + h \cdot e$. For [liveness](#def-b3-program-optimisation-liveness) on `sumsq` the bound is $6 + 7 \times 5 = 41$, with $h = 7$ temporaries (`n`, `s`, `i`, `t3`, `sq`, `t5`, `t6`) and $e = 5$ edges; the actual count is 12.

**Exercise 8.8 ★★.**

Colour the [interference graph](#def-b3-program-optimisation-regalloc) of [Output 8.3](#out-b3-program-optimisation-colour) with three registers, or prove that a [spill](#def-b3-program-optimisation-spill) is needed.

**Solution of Exercise 8.8.**

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

**Exercise 8.9 ★★.**

A nest of $d$ `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](#thm-b3-program-optimisation-phi) put, as a function of $d$? How many are useful?

**Solution of Exercise 8.9.**

$d(d + 3)/2$: 2, 5, 9, 14, 20 for $d = 1, \dots, 5$ (`exercise_9_phis_of_nested_loops`). `s` is assigned in the innermost body, whose iterated frontier contains every header: $d$ $\phi$-functions. The counter of the loop at depth $j$ is assigned before its loop, in the body of the loop at depth $j - 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 - 1$ loops around it: $j$ $\phi$-functions, $d(d+1)/2$ in all. Only $2d$ are useful: `s` is [live](#def-b3-program-optimisation-liveness) 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](#def-b3-program-optimisation-liveness) gives the *pruned* SSA form, with $2d$.

**Exercise 8.10 ★★★.**

A framework is *distributive* if $f(x \sqcup y) = f(x) \sqcup f(y)$ for every [transfer function](#def-b3-program-optimisation-framework). Show that [constant propagation](#def-b3-program-optimisation-constprop) is not, with the program of the remark in [Section 8.3](#sec-8-3), and prove that for a distributive framework the [least fixed point](#def-b3-program-optimisation-lfp) equals the join, over all paths to a point, of the facts computed along each path.

**Solution of Exercise 8.10.**

Let $x_1 = \{a \mapsto 2, b \mapsto 3\}$ and $x_2 = \{a \mapsto 3, b \mapsto 2\}$ be the facts at the end of the two branches, and $f$ the transfer of `x = a + b`. Then $f(x_1) \sqcup f(x_2)$ maps $x$ to $5 \sqcup 5 = 5$, but $f(x_1 \sqcup x_2) = f(\{a \mapsto \top, b \mapsto \top\})$ maps $x$ to $\top$ (`exercise_10_not_distributive`).

For the theorem, let $\mathrm{MOP}(b)$ be the join over all paths $p$ from the entry to $b$ of $f_p(\mathit{boundary})$, $f_p$ being the composition of the transfers along $p$; the lattice has finite height, so this join is a finite one. First, $\mathrm{MOP} \sqsubseteq$ the [least fixed point](#def-b3-program-optimisation-lfp) $X$ in any [monotone framework](#def-b3-program-optimisation-framework): by induction on the length of $p$, $f_p(\mathit{boundary}) \sqsubseteq X(b)$, since each step applies a monotone transfer and $X$ satisfies the equations. Second, if every $f_B$ distributes over joins, MOP satisfies the equations: the join over the predecessors $P$ of $f_P(\mathrm{MOP}(P))$ is the join over $P$ of the join over the paths to $P$ of $f_P(f_p(\mathit{boundary}))$, which is the join over all paths to $b$. So MOP is a [fixed point](#def-b3-program-optimisation-lfp), and the [least fixed point](#def-b3-program-optimisation-lfp) is below it. The two are equal. For [constant propagation](#def-b3-program-optimisation-constprop) the [least fixed point](#def-b3-program-optimisation-lfp) 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](#def-b3-program-optimisation-regalloc) of a program in SSA form, with interference defined at [definitions](#def-b3-program-optimisation-reaching), is chordal. Prove that a chordal graph has a vertex whose neighbours form a clique, deduce that simplify never gets stuck when $k$ is at least the largest clique, and conclude that such a program needs exactly as many registers as the most temporaries [live](#def-b3-program-optimisation-liveness) at one point.

**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 $G$ is not complete, take non-adjacent $a, b$ and a minimal set $S$ separating them. $S$ is a clique: for $u, v \in S$, both have neighbours in the component $A$ of $a$ and in the component $B$ of $b$ of $G - S$ (otherwise $S$ would not be minimal), so there are shortest paths $u \dots v$ through $A$ and through $B$; together they form a cycle of length at least 4 whose only possible chord is $uv$, since $A$ and $B$ are not joined. By induction, $G[A \cup S]$ has a simplicial vertex in $A$ (two non-adjacent ones if it is not complete, and they cannot both be in the clique $S$; if it is complete, any vertex of $A$), and its neighbours in $G$ are all in $A \cup S$, so it is simplicial in $G$; the same in $B$.

A simplicial vertex in a graph whose largest clique has $\omega$ vertices has at most $\omega - 1$ neighbours. Removing a vertex leaves a chordal graph, an induced subgraph. So if $k \ge \omega$, simplify always finds a vertex of degree less than $k$, never [spills](#def-b3-program-optimisation-spill), 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](#def-b3-program-optimisation-liveness) together at one point (the [definition](#def-b3-program-optimisation-reaching) of the one defined last, which the others’ [definitions](#def-b3-program-optimisation-reaching) dominate), so $\omega$ is the largest number of temporaries [live](#def-b3-program-optimisation-liveness) 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 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$, as on the processor. In a language where division by zero stops the program, only an operation that [dominates](#def-b3-program-optimisation-dominator) 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 = 6$ and $b = 7$ both versions print $\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](#out-b3-program-optimisation-pbgraph) gives the [interference graph](#def-b3-program-optimisation-regalloc) of the program after `-O1` and two colourings; [Output 8.6](#out-b3-program-optimisation-pbcounts) compiles it at each level, with fewer and fewer registers, and counts.

```text
    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](#def-b3-program-optimisation-regalloc) of `billing.moor` after `-O1`, and colourings with seven and six registers. `t0` is `n`: [copy propagation](#def-b3-program-optimisation-others) 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](#def-b3-program-optimisation-liveness) 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](#def-b3-program-optimisation-liveness) across the test `fine > cap` , and `days` not after the computation of `fine` ?
4. Which temporaries are [live](#def-b3-program-optimisation-liveness) 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.**

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

**Part III — Fewer registers.**

13. With six registers, which temporary is [spilled](#def-b3-program-optimisation-spill) , and why that one by the cost per neighbour?
14. Count, from the program, the extra loads that spilling `t0` adds per iteration of each loop, and check against the table.
15. With five registers, which temporaries would you expect to be [spilled](#def-b3-program-optimisation-spill) next? Check the table’s loads and stores.
16. Why do the counts with 12 and with 8 registers coincide, while 6 differ? (8 is not in the table; argue from the graph.)
17. With one register, half the temporaries are [spilled](#def-b3-program-optimisation-spill) . Why is the count still well below `-O1` ’s?
18. Plot or tabulate the instructions against $k$ . Where is the largest step?

**Part IV — The counts.**

19. In the hot loop, what fraction of `-O0` ’s loads and stores does `-O1` remove, and what fraction of its instructions?
20. 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.
21. Where do the 385 loads that remain in the whole run with 12 registers come from? And the 385 stores?
22. How many instructions does one iteration of the hot loop execute at `-O1` , and at `-O2` , on average?
23. What would coalescing save on this loop? Count the `mv` instructions in it.
24. 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 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](#def-b3-program-optimisation-constprop): 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](#def-b3-program-optimisation-liveness).

**6.** Each use or [definition](#def-b3-program-optimisation-reaching) of `i` weighted by $10^{\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](#out-b3-program-optimisation-pbgraph). 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](#def-b3-program-optimisation-liveness) from its [definition](#def-b3-program-optimisation-reaching) 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](#def-b3-program-optimisation-liveness) throughout the loop: an edge. `t14` and `t16` are in different branches of the `if`; neither is [live](#def-b3-program-optimisation-liveness) 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.4$, against $22/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 = 1142$. In the hot loop, $378 + 379 = 757$ loads and stores. The [spill](#def-b3-program-optimisation-spill)’s store replaces that register’s save: the stores stay at 385.

**15.** `total` is [spilled](#def-b3-program-optimisation-spill) next (`color_demo` with $k = 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 \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](#def-b3-program-optimisation-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](#def-b3-program-optimisation-spill) temporary costs a load per use and a store per [definition](#def-b3-program-optimisation-reaching), as at `-O1`, but the operands in the register cost nothing, and the [code generator](https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation#def-b3-code-generation-selection) 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](#def-b3-program-optimisation-spill) the loop counter `i`, then from 3 to 2 (1,771), which [spills](#def-b3-program-optimisation-spill) `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 \approx 37.8$ at `-O1` and $7{,}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](#def-b3-program-optimisation-liveness) 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](#def-b3-program-optimisation-liveness) at once; below that, each [spilled](#def-b3-program-optimisation-spill) temporary costs about one access per use in the loop.
