04 / 32 · RISC-V Assembly
The processor and the instruction set
What software may rely on when it runs on a processor: the instruction set as a contract, RISC against CISC, the RISC-V base and extensions with its 32 registers, and how the assembler and the RARS simulator turn a text file into a running program.
On this page 8
The floating-point note completed the Foundations: integers, characters and real numbers are patterns of bits in memory, and the first note showed the loop that a processor runs over such patterns, fetching an instruction, decoding it and executing it. That loop leaves the main question open. Which instructions are there, what exactly does each one do, and how much of the machine may a program depend on? This note answers it for the processor we program in this part of the course. It treats the instruction set as a contract between hardware and software, compares the two traditions of designing one, introduces RISC-V with its registers, and follows a text file of assembly through the assembler into the memory of the RARS simulator, ending with two complete programs.
Notation. Numbers written 0x… are hexadecimal. Addresses and instruction words are 32 bits wide and are written with all eight hex digits, as in 0x00400018. The integer registers are x0 to x31; each also has an ABI name such as a0 or t1, and the two names denote the same register. pc is the program counter, the address of the instruction being executed. , and are the instruction count, cycles per instruction and clock period of the performance equation.
Baseline: a program written for one machine#
The simplest way to make a processor programmable is to let programs use whatever instructions its designers happened to build. Early computers worked this way. Each design had its own instructions, register layout and data formats, and a program written in those instructions ran on that design and nowhere else.
The cost showed as soon as there were two machines. A faster successor with a different design could not run the old programs, so each new machine meant rewriting the software, and a manufacturer that sold small and large computers had to maintain several incompatible lines with their own compilers and libraries. IBM’s System/360, announced in 1964, was designed to end this: one instruction set for a whole family of models that differed widely in speed and price, so that the same program ran on any of them. Its designers also gave the word architecture its meaning in computing: the attributes of a machine as the programmer sees them, its structure and behaviour, as distinct from the data paths, logic and technology of any particular model (Amdahl, Blaauw and Brooks, 1964).
The baseline breaks because it ties two things that change at different speeds. Software lives for decades; a hardware design is overtaken in a few years. Without a stable interface between them, every improvement in hardware throws software away, and every program pins the hardware it needs.
The instruction set as a contract#
A contract is only useful if it is precise. The RISC-V specification fixes these things, and leaves the rest to the implementation, its microarchitecture:
| The ISA fixes | The implementation chooses |
|---|---|
the registers a program sees: 32 integer registers of 32 bits in RV32I, and pc | how the register file is built, how many physical registers stand behind it |
| memory as an array of bytes with 32-bit addresses | the memory technology, the caches, the latency of an access |
| every instruction: its encoding as a 32-bit word and its effect, including corner cases | how many cycles each takes, pipelining, executing several at once or out of order |
| what happens on an error, such as an illegal instruction | clock rate, power, area, price |
The corner cases are where the contract earns its keep. Dividing by zero has no meaningful answer, yet a processor must do something, and the ISA says what. In RISC-V, div by zero returns −1 (all bits set) and rem by zero returns the dividend; there is no trap, because it would be the only arithmetic trap in the whole ISA, and a language that requires one adds a single branch after the division (RISC-V Unprivileged ISA, the M extension). The ARMv8 instruction sdiv returns 0 instead; on an Apple M-series processor, sdiv of 7 by 0 gives 0 and the remainder computed from it is 7. The x86 idiv raises a divide-error exception (Intel SDM, IDIV), which the operating system turns into a crash of the program. Three architectures, three contracts; a program that relies on one of them is correct on every processor of that architecture and wrong on the others. The Code section runs the RISC-V cases.
Two more layers sit next to the ISA, and it pays to keep them apart:
- Microarchitecture is one implementation of the contract. A small microcontroller that runs one instruction every few cycles and a server core that runs several per cycle can implement the same ISA and run the same binary.
- The application binary interface (ABI) is a set of software conventions on top of the ISA: which register holds the return address, where arguments go, how the stack is laid out, how a program asks the operating system for a service. The hardware treats
x5andx10alike; it is the ABI that calls onet0and the othera0and says how compilers must use them. Programs compiled by different compilers can call each other only because they follow one ABI.
RISC and CISC#
Instruction sets have been designed in two traditions. CISC (complex instruction set computer) instruction sets, such as the VAX and x86 of the 1970s, gave single instructions a lot of work: an arithmetic instruction could take its operands from memory and write the result back to memory, addresses could be computed in many ways, and instructions had many lengths. That suited the time: memory was small and expensive, so dense code mattered; much software was written in assembly, where powerful instructions are convenient; and microcode made new instructions cheap to add.
RISC (reduced instruction set computer) designs reversed the bet. Patterson and Ditzel (1980) argued that compilers, by then the main producers of machine code, used mostly the simple instructions, and that the complex ones cost hardware and slowed down everything else. The RISC designs of the 1980s, Berkeley’s RISC I and Stanford’s MIPS among them, kept a small set of simple instructions with a few common properties:
- load/store: only load and store instructions touch memory; arithmetic works on registers;
- one instruction length, so the next instruction is always 4 bytes further and decoding is simple;
- many registers (32 rather than 8 or 16), so that values stay in registers instead of memory;
- few, regular formats, with the register fields in fixed positions.
In the terms of the performance equation , CISC lowers the instruction count , and RISC accepts a larger to make the cycles per instruction and the clock period smaller, mainly by making the instructions easy to pipeline, a subject of the pipelining note.
One C function in four encodings
Worked example (measured). The C function void add_to(int *a, int i, int x) { a[i] += x; }, compiled by clang 17.0.4 with -O2 and disassembled, gives the code in the figure. On x86-64 it takes 3 instructions in 7 bytes; one of them, add dword ptr [rdi + 4*rax], edx, reads a[i] from memory, adds x and writes the sum back, all by itself. On RISC-V (RV32IM) it takes 6 instructions in 24 bytes: shift the index left by 2 (multiply by 4, the size of an int), add it to the address of a, load, add, store, return. AArch64, ARM’s 64-bit instruction set, is a RISC design too and needs 5 instructions in 20 bytes. With RISC-V’s compressed extension C, the same 6 instructions take 2 bytes each, 12 bytes in all. Which version runs faster depends on CPI and , which this code alone cannot tell.
The two camps have since converged. Since Intel’s P6 design of 1995, the Pentium Pro, x86 processors translate each instruction internally into simpler RISC-like micro-operations and schedule those (Gwennap, 1995), and RISC instruction sets added compressed encodings and specialized instructions of their own. What remains of the distinction is visible to software and to the decoder: variable against fixed length, memory operands against load/store, and a large, historically grown instruction set against a small, regular one.
RISC-V: a small base and optional extensions#
RISC-V was started at UC Berkeley in 2010 as an instruction set for research and teaching; its name marks it as the fifth RISC design from Berkeley (Waterman, 2016). Two choices make it suitable for this course. It is open: anyone may implement it without a license, and its specifications are maintained by the non-profit RISC-V International (Asanović and Patterson, 2014). And it is modular: a small base that is enough for a compiler and an operating system, plus optional extensions.
There are four base integer instruction sets: RV32I and RV64I, with 32 registers of 32 or 64 bits and 32- or 64-bit addresses, and RV32E and RV64E, the same with 16 registers for small microcontrollers. A 128-bit base is reserved for the future. RV32I has 40 instructions (RISC-V Unprivileged ISA, the RV32I chapter). The standard extensions add what the base lacks:
| Letter | Extension | Adds |
|---|---|---|
| M | integer multiplication and division | mul, mulh, div, rem, … |
| A | atomic instructions | read-modify-write on memory for synchronization |
| F, D | single- and double-precision floating point | 32 floating-point registers and IEEE 754 arithmetic |
| C | compressed instructions | 16-bit encodings of the most common instructions |
| V | vector instructions | operations on whole arrays of numbers |
| Zicsr, Zifencei | control registers, instruction-fetch fence | access to control and status registers; synchronizing instruction memory |
An ISA name lists the base and then the extensions in a fixed order, and G abbreviates the general-purpose set IMAFD with Zicsr and Zifencei. So RV64GC, the usual target of Linux-capable RISC-V processors, means RV64IMAFDCZicsr_Zifencei: the 64-bit base with multiply and divide, atomics, single and double precision, compressed instructions and the two Z extensions.
This part of the course uses RV32IM: the 32-bit base with multiplication and division. It is small enough to learn completely, and everything in the next three notes is written in it. The RARS simulator implements more (RV32 and RV64 with I, M, F, D and N), so the programs run there unchanged.
The 32 registers and their ABI names#
Registers are the processor’s own storage: a few words that an instruction can read and write within a single clock cycle, as opposed to memory, which is large and much slower (the caches note measures how much). In a load/store architecture every arithmetic operand must be in a register, so the registers are what a program works with most of the time.
RV32I has 32 registers of 32 bits, x0 to x31. The hardware treats 31 of them identically; only x0 is special, because it always reads as zero and ignores writes. The ABI gives each register a name that says how software uses it (RISC-V psABI, the register convention):
| Register | ABI name | Use | Preserved across calls |
|---|---|---|---|
x0 | zero | always zero | (cannot change) |
x1 | ra | return address | no |
x2 | sp | stack pointer | yes |
x3 | gp | global pointer | (not allocated) |
x4 | tp | thread pointer | (not allocated) |
x5–x7 | t0–t2 | temporaries | no |
x8 | s0 / fp | saved register, frame pointer | yes |
x9 | s1 | saved register | yes |
x10–x11 | a0–a1 | arguments and return values | no |
x12–x17 | a2–a7 | arguments | no |
x18–x27 | s2–s11 | saved registers | yes |
x28–x31 | t3–t6 | temporaries | no |
The last column belongs to the calling convention, the subject of the procedures note; until then we use the t registers for scratch values and the a registers to talk to the system. pc is not among the 32: no instruction names it as an operand, and it changes only by moving to the next instruction or by a jump or branch.
Why x0? A constant zero register makes many operations special cases of others, so the instruction set stays small. Copying a register is adding zero to it, addi a0, t0, 0; loading a small constant is adding it to zero, addi a7, zero, 4; doing nothing is addi zero, zero, 0, whose result is discarded. The assembler offers these as mv, li and nop, and the processor never sees those names.
Why 32? A register number takes 5 bits, and an instruction with two sources and a destination spends 15 of its 32 bits on register numbers. More registers would need longer fields and a larger, slower register file; fewer would force more values out to memory. RV32E halves the count to 16 for the smallest chips, where the register file is a noticeable part of the area.
The assembler, directives and RARS#
Writing instruction words by hand is possible (the next note does it for a few) but slow and error-prone. Assembly language writes one instruction per line in a readable form, and an assembler translates it into machine code. A line has up to four parts:
loop: addi t0, t0, 1 # label, mnemonic, operands, comment
A label names the address of what follows it, so that other instructions can refer to it by name. A mnemonic with its operands is an instruction. Everything after # is a comment. Lines that start with a dot are directives: they are not instructions but orders to the assembler about where to put things and what data to emit.
| Directive | Effect |
|---|---|
.text, .data | put what follows into the code segment or the data segment |
.word, .half, .byte | emit 32-, 16- or 8-bit integers |
.asciz (also .string), .ascii | emit the bytes of a string, with or without a terminating zero byte |
.space n | reserve n bytes |
.align k | advance to the next multiple of bytes |
.globl name | make a label visible to other files |
.eqv name, value | define a named constant |
Some mnemonics are pseudo-instructions: names the assembler accepts and replaces by one or two real instructions. li (load immediate), la (load address), mv, j (jump) and ret are the most common; the branches note lists them.
RARS, the RISC-V Assembler and Runtime Simulator, is a Java program built on the MIPS simulator MARS (RARS). It edits and assembles a program, runs it to the end or one instruction at a time, and shows the registers, the memory and, next to every source line, the machine code it became. It places a program in memory as follows (its default configuration):
| Region | Address |
|---|---|
code (.text) | starts at 0x00400000 |
global pointer gp | 0x10008000 |
data (.data) | starts at 0x10010000 |
| heap | starts at 0x10040000 |
stack pointer sp at start | 0x7fffeffc, growing down |
| memory-mapped devices | from 0xffff0000 |
RARS starts at the first instruction of .text unless the setting that starts at the global label main is turned on, so our programs put main first.
Two passes#
How the assembler turns hello.s into memory contents
An assembler cannot encode a line the moment it reads it, because a line may use a label defined later. It therefore reads the program twice:
- Pass 1 walks the lines with one location counter per segment,
.textfrom0x00400000and.datafrom0x10010000. Each instruction advances the text counter by 4 bytes per real instruction, each data directive advances the data counter by the bytes it emits, and every label is recorded with the current counter in a symbol table. - The data directives produce their bytes:
.asciz "Hello, RISC-V!\n"emits 15 characters and a terminating zero, 16 bytes. - Pseudo-instructions are expanded already in pass 1, because their size moves every later address:
li a7, 4is one instruction,la a0, greetingis two. - Pass 2 encodes every instruction as a 32-bit word, replacing labels by addresses or by offsets from the instruction’s own address.
- RARS copies the words and bytes into memory and sets
pcto the start ofmain.
Worked example. In the hello-world program, pass 1 gives greeting = 0x10010000 and main = 0x00400000. The la a0, greeting sits at 0x00400004 and becomes two instructions. auipc adds a constant times 4096 to its own address, and addi adds a small constant, so the assembler splits the distance to the label:
Why −4 and not 0xffc, and why the upper part is 0x0fc10 rather than 0x0fc0f, is the sign-adjustment trick of the next note. Because the address is computed relative to pc, the same code works wherever it is loaded.
The bytes of the string sit in memory in order: 0x48 (H) at 0x10010000, 0x65 (e) at 0x10010001, and so on. A 32-bit read of the word at 0x10010004 returns the four bytes o, ,, space and R, that is 0x6f 0x2c 0x20 0x52, and because RISC-V is little-endian, the first byte is the least significant: the word is 0x52202c6f. The byte order is the one of the integers note.
System calls#
A program in RARS has no screen or keyboard of its own; it asks the simulator, which plays the role of the operating system, with the instruction ecall (environment call). The number in a7 selects the service, arguments go in a0 and up, and a result comes back in a0:
a7 | Service | Arguments and result |
|---|---|---|
| 1 | PrintInt | print a0 as a signed decimal |
| 4 | PrintString | print the zero-terminated string at address a0 |
| 5 | ReadInt | read an integer; result in a0 |
| 10 | Exit | end the program |
| 11 | PrintChar | print the character whose code is in a0 |
| 34 | PrintIntHex | print a0 in hexadecimal |
| 93 | Exit2 | end the program with exit code a0 |
These numbers are RARS’s own, inherited from the MIPS simulators it descends from. On Linux the mechanism is the same, ecall with a number in a7, but the services are those of the kernel: read is 63, write is 64 and exit is 93 on RISC-V (Linux asm-generic/unistd.h). The system-calls note follows ecall into the kernel.
A first program: hello world and a sum#
The hello-world program of the figure, in full:
.data
greeting:
.asciz "Hello, RISC-V!\n" # 15 characters and a terminating zero byte
.text
.globl main
main:
li a7, 4 # system call 4, PrintString: print the string at address a0
la a0, greeting # a0 = address of the first byte of greeting
ecall
li a7, 10 # system call 10, Exit
ecall
# Output:
# Hello, RISC-V!
The program executes 6 instructions: li is one, la two, and the two ecalls and the last li one each. The first ecall finds 4 in a7, reads bytes from the address in a0 up to the zero byte and prints them. The second finds 10 and stops the program. Without it, the processor would go on fetching whatever words follow the program in memory.
The second program reads two integers and prints their sum, 17 + 25 = 42 for the input 17 and 25 (the full text is in the Code section). Its core is three instructions:
li a7, 5 # ReadInt: the integer typed goes to a0
ecall
mv t0, a0 # keep it in t0, because the next ecall overwrites a0
repeated for the second number into t1, then add t2, t0, t1, then one ecall per piece of output: PrintInt for the numbers, PrintString for " + " and " = ", PrintChar for the final newline. Two habits start here. Every value we need later is moved out of a0 into a register that the next system call does not touch. And output is built from pieces, because the system calls print one number or one string at a time.
What changed#
| Baseline: programs for one machine | Programs written to an ISA | |
|---|---|---|
| What a program relies on | the details of one hardware design | the documented effect of each instruction |
| A faster processor | needs the software rewritten | runs the same binary |
| Corner cases (division by zero, overflow) | whatever the hardware happens to do | specified, per ISA |
| Who may build a compatible processor | the original manufacturer | anyone implementing the specification; for RISC-V, without a license |
| Where speed comes from | the design itself | the microarchitecture, hidden behind the contract |
Limitations#
- The contract promises results, not speed. Two processors that implement RV32IM run the same binary at very different speeds, and the reasons (pipelines, caches, parallel execution) are below the contract. Fast code needs a model of what lies below; the Memory Hierarchy and Inside the Processor sections build it.
- Some things are left to the execution environment. The RISC-V specification lets the environment decide what
ecalldoes, whether misaligned memory accesses are allowed and even the byte order. RARS’s services are not Linux’s; a RARS program is not a Linux program. - Compatibility preserves mistakes. An ISA can add instructions but hardly ever remove them, because some binary uses each. Every x86 processor still decodes instructions of the 8086 of 1978.
- Assembly is tied to one ISA. The programs in this part of the course must be rewritten for x86 or ARM; making programs portable across ISAs is the job of compilers (compilers note).
- RARS is a teaching simulator. It runs one instruction at a time with no caches or pipeline, so it says nothing about time, and its devices are simulated.
What you should remember#
- The ISA is the contract between hardware and software: registers, memory as a byte array, every instruction with its encoding and effect, including corner cases. The microarchitecture implements it; the ABI adds software conventions on top.
- CISC instructions do more each and vary in length; RISC instructions are simple, fixed-length, and only loads and stores touch memory.
a[i] += xis 3 instructions in 7 bytes on x86-64 and 6 instructions in 24 bytes on RV32IM (12 bytes with compressed instructions). - RISC-V is open and modular: a base (RV32I, RV64I, RV32E, RV64E) plus extensions (M, A, F, D, C, V, …); G = IMAFD with Zicsr and Zifencei. We use RV32IM.
- 32 registers:
x0is always zero; the ABI names (ra,sp,t0–t6,s0–s11,a0–a7) describe how software uses them.pcis separate. - An assembler makes two passes: addresses and labels first, encodings second. Directives place data and choose segments; pseudo-instructions expand into real ones.
- In RARS, code starts at
0x00400000, data at0x10010000,spat0x7fffeffc;ecallwitha7= 1, 4, 5, 10, 11, 34 or 93 asks for a service.
Code#
The sum of two numbers, the full program (run with the input 17 25):
.data
plus: .asciz " + "
equals: .asciz " = "
.text
.globl main
main:
li a7, 5 # system call 5, ReadInt: the integer typed goes to a0
ecall
mv t0, a0 # t0 = a
li a7, 5
ecall
mv t1, a0 # t1 = b
add t2, t0, t1 # t2 = a + b
li a7, 1 # system call 1, PrintInt: print a0 in decimal
mv a0, t0
ecall
li a7, 4 # print " + "
la a0, plus
ecall
li a7, 1
mv a0, t1
ecall
li a7, 4 # print " = "
la a0, equals
ecall
li a7, 1
mv a0, t2
ecall
li a7, 11 # system call 11, PrintChar: print the character in a0
li a0, 10 # 10 is the ASCII code of the newline character
ecall
li a7, 10 # system call 10, Exit
ecall
# Input: 17 25
# Output: 17 + 25 = 42
# (29 instructions executed; with the input -5 3 it prints -5 + 3 = -2)
What the RISC-V contract says about the corner cases of division:
.text
.globl main
main:
li t0, 7
div a0, t0, zero # 7 / 0: the quotient has all bits set
li a7, 1
ecall # prints -1
li a0, ' '
li a7, 11
ecall
rem a0, t0, zero # 7 % 0: the remainder is the dividend
li a7, 1
ecall # prints 7
li a0, ' '
li a7, 11
ecall
li t1, 0x80000000 # the most negative 32-bit integer, -2147483648
li t2, -1
div a0, t1, t2 # -2147483648 / -1 overflows: the quotient is the dividend
li a7, 34
ecall # prints 0x80000000
li a7, 10
ecall
# Output: -1 7 0x80000000
The assembler’s arithmetic for the hello-world program, the numbers of the figure:
TEXT, DATA = 0x00400000, 0x10010000 # where RARS puts .text and .data
# pass 1: addresses. greeting is the first data item; main is the first instruction.
greeting, main = DATA, TEXT
s = b'Hello, RISC-V!\n' + b'\0' # .asciz adds the terminating zero
print(len(s), hex(greeting), hex(main)) # 16 0x10010000 0x400000
# la a0, greeting at main + 4 becomes auipc (adds hi * 4096 to pc) and addi (adds lo, -2048..2047)
pc = main + 4
off = (greeting - pc) % 2**32
lo = ((off & 0xfff) ^ 0x800) - 0x800 # the low 12 bits, read as a signed number
hi = ((off - lo) >> 12) & 0xfffff
print(hex(off), hex(hi), lo, hex((pc + (hi << 12) + lo) % 2**32)) # 0xfc0fffc 0xfc10 -4 0x10010000
# the word at greeting + 4, read as a little-endian 32-bit integer
print(hex(int.from_bytes(s[4:8], 'little')), s[4:8]) # 0x52202c6f b'o, R'
Next#
The programs so far used a handful of instructions and saw each one as a mnemonic. The next note lists the arithmetic, logic and shift instructions of RV32I and opens the 32-bit words themselves: the six instruction formats, encoding an instruction by hand, why some constants are cut into pieces, and how lui and addi build any 32-bit constant, including the split that turned la into 0x0fc10 and −4.
References#
- A. Tatarnikov. Computer Architecture and Operating Systems (HSE), lecture 3: computer architecture and assembly language.
- D. A. Patterson, J. L. Hennessy. Computer Organization and Design, RISC-V Edition, 2nd ed. Morgan Kaufmann, 2020. Chapter 1 (computer abstractions), chapter 2 (instructions: the language of the computer; section 2.12, translating and starting a program).
- S. L. Harris, D. M. Harris. Digital Design and Computer Architecture, RISC-V Edition. Morgan Kaufmann, 2021. Sections 6.1–6.2 (architecture and assembly language).
- G. M. Amdahl, G. A. Blaauw, F. P. Brooks. Architecture of the IBM System/360. IBM Journal of Research and Development, 8(2):87–101, 1964.
- D. A. Patterson, D. R. Ditzel. The case for the reduced instruction set computer. ACM SIGARCH Computer Architecture News, 8(6):25–33, 1980.
- A. Waterman. Design of the RISC-V Instruction Set Architecture. PhD thesis, UC Berkeley, technical report UCB/EECS-2016-1, 2016.
- K. Asanović, D. A. Patterson. Instruction Sets Should Be Free: The Case For RISC-V. Technical report UCB/EECS-2014-146, UC Berkeley, 2014.
- RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged ISA. The introduction (base ISAs and extensions), the RV32I chapter, the M extension (division by zero), and the ISA naming conventions.
- RISC-V International. RISC-V ELF psABI specification, the calling convention chapter (integer register convention).
- RARS: RISC-V Assembler and Runtime Simulator, the repository and its wiki pages on assembler directives and environment calls.
- Intel. Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 2, the
IDIVinstruction (divide error on a zero divisor). - L. Gwennap. Intel’s P6 uses decoupled scalar design. Microprocessor Report, 9(2), 1995.
- Linux
include/uapi/asm-generic/unistd.h, the system-call numbers shared by RISC-V and other newer architectures. - CS 61C: Great Ideas in Computer Architecture, UC Berkeley, the RISC-V lectures.