CPUSimulation
Aus ExpeccoWiki
Inhaltsverzeichnis |
Overview
The following example is more a simulation than a test. It shows how the operation of a simple 8 bit CPU can be modelled and simulated. To keep things simple, the CPU only supports a single Accumulator register (Accu), a 16bit ProgramCounter (PC) and can execute some simple instructions: LOD (Load Memory into Accu), STO (Store from Accu into Memory), ADD (Add Memory to Accu), JMP (Jump unconditionally) and JPZ (Jump if Accu is Zero). Its operations are comparable in complexity to that of a simple CPU like the 6502 or 6800 Chips of the early days of microcomputers.
Memory and Registers
First, we model the memory as an array of bytes and the registers as integer values and keep them in the projects top environment:
then, we need some primitive blocks to access memory and registers:
execute
|env mem addr|
env := self topEnvironment.
(env includesKey:#MEMORY) ifFalse:[
env at:#MEMORY put:(ByteArray new:16r10000).
].
mem := env at:#MEMORY.
addr := address value.
write value ifTrue:[
mem at:(addr+1) put:(dataIn value)
] ifFalse:[
dataOut value:(mem at:(addr+1))
].
Instruction Fetch
The instruction fetch phase fetches the memory location as addressed by the PC, and delivers the fetched byte as its output. Also, the PC is incremented after the fetch:
Instruction Decode
The decoder takes the fetched instruction byte and dispatches a control-signal to one of the instruction outputs:
As you can see, this is very similar to the AND-OR decoder circuit of a real digital computer's control section.
Instruction Execute
finally, we add one instruction block per decoded operation. Here, is one of the more complex instructions, the LOD. It first fetches the next two bytes from the memory at the current PC location (which has already been incremented after the instruction-fetch), stores them in a temporary register. This is the address of the loaded byte. Then, the temp-registers contents is used as address for the memory fetch. Finally, the value returned from memory is stored into the Accu to complete the instruction.
Start and Execution
The above blocks are combined in an execution action, which first loads a program into memory, then resets the CPU (simply clears the PC), and then executes instructions in an endless loop. The HALT instruction is executing a PASS block to stop the execution.
Download
Here is the project to be loaded into expecco: [CPU_Simulation.ets]
I hope you like this example - it may even serve to demonstrate to students how computers work internally. Maybe someone finds the time to enhance this example and make it simulate a real CPU, such as a 6502, 6800 or even a 8086. It would be fun to see MSDOS running on it !
Back to Examples.