fromscratch-pycpu 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
- fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
- fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
- fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
- fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
- pycpu/__init__.py +11 -0
- pycpu/__main__.py +68 -0
- pycpu/_version.py +24 -0
- pycpu/arithmetic.py +176 -0
- pycpu/assembler.py +580 -0
- pycpu/circuit.py +359 -0
- pycpu/cockpit/__init__.py +8 -0
- pycpu/cockpit/app.py +545 -0
- pycpu/cockpit/code.py +161 -0
- pycpu/cockpit/examples/countdown.pebble +7 -0
- pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
- pycpu/cockpit/examples/factorial.pebble +9 -0
- pycpu/cockpit/examples/greeting.pebble +4 -0
- pycpu/cockpit/examples/times-table.pebble +6 -0
- pycpu/cockpit/examples/tour.pebble +31 -0
- pycpu/cockpit/explain.py +660 -0
- pycpu/cockpit/page.html +1261 -0
- pycpu/cockpit/picture.py +470 -0
- pycpu/cockpit/session.py +778 -0
- pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
- pycpu/cockpit/walks/many-instructions.toml +39 -0
- pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
- pycpu/cockpit/walks/where-n-lives.toml +39 -0
- pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
- pycpu/cockpit/walks.py +518 -0
- pycpu/computer.py +175 -0
- pycpu/cpu.py +648 -0
- pycpu/cpu_parts.py +140 -0
- pycpu/fast.py +320 -0
- pycpu/isa.py +243 -0
- pycpu/logic.py +222 -0
- pycpu/memory.py +268 -0
- pycpu/proof.py +263 -0
- pycpu/py.typed +0 -0
- pycpu/simulator.py +361 -0
- pycpu/state.py +146 -0
- pycpu/translator/__init__.py +29 -0
- pycpu/translator/codegen.py +493 -0
- pycpu/translator/program.py +211 -0
- pycpu/translator/runtime.py +166 -0
- pycpu/translator/subset.py +688 -0
- pycpu/view.py +55 -0
pycpu/cpu_parts.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""The control unit's parts: a signal box, a row of lockers, and two small helpers.
|
|
2
|
+
|
|
3
|
+
Think of a railway signal box beside the tracks. The signaller pulls lever 7 and
|
|
4
|
+
exactly the signals for route 7 turn green, because the wiring does the thinking.
|
|
5
|
+
A CPU has the same thing: an opcode goes in and one wire lights up. Next to the
|
|
6
|
+
signal box is a row of eight lockers (the register file), each holding one number,
|
|
7
|
+
with two windows to look through and one slot to post a new number into a locker.
|
|
8
|
+
|
|
9
|
+
Everything here is built from the gates in `logic.py` and the registers in
|
|
10
|
+
`memory.py`, so underneath it is all NAND. Each part opens its own scope (`decode`,
|
|
11
|
+
`condition`, `registers`, `address_check`) so the Cockpit can zoom in on it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
|
|
16
|
+
from pycpu.circuit import Bus, Circuit, Clock, Wire
|
|
17
|
+
from pycpu.logic import and_, decoder, mux_bus, not_, or_, or_many, xor
|
|
18
|
+
from pycpu.memory import WORD_BITS, Register
|
|
19
|
+
from pycpu.state import REGISTER_COUNT
|
|
20
|
+
|
|
21
|
+
REGISTER_SELECT_BITS = 3
|
|
22
|
+
CONDITION_PAIR_BIT = 0 # the lowest condition bit says "the opposite answer"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def opcode_lines(c: Circuit, opcode: Bus) -> Bus:
|
|
26
|
+
"""Turn the 4-bit opcode into 16 wires, of which exactly one is high.
|
|
27
|
+
|
|
28
|
+
Line `n` is high when the opcode bits spell the number `n`. This is a
|
|
29
|
+
`decoder` filed in a part named `decode`.
|
|
30
|
+
"""
|
|
31
|
+
with c.scope("decode"):
|
|
32
|
+
return decoder(c, opcode)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def condition_met(
|
|
36
|
+
c: Circuit, cond: Bus, zero: Wire, negative: Wire, carry: Wire, overflow: Wire
|
|
37
|
+
) -> Wire:
|
|
38
|
+
"""Return a wire that is 1 when the branch condition `cond` holds for the flags.
|
|
39
|
+
|
|
40
|
+
The eight conditions come in opposite pairs (EQ/NE, LT/GE, LE/GT, LTU/GEU),
|
|
41
|
+
so only four answers are built: zero, less-than, less-or-equal and
|
|
42
|
+
not-carry. A chooser tree steered by the top two bits of `cond` picks one,
|
|
43
|
+
then an XOR with the lowest bit turns it into its opposite when that bit is 1.
|
|
44
|
+
"""
|
|
45
|
+
with c.scope("condition"):
|
|
46
|
+
less = xor(c, negative, overflow) # signed less-than: the sign, unless it overflowed
|
|
47
|
+
answers: list[Bus] = [
|
|
48
|
+
(zero,),
|
|
49
|
+
(less,),
|
|
50
|
+
(or_(c, zero, less),),
|
|
51
|
+
(not_(c, carry),),
|
|
52
|
+
]
|
|
53
|
+
level = answers
|
|
54
|
+
for select in cond[CONDITION_PAIR_BIT + 1 :]:
|
|
55
|
+
level = [mux_bus(c, select, level[i], level[i + 1]) for i in range(0, len(level), 2)]
|
|
56
|
+
return xor(c, level[0][0], cond[CONDITION_PAIR_BIT])
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def sign_extend(c: Circuit, bits: Bus, width: int = WORD_BITS) -> Bus:
|
|
60
|
+
"""Stretch a short signed number to `width` bits by copying its top bit.
|
|
61
|
+
|
|
62
|
+
This adds no gates: the top wire is simply run to every new place.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
ValueError: If `width` is narrower than `bits`.
|
|
66
|
+
|
|
67
|
+
"""
|
|
68
|
+
if width < len(bits):
|
|
69
|
+
msg = f"cannot sign-extend {len(bits)} wires into a narrower {width}"
|
|
70
|
+
raise ValueError(msg)
|
|
71
|
+
del c # wires only: the circuit is not touched, but callers pass it for symmetry
|
|
72
|
+
return (*bits, *([bits[-1]] * (width - len(bits))))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def outside_ram(c: Circuit, address: Bus, ram_bits: int) -> Wire:
|
|
76
|
+
"""Return a wire that is 1 when `address` is too big for a RAM of `ram_bits` bits.
|
|
77
|
+
|
|
78
|
+
RAM holds addresses 0 up to `(1 << ram_bits) - 1`, so any 1 in a higher
|
|
79
|
+
address bit means the address points off the end of memory.
|
|
80
|
+
"""
|
|
81
|
+
with c.scope("address_check"):
|
|
82
|
+
return or_many(c, address[ram_bits:])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class RegisterFile:
|
|
86
|
+
"""Eight 16-bit registers, `r0` to `r7`, with two read windows and one write slot.
|
|
87
|
+
|
|
88
|
+
The windows are `a` and `b`: they show the registers picked by `read_a` and
|
|
89
|
+
`read_b`, both at once. To write, put a number on `data`, spell the register
|
|
90
|
+
on `write_select` and raise `write`; on the next clock beat only that
|
|
91
|
+
register loads. Each window is a tree of choosers (the same shape as the
|
|
92
|
+
ALU's answer picker), and register `n` loads when `write` is 1 and a decoder
|
|
93
|
+
on `write_select` lights line `n`.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
c: Circuit,
|
|
99
|
+
data: Bus,
|
|
100
|
+
write: Wire,
|
|
101
|
+
write_select: Bus,
|
|
102
|
+
read_a: Bus,
|
|
103
|
+
read_b: Bus,
|
|
104
|
+
clock: Clock,
|
|
105
|
+
) -> None:
|
|
106
|
+
"""Add the register file's gates to the circuit, inside a part named `registers`.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
c: The circuit to build in.
|
|
110
|
+
data: The 16 wires to copy into the chosen register; may be placeholders.
|
|
111
|
+
write: 1 when a register should load on the next beat.
|
|
112
|
+
write_select: 3 wires spelling which register loads.
|
|
113
|
+
read_a: 3 wires spelling which register shows in window `a`.
|
|
114
|
+
read_b: 3 wires spelling which register shows in window `b`.
|
|
115
|
+
clock: The clock whose beat steps the registers.
|
|
116
|
+
|
|
117
|
+
"""
|
|
118
|
+
self.registers: list[Register] = []
|
|
119
|
+
with c.scope("registers"):
|
|
120
|
+
lines = decoder(c, write_select)
|
|
121
|
+
for n in range(REGISTER_COUNT):
|
|
122
|
+
load = and_(c, write, lines[n])
|
|
123
|
+
self.registers.append(Register(c, WORD_BITS, data, load, clock, f"r{n}"))
|
|
124
|
+
outputs = [register.q for register in self.registers]
|
|
125
|
+
with c.scope("read_a"):
|
|
126
|
+
self.a: Bus = _pick(c, outputs, read_a)
|
|
127
|
+
with c.scope("read_b"):
|
|
128
|
+
self.b: Bus = _pick(c, outputs, read_b)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _pick(c: Circuit, buses: Sequence[Bus], select: Bus) -> Bus:
|
|
132
|
+
"""Choose one of `buses` by the number on `select`, with a tree of choosers.
|
|
133
|
+
|
|
134
|
+
The lowest select bit picks between neighbours first, then the next bit
|
|
135
|
+
picks between those winners, and so on until one bus is left.
|
|
136
|
+
"""
|
|
137
|
+
level = list(buses)
|
|
138
|
+
for bit in select:
|
|
139
|
+
level = [mux_bus(c, bit, level[i], level[i + 1]) for i in range(0, len(level), 2)]
|
|
140
|
+
return level[0]
|
pycpu/fast.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""The fast engine: a cook who follows recipe cards using plain arithmetic, not gates.
|
|
2
|
+
|
|
3
|
+
The gate-built CPU does every step with real NAND gates, which is wonderful to
|
|
4
|
+
look inside and slow to run. The fast engine does exactly the same job with ordinary
|
|
5
|
+
Python numbers and `if` statements, thousands of times quicker. It is the answer
|
|
6
|
+
key: later, a test runs both engines on the same programs and checks that they never
|
|
7
|
+
disagree. That is why this is the one place, besides the test helpers, where Python
|
|
8
|
+
works out logic directly, and why it never feeds the gate view.
|
|
9
|
+
|
|
10
|
+
`alu_model` is the ALU written as plain arithmetic, and `FastMachine` is the whole
|
|
11
|
+
computer built on it, following the definitions in `isa.py`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from collections.abc import Callable, Sequence
|
|
15
|
+
|
|
16
|
+
from pycpu.arithmetic import AluOp
|
|
17
|
+
from pycpu.isa import (
|
|
18
|
+
OUTPUT_PORT,
|
|
19
|
+
Condition,
|
|
20
|
+
Fault,
|
|
21
|
+
Instruction,
|
|
22
|
+
Opcode,
|
|
23
|
+
condition_holds,
|
|
24
|
+
decode,
|
|
25
|
+
)
|
|
26
|
+
from pycpu.memory import RAM_WORDS, WORD_BITS
|
|
27
|
+
from pycpu.state import (
|
|
28
|
+
BYTE_MASK,
|
|
29
|
+
WORD_MASK,
|
|
30
|
+
Flags,
|
|
31
|
+
MachineState,
|
|
32
|
+
power_on,
|
|
33
|
+
program_state,
|
|
34
|
+
validate_state,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
SIGN_BIT = 1 << (WORD_BITS - 1)
|
|
38
|
+
BYTE_BITS = 8
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def alu_model(a: int, b: int, op: AluOp) -> tuple[int, Flags]:
|
|
42
|
+
"""Work out what the gate ALU would give, using plain integers.
|
|
43
|
+
|
|
44
|
+
Return the 16-bit result and the four flags, matching `pycpu.arithmetic.alu`
|
|
45
|
+
bit for bit: carry is the carry out for `ADD`, 1 for `SUB` when nothing was
|
|
46
|
+
borrowed, the bit shifted out for `SHL` and `SHR`, and 0 for the logic
|
|
47
|
+
operations and `PASS_B`; overflow is 1 only for a signed `ADD` or `SUB` that
|
|
48
|
+
does not fit.
|
|
49
|
+
"""
|
|
50
|
+
carry = overflow = 0
|
|
51
|
+
match op:
|
|
52
|
+
case AluOp.ADD:
|
|
53
|
+
total = a + b
|
|
54
|
+
result, carry = total & WORD_MASK, total >> WORD_BITS
|
|
55
|
+
overflow = int(bool(~(a ^ b) & (a ^ result) & SIGN_BIT))
|
|
56
|
+
case AluOp.SUB:
|
|
57
|
+
total = a + (WORD_MASK - b) + 1
|
|
58
|
+
result, carry = total & WORD_MASK, total >> WORD_BITS
|
|
59
|
+
overflow = int(bool((a ^ b) & (a ^ result) & SIGN_BIT))
|
|
60
|
+
case AluOp.AND:
|
|
61
|
+
result = a & b
|
|
62
|
+
case AluOp.OR:
|
|
63
|
+
result = a | b
|
|
64
|
+
case AluOp.XOR:
|
|
65
|
+
result = a ^ b
|
|
66
|
+
case AluOp.SHL:
|
|
67
|
+
result, carry = (a << 1) & WORD_MASK, a >> (WORD_BITS - 1)
|
|
68
|
+
case AluOp.SHR:
|
|
69
|
+
result, carry = a >> 1, a & 1
|
|
70
|
+
case AluOp.PASS_B:
|
|
71
|
+
result = b
|
|
72
|
+
flags = Flags(
|
|
73
|
+
zero=int(result == 0),
|
|
74
|
+
negative=int(bool(result & SIGN_BIT)),
|
|
75
|
+
carry=carry,
|
|
76
|
+
overflow=overflow,
|
|
77
|
+
)
|
|
78
|
+
return result, flags
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class FastMachine:
|
|
82
|
+
"""A whole computer run with plain Python: fetch a word, obey it, repeat.
|
|
83
|
+
|
|
84
|
+
It keeps its state in lists and only builds a frozen `MachineState` when asked
|
|
85
|
+
(`state()`), because that is quicker. Any word is a valid instruction and any
|
|
86
|
+
state can be loaded; a bad memory address halts the machine with
|
|
87
|
+
`Fault.BAD_ADDRESS` and never raises an exception.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, words: int = RAM_WORDS) -> None:
|
|
91
|
+
"""Make a powered-on machine with `words` words of memory.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
ValueError: If `words` is below 1 or reaches the output port's address.
|
|
95
|
+
|
|
96
|
+
"""
|
|
97
|
+
if not 1 <= words < OUTPUT_PORT:
|
|
98
|
+
msg = f"words must be from 1 to {OUTPUT_PORT - 1}, not {words}"
|
|
99
|
+
raise ValueError(msg)
|
|
100
|
+
self.words = words
|
|
101
|
+
self._pc: int = 0
|
|
102
|
+
self._sp = words
|
|
103
|
+
self._registers: list[int] = []
|
|
104
|
+
self._flags = Flags(0, 0, 0, 0)
|
|
105
|
+
self._memory: list[int] = []
|
|
106
|
+
self._halted = False
|
|
107
|
+
self._halt_code = 0
|
|
108
|
+
self._output: list[int] = []
|
|
109
|
+
# Built once: the table only holds bound methods, which never change.
|
|
110
|
+
self._handler_table: dict[Opcode, Callable[[Instruction], None]] = self._build_handlers()
|
|
111
|
+
self.load_state(power_on(words))
|
|
112
|
+
|
|
113
|
+
def load_state(self, state: MachineState) -> None:
|
|
114
|
+
"""Replace the whole machine with `state`.
|
|
115
|
+
|
|
116
|
+
Raises:
|
|
117
|
+
ValueError: If the memory is the wrong length, or a register, `pc`,
|
|
118
|
+
`sp` or output word is outside 0-65535, or `halt_code` is outside
|
|
119
|
+
0-255, or a flag is not 0 or 1. The machine is left unchanged.
|
|
120
|
+
|
|
121
|
+
"""
|
|
122
|
+
validate_state(state, self.words)
|
|
123
|
+
self._pc = state.pc
|
|
124
|
+
self._sp = state.sp
|
|
125
|
+
self._registers = list(state.registers)
|
|
126
|
+
self._flags = state.flags
|
|
127
|
+
self._memory = list(state.memory)
|
|
128
|
+
self._halted = state.halted
|
|
129
|
+
self._halt_code = state.halt_code
|
|
130
|
+
self._output = list(state.output)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def pc(self) -> int:
|
|
134
|
+
"""Return the program counter, without building a whole `state()`."""
|
|
135
|
+
return self._pc
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def halted(self) -> bool:
|
|
139
|
+
"""Return True if the machine has stopped, without building a whole `state()`."""
|
|
140
|
+
return self._halted
|
|
141
|
+
|
|
142
|
+
def register(self, index: int) -> int:
|
|
143
|
+
"""Return register `index` (0-7), without building a whole `state()`."""
|
|
144
|
+
return self._registers[index]
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def handler_table_for_tests(self) -> dict[Opcode, Callable[[Instruction], None]]:
|
|
148
|
+
"""Return the opcode table `step` uses, so a test can check it is built only once."""
|
|
149
|
+
return self._handler_table
|
|
150
|
+
|
|
151
|
+
def state(self) -> MachineState:
|
|
152
|
+
"""Return a frozen copy of the machine as it is now."""
|
|
153
|
+
return MachineState(
|
|
154
|
+
pc=self._pc,
|
|
155
|
+
sp=self._sp,
|
|
156
|
+
registers=tuple(self._registers),
|
|
157
|
+
flags=self._flags,
|
|
158
|
+
memory=tuple(self._memory),
|
|
159
|
+
halted=self._halted,
|
|
160
|
+
halt_code=self._halt_code,
|
|
161
|
+
output=tuple(self._output),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def load_program(self, words: Sequence[int]) -> None:
|
|
165
|
+
"""Power on, then put `words` into memory starting at address 0.
|
|
166
|
+
|
|
167
|
+
Raises:
|
|
168
|
+
ValueError: If the program is bigger than memory or holds a non-word.
|
|
169
|
+
|
|
170
|
+
"""
|
|
171
|
+
self.load_state(program_state(words, self.words))
|
|
172
|
+
|
|
173
|
+
def run(self, max_steps: int) -> int:
|
|
174
|
+
"""Step until the machine halts or `max_steps` steps are taken; return the count."""
|
|
175
|
+
steps = 0
|
|
176
|
+
while steps < max_steps and self.step():
|
|
177
|
+
steps += 1
|
|
178
|
+
return steps
|
|
179
|
+
|
|
180
|
+
def _fault(self) -> None:
|
|
181
|
+
"""Stop the machine with `Fault.BAD_ADDRESS`, changing nothing else."""
|
|
182
|
+
self._halted = True
|
|
183
|
+
self._halt_code = Fault.BAD_ADDRESS
|
|
184
|
+
|
|
185
|
+
def step(self) -> bool:
|
|
186
|
+
"""Fetch and obey one instruction; return False if the machine had already halted."""
|
|
187
|
+
if self._halted:
|
|
188
|
+
return False
|
|
189
|
+
pc = self._pc
|
|
190
|
+
if pc >= self.words:
|
|
191
|
+
self._fault() # a fetch fault leaves pc on the bad address
|
|
192
|
+
return True
|
|
193
|
+
instruction = decode(self._memory[pc])
|
|
194
|
+
self._pc = (pc + 1) & WORD_MASK
|
|
195
|
+
self._handler_table[instruction.opcode](instruction)
|
|
196
|
+
return True
|
|
197
|
+
|
|
198
|
+
def _build_handlers(self) -> dict[Opcode, Callable[[Instruction], None]]:
|
|
199
|
+
"""Map each opcode to the method that obeys it."""
|
|
200
|
+
return {
|
|
201
|
+
Opcode.ALU: self._alu,
|
|
202
|
+
Opcode.CMP: self._cmp,
|
|
203
|
+
Opcode.LI: self._li,
|
|
204
|
+
Opcode.LHI: self._lhi,
|
|
205
|
+
Opcode.LOAD: self._load,
|
|
206
|
+
Opcode.STORE: self._store,
|
|
207
|
+
Opcode.JMP: self._jmp,
|
|
208
|
+
Opcode.CALL: self._call,
|
|
209
|
+
Opcode.BR: self._br,
|
|
210
|
+
Opcode.RET: self._ret,
|
|
211
|
+
Opcode.PUSH: self._push,
|
|
212
|
+
Opcode.POP: self._pop,
|
|
213
|
+
Opcode.GETSP: self._getsp,
|
|
214
|
+
Opcode.SETSP: self._setsp,
|
|
215
|
+
Opcode.ADDI: self._addi,
|
|
216
|
+
Opcode.HALT: self._halt,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
def _alu(self, i: Instruction) -> None:
|
|
220
|
+
"""Obey `ALU`: `rd = ra <fn> rb`, setting the flags."""
|
|
221
|
+
result, self._flags = alu_model(self._registers[i.ra], self._registers[i.rb], AluOp(i.fn))
|
|
222
|
+
self._registers[i.rd] = result
|
|
223
|
+
|
|
224
|
+
def _cmp(self, i: Instruction) -> None:
|
|
225
|
+
"""Obey `CMP`: set the flags from `ra - rb` and keep no answer."""
|
|
226
|
+
_, self._flags = alu_model(self._registers[i.ra], self._registers[i.rb], AluOp.SUB)
|
|
227
|
+
|
|
228
|
+
def _li(self, i: Instruction) -> None:
|
|
229
|
+
"""Obey `LI`: put the immediate in `rd`."""
|
|
230
|
+
self._registers[i.rd] = i.imm
|
|
231
|
+
|
|
232
|
+
def _lhi(self, i: Instruction) -> None:
|
|
233
|
+
"""Obey `LHI`: put the immediate in the high byte of `rd`, keeping the low byte."""
|
|
234
|
+
self._registers[i.rd] = (i.imm << BYTE_BITS) | (self._registers[i.rd] & BYTE_MASK)
|
|
235
|
+
|
|
236
|
+
def _load(self, i: Instruction) -> None:
|
|
237
|
+
"""Obey `LOAD`: `rd = mem[ra + off6]`, a fault outside RAM."""
|
|
238
|
+
address = (self._registers[i.ra] + i.imm) & WORD_MASK
|
|
239
|
+
if address >= self.words:
|
|
240
|
+
self._fault()
|
|
241
|
+
else:
|
|
242
|
+
self._registers[i.rd] = self._memory[address]
|
|
243
|
+
|
|
244
|
+
def _store(self, i: Instruction) -> None:
|
|
245
|
+
"""Obey `STORE`: `mem[ra + off6] = rd`, or send it to the output port."""
|
|
246
|
+
address = (self._registers[i.ra] + i.imm) & WORD_MASK
|
|
247
|
+
if address < self.words:
|
|
248
|
+
self._memory[address] = self._registers[i.rd]
|
|
249
|
+
elif address == OUTPUT_PORT:
|
|
250
|
+
self._output.append(self._registers[i.rd])
|
|
251
|
+
else:
|
|
252
|
+
self._fault()
|
|
253
|
+
|
|
254
|
+
def _jmp(self, i: Instruction) -> None:
|
|
255
|
+
"""Obey `JMP`: go to the address (a bad one faults at the next fetch)."""
|
|
256
|
+
self._pc = i.imm
|
|
257
|
+
|
|
258
|
+
def _push_word(self, value: int) -> bool:
|
|
259
|
+
"""Push `value` on the stack; return False after a fault, with nothing changed."""
|
|
260
|
+
address = (self._sp - 1) & WORD_MASK
|
|
261
|
+
if address >= self.words:
|
|
262
|
+
self._fault()
|
|
263
|
+
return False
|
|
264
|
+
self._memory[address] = value
|
|
265
|
+
self._sp = address
|
|
266
|
+
return True
|
|
267
|
+
|
|
268
|
+
def _call(self, i: Instruction) -> None:
|
|
269
|
+
"""Obey `CALL`: push the return address, then jump."""
|
|
270
|
+
if self._push_word(self._pc):
|
|
271
|
+
self._pc = i.imm
|
|
272
|
+
|
|
273
|
+
def _br(self, i: Instruction) -> None:
|
|
274
|
+
"""Obey `BR`: jump by the offset if the condition (held in `rd`) is true."""
|
|
275
|
+
if condition_holds(Condition(i.rd), self._flags):
|
|
276
|
+
self._pc = (self._pc + i.imm) & WORD_MASK
|
|
277
|
+
|
|
278
|
+
def _pop_word(self) -> int | None:
|
|
279
|
+
"""Pop a word off the stack; return None after a fault, with nothing changed."""
|
|
280
|
+
if self._sp >= self.words:
|
|
281
|
+
self._fault()
|
|
282
|
+
return None
|
|
283
|
+
value = self._memory[self._sp]
|
|
284
|
+
self._sp = (self._sp + 1) & WORD_MASK
|
|
285
|
+
return value
|
|
286
|
+
|
|
287
|
+
def _ret(self, _i: Instruction) -> None:
|
|
288
|
+
"""Obey `RET`: pop the return address into `pc`."""
|
|
289
|
+
value = self._pop_word()
|
|
290
|
+
if value is not None:
|
|
291
|
+
self._pc = value
|
|
292
|
+
|
|
293
|
+
def _push(self, i: Instruction) -> None:
|
|
294
|
+
"""Obey `PUSH`: put `rd` on the stack."""
|
|
295
|
+
self._push_word(self._registers[i.rd])
|
|
296
|
+
|
|
297
|
+
def _pop(self, i: Instruction) -> None:
|
|
298
|
+
"""Obey `POP`: take the top of the stack into `rd`."""
|
|
299
|
+
value = self._pop_word()
|
|
300
|
+
if value is not None:
|
|
301
|
+
self._registers[i.rd] = value
|
|
302
|
+
|
|
303
|
+
def _getsp(self, i: Instruction) -> None:
|
|
304
|
+
"""Obey `GETSP`: copy the stack pointer into `rd`."""
|
|
305
|
+
self._registers[i.rd] = self._sp
|
|
306
|
+
|
|
307
|
+
def _setsp(self, i: Instruction) -> None:
|
|
308
|
+
"""Obey `SETSP`: copy `rd` into the stack pointer."""
|
|
309
|
+
self._sp = self._registers[i.rd]
|
|
310
|
+
|
|
311
|
+
def _addi(self, i: Instruction) -> None:
|
|
312
|
+
"""Obey `ADDI`: add the signed immediate to `rd`, setting the flags."""
|
|
313
|
+
self._registers[i.rd], self._flags = alu_model(
|
|
314
|
+
self._registers[i.rd], i.imm & WORD_MASK, AluOp.ADD
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
def _halt(self, i: Instruction) -> None:
|
|
318
|
+
"""Obey `HALT`: stop with the immediate as the halt code."""
|
|
319
|
+
self._halted = True
|
|
320
|
+
self._halt_code = i.imm
|
pycpu/isa.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""The instruction set: the codebook that says what every 16-bit order means.
|
|
2
|
+
|
|
3
|
+
Think of a spy's codebook. Each order is a row of boxes on a card: the first box
|
|
4
|
+
says what to do and the other boxes give the details. Whoever writes a card and
|
|
5
|
+
whoever reads it must use the very same book, or the spy opens the wrong door.
|
|
6
|
+
This file is that book for PyCPU. The assembler writes cards with it, the fast
|
|
7
|
+
engine and the gate-built CPU read them with it, and nothing else in the project
|
|
8
|
+
decides what a number means.
|
|
9
|
+
|
|
10
|
+
An instruction is one 16-bit word with the opcode in the top four bits. The other
|
|
11
|
+
fields sit at fixed places: `rd` (or the condition) in bits 11-9, `ra` in 8-6, `rb`
|
|
12
|
+
in 5-3, `fn` in 2-0, and the immediate (a number written inside the instruction)
|
|
13
|
+
in the low bits. Unused bits are written as 0 and ignored when read, so every word
|
|
14
|
+
from 0 to 65535 is a valid instruction.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from enum import IntEnum
|
|
19
|
+
|
|
20
|
+
from pycpu.state import REGISTER_COUNT, WORD_MASK, Flags
|
|
21
|
+
|
|
22
|
+
OUTPUT_PORT = 0xFFFF
|
|
23
|
+
|
|
24
|
+
OPCODE_SHIFT = 12
|
|
25
|
+
RD_SHIFT = 9
|
|
26
|
+
RA_SHIFT = 6
|
|
27
|
+
RB_SHIFT = 3
|
|
28
|
+
REGISTER_MASK = 0b111
|
|
29
|
+
FN_MASK = 0b111
|
|
30
|
+
FN_COUNT = 8
|
|
31
|
+
|
|
32
|
+
IMM8_BITS = 8
|
|
33
|
+
OFF6_BITS = 6
|
|
34
|
+
OFF9_BITS = 9
|
|
35
|
+
ADDR12_BITS = 12
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Opcode(IntEnum):
|
|
39
|
+
"""What an instruction does: the top four bits of the word."""
|
|
40
|
+
|
|
41
|
+
ALU = 0
|
|
42
|
+
CMP = 1
|
|
43
|
+
LI = 2
|
|
44
|
+
LHI = 3
|
|
45
|
+
LOAD = 4
|
|
46
|
+
STORE = 5
|
|
47
|
+
JMP = 6
|
|
48
|
+
CALL = 7
|
|
49
|
+
BR = 8
|
|
50
|
+
RET = 9
|
|
51
|
+
PUSH = 10
|
|
52
|
+
POP = 11
|
|
53
|
+
GETSP = 12
|
|
54
|
+
SETSP = 13
|
|
55
|
+
ADDI = 14
|
|
56
|
+
HALT = 15
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Condition(IntEnum):
|
|
60
|
+
"""The question a branch asks about the flag lamps (3 bits)."""
|
|
61
|
+
|
|
62
|
+
EQ = 0
|
|
63
|
+
NE = 1
|
|
64
|
+
LT = 2
|
|
65
|
+
GE = 3
|
|
66
|
+
LE = 4
|
|
67
|
+
GT = 5
|
|
68
|
+
LTU = 6
|
|
69
|
+
GEU = 7
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Fault(IntEnum):
|
|
73
|
+
"""Why a machine stopped when it did not finish normally (the `halt_code`)."""
|
|
74
|
+
|
|
75
|
+
BAD_ADDRESS = 1
|
|
76
|
+
STACK_OVERFLOW = 2
|
|
77
|
+
DIVIDE_BY_ZERO = 3
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Instruction:
|
|
82
|
+
"""One instruction taken apart into its fields.
|
|
83
|
+
|
|
84
|
+
`rd` holds bits 11-9: the destination register for most opcodes, the
|
|
85
|
+
condition for `BR`, and the register to read for `STORE`, `PUSH` and `SETSP`.
|
|
86
|
+
`imm` holds the signed value of whichever immediate the opcode uses; fields
|
|
87
|
+
that the opcode does not use are 0.
|
|
88
|
+
|
|
89
|
+
Attributes:
|
|
90
|
+
opcode: What to do.
|
|
91
|
+
rd: The destination register, or the condition for `BR`.
|
|
92
|
+
ra: The first source register.
|
|
93
|
+
rb: The second source register.
|
|
94
|
+
fn: The ALU operation (an `AluOp` number) for `ALU`.
|
|
95
|
+
imm: The immediate: 0-255 for `LI`/`LHI`/`HALT`, -128 to 127 for `ADDI`,
|
|
96
|
+
a signed 6-bit offset for `LOAD`/`STORE`, a signed 9-bit offset for
|
|
97
|
+
`BR`, and a 12-bit address for `JMP`/`CALL`.
|
|
98
|
+
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
opcode: Opcode
|
|
102
|
+
rd: int = 0
|
|
103
|
+
ra: int = 0
|
|
104
|
+
rb: int = 0
|
|
105
|
+
fn: int = 0
|
|
106
|
+
imm: int = 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# Which register-like fields each opcode reads or writes. Fields not listed are ignored.
|
|
110
|
+
_USES: dict[Opcode, tuple[str, ...]] = {
|
|
111
|
+
Opcode.ALU: ("rd", "ra", "rb", "fn"),
|
|
112
|
+
Opcode.CMP: ("ra", "rb"),
|
|
113
|
+
Opcode.LI: ("rd",),
|
|
114
|
+
Opcode.LHI: ("rd",),
|
|
115
|
+
Opcode.LOAD: ("rd", "ra"),
|
|
116
|
+
Opcode.STORE: ("rd", "ra"),
|
|
117
|
+
Opcode.JMP: (),
|
|
118
|
+
Opcode.CALL: (),
|
|
119
|
+
Opcode.BR: ("rd",),
|
|
120
|
+
Opcode.RET: (),
|
|
121
|
+
Opcode.PUSH: ("rd",),
|
|
122
|
+
Opcode.POP: ("rd",),
|
|
123
|
+
Opcode.GETSP: ("rd",),
|
|
124
|
+
Opcode.SETSP: ("rd",),
|
|
125
|
+
Opcode.ADDI: ("rd",),
|
|
126
|
+
Opcode.HALT: (),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
# The immediate each opcode carries: (width in bits, signed?). No entry means no immediate.
|
|
130
|
+
_IMMEDIATE: dict[Opcode, tuple[int, bool]] = {
|
|
131
|
+
Opcode.LI: (IMM8_BITS, False),
|
|
132
|
+
Opcode.LHI: (IMM8_BITS, False),
|
|
133
|
+
Opcode.HALT: (IMM8_BITS, False),
|
|
134
|
+
Opcode.ADDI: (IMM8_BITS, True),
|
|
135
|
+
Opcode.LOAD: (OFF6_BITS, True),
|
|
136
|
+
Opcode.STORE: (OFF6_BITS, True),
|
|
137
|
+
Opcode.BR: (OFF9_BITS, True),
|
|
138
|
+
Opcode.JMP: (ADDR12_BITS, False),
|
|
139
|
+
Opcode.CALL: (ADDR12_BITS, False),
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _check(name: str, value: int, low: int, high: int) -> None:
|
|
144
|
+
"""Raise a ValueError naming the field when `value` is outside `low`..`high`."""
|
|
145
|
+
if not low <= value <= high:
|
|
146
|
+
msg = f"{name} {value} does not fit: it must be from {low} to {high}"
|
|
147
|
+
raise ValueError(msg)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def encode(
|
|
151
|
+
opcode: Opcode,
|
|
152
|
+
*,
|
|
153
|
+
rd: int = 0,
|
|
154
|
+
ra: int = 0,
|
|
155
|
+
rb: int = 0,
|
|
156
|
+
fn: int = 0,
|
|
157
|
+
imm: int = 0,
|
|
158
|
+
) -> int:
|
|
159
|
+
"""Write an instruction as one 16-bit word.
|
|
160
|
+
|
|
161
|
+
Every register and `fn` value is checked, and so is the immediate when the
|
|
162
|
+
opcode has one. Fields that the opcode does not use are left out of the word.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
opcode: What to do.
|
|
166
|
+
rd: Destination register (or the condition for `BR`), 0 to 7.
|
|
167
|
+
ra: First source register, 0 to 7.
|
|
168
|
+
rb: Second source register, 0 to 7.
|
|
169
|
+
fn: ALU operation number, 0 to 7.
|
|
170
|
+
imm: The immediate, signed or not as the opcode needs.
|
|
171
|
+
|
|
172
|
+
Raises:
|
|
173
|
+
ValueError: If a value does not fit its field; the message names the field.
|
|
174
|
+
|
|
175
|
+
"""
|
|
176
|
+
_check("rd", rd, 0, REGISTER_COUNT - 1)
|
|
177
|
+
_check("ra", ra, 0, REGISTER_COUNT - 1)
|
|
178
|
+
_check("rb", rb, 0, REGISTER_COUNT - 1)
|
|
179
|
+
_check("fn", fn, 0, FN_COUNT - 1)
|
|
180
|
+
word = int(opcode) << OPCODE_SHIFT
|
|
181
|
+
uses = _USES[opcode]
|
|
182
|
+
if "rd" in uses:
|
|
183
|
+
word |= rd << RD_SHIFT
|
|
184
|
+
if "ra" in uses:
|
|
185
|
+
word |= ra << RA_SHIFT
|
|
186
|
+
if "rb" in uses:
|
|
187
|
+
word |= rb << RB_SHIFT
|
|
188
|
+
if "fn" in uses:
|
|
189
|
+
word |= fn
|
|
190
|
+
if opcode in _IMMEDIATE:
|
|
191
|
+
bits, signed = _IMMEDIATE[opcode]
|
|
192
|
+
if signed:
|
|
193
|
+
_check("imm", imm, -(1 << (bits - 1)), (1 << (bits - 1)) - 1)
|
|
194
|
+
else:
|
|
195
|
+
_check("imm", imm, 0, (1 << bits) - 1)
|
|
196
|
+
word |= imm & ((1 << bits) - 1)
|
|
197
|
+
return word
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def decode(word: int) -> Instruction:
|
|
201
|
+
"""Take a 16-bit word apart into an `Instruction`. Every word is accepted.
|
|
202
|
+
|
|
203
|
+
Fields the opcode does not use come back as 0, whatever bits the word holds.
|
|
204
|
+
"""
|
|
205
|
+
word &= WORD_MASK
|
|
206
|
+
opcode = Opcode(word >> OPCODE_SHIFT)
|
|
207
|
+
uses = _USES[opcode]
|
|
208
|
+
imm = 0
|
|
209
|
+
if opcode in _IMMEDIATE:
|
|
210
|
+
bits, signed = _IMMEDIATE[opcode]
|
|
211
|
+
imm = word & ((1 << bits) - 1)
|
|
212
|
+
if signed and imm >> (bits - 1):
|
|
213
|
+
imm -= 1 << bits
|
|
214
|
+
return Instruction(
|
|
215
|
+
opcode=opcode,
|
|
216
|
+
rd=(word >> RD_SHIFT) & REGISTER_MASK if "rd" in uses else 0,
|
|
217
|
+
ra=(word >> RA_SHIFT) & REGISTER_MASK if "ra" in uses else 0,
|
|
218
|
+
rb=(word >> RB_SHIFT) & REGISTER_MASK if "rb" in uses else 0,
|
|
219
|
+
fn=word & FN_MASK if "fn" in uses else 0,
|
|
220
|
+
imm=imm,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def condition_holds(cond: Condition, flags: Flags) -> bool:
|
|
225
|
+
"""Answer a branch's question: does `cond` hold for these flag lamps.
|
|
226
|
+
|
|
227
|
+
Signed comparisons (`LT`, `GE`, `LE`, `GT`) compare `negative` with `overflow`;
|
|
228
|
+
the unsigned ones (`LTU`, `GEU`) use `carry`, which after a subtraction is 1
|
|
229
|
+
when nothing had to be borrowed.
|
|
230
|
+
"""
|
|
231
|
+
zero, carry = bool(flags.zero), bool(flags.carry)
|
|
232
|
+
signed_less = flags.negative != flags.overflow
|
|
233
|
+
answers = {
|
|
234
|
+
Condition.EQ: zero,
|
|
235
|
+
Condition.NE: not zero,
|
|
236
|
+
Condition.LT: signed_less,
|
|
237
|
+
Condition.GE: not signed_less,
|
|
238
|
+
Condition.LE: zero or signed_less,
|
|
239
|
+
Condition.GT: not zero and not signed_less,
|
|
240
|
+
Condition.LTU: not carry,
|
|
241
|
+
Condition.GEU: carry,
|
|
242
|
+
}
|
|
243
|
+
return answers[cond]
|