---
title: From C to assembly
heading: What a compiler turns your code into
eyebrow: C8 · Lesson 17 · From C to assembly
xp: 60
---

::: hook
Firmware for microcontrollers is mostly written in C, and a compiler turns it into instructions like the ones in the last five lessons. Each C construct has a usual translation: a variable becomes a register, an array access becomes a shift, an add and a load, a `for` loop becomes a test, a body and a jump back, and a function call follows the calling convention. Knowing the translation tells you what your code costs and lets you read a disassembly when something goes wrong. Below, a function that adds up an array steps along in C and in assembly together.

::: play
- Step through. The highlighted C line is the one the current instruction belongs to.
- Which instructions does `total = total + a[i];` become?
- Where do `total` and `i` live while the loop runs?
:::
:::

```sim cpu
c:
int nums[5] = {4, 9, -2, 7, 5};

int sum(int *a, int n) {
    int total = 0;
    for (int i = 0; i < n; i++) {
        total = total + a[i];
    }
    return total;
}

int main(void) {
    int s = sum(nums, 5);
    return s;
}
asm:
.data
nums: .word 4, 9, -2, 7, 5
.text
main:
    la a0, nums         # the array's address  #@12
    li a1, 5            # its length           #@12
    call sum                                   #@12
    mv s0, a0           # s = the result       #@12
    ebreak                                     #@13
sum:
    li t0, 0            # total = 0            #@4
    li t1, 0            # i = 0                #@5
loop:
    bge t1, a1, done    # leave when i >= n    #@5
    slli t2, t1, 2      # 4i                   #@6
    add t2, a0, t2      # the address of a[i]  #@6
    lw t3, 0(t2)        # a[i]                 #@6
    add t0, t0, t3      # total + a[i]         #@6
    addi t1, t1, 1      # i++                  #@5
    j loop                                     #@5
done:
    mv a0, t0           # the result goes in a0  #@8
    ret                                        #@8
show: a0, a1, s0, t0, t1, t3
hex: t2
speed: 4
```

::: predict
## How many instructions run in one pass of the loop, from `bge` to `j loop`?

- [ ] 2
- [ ] 5
- [x] 7
- [ ] 10

::: reveal
Seven: the test (`bge`), four for `total = total + a[i]` (a shift, an add to make the address, the load and the add), then `addi` for `i++` and `j` back to the test. For five elements that's 35, plus one last `bge` that leaves the loop.
:::
:::

::: nameit
## How C constructs compile

The assembly above is the kind of code an optimizing compiler writes for RV32I; a real compiler's output differs in details, such as how it orders the loop.

| C | Assembly |
|---|---|
| a local `int` | a register (t0 to t6 if it isn't needed after a call, s0 to s11 if it is) |
| `x = y + 3` | `addi` |
| `a[i]` for 4-byte `int` | `slli` by 2, `add` the base, `lw` |
| `p->field` or `*(p + k)` | `lw` with an offset from p |
| `if (x < y) {…}` | `bge x, y, skip`, then the body |
| `for (init; test; step) {…}` | init; a test that branches out; the body; the step; `j` back |
| `f(x, y)` | x in a0, y in a1, `call f`, the result in a0 |
| `return v` | v into a0, `ret` |

**Types set the scale.** An array of `char` (1 byte) needs no shift, `short` (2 bytes) a shift by 1, `int` (4 bytes) a shift by 2. Signed types load with `lb`/`lh` and compare with `blt`; unsigned ones load with `lbu`/`lhu` and compare with `bltu`.

**What costs what.** Each pass of this loop runs 7 instructions, so `sum` takes 7n + 5 instructions for n elements: 2 to set up, 7 per pass, 1 last test, and 2 to return. Arithmetic on registers is cheap. Loads, stores, branches and calls are where time goes, which is why compilers keep busy variables in registers.
:::


::: example
## Compile `x = a[i] + 1;` for an `int` array, with a in a0, i in a1 and x in t2.

::: solution
1. **Scale the index.** `slli t0, a1, 2` makes 4i.
2. **Form the address.** `add t0, a0, t0` adds the base.
3. **Load the element.** `lw t1, 0(t0)` loads a[i].
4. **Add one.** `addi t2, t1, 1` adds one into x.

**Answer:** `slli t0, a1, 2`, `add t0, a0, t0`, `lw t1, 0(t0)`, `addi t2, t1, 1`.
:::
:::

::: example
## Compile `while (n != 0) { n = n >> 1; c++; }` for unsigned n in a0 and c in a1.

::: solution
1. **Test first.** A while loop may run zero times, so the test comes before the body.
2. **The body.** Shift n right by one and count.
3. **Jump back.** Jump to the test, which leaves at `done`.

```asm
loop:
    beqz a0, done
    srli a0, a0, 1
    addi a1, a1, 1
    j    loop
done:
```

**Answer:** `loop: beqz a0, done`, then `srli a0, a0, 1`, `addi a1, a1, 1`, `j loop`, and `done:`.
:::
:::

::: example
## Compile `s->count++;` where s points to `struct { int id; int count; }` and is in a0.

::: solution
1. **Find the offset.** id takes bytes 0 to 3, so count sits at offset 4.
2. **Load, add and store.** `lw t0, 4(a0)`, `addi t0, t0, 1`, `sw t0, 4(a0)`.
3. **What `->` costs.** The compiler turns every field name into a fixed offset from the struct's address, so `->` costs nothing beyond the load itself.
4. **A warning.** If another piece of code (an interrupt handler, say) can change count between the load and the store, one increment is lost: the read-modify-write isn't atomic.

**Answer:** `lw t0, 4(a0)`, `addi t0, t0, 1`, `sw t0, 4(a0)`.
:::
:::

::: check
kind: choice

## Which instructions compute the address of `a[i]`?

- [ ] `lw t3, 0(t2)` alone
- [x] `slli t2, t1, 2` and `add t2, a0, t2`
- [ ] `addi t1, t1, 1` and `j loop`
- [ ] `bge t1, a1, done`

::: right
Right. i × 4 bytes, added to the array's base address. The load then reads the word there.
:::

::: misses
- [1] The load reads a[i], but only after the address is built.
- [3] Those are `i++` and the jump back.
- [4] That's the loop test.
:::
:::

::: check
given: n = 5..200 int
answer: 7*n + 5
tolerance: 0

## How many instructions does `sum` run for an array of {n} elements, from its first instruction to its `ret`?

::: right
Right: {answer}. 2 to set up, 7 per pass, 1 final test, then `mv` and `ret`.
:::

::: misses
- [7*n] That's the passes alone. Add the setup, the final test and the return.
- [7*n + 1] Add the 2 setup instructions and the 2 at the end.
- [any] Not yet. Count 7 per pass, then add what runs only once.
:::
:::

::: check
given: p = 1024..2000 int; i = 1..50 int; s = 2 | 4 | 8; let B = 4*p
answer: B + s*i
base: 16
width: 4

## An array whose elements are {s} bytes each starts at 0x{B:hex4}. What's the address of element {i}?

::: right
Right: 0x{answer}. The compiler scales the index by the element's size.
:::

::: misses
- [B + i] Scale by the element size, {s} bytes.
- [any] Not yet. Base + size × index, in hex.
:::
:::

::: check
kind: asm
given: m = 1..500 int; s = -1 | 1; let x = s*m
setup: a0 = x
expect: a1 = m

## Translate this C, with x in a0 and y in a1:

```
y = x;
if (y < 0) {
    y = -y;
}
```

```asm starter
    # x is in a0; leave y in a1
    ebreak
```

```asm solution
    mv a1, a0
    bgez a1, done       # skip the body when y >= 0
    neg a1, a1
done:
    ebreak
```

::: right
Right. The branch skips the body when the condition is false: `bgez` for `y >= 0`.
:::
:::

::: check
kind: asm
given: n = 1..20 int
setup: a0 = n
expect: a1 = 2^n

## Translate this C, with n in a0 and f in a1:

```
int f = 1;
for (int i = 0; i < n; i++) {
    f = f * 2;
}
```

```asm starter
    # n is in a0; leave f in a1
    li a1, 1
    ebreak
```

```asm solution
    li a1, 1            # f = 1
    li t0, 0            # i = 0
loop:
    bge t0, a0, done    # i < n ?
    slli a1, a1, 1      # f = f * 2
    addi t0, t0, 1      # i++
    j loop
done:
    ebreak
```

::: right
Right. Init, test, body, step, jump back. Multiplying by 2 is a shift left by 1.
:::
:::

::: check
kind: order

## Put the instructions for `total = total + a[i];` in order (i in t1, the array's address in a0, total in t0).

1. `slli t2, t1, 2`
2. `add t2, a0, t2`
3. `lw t3, 0(t2)`
4. `add t0, t0, t3`

::: right
Right. Scale the index, add the base, load, then add.
:::
:::

::: check
kind: asm
given: d = 1..99 int; c = 0..500 int; k = 2..9 int
setup: a1 = k
expect: a2 = c + k

## a0 points to `struct { int id; int count; }`. Add a1 to s->count, store it back, and leave the new count in a2.

```asm starter
.data
s: .word d, c
.text
    la a0, s
    li a2, 0
    ebreak
```

```asm solution
.data
s: .word d, c
.text
    la a0, s
    lw t0, 4(a0)
    add t0, t0, a1
    sw t0, 4(a0)
    mv a2, t0
    ebreak
```

::: right
Right. count is 4 bytes past the struct's start: load, add, store.
:::
:::

::: check
kind: parts
given: R = 5 | 10 | 16; C = 8 | 20 | 32; i = 2 | 3; j = 5 | 7

## `int m[{R}][{C}]` is stored row by row from address 0.

::: part
answer: 4*(i*C + j)
tolerance: 0

### At what address is m[{i}][{j}]?

::: misses
- [4*(j*R + i)] That's column-major order; C stores rows.
- [i*C + j] Multiply by 4 bytes per int.
- [any] $4(iC + j)$.
:::
:::

::: part
answer: 4*C
tolerance: 0

### How many bytes apart are m[i][j] and m[i + 1][j]?

::: misses
- [any] One whole row.
:::
:::
:::

::: explain
## Why does the compiled loop keep `total` and `i` in registers rather than in memory?

::: model
Instructions can read two registers and write one directly, but they can only reach memory through loads and stores, each an extra instruction (and, on a real chip, often slower than a register access). `total` and `i` are read and written on every pass, so keeping them in memory would add a load and a store per use and make every pass longer. A compiler keeps busy variables in registers and only falls back to memory, on the stack, when it runs out of registers or when the program needs the variable's address.
:::
:::

::: practice

::: check
given: p = 1024..3000 int; i = 1..80 int; s = 2 | 4 | 8; let B = 4*p
answer: B + s*i
base: 16
width: 4

## Element {i} of an array of {s}-byte items at 0x{B:hex4}?

::: misses
- [B + i] Scale by {s}.
- [any] Base + size × index.
:::
:::

::: check
given: k = 3..9 int; n = 4..50 int
answer: n*(k + 2) + 1
tolerance: 0

## A loop's body is {k} instructions; each pass adds a test and a jump back. It runs {n} passes and leaves on one last test. Instructions?

::: misses
- [n*k] Each pass also runs the test and the jump.
- [n*(k + 2)] Plus the final test.
- [any] {n} × ({k} + 2) + 1.
:::
:::

::: check
kind: asm
given: a = 1..500 int; d = 1..300 int; s = -1 | 1; let b = a + s*d
setup: a0 = a; a1 = b
expect: a2 = d

## Translate `if (a > b) m = a - b; else m = b - a;` with a in a0, b in a1, m in a2.

```asm starter
    ebreak
```

```asm solution
    ble a0, a1, other
    sub a2, a0, a1
    j done
other:
    sub a2, a1, a0
done:
    ebreak
```

::: misses
- [any] Branch on the opposite test to the else part; jump over it after the then part.
:::
:::
:::
