---
title: What the compiler does
heading: How an optimizing compiler turns the same C into fewer instructions
eyebrow: C8 · Lesson 32 · What the compiler does
xp: 40
---

::: hook
The loop `for (i = 0; i < n; i++) s += a[i] * 3;` is one line of C. Compiled without optimization, eight passes of it take 147 instructions. Compiled with the optimizer on, the same eight passes take 53, and the answer is the same. The optimizer hasn't done anything clever with the algorithm. It has made a dozen small, safe substitutions, the same ones you'd make writing the assembly by hand, and knowing what they are tells you what to leave to the compiler and what it can't do for you.
:::

::: play
- This is the loop compiled the way `-O0` does it: every variable (i, n and s) lives in the stack frame, so each use is a load and each change a store.
- Each pass reloads i and n, recomputes the address of `a`, multiplies by 3 with `mul`, and loads and stores s.
- At the end a0 holds the sum, 93, and a1 reads the board's TIMER, which counts the instructions run: 147.
:::

```sim cpu
.data
a: .word 3, 1, 4, 1, 5, 9, 2, 6
.text
    addi sp, sp, -16     # a stack frame for the variables
    li t0, 8
    sw t0, 12(sp)        # n = 8
    sw zero, 8(sp)       # s = 0
    sw zero, 4(sp)       # i = 0
loop:
    lw t0, 4(sp)         # load i
    lw t1, 12(sp)        # load n
    bge t0, t1, done     # i < n?
    la t2, a             # &a[0], every time
    slli t3, t0, 2       # i * 4
    add t2, t2, t3       # &a[i]
    lw t2, 0(t2)         # a[i]
    li t3, 3
    mul t2, t2, t3       # a[i] * 3
    lw t4, 8(sp)         # load s
    add t4, t4, t2
    sw t4, 8(sp)         # store s
    lw t0, 4(sp)         # load i again
    addi t0, t0, 1
    sw t0, 4(sp)         # store i
    j loop
done:
    lw a0, 8(sp)         # the result
    addi sp, sp, 16
    li t5, 0x20000
    lw a1, 8(t5)         # TIMER: instructions run so far
    ebreak
show: a0, a1, t0
hex: sp, t2
speed: 30
```

::: predict
## The optimized version keeps s in a register, walks a pointer instead of computing i × 4, and multiplies by 3 with a shift and an add. About how many instructions does one pass of its loop take?

- [ ] 17, the same: the work is the same
- [ ] 12
- [x] 6
- [ ] 2

::: reveal
6: load the element, shift, add (that's the × 3), add to s, move the pointer, branch. The rest of the 17 were loads and stores of variables, address arithmetic redone every pass, and a jump that rotating the loop removes. The whole run drops from 147 instructions to 53.
:::
:::

::: nameit
## The common optimizations

- **Register allocation.** Keep variables in registers instead of the stack. At `-O0` every variable has a stack slot, and every use is a `lw` and every change a `sw`. This alone is usually the biggest difference between `-O0` and `-O1`.
- **Constant folding and propagation.** Work out `3 * 4` or `n = 8; ... n` at compile time.
- **Common subexpression elimination.** Compute `a[i]`'s address once if two expressions use it.
- **Loop-invariant code motion.** Move work that gives the same result every pass, like `la t2, a`, out of the loop.
- **Strength reduction.** Replace an expensive operation with a cheaper one: `i * 4` with a pointer that moves by 4, `x * 3` with `(x << 1) + x`, division by a constant with a multiply and a shift.
- **Loop rotation.** Put the test at the bottom so each pass needs one branch instead of a branch and a jump.
- **Inlining.** Copy a small function's body into its caller, removing the call, the return and the argument moves, and often opening the way to the other optimizations.
- **Dead-code elimination** and **unrolling** (several copies of the body per pass, fewer branches).

## What the compiler can't do

It must keep the program's meaning for every possible input, so it's cautious where it can't prove something:

- **Aliasing.** If two pointers might point at the same memory, a store through one may change what the other reads, so the compiler reloads values it would otherwise keep in registers. C's `restrict` promises they don't overlap.
- **Calls to unknown code** may change any global, so globals are reloaded after them.
- **`volatile`** variables are loaded and stored exactly as written (lesson 18).
- **Floating-point** sums can't be reordered, because rounding makes $(a + b) + c$ differ from $a + (b + c)$.

## Reading the result

Optimization levels trade compile time, speed and size: `-O1` and `-O2` for speed, `-Os` for size, which matters on small flash chips. To see what was done, read the assembly (`-S`) or step through it in a debugger, and to know whether it helped, measure (lesson 31).
:::

The same loop as the optimizer writes it. Step through and compare the passes.

```sim cpu
.data
a: .word 3, 1, 4, 1, 5, 9, 2, 6
.text
    la t0, a             # p = &a[0], once
    addi t1, t0, 32      # end = &a[8]
    li a0, 0             # s lives in a register
loop:
    lw t2, 0(t0)         # *p
    slli t3, t2, 1       # *p * 3 as (x << 1) + x
    add t2, t2, t3
    add a0, a0, t2       # s += *p * 3
    addi t0, t0, 4       # p++ replaces i * 4
    bne t0, t1, loop     # test at the bottom
    li t5, 0x20000
    lw a1, 8(t5)         # TIMER: instructions run so far
    ebreak
show: a0, a1, t2
hex: t0, t1
speed: 30
```

::: example
## A loop over 1000 elements computes each address with `slli` and `add` from an index. Strength reduction replaces that with a pointer that moves by 4. How many instructions does that save?

::: solution
1. **Before.** 2 instructions a pass for the address, plus an `addi` for i.
2. **After.** One `addi` for the pointer, and the index often disappears entirely, since the loop can stop when the pointer reaches the end.
3. **The saving.** That's 2 instructions saved per pass, 2000 in all.
4. **In the program above.** The change from 17 to 6 instructions a pass is this plus register allocation, hoisting and rotation together.

**Answer:** 2 instructions a pass, 2000 over the loop.
:::
:::

::: example
## A 3-instruction function is called a million times; each call costs a `jal`, a `ret` and two argument moves. What does inlining save?

::: solution
1. **Before.**
   $$\begin{aligned} N &= 10^6 \times (3 + 4) \\ &= 7 \times 10^6 \end{aligned}$$
2. **After.**
   $$N = 3 \times 10^6$$
   so the calls were 57% of the work.
3. **More savings.** Inlining also lets the compiler optimize the body together with the caller's code, for instance folding a constant argument, which often saves more than the call itself.
4. **The cost.** It costs size: a big function inlined in many places makes the program larger.

**Answer:** inlining saves 4 million instructions, the 57% of the work that went to the calls.
:::
:::

::: example
## `void f(int *a, int *b) { *a += *b; *a += *b; }`. Why can't the compiler load `*b` once? Work it out for a call where a and b both point at an int holding 1.

::: solution
1. **What overlap does.** If a and b point at the same int, the first statement changes `*b` too.
2. **The right result.** 1 + 1 = 2, then 2 + 2 = 4.
3. **Loading `*b` once.** A compiler that loaded `*b` once into a register would compute 1 + 1 + 1 = 3.
4. **So it reloads.** Since it can't rule out that call, it must reload `*b` after the store.
5. **`restrict`.** Declaring `int *restrict a, int *restrict b` promises the pointers never overlap, and then it may keep `*b` in a register.

**Answer:** a and b may point at the same int, which should end at 4, and loading `*b` once would give 3.
:::
:::

::: check
kind: parts
given: n = 100 | 1000 | 10000; u = 14 | 17 | 20; o = 4 | 5 | 6

## An unoptimized loop takes {u} instructions a pass; optimized, it takes {o}. It runs {n} passes.

::: part
answer: n*(u - o)
tolerance: 0.5%

### How many instructions does optimization save?

::: misses
- [any] Passes × the difference per pass.
:::
:::

::: part
answer: u/o
tolerance: 0.5%

### By what factor does the loop speed up, at one instruction a cycle?

::: misses
- [any] The ratio of instructions per pass.
:::
:::
:::

::: check
kind: parts
given: N = 1000 | 1000000; b = 2 | 5 | 12; c = 3 | 4 | 6

## A function with a {b}-instruction body is called {N} times, and each call costs {c} more instructions.

::: part
answer: N*(b + c)
tolerance: 0.5%

### How many instructions do the calls run in all?

::: misses
- [any] Calls × (body + call cost).
:::
:::

::: part
answer: c/(b + c)*100
unit: %
tolerance: 0.5%

### What share of that does inlining remove?

::: misses
- [any] The call cost's share.
:::
:::
:::

::: check
kind: derivation
vars: x = -1000..1000, m = 1..10

## Strength reduction turns a multiply by $2^m + 1$ into a shift and an add.

::: step
answer: x*2^m

### What is x shifted left by m?
:::

::: step
answer: x*(2^m + 1)

### What does adding x to that give?
:::

::: right
Right. So × 3, × 5, × 9 and × 17 each cost a shift and an add.
:::
:::

::: check
kind: asm
given: x = -10000..10000 int
setup: a0 = x
expect: a1 = 10*x

## Multiply a0 by 10 without `mul`, and put the result in a1.

```asm starter
    mv a1, a0
    ebreak
```

```asm solution
    slli t0, a0, 3
    slli t1, a0, 1
    add a1, t0, t1
    ebreak
```

::: right
Right. 10x = 8x + 2x: two shifts and an add.
:::
:::

::: check
kind: parts
given: v = 2 | 5 | 7

## `*a += *b; *a += *b;` runs with a and b pointing at the same int, which holds {v}.

::: part
answer: 4*v
tolerance: 0

### What does the int hold afterward?

::: misses
- [3*v] That assumes `*b` didn't change, but it's the same int as `*a`.
- [any] After the first statement it's 2v, and `*b` is 2v too.
:::
:::

::: part
answer: 3*v
tolerance: 0

### What would a compiler that loaded `*b` only once produce?

::: misses
- [any] It would add the original value twice.
:::
:::
:::

::: check
kind: parts
given: n = 1000 | 4096; b = 3 | 5; u = 2 | 4 | 8

## A loop runs {n} passes of a {b}-instruction body, with 2 instructions of loop overhead per pass.

::: part
answer: n*(b + 2)
tolerance: 0

### How many instructions does it run?

::: misses
- [any] Passes × (body + overhead).
:::
:::

::: part
answer: n*b + 2*n/u
tolerance: 0.5%

### Unrolled by {u}?

::: misses
- [any] The bodies stay; the overhead is paid once per {u} bodies.
:::
:::
:::

::: check
kind: choice

## A loop sums the elements of a `float` array. Why won't the compiler split the sum into four partial sums to use four adders at once, as it would for an `int` array?

- [ ] Floats are too big for registers
- [x] Floating-point addition isn't associative: adding in a different order can round differently and change the result
- [ ] Floating-point adders can't run in parallel
- [ ] It would, at any optimization level

::: misses
- [1] Floats fit in registers fine.
- [3] They can; the problem is what the reordering does to the answer.
- [4] Only with flags like `-ffast-math` that allow it to change results.
:::
:::

::: explain
## Why does compiling with `-O0` produce so many loads and stores, and why is that useful when debugging?

::: model
At `-O0` the compiler gives every variable a home in the stack frame and translates each statement on its own: it loads the variables the statement reads, computes, and stores the result back before moving on. That's slow, because most instructions just shuffle values between memory and registers, but it means that at every line the variables in memory hold exactly the values the source says they should. A debugger can stop anywhere and show them, and stepping line by line follows the source. With optimization, values live in registers, statements are merged or moved, and some variables vanish, so the machine state no longer lines up neatly with the source.
:::
:::

::: practice
::: check
given: n = 500 | 2000; u = 12 | 16; o = 5 | 7
answer: n*(u - o)
tolerance: 0.5%

## {u} instructions a pass before, {o} after, {n} passes. Instructions saved?

::: misses
- [any] $n(u - o)$.
:::
:::

::: check
given: m = 1 | 2 | 3 | 4; x = 3 | 11 | 25
answer: x*(2^m + 1)
tolerance: 0

## What does `(x << {m}) + x` give for x = {x}?

::: misses
- [any] $x(2^m + 1)$.
:::
:::

::: check
given: N = 10000 | 1000000; b = 4 | 8; c = 4 | 5
answer: N*c
tolerance: 0.5%

## Inlining a {b}-instruction function called {N} times, at {c} instructions per call. Instructions saved?

::: misses
- [any] Calls × call cost.
:::
:::
:::
