কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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
Listing 10.1. 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
Output 10.1. Shift, add, load, add: the address of 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: −2048-2048 to 20472047.

registerABI namerolepreserved across calls
x0zeroalways 0—
x1rareturn addressno
x2spstack pointeryes
x3, x4gp, tpglobal and thread pointersnot allocated
x5–x7, x28–x31t0–t6temporariesno (caller-saved)
x8, x9, x18–x27s0–s11saved registersyes (callee-saved)
x10–x17a0–a7arguments; a0, a1 resultsno (caller-saved)
The register file under its ABI names, the names programs use. The last column is the calling convention of Section 10.5.

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 11 to 100100:

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
Listing 10.2. The sum of the first hundred integers code/bachelor-2/10-assembly-and-calling-convention/listings/first.S
$ python -m rv run first.S
5050
Output 10.2. 100⋅101/2100 \cdot 101 / 2.

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 t0+8\texttt{t0} + 8, 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
Listing 10.3. Bytes of a word, signed and unsigned code/bachelor-2/10-assembly-and-calling-convention/listings/memory.S
$ python -m rv run memory.S
78 56 34 12 -1 255 32767 
Output 10.3. The lowest byte comes first; the same byte 0xff is −1-1 or 255.
$ python -m rv run misaligned.S
rv: line 7: lw a0, 2(t0): misaligned word load at 0x10000002
[exit status 1]
Output 10.4. misaligned.S loads a word at an address ≡2(mod4)\equiv 2 \pmod 4.
The memory of an rv program, addresses growing upwards. Every address outside the shaded regions faults.
The memory of an 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
Listing 10.4. A pointer walk: the loop ends when the pointer reaches the end code/bachelor-2/10-assembly-and-calling-convention/listings/array_sum.S
$ python -m rv run array_sum.S
1279
Output 10.5. The sum of the six page counts.

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
Listing 10.5. 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
Output 10.6. The length of the street name.
# 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
Listing 10.6. Fields at offsets 0, 4 and 6 of an 8-byte struct code/bachelor-2/10-assembly-and-calling-convention/listings/struct_access.S
$ python -m rv run struct_access.S
477
Output 10.7. The pages of the two books on shelf B, 65+41265 + 412.

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
Listing 10.7. An absolute value, and the 3n+13n + 1 walk from 27 code/bachelor-2/10-assembly-and-calling-convention/listings/if_while.S
$ python -m rv run if_while.S
42 111
Output 10.8. ∣−42∣|-42|, and the 111 steps of the walk from 27 down to 1.
The control-flow graph of the while loop of : each box is a straight run of instructions entered only at its top, each arrow a branch or a fall-through.
The control-flow graph of the 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 vv checks that vv is in range, loads the entry at index vv, 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
Listing 10.8. A table of four case addresses, the bounds check, the cases and the printing loop code/bachelor-2/10-assembly-and-calling-convention/listings/switch_table.S
$ python -m rv run switch_table.S
50 10 20 0 5 
Output 10.9. The kinds 1, 0, 3, 7 and 2; kind 7 fails the bounds check.

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 six formats, bit 31 on the left. The register fields stay in the same place in every format, so the processor can read the registers before it knows the instruction; the immediates are scattered to make that possible. B and J store an even offset without its bit 0.
The six formats, bit 31 on the left. The register fields stay in the same place in every format, so the processor can read the registers before it knows the instruction; the immediates are scattered to make that possible. B and J store an even offset without its bit 0.

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
Output 10.10. constants.S assembled: address, word, disassembly, source.

Proposition 10.10 (Building a 32-bit constant)

Let cc be a 32-bit word. Let hi=⌊(c+211)/212⌋ mod 220\mathit{hi} = \lfloor (c + 2^{11}) / 2^{12} \rfloor \bmod 2^{20} and let lo\mathit{lo} be the low 12 bits of cc read as a signed number, in [−2048,2047][-2048, 2047]. Then lui rd, hi followed by addi rd, rd, lo leaves cc in rd (modulo 2322^{32}).

Proof. lui places hi⋅212\mathit{hi} \cdot 2^{12} in rd; addi adds lo\mathit{lo}, sign-extended. Write c=212q+rc = 2^{12} q + r with 0≤r<2120 \le r < 2^{12}. If r<211r < 2^{11}, then c+211=212q+(r+211)c + 2^{11} = 2^{12} q + (r + 2^{11}) with r+211<212r + 2^{11} < 2^{12}, so hi=q\mathit{hi} = q; bit 11 of cc is 0, so lo=r\mathit{lo} = r, and 212q+r=c2^{12} q + r = c. If r≥211r \ge 2^{11}, then c+211=212(q+1)+(r−211)c + 2^{11} = 2^{12} (q + 1) + (r - 2^{11}), so hi=q+1\mathit{hi} = q + 1; bit 11 is 1, so lo=r−212\mathit{lo} = r - 2^{12}, negative, and 212(q+1)+r−212=c2^{12}(q + 1) + r - 2^{12} = c. All sums are taken modulo 2322^{32}, which lui and addi also do. ∎

The term 2112^{11} 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 pc−4096\mathit{pc} - 4096 to pc+4094\mathit{pc} + 4094, and jal the addresses pc−220\mathit{pc} - 2^{20} to pc+220−2\mathit{pc} + 2^{20} - 2: about ±4\pm 4 KiB and ±1\pm 1 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 −212-2^{12} to 212−22^{12} - 2. A J immediate stores bits 20 to 1: a 21-bit even number, from −220-2^{20} to 220−22^{20} - 2. The target is pc\mathit{pc} 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
Output 10.11. Five words of 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)

  1. List what must survive a call: ra if the function calls; each value used after a call, to be kept in an s register.
  2. 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).
  3. Prologue: addi sp, sp, -size; sw ra, size-4(sp); sw s0, size-8(sp), and so on.
  4. Epilogue, in reverse: the loads, then addi sp, sp, size, then ret. 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
Listing 10.9. A recursive function under the convention code/bachelor-2/10-assembly-and-calling-convention/listings/factorial.S
$ 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
Output 10.12. The trace of fact(3): the first call, the deepest one, and the first return. Some lines are left out.
The stack when 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 stack when 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
Listing 10.10. A callee that clobbers s0 code/bachelor-2/10-assembly-and-calling-convention/listings/clobber_bug.S
$ python -m rv run clobber_bug.S
61
Output 10.13. 61 instead of 130.

fine sets s0 to 21 at each call, so the caller’s running total restarts from 21: 21+021 + 0, then 21+40=6121 + 40 = 61. 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
Output 10.14. 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 n≤0n \le 0 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
Output 10.15. 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
Listing 10.11. Shifts, comparisons and xori code/bachelor-2/10-assembly-and-calling-convention/listings/exo_regs.S
Solution

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
Output 10.18. The register dump at the end. Some lines are left out.

−5-5 is 0xfffffffb. srai by 1 copies the sign bit in: ⌊−5/2⌋=−3\lfloor -5/2 \rfloor = -3 (it rounds down, unlike C’s division, which gives −2-2). srli by 28 brings in zeros and keeps the top four bits, 0xf =15= 15. slti compares signed: −5<0-5 < 0, so 1. sltiu compares unsigned, and no number is below 0: 0. xori with −1-1 flips every bit: ¬(−5)=4\lnot(-5) = 4. 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
Listing 10.12. A loop that runs once code/bachelor-2/10-assembly-and-calling-convention/listings/exo_bge.S
Solution

Solution of Exercise 10.2.

$ python -m rv run exo_bge.S
1
Output 10.19. The output.

bge t1, t0, loop branches back while k≥nk \ge n, the opposite of the intended test. After the first turn k=2<10k = 2 < 10, 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 k≤nk \le n holds, that is bge t0, t1, loop (“n≥kn \ge k”), 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 n≥1n \ge 1 signed words, and test it on the temperatures −12,4,−3,19,7,−40-12, 4, -3, 19, 7, -40. 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 maximum, a leaf code/bachelor-2/10-assembly-and-calling-convention/exercises/max.S

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 2312^{31} 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
Output 10.20. The check, with the fields. Some lines are left out.

addi a0, a0, -1 is I-type: imm =−1= -1 is twelve 1s; rs1 =10=01010= 10 = 01010, funct3 000, rd =01010= 01010, opcode 0010011. The bits 1111 1111 1111 0101 0000 0101 0001 0011 are 0xfff50513. sw ra, 12(sp) is S-type: 12=0000000 0110012 = 0000000\,01100, so imm[11:5] =0000000= 0000000 and imm[4:0] =01100= 01100; rs2 =1= 1, rs1 =2= 2, funct3 010: 0x00112623. The branch is at main +8+ 8, so its offset is −8-8, 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 11111111111111 and 1100111001, with rs2 =0= 0, rs1 =10= 10: 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)
Output 10.21. The check.

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 −16-16, so the target is 0x00010008−16=0x0000fff8\texttt{0x00010008} - 16 = \texttt{0x0000fff8}. 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
Listing 10.13. A non-leaf function code/bachelor-2/10-assembly-and-calling-convention/listings/exo_ra.S
rv: line 17: ret: stopped after 200 steps, the step limit (raise it with --steps N)
Output 10.16. The step limit. Some lines are left out.
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
The fix: a frame for ra code/bachelor-2/10-assembly-and-calling-convention/exercises/exo_ra_fixed.S

It 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.S

The 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 (hi,lo)(\mathit{hi}, \mathit{lo}) of Proposition 10.10 is the only one with lo∈[−2048,2047]\mathit{lo} \in [-2048, 2047] and hi∈[0,220)\mathit{hi} \in [0, 2^{20}). (b) For which constants does li need only one instruction, addi or lui? (c) Compute hi\mathit{hi} for 0x7ffff800 and check, modulo 2322^{32}, that the pair still works.

Solution

Solution of Exercise 10.8.

(a) Suppose hi⋅212+lo≡hi′⋅212+lo′(mod232)\mathit{hi} \cdot 2^{12} + \mathit{lo} \equiv \mathit{hi}' \cdot 2^{12} + \mathit{lo}' \pmod{2^{32}}. Modulo 2122^{12}, lo≡lo′\mathit{lo} \equiv \mathit{lo}'; both lie in an interval of 4096 consecutive integers, so lo=lo′\mathit{lo} = \mathit{lo}'. Then 212(hi−hi′)≡0(mod232)2^{12}(\mathit{hi} - \mathit{hi}') \equiv 0 \pmod{2^{32}}, so hi≡hi′(mod220)\mathit{hi} \equiv \mathit{hi}' \pmod{2^{20}}, and both are in [0,220)[0, 2^{20}): they are equal. (b) One addi from zero when cc, read signed, is in [−2048,2047][-2048, 2047] (hi=0\mathit{hi} = 0); one lui when the low 12 bits of cc are zero (lo=0\mathit{lo} = 0), as 0x7ffff000 in Output 10.10. (c) c=0x7ffff800c = \texttt{0x7ffff800}: the low part is 0x800, so lo=2048−4096=−2048\mathit{lo} = 2048 - 4096 = -2048 and hi=(c+0x800)/212=0x80000\mathit{hi} = (c + \texttt{0x800}) / 2^{12} = \texttt{0x80000}. lui gives 0x80000000, which is negative when read signed, and adding −2048-2048 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 (days−21)⋅rate(\mathit{days} - 21) \cdot \mathit{rate} 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.S

lbu 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 −1-1, 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
A recursive binary search code/bachelor-2/10-assembly-and-calling-convention/exercises/bsearch.S

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 −1-1 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 n<2n < 2. (a) Prove that it makes C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1 calls, where FF 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) C(0)=C(1)=1C(0) = C(1) = 1 and C(n)=1+C(n−1)+C(n−2)C(n) = 1 + C(n-1) + C(n-2) for n≥2n \ge 2. Let D(n)=C(n)+1D(n) = C(n) + 1: then D(n)=D(n−1)+D(n−2)D(n) = D(n-1) + D(n-2) with D(0)=D(1)=2D(0) = D(1) = 2, so D(n)=2Fn+1D(n) = 2F_{n+1} by induction (as F1=F2=1F_1 = F_2 = 1), and C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1. (b) The deepest chain is fib(n), fib(n-1), …, fib(1); the last one allocates no frame, so for n≥2n \ge 2 there are n−1n - 1 frames of 16 bytes, 16(n−1)16(n-1) 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 2C(n)+1=4Fn+1−12C(n) + 1 = 4F_{n+1} - 1 jumps, 355 for n=10n = 10.

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.S

Exercise 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
The case value shifted to start at 0 code/bachelor-2/10-assembly-and-calling-convention/exercises/switch2.S

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 v<3v < 3, negative ones included, gives v−3<0v - 3 < 0, whose bit pattern read unsigned is at least 2312^{31}, so the single test bgeu t0, t1, other rejects it together with every v>7v > 7. 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;
}
Listing 10.14. The check digit in C code/bachelor-2/10-assembly-and-calling-convention/listings/check_digit.c
  1. Compute by hand the check digit of 4006, and compare with the output in the solution.
  2. Why a do–while rather than a while? What would check_digit(0) return?
  3. Show that changing one digit of a code always changes the check digit. (Consider the weights 1 and 3 modulo 10.)
  4. Swapping two adjacent digits xx and yy changes the weighted sum by ±2(x−y)\pm 2(x - y). When is the swap not caught?
  5. Which values live across the call to weigh? Which may be lost?
  6. 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
Listing 10.15. The prologue and the loop code/bachelor-2/10-assembly-and-calling-convention/listings/count.S
  1. Which registers hold code, i and sum, and why s registers?
  2. The frame is 16 bytes for four saved registers. Write the epilogue, and check it against count.S.
  3. Which instructions compute code modulo 10 and code / 10? Why the unsigned forms?
  4. Where is the loop’s test, and which method of this chapter was applied?
  5. Rewrite the loop to keep sum in a2 instead of s2. What breaks?
  6. The final expression uses remu twice. 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
Listing 10.16. weigh, a leaf code/bachelor-2/10-assembly-and-calling-convention/listings/count.S
  1. Why does weigh need no prologue at all?
  2. weigh computes the weight without a branch. Prove that 3 - 2 * (i & 1) is 3 for even ii and 1 for odd ii.
  3. weigh changes t0 and t1. Is that allowed? Which caller would it break, and how is that caller’s bug avoided?
  4. Inline weigh into the loop. How many instructions per digit are saved?
  5. A real assembler emits call as two instructions, auipc and jalr, for a target that may be far. How would that change the count?
  6. 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
Output 10.17. rv --stats on codes of 1, 4 and 9 digits.
  1. Count the instructions executed per digit, from digit: through bnez, including weigh.
  2. Count the instructions executed once, before and after the loop.
  3. Prove that a code of nn digits executes exactly an+ban + b instructions, and give aa and bb.
  4. Check the formula against the three counts of the output.
  5. Why does the count depend only on nn, not on the digits themselves?
  6. 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
Output 10.22. The C version.

1. From the right: 6⋅3+0⋅1+0⋅3+4⋅1=226 \cdot 3 + 0 \cdot 1 + 0 \cdot 3 + 4 \cdot 1 = 22; (10−2) mod 10=8(10 - 2) \bmod 10 = 8.

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 (10−0) mod 10=0(10 - 0) \bmod 10 = 0, the same value a while would give, but the do form counts 0 as the one-digit code it is.

3. Changing the digit dd at weight ww into d′≠dd' \ne d changes the sum by w(d′−d)w(d' - d), with 0<∣d′−d∣≤90 < |d' - d| \le 9. For w=1w = 1 that is not a multiple of 10; for w=3w = 3, since 3 and 10 are coprime, 3(d′−d)≡0(mod10)3(d' - d) \equiv 0 \pmod{10} would force 10∣d′−d10 \mid d' - d. So the sum changes modulo 10, and s↦(10−s) mod 10s \mapsto (10 - s) \bmod 10 is a bijection on the residues: the check digit changes.

4. xx and yy at adjacent positions have the weights 3 and 1 in some order: the sum changes by ±(3x+y−3y−x)=±2(x−y)\pm(3x + y - 3y - x) = \pm 2(x - y). That is a multiple of 10 exactly when x−yx - y 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. 232−1=4 294 967 2952^{32} - 1 = 4\,294\,967\,295 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 2312^{31} 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 s mod 10s \bmod 10, 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: 10−(s mod 10)10 - (s \bmod 10) 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. i&1i \mathbin{\&} 1 is the last bit of ii: 0 for even ii, giving 3−0=33 - 0 = 3, and 1 for odd ii, giving 3−2=13 - 2 = 1.

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: 15n+2615n + 26.

18. From question 21: 14⋅2+26=5414 \cdot 2 + 26 = 54 for 12, and 14⋅9+26=15214 \cdot 9 + 26 = 152 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 nn-digit code, 10n−1≤c<10n10^{n-1} \le c < 10^n (or c=0c = 0, n=1n = 1), and after kk turns s0 holds ⌊c/10k⌋\lfloor c / 10^k \rfloor, which is nonzero for k<nk < n and zero for k=nk = n: the loop runs exactly nn times. The count is 10+14n+16=14n+2610 + 14n + 16 = 14n + 26: a=14a = 14, b=26b = 26.

22. 14+26=4014 + 26 = 40, 56+26=8256 + 26 = 82 and 126+26=152126 + 26 = 152, the three counts printed; the test adds the seven-digit code 9780306, 98+26=12498 + 26 = 124.

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 nn-digit code, hand-compiled under the calling convention with a helper call per digit, executes exactly 14n+2614n + 26 instructions: an+ban + b with a=14a = 14 and b=26b = 26, proved from the code and counted by rv on every tested code.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো