$ cat posts/from-c-to-risc-v.md

From C to RISC-V: following one program down to the pipeline

#compilers#hardware2 min read

We study computer architecture from Patterson & Hennessy’s RISC-V edition. The book explains each step from C code to a running processor, but I wanted to watch one program go through every step. So I built Silicon Path.

The stations

Silicon Path takes a small C program through every step, and you can stop and look at each one:

  1. Tokens: the lexer splits the source into words and symbols.
  2. Syntax tree: the parser works out the program’s structure.
  3. Symbols and types: semantic analysis checks that the program makes sense.
  4. IR: the tree is lowered to simple three-address code, and seven optimisation passes clean it up.
  5. RISC-V assembly: register allocation and code generation for RV32IM.
  6. Machine code and linking: my own assembler and linker produce a binary.
  7. The pipeline: the classic 5-stage pipeline (IF, ID, EX, MEM, WB) with hazards, forwarding and stalls, plus L1 and L2 caches in front of memory.

One loop, all the way down

Take this function:

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

Its loop turns into RISC-V along these lines:

sum:    li   t0, 0          # s = 0
        li   t1, 0          # i = 0
loop:   bge  t1, a1, done   # stop when i >= n
        slli t2, t1, 2      # byte offset = i * 4
        add  t2, a0, t2     # address of a[i]
        lw   t3, 0(t2)      # load a[i]
        add  t0, t0, t3     # s += a[i]
        addi t1, t1, 1      # i++
        j    loop
done:   mv   a0, t0         # return s
        ret

Look at the lw followed straight away by an add that uses the loaded value. Even with forwarding, the pipeline has to stall for one cycle, because the data only arrives at the end of the MEM stage. In the pipeline view you can see the bubble move through the stages. That’s a load-use hazard, the kind of thing the book draws as a diagram, happening live.

How do you know a compiler is right?

You compare it against something you trust. Every test program runs three ways: on a reference interpreter that walks the syntax tree, on an instruction-set simulator, and on the cycle-accurate pipeline. All three must print the same output. The hand-written tests are also checked against the output of clang.

On top of that, a random program generator writes over a thousand programs, and each one is compiled with 18 different build settings and run on 5 pipeline configurations. If any of them disagree, there’s a bug.

The code is on GitHub: rivija21/silicon_RISC.