Still a lot of magic in the interpreter of [%x interp %]
Build something that mimics hardware more closely
See [%b Nisan2021 %] for a fuller description
Or play [Human Resource Machine][human_resource_machine]
[% figure slug=“vm-architecture” img=“architecture.svg” alt=“Virtual machine architecture” caption=“Architecture of the virtual machine.” %]
[%g instruction_pointer “Instruction pointer” %] (IP) holds the address of the next instruction
Instructions can access [%g register_hardware “registers” %] R0 to R3 directly
256 [%g word_memory “words” %] of memory
[%g instruction_set “Instruction set” %] defines what the processor can do
Each instruction is 3 bytes
[%g op_code “op code” %] fits in one byte
May have zero, one, or two single-byte operands
Each operand is a register identifier, a constant, or an address
Instructions are numbers,
Write them in [%g assembly_code “assembly code” %] for readability
| Name | Code | Format | Action | Example |
|---|---|---|---|---|
hlt
|
1 |
–
|
Halt program |
hlt
|
ldc
|
2 |
rv
|
Load constant |
ldc R0 123
|
ldr
|
3 |
rr
|
Load register |
ldr R0 R1
|
add
|
6 |
rr
|
Add |
add R0 R1
|
bne
|
9 |
rv
|
Branch if not equal |
bne R0 123
|
prr
|
10 |
r-
|
Print register |
prr R0
|
[%inc architecture.py %]
[%inc vm.py mark=init %]
[%inc vm.py mark=fetch %]
[% figure slug=“vm-unpacking” img=“unpacking.svg” alt=“Unpacking instructions” caption=“Using bitwise operations to unpack instructions.” %]
[%inc vm.py mark=run omit=skip %]
[%inc vm.py mark=store %]
[%inc vm.py mark=add %]
[%inc vm.py mark=beq %]
[%inc print_r1.mx %]
[%inc print_r1.as %]
Instruction set doesn’t have names for addresses
But we want [%g label_address “labels” %] for readability
[%inc count_up.as %]
[%inc count_up.out %]
[% figure slug=“vm-count-up” img=“count_up.svg” alt=“Counting from 0 to 2” caption=“Flowchart of assembly language program to count up from 0 to 2.” %]
[% figure slug=“vm-count-trace” img=“count_trace.svg” alt=“Trace counting program” caption=“Tracing registers and memory values for a simple counting program.” %]
[%inc assembler.py mark=class %]
[%inc assembler.py mark=labels %]
[%inc assembler.py mark=compile %]
Look up label’s address if value starts with
@
Convert value to number if it doesn’t
[%inc assembler.py mark=value %]
[% figure slug=“vm-concept-map” img=“concept_map.svg” alt=“Concept map for virtual machine and assembler” caption=“Concept map.” %]