---
title: "Intermediate Code and Code Generation"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 7
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/7-intermediate-code-and-code-generation
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 7 — Intermediate Code and Code Generation

Chapters [1](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#ch-b3-lexical-analysis) to [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis) turned the text of a Moor program into a tree whose names are resolved and whose types are checked, and the interpreter of chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis) ran that tree. This chapter makes the tree into a program for a machine: the RISC-V subset of the Year 2 volume, run by `rv`. It goes there in two steps. The tree is first flattened into a simple intermediate code with one operator per instruction and explicit jumps, then each intermediate instruction is replaced by a few machine instructions. The result is slow, and the next chapter makes it faster. Here the point is that it is right: on every sample, the compiled program prints what the interpreter prints.

## 7.1 Three-address code

A tree is a good shape for checking a program and a poor one for running it. A machine has no nested expressions: it has registers, memory, and instructions that each do one operation and then go on to the next one or jump. Between the two sits a representation with the machine’s shape and none of its details.

**Definition 7.1 (Intermediate representation).**

An *intermediate representation* is a form of the program, between the source and the target code, on which a compiler translates, analyses and transforms. A tree is a high-level intermediate representation; the code below is a low-level one.

**Definition 7.2 (Three-address code, temporary).**

*Three-address code* is a list of instructions of the forms $t = a \mathbin{\mathit{op}} b$, $t = \mathit{op}\,a$, $t = a$, loads and stores, labels $L\!:$, $\mathtt{goto}\ L$, $\mathtt{if}\ a \mathbin{\mathit{rel}} b\ \mathtt{goto}\ L$, calls and returns. Each names at most three places, its *addresses*: two operands and a result. An operand is a constant or a *temporary*, a named place for a value with no limit on how many there are; temporaries are also called *virtual registers*. Stored as a record of an operator and three addresses, an instruction is a *quadruple*.

[Listing 7.1](#lst-b3-code-generation-tac) is Moor’s [three-address code](#def-b3-code-generation-tac) as a Rust type. A local variable or a parameter is a [temporary](#def-b3-code-generation-tac) like any other, and only globals and arrays live in memory. The operators are those of the tree, except `&&` and `||`, which become jumps.

```rust
pub enum Val {
    T(u32),  // a temporary: a local, a parameter or an intermediate result
    K(i32),  // a constant
}

#[derive(Clone, Debug, PartialEq)]
pub enum Tac {
    Bin(u32, BinOp, Val, Val),         // t = a op b, op neither && nor ||
    Neg(u32, Val),                     // t = -a
    Not(u32, Val),                     // t = !a
    Copy(u32, Val),                    // t = a
    LoadG(u32, String),                // t = g
    StoreG(String, Val),               // g = a
    LoadA(u32, String, Val),           // t = arr[i]
    StoreA(String, Val, Val),          // arr[i] = a
    Label(u32),                        // L:
    Jump(u32),                         // goto L
    Branch(BinOp, Val, Val, u32),      // if a rel b goto L
    Call(Option<u32>, String, Vec<Val>),
    Ret(Option<Val>),
}
```

***Listing 7.1.** [Three-address code](#def-b3-code-generation-tac): values are temporaries or constants; every instruction does one thing. code/bachelor-3/07-code-generation/listings/tac.rs*

The translation of an expression walks the tree and returns where its value is ([Listing 7.2](#lst-b3-code-generation-expr)). A constant is its own place and costs no instruction. A local variable is already in its [temporary](#def-b3-code-generation-tac). An operator translates its operands first, then allocates a new [temporary](#def-b3-code-generation-tac) for its own result and emits one instruction. A negative literal such as `-5` is folded into the constant $-5$ here, and the reason is told in exercise [7.12](#exo-b3-code-generation-12).

```rust
    fn expr(&mut self, e: &Expr) -> Val {
        match &e.kind {
            ExprKind::Int(n) => Val::K(*n as i32),
            ExprKind::Bool(b) => Val::K(*b as i32),
            ExprKind::Var(_) => match self.place(e.span.start) {
                Ok(t) => Val::T(t),
                Err(g) => { let t = self.temp(); self.emit(Tac::LoadG(t, g)); Val::T(t) }
            },
            ExprKind::Unary(UnOp::Neg, a) if matches!(a.kind, ExprKind::Int(_)) => {
                let ExprKind::Int(n) = a.kind else { unreachable!() };
                Val::K((n as i32).wrapping_neg()) // a negative literal
            }
            ExprKind::Unary(op, a) => {
                let v = self.expr(a);
                let t = self.temp();
                self.emit(if *op == UnOp::Neg { Tac::Neg(t, v) } else { Tac::Not(t, v) });
                Val::T(t)
            }
            ExprKind::Binary(BinOp::And | BinOp::Or, ..) => {
                // a value from jumping code: t = 1 on one path, 0 on the other
                let (t, yes, no, end) = (self.temp(), self.label(), self.label(), self.label());
                self.cond(e, yes, no);
                self.emit(Tac::Label(yes));
                self.emit(Tac::Copy(t, Val::K(1)));
                self.emit(Tac::Jump(end));
                self.emit(Tac::Label(no));
                self.emit(Tac::Copy(t, Val::K(0)));
                self.emit(Tac::Label(end));
                Val::T(t)
            }
            ExprKind::Binary(op, a, b) => {
                let (va, vb) = (self.expr(a), self.expr(b));
                let t = self.temp();
                self.emit(Tac::Bin(t, *op, va, vb));
                Val::T(t)
            }
```

***Listing 7.2.** Expressions: operands first, then one instruction into a fresh [temporary](#def-b3-code-generation-tac). `&&` and `||` produce their value by jumping. code/bachelor-3/07-code-generation/listings/tac.rs*

[Output 7.1](#out-b3-code-generation-tac) translates `expr.moor`. Its first lines are the expression $c = (a + b) \times (a - 2) / b$: each operator of the tree became one instruction, in the order of a post-order walk, and each interior node one [temporary](#def-b3-code-generation-tac) (the figure below).

```
$ rustc --edition 2021 -O -o tac_demo tac_demo.rs && ./tac_demo expr.moor
main: 7 temporaries
  0      a = 6
  1      b = 7
  2      t2 = a + b
  3      t3 = a - 2
  4      t4 = t2 * t3
  5      t5 = t4 / b
  6      c = t5
  7      if a < b goto L4
  8      goto L2
  9  L4:
 10      if c == 0 goto L1
 11      goto L5
 12  L5:
 13      if b != 1 goto L1
 14      goto L2
 15  L1:
 16      call print(c)
 17      goto L3
 18  L2:
 19  L3:
 20      return c
 21      return
```

***Output 7.1.** The [three-address code](#def-b3-code-generation-tac) of `expr.moor`, numbered. Temporaries that hold a variable print with its name.*

![The expression of expr.moor as a tree and as quadruples, one per interior node plus the final copy. The temporary beside each node holds its value. The leaves need no instruction: they are variables, already in temporaries, or constants.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-code-generation/fig-67640d021a70.svg)

*The expression of `expr.moor` as a tree and as [quadruples](#def-b3-code-generation-tac), one per interior node plus the final copy. The [temporary](#def-b3-code-generation-tac) beside each node holds its value. The leaves need no instruction: they are variables, already in temporaries, or constants.*

The temporaries are numbered from 0 in each function, and the variables `a`, `b` and `c` are temporaries 0, 1 and 6. A [temporary](#def-b3-code-generation-tac) is written once by the expression that creates it and never reused, which costs memory and buys simplicity: a value, once computed, stays where it was put until the function returns. The next chapter will make the temporaries share registers.

### 7.1.1 Conditions as jumps

Moor’s `&&` and `||` do not evaluate their right operand when the left one decides the result. In `d != 0 && n / d > 1`, the division must not happen when `d` is 0. A translation that computes both operands and then combines them is therefore wrong, not only slow. The translation of a condition is instead a piece of code that jumps.

**Definition 7.3 (Jumping code, label generation).**

The *jumping code* of a condition $e$ for two labels $L_{\mathrm{t}}$ and $L_{\mathrm{f}}$ is code that evaluates as much of $e$ as needed and then jumps to $L_{\mathrm{t}}$ if $e$ is true and to $L_{\mathrm{f}}$ if it is false. The labels are made before the code that jumps to them, with fresh numbers: this is *label generation*. A one-pass generator that emits machine words directly cannot name a label it has not placed yet; it emits the jump with an empty target, records it, and fills the target in when the label’s address is known, which is *back-patching*.

[Listing 7.3](#lst-b3-code-generation-cond) is the whole of it. For $a \mathbin{\&\&} b$, a false $a$ jumps straight to $L_{\mathrm{f}}$ and a true $a$ goes on to the code of $b$. `||` is the mirror image, and `!` swaps the two labels without emitting anything. A comparison is one conditional branch and one jump. Any other boolean, a variable or a call, is compared with 0. A boolean that is stored rather than tested, as in `var ok = x > 0 && y > 0;`, is made from [jumping code](#def-b3-code-generation-jumping) by the arm of [Listing 7.2](#lst-b3-code-generation-expr) that writes 1 on one path and 0 on the other.

```rust
    /// Jumping code: go to `yes` if e is true, to `no` if it is false.
    fn cond(&mut self, e: &Expr, yes: u32, no: u32) {
        match &e.kind {
            ExprKind::Binary(BinOp::And, a, b) => {
                let mid = self.label();
                self.cond(a, mid, no); // a false: b is never evaluated
                self.emit(Tac::Label(mid));
                self.cond(b, yes, no);
            }
            ExprKind::Binary(BinOp::Or, a, b) => {
                let mid = self.label();
                self.cond(a, yes, mid); // a true: b is never evaluated
                self.emit(Tac::Label(mid));
                self.cond(b, yes, no);
            }
            ExprKind::Unary(UnOp::Not, a) => self.cond(a, no, yes),
            ExprKind::Binary(op, a, b) if relation(*op) => {
                let (va, vb) = (self.expr(a), self.expr(b));
                self.emit(Tac::Branch(*op, va, vb, yes));
                self.emit(Tac::Jump(no));
            }
            _ => {
                let v = self.expr(e);
                self.emit(Tac::Branch(BinOp::Ne, v, Val::K(0), yes));
                self.emit(Tac::Jump(no));
            }
        }
    }
```

***Listing 7.3.** [Jumping code](#def-b3-code-generation-jumping) for conditions. The right operand of `&&` is reached only from the place where the left one was true. code/bachelor-3/07-code-generation/listings/tac.rs*

In [Output 7.1](#out-b3-code-generation-tac), instructions 7 to 14 are the condition `a < b && (c == 0 || b != 1)`. Instruction 7 tests `a < b` and jumps to the right operand at L4 only if it holds; instruction 10 tests `c == 0` and, when it fails, goes on at L5 to the test of `b != 1`. Each comparison is reached only on the paths where the operators before it have not yet decided the result. Exercise [7.8](#exo-b3-code-generation-8) turns this into a proof. [Output 7.2](#out-b3-code-generation-shortcircuit) compiles the program, lists its branches and jumps, and runs it: of the three branches executed, two were taken (`a < b` and `b != 1`), so `c == 0` was false and the right operand of `||` was needed.

```
$ rustc --edition 2021 -O -o moorc $CH/moorc.rs
$ ./moorc expr.moor > expr.S
$ grep -n -E '^    (b|j )' expr.S
29:    blt t0, t1, .Lmain_4
30:    j .Lmain_2
34:    beq t0, t1, .Lmain_1
35:    j .Lmain_5
39:    bne t0, t1, .Lmain_1
40:    j .Lmain_2
48:    j .Lmain_3
52:    j .Lmain_ret
54:    j .Lmain_ret
$ python -m rv run expr.S --stats
7
--- stats ---
instructions        45
loads               15
stores               8
branches             3  (2 taken)
jumps                4
ecalls               2
```

***Output 7.2.** `expr.moor` compiled: its conditional branches and jumps, then a run that prints $c = 7$.*

## 7.2 Control-flow graphs

[Three-address code](#def-b3-code-generation-tac) is a list, and the jumps make it a graph. The analyses of the next chapter work on that graph, whose nodes are the straight runs of the list.

**Definition 7.4 (Basic block, leader).**

A *basic block* is a maximal sequence of consecutive instructions that control can enter only at the first and leave only at the last. A *leader* is the first instruction of a block: the first instruction of the function, every label, and every instruction that follows a jump, a branch or a return.

**You already know.**

The Year 1 volume drew a function’s control-flow graph to measure how much of it its tests cover: one node per straight run of code, one edge per way control can pass from one to the next. For [three-address code](#def-b3-code-generation-tac), the nodes are the [basic blocks](#def-b3-code-generation-cfg), and there is an edge from $B$ to $C$ when control can pass from the end of $B$ to the start of $C$: by a jump or a taken branch to $C$’s label, or by falling through when $C$ follows $B$ and $B$ does not end in a jump or a return.

**Proposition 7.5 (Blocks from leaders).**

Cutting the code before each [leader](#def-b3-code-generation-cfg) gives exactly its [basic blocks](#def-b3-code-generation-cfg).

**Proof.** Within a piece from one [leader](#def-b3-code-generation-cfg) to the next, no instruction after the first is a label, so none can be jumped to, and none before the last is a jump, a branch or a return, so control leaves only at the end. Control therefore enters only at the first and leaves only at the last. The piece is maximal: the instruction after it is a [leader](#def-b3-code-generation-cfg), either a label, which may be entered from elsewhere, or the successor of a transfer, after which control may not arrive from the piece’s last instruction; in both cases joining it would break the definition. ∎

[Listing 7.4](#lst-b3-code-generation-cfg) computes the [leaders](#def-b3-code-generation-cfg), cuts the code into blocks and adds the edges: a jump has one successor, a branch two (taken first), a return none, and anything else falls through to the next block.

```rust
/// A leader starts a block: the first instruction, every label, and
/// every instruction that follows a jump, a branch or a return.
pub fn leaders(code: &[Tac]) -> Vec<usize> {
    let mut ls = vec![];
    for (i, ins) in code.iter().enumerate() {
        let after_transfer =
            i > 0 && matches!(code[i - 1], Tac::Jump(_) | Tac::Branch(..) | Tac::Ret(_));
        if i == 0 || matches!(ins, Tac::Label(_)) || after_transfer {
            ls.push(i);
        }
    }
    ls
}

pub fn build(f: &FuncTac) -> Cfg {
    let ls = leaders(&f.code);
    let ends = ls.iter().skip(1).copied().chain([f.code.len()]);
    let blocks: Vec<(usize, usize)> = ls.iter().copied().zip(ends).collect();
    let block_of_label =
        |l: u32| blocks.iter().position(|&(s, _)| f.code[s] == Tac::Label(l)).unwrap();
    let mut succ = vec![];
    for (k, &(_, end)) in blocks.iter().enumerate() {
        let next = if k + 1 < blocks.len() { vec![k + 1] } else { vec![] };
        succ.push(match &f.code[end - 1] {
            Tac::Jump(l) => vec![block_of_label(*l)],
            Tac::Branch(.., l) => {
                let target = block_of_label(*l);
                let fall: Vec<usize> = next.into_iter().filter(|&n| n != target).collect();
                [vec![target], fall].concat() // taken, then fall through
            }
            Tac::Ret(_) => vec![], // to the exit
            _ => next,
        });
    }
    Cfg { blocks, succ }
}
```

***Listing 7.4.** [Leaders](#def-b3-code-generation-cfg), blocks and edges. A block is a range of the code; successors are block numbers. code/bachelor-3/07-code-generation/listings/cfg.rs*

```
$ rustc --edition 2021 -O -o cfg_demo cfg_demo.rs && ./cfg_demo fib.moor
B0  (instructions 0..0)  -> B2, B1
        if n < 2 goto L1
B1  (instructions 1..1)  -> B4
        goto L2
B2  (instructions 2..3)  -> exit
        L1:
        return n
B3  (instructions 4..4)  -> B5
        goto L3
B4  (instructions 5..5)  -> B5
        L2:
B5  (instructions 6..12)  -> exit
        L3:
        t1 = n - 1
        t2 = call fib(t1)
        t3 = n - 2
        t4 = call fib(t3)
        t5 = t2 + t4
        return t5
B6  (instructions 13..13)  -> exit
        return
```

***Output 7.3.** The [basic blocks](#def-b3-code-generation-cfg) of `fib` and their successors. “exit” marks a block that ends in a return.*

![The control-flow graph of fib, from . The dashed blocks B3 and B6 have no predecessor: they are the jump that follows the then branch and the return added at the end of every function, and both follow a return, so no path from the entry reaches them.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-code-generation/fig-ca5aabd1a5b8.svg)

*The control-flow graph of `fib`, from [Output 7.3](#out-b3-code-generation-cfgout). The dashed blocks B3 and B6 have no predecessor: they are the jump that follows the `then` branch and the return added at the end of every function, and both follow a return, so no path from the entry reaches them.*

The graph of `fib` has two blocks that can never run. The translation of `if` always emits a jump over the `else` part, even when the `then` part ends in `return`, and every function gets a final `return` in case its body falls off the end. Removing such blocks is the simplest of the clean-ups of the next chapter; here they cost space and no time.

## 7.3 Translating control flow and calls

A statement translates into [three-address code](#def-b3-code-generation-tac) with labels made fresh for it ([Listing 7.5](#lst-b3-code-generation-stmt)). An `if` jumps to its `then` label or its `else` label by the [jumping code](#def-b3-code-generation-jumping) of its condition; both parts end at a common label. A `while` has a label at the top, tested on every iteration, and its body ends with a jump back to it.

```rust
            StmtKind::If(c, then, els) => {
                let (yes, no, end) = (self.label(), self.label(), self.label());
                self.cond(c, yes, no);
                self.emit(Tac::Label(yes));
                self.block(then);
                self.emit(Tac::Jump(end));
                self.emit(Tac::Label(no));
                if let Some(b) = els {
                    self.block(b);
                }
                self.emit(Tac::Label(end));
            }
            StmtKind::While(c, body) => {
                let (top, go, exit) = (self.label(), self.label(), self.label());
                self.emit(Tac::Label(top));
                self.cond(c, go, exit);
                self.emit(Tac::Label(go));
                self.block(body);
                self.emit(Tac::Jump(top));
                self.emit(Tac::Label(exit));
            }
            StmtKind::Return(e) => {
                let v = e.as_ref().map(|e| self.expr(e));
                self.emit(Tac::Ret(v));
            }
```

***Listing 7.5.** `if`, `while` and `return`. Each statement makes its own labels, so nesting needs no bookkeeping. code/bachelor-3/07-code-generation/listings/tac.rs*

**You already know.**

The Year 2 volume wrote RISC-V functions by hand under the processor’s standard calling convention. The ABI names: `ra` holds the return address, `sp` the stack pointer, `t0`–`t6` are temporaries, `a0`–`a7` argument registers, `s0`–`s11` saved registers. The eight argument registers carry the first arguments, and the first two also return the results. A callee must give back `sp` and `s0`–`s11` as it found them; `ra`, the `t` and the `a` registers it may overwrite. The stack grows downwards, and `sp` is a multiple of 16 on entry to a function. `call f` saves the return address in `ra` and jumps.

A function that calls another loses its own return address, since the call overwrites `ra`. It must save `ra` somewhere the callee will not touch, and its own part of the stack is the place.

**Definition 7.6 (Frame layout).**

The *frame* of a function is the block of stack it allocates on entry, by lowering `sp`, and frees on return. Its *layout* assigns each item that must outlive a call, such as temporaries, saved registers and outgoing arguments that do not fit in registers, a fixed offset from `sp`.

The [frame](#def-b3-code-generation-frame) is set up by the function’s prologue and freed by its epilogue, as in the Year 2 volume.

The naive compiler gives every [temporary](#def-b3-code-generation-tac) a word of the [frame](#def-b3-code-generation-frame), and a [temporary](#def-b3-code-generation-tac) lives there and nowhere else ([Listing 7.6](#lst-b3-code-generation-frame)). Above the temporaries is the saved `ra`, and the size is rounded up to 16 to keep `sp` aligned. Since all temporaries are in memory and the compiler uses only `t0`–`t2` and the `a` registers between two instructions of the intermediate code, no register needs to survive a call, and no `s` register is ever used or saved.

```rust
// frame.rs -- the stack frame of a function compiled naively: one word per
// temporary, then the saved return address, the size rounded up to 16.
#![allow(dead_code)]

#[derive(Clone, Copy)]
pub struct Frame {
    pub size: i32,   // bytes, a multiple of 16
    pub ra: i32,     // offset of the saved ra from sp
}

impl Frame {
    pub fn new(temps: u32) -> Frame {
        let used = 4 * temps as i32 + 4; // the temporaries, then ra
        let size = (used + 15) / 16 * 16;
        Frame { size, ra: size - 4 }
    }
    /// Offset from sp of temporary t.
    pub fn slot(&self, t: u32) -> i32 {
        4 * t as i32
    }
}
```

***Listing 7.6.** The [frame](#def-b3-code-generation-frame) of the naive compiler: four bytes per [temporary](#def-b3-code-generation-tac) from `sp` upwards, then `ra`. code/bachelor-3/07-code-generation/listings/frame.rs*

![The frame of fib: six temporaries at offsets 4t, then the saved ra at the top. 4 × 6 + 4 = 28 bytes, rounded up to 32. The offsets are those of Frame::new(6), which the test frames_of_fib_and_main checks.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-code-generation/fig-29398922de50.svg)

*The [frame](#def-b3-code-generation-frame) of `fib`: six temporaries at offsets $4t$, then the saved `ra` at the top. $4 \times 6 + 4 = 28$ bytes, rounded up to 32. The offsets are those of `Frame::new(6)`, which the test `frames_of_fib_and_main` checks.*

A call loads its arguments into `a0`, `a1`, …, emits `call`, and stores `a0` into the result’s slot ([Listing 7.7](#lst-b3-code-generation-call)). The three built-in functions become system calls of `rv` instead: `print` is “print integer” followed by “print character” with a newline, and `read` is “read integer”. The prologue of a function lowers `sp`, saves `ra` and stores the incoming arguments into their parameters’ slots; the epilogue, at a label every `return` jumps to, reloads `ra`, raises `sp` and returns ([Listing 7.8](#lst-b3-code-generation-function)).

```rust
    fn call(&mut self, d: Option<u32>, g: &str, args: &[Val]) -> Result<(), String> {
        if args.len() > 8 {
            return Err(format!("{g}: more than 8 arguments"));
        }
        for (k, a) in args.iter().enumerate() {
            self.load(*a, &format!("a{k}"));
        }
        match g {
            "print" => {
                for s in ["li a7, 1", "ecall", "li a0, 10", "li a7, 11", "ecall"] {
                    self.i(s.into());
                }
            }
            "print_char" => { self.i("li a7, 11".into()); self.i("ecall".into()) }
            "read" => { self.i("li a7, 5".into()); self.i("ecall".into()) }
            _ => self.i(format!("call {g}")),
        }
        if let Some(d) = d {
            self.store(d, "a0");
        }
        Ok(())
    }
```

***Listing 7.7.** A call: arguments into `a0`–`a7`, the result out of `a0`. The built-ins are system calls. code/bachelor-3/07-code-generation/listings/riscv.rs*

```rust
/// One function: prologue, body, epilogue.
pub fn function(f: &FuncTac, extra: Option<Extra>) -> Result<Vec<String>, String> {
    let frame = Frame::new(f.temps);
    let mut a = Asm { lines: vec![format!("{}:", f.name)], f, frame };
    a.i(format!("addi sp, sp, -{}", frame.size));
    a.i(format!("sw ra, {}(sp)", frame.ra));
    for (k, p) in f.params.iter().enumerate() {
        a.store(*p, &format!("a{k}"));
    }
    for ins in &f.code {
        if let Some(x) = extra {
            if x(ins, &frame, &mut a.lines) {
                continue;
            }
        }
        a.instr(ins)?;
    }
    a.lines.push(format!(".L{}_ret:", f.name));
    a.i(format!("lw ra, {}(sp)", frame.ra));
    a.i(format!("addi sp, sp, {}", frame.size));
    a.i("ret".into());
    Ok(a.lines)
}
```

***Listing 7.8.** One function: prologue, the body instruction by instruction, epilogue. `extra` lets a caller select some instructions itself. code/bachelor-3/07-code-generation/listings/riscv.rs*

**In practice — One exit per function.**

Every `return` of the generated code stores its value in `a0` and jumps to the single epilogue. A function with ten returns then restores its [frame](#def-b3-code-generation-frame) in one place, and when the [frame](#def-b3-code-generation-frame) changes, as it will when the next chapter saves `s` registers, only that place changes. Copying the epilogue to each return is an optimisation, and it is safe only once the [frame](#def-b3-code-generation-frame) is final.

## 7.4 Selecting instructions

**Definition 7.7 (Instruction selection, code generator).**

*Instruction selection* chooses the target instructions that implement each operation of the [intermediate representation](#def-b3-code-generation-ir). A *code generator* is the part of a compiler that produces target code from the [intermediate representation](#def-b3-code-generation-ir): instruction selection, the layout of [frames](#def-b3-code-generation-frame) and data, and register allocation.

The simplest selection takes one intermediate instruction at a time: load the operands from their slots into `t0` and `t1`, compute into `t0`, store `t0` into the result’s slot ([Listing 7.9](#lst-b3-code-generation-bin)). Two refinements come free. A constant operand that fits in 12 signed bits goes into the immediate field of `addi`, saving a `li`; a subtraction of a constant is an addition of its negation. And the six comparisons are built from `slt`, the only comparison that writes a register: $a > b$ is $b < a$, $a \le b$ is $\lnot (b < a)$, so `slt` with swapped operands then `xori` with 1; equality is “the exclusive or is zero”, `seqz`. Modulo and negation are refused, and exercise [7.6](#exo-b3-code-generation-6) adds them.

```rust
    fn bin(&mut self, d: u32, op: BinOp, a: Val, b: Val) -> Result<(), String> {
        use BinOp::*;
        self.load(a, "t0");
        match (op, b) {
            (Add, Val::K(n)) if fits12(n) => self.i(format!("addi t0, t0, {n}")),
            (Sub, Val::K(n)) if fits12(-n) => self.i(format!("addi t0, t0, {}", -n)),
            _ => {
                self.load(b, "t1");
                let ops: &[&str] = match op {
                    Add => &["add t0, t0, t1"], Sub => &["sub t0, t0, t1"],
                    Mul => &["mul t0, t0, t1"], Div => &["div t0, t0, t1"],
                    Lt => &["slt t0, t0, t1"], Gt => &["slt t0, t1, t0"],
                    Le => &["slt t0, t1, t0", "xori t0, t0, 1"],
                    Ge => &["slt t0, t0, t1", "xori t0, t0, 1"],
                    Eq => &["xor t0, t0, t1", "seqz t0, t0"],
                    Ne => &["xor t0, t0, t1", "snez t0, t0"],
                    Rem => return Err("no instructions selected for '%' (exercise 6)".into()),
                    And | Or => unreachable!("translated as jumps"),
                };
                for s in ops {
                    self.i(s.to_string());
                }
            }
        }
        self.store(d, "t0");
        Ok(())
    }
```

***Listing 7.9.** Binary operators. Each comparison becomes one or two instructions around `slt`. code/bachelor-3/07-code-generation/listings/riscv.rs*

### 7.4.1 Tiling trees

Selecting one intermediate instruction at a time misses instructions that do more than one operation. RISC-V’s `lw 4(t2)` adds 4 to an address and loads, and `slli` by 2 multiplies by 4. To use them, a selector looks at the tree of an expression rather than at its [three-address code](#def-b3-code-generation-tac).

**Definition 7.8 (Tile, tiling).**

A *tile* is a tree pattern with a target instruction and a cost: the pattern `(mem (+ r c))` with $c$ a 12-bit constant is `lw c(r)` at cost 1. A *tiling* of an expression tree covers each of its nodes by exactly one tile, the tiles fitting together at their leaves, which are the results of other tiles. Its cost is the sum of the costs of its tiles, and an *optimal tiling* has the least cost.

**Theorem 7.9 (Optimal tiling by dynamic programming).**

Let $\mathrm{best}(n)$ be the least cost of a [tiling](#def-b3-code-generation-tiling) of the subtree rooted at $n$. Then

$$
\mathrm{best}(n) = \min_{\text{tile } T \text{ matching at } n} \Big( \mathrm{cost}(T) + \sum_{m \in \mathrm{leaves}(T, n)} \mathrm{best}(m) \Big),
$$

where $\mathrm{leaves}(T, n)$ are the subtrees left uncovered by $T$ placed at $n$. Computed from the leaves up, it takes time proportional to the number of nodes times the number of [tiles](#def-b3-code-generation-tiling), for a fixed set of [tiles](#def-b3-code-generation-tiling) of bounded size.

**Proof.** Every [tiling](#def-b3-code-generation-tiling) of the subtree at $n$ has exactly one [tile](#def-b3-code-generation-tiling) $T$ covering $n$, and the rest of it is a [tiling](#def-b3-code-generation-tiling) of each subtree in $\mathrm{leaves}(T, n)$; these subtrees are disjoint, so their [tilings](#def-b3-code-generation-tiling) are independent. The cost is $\mathrm{cost}(T)$ plus their costs, so it is at least the bracket for $T$, with equality when each subtree is tiled optimally. Taking the minimum over $T$ gives the least cost, by induction on the height of $n$: the subtrees in $\mathrm{leaves}(T, n)$ are strictly smaller, so their $\mathrm{best}$ is correct by hypothesis. Visiting children before parents, each node tries each [tile](#def-b3-code-generation-tiling) once, and a [tile](#def-b3-code-generation-tiling) of bounded size is matched and its leaves summed in constant time. ∎

The proof relies on one property of the problem: the best way to compute a subtree does not depend on what uses its result. This is optimal substructure, the condition the Year 1 volume gave for dynamic programming, and it holds because a [tile](#def-b3-code-generation-tiling)’s result is always a register. [Listing 7.10](#lst-b3-code-generation-tiles) lists the [tiles](#def-b3-code-generation-tiling) of a tiny selector: `li`, `la` (two words, `auipc` and `addi`), `add` and `addi`, `mul` and `slli` for a power of two, and `lw` with or without an offset. [Output 7.4](#out-b3-code-generation-tiling) applies it to the tree of `sq[i + 1] * 4 + 7`, the address of `sq[i + 1]` being written as $\&\mathtt{sq} + 4i + 4$.

```rust
/// Every tile that matches at n: (instruction, its cost, the subtrees it leaves).
fn tiles(n: &N) -> Vec<(String, u32, Vec<&N>)> {
    let mut t = vec![];
    match n {
        Reg(_) => t.push(("(in a register)".into(), 0, vec![])),
        Const(c) => t.push((format!("li {c}"), 1, vec![])),
        Addr(g) => t.push((format!("la {g}"), 2, vec![])),
        Add(a, b) => {
            t.push(("add".into(), 1, vec![&**a, &**b]));
            if let Some(c) = imm(b) { t.push((format!("addi {c}"), 1, vec![&**a])); }
        }
        Mul(a, b) => {
            t.push(("mul".into(), 1, vec![&**a, &**b]));
            if let Some(k) = shift(b) { t.push((format!("slli {k}"), 1, vec![&**a])); }
        }
        Load(a) => {
            t.push(("lw 0(r)".into(), 1, vec![&**a]));
            if let Add(x, y) = &**a {
                if let Some(c) = imm(y) { t.push((format!("lw {c}(r)"), 1, vec![&**x])); }
            }
        }
    }
    t
}
```

***Listing 7.10.** The [tiles](#def-b3-code-generation-tiling) that match at a node: each with its instruction, its cost and the subtrees it leaves to other [tiles](#def-b3-code-generation-tiling). code/bachelor-3/07-code-generation/listings/tiling.rs*

```rust
/// Children first, then the node: its cost is the cheapest tile plus the
/// best costs, already known, of the subtrees that tile leaves.
fn best(n: &N, memo: &mut HashMap<*const N, u32>, naive: &mut u32) -> u32 {
    for k in children(n) {
        best(k, memo, naive);
    }
    let options: Vec<(String, u32)> = tiles(n).into_iter()
        .map(|(ins, c, kids)| {
            let below: u32 = kids.iter().map(|k| memo[&(*k as *const N)]).sum();
            (ins, c + below)
        })
        .collect();
    *naive += tiles(n)[0].1; // the first tile covers this node alone
    let (ins, cost) = options.into_iter().min_by_key(|o| o.1).unwrap();
    println!("{:<40} {:<16} {cost:>2}", show(n), ins);
    memo.insert(n as *const N, cost);
    cost
}
```

***Listing 7.11.** The bottom-up computation of the theorem, children before parents. code/bachelor-3/07-code-generation/listings/tiling.rs*

```
$ rustc --edition 2021 -O -o tiling tiling.rs && ./tiling
subtree                                  best tile        cost
&sq                                      la sq             2
i                                        (in a register)   0
4                                        li 4              1
(* i 4)                                  slli 2            1
(+ &sq (* i 4))                          add               4
4                                        li 4              1
(+ (+ &sq (* i 4)) 4)                    addi 4            5
(mem (+ (+ &sq (* i 4)) 4))              lw 4(r)           5
4                                        li 4              1
(* (mem (+ (+ &sq (* i 4)) 4)) 4)        slli 2            6
7                                        li 7              1
(+ (* (mem (+ (+ &sq (* i 4)) 4)) 4) 7)  addi 7            7
optimal: 7 instructions; one tile per node: 12
```

***Output 7.4.** Every subtree, the [tile](#def-b3-code-generation-tiling) that [tiles](#def-b3-code-generation-tiling) it best, and its best cost, children first. One [tile](#def-b3-code-generation-tiling) per node would cost 12 instructions; the optimal [tiling](#def-b3-code-generation-tiling) costs 7.*

![The optimal tiling of : six tiles, seven instructions (la is two). Thick edges join the nodes of one tile, whose instruction is written beside its root; a dashed edge passes a result from one tile to another. The register i needs no tile. The tile lw 4(r) covers three nodes, the load, the addition and the constant 4; covering them one by one would cost a li, an add and a lw.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-code-generation/fig-95dc65dc2629.svg)

*The optimal [tiling](#def-b3-code-generation-tiling) of [Output 7.4](#out-b3-code-generation-tiling): six [tiles](#def-b3-code-generation-tiling), seven instructions (`la` is two). Thick edges join the nodes of one [tile](#def-b3-code-generation-tiling), whose instruction is written beside its root; a dashed edge passes a result from one [tile](#def-b3-code-generation-tiling) to another. The register `i` needs no [tile](#def-b3-code-generation-tiling). The [tile](#def-b3-code-generation-tiling) `lw 4(r)` covers three nodes, the load, the addition and the constant 4; covering them one by one would cost a `li`, an `add` and a `lw`.*

A selector built on the theorem needs trees, so it [tiles](#def-b3-code-generation-tiling) the tree of each statement, or trees rebuilt from the [three-address code](#def-b3-code-generation-tac) of a [basic block](#def-b3-code-generation-cfg). Our compiler does not: it selects from [three-address code](#def-b3-code-generation-tac) one instruction at a time, which is the [tiling](#def-b3-code-generation-tiling) with the smallest [tiles](#def-b3-code-generation-tiling), and it leaves every [temporary](#def-b3-code-generation-tac) in memory.

**Definition 7.10 (Naive allocator).**

The *naive allocator* keeps every [temporary](#def-b3-code-generation-tac) in its stack slot, loads its operands into fixed scratch registers before each instruction and stores the result after it.

It is the worst allocation that works, and it has a use: it makes every intermediate instruction independent of the others, so each can be translated and checked alone. Its cost is visible in [Listing 7.13](#lst-b3-code-generation-fibs): the value of `n - 1` is stored to `4(sp)` and loaded back from there into `a0` on the next line.

## 7.5 The whole compiler

The compiler `moorc` chains the parts: the [front end](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-phases) of chapters [1](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#ch-b3-lexical-analysis) to [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis), the translation to [three-address code](#def-b3-code-generation-tac), and the [code generator](#def-b3-code-generation-selection), which writes the globals as `.word`, the arrays as `.space`, then the functions ([Listing 7.12](#lst-b3-code-generation-moorc)). An array element `sq[i]` is at the address `la sq` plus $4i$.

```rust
fn main() {
    let file = std::env::args().nth(1).expect("usage: moorc FILE.moor");
    let src = std::fs::read_to_string(&file).expect("a readable file");
    let result = typecheck::check_source(&src, &file)
        .and_then(|(prog, res, _)| riscv::program(&prog, &tac::translate(&prog, &res), None));
    match result {
        Ok(asm) => print!("{asm}"),
        Err(msg) => {
            eprint!("{msg}");
            std::process::exit(1);
        }
    }
}
```

***Listing 7.12.** The driver: a type error stops it; otherwise the assembly goes to standard output. code/bachelor-3/07-code-generation/listings/moorc.rs*

```
$ rustc --edition 2021 -O -o moorc $CH/moorc.rs
$ ./moorc fib.moor > fib.S
$ wc -l fib.S
65 fib.S
$ echo 10 | python -m rv run fib.S --stats
10
55
--- stats ---
instructions      3464
loads             1063
stores             798
branches           177  (89 taken)
jumps              621
ecalls               3
```

***Output 7.5.** Building `moorc`, compiling `fib.moor` and running the result. `rv` echoes the number it reads, then the program prints $F(10) = 55$.*

```text
fib:
    addi sp, sp, -32
    sw ra, 28(sp)
    sw a0, 0(sp)
    lw t0, 0(sp)
    li t1, 2
    blt t0, t1, .Lfib_1
    j .Lfib_2
.Lfib_1:
    lw a0, 0(sp)
    j .Lfib_ret
    j .Lfib_3
.Lfib_2:
.Lfib_3:
    lw t0, 0(sp)
    addi t0, t0, -1
    sw t0, 4(sp)
    lw a0, 4(sp)
    call fib
    sw a0, 8(sp)
    lw t0, 0(sp)
    addi t0, t0, -2
    sw t0, 12(sp)
    lw a0, 12(sp)
    call fib
    sw a0, 16(sp)
    lw t0, 8(sp)
    lw t1, 16(sp)
    add t0, t0, t1
    sw t0, 20(sp)
    lw a0, 20(sp)
    j .Lfib_ret
    li a0, 0
    j .Lfib_ret
.Lfib_ret:
    lw ra, 28(sp)
    addi sp, sp, 32
    ret
```

***Listing 7.13.** The code of `fib` as `moorc` writes it (`main` follows). Every value goes through the stack. code/bachelor-3/07-code-generation/listings/fib.S*

**Remark 7.11.**

The instruction `j .Lfib_3` just after `j .Lfib_ret` is block B3 of the control-flow graph of `fib`: it cannot run, and it is translated anyway. The final `li a0, 0` and `j .Lfib_ret` are block B6. They cost four bytes each and no time.

### 7.5.1 Correctness

A compiler is [correct](#def-b3-code-generation-correctness) if it does not change what programs do. “What a program does” was defined in chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis), by an interpreter: its output and its exit code.

**Definition 7.12 (Compiler correctness).**

A compiler $C$ from a source language with semantics $\mathcal{S}$ to a target language with semantics $\mathcal{T}$ is *correct* if for every source program $P$ it accepts and every input $x$ such that $\mathcal{S}(P, x)$ is a normal termination with output $o$ and exit code $k$, $\mathcal{T}(C(P), x)$ is a normal termination with the same $o$ and $k$. The square below then *commutes*: both paths from $(P, x)$ end at the same behaviour.

![](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-code-generation/fig-810c44343bd3.svg)

The definition says nothing of programs that fail at run time. The interpreter stops on an array index out of bounds, and `moorc` emits no bounds check, so the compiled program reads or writes past the array. The definition is honest about it: the theorem holds only where the source semantics has a result. A deep recursion that the interpreter’s fuel allows may also overflow `rv`’s stack, and the definition does not cover it either.

The core of the argument is the translation of expressions. Write $\rho$ for the values of the variables and $\sigma$ for the contents of the temporaries.

**Theorem 7.13 (Expressions are translated correctly).**

Let $e$ be an expression without calls, `&&` or `||`, and let the code emitted by `expr(e)` start in a state where each variable’s [temporary](#def-b3-code-generation-tac) holds its value under $\rho$. Then it ends with its result, a constant or a [temporary](#def-b3-code-generation-tac), holding $[\![e]\!]\rho$, the value the interpreter computes, and with every [temporary](#def-b3-code-generation-tac) allocated before it unchanged.

**Proof.** By induction on $e$. A constant emits nothing and its result is the constant. A variable emits nothing and its result is its [temporary](#def-b3-code-generation-tac), which holds $\rho(x)$ by hypothesis; a global is loaded into a fresh [temporary](#def-b3-code-generation-tac), which holds its value. For $e_1 \mathbin{\mathit{op}} e_2$: by induction the code of $e_1$ leaves $[\![e_1]\!]\rho$ in its result $v_1$ and changes no older [temporary](#def-b3-code-generation-tac); the code of $e_2$ then leaves $[\![e_2]\!]\rho$ in $v_2$ and changes no [temporary](#def-b3-code-generation-tac) older than itself, $v_1$ included, because every [temporary](#def-b3-code-generation-tac) it writes is fresh. The last instruction writes $v_1 \mathbin{\mathit{op}} v_2$ into a fresh [temporary](#def-b3-code-generation-tac), and the interpreter computes the same operation, on 32-bit words with the same division rules. Unary operators are the same with one operand. ∎

Exercise [7.8](#exo-b3-code-generation-8) adds the [jumping code](#def-b3-code-generation-jumping), and the statements follow by the same kind of induction, one case per form, with a while loop needing an induction on the number of iterations. The second half of the argument is local: each intermediate instruction’s selected code does what the instruction says, on the slots. That is a finite list of cases, such as $a \le b$ being `slt t0, t1, t0` then `xori t0, t0, 1`, each checked once.

Proving a whole compiler [correct](#def-b3-code-generation-correctness) is possible, and has been done for a compiler of a real language (the history box below). This book tests the square instead. One test compiles every sample of this chapter and the Moor samples of chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis), runs each on `rv` and on the interpreter, and compares outputs and exit codes; `fib.moor` is checked for ten inputs. Exercise [7.12](#exo-b3-code-generation-12) adds random programs.

### 7.5.2 What a real compiler makes of it

[Output 7.6](#out-b3-code-generation-gcc) gives gcc the same function, written in C, for the laptop’s processor, an x86-64, with optimisation level 1. The instruction set is different, and this book does not teach it; three things can still be read off.

```
$ gcc --version | head -n 1
gcc (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0
$ gcc -S -O1 -fno-asynchronous-unwind-tables -fcf-protection=none -o fib.s fib.c
$ grep -vE '^\s+\.|^[0-9]+:' fib.s | expand -t 8
fib:
        movl    %edi, %eax
        cmpl    $1, %edi
        jle     .L5
        pushq   %rbp
        pushq   %rbx
        subq    $8, %rsp
        movl    %edi, %ebx
        leal    -1(%rdi), %edi
        call    fib
        movl    %eax, %ebp
        leal    -2(%rbx), %edi
        call    fib
        addl    %ebp, %eax
        addq    $8, %rsp
        popq    %rbx
        popq    %rbp
        ret
.L5:
        ret
```

***Output 7.6.** `fib` in C, compiled by gcc with `-O1`. Directives are filtered out; what remains is labels and instructions.*

**Facts as of 2026.**

gcc 11.4, the version on the author’s laptop, as its first line says. The flags remove the tables used for stack unwinding and the marker instructions of control-flow protection, which would otherwise make the listing longer.

First, no value goes to memory without a reason. `n` arrives in the register `edi` and is kept in `ebx` across the first call; the first result is kept in `ebp` across the second. Second, it pushes the two registers it keeps values in, `rbx` and `rbp`, on entry and pops them on exit, so that its caller finds them unchanged, as RISC-V’s convention asks of the `s` registers. Third, the case $n < 2$ returns at once, at `.L5`, without building a [frame](#def-b3-code-generation-frame). A call with $n \ge 2$ executes 17 instructions here, against 28 for `moorc`’s code, and a call with $n < 2$ executes 4, against 11. The next chapter’s register allocator is most of the difference.

**History — Optimal code.**

Ravi Sethi and Jeffrey Ullman published in 1970 how to generate optimal code for arithmetic expressions, with the fewest registers. In 1989 Alfred Aho, Mahadevan Ganapathi and Steven Tjiang described code generation by tree matching and dynamic programming, the method of the theorem above. Xavier Leroy described in 2009 the formal verification of a realistic compiler: a proof, checked by a machine, that the square commutes.

## 7.6 Exercises

**Exercise 7.1 ★.**

Write the [three-address code](#def-b3-code-generation-tac) of `x = a * b + c;`, where `a`, `b`, `c` and `x` are locals. How many temporaries does it create besides the variables?

**Solution of Exercise 7.1.**

`t4 = a * b`, `t5 = t4 + c`, `x = t5`: two temporaries besides the four variables, one per operator; the assignment is a copy (`exercise_1_tac_of_an_assignment`).

**Exercise 7.2 ★.**

List the [leaders](#def-b3-code-generation-cfg) of the [three-address code](#def-b3-code-generation-tac) of `var i = 0; while i < 3 { if i == 1 { print(i); } i = i + 1; }`, writing the instruction each one is.

**Solution of Exercise 7.2.**

The loop takes the labels L1 (top), L2 (body) and L3 (exit), the `if` L4, L5 and L6. The [leaders](#def-b3-code-generation-cfg) are `i = 0` (the first instruction), `L1:`, `goto L3` (after the branch of the loop’s test), `L2:`, `goto L5` (after the branch of `i == 1`), `L4:`, `L5:`, `L6:` and `L3:`: nine blocks (`exercise_2_leaders`). `L5:` and `L6:` are consecutive labels, so the block of `L5:` holds that label alone.

**Exercise 7.3 ★.**

Predict what `rv` prints for `sum_array.moor` compiled by `moorc`, and the exit code of the program.

**Solution of Exercise 7.3.**

The array holds $0, 1, 4, \dots, 81$, whose sum is $\sum_{i < 10} i^2 = 285$: `rv` prints `285`. `main` returns 285, and `rv` exits with $285 \bmod 256 = 29$ (`exercise_3_sum_array_on_rv`).

**Exercise 7.4 ★.**

What is the [frame](#def-b3-code-generation-frame) size of a function with 7 temporaries? With 8? Where is `ra` in each?

**Solution of Exercise 7.4.**

$4 \times 7 + 4 = 32$, already a multiple of 16: 32 bytes, `ra` at `28(sp)`. $4 \times 8 + 4 = 36$, rounded up to 48: `ra` at `44(sp)`, and bytes 32 to 43 are padding (`frames_of_fib_and_main`).

**Exercise 7.5 ★★.**

Delete the two lines of [Listing 7.13](#lst-b3-code-generation-fibs) that save and restore `ra`. With input 1 the program still prints 1. With input 2 `rv` stops on `sw a0, 16(sp)` with “store access fault at 0x80000010”. Explain both behaviours, and the address.

**Solution of Exercise 7.5.**

With input 1, `fib(1)` makes no call, so `ra` still holds the address `main`’s `call` put there, and the return is right. With input 2, `fib(2)` calls `fib(1)` and then `fib(0)`, and the second call leaves in `ra` the address of the line after it, `sw a0, 16(sp)`. When `fib(2)` returns, it pops its [frame](#def-b3-code-generation-frame) and jumps there: it runs the end of its own body again, in `main`’s [frame](#def-b3-code-generation-frame) this time, and returns again to the same place, $32$ bytes higher. `sp` started at `0x7ffffff0` and `main` lowered it by 16, so the second time round `sp` is $\texttt{0x7fffffe0} + 32 = \texttt{0x80000000}$, above the top of the stack, and `16(sp)` is `0x80000010`, an address `rv` does not map (`exercise_5_ra_not_saved`). A wrong output can take this shape: nothing fails where the bug is, in the prologue, and the fault comes two returns later.

**Exercise 7.6 ★★.**

`moorc` refuses `%` and unary minus. Write the instructions for them as the hook `exercises/ex6_rem_neg.rs`, passed as `extra` to [Listing 7.8](#lst-b3-code-generation-function), and test it against the interpreter on `17 % 5`, `-17 % -5`, `17 % 0` and `-(a - 20)`. What must be true of the processor’s remainder for the test to pass?

**Solution of Exercise 7.6.**

The hook selects `rem t0, t0, t1` for `%` and `neg t0, t0`, which is `sub t0, zero, t0`, for unary minus, with the same loads and store as [Listing 7.9](#lst-b3-code-generation-bin). The four values are $2$, $-2$, $17$ and $3$, and the program exits with $-17 \bmod 7 + 10 = 7$ in both semantics (`exercise_6_rem_and_neg`). For the test to pass, the processor’s remainder must follow the interpreter’s rules: rounding toward zero, so that the remainder has the sign of the dividend, and a remainder by zero equal to the dividend, with no trap. RISC-V’s `rem` does both, which is why chapter [4](https://one-course.com/books/computer-science/5/en/chapter/4-abstract-syntax-and-semantic-analysis#ch-b3-semantic-analysis) chose these rules for Moor.

**Exercise 7.7 ★★.**

How many instructions does `moorc` emit for `a[i] = a[i] + 1;`, with `a` a global array and `i` a local? How many 32-bit words? How many words would an optimal [tiling](#def-b3-code-generation-tiling) need, with the [tiles](#def-b3-code-generation-tiling) of [Listing 7.10](#lst-b3-code-generation-tiles), a store [tile](#def-b3-code-generation-tiling) `sw 0(r)` at cost 1 and `i` in a register?

**Solution of Exercise 7.7.**

The [three-address code](#def-b3-code-generation-tac) is `t1 = a[i]`, `t2 = t1 + 1`, `a[i] = t2`. The load is 6 instructions (`lw`, `slli`, `la`, `add` for the address, then `lw` and `sw`), the addition 3, the store 6: 15 instructions, 17 words since each of the two `la` is two (`exercise_7_instructions_for_an_increment`). Tiled as a tree, the load side is `la a`, `slli`, `add`, `lw 0(r)`, `addi 1`: 6 words; the store recomputes the address (4 words) and stores (1): 11 words. If the address is computed once and used twice, the tree becomes a graph with a shared node, and 7 words suffice; [tiling](#def-b3-code-generation-tiling) graphs optimally is harder than [tiling](#def-b3-code-generation-tiling) trees, which is one reason selectors work on trees.

**Exercise 7.8 ★★.**

Prove that the [jumping code](#def-b3-code-generation-jumping) of [Listing 7.3](#lst-b3-code-generation-cond) for a condition $e$ and labels $L_{\mathrm{t}}$, $L_{\mathrm{f}}$ reaches $L_{\mathrm{t}}$ if $e$ is true and $L_{\mathrm{f}}$ otherwise, and that the code of the right operand of $a \mathbin{\&\&} b$ runs only when $a$ is true.

**Solution of Exercise 7.8.**

By induction on $e$, with the claim: the code of `cond(e, yes, no)` computes only fresh temporaries, ends with a jump to `yes` if $e$ is true and to `no` if it is false, and never falls off its end. A comparison: the branch goes to `yes` exactly when the relation holds, and otherwise the jump goes to `no`; by [Theorem 7.13](#thm-b3-code-generation-expr) the operands hold their values. Another boolean $e$: the same, the relation being $e \ne 0$. $\lnot a$: the code of $a$ with the labels swapped reaches `no` when $a$ is true, that is when $\lnot a$ is false. $a \mathbin{\&\&} b$: by induction, the code of $a$ jumps to `no` if $a$ is false, which is right since then $a \mathbin{\&\&} b$ is false, and to `mid` if $a$ is true. The label `mid` is fresh and placed just before the code of $b$, and the code of $a$ never falls through, so the only way into the code of $b$ is the jump to `mid`: $b$ runs only when $a$ is true. Then $a \mathbin{\&\&} b$ has the value of $b$, and by induction the code of $b$ jumps to the right label. $a \mathbin{||} b$ is the mirror image.

**Exercise 7.9 ★★.**

Predict the [basic blocks](#def-b3-code-generation-cfg) and the edges of the control-flow graph of `fn f(n: int) -> int { while n > 0 { if n == 3 { return 1; } n = n - 1; } return 0; }`. Which blocks have no predecessor?

**Solution of Exercise 7.9.**

Ten blocks: B0 `L1:` and the test `n > 0` (successors B2 taken, B1); B1 `goto L3` (B8); B2 `L2:` and the test `n == 3` (B4, B3); B3 `goto L5` (B6); B4 `L4: return 1` (exit); B5 `goto L6`, the jump after the `then` part (B7); B6 `L5:`, the empty `else` (B7); B7 `L6:`, `n = n - 1` and `goto L1` (B0); B8 `L3: return 0` (exit); B9 the final `return` (exit). B5 and B9 follow a `return` and no jump targets them: they have no predecessor. B0, the entry, has one, the back edge from B7 (`exercise_9_cfg_of_a_loop_with_return`).

**Exercise 7.10 ★★★.**

*[Maximal munch](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-munch)* [tiles](#def-b3-code-generation-tiling) a tree from the root down, choosing at each node the matching [tile](#def-b3-code-generation-tiling) that covers the most nodes. (a) With the [tiles](#def-b3-code-generation-tiling) `add` and `mul` at cost 1 and a multiply-add [tile](#def-b3-code-generation-tiling) for `(+ (* x y) z)` at cost 3, find a tree on which [maximal munch](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-munch) is not optimal. (b) Show that [maximal munch](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-munch) can fail even when every [tile](#def-b3-code-generation-tiling) costs 1, covers one node or two (a node and one of its children), and every node has a one-node [tile](#def-b3-code-generation-tiling), and that the program of [Theorem 7.9](#thm-b3-code-generation-tiling) does not.

**Solution of Exercise 7.10.**

(a) The tree `(+ (* x y) z)` with `x`, `y`, `z` in registers: [maximal munch](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-munch) takes the multiply-add at the root, cost 3; `mul` then `add` cost 2.

(b) Take a root $r$ with two children $c$ and $c'$, where $c$ has a child $d$, and allow the two-node [tiles](#def-b3-code-generation-tiling) $(r, c)$, $(r, c')$ and $(c, d)$, a node with one of its children, besides a one-node [tile](#def-b3-code-generation-tiling) for each node. Both [tiles](#def-b3-code-generation-tiling) at the root cover two nodes, so [maximal munch](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-munch) may take $(r, c)$; then $d$ and $c'$ need a [tile](#def-b3-code-generation-tiling) each, and the [tiling](#def-b3-code-generation-tiling) costs 3. The [tiles](#def-b3-code-generation-tiling) $(r, c')$ and $(c, d)$ cover the four nodes for 2. The choice at the root depends on what lies below, which a top-down greedy rule does not look at. The program of [Theorem 7.9](#thm-b3-code-generation-tiling) computes $\mathrm{best}(c) = 1$ and $\mathrm{best}(c') = 1$ before choosing at $r$, so it finds $\min(1 + \mathrm{best}(d) + \mathrm{best}(c'), 1 + \mathrm{best}(c)) = \min(3, 2) = 2$ for the [tile](#def-b3-code-generation-tiling) $(r, c)$ or $(r, c')$ respectively, and takes the second.

**Exercise 7.11 ★★★.**

Without storing intermediate results, an expression tree can be evaluated with few registers if the operand that needs more is evaluated first. Define $\mathrm{need}(\text{leaf}) = 1$ and, for an operator with children needing $x$ and $y$, $\mathrm{need} = \max(x, y)$ if $x \ne y$ and $x + 1$ if $x = y$. Prove that $\mathrm{need}(e)$ registers suffice and are necessary, and compare with the registers used when the left operand always goes first, on a left comb and a right comb of three operators. `exercises/ex11_registers.rs` computes both.

**Solution of Exercise 7.11.**

Sufficient, by induction: a leaf needs one register. For an operator with children needing $x \ge y$, evaluate the first child with $x$ registers, keep its result in one, and evaluate the second with $y$ of the others; at most $\max(x, 1 + y)$ registers are busy, which is $x$ if $x > y$ and $x + 1$ if $x = y$. Necessary, by induction: each child alone needs its own number, so the operator needs at least $\max(x, y)$; and if $x = y$, whichever child is finished first holds its result in a register while the other, which needs $x$, is evaluated, so $x + 1$ are needed. A left comb `((a op b) op c) op d` needs 2, and left first uses 2; a right comb `a op (b op (c op d))` also needs 2, but left first keeps `a`, then `b`, then `c` while it descends and uses 4 (`exercise_11_register_need`). Sethi and Ullman’s 1970 paper is this analysis, with stores for trees that need more registers than the machine has.

**Exercise 7.12 ★★★.**

Write a test oracle: a generator of random Moor programs (three variables, assignments, `if`, bounded `while`, `&&`, `||`, `!`) and a test that compiles each one, runs it on `rv` and on the interpreter, and compares. `exercises/ex12_oracle.rs` is one. Run it on 60 programs. What did it find in the first version of [Listing 7.2](#lst-b3-code-generation-expr), which had no arm for negative literals?

**Solution of Exercise 7.12.**

The generator draws three initial values, then up to four statements, nested to depth 2, from assignments of random expressions of depth 3, `print`, `if` with an `else`, and `while` loops with a counter that bounds them; conditions mix comparisons with `&&`, `||` and `!`. Every program ends by printing the three variables and returning an expression of them, so a wrong value anywhere is seen. The test `exercise_12_random_programs` runs 60 programs. On its first run it found a disagreement: the parser reads `-7` as unary minus applied to 7, the [code generator](#def-b3-code-generation-selection) had no instructions for unary minus, and every program with a negative constant was refused by `moorc` while the interpreter ran it. The arm for negative literals in [Listing 7.2](#lst-b3-code-generation-expr) fixed it, and the 60 programs now agree in output and exit code. The oracle found the bug because it wrote programs no one had thought to write; its limit is the generator, which never makes a function call, an array or a division by a variable that may be zero.

## 7.7 Weekend problem

**Problem 7.1.**

Weekend problem — Fibonacci on the RISC-V subset

`fib.moor` computes $F(n)$, with $F(0) = 0$, $F(1) = 1$ and $F(k) = F(k-1) + F(k-2)$, by the naive recursion. `pb_fib.py` runs its compiled code on `rv` for $n = 0, \dots, 20$ and records, for each run, the calls of `fib` and `rv`’s counts of instructions, loads and stores.

```
$ python pb_fib.py
 n  F(n+1)  calls  instructions  loads  stores
 0       1      1            32      7       6
 1       1      1            32      7       6
 2       2      3            71     19      15
 3       3      5           110     31      24
 4       5      9           188     55      42
 5       8     15           305     91      69
 6      13     25           500    151     114
 7      21     41           812    247     186
 8      34     67          1319    403     303
 9      55    109          2138    655     492
10      89    177          3464   1063     798
11     144    287          5609   1723    1293
12     233    465          9080   2791    2094
13     377    753         14696   4519    3390
14     610   1219         23783   7315    5487
15     987   1973         38486  11839    8880
16    1597   3193         62276  19159   14370
17    2584   5167        100769  31003   23253
18    4181   8361        163052  50167   37626
19    6765  13529        263828  81175   60882
20   10946  21891        426887  131347   98511
```

***Output 7.7.** For each $n$: $F(n+1)$, the calls of `fib` (each `jal ra`), and the counters of `rv`.*

**Part I — The code.**

1. Write the [three-address code](#def-b3-code-generation-tac) of `fib` from [Output 7.3](#out-b3-code-generation-cfgout) . Why are there five temporaries besides `n` ?
2. Which blocks of the control-flow graph can run, and in what order, for $n = 1$ ? For $n = 5$ ?
3. Translate `if n < 2 { return n; }` by hand into [jumping code](#def-b3-code-generation-jumping) , and compare with instructions 0 to 3.
4. Draw the [frame](#def-b3-code-generation-frame) of `main` : how many temporaries, which offsets, what size?
5. Why does `fib` save `ra` but no `s` register?
6. In [Listing 7.13](#lst-b3-code-generation-fibs) , find the lines of the prologue, the epilogue and the two calls.

**Part II — One call.**

7. Count the instructions executed by one call of `fib` with $n < 2$ , from its first instruction to its `ret` .
8. Count those of a call with $n \ge 2$ , not counting what the two inner calls execute.
9. Count the instructions executed by `main` , not counting the call of `fib` it makes.
10. Count the loads and the stores of each of the three, the same way.
11. How many conditional branches does each call execute, and when is it taken?

**Part III — How many calls.**

12. Write a recurrence for $c(n)$ , the calls of `fib` made to compute `fib(n)` , that one included.
13. Prove that $c(n) = 2F(n+1) - 1$ .
14. Prove that the calls with $n < 2$ , the leaves of the call tree, number $F(n+1)$ .
15. Deduce the number of calls with $n \ge 2$ .
16. Check the three formulas against the `calls` column and against the branch counts of [Output 7.5](#out-b3-code-generation-compilefib) .

**Part IV — The count.**

17. From Parts II and III, give the instructions executed for input $n$ as $a F(n+1) + b$ . Find $a$ and $b$ .
18. Check the formula against the `instructions` column for $n = 0$ , 10 and 20.
19. Do the same for the loads and the stores.
20. What fraction of the instructions of a large run are loads or stores? What does this say of the [naive allocator](#def-b3-code-generation-naive) ?
21. $F(n+1)$ grows by a factor tending to $\varphi = (1 + \sqrt 5)/2$ per step of $n$ . Estimate the instructions executed for $n = 40$ , without running it.
22. Using [Output 7.6](#out-b3-code-generation-gcc) , give the corresponding formula for gcc’s code, counting instructions the same way and ignoring `main` .
23. An allocator that kept `n` and the first result in the saved registers `s0` and `s1` , and stored nothing else, would remove which instructions of a call, and add which? Estimate its $a$ , then again with the test $n < 2$ moved before the prologue, as gcc does.
24. Rewrite `fib` with a loop in Moor. How does its count grow with $n$ ?
25. Sum up: the exact count of the naive code, what it is made of, and which of its terms the next chapter can reduce.

**Solution of Problem 7.1.**

**1.** `if n < 2 goto L1`; `goto L2`; `L1:`; `return n`; `goto L3`; `L2:`; `L3:`; `t1 = n - 1`; `t2 = call fib(t1)`; `t3 = n - 2`; `t4 = call fib(t3)`; `t5 = t2 + t4`; `return t5`; `return`. Each of the two subtractions, the two calls and the addition makes one [temporary](#def-b3-code-generation-tac).

**2.** For $n = 1$: B0, then B2, which returns. For $n = 5$: B0, B1, B4, B5, which returns; the two calls in B5 run their own blocks. B3 and B6 never run.

**3.** `if n < 2 goto L1; goto L2; L1:` then the `then` part, `return n`: instructions 0 to 3, as [Listing 7.3](#lst-b3-code-generation-cond) produces them.

**4.** Three temporaries: the result of `read` at `0(sp)`, `n` at `4(sp)`, the result of `fib` at `8(sp)`; `ra` at `12(sp)`; $4 \times 3 + 4 = 16$ bytes.

**5.** It uses only `t0`, `t1`, `a0` and `a7`, which a callee may overwrite; it writes no `s` register, so it has none to give back. It saves `ra` because its own calls overwrite it.

**6.** The prologue is lines 4 to 6 of `fib.S` ([frame](#def-b3-code-generation-frame), `ra`, the argument into `n`’s slot); the calls are lines 21 and 27; the epilogue is lines 37 to 40.

**7.** 11: `addi`, `sw ra`, `sw a0`, `lw`, `li`, `blt` (taken), `lw a0`, `j`, `lw ra`, `addi`, `ret`.

**8.** 28: the six of the prologue and the test, the `j` to `.Lfib_2`, the 18 instructions of lines 17 to 34, from `lw t0, 0(sp)` to the jump to the epilogue, the two `call`s included, and the three of the epilogue: $6 + 1 + 18 + 3 = 28$.

**9.** 21: prologue 2, `read` 3 with its store, the copy into `n` 2, the call of `fib` with its argument and result 3, `print` 6, `return 0` 2, epilogue 3.

**10.** Loads: 3 per leaf call, 9 per inner call, 4 in `main`. Stores: 2, 7 and 4.

**11.** One, the `blt` of the test; it is taken exactly when $n < 2$.

**12.** $c(0) = c(1) = 1$ and $c(n) = 1 + c(n-1) + c(n-2)$ for $n \ge 2$.

**13.** By induction: $2F(1) - 1 = 2F(2) - 1 = 1$; and $1 + (2F(n) - 1) + (2F(n-1) - 1) = 2(F(n) + F(n-1)) - 1 = 2F(n+1) - 1$ (`calls_are_2_f_minus_1`).

**14.** The leaves satisfy $\ell(0) = \ell(1) = 1$ and $\ell(n) = \ell(n-1) + \ell(n-2)$, the recurrence of $F(n+1)$ with the same start.

**15.** $c(n) - \ell(n) = F(n+1) - 1$.

**16.** For $n = 10$: $F(11) = 89$, and the column says $177 = 2 \times 89 - 1$; `rv` counted 177 branches, one per call, of which 89 were taken, one per leaf.

**17.** $11F(n+1) + 28(F(n+1) - 1) + 21 = 39F(n+1) - 7$: $a = 39$, $b = -7$.

**18.** $39 - 7 = 32$; $39 \times 89 - 7 = 3464$; $39 \times 10946 - 7 = 426887$. All three are in the table, and the test `instructions_are_39_f_minus_7` checks every $n \le 20$.

**19.** Loads $3F + 9(F - 1) + 4 = 12F(n+1) - 5$, stores $2F + 7(F - 1) + 4 = 9F(n+1) - 3$: for $n = 20$, $131347$ and $98511$, as in the table.

**20.** $(12 + 9)/39 = 21/39$, about 54 %. More than half of the work moves values between the [frame](#def-b3-code-generation-frame) and the registers and back, which is the price of the [naive allocator](#def-b3-code-generation-naive).

**21.** $F(41) = 165{,}580{,}141$, so $39 F(41) - 7 = 6{,}457{,}625{,}492$: about $6.5 \times 10^9$ instructions, $\varphi^{20}$, about 15,000, times the count for $n = 20$.

**22.** 4 per leaf, 17 per inner call: $4F(n+1) + 17(F(n+1) - 1) = 21F(n+1) - 17$.

**23.** Gone: the stores of `n` and of the five temporaries and their reloads. Added: saving and restoring `s0` and `s1`, and two moves into them. An inner call becomes about 19 instructions (`addi`, three saves, `mv s0, a0`, `li`, `blt`, then `addi a0, s0, -1`, `call`, `mv s1, a0`, `addi a0, s0, -2`, `call`, `add`, `j`, then three restores, `addi`, `ret`), but a leaf becomes about 13, since it too saves and restores, so $a \approx 32$: hardly better. With the test before the prologue, a leaf is `li`, `blt`, `ret`, 3 instructions, and $a \approx 22$, close to gcc’s 21. Where the [frame](#def-b3-code-generation-frame) is built matters as much as what is kept in registers.

**24.** With the loop of `exercises/pb_fibloop.moor`, which keeps $F(i)$ and $F(i+1)$ in two variables and adds them $n$ times, `rv` counts $19n + 39$ instructions (`problem_loop_version_is_linear`): linear, against exponential.

**25.** The naive code executes exactly $39F(n+1) - 7$ instructions: 11 per leaf call, 28 per inner call, 21 in `main`, of which 21 out of every 39 are memory accesses. An allocator and a better placement of the [frame](#def-b3-code-generation-frame) can bring the 39 down towards 21. The factor $F(n+1)$ comes from the algorithm, and no compiler of this kind removes it: the loop of question 24 does.
