XL1200-EMU Symbolics XL1200 Emulator
Plans & Roadmap SpecsDONE docs/cpu-acceleration-plan.md

CPU Acceleration Plan (Zen 4 AVX-512 & Universal 64-Bit)

NOTE

Status: Implemented (Phases 1–4 Complete). All three execution tiers (portable, avx512_c, avx512), the 256-page IvoryDcache, OS-independent SysV/Win64 hot assembly loop (emu/src/cpu_zen4_loop.S), and lockstep verification have landed. See docs/emulator/core-and-acceleration.md for the live architecture, runtime knobs (ISA_MODE, IVORY_ACCEL), and verified benchmark measurements (149.7–151.4 MIPS on 45M-step fep330 boot, 2.31× vs portable). This document is retained as the historical design record.

Companion Note: Builds on avx512.md and audits against the from-scratch C11 emulator in emu/ and emu/AGENTS.md.


1. Executive Summary & Settled Design Decisions

This plan accelerates the from-scratch C11 Ivory/XL1200 emulator on AMD Ryzen 9 7940HS (Zen 4) (AVX-512F/DQ/BW/VL/CD, VBMI, VBMI2, BITALG, VPOPCNTDQ, BMI1/2, LZCNT/TZCNT, zero AVX-512 clock downthrottling) while keeping the baseline portable to any 64-bit little-endian CPU & OS (Linux, Windows x64, macOS/BSD across x86_64, aarch64, riscv64, ppc64le, loongarch64) and making the hot x86-64 assembly OS-independent across Linux/SysV and Windows x64.

Settled Architectural Choices

  1. Default Build Mode (ISA_MODE=runtime): make -C emu defaults to ISA_MODE=runtime, building portable -O3 baseline C11 code plus x86_64 accelerated units selected at startup via stateless CPUID + XGETBV. ISA_MODE=portable and ISA_MODE=native remain optional compile-time modes; IVORY_ACCEL=auto|portable|avx512_c|avx512 overrides tier selection at runtime for lockstep A/B verification and benchmarking.
  2. Decoded Page Cache Size (256 Pages): 256 decoded pages (~1.06 MiB) organized as 128 sets × 2 ways, fitting inside Zen 4's 1 MiB L2 / 16 MiB L3 cache.
  3. Full Architectural RAM Readiness (Up to 4 GigaWords / \(2^{24}\) PPNs): Rather than an 8 MW-only cached_ppn_bitmap (which would grow to 2 MiB across sparse MMIO holes at \(2^{24}\) PPNs), IvoryDcache uses a fixed 1 KiB 2-way PPN tag directory (uint64_t ppn_pair[128]) folding all 24 PPN bits (+ 64-bit (size_t)pma host indexing), scaling with O(1) memory and zero resizing from 8 MW to 4 GW.
  4. Two Pre-Assembly Phases + OS-Independent Assembly:
    • Phase 1: Pure C11/GNU C portable direct-threaded engine + 256-page IvoryDcache + 256-µs timer batching + inline DATA_READ + O(1) shell dirty-gating (zero intrinsics, zero assembly).
    • Phase 2: Stateless runtime CPUID/XGETBV dispatch + OS-independent <immintrin.h> AVX-512 C kernels (256-word page decoder, 64B PHT bucket probe, 4-insn vpshufbitqmb PHT hash) + profiling gate before assembly.
    • Phase 3: OS-independent x86-64 hot assembly loop (cpu_zen4_loop.S + asm_abi.h, ~28 hot opcodes + single C slow-path trampoline) supporting both System V AMD64 and Microsoft Windows x64 (_WIN64).
    • Phase 4: Profile-guided opcode tuning & optional stretch goals.
ComponentTarget Phase & TierExpected Impact
1. 512-Slot Strided Decoded Page Cache (256 pp) + Direct ThreadingPhase 1 (portable64, pure C11/GNU C goto *)~3–4× over current double-switch — eliminates per-insn fetch, Even/Odd extraction, CDR branches, and two-level k_opcode_router -> isa_* switch dispatch.
2. Capped 256-µs Event-Horizon Timer Batching + Fast DATA_READPhase 1 (portable64, all hosts)Cuts merlin_tick() calls by 99.6% in deterministic mode (cpu.c) and inlines non-forwarding RAM DATA_READ / CDR_READ.
3. Stateless Runtime Dispatch + <immintrin.h> AVX-512 KernelsPhase 2 (zen4_avx512 C intrinsics — Linux & Windows)~45–70 ns per 256-word page decode (vpermi2b + vpsrlvq), 4-insn vpshufbitqmb PHT hash, and 1-cache-line ZMM 4-way PHT bucket probe.
4. OS-Independent x86-64 Assembly Fast-Loop (~28 Hot Opcodes)Phase 3 (zen4_avx512 .S — SysV + Win64 ABI shim)Additional ~1.4–1.7× (~150–250+ MIPS total) — pins hot state in universal non-volatile GPRs (rbx, rbp, r12..r15) with relocation-free .rodata per-handler dispatch.
IMPORTANT

Non-Negotiable ABI, Hot-Reload & Source-Provenance Invariants (emu/AGENTS.md):

  • Reference sources only: Consult only genera-original/, I_Machine/, docs/hardware-reference/, and emu/. Never read, inspect, grep, or cite linux-vlm/, xl1200-emu/, or archive/.
  • Frozen state struct sizes: sizeof(IvoryCpu) == 4096U, sizeof(IvoryMem) == 32768U, and sizeof(MerlinBoard) == 278528U across LP64 (Linux) and LLP64 (Windows x64).
  • ELF zero-.data/.bss hygiene: Every emu/build/obj/core/*.o must retain 0 bytes in writable .data and .bss verified via readelf -WS (read-only .rodata and .data.rel.ro[.local] are permitted).
  • Export & hot-reload safety: libivory_core exports only ivory_core_get_api and must survive live dlclose/dlopen reloads and .snap/COW checkpoint rollbacks with zero dangling code pointers.

2. Portability, Build Modes & Runtime Dispatch (ISA_MODE=runtime Default)

2.1 Per-TU Target Flags (Fixing Makefile -march=native Leakage)

Currently, CORE_OPT_FLAGS passes -march=native -mtune=native to every file in CORE_SRCS, which makes GCC emit EVEX/AVX-512 instructions into baseline C translation units on Zen 4 (causing SIGILL if run on non-AVX-512 x86-64 machines). Under the new build setup:

flowchart LR
    subgraph Build["Build Modes (Makefile: ISA_MODE ?= runtime)"]
        M_RT["ISA_MODE=runtime (Default)<br/>Baseline CORE_SRCS: -O3 -funroll-loops (any 64-bit)<br/>x86_64 adds cpu_zen4_avx512.c (-march=znver4)<br/>+ Phase 3 cpu_zen4_loop.S"]
        M_PORT["ISA_MODE=portable<br/>Pure C11 across all files (-DIVORY_FORCE_PORTABLE=1)<br/>Zero intrinsics / zero asm"]
        M_NAT["ISA_MODE=native<br/>Compile-time -march=native across all CORE_SRCS"]
    end

    subgraph Runtime["Stateless Runtime Selection (0 .data / .bss)"]
        CPUID["ivory_host_select_tier()<br/>OS-independent CPUID + XGETBV ((xcr0 & 0xE6)==0xE6)<br/>+ getenv('IVORY_ACCEL') override"]
        VTBL["Read-Only Tier Table<br/>TIER_PORTABLE64 | TIER_AVX512_C | TIER_AVX512_ASM"]
        CPUID --> VTBL
    end

    M_RT --> CPUID
  • Two Core Families (No Redundant AVX2 Middle Tier):
    • TIER_PORTABLE64 (0): Universal 64-bit little-endian C11 (_Static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) matching IvoryWord bitfields in ivory_hw.h). Uses GNU C computed-goto (&&lbl, supported by GCC and Clang under -std=c11 -Wall -Wextra -Werror) over the 512-slot decoded page cache, falling back to existing cpu_step_internal() if !defined(__GNUC__).
    • TIER_AVX512_C (1, Phase 2) / TIER_AVX512_ASM (2, Phase 3): Compiled under #if defined(__x86_64__) && !defined(IVORY_FORCE_PORTABLE). Requires OS-enabled XMM/YMM/ZMM/opmask state ((xgetbv(0) & 0xE6) == 0xE6) + AVX512F/DQ/BW/VL + VBMI + VBMI2 + BITALG + BMI1/2.
  • Cross-Compiler Intrinsics Portability: cpu_zen4_avx512.c uses standard <immintrin.h> intrinsics (-march=znver4 on GCC/Clang across Linux/MinGW-w64/macOS/BSD, or /arch:AVX512 on clang-cl/MSVC).
  • Hot-Reload & Snapshot State Placement:
    • In snapshot.c, checkpoint save/restore performs whole-struct assignment (*dst = *src) on IvoryCpu and MerlinBoard, whereas IvoryMem copies only boot_comm, map_cache, io_sram, ram, and vram.
    • Therefore, IvoryMem owns IvoryDcache *dcache by carving 1 uint64_t slot from IvoryMem._reserved[938] -> _reserved[937] in ivory_emu.h (sizeof(IvoryMem) stays 32768U), allocated in ivory_mem_init and freed in ivory_mem_destroy.
    • Never store raw function pointers in IvoryDcache: IvoryDcache stores only uint8_t accel_tier and uintptr_t core_cookie = (uintptr_t)&ivory_core_get_api, indexing a read-only .data.rel.ro.local vtable inside the currently mapped libivory_core. When core_cookie changes after a live reload, dcache flushes its decoded pages and refreshes accel_tier + core_cookie.

3. Decoded Page Cache & Architectural Max-RAM Scaling (8 MW -> 4 GW)

3.1 Ivory & Merlin-II Architectural RAM Ceilings Beyond 8 MW

Per genera-original/sys.sct/i-sys/sysdef.lisp, genera-original/sys.sct/i-sys/configuration.lisp (local-only when present), and ivory_hw.h, there are three RAM ceilings above the standard 8 MW (0x00800000):

RAM CeilingPhysical Address LayoutPages (256 W/pg)Host IvoryWord FootprintHardware / Genera Constraints
1. Zone-31 Contiguous Max (127.875 MW)0x00000000 .. 0x07FDFFFF (2,046 quanta)523,776 pages~1.00 GiBDirectly addressable via unmapped Zone 31 (VMA & 0x07FFFFFF) right up to IVORY_BOOT_PROM_BASE_PMA (0x07FE0000) and MERLIN_TIMER_BASE_PMA (0x08000000).
2. Merlin-II Hardware Max (895.875 MW)Main (127.875 MW) + 3 merlin-memory-board slots at 0x10000000, 0x20000000, 0x30000000 (3 × 256 MW, below MERLIN_IO_BOARD0 0x40000000)3,669,504 pages (discontiguous)~7.00 GiB (virtual; sparse on-demand)Genera find-merlin-boards (genera-original/sys.sct/i-sys/configuration.lisp) probes all 3 expansion slots when ECO nibbles <15:4> != 0xF. Accessed via PHT (Zones 0..30) and DTP-PHYSICAL-ADDRESS.
3. Ivory VLSI Architectural Max (4 GigaWords, minus MMIO holes)%%PHT1-PPN is 24 bits (<31:8>), %MMPT-Y-BITS = 16 + %MMPT-X-BITS = 8, %%MAIN-MEMORY-MAP-QUANTUM = (byte 24 0)Up to 16,777,216 PPNs (2^24)Up to 32 GiB virtual reservation (sparse on-demand)Requires 64-bit (size_t)pma host indexing (since pma >= 512 MW exceeds 32-bit byte offsets) and sparse host reservation (mmap(MAP_NORESERVE) / VirtualAlloc(MEM_RESERVE)).

3.2 O(1) 1 KiB 2-Way Set-Associative PPN Tag Directory

Because IvoryDcache holds 256 active pages, we organize it as 128 sets × 2 ways indexed by a 7-bit hash folding all 24 architectural PPN bits:

#define IVORY_DCACHE_SETS 128U
#define IVORY_DCACHE_WAYS 2U   /* 256 decoded pages total (~1.06 MiB) */

static inline uint32_t ivory_dcache_set_idx(uint32_t ppn) {
    return (ppn ^ (ppn >> 7) ^ (ppn >> 14) ^ (ppn >> 21)) & (IVORY_DCACHE_SETS - 1U);
}
  • 1 KiB L1d-Resident Tag Array: uint64_t ppn_pair[128] (1,024 bytes = 16 cache lines) packs { uint32_t way0_ppn, uint32_t way1_ppn } (0xFFFFFFFFU = empty; Boot PROM pages use sentinel 0x80000000U | prom_page outside the 24-bit RAM PPN space).
  • Universal Write-Coherence Hook (ivory_mem_note_ram_write_pma):
    WARNING

    In mem.c, write_word_with_translation() writes Zone 31 and Map-Cache hits directly into mem->ram[pma] and mc->host_page[off] without calling ivory_mem_raw_write_pma(), and ifep_install() (loader.c) writes mem->ram directly during boot and power-reset.

    • Route RAM dirty-marking + code-cache invalidation through a single inline ivory_mem_note_ram_write_pma(mem, pma) called by write_word_with_translation(), ivory_mem_raw_write_pma(), and ivory_mem_mark_ram_dirty() (and call ivory_mem_mark_ram_dirty() from ifep_install()).
    • On each write, ppn = pma >> 8 loads uint64_t pair = dcache->ppn_pair[set] and invalidates any matching way ((uint32_t)pair == ppn || (uint32_t)(pair >> 32) == ppn) in 1 L1d load with 0% false positives and zero scaling cost up to 4 GW.
    • Flush memset(dcache->ppn_pair, 0xFF, sizeof(dcache->ppn_pair)) (~8 ns) in ivory_mem_reset(), ivory_mem_invalidate_map_cache() (also called on checkpoint restore in snapshot.c), and ivory_cpu_reset().
    • Virtual-to-physical entry still validates CpuIcache64 against mem->map_epoch, so single-VPN remaps (ivory_mem_invalidate_map_entry / ivory_mem_load_map_entry) take effect immediately.
    • Ensure all mem->ram pointer indexing uses (size_t)pma so pma >= 512 MW (>= 4 GiB byte offset) never truncates on Linux LP64 or Windows LLP64.

3.3 8-Byte IvoryDecodedSlot & Boundary Sentinels

typedef struct IvoryDecodedSlot {
    uint16_t handler_id; /* 0..511 index into read-only dispatch table (reload-safe)  */
    int8_t   stride;     /* Sequential delta: -1 (CDR=2), +1, +2 (CDR=3/FW), +3 (Odd CDR=3) */
    uint8_t  aux;        /* DTP for constants/calls, min_args for ENTRY, or mode      */
    uint32_t imm;        /* 32-bit pointer/constant payload, branch delta, or offset  */
} IvoryDecodedSlot;      /* 8 bytes -> 8 slots per 64B cache line                     */

typedef struct IvoryDecodedPage {
    const IvoryWord  *raw_page;      /* Underlying 256-word RAM/PROM page for cold paths */
    uint32_t          ppn_tag;       /* 24-bit RAM PPN or 0x80000000|prom_pg             */
    uint8_t           lru_bit;
    uint8_t           _pad[3];
    IvoryDecodedSlot  raw_slots[516];/* [0]=slot -1, [1..512]=0..511, [513..515]=512..514 */
} IvoryDecodedPage;

#define DPAGE_SLOTS(dp) (&(dp)->raw_slots[1])
  • Exact stride parity with cpu.c:
    • CDR=0: +1 (packed) / +2 (fullword).
    • CDR=1 (IVORY_SEQ_FENCE): both Even and Odd emit HANDLER_TRAP_FENCE (IVORY_REV4_USTATE_I_STAGE_ERROR).
    • CDR=2 (IVORY_SEQ_PC_MINUS_1): -1 (slot == 0 steps cleanly into DPAGE_SLOTS(dp)[-1], avoiding C11 negative-index UB).
    • CDR=3 (IVORY_SEQ_PC_EVEN_2_ODD_3): +2 on Even/fullword, +3 on Odd packed (slots 510..511 step cleanly into DPAGE_SLOTS(dp)[512..514]).
    • Non-packed Odd slots emit HANDLER_TRAP_ODD_FULLWORD (IVORY_REV4_USTATE_I_STAGE_ERROR).
  • Zero raw_page load for 40-bit inline constants: Inline literals (tag < 0o50) push CDR = IVORY_CDR_NEXT (0), reconstructed directly from ((uint64_t)slot.aux << 32) | slot.imm.
  • O(1) intra-page branches: Branch/loop targets satisfying 0 <= slot + delta < 512 and delta != 0 (delta == 0 traps BRANCH_DOT_ERROR) adjust ip += delta directly; backward intra-page branches decrement rem_budget so tight loops never starve timers/IRQs.

4. Phase-by-Phase Technical Design

Phase 1: Universal Portable Threaded Baseline & Timer Batching (portable64)

  1. Direct-Threaded Loop (cpu_decode.c / cpu.c):
    • Single-function GNU C computed-goto interpreter (goto *k_portable_disp[slot.handler_id], #else fallback to cpu_step_internal() for non-GNU compilers).
    • Falls back to cpu_step_internal() whenever trace_enabled, has_break, num_watchpoints > 0, (cr.raw & 0x38000000U) != 0 (trace_pending | call_trace | instruction_trace), or ivory_mem_resolve_icache_page() returns NULL (stack_cache overlap or first 64-word boot_comm PROM page).
  2. Capped 256-µs Event-Horizon Timer Batching (cpu.c):
    • In deterministic !cpu->external_clock mode, batch merlin_tick() up to min(merlin_us_until_next_timer_irq(board), 256U) µs (<= 1,024 insns, preserving eth_82586_poll_rx's 256-µs divider in merlin.c even when PIT channels are disarmed and return UINT64_MAX).
    • Flush accrued cycles (delta_us = accrued >> 2) lazily before OP_READ/WRITE_INTERNAL_REGISTER (0047 clock, 0023 preempt), OP_COPROCESSOR_READ/WRITE (01002), and any merlin_io_read/write (including PIT Counter Latch writes to 0x08000003), and service board->dma_service_pending immediately when non-zero after MMIO.
    • Check deferred async interrupts at backward branches, calls, page exits, and immediately after OP_RETURN_* (which restores cr.raw and can drop trap_mode to EMULATOR, unmasking pending sequence breaks/preempt!), OP_WRITE_INTERNAL_REGISTER, OP_CHECK_PREEMPT_REQUEST, OP_UNBIND_N, OP_RESTORE_BINDING_STACK, and OP_CATCH_CLOSE.
  3. Portable Micro-Optimizations:
    • 15-op grouped bit-run ivory_pht_hash() fallback (replacing ~130 scalar ops in ivory_hw.h).
    • Unified pht_probe_bucket() in mem.c shared by pht_search() and pht_sync_write_attributes().
    • Inline non-forwarding ivory_fast_data_read() for isa_lisp.c (preserving cpu->memory_data = word and transport_trap && is_oldspace_pointer checks).
    • Host-shell pure-C11 wins: O(1) (vram_write_count, video_ctrl) caching in debug_ctl_compute_vram_metrics() (debug_ctl.c) and __builtin_ctzll(dirty_bm[w]) clean-page skipping in snapshot.c.

Phase 2: Runtime Dispatch & OS-Independent AVX-512 C Intrinsics (cpu_zen4_avx512.c)

Implemented in portable C11 + <immintrin.h> (compiles identically on Linux and Windows x64 before introducing assembly):

  1. Stateless CPUID + XGETBV Capability Detector:
    • Verifies OS XMM/YMM/ZMM/opmask save state ((xcr0 & 0xE6) == 0xE6) plus AVX512F/DQ/BW/VL, VBMI, VBMI2, BITALG, and BMI1/2.
  2. AVX-512 256-Word Page Decoder (~45–70 ns/page):
    • 32 ZMM iterations (8 IvoryWords -> 16 IvoryDecodedSlots per iteration).
    • Register-resident 256-opcode LUT in 4 ZMM constants using AVX512_VBMI _mm512_permutex2var_epi8 (zero vpgatherdd port pressure), 1-cycle fullword DTP legality bitmask via vpsrlvq, pre-paired ENTRY (0176/0177) min_args + Odd-halfword max_args, and branchless Even/Odd stride interleave.
  3. AVX-512 PHT Bucket Probe & 4-Insn vpshufbitqmb Hash:
    • _mm512_loadu_si512 loads all 4 IvoryPhtEntry pairs (64 B = 1 cache line). Mask <31:8> (_mm512_and_epi64(..., 0xFFFFFF00ULL)) so age/fault_request/end_collision_chain never cause false misses, and compare with even-lane opmask 0x55 (_mm512_mask_cmpeq_epi64_mask(0x55, ...)) so pht1.ppn in odd lanes never causes false hits.
    • Two _mm256_bitshuffle_epi64_mask (vpshufbitqmb) + _kxor_mask32 compute all 23 XOR bits of ivory_pht_hash(vma) in 4 instructions.
  4. Benchmarking & Profiling Gate:
    • Measure IVORY_ACCEL=portable vs IVORY_ACCEL=avx512_c MIPS and perf stat counters across IFEP boot and Genera workloads to validate hot-opcode coverage prior to Phase 3.

Phase 3: OS-Independent x86-64 Assembly Hot Loop (Linux/SysV + Windows x64)

Cross-OS Assembly Design (cpu_zen4_loop.S + asm_abi.h)

Standard x86-64 assembly breaks on Windows (_WIN64) due to: (1) %rcx/%rdx vs %rdi/%rsi arg registers, (2) %rdi/%rsi and XMM6..15 being non-volatile on Win64, (3) Win64 requiring 32 bytes of caller shadow space before call plus .seh_* unwind directives instead of ELF .cfi_*/.note.GNU-stack, and (4) 32-bit long (LLP64).

We isolate all OS differences inside a ~35-line asm_abi.h header so 100% of the ~28 hot opcode handlers share one identical assembly body (buildable with GCC or Clang/clang-cl on Linux, Windows MinGW-w64, Windows MSVC-ABI clang-cl, macOS, and BSD):

flowchart TD
    C_CALLER["C Caller: ivory_cpu_run_zen4_asm(&ctx)<br/>Single pointer arg: IvoryAsmLoopCtx *ctx"] --> PROLOGUE
    PROLOGUE["asm_abi.h Prologue (~20 lines)<br/>• _WIN64: %rcx -> ctx, emits .seh_proc/.seh_pushreg, saves %rdi/%rsi<br/>• SysV:   %rdi -> ctx, emits .cfi_startproc<br/>• Both:   reserves 32B shadow space + 32B locals (64B aligned frame)"]
    PROLOGUE --> HOT_LOOP["OS-Independent Hot Threaded Loop (~320 LOC)<br/>• Pinned universal non-volatile GPRs: rbx=cpu, rbp=ip, r12=tos, r13d=sp, r14d=fp, r15=tbl<br/>• Scratch GPRs: rax, rcx, rdx, rsi, rdi, r8..r11 (zero XMM6..15 used!)<br/>• Relocation-free 2 KiB .rodata relative jump table (.long .L_op - .L_tbl)"]
    HOT_LOOP -->|"Cold opcode (~190 ops) / Miss / Trap"| TRAMP["Single Slow-Path Trampoline (~15 lines)<br/>Flushes r12..r14 & PC/current_instruction to IvoryCpu;<br/>sets ABI_ARG0 = %rsp, ABI_ARG1 = reason;<br/>call ivory_cpu_slow_trampoline (uses pre-reserved 32B shadow space!)"]
    TRAMP -->|"Reloads ip, sp, fp, tos or exits"| HOT_LOOP
  1. Single-Pointer Entry & Single-Helper Exit:
    • Entry ivory_cpu_run_zen4_asm(IvoryAsmLoopCtx *ctx) and slow-path ivory_cpu_slow_trampoline(IvoryAsmLoopCtx *ctx, uint32_t reason) reduce ABI argument differences to two macros (ABI_ARG0 = %rcx/%rdi, ABI_ARG1_32 = %edx/%esi).
  2. Universal Non-Volatile Register Pinning & Write-Through tos:
    • %rbx (cpu), %rbp (ip), %r12 (tos), %r13d (sp_vma), %r14d (fp_vma), and %r15 (disp_table) are callee-saved on both System V AMD64 and Windows x64 (note: %r10/%r11 are caller-saved scratch!).
    • %r12 (tos) must be write-through into cpu->stack_cache[sp_vma & 127] (and refreshed if a store hits vma == sp_vma) so aliased FP+k, LP+k, SP-255, or DTP_LOCATIVE stack-cache accesses never read stale values.
    • Saving %rdi and %rsi once in the prologue makes all 9 scratch GPRs (%rax, %rcx, %rdx, %rsi, %rdi, %r8..%r11) identical across OSes; touching zero XMM registers avoids Win64 XMM6..15 save/restore; always reserving 0(%rsp)..31(%rsp) as shadow space keeps rem_budget and dpage stack offsets identical.
  3. Relocation-Free 2 KiB Relative Jump Table (.rodata / .rdata):
    • disp_table stores 512 × 32-bit signed offsets (.long .L_op_k - .L_disp_tbl) in pure read-only .rodata/.rdata (zero dynamic relocations on ELF .so, Windows .dll, and Mach-O .dylib; 2 KiB L1d footprint):
      movsbq  2(%rbp), %rcx           # current slot.stride (-1, +1, +2, +3)
      leaq    (%rbp,%rcx,8), %rbp     # ip += stride
      movq    (%rbp), %rdx            # load next 8-byte IvoryDecodedSlot
      movzwl  %dx, %eax               # handler_id
      shrq    $32, %rdx               # next slot.imm in %edx
      movslq  (%r15,%rax,4), %rcx     # PIC/DLL-clean 32-bit relative handler offset
      addq    %r15, %rcx
      jmp     *%rcx                   # per-handler indirect jmp -> Zen 4 ITTAGE friendly
      
  4. Slow-Path State Materialization & LP64/LLP64 Offset Guards:
    • Before calling ivory_cpu_slow_trampoline, materialize cpu->pc, cpu->d_pc, cpu->sp, cpu->macro_sp = pre_insn_sp (required for pre-trap SP rollback in cpu.c), cpu->fp, cpu->scratchpad[0] = tos, and cpu->current_instruction = dpage->raw_page[slot >> 1] & IVORY_WORD_MASK (required for post_trap, FINISH_CALL, CATCH_CLOSE, and %REGISTER-INSTRUCTION 0040..0042). Note that ivory_isa_exec_fullword_call() (isa_call.c) advances cpu->pc internally — do not double-advance!
    • Guard all assembly struct offsets via ivory_asm_offsets.h with C _Static_assert(offsetof(...) == ...) checks across LP64 and LLP64, and pair __declspec(dllexport) / LoadLibraryA shims in ivory_core_api.h and core_loader.c for Windows DLL builds.
  5. Top ~28 Inlined Hot Opcodes:
    • Stack & Constants: Fullword PUSH_CONST, OP_PUSH (FP/LP/SP-pop/SP-idx/IMM), OP_POP, OP_MOVEM, OP_PUSH_ADDRESS, OP_SET_SP_TO_ADDRESS, OP_SET_SP_TO_ADDRESS_SAVE_TOS.
    • Branches & Loops: Intra/inter-page OP_BRANCH, OP_BRANCH_TRUE* / OP_BRANCH_FALSE* (0060..0077), OP_LOOP_DECREMENT_TOS, OP_LOOP_INCREMENT_TOS_LESS_THAN.
    • Predicates: OP_EQ/NO_POP, OP_EQL/NO_POP, OP_ZEROP, OP_PLUSP, OP_MINUSP, OP_ENDP, OP_TYPE_MEMBER_*, Fixnum OP_LESSP/GREATERP/EQUAL_NUMBER/LOGTEST.
    • Fixnum ALU & Bitfields: Fixnum OP_ADD/OP_SUB (jo -> C trap), OP_INCREMENT/DECREMENT, OP_32_BIT_PLUS/DIFFERENCE, OP_LOGAND/LOGIOR/LOGXOR, OP_LDB (rorx+bzhi), OP_DPB, OP_TAG, OP_POINTER_PLUS, OP_POINTER_INCREMENT.
    • List & Fast Call/Return: OP_CAR, OP_CDR, OP_SET_TO_CAR, OP_SET_TO_CDR, OP_SET_TO_CDR_PUSH_CAR, DTP_CALL_COMPILED_EVEN/ODD, OP_FINISH_CALL_N, OP_ENTRY_REST_NOT_ACCEPTED, OP_RETURN_SINGLE.

5. Implementation Roadmap & Verification Gates

PhaseScope & FilesVerification & Gate Criteria
Phase 1: Portable Threaded Engine, 4 GW-Ready IvoryDcache & Timer BatchingMakefile (ISA_MODE ?= runtime), ivory_emu.h, ivory_hw.h, mem.c, cpu.c, isa_lisp.c, loader.c, debug_ctl.c, snapshot.c, new emu/src/cpu_decode.c (+ update test_cpu_core / test_mem link rules in Makefile)• ISA_MODE=portable & ISA_MODE=runtime pass make -C emu clean all test test-e2e.
• sizeof (4096, 32768, 278528) & readelf -WS (0 .data/.bss in core/*.o) pass.
• Record Phase 1 MIPS baseline vs current switch interpreter.
Phase 2: Runtime Dispatch + <immintrin.h> AVX-512 Kernels (Pre-ASM Gate)New emu/src/cpu_zen4_avx512.c (-march=znver4 / /arch:AVX512), test_cpu_core.c, test_mem.c• Bit-exact memcmp parity of IvoryDecodedSlot[516] (scalar vs AVX-512) across rom.dump + IFEP-Kernel + edge-case CDR/DTP words.
• 1M-VMA randomized ivory_pht_hash & PHT bucket parity tests.
• Profiling checkpoint: Measure MIPS & hot-opcode histogram before starting Phase 3.
Phase 3: OS-Independent x86-64 Assembly Hot Loop (Linux + Windows x64)New emu/include/ivory_asm_offsets.h, emu/src/asm_abi.h, emu/src/cpu_zen4_loop.S (~320–380 LOC), Windows DLL export/loader shims in ivory_core_api.h & core_loader.c• readelf -lW (RW GNU_STACK), readelf -WS (0 .data/.bss), and cross-target clang -target x86_64-pc-windows-msvc -c cpu_zen4_loop.S object check.
• 10M+ insn lockstep gate: IVORY_ACCEL=portable vs IVORY_ACCEL=avx512 match instr_count, pc, sp, fp, lp, cr, vram_hash + mid-run live reload swap test.
Phase 4: Profile-Guided Tuning & Optional Stretch GoalsTune ~28 ASM opcode set against live Genera 8.3 profiles; optional AVX-512 .y4m 1bpp->ARGB8888 blitter; optional sparse mmap/VirtualAlloc backing if >127.875 MW / Merlin expansion RAM is enabled• Final perf stat report (MIPS, L1i/µop-cache hit rate, ITTAGE indirect branch miss rate).