Home / Learn Chip Programming / RISC-V Assembly Programming
RISC-V Assembly Programming
Write real RISC-V code: loops, memory access, function calls.
In shortWrite real RISC-V code: loops, memory access, function calls.
Theory in plain words
What it is
RISC-V assembly uses registers and a few pseudo-instructions (li, mv, j, ret, call). Memory access via lw/sw with base + offset. Branches compare two registers.
Why we use it
It is the cleanest ISA to learn assembly and the same code runs in simulators like Venus or Spike, and on real boards.
How it works
Sum an array: load each element with lw, add, advance pointer by 4, loop with bne. Functions: arguments in a0 to a7, return in a0, return address in ra.
Where it is used
- Learning CPU design
- Bootloaders and startup code
- Writing a RISC-V simulator
Mini RV32 simulator
Run a RISC-V program step by stepTry it Yourself
x6 ends at 15: the same loop as the teaching CPU earlier, now in real RISC-V instructions.
.text
fact: # a0 = n ; returns n! in a0
li t0, 1
1: beqz a0, 2f
mul t0, t0, a0
addi a0, a0, -1
j 1b
2: mv a0, t0
ret
sum: # a0 = pointer, a1 = count
li t0, 0
loop:
lw t1, 0(a0)
add t0, t0, t1
addi a0, a0, 4
addi a1, a1, -1
bnez a1, loop
mv a0, t0
retTip:Try it in the browser at the Venus RISC-V simulator, or locally with
riscv64-unknown-elf-gcc and QEMU (qemu-system-riscv32 -machine virt).Quick quiz
1. Where is the return address kept?
jal stores it in ra.
2. lw t1, 0(a0) does...
Base + offset addressing.