কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

High School Computer Science · শ্রেণি 10–12

13The von Neumann Machine and Assembly Language

In a computer’s memory, the instruction “add register 22 to register 11” and the number 1717 followed by the number 22 are the same two bytes. The processor cannot tell them apart; it reads whatever its program counter points at, and runs it as an instruction. This single idea, program and data in the same memory, is what makes a computer able to load a new program as easily as new data, and it is also why a wrong write can turn data into code.

This chapter takes the toy machine of Book 1 seriously: its whole instruction set, programs with jumps and loops, the stack and subroutines, and the step from a line of Python down to the machine’s instructions.

You already know

A processor repeats the same cycle: fetch the instruction at the address in the program counter, decode it, execute it. Its registers are a few fast cells inside it; machine language is the numbers that encode its instructions; a chip may hold several cores, each running its own program (Book 1, grade 7). An adder, a multiplexer and a register of flip-flops are built from gates (the previous chapter).

13.1 Processor, memory, buses

Definition 13.1 (von Neumann architecture)

A computer has a von Neumann architecture when it is made of a processor (a control unit, an ALU and registers), one memory that holds both the program and its data, and input and output devices, and when the processor runs the program by fetching its instructions from that memory one after the other.

Definition 13.2 (Bus)

A bus is a set of wires shared by several components to carry one kind of signal. The address bus carries the number of the memory cell or device being accessed, the data bus the value read or written, and the control bus the signals that say what to do and when, such as “read” or “write”.

The von Neumann model. The processor reaches the memory and the devices through the same three buses; one memory holds the program and its data.
The von Neumann model. The processor reaches the memory and the devices through the same three buses; one memory holds the program and its data.

Each fetch, each LOAD and each STORE is a trip over the buses: the processor puts an address on the address bus and “read” on the control bus, and the memory answers on the data bus. A machine with several processors, or several cores, has them share the memory in the same way, each running its own instructions.

History — A report and a baby

In 1945, the mathematician John von Neumann circulated a First Draft of a Report on the EDVAC, which described a computer keeping its program in the same electronic memory as its data, instead of on plugboards or punched tape.

The first machine to run such a stored program was built in Manchester, England, by Freddie Williams, Tom Kilburn and Geoff Tootill: nicknamed the Baby, it ran its first program, 1717 instructions written by Kilburn to find the largest factor of a number, on 21 June 1948.

A replica of the Baby on display in Manchester: racks of valves, and in the middle the small screen that showed its memory. Photograph: KGGucwa, CC BY-SA 3.0.
A replica of the Baby on display in Manchester: racks of valves, and in the middle the small screen that showed its memory. Photograph: KGGucwa, CC BY-SA 3.0.

13.2 The toy machine in full

Book 1 traced small programs of the toy machine by hand. Its full description is short: 256256 cells of one byte, four registers R0 to R3, a program counter PC, a stack pointer SP, and the three flags of the previous chapter. Arithmetic wraps modulo 256256.

Definition 13.3 (Instruction set)

The instruction set of a processor is the list of the instructions it can execute, with their encoding in bytes and their exact effect on registers, flags and memory.

The toy machine has 2828 instructions. Each takes two bytes: the first holds a 66-bit operation code and a 22-bit register number, the second an operand: a number, an address, or a second register.

0HALT10NOT r20OUT r
1LOADI r, n11SHL r21LOADR r, s
2LOAD r, [a]12SHR r22STORER r, s
3STORE r, [a]13CMP r, s23PUSH r
4ADD r, s14JMP a24POP r
5SUB r, s15JZ a25CALL a
6ADDI r, n16JNZ a26RET
7AND r, s17JN a27NOP
8OR r, s18JC a
9XOR r, s19IN r

LOADI puts a number in a register, LOAD and STORE move a byte between a register and a cell, and LOADR and STORER do the same with the address in a register. The arithmetic and logic instructions, and CMP, which subtracts without keeping the result, set the flags ZZ, NN and CC.

The encoding of an instruction: the first byte is 4 × operation code + r. Below, ADD R1, R2: the bytes 4 × 4 + 1 = 17 and 2.
The encoding of an instruction: the first byte is 4×operation code+r4 \times \text{operation code} + r. Below, ADD R1, R2: the bytes 4×4+1=174 \times 4 + 1 = 17 and 22.

The step of the machine refines the cycle of Book 1: fetch the two bytes at PC and PC + 1, add 22 to PC, decode, execute. A jump writes a new address into PC after that increment, so the next fetch happens there.

13.3 Assembly programs with jumps

Definition 13.4 (Assembly language, assembler, label)

An assembly language writes a machine’s instructions with names instead of numbers, one instruction per line. A label is a name given to the address of a line, so that other instructions can refer to it. An assembler is the program that translates assembly language into machine code, replacing every name and every label by its number.

Definition 13.5 (Jump, conditional jump)

A jump writes an address into the program counter, so that execution goes on there. A conditional jump does so only if a flag has a given value (JZ if Z=1Z = 1, JNZ if Z=0Z = 0, JN if N=1N = 1, JC if C=1C = 1), and otherwise lets execution go on to the next instruction.

Conditions and loops are built from these. CMP R0, R1 computes R0−R1R_0 - R_1 and sets CC when it needs a borrow, that is when R0<R1R_0 < R_1 for numbers without sign: JC after a CMP means “jump if smaller”.

; max2.toy -- reads two numbers, prints the larger
        IN    R0
        IN    R1
        CMP   R0, R1      ; R0 - R1: C = 1 when R0 < R1
        JC    second
        OUT   R0
        HALT
second: OUT   R1
        HALT
Listing 13.1. An if: the larger of two numbers. code/grade-11/02-von-neumann-machine/listings/max2.toy
$ python -m toymachine run max2.toy
201
Output 13.1. With the inputs 5757 and 201201, from max2.stdin.

A loop is a jump backwards. The option --trace prints a row before each step: the step number, PC, the instruction, the four registers and the three flags.

; count_down.toy -- prints 3, 2, 1
; capture: args=--trace
        LOADI R0, 3
        LOADI R1, 1
loop:   OUT   R0
        SUB   R0, R1      ; sets Z when R0 reaches 0
        JNZ   loop
        HALT
Listing 13.2. A loop: a counter, a subtraction that sets ZZ, a jump back while Z=0Z = 0. code/grade-11/02-von-neumann-machine/listings/count_down.toy
$ python -m toymachine run count_down.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 3        0   0   0   0  0 0 0
   2   2  LOADI R1, 1        3   0   0   0  0 0 0
   3   4  OUT R0             3   1   0   0  0 0 0
3
   4   6  SUB R0, R1         3   1   0   0  0 0 0
   5   8  JNZ 4              2   1   0   0  0 0 0
   6   4  OUT R0             2   1   0   0  0 0 0
2
   7   6  SUB R0, R1         2   1   0   0  0 0 0
   8   8  JNZ 4              1   1   0   0  0 0 0
   9   4  OUT R0             1   1   0   0  0 0 0
1
  10   6  SUB R0, R1         1   1   0   0  0 0 0
  11   8  JNZ 4              0   1   0   0  1 0 0
  12  10  HALT               0   1   0   0  1 0 0
halted after 12 steps
Output 13.2. The trace: JNZ 4 jumps back to address 44 until the subtraction reaches 00 (step 1111, Z=1Z = 1).
The flow of the loop, with the address of each instruction. The label loop is the number 4; the assembler writes JNZ 4. When Z = 1, execution goes on to the next line, HALT.
The flow of the loop, with the address of each instruction. The label loop is the number 44; the assembler writes JNZ 4. When Z=1Z = 1, execution goes on to the next line, HALT.

The data of a program can sit in memory right after its code: DATA places bytes there, and a label gives their address. With an address in a register, LOADR reads a cell chosen at run time, which is how a loop walks through an array.

; sum_array.toy -- adds the numbers of an array stored after the program
        LOADI R0, 0         ; the total
        LOADI R1, array     ; address of the next number
        LOAD  R2, [length]  ; how many are left
loop:   LOADR R3, R1        ; R3 = M[R1]
        ADD   R0, R3
        ADDI  R1, 1
        ADDI  R2, -1        ; Z when none is left
        JNZ   loop
        OUT   R0
        HALT
length: DATA  6
array:  DATA  12, 7, 30
        DATA  1, 25, 9
Listing 13.3. An array in memory, and a loop that adds it up. code/grade-11/02-von-neumann-machine/listings/sum_array.toy
$ python -m toymachine run sum_array.toy
84
Output 13.3. 12+7+30+1+25+9=8412 + 7 + 30 + 1 + 25 + 9 = 84.

The assembler shows what the program becomes: for each line, its address, its two bytes in decimal and in binary, and the source.

$ python -m toymachine asm sum_array.toy
  0:   4   0  00000100 00000000  LOADI R0, 0         ; the total
  2:   5  21  00000101 00010101  LOADI R1, array     ; address of the next number
  4:  10  20  00001010 00010100  LOAD  R2, [length]  ; how many are left
  6:  87   1  01010111 00000001  loop:   LOADR R3, R1        ; R3 = M[R1]
  8:  16   3  00010000 00000011  ADD   R0, R3
 10:  25   1  00011001 00000001  ADDI  R1, 1
 12:  26 255  00011010 11111111  ADDI  R2, -1        ; Z when none is left
 14:  64   6  01000000 00000110  JNZ   loop
 16:  80   0  01010000 00000000  OUT   R0
 18:   0   0  00000000 00000000  HALT
 20:   6      00000110           length: DATA  6
 21:  12   7  30 00001100 00000111 00011110  array:  DATA  12, 7, 30
 24:   1  25   9 00000001 00011001 00001001  DATA  1, 25, 9
Output 13.4. The machine code of sum_array.toy. The label array became 2121 and loop became 66; the DATA lines take one byte per number.
The memory of sum_array.toy: ten instructions in cells 0 to 19, the data in 20 to 26. A program that uses the stack fills it from cell 255 down, towards the code.
The memory of sum_array.toy: ten instructions in cells 00 to 1919, the data in 2020 to 2626. A program that uses the stack fills it from cell 255255 down, towards the code.

Negative numbers are stored in two’s complement; IN reads −42-42 as 256−42=214256 - 42 = 214. The flag NN tells a negative result, and JN acts on it.

; abs_value.toy -- reads a number from -128 to 127, prints its absolute value
        IN    R0
        ADDI  R0, 0         ; adds nothing, but sets N from bit 7
        JN    negative
        OUT   R0
        HALT
negative:
        NOT   R0            ; two's complement: flip every bit...
        ADDI  R0, 1         ; ...and add 1
        OUT   R0
        HALT
Listing 13.4. The absolute value: NOT and ADDI 1 negate a number. code/grade-11/02-von-neumann-machine/listings/abs_value.toy
$ python -m toymachine run abs_value.toy
42
Output 13.5. With the input −42-42.

The toy machine has no multiplication. A loop adds aa to a total bb times; the weekend problem measures its cost and finds a much faster way.

; multiply.toy -- reads a and b, prints a * b by adding a, b times
        IN    R0            ; a
        IN    R1            ; b, the number of additions left
        LOADI R2, 0         ; the product
        LOADI R3, 1
        ADDI  R1, 0         ; sets Z if b is 0
        JZ    done
loop:   ADD   R2, R0
        SUB   R1, R3
        JNZ   loop
done:   OUT   R2
        HALT
Listing 13.5. Multiplication by repeated addition. code/grade-11/02-von-neumann-machine/listings/multiply.toy
$ python -m toymachine run multiply.toy
143
Output 13.6. 13×1113 \times 11, from multiply.stdin.

13.4 Subroutines and the stack

A piece of code used in several places is written once, as a subroutine, and called. The difficulty is to come back: the subroutine must know where it was called from.

Definition 13.6 (Subroutine, stack pointer)

A subroutine is a sequence of instructions that is entered by CALL and left by RET. The stack pointer SP holds the address of the top of a zone of memory, the stack, used last in, first out: PUSH r lowers SP by one and stores r there, POP r reads it back and raises SP. CALL a pushes the address of the next instruction and jumps to a; RET pops an address into PC.

The stack starts at the top of memory: SP is 00 at the start, so the first PUSH writes cell 255255. A subroutine that uses a register the caller needs saves it with PUSH and gives it back with POP before returning.

; call_square.toy -- a subroutine that squares R0 into R1
; capture: args=--trace
        LOADI R0, 3
        CALL  square        ; pushes the return address 4, jumps
        OUT   R1
        HALT
square: PUSH  R2            ; keep the caller's R2
        LOADI R1, 0
        LOADI R2, 0
        ADD   R2, R0        ; R2 = R0 additions to do
again:  ADD   R1, R0
        ADDI  R2, -1
        JNZ   again
        POP   R2            ; give R2 back
        RET                 ; pops 4 into PC
Listing 13.6. A subroutine that squares R0, and keeps the caller’s R2. code/grade-11/02-von-neumann-machine/listings/call_square.toy
$ python -m toymachine run call_square.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 3        0   0   0   0  0 0 0
   2   2  CALL 8             3   0   0   0  0 0 0
   3   8  PUSH R2            3   0   0   0  0 0 0
   4  10  LOADI R1, 0        3   0   0   0  0 0 0
   5  12  LOADI R2, 0        3   0   0   0  0 0 0
   6  14  ADD R2, R0         3   0   0   0  0 0 0
   7  16  ADD R1, R0         3   0   3   0  0 0 0
   8  18  ADDI R2, 255       3   3   3   0  0 0 0
   9  20  JNZ 16             3   3   2   0  0 0 1
  10  16  ADD R1, R0         3   3   2   0  0 0 1
  11  18  ADDI R2, 255       3   6   2   0  0 0 0
  12  20  JNZ 16             3   6   1   0  0 0 1
  13  16  ADD R1, R0         3   6   1   0  0 0 1
  14  18  ADDI R2, 255       3   9   1   0  0 0 0
  15  20  JNZ 16             3   9   0   0  1 0 1
  16  22  POP R2             3   9   0   0  1 0 1
  17  24  RET                3   9   0   0  1 0 1
  18   4  OUT R1             3   9   0   0  1 0 1
9
  19   6  HALT               3   9   0   0  1 0 1
halted after 19 steps
Output 13.7. Step 22 pushes 44, the address after the CALL; step 1717 pops it, and the program goes on at OUT R1.

During the call, cell 255255 holds the return address 44 and cell 254254 the saved R2. POP R2 takes back the last value pushed, the saved register, which leaves the return address on top for RET. Every PUSH needs its POP before the RET; a missing one makes RET jump to whatever value is on top. The stack and its uses are a chapter of their own in grade 12.

Since program and data share the memory, nothing stops a program from writing over its own instructions. Here a number meant as data lands on the code:

; self_modify.toy -- a number written over an instruction
; capture: args=--trace
        LOADI R0, 80        ; just a number...
        STORE R0, [stop]    ; ...stored at an address that holds code
        LOADI R1, 7
stop:   HALT                ; the byte 80 is 4 x 20 + 0: OUT R0
        HALT
Listing 13.7. A store into the code. code/grade-11/02-von-neumann-machine/listings/self_modify.toy
$ python -m toymachine run self_modify.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 80       0   0   0   0  0 0 0
   2   2  STORE R0, [6]     80   0   0   0  0 0 0
   3   4  LOADI R1, 7       80   0   0   0  0 0 0
   4   6  OUT R0            80   7   0   0  0 0 0
80
   5   8  HALT              80   7   0   0  0 0 0
halted after 5 steps
Output 13.8. The HALT at address 66 has become OUT R0: the machine runs the number 8080 as an instruction.

Safe use

A program that writes outside its data can change what the machine does next. Attacks on real software have used this for decades: send more data than a buffer holds, let it overwrite code or a return address on the stack, and the processor runs the attacker’s bytes. Modern systems mark memory pages as either writable or executable, never both, to stop it.

13.5 From a line of Python to the machine

A compiler translates an if or a while into tests and jumps, as this chapter did by hand. The loop while n > 0: n = n - 1 becomes: a label; a comparison of n with 00; a conditional jump past the loop when the condition is false; the body; and a jump back to the label.

Python itself does not run on the processor directly. It first translates a function into the instructions of another machine, simple enough to be run by a program: its bytecode. The module dis shows them.

import dis


def count_down(n):
    while n > 0:
        n = n - 1
    return n


dis.dis(count_down)
Listing 13.8. Asking Python for the instructions of a function. code/grade-11/02-von-neumann-machine/listings/py_dis.py
$ python py_dis.py
  4           0 RESUME                   0

  5           2 LOAD_FAST                0 (n)
              4 LOAD_CONST               1 (0)
              6 COMPARE_OP              68 (>)
             10 POP_JUMP_IF_FALSE       11 (to 34)

  6     >>   12 LOAD_FAST                0 (n)
             14 LOAD_CONST               2 (1)
             16 BINARY_OP               10 (-)
             20 STORE_FAST               0 (n)

  5          22 LOAD_FAST                0 (n)
             24 LOAD_CONST               1 (0)
             26 COMPARE_OP              68 (>)
             30 POP_JUMP_IF_FALSE        1 (to 34)
             32 JUMP_BACKWARD           11 (to 12)

  7     >>   34 LOAD_FAST                0 (n)
             36 RETURN_VALUE
Output 13.9. The bytecode of count_down: the left column is the line of the source, the next the address of the instruction.

The shape is the toy machine’s: loads, a comparison, POP_JUMP_IF_FALSE out of the loop, the body, a jump back. One difference: Python copies the test to the bottom of the loop (addresses 2222 to 3030), and its jump back goes to the body, at 1212, not to the first test; the first test runs only once, before the first turn. Bytecode is an internal detail of Python, which changes from one version to the next; this output comes from Python 3.12.

Definition 13.7 (System on a chip)

A system on a chip is a single chip that gathers what used to be separate components: processor cores, memory caches, a graphics processor, a memory controller, radios, controllers for the devices, and the management of power.

The blocks of a typical system on a chip, as found in phones and many laptops. Their number and their names vary from one chip to another.
The blocks of a typical system on a chip, as found in phones and many laptops. Their number and their names vary from one chip to another.

Gathering the components on one chip shortens the wires between them: signals travel faster, and moving data costs less energy, which matters for a battery. The price is that nothing can be changed or added afterwards.

13.6 Exercises

Exercise 13.1 ★

What does this program print?

LOADI R0, 6 LOADI R1, 9 SUB R1, R0 OUT R1 HALT

Solution

Solution of Exercise 13.1.

R1 becomes 9−6=39 - 6 = 3, and the program prints 3.

Exercise 13.2 ★

Encode ADD R1, R2 and JNZ 6 in two bytes each, in decimal and in binary.

Solution

Solution of Exercise 13.2.

ADD R1, R2: operation code 44, r=1r = 1, so 4×4+1=174 \times 4 + 1 = 17, then 22: 00010001 00000010. JNZ 6: operation code 1616, r=0r = 0, so 6464, then 66: 01000000 00000110.

Exercise 13.3 ★

Decode the bytes 52,352, 3 and then 60,1860, 18.

Solution

Solution of Exercise 13.3.

52=4×13+052 = 4 \times 13 + 0: operation 1313, CMP, with r=0r = 0 and s=3s = 3: CMP R0, R3. 60=4×15+060 = 4 \times 15 + 0: JZ, to the address 1818: JZ 18.

Exercise 13.4 ★

R0 holds 55 and R1 holds 1010. Give the result and the flags ZZ, NN, CC after SUB R0, R1, then after SUB R1, R0.

Solution

Solution of Exercise 13.4.

5−105 - 10 wraps to 256−5=251256 - 5 = 251: Z=0Z = 0, N=1N = 1 (bit 7 is 11, the result read with sign is −5-5), C=1C = 1 (a borrow). Starting again from 55 and 1010, SUB R1, R0 gives 55: Z=0Z = 0, N=0N = 0, C=0C = 0.

Exercise 13.5 ★

Write max3.toy, which reads three numbers and prints the largest.

Solution

Solution of Exercise 13.5.

Keep the largest in R0; read the next number into R1, CMP R0, R1, and when JC shows R0 smaller, copy R1 into R0 (LOADI R0, 0 then ADD R0, R1, since there is no move instruction). The file exercises/max3.toy does it; the tests run it on 5050 random triples.

Exercise 13.6 ★★

A student changes count_down.toy to start at 77 and subtract 22, to print 77, 55, 33, 11. What happens? Fix it with one more instruction.

Solution

Solution of Exercise 13.6.

It prints 77, 55, 33, 11, then 1−21 - 2 wraps to 255255, and the odd numbers 255255, 253253, … follow: the counter never reaches 00, so JNZ always jumps, until the machine stops the program after 10 00010\,000 steps. The fix is JC done right after the SUB: the subtraction borrows exactly when the counter was smaller than 22 (exercises/count_by_two_fixed.toy).

Exercise 13.7 ★★

Write max_array.toy, which prints the largest number of an array stored with its length after the program.

Solution

Solution of Exercise 13.7.

As sum_array.toy, but with CMP R0, R3 and JC to a block that copies R3 into R0 before going on (exercises/max_array.toy). On the array 12,7,130,1,25,9,6412, 7, 130, 1, 25, 9, 64 it prints 130130.

Exercise 13.8 ★★

The program sum.toy of Book 1 reads nn, sets a total to 00 and a register to 11, then repeats ADD R1, R0, SUB R0, R2, JNZ loop, and finally prints and halts. How many steps does it execute for an input n≥1n \ge 1? What happens for n=0n = 0?

Solution

Solution of Exercise 13.8.

Three steps before the loop, three per turn, and OUT and HALT: 3n+53n + 5. For n=0n = 0, the first SUB gives 255255 and Z=0Z = 0: the loop runs 256256 times, adding 0+255+254+⋯+1=32 6400 + 255 + 254 + \dots + 1 = 32\,640, which modulo 256256 is 128128. The program prints 128128 after 773773 steps. The tests check 3n+53n + 5 for n=1n = 1, 55, 2020.

Exercise 13.9 ★★

In the trace of call_square.toy, give the value of SP and the contents of cells 255255 and 254254 after steps 22, 33, 1616 and 1717.

Solution

Solution of Exercise 13.9.

After step 22 (CALL): SP =255= 255, cell 255255 holds 44. After step 33 (PUSH R2): SP =254= 254, cell 254254 holds 00, the caller’s R2. After step 1616 (POP R2): SP =255= 255; cell 254254 still holds 00, since popping does not erase. After step 1717 (RET): SP =255+1= 255 + 1, which wraps to 00; cell 255255 still holds 44.

Exercise 13.10 ★★

In a copy of the subroutine, the line POP R2 has been removed, and the caller had put 4040 in R2. What does RET do, and what does the program print?

Solution

Solution of Exercise 13.10.

On top of the stack is the 4040 pushed by PUSH R2, not the return address: RET pops it and jumps to address 4040. That cell is empty, and two bytes 00 are HALT: the program stops there and prints nothing (exercises/bad_return.toy; the tests check it). With other values in R2, it could have run anything.

Exercise 13.11 ★★

Write times_ten.toy, which reads xx and prints 10x10x (modulo 256256) with three shifts and additions, writing 10x10x as 8x+2x8x + 2x (the machine has no copy instruction: copying a register takes a LOADI of 00 and an addition).

Solution

Solution of Exercise 13.11.

SHL R0 gives 2x2x, which is copied into R1; two more SHL R0 give 8x8x, and ADD R0, R1 gives 10x10x (exercises/times_ten.toy). All modulo 256256: for x=26x = 26, 260 mod 256=4260 \bmod 256 = 4.

Exercise 13.12 ★★★

Prove that shift_multiply.toy, from the weekend problem, executes exactly 7+7L7 + 7L steps, where LL is the number of bits of bb (L=0L = 0 for b=0b = 0). Deduce a bound that holds for every input.

Solution

Solution of Exercise 13.12.

Before the loop: IN, IN, LOADI, 33 steps. Each turn with a bit 11 runs ADDI, JZ, SHR, JC (taken), ADD, SHL, JMP; with a bit 00, ADDI, JZ, SHR, JC (not taken), JMP next, SHL, JMP: 77 steps either way. Each turn shifts R1 right by one, so after LL turns it is 00; then ADDI, JZ, OUT, HALT: 44 steps. In all 3+7L+4=7+7L3 + 7L + 4 = 7 + 7L. Since L≤8L \le 8 for an 88-bit number, no input takes more than 6363 steps.

Exercise 13.13 ★★★

Write divide.toy, which reads aa and b>0b > 0 and prints the quotient and the remainder of aa by bb, by repeated subtraction.

Solution

Solution of Exercise 13.13.

While a≥ba \ge b (CMP R0, R1 then JC done), subtract bb from aa and add 11 to the quotient; then print the quotient and what is left of aa, the remainder (exercises/divide.toy; the tests compare it with // and % on 888888 pairs).

Exercise 13.14 ★★★

A program needs dd cells of data, and calls subroutines nested at most kk deep, each of which pushes at most pp registers. How many instructions can its code have at most, so that the stack never reaches the code or the data? Apply it to d=30d = 30, k=4k = 4, p=2p = 2.

Solution

Solution of Exercise 13.14.

ii instructions take 2i2i cells from address 00, then come the dd data cells. Each level of call pushes a return address and at most pp registers: the stack holds at most k(1+p)k(1 + p) cells, from 255255 down. Nothing overlaps if 2i+d+k(1+p)≤2562i + d + k(1 + p) \le 256. For d=30d = 30, k=4k = 4, p=2p = 2: 2i≤256−30−12=2142i \le 256 - 30 - 12 = 214, so at most 107107 instructions.

Exercise 13.15 ★★★

Translate into toy assembly, and test on several inputs:

while a != b: if a > b: a = a - b else: b = b - a

which leaves in a the greatest common divisor of two numbers a,b≥1a, b \ge 1; the program reads aa and bb and prints the result.

Solution

Solution of Exercise 13.15.

After reading aa into R0 and bb into R1: CMP R0, R1; JZ done when they are equal; JC to a block that does SUB R1, R0 when a<ba < b; otherwise SUB R0, R1; both jump back to the comparison; done prints R0 (exercises/gcd.toy). The tests compare it with math.gcd on 720720 pairs.

13.7 Problem: Multiplication on a Machine That Cannot

Problem 13.1

Weekend problem — two ways to multiply, and their cost

The toy machine has no instruction to multiply. The program multiply.toy adds aa to a total bb times. The program below uses the binary digits of bb instead: a×ba \times b is the sum of a×2ia \times 2^i over the bits ii of bb that are 11, and a×2ia \times 2^i is aa shifted left ii times.

; shift_multiply.toy -- a * b by shifts and additions, one bit of b at a time
        IN    R0            ; a, doubled at each bit
        IN    R1            ; b, halved at each bit
        LOADI R2, 0         ; the product
loop:   ADDI  R1, 0         ; Z when no bit of b is left
        JZ    done
        SHR   R1            ; the lowest bit of b goes into C
        JC    add
        JMP   next
add:    ADD   R2, R0        ; this bit is 1: add a times its weight
next:   SHL   R0
        JMP   loop
done:   OUT   R2
        HALT
Listing 13.9. Multiplication by shifts and additions. code/grade-11/02-von-neumann-machine/listings/shift_multiply.toy
"""Problem: the steps of both multiplications, for every b from 0 to 255."""
from pathlib import Path

from toymachine import Machine, assemble

HERE = Path(__file__).parent


def steps(program, a, b):
    m = Machine(program, inputs=[a, b])
    m.run()
    assert m.outputs == [a * b % 256]
    return m.steps


repeated = assemble((HERE / "multiply.toy").read_text())
shifting = assemble((HERE / "shift_multiply.toy").read_text())
for name, program in (("repeated addition", repeated), ("shift and add", shifting)):
    counts = [steps(program, 13, b) for b in range(256)]
    worst = max(counts)
    mean = sum(counts) / 256
    print(f"{name:17}: b = 0 -> {counts[0]:3} steps, b = 1 -> {counts[1]:3},"
          f" worst {worst} (first at b = {counts.index(worst)}), mean {mean:.1f}")
Listing 13.10. Both programs run for every bb from 00 to 255255, with a=13a = 13. code/grade-11/02-von-neumann-machine/listings/step_counts.py
$ python step_counts.py
repeated addition: b = 0 ->   8 steps, b = 1 ->  11, worst 773 (first at b = 255), mean 390.5
shift and add    : b = 0 ->   7 steps, b = 1 ->  14, worst 63 (first at b = 128), mean 56.0
Output 13.10. The steps of both methods. Every product is checked against Python’s, modulo 256256.

Part I — Repeated addition.

  1. Count the steps of multiply.toy for b=0b = 0, line by line.
  2. Show that for b≥1b \ge 1 it takes 8+3b8 + 3b steps. Check b=1b = 1 and b=255b = 255 against the output.
  3. Does the number of steps depend on aa?
  4. Compute the mean over the 256256 values of bb, and compare with the output.

Part II — Shift and add.

  1. Run shift_multiply.toy by hand for a=13a = 13, b=11b = 11: give R0, R1, R2 at each passage through loop.
  2. Why does SHR R1 followed by JC test the lowest bit of bb?
  3. What does SHL R0 compute, and why must it run at every turn, whether the bit was 11 or 00?
  4. Show that the loop turns once per bit of bb, up to its highest 11.
  5. What happens to the product when it does not fit in 88 bits?

Part III — Counting all the cases.

  1. Count the steps of one turn of the loop when the bit is 11, and when it is 00.
  2. Deduce that the program takes 7+7L7 + 7L steps, where LL is the number of bits of bb. Check b=0b = 0 and b=1b = 1.
  3. For how many values of bb is L=8L = 8? Explain why the worst case is first reached at b=128b = 128.
  4. Compute the mean number of steps from the number of values of bb having each LL, and compare with 56.056.0.
  5. In step_counts.py, what does the assert in steps check, and why is % 256 needed?

Part IV — The worst cases.

  1. Give the worst case of each method, and their ratio.
  2. For which values of bb is repeated addition faster? Faster by how much at most?
  3. A program combines both: repeated addition for small bb, shift and add otherwise. Where should it switch?
  4. On a machine with 1616-bit registers, what would the worst cases become?
  5. Real processors have a multiplication instruction, built as a circuit. Which idea of this problem does such a circuit use, and what does it do at once that the program does one turn at a time?
  6. State the result: the worst-case steps of both methods over all 88-bit values of bb, and the formula for shift and add.
Solution

Solution of Problem 13.1.

1. IN, IN, LOADI, LOADI, ADDI, JZ (taken), OUT, HALT: 88 steps.

2. The same 66 steps before the loop, 33 per turn for bb turns, then OUT and HALT: 8+3b8 + 3b. For b=1b = 1, 1111; for b=255b = 255, 773773, as printed.

3. No: R0 is only added, never tested.

4. 1256(8+∑b=1255(8+3b))=8+3256⋅255×2562=8+382.5=390.5\frac{1}{256}\left(8 + \sum_{b=1}^{255} (8 + 3b)\right) = 8 + \frac{3}{256} \cdot \frac{255 \times 256}{2} = 8 + 382.5 = 390.5, as printed.

5. At loop: (13,11,0)(13, 11, 0), then (26,5,13)(26, 5, 13), (52,2,39)(52, 2, 39), (104,1,39)(104, 1, 39), (208,0,143)(208, 0, 143); the last test finds b=0b = 0, and the program prints 143143.

6. SHR moves every bit one place right, and the bit that falls out, the lowest, goes into CC; JC jumps exactly when it was 11.

7. 2a2a: after ii turns R0 holds a×2ia \times 2^i, the value of bit ii of bb. It must double at every turn so that it matches the weight of the next bit, which the next turn tests, whatever this one was.

8. Each turn halves R1, dropping its lowest bit; it becomes 00 once every bit up to the highest 11 has been dropped, after LL turns.

9. ADD and SHL wrap modulo 256256, so the program prints a×b mod 256a \times b \bmod 256, the low byte of the product.

10. 77 in both cases (the list is in the solution of exercise 12): taking JC to add costs the ADD, not taking it costs a JMP next.

11. 33 steps before, 77 per turn, 44 at the end: 7+7L7 + 7L. For b=0b = 0, L=0L = 0 and 77 steps; for b=1b = 1, L=1L = 1 and 1414; as printed.

12. L=8L = 8 for bb from 128128 to 255255: 128128 values. 128=10000000128 = 10000000 is the smallest of them, so the worst case, 7+56=637 + 56 = 63, appears first there.

13. One value has L=0L = 0, and 2L−12^{L - 1} values have each LL from 11 to 88. The mean is

1256(7+∑L=182L−1(7+7L))=7+1785+12 551256=14 343256≈56.03,\frac{1}{256}\left(7 + \sum_{L=1}^{8} 2^{L-1}(7 + 7L)\right) = \frac{7 + 1785 + 12\,551}{256} = \frac{14\,343}{256} \approx 56.03,

printed 56.056.0.

14. That the machine printed exactly one number, the product modulo 256256: the machine’s arithmetic wraps while Python’s does not.

15. 773773 and 6363 steps: repeated addition is about 12.312.3 times slower in the worst case.

16. For bb from 11 to 66, and 88; at b=9b = 9 both take 3535. The largest saving is 88 steps, at b=4b = 4 (2020 against 2828).

17. Below 77, but the test that chooses costs a CMP and a jump, 22 steps, which eats most of a saving of at most 88: it is not worth it.

18. Repeated addition: 8+3×65 535=196 6138 + 3 \times 65\,535 = 196\,613 steps; shift and add: 7+7×16=1197 + 7 \times 16 = 119.

19. The same idea, shifted copies of aa for the bits of bb that are 11, added up. The circuit makes all the shifted copies at once with AND gates and adds them with a tree of adders, in a few levels of gates instead of one turn per bit.

20. Over all 88-bit values of bb, multiplication by repeated addition takes up to 773773 steps (8+3b8 + 3b), and by shift and add at most 6363 (7+7L7 + 7L, where L≤8L \le 8 is the number of bits of bb): about 1212 times fewer in the worst case, and 56.056.0 against 390.5390.5 steps on average.

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

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