Optimisation Deep Dive
Compiler Optimisations
How rg-cc turns C into tight 68000 code, from SSA and VMIR passes down to machine peepholes. Because 16-bit and 8-bit ops run twice as fast as 32-bit ones on the 68000, the optimiser keeps arithmetic narrow wherever C's rules allow.
High-Level Pipeline Optimisations
These passes transform SSA and VMIR before register allocation.
Scalar Replacement of Aggregates (SROA & mem2reg)
In C, declaring local structures typically forces compilers to allocate activation stack space and generate pointer arithmetic for every field access. In Layer 4, rg-cc identifies non-escaping aggregate local variables and decomposes them into independent 16-bit scalar values promoted directly into SSA registers:
// C source
struct Vec2D {
int16_t x;
int16_t y;
};
int32_t step_and_dist_sq(int16_t x, int16_t y) {
struct Vec2D pos;
pos.x = x;
pos.y = y;
return (int32_t)pos.x * pos.x + (int32_t)pos.y * pos.y;
}
Without optimisation (stack-allocated aggregate):
_step_and_dist_sq_naive:
link a5,#-4 ; 16 cycles: allocate 4-byte stack frame for struct Vec2D
move.w d0,-4(a5) ; 12 cycles: store pos.x to stack
move.w d1,-2(a5) ; 12 cycles: store pos.y to stack
move.w -4(a5),d0 ; 12 cycles: reload pos.x from stack
muls.w d0,d0 ; ~40 cycles: (int32_t)pos.x * pos.x
move.w -2(a5),d1 ; 12 cycles: reload pos.y from stack
muls.w d1,d1 ; ~40 cycles: (int32_t)pos.y * pos.y
add.l d1,d0 ; 8 cycles: sum 32-bit squares
unlk a5 ; 12 cycles: tear down stack frame
rts ; 16 cycles
; Heavy stack traffic: 6 memory operations just to manage a 4-byte local struct
With rg-cc SROA & mem2reg:
_step_and_dist_sq_opt:
; Stack frame eliminated completely; struct fields live directly in registers d0 and d1
muls.w d0,d0 ; ~40 cycles: (int32_t)pos.x * pos.x
muls.w d1,d1 ; ~40 cycles: (int32_t)pos.y * pos.y
add.l d1,d0 ; 8 cycles: sum 32-bit squares
rts ; 16 cycles
; Zero memory reads, zero memory writes, zero stack frame overhead
Dense Affine Switch Lowering
When switch statements return values that form an arithmetic progression relative to a 16-bit selector, rg-cc recognises the affine pattern (base + stride * selector) and lowers the switch into branchless closed-form arithmetic with no jump tables, bounds checks, or indirect jumps:
// C source
int16_t get_tile_offset(int16_t tile_index) {
switch (tile_index) {
case 0: return 0;
case 1: return 40;
case 2: return 80;
case 3: return 120;
default: return 0;
}
}
Without optimisation (standard jump table):
_get_tile_offset_table:
cmpi.w #3,d0 ; 8 cycles: check range bounds
bhi.s .Ldefault ; 8/10 cycles
add.w d0,d0 ; 4 cycles: word index to byte offset
move.w .Ljt(pc,d0.w),d0 ; 14 cycles: load jump target offset
jmp .Ljt(pc,d0.w) ; 14 cycles: indirect branch
.Ljt:
dc.w .Lcase0-.Ljt
dc.w .Lcase1-.Ljt
dc.w .Lcase2-.Ljt
dc.w .Lcase3-.Ljt
.Lcase0: clr.w d0; rts
.Lcase1: moveq #40,d0; rts
.Lcase2: moveq #80,d0; rts
.Lcase3: move.w #120,d0; rts
.Ldefault: clr.w d0; rts
With rg-cc affine switch elimination:
_get_tile_offset_opt:
cmpi.w #3,d0 ; 8 cycles: bounds check
bhi.s .Ldefault ; 8/10 cycles
move.w d0,d1 ; 4 cycles
lsl.w #5,d0 ; 16 cycles: tile * 32
lsl.w #3,d1 ; 12 cycles: tile * 8
add.w d1,d0 ; 4 cycles: (tile * 32) + (tile * 8) = tile * 40
rts ; 16 cycles
.Ldefault:
clr.w d0 ; 4 cycles: return 0
rts
; Memory footprint reduced from 38 bytes to 18 bytes; zero table lookups
Boolean Branch Fusion
In C, evaluating conditions like int16_t hit = (x1 == x2) ? 1 : 0; typically causes naive compilers to emit conditional branch diamonds (three basic blocks, jumps around 0 and 1, and join phi nodes). When the resulting boolean is immediately tested in an if statement, standard compilers emit a second branch and redundant tst instruction.
rg-cc's bool_select_fold pass matches {0, 1} phi diamonds in the SSA graph and collapses them. If the result feeds a branch, it fuses the original comparison directly into the branch with no intermediate boolean materialisation, diamond blocks, or redundant test:
// C source
extern void trigger_event(void);
int16_t check_trigger(int16_t x, int16_t target) {
int16_t active = (x == target) ? 1 : 0;
if (active) {
trigger_event();
return 1;
}
return 0;
}
Without optimisation (conditional diamond + redundant test):
_check_trigger_naive:
; Block 1: Evaluate condition
cmp.w d1,d0 ; 4 cycles: compare x and target
bne.s .Lset_zero ; 8/10 cycles
; Block 2: True arm
moveq #1,d2 ; 4 cycles: active = 1
bra.s .Ljoin ; 10 cycles
.Lset_zero:
; Block 3: False arm
moveq #0,d2 ; 4 cycles: active = 0
.Ljoin:
; Block 4: Test boolean flag and branch again!
tst.w d2 ; 4 cycles: redundant test
beq.s .Lexit ; 8/10 cycles
jsr _trigger_event ; call subroutine
moveq #1,d0 ; 4 cycles
rts
.Lexit:
moveq #0,d0 ; 4 cycles
rts
; Requires 3 branches, 4 basic blocks, and register d2 clobbered
With rg-cc branch fusion (bool_select_fold):
_check_trigger_fused:
; Diamond and boolean materialisation collapsed into single direct branch
cmp.w d1,d0 ; 4 cycles: compare x and target
bne.s .Lexit ; 8/10 cycles: branches directly on original condition!
jsr _trigger_event ; call subroutine
moveq #1,d0 ; 4 cycles
rts
.Lexit:
moveq #0,d0 ; 4 cycles
rts
; 2 branches, 1 join, and 22+ clock cycles eliminated; zero scratch registers wasted
When a boolean value must be materialised into an 8-bit storage variable or return value rather than branching, rg-cc avoids branch diamonds by using Scc + neg.b directly in place:
// C source
uint8_t is_grounded(int16_t y) {
return y >= 200;
}
Without optimisation (branchy control-flow diamond):
_is_grounded_naive:
cmpi.w #200,d0 ; 8 cycles: compare y with 200
blt.s .Lfalse ; 8/10 cycles: branch if y < 200
moveq #1,d0 ; 4 cycles: true arm (1)
bra.s .Ldone ; 10 cycles: jump over false arm
.Lfalse:
moveq #0,d0 ; 4 cycles: false arm (0)
.Ldone:
rts ; 16 cycles
; 22-30 cycle body, 12 bytes, 2 conditional/unconditional branches
With rg-cc branchless materialisation (Scc + neg.b):
_is_grounded_branchless:
cmpi.w #200,d0 ; 8 cycles: compare y with 200
sge d0 ; 4/6 cycles: set d0.b = $FF if true, $00 if false
neg.b d0 ; 4 cycles: negate byte ($FF -> 1, $00 -> 0)
rts ; 16 cycles
; Compact 8 bytes, deterministic 16-18 cycle body, zero conditional jumps
Streaming Store Synthesis (VMIR)
When updating adjacent 16-bit structure fields or array entries, naive compilers emit sequential displacement stores (move.w d0,0(a0), move.w d1,2(a0)). During Virtual Machine IR lowering (vmir_memfold), rg-cc identifies sequential stores to the same base address and synthesises streaming post-increment writes:
// C source
struct Sprite16 {
int16_t x;
int16_t y;
uint16_t pattern;
};
void set_sprite(struct Sprite16 *s, int16_t x, int16_t y, uint16_t pattern) {
s->x = x;
s->y = y;
s->pattern = pattern;
}
Without optimisation (displacement addressing):
_set_sprite_displacement:
move.w d0,0(a0) ; 12 cycles: store x (displacement mode)
move.w d1,2(a0) ; 12 cycles: store y
move.w 6(sp),4(a0) ; 20 cycles: store pattern low word from stack (3rd int arg)
rts
; Total stores: 44 cycles, 14 bytes of code
With rg-cc streaming store synthesis:
_set_sprite_streaming:
move.w d0,(a0)+ ; 8 cycles: store x and advance pointer
move.w d1,(a0)+ ; 8 cycles: store y and advance pointer
move.w 6(sp),(a0) ; 16 cycles: store pattern low word from stack (3rd int arg)
rts
; Total stores: 32 cycles, 8 bytes of code (27% faster, 43% smaller)
Memory-Operand Folding
In RISC compilers, every memory value must be loaded into a register before operating on it. The 68000 supports ALU instructions with memory sources as well as direct memory-to-memory moves. rg-cc folds single-use memory loads into consumer instructions before register allocation, preventing temporary virtual registers from entering the interference graph:
// C source
extern uint16_t active_palette_mask;
uint16_t apply_palette(uint16_t colour) {
return colour & active_palette_mask;
}
void copy_pixel_plane(uint16_t *dst, const uint16_t *src) {
*dst = *src;
}
Without folding (register-bound load/store):
move.w _active_palette_mask,d1 ; 16 cycles: load global to register d1
and.w d1,d0 ; 4 cycles: perform 16-bit AND in register
; Allocates 2 data registers (d0, d1)
move.w (a1),d0 ; 8 cycles: load into d0
move.w d0,(a0) ; 8 cycles: store from d0
With rg-cc memory-operand folding:
and.w _active_palette_mask,d0 ; 16 cycles: memory-source AND in a single instruction
; Only 1 register needed (d0); register pressure reduced
move.w (a1)+,(a0)+ ; 12 cycles: direct memory-to-memory move
; Zero data registers consumed; 25% faster and avoids register spilling
Scratch Stack Spills
When multiple variables stay live across a function call, standard register allocators assign them to callee-saved registers (such as D3–D5), which forces multi-register movem.l saves in the prologue and restores in the epilogue. In vmir_memfold, rg-cc spills those live arguments to -(sp) around the call and pops them with (sp)+ so shallow functions stay in caller-saved scratch registers without movem:
// C source
extern void play_sound_effect(int16_t sound_id);
int16_t update_hazard(int16_t player_x, int16_t sound_id) {
play_sound_effect(sound_id);
return player_x + 16;
}
Without optimisation (callee-saved multi-register MOVEM allocation):
_update_hazard_callee_saved:
move.l d3,-(sp) ; 12 cycles: save callee-saved register d3
move.w d0,d3 ; 4 cycles: home player_x in callee-saved d3
move.w d1,d0 ; 4 cycles: setup sound_id in d0 (fastcall arg 1)
jsr _play_sound_effect
move.w d3,d0 ; 4 cycles: retrieve player_x
addq.w #16,d0 ; 4 cycles: + 16
move.l (sp)+,d3 ; 12 cycles: restore d3
rts ; 16 cycles
; 24 clock cycles spent saving and restoring callee-saved D3 across call
With rg-cc call-crossing stack spill:
_update_hazard_scratch:
move.w d0,-(sp) ; 8 cycles: push player_x to stack
move.w d1,d0 ; 4 cycles: setup sound_id in d0 (fastcall arg 1)
jsr _play_sound_effect
move.w (sp)+,d0 ; 8 cycles: pop player_x directly into return register d0
addq.w #16,d0 ; 4 cycles: + 16
rts ; 16 cycles
; Zero MOVEM instructions; D3 untouched; 8 clock cycles saved
Machine Peepholes
Layer 7 passes operate directly on physical 68000 machine instructions. They exploit condition code side effects, algebraic identities, instruction pipeline peculiarities, and target hardware timings.
NAF Shift-Add Constant Multiplication
On the 68000, 16-bit multiplication (muls.w / mulu.w) takes 38 to 54 cycles, and 32-bit multiplication calls a ~140-cycle helper. When multiplying by a constant, rg-cc decomposes the factor into shifts and adds/subtracts using Canonical Signed Digit (CSD) / Non-Adjacent Form (NAF) when that beats the multiply instruction:
uint16_t mul40(uint16_t x) {
return x * 40;
}
Without optimisation (hardware multiply):
_mul40_naive:
mulu.w #40,d0 ; ~46 cycles: 16x16 hardware multiply
rts ; 16 cycles
With rg-cc NAF shift-add decomposition:
_mul40:
; Decomposed into (x * 32) + (x * 8)
move.w d0,d1 ; 4 cycles: copy x
lsl.w #5,d0 ; 16 cycles: x << 5 (x * 32)
lsl.w #3,d1 ; 12 cycles: x << 3 (x * 8)
add.w d1,d0 ; 4 cycles: (x * 32) + (x * 8) = x * 40
rts ; 16 cycles
; Total body: 36 cycles (faster than hardware MULU.W at 42-46 cycles)
Constant Division via Fixed-Point Reciprocals
Hardware integer division (divu.w / divs.w) is one of the slowest instructions on the 68000, taking up to 140 clock cycles. For divisions by compile-time constants, rg-cc multiplies by precomputed fixed-point reciprocals, replacing the hardware division with a fast 16-bit multiplication and shift:
// C source
uint16_t div_by_10(uint16_t n) {
return n / 10;
}
Without optimisation (hardware division):
_div_by_10_naive:
andi.l #$FFFF,d0 ; 16 cycles: zero-extend 16-bit dividend to 32-bit for DIVU.W
divu.w #10,d0 ; ~140 cycles: hardware 32/16 unsigned division
rts ; 16 cycles
With rg-cc reciprocal multiplication:
_div_by_10:
; Reciprocal factor $CCCD = 52429 = 2^19 / 10
mulu.w #$CCCD,d0 ; ~46 cycles: 16x16->32-bit product (n * 52429)
swap d0 ; 4 cycles: d0.w = (n * 52429) >> 16
lsr.w #3,d0 ; 10 cycles: (n * 52429) >> 19
rts ; 16 cycles
; Total: ~60 clock cycles — more than 2.5x faster than hardware DIVU.W (~156 cycles)
Unsigned Divide-Equality Folding
When an expression checks whether an integer division equals a specific constant, rg-cc completely eliminates the division, transforming it into a single 16-bit subtraction and range check:
// C source
int16_t is_speed_tier_three(uint16_t speed) {
return (speed / 10) == 3;
}
Without optimisation (hardware division + compare):
_is_speed_tier_three_naive:
andi.l #$FFFF,d0 ; 16 cycles: zero-extend 16-bit dividend to 32-bit
divu.w #10,d0 ; ~140 cycles: hardware division (speed / 10)
cmpi.w #3,d0 ; 8 cycles: compare quotient with 3
beq.s .Lmatch ; 8/10 cycles
clr.w d0 ; 4 cycles: return 0
rts
.Lmatch:
moveq #1,d0 ; 4 cycles: return 1
rts
With rg-cc unsigned divide-equality folding:
_is_speed_tier_three:
; Mathematical reduction: (speed / 10) == 3 is identical to unsigned (speed - 30) < 10
subi.w #30,d0 ; 8 cycles: bias input by (3 * 10)
cmpi.w #10,d0 ; 8 cycles: check if within bucket range < 10
blo.s .Lmatch ; 10/8 cycles: branch if unsigned lower
clr.w d0 ; 4 cycles: return 0
rts
.Lmatch:
moveq #1,d0 ; 4 cycles: return 1
rts
; Complete division routine eliminated entirely in 30 clock cycles
Known-Width Narrowing
C integer promotion rules require expanding char and short to 32-bit int during arithmetic. rg-cc's mi_knownwidth dataflow pass tracks known-zero and sign-extended bit widths across physical registers to drop unnecessary ext.w, ext.l, and masking instructions:
// C source
uint8_t add_bytes(uint8_t a, uint8_t b) {
return (uint8_t)(a + b);
}
Without optimisation (standard 32-bit promotion):
andi.l #$FF,d0 ; 16 cycles: zero-extend byte a
andi.l #$FF,d1 ; 16 cycles: zero-extend byte b
add.l d1,d0 ; 8 cycles: 32-bit addition
andi.l #$FF,d0 ; 16 cycles: truncate back to byte
rts
With rg-cc known-width narrowing:
add.b d1,d0 ; 4 cycles: direct 8-bit native addition
rts ; 16 cycles
; Saved: 52 clock cycles and 14 bytes of code
Hardware Countdown Loops (dbra)
The 68000 provides the single-instruction loop primitive dbra Dn, label (also named dbf), which decrements a 16-bit register and branches if not -1. rg-cc rotates while- and for-loops into countdown structures terminating with dbra:
// C source
void clear_scanline(uint16_t *line, int16_t word_count) {
for (int16_t i = 0; i < word_count; ++i) {
*line++ = 0;
}
}
Without optimisation (upward induction variable + compare):
_clear_scanline_naive:
clr.w d1 ; 4 cycles: i = 0
bra.s .Lcheck ; 10 cycles
.Lloop:
clr.w (a0)+ ; 12 cycles: *line++ = 0 (68000 CLR performs a read+write)
addq.w #1,d1 ; 4 cycles: ++i
.Lcheck:
cmp.w d0,d1 ; 4 cycles: i < word_count
blt.s .Lloop ; 10 cycles: 18 cycles loop control overhead per word
rts
With rg-cc hardware countdown loop (dbra):
_clear_scanline:
subq.w #1,d0 ; 4 cycles: adjust count for -1 exit
bmi.s .Lexit ; 8/10 cycles: handle count <= 0
.Lloop:
clr.w (a0)+ ; 12 cycles: clear 16-bit word and advance pointer
dbra d0,.Lloop ; 10 cycles: decrement and branch
.Lexit:
rts
; Tight 22-cycle loop body clearing 1 word per iteration (saves 8 cycles loop overhead)
Redundant Flag Test Elimination
In the 68000 architecture, most ALU instructions (add, sub, move, and, or) automatically set the Zero (Z) and Negative (N) flags in the Condition Code Register (CCR). rg-cc tracks CCR state across instructions to drop redundant tst and cmp #0 operations:
// C source
int16_t decrement_timer(int16_t *timer) {
int16_t t = *timer - 1;
*timer = t;
if (t == 0) return 1;
return 0;
}
Without optimisation:
move.w (a0),d0 ; 8 cycles: load timer
subq.w #1,d0 ; 4 cycles: decrement
move.w d0,(a0) ; 8 cycles: store timer
tst.w d0 ; 4 cycles: redundant test instruction!
bne.s .Lnot_zero ; 8/10 cycles
With rg-cc flag tracking:
subq.w #1,(a0) ; 16 cycles: in-place 16-bit memory decrement (sets Z flag!)
bne.s .Lnot_zero ; 8/10 cycles: branches directly on CCR result
; 8 clock cycles and 2 instructions eliminated
General Frame-Pointer Omission
Standard 68k calling conventions set up a stack frame using link a5,#-N (16 clock cycles) and tear it down with unlk a5 (12 clock cycles). rg-cc re-bases all stack parameters and locals relative to (sp), completely omitting the frame pointer when dynamic stack allocation is not required:
// C source
int16_t step_with_stack_limit(int16_t x, int16_t dx, const int16_t *table, int16_t index) {
int16_t pos = x + dx;
return pos + table[index]; // 3rd integer parameter 'index' passed on stack (table in a0)
}
Without optimisation (standard frame pointer link / unlk):
_step_with_stack_limit_naive:
link a5,#0 ; 16 cycles: set up frame pointer A5
add.w d1,d0 ; 4 cycles: x + dx
move.w 8(a5),d1 ; 12 cycles: load index from stack (via frame pointer)
add.w d1,d1 ; 4 cycles: word index to byte offset
add.w (a0,d1.w),d0 ; 14 cycles: + table[index]
unlk a5 ; 12 cycles: restore frame pointer A5
rts ; 16 cycles
; 28 cycles wasted on link/unlk; address register A5 tied up
With rg-cc frame-pointer omission:
_step_with_stack_limit_opt:
add.w d1,d0 ; 4 cycles: x + dx
move.w 4(sp),d1 ; 12 cycles: load index directly from SP!
add.w d1,d1 ; 4 cycles: word index to byte offset
add.w (a0,d1.w),d0 ; 14 cycles: + table[index]
rts ; 16 cycles
; Zero frame overhead; 28 clock cycles saved; A5 free for allocation
Small Data Base Addressing (-msmall-data)
Under Small Data mode, the linker aggregates eligible file-scope globals (up to 8 bytes, without custom sections) into a single 64 KB .sdata/.sbss segment, and A6 is reserved system-wide to hold __sda_base. References to those locally defined globals are rewritten to single-word 16-bit displacements instead of 32-bit absolute addresses:
// C source
int16_t player_lives = 3;
int16_t bonus_score = 0;
int16_t award_extra_life(int16_t points) {
bonus_score += points;
return ++player_lives;
}
Without optimisation (standard 32-bit absolute addressing):
_award_extra_life_abs:
add.w d0,_bonus_score.l ; 20 cycles, 6 bytes: 32-bit absolute RMW
addq.w #1,_player_lives.l ; 20 cycles, 6 bytes: 32-bit absolute RMW
move.w _player_lives.l,d0 ; 16 cycles, 6 bytes: 32-bit absolute load
rts ; 16 cycles
; 56 cycles body, 18 bytes for globals, 3 load-time 32-bit relocations
With rg-cc Small Data addressing (-msmall-data):
_award_extra_life_sda:
add.w d0,_bonus_score(a6) ; 12 cycles, 4 bytes: d16(a6) RMW
addq.w #1,_player_lives(a6) ; 12 cycles, 4 bytes: d16(a6) RMW
move.w _player_lives(a6),d0 ; 8 cycles, 4 bytes: d16(a6) load
rts ; 16 cycles
; 32 cycles body, 12 bytes for globals, zero load-time relocations