5 Commits
Author SHA1 Message Date
ed a2d79d65eb amazing bug 2026-08-11 01:25:40 -04:00
ed bebcc6a585 wip: going to incremnetally test this. 2026-08-11 01:25:09 -04:00
ed ece21ed368 mark current crashing path. 2026-08-10 23:29:38 -04:00
ed 144c605ad8 some more review. not working still. 2026-08-10 23:04:43 -04:00
ed 4afd1af0fd started to review this... 2026-08-10 19:53:34 -04:00
16 changed files with 551 additions and 1171 deletions
-62
View File
@@ -175,68 +175,6 @@ WORD_COUNT(mac_gte_sqr_v3, 8)
, shift_aright_var(r_dz, r_dz, r_shift) , shift_aright_var(r_dz, r_dz, r_shift)
WORD_COUNT(mac_gte_gpf_scale, 13) WORD_COUNT(mac_gte_gpf_scale, 13)
#define mac_normalize_v3s4(...) \
load_word(r_src, R_TapePtr, O_(Binds_NormalizeV3S4,src)) /* pop src ptr (scratch addr) */ \
, load_word(r_dst, R_TapePtr, O_(Binds_NormalizeV3S4,dst)) /* pop dst ptr (scratch addr) */ \
, add_ui_self( R_TapePtr, S_(Binds_NormalizeV3S4)) \
, load_word(r_sx, r_src, O_(V3_S4,x)) \
, load_word(r_sy, r_src, O_(V3_S4,y)) \
, load_word(r_sz, r_src, O_(V3_S4,z)) \
, nop /* load-delay */ /* ── 48-word normalize body (preserved verbatim from ac_normalize_v3s4) ─────── */ /* Stage 1: mtc2 src → IR1/2/3, SQR fires (MAC1/2/3 = IR², IR ← MAC saturated) */ \
, gte_mv_to_data_r(r_sx, C2_IR1) \
, gte_mv_to_data_r(r_sy, C2_IR2) \
, gte_mv_to_data_r(r_sz, C2_IR3) \
, nop \
, gte_cmdw_sqr /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS */ \
, gte_mv_from_data_r(r_sq_y, C2_MAC1) /* r_sq_y = MAC1 = sx² */ \
, gte_mv_from_data_r(r_sq_z, C2_MAC2) /* r_sq_z = MAC2 = sy² */ \
, gte_mv_from_data_r(r_recip_est, C2_MAC3) /* r_recip_est = MAC3 = sz² */ \
, nop /* MFC2→GPR load delay (1 slot) */ \
, add_u(r_recip_est, r_recip_est, r_sq_z) /* r_recip_est += sy² */ \
, add_u(r_recip_est, r_recip_est, r_sq_y) /* r_recip_est += sx² (sum = |v|²) */ \
, gte_mv_to_data_r( r_recip_est, C2_LZCS) /* LZCS = |v|² */ \
, nop2 \
, gte_mv_from_data_r(r_lzcr, C2_LZCR) /* r_lzcr = LZCR (count of leading bits) */ \
, nop /* MFC2→GPR load delay (1 slot) */ /* Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v| */ \
, and_i( r_lzcr, r_lzcr, -2) /* r_lzcr &= ~1 (force even for halving) */ \
, li_s( r_shift, 31) /* r_shift = 31 */ \
, sub_s( r_shift, r_shift, r_lzcr) /* r_shift = 31 - LZCR */ \
, shift_aright( r_shift, r_shift, 1) /* r_shift = (31 - LZCR) / 2 */ \
, add_si( r_tmp, r_lzcr, -24) /* r_tmp = LZCR - 24 (signed, for branch) */ \
, branch_lt_zero(r_tmp, atom_offset(srav_path, aligned_done)) \
, nop \
, jump_rel( atom_offset(aligned_done, srav_path)) \
, shift_lleft_var(r_recip_est, r_recip_est, r_tmp) /* BD-slot of branch_equal: r_recip_est = |v|² << (LZCR - 24) */ \
, atom_label(srav_path) /* SRAV path: |v|² is small (top bit < bit 24) */ \
, li_s( r_tmp, 24) \
, sub_s( r_tmp, r_tmp, r_lzcr) /* r_tmp = 24 - LZCR */ \
, shift_aright_var(r_recip_est, r_recip_est, r_tmp) /* r_recip_est = |v|² >> (24 - LZCR) */ \
, atom_label(aligned_done) /* Both paths converge here with |v|² aligned to bit 24 */ /* r_recip_est now holds |v|² aligned to bit 24 — convert to byte offset, -64 to skip zero pad. */ \
, add_si( r_recip_est, r_recip_est, -64) \
, shift_lleft( r_recip_est, r_recip_est, 1) /* r_recip_est *= 2 (half-word index) */ /* Reference OUR local sqrtbl via &-address split. Compiler/linker resolves both halves. */ \
, load_upper_i( r_tmp, u4_hi(& gte_normalize_sqr_tbl)) /* lui */ \
, or_i_self( r_tmp, u4_lo(& gte_normalize_sqr_tbl)) /* ori */ \
, add_u( r_tmp, r_tmp, r_recip_est) /* r_tmp = sqrtbl base + byte offset (matches libgte 0x80016118: addu t5,t5,t4) */ \
, load_half( r_recip_est, r_tmp, 0) /* r_recip_est = sqrtbl[r_recip_est] = 1/|v| estimate */ \
, nop /* retire load_half before MTC2 (matches libgte 0x80016120: nop) */ /* Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize */ \
, gte_mv_to_data_r(r_recip_est, C2_IR0) /* IR0 = 1/|v| estimate */ \
, gte_mv_to_data_r(r_sx, C2_IR1) /* IR1 = src.x */ \
, gte_mv_to_data_r(r_sy, C2_IR2) /* IR2 = src.y */ \
, gte_mv_to_data_r(r_sz, C2_IR3) /* IR3 = src.z */ \
, nop2 /* COP2 transfer latency (2 slots) */ \
, gte_cmdw_gpf \
, gte_mv_from_data_r(r_sx, C2_MAC1) /* MAC1 → r_sx (overwrites src.x with raw reciprocal-scaled) */ \
, gte_mv_from_data_r(r_sy, C2_MAC2) \
, gte_mv_from_data_r(r_sz, C2_MAC3) \
, shift_aright_var(r_sx, r_sx, r_shift) \
, shift_aright_var(r_sy, r_sy, r_shift) \
, shift_aright_var(r_sz, r_sz, r_shift) /* ── I/O wrapper tail (~3 words) ───────────────────────────────────────────── */ \
, store_word(r_sx, r_dst, O_(V3_S4,x)) \
, store_word(r_sy, r_dst, O_(V3_S4,y)) \
, store_word(r_sz, r_dst, O_(V3_S4,z)) /* ── atom_reads(R_TapePtr) atom_writes(R_TapePtr) ────────────────────────── */ \
, mac_yield()
WORD_COUNT(mac_normalize_v3s4, 62)
#define mac_gcmd_push(cmd, reg_transfer, reg_base, port) \ #define mac_gcmd_push(cmd, reg_transfer, reg_base, port) \
load_upper_i(reg_transfer, cmd >> 16) \ load_upper_i(reg_transfer, cmd >> 16) \
, or_i_self( reg_transfer, cmd & 0xFFFF) \ , or_i_self( reg_transfer, cmd & 0xFFFF) \
+107 -112
View File
@@ -83,6 +83,10 @@ FI_ Slice_MipsCode ac_gte_gpf_scale(MipsAtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r
shift_aright_var(r_dz, r_dz, r_shift), shift_aright_var(r_dz, r_dz, r_shift),
}) })
#pragma endregion MACs (Mips Atom Components)
#pragma region Atom Procs
/* ─── Local copy of PSYQ's sqrtbl (1/sqrt lookup table for VectorNormal). ─── /* ─── Local copy of PSYQ's sqrtbl (1/sqrt lookup table for VectorNormal). ───
* Source: PSYQ 4.7 libgte sqrtbl at 0x800185B4 in hello_camera.elf. * Source: PSYQ 4.7 libgte sqrtbl at 0x800185B4 in hello_camera.elf.
* objdump -s --start-address=0x800185B4 --stop-address=0x800185F4 hello_camera.elf * objdump -s --start-address=0x800185B4 --stop-address=0x800185F4 hello_camera.elf
@@ -97,7 +101,8 @@ FI_ Slice_MipsCode ac_gte_gpf_scale(MipsAtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r
* Octave 1 (entries 48- 95): mantissa in [0x10000, 0x20000) output ~[0.707, 0.500] * Octave 1 (entries 48- 95): mantissa in [0x10000, 0x20000) output ~[0.707, 0.500]
* Octave 2 (entries 96-143): mantissa in [0x20000, 0x40000) output ~[0.500, 0.354] * Octave 2 (entries 96-143): mantissa in [0x20000, 0x40000) output ~[0.500, 0.354]
* Octave 3 (entries144-191): mantissa in [0x40000, 0x80000) output ~[0.354, 0.251] * Octave 3 (entries144-191): mantissa in [0x40000, 0x80000) output ~[0.354, 0.251]
* Within each octave, 8 sub-entries interpolate over the 8 fractional bits of the mantissa (the byte `(0x80 | (i mod 8))` for the lower-byte of the aligned value). * Within each octave, 8 sub-entries interpolate over the 8 fractional bits of the mantissa
* (the byte `(0x80 | (i mod 8))` for the lower-byte of the aligned value).
* Sampling the first value of each octave: * Sampling the first value of each octave:
* [0] 0x1000 = 1.0000 ; 1 / sqrt(1.0000) * [0] 0x1000 = 1.0000 ; 1 / sqrt(1.0000)
* [48] 0x0e4f = 0.8940 ; 1 / sqrt(1.2500) * [48] 0x0e4f = 0.8940 ; 1 / sqrt(1.2500)
@@ -149,131 +154,121 @@ internal S2 const gte_normalize_sqr_tbl[192] align_(2) = {
}; };
/* ─── Full normalize (all 4 stages inline) ─── /* ─── Full normalize (all 4 stages inline) ───
* Generic 4-stage GTE normalize (SQR → sum+LZCR → align+sqrtbl → GPF+srav).
*
* Parameterized by caller-provided scratch base + src/dst offsets.
* The caller passes r_src_offset and r_dst_offset as compile-time constants
* (typically derived from O_ macros in the caller's struct schema, e.g., `O_(CallerBundleScratch, fwd)`).
*
* This design lets any caller (with a scratch base + struct schema) use `normalize_v3s4_proc`
* without putting magic offsets in the C-side bundle helper — the offsets come from O_ macros at the call site.
*
* Body uses 9 GPRs (r_src_ptr..r_branch_tmp):
* r_src_ptr, r_dst_ptr : src/dst pointers (computed from r_scratch + caller offsets)
* r_tmp : scratch (reserved for misc use)
* r_mac1_scratch : MAC1 result scratch (before sum into r_recip_est)
* r_mac2_scratch : MAC2 result scratch (clobbered to IR1 in stage 4)
* r_recip_est : |v|² sum + shift-input + sqrtbl[index] (the main chain)
* r_lzcr : LZCR value (consumed by stage 3 alignment calc)
* r_shift : final srav amount (consumed by stage 4 shift_aright_var)
* r_branch_tmp : scratch (shift count, branch target, sqrtbl base addr)
*
* Atom_labels are srav_path / aligned_done
* (NOT namespaced — they're internal to this proc;
* the metaprogram's per-atom-name enum emission handles any collision across different atoms/files that share the same labels).
*
* Pool cost: 11 GPRs (well within the 9-10 caller-trash GPR budget when r_scratch is a wave-context carrier).
*
* Direct port of PSYQ libgte msc02.rel.text VectorNormal disassembly (0x800160a0..0x8001615c). * Direct port of PSYQ libgte msc02.rel.text VectorNormal disassembly (0x800160a0..0x8001615c).
* * Words: ~59 (matches libgte 0x800160a0..0x8001615c at +/- 0-2 words for BD-slot reshuffling).
* Component variants that could apply: * Sqrtbl: hardcoded to 0x800185B4 (libgte msc02.rel.data). Note: swapped to local.
* - `ac_gte_sqr_v3` (line ~56) covers stage 1's `mtc2 IR1/2/3 + nop + gte_cmdw_sqr`.
* We do NOT call it because the inlined version of stage 1 is followed immediately by stage 2's `mfc2 MAC1/2/3` chain
* (the operands of `ac_gte_sqr_v3`'s r_sq_x/r_sq_y/r_sq_z would each require an explicit GPR to receive the MAC result,
* then a move to land in r_recip_est for the partial-sum chain).
* Inlining saves ~3 cycles of `or`-merge + register pressure
* (squared MAC3 lands DIRECTLY in r_recip_est which doubles as the partial-sum accumulator and the LZCS input — see r_recip_est row below).
* - `ac_gte_gpf_scale` (line ~71) covers stage 4's `mtc2 IR0..3 + nop2 + gte_cmdw_gpf + mfc2 MAC1/2/3 + sra`.
* We do NOT call it for the symmetric reason: the normalize in-place semantics overwrite the input regs (r_sx/r_sy/r_sz) with the normalized output,
* which `ac_gte_gpf_scale`'s r_dx/r_dy/r_dz output GPRs would not match.
* `gte_cmdw_sqr` and `gte_cmdw_gpf` primitive macros ARE used in the inlined body, so changes to those primitives
* (e.g., the libgte `fake_cmd` signature bits) propagate automatically. The components remain available for callers that want the explicit GPR-shape variants.
*
* Argument aliasing (9 unique physical regs needed, can drop to 8 with r_sq_y ≡ r_lzcr):
* r_sx, r_sy, r_sz : src components in regs (clobbered by mtc2 → IR1/2/3 in stage 1, then by mfc2 MAC1/2/3 in stage 4 — in-place semantics)
* r_sq_y, r_sq_z : MAC2, MAC3 → DIE after stage 2 accumulate (r_sq_y can alias r_lzcr after stage 2 to save one reg)
* r_recip_est : ≡ r_sqmag — multi-purpose (holds |v|² in stage 2, shift-input in stage 3, sqrtbl[index] in stage 4)
* r_lzcr : LZCR value, alive across stage 3 (srav path needs `24 - LZCR`)
* r_shift : (31 - LZCR & ~1) >> 1 — final srav amount (stages 3-4)
* r_tmp : scratch (shift count, branch target, lookup addr, table base)
*
* GPR ccount peak: 9.
* Pipeline: clobbers IR0..3, MAC1..3, LZCS, LZCR. * Pipeline: clobbers IR0..3, MAC1..3, LZCS, LZCR.
* Words: ~35 (pending re-gen; matches libgte 0x800160a0..0x8001615c at +/- 0-2 words for BD-slot reshuffling). */
* Sqrtbl: hardcoded to 0x800185B4 (libgte msc02.rel.data). Note: swapped to local. */
/* ─── Binds_NormalizeV3S4 — declared here so the MipsAtom_Proc_ body can reference
* O_(Binds_NormalizeV3S4,*). Inlined at the proc-call site; not exposed in gen/macs.h. */
typedef Struct_(Binds_NormalizeV3S4) {
U4 src; /* V3_S4* (scratch address — read from tape) */
U4 dst; /* V3_S4* (scratch address — write to tape) */
};
/* NOTE: The bundle-specific scratchpad offset schema was intentionally kept out of this file.
* gte.atom.c is the GENERIC GTE primitives file — it exposes only the parameter-style normalize_v3s4_proc for any future caller. */
I_ void normalize_v3s4_proc(
MipsAtomBuilder_R ab
, U4 r_src /* GPR code: scratch base carrier (wave-context, e.g., R_T4) */
, U4 r_dst /* GPR code: scratch dst pointer carrier (wave-context, e.g., R_T5) */
, U4 r_sx, U4 r_sy, U4 r_sz /* GPR codes: src.x/y/z scratch (atom-local) */
, U4 r_sq_y, U4 r_sq_z /* GPR codes: MAC1/2 scratch (atom-local) */
, U4 r_recip_est /* GPR code: |v|² sum + shift-input + sqrtbl[index] (atom-local) */
, U4 r_lzcr /* GPR code: LZCR value (atom-local) */
, U4 r_shift /* GPR code: final srav amount (atom-local) */
, U4 r_tmp /* GPR code: scratch (shift count, branch target, lookup addr, table base) */
)
/* MipsAtom_Proc_ wrapper: declares the static MipsCode[] body, then calls atombuilder_unroll(ab, ...) to copy the encoded instructions into the caller's MipsAtomBuilder arena. */ /* MipsAtom_Proc_ wrapper: declares the static MipsCode[] body, then calls atombuilder_unroll(ab, ...) to copy the encoded instructions into the caller's MipsAtomBuilder arena. */
I_ void normalize_v3s4_proc(MipsAtomBuilder_R ab, U4 r_scratch /* GPR code: scratch base carrier (e.g., R_T4 = R_ResolveScratch) */
, U4 r_src_offset, U4 r_dst_offset /* GPR codes: PARAMETERIZED offsets (caller passes O_ macros) */
, U4 r_src_ptr, U4 r_dst_ptr, U4 r_tmp /* GPR codes: 3 scratch regs (src/dst computed + tmp) */
, U4 r_mac1_scratch, U4 r_mac2_scratch /* GPR codes: 2 more: MAC1/MAC2 scratch */
, U4 r_recip_est /* GPR code: |v|² sum + shift-input + sqrtbl[index] */
, U4 r_lzcr, U4 r_shift /* GPR codes: lzcr + final srav amount */
, U4 r_branch_tmp /* GPR code: scratch (shift count, branch target, lookup addr) */
)
MipsAtom_Proc_(normalize_v3s4, ab, { MipsAtom_Proc_(normalize_v3s4, ab, {
/* ── I/O wrapper (~10 words: 3 bind-pop + 3 src-load + 1 nop + 3 dst-store) ─── */ add_si(r_src_ptr, r_scratch, r_src_offset), /* r_src_ptr = &src */
load_word(r_src, R_TapePtr, O_(Binds_NormalizeV3S4,src)), /* pop src ptr (scratch addr) */ add_si(r_dst_ptr, r_scratch, r_dst_offset), /* r_dst_ptr = &dst */
load_word(r_dst, R_TapePtr, O_(Binds_NormalizeV3S4,dst)), /* pop dst ptr (scratch addr) */ nop,
add_ui_self( R_TapePtr, S_(Binds_NormalizeV3S4)),
load_word(r_sx, r_src, O_(V3_S4,x)), /* Load src.x/y/z from r_src_ptr (caller-determined address) into r_mac2_scratch/r_recip_est/r_branch_tmp. */
load_word(r_sy, r_src, O_(V3_S4,y)), load_word(r_mac2_scratch, r_src_ptr, O_(V3_S4,x)),
load_word(r_sz, r_src, O_(V3_S4,z)), load_word(r_recip_est, r_src_ptr, O_(V3_S4,y)),
load_word(r_branch_tmp, r_src_ptr, O_(V3_S4,z)),
nop, /* load-delay */ nop, /* load-delay */
/* ── 48-word normalize body (preserved verbatim from ac_normalize_v3s4) ─────── */ /* Stage 1: mtc2 src → IR1/2/3, SQR fires. */
// Stage 1: mtc2 src → IR1/2/3, SQR fires (MAC1/2/3 = IR², IR ← MAC saturated) gte_mv_to_data_r(r_mac2_scratch, C2_IR1),
gte_mv_to_data_r(r_sx, C2_IR1), gte_mv_to_data_r(r_recip_est, C2_IR2),
gte_mv_to_data_r(r_sy, C2_IR2), gte_mv_to_data_r(r_branch_tmp, C2_IR3),
gte_mv_to_data_r(r_sz, C2_IR3),
nop, gte_cmdw_sqr, nop, gte_cmdw_sqr,
// Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS
gte_mv_from_data_r(r_sq_y, C2_MAC1), /* r_sq_y = MAC1 = sx² */ /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */
gte_mv_from_data_r(r_sq_z, C2_MAC2), /* r_sq_z = MAC2 = sy² */ gte_mv_from_data_r(r_mac1_scratch, C2_MAC1),
gte_mv_from_data_r(r_recip_est, C2_MAC3), /* r_recip_est = MAC3 = sz² */ gte_mv_from_data_r(r_mac2_scratch, C2_MAC2),
nop, /* MFC2→GPR load delay (1 slot) */ gte_mv_from_data_r(r_lzcr, C2_MAC3),
add_u(r_recip_est, r_recip_est, r_sq_z), /* r_recip_est += sy² */ nop,
add_u(r_recip_est, r_recip_est, r_sq_y), /* r_recip_est += sx² (sum = |v|²) */ add_u(r_lzcr, r_lzcr, r_mac2_scratch),
gte_mv_to_data_r( r_recip_est, C2_LZCS), /* LZCS = |v|² */ add_u(r_lzcr, r_lzcr, r_mac1_scratch),
gte_mv_to_data_r(r_lzcr, C2_LZCS),
nop2, nop2,
gte_mv_from_data_r(r_lzcr, C2_LZCR), /* r_lzcr = LZCR (count of leading bits) */ gte_mv_from_data_r(r_shift, C2_LZCR),
nop, /* MFC2→GPR load delay (1 slot) */ nop,
// Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v|
and_i( r_lzcr, r_lzcr, -2), /* r_lzcr &= ~1 (force even for halving) */
li_s( r_shift, 31), /* r_shift = 31 */
sub_s( r_shift, r_shift, r_lzcr), /* r_shift = 31 - LZCR */
shift_aright( r_shift, r_shift, 1), /* r_shift = (31 - LZCR) / 2 */
add_si( r_tmp, r_lzcr, -24), /* r_tmp = LZCR - 24 (signed, for branch) */
branch_lt_zero(r_tmp, atom_offset(srav_path, aligned_done)), nop,
jump_rel( atom_offset(aligned_done, srav_path)),
shift_lleft_var(r_recip_est, r_recip_est, r_tmp), /* BD-slot of branch_equal: r_recip_est = |v|² << (LZCR - 24) */
atom_label(srav_path) /* SRAV path: |v|² is small (top bit < bit 24) */
li_s( r_tmp, 24),
sub_s( r_tmp, r_tmp, r_lzcr), /* r_tmp = 24 - LZCR */
shift_aright_var(r_recip_est, r_recip_est, r_tmp), /* r_recip_est = |v|² >> (24 - LZCR) */
atom_label(aligned_done) /* Both paths converge here with |v|² aligned to bit 24 */
/* r_recip_est now holds |v|² aligned to bit 24 — convert to byte offset, -64 to skip zero pad. */
add_si( r_recip_est, r_recip_est, -64),
shift_lleft( r_recip_est, r_recip_est, 1), /* r_recip_est *= 2 (half-word index) */
/* Reference OUR local sqrtbl via &-address split. Compiler/linker resolves both halves. */
load_upper_i( r_tmp, u4_hi(& gte_normalize_sqr_tbl)), /* lui */
or_i_self( r_tmp, u4_lo(& gte_normalize_sqr_tbl)), /* ori */
add_u( r_tmp, r_tmp, r_recip_est), /* r_tmp = sqrtbl base + byte offset (matches libgte 0x80016118: addu t5,t5,t4) */
load_half( r_recip_est, r_tmp, 0), /* r_recip_est = sqrtbl[r_recip_est] = 1/|v| estimate */
nop, /* retire load_half before MTC2 (matches libgte 0x80016120: nop) */
// Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize
gte_mv_to_data_r(r_recip_est, C2_IR0), /* IR0 = 1/|v| estimate */
gte_mv_to_data_r(r_sx, C2_IR1), /* IR1 = src.x */
gte_mv_to_data_r(r_sy, C2_IR2), /* IR2 = src.y */
gte_mv_to_data_r(r_sz, C2_IR3), /* IR3 = src.z */
nop2, /* COP2 transfer latency (2 slots) */
gte_cmdw_gpf,
gte_mv_from_data_r(r_sx, C2_MAC1), /* MAC1 → r_sx (overwrites src.x with raw reciprocal-scaled) */
gte_mv_from_data_r(r_sy, C2_MAC2),
gte_mv_from_data_r(r_sz, C2_MAC3),
shift_aright_var(r_sx, r_sx, r_shift),
shift_aright_var(r_sy, r_sy, r_shift),
shift_aright_var(r_sz, r_sz, r_shift),
/* ── I/O wrapper tail (~3 words) ───────────────────────────────────────────── */ /* Stage 3: compute srav amount (r_lzcr) + align |v|² to bit 24. */
store_word(r_sx, r_dst, O_(V3_S4,x)), and_i( r_shift, r_shift, -2),
store_word(r_sy, r_dst, O_(V3_S4,y)), li_s( r_lzcr, 31),
store_word(r_sz, r_dst, O_(V3_S4,z)), sub_s( r_lzcr, r_lzcr, r_shift),
shift_aright(r_lzcr, r_lzcr, 1),
/* r_branch_tmp = LZCR - 24 (overwrites r_branch_tmp; src.z no longer needed after SQR) */
add_si( r_branch_tmp, r_shift, -24),
branch_lt_zero(r_branch_tmp, atom_offset(srav_path, aligned_done)), nop,
jump_rel(atom_offset(aligned_done, srav_path)),
shift_lleft_var(r_lzcr, r_lzcr, r_branch_tmp), /* when r_branch_tmp < 0 (LZCR < 24): shift r_lzcr left by (24-LZCR) */
atom_label(srav_path)
li_s( r_branch_tmp, 24),
sub_s( r_branch_tmp, r_branch_tmp, r_shift),
shift_aright_var(r_lzcr, r_lzcr, r_branch_tmp), /* when r_branch_tmp >= 0 (LZCR >= 24): shift r_lzcr right by (LZCR-24) */
atom_label(aligned_done)
/* r_lzcr holds |v|² aligned to bit 24. */
add_si( r_lzcr, r_lzcr, -64),
shift_lleft(r_lzcr, r_lzcr, 1),
load_upper_i(r_branch_tmp, u4_hi(& gte_normalize_sqr_tbl)),
or_i_self( r_branch_tmp, u4_lo(& gte_normalize_sqr_tbl)),
add_u(r_branch_tmp, r_branch_tmp, r_lzcr),
load_half(r_lzcr, r_branch_tmp, 0), nop,
/* Stage 4: GPF + srav finalize (r_lzcr = srav_amount carried from stage 3). */
gte_mv_to_data_r(r_lzcr, C2_IR0),
gte_mv_to_data_r(r_mac2_scratch, C2_IR1),
gte_mv_to_data_r(r_recip_est, C2_IR2),
gte_mv_to_data_r(r_branch_tmp, C2_IR3),
nop2, gte_cmdw_gpf,
gte_mv_from_data_r(r_mac2_scratch, C2_MAC1),
gte_mv_from_data_r(r_recip_est, C2_MAC2),
gte_mv_from_data_r(r_branch_tmp, C2_MAC3),
shift_aright_var(r_mac2_scratch, r_mac2_scratch, r_lzcr),
shift_aright_var(r_recip_est, r_recip_est, r_lzcr),
shift_aright_var(r_branch_tmp, r_branch_tmp, r_lzcr),
/* Store result.x/y/z to r_dst_ptr (caller-determined dst address). */
store_word(r_mac2_scratch, r_dst_ptr, O_(V3_S4,x)),
store_word(r_recip_est, r_dst_ptr, O_(V3_S4,y)),
store_word(r_branch_tmp, r_dst_ptr, O_(V3_S4,z)),
/* ── atom_reads(R_TapePtr) atom_writes(R_TapePtr) ────────────────────────── */
mac_yield() mac_yield()
}) })
#pragma endregion MACs (Mips Atom Components) #pragma endregion Atom Procs
#pragma region Bsked Atoms #pragma region Baked Atoms
typedef Struct_(Binds_SetGteMT3S2S4) { typedef Struct_(Binds_SetGteMT3S2S4) {
MT3_S2S4* transform; MT3_S2S4* transform;
+11 -6
View File
@@ -27,9 +27,9 @@
* to author and compose programs with. From here various conventions can be further applied. * to author and compose programs with. From here various conventions can be further applied.
* To make things easier to understand it may be better to focus on what this ABI does not have. * To make things easier to understand it may be better to focus on what this ABI does not have.
* It does not have have any branching within the tape but relative branches within atoms or between atoms. * It does not have have any branching within the tape but relative branches within atoms or between atoms.
* Branching nearly is always downstream. Stack usage is non-existent. * Branching nearly is always downstream. Atuomatic stack usage is non-existent.
* Push/Pop, FIFO, or Arena/Bump data structures are used by atoms explicitly. * Push/Pop, FIFO, or Arena/Bump data structures are used by atoms explicitly.
* In it's current form with the C11 macro dsl, the user also has fullfill manual register allocation per atom. * In it's current form with the C11 macro DSL, the user also has fullfill manual register allocation per atom.
* *
* One of the remarkable things about utilizing this ABI is its essentially interopable with CPUs, GPUs, FPGA, * One of the remarkable things about utilizing this ABI is its essentially interopable with CPUs, GPUs, FPGA,
* or, basically anything from the 5th generation consoles and onward. * or, basically anything from the 5th generation consoles and onward.
@@ -186,14 +186,14 @@ FI_ void tape_run_a02_s07(Tape tape) { register U4* tape_ptr rgcc(R_TapePtr) = u
typedef Relative_(FArena) Struct_(TapeBuilder) { U4 ptr; U4 capacity; U4 used; }; typedef Relative_(FArena) Struct_(TapeBuilder) { U4 ptr; U4 capacity; U4 used; };
FI_ void tb_init(TapeBuilder* tb, FArena* arena) { tb->ptr = arena->start; tb->used = 0; } FI_ void tb_init(TapeBuilder* tb, FArena* arena) { tb->ptr = arena->start; tb->used = 0; }
FI_ TapeBuilder tb_make_old( FArena* arena) { return (TapeBuilder){ arena->start, 0 }; } FI_ TapeBuilder tb_make_old( FArena* arena) { return (TapeBuilder){ arena->start, 0 }; }
FI_ TapeBuilder tb_make(Slice mem) { return (TapeBuilder){ mem.ptr, mem.len, 0 }; } FI_ TapeBuilder tb_make(Slice mem) { return (TapeBuilder){ u4_(mem.ptr), mem.len, 0 }; } /* capacity in elements (matches used units) */
FI_ void tb_emit(TapeBuilder* tb, MipsAtom* atom) { u4_r(tb->ptr)[tb->used] = u4_(atom); ++ tb->used; } FI_ void tb_emit(TapeBuilder* tb, MipsAtom* atom) { u4_r(tb->ptr)[tb->used] = u4_(atom); ++ tb->used; }
FI_ void tb_data(TapeBuilder* tb, U4 data) { u4_r(tb->ptr)[tb->used] = u4_(data); ++ tb->used; } FI_ void tb_data(TapeBuilder* tb, U4 data) { u4_r(tb->ptr)[tb->used] = u4_(data); ++ tb->used; }
#define tb_emit_(atom) tb_emit(& tb, atom) #define tb_emit_(atom) tb_emit(& tb, atom)
#define tb_data_(field, data) tb_data(& tb, u4_(data)) #define tb_data_(field, data) tb_data(& tb, u4_(data))
FI_ void tb_emit_bundle(TapeBuilder_R tb, Slice_MipsAtom atoms) { mem_copy(u4_(tb->ptr), u4_(atoms.ptr), tb->used); tb->used += atoms.len; } FI_ void tb_emit_bundle(TapeBuilder_R tb, Slice_MipsAtom atoms) { mem_copy(u4_(tb->ptr), u4_(atoms.ptr), S_slice(atoms)); tb->used += atoms.len; }
FI_ Tape tb_end (TapeBuilder* tb) { tb_emit(tb,tape_exit); return (Tape){ C_(U4*,tb->ptr), tb->used }; } FI_ Tape tb_end (TapeBuilder* tb) { tb_emit(tb,tape_exit); return (Tape){ C_(U4*,tb->ptr), tb->used }; }
FI_ Tape tb_slice(TapeBuilder tb) { return (Tape){ C_(U4*,tb.ptr), tb.used }; } FI_ Tape tb_slice(TapeBuilder tb) { return (Tape){ C_(U4*,tb.ptr), tb.used }; }
@@ -242,18 +242,23 @@ typedef Relative_(FArena) Struct_(MipsAtomBuilder) { U4 start; U4 capacity; U4 u
// to something that can fit within instruction cache? // to something that can fit within instruction cache?
FI_ void atombuilder_unroll(MipsAtomBuilder_R ab, Slice_MipsCode code) { FI_ void atombuilder_unroll(MipsAtomBuilder_R ab, Slice_MipsCode code) {
/* code.len is in ELEMENTS (per slice_from_array convention); ab->used is also in elements
* (the init uses `ab->used * sizeof(U4)` for byte offset arithmetic — sizeof(U4)==4==sizeof(MipsCode)).
* mem_copy needs BYTES, so we use S_slice(code) for the length. */
assert(ab->capacity - ab->used - code.len); assert(ab->capacity - ab->used - code.len);
U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot (arena accumulation) */ U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot (arena accumulation) */
mem_copy(u4_(dest), u4_(code.ptr), code.len); mem_copy(u4_(dest), u4_(code.ptr), S_slice(code));
mem_bump(ab->start, ab->capacity, & ab->used, code.len); mem_bump(ab->start, ab->capacity, & ab->used, code.len);
} }
#define atombuilder_unroll_mac(ab, mac) atombuilder_unroll(ab, slice_arg_from_array(Slice_MipsCode, mac)) #define atombuilder_unroll_mac(ab, mac) atombuilder_unroll(ab, slice_arg_from_array(Slice_MipsCode, mac))
// When done authoring, utilize this to cap-off the atom (if not utilizing a MipsAtom_Proc). // When done authoring, utilize this to cap-off the atom (if not utilizing a MipsAtom_Proc).
FI_ void atombuilder_end(MipsAtomBuilder_R ab) { FI_ void atombuilder_end(MipsAtomBuilder_R ab) {
/* ac_yield is a MipsCode[] of 4 elements; S_(ac_yield)=bytes, array_len(ac_yield)=elements.
* ab->used is in elements, so mem_bump needs element count. */
U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot */ U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot */
mem_copy(u4_(dest), u4_(ac_yield), S_(ac_yield)); mem_copy(u4_(dest), u4_(ac_yield), S_(ac_yield));
mem_bump(ab->start, ab->capacity, & ab->used, S_(ac_yield)); mem_bump(ab->start, ab->capacity, & ab->used, array_len(ac_yield));
} }
#define mipsatom_from_builder(ab) C_(MipsAtom*, (ab).start) #define mipsatom_from_builder(ab) C_(MipsAtom*, (ab).start)
+10 -10
View File
@@ -58,13 +58,13 @@ typedef Struct_(Str8) { UTF8* ptr; U4 len; };
typedef Struct_(Slice_Str8) { Str8* ptr; U4 len; }; typedef Struct_(Slice_Str8) { Str8* ptr; U4 len; };
#define slit(string_literal) (Str8){ (UTF8*) string_literal, S_(string_literal) - 1 } #define slit(string_literal) (Str8){ (UTF8*) string_literal, S_(string_literal) - 1 }
typedef Struct_(Slice) { U4 ptr, len; }; // Untyped Slice typedef Struct_(Slice) { B1* ptr; U4 len; }; // Untyped Slice (byte-addressable; .len in elements)
FI_ Slice slice_ut_(U4 ptr, U4 len) { return (Slice){ptr, len}; } FI_ Slice slice_ut_(U4 ptr, U4 len) { return (Slice){(B1*)ptr, len}; }
#define Slice_(type) Struct_(tmpl(Slice,type)) { type* ptr; U4 len; } #define Slice_(type) Struct_(tmpl(Slice,type)) { type* ptr; U4 len; }
typedef Slice_(B1); typedef Slice_(B1);
#define slice_assert(s) do { assert((s).ptr != 0); assert((s).len > 0); } while(0) #define slice_assert(s) do { assert((s).ptr != 0); assert((s).len > 0); } while(0)
#define slice_end(slice) ((slice).ptr + (slice).len) #define slice_end(slice) ((slice).ptr + S_slice(slice) / S_(B1)) /* byte-ptr arithmetic; .len is in elements per slice convention */
#define S_slice(s) ((s).len * S_((s).ptr[0])) #define S_slice(s) ((s).len * S_((s).ptr[0]))
#define slice_ut(ptr,len) slice_ut_(u4_(ptr), u4_(len)) #define slice_ut(ptr,len) slice_ut_(u4_(ptr), u4_(len))
@@ -73,16 +73,16 @@ typedef Slice_(B1);
#define slice_iter(container, iter) (T_((container).ptr) iter = (container).ptr; iter != slice_end(container); ++ iter) #define slice_iter(container, iter) (T_((container).ptr) iter = (container).ptr; iter != slice_end(container); ++ iter)
#define slice_arg_from_array(type, ...) & (tmpl(Slice,type)) { .ptr = array_decl(type,__VA_ARGS__), .len = array_len( array_decl(type,__VA_ARGS__)) } #define slice_arg_from_array(type, ...) & (tmpl(Slice,type)) { .ptr = array_decl(type,__VA_ARGS__), .len = array_len( array_decl(type,__VA_ARGS__)) }
#define slice_from_array(type, array) (tmpl(Slice,type)) { .ptr = array, .len = S_(array) } #define slice_from_array(type, array) (tmpl(Slice,type)) { .ptr = array, .len = S_(array) / S_(type) } /* .len in elements (matches S_slice/slice_arg_from_array convention) */
FI_ void slice_zero_(Slice s) { slice_assert(s); mem_zero(s.ptr, s.len); } FI_ void slice_zero_(Slice s) { slice_assert(s); mem_zero(u4_(s.ptr), S_slice(s)); }
#define slice_zero(s) slice_zero_(slice_to_ut(s)) #define slice_zero(s) slice_zero_(slice_to_ut(s))
FI_ void slice_copy_(Slice dest, Slice src) { FI_ void slice_copy_(Slice dest, Slice src) {
assert(dest.len >= src.len); assert(S_slice(dest) >= S_slice(src));
slice_assert(dest); slice_assert(dest);
slice_assert(src); slice_assert(src);
mem_copy(dest.ptr, src.ptr, src.len); mem_copy(u4_(dest.ptr), u4_(src.ptr), S_slice(src));
} }
#define slice_copy(dest, src) do { \ #define slice_copy(dest, src) do { \
static_assert(T_same(dest, src)); \ static_assert(T_same(dest, src)); \
@@ -98,8 +98,8 @@ typedef Slice_(U4);
typedef Opt_(farena) { U4 alignment, type_width; }; typedef Opt_(farena) { U4 alignment, type_width; };
typedef Struct_(FArena) { U4 start, capacity, used; }; typedef Struct_(FArena) { U4 start, capacity, used; };
FI_ void farena_init(FArena_R arena, Slice mem) { assert(arena != nullptr); FI_ void farena_init(FArena_R arena, Slice mem) { assert(arena != nullptr);
arena->start = mem.ptr; arena->start = u4_(mem.ptr);
arena->capacity = mem.len; arena->capacity = S_slice(mem); /* FArena.used is in BYTES; capacity must be bytes too */
arena->used = 0; arena->used = 0;
} }
FI_ FArena farena_make(Slice mem) { FArena a; farena_init(& a, mem); return a; } FI_ FArena farena_make(Slice mem) { FArena a; farena_init(& a, mem); return a; }
@@ -109,7 +109,7 @@ I_ Slice farena_push(FArena_R arena, U4 amount, Opt_farena o) {
U4 to_commit = align_pow2(desired, o.alignment ? o.alignment : MEM_ALIGNMENT_DEFAULT); U4 to_commit = align_pow2(desired, o.alignment ? o.alignment : MEM_ALIGNMENT_DEFAULT);
U4 ptr = arena->start + arena->used; U4 ptr = arena->start + arena->used;
mem_bump(arena->start, arena->capacity, & arena->used, to_commit); mem_bump(arena->start, arena->capacity, & arena->used, to_commit);
return (Slice){ ptr, to_commit }; return (Slice){ (B1*)ptr, to_commit };
} }
FI_ void farena_reset (FArena_R arena) { arena->used = 0; } FI_ void farena_reset (FArena_R arena) { arena->used = 0; }
FI_ void farena_rewind(FArena_R arena, U4 save_point) { FI_ void farena_rewind(FArena_R arena, U4 save_point) {
+13
View File
@@ -0,0 +1,13 @@
#ifdef INTELLISENSE_DIRECTIVES
#pragma once
#endif
// Auto-generated by ps1_meta.lua (passes/auto_reg.lua) — DO NOT EDIT
// Directory: C:\projects\Pikuma\ps1\code\hello_camera
// source: C:/projects/Pikuma/ps1/code/hello_camera/hello_camera.c
// source: C:/projects/Pikuma/ps1/code/hello_camera/hello_camera.h
// source: C:/projects/Pikuma/ps1/code/hello_camera/hello_camera.atom.c
// Per-phase register allocations resolved by the lua pass.
// R_<Sym>_Code = <chosen GPR's _Code constant> for every marker in this directory.
#define R_GpTmp_Code R_V0_Code
-347
View File
@@ -39,350 +39,3 @@ WORD_COUNT(mac_put_disp_env, 5)
, mac_gcmd_push(gp0_word_nop(), reg_transfer, reg_base, port) , mac_gcmd_push(gp0_word_nop(), reg_transfer, reg_base, port)
WORD_COUNT(mac_put_draw_env, 16) WORD_COUNT(mac_put_draw_env, 16)
#define mac_resolve_look_at__input_and_sub(...) \
load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)) \
, load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)) \
, load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)) \
, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)) \
, load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtScratch,scratch_base)) \
, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtScratch)) /* Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation
* column). Reuse r_tmp0/r_tmp1/r_tmp2. Offsets via O_(ResolveLookAtScratch,*). */ \
, load_word(r_tmp0, r_eye_ptr, O_(P3_S4,x)) \
, load_word(r_tmp1, r_eye_ptr, O_(P3_S4,y)) \
, load_word(r_tmp2, r_eye_ptr, O_(P3_S4,z)) \
, nop /* load-delay */ \
, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,eye.x)) \
, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,eye.y)) \
, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,eye.z)) /* Stage up_in.x/y/z into the scratchpad (atom 2 reads these for the outer
* product with uz). Reuse r_tmp0/r_tmp1/r_tmp2. */ \
, load_word(r_tmp0, r_up_in_ptr, O_(V3_S4,x)) \
, load_word(r_tmp1, r_up_in_ptr, O_(V3_S4,y)) \
, load_word(r_tmp2, r_up_in_ptr, O_(V3_S4,z)) \
, nop /* load-delay */ \
, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,up_in.x)) \
, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,up_in.y)) \
, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,up_in.z)) /* Compute fwd = target - eye. */ \
, load_word(r_tmp0, r_target_ptr, O_(P3_S4,x)) \
, load_word(r_tmp1, r_target_ptr, O_(P3_S4,y)) \
, load_word(r_tmp2, r_target_ptr, O_(P3_S4,z)) \
, load_word(r_tmp3, r_eye_ptr, O_(P3_S4,x)) \
, load_word(R_AT, r_eye_ptr, O_(P3_S4,y)) \
, load_word(R_V0, r_eye_ptr, O_(P3_S4,z)) \
, nop /* load-delay */ \
, sub_u(r_tmp0, r_tmp0, r_tmp3) \
, sub_u(r_tmp1, r_tmp1, R_AT) \
, sub_u(r_tmp2, r_tmp2, R_V0) /* Store fwd.x/y/z (atom 1 reads these as the normalize src). */ \
, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,fwd.x)) \
, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,fwd.y)) \
, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,fwd.z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__input_and_sub, 34)
#define mac_resolve_look_at__cross_uz_up_in_to_right(...) \
add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_g = &uz */ \
, add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)) /* r_h = &up_in */ \
, add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)) /* r_f = &right (out) */ \
, nop /* Load a (uz).x/y/z into r_a/r_b/r_c. */ \
, load_word(r_a, r_g, O_(V3_S4,x)) \
, load_word(r_b, r_g, O_(V3_S4,y)) \
, load_word(r_c, r_g, O_(V3_S4,z)) \
, nop /* Load b (up_in).x/y/z into r_d + R_AT/R_V0 (hardcoded; reusing the
* body's last two loads is fine because the load-delay slot is the nop
* after the third load, and mtc2 below doesn't read these regs). */ \
, load_word(r_d, r_h, O_(V3_S4,x)) \
, load_word(R_AT, r_h, O_(V3_S4,y)) \
, load_word(R_V0, r_h, O_(V3_S4,z)) \
, nop /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ \
, gte_mv_to_data_r(r_a, C2_IR1) \
, gte_mv_to_data_r(r_b, C2_IR2) \
, gte_mv_to_data_r(r_c, C2_IR3) \
, gte_mv_to_data_r(r_d, C2_VXY0) /* D1 = b.x */ \
, gte_mv_to_data_r(R_AT, C2_VZ0) /* D2 = b.y */ \
, gte_mv_to_data_r(R_V0, C2_VXY1) /* D3 = b.z */ \
, nop2 /* MTC2 retirement (CPU→COP2 2-slot delay) */ \
, gte_cmdw_outer_product /* OP fires; MAC1/2/3 = a × b */ /* mfc2 MAC1/2/3 → r_a/r_b/r_c (out.x/y/z). */ \
, gte_mv_from_data_r(r_a, C2_MAC1) \
, gte_mv_from_data_r(r_b, C2_MAC2) \
, gte_mv_from_data_r(r_c, C2_MAC3) \
, nop /* MFC2 retirement */ /* Store out.x/y/z to r_f (out ptr = scratch+32). */ \
, store_word(r_a, r_f, O_(V3_S4,x)) \
, store_word(r_b, r_f, O_(V3_S4,y)) \
, store_word(r_c, r_f, O_(V3_S4,z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__cross_uz_up_in_to_right, 29)
#define mac_resolve_look_at__cross_uz_ux_to_up(...) \
add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_g = &uz */ \
, add_si(r_h, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_h = &ux */ \
, add_si(r_f, r_scratch, O_(ResolveLookAtScratch,up)) /* r_f = &up (out) */ \
, nop /* Load a (uz).x/y/z into r_a/r_b/r_c. */ \
, load_word(r_a, r_g, O_(V3_S4,x)) \
, load_word(r_b, r_g, O_(V3_S4,y)) \
, load_word(r_c, r_g, O_(V3_S4,z)) \
, nop /* Load b (ux).x/y/z into r_d + R_AT/R_V0. */ \
, load_word(r_d, r_h, O_(V3_S4,x)) \
, load_word(R_AT, r_h, O_(V3_S4,y)) \
, load_word(R_V0, r_h, O_(V3_S4,z)) \
, nop /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ \
, gte_mv_to_data_r(r_a, C2_IR1) \
, gte_mv_to_data_r(r_b, C2_IR2) \
, gte_mv_to_data_r(r_c, C2_IR3) \
, gte_mv_to_data_r(r_d, C2_VXY0) \
, gte_mv_to_data_r(R_AT, C2_VZ0) \
, gte_mv_to_data_r(R_V0, C2_VXY1) \
, nop2 \
, gte_cmdw_outer_product \
, gte_mv_from_data_r(r_a, C2_MAC1) \
, gte_mv_from_data_r(r_b, C2_MAC2) \
, gte_mv_from_data_r(r_c, C2_MAC3) \
, nop \
, store_word(r_a, r_f, O_(V3_S4,x)) \
, store_word(r_b, r_f, O_(V3_S4,y)) \
, store_word(r_c, r_f, O_(V3_S4,z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__cross_uz_ux_to_up, 29)
#define mac_resolve_look_at__normalize_fwd_to_uz(...) \
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,fwd)) /* r_a = &fwd */ \
, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_b = &uz */ \
, nop /* Load src.x/y/z from r_a into r_e/r_f/r_i. */ \
, load_word(r_e, r_a, O_(V3_S4,x)) \
, load_word(r_f, r_a, O_(V3_S4,y)) \
, load_word(r_i, r_a, O_(V3_S4,z)) \
, nop /* load-delay */ /* Stage 1: mtc2 src → IR1/2/3, SQR fires. */ \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop \
, gte_cmdw_sqr /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */ \
, gte_mv_from_data_r(r_d, C2_MAC1) \
, gte_mv_from_data_r(r_g, C2_MAC2) \
, gte_mv_from_data_r(r_recip_est, C2_MAC3) \
, nop \
, add_u(r_recip_est, r_recip_est, r_g) \
, add_u(r_recip_est, r_recip_est, r_d) \
, gte_mv_to_data_r(r_recip_est, C2_LZCS) \
, nop2 \
, gte_mv_from_data_r(r_h, C2_LZCR) \
, nop /* Stage 3: compute shift amount, align |v|² to bit 24. */ \
, and_i( r_h, r_h, -2) \
, li_s( r_shift, 31) \
, sub_s( r_shift, r_shift, r_h) \
, shift_aright(r_shift, r_shift, 1) \
, add_si( r_a, r_h, -24) /* r_a = LZCR - 24 (overlapping with r_recip_est; src ptr no longer needed) */ \
, branch_lt_zero(r_a, atom_offset(srav_path_fwd_to_uz, aligned_done_fwd_to_uz)) \
, nop \
, jump_rel(atom_offset(aligned_done_fwd_to_uz, srav_path_fwd_to_uz)) \
, shift_lleft_var(r_recip_est, r_recip_est, r_a) \
, atom_label(srav_path_fwd_to_uz) \
, li_s( r_a, 24) \
, sub_s( r_a, r_a, r_h) \
, shift_aright_var(r_recip_est, r_recip_est, r_a) \
, atom_label(aligned_done_fwd_to_uz) /* r_recip_est holds |v|² aligned to bit 24. */ \
, add_si( r_recip_est, r_recip_est, -64) \
, shift_lleft(r_recip_est, r_recip_est, 1) \
, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \
, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \
, add_u(r_a, r_a, r_recip_est) \
, load_half(r_recip_est, r_a, 0) \
, nop /* Stage 4: GPF + srav finalize. */ \
, gte_mv_to_data_r(r_recip_est, C2_IR0) \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop2 \
, gte_cmdw_gpf \
, gte_mv_from_data_r(r_e, C2_MAC1) \
, gte_mv_from_data_r(r_f, C2_MAC2) \
, gte_mv_from_data_r(r_i, C2_MAC3) \
, shift_aright_var(r_e, r_e, r_shift) \
, shift_aright_var(r_f, r_f, r_shift) \
, shift_aright_var(r_i, r_i, r_shift) /* Store result.x/y/z to r_b (dst ptr = scratch+16). */ \
, store_word(r_e, r_b, O_(V3_S4,x)) \
, store_word(r_f, r_b, O_(V3_S4,y)) \
, store_word(r_i, r_b, O_(V3_S4,z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__normalize_fwd_to_uz, 59)
#define mac_resolve_look_at__normalize_right_to_ux(...) \
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,right)) /* r_a = &right */ \
, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_b = &ux */ \
, nop \
, load_word(r_e, r_a, O_(V3_S4,x)) \
, load_word(r_f, r_a, O_(V3_S4,y)) \
, load_word(r_i, r_a, O_(V3_S4,z)) \
, nop \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop \
, gte_cmdw_sqr \
, gte_mv_from_data_r(r_d, C2_MAC1) \
, gte_mv_from_data_r(r_g, C2_MAC2) \
, gte_mv_from_data_r(r_recip_est, C2_MAC3) \
, nop \
, add_u(r_recip_est, r_recip_est, r_g) \
, add_u(r_recip_est, r_recip_est, r_d) \
, gte_mv_to_data_r(r_recip_est, C2_LZCS) \
, nop2 \
, gte_mv_from_data_r(r_h, C2_LZCR) \
, nop \
, and_i( r_h, r_h, -2) \
, li_s( r_shift, 31) \
, sub_s( r_shift, r_shift, r_h) \
, shift_aright(r_shift, r_shift, 1) \
, add_si( r_a, r_h, -24) \
, branch_lt_zero(r_a, atom_offset(srav_path_right_to_ux, aligned_done_right_to_ux)) \
, nop \
, jump_rel(atom_offset(aligned_done_right_to_ux, srav_path_right_to_ux)) \
, shift_lleft_var(r_recip_est, r_recip_est, r_a) \
, atom_label(srav_path_right_to_ux) \
, li_s( r_a, 24) \
, sub_s( r_a, r_a, r_h) \
, shift_aright_var(r_recip_est, r_recip_est, r_a) \
, atom_label(aligned_done_right_to_ux) \
, add_si( r_recip_est, r_recip_est, -64) \
, shift_lleft(r_recip_est, r_recip_est, 1) \
, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \
, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \
, add_u(r_a, r_a, r_recip_est) \
, load_half(r_recip_est, r_a, 0) \
, nop \
, gte_mv_to_data_r(r_recip_est, C2_IR0) \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop2 \
, gte_cmdw_gpf \
, gte_mv_from_data_r(r_e, C2_MAC1) \
, gte_mv_from_data_r(r_f, C2_MAC2) \
, gte_mv_from_data_r(r_i, C2_MAC3) \
, shift_aright_var(r_e, r_e, r_shift) \
, shift_aright_var(r_f, r_f, r_shift) \
, shift_aright_var(r_i, r_i, r_shift) \
, store_word(r_e, r_b, O_(V3_S4,x)) \
, store_word(r_f, r_b, O_(V3_S4,y)) \
, store_word(r_i, r_b, O_(V3_S4,z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__normalize_right_to_ux, 59)
#define mac_resolve_look_at__normalize_up_to_uy(...) \
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,up)) /* r_a = &up */ \
, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uy)) /* r_b = &uy */ \
, nop \
, load_word(r_e, r_a, O_(V3_S4,x)) \
, load_word(r_f, r_a, O_(V3_S4,y)) \
, load_word(r_i, r_a, O_(V3_S4,z)) \
, nop \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop \
, gte_cmdw_sqr \
, gte_mv_from_data_r(r_d, C2_MAC1) \
, gte_mv_from_data_r(r_g, C2_MAC2) \
, gte_mv_from_data_r(r_recip_est, C2_MAC3) \
, nop \
, add_u(r_recip_est, r_recip_est, r_g) \
, add_u(r_recip_est, r_recip_est, r_d) \
, gte_mv_to_data_r(r_recip_est, C2_LZCS) \
, nop2 \
, gte_mv_from_data_r(r_h, C2_LZCR) \
, nop \
, and_i( r_h, r_h, -2) \
, li_s( r_shift, 31) \
, sub_s( r_shift, r_shift, r_h) \
, shift_aright(r_shift, r_shift, 1) \
, add_si( r_a, r_h, -24) \
, branch_lt_zero(r_a, atom_offset(srav_path_up_to_uy, aligned_done_up_to_uy)) \
, nop \
, jump_rel(atom_offset(aligned_done_up_to_uy, srav_path_up_to_uy)) \
, shift_lleft_var(r_recip_est, r_recip_est, r_a) \
, atom_label(srav_path_up_to_uy) \
, li_s( r_a, 24) \
, sub_s( r_a, r_a, r_h) \
, shift_aright_var(r_recip_est, r_recip_est, r_a) \
, atom_label(aligned_done_up_to_uy) \
, add_si( r_recip_est, r_recip_est, -64) \
, shift_lleft(r_recip_est, r_recip_est, 1) \
, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \
, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \
, add_u(r_a, r_a, r_recip_est) \
, load_half(r_recip_est, r_a, 0) \
, nop \
, gte_mv_to_data_r(r_recip_est, C2_IR0) \
, gte_mv_to_data_r(r_e, C2_IR1) \
, gte_mv_to_data_r(r_f, C2_IR2) \
, gte_mv_to_data_r(r_i, C2_IR3) \
, nop2 \
, gte_cmdw_gpf \
, gte_mv_from_data_r(r_e, C2_MAC1) \
, gte_mv_from_data_r(r_f, C2_MAC2) \
, gte_mv_from_data_r(r_i, C2_MAC3) \
, shift_aright_var(r_e, r_e, r_shift) \
, shift_aright_var(r_f, r_f, r_shift) \
, shift_aright_var(r_i, r_i, r_shift) \
, store_word(r_e, r_b, O_(V3_S4,x)) \
, store_word(r_f, r_b, O_(V3_S4,y)) \
, store_word(r_i, r_b, O_(V3_S4,z)) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__normalize_up_to_uy, 59)
#define mac_resolve_look_at__populate_and_translate(...) \
load_word(r_look_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)) \
, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)) /* Compute the 4 scratch pointers in their dedicated GPRs. */ \
, add_si(r_pux, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_pux = &ux */ \
, add_si(r_puy, r_scratch, O_(ResolveLookAtScratch,uy)) /* r_puy = &uy */ \
, add_si(r_puz, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_puz = &uz */ \
, add_si(r_peye, r_scratch, O_(ResolveLookAtScratch,eye)) /* r_peye = &eye */ \
, nop /* ── m[0] = (S2)ux ── */ \
, load_word(r_tmp0, r_pux, O_(V3_S4,x)) \
, load_word(r_tmp1, r_pux, O_(V3_S4,y)) \
, load_word(r_tmp2, r_pux, O_(V3_S4,z)) \
, nop \
, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[0][0])) \
, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[0][1])) \
, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[0][2])) /* ── m[1] = (S2)uy ── */ \
, load_word(r_tmp0, r_puy, O_(V3_S4,x)) \
, load_word(r_tmp1, r_puy, O_(V3_S4,y)) \
, load_word(r_tmp2, r_puy, O_(V3_S4,z)) \
, nop \
, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[1][0])) \
, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[1][1])) \
, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[1][2])) /* ── m[2] = (S2)uz ── */ \
, load_word(r_tmp0, r_puz, O_(V3_S4,x)) \
, load_word(r_tmp1, r_puz, O_(V3_S4,y)) \
, load_word(r_tmp2, r_puz, O_(V3_S4,z)) \
, nop \
, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[2][0])) \
, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[2][1])) \
, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[2][2])) /* ── Translation column t[i] = R * (-eye) ─────────────────────────────
* pos = -eye: load eye.x/y/z from r_peye, negate via sub_u from R_0. */ \
, load_word(r_tmp0, r_peye, O_(P3_S4,x)) \
, load_word(r_tmp1, r_peye, O_(P3_S4,y)) \
, load_word(r_tmp2, r_peye, O_(P3_S4,z)) \
, nop \
, sub_u(r_tmp0, R_0, r_tmp0) /* pos.x = -eye.x */ \
, sub_u(r_tmp1, R_0, r_tmp1) \
, sub_u(r_tmp2, R_0, r_tmp2) /* mtc2 IR1/2/3 = pos (for MVMVA — input vector registers). */ \
, gte_mv_to_data_r(r_tmp0, C2_IR1) \
, gte_mv_to_data_r(r_tmp1, C2_IR2) \
, gte_mv_to_data_r(r_tmp2, C2_IR3) \
, nop2 /* MVMVA: MAC1/2/3 = R * IR with cv=0 (no TR vector), mx=0 (rotation matrix),
* sf=0 (no shift), v=0 (V0 = IR1/2/3, no far-plane clipping). The pre-set
* rotation matrix is the one set by the preceding set_gte_world atom.
* gte_cmdw_mvmva is parameterless and defaults to cv=0/mx=0/sf=0/v=0. */ \
, gte_cmdw_mvmva \
, nop /* GTE interlock */ /* mfc2 MAC1/2/3 → r_tmp0/r_tmp1/r_tmp2 (sign-extended into 32-bit GPRs).
* MAC1/2/3 hold R*v with no TR add and no perspective divide — exactly the
* 3 distinct world-space translation values we need for t[0..2]. */ \
, gte_mv_from_data_r(r_tmp0, C2_MAC1) \
, gte_mv_from_data_r(r_tmp1, C2_MAC2) \
, gte_mv_from_data_r(r_tmp2, C2_MAC3) \
, nop \
, store_word(r_tmp0, r_look_at, O_(MT3_S2S4,t[0])) \
, store_word(r_tmp1, r_look_at, O_(MT3_S2S4,t[1])) \
, store_word(r_tmp2, r_look_at, O_(MT3_S2S4,t[2])) \
, mac_yield()
WORD_COUNT(mac_resolve_look_at__populate_and_translate, 50)
-30
View File
@@ -8,36 +8,6 @@
#pragma region hello_camera #pragma region hello_camera
// --- atom: resolve_look_at__normalize_fwd_to_uz (62 words) ---
#define _atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz 6
#define _atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz 1
enum {
atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz = _atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz,
atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz = _atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz,
};
// --- atom: resolve_look_at__normalize_right_to_ux (62 words) ---
#define _atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux 6
#define _atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux 1
enum {
atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux = _atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux,
atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux = _atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux,
};
// --- atom: resolve_look_at__normalize_up_to_uy (62 words) ---
#define _atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy 6
#define _atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy 1
enum {
atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy = _atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy,
atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy = _atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy,
};
// --- atom: pad_input_cube_rotation (60 words) --- // --- atom: pad_input_cube_rotation (60 words) ---
#define _atom_offset_dpad_left_exit_dpad_left 6 #define _atom_offset_dpad_left_exit_dpad_left 6
+140 -420
View File
@@ -17,6 +17,7 @@
# include "duffle/psyq.atom.c" # include "duffle/psyq.atom.c"
# include "gen/offsets.h" # include "gen/offsets.h"
# include "gen/macs.h" # include "gen/macs.h"
# include "gen/auto_reg.h"
# include "hello_camera.h" # include "hello_camera.h"
#endif #endif
@@ -50,18 +51,18 @@ MipsAtomComp_Proc_(ac_put_draw_env, ab, {
* (binary; the PutDrawEnv implementation builds the 16-word DR_ENV from the user's DRAWENV struct and emits it via GP0 GPU commands.) * (binary; the PutDrawEnv implementation builds the 16-word DR_ENV from the user's DRAWENV struct and emits it via GP0 GPU commands.)
* *
* Word indices (libpsyx PutDrawEnv / SetDrawEnv order): * Word indices (libpsyx PutDrawEnv / SetDrawEnv order):
* tag = (length << 24) | addr — 16-word packet (1 tag + 15 code) * tag = (length << 24) | addr — 16-word packet (1 tag + 15 code)
* code[0] = DrawMode (dfe=1, dtd=0, tpage=0) — must come first per libpsyx * code[0] = DrawMode (dfe=1, dtd=0, tpage=0) — must come first per libpsyx
* code[1] = TextureWindow (tw=(0,0)) — bare-cmd word; GPU uses current state * code[1] = TextureWindow (tw=(0,0)) — bare-cmd word; GPU uses current state
* code[2] = DrawArea top-left (clip.x=0, clip.y=240) * code[2] = DrawArea top-left (clip.x=0, clip.y=240)
* code[3] = DrawArea bottom-right (clip.x+w=320, clip.y+h=480) * code[3] = DrawArea bottom-right (clip.x+w=320, clip.y+h=480)
* code[4] = DrawOffset (ofs=(0,0)) — bare-cmd word * code[4] = DrawOffset (ofs=(0,0)) — bare-cmd word
* code[5] = Mask (dtd=0, dfe=1, isbg=1) — 0xE6 cmd + isbg bit * code[5] = Mask (dtd=0, dfe=1, isbg=1) — 0xE6 cmd + isbg bit
* code[6] = Initial-bg-color (isbg=1, r=7, g=7, b=7) * code[6] = Initial-bg-color (isbg=1, r=7, g=7, b=7)
* code[7] = DrawMode (isbg=1, tpage=0) — re-asserts DrawMode with isbg * code[7] = DrawMode (isbg=1, tpage=0) — re-asserts DrawMode with isbg
* code[8..10] = padding (NOP) — 3 words to fill the packet * code[8..10] = padding (NOP) — 3 words to fill the packet
* code[11..12] = TextureWindow bottom-right — defaults to (0,0,0,0) * code[11..12] = TextureWindow bottom-right — defaults to (0,0,0,0)
* code[13..14] = padding (NOP) — completes the 16-word packet * code[13..14] = padding (NOP) — completes the 16-word packet
*/ */
mac_gcmd_push(gp0_dr_env_tag, reg_transfer, reg_base, port), /* tag (length=15 << 24, addr=0) — packet header for the DR_ENV sequence. The GPU needs this to recognize the next 15 words as a DR_ENV packet and trigger the isbg auto-clear. */ mac_gcmd_push(gp0_dr_env_tag, reg_transfer, reg_base, port), /* tag (length=15 << 24, addr=0) — packet header for the DR_ENV sequence. The GPU needs this to recognize the next 15 words as a DR_ENV packet and trigger the isbg auto-clear. */
mac_gcmd_push(gp0_word_draw_mode_drawing_allowed, reg_transfer, reg_base, port), /* code[0] DrawMode (dfe=1, dtd=0, tpage=0) */ mac_gcmd_push(gp0_word_draw_mode_drawing_allowed, reg_transfer, reg_base, port), /* code[0] DrawMode (dfe=1, dtd=0, tpage=0) */
@@ -93,16 +94,35 @@ MipsAtomComp_Proc_(ac_put_draw_env, ab, {
#pragma region Atom Procs #pragma region Atom Procs
// Modular Atoms // Modular Atoms
/* Scratchpad layout for the resolve_look_at bundle.
* The chain atoms communicate entirely via the wave-context GPR carrier R_ResolveScratch (R_T4) + hardcoded offsets into smem.scratchpad
* (PS1 hardware scratchpad at 0x1F800000).
*
* Atom 0 (input_and_sub) STAGES the C-side inputs (eye, up_in) into the scratchpad;
* AT THE SAME TIME it computes fwd = target - eye and stores it at scratch+0.
* Atoms 1-6 then read/write specific scratchpad offsets internally using
* `r_scratch + hardcoded_offset` — no tape-data pointers are passed between atoms.
* +0 fwd (atom 0 writes; atom 1 reads)
* +16 uz (atom 1 writes; atoms 2 + 4 read)
* +32 right (atom 2 writes; atom 3 reads)
* +48 ux (atom 3 writes; atoms 4 + 6 read)
* +64 up (atom 4 writes; atom 5 reads)
* +80 uy (atom 5 writes; atom 6 reads)
* +96 eye (atom 0 stages from C-side pointer; atom 6 reads)
* +128 up_in (atom 0 stages from C-side pointer; atom 2 reads)
*/
// enum {
// R_LookAt = R_T0 atom_reg atom_type(MT3_S2S4*),
// R_CamEye = R_T1 atom_reg atom_type(P3_S4*),
// R_CamTarget = R_T2 atom_reg atom_type(P3_S4*),
// R_WorldUp = R_T3 atom_reg atom_type(V3_S4*),
// };
enum { enum {
/* Wave-context GPR carrier for the resolve_look_at bundle: the scratch base. /* Wave-context GPR carrier for the resolve_look_at bundle: the scratch base.
* Set by atom 0 (popped from tape), read by atoms 1-6 (used as pointer base). * Set by atom 0 (popped from tape), read by atoms 1-6 (used as pointer base). */
* Type is U4* — this holds the scratch base address (smem.scratchpad value).
*
* Other wave-context carriers (R_ResolveUzPtr / UxPtr / UyPtr) used in the
* prior design were dropped: the new chain atoms compute their src/dst
* addresses internally from R_ResolveScratch + hardcoded_offset. */
R_ResolveScratch = R_T4 atom_reg atom_type(U4*), R_ResolveScratch = R_T4 atom_reg atom_type(U4*),
#define R_ResolveScratch_Code R_T4_Code
}; };
typedef Struct_(Binds_ResolveLookAt) { typedef Struct_(Binds_ResolveLookAt) {
MT3_S2S4* look_at; MT3_S2S4* look_at;
@@ -111,11 +131,7 @@ typedef Struct_(Binds_ResolveLookAt) {
V3_S4* up_in; V3_S4* up_in;
}; };
/* Per-atom bind-pop structs for the resolve_look_at bundle. /* Per-atom bind-pop structs for the resolve_look_at bundle. */
* Atom 0 (input_and_sub) is the ONLY atom that touches the C-side pointers +
* scratch base. Atoms 1-6 use scratch + hardcoded offsets internally.
* Field types are U4 (raw pointer value) because the structs are populated
* by the frame-time bundle helper with the literal C-side pointer values. */
typedef Struct_(Binds_ResolveLookAtScratch) { typedef Struct_(Binds_ResolveLookAtScratch) {
U4 scratch_base; /* U4 (scratch base address — populated by helper with u4_(smem.scratchpad)) */ U4 scratch_base; /* U4 (scratch base address — populated by helper with u4_(smem.scratchpad)) */
}; };
@@ -125,30 +141,25 @@ typedef Struct_(Binds_ResolveLookAtScratch) {
* *
* Each slot is 16 bytes: V3_S4 is already 16 bytes (4 × S4 = x/y/z/pad). * Each slot is 16 bytes: V3_S4 is already 16 bytes (4 × S4 = x/y/z/pad).
* The struct fields are contiguous — slot i starts at offset i*16. * The struct fields are contiguous — slot i starts at offset i*16.
* Used by the assembly via O_(ResolveLookAtScratch, fld.x/y/z) which resolves * Used by the assembly via O_(ResolveLookAtScratch, fld.x/y/z) which resolves to a compile-time byte offset.
* to a compile-time byte offset. NOT a runtime struct — the struct is purely * NOT a runtime struct — the struct is purely a schema for offsets; the assembly uses `r_scratch + O_(...)` to compute slot addresses at runtime.
* a schema for offsets; the assembly uses `r_scratch + O_(...)` to compute
* slot addresses at runtime.
* *
* Slot producers/consumers (referenced by the resolve_look_at chain atoms): * Slot producers/consumers (referenced by the resolve_look_at chain atoms):
* * +0 fwd 0 writes (target - eye); atom 1 (normalize) reads
* +0 fwd atom 0 writes (target - eye); atom 1 (normalize) reads * +16 uz 1 writes (normalize fwd); atoms 2 + 4 read (cross operands)
* +16 uz atom 1 writes (normalize fwd); atoms 2 + 4 read (cross operands) * +32 right 2 writes (cross uz x up_in); atom 3 (normalize) reads
* +32 right atom 2 writes (cross uz x up_in); atom 3 (normalize) reads * +48 ux 3 writes (normalize right); atoms 4 + 6 read
* +48 ux atom 3 writes (normalize right); atoms 4 + 6 read * +64 up 4 writes (cross uz x ux); atom 5 (normalize) reads
* +64 up atom 4 writes (cross uz x ux); atom 5 (normalize) reads * +80 uy 5 writes (normalize up); atom 6 reads
* +80 uy atom 5 writes (normalize up); atom 6 reads * +96 eye 0 stages (C-side input); atom 6 reads (translation column)
* +96 eye atom 0 stages (C-side input); atom 6 reads (translation column) * +112 target reserved (currently written nowhere — kept for symmetry w/ eye)
* +112 target reserved (currently written nowhere — kept for symmetry w/ eye) * +128 up_in 0 stages (C-side input); atom 2 reads (cross operand)
* +128 up_in atom 0 stages (C-side input); atom 2 reads (cross operand)
* *
* Fields use P3_S4 (point) for eye/target (RGA: affine point, implicit weight 1); * Fields use P3_S4 (point) for eye/target (RGA: affine point, implicit weight 1);
* V3_S4 (vector) for fwd/uz/right/ux/up/uy/up_in (RGA: Euclidean vector). P3_S4 * V3_S4 (vector) for fwd/uz/right/ux/up/uy/up_in (RGA: Euclidean vector).
* is a storage alias of V3_S4 (see math.h comment: "Storage alias of V3_S4. * P3_S4 is a storage alias of V3_S4 (see math.h comment: "Storage alias of V3_S4.
* Use P3_S4 when the value is a point.") — both are 16 bytes. * Use P3_S4 when the value is a point.") — both are 16 bytes.
* */
* Moved from gte.atom.c (Task 12.11): gte.atom.c is the GENERIC GTE primitives
* file and must not know about any specific atom bundle's scratch layout. */
typedef Struct_(ResolveLookAtScratch) { typedef Struct_(ResolveLookAtScratch) {
V3_S4 fwd; /* offset +0 (16 bytes — 4 S4 fields incl. internal pad) */ V3_S4 fwd; /* offset +0 (16 bytes — 4 S4 fields incl. internal pad) */
V3_S4 uz; /* offset +16 (16 bytes) */ V3_S4 uz; /* offset +16 (16 bytes) */
@@ -161,38 +172,23 @@ typedef Struct_(ResolveLookAtScratch) {
V3_S4 up_in; /* offset +128 (16 bytes) */ V3_S4 up_in; /* offset +128 (16 bytes) */
}; };
/* ─── resolve_look_at bundle chain atoms (Task 5) ──────────────────────────── /* ─── resolve_look_at bundle chain atoms ────────────────────────────
* 7 unique atom procs in the resolve_look_at bundle (4 chain atoms + 3 normalize * 4 unique atom procs in the resolve_look_at bundle (4 chain atoms + 3 calls to generic normalize_v3s4_proc).
* variants). All 7 are runtime-built MipsAtom_Proc_ atoms: each function declares * All 4 chain atoms are runtime-built MipsAtom_Proc_ atoms: each function declares a static MipsCode[] body,
* a static MipsCode[] body, then calls atombuilder_unroll() to append it to the * then calls atombuilder_unroll() to append it to the caller's MipsAtomBuilder arena. resolve_look_at_init()
* caller's MipsAtomBuilder arena. Task 6's resolve_look_at_init() uses this pattern * uses this pattern to pre-build the bundle into the static arena (smem.resolve_look_at_arena).
* to pre-build the bundle into the static arena (smem.resolve_look_at_arena).
* *
* Atom roster (positions 0-6 in the bundle): * Atom roster:
* Atom 0: resolve_look_at__input_and_sub (chain atom) * 0: resolve_look_at__input_and_sub (chain atom)
* Atom 1: resolve_look_at__normalize_fwd_to_uz (normalize wrapper) * 1: normalize_v3s4_proc (gte.atom.c) (generic normalize; called for fwd→uz)
* Atom 2: resolve_look_at__cross_uz_up_in_to_right (chain atom) * 2: resolve_look_at__cross_uz_up_in_to_right (chain atom)
* Atom 3: resolve_look_at__normalize_right_to_ux (normalize wrapper) * 3: normalize_v3s4_proc (gte.atom.c) (generic normalize; called for right→ux)
* Atom 4: resolve_look_at__cross_uz_ux_to_up (chain atom) * 4: resolve_look_at__cross_uz_ux_to_up (chain atom)
* Atom 5: resolve_look_at__normalize_up_to_uy (normalize wrapper) * 5: normalize_v3s4_proc (gte.atom.c) (generic normalize; called for up→uy)
* Atom 6: resolve_look_at__populate_and_translate (chain atom) * 6: resolve_look_at__populate_and_translate (chain atom)
* *
* The 3 normalize wrappers are CHAIN-SPECIFIC — they hardcode src/dst scratch * The generic normalize_v3s4_proc is a parameterized 4-stage GTE normalize (SQR → mfc2 → LZCS → GPF → srav);
* offsets in the body (computed via r_scratch + O_(ResolveLookAtScratch, fld)). * it accepts scratch base + offset args so any caller (with a scratch base + struct schema) can use it.
* The generic normalize_v3s4_proc (in gte.atom.c) takes src/dst as GPR parameters
* and is NOT used by this bundle. (Layering rule: gte.atom.c contains only
* generic GTE primitives; bundle-specific code lives in this file.)
*
* The 3 normalize procs were moved from gte.atom.c to this file in Task 12.11
* (user feedback: "normalize is not supposed to be aware of a specific scratch
* for one atom bundle"). The procs were renamed to resolve_look_at__normalize_*_proc
* to make their bundle-specific nature clear.
*
* Lua metaprogram support (Task 12.10): the metaprogram auto-emits
* `atom_offset__X__Y` defs in gen/offsets.h for each atom_label/atom_offset pair
* in the body. The 3 normalize procs each have internal branches (srav_path /
* aligned_done variants) and get their per-proc-instance defs (e.g.,
* `atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz`).
*/ */
typedef Struct_(Binds_ResolveLookAtSub) { typedef Struct_(Binds_ResolveLookAtSub) {
@@ -201,23 +197,19 @@ typedef Struct_(Binds_ResolveLookAtSub) {
U4 up_in; /* U4 (C-side V3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */ U4 up_in; /* U4 (C-side V3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */
}; };
/* Atom 0 in the bundle: input_and_sub. Stages C-side inputs into the scratchpad /* Atom 0 in the bundle: input_and_sub. Stages C-side inputs into the scratchpad and computes fwd = target - eye.
* and computes fwd = target - eye. * Inputs (C-side pointers popped from the tape):
*
* Inputs (C-side pointers popped from the tape; NOT scratchpad addresses):
* r_target_ptr : P3_S4* (C-side struct; atom 0 reads target.x/y/z directly) * r_target_ptr : P3_S4* (C-side struct; atom 0 reads target.x/y/z directly)
* r_eye_ptr : P3_S4* (C-side struct; staged into scratchpad at +96/+100/+104) * r_eye_ptr : P3_S4* (C-side struct; staged into scratchpad at +96/+100/+104)
* r_up_in_ptr : V3_S4* (C-side struct; staged into scratchpad at +128/+132/+136) * r_up_in_ptr : V3_S4* (C-side struct; staged into scratchpad at +128/+132/+136)
*
* Wave-context output: * Wave-context output:
* r_scratch : R_ResolveScratch (R_T4) — scratch base, read by atoms 1-6 * r_scratch : R_ResolveScratch (R_T4) — scratch base, read by atoms 1-6
* *
* Bind-pop layout: * Bind-pop layout:
* Binds_ResolveLookAtSub = 12 bytes (target + eye + up_in ptrs) * Binds_ResolveLookAtSub = 12 bytes (target + eye + up_in ptrs)
* Binds_ResolveLookAtScratch = 4 bytes (scratch_base) * Binds_ResolveLookAtScratch = 4 bytes (scratch_base)
*
* Staging work: * Staging work:
* * Stage eye.x/y/z → scratch+96/+100/+104 (for atom 6's translation column) * * Stage eye.x/y/z → scratch+96/+100/+104 (for atom 6's translation column)
* * Stage up_in.x/y/z → scratch+128/+132/+136 (for atom 2's outer-product operand) * * Stage up_in.x/y/z → scratch+128/+132/+136 (for atom 2's outer-product operand)
* * Compute fwd = target - eye, store fwd.x/y/z → scratch+0/+4/+8 (for atom 1) * * Compute fwd = target - eye, store fwd.x/y/z → scratch+0/+4/+8 (for atom 1)
* *
@@ -235,20 +227,17 @@ typedef Struct_(Binds_ResolveLookAtSub) {
* *
* Pool cost: 8 GPRs + R_T4 (carrier) + R_AT + R_V0 (hardcoded) = 11 GPRs. * Pool cost: 8 GPRs + R_T4 (carrier) + R_AT + R_V0 (hardcoded) = 11 GPRs.
*/ */
I_ void resolve_look_at__input_and_sub_proc(MipsAtomBuilder_R ab I_ void resolve_look_at__input_and_sub_proc(MipsAtomBuilder_R ab, U4 r_scratch
, U4 r_target_ptr , U4 r_target_ptr,U4 r_eye_ptr, U4 r_up_in_ptr
, U4 r_eye_ptr , U4 r_tmp0, U4 r_tmp1, U4 r_tmp2, U4 r_tmp3
, U4 r_up_in_ptr
, U4 r_scratch
, U4 r_tmp0, U4 r_tmp1, U4 r_tmp2, U4 r_tmp3
) MipsAtom_Proc_(resolve_look_at__input_and_sub, ab, { ) MipsAtom_Proc_(resolve_look_at__input_and_sub, ab, {
/* Pop the 3 C-side pointers + scratch_base from the tape. */ /* Pop the 3 C-side pointers + scratch_base from the tape. */
load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)), load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)),
load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)), load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)),
load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)), load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)),
add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)), add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)),
load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtScratch,scratch_base)), load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtScratch,scratch_base)),
add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtScratch)), add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtScratch)),
/* Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation /* Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation
* column). Reuse r_tmp0/r_tmp1/r_tmp2. Offsets via O_(ResolveLookAtScratch,*). */ * column). Reuse r_tmp0/r_tmp1/r_tmp2. Offsets via O_(ResolveLookAtScratch,*). */
@@ -291,32 +280,30 @@ I_ void resolve_look_at__input_and_sub_proc(MipsAtomBuilder_R ab
}) })
/* Atoms 2 + 4 in the bundle: out = a × b (GTE outer product on IR/D vectors). /* Atoms 2 + 4 in the bundle: out = a × b (GTE outer product on IR/D vectors).
* No bind pop — the three operand pointers (a, b, out) are derived in-body * No bind pop — the three operand pointers (a, b, out) are derived in-body from r_scratch + hardcoded_offset.
* from r_scratch + hardcoded_offset. Each atom has its own variant because * Each atom has its own variant because the offsets are baked into the body and each atom uses unique GPRs.
* the offsets are baked into the body and each atom uses unique GPRs.
* *
* GTE register layout (per PSX-SPX + duffle gte.h): * GTE register layout (per PSX-SPX + duffle gte.h):
* IR1/2/3 = a.x/y/z (mtc2) * IR1/2/3 = a.x/y/z (mtc2)
* VXY0 = b.x (mtc2) * VXY0 = b.x (mtc2)
* VZ0 = b.y (mtc2) * VZ0 = b.y (mtc2)
* VXY1 = b.z (mtc2) * VXY1 = b.z (mtc2)
* OP = outer product * OP = outer product
* MAC1/2/3 = out.x/y/z (mfc2) * MAC1/2/3 = out.x/y/z (mfc2)
* *
* Pool cost: r_scratch (R_T4 carrier) + 7 body GPRs + R_AT + R_V0 (hardcoded) = 10 GPRs. * Pool cost: r_scratch (R_T4 carrier) + 7 body GPRs + R_AT + R_V0 (hardcoded) = 10 GPRs.
*/ */
/* Atom 2: cross uz × up_in → right. */ /* Atom 2: cross uz × up_in → right. */
I_ void resolve_look_at__cross_uz_up_in_to_right_proc(MipsAtomBuilder_R ab I_ void resolve_look_at__cross_uz_up_in_to_right_proc(MipsAtomBuilder_R ab, U4 r_scratch
, U4 r_scratch , U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */
, U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */ , U4 r_d /* load b.x */
, U4 r_d /* load b.x */ , U4 r_f, U4 r_g, U4 r_h /* r_f = &right (out ptr), r_g = &uz, r_h = &up_in */
, U4 r_f, U4 r_g, U4 r_h /* r_f = &right (out ptr), r_g = &uz, r_h = &up_in */
) MipsAtom_Proc_(resolve_look_at__cross_uz_up_in_to_right, ab, { ) MipsAtom_Proc_(resolve_look_at__cross_uz_up_in_to_right, ab, {
/* Compute the three scratch pointers from r_scratch. */ /* Compute the three scratch pointers from r_scratch. */
add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */ add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */
add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)), /* r_h = &up_in */ add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)), /* r_h = &up_in */
add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)), /* r_f = &right (out) */ add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)), /* r_f = &right (out) */
nop, nop,
/* Load a (uz).x/y/z into r_a/r_b/r_c. */ /* Load a (uz).x/y/z into r_a/r_b/r_c. */
@@ -325,9 +312,9 @@ I_ void resolve_look_at__cross_uz_up_in_to_right_proc(MipsAtomBuilder_R ab
load_word(r_c, r_g, O_(V3_S4,z)), load_word(r_c, r_g, O_(V3_S4,z)),
nop, nop,
/* Load b (up_in).x/y/z into r_d + R_AT/R_V0 (hardcoded; reusing the /* Load b (up_in).x/y/z into r_d + R_AT/R_V0
* body's last two loads is fine because the load-delay slot is the nop (hardcoded; reusing the body's last two loads is fine because the load-delay slot is the nop after the third load,
* after the third load, and mtc2 below doesn't read these regs). */ and mtc2 below doesn't read these regs). */
load_word(r_d, r_h, O_(V3_S4,x)), load_word(r_d, r_h, O_(V3_S4,x)),
load_word(R_AT, r_h, O_(V3_S4,y)), load_word(R_AT, r_h, O_(V3_S4,y)),
load_word(R_V0, r_h, O_(V3_S4,z)), load_word(R_V0, r_h, O_(V3_S4,z)),
@@ -359,8 +346,7 @@ I_ void resolve_look_at__cross_uz_up_in_to_right_proc(MipsAtomBuilder_R ab
}) })
/* Atom 4: cross uz × ux → up. */ /* Atom 4: cross uz × ux → up. */
I_ void resolve_look_at__cross_uz_ux_to_up_proc(MipsAtomBuilder_R ab I_ void resolve_look_at__cross_uz_ux_to_up_proc(MipsAtomBuilder_R ab, U4 r_scratch
, U4 r_scratch
, U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */ , U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */
, U4 r_d /* load b.x */ , U4 r_d /* load b.x */
, U4 r_f, U4 r_g, U4 r_h /* r_f = &up (out ptr), r_g = &uz, r_h = &ux */ , U4 r_f, U4 r_g, U4 r_h /* r_f = &up (out ptr), r_g = &uz, r_h = &ux */
@@ -404,259 +390,10 @@ I_ void resolve_look_at__cross_uz_ux_to_up_proc(MipsAtomBuilder_R ab
mac_yield() mac_yield()
}) })
/* Atoms 1, 3, 5 in the bundle: chain-specific normalize wrappers around the
* generic normalize_v3s4_proc (gte.atom.c). The generic proc takes src/dst as
* GPR parameters; these wrappers HARDCODE src/dst via r_scratch + O_(ResolveLookAtScratch, fld)
* so the C-side bundle helper doesn't need to push scratchpad addresses via
* tb_data between atoms. (Task 12.8 fix: eliminate magic offsets.)
*
* The 4-stage normalize body (SQR → mfc2 → LZCS → GPF → srav) is identical to
* the generic version (GPR-renamed); cycle counts match. The only per-atom
* difference is the (src, dst) scratch offsets and the per-proc atom_label
* suffixes (srav_path_fwd_to_uz, srav_path_right_to_ux, srav_path_up_to_uy) so
* the per-proc-instance offsets are emitted disjointly in gen/offsets.h.
*
* GPR pool (10 free regs: R_T0..R_T3, R_T5..R_T7, R_V0, R_V1, R_AT; R_T4 reserved for R_ResolveScratch):
* r_a : src ptr (overlaps with r_recip_est carrier after the 3 src-loads)
* r_b : dst ptr (saved throughout)
* r_e/r_f/r_i : src.x/y/z → result.x/y/z (preserved across stages 1-2 via r_d/r_g/r_recip_est scratch)
* r_d/r_g : MAC1/2 scratch (dead after stage 2)
* r_h : LZCR (saved across stages 3-4)
* r_recip_est : |v|² accumulator + sqrtbl[index] + 1/|v| (saved throughout)
* r_shift : final srav amount (saved across stages 3-4)
*
* The Lua metaprogram (Task 12.10) auto-emits:
* - `mac_resolve_look_at__normalize_<from>_to_<to>` alias in gen/macs.h
* - `atom_offset__srav_path_<from>_to_<to>__aligned_done_<from>_to_<to>` defs in gen/offsets.h
*/
/* Atom 1: normalize fwd (scratch+0) → uz (scratch+16). */
I_ void resolve_look_at__normalize_fwd_to_uz_proc(MipsAtomBuilder_R ab
, U4 r_scratch
, U4 r_a, U4 r_b /* src/dst scratch pointers */
, U4 r_e, U4 r_f, U4 r_i /* src.x/y/z → result.x/y/z */
, U4 r_d, U4 r_g /* MAC1/2 scratch (dead after stage 2) */
, U4 r_h /* LZCR */
, U4 r_recip_est
, U4 r_shift
) MipsAtom_Proc_(resolve_look_at__normalize_fwd_to_uz, ab, {
/* Compute src/dst pointers from r_scratch. */
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,fwd)), /* r_a = &fwd */
add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_b = &uz */
nop,
/* Load src.x/y/z from r_a into r_e/r_f/r_i. */
load_word(r_e, r_a, O_(V3_S4,x)),
load_word(r_f, r_a, O_(V3_S4,y)),
load_word(r_i, r_a, O_(V3_S4,z)),
nop, /* load-delay */
/* Stage 1: mtc2 src → IR1/2/3, SQR fires. */
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop, gte_cmdw_sqr,
/* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */
gte_mv_from_data_r(r_d, C2_MAC1),
gte_mv_from_data_r(r_g, C2_MAC2),
gte_mv_from_data_r(r_recip_est, C2_MAC3),
nop,
add_u(r_recip_est, r_recip_est, r_g),
add_u(r_recip_est, r_recip_est, r_d),
gte_mv_to_data_r(r_recip_est, C2_LZCS),
nop2,
gte_mv_from_data_r(r_h, C2_LZCR),
nop,
/* Stage 3: compute shift amount, align |v|² to bit 24. */
and_i( r_h, r_h, -2),
li_s( r_shift, 31),
sub_s( r_shift, r_shift, r_h),
shift_aright(r_shift, r_shift, 1),
add_si( r_a, r_h, -24), /* r_a = LZCR - 24 (overlapping with r_recip_est; src ptr no longer needed) */
branch_lt_zero(r_a, atom_offset(srav_path_fwd_to_uz, aligned_done_fwd_to_uz)), nop,
jump_rel(atom_offset(aligned_done_fwd_to_uz, srav_path_fwd_to_uz)),
shift_lleft_var(r_recip_est, r_recip_est, r_a),
atom_label(srav_path_fwd_to_uz)
li_s( r_a, 24),
sub_s( r_a, r_a, r_h),
shift_aright_var(r_recip_est, r_recip_est, r_a),
atom_label(aligned_done_fwd_to_uz)
/* r_recip_est holds |v|² aligned to bit 24. */
add_si( r_recip_est, r_recip_est, -64),
shift_lleft(r_recip_est, r_recip_est, 1),
load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)),
or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)),
add_u(r_a, r_a, r_recip_est),
load_half(r_recip_est, r_a, 0),
nop,
/* Stage 4: GPF + srav finalize. */
gte_mv_to_data_r(r_recip_est, C2_IR0),
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop2,
gte_cmdw_gpf,
gte_mv_from_data_r(r_e, C2_MAC1),
gte_mv_from_data_r(r_f, C2_MAC2),
gte_mv_from_data_r(r_i, C2_MAC3),
shift_aright_var(r_e, r_e, r_shift),
shift_aright_var(r_f, r_f, r_shift),
shift_aright_var(r_i, r_i, r_shift),
/* Store result.x/y/z to r_b (dst ptr = scratch+16). */
store_word(r_e, r_b, O_(V3_S4,x)),
store_word(r_f, r_b, O_(V3_S4,y)),
store_word(r_i, r_b, O_(V3_S4,z)),
mac_yield()
})
/* Atom 3: normalize right (scratch+32) → ux (scratch+48). */
I_ void resolve_look_at__normalize_right_to_ux_proc(MipsAtomBuilder_R ab
, U4 r_scratch
, U4 r_a, U4 r_b
, U4 r_e, U4 r_f, U4 r_i
, U4 r_d, U4 r_g
, U4 r_h
, U4 r_recip_est
, U4 r_shift
) MipsAtom_Proc_(resolve_look_at__normalize_right_to_ux, ab, {
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,right)), /* r_a = &right */
add_si(r_b, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_b = &ux */
nop,
load_word(r_e, r_a, O_(V3_S4,x)),
load_word(r_f, r_a, O_(V3_S4,y)),
load_word(r_i, r_a, O_(V3_S4,z)),
nop,
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop, gte_cmdw_sqr,
gte_mv_from_data_r(r_d, C2_MAC1),
gte_mv_from_data_r(r_g, C2_MAC2),
gte_mv_from_data_r(r_recip_est, C2_MAC3),
nop,
add_u(r_recip_est, r_recip_est, r_g),
add_u(r_recip_est, r_recip_est, r_d),
gte_mv_to_data_r(r_recip_est, C2_LZCS),
nop2,
gte_mv_from_data_r(r_h, C2_LZCR),
nop,
and_i( r_h, r_h, -2),
li_s( r_shift, 31),
sub_s( r_shift, r_shift, r_h),
shift_aright(r_shift, r_shift, 1),
add_si( r_a, r_h, -24),
branch_lt_zero(r_a, atom_offset(srav_path_right_to_ux, aligned_done_right_to_ux)), nop,
jump_rel(atom_offset(aligned_done_right_to_ux, srav_path_right_to_ux)),
shift_lleft_var(r_recip_est, r_recip_est, r_a),
atom_label(srav_path_right_to_ux)
li_s( r_a, 24),
sub_s( r_a, r_a, r_h),
shift_aright_var(r_recip_est, r_recip_est, r_a),
atom_label(aligned_done_right_to_ux)
add_si( r_recip_est, r_recip_est, -64),
shift_lleft(r_recip_est, r_recip_est, 1),
load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)),
or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)),
add_u(r_a, r_a, r_recip_est),
load_half(r_recip_est, r_a, 0),
nop,
gte_mv_to_data_r(r_recip_est, C2_IR0),
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop2,
gte_cmdw_gpf,
gte_mv_from_data_r(r_e, C2_MAC1),
gte_mv_from_data_r(r_f, C2_MAC2),
gte_mv_from_data_r(r_i, C2_MAC3),
shift_aright_var(r_e, r_e, r_shift),
shift_aright_var(r_f, r_f, r_shift),
shift_aright_var(r_i, r_i, r_shift),
store_word(r_e, r_b, O_(V3_S4,x)),
store_word(r_f, r_b, O_(V3_S4,y)),
store_word(r_i, r_b, O_(V3_S4,z)),
mac_yield()
})
/* Atom 5: normalize up (scratch+64) → uy (scratch+80). */
I_ void resolve_look_at__normalize_up_to_uy_proc(MipsAtomBuilder_R ab
, U4 r_scratch
, U4 r_a, U4 r_b
, U4 r_e, U4 r_f, U4 r_i
, U4 r_d, U4 r_g
, U4 r_h
, U4 r_recip_est
, U4 r_shift
) MipsAtom_Proc_(resolve_look_at__normalize_up_to_uy, ab, {
add_si(r_a, r_scratch, O_(ResolveLookAtScratch,up)), /* r_a = &up */
add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uy)), /* r_b = &uy */
nop,
load_word(r_e, r_a, O_(V3_S4,x)),
load_word(r_f, r_a, O_(V3_S4,y)),
load_word(r_i, r_a, O_(V3_S4,z)),
nop,
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop, gte_cmdw_sqr,
gte_mv_from_data_r(r_d, C2_MAC1),
gte_mv_from_data_r(r_g, C2_MAC2),
gte_mv_from_data_r(r_recip_est, C2_MAC3),
nop,
add_u(r_recip_est, r_recip_est, r_g),
add_u(r_recip_est, r_recip_est, r_d),
gte_mv_to_data_r(r_recip_est, C2_LZCS),
nop2,
gte_mv_from_data_r(r_h, C2_LZCR),
nop,
and_i( r_h, r_h, -2),
li_s( r_shift, 31),
sub_s( r_shift, r_shift, r_h),
shift_aright(r_shift, r_shift, 1),
add_si( r_a, r_h, -24),
branch_lt_zero(r_a, atom_offset(srav_path_up_to_uy, aligned_done_up_to_uy)), nop,
jump_rel(atom_offset(aligned_done_up_to_uy, srav_path_up_to_uy)),
shift_lleft_var(r_recip_est, r_recip_est, r_a),
atom_label(srav_path_up_to_uy)
li_s( r_a, 24),
sub_s( r_a, r_a, r_h),
shift_aright_var(r_recip_est, r_recip_est, r_a),
atom_label(aligned_done_up_to_uy)
add_si( r_recip_est, r_recip_est, -64),
shift_lleft(r_recip_est, r_recip_est, 1),
load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)),
or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)),
add_u(r_a, r_a, r_recip_est),
load_half(r_recip_est, r_a, 0),
nop,
gte_mv_to_data_r(r_recip_est, C2_IR0),
gte_mv_to_data_r(r_e, C2_IR1),
gte_mv_to_data_r(r_f, C2_IR2),
gte_mv_to_data_r(r_i, C2_IR3),
nop2,
gte_cmdw_gpf,
gte_mv_from_data_r(r_e, C2_MAC1),
gte_mv_from_data_r(r_f, C2_MAC2),
gte_mv_from_data_r(r_i, C2_MAC3),
shift_aright_var(r_e, r_e, r_shift),
shift_aright_var(r_f, r_f, r_shift),
shift_aright_var(r_i, r_i, r_shift),
store_word(r_e, r_b, O_(V3_S4,x)),
store_word(r_f, r_b, O_(V3_S4,y)),
store_word(r_i, r_b, O_(V3_S4,z)),
mac_yield()
})
typedef Struct_(Binds_ResolveLookAtPopAndTrans) { typedef Struct_(Binds_ResolveLookAtPopAndTrans) {
U4 look_at; /* U4 (MT3_S2S4* — destination matrix address) */ U4 look_at; /* U4 (MT3_S2S4* — destination matrix address) */
}; };
/* Atom 6 in the bundle: write look_at->m[][] from ux/uy/uz, then compute /* Atom 6 in the bundle: write look_at->m[][] from ux/uy/uz, then compute the translation column t[] = R * (-eye).
* the translation column t[] = R * (-eye).
* *
* GPR codes (assigned by resolve_look_at_init): * GPR codes (assigned by resolve_look_at_init):
* r_look_at : MT3_S2S4* (popped from tape; output matrix destination) * r_look_at : MT3_S2S4* (popped from tape; output matrix destination)
@@ -666,14 +403,15 @@ typedef Struct_(Binds_ResolveLookAtPopAndTrans) {
* r_peye : pointer to eye (offset O_(ResolveLookAtScratch,eye)) * r_peye : pointer to eye (offset O_(ResolveLookAtScratch,eye))
* r_tmp0/1/2 : atom-local scratch (load + MVMVA + store temps) * r_tmp0/1/2 : atom-local scratch (load + MVMVA + store temps)
* *
* The 4 pointer regs (r_pux/r_puy/r_puz/r_peye) are DEDICATED — they hold the scratch addresses for the entire body. * 4 pointer regs (r_pux/r_puy/r_puz/r_peye) are DEDICATED — they hold the scratch addresses for the entire body.
* They are computed in-body via `add_si(r_px, r_scratch, O_(ResolveLookAtScratch, field))` so no tape-data pointer is needed. * They are computed in-body via `add_si(r_px, r_scratch, O_(ResolveLookAtScratch, field))` so no tape-data pointer is needed.
* *
* Struct layout (per duffle/math.h): * Struct layout (per duffle/math.h):
* MT3_S2S4 { A3x3_S2 m; A3_S4 t; } → m[][] is S2 packed (9 × 2 = 18 bytes at offset 0) * MT3_S2S4 { A3x3_S2 m; A3_S4 t; } → m[][] is S2 packed (9 × 2 = 18 bytes at offset 0)
* t[0/1/2] is S4 (3 × 4 = 12 bytes at offset 18) * t[0/1/2] is S4 (3 × 4 = 12 bytes at offset 18)
* *
* Translation column: GTE MVMVA with the world rotation matrix pre-set (helper emits set_gte_world before the bundle, per the bundle design). * Translation column: GTE MVMVA with the world rotation matrix pre-set
* (helper emits set_gte_world before the bundle, per the bundle design).
* MVMVA computes R * pos (with cv=0/mx=0/sf=0/v=0); MAC1/2/3 = R * (-eye). * MVMVA computes R * pos (with cv=0/mx=0/sf=0/v=0); MAC1/2/3 = R * (-eye).
* Pool cost: r_look_at (1) + r_scratch (R_T4 carrier) + 4 ptr regs + 3 tmp regs = 9 GPRs. * Pool cost: r_look_at (1) + r_scratch (R_T4 carrier) + 4 ptr regs + 3 tmp regs = 9 GPRs.
*/ */
@@ -737,16 +475,14 @@ I_ void resolve_look_at__populate_and_translate_proc(MipsAtomBuilder_R ab
gte_mv_to_data_r(r_tmp2, C2_IR3), gte_mv_to_data_r(r_tmp2, C2_IR3),
nop2, nop2,
/* MVMVA: MAC1/2/3 = R * IR with cv=0 (no TR vector), mx=0 (rotation matrix), /* MVMVA: MAC1/2/3 = R * IR with cv=0 (no TR vector), mx=0 (rotation matrix), sf=0 (no shift), v=0 (V0 = IR1/2/3, no far-plane clipping).
* sf=0 (no shift), v=0 (V0 = IR1/2/3, no far-plane clipping). The pre-set * The pre-set rotation matrix is the one set by the preceding set_gte_world atom.
* rotation matrix is the one set by the preceding set_gte_world atom.
* gte_cmdw_mvmva is parameterless and defaults to cv=0/mx=0/sf=0/v=0. */ * gte_cmdw_mvmva is parameterless and defaults to cv=0/mx=0/sf=0/v=0. */
gte_cmdw_mvmva, gte_cmdw_mvmva,
nop, /* GTE interlock */ nop, /* GTE interlock */
/* mfc2 MAC1/2/3 → r_tmp0/r_tmp1/r_tmp2 (sign-extended into 32-bit GPRs). /* mfc2 MAC1/2/3 → r_tmp0/r_tmp1/r_tmp2 (sign-extended into 32-bit GPRs).
* MAC1/2/3 hold R*v with no TR add and no perspective divide — exactly the * MAC1/2/3 hold R*v with no TR add and no perspective divide — exactly the 3 distinct world-space translation values we need for t[0..2]. */
* 3 distinct world-space translation values we need for t[0..2]. */
gte_mv_from_data_r(r_tmp0, C2_MAC1), gte_mv_from_data_r(r_tmp0, C2_MAC1),
gte_mv_from_data_r(r_tmp1, C2_MAC2), gte_mv_from_data_r(r_tmp1, C2_MAC2),
gte_mv_from_data_r(r_tmp2, C2_MAC3), gte_mv_from_data_r(r_tmp2, C2_MAC3),
@@ -821,32 +557,52 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init)
mac_yield(), mac_yield(),
}; };
/* gp_screen_init's GPR setup. Tests the mixed user-pinning + auto-reg pattern:
* - R_IO_BaseAddr = R_T4 (user-pinned via atom_reg; pre-existing)
* - R_GP1_Offset = R_T2 (user-pinned via atom_reg; NEW -- for GPIO_PORT1_OFFSET)
* - R_ScreenX = R_T5 (user-pinned via atom_reg; used as a transfer and GTE setup reg)
* - R_GpTmp = auto-allocated by the lua pass and used for several GPU transfers;
* the C preprocessor resolves it to the chosen free pool GPR.
*
* For gp_screen_init, the auto-reg pool exclusions are:
* user_pinned (from the corpus register_alias_registry) : R_T0..R_T7 (all 8 user-pinned across hello_camera.atom.c)
* body-parsed physical registers : aliases resolve through the registry;
* the body uses R_ScreenX, not raw R_T5
* source_pool after both subtractions : {R_V0, R_V1} only
* R_GpTmp gets R_V0 (the first-fit choice). Its repeated GPU-transfer use proves that the
* auto-reg allocation is active while the R_ScreenX references prove the pinned alias is used.
* R_TapePtr (R_T9), R_AtomJmp (R_T8), R_AT are excluded from the POOL by construction in
* passes/auto_reg.lua -- see the "obvious exclusions" comment block at the top of that file.
*/
enum { enum {
R_IO_BaseAddr = R_T4 atom_reg, /* Caller-pinned: IO_BASE_ADDR = 0x1F800000 */ R_IO_BaseAddr = R_T4 atom_reg, /* Caller-pinned: IO_BASE_ADDR = 0x1F800000 */
R_GP1_Offset = R_T2 atom_reg, /* Caller-pinned: GPIO_PORT1_OFFSET = 0x10 */
atom_auto_reg(gp_screen_init, R_GpTmp), /* Auto-allocated scratch; resolved to a free pool GPR by the lua pass. C-preprocessor expands to R_GpTmp = R_GpTmp_Code with an atom_auto_reg trailing comment. */
#define R_IO_BaseAddr_Code R_T4_Code #define R_IO_BaseAddr_Code R_T4_Code
#define R_GP1_Offset_Code R_T2_Code
}; };
internal MipsAtom_(gp_screen_init) atom_info(atom_phase(screen_init), atom_reads(R_IO_BaseAddr)) { internal MipsAtom_(gp_screen_init) atom_info(atom_phase(screen_init), atom_reads(R_IO_BaseAddr)) {
store_word(R_0, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(00h) Reset */ store_word(R_0, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(00h) Reset */
mac_gcmd_push(gp1_word_ResetCmdBuffer(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(01h) ClearFIFO */ mac_gcmd_push(gp1_word_ResetCmdBuffer(), R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(01h) ClearFIFO; uses pinned R_ScreenX as the transfer reg. */
mac_gcmd_push(gp1_word_AcknowledgeIRQ(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(02h) AckIRQ */ mac_gcmd_push(gp1_word_AcknowledgeIRQ(), R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(02h) AckIRQ; uses pinned R_ScreenX as the transfer reg. */
mac_gcmd_push(gp1_word_DisplayOn(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(03h) Display ON */ mac_gcmd_push(gp1_word_DisplayOn(), R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(03h) Display ON; uses pinned R_ScreenX as the transfer reg. */
mac_gcmd_push(gp1_word_dma_to_gpu(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(04h) DMADirection=2 (CPUGPU). libpsyx's per-frame PutDrawEnv/DrawOTag use DMA2; without this the DMA queue never drains. */ mac_gcmd_push(gp1_word_dma_to_gpu(), R_GpTmp, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(04h) DMADirection=2 (CPU->GPU). libpsyx's per-frame PutDrawEnv/DrawOTag use DMA2; without this the DMA queue never drains. Uses auto-allocated R_GpTmp. */
mac_gcmd_push(gp1_word_StartDisplayArea(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(05h) StartDisplayArea (X=0, Y=0) */ mac_gcmd_push(gp1_word_StartDisplayArea(), R_GpTmp, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* GP1(05h) StartDisplayArea (X=0, Y=0); uses auto-allocated R_GpTmp. */
/* GP1: DisplayMode + Display Ranges */ /* GP1: DisplayMode + Display Ranges. */
mac_gcmd_push(gp1_word_display_mode_320x240_15bit_ntsc, R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), mac_gcmd_push(gp1_word_display_mode_320x240_15bit_ntsc, R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET),
mac_gcmd_push(gp1_word_horizontal_range_ntsc, R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), mac_gcmd_push(gp1_word_horizontal_range_ntsc, R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET),
mac_gcmd_push(gp1_word_vertical_range_ntsc, R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), mac_gcmd_push(gp1_word_vertical_range_ntsc, R_ScreenX, R_IO_BaseAddr, GPIO_PORT1_OFFSET),
/* GTE: SetGeomOffset (OFX, OFY) — ScreenRes_CenterX, ScreenRes_CenterY. */ /* GTE: SetGeomOffset (OFX, OFY) — ScreenRes_CenterX, ScreenRes_CenterY. */
load_upper_i(R_T5, ScreenRes_CenterX), gte_mv_to_ctrl_r(R_T5, gte_cr_OFX_Code), load_upper_i(R_ScreenX, ScreenRes_CenterX), gte_mv_to_ctrl_r(R_ScreenX, gte_cr_OFX_Code),
load_upper_i(R_T5, ScreenRes_CenterY), gte_mv_to_ctrl_r(R_T5, gte_cr_OFY_Code), load_upper_i(R_ScreenX, ScreenRes_CenterY), gte_mv_to_ctrl_r(R_ScreenX, gte_cr_OFY_Code),
/* GTE: SetGeomScreen (H) — CR26 (per PSX-SPX / libpsyx), value is the raw projection-plane distance, NOT shifted. */ /* GTE: SetGeomScreen (H) — CR26 (per PSX-SPX / libpsyx), value is the raw projection-plane distance, NOT shifted. */
add_ui(R_T5, R_0, ScreenZ), gte_mv_to_ctrl_r(R_T5, gte_cr_H_Code), add_ui(R_ScreenX, R_0, ScreenZ), gte_mv_to_ctrl_r(R_ScreenX, gte_cr_H_Code),
/* GP1: DisplayEnable — bit 0 = 0 (Display ON). */ /* GP1: DisplayEnable — bit 0 = 0 (Display ON). */
mac_gcmd_push(gp1_word_DisplayOn(), R_T5, R_IO_BaseAddr, GPIO_PORT1_OFFSET), mac_gcmd_push(gp1_word_DisplayOn(), R_GpTmp, R_IO_BaseAddr, GPIO_PORT1_OFFSET), /* Uses auto-allocated R_GpTmp. */
mac_yield(), mac_yield(),
}; };
@@ -1015,43 +771,8 @@ atom_label(exit_circle_z)
mac_yield_tail(), mac_yield_tail(),
}; };
/* Scratchpad layout for the resolve_look_at bundle.
* The chain atoms communicate entirely via the wave-context GPR carrier
* R_ResolveScratch (R_T4) + hardcoded offsets into smem.scratchpad
* (PS1 hardware scratchpad at 0x1F800000).
*
* Atom 0 (input_and_sub) STAGES the C-side inputs (eye, up_in) into the scratchpad;
* AT THE SAME TIME it computes fwd = target - eye and stores it at scratch+0.
* Atoms 1-6 then read/write specific scratchpad offsets internally using
* `r_scratch + hardcoded_offset` — no tape-data pointers are passed between atoms.
*
* +0 fwd (atom 0 writes; atom 1 reads)
* +16 uz (atom 1 writes; atoms 2 + 4 read)
* +32 right (atom 2 writes; atom 3 reads)
* +48 ux (atom 3 writes; atoms 4 + 6 read)
* +64 up (atom 4 writes; atom 5 reads)
* +80 uy (atom 5 writes; atom 6 reads)
* +96 eye (atom 0 stages from C-side pointer; atom 6 reads)
* +128 up_in (atom 0 stages from C-side pointer; atom 2 reads)
*
* No struct view is required — the C-side bundle helper passes only C-side
* pointers (target, eye, up_in, look_at) and the scratch base address;
* the assembly hardcodes all inter-slot offsets. The original Task 12.7 magic
* offsets `& smem.scratchpad[N]` in the C-side helper were eliminated by this
* redesign; the user feedback was: "you didn't have to use magic offsets into
* the scratchpad memory. those are harcoded." */
enum { enum {
R_LookAt = R_T0 atom_reg atom_type(MT3_S2S4*), R_PrimCursor = R_T7 atom_reg atom_type(U4*), /* Output cursor (primitive buffer) */
R_CamEye = R_T1 atom_reg atom_type(P3_S4*),
R_CamTarget = R_T2 atom_reg atom_type(P3_S4*),
R_WorldUp = R_T3 atom_reg atom_type(V3_S4*),
};
enum {
R_PrimCursor = R_T7 atom_reg atom_type(U4*), /* VRAM output cursor (primitive buffer) */
R_FaceCursor = R_T4 atom_reg atom_type(V4_S2*), /* Cube face-index cursor (V4_S2*); floor context switches to V3_S2* via atom_phase */ R_FaceCursor = R_T4 atom_reg atom_type(V4_S2*), /* Cube face-index cursor (V4_S2*); floor context switches to V3_S2* via atom_phase */
R_VertBase = R_T5 atom_reg atom_type(V3_S2*), /* Base address of the vertex array */ R_VertBase = R_T5 atom_reg atom_type(V3_S2*), /* Base address of the vertex array */
R_OtBase = R_T6 atom_reg atom_type(U4*), /* Base address of the Ordering Table */ R_OtBase = R_T6 atom_reg atom_type(U4*), /* Base address of the Ordering Table */
@@ -1060,7 +781,6 @@ enum {
#define R_VertBase_Code R_T5_Code #define R_VertBase_Code R_T5_Code
#define R_OtBase_Code R_T6_Code #define R_OtBase_Code R_T6_Code
}; };
typedef Struct_(Binds_CubeTri) { typedef Struct_(Binds_CubeTri) {
U4 PrimCursor; U4 PrimCursor;
V4_S2* FaceCursor; V4_S2* FaceCursor;
@@ -1097,7 +817,7 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4),
gte_mv_from_data_r(R_T0, C2_MAC0), nop, gte_mv_from_data_r(R_T0, C2_MAC0), nop,
branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)), branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)),
/* BD-slot: write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer). /* BD-slot: Write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer).
* If branch IS taken (face culled), the body is skipped and this 0-tag is stranded — * If branch IS taken (face culled), the body is skipped and this 0-tag is stranded —
* harmless because the OT entry that points to this prim is created later. */ * harmless because the OT entry that points to this prim is created later. */
store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)), store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)),
+108 -65
View File
@@ -43,6 +43,7 @@
#pragma region Hello Camera Headers #pragma region Hello Camera Headers
# include "gen/macs.h" # include "gen/macs.h"
# include "gen/offsets.h" # include "gen/offsets.h"
# include "gen/auto_reg.h"
#include "hello_camera.h" #include "hello_camera.h"
#pragma endregion Hello Camera Headers #pragma endregion Hello Camera Headers
@@ -132,20 +133,27 @@ resolve_look_at_c11(MT3_S2S4* look_at, P3_S4* eye, P3_S4* target, V3_S4* up_in)
} }
/* Pre-build all 7 chain atoms of the resolve_look_at bundle into the static arena. /* Pre-build all 7 chain atoms of the resolve_look_at bundle into the static arena.
* Called ONCE from main() before the frame loop. * Called ONCE from main() before the frame loop.
* After this returns, the smem.resolve_look_at_atom_addrs[] array contains valid MIPS atom pointers * After this returns, the smem.resolve_look_at_atom_addrs[] array contains valid MIPS atom pointers
* for the frame-time bundle helper to emit via tb_emit(tb, captured_addr). * for the frame-time bundle helper to emit via tb_emit(tb, captured_addr).
* *
* 7 atoms are within hello_camera.atom.c: * 4 unique procs in hello_camera.atom.c (chain atoms 0, 2, 4, 6); atoms 1, 3, 5
* share the GENERIC normalize_v3s4_proc from gte.atom.c (called 3x with different
* O_(ResolveLookAtScratch,...) offsets):
* 0: resolve_look_at__input_and_sub_proc * 0: resolve_look_at__input_and_sub_proc
* 1: resolve_look_at__normalize_fwd_to_uz_proc * 1: normalize_v3s4_proc (fwd → uz; offsets 0, 16)
* 2: resolve_look_at__cross_uz_up_in_to_right_proc * 2: resolve_look_at__cross_uz_up_in_to_right_proc
* 3: resolve_look_at__normalize_right_to_ux_proc * 3: normalize_v3s4_proc (right → ux; offsets 32, 48)
* 4: resolve_look_at__cross_uz_ux_to_up_proc * 4: resolve_look_at__cross_uz_ux_to_up_proc
* 5: resolve_look_at__normalize_up_to_uy_proc * 5: normalize_v3s4_proc (up → uy; offsets 64, 80)
* 6: resolve_look_at__populate_and_translate_proc * 6: resolve_look_at__populate_and_translate_proc
* *
* (gte.atom.c contains only normalize_v3s4_proc — bundle-specific scratch layout is no longer exposed to the GTE primitives file.) * Task 12.16 promotion: the bundle-specific resolve_look_at__chain_normalize_proc
* has been promoted to the generic normalize_v3s4_proc (gte.atom.c), which now
* takes r_scratch + r_src_offset + r_dst_offset as U4 parameters. The 3 callers
* pass O_(ResolveLookAtScratch,...) macros as offset args. The metaprogram emits
* one set of `atom_offset__normalize_v3s4__srav_path__aligned_done` defs
* (namespaced by atom name) in duffle/gen/offsets.h, shared by all 3 callers.
* *
* GPR pool per atom: 10 free GPRs (R_T0..R_T3 + R_T5..R_T7 + R_V0 + R_V1 + R_AT). * GPR pool per atom: 10 free GPRs (R_T0..R_T3 + R_T5..R_T7 + R_V0 + R_V1 + R_AT).
* R_T4 is reserved as the wave-context carrier (R_ResolveScratch). * R_T4 is reserved as the wave-context carrier (R_ResolveScratch).
@@ -161,75 +169,82 @@ internal void resolve_look_at_init(void) {
* computes fwd = target - eye; binds R_ResolveScratch (R_T4) as the wave-context carrier for atoms 1-6. * computes fwd = target - eye; binds R_ResolveScratch (R_T4) as the wave-context carrier for atoms 1-6.
* The body hardcodes R_AT and R_V0 as eye.y/eye.z temps (the existing sub_u(eye.x, eye.y, eye.z) chain from the prior Task 12.7 design). */ * The body hardcodes R_AT and R_V0 as eye.y/eye.z temps (the existing sub_u(eye.x, eye.y, eye.z) chain from the prior Task 12.7 design). */
smem.resolve_look_at_atom_addrs[0] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[0] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__input_and_sub_proc(ab, resolve_look_at__input_and_sub_proc(ab, R_ResolveScratch,
R_T0, /* r_target_ptr (popped from tape) */ R_T0, /* r_target_ptr (popped from tape) */
R_T1, /* r_eye_ptr (popped from tape) */ R_T1, /* r_eye_ptr (popped from tape) */
R_T2, /* r_up_in_ptr (popped from tape) */ R_T2, /* r_up_in_ptr (popped from tape) */
R_ResolveScratch, /* r_scratch (wave-context carrier; popped from tape) */ R_T3, R_T5, R_T6, R_T7); /* r_tmp<0-3> */
R_T3, /* r_tmp0 */
R_T5, /* r_tmp1 */
R_T6, /* r_tmp2 */
R_T7); /* r_tmp3 */
/* Atom 1: resolve_look_at__normalize_fwd_to_uz — src=scratch+0, dst=scratch+16 (HARDCODED in body). /* Atom 1: normalize_v3s4_proc (generic, from gte.atom.c) — src=scratch+0=fwd, dst=scratch+16=uz.
* GPR pool: r_scratch (R_T4 carrier) + 10 body GPRs = 11. * The proc takes r_src_offset + r_dst_offset as U4 PARAMETERS — we pass the O_(...) macros here (evaluating to numeric literals 0 and 16).
* r_a/r_b (R_T0/R_T1) : src/dst pointers (r_a overlaps r_recip_est after the loads) * The 4-stage body is identical across the 3 call sites (atoms 1, 3, 5); only the offset args differ.
* r_e/r_f/r_i (R_T2/R_T3/R_T5) : src.x/y/z → result.x/y/z * GPR pool: r_scratch (R_T4 carrier) + 9 body GPRs = 10.
* r_d/r_g (R_T6/R_T7) : MAC1/2 scratch (dead after stage 2) * r_src_ptr (R_T0) : src ptr
* r_h (R_V0) : LZCR * r_dst_ptr (R_T1) : dst ptr
* r_recip_est (R_V1), r_shift (R_AT) : saved throughout */ * r_tmp (R_T2) : unused (reserved for symmetry)
* r_mac1_scratch (R_T3) : MAC1 scratch
* r_mac2_scratch (R_T5) : src.x → result.x (carries through stages 1-2)
* r_recip_est (R_T6) : src.y → result.y
* r_lzcr (R_T7) : |v|² accumulator + srav amount (single reg)
* r_shift (R_V0) : LZCR (saved across stages 3-4)
* r_branch_tmp (R_V1) : src.z → result.z (reused after stage 1)
*/
smem.resolve_look_at_atom_addrs[1] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[1] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__normalize_fwd_to_uz_proc(ab, normalize_v3s4_proc(ab, R_ResolveScratch, /* r_scratch (wave-context carrier) */
R_ResolveScratch, /* r_scratch (wave-context carrier; src/dst base) */ O_(ResolveLookAtScratch, fwd), /* r_src_offset = 0 */
R_T0, R_T1, /* r_a, r_b (src/dst ptrs) */ O_(ResolveLookAtScratch, uz), /* r_dst_offset = 16 */
R_T2, R_T3, R_T5, /* r_e, r_f, r_i (src components) */ R_T0, R_T1, R_T2, /* r_src_ptr, r_dst_ptr, r_tmp */
R_T6, R_T7, /* r_d, r_g (MAC scratch) */ R_T3, /* r_mac1_scratch */
R_V0, /* r_h (LZCR) */ R_T5, /* r_mac2_scratch */
R_V1, /* r_recip_est */ R_T6, /* r_recip_est */
R_AT); /* r_shift */ R_T7, /* r_lzcr */
R_V0, /* r_shift */
R_V1); /* r_branch_tmp */
/* Atom 2: resolve_look_at__cross_uz_up_in_to_right — a=scratch+16, b=scratch+128, /* Atom 2: resolve_look_at__cross_uz_up_in_to_right — a=scratch+16, b=scratch+128,
* out=scratch+32 (HARDCODED in body). GPR pool: r_scratch + 7 body + R_AT + R_V0 = 10. */ * out=scratch+32 (HARDCODED in body). GPR pool: r_scratch + 7 body + R_AT + R_V0 = 10. */
smem.resolve_look_at_atom_addrs[2] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[2] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__cross_uz_up_in_to_right_proc(ab, resolve_look_at__cross_uz_up_in_to_right_proc(ab, R_ResolveScratch, /* r_scratch (wave-context carrier; src/dst base) */
R_ResolveScratch, /* r_scratch (wave-context carrier; src/dst base) */ R_T0, R_T1, R_T2, /* r_a, r_b, r_c (a.x/y/z → out.x/y/z) */
R_T0, R_T1, R_T2, /* r_a, r_b, r_c (a.x/y/z → out.x/y/z) */ R_T3, /* r_d (b.x) */
R_T3, /* r_d (b.x) */ R_T5, /* r_f (out ptr = scratch+32) */
R_T5, /* r_f (out ptr = scratch+32) */ R_T6, /* r_g (a ptr = scratch+16) */
R_T6, /* r_g (a ptr = scratch+16) */ R_T7); /* r_h (b ptr = scratch+128) */
R_T7); /* r_h (b ptr = scratch+128) */
/* Atom 3: resolve_look_at__normalize_right_to_ux — src=scratch+32, dst=scratch+48 (HARDCODED). */ /* Atom 3: normalize_v3s4_proc (generic, from gte.atom.c) — src=scratch+32=right, dst=scratch+48=ux. */
smem.resolve_look_at_atom_addrs[3] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[3] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__normalize_right_to_ux_proc(ab, normalize_v3s4_proc(ab, R_ResolveScratch,
R_ResolveScratch, O_(ResolveLookAtScratch, right), /* r_src_offset = 32 */
R_T0, R_T1, O_(ResolveLookAtScratch, ux), /* r_dst_offset = 48 */
R_T2, R_T3, R_T5, R_T0, R_T1, R_T2,
R_T6, R_T7, R_T3,
R_T5,
R_T6,
R_T7,
R_V0, R_V0,
R_V1, R_V1);
R_AT);
/* Atom 4: resolve_look_at__cross_uz_ux_to_up — a=scratch+16, b=scratch+48, out=scratch+64 (HARDCODED). */ /* Atom 4: resolve_look_at__cross_uz_ux_to_up — a=scratch+16, b=scratch+48, out=scratch+64 (HARDCODED). */
smem.resolve_look_at_atom_addrs[4] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[4] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__cross_uz_ux_to_up_proc(ab, resolve_look_at__cross_uz_ux_to_up_proc(ab, R_ResolveScratch,
R_ResolveScratch,
R_T0, R_T1, R_T2, R_T0, R_T1, R_T2,
R_T3, R_T3,
R_T5, /* r_f (out ptr = scratch+64) */ R_T5, /* r_f (out ptr = scratch+64) */
R_T6, /* r_g (a ptr = scratch+16) */ R_T6, /* r_g (a ptr = scratch+16) */
R_T7); /* r_h (b ptr = scratch+48) */ R_T7); /* r_h (b ptr = scratch+48) */
/* Atom 5: resolve_look_at__normalize_up_to_uy — src=scratch+64, dst=scratch+80 (HARDCODED). */ /* Atom 5: normalize_v3s4_proc (generic, from gte.atom.c) — src=scratch+64=up, dst=scratch+80=uy. */
smem.resolve_look_at_atom_addrs[5] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); smem.resolve_look_at_atom_addrs[5] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4));
resolve_look_at__normalize_up_to_uy_proc(ab, normalize_v3s4_proc(ab, R_ResolveScratch,
R_ResolveScratch, O_(ResolveLookAtScratch, up), /* r_src_offset = 64 */
R_T0, R_T1, O_(ResolveLookAtScratch, uy), /* r_dst_offset = 80 */
R_T2, R_T3, R_T5, R_T0, R_T1, R_T2,
R_T6, R_T7, R_T3,
R_T5,
R_T6,
R_T7,
R_V0, R_V0,
R_V1, R_V1);
R_AT);
/* Atom 6: resolve_look_at__populate_and_translate — write look_at->m[][] from ux/uy/uz (computed from r_scratch+offset internally), /* Atom 6: resolve_look_at__populate_and_translate — write look_at->m[][] from ux/uy/uz (computed from r_scratch+offset internally),
then compute translation column t[] = R * (-eye). GPR pool: r_look_at + r_scratch + 4 ptr regs + 3 tmp regs = 9. */ then compute translation column t[] = R * (-eye). GPR pool: r_look_at + r_scratch + 4 ptr regs + 3 tmp regs = 9. */
@@ -336,20 +351,48 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
A2_S2 p; //??? A2_S2 p; //???
S4 flag; //???? S4 flag; //????
// Camera Look at // Camera Look at (Tape) + inline C11 fallback — bundle runs, then C11 inlines the look_at.
// Currently: bundle's atom 0 (input_and_sub) runs + C11 does the rest. As bundle atoms
// are incrementally fixed, the corresponding C11 lines get commented out.
if (1) if (1)
{ {
camera_look_at_c11(& smem.cam, & smem.cube.pos, & v3s4(0, -fp_one, 0));
}
// Camera look at (Tape)
{
MT3_S2S4* look_at = & smem.cam.look_at;
P3_S4* eye = & smem.cam.pos;
V3_S4* up_in = & v3s4(0, -fp_one, 0);
tb.used = 0; tb_scope_run(& tb) { tb.used = 0; tb_scope_run(& tb) {
resolve_look_at(& tb, & smem.cam.look_at, & smem.cam.pos, & smem.cube.pos, & v3s4(0, -fp_one, 0)); resolve_look_at(& tb, & smem.cam.look_at, & smem.cam.pos, & smem.cube.pos, & v3s4(0, -fp_one, 0));
} }
// RGA(Lengyel): Build matrix expansion of a rigid transformation. Corresponding motor is not constructed; we write the LA form for GTE.
// Preconditions: eye != target, up_in not collinear with (target - eye).
V3_S4 right, up, forward;
V3_S4 ux, uy, uz;
V3_S4 pos, off;
// forward = smem.cube.pos; sub_v3s4(& forward, smem.cam.pos); // RGA(Lengyel): Affine point - point = zero-weight direction. (now done by bundle atom 0)
// Read fwd from scratchpad[+0] (atom 0's output)
forward.x = u4_v(0x1F800000)[0];
forward.y = u4_v(0x1F800000)[1];
forward.z = u4_v(0x1F800000)[2];
forward.pad = u4_v(0x1F800000)[3];
// normalize_v3s4(& forward, & uz); // RGA(Lengyel): Normalize the direction bulk. Not finite-point unitization. (now done by bundle atom 1)
// Read uz from scratchpad[+16] (atom 1's output)
uz.x = u4_v(0x1F800010)[0];
uz.y = u4_v(0x1F800010)[1];
uz.z = u4_v(0x1F800010)[2];
uz.pad = u4_v(0x1F800010)[3];
cross_v3s4(& uz, & v3s4(0, -fp_one, 0), & right); normalize_v3s4(& right, & ux); // RGA(Lengyel): Complement(Wedge(forward, up_in)) -> right axis.
cross_v3s4(& uz, & ux, & up); normalize_v3s4(& up, & uy); // RGA(Lengyel): Complement(Wedge(forward, right)) -> up axis.
// RGA(Lengyel): matrix expansion of the world-to-camera rotation (basis rows).
smem.cam.look_at.m[0][0] = ux.x; smem.cam.look_at.m[0][1] = ux.y; smem.cam.look_at.m[0][2] = ux.z;
smem.cam.look_at.m[1][0] = uy.x; smem.cam.look_at.m[1][1] = uy.y; smem.cam.look_at.m[1][2] = uy.z;
smem.cam.look_at.m[2][0] = uz.x; smem.cam.look_at.m[2][1] = uz.y; smem.cam.look_at.m[2][2] = uz.z;
pos = smem.cam.pos; mul_v3s4(& pos, v3s4(-1,-1,-1)); // RGA(Lengyel): -eye in world coordinates (spatial bulk only; implicit weight is dropped).
// RGA(Lengyel): R * (-eye) is the full matrix translation column.
// Motor translator would store half this displacement in m.xyz; GTE consumes full column.
mul_m3s2_v3s4(& smem.cam.look_at, & pos, & off);
trans_m3s2( & smem.cam.look_at, & off);
} }
// Draw cube // Draw cube
+4 -4
View File
@@ -217,7 +217,7 @@ local function parse_path_root(input)
if not server_end or server_end == server_start then if not server_end or server_end == server_start then
error("UNC path requires //server/share: " .. input, 3) error("UNC path requires //server/share: " .. input, 3)
end end
local server = input:sub(server_start, server_end - 1) local server = input:sub(server_start, server_end - 1)
local share_start = server_end + 1 local share_start = server_end + 1
while input:sub(share_start, share_start) == "/" do while input:sub(share_start, share_start) == "/" do
share_start = share_start + 1 share_start = share_start + 1
@@ -515,8 +515,7 @@ local function splice_c_lines(source)
local splice_len = nil local splice_len = nil
if byte == BYTE_BACKSLASH and source:byte(pos + 1) == BYTE_NEWLINE then if byte == BYTE_BACKSLASH and source:byte(pos + 1) == BYTE_NEWLINE then
splice_len = 2 splice_len = 2
elseif byte == BYTE_BACKSLASH and source:byte(pos + 1) == BYTE_CR elseif byte == BYTE_BACKSLASH and source:byte(pos + 1) == BYTE_CR and source:byte(pos + 2) == BYTE_NEWLINE then
and source:byte(pos + 2) == BYTE_NEWLINE then
splice_len = 3 splice_len = 3
end end
@@ -2095,7 +2094,8 @@ local E_MAC_PREFIX_LEN = 4
--- * Unknown `mac_X` (not in `component_index`): fall back to `word_counts[ident]` if present; otherwise emit one opaque event so the cycle budget accounts for the word. --- * Unknown `mac_X` (not in `component_index`): fall back to `word_counts[ident]` if present; otherwise emit one opaque event so the cycle budget accounts for the word.
--- * Marker Tokens (`atom_label(...)` / `atom_offset(...)`): Zero events (they are pure metaprogram hints). --- * Marker Tokens (`atom_label(...)` / `atom_offset(...)`): Zero events (they are pure metaprogram hints).
--- ---
--- Cycle protection: a per-expansion `visiting` set tracks components currently on the expansion stack; a re-entry produces a deterministic `{kind = "cycle", ...}` error and aborts that branch (does NOT hang, does NOT recurse). --- Cycle protection: a per-expansion `visiting` set tracks components currently on the expansion stack;
--- a re-entry produces a deterministic `{kind = "cycle", ...}` error and aborts that branch (does NOT hang, does NOT recurse).
--- ---
--- Pure: reads `body_entry` / `component_index` / `word_counts`. Memoization is the caller's responsibility. --- Pure: reads `body_entry` / `component_index` / `word_counts`. Memoization is the caller's responsibility.
--- Callers wanting `word_events` / `word_event_errors` precomputed for many atoms should memoize them per atom. --- Callers wanting `word_events` / `word_event_errors` precomputed for many atoms should memoize them per atom.
+2 -3
View File
@@ -47,15 +47,14 @@ local function find_repo_root()
return root return root
end end
--- Set `package.path` (for `require("duffle")` + `require("passes.X")`) and --- Set `package.path` (for `require("duffle")` + `require("passes.X")`) and `package.cpath` (for `lpeg.dll`).
--- `package.cpath` (for `lpeg.dll`).
--- ---
--- This script does NOT touch the OS environment: no `os.setenv`, no `os.putenv`, no `$PATH` mods. --- This script does NOT touch the OS environment: no `os.setenv`, no `os.putenv`, no `$PATH` mods.
--- It just sets `package.path` and `package.cpath` (the standard Lua way to register module search dirs). --- It just sets `package.path` and `package.cpath` (the standard Lua way to register module search dirs).
--- lpeg is built by `update_deps.ps1` to `toolchain/lpeg/`, --- lpeg is built by `update_deps.ps1` to `toolchain/lpeg/`,
--- which we wire into `package.cpath` here (so `require("lpeg")` from `duffle.lua` resolves without any global state). --- which we wire into `package.cpath` here (so `require("lpeg")` from `duffle.lua` resolves without any global state).
function M.setup() function M.setup()
local repo_root = find_repo_root() local repo_root = find_repo_root()
if not repo_root then if not repo_root then
-- Unreachable in practice: find_repo_root() derives the repo root from this script's -- Unreachable in practice: find_repo_root() derives the repo root from this script's
-- own source path via debug.getinfo(1, "S").source (no subprocess, no git CLI, <1ms). -- own source path via debug.getinfo(1, "S").source (no subprocess, no git CLI, <1ms).
+90 -57
View File
@@ -4,22 +4,21 @@
--- Runs a deterministic first-fit allocator in the `R_T0..R_T7 + R_V0..R_V1` pool (10 physical GPRs). --- Runs a deterministic first-fit allocator in the `R_T0..R_T7 + R_V0..R_V1` pool (10 physical GPRs).
--- Emits one `#define R_<Sym>_Code R_Tn_Code` per marker into per-directory `gen/auto_reg.h`. --- Emits one `#define R_<Sym>_Code R_Tn_Code` per marker into per-directory `gen/auto_reg.h`.
--- ---
--- User-pinned GPRs (added 2026-08-10): The corpus's `register_alias_registry` is consulted to --- User-pinned GPRs : The corpus's `register_alias_registry` is consulted to exclude GPRs the user has pinned via
--- exclude GPRs the user has pinned via `atom_reg` + `_Code` defs (e.g. wave-context carriers like --- `atom_reg` + `_Code` defs (e.g. carriers like `R_ResolveScratch = R_T4 atom_reg`).
--- `R_ResolveScratch = R_T4 atom_reg`). These GPRs are unavailable to EVERY atom's source pool, --- These GPRs are unavailable to EVERY atom's source pool.
--- not just to atoms in the same phase — wave-context carriers are preserved across atoms by the --- Carriers are preserved across atoms by context discipline and must never be reallocated.
--- wave-context discipline and must never be reallocated.
--- Per-atom body parsing also catches alias references (R_<Alias>) and hardcoded R_Tn references, --- Per-atom body parsing also catches alias references (R_<Alias>) and hardcoded R_Tn references,
--- so the user can write either `R_T4` or `R_ResolveScratch` in an atom body and the pass will --- so the user can write either `R_T4` or `R_ResolveScratch` in an atom body and the pass will
--- exclude R_T4 from that atom's pool. --- exclude R_T4 from that atom's pool.
--- ---
--- Conflict detection: If the user hardcodes `R_Tn` in an atom body that shares a phase with an auto-reg that picked `R_Tn`, --- Conflict detection: If the user hardcodes `R_Tn` in an atom body that shares a phase with an auto-reg that picked `R_Tn`,
--- emit `phase_register_clash` as an info finding (no build stop). Should be unreachable after the --- emit `phase_register_clash` as an info finding (no build stop).
--- user-pinning + body-parsing fix above; kept as a defensive safety net. --- Should be unreachable after the user-pinning + body-parsing fix above; kept as a defensive safety net.
--- ---
--- Pool exhaustion: if a phase declares more `R_<Sym>` mappings than the 10-register pool can hold, --- Pool exhaustion: If a phase declares more `R_<Sym>` mappings than the 10-register pool can hold,
--- emit `phase_register_pool_exhausted` as a build-stopping error. --- emit `phase_register_pool_exhausted` as a build-stopping error.
---
--- @class AutoRegResult --- @class AutoRegResult
--- @field outputs table[] -- {kind=, path=} entries --- @field outputs table[] -- {kind=, path=} entries
--- @field errors table[] -- {line=, msg=} entries (build-stops) --- @field errors table[] -- {line=, msg=} entries (build-stops)
@@ -28,20 +27,57 @@
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
-- The fixed allocation pool: 10 physical GPRs whose `R_<Sym>_Code` macros exist in mips.h (lines 92-107). --- ════════════════════════════════════════════════════════════════════════════
-- Each pool entry is the PHYSICAL GPR ident (R_T0 etc.); --- THE GPR ALLOCATION POOL — what is allocatable, and (more importantly) WHY
-- `gpr .. "_Code"` resolves to the matching `R_Tn_Code` constant the source code references via `#define R_Load_Code R_T0_Code`. --- ════════════════════════════════════════════════════════════════════════════
-- Excluded: R_AT (assembler temp per lottes_tape.h:86), R_T8 (deferred to ac_yield_load pattern), ---
-- R_T9 (R_TapePtr; owned by the tape runtime). --- The auto-reg pass picks physical GPRs for `atom_auto_reg(...)` / `phase_auto_reg(...)` markers.
--- It allocates from a FIXED 10-register pool.
--- This comment block makes the inclusion AND exclusion criteria obvious so a reader doesn't have
--- to grep lottes_tape.h + mips.h to understand the design.
---
--- ── WHAT'S IN THE POOL (10 GPRs, all caller-trash per the O32 ABI) ────────
--- R_T0..R_T7 (GPR codes 8..15), R_V0..R_V1 (GPR codes 2..3)
--- The workhorse of every atom body. The uesr should be aware of atom allocation across atoms they chain.
--- If they have a collision it means either they didn't saturate the register file optimally for a phase,
--- or the may have made the workload to large for the run.
---
--- ── WHAT'S NOT IN THE POOL — and WHY (the "obvious exclusions") ────────────
--- R_T9 (GPR code 25) — R_TapePtr, the tape instruction stream pointer.
--- Owned by the tape runtime (in tape_run / tape_run_a02_s07).
--- `rgcc(R_TapePtr)` register-variable ties the C compiler's view to $t9 across the whole tape_run.
--- The auto-reg pass MUST NOT clobber this; doing so would desync the C-side tape pointer from the
--- hardware pointer and crash on the next tape_run.
---
--- R_T8 (GPR code 24) — R_AtomJmp, the atom-jump register used by the 4-word yield handshake.
--- Every `mac_yield()` / `mac_yield_tail` does `load_word R_AtomJmp, R_TapePtr, 0` then
--- `jump_reg R_AtomJmp`. The auto-reg pass MUST NOT clobber this either, or the atom dispatcher breaks.
--- Owned by the tape runtime, same family as R_TapePtr.
---
--- R_AT (GPR code 1) — Assembler temporary. Reserved by the MIPS O32 ABI for pseudoinstruction expansion
--- (lottes_tape.h:86, mips.h:93). The ISA's psuedo instructions use it as a scratch temporary.
---
--- R_A0..A3 (codes 4..7) — Function arguments. Used in tape_run_a02_s07, see below.
--- R_S0..S7 (codes 16..23) — Callee-saved. Preserved across C-ABI calls by convention.
--- The `tape_run_a02_s07` variant clobbers them deliberately, but the default `tape_run` does NOT.
--- Kept out of POOL to preserve the conservative default.
--- Add them in a separate "big clobber" pool if/when needed.
---
--- R_K0/K1 (codes 26..27) — Kernel / interrupt handler reserves. Never touched by user code; OS-internal.
--- R_GP/SP/FP/RA (codes 28..31) — Stack frame + return-address. Owned by the C compiler; never allocatable.
--- R_0 (code 0) — Hardwired zero. Cannot be written.
---
local POOL = { local POOL = {
"R_T0", "R_T1", "R_T2", "R_T3", "R_T0", "R_T1", "R_T2", "R_T3",
"R_T4", "R_T5", "R_T6", "R_T7", "R_T4", "R_T5", "R_T6", "R_T7",
"R_V0", "R_V1", "R_V0", "R_V1",
} }
-- Map from integer MIPS GPR code (the `code` field on AliasEntry) to the physical GPR ident -- Map from integer MIPS GPR code (the `code` field on AliasEntry) to the physical GPR ident in POOL.
-- in POOL. The standard MIPS O32 ABI register numbering matches mips.h's R_*_Code #defines -- The standard MIPS O32 ABI register numbering matches mips.h's R_*_Code #defines (mips.h).
-- (mips.h:92-123). Only the POOL entries matter for auto_reg — non-pool aliases are out of scope. -- Only the POOL entries matter for auto_reg — non-pool aliases
-- (R_AT=1, R_A0..A3=4..7, R_T8=24, R_T9=25, R_K0/K1=26..27, R_GP/SP/FP/RA=28..31)
-- are deliberately omitted — see the comment block above for the WHY of each exclusion.
local INT_CODE_TO_POOL_GPR = { local INT_CODE_TO_POOL_GPR = {
[2] = "R_V0", [3] = "R_V1", [2] = "R_V0", [3] = "R_V1",
[8] = "R_T0", [9] = "R_T1", [10] = "R_T2", [11] = "R_T3", [8] = "R_T0", [9] = "R_T1", [10] = "R_T2", [11] = "R_T3",
@@ -71,9 +107,10 @@ local function allocate_phase(phase_label, decls)
if not next_gpr then if not next_gpr then
errors[#errors + 1] = { errors[#errors + 1] = {
line = 0, line = 0,
msg = string.format( msg = string.format("phase_register_pool_exhausted: "
"phase_register_pool_exhausted: phase '%s' requested symbol '%s' but the pool has no remaining registers (max 10 per phase: R_T0..R_T7 + R_V0..R_V1). Split the phase or use hardcoded GPRs." .. "phase '%s' requested symbol '%s' but the pool has no remaining registers "
, phase_label, sym), .. "(max 10 per phase: R_T0..R_T7 + R_V0..R_V1). Split the phase or use hardcoded GPRs."
, phase_label, sym),
} }
return result, errors return result, errors
end end
@@ -83,26 +120,22 @@ local function allocate_phase(phase_label, decls)
end end
-- Build two projections from corpus.register_alias_registry: -- Build two projections from corpus.register_alias_registry:
-- user_pinned -- { [physical_gpr_ident] = true } -- GPRs unavailable to auto_reg globally -- user_pinned -- { [physical_gpr_ident] = true } -- GPRs unavailable to auto_reg globally (wave-context carriers, file-scope pinned aliases)
-- -- (wave-context carriers, file-scope pinned aliases) -- alias_to_gpr -- { [alias_ident] = physical_gpr_ident } -- for body parsing
-- alias_to_gpr -- { [alias_ident] = physical_gpr_ident } -- for body parsing -- Both projections are derived from the same set of entries: every AliasEntry in register_alias_registry has `has_atom_reg = true`
-- Both projections are derived from the same set of entries: every AliasEntry in -- (only those entries are added to the registry; see passes/scan_source.lua parse_enum_entry).
-- register_alias_registry has `has_atom_reg = true` (only those entries are added to the -- Each entry's `code` is the integer MIPS GPR number (0..31); INT_CODE_TO_POOL_GPR translates it back to the physical GPR ident.
-- registry; see passes/scan_source.lua parse_enum_entry). Each entry's `code` is the integer -- Aliases whose `code` points to a non-POOL GPR (e.g. R_S0, R_T8, R_K1) are ignored —
-- MIPS GPR number (0..31); INT_CODE_TO_POOL_GPR translates it back to the physical GPR ident. -- they don't affect the auto_reg pool, and they're already excluded from POOL above.
-- Aliases whose `code` points to a non-POOL GPR (e.g. R_S0, R_T8, R_K1) are ignored — they
-- don't affect the auto_reg pool, and they're already excluded from POOL above.
local function build_user_pins(corpus) local function build_user_pins(corpus)
local user_pinned = {} local user_pinned = {}
local alias_to_gpr = {} local alias_to_gpr = {}
if not corpus.register_alias_registry then if not corpus.register_alias_registry then return user_pinned, alias_to_gpr end
return user_pinned, alias_to_gpr
end
for alias_name, alias_entry in pairs(corpus.register_alias_registry) do for alias_name, alias_entry in pairs(corpus.register_alias_registry) do
if alias_entry.has_atom_reg and alias_entry.code then if alias_entry.has_atom_reg and alias_entry.code then
local gpr = INT_CODE_TO_POOL_GPR[alias_entry.code] local gpr = INT_CODE_TO_POOL_GPR[alias_entry.code]
if gpr then if gpr then
user_pinned[gpr] = true user_pinned[gpr] = true
alias_to_gpr[alias_name] = gpr alias_to_gpr[alias_name] = gpr
end end
end end
@@ -111,10 +144,10 @@ local function build_user_pins(corpus)
end end
-- Find every physical GPR referenced in the atom body, via EITHER: -- Find every physical GPR referenced in the atom body, via EITHER:
-- (a) a hardcoded physical GPR ident (R_T\d+|R_V\d+|R_A\d+|R_S\d+) — the existing regex; -- (a) A hardcoded physical GPR ident (R_T\d+|R_V\d+|R_A\d+|R_S\d+) — the existing regex;
-- (b) an alias ident (R_<Alias>) resolved via alias_to_gpr back to its physical GPR ident. -- (b) An alias ident (R_<Alias>) resolved via alias_to_gpr back to its physical GPR ident.
-- Returns { [physical_gpr_ident] = count }. The clash-detection and source-pool-exclusion logic -- Returns { [physical_gpr_ident] = count }. Clash-detection and source-pool-exclusion logic
-- only needs the presence of each GPR (boolean test), but keeping the count preserves the -- only needs the presence of each GPR (boolean test), but keeping count preserves the
-- original find_hardcoded_rn shape so callers can switch without churn. -- original find_hardcoded_rn shape so callers can switch without churn.
-- The alias pattern is sorted lexicographically to keep the regex deterministic. -- The alias pattern is sorted lexicographically to keep the regex deterministic.
local function find_used_gprs(body_text, alias_to_gpr) local function find_used_gprs(body_text, alias_to_gpr)
@@ -161,8 +194,8 @@ local function emit_auto_reg_h(out_dir, dir, sources, mappings)
lines[#lines + 1] = "// R_<Sym>_Code = <chosen GPR's _Code constant> for every marker in this directory." lines[#lines + 1] = "// R_<Sym>_Code = <chosen GPR's _Code constant> for every marker in this directory."
lines[#lines + 1] = "" lines[#lines + 1] = ""
for _, sym in ipairs(stable_sort_keys(mappings)) do for _, sym in ipairs(stable_sort_keys(mappings)) do
local gpr = mappings[sym] local gpr = mappings[sym]
local gpr_code = gpr .. "_Code" local gpr_code = gpr .. "_Code"
lines[#lines + 1] = "#define " .. sym .. "_Code " .. gpr_code lines[#lines + 1] = "#define " .. sym .. "_Code " .. gpr_code
end end
lines[#lines + 1] = "" lines[#lines + 1] = ""
@@ -190,12 +223,10 @@ function M.run(ctx)
end end
-- 0. Build the user-pinned GPR exclusion set + alias-to-GPR resolution map. -- 0. Build the user-pinned GPR exclusion set + alias-to-GPR resolution map.
-- Wave-context carriers (e.g. `R_ResolveScratch = R_T4 atom_reg` in -- Wave-context carriers (e.g. `R_ResolveScratch = R_T4 atom_reg` in hello_camera.atom.c)
-- hello_camera.atom.c) MUST NOT be allocated to any auto-reg marker — they're -- MUST NOT be allocated to any auto-reg marker — they're preserved across atoms by the wave-context discipline.
-- preserved across atoms by the wave-context discipline. The corpus's -- The corpus's register_alias_registry is the source of truth for these opt-in pins.
-- register_alias_registry is the source of truth for these opt-in pins. -- Body references to those aliases (via alias_to_gpr) are also excluded on a per-atom basis in step 2 below.
-- Body references to those aliases (via alias_to_gpr) are also excluded on a
-- per-atom basis in step 2 below.
local user_pinned, alias_to_gpr = build_user_pins(corpus) local user_pinned, alias_to_gpr = build_user_pins(corpus)
-- 1. Allocate phase pools first (phase declarations take precedence over per-atom declarations). -- 1. Allocate phase pools first (phase declarations take precedence over per-atom declarations).
@@ -213,8 +244,8 @@ function M.run(ctx)
-- 2. Allocate per-atom auto-regs. If the atom scope matches a phase, reuse the phase pool. -- 2. Allocate per-atom auto-regs. If the atom scope matches a phase, reuse the phase pool.
-- Otherwise, allocate a private pool for the atom. -- Otherwise, allocate a private pool for the atom.
-- The phase membership is in `corpus.atom_phases[phase_label].atoms` (an array of atom names declared via `atom_phase(<phase>)` in the atom's `atom_info` line). -- The phase membership is in `corpus.atom_phases[phase_label].atoms` (an array of atom names declared via `atom_phase(<phase>)`
-- Build a reverse map `atom_name -> phase_label` so the lookup is O(1) per atom scope. -- in the atom's `atom_info` line). Build a reverse map `atom_name -> phase_label` so the lookup is O(1) per atom scope.
local atom_name_to_phase = {} local atom_name_to_phase = {}
for phase_label, entry in pairs(corpus.atom_phases or {}) do for phase_label, entry in pairs(corpus.atom_phases or {}) do
for _, atom_name in ipairs(entry.atoms or {}) do for _, atom_name in ipairs(entry.atoms or {}) do
@@ -229,8 +260,7 @@ function M.run(ctx)
-- (a) every GPR already committed (phase allocations + prior atom allocations) -- (a) every GPR already committed (phase allocations + prior atom allocations)
-- (b) every USER-PINNED GPR (wave-context carriers + file-scope pinned aliases) -- (b) every USER-PINNED GPR (wave-context carriers + file-scope pinned aliases)
-- (c) every GPR referenced in the atom's body — either hardcoded R_X or alias R_Xxx -- (c) every GPR referenced in the atom's body — either hardcoded R_X or alias R_Xxx
-- (the latter resolved via alias_to_gpr; this catches cases where the user -- (the latter resolved via alias_to_gpr; this catches cases where the user wrote R_ResolveScratch instead of R_T4 directly)
-- wrote R_ResolveScratch instead of R_T4 directly)
-- Atoms whose scope matches a phase share the global pool with the phase allocations; -- Atoms whose scope matches a phase share the global pool with the phase allocations;
-- the original `source_pool = phase_allocations[phase_label]` form used the phase -- the original `source_pool = phase_allocations[phase_label]` form used the phase
-- allocation MAP as a pool, but that map has no array part, so `table.remove(source_pool, 1)` -- allocation MAP as a pool, but that map has no array part, so `table.remove(source_pool, 1)`
@@ -239,7 +269,7 @@ function M.run(ctx)
for _, m in pairs(phase_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end for _, m in pairs(phase_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end
for _, m in pairs(atom_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end for _, m in pairs(atom_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end
-- (c) Body references — scan the atom body for hardcoded + alias-resolved GPRs. -- (c) Body references — scan the atom body for hardcoded + alias-resolved GPRs.
-- Folded into `used` so the source_pool exclusion is a single check. -- Folded into `used` so the source_pool exclusion is a single check.
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope]
if atom and atom.body then if atom and atom.body then
local body_used = find_used_gprs(atom.body, alias_to_gpr) local body_used = find_used_gprs(atom.body, alias_to_gpr)
@@ -259,7 +289,8 @@ function M.run(ctx)
if not next_gpr then if not next_gpr then
errors[#errors + 1] = { errors[#errors + 1] = {
line = 0, line = 0,
msg = string.format("phase_register_pool_exhausted: atom '%s' requested symbol '%s' but no free registers remain in its scope pool." msg = string.format("phase_register_pool_exhausted: atom '%s' requested symbol '%s' "
.. "but no free registers remain in its scope pool."
, atom_scope, sym), , atom_scope, sym),
} }
else else
@@ -271,10 +302,10 @@ function M.run(ctx)
-- 3. Conflict-with-hardcoded detection (defensive — should be unreachable now). -- 3. Conflict-with-hardcoded detection (defensive — should be unreachable now).
-- The source_pool exclusion in step 2 (b) + (c) already accounts for both user-pinned GPRs -- The source_pool exclusion in step 2 (b) + (c) already accounts for both user-pinned GPRs
-- and body-referenced GPRs (hardcoded R_Tn OR alias R_<Alias>). An auto-reg allocation that -- and body-referenced GPRs (hardcoded R_Tn OR alias R_<Alias>).
-- matched an existing body reference would be impossible by construction. This warning is kept -- An auto-reg allocation that matched an existing body reference would be impossible by construction.
-- as a defensive safety net for cases the body scanner might miss (e.g. macros that expand to -- This warning is kept as a defensive safety net for cases the body scanner might miss
-- register references the scanner cannot resolve). -- (e.g. macros that expand to register references the scanner cannot resolve).
-- For each resolved (scope, sym) -> R_Tn mapping, scan the atom body source for used GPRs. -- For each resolved (scope, sym) -> R_Tn mapping, scan the atom body source for used GPRs.
for atom_scope, decls in pairs(atom_allocations) do for atom_scope, decls in pairs(atom_allocations) do
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope]
@@ -284,7 +315,8 @@ function M.run(ctx)
if used_in_body[allocated_gpr] and used_in_body[allocated_gpr] > 0 then if used_in_body[allocated_gpr] and used_in_body[allocated_gpr] > 0 then
warnings[#warnings + 1] = { warnings[#warnings + 1] = {
line = atom.line or 0, line = atom.line or 0,
msg = string.format("phase_register_clash: atom '%s' has hardcoded '%s' in its body AND an auto-reg marker '%s' that was allocated to '%s' (same phase). Resolve by removing the hardcoded reference or renaming the auto-reg." msg = string.format("phase_register_clash: atom '%s' has hardcoded '%s' in its body AND an auto-reg marker '%s' "
.. "that was allocated to '%s' (same phase). Resolve by removing the hardcoded reference or renaming the auto-reg."
, atom_scope, allocated_gpr, sym, allocated_gpr), , atom_scope, allocated_gpr, sym, allocated_gpr),
} }
end end
@@ -300,7 +332,8 @@ function M.run(ctx)
for _, src in ipairs(sources) do for _, src in ipairs(sources) do
-- Collect every (sym -> gpr) entry that originated from a source in this directory. -- Collect every (sym -> gpr) entry that originated from a source in this directory.
-- `src.scan.atom_auto_regs` is keyed by ATOM SCOPE NAME; `pairs(t)` iterates KEYS so `scope_name` here is the scope ident (e.g. "cube_g4_face"). -- `src.scan.atom_auto_regs` is keyed by ATOM SCOPE NAME; `pairs(t)` iterates KEYS so `scope_name` here is the scope ident (e.g. "cube_g4_face").
-- The previous `for _, scan_atom_auto` form silently assigned the VALUE (a `{sym = sym}` table) to the variable, which made `atom_allocations[scan_atom_auto]` a table-indexed lookup that never resolved. -- The previous `for _, scan_atom_auto` form silently assigned the VALUE (a `{sym = sym}` table) to the variable,
-- which made `atom_allocations[scan_atom_auto]` a table-indexed lookup that never resolved.
for scope_name in pairs(src.scan and src.scan.atom_auto_regs or {}) do for scope_name in pairs(src.scan and src.scan.atom_auto_regs or {}) do
for sym, gpr in pairs(atom_allocations[scope_name] or {}) do for sym, gpr in pairs(atom_allocations[scope_name] or {}) do
per_dir_mappings[sym] = gpr per_dir_mappings[sym] = gpr
+37 -35
View File
@@ -3,9 +3,12 @@
--- Ownership: `corpus.word_counts`, `corpus.components`, and `corpus.component_body_index`. --- Ownership: `corpus.word_counts`, `corpus.components`, and `corpus.component_body_index`.
--- Scanner owns `declaration_comment` and `debug_skip` on each declaration record; this pass projects both forward. --- Scanner owns `declaration_comment` and `debug_skip` on each declaration record; this pass projects both forward.
--- ---
--- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)`, `MipsAtomComp_Proc_(ac_X, { body })`, and `MipsAtom_Proc_(X, ab, { body })` declarations, --- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations (kind="comp_bare" / "comp_proc"),
--- then resolves the function-args string from the preceding `FI_ Slice_MipsCode ac_X(...)` declaration via a backward walk. --- then resolves the function-args string from the preceding `FI_ Slice_MipsCode ac_X(...)` declaration via a backward walk.
--- ---
--- `MipsAtom_Proc_(X, ab, { body })` declarations (kind="atom_proc") are ATOMS, not components, and are deliberately excluded —
--- atoms get emitted via `tb_emit(tb, code_<name>)` linker symbols, not inlined as `mac_*` macros.
---
--- Emits one `gen/macs.h` per *immediate source directory* with `#define mac_X(sig) \` macros plus `WORD_COUNT(mac_X, N)` entries for downstream offset computation. --- Emits one `gen/macs.h` per *immediate source directory* with `#define mac_X(sig) \` macros plus `WORD_COUNT(mac_X, N)` entries for downstream offset computation.
--- All sources inside the same directory contribute to the same file (per-directory aggregation). --- All sources inside the same directory contribute to the same file (per-directory aggregation).
--- The directory itself is the namespace, so the filename does not repeat the module name. --- The directory itself is the namespace, so the filename does not repeat the module name.
@@ -76,7 +79,7 @@ local MACS_FILENAME = "macs.h"
--- @field args string|nil -- Function-args string (function form only) --- @field args string|nil -- Function-args string (function form only)
--- @field line integer -- Source line of the declaration --- @field line integer -- Source line of the declaration
--- @field comment string|nil -- Scanner-owned `declaration_comment`; the components pass reads it from the scanner record --- @field comment string|nil -- Scanner-owned `declaration_comment`; the components pass reads it from the scanner record
--- @field kind string -- "comp_bare" | "comp_proc" | "atom_proc" --- @field kind string -- "comp_bare" | "comp_proc" (atom_proc is NOT a component — see `project_components`)
--- @field debug_skip boolean -- Mirror of `a.debug_skip` (scanner-owned); true iff a bare `atom_dbg_skip` marker immediately preceded the declaration --- @field debug_skip boolean -- Mirror of `a.debug_skip` (scanner-owned); true iff a bare `atom_dbg_skip` marker immediately preceded the declaration
-- ════════════════════════════════════════════════════════════════════════════ -- ════════════════════════════════════════════════════════════════════════════
@@ -200,16 +203,17 @@ end
local function project_components(source, scan) local function project_components(source, scan)
local out = {} local out = {}
for _, a in ipairs(scan.atoms) do for _, a in ipairs(scan.atoms) do
if a.kind == "comp_bare" or a.kind == "comp_proc" or a.kind == "atom_proc" then -- Only `MipsAtomComp_(ac_X)` (kind="comp_bare") and `MipsAtomComp_Proc_(ac_X, ...)` (kind="comp_proc")
-- `MipsAtom_Proc_` atoms have no `FI_ Slice_MipsCode ac_X(...)` function-decl prelude -- are COMPONENTS — they get inlined via `mac_<name>` aliases inside atom bodies.
-- (the macro sits inside a wrapping `I_ void <proc_name>(...)` body), so the function-args -- `MipsAtom_Proc_` (kind="atom_proc") is an ATOM (ends with `mac_yield()`); it gets emitted via
-- lookup is meaningless; signature defaults to `...` (variadic-ignored). -- `tb_emit(tb, code_<name>)` (linker symbol), NOT inlined as a macro. Including `atom_proc` here
-- The `mac_<name>` alias expansion discards the `ab` (atom-builder) arg the same way -- would incorrectly emit `mac_<name>` aliases for atoms, polluting `gen/macs.h`.
-- `MipsAtomComp_Proc_` components do. -- See `docs/duffle_dsl_primer.md` §"mac_* aliases" for the contract.
local args = nil if a.kind == "comp_bare" or a.kind == "comp_proc" then
if a.kind ~= "atom_proc" then -- Function-args lookup is meaningful for `MipsAtomComp_Proc_` components
args = find_function_args_for(source, a.raw_name, a.ident_pos) -- (the macro sits inside `FI_ Slice_MipsCode ac_X(...)`); the alias expansion
end -- discards the `ab` (atom-builder) arg the same way both forms do.
local args = find_function_args_for(source, a.raw_name, a.ident_pos)
-- Comment ownership: scan_source.lua stamps `declaration_comment` on the record by walking backward past any associated bare marker. -- Comment ownership: scan_source.lua stamps `declaration_comment` on the record by walking backward past any associated bare marker.
-- The pass reads `declaration_comment` directly. -- The pass reads `declaration_comment` directly.
local comment = a.declaration_comment or "" local comment = a.declaration_comment or ""
@@ -221,7 +225,7 @@ local function project_components(source, scan)
body_tokens = a.body_tokens, body_tokens = a.body_tokens,
args = args, args = args,
comment = comment, comment = comment,
kind = a.kind, -- "comp_bare" | "comp_proc" | "atom_proc"; provenance emitter reads this. kind = a.kind, -- "comp_bare" | "comp_proc"; provenance emitter reads this.
debug_skip = a.debug_skip == true, debug_skip = a.debug_skip == true,
} }
end end
@@ -400,8 +404,7 @@ local function cycle_cost_rec(name, comp_by_name, latency, cache)
end end
--- (internal) Recursive GP0 prim-buffer contribution. Count `store_word` / `store_half` / `store_byte` --- (internal) Recursive GP0 prim-buffer contribution. Count `store_word` / `store_half` / `store_byte`
--- calls in the component body that target `R_PrimCursor` (these are the --- calls in the component body that target `R_PrimCursor` (these are the RAM-side prim-buffer words the macro contributes), recursing through nested `mac_*` calls.
--- RAM-side prim-buffer words the macro contributes), recursing through nested `mac_*` calls.
--- Only `R_PrimCursor`-targeting stores count. Stores targeting other registers (e.g. `R_OtBase`, heap pointers) are not prim-buffer contributions. --- Only `R_PrimCursor`-targeting stores count. Stores targeting other registers (e.g. `R_OtBase`, heap pointers) are not prim-buffer contributions.
--- @param name string --- @param name string
--- @param comp_by_name table<string, Component> --- @param comp_by_name table<string, Component>
@@ -484,10 +487,9 @@ end
--- Determine the macro signature: function-args list (function form) or variadic-ignored (bare form). --- Determine the macro signature: function-args list (function form) or variadic-ignored (bare form).
--- For `MipsAtomComp_Proc_` components, the leading `ab` (atom-builder) arg is dropped: --- For `MipsAtomComp_Proc_` components, the leading `ab` (atom-builder) arg is dropped:
--- the generated `mac_<name>` macros are inline-expansion aliases for baked atoms; their bodies --- the generated `mac_<name>` macros are inline-expansion aliases for baked atoms; their bodies don't reference `ab`
--- don't reference `ab` (the builder is only consumed by the procedural `atombuilder_unroll` line --- (the builder is only consumed by the procedural `atombuilder_unroll` line that `MipsAtomComp_Proc_` appends after the body).
--- that `MipsAtomComp_Proc_` appends after the body). Inline callers therefore don't need to thread --- Inline callers therefore don't need to thread a builder context.
--- a builder context.
--- @param args_str string|nil --- @param args_str string|nil
--- @return string --- @return string
local function signature_from_args(args_str) local function signature_from_args(args_str)
@@ -544,7 +546,7 @@ local function build_component_lines(c, counts)
-- Marker comment: emitted once for every skipped component. -- Marker comment: emitted once for every skipped component.
-- The marker is scanner-owned (declared by `atom_dbg_skip` immediately before the declaration in the source); -- The marker is scanner-owned (declared by `atom_dbg_skip` immediately before the declaration in the source);
-- the components pass projects `c.debug_skip` and emits the marker as a generated comment. -- This pass projects `c.debug_skip` and emits the marker as a generated comment.
if c.debug_skip then if c.debug_skip then
lines[#lines + 1] = "/* atom_dbg_skip */" lines[#lines + 1] = "/* atom_dbg_skip */"
end end
@@ -578,8 +580,8 @@ end
--- Build the boilerplate header lines (the `#ifdef INTELLISENSE_DIRECTIVES` block, --- Build the boilerplate header lines (the `#ifdef INTELLISENSE_DIRECTIVES` block,
--- the `// Auto-generated` comment, the `// Source:` line, and the self-contained `WORD_COUNT` macro definition). --- the `// Auto-generated` comment, the `// Source:` line, and the self-contained `WORD_COUNT` macro definition).
--- @param dir string -- the absolute source directory --- @param dir string -- Absolute source directory
--- @param sources SourceFile[] -- sources contributing to this directory (for the header comment) --- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
--- @return string[] --- @return string[]
local function header_boilerplate(dir, sources) local function header_boilerplate(dir, sources)
local source_lines = { "// Directory: " .. duffle.to_absolute_path(dir) .. "/" } local source_lines = { "// Directory: " .. duffle.to_absolute_path(dir) .. "/" }
@@ -610,9 +612,9 @@ end
--- Compute the per-directory output path for `.macs.h`. --- Compute the per-directory output path for `.macs.h`.
--- e.g. any source in `code/duffle/` produces `code/duffle/gen/macs.h` regardless of source filename. --- e.g. any source in `code/duffle/` produces `code/duffle/gen/macs.h` regardless of source filename.
--- The directory name is the namespace; the filename does not repeat it. --- The directory name is the namespace; the filename does not repeat it.
--- @param dir string -- the absolute source directory --- @param dir string -- Absolute source directory
--- @return string -- the output directory --- @return string -- Output directory
--- @return string -- the full output path --- @return string -- Full output path
local function compute_macs_h_path(dir) local function compute_macs_h_path(dir)
local out_dir = dir .. "/" .. GEN_SUBDIR local out_dir = dir .. "/" .. GEN_SUBDIR
local out_path = out_dir .. "/" .. MACS_FILENAME local out_path = out_dir .. "/" .. MACS_FILENAME
@@ -622,11 +624,11 @@ end
--- Emit a per-directory `.macs.h` header with the aggregated `mac_X` macros + `WORD_COUNT` entries. --- Emit a per-directory `.macs.h` header with the aggregated `mac_X` macros + `WORD_COUNT` entries.
--- Writes in BINARY mode so LF line endings are preserved (the git blob is LF; Windows text-mode would emit CRLF and break the byte-identical diff). --- Writes in BINARY mode so LF line endings are preserved (the git blob is LF; Windows text-mode would emit CRLF and break the byte-identical diff).
--- @param ctx PassCtx --- @param ctx PassCtx
--- @param dir string -- the absolute source directory --- @param dir string -- Absolute source directory
--- @param sources SourceFile[] -- sources contributing to this directory (for the header comment) --- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
--- @param components Component[] -- aggregated components from all sources in this directory --- @param components Component[] -- Aggregated components from all sources in this directory
--- @param counts table<string, integer> -- precomputed word counts (from count_all_components) --- @param counts table<string, integer> -- Precomputed word counts (from count_all_components)
--- @return string|nil -- path to the written file (nil if no components) --- @return string|nil -- Path to the written file (nil if no components)
local function emit_component_macros_h(ctx, dir, sources, components, counts) local function emit_component_macros_h(ctx, dir, sources, components, counts)
if #components == 0 then return nil end if #components == 0 then return nil end
local out_dir, out_path = compute_macs_h_path(dir) local out_dir, out_path = compute_macs_h_path(dir)
@@ -665,11 +667,11 @@ local function update_canonical_word_counts(corpus, components, counts)
end end
--- @class ComponentDef --- @class ComponentDef
--- @field name string -- bare name (without ac_/mac_ prefix) --- @field name string -- Bare name (without ac_/mac_ prefix)
--- @field line integer -- definition source line (line of `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`) --- @field line integer -- Definition source line (line of `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`)
--- @field path string -- absolute source path of the definition --- @field path string -- Absolute source path of the definition
--- @field kind string -- "comp_bare" | "comp_proc" | "atom_proc" --- @field kind string -- "comp_bare" | "comp_proc" (atom_proc is NOT a component)
--- @field debug_skip boolean -- mirror of the scanner-owned `a.debug_skip`; consumers read this directly --- @field debug_skip boolean -- Mirror of the scanner-owned `a.debug_skip`; consumers read this directly
--- (internal) Populate `corpus.components` with this source's components-by-name map. --- (internal) Populate `corpus.components` with this source's components-by-name map.
--- First declaration wins; later declarations of the same bare name are dropped and recorded as a collision via `corpus.collisions` (kind = "component"). --- First declaration wins; later declarations of the same bare name are dropped and recorded as a collision via `corpus.collisions` (kind = "component").
+18 -17
View File
@@ -703,9 +703,9 @@ end
--- `{comp_name, call_file, call_line, comp_file, comp_line, start_pos, end_pos, body_lines, debug_skip}`. `body_lines[k]` --- `{comp_name, call_file, call_line, comp_file, comp_line, start_pos, end_pos, body_lines, debug_skip}`. `body_lines[k]`
--- is the k-th word's source line within the component body. --- is the k-th word's source line within the component body.
--- ---
--- @param corpus table -- the corpus from `ctx.shared.corpus` --- @param corpus table -- From `ctx.shared.corpus`
--- @param addrs table -- ELF symbols keyed by atom name from `elf_dwarf.read_nm` --- @param addrs table -- ELF symbols keyed by atom name from `elf_dwarf.read_nm`
--- @return table[] -- list of {name, addr, size_bytes, words, entries, invocations, debug_skip?} --- @return table[] -- List of {name, addr, size_bytes, words, entries, invocations, debug_skip?}
local function build_atom_table(corpus, addrs) local function build_atom_table(corpus, addrs)
-- Cross-ref: keep only atoms present in BOTH the nm symbol table AND `corpus.atoms_by_name`. Output is sorted by ascending addr. -- Cross-ref: keep only atoms present in BOTH the nm symbol table AND `corpus.atoms_by_name`. Output is sorted by ascending addr.
local atoms_by_name = corpus.atoms_by_name or {} local atoms_by_name = corpus.atoms_by_name or {}
@@ -834,10 +834,10 @@ end
--- This is intentional: silently falling back to a hardcoded GPR would mask the missing opt-in. --- This is intentional: silently falling back to a hardcoded GPR would mask the missing opt-in.
--- ---
--- Pre-tokenized: `body_tokens` is the scan-source pass's pre-split list of top-level statements (each entry is a single `load_*` call or other statement). --- Pre-tokenized: `body_tokens` is the scan-source pass's pre-split list of top-level statements (each entry is a single `load_*` call or other statement).
--- @param body_tokens table[] -- the atom's pre-tokenized body statements (from atom.body_tokens) --- @param body_tokens table[] -- The atom's pre-tokenized body statements (from atom.body_tokens)
--- @param binds_name string -- expected Binds_X name (skip pairs with mismatching binds) --- @param binds_name string -- Expected Binds_X name (skip pairs with mismatching binds)
--- @param registries table -- merged registries from collect_per_source_registries --- @param registries table -- Merged registries from collect_per_source_registries
--- @return table[] -- list of {reg = <MIPS index>, field = <field name>} --- @return table[] -- List of {reg = <MIPS index>, field = <field name>}
local function parse_body_load_pairs(body_tokens, binds_name, registries) local function parse_body_load_pairs(body_tokens, binds_name, registries)
local pairs = {} local pairs = {}
local reg_index_by_name = (registries and registries.register_alias_registry) or {} local reg_index_by_name = (registries and registries.register_alias_registry) or {}
@@ -880,9 +880,9 @@ end
--- The piece chain uses (DW_OP_regN, DW_OP_piece, ULEB128(field_size)). --- The piece chain uses (DW_OP_regN, DW_OP_piece, ULEB128(field_size)).
--- ---
--- Binds fields come from `scan.binds`; the per-source `scan.binds[i].fields` already carries the typed-field record after the scan-source generalization. --- Binds fields come from `scan.binds`; the per-source `scan.binds[i].fields` already carries the typed-field record after the scan-source generalization.
--- @param corpus table -- the corpus from `ctx.shared.corpus` --- @param corpus table -- From `ctx.shared.corpus`
--- @param atom_table table[] -- the cross-ref'd atom table from build_atom_table --- @param atom_table table[] -- Cross-ref'd atom table from build_atom_table
--- @param registries table -- merged registries from collect_per_source_registries --- @param registries table -- Merged registries from collect_per_source_registries
--- @return table, table -- (rbind_atoms, rbind_structs) --- @return table, table -- (rbind_atoms, rbind_structs)
local function parse_rbind_atoms(corpus, atom_table, registries) local function parse_rbind_atoms(corpus, atom_table, registries)
registries = registries or {} registries = registries or {}
@@ -944,7 +944,7 @@ local function parse_rbind_atoms(corpus, atom_table, registries)
binds = ai.binds, binds = ai.binds,
fields = struct.fields, -- {name, offset} from scan.binds fields = struct.fields, -- {name, offset} from scan.binds
bytes = struct.bytes, bytes = struct.bytes,
regs = pairs, -- ordered list of {reg, field} regs = pairs, -- Ordered list of {reg, field}
info_line = ai.info_line, info_line = ai.info_line,
} }
table.insert(struct.atom_names, atom_name) table.insert(struct.atom_names, atom_name)
@@ -1036,13 +1036,13 @@ local function build_dwarf_aranges_section(existing, atom_table)
-- We bump the unit's length field accordingly. -- We bump the unit's length field accordingly.
-- --
-- Unit structure (DWARF4 §7.21): -- Unit structure (DWARF4 §7.21):
-- unit_length (4) -- unit_length (4)
-- version (2) -- version (2)
-- debug_info_offset (4) -- CU DIE offset in .debug_info -- debug_info_offset (4) -- CU DIE offset in .debug_info
-- address_size (1) -- address_size (1)
-- segment_size (1) -- segment_size (1)
-- entries... (4-byte addr + 4-byte length) -- entries... (4-byte addr + 4-byte length)
-- terminator (8 bytes: addr=0, length=0) -- terminator (8 bytes: addr=0, length=0)
-- Walk all units and emit each one (preserving existing structure). -- Walk all units and emit each one (preserving existing structure).
-- For the LAST unit, replace the terminator with my entries + new term. -- For the LAST unit, replace the terminator with my entries + new term.
@@ -1780,7 +1780,8 @@ local function build_inserted_children(main_cu_offset, main_cu_end_excl, atom_ta
emit(uleb128(ABBREV_TYPED_VIEW_POINTER)) -- DW_TAG_pointer_type (abbrev 110; NOT 9; void chain target) emit(uleb128(ABBREV_TYPED_VIEW_POINTER)) -- DW_TAG_pointer_type (abbrev 110; NOT 9; void chain target)
emit(elf_dwarf.write_u32_le(ref4_of(void_chain_offset))) -- 4-byte ref4: points at the void base_type's tag byte emit(elf_dwarf.write_u32_le(ref4_of(void_chain_offset))) -- 4-byte ref4: points at the void base_type's tag byte
-- type_chain_offsets["void|1"] is what step (f) of the per-RR_<R_Name> chain looks up. -- type_chain_offsets["void|1"] is what step (f) of the per-RR_<R_Name> chain looks up.
type_chain_offsets["void|1"] = void_chain_offset -- both the base_type offset and the pointer_type are emitted consecutively; the OUTERMOST is the pointer_type. The variable's DW_AT_type must reference the pointer_type, not the base_type. Patch below. type_chain_offsets["void|1"] = void_chain_offset -- both the base_type offset and the pointer_type are emitted consecutively; the OUTERMOST is the pointer_type.
-- The variable's DW_AT_type must reference the pointer_type, not the base_type. Patch below.
-- Capture the pointer_type's offset (the last-thing-emitted DIE start) and overwrite the lookup. -- Capture the pointer_type's offset (the last-thing-emitted DIE start) and overwrite the lookup.
-- The pointer_type was emitted as: uleb(9) (1 byte) + 4-byte ref4 = 5 bytes. Its tag byte is at void_chain_offset + 8 (the base_type's 8 bytes: 1 tag + 5 name + 1 byte_size + 1 encoding). -- The pointer_type was emitted as: uleb(9) (1 byte) + 4-byte ref4 = 5 bytes. Its tag byte is at void_chain_offset + 8 (the base_type's 8 bytes: 1 tag + 5 name + 1 byte_size + 1 encoding).
local ptr_void_offset = void_chain_offset + 8 local ptr_void_offset = void_chain_offset + 8
+8
View File
@@ -4,9 +4,17 @@
--- for `MipsAtom_(name)` and `MipsCode code_<name>` declarations, computes the word offset --- for `MipsAtom_(name)` and `MipsCode code_<name>` declarations, computes the word offset
--- from each `atom_offset(F, T)` marker to its target `atom_label(T)` declaration, and emits --- from each `atom_offset(F, T)` marker to its target `atom_label(T)` declaration, and emits
--- `gen/offsets.h` with one `#define _atom_offset_F_T = N` per branch. --- `gen/offsets.h` with one `#define _atom_offset_F_T = N` per branch.
---
--- Per-directory aggregation: every source in the same directory contributes to the same `gen/offsets.h`. --- Per-directory aggregation: every source in the same directory contributes to the same `gen/offsets.h`.
--- The directory itself is the namespace; the filename does not repeat the module name. --- The directory itself is the namespace; the filename does not repeat the module name.
--- ---
--- (Task 12.16 note: atom-namespaced enum names — e.g., `atom_offset__normalize_v3s4__srav_path__aligned_done` —
--- were considered to prevent cross-atom label collisions, but the C-side `atom_offset(F, T)` macro in
--- `code/duffle/dsl.atom.h` doesn't know the current atom_name at expansion time, so any namespacing
--- on the metaprogram side breaks the C build. Reverted. The C-side would need a per-atom
--- `CURRENT_ATOM` #define (set by `MipsAtom_`/`MipsAtom_Proc_` macros) plus an updated `atom_offset`
--- macro that uses it. That's a coordinated refactor — deferred to a future track.)
---
--- The offset is `target_word - branch_word - 1` (the standard MIPS branch-immediate encoding: branch_offset = relative_pc_in_words - 1). --- The offset is `target_word - branch_word - 1` (the standard MIPS branch-immediate encoding: branch_offset = relative_pc_in_words - 1).
-- ════════════════════════════════════════════════════════════════════════════ -- ════════════════════════════════════════════════════════════════════════════
+3 -3
View File
@@ -39,8 +39,8 @@
--- `── Info` section renders finding-level info between `── Warnings` and the per-atom cycle counts. --- `── Info` section renders finding-level info between `── Warnings` and the per-atom cycle counts.
--- ---
--- The structural handshake checks (`mac_yield_uniformity`, `hazard_nop_use`, `control_transfer_delay_slot_use`) skip atoms/components with `debug_skip == true`. --- The structural handshake checks (`mac_yield_uniformity`, `hazard_nop_use`, `control_transfer_delay_slot_use`) skip atoms/components with `debug_skip == true`.
--- The `atom_dbg_skip` marker designates runtime-helper declarations whose structure is fixed by the tape runtime (e.g. `tape_exit`, `ac_yield`). --- `atom_dbg_skip` marker designates runtime-helper declarations whose structure is fixed by the tape runtime (e.g. `tape_exit`, `ac_yield`).
--- Flagging them as "missing mac_yield" or "BD slot is redundant" is signal noise, not a logic failure. --- Flagging them as "missing mac_yield" or "BD slot is redundant".
--- Other checks (transfer_hazards, gpu_portstore_shape, abi_handoff, enum_alias_membership, …) still apply to debug_skip declarations because real hazards / typos can still surface in them. --- Other checks (transfer_hazards, gpu_portstore_shape, abi_handoff, enum_alias_membership, …) still apply to debug_skip declarations because real hazards / typos can still surface in them.
--- ---
--- The orchestrator (`ps1_meta.lua`) wires this module in via the PASSES table: --- The orchestrator (`ps1_meta.lua`) wires this module in via the PASSES table:
@@ -452,7 +452,7 @@ local function is_cop2_consumer_of(consumer_event, destination, producer_rel)
end end
-- True iff `consumer_event` reads the GPR operand at any position the destination register occupies. -- True iff `consumer_event` reads the GPR operand at any position the destination register occupies.
-- The read-position lookup consults `duffle.OPERAND_READ_POSITIONS` for the consumer's encoder and walks each `args[pos]` to find an operand-equal match. -- read_pos lookup consults `duffle.OPERAND_READ_POSITIONS` for the consumer's encoder and walks each `args[pos]` to find an operand-equal match.
local function is_gpr_consumer_of(consumer_event, destination) local function is_gpr_consumer_of(consumer_event, destination)
local consumer_token = consumer_event.encoder or consumer_event.ident local consumer_token = consumer_event.encoder or consumer_event.ident
local read_pos = duffle.OPERAND_READ_POSITIONS or {} local read_pos = duffle.OPERAND_READ_POSITIONS or {}