Architecture
Compiler Architecture
How rg-cc compiles C99 into 680x0 machine code, from preprocessing and SSA passes to VMIR, register allocation, and direct binary emission.
Architectural Overview
rg-cc is an optimising C99 compiler built specifically for the Motorola 680x0. Generic compilers (such as GCC or LLVM) lower C into a 32-bit, load-store, uniform-register RISC IR and only discover the 68000 at the very end, leaving late peepholes to clean up 32-bit sign extensions, scratch register moves, and missed CISC addressing modes.
rg-cc pushes 68000 architectural knowledge up into SSA, VMIR, and register allocation:
- 68k-native widths: Keeps arithmetic in 8 and 16 bits instead of blindly widening to 32 bits, avoiding 140-cycle 32-bit soft-multiplies and slow
divu.winstructions. - CISC addressing before regalloc: Forms
(An)+,-(An),d8(An,Dn), and direct memory-to-memory moves in VMIR before registers are assigned, so those addresses never occupy a register or cause spills. - Split
Dn/Anawareness: Spills short-lived values across calls onto-(sp)to avoid callee-savedmovem.lprologues, shrink-wraps early returns to barerts, and omits frame pointers soA5stays free. - One in-memory toolchain: Embeds
rg-asm,rg-ar, andrg-linkin the same binary, writing ELF objects or Atari.PRG/.TOSexecutables straight from memory with no text-assembly round-trips.
.c)
Expands macros and #include files, then breaks C source into tokens.
Checks C99 types and syntax, evaluates constants, and builds a syntax tree.
Converts the tree into single-assignment blocks and applies the calling convention.
Folds constants, drops dead code, simplifies loops, and inlines small functions.
Picks 68k instructions and addressing modes while values still use virtual registers.
Assigns virtual variables to physical Dn, An, and FPU registers, or spills them to the stack.
Narrows bit widths, trims redundant instructions, and schedules ops for the target CPU.
Writes ELF objects (.o), Atari executables (.PRG/.TOS), or .s assembly.
Compiler Pipeline
Layer 1: Preprocessor
Before any C grammar rules run, the preprocessor expands #include files and #define macros, and the lexer splits the text into tokens (keywords, identifiers, numbers, and punctuation).
rg-cc slices source files into zero-copy token spans without allocating heap strings for identifiers or literals. The C99 preprocessor handles variadic macros (__VA_ARGS__), stringification (#), token pasting (##), #if expressions, and built-in Atari headers. Dialect flags switch between C89, C99, and a C11 subset, plus compatibility extensions for older Atari C compilers (such as Pure C, VBCC, and Lattice C).
Layer 2: Parser (AST)
An Abstract Syntax Tree (AST) is a tree representing the structure of your C code (functions, statements, expressions, and types) with macro and whitespace syntax gone.
A recursive-descent parser builds a typed AST while checking C99 semantics (including _Bool, designated initialisers, and VLAs). It evaluates constant expressions at compile time, lays out structs and unions to match the target ABI, and rejects recursive by-value aggregates cleanly.
Layer 3: SSA Lowering
Static Single Assignment (SSA) is an intermediate form where every variable is assigned only once. When two branches merge (such as after an if/else), a phi node selects which version of a variable to use depending on which path ran.
rg-cc lowers the AST into typed SSA basic blocks with minimal phi placement. Boolean conditions in if, while, and for lower directly to short-circuit branches rather than materialising temporary 0/1 values. Calls lower to the active ABI: fastcall (default, passing up to two ints in D0–D1 and two pointers in A0–A1), cdecl (stack-passed), or __interrupt (saving all clobbered registers and ending with rte).
Layer 4: SSA Optimisations
Because every SSA value has a single definition, the compiler can trace data flow and simplify code without guessing which variable writes alias each other. Alongside standard scalar and loop passes, rg-cc runs 68000-specific transforms high up in SSA before instruction selection:
- Constants & dead code: Propagates constants and value ranges, folds read-only globals and pure zero-arg functions, removes duplicate expressions (Global Value Numbering), and strips unreachable blocks and dead stores.
- 68k arithmetic & switches: Decomposes constant multiplies into NAF shift-add sequences (beating 40-cycle
muls.w), turns constant divides into fixed-point reciprocals (replacing 140-cycledivu.w), folds(x / C) == Kinto a single range check, and lowers dense affine switches into arithmetic instead of jump tables. - Loops & structs: Hoists loop invariants, turns array-index multiplies into pointer increments, splits non-escaping local structs into scalar SSA registers (Scalar Replacement of Aggregates), and unrolls hot loops within a code-size budget.
- Calls & control flow: Inlines small functions (and cross-file calls under
--lto), turns tail calls into loops, devirtualises constant function pointers, and collapses{0, 1}boolean phi diamonds directly into branches.
Layer 5: VMIR
Virtual Machine IR (VMIR) sits between abstract SSA and final 68000 machine code: instructions already match real 68k ops and addressing modes, but still use unlimited virtual registers. This is where rg-cc differs most from RISC-first compilers.
Because the 68000 only has 8 data and 7 usable address registers, forming CISC patterns before register allocation is critical. Folding a single-use load into an ALU operand (add.l _g,d0) or a direct memory-to-memory move (move.w (a1)+,(a0)+) removes the temporary virtual register from the interference graph completely. VMIR also turns sequential struct writes into streaming (a0)+ stores, spills short-lived values across calls onto -(sp) so shallow functions avoid callee-saved movem prologues, and shrink-wraps early-return guard checks to exit with a bare rts.
Layer 6: Register Allocation
Graph colouring treats register assignment like colouring a map: any two variables live at the same time cannot share a physical register, and anything that doesn't fit spills to the stack.
Unlike RISC CPUs with one uniform register pool, the 68000 splits Data (Dn) and Address (An) registers with asymmetric rules (shifts and bitwise ops require Dn; pointer dereferences require An). rg-cc uses a Chaitin-Briggs graph-colouring allocator tuned for both banks, coalescing copies and falling back to a linear-time pass for huge generated functions. Under -msmall-data, A6 is reserved for a 64 KB global base so globals use 4-byte d16(a6) instead of 6-byte 32-bit absolutes, while frame-pointer omission frees A5 for general allocation.
| Bank | Registers | Notes |
|---|---|---|
| Data | D0–D7 |
ALU, shifts, logic, conditions (D0–D1 scratch) |
| Address | A0–A6 |
A7 is SP; A6 reserved in Small Data mode; A5 optional frame pointer |
| FPU | FP0–FP7 |
Used with 68881/68882 or on-chip 68040/68060 FPUs |
Layer 7: Machine Passes
Once physical registers are assigned, machine passes clean up the 68k instruction stream. Bit-width dataflow tracks known-zero and sign-extended registers to drop redundant ext.w/ext.l instructions and narrow 32-bit multiplies to 16-bit muls.w/mulu.w where inputs fit.
A peephole pass scans a small sliding window of adjacent instructions for wasteful patterns: reusing condition codes set by prior instructions (dropping redundant tst), threading branches, rotating counted loops into dbra, shrinking prologue/epilogue movem masks to only clobbered registers, and omitting link/unlk when stack offsets can use (sp) directly. On 68020–68060 targets, an instruction scheduler reorders independent ops to avoid pipeline stalls.
Layer 8: Binary Emission
By default, rg-cc encodes machine instructions straight to bytes in memory rather than writing text assembly and spawning an external assembler. Depending on the flags, it emits one of three outputs:
| Output | Trigger | Details |
|---|---|---|
ELF32 object (.o) |
-c |
Standard 68k relocations and DWARF 4 debug info (-g); compatible with rg-link, vlink, and vasm |
Atari executable (.PRG / .TOS) |
Default (no -c) |
Linked in memory via rg-link-core with GEMDOS $601A header, relocation table, and DRI/GST symbols |
Assembly text (.s) |
-S / --emit-asm |
Motorola-syntax assembly compatible with rg-asm and vasm |
Optimisation Passes
For side-by-side C and 68000 assembly listings, cycle counts, NAF shift-add multiplies, and reciprocal division examples, see Compiler Optimisations.
Folds constants, drops dead code and unused stores, splits local structs, and turns tail calls into loops.
Moves invariant work out of loops, turns array multiplies into pointer steps, and emits dbra countdowns.
Replaces divides with multiplies, keeps math in 8/16 bits, and folds memory reads into 68k instructions.
Target Architecture
Instruction selection and scheduling adapt to the target CPU:
| Feature / Architecture | MC68000 / MC68010 | MC68020 / MC68030 | MC68040 / MC68060 |
|---|---|---|---|
| Integer Multiplication | 16-bit (muls.w / mulu.w) + NAF chains |
Full 32-bit (muls.l, mulu.l) |
Single-cycle 32-bit hardware multiplier |
| Integer Division | 16-bit hardware + magic reciprocals | Full 32-bit (divs.l, divu.l) |
Pipelined 32-bit hardware divider |
| Addressing Modes | d16(An), d8(An,Dn), (An)+, -(An) |
Scaled (An,Dn*scale), full 32-bit displacements |
Full 68020 modes with optimised cache access |
| Bitfield Operations | Synthesised boolean logic (and, or, lsl) |
Hardware bfextu, bfins, bftst, bfclr |
Integrated hardware bitfield execution unit |
| Floating-Point Math | Fast IEEE 754 software runtime helpers | Software float or MC68881 / MC68882 coprocessor | Integrated high-speed on-chip FPU |
| Pipeline & Cache | Prefetch queue timing optimisation | Instruction cache burst alignment & loop mode | Superscalar dual-issue instruction scheduling |
Determinism
Compiler maps and symbol tables use fixed-seed deterministic hashing, so building the same source tree on Linux, macOS, or Windows produces bit-identical binaries. Multi-file builds compile translation units in parallel across host CPU cores, and Link-Time Optimisation (--lto) merges all .c files into one SSA graph before optimising so the compiler can inline and share registers across file boundaries.