The processor: trace and decode
Trace small programs in the toy instruction set, predict register and program-counter state, decode a machine-code word, and count clock cycles.
Understanding the processor means being able to run it in your head. Each snippet below is a tiny program or a single machine-code word; read it, step the loop, and predict the state the way the CPU would produce it.
Practise the core skill of the unit: take instructions plus an initial state, step the fetch-decode-execute loop by hand, and read off the resulting register values, program-counter value, machine-code meaning, and cycle count.
These snippets use the toy instruction set from the unit: each instruction is 2 bytes, the program counter advances by 2 after every non-JUMP instruction, and the registers are R0 and R1.
Snippet 1 — tracing register state
; Initial state: R0 = 0, R1 = 0, PC = 0
; Memory: mem[200] = 9, mem[201] = 4
0: LOAD R0, 201
2: LOAD R1, 200
4: ADD R0, R1 ; R0 <- R0 + R1
6: STORE 202, R0
After all four instructions execute, what value is stored in memory address 202?
Snippet 2 — the program counter and a jump
; Initial state: PC = 0, R0 = 0
; Each instruction is 2 bytes.
0: LOAD R0, 200
2: JUMP 6
4: ADD R0, R1 ; never reached
6: STORE 202, R0
Which instruction at address 4 does NOT run, and what is the program-counter value immediately after the JUMP at address 2 executes?
Snippet 3 — decoding a machine-code word
; 16-bit instruction encoding:
; bits 15-12 (4 bits) = opcode
; bits 11-8 (4 bits) = destination register number
; bits 7-0 (8 bits) = immediate value
; opcode 0001 = LOAD-IMMEDIATE (put the constant into the register)
Word in memory: 0001 0011 00010010
Decoding this 16-bit word, which instruction does it represent?
Snippet 4 — counting clock cycles
; A program runs 6 instructions in a tight loop body.
; On this CPU every instruction takes exactly 1 clock cycle.
; The loop body runs 100 times. The CPU clock runs at 2 GHz
; (2,000,000,000 clock cycles per second).
How many clock cycles does the loop body consume in total, and roughly how long does that take at 2 GHz?
Every question here was answered by stepping the same loop: fetch the instruction the PC points to, decode its opcode and operands, execute it (LOAD and STORE move data between memory and registers; ADD uses the ALU on register values; JUMP rewrites the PC), then advance the PC by the instruction size — unless a JUMP set it directly. Machine code decodes by splitting the word into opcode and operand fields. And run time is just instructions x iterations x cycles-per-instruction, divided by the clock rate. Trace it by hand and the processor stops being a black box.
Something unclear?
Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.