এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
10Assembly Language and the Calling Convention
What does the C statement x = a[i] + 1; become inside the processor? Four instructions, each doing one small thing, traced here one line per instruction as the series’ RISC-V machine runs them.
main: la a0, a # the address of the array
li a1, 2 # i = 2
slli t0, a1, 2 # i * 4: an int is 4 bytes
add t0, a0, t0 # the address of a[i]
lw t1, 0(t0) # load a[i] from memory into a register
addi a2, t1, 1 # a[i] + 1, in a register
x = a[i] + 1 in RISC-V code/bachelor-2/10-assembly-and-calling-convention/listings/hook.S$ python -m rv run hook.S --trace
step pc word instruction effect
4 0001000c 00259293 slli t0, a1, 2 t0 = 8
5 00010010 005502b3 add t0, a0, t0 t0 = 0x10000008
6 00010014 0002a303 lw t1, 0(t0) t1 = 412 <- mem[0x10000008] (word)
7 00010018 00130613 addi a2, t1, 1 a2 = 413
a[i] is computed, then the value fetched. Some lines are left out.The C line hid an address computation, a memory access, and the fact that arithmetic happens only between registers. This chapter reads and writes such code: the instructions of a real instruction set, how they are encoded in 32-bit words, how C’s if, loops, arrays and structures become them, and the convention that lets functions compiled separately call one another.
You already know
Book 2: the toy machine has registers, flags, jumps, and CALL/RET through a stack. Book 3: a program becomes object files, then a process whose memory holds text, data, heap and stack; each call pushes a stack frame; values are aligned to their size; Book 3 also covers byte order, sign extension and the return address. Two’s complement represents negative integers.
10.1 The machine and its instructions
Definition 10.1 (Instruction set architecture)
An instruction set architecture (ISA) is the contract between a processor and its programs: the registers, the instructions with their encodings and effects, the memory model, and what happens on an error. Every processor that implements the ISA runs the same programs, however it is built (Chapter 11).
This book uses RISC-V, an open ISA whose specification is public, small and regular. The series’ machine rv implements the base integer set RV32I with the multiply-and-divide extension M, on 32-bit words.
History — An open instruction set
RISC-V began in May 2010 as a research project on instruction sets in a university laboratory, meant at first for teaching and experiments. Its authors published the specification openly; a foundation took it over in 2015, and an international association has maintained it since 2020. Anyone may build a RISC-V processor without a licence, which is why it is found today in microcontrollers, storage controllers and research chips.
Definition 10.2 (General-purpose register, register file)
A general-purpose register is a storage cell inside the processor, holding one word, that instructions name directly as operands. The register file is the set of them: in RV32, 32 registers x0 to x31 of 32 bits, where x0 always reads 0 and ignores writes.
Definition 10.3 (Immediate)
An immediate is a constant operand stored inside the instruction word itself, such as the 1 of addi a2, t1, 1. In RV32I most immediates have 12 bits, read signed: to .
| register | ABI name | role | preserved across calls |
|---|---|---|---|
x0 | zero | always 0 | — |
x1 | ra | return address | no |
x2 | sp | stack pointer | yes |
x3, x4 | gp, tp | global and thread pointers | not allocated |
x5–x7, x28–x31 | t0–t6 | temporaries | no (caller-saved) |
x8, x9, x18–x27 | s0–s11 | saved registers | yes (callee-saved) |
x10–x17 | a0–a7 | arguments; a0, a1 results | no (caller-saved) |
The arithmetic and logic instructions take two registers, or a register and an immediate, and write a third: add, sub, and, or, xor, the shifts sll, srl (logical, zeros in) and sra (arithmetic, copies of the sign bit in), the comparisons slt and sltu (set to 1 if less, signed or unsigned), and mul, div, rem from the M extension; each has an immediate form with an i suffix. A first program sums to :
main: li t0, 100 # n
li a0, 0 # sum = 0
li t1, 1 # k = 1
loop: add a0, a0, t1 # sum = sum + k
addi t1, t1, 1 # k = k + 1
bge t0, t1, loop # while n >= k
li a7, 1 # print int: the number in a7, the argument in a0
ecall
li a0, '\n'
li a7, 11 # print char
ecall
li a0, 0 # exit status 0
ret
$ python -m rv run first.S
5050
Definition 10.4 (Assembler directive, label, pseudo-instruction)
An assembly source line holds at most one statement. An assembler directive, a word starting with a dot (.text, .data, .word, .asciz), tells the assembler where to put what follows or which bytes to emit. A label, loop:, names the address of the next statement. A pseudo-instruction (li, la, mv, j, ret, call) is a convenient name that the assembler expands into one or two real instructions.
ecall asks the environment for a service: the number in a7 selects it (1 prints an integer, 11 a character, 93 exits), a0 carries the argument. li loads any 32-bit constant; how is the subject of the encoding section.
10.2 Memory
Definition 10.5 (Load–store architecture, base-plus-offset addressing)
In a load–store architecture only loads and stores access memory; every other instruction works on registers. RISC-V addresses memory by base plus offset: lw t1, 8(t0) loads the word at the address , the offset a 12-bit signed immediate.
Loads come in three sizes: lw a word, lh a half (16 bits) and lb a byte, the last two sign-extended to 32 bits, with lhu and lbu zero-extending; stores are sw, sh, sb. RISC-V is little-endian, and rv requires a word access to be at a multiple of 4 and a half at a multiple of 2.
.data
w: .word 0x12345678
b: .byte 0xff, 0x7f
.text
main: la s0, w
li s1, 0
bytes: add t0, s0, s1
lbu a0, 0(t0) # the bytes of w, from the lowest address up
call print_hex
addi s1, s1, 1
li t1, 4
blt s1, t1, bytes
la s0, b
lb a0, 0(s0) # 0xff read signed: -1
call print_dec
lbu a0, 0(s0) # 0xff read unsigned: 255
call print_dec
lh a0, 0(s0) # the half 0x7fff (bytes ff 7f, little-endian): 32767
call print_dec
$ python -m rv run memory.S
78 56 34 12 -1 255 32767
0xff is or 255.$ python -m rv run misaligned.S
rv: line 7: lw a0, 2(t0): misaligned word load at 0x10000002
[exit status 1]
misaligned.S loads a word at an address .rv program, addresses growing upwards. Every address outside the shaded regions faults.Arrays and strings are walked with a pointer that a loop advances by the element size; a structure is a base address and fixed offsets, padding included.
main: la t0, pages # p = &pages[0]
la t1, n
lw t1, 0(t1) # n
slli t1, t1, 2
add t1, t0, t1 # end = p + 4n: one past the last element
li a0, 0
loop: bgeu t0, t1, done # while p < end (addresses compare unsigned)
lw t2, 0(t0)
add a0, a0, t2
addi t0, t0, 4 # p++ moves 4 bytes
j loop
done: li a7, 1
ecall
li a0, 0
ret
$ python -m rv run array_sum.S
1279
A C string has no length stored anywhere: the code walks bytes until it meets the NUL, and the length is the difference of two pointers.
main: la t0, s
mv t1, t0 # start
next: lbu t2, 0(t0)
beqz t2, end # the NUL byte ends the string
addi t0, t0, 1
j next
end: sub a0, t0, t1 # length = end - start
li a7, 1
ecall
li a0, 0
ret
strlen: one byte per turn, lbu because a byte above 127 is not negative text code/bachelor-2/10-assembly-and-calling-convention/listings/strlen.S$ python -m rv run strlen.S
11
# struct_access.S: struct book { int pages; short year; char shelf; }, 8 bytes; three of them.
# The total of the pages of the books on shelf 'B'.
.data
books: .word 65 # books[0].pages offset 0
.half 2002 # .year offset 4
.byte 'B', 0 # .shelf offset 6, then one byte of padding
.word 133
.half 1996
.byte 'A', 0
.word 412
.half 2011
.byte 'B', 0
.text
main: la t0, books
li t1, 3 # count
li t3, 'B'
li a0, 0
loop: lbu t2, 6(t0) # books[i].shelf: base + 6
bne t2, t3, skip
lw t2, 0(t0) # books[i].pages: base + 0
add a0, a0, t2
skip: addi t0, t0, 8 # the next book: 8 bytes further
addi t1, t1, -1
bnez t1, loop
$ python -m rv run struct_access.S
477
10.3 Control flow
There are no structured statements in assembly: only conditional branches (beq, bne, blt, bge, and bltu, bgeu for unsigned comparisons), which jump to a label if their two registers compare as asked, and unconditional jumps, jal and jalr. Compiling a statement is a method.
Method 10.6 (Compiling an if)
For if (c) A else B: evaluate the operands of c; branch on the opposite condition to a label else; write A, then j end; write else: and B; write end:. Without an else, the branch goes directly to end.
Method 10.7 (Compiling a loop)
For while (c) B: write a label test:, branch on the opposite of c to out, write B, j test, and out:. When the body is known to run at least once (do B while (c)), put the test at the bottom: loop:, B, branch on c to loop, one branch per turn instead of two. A for loop is its initialisation followed by a while.
main: li a0, -42 # x
bgez a0, pos # the condition reversed: skip the then-part when x >= 0
neg a0, a0 # x = -x
pos: li a7, 1
ecall # prints 42
li a0, ' '
li a7, 11
ecall
li t0, 27 # n
li a0, 0 # steps
li t2, 1
test: beq t0, t2, out # while (n != 1): the test at the top
andi t1, t0, 1
bnez t1, odd
srli t0, t0, 1 # n / 2
j step
odd: slli t1, t0, 1
add t0, t0, t1 # 3n
addi t0, t0, 1 # 3n + 1
step: addi a0, a0, 1
j test
out: li a7, 1
ecall # prints 111
li a0, 0
ret
$ python -m rv run if_while.S
42 111
while loop of Listing 10.7: each box is a straight run of instructions entered only at its top, each arrow a branch or a fall-through.A switch on a dense range of values compiles to a table of addresses.
Definition 10.8 (Jump table)
A jump table is an array of code addresses, one per case value; a switch on checks that is in range, loads the entry at index , and jumps to it with jr: one indirect jump, whatever the number of cases.
# switch (kind) { case 0: 10; case 1: 50; case 2: 5; case 3: 20; default: 0 }
.data
kinds: .word 1, 0, 3, 7, 2
table: .word book, film, magazine, map # the addresses of the four cases
.text
main: la s0, kinds
li s1, 5
next: lw t0, 0(s0)
li t1, 4
bgeu t0, t1, other # bounds check: kind < 4, unsigned (a negative kind is huge)
la t1, table
slli t0, t0, 2
add t1, t1, t0
lw t1, 0(t1) # the address of the case
jr t1 # one indirect jump, whatever the number of cases
book: li a0, 10
j done
film: li a0, 50
j done
magazine:
li a0, 5
j done
map: li a0, 20
j done
other: li a0, 0
done: li a7, 1
ecall
li a0, ' '
li a7, 11
ecall
addi s0, s0, 4
addi s1, s1, -1
bnez s1, next
li a0, 0
li a7, 93
ecall
$ python -m rv run switch_table.S
50 10 20 0 5
10.4 Encoding
Definition 10.9 (Instruction format, opcode)
Every RV32I instruction is one 32-bit word. Its opcode, the low 7 bits, with the fields funct3 and funct7, selects the operation. An instruction format is the layout of the other fields; RV32I has six, named by letter.
The assembler’s listing shows each word next to its source. Here li at work:
$ python -m rv asm constants.S
00010000 7ff00293 addi t0, zero, 2047 main: li t0, 2047
00010004 80000313 addi t1, zero, -2048 li t1, -2048
00010008 000013b7 lui t2, 0x1 li t2, 2048
0001000c 80038393 addi t2, t2, -2048
00010010 12345e37 lui t3, 0x12345 li t3, 0x12345678
00010014 678e0e13 addi t3, t3, 1656
00010018 12346eb7 lui t4, 0x12346 li t4, 0x12345fff
0001001c fffe8e93 addi t4, t4, -1
00010020 7fffff37 lui t5, 0x7ffff li t5, 0x7ffff000
00010024 fff00f93 addi t6, zero, -1 li t6, -1
00010028 00008067 jalr zero, 0(ra) ret
constants.S assembled: address, word, disassembly, source.Proposition 10.10 (Building a 32-bit constant)
Let be a 32-bit word. Let and let be the low 12 bits of read as a signed number, in . Then lui rd, hi followed by addi rd, rd, lo leaves in rd (modulo ).
Proof. lui places in rd; addi adds , sign-extended. Write with . If , then with , so ; bit 11 of is 0, so , and . If , then , so ; bit 11 is 1, so , negative, and . All sums are taken modulo , which lui and addi also do. ∎
The term is the rounding: when the low part will be read as negative, the high part must be one larger. 0x12345fff becomes lui 0x12346 and addi -1 in Output 10.10. The scattered B and J immediates also fix how far control can go.
Proposition 10.11 (Reach of branches and jumps)
A conditional branch reaches the addresses to , and jal the addresses to : about KiB and MiB.
Proof. A B immediate has 12 stored bits, bits 12 to 1 of an even offset, whose bit 0 is 0: a 13-bit two’s-complement number, from to . A J immediate stores bits 20 to 1: a 21-bit even number, from to . The target is plus the offset. ∎
Decoding reverses the process: read the opcode, pick the format, extract the fields. rv dis does it for a file of words, as a debugger does for a memory dump:
$ python -m rv dis words.hex
00010000 00a50533 add a0, a0, a0
00010004 fec42783 lw a5, -20(s0)
00010008 00f71463 bne a4, a5, 0x00010010
0001000c 008000ef jal ra, 0x00010014
00010010 4015d593 srai a1, a1, 1
words.hex, disassembled.10.5 The calling convention
A function compiled today must be callable from code compiled years ago, by another compiler. They agree on a contract.
Definition 10.12 (Calling convention, argument register, return-value register)
A calling convention fixes how functions pass arguments and results, which registers a call may change, and how the stack is used. In RISC-V the integer arguments go in the argument registers a0 to a7, in order (more on the stack), and the result comes back in the return-value registers a0 and a1. jal ra, f (call f) jumps and leaves the return address in ra; jalr zero, 0(ra) (ret) goes back.
Definition 10.13 (Caller-saved register, callee-saved register)
A caller-saved register (t0–t6, a0–a7, ra) may be changed by any call: a caller that needs its value after the call must save it first. A callee-saved register (s0–s11, sp) must have the same value after the call as before: a function that uses one saves it on entry and restores it before returning.
Definition 10.14 (Leaf function, prologue, epilogue)
A leaf function calls no other function. A non-leaf function, or one that uses callee-saved registers, opens with a prologue, which allocates its stack frame and saves ra and the callee-saved registers it will use, and ends with an epilogue, which restores them, frees the frame and returns.
Method 10.15 (Writing a prologue and an epilogue)
- List what must survive a call:
raif the function calls; each value used after a call, to be kept in ansregister. - Frame size: 4 bytes per saved register plus locals, rounded up to a multiple of 16 (the stack pointer stays 16-byte aligned at every call).
- Prologue:
addi sp, sp, -size;sw ra, size-4(sp);sw s0, size-8(sp), and so on. - Epilogue, in reverse: the loads, then
addi sp, sp, size, thenret. Every path out of the function goes through it.
fact: addi sp, sp, -16 # prologue: a 16-byte frame
sw ra, 12(sp) # save the return address (fact calls fact)
sw s0, 8(sp) # save s0, callee-saved, before using it
mv s0, a0 # keep n across the call
bnez a0, rec
li a0, 1 # fact(0) = 1
j epi
rec: addi a0, a0, -1
call fact # a0 = fact(n - 1)
mul a0, s0, a0 # n * fact(n - 1)
epi: lw s0, 8(sp) # epilogue: restore, pop, return
lw ra, 12(sp)
addi sp, sp, 16
ret
$ python -m rv run factorial.S --trace
step pc word instruction effect
3 00010008 00300513 addi a0, zero, 3 a0 = 3
4 0001000c 01c000ef jal ra, fact ra = 0x00010010, -> 00010028
5 00010028 ff010113 addi sp, sp, -16 sp = 0x7fffffd0
6 0001002c 00112623 sw ra, 12(sp) mem[0x7fffffdc] = 0x00010010 (word)
7 00010030 00812423 sw s0, 8(sp) mem[0x7fffffd8] = 0 (word)
8 00010034 00050413 addi s0, a0, 0 s0 = 3
9 00010038 00051663 bne a0, zero, rec taken -> 00010044
10 00010044 fff50513 addi a0, a0, -1 a0 = 2
11 00010048 fe1ff0ef jal ra, fact ra = 0x0001004c, -> 00010028
24 00010044 fff50513 addi a0, a0, -1 a0 = 0
25 00010048 fe1ff0ef jal ra, fact ra = 0x0001004c, -> 00010028
26 00010028 ff010113 addi sp, sp, -16 sp = 0x7fffffa0
27 0001002c 00112623 sw ra, 12(sp) mem[0x7fffffac] = 0x0001004c (word)
28 00010030 00812423 sw s0, 8(sp) mem[0x7fffffa8] = 1 (word)
31 0001003c 00100513 addi a0, zero, 1 a0 = 1
32 00010040 0100006f jal zero, epi -> 00010050
33 00010050 00812403 lw s0, 8(sp) s0 = 1 <- mem[0x7fffffa8] (word)
34 00010054 00c12083 lw ra, 12(sp) ra = 0x0001004c <- mem[0x7fffffac] (word)
35 00010058 01010113 addi sp, sp, 16 sp = 0x7fffffb0
36 0001005c 00008067 jalr zero, 0(ra) -> 0001004c
37 0001004c 02a40533 mul a0, s0, a0 a0 = 1
fact(3): the first call, the deepest one, and the first return. Some lines are left out.fact(0) has saved its registers (step 28), drawn from the trace: five 16-byte frames, each with the saved ra at offset 12 and the saved s0 at offset 8 (the other 8 bytes unused). Each fact(n) saved its caller’s n, which it restores on the way back.The convention is a promise each function makes to its callers; breaking it breaks code far away. Here a helper uses s0 without saving it:
main: addi sp, sp, -16
sw ra, 12(sp)
la s1, days
li s0, 0 # total, in a callee-saved register: should survive calls
li s2, 3
loop: lw a0, 0(s1)
call fine
add s0, s0, a0
addi s1, s1, 4
addi s2, s2, -1
bnez s2, loop
mv a0, s0
li a7, 1
ecall # expected: 90 + 0 + 40 = 130
lw ra, 12(sp)
addi sp, sp, 16
li a0, 0
ret
fine: li s0, 21 # BUG: s0 is callee-saved, and fine() does not save it
sub a0, a0, s0 # days late
bgtz a0, late
li a0, 0
ret
late: li t0, 10
mul a0, a0, t0 # 10 cents a day
ret
s0 code/bachelor-2/10-assembly-and-calling-convention/listings/clobber_bug.S$ python -m rv run clobber_bug.S
61
fine sets s0 to 21 at each call, so the caller’s running total restarts from 21: , then . Nothing in either function alone is wrong for its own purpose; the bug is the broken contract, which is why it is so hard to find in a large program. fine should use t0, which it may change freely.
This main, like the short ones before it, uses s0, s1 and s2 without saving them, which the convention forbids to a callee. Here it is harmless only because rv starts main with ra at its exit address: nothing runs after main returns, so nothing needs those registers kept. A main called by real start-up code is a callee like any other and must save the s registers it uses, as count.S does in the problem.
10.6 Reading a compiler’s output
A compiler does the same work. gcc -O1 -S writes the assembly of a C file for the machine at hand, here x86-64, an older and larger ISA with 16 registers, two-operand instructions, and memory operands inside arithmetic.
sum:
endbr64
testl %esi, %esi
jle .L4
movq %rdi, %rax
leal -1(%rsi), %edx
leaq 4(%rdi,%rdx,4), %rcx
movl $0, %edx
.L3:
addl (%rax), %edx
addq $4, %rax
cmpq %rcx, %rax
jne .L3
.L1:
movl %edx, %eax
ret
.L4:
movl $0, %edx
jmp .L1
sum(a, n) compiled by gcc for x86-64, directives removed (compiled.sh). Some lines are left out.The ideas are the same. The x86-64 convention passes the first integer arguments in rdi, rsi, rdx, rcx, r8, r9 and returns in rax (eax is its low half): here a in rdi, n in esi. The loop is a pointer walk like Listing 10.4, with the end pointer computed once (leaq) and the test at the bottom; the case is handled by a branch around the loop. The first instruction, endbr64, only marks a legal target for indirect jumps, a protection of recent x86-64 processors. And the switch of five cases became a jump table:
fine_per_day:
endbr64
cmpl $4, %edi
ja .L7
movl %edi, %edi
leaq .L9(%rip), %rdx
movslq (%rdx,%rdi,4), %rax
addq %rdx, %rax
notrack jmp *%rax
.L9:
.long .L14-.L9
.long .L12-.L9
.long .L11-.L9
.long .L10-.L9
.long .L8-.L9
fine_per_day: one unsigned comparison (ja), then an indirect jump through .L9. Some lines are left out.In practice — Reading assembly
Read compiler output to check what the optimiser did, not to write it: compile with -O1 or -O2 and -S, or use objdump -d on an object file. Find the arguments in their registers first, then the loop (a backward branch), then the stores. When a program fails under a debugger, the disassembly and the registers are the ground truth; the convention tells you which values the caller can still trust.
10.7 Exercises
Exercise 10.1 ★
Predict, in decimal, the values of a1 to a5 after these instructions, then check with the register dump in the solution.
main: li a0, -5
srai a1, a0, 1
srli a2, a0, 28
slti a3, a0, 0
sltiu a4, a0, 0
xori a5, a0, -1
li a0, 0
ret
xori code/bachelor-2/10-assembly-and-calling-convention/listings/exo_regs.SSolution
Solution of Exercise 10.1.
--- registers (pc = 0xffff0000) ---
zero 0 ra 0xffff0000 sp 0x7ffffff0 gp 0
tp 0 t0 0 t1 0 t2 0
s0 0 s1 0 a0 0 a1 -3
is 0xfffffffb. srai by 1 copies the sign bit in: (it rounds down, unlike C’s division, which gives ). srli by 28 brings in zeros and keeps the top four bits, 0xf . slti compares signed: , so 1. sltiu compares unsigned, and no number is below 0: 0. xori with flips every bit: . a0 is 0 because the program sets it before returning.
Exercise 10.2 ★
This program prints 1. Explain why with Method 10.7, and fix the branch.
main: li t0, 10 # n
li t1, 1 # k
li a0, 0
loop: add a0, a0, t1
addi t1, t1, 1
bge t1, t0, loop # "while k <= n"?
li a7, 1
ecall
li a0, 0
ret
Solution
Solution of Exercise 10.2.
$ python -m rv run exo_bge.S
1
bge t1, t0, loop branches back while , the opposite of the intended test. After the first turn , the branch falls through, and the sum is 1. With the test at the bottom (Method 10.7), the branch must go back while the loop’s condition holds, that is bge t0, t1, loop (“”), as in Listing 10.2. It then prints 55.
Exercise 10.3 ★
Write max(a0 = address, a1 = n), a leaf that returns the largest of signed words, and test it on the temperatures . Which branch would be wrong for unsigned words?
Solution
Solution of Exercise 10.3.
max: lw t0, 0(a0) # best = a[0]
slli a1, a1, 2
add a1, a0, a1 # end
next: addi a0, a0, 4
bgeu a0, a1, done
lw t1, 0(a0)
bge t0, t1, next # signed comparison: keep best if best >= a[i]
mv t0, t1
j next
done: mv a0, t0
ret
.data
temps: .word -12, 4, -3, 19, 7, -40
The function keeps the best value in t0 and walks a pointer to the end; it prints 19. The branch bge t0, t1, next compares signed words: on unsigned words it must be bgeu, or a value above would be read as negative and lose to every small one. The pointer comparison bgeu is unsigned in both cases, as addresses are.
Exercise 10.4 ★
Encode by hand, in hexadecimal, using the formats of this chapter: addi a0, a0, -1; sw ra, 12(sp); and beq a0, zero, main placed 8 bytes after main. (a0 is x10, ra x1, sp x2; the opcodes are 0010011, 0100011 and 1100011; funct3 is 0, 2 and 0.)
Solution
Solution of Exercise 10.4.
00010000 fff50513 addi a0, a0, -1 main: addi a0, a0, -1
I imm=111111111111 rs1=01010 f3=000 rd=01010 op=0010011
00010004 00112623 sw ra, 12(sp) sw ra, 12(sp)
S imm[11:5]=0000000 rs2=00001 rs1=00010 f3=010 imm[4:0]=01100 op=0100011
00010008 fe050ce3 beq a0, zero, main beq a0, zero, main
addi a0, a0, -1 is I-type: imm is twelve 1s; rs1 , funct3 000, rd , opcode 0010011. The bits 1111 1111 1111 0101 0000 0101 0001 0011 are 0xfff50513. sw ra, 12(sp) is S-type: , so imm[11:5] and imm[4:0] ; rs2 , rs1 , funct3 010: 0x00112623. The branch is at main , so its offset is , in 13 bits 1 1111 1111 1000: bit 12 is 1, bits 10–5 are 111111, bits 4–1 are 1100, bit 11 is 1. The B fields are then and , with rs2 , rs1 : 0xfe050ce3.
Exercise 10.5 ★★
Decode by hand the five words 00b50633, 00452283, fe0518e3, 00c000ef and 0005a503, as if they started at address 0x00010000. For the branch and the jump, give the target.
Solution
Solution of Exercise 10.5.
$ python -m rv dis exo_words.hex
00010000 00b50633 add a2, a0, a1
00010004 00452283 lw t0, 4(a0)
00010008 fe0518e3 bne a0, zero, 0x0000fff8
0001000c 00c000ef jal ra, 0x00010018
00010010 0005a503 lw a0, 0(a1)
00b50633: opcode 0110011 (R), rd 12, funct3 0, rs1 10, rs2 11, funct7 0: add a2, a0, a1. 00452283: opcode 0000011, a load; funct3 010 is lw; rd 5, rs1 10, imm 4: lw t0, 4(a0). fe0518e3: opcode 1100011, funct3 001, bne, rs1 10, rs2 0; the B immediate reassembles to , so the target is . 00c000ef: opcode 1101111, jal, rd 1; the J immediate is 12, target 0x00010018. 0005a503: lw a0, 0(a1). The branch target lies below the text, which shows that these five words are a fragment of a larger program.
Exercise 10.6 ★★
This program never ends; rv stops it at the step limit. Explain, following ra, where each ret goes, and fix double_plus_two.
main: addi sp, sp, -16
sw ra, 12(sp)
li a0, 20
call double_plus_two
li a7, 1
ecall
lw ra, 12(sp)
addi sp, sp, 16
li a0, 0
ret
double_plus_two: # returns 2x + 2
add a0, a0, a0
call inc
call inc
ret
inc: addi a0, a0, 1
ret
rv: line 17: ret: stopped after 200 steps, the step limit (raise it with --steps N)
Solution
Solution of Exercise 10.6.
The first call inc sets ra to the address of the second call, which overwrites main’s return address for good; the second call inc sets ra to the address of the ret that follows it. inc returns there, and that ret jumps to ra, that is to itself, for ever: line 17 is where rv stops. A function that calls must save ra (Method 10.15):
double_plus_two: # returns 2x + 2
addi sp, sp, -16
sw ra, 12(sp) # it calls: save its return address
add a0, a0, a0
call inc
call inc
lw ra, 12(sp)
addi sp, sp, 16
ret
inc: addi a0, a0, 1
ret
ra code/bachelor-2/10-assembly-and-calling-convention/exercises/exo_ra_fixed.SIt then prints 42.
Exercise 10.7 ★★
Write strcmp(a0, a1) under the convention: negative, zero or positive as the first string is smaller, equal or larger, comparing bytes as unsigned. Test it on Mill Lane against Mill Row, a string against itself, and Mill against Mill Lane.
Solution
Solution of Exercise 10.7.
strcmp: lbu t0, 0(a0)
lbu t1, 0(a1)
bne t0, t1, diff
beqz t0, diff # both ended: equal (t0 - t1 = 0)
addi a0, a0, 1
addi a1, a1, 1
j strcmp
diff: sub a0, t0, t1
ret
strcmp, a leaf code/bachelor-2/10-assembly-and-calling-convention/exercises/strcmp.SThe loop stops at the first difference, or at the end of both strings together; the result is the difference of the two bytes read with lbu, so a byte above 127 counts as large, as C requires. The program prints -1 0 -1: L comes before R, and Mill is a prefix of Mill Lane, whose space is compared with the NUL that ends Mill. Being a leaf using only t and a registers, it needs no frame.
Exercise 10.8 ★★
(a) Show that the pair of Proposition 10.10 is the only one with and . (b) For which constants does li need only one instruction, addi or lui? (c) Compute for 0x7ffff800 and check, modulo , that the pair still works.
Solution
Solution of Exercise 10.8.
(a) Suppose . Modulo , ; both lie in an interval of 4096 consecutive integers, so . Then , so , and both are in : they are equal. (b) One addi from zero when , read signed, is in (); one lui when the low 12 bits of are zero (), as 0x7ffff000 in Output 10.10. (c) : the low part is 0x800, so and . lui gives 0x80000000, which is negative when read signed, and adding gives 0x7ffff800: the wrap-around of the 32-bit sum is exactly what makes it right.
Exercise 10.9 ★★
Compile by hand int fine(const struct loan *l), where struct loan { int days; short rate; char lost; }, which returns 2000 if lost, else when positive, else 0. Give the offsets and the size of the structure first.
Solution
Solution of Exercise 10.9.
int needs alignment 4 and short 2: days at offset 0, rate at 4, lost at 6; the size is rounded up to a multiple of 4, so 8, with one byte of padding.
fine: lbu t0, 6(a0) # l->lost
bnez t0, lost
lw t1, 0(a0) # l->days
addi t1, t1, -21
blez t1, none
lh t2, 4(a0) # l->rate, a signed short
mul a0, t1, t2
ret
lost: li a0, 2000
ret
none: li a0, 0
ret
fine, a leaf code/bachelor-2/10-assembly-and-calling-convention/exercises/loan_fine.Slbu reads the char, lh the signed short; blez is the reversed test of d > 0. On the three loans (30 days at 10, 12 days at 10, lost) it prints 90, 0 and 2000.
Exercise 10.10 ★★★
Write a recursive binary search find(a0 = array, a1 = lo, a2 = hi, a3 = key) that returns the index of key in the sorted range a[lo..hi), or , under the convention, and test it on the seven sorted page counts for keys present, absent, smaller than all and larger than all. Which registers must it save, and why are its recursive calls tail calls in disguise?
Solution
Solution of Exercise 10.10.
find: blt a1, a2, split
li a0, -1 # empty range
ret
split: addi sp, sp, -16
sw ra, 12(sp)
add t0, a1, a2
srai t0, t0, 1 # mid = (lo + hi) / 2, no overflow for these sizes
slli t1, t0, 2
add t1, a0, t1
lw t1, 0(t1) # a[mid]
beq t1, a3, found
blt a3, t1, left
addi a1, t0, 1 # search a[mid+1..hi)
call find
j out
left: mv a2, t0 # search a[lo..mid)
call find
j out
found: mv a0, t0
out: lw ra, 12(sp)
addi sp, sp, 16
ret
Only ra needs saving: no value is used after a recursive call, whose result is returned as it is. The test finds every key at its index and returns for 100, 1 and 999. That is also why the calls are tail calls in disguise: after call find the function only restores ra and returns, so it could instead free its frame and jump to find with j, leaving the original ra in place; the search then runs in a single frame, like a loop. The empty case returns before allocating a frame at all.
Exercise 10.11 ★★★
A naive recursive fib(n) saves ra, s0 and s1 in a 16-byte frame, and returns at once, with no frame, for . (a) Prove that it makes calls, where is the Fibonacci sequence. (b) What is the deepest stack, in frames and in bytes? (c) The test of the solution counts the jal and jalr executed: what number should it expect?
Solution
Solution of Exercise 10.11.
(a) and for . Let : then with , so by induction (as ), and . (b) The deepest chain is fib(n), fib(n-1), …, fib(1); the last one allocates no frame, so for there are frames of 16 bytes, bytes, below main’s own 16. The stack grows linearly although the number of calls grows exponentially. (c) Each call is one jal and one ret (a jalr); main adds its own ret. The test expects jumps, 355 for .
fib: li t0, 2
blt a0, t0, base # fib(0) = 0, fib(1) = 1
addi sp, sp, -16
sw ra, 12(sp)
sw s0, 8(sp)
sw s1, 4(sp)
mv s0, a0
addi a0, a0, -1
call fib
mv s1, a0 # fib(n - 1)
addi a0, s0, -2
call fib
add a0, s1, a0
lw s1, 4(sp)
lw s0, 8(sp)
lw ra, 12(sp)
addi sp, sp, 16
base: ret
fib with three saved registers code/bachelor-2/10-assembly-and-calling-convention/exercises/fib.SExercise 10.12 ★★★
Compile with a jump table switch (shelf) { case 3: 'A'; case 4: case 5: 'B'; case 7: 'D'; default: '?' }. Use one unsigned comparison for the bounds check, and explain why it also rejects values below 3 and negative ones.
Solution
Solution of Exercise 10.12.
loop: lw t0, 0(s0)
addi t0, t0, -3 # case 3 becomes index 0
li t1, 5
bgeu t0, t1, other # one unsigned test: below 3 wraps to a huge number
la t1, table
slli t0, t0, 2
add t1, t1, t0
lw t1, 0(t1)
jr t1
ca: li a0, 'A'
j print
cb: li a0, 'B'
j print
cd: li a0, 'D'
j print
other: li a0, '?'
print: li a7, 11
ecall
addi s0, s0, 4
addi s1, s1, -1
bnez s1, loop
li a0, 0
li a7, 93
ecall
.data
table: .word ca, cb, cb, other, cd # case 6 is a gap: it goes to default
shelves: .word 3, 4, 5, 6, 7, 2, 8
Subtracting 3 maps the cases 3 to 7 to the indices 0 to 4; the gap 6 gets an entry pointing to the default. A value , negative ones included, gives , whose bit pattern read unsigned is at least , so the single test bgeu t0, t1, other rejects it together with every . On the shelves 3, 4, 5, 6, 7, 2, 8 the program prints ABB?D??.
10.8 Problem: Hand-compiling the library’s check digit
Problem 10.1
Weekend problem — Hand-compiling the library’s check digit
The library’s book codes end with a check digit computed from the other digits, so that a mistyped digit is caught at the desk. This problem compiles the function by hand, calls a helper under the convention, and proves exactly how many instructions it executes.
Part I — The C function.
unsigned weigh(unsigned digit, unsigned i)
{
return digit * (i % 2 == 0 ? 3 : 1); /* weight 3 at even positions from the right */
}
unsigned check_digit(unsigned code)
{
unsigned sum = 0, i = 0;
do { /* a code has at least one digit */
sum += weigh(code % 10, i);
code /= 10;
i++;
} while (code != 0);
return (10 - sum % 10) % 10;
}
- Compute by hand the check digit of 4006, and compare with the output in the solution.
- Why a
do–whilerather than awhile? What wouldcheck_digit(0)return? - Show that changing one digit of a code always changes the check digit. (Consider the weights 1 and 3 modulo 10.)
- Swapping two adjacent digits and changes the weighted sum by . When is the swap not caught?
- Which values live across the call to
weigh? Which may be lost? - How large a code fits in a 32-bit unsigned word, in digits?
Part II — Compiled by hand.
main: addi sp, sp, -16
sw ra, 12(sp)
sw s0, 8(sp)
sw s1, 4(sp)
sw s2, 0(sp)
li a7, 5
ecall # a0 = the code
mv s0, a0 # the digits still to read
li s1, 0 # i
li s2, 0 # the weighted sum
digit: li t0, 10
remu a0, s0, t0 # the last digit
divu s0, s0, t0 # drop it
mv a1, s1
call weigh # a0 = weight(i) * digit
add s2, s2, a0
addi s1, s1, 1
bnez s0, digit # a code has at least one digit: the test at the bottom
- Which registers hold
code,iandsum, and whysregisters? - The frame is 16 bytes for four saved registers. Write the epilogue, and check it against
count.S. - Which instructions compute
codemodulo 10 andcode / 10? Why the unsigned forms? - Where is the loop’s test, and which method of this chapter was applied?
- Rewrite the loop to keep
sumina2instead ofs2. What breaks? - The final expression uses
remutwice. Could the first be avoided?
Part III — A helper under the convention.
weigh: # a leaf: a0 = digit, a1 = position -> weighted digit
andi t0, a1, 1 # 0 at even positions, 1 at odd ones
slli t0, t0, 1 # 0 or 2
li t1, 3
sub t1, t1, t0 # weight 3 or 1, without a branch
mul a0, a0, t1
ret
weigh, a leaf code/bachelor-2/10-assembly-and-calling-convention/listings/count.S- Why does
weighneed no prologue at all? weighcomputes the weight without a branch. Prove that3 - 2 * (i & 1)is 3 for even and 1 for odd .weighchangest0andt1. Is that allowed? Which caller would it break, and how is that caller’s bug avoided?- Inline
weighinto the loop. How many instructions per digit are saved? - A real assembler emits
callas two instructions,auipcandjalr, for a target that may be far. How would that change the count? - The chapter’s test also runs the codes 12, 123456789 and 100000000. Predict their instruction counts.
Part IV — Every instruction counted.
$ for c in 7 4006 978030640; do echo $c | python -m rv run count.S --stats | sed -n 2,4p; done
9
--- stats ---
instructions 40
8
--- stats ---
instructions 82
1
--- stats ---
instructions 152
rv --stats on codes of 1, 4 and 9 digits.- Count the instructions executed per digit, from
digit:throughbnez, includingweigh. - Count the instructions executed once, before and after the loop.
- Prove that a code of digits executes exactly instructions, and give and .
- Check the formula against the three counts of the output.
- Why does the count depend only on , not on the digits themselves?
- State the result of the problem.
Solution
Solution of Problem 10.1.
$ gcc -std=c17 -O2 -Wall -Wextra -o check_digit check_digit.c -lm && ./check_digit
7 -> 9
4006 -> 8
9780306 -> 5
978030640 -> 1
1. From the right: ; .
2. Every code has at least one digit, so the body runs at least once and the test can sit at the bottom. For check_digit(0) the body runs once on the digit 0: the sum is 0 and the result , the same value a while would give, but the do form counts 0 as the one-digit code it is.
3. Changing the digit at weight into changes the sum by , with . For that is not a multiple of 10; for , since 3 and 10 are coprime, would force . So the sum changes modulo 10, and is a bijection on the residues: the check digit changes.
4. and at adjacent positions have the weights 3 and 1 in some order: the sum changes by . That is a multiple of 10 exactly when is a multiple of 5: swapping two digits that differ by 5, such as 2 and 7, is not caught.
5. code, i and sum are used after the call. The digit and the position are consumed by the call, and the constant 10 can be loaded again.
6. has ten digits: every code of nine digits fits, and ten-digit codes only up to that value.
7. s0 holds code, s1 holds i, s2 holds sum. They are callee-saved, so weigh, or any function the loop calls later, must leave them intact; in t or a registers the loop would have to save them around each call.
8. The epilogue undoes the prologue in reverse: lw s2, 0(sp), lw s1, 4(sp), lw s0, 8(sp), lw ra, 12(sp), addi sp, sp, 16, then ret, as in lines 32 to 38 of count.S, where li a0, 0 sets the exit status just before the ret. Four words fill the 16 bytes exactly.
9. remu a0, s0, t0 and divu s0, s0, t0. The C variable is unsigned: a code above read signed would be negative, and rem and div would give negative digits.
10. bnez s0, digit at the bottom of the loop: the do–while form of Method 10.7, one branch per digit.
11. a2 is caller-saved: weigh may change it. The present weigh happens not to touch it, so the program would still print the right digits, but only by accident: the next version of weigh, or a compiler that inlines something into it, may use a2 and the total is lost, the bug of Listing 10.10 with the roles reversed.
12. The first remu computes , which the formula needs; avoiding it would mean keeping the sum reduced modulo 10 in the loop, one remu per digit instead of one in all. The second can be replaced by a comparison: is between 1 and 10, and only 10 must become 0.
13. It calls nothing, so ra stays intact, and it uses only t0, t1, a0 and a1, which are caller-saved: nothing to save, no frame.
14. is the last bit of : 0 for even , giving , and 1 for odd , giving .
15. Yes: t0 and t1 are caller-saved. The loop itself uses t0 for the constant 10 before the call, and would be broken if it relied on it afterwards; it reloads 10 into t0 after the loop instead (line 23), as the convention requires of a caller.
16. The mv a1, s1, the call and the ret disappear (andi reads s1 directly): 3 instructions per digit, 11 instead of 14.
17. One more instruction per call, so one more per digit: .
18. From question 21: for 12, and for the two nine-digit codes; the test checks them, and their check digits 3, 5 and 7, against a Python reference.
19. In main, li, remu, divu, mv and jal (5); in weigh, six including ret; back in the loop, add, addi and bnez (3): 14 per digit.
20. Before the loop: five for the prologue, then li, ecall, mv and two li: 10. After it: li, remu, sub, remu, the printing of the digit and of the newline (five), then the four loads, addi, li and ret (seven): 16. In all 26.
21. The code outside the loop is straight-line, and so is the body, weigh included: the only branch is bnez. For an -digit code, (or , ), and after turns s0 holds , which is nonzero for and zero for : the loop runs exactly times. The count is : , .
22. , and , the three counts printed; the test adds the seven-digit code 9780306, .
23. No branch depends on a digit’s value: the weight is computed without a branch (question 14), and divu and remu count as one instruction each whatever their operands. Only the number of turns varies.
24. The check digit of an -digit code, hand-compiled under the calling convention with a helper call per digit, executes exactly instructions: with and , proved from the code and counted by rv on every tested code.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Assembler directive, label, pseudo-instruction
- Caller-saved register, callee-saved register
- Calling convention, argument register, return-value register
- General-purpose register, register file
- Immediate
- Instruction format, opcode
- Instruction set architecture
- Jump table
- Leaf function, prologue, epilogue
- Load–store architecture, base-plus-offset addressing