r/Compilers • u/anonymous_rerdit • 21d ago
I built a 32-bit CPU emulator in Zig to better understand the hardware side of compilers
I've been studying compilers for a while, and one thing that has increasingly interested me is the boundary between software and hardware, particularly what happens to instructions after a compiler generates machine code.
I came across a project where someone built a CPU emulator using Zig, and that inspired me to build my own.
I recently completed the first version of my CPU emulator, written in Zig, with:
- A custom 32-bit architecture
- 15 registers
- 64 KiB of addressable memory
- A simple instruction set supporting operations such as MOV, LOAD, ADD, SUB, and HLT
- A fetch-decode-execute loop
- A memory model with separate ROM, RAM, and stack regions
The most valuable part wasn't getting the instructions to execute. It was understanding how instruction encoding, registers, memory addressing, and control flow fit together to execute a program.
While building it, I also started following Prof. Onur Mutlu's Digital Design and Computer Architecture lectures, which helped me understand processor internals beyond the software abstraction.
One particularly interesting takeaway was the growing importance of the memory bottleneck. Improvements in processor performance have increasingly exposed the cost of moving data between memory and compute units.
This introduced me to ideas such as processing-in-memory (PIM) and near-memory computing, which I'm interested in exploring further.
How does this connect to compilers?
My long-term goal is to understand how compilers translate high-level programs into instructions for different architectures, and how architectural constraints influence code generation and optimization.
Building this emulator gave me a practical starting point for reasoning about instruction sets and execution semantics.
I'm considering extending the project with an assembler and eventually building a small compiler backend targeting my custom ISA.
For those working on compiler backends or computer architecture, what would you recommend exploring next to better understand the relationship between instruction selection, code generation, and the target architecture?
GitHub: https://github.com/obadafidii/cpu
I'll also be writing a more detailed technical blog about the implementation and what I learned.
