Course contents 04 / 32

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. II, CPI\mathrm{CPI} and TcT_c 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 fixesThe implementation chooses
the registers a program sees: 32 integer registers of 32 bits in RV32I, and pchow the register file is built, how many physical registers stand behind it
memory as an array of bytes with 32-bit addressesthe memory technology, the caches, the latency of an access
every instruction: its encoding as a 32-bit word and its effect, including corner caseshow many cycles each takes, pipelining, executing several at once or out of order
what happens on an error, such as an illegal instructionclock 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 x5 and x10 alike; it is the ABI that calls one t0 and the other a0 and 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 time=I×CPI×Tc\text{time} = I \times \mathrm{CPI} \times T_c, CISC lowers the instruction count II, and RISC accepts a larger II 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.

Figure

One C function in four encodings

Machine-code length of one function for x86-64, AArch64, RV32IM and RV32IMCFour strips of bytes. x86-64: 7 bytes, 3 instructions; AArch64: 20 bytes, 5 instructions; RV32IM: 24 bytes, 6 instructions; RV32IMC: 12 bytes, 6 instructions. Instructions that access memory are highlighted: one on x86-64, two on the others.x86-647 bytes, 3 instructions4863c6movsxd011487addc3retAArch6420 bytes, 5 instructions287c7e93sbfiz096868b8ldr2901020badd096828b8strc0035fd6retRV32IM24 bytes, 6 instructions93952500slli3305b500add83250500lwb385c500add2320b500sw67800000retRV32IMC12 bytes, 6 instructions8a05slli2e95add0c41lwb295add0cc1sw8280ret04812162024bytereads or writes memoryregisters onlyMachine-code length of one function for x86-64, AArch64, RV32IM and RV32IMCFour strips of bytes. x86-64: 7 bytes, 3 instructions; AArch64: 20 bytes, 5 instructions; RV32IM: 24 bytes, 6 instructions; RV32IMC: 12 bytes, 6 instructions. Instructions that access memory are highlighted: one on x86-64, two on the others.x86-64 · 7 bytes, 3 instructionsAArch64 · 20 bytes, 5 instructionsRV32IM · 24 bytes, 6 instructionsRV32IMC · 12 bytes, 6 instructions04812162024bytereads or writes memoryregisters only
The function void add_to(int *a, int i, int x) { a[i] += x; } compiled by clang 17.0.4 with -O2 for four targets; each cell is one byte of machine code in memory order, and each group of cells is one instruction. x86-64 (CISC) needs three instructions of different lengths, and one of them reads a[i] from memory, adds x and writes the result back by itself. AArch64 and RISC-V (RISC) read memory only with a load (ldr, lw) and write it only with a store (str, sw), and all their instructions have one length, 4 bytes. The C extension of RISC-V encodes the same six instructions in 2 bytes each. On x86-64 and AArch64 the index i is first widened to 64 bits (movsxd, sbfiz), because pointers there are 64 bits wide.

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 TcT_c, 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:

LetterExtensionAdds
Minteger multiplication and divisionmul, mulh, div, rem, …
Aatomic instructionsread-modify-write on memory for synchronization
F, Dsingle- and double-precision floating point32 floating-point registers and IEEE 754 arithmetic
Ccompressed instructions16-bit encodings of the most common instructions
Vvector instructionsoperations on whole arrays of numbers
Zicsr, Zifenceicontrol registers, instruction-fetch fenceaccess 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):

RegisterABI nameUsePreserved across calls
x0zeroalways zero(cannot change)
x1rareturn addressno
x2spstack pointeryes
x3gpglobal pointer(not allocated)
x4tpthread pointer(not allocated)
x5–x7t0–t2temporariesno
x8s0 / fpsaved register, frame pointeryes
x9s1saved registeryes
x10–x11a0–a1arguments and return valuesno
x12–x17a2–a7argumentsno
x18–x27s2–s11saved registersyes
x28–x31t3–t6temporariesno

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.

DirectiveEffect
.text, .dataput what follows into the code segment or the data segment
.word, .half, .byteemit 32-, 16- or 8-bit integers
.asciz (also .string), .asciiemit the bytes of a string, with or without a terminating zero byte
.space nreserve n bytes
.align kadvance to the next multiple of 2k2^k bytes
.globl namemake a label visible to other files
.eqv name, valuedefine 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):

RegionAddress
code (.text)starts at 0x00400000
global pointer gp0x10008000
data (.data)starts at 0x10010000
heapstarts at 0x10040000
stack pointer sp at start0x7fffeffc, growing down
memory-mapped devicesfrom 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#

Figure

How the assembler turns hello.s into memory contents

The two passes of the assembler for the hello-world programOn the left, the 11-line source text. The symbol table: greeting at 0x10010000, main at 0x00400000. Pseudo-instruction expansion: li a7, 4 becomes addi a7, zero, 4; la a0, greeting becomes auipc a0, 0x0fc10 and addi a0, a0, -4. At the bottom, memory: four data words holding the bytes of Hello, RISC-V! and six code words from 0x00400000 to 0x00400014; pc points at the first.source text.datagreeting:  .asciz "Hello, RISC-V!\n".text.globl mainmain:  li   a7, 4  la   a0, greeting  ecall  li   a7, 10  ecallpass 1: addresses of labelslabel     segment  addressgreeting  .data    0x10010000main      .text    0x004000001pseudo-instructions expandli a7, 4         →  addi  a7, zero, 4la a0, greeting  →  auipc a0, 0x0fc10                    addi  a0, a0, -40x10010000 − 0x00400004 = 0x0fc10·4096 − 43memory after loading: .data0x10010000  48 65 6c 6c  Hell0x10010004  6f 2c 20 52  o, R0x10010008  49 53 43 2d  ISC-0x1001000c  56 21 0a 00  V!\n\02memory after loading: .text0x00400000  0x00400893  addi  a7, zero, 40x00400004  0x0fc10517  auipc a0, 0x0fc100x00400008  0xffc50513  addi  a0, a0, -40x0040000c  0x00000073  ecall0x00400010  0x00a00893  addi  a7, zero, 100x00400014  0x00000073  ecall4← pc5The two passes of the assembler for the hello-world programOn the left, the 11-line source text. The symbol table: greeting at 0x10010000, main at 0x00400000. Pseudo-instruction expansion: li a7, 4 becomes addi a7, zero, 4; la a0, greeting becomes auipc a0, 0x0fc10 and addi a0, a0, -4. At the bottom, memory: four data words holding the bytes of Hello, RISC-V! and six code words from 0x00400000 to 0x00400014; pc points at the first.source text.datagreeting:  .asciz "Hello, RISC-V!\n".text.globl mainmain:  li   a7, 4  la   a0, greeting  ecall  li   a7, 10  ecallpass 1: addresses of labelslabel     segment  addressgreeting  .data    0x10010000main      .text    0x004000001pseudo-instructions expandli a7, 4         →  addi  a7, zero, 4la a0, greeting  →  auipc a0, 0x0fc10                    addi  a0, a0, -40x10010000 − 0x00400004 = 0x0fc10·4096 − 43memory after loading: .data0x10010000  48 65 6c 6c  Hell0x10010004  6f 2c 20 52  o, R0x10010008  49 53 43 2d  ISC-0x1001000c  56 21 0a 00  V!\n\02memory after loading: .text0x00400000  0x00400893  addi0x00400004  0x0fc10517  auipc0x00400008  0xffc50513  addi0x0040000c  0x00000073  ecall0x00400010  0x00a00893  addi0x00400014  0x00000073  ecall4← pc5
The hello-world program of this note. The first pass walks the lines with two location counters and records every label in the symbol table: greeting = 0x10010000, main = 0x00400000 (1). The .asciz directive emits 16 bytes: 15 characters and a terminating zero (2). The pseudo-instruction la expands into two instructions, auipc and addi, so everything after it moves by 4 bytes (3). The second pass encodes every instruction; for la the offset 0x10010000 − 0x00400004 = 0x0fc0fffc is split into an upper part 0x0fc10 for auipc and a lower part -4 for addi (4). RARS places the words in the text segment and the bytes in the data segment and starts at main (5). The bytes of the string appear in memory in order; the word at 0x10010004 read as a whole is 0x52202c6f, because RISC-V stores the least significant byte first.

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:

  1. Pass 1 walks the lines with one location counter per segment, .text from 0x00400000 and .data from 0x10010000. 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.
  2. The data directives produce their bytes: .asciz "Hello, RISC-V!\n" emits 15 characters and a terminating zero, 16 bytes.
  3. Pseudo-instructions are expanded already in pass 1, because their size moves every later address: li a7, 4 is one instruction, la a0, greeting is two.
  4. Pass 2 encodes every instruction as a 32-bit word, replacing labels by addresses or by offsets from the instruction’s own address.
  5. RARS copies the words and bytes into memory and sets pc to the start of main.

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:

0x10010000−0x00400004=0x0fc0fffc=0x0fc10⋅4096−4,auipc a0, 0x0fc10: a0=0x00400004+0x0fc10000=0x10010004,addi a0, a0, -4: a0=0x10010000.\begin{aligned} \texttt{0x10010000} - \texttt{0x00400004} &= \texttt{0x0fc0fffc} = \texttt{0x0fc10} \cdot 4096 - 4, \\ \texttt{auipc a0, 0x0fc10} &: \ \texttt{a0} = \texttt{0x00400004} + \texttt{0x0fc10000} = \texttt{0x10010004}, \\ \texttt{addi a0, a0, -4} &: \ \texttt{a0} = \texttt{0x10010000}. \end{aligned}

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:

a7ServiceArguments and result
1PrintIntprint a0 as a signed decimal
4PrintStringprint the zero-terminated string at address a0
5ReadIntread an integer; result in a0
10Exitend the program
11PrintCharprint the character whose code is in a0
34PrintIntHexprint a0 in hexadecimal
93Exit2end 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 machinePrograms written to an ISA
What a program relies onthe details of one hardware designthe documented effect of each instruction
A faster processorneeds the software rewrittenruns the same binary
Corner cases (division by zero, overflow)whatever the hardware happens to dospecified, per ISA
Who may build a compatible processorthe original manufactureranyone implementing the specification; for RISC-V, without a license
Where speed comes fromthe design itselfthe 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 ecall does, 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] += x is 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: x0 is always zero; the ABI names (ra, sp, t0–t6, s0–s11, a0–a7) describe how software uses them. pc is 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 at 0x10010000, sp at 0x7fffeffc; ecall with a7 = 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#