ZINC: an OCaml bytecode CPU on a Nexys A7
Mark Elvers
12 min read

Categories

  • fpga
  • ocaml

Tags

  • tunbury.org

I’ve had a Digilent Nexys A7-100T sitting in its box for a while. The reason it was still in the box is that I couldn’t think of what to do with it. LED counters, VGA, UARTs, soft RISC-V cores and retro CPUs on FPGAs are all well-trodden ground. I recently enjoyed a YouTube series about building a 6502 on an FPGA, Gate by Gate, but what would I do with a 6502?

What I settled on was a CPU whose instruction set is OCaml bytecode. It’s the same fun as building a CPU from scratch, but with OCaml all the way down, as the CPU is written in Hardcaml, and there’s a ready-made reference model in ocamlrun. Twelve days later, the unmodified OCaml 5.5.2 toplevel runs on it.

The name comes from Xavier Leroy’s 1990 report The ZINC experiment: an economical implementation of the ML language. ZINC (“ZINC Is Not Caml”) introduced the abstract machine which became Caml Light’s bytecode, and ocamlrun still implements a descendant of it.

Out of the box #

The board is an XC7A100T with 63,400 LUTs, 135 block RAMs (about 600 KB), 240 DSP slices, and 128 MiB of DDR2 memory, plus the usual switches, LEDs, a 7-segment display, and a USB-UART. I connected it to the Raspberry Pi 5, which already sits on my desk, and openFPGALoader from Debian found it straight away. The Pi programs the board and talks to its UART, while bitstreams are built on an x86 machine.

The Nexys A7-100T

The Nexys A7-100T running ZINC, with the instruction count in hex on the 7-segment display

AMD’s Vivado was a pain. It wouldn’t let me sign up with my cam.ac.uk address, but then when I tried to reset the password, it wanted to send me an activation email. The download was 21 GB, even with only Artix-7 selected, and it occupies 61 GB on disk. Then, from 2026.1, it requires a node-locked licence, even for free devices, renewed yearly, and the licence tool won’t run on Ubuntu as shipped because it expects an LSB loader.

So I also tried the open-source openXC7 flow (Yosys, nextpnr and Project X-Ray). It’s 1.5 GB, builds in seconds rather than minutes, and doesn’t require an account. Digilent’s XDC file crashed nextpnr’s parser, but a couple of sed lines sorted that out.

  Vivado 2026.1 openXC7
Install 61 GB + licence 1.5 GB
Blinky build time 2 min 7 s 12.7 s
Blinky timing at 100 MHz +6.83 ns slack 242 MHz estimate

The first design was a Hardcaml LED counter, simulated with Cyclesim, then built with both toolchains. It’s blinking! The headline for Hardcaml is that it replaces the Verilog description with an OCaml one, so the tests, the simulator and the generator are all ordinary OCaml programs built with dune.

I kept both workflows throughout, with Vivado as the official timing. nextpnr’s timing estimates proved optimistic for paths through the DSP multipliers, and later, openXC7 couldn’t drive the DDR2 at all.

The ZINC machine in hardware #

The core uses 32-bit values, as on 32-bit OCaml: 31-bit tagged integers and pointers as byte addresses. Bytecode doesn’t depend on the word size, which halves the memory needed and fits in 32-bit block RAMs. The host does the loading: it reads the bytecode executable, unmarshals the initial global data with the host’s own Marshal, and lays it out again as 32-bit blocks. The hardware only ever sees a memory image.

The core itself is a multi-cycle state machine (fetch, decode, execute) written with Hardcaml’s Always DSL. Unimplemented opcodes halt the core with the opcode visible, so each new test program reports what to build next.

The key piece is lockstep checking. OCaml’s debug runtime, ocamlrund, prints the complete machine state before every instruction when run with OCAMLRUNPARAM=t=2:

##3
[00]      2  MULINT
env=0x5f090bbd9628=block<T0/s0>
accu=0x5=long2
 sp=0x5f0946c87a88 @1:
[1] 0x7=long3

The test harness loads the same image into the simulated memories and compares each step against this trace: pc, opcode, accu, env, stack depth, and every stack slot, with pointers compared by tag and size rather than by address. Adding a test is just adding a .ml file. The checker earned its keep straight away. In an early test program, 100 - 58 loads 100 with CONSTINT, whose operand is stored untagged (accu = Val_int(*pc)). The core put it into accu as-is, and on the very next step, the checker read the even value 100 as a pointer.

Onto the board #

The board design wraps the core with a UART loader that uses fixed 9-byte packets to write code and data, start the core, and read back the status. The 7-segment display shows the instruction count, and the LEDs show the current opcode. The host side of the protocol was tested end-to-end in simulation by bit-banging the UART before it touched the hardware. On the board, every program produced the same results as the simulation, with identical instruction and cycle counts.

The first build with real logic depth failed timing at 100 MHz by 5.7 ns, through two cascaded DSP48s for MULINT. After four rounds of pipelining and restructuring, the critical path was dominated by routing, as the data RAM address fans out to 64 block RAMs. With the core about to grow significantly, I clocked it at 50 MHz instead, leaving 4 ns of slack.

Then, in roughly the order the test programs needed them:

  • Functions: closures, APPLY, tail calls with APPTERM, and partial application through GRAB and RESTART. Rather than write states for each, the core has one reusable micro-sequence: copy n words up or down the stack, write up to four words, then fetch, jump or return.
  • Exceptions, SWITCH, a divider, mutable fields, arrays, strings and mutual recursion with infix closures.
  • A garbage collector: a copying Cheney collector over two semispaces, as its work queue is the destination semispace itself, so it needs no other memory. Every allocating instruction checks that the block fits; if it doesn’t, the core collects and then re-executes the same instruction. At that point nothing has changed state, so the only roots are accu, env, the globals and the stack. A stress test allocating 20 semispaces’ worth ran 4.2 million instructions with 21 collections in 0.32 s.

The real standard library #

All of that was with test programs compiled with -nopervasives -nostdlib, declaring primitives directly. Compiling ordinary programs against the standard library showed that the opcodes weren’t the problem. Instead, it was code size (Printf brings in all of CamlinternalFormat, 51K words), primitives, and the reference itself. Sys initialises from caml_sys_const_word_size, so the 64-bit ocamlrund diverges almost immediately from a 32-bit core.

I built OCaml 5.5.2’s runtime for i686, bytecode only and statically linked. That needed one workaround, as glibc 2.39’s 32-bit static libm only exports fmod as a compat symbol. All of the existing tests passed unchanged against the 32-bit traces.

Along the way, I found two bugs in ocamlrund’s trace printing. It segfaults when a stack slot holds an infix pointer, because caml_trace_value_file treats the infix header’s offset as a field count and reads past the end of the closure. And on 32-bit, it prints a float array as one double per word.

C primitives which aren’t in hardware become host calls. The core reserves some heap, then waits while the Pi reads the arguments over the UART, runs the primitive in OCaml against the board’s memory, and resumes the core with the result. One mechanism covers all of I/O and Sys, and output appears in the terminal. caml_hash and caml_compare were ported from the C runtime, and the Hashtbl test prints its keys in exactly the same order as ocamlrun, so the hash agrees bit for bit.

$ zinc run _build/default/test/programs/hello.byte
Hello, ZINC!
[zinc] loaded 3767 words and ran in 5.11s with 19 host calls
[zinc] halted after 428 instructions in 2355 cycles, 0 garbage collections

That’s print_endline "Hello, ZINC!" compiled normally with the standard library. It works, but host calls cost 90-160 ms each, as every memory word is a separate round trip through ssh, socat and USB. A list-heavy test took 322 s. Most of the next few days went into making that faster:

  • the hot primitives (array get/set, integer compare, string length) in hardware, which took the lists test from 3,546 host calls to 54, and from 322 s to 9 s;
  • the UART at 2 Mbaud (exactly 25 clocks per bit at 50 MHz);
  • block reads in the protocol, and the FTDI latency timer turned down from 16 ms to 1 ms;
  • the host side running on the Pi itself, rather than over ssh, which took a host call from about 70 ms to 3-4 ms;
  • caml_hash and caml_compare as micro-sequences in hardware, with anything rare, such as closures or a very deep structure, restarting as a host call.

The Hashtbl test went from 183 s to 3.73 s.

Is it faster than the CPU? #

No, of course not! On the same bytecode, fib 30 takes 1.94 s on the FPGA, against 0.045 s for the 32-bit ocamlrun on a Xeon E5-2640 v4, about 40-60 times slower. Per clock, though, the two are close: the core averages about 4.5 cycles per bytecode instruction and ocamlrun about 5. The gap is the 50 MHz clock. Pipelining and a faster clock might give 5-10x, which still wouldn’t catch a Xeon, but the board uses a watt or two.

Calling it done #

This had been fun, but practically, we needed a target whereby we could call the project complete. As it stood, we couldn’t claim feature completeness, nor did we have a flashy demo to show. So the plan was: run OCaml’s own test suite, implement the remaining opcodes, then investigate the DDR memory. If DDR looked tricky, the fallback was a standalone demo booting from flash; if it looked reasonable, we’d try for the toplevel.

The conformance harness takes the 215 single-file tests from OCaml 5.5.2’s test suite, runs each on the 32-bit ocamlrun and on the board, and compares stdout and the exit status. The first run passed 65. Adding missing host primitives brought it to 106.

Then came the last opcodes. OCaml 5’s effect handlers run each handled computation on its own stack, a fiber, and switch stacks on PERFORM, RESUME and return. The core transcribes interp.c, with eight fiber slots of 512 words, each ending in a record shaped like the runtime’s struct stack_info, and the collector scans every live stack. Objects needed GETMETHOD and a binary search of the method table for GETPUBMET. With those, every opcode ocamlc emits is implemented, except the debugger’s EVENT and BREAK, and the effects test matches ocamlrund over 47,091 instructions.

The final score was 142 of 215. Of the rest, 31 need primitives this machine doesn’t aim to provide (files, domains, weak pointers, marshalling to strings), 21 run out of memory with two 12K-word semispaces, 13 hit the time limit (mostly Int64 arithmetic, where every operation is a host call), and two effects tests need more than eight fibers alive at once.

DDR2 #

The 128 MiB of DDR2 would fix most of those, and it’s what the toplevel would need: 803K words of code, eight times the code memory, and a heap of megabytes for type-checking. Xilinx’s memory controller would tie the design to Vivado, so I used LiteDRAM instead, generated as a standalone Verilog core without LiteX’s usual soft CPU. Normally, that CPU runs the DRAM initialisation and read levelling from LiteX’s BIOS, so instead the Pi does it over the UART: a page of OCaml which tries each of 8 bitslips and 32 delay taps on both byte lanes and picks the middle of the widest working window.

bitslip 2: 11111111111100000000000000000000
bitslip 3: 00000000000000111111111111111111
-> bitslip 3, delay 23 (window 14..31)

It worked the first time under Vivado, with 32,768 words spread across all 128 MiB written and read back with no errors. openXC7 built the same design, but no read ever came back right. nextpnr warns that it ignores INTERNAL_VREF, which the SSTL18 inputs need, so I didn’t pursue it.

The toplevel #

To run from DDR2, the core needed to be able to wait. Every state assumed that memory answers the next cycle, so the core no longer owns its memories. It issues requests and has a stall input that freezes all registers. In front of the DDR2 are write-back, direct-mapped caches for code and data in block RAM, and a bridge into LiteDRAM’s 75 MHz clock domain. All of the traced programs still matched in lockstep with tiny 16-line caches and constant misses, and hello world ran from DDR2.

Then the toplevel’s own needs, primitive by primitive: files and channels on the Pi’s file system, so it can read the standard library’s .cmi files; an unmarshaller building directly into the board’s heap for input_value; ocamlyacc and ocamllex’s automata ported from the C runtime; and caml_reify_bytecode. The toplevel compiles each phrase into bytecode in a Bigarray, and the host copies it into code memory after the program, returning a closure.

The first attempt printed - : int = 0 for 1 + 2;;. Bigarray.Array1.sub was a copy rather than a view, and the bytecode emitter grows its buffer with blit (sub src 0 n) (sub dst 0 n), so every phrase after the first buffer growth compiled to zeros. With subs as proper views:

        OCaml version 5.5.2
Enter #help;; for help.

# - : int = 3
# val fib : int -> int = <fun>
# - : int = 6765

Every phrase is lexed, parsed, type-checked and compiled to bytecode by the compiler running on the ZINC core, and then run there. Here it is working through the example from the ocaml.org homepage.

Making the toplevel quick #

That session took 268 s, almost all of it host calls: 40,305 of them. Moving string and bytes access, blits and copies into hardware, plus a command which returns the status and the top of the stack in one round trip, brought it down to 154 s.

For a while, the profile was misleading. It said the core and waiting took 100 s, but counting the core’s own cycles showed it ran for 0.6 s. Counting the bytes sent per primitive found 18.6 MB sent by caml_dynlink_get_bytecode_sections. A host call which runs out of heap asks the core to retry with what the failing allocation needs, so a call which allocates in several steps failed once per step: 958 retries, each rewriting 19 KB. With retries doubling the reservation, the session takes 31 s.

Toplevel session times

The same four-phrase toplevel session through each round of changes

About 22 s of that is loading 4.5 MB of code and data over the 2 Mbaud UART. The toplevel’s startup and four phrases take about 9 s, of which the core runs for 1 s. Timing at 50 MHz is met by 0.016 ns, which is uncomfortably close.

Where it is now #

The design uses about 20K LUTs (31%) and 70 block RAMs. What’s left:

  • Faster loading: a faster link, or keeping the toplevel resident between runs.
  • Weak references and ephemerons are held strongly, finalisers never run, and fiber stacks are a fixed size.
  • The DDR2 build needs Vivado.
  • Report the two ocamlrund trace bugs upstream.

The code is available on GitHub mtelvers/zinc-fpga.