Skip to main content

logicaffeine_forge/
regalloc.rs

1//! Contiguous register-allocated region codegen for EXODIA, the copy-and-patch JIT.
2//!
3//! Where [`crate::jit::compile_straightline_coded`] lowers ONE stencil PIECE
4//! per [`MicroOp`] (each piece re-establishing operands from the frame, doing
5//! its op, storing the result, and tail-calling the next), this backend emits
6//! the WHOLE supported region as ONE contiguous x86-64 function. A global
7//! register assignment keeps the hottest slots resident in physical registers
8//! across every op, so a reg-resident operand is read with a register move (or
9//! used directly) rather than a frame round-trip — eliminating the per-piece
10//! ABI/operand overhead that holds the tiered cluster at 3-6× V8.
11//!
12//! ## Soundness contract (the differential gate is sacred)
13//!
14//! The emitted function is BIT-IDENTICAL to [`crate::jit::reference_eval`] and
15//! thus to the tree-walker:
16//! - i64 wrapping arithmetic (x86 `add`/`sub`/`imul` wrap natively);
17//! - the kernel's exact shift spec (count truncates to the low 6 bits via `cl`);
18//! - `Div`/`Mod` side-EXIT on a zero divisor BEFORE any effect (a
19//!   `ChainOutcome::Deopt` through the shared status cell, replayed on
20//!   bytecode where the kernel raises the precise error), and reproduce
21//!   `MIN / -1 = MIN` / `MIN % -1 = 0` without the `#DE` overflow trap.
22//!
23//! On exit (every `Return`) ALL reg-resident slots are flushed back to the
24//! frame, so the frame the caller observes is consistent with the tree-walker's
25//! full frame state — the region tier can resume / deopt from frame slots.
26//!
27//! ## Assignment model
28//!
29//! A slot is either RESIDENT (lives in one fixed physical register for the
30//! whole function) or SPILLED (lives in its frame slot). Slots are ranked by
31//! reference count; the top ones that fit get the allocatable callee/caller
32//! saved GPRs. This is a *global* per-slot assignment (no per-point churn), so
33//! it is trivially correct across loops and back-edges: a slot is always in the
34//! same place. `rax`/`rdx`/`rcx` are reserved scratch (arithmetic, division,
35//! shift count); `r15` holds the frame base pointer.
36
37#![cfg(target_arch = "x86_64")]
38
39use std::sync::atomic::AtomicI64;
40
41use crate::buffer::JitChain;
42use crate::jit::{Cmp, CompiledChain, MicroOp, Slot};
43use crate::x64asm::{Asm, Cond, LabelId, Reg, Xmm};
44
45/// Where a slot's value lives for the whole function.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47enum Loc {
48    /// Resident in a physical general-purpose register (an INT-class slot).
49    Reg(Reg),
50    /// Resident in a physical XMM register (a FLOAT-class slot). The slot's f64
51    /// value lives here for the whole function; never simultaneously GP-resident.
52    Xmm(Xmm),
53    /// Spilled to `frame[slot]` (byte displacement = `slot * 8`). Both classes
54    /// load/store the SAME 8 raw bytes here, so a slot used by both an int and a
55    /// float op (or whose class is ambiguous) is kept in the frame, where bits
56    /// are reinterpreted freely.
57    Frame,
58}
59
60/// The frame base register (`*mut i64`, the chain ABI's first argument).
61const BASE: Reg = Reg::R15;
62/// Primary arithmetic scratch / division quotient / return value.
63const S0: Reg = Reg::Rax;
64/// Secondary arithmetic scratch / division remainder.
65const S1: Reg = Reg::Rdx;
66/// Shift-count scratch (the only register `shl`/`sar` by `cl` can use).
67const SC: Reg = Reg::Rcx;
68
69/// Primary XMM scratch (float arithmetic accumulator / load target).
70const FS0: Xmm = Xmm::Xmm14;
71/// Secondary XMM scratch (float second operand / abs-mask staging).
72const FS1: Xmm = Xmm::Xmm15;
73
74/// The BYTE offset of the `capacity` and `len` fields WITHIN a `Vec<T>`,
75/// discovered by PROBING the running binary's actual `Vec` layout — NEVER a
76/// hardcoded assumption.
77///
78/// `Vec<T>`'s field order (`ptr`/`cap`/`len`) is an implementation detail the
79/// Rust language does NOT guarantee (it differs across `std` builds — on the
80/// current toolchain the order is `cap, ptr, len`). The inline [`ArrPush`] fast
81/// path needs `cap` (the realloc test) and must keep the real `Vec::len` field
82/// coherent (so a later helper push / drop / deopt sees the appended element), so
83/// it reads/writes those two fields at these offsets. Probing the LIVE layout —
84/// constructing a real `Vec` and matching each word against the known
85/// `capacity()`/`len()` — makes the inline path bit-identical to `Vec::push` on
86/// EXACTLY this binary, with no cross-version layout assumption. The probe is
87/// computed once. The `ptr` field is never read inline (the mirrored frame
88/// `ptr_slot` is the source of truth and never moves on the fast path), so only
89/// these two offsets are needed.
90///
91/// The offsets are T-INDEPENDENT: `Vec<T>` is `RawVec<T> { ptr: NonNull<T>, cap }`
92/// + `len`, all word-sized regardless of `T`, so one `Vec<i64>` probe serves the
93/// Int / Float / Bool element buffers alike.
94struct VecLayout {
95    cap_off: i32,
96    len_off: i32,
97}
98
99fn vec_layout() -> &'static VecLayout {
100    use std::sync::OnceLock;
101    static LAYOUT: OnceLock<VecLayout> = OnceLock::new();
102    LAYOUT.get_or_init(|| {
103        // Distinct, recognizable cap and len so each maps to exactly one word.
104        let mut v: Vec<i64> = Vec::with_capacity(8);
105        // SAFETY: capacity is 8 ≥ 3, so setting len to 3 is in-bounds; the
106        // backing memory is uninitialized but never read (we forget `v`).
107        unsafe { v.set_len(3) };
108        let cap = v.capacity(); // 8
109        let len = v.len(); // 3
110        debug_assert_eq!(
111            std::mem::size_of::<Vec<i64>>(),
112            24,
113            "Vec is a 3-word triple"
114        );
115        let base = &v as *const Vec<i64> as *const usize;
116        // SAFETY: a `Vec<i64>` is exactly three `usize`-sized words.
117        let words = unsafe { std::slice::from_raw_parts(base, 3) };
118        let cap_off = words
119            .iter()
120            .position(|&w| w == cap)
121            .expect("Vec capacity field located") as i32
122            * 8;
123        let len_off = words
124            .iter()
125            .position(|&w| w == len)
126            .expect("Vec len field located") as i32
127            * 8;
128        // Restore len so the (forgotten) Vec drops its real (empty) contents
129        // without touching the uninitialized tail.
130        unsafe { v.set_len(0) };
131        VecLayout { cap_off, len_off }
132    })
133}
134
135/// XMM registers we may assign to FLOAT-class slots. All are caller-saved under
136/// SysV (no prologue save/restore); `xmm14`/`xmm15` are reserved as scratch
137/// (`FS0`/`FS1`). Ordered low→high so the assignment is deterministic.
138const FLOAT_REGS: [Xmm; 14] = [
139    Xmm::Xmm0,
140    Xmm::Xmm1,
141    Xmm::Xmm2,
142    Xmm::Xmm3,
143    Xmm::Xmm4,
144    Xmm::Xmm5,
145    Xmm::Xmm6,
146    Xmm::Xmm7,
147    Xmm::Xmm8,
148    Xmm::Xmm9,
149    Xmm::Xmm10,
150    Xmm::Xmm11,
151    Xmm::Xmm12,
152    Xmm::Xmm13,
153];
154
155/// Callee-saved registers we may assign (must be saved/restored).
156const CALLEE_SAVED: [Reg; 4] = [Reg::Rbx, Reg::R12, Reg::R13, Reg::R14];
157/// Caller-saved registers we may assign freely (no save/restore needed).
158/// `rdi`/`rsi` are the incoming `base`/`sp` args — `base` is copied to r15 in
159/// the prologue and `sp` is unused by the int subset, so both are free after
160/// entry.
161const CALLER_SAVED: [Reg; 6] = [Reg::R8, Reg::R9, Reg::R10, Reg::R11, Reg::Rdi, Reg::Rsi];
162
163/// Whether the contiguous register-allocating backend is selected. Default ON:
164/// it is bit-identical to the stencil tier (proven by the full corpus
165/// differential with the flag on) and 4-6x faster on the regions it supports,
166/// falling back to the per-piece tier on any unsupported op. `LOGOS_REGALLOC=0`
167/// is the kill-switch. Read once.
168pub fn regalloc_enabled() -> bool {
169    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
170    *ON.get_or_init(|| std::env::var("LOGOS_REGALLOC").map_or(true, |v| v != "0"))
171}
172
173/// `LOGOS_SIMD=1` opts a recognized PURE ELEMENT-WISE MAP region (Oracle-proven
174/// in-bounds, unit-stride, no loop-carried scalar — see
175/// [`crate::vectorize::recognize_elementwise_map`]) into a 2-wide packed-double
176/// loop. DEFAULT OFF: the bit-identical differential gate must certify it before
177/// promotion, and no current benchmark exercises a float map. Read once.
178pub fn simd_enabled() -> bool {
179    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
180    *ON.get_or_init(|| std::env::var("LOGOS_SIMD").is_ok_and(|v| v == "1"))
181}
182
183/// Whether the CALL-LOCALITY ranking bonus is applied (Fix 1). Default ON: it is
184/// a pure register-assignment reorder (bit-identical, proven by the corpus
185/// differential) that lands call-surviving values in callee-saved registers so a
186/// call-heavy loop pays no per-call spill/reload. `LOGOS_CALL_WEIGHT=0` is the
187/// kill-switch (also used to A/B the lever's effect on a quiet box). Read once.
188fn call_weight_enabled() -> bool {
189    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
190    *ON.get_or_init(|| std::env::var("LOGOS_CALL_WEIGHT").map_or(true, |v| v != "0"))
191}
192
193/// Whether the INLINE `ArrPush` fast path is emitted (Wave 25). Default ON: it is
194/// bit-identical to the helper-call lowering (proven by the corpus differential
195/// and the dedicated `inline_push_*` tests), eliminating the per-push spill+call
196/// in the common (`len < cap`) case. `LOGOS_NO_INLINE_PUSH=1` falls back to the
197/// always-call lowering — the kill-switch AND the A/B toggle for the relative
198/// on/off timing on a noisy box. Read once.
199fn inline_push_enabled() -> bool {
200    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
201    *ON.get_or_init(|| std::env::var("LOGOS_NO_INLINE_PUSH").map_or(true, |v| v == "0"))
202}
203
204/// Whether the SCALED-INDEX CSE is emitted (Wave 26). A straight-line run of
205/// array accesses sharing one index slot recomputes the 0-based index `im1 =
206/// idx - 1` (and its scaled byte offset `im1 * 8`) once into reserved
207/// caller-saved register(s), then reuses it for each `base + off` address — the
208/// LLVM/V8 "compute the scaled offset once, reuse across base pointers" idiom.
209/// nbody's inner force loop reads/writes 7 co-indexed arrays at the same `i`
210/// (and another set at `j`); matrix_mult / spectral_norm / prefix_sum likewise
211/// touch several arrays at a shared index. Default ON: it is bit-identical to
212/// the per-access recompute (the cache is recomputed whenever the index slot is
213/// reassigned, at every jump target, and across any SysV call), proven by the
214/// corpus differential and the dedicated `off_cse_*` tests. `LOGOS_NO_OFF_CSE=1`
215/// falls back to the per-access recompute — the kill-switch AND the A/B toggle
216/// for the relative on/off timing on a noisy box. Read once.
217fn off_cse_enabled() -> bool {
218    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
219    *ON.get_or_init(|| std::env::var("LOGOS_NO_OFF_CSE").map_or(true, |v| v != "1"))
220}
221
222/// Whether the LOOP-INVARIANT ARRAY PTR/LEN HOIST is emitted (Wave 27a). When an
223/// array's ptr/len handle slots are FRAME-resident and are never written inside a
224/// loop (only in-place `ArrLoad`/`ArrStore` of that array — no reallocating
225/// `ArrPush`/`ListClear`/`NewList`/`ListTriple`, no scalar write to the slot),
226/// the per-access `emit_arr_addr` reload of those slots from the frame is
227/// loop-invariant. The hoist loads them ONCE into loop-persistent CALLEE-SAVED
228/// registers at the loop pre-header, so the inner accesses read the register
229/// instead of re-touching the frame every iteration (the knapsack inner `w`-loop
230/// reads `prev`'s ptr/len every iteration though `prev` only changes on the OUTER
231/// loop's `Set prev to curr`). Default ON: bit-identical to the per-access reload
232/// (the hoisted register holds exactly `frame[slot]`, which is invariant over the
233/// span, and the bounds check still runs per access against the hoisted length),
234/// proven by the corpus differential and the dedicated `ptr_hoist_*` tests.
235/// `LOGOS_NO_PTR_HOIST=1` falls back to the per-access reload — the kill-switch
236/// AND the A/B toggle for the relative on/off timing on a noisy box. Read once.
237fn ptr_hoist_enabled() -> bool {
238    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
239    *ON.get_or_init(|| std::env::var("LOGOS_NO_PTR_HOIST").map_or(true, |v| v != "1"))
240}
241
242/// Whether the LOOP-INVARIANT CONSTANT HOIST is emitted (Wave 28). A
243/// `LoadConst { dst, value }` INSIDE a natural loop, whose `dst` is written by no
244/// other op in the span (so the value is invariant across iterations) and lands
245/// in a GP register, has its `mov reg, imm` re-executed every iteration in the
246/// body. The hoist emits it ONCE in the loop pre-header instead, leaving the
247/// register resident across the back-edge — the V8/LLVM loop-invariant-code-
248/// motion idiom (collatz −7%, loop_sum, every pure-GP scalar loop with an
249/// invariant constant).
250///
251/// FLOAT (XMM-resident) consts are EXCLUDED — the investigation began with
252/// mandelbrot's `2.0`/`4.0` GP→XMM reloads, the obvious target, but hoisting them
253/// into the SATURATED XMM file is bit-identical yet measured ~8% SLOWER (the
254/// per-iteration `movabs;movq` is FREE out-of-order work that overlaps the float
255/// chain; pinning the invariant in a read-heavy XMM register serializes worse).
256/// See the `const_hoist_*` tests and the call site's exclusion comment.
257///
258/// Default ON: bit-identical to the per-iteration `LoadConst` on every observed
259/// slot. The register holds exactly the same constant bits, the body simply
260/// stops re-loading them, and a hoist requires `dst` dead at the loop head (see
261/// [`loop_invariant_const_hoists`]), so no read and no caller-read exit flush can
262/// see the pre-header write in place of the entry value. Proven by the corpus
263/// differential and the dedicated `const_hoist_*` tests. `LOGOS_NO_CONST_HOIST=1` falls back to
264/// the per-iteration materialization — the kill-switch AND the A/B toggle for the
265/// relative on/off timing on a noisy box. Read LIVE (not cached) so a single
266/// process can A/B the two emissions for the structural gate.
267fn const_hoist_enabled() -> bool {
268    std::env::var("LOGOS_NO_CONST_HOIST").map_or(true, |v| v != "1")
269}
270
271/// Diagnostic: when `LOGOS_DUMP_CLASS=1`, [`compile_impl`] prints a one-line
272/// slot-class + placement histogram per compiled region that touches any float
273/// (Int/Float/Mixed counts, how many Float slots won an XMM register vs spilled
274/// to the frame under pressure, and the Mixed-slot indices). Pure observability,
275/// no behavior change — it is how the campaign tells a Mixed-frame wall apart
276/// from an XMM-pressure wall before choosing a lever.
277fn dump_class_enabled() -> bool {
278    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
279    *ON.get_or_init(|| std::env::var("LOGOS_DUMP_CLASS").map_or(false, |v| v != "0"))
280}
281
282/// LS1 linear-scan register allocation (reuse a register across disjoint live
283/// ranges, float slots only). MEASURED LOSS — parked default-OFF. It is sound
284/// (forge 93/93 with `=1`, all benchmarks bit-identical) but a net SLOWDOWN on
285/// the float-pressured regions (nbody +74%, mandelbrot +104%): the floats the
286/// rank-based per-slot model leaves in the frame are COLD, so frame residency is
287/// already the cheap, correct choice — forcing them into reused registers adds a
288/// per-iteration spill-at-end store that exceeds their cold frame cost. `maxLive
289/// <= 14` measured liveness, not HOTNESS, so it overstated the win. Do NOT promote;
290/// kept behind the flag with the `LOGOS_DUMP_CLASS` diagnostic as a documented
291/// negative result. The float-cluster lever is op-count (fusion), not allocation.
292fn linear_scan_enabled() -> bool {
293    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
294    *ON.get_or_init(|| std::env::var("LOGOS_LINEAR_SCAN").map_or(false, |v| v == "1"))
295}
296
297/// The maximum LOGOS call depth, baked into the self-call codegen exactly as it
298/// is baked into `logos_stencil_call_self` — the kernel's locked
299/// `MAX_CALL_DEPTH`. Reusing the single forge constant keeps the contiguous
300/// FUNCTION backend's depth guard in lockstep with the stencil tier and the
301/// kernel (a drift would diverge the depth-exceeded error). See the
302/// `max-call-depth-sync-jit-forge` invariant.
303const SELF_CALL_DEPTH_LIMIT: i64 = crate::jit::BAKED_CALL_DEPTH;
304
305/// Is this op in the supported subset of the contiguous backend? An op outside
306/// it makes [`compile_region_regalloc`] return `None`, so the caller falls back
307/// to the per-piece tier and behavior is unchanged.
308fn supported(op: &MicroOp) -> bool {
309    matches!(
310        op,
311        MicroOp::Move { .. }
312            | MicroOp::LoadConst { .. }
313            | MicroOp::Add { .. }
314            | MicroOp::Sub { .. }
315            | MicroOp::Mul { .. }
316            | MicroOp::Lt { .. }
317            | MicroOp::Gt { .. }
318            | MicroOp::LtEq { .. }
319            | MicroOp::GtEq { .. }
320            | MicroOp::Eq { .. }
321            | MicroOp::Neq { .. }
322            | MicroOp::BitAnd { .. }
323            | MicroOp::BitOr { .. }
324            | MicroOp::BitXor { .. }
325            | MicroOp::Shl { .. }
326            | MicroOp::Shr { .. }
327            | MicroOp::Ushr { .. }
328            | MicroOp::Rotate { .. }
329            | MicroOp::NotInt { .. }
330            | MicroOp::NotBool { .. }
331            | MicroOp::Div { .. }
332            | MicroOp::Mod { .. }
333            | MicroOp::DivPow2 { .. }
334            | MicroOp::MagicDivU { .. }
335            | MicroOp::Branch { .. }
336            | MicroOp::Jump { .. }
337            | MicroOp::JumpIfFalse { .. }
338            | MicroOp::JumpIfTrue { .. }
339            | MicroOp::Return { .. }
340            // Integer (8-byte element) array load/store. A FLOAT array element
341            // is also an 8-byte (`byte: false`) slot: the raw bits load into /
342            // store from a frame slot, and the float arithmetic reinterprets
343            // them — no separate "float array" op is needed.
344            | MicroOp::ArrLoad { byte: false, .. }
345            | MicroOp::ArrStore { byte: false, .. }
346            // BYTE (1-byte element) array load/store — the `Seq of Bool` buffer
347            // (sieve's `flags`, graph_bfs would-be `visited`). A `byte: true`
348            // load is a zero-extended `movzx` (`u8 as i64`); a `byte: true`
349            // store writes the BOOLEAN NORMALIZATION `(v != 0) as u8`. The
350            // address machinery and OOB side-exit are the 8-byte path with a
351            // unit stride — bit-identical to `ST_ARRLDB`/`ST_ARRSTB`.
352            | MicroOp::ArrLoad { byte: true, .. }
353            | MicroOp::ArrStore { byte: true, .. }
354            // FLOAT (f64) ops — the XMM register class (wave 11). Arithmetic is
355            // IEEE; `FmaF` is TWO roundings (mulsd then addsd, NOT a fused
356            // `vfmadd`); ordering compares are exact IEEE (NaN → false); `EqF`/
357            // `NeqF` use the kernel's `|a-b| < EPSILON` rule; `DivF` side-exits
358            // on a `0.0` divisor like the integer `Div`.
359            | MicroOp::AddF { .. }
360            | MicroOp::SubF { .. }
361            | MicroOp::MulF { .. }
362            | MicroOp::DivF { .. }
363            | MicroOp::SqrtF { .. }
364            | MicroOp::IntToFloat { .. }
365            | MicroOp::FmaF { .. }
366            | MicroOp::LtF { .. }
367            | MicroOp::GtF { .. }
368            | MicroOp::LtEqF { .. }
369            | MicroOp::GtEqF { .. }
370            | MicroOp::EqF { .. }
371            | MicroOp::NeqF { .. }
372            | MicroOp::BranchF { .. }
373            // LIST MUTATION (wave 13) — helper calls into the JIT runtime.
374            // `ArrPush` appends through `logos_rt_push_*` (the call MAY
375            // reallocate, so the pinned ptr/len are refreshed in the frame
376            // after); `ListClear` truncates a SOLE-OWNED buffer in place
377            // through `logos_rt_clear_*` (the alias-safety of the reuse is
378            // proven UPSTREAM in the micro-op lowering — a `ListClear` reaching
379            // here is unaliased). Both keep their vec/ptr/len handle slots
380            // FRAME-resident (the helper reads/writes those frame cells) and
381            // spill the caller-saved residents across the SysV call.
382            | MicroOp::ArrPush { .. }
383            | MicroOp::ListClear { .. }
384            // MUTABLE-TEXT append (`Set text to text + ch`). A helper call into
385            // the JIT runtime that grows the accumulator THROUGH the pinned
386            // `*mut Value` cell handle with the VM's exact `add_assign`
387            // (in-place / copy-on-write) semantics; the handle slot is forced
388            // frame-resident and the caller-saved residents are spilled across
389            // the SysV call, exactly like `ArrPush`.
390            | MicroOp::StrAppend { .. }
391    )
392}
393
394/// Is this op in the supported subset of the contiguous FUNCTION backend
395/// ([`compile_function_regalloc`])? It is the region subset PLUS the DIRECT
396/// self-call ops (`CallSelf`/`CallSelfCopy`). A cross-function `Call`, list/map
397/// ops, byte arrays, etc. remain unsupported → the function falls back to the
398/// per-piece stencil tier, byte-identical to today.
399fn supported_function(op: &MicroOp) -> bool {
400    supported(op) || matches!(op, MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. })
401}
402
403/// Is this op in the supported subset of the contiguous PRECISE
404/// FUNCTION backend ([`compile_function_regalloc_precise`])? This spans two
405/// recursion shapes:
406///
407///  - the IN-PLACE-ARRAY shape (heap_sort's `siftDown`, quicksort's `qs`):
408///    scalar arithmetic, checked int/byte array load/store (the in-place
409///    mutation), and the precise self-`Call` (windowed disjointly, resuming AT
410///    the faulting op on a side exit); and
411///  - the fresh-list-RETURN shape (mergesort: allocate fresh `left`/`right`/
412///    `result`, push into them, and return a new list): the registry-owned
413///    allocation `NewList`, the reallocating `ArrPush`, the in-place `ListClear`,
414///    and the `ListTriple` pin refresh from a live handle (a self-call's returned
415///    list, seen from the caller).
416///
417/// SOUNDNESS of the list-return shape: the regalloc body shares the SAME
418/// `adapt_function` micro stream, per-op `deopt_codes` table, runtime helpers
419/// (`logos_rt_alloc_list_i64` / push / triple), and `ChainFn::call`+`materialize`
420/// boundary as the per-piece precise stencil tier — only the body codegen
421/// changes. `NewList`/`ArrPush`/`ListTriple` each force their vec/ptr/len triple
422/// FRAME-resident (the helper's frame writes are the single source of truth, so a
423/// reallocating push's refreshed pointer/length is always read by the next
424/// access), every precise-path machinery slot (`>= rc`) stays frame-resident, and every
425/// precise side exit flushes the resident-written scalars to the frame. So a
426/// registry-owned fresh list materializes (detaches) on a precise resume exactly
427/// as in the stencil tier; the differential gate proves it bit-identical.
428///
429/// It still does NOT admit the classic `CallSelf`/`CallSelfCopy` (those replay
430/// from head — sound only for the scalar mode-A path), nor maps/cross-function
431/// calls. Frame-based Host helpers use the same precise exit channel and
432/// preserve their declared operand window across the SysV call.
433fn supported_function_precise(op: &MicroOp) -> bool {
434    supported(op)
435        || matches!(
436            op,
437            MicroOp::Call { .. }
438                | MicroOp::ListTriple { .. }
439                | MicroOp::NewList { .. }
440                | MicroOp::Host { .. }
441        )
442}
443
444/// Whether `op` is a CHECKED operation needing the deopt side-exit channel (the
445/// status cell): a divisor-check on `Div`/`Mod`, or a bounds-check on a checked
446/// integer array load/store. A self-call also writes the status cell (its depth/
447/// arena/entry guards and the propagation of an in-callee deopt), so it too
448/// requires the channel.
449fn needs_deopt(op: &MicroOp) -> bool {
450    matches!(
451        op,
452        MicroOp::Div { .. }
453            | MicroOp::Mod { .. }
454            | MicroOp::DivF { .. }
455            | MicroOp::ArrLoad { checked: true, .. }
456            | MicroOp::ArrStore { checked: true, .. }
457            // Integer add/sub/mul side-exit on signed overflow (`jo`) so the exact
458            // tier recomputes and promotes to BigInt — overflow is no longer a
459            // silent wrap. (A later perf pass elides the guard where the prover
460            // proves no overflow; for now every integer arith op is checked.)
461            | MicroOp::Add { .. }
462            | MicroOp::Sub { .. }
463            | MicroOp::Mul { .. }
464            | MicroOp::CallSelf { .. }
465            | MicroOp::CallSelfCopy { .. }
466            // The mode-B precise self-call writes the status cell (its depth/
467            // arena/entry guards and the propagation of an in-callee deopt).
468            | MicroOp::Call { .. }
469            // `chr` guard side-exits when the code is not a valid Unicode scalar
470            // (so the VM re-runs `chr` and traps, matching the tree-walker).
471            | MicroOp::ChrGuard { .. }
472            | MicroOp::Host { .. }
473    )
474}
475
476/// Every slot index an op reads or writes (for reference-count ranking and the
477/// max-slot frame bound).
478fn slots_of(op: &MicroOp, out: &mut Vec<Slot>) {
479    match *op {
480        MicroOp::Move { dst, src }
481        | MicroOp::NotInt { dst, src }
482        | MicroOp::NotBool { dst, src }
483        | MicroOp::Popcnt { dst, src }
484        | MicroOp::Lzcnt { dst, src }
485        | MicroOp::Tzcnt { dst, src }
486        | MicroOp::Utf8Len { dst, src }
487        | MicroOp::ChrGuard { dst, src } => out.extend([dst, src]),
488        MicroOp::LoadConst { dst, .. } => out.push(dst),
489        MicroOp::Add { dst, lhs, rhs }
490        | MicroOp::Sub { dst, lhs, rhs }
491        | MicroOp::Mul { dst, lhs, rhs }
492        | MicroOp::Lt { dst, lhs, rhs }
493        | MicroOp::Gt { dst, lhs, rhs }
494        | MicroOp::LtEq { dst, lhs, rhs }
495        | MicroOp::GtEq { dst, lhs, rhs }
496        | MicroOp::Eq { dst, lhs, rhs }
497        | MicroOp::Neq { dst, lhs, rhs }
498        | MicroOp::BitAnd { dst, lhs, rhs }
499        | MicroOp::BitOr { dst, lhs, rhs }
500        | MicroOp::BitXor { dst, lhs, rhs }
501        | MicroOp::Shl { dst, lhs, rhs }
502        | MicroOp::Shr { dst, lhs, rhs }
503        | MicroOp::Ushr { dst, lhs, rhs }
504        | MicroOp::Rotate { dst, lhs, rhs, .. }
505        | MicroOp::Div { dst, lhs, rhs }
506        | MicroOp::Mod { dst, lhs, rhs }
507        | MicroOp::AddF { dst, lhs, rhs }
508        | MicroOp::SubF { dst, lhs, rhs }
509        | MicroOp::MulF { dst, lhs, rhs }
510        | MicroOp::DivF { dst, lhs, rhs }
511        | MicroOp::LtF { dst, lhs, rhs }
512        | MicroOp::GtF { dst, lhs, rhs }
513        | MicroOp::LtEqF { dst, lhs, rhs }
514        | MicroOp::GtEqF { dst, lhs, rhs }
515        | MicroOp::EqF { dst, lhs, rhs }
516        | MicroOp::NeqF { dst, lhs, rhs } => out.extend([dst, lhs, rhs]),
517        MicroOp::FmaF { dst, a, b, c } => out.extend([dst, a, b, c]),
518        MicroOp::IntToFloat { dst, src }
519        | MicroOp::SqrtF { dst, src }
520        | MicroOp::FloorToInt { dst, src }
521        | MicroOp::CeilToInt { dst, src }
522        | MicroOp::RoundToInt { dst, src } => out.extend([dst, src]),
523        MicroOp::DivPow2 { dst, lhs, .. } => out.extend([dst, lhs]),
524        MicroOp::MagicDivU { dst, lhs, .. } => out.extend([dst, lhs]),
525        MicroOp::Branch { lhs, rhs, .. } | MicroOp::BranchF { lhs, rhs, .. } => {
526            out.extend([lhs, rhs])
527        }
528        MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => out.push(cond),
529        MicroOp::Return { src } => out.push(src),
530        MicroOp::Host {
531            dst, src, count, ..
532        } => {
533            out.push(dst);
534            out.extend(src..src + count);
535        }
536        MicroOp::ArrLoad {
537            dst,
538            idx,
539            ptr_slot,
540            len_slot,
541            checked,
542            ..
543        } => {
544            out.extend([dst, idx, ptr_slot]);
545            if checked {
546                out.push(len_slot);
547            }
548        }
549        MicroOp::ArrStore {
550            src,
551            idx,
552            ptr_slot,
553            len_slot,
554            checked,
555            ..
556        } => {
557            out.extend([src, idx, ptr_slot]);
558            if checked {
559                out.push(len_slot);
560            }
561        }
562        // A push reads its `src` value (rank it — it may be register/XMM
563        // resident) and the vec/ptr/len handle TRIPLE, which is forced
564        // frame-resident below (the helper reads/writes those frame cells), so
565        // we list the triple only to extend `max_slot`, never to rank it.
566        MicroOp::ArrPush {
567            src,
568            vec_slot,
569            ptr_slot,
570            len_slot,
571            ..
572        } => out.extend([src, vec_slot, ptr_slot, len_slot]),
573        MicroOp::ListClear {
574            vec_slot,
575            ptr_slot,
576            len_slot,
577            ..
578        } => out.extend([vec_slot, ptr_slot, len_slot]),
579        // A fresh-list allocation writes the vec/ptr/len handle TRIPLE (forced
580        // frame-resident below — the helper writes those frame cells); list it
581        // only to extend `max_slot`, never to rank it (the triple stays in the
582        // frame, so it competes for no register).
583        MicroOp::NewList {
584            vec_slot,
585            ptr_slot,
586            len_slot,
587            ..
588        } => out.extend([vec_slot, ptr_slot, len_slot]),
589        // A str-append reads its handle slot (forced frame-resident below — the
590        // helper indexes it) and, for the byte and Int forms, the value slot (ranked:
591        // it may be register-resident). The const form has no extra slot.
592        MicroOp::StrAppend {
593            text_handle_slot,
594            src,
595            ..
596        } => {
597            out.push(text_handle_slot);
598            if let Some(s) = src.slot() {
599                out.push(s);
600            }
601        }
602        // The mode-B precise self-call writes `dst` and reads `limit_slot` (the
603        // arena bound). The callee window (args_start..) is forced frame-
604        // resident below; the staging Moves into it account those slots already,
605        // and `extend_self_call_slots` is not used (the disjoint window's extent
606        // is covered by the Move ops the adapter emits into it).
607        MicroOp::Call {
608            dst, limit_slot, ..
609        } => out.extend([dst, limit_slot]),
610        // A triple-plant reads `handle_slot` and writes the vec/ptr/len triple
611        // (all forced frame-resident); `handle_slot` is ranked so a register-
612        // resident handle is still read correctly (the codegen spills it to its
613        // forced frame cell so the helper sees it).
614        MicroOp::ListTriple {
615            handle_slot,
616            vec_slot,
617            ptr_slot,
618            len_slot,
619            ..
620        } => out.extend([handle_slot, vec_slot, ptr_slot, len_slot]),
621        // A self-call writes `dst` and reads `limit_slot` (the arena bound). The
622        // callee window (args_start..) and a `CallSelfCopy`'s source block
623        // (src_start..) are accounted by `extend_self_call_slots` so `max_slot`
624        // covers them; the staging slots stay FRAME-resident (the callee reads
625        // them from the frame) and so are NOT ranked for a register here.
626        MicroOp::CallSelf {
627            dst, limit_slot, ..
628        } => out.extend([dst, limit_slot]),
629        MicroOp::CallSelfCopy {
630            dst,
631            src_start,
632            arg_count,
633            limit_slot,
634            ..
635        } => {
636            out.extend([dst, limit_slot]);
637            // The source args are READ; rank them (they may be register-resident
638            // — the codegen reads them from wherever they live, then stages).
639            for j in 0..arg_count {
640                out.push(src_start + j);
641            }
642        }
643        MicroOp::Jump { .. } => {}
644        _ => {}
645    }
646}
647
648/// The control-flow TARGET of a transfer op (`Jump`/`JumpIf*`/`Branch*`), if
649/// any. A target whose index is `<` the op's own index is a loop BACK-EDGE.
650fn op_target(op: &MicroOp) -> Option<usize> {
651    match *op {
652        MicroOp::Jump { target }
653        | MicroOp::JumpIfFalse { target, .. }
654        | MicroOp::JumpIfTrue { target, .. }
655        | MicroOp::Branch { target, .. }
656        | MicroOp::BranchF { target, .. } => Some(target),
657        _ => None,
658    }
659}
660
661/// The LOOP NESTING DEPTH of every op in the region. A loop is the span
662/// `[target, idx]` of a BACK-EDGE — a transfer op at `idx` whose `target <= idx`
663/// (so its body runs repeatedly). The depth of op `j` is the number of such
664/// spans that contain `j`; ops inside a doubly-nested loop have depth 2, etc.
665/// This is a structural over-approximation (it counts every back-edge span, not
666/// just reducible natural loops), which is exactly what the spill heuristic
667/// wants: a value referenced under a back-edge is hot and should win a register.
668fn loop_depths(ops: &[MicroOp]) -> Vec<u32> {
669    let n = ops.len();
670    let mut depth = vec![0u32; n];
671    for (idx, op) in ops.iter().enumerate() {
672        if let Some(target) = op_target(op) {
673            if target <= idx {
674                for d in depth.iter_mut().take(idx + 1).skip(target) {
675                    *d += 1;
676                }
677            }
678        }
679    }
680    depth
681}
682
683/// Does the region contain a SCALED-INDEX CSE opportunity — two or more array
684/// accesses (`ArrLoad`/`ArrStore`) sharing one index slot AND element stride
685/// across a straight-line run, with NO intervening invalidation? This is the
686/// gate for reserving a cache register: without a reusable run the CSE never
687/// fires, so the reservation (which spills the coldest int scalar to the frame)
688/// would be a pure cost. The invalidation here MIRRORS the runtime exactly —
689/// the cache is dropped at a jump TARGET (control join), when the cached index
690/// slot is reassigned, and across a SysV call — so this returns `true` iff at
691/// least one access would HIT the cache the codegen builds.
692fn has_shared_index_run(ops: &[MicroOp]) -> bool {
693    // Precompute jump-target indices (control joins drop the cache).
694    let mut is_target = vec![false; ops.len()];
695    for op in ops {
696        if let Some(t) = op_target(op) {
697            if let Some(slot) = is_target.get_mut(t) {
698                *slot = true;
699            }
700        }
701    }
702    let mut cache: Option<(Slot, bool)> = None; // (idx, byte)
703    for (i, op) in ops.iter().enumerate() {
704        if is_target[i] {
705            cache = None;
706        }
707        match *op {
708            MicroOp::ArrLoad { idx, byte, .. } | MicroOp::ArrStore { idx, byte, .. } => {
709                if cache == Some((idx, byte)) {
710                    return true; // a reuse hit — the run pays off.
711                }
712                cache = Some((idx, byte));
713            }
714            _ => {}
715        }
716        // Post-op invalidation, mirroring the codegen: a SysV call clobbers the
717        // reserved caller-saved register; a write to the cached index slot makes
718        // the held `im1` stale.
719        if is_sysv_call(op) {
720            cache = None;
721        } else if let Some((idx, _)) = cache {
722            if dest_of(op) == Some(idx) {
723                cache = None;
724            }
725        }
726    }
727    false
728}
729
730/// Whether `op` is a REAL SysV `call` (it clobbers the caller-saved registers per
731/// the ABI). This is the universe of ops the call-weight ranking and the
732/// per-call-site spill machinery key off: the self-call families (`CallSelf`,
733/// `CallSelfCopy`, the precise `Call`) and the list/string-mutation
734/// helpers (`NewList`, `ArrPush`, `ListClear`, `ListTriple`, `StrAppend`), each
735/// of which enters JIT-runtime code through a SysV `call`. Mirrors the
736/// `has_self_call || has_list_call || has_precise_call` disjunction that defines
737/// `has_call`.
738fn is_sysv_call(op: &MicroOp) -> bool {
739    matches!(
740        op,
741        MicroOp::CallSelf { .. }
742            | MicroOp::CallSelfCopy { .. }
743            | MicroOp::Call { .. }
744            | MicroOp::NewList { .. }
745            | MicroOp::ArrPush { .. }
746            | MicroOp::ListClear { .. }
747            | MicroOp::ListTriple { .. }
748            | MicroOp::StrAppend { .. }
749            | MicroOp::Host { .. }
750    )
751}
752
753/// A loop-invariant array ptr/len hoist (Wave 27a): one array, invariant over one
754/// loop span, whose handle slots are loaded ONCE at the loop pre-header into
755/// persistent callee-saved registers and reused for every in-span access.
756#[derive(Clone, Copy)]
757struct HoistPlan {
758    /// The loop head op index (the back-edge target). The hoist loads fire at this
759    /// op's PRE-HEADER (just before binding the head's label), reached only by the
760    /// entry fall-through — the back-edge jumps to the bound label and skips them.
761    head: usize,
762    /// The last op index INSIDE the loop (the back-edge op). The hoist registers
763    /// are live (used by `emit_arr_addr`) for ops in `head..=back`; outside this
764    /// span the array falls back to the per-access frame reload.
765    back: usize,
766    /// The frame-resident ptr slot loaded once and reused for every in-span access.
767    ptr_slot: Slot,
768    /// The len slot, loaded once and reused for every CHECKED in-span access; only
769    /// loaded when `needs_len` (some in-span access of this array is checked).
770    len_slot: Slot,
771    /// Whether any in-span access of this array is CHECKED (so `len` must hoist).
772    needs_len: bool,
773    /// How many `ArrLoad`/`ArrStore` of this array occur in the span — the reuse
774    /// count the hoist amortizes (one pre-header load serves all of them).
775    accesses: u32,
776}
777
778/// Whether op `op` WRITES the frame cell of slot `s` — either it is the op's
779/// destination (a scalar def, an `ArrLoad` dst, a self-call result), OR a
780/// list-mutation helper REFRESHES it through the frame (`ArrPush`/`NewList`/
781/// `ListClear`/`ListTriple` write `frame[vec/ptr/len]` after a possible realloc).
782/// An array whose ptr/len slot is written this way INSIDE a loop is NOT invariant
783/// there and must not be hoisted (its hoisted register would go stale).
784fn op_writes_slot(op: &MicroOp, s: Slot) -> bool {
785    if dest_of(op) == Some(s) {
786        return true;
787    }
788    match *op {
789        MicroOp::NewList {
790            vec_slot,
791            ptr_slot,
792            len_slot,
793            ..
794        }
795        | MicroOp::ArrPush {
796            vec_slot,
797            ptr_slot,
798            len_slot,
799            ..
800        }
801        | MicroOp::ListClear {
802            vec_slot,
803            ptr_slot,
804            len_slot,
805            ..
806        } => s == vec_slot || s == ptr_slot || s == len_slot,
807        MicroOp::ListTriple {
808            handle_slot,
809            vec_slot,
810            ptr_slot,
811            len_slot,
812            ..
813        } => s == handle_slot || s == vec_slot || s == ptr_slot || s == len_slot,
814        _ => false,
815    }
816}
817
818/// Identify every loop-invariant array ptr/len hoist available in `ops`. A
819/// candidate is one (`ptr_slot`, `len_slot`) pair that:
820///
821///  1. is accessed by an `ArrLoad`/`ArrStore` INSIDE a natural loop span
822///     `[head, back]` (a back-edge whose `target == head <= back`);
823///  2. has NEITHER slot written anywhere inside `[head, back]` (no scalar def, no
824///     reallocating push/clear/triple of that array) — so `frame[ptr]`/`frame[len]`
825///     are constant across the whole span;
826///  3. enters the loop ONLY via the pre-header fall-through — every transfer that
827///     targets `head` originates INSIDE `[head, back]` (a back-edge). A forward
828///     jump into `head` from outside would skip the pre-header load and read a
829///     stale register, so such a loop is rejected (no hoist).
830///
831/// Frame-residency is NOT decided here (the analysis is purely structural over the
832/// op stream); the caller filters to slots that are actually `Loc::Frame` before
833/// reserving a register (a slot the linear scan already keeps in a register has
834/// no per-access reload to hoist).
835///
836/// For nested loops the INNERMOST span containing an access is preferred: its
837/// pre-header runs once per outer iteration (the highest reuse), and a slot
838/// invariant in the inner loop may be written between inner loops at the outer
839/// level (knapsack's `Set prev to curr`), so the outer span would not be
840/// invariant. We therefore emit one plan per (innermost-loop, array) pair.
841fn loop_invariant_array_hoists(ops: &[MicroOp]) -> Vec<HoistPlan> {
842    // Every natural-loop span: a back-edge at `back` with `target == head <= back`.
843    let mut loops: Vec<(usize, usize)> = Vec::new();
844    for (back, op) in ops.iter().enumerate() {
845        if let Some(head) = op_target(op) {
846            if head <= back {
847                loops.push((head, back));
848            }
849        }
850    }
851    let mut plans: Vec<HoistPlan> = Vec::new();
852    for &(head, back) in &loops {
853        // Entry-discipline guard: every transfer targeting `head` must originate
854        // inside `[head, back]` (a back-edge). A forward jump into `head` from
855        // outside the span would skip the pre-header load → reject this loop.
856        let entry_ok = ops.iter().enumerate().all(|(i, op)| match op_target(op) {
857            Some(t) if t == head => (head..=back).contains(&i),
858            _ => true,
859        });
860        if !entry_ok {
861            continue;
862        }
863        // The array (ptr, len) pairs accessed inside the span, and whether any
864        // access of each is checked. A pair is keyed by ptr_slot (the address
865        // base); the len_slot rides along (a checked access of a given array
866        // always names the same len_slot — the lowering pins one handle triple
867        // per array).
868        let mut accessed: std::collections::BTreeMap<Slot, (Slot, bool, u32)> =
869            std::collections::BTreeMap::new();
870        for op in &ops[head..=back] {
871            match *op {
872                MicroOp::ArrLoad {
873                    ptr_slot,
874                    len_slot,
875                    checked,
876                    ..
877                }
878                | MicroOp::ArrStore {
879                    ptr_slot,
880                    len_slot,
881                    checked,
882                    ..
883                } => {
884                    let e = accessed.entry(ptr_slot).or_insert((len_slot, false, 0));
885                    e.1 |= checked;
886                    e.2 += 1;
887                }
888                _ => {}
889            }
890        }
891        for (ptr_slot, (len_slot, any_checked, accesses)) in accessed {
892            // Invariance: neither handle slot is written anywhere in the span.
893            let invariant = !ops[head..=back]
894                .iter()
895                .any(|op| op_writes_slot(op, ptr_slot) || op_writes_slot(op, len_slot));
896            if invariant {
897                plans.push(HoistPlan {
898                    head,
899                    back,
900                    ptr_slot,
901                    len_slot,
902                    needs_len: any_checked,
903                    accesses,
904                });
905            }
906        }
907    }
908    // For an array accessed in several NESTED spans, keep only the innermost (the
909    // smallest span) so the pre-header sits at the tightest loop (highest reuse)
910    // and no two plans claim the same array with overlapping spans. Two disjoint
911    // loops touching the same array each keep their own plan.
912    plans.sort_by_key(|p| (p.ptr_slot, p.back - p.head));
913    let mut chosen: Vec<HoistPlan> = Vec::new();
914    for p in plans {
915        let overlaps_kept = chosen
916            .iter()
917            .any(|c| c.ptr_slot == p.ptr_slot && c.head <= p.back && p.head <= c.back);
918        if !overlaps_kept {
919            chosen.push(p);
920        }
921    }
922    chosen
923}
924
925/// A loop-invariant constant hoist (Wave 28): one `LoadConst` op inside a loop
926/// whose `dst` is invariant across the span, materialized ONCE at the loop
927/// pre-header instead of every iteration.
928#[derive(Clone, Copy)]
929struct ConstHoist {
930    /// The op index of the `LoadConst` being hoisted. The emit loop SKIPS this op
931    /// inside the span (the pre-header already loaded its register).
932    op: usize,
933    /// The loop head op index (the back-edge target). The hoist materialization
934    /// fires at this op's PRE-HEADER, reached only by the entry fall-through.
935    head: usize,
936    /// The destination slot the constant lands in (register-resident).
937    dst: Slot,
938    /// The raw 64-bit constant value (`MicroOp::LoadConst::value`).
939    value: i64,
940}
941
942/// Identify every loop-invariant `LoadConst` hoist available in `ops`. A
943/// `LoadConst { dst, value }` at op index `i` is a candidate when:
944///
945///  1. it sits INSIDE a natural loop span `[head, back]` (a back-edge whose
946///     `target == head <= back`) — the INNERMOST such span containing `i` (the
947///     tightest pre-header, the highest reuse: mandelbrot's `2.0`/`4.0` sit in
948///     the 50-iteration inner loop);
949///  2. the loop is entered ONLY via the pre-header fall-through (every transfer
950///     targeting `head` originates inside `[head, back]`) — otherwise a forward
951///     jump into `head` would skip the pre-header materialization and read a
952///     stale register;
953///  3. `dst` is written by NO OTHER op anywhere in `[head, back]` (the ONLY
954///     writer in the span is this `LoadConst`) — so the register holds the same
955///     constant bits on every iteration. A slot reused for two different
956///     constants (a scratch `LoadConst {dst,0}` then `LoadConst {dst,1}`) has two
957///     writers and is therefore NOT hoisted;
958///  4. `dst` is DEAD at `head` under [`liveness`] with the region's `live_out`
959///     read at every exit — the value it enters the loop with is never observed.
960///     The pre-header write replaces that value on every path, including the
961///     ones that never reach this `LoadConst`: a read before the write in the
962///     body, an exit taken before the first write (a zero-trip loop), or an exit
963///     block that sits inside the span but never returns to the back-edge (a
964///     found-flag set on the way out). Each of those observes the entry value,
965///     so each makes `dst` live at `head`.
966///
967/// Register-residency is NOT decided here (the analysis is purely structural over
968/// the op stream); the caller filters to `dst`s that are actually `Loc::Reg`/
969/// `Loc::Xmm` before materializing (a frame-resident const has no per-iteration
970/// register reload to amortize).
971fn loop_invariant_const_hoists(ops: &[MicroOp], live_out: &[Slot]) -> Vec<ConstHoist> {
972    // Every natural-loop span: a back-edge at `back` with `target == head <= back`.
973    let mut loops: Vec<(usize, usize)> = Vec::new();
974    for (back, op) in ops.iter().enumerate() {
975        if let Some(head) = op_target(op) {
976            if head <= back {
977                loops.push((head, back));
978            }
979        }
980    }
981    if !ops.iter().any(|op| matches!(op, MicroOp::LoadConst { .. })) || loops.is_empty() {
982        return Vec::new();
983    }
984    let (live_in, _) = liveness(ops, max_slot_of(ops), live_out);
985    let mut chosen: Vec<ConstHoist> = Vec::new();
986    for (i, op) in ops.iter().enumerate() {
987        let MicroOp::LoadConst { dst, value } = *op else {
988            continue;
989        };
990        // The INNERMOST loop span that contains this op (smallest span). A const is
991        // invariant in every enclosing loop, but the innermost pre-header runs the
992        // most often, and an enclosing loop might write `dst` between inner loops.
993        let inner = loops
994            .iter()
995            .copied()
996            .filter(|&(head, back)| (head..=back).contains(&i))
997            .min_by_key(|&(head, back)| back - head);
998        let Some((head, back)) = inner else { continue };
999        // Entry-discipline: every transfer targeting `head` must originate inside
1000        // `[head, back]`. A forward jump into `head` from outside would skip the
1001        // pre-header materialization.
1002        let entry_ok = ops.iter().enumerate().all(|(j, o)| match op_target(o) {
1003            Some(t) if t == head => (head..=back).contains(&j),
1004            _ => true,
1005        });
1006        if !entry_ok {
1007            continue;
1008        }
1009        // Invariance: NO other op in the span writes `dst` (this LoadConst is the
1010        // sole writer). A slot reused for two constants has a second writer here.
1011        let sole_writer = ops[head..=back]
1012            .iter()
1013            .enumerate()
1014            .all(|(off, o)| head + off == i || dest_of(o) != Some(dst));
1015        let dead_at_head = !live_in[head].get(dst as usize).copied().unwrap_or(true);
1016        if sole_writer && dead_at_head {
1017            chosen.push(ConstHoist {
1018                op: i,
1019                head,
1020                dst,
1021                value,
1022            });
1023        }
1024    }
1025    chosen
1026}
1027
1028/// The largest slot index the region touches, INCLUDING each self-call window's
1029/// full extent (`args_start + frame_size - 1`). The frame indexing allocates
1030/// `loc`/`written`/liveness bitvectors up to this bound, so it must cover the
1031/// callee window staging slots even though those stay frame-resident.
1032fn max_slot_of(ops: &[MicroOp]) -> usize {
1033    let mut max_slot: usize = 0;
1034    let mut buf = Vec::new();
1035    for op in ops {
1036        buf.clear();
1037        slots_of(op, &mut buf);
1038        for &s in &buf {
1039            max_slot = max_slot.max(s as usize);
1040        }
1041        if let MicroOp::CallSelf {
1042            args_start,
1043            frame_size,
1044            ..
1045        }
1046        | MicroOp::CallSelfCopy {
1047            args_start,
1048            frame_size,
1049            ..
1050        } = *op
1051        {
1052            let last = (args_start as i64) + frame_size - 1;
1053            if last >= 0 {
1054                max_slot = max_slot.max(last as usize);
1055            }
1056        }
1057    }
1058    max_slot
1059}
1060
1061/// Loop-weighted reference ranking with a CALL-LOCALITY tie-break.
1062///
1063/// The PRIMARY key is the loop-weighted reference count: each reference at loop
1064/// depth `d` is worth `base^depth`, so a loop-carried value out-ranks a colder
1065/// slot referenced more times outside any loop. This key — and therefore the
1066/// RESIDENT-vs-SPILLED boundary it induces (the first `pool.len()` slots are
1067/// resident) — is EXACTLY the pre-Fix-1 ranking. The call bonus is a SECONDARY
1068/// key only, so it can NEVER evict a hotter loop slot from a register: it merely
1069/// reorders slots that would be resident anyway.
1070///
1071/// The SECONDARY key prices CALL-LOCALITY. A slot LIVE ACROSS a SysV call (in
1072/// `live_after[call_idx]`) pays a caller-saved spill+reload pair on EVERY
1073/// execution of that call unless it lives in a callee-saved register. The bonus
1074/// is `call_weight * base^depth(call)` per surviving call (a call inside a hot
1075/// loop pays the pair per iteration). Because the `has_call` pool puts the four
1076/// CALLEE-SAVED registers FIRST, and a slot's callee-vs-caller placement is
1077/// decided by its rank position, lifting call-survivors above call-dead slots OF
1078/// EQUAL LOOP WEIGHT steers exactly the survivors into the callee-saved regs —
1079/// eliminating their per-call reload for a one-time prologue push/pop — without
1080/// disturbing which slots are resident at all.
1081///
1082/// This ONLY changes which physical register a resident slot occupies (and, on a
1083/// primary-key tie, which equally-cold slot spills). A slot still lives in
1084/// exactly one place for the whole function and its value never changes, so the
1085/// assignment is bit-identical to any other ranking. `live_after` is `None` for a
1086/// call-free region (no bonus). Returns the order (descending by the composite
1087/// key, then ascending by slot for determinism) and the observed `max_slot`. The
1088/// returned per-slot `u64` is the PRIMARY loop-weight (the secondary key is
1089/// internal to the sort) — downstream consumes only the slot ORDER.
1090fn rank_slots(
1091    ops: &[MicroOp],
1092    loop_weight_base: u64,
1093    loop_depth_cap: u32,
1094    call_weight: u64,
1095    live_after: Option<&[Vec<bool>]>,
1096) -> (Vec<(Slot, u64)>, usize) {
1097    let depths = loop_depths(ops);
1098    let max_slot = max_slot_of(ops);
1099    // PRIMARY: loop-weighted reference count.
1100    let mut refs: std::collections::HashMap<Slot, u64> = std::collections::HashMap::new();
1101    // SECONDARY: call-survival weight (a separate key, never folded into refs).
1102    let mut call_surv: std::collections::HashMap<Slot, u64> = std::collections::HashMap::new();
1103    let mut buf = Vec::new();
1104    for (idx, op) in ops.iter().enumerate() {
1105        let weight = loop_weight_base.saturating_pow(depths[idx].min(loop_depth_cap));
1106        buf.clear();
1107        slots_of(op, &mut buf);
1108        for &s in &buf {
1109            let e = refs.entry(s).or_insert(0);
1110            *e = e.saturating_add(weight);
1111        }
1112    }
1113    if let Some(la) = live_after {
1114        for (idx, op) in ops.iter().enumerate() {
1115            if !is_sysv_call(op) {
1116                continue;
1117            }
1118            let call_depth_weight =
1119                loop_weight_base.saturating_pow(depths[idx].min(loop_depth_cap));
1120            let bonus = call_weight.saturating_mul(call_depth_weight);
1121            for (s, &live) in la[idx].iter().enumerate() {
1122                if live {
1123                    // Only slots that ALSO carry loop/ref weight can ever be
1124                    // resident; recording survival for a slot with no refs is
1125                    // harmless (it sorts last on the primary key regardless).
1126                    let e = call_surv.entry(s as Slot).or_insert(0);
1127                    *e = e.saturating_add(bonus);
1128                }
1129            }
1130        }
1131    }
1132    let mut order: Vec<(Slot, u64)> = refs.iter().map(|(&s, &c)| (s, c)).collect();
1133    order.sort_by(|a, b| {
1134        // PRIMARY desc, then call-survival desc (the tie-break that picks
1135        // callee-saved for the survivor), then slot asc for determinism.
1136        b.1.cmp(&a.1)
1137            .then_with(|| call_surv.get(&b.0).cmp(&call_surv.get(&a.0)))
1138            .then(a.0.cmp(&b.0))
1139    });
1140    (order, max_slot)
1141}
1142
1143/// Every slot an op READS (its use set), for backward liveness. This enumerates
1144/// the READ operands by POSITION (not by value), so a self-referential op like
1145/// `Add { dst: i, lhs: i, rhs: 1 }` (`i = i + 1`) correctly reports `i` as a USE
1146/// even though it is also the destination — a value-based "all-slots minus dst"
1147/// would wrongly drop it. Every op in the supported subset has a pure write-only
1148/// destination (the operands `lhs`/`rhs`/`src`/`a`/`b`/`c`/`idx`/`cond`/… are the
1149/// reads); `dst` is never itself read by the op. A self-call READS `limit_slot`
1150/// (and a `CallSelfCopy`'s source args) and WRITES `dst`. An
1151/// `ArrStore`/`ArrPush`/`ListClear`/`ListTriple` has no `dst`, so all its slots
1152/// are reads. Used ONLY by the per-call-site spill-liveness lever (a pure
1153/// scheduling optimization): a missed read here would be UNSOUND, so this is the
1154/// authoritative read set — derived as `slots_of` (read ∪ write) minus the
1155/// POSITIONAL destination, by removing exactly the dst's first occurrence is
1156/// wrong; instead we list reads directly.
1157fn read_slots_of(op: &MicroOp, out: &mut Vec<Slot>) {
1158    match *op {
1159        MicroOp::Move { src, .. } | MicroOp::NotInt { src, .. } | MicroOp::NotBool { src, .. } => {
1160            out.push(src)
1161        }
1162        MicroOp::LoadConst { .. } => {}
1163        MicroOp::Add { lhs, rhs, .. }
1164        | MicroOp::Sub { lhs, rhs, .. }
1165        | MicroOp::Mul { lhs, rhs, .. }
1166        | MicroOp::Lt { lhs, rhs, .. }
1167        | MicroOp::Gt { lhs, rhs, .. }
1168        | MicroOp::LtEq { lhs, rhs, .. }
1169        | MicroOp::GtEq { lhs, rhs, .. }
1170        | MicroOp::Eq { lhs, rhs, .. }
1171        | MicroOp::Neq { lhs, rhs, .. }
1172        | MicroOp::BitAnd { lhs, rhs, .. }
1173        | MicroOp::BitOr { lhs, rhs, .. }
1174        | MicroOp::BitXor { lhs, rhs, .. }
1175        | MicroOp::Shl { lhs, rhs, .. }
1176        | MicroOp::Shr { lhs, rhs, .. }
1177        | MicroOp::Ushr { lhs, rhs, .. }
1178        | MicroOp::Rotate { lhs, rhs, .. }
1179        | MicroOp::Div { lhs, rhs, .. }
1180        | MicroOp::Mod { lhs, rhs, .. }
1181        | MicroOp::AddF { lhs, rhs, .. }
1182        | MicroOp::SubF { lhs, rhs, .. }
1183        | MicroOp::MulF { lhs, rhs, .. }
1184        | MicroOp::DivF { lhs, rhs, .. }
1185        | MicroOp::LtF { lhs, rhs, .. }
1186        | MicroOp::GtF { lhs, rhs, .. }
1187        | MicroOp::LtEqF { lhs, rhs, .. }
1188        | MicroOp::GtEqF { lhs, rhs, .. }
1189        | MicroOp::EqF { lhs, rhs, .. }
1190        | MicroOp::NeqF { lhs, rhs, .. } => out.extend([lhs, rhs]),
1191        MicroOp::FmaF { a, b, c, .. } => out.extend([a, b, c]),
1192        MicroOp::IntToFloat { src, .. }
1193        | MicroOp::SqrtF { src, .. }
1194        | MicroOp::FloorToInt { src, .. }
1195        | MicroOp::CeilToInt { src, .. }
1196        | MicroOp::RoundToInt { src, .. } => out.push(src),
1197        MicroOp::DivPow2 { lhs, .. } => out.push(lhs),
1198        MicroOp::MagicDivU { lhs, .. } => out.push(lhs),
1199        MicroOp::Branch { lhs, rhs, .. } | MicroOp::BranchF { lhs, rhs, .. } => {
1200            out.extend([lhs, rhs])
1201        }
1202        MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => out.push(cond),
1203        MicroOp::Return { src } => out.push(src),
1204        MicroOp::Host { src, count, .. } => out.extend(src..src + count),
1205        MicroOp::ArrLoad {
1206            idx,
1207            ptr_slot,
1208            len_slot,
1209            checked,
1210            ..
1211        } => {
1212            out.extend([idx, ptr_slot]);
1213            if checked {
1214                out.push(len_slot);
1215            }
1216        }
1217        MicroOp::ArrStore {
1218            src,
1219            idx,
1220            ptr_slot,
1221            len_slot,
1222            checked,
1223            ..
1224        } => {
1225            out.extend([src, idx, ptr_slot]);
1226            if checked {
1227                out.push(len_slot);
1228            }
1229        }
1230        MicroOp::ArrPush {
1231            src,
1232            vec_slot,
1233            ptr_slot,
1234            len_slot,
1235            ..
1236        } => out.extend([src, vec_slot, ptr_slot, len_slot]),
1237        MicroOp::ListClear {
1238            vec_slot,
1239            ptr_slot,
1240            len_slot,
1241            ..
1242        } => out.extend([vec_slot, ptr_slot, len_slot]),
1243        MicroOp::StrAppend {
1244            text_handle_slot,
1245            src,
1246            ..
1247        } => {
1248            out.push(text_handle_slot);
1249            if let Some(s) = src.slot() {
1250                out.push(s);
1251            }
1252        }
1253        MicroOp::Call { limit_slot, .. } => out.push(limit_slot),
1254        MicroOp::ListTriple {
1255            handle_slot,
1256            vec_slot,
1257            ptr_slot,
1258            len_slot,
1259            ..
1260        } => out.extend([handle_slot, vec_slot, ptr_slot, len_slot]),
1261        MicroOp::CallSelf { limit_slot, .. } => out.push(limit_slot),
1262        MicroOp::CallSelfCopy {
1263            src_start,
1264            arg_count,
1265            limit_slot,
1266            ..
1267        } => {
1268            out.push(limit_slot);
1269            for j in 0..arg_count {
1270                out.push(src_start + j);
1271            }
1272        }
1273        MicroOp::Jump { .. } => {}
1274        _ => {}
1275    }
1276}
1277
1278/// Backward LIVENESS: `live_after[i]` is the set of slots that may be READ on
1279/// some control-flow path AFTER op `i` finishes (before being overwritten). A
1280/// standard iterative backward dataflow to a fixpoint over the op stream's CFG
1281/// (fall-through `i+1` plus the branch/jump TARGET of `i`):
1282///
1283///   live_in[i]  = uses(i) ∪ (live_out[i] \ {def(i)})
1284///   live_out[i] = ⋃ live_in[succ]   over the successors of i
1285///
1286/// This is a SOUND OVER-approximation of "definitely dead after the call": every
1287/// slot a later op (on any path, including a loop back-edge) reads is marked
1288/// live, and an unconditional `Jump`/`Return` has no fall-through successor. The
1289/// result drives the spill-liveness lever, which spills/reloads only the
1290/// caller-saved residents that are live AFTER a call site; a slot NOT in
1291/// `live_after[call]` is read by no later op on any path (so the success-path
1292/// reload is dead) and is never observed by a deopt resume either (classic
1293/// replay recomputes mid-call temps from the boundary args; a precise resume at
1294/// a later op re-boxes only its own live slots — a subset of these). Eliding its
1295/// spill is therefore bit-identical. Returns one bitset (`Vec<bool>` over
1296/// `0..=max_slot`) per op.
1297fn liveness_after(ops: &[MicroOp], max_slot: usize) -> Vec<Vec<bool>> {
1298    liveness(ops, max_slot, &[]).1
1299}
1300
1301/// The backward dataflow behind [`liveness_after`], returning both `live_in` and
1302/// `live_after` per op. `exit_uses` are the frame slots the caller reads once the
1303/// region has exited: every `Return` reads them, so such a slot is live at every
1304/// point from which an exit is reachable without a write to it.
1305fn liveness(
1306    ops: &[MicroOp],
1307    max_slot: usize,
1308    exit_uses: &[Slot],
1309) -> (Vec<Vec<bool>>, Vec<Vec<bool>>) {
1310    let n = ops.len();
1311    let width = max_slot + 1;
1312    let mut live_in: Vec<Vec<bool>> = vec![vec![false; width]; n];
1313    // Precompute each op's use set and def (stable across iterations).
1314    let mut uses: Vec<Vec<Slot>> = Vec::with_capacity(n);
1315    let mut defs: Vec<Option<Slot>> = Vec::with_capacity(n);
1316    for op in ops {
1317        let mut u = Vec::new();
1318        read_slots_of(op, &mut u);
1319        if matches!(op, MicroOp::Return { .. }) {
1320            u.extend_from_slice(exit_uses);
1321        }
1322        uses.push(u);
1323        defs.push(dest_of(op));
1324    }
1325
1326    let mut changed = true;
1327    while changed {
1328        changed = false;
1329        // Process in reverse for faster convergence (data flows backward).
1330        for i in (0..n).rev() {
1331            // live_out[i] = union of live_in over successors.
1332            let mut out = vec![false; width];
1333            // Fall-through successor (i+1) unless this op is an unconditional
1334            // transfer (Jump has no fall-through; Return terminates).
1335            let unconditional_transfer =
1336                matches!(ops[i], MicroOp::Jump { .. } | MicroOp::Return { .. });
1337            if !unconditional_transfer {
1338                if let Some(succ) = live_in.get(i + 1) {
1339                    for (o, &s) in out.iter_mut().zip(succ.iter()) {
1340                        *o |= s;
1341                    }
1342                }
1343            }
1344            // Branch/jump target successor.
1345            if let Some(t) = op_target(&ops[i]) {
1346                if let Some(succ) = live_in.get(t) {
1347                    for (o, &s) in out.iter_mut().zip(succ.iter()) {
1348                        *o |= s;
1349                    }
1350                }
1351            }
1352            // live_in[i] = uses ∪ (live_out \ def).
1353            let mut new_in = out.clone();
1354            if let Some(d) = defs[i] {
1355                if (d as usize) < width {
1356                    new_in[d as usize] = false;
1357                }
1358            }
1359            for &u in &uses[i] {
1360                if (u as usize) < width {
1361                    new_in[u as usize] = true;
1362                }
1363            }
1364            if new_in != live_in[i] {
1365                live_in[i] = new_in;
1366                changed = true;
1367            }
1368        }
1369    }
1370
1371    // live_after[i] == live_out[i]: rebuild from the converged live_in.
1372    let mut live_after: Vec<Vec<bool>> = vec![vec![false; width]; n];
1373    for i in 0..n {
1374        let unconditional_transfer =
1375            matches!(ops[i], MicroOp::Jump { .. } | MicroOp::Return { .. });
1376        if !unconditional_transfer {
1377            if let Some(succ) = live_in.get(i + 1) {
1378                for (o, &s) in live_after[i].iter_mut().zip(succ.iter()) {
1379                    *o |= s;
1380                }
1381            }
1382        }
1383        if let Some(t) = op_target(&ops[i]) {
1384            if let Some(succ) = live_in.get(t) {
1385                for (o, &s) in live_after[i].iter_mut().zip(succ.iter()) {
1386                    *o |= s;
1387                }
1388            }
1389        }
1390    }
1391    (live_in, live_after)
1392}
1393
1394/// The condition for a `Cmp`.
1395fn cond_of(cmp: Cmp) -> Cond {
1396    match cmp {
1397        Cmp::Lt => Cond::Lt,
1398        Cmp::Gt => Cond::Gt,
1399        Cmp::LtEq => Cond::Le,
1400        Cmp::GtEq => Cond::Ge,
1401        Cmp::Eq => Cond::Eq,
1402        Cmp::NotEq => Cond::Ne,
1403    }
1404}
1405
1406/// The register CLASS a slot may be resident in. A slot that appears in BOTH an
1407/// integer role and a float role (or only ever as a raw-bits/neutral operand) is
1408/// kept frame-resident, where the two classes share the same 8 raw bytes.
1409#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1410enum Class {
1411    /// Used only in integer roles → eligible for a GP register.
1412    Int,
1413    /// Used only in float (f64) roles → eligible for an XMM register.
1414    Float,
1415    /// Used in both classes (or class-ambiguous): frame-resident only.
1416    Mixed,
1417}
1418
1419/// Per-slot role tally for [`Class`] assignment.
1420#[derive(Clone, Copy, Default)]
1421struct Roles {
1422    int: bool,
1423    float: bool,
1424}
1425
1426/// Mark every slot an op touches with its INT and/or FLOAT roles. Type-NEUTRAL
1427/// roles (a `Move`/`LoadConst`/`Return` operand, an `ArrLoad` dst / `ArrStore`
1428/// src — all raw-bits transfers) impose NO class; the slot's class comes from
1429/// the strongly-typed ops it also appears in. A slot with no typed role at all
1430/// defaults to INT (the historical behavior).
1431fn tally_roles(op: &MicroOp, roles: &mut [Roles]) {
1432    macro_rules! mark_int {
1433        ($s:expr) => {
1434            roles[$s as usize].int = true
1435        };
1436    }
1437    match *op {
1438        // Integer arithmetic / compare / bitwise / shift: all operands + dst int.
1439        MicroOp::Add { dst, lhs, rhs }
1440        | MicroOp::Sub { dst, lhs, rhs }
1441        | MicroOp::Mul { dst, lhs, rhs }
1442        | MicroOp::Div { dst, lhs, rhs }
1443        | MicroOp::Mod { dst, lhs, rhs }
1444        | MicroOp::Lt { dst, lhs, rhs }
1445        | MicroOp::Gt { dst, lhs, rhs }
1446        | MicroOp::LtEq { dst, lhs, rhs }
1447        | MicroOp::GtEq { dst, lhs, rhs }
1448        | MicroOp::Eq { dst, lhs, rhs }
1449        | MicroOp::Neq { dst, lhs, rhs }
1450        | MicroOp::BitAnd { dst, lhs, rhs }
1451        | MicroOp::BitOr { dst, lhs, rhs }
1452        | MicroOp::BitXor { dst, lhs, rhs }
1453        | MicroOp::Shl { dst, lhs, rhs }
1454        | MicroOp::Shr { dst, lhs, rhs }
1455        | MicroOp::Ushr { dst, lhs, rhs } => {
1456            mark_int!(dst);
1457            mark_int!(lhs);
1458            mark_int!(rhs);
1459        }
1460        MicroOp::Rotate { dst, lhs, rhs, .. } => {
1461            mark_int!(dst);
1462            mark_int!(lhs);
1463            mark_int!(rhs);
1464        }
1465        MicroOp::DivPow2 { dst, lhs, .. } | MicroOp::MagicDivU { dst, lhs, .. } => {
1466            mark_int!(dst);
1467            mark_int!(lhs);
1468        }
1469        MicroOp::NotInt { dst, src }
1470        | MicroOp::NotBool { dst, src }
1471        | MicroOp::Popcnt { dst, src }
1472        | MicroOp::Lzcnt { dst, src }
1473        | MicroOp::Tzcnt { dst, src }
1474        | MicroOp::ChrGuard { dst, src }
1475        | MicroOp::Utf8Len { dst, src } => {
1476            mark_int!(dst);
1477            mark_int!(src);
1478        }
1479        MicroOp::Branch { lhs, rhs, .. } => {
1480            mark_int!(lhs);
1481            mark_int!(rhs);
1482        }
1483        MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => mark_int!(cond),
1484        // Array address machinery is INT; the loaded/stored value is NEUTRAL.
1485        MicroOp::ArrLoad {
1486            idx,
1487            ptr_slot,
1488            len_slot,
1489            checked,
1490            ..
1491        } => {
1492            mark_int!(idx);
1493            mark_int!(ptr_slot);
1494            if checked {
1495                mark_int!(len_slot);
1496            }
1497        }
1498        MicroOp::ArrStore {
1499            idx,
1500            ptr_slot,
1501            len_slot,
1502            checked,
1503            ..
1504        } => {
1505            mark_int!(idx);
1506            mark_int!(ptr_slot);
1507            if checked {
1508                mark_int!(len_slot);
1509            }
1510        }
1511        // The list-mutation handle slots (vec/ptr/len) are INT machinery; the
1512        // pushed VALUE is NEUTRAL (its raw bits travel to the buffer regardless
1513        // of class — a float-list push bit-copies through a GP reg). The handle
1514        // slots are also forced frame-resident, so their class is moot, but
1515        // marking them INT keeps the role tally accurate.
1516        MicroOp::ArrPush {
1517            vec_slot,
1518            ptr_slot,
1519            len_slot,
1520            ..
1521        } => {
1522            mark_int!(vec_slot);
1523            mark_int!(ptr_slot);
1524            mark_int!(len_slot);
1525        }
1526        MicroOp::ListClear {
1527            vec_slot,
1528            ptr_slot,
1529            len_slot,
1530            ..
1531        } => {
1532            mark_int!(vec_slot);
1533            mark_int!(ptr_slot);
1534            mark_int!(len_slot);
1535        }
1536        // Float arithmetic: all operands + dst float.
1537        MicroOp::AddF { dst, lhs, rhs }
1538        | MicroOp::SubF { dst, lhs, rhs }
1539        | MicroOp::MulF { dst, lhs, rhs }
1540        | MicroOp::DivF { dst, lhs, rhs } => {
1541            roles[dst as usize].float = true;
1542            roles[lhs as usize].float = true;
1543            roles[rhs as usize].float = true;
1544        }
1545        // Float compares: operands float, RESULT (dst) is an int 0/1.
1546        MicroOp::LtF { dst, lhs, rhs }
1547        | MicroOp::GtF { dst, lhs, rhs }
1548        | MicroOp::LtEqF { dst, lhs, rhs }
1549        | MicroOp::GtEqF { dst, lhs, rhs }
1550        | MicroOp::EqF { dst, lhs, rhs }
1551        | MicroOp::NeqF { dst, lhs, rhs } => {
1552            roles[dst as usize].int = true;
1553            roles[lhs as usize].float = true;
1554            roles[rhs as usize].float = true;
1555        }
1556        MicroOp::BranchF { lhs, rhs, .. } => {
1557            roles[lhs as usize].float = true;
1558            roles[rhs as usize].float = true;
1559        }
1560        MicroOp::FmaF { dst, a, b, c } => {
1561            roles[dst as usize].float = true;
1562            roles[a as usize].float = true;
1563            roles[b as usize].float = true;
1564            roles[c as usize].float = true;
1565        }
1566        MicroOp::SqrtF { dst, src } => {
1567            roles[dst as usize].float = true;
1568            roles[src as usize].float = true;
1569        }
1570        // IntToFloat: src is INT, dst is FLOAT.
1571        MicroOp::IntToFloat { dst, src } => {
1572            roles[dst as usize].float = true;
1573            mark_int!(src);
1574        }
1575        // FloorToInt/CeilToInt/RoundToInt: src is FLOAT, dst is INT (the mirror of IntToFloat).
1576        MicroOp::FloorToInt { dst, src }
1577        | MicroOp::CeilToInt { dst, src }
1578        | MicroOp::RoundToInt { dst, src } => {
1579            roles[src as usize].float = true;
1580            mark_int!(dst);
1581        }
1582        // A self-call: `dst` (the result) and `limit_slot` (the arena bound) are
1583        // INT. The staged scalar args are 8-byte raw copies (NEUTRAL — the copy
1584        // preserves their bits regardless of class), so they impose no class
1585        // here; their class comes from the ops that produced them.
1586        MicroOp::CallSelf {
1587            dst, limit_slot, ..
1588        } => {
1589            mark_int!(dst);
1590            mark_int!(limit_slot);
1591        }
1592        MicroOp::CallSelfCopy {
1593            dst, limit_slot, ..
1594        } => {
1595            mark_int!(dst);
1596            mark_int!(limit_slot);
1597        }
1598        // The mode-B precise self-call: `dst` (the result handle, an i64) and
1599        // `limit_slot` are INT. The staged args are NEUTRAL raw copies (their
1600        // class comes from the producing ops).
1601        MicroOp::Call {
1602            dst, limit_slot, ..
1603        } => {
1604            mark_int!(dst);
1605            mark_int!(limit_slot);
1606        }
1607        // List-machinery handle/triple slots are INT (raw `*mut Vec` words);
1608        // they are also forced frame-resident, so the class is moot, but the
1609        // tally stays accurate.
1610        MicroOp::ListTriple {
1611            handle_slot,
1612            vec_slot,
1613            ptr_slot,
1614            len_slot,
1615            ..
1616        } => {
1617            mark_int!(handle_slot);
1618            mark_int!(vec_slot);
1619            mark_int!(ptr_slot);
1620            mark_int!(len_slot);
1621        }
1622        // The str-append handle (a raw `*mut Value` word) and a byte- or Int-form
1623        // value are INT. The handle is forced frame-resident, so its class is moot,
1624        // but the tally stays accurate.
1625        MicroOp::StrAppend {
1626            text_handle_slot,
1627            src,
1628            ..
1629        } => {
1630            mark_int!(text_handle_slot);
1631            if let Some(s) = src.slot() {
1632                mark_int!(s);
1633            }
1634        }
1635        // Move / LoadConst / Return are NEUTRAL — no class imposed.
1636        MicroOp::Move { .. }
1637        | MicroOp::LoadConst { .. }
1638        | MicroOp::Return { .. }
1639        | MicroOp::Jump { .. } => {}
1640        _ => {}
1641    }
1642}
1643
1644/// Classify every slot up to `max_slot` into its register [`Class`].
1645fn classify_slots(ops: &[MicroOp], max_slot: usize) -> Vec<Class> {
1646    let mut roles = vec![Roles::default(); max_slot + 1];
1647    for op in ops {
1648        tally_roles(op, &mut roles);
1649    }
1650    roles
1651        .iter()
1652        .map(|r| match (r.int, r.float) {
1653            (_, true) if r.int => Class::Mixed,
1654            (false, true) => Class::Float,
1655            // int-only OR neutral-only (default int).
1656            _ => Class::Int,
1657        })
1658        .collect()
1659}
1660
1661/// A slot's coarse LIVE INTERVAL as a single `[start, end]` span over op indices:
1662/// `start` = the first op that defines or uses it, `end` = the last op that uses
1663/// or defines it. This omits holes (a slot dead in the middle of its span still
1664/// occupies it), so the max overlap of these intervals is an UPPER BOUND on true
1665/// register pressure — the pessimistic input a classic linear-scan allocator
1666/// consumes. Used by the linear-scan SIMULATION the class diagnostic reports, to
1667/// confirm a simple interval allocator would reclaim the spills the whole-region
1668/// per-slot model leaves on the table.
1669#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1670struct LiveInterval {
1671    slot: u16,
1672    start: usize,
1673    end: usize,
1674}
1675
1676/// One coarse `[first-touch, last-touch]` interval per slot the op stream reads
1677/// or writes. A slot never touched gets no interval (it needs no register).
1678fn live_intervals(ops: &[MicroOp], max_slot: usize) -> Vec<LiveInterval> {
1679    let mut first = vec![usize::MAX; max_slot + 1];
1680    let mut last = vec![0usize; max_slot + 1];
1681    let mut reads = Vec::new();
1682    for (i, op) in ops.iter().enumerate() {
1683        reads.clear();
1684        read_slots_of(op, &mut reads);
1685        let mut touch = |s: Slot| {
1686            let s = s as usize;
1687            if s <= max_slot {
1688                if first[s] == usize::MAX {
1689                    first[s] = i;
1690                }
1691                last[s] = i;
1692            }
1693        };
1694        for &s in &reads {
1695            touch(s);
1696        }
1697        if let Some(d) = dest_of(op) {
1698            touch(d);
1699        }
1700    }
1701    (0..=max_slot)
1702        .filter(|&s| first[s] != usize::MAX)
1703        .map(|s| LiveInterval {
1704            slot: s as u16,
1705            start: first[s],
1706            end: last[s],
1707        })
1708        .collect()
1709}
1710
1711/// Classic linear-scan over the coarse intervals of ONE register class: how many
1712/// of that class's intervals would SPILL given `regs` physical registers,
1713/// reusing a register the instant an interval expires. The spill victim on
1714/// overflow is the active interval whose end is farthest (the textbook
1715/// heuristic) — but the COUNT (what we report) is heuristic-independent: it is
1716/// `intervals − (intervals placeable in `regs` colors)`, i.e. one spill per
1717/// point where more than `regs` intervals overlap. This is the number the
1718/// whole-region per-slot model fails to achieve (it spills every slot beyond the
1719/// top-`regs` ranked, even when their ranges never overlap).
1720fn linscan_spills(intervals: &[LiveInterval], class: &[Class], want: Class, regs: usize) -> usize {
1721    let mut iv: Vec<&LiveInterval> = intervals
1722        .iter()
1723        .filter(|i| class[i.slot as usize] == want)
1724        .collect();
1725    iv.sort_by_key(|i| (i.start, i.end));
1726    // `active` ends, kept sorted ascending so the farthest end is last.
1727    let mut active: Vec<usize> = Vec::new();
1728    let mut spills = 0usize;
1729    for cur in iv {
1730        active.retain(|&e| e >= cur.start); // expire intervals that ended before cur starts
1731        if regs == 0 {
1732            spills += 1;
1733            continue;
1734        }
1735        if active.len() < regs {
1736            let pos = active.partition_point(|&e| e <= cur.end);
1737            active.insert(pos, cur.end);
1738        } else {
1739            // Pool full: spill the farthest-ending of {actives ∪ cur}.
1740            let far = *active.last().unwrap();
1741            if far > cur.end {
1742                active.pop();
1743                let pos = active.partition_point(|&e| e <= cur.end);
1744                active.insert(pos, cur.end);
1745            }
1746            spills += 1;
1747        }
1748    }
1749    spills
1750}
1751
1752/// Per-slot loop-aware live RANGE `[start, end]` (op indices), or `None` if the
1753/// slot is never touched. Built from the `liveness_after` backward fixpoint, so a
1754/// loop-carried slot — live on the back-edge path at every body op — spans the
1755/// whole loop automatically (min..max over its live points), with NO explicit
1756/// loop-extension step. This is the SOUND interval the real allocator consumes
1757/// (unlike `live_intervals`, naive first/last touch, used only by the diagnostic).
1758fn live_ranges(ops: &[MicroOp], max_slot: usize) -> Vec<Option<(usize, usize)>> {
1759    let la = liveness_after(ops, max_slot);
1760    let mut start = vec![usize::MAX; max_slot + 1];
1761    let mut end = vec![0usize; max_slot + 1];
1762    let mut reads = Vec::new();
1763    for i in 0..ops.len() {
1764        // A slot OCCUPIES op i if it is live out of i, used at i, or defined at i
1765        // (live_in is uses ∪ (live_after \ def), all subsumed by these three).
1766        for s in 0..=max_slot {
1767            if la[i][s] {
1768                if start[s] == usize::MAX {
1769                    start[s] = i;
1770                }
1771                end[s] = i;
1772            }
1773        }
1774        reads.clear();
1775        read_slots_of(&ops[i], &mut reads);
1776        let mut touch = |s: usize| {
1777            if s <= max_slot {
1778                if start[s] == usize::MAX {
1779                    start[s] = i;
1780                }
1781                if i > end[s] {
1782                    end[s] = i;
1783                }
1784            }
1785        };
1786        for &u in &reads {
1787            touch(u as usize);
1788        }
1789        if let Some(d) = dest_of(&ops[i]) {
1790            touch(d as usize);
1791        }
1792    }
1793    (0..=max_slot)
1794        .map(|s| (start[s] != usize::MAX).then_some((start[s], end[s])))
1795        .collect()
1796}
1797
1798/// LINEAR-SCAN ASSIGNMENT (the LS1 keystone). Assign each slot a physical
1799/// register of its class for its whole loop-aware live range, REUSING a register
1800/// the instant its previous holder's range expires — so disjoint temporaries
1801/// share registers instead of each consuming a whole-region frame home. Returns a
1802/// per-slot [`Loc`]; a slot that finds no register stays `Loc::Frame` (exactly the
1803/// current behavior, so the fallback is bit-identical).
1804///
1805/// SOUNDNESS — register REUSE is permitted only across a STRAIGHT-LINE gap: a
1806/// register freed at op `e` may host a new range starting at `s` only when no
1807/// control point (a branch/jump OR a jump target) lies in `(e, s]`. That confines
1808/// every register reassignment to a single-predecessor, single-successor stretch,
1809/// so the binding is identical on every path reaching it — no inconsistent state
1810/// at a control join. Overlapping ranges never share (a holder is freed only once
1811/// its end is strictly before the newcomer's start). Loop-carried slots span the
1812/// whole loop (their range covers every body op), so their register is never
1813/// reused mid-loop. The caller gates this to no-deopt / no-call regions so there
1814/// is no mid-region side-exit whose flush would observe a transient binding.
1815fn linscan_assign(
1816    ops: &[MicroOp],
1817    max_slot: usize,
1818    class: &[Class],
1819    gp: &[Reg],
1820    xmm: &[Xmm],
1821) -> Vec<Loc> {
1822    let n = ops.len();
1823    let ranges = live_ranges(ops, max_slot);
1824    // Control-point prefix sum: ctrl[j] = 1 if op j transfers OR is a jump target.
1825    let mut is_jt = vec![false; n];
1826    for op in ops {
1827        if let Some(t) = op_target(op) {
1828            if t < n {
1829                is_jt[t] = true;
1830            }
1831        }
1832    }
1833    let mut pref = vec![0u32; n + 1];
1834    for j in 0..n {
1835        pref[j + 1] = pref[j] + u32::from(op_target(&ops[j]).is_some() || is_jt[j]);
1836    }
1837    // Any control point in the half-open gap (e, s]?
1838    let ctrl_between = |e: usize, s: usize| -> bool {
1839        let lo = (e + 1).min(n);
1840        let hi = (s + 1).min(n);
1841        pref[hi].saturating_sub(pref[lo]) > 0
1842    };
1843    // Slots with a range, in start order (then end, then slot — deterministic).
1844    let mut order: Vec<usize> = (0..=max_slot).filter(|&s| ranges[s].is_some()).collect();
1845    order.sort_by_key(|&s| {
1846        let (a, b) = ranges[s].unwrap();
1847        (a, b, s)
1848    });
1849    // Fresh pools (never used) popped from the front; freed pools carry the op
1850    // index at which each register became free, for the gap test.
1851    let mut gp_fresh: Vec<Reg> = gp.iter().rev().copied().collect();
1852    let mut xmm_fresh: Vec<Xmm> = xmm.iter().rev().copied().collect();
1853    let mut gp_freed: Vec<(Reg, usize)> = Vec::new();
1854    let mut xmm_freed: Vec<(Xmm, usize)> = Vec::new();
1855    let mut active: Vec<(usize, usize)> = Vec::new(); // (end, slot)
1856    let mut out = vec![Loc::Frame; max_slot + 1];
1857    for &s in &order {
1858        let (st, en) = ranges[s].unwrap();
1859        // Expire holders whose range ended strictly before this one starts.
1860        let mut still = Vec::with_capacity(active.len());
1861        for &(ae, asl) in &active {
1862            if ae < st {
1863                match out[asl] {
1864                    Loc::Reg(r) => gp_freed.push((r, ae)),
1865                    Loc::Xmm(x) => xmm_freed.push((x, ae)),
1866                    Loc::Frame => {}
1867                }
1868            } else {
1869                still.push((ae, asl));
1870            }
1871        }
1872        active = still;
1873        // PREFER A FRESH register over reusing a freed one: a slot in a register
1874        // all to itself needs no spill-at-end, so as long as a never-used register
1875        // remains we pay no reuse overhead — reuse (and its one end-spill) kicks in
1876        // ONLY under real pressure, once the pool is exhausted. This makes a region
1877        // that already fits (<= pool size) bit-identical in COST to the classic
1878        // per-slot assignment, and reclaims frame spills only where they exist.
1879        match class[s] {
1880            Class::Int => {
1881                let pick = gp_fresh.pop().or_else(|| {
1882                    gp_freed
1883                        .iter()
1884                        .position(|&(_, e)| !ctrl_between(e, st))
1885                        .map(|i| gp_freed.swap_remove(i).0)
1886                });
1887                if let Some(r) = pick {
1888                    out[s] = Loc::Reg(r);
1889                    active.push((en, s));
1890                }
1891            }
1892            Class::Float => {
1893                let pick = xmm_fresh.pop().or_else(|| {
1894                    xmm_freed
1895                        .iter()
1896                        .position(|&(_, e)| !ctrl_between(e, st))
1897                        .map(|i| xmm_freed.swap_remove(i).0)
1898                });
1899                if let Some(x) = pick {
1900                    out[s] = Loc::Xmm(x);
1901                    active.push((en, s));
1902                }
1903            }
1904            Class::Mixed => {}
1905        }
1906    }
1907    out
1908}
1909
1910/// Per-self-call support: the label of the "bare return" epilogue that a
1911/// PROPAGATED in-callee deopt jumps to — flush the frame and return WITHOUT
1912/// touching the status cell (which already holds the inner exit code). The
1913/// per-call-site caller-saved spill/reload lists live on [`Gen`]
1914/// (`call_gp`/`call_xmm`), shared with the list-mutation helper-call path.
1915struct SelfCall {
1916    /// The bare flush+return epilogue (no status write) for deopt PROPAGATION.
1917    propagate_label: LabelId,
1918}
1919
1920/// PRECISE deopt support. Every checked op and the precise self-call's
1921/// guards side-exit with the op's ENCODED resume tag (`(pc << 2) | 3`) OR'd with
1922/// the live call depth in the high 32 bits, mirroring `logos_stencil_deopt_at` /
1923/// `logos_stencil_call_precise`. A checked op routes its bounds/divisor failure
1924/// to the out-of-line block for its code (`code_blocks[code]`), which stages the
1925/// tag in `S1` and jumps to the shared `epilogue`. The epilogue reads the live
1926/// depth, ORs it into the high bits, writes the status cell, flushes every
1927/// resident-written slot (so the precise-deopt walk reads the right frame), and
1928/// returns.
1929struct Precise<'a> {
1930    /// The per-op resume codes (parallel to the op stream).
1931    codes: &'a [i64],
1932    /// Distinct non-plain code → its out-of-line tag-staging block label (each
1933    /// block stages the tag in `S1` and jumps to the shared precise epilogue).
1934    code_blocks: &'a std::collections::HashMap<i64, LabelId>,
1935}
1936
1937/// The codegen context: the slot→location map plus the assembler.
1938struct Gen<'a> {
1939    asm: Asm,
1940    /// Per-slot location (GP reg / XMM reg / frame). The location already
1941    /// encodes the slot's register class, so Move/LoadConst/array transfers read
1942    /// `loc` directly to decide whether to bridge between the GP and XMM classes.
1943    /// OWNED (not borrowed) so the linear-scan path can MUTATE a slot's home as
1944    /// the emission walks the ops — a register cache reused across disjoint live
1945    /// ranges (a reused slot is spilled to its frame home and set `Frame` at its
1946    /// interval end). The classic per-slot path sets it once and never mutates.
1947    loc: Vec<Loc>,
1948    /// Op-index → label, for jump targets.
1949    op_labels: &'a [LabelId],
1950    /// The label of the deopt epilogue (set status = 1, flush, return), if any.
1951    deopt_label: Option<LabelId>,
1952    /// Stack-pointer realignment padding applied in the prologue (so RSP is
1953    /// 16-aligned at every `call`) and undone in every epilogue. 0 or 8.
1954    stack_pad: i32,
1955    /// Self-call support (present only for the FUNCTION backend with self-calls).
1956    self_call: Option<SelfCall>,
1957    /// PER-CALL-SITE caller-saved GP residents to spill/reload around the SysV
1958    /// call at op index `i` — `call_gp[i]` is the global caller-saved-GP-resident
1959    /// universe INTERSECTED with the slots LIVE AFTER op `i` (so a resident dead
1960    /// after the call is not spilled/reloaded). Empty for a non-call op. The XMM
1961    /// counterpart lives in `call_xmm`.
1962    call_gp: &'a [Vec<Slot>],
1963    /// PER-CALL-SITE XMM residents to spill/reload around the call at op `i` (all
1964    /// XMM are caller-saved). The live-after subset, parallel to `call_gp`.
1965    call_xmm: &'a [Vec<Slot>],
1966    /// PRECISE deopt support; `None` for the classic region/function
1967    /// paths (which replay from head). When `Some`, every checked op's side exit
1968    /// and the precise self-call's guards route through it.
1969    precise: Option<Precise<'a>>,
1970    /// SCALED-INDEX CSE (Wave 26). Reserved caller-saved register(s) that hold a
1971    /// run's shared 0-based index `im1 = idx - 1` (`im1_reg`) and, when a second
1972    /// register is free, its scaled byte offset `im1 * 8` (`scaled_reg`). Both
1973    /// are `None` when no caller-saved register is free (CSE disabled for the
1974    /// region) or the kill-switch is off. The reserved registers are never
1975    /// assigned to a resident slot and are touched by NOTHING but [`emit_arr_addr`],
1976    /// so they stay live across intervening arithmetic — invalidated only when the
1977    /// index slot is reassigned, at a jump target, or across a SysV call.
1978    off_im1_reg: Option<Reg>,
1979    /// The second reserved register holding the scaled byte offset, when free.
1980    off_scaled_reg: Option<Reg>,
1981    /// The currently-cached run, or `None` when the cache is invalid. `byte`
1982    /// records the element stride the offset was scaled for (1 vs 8); a different
1983    /// stride for the same index slot is a cache miss (recompute). `verified`
1984    /// records whether the FIRST access of the run bounds-checked `im1` (so a
1985    /// later checked access may reuse the cached scaled offset soundly).
1986    off_cache: Option<OffCacheState>,
1987    /// LOOP-INVARIANT PTR/LEN HOIST (Wave 27a). The per-plan reserved registers
1988    /// holding the invariant `frame[ptr_slot]` (and `frame[len_slot]`) for a loop
1989    /// span. Each entry is one [`HoistPlan`] plus the callee-saved registers it
1990    /// claimed. `emit_arr_addr` consults [`Gen::hoisted`] to read the register
1991    /// instead of reloading the frame, but ONLY while codegen is inside the plan's
1992    /// span — the active-set is keyed per op index in the emit loop.
1993    hoists: &'a [HoistEntry],
1994    /// The ptr/len slots whose hoist registers are ACTIVE at the current op (the
1995    /// codegen is inside their span). Reset/recomputed per op in the emit loop;
1996    /// `emit_arr_addr` reads it to decide whether a given ptr/len slot is hoisted
1997    /// here. Indexed lookups are over a tiny vec (at most a few hoists per loop).
1998    active_hoists: Vec<usize>,
1999}
2000
2001/// A resolved [`HoistPlan`]: the plan plus the callee-saved registers reserved to
2002/// hold its invariant `frame[ptr_slot]` (`ptr_reg`) and, when `needs_len`, its
2003/// `frame[len_slot]` (`len_reg`). A plan that could not claim a register is not
2004/// materialized into a `HoistEntry` (it falls back to the per-access reload).
2005#[derive(Clone, Copy)]
2006struct HoistEntry {
2007    plan: HoistPlan,
2008    ptr_reg: Reg,
2009    len_reg: Option<Reg>,
2010}
2011
2012/// The live scaled-index cache: the reserved registers hold `im1`/`im1*8` for
2013/// this `idx` slot at this element stride.
2014#[derive(Clone, Copy)]
2015struct OffCacheState {
2016    idx: Slot,
2017    byte: bool,
2018}
2019
2020impl Gen<'_> {
2021    /// The label an op at index `idx` jumps to on a CHECKED side exit, or `None`
2022    /// when no deopt channel exists (an UNCHECKED op in a region with no checked
2023    /// op — the label is never referenced). In the classic paths this is the
2024    /// shared `deopt_label` (writes status = 1); in the PRECISE path it is the
2025    /// out-of-line tag-staging block for this op's code (which stages the precise
2026    /// tag and jumps to the precise epilogue). A precise op whose code is the
2027    /// plain marker `1` still uses `deopt_label`. The CHECKED-op emitters
2028    /// `.expect()` this where a missing label would be a real bug; the unchecked
2029    /// path never reads it.
2030    fn checked_exit(&self, idx: usize) -> Option<LabelId> {
2031        if let Some(p) = &self.precise {
2032            let code = p.codes[idx];
2033            if code != 1 {
2034                return Some(p.code_blocks[&code]);
2035            }
2036        }
2037        self.deopt_label
2038    }
2039
2040    /// Drop the scaled-index cache: the reserved register(s) no longer hold a
2041    /// usable `im1`/offset for any index. Called at a jump target (control could
2042    /// enter here with a stale register), across a SysV call (which clobbers the
2043    /// caller-saved reserved register), and whenever the cached index slot is
2044    /// reassigned (so the next access recomputes from the fresh index value).
2045    fn invalidate_off_cache(&mut self) {
2046        self.off_cache = None;
2047    }
2048
2049    /// Drop the cache if `op` writes the cached index slot. A write to the slot
2050    /// the cache keys off makes the held `im1` stale; the next access must
2051    /// recompute from the new index value. (A write to ANY other slot leaves the
2052    /// cached `im1` valid, so cross-arithmetic reuse is preserved.)
2053    fn invalidate_off_cache_if_writes_idx(&mut self, op: &MicroOp) {
2054        if let Some(state) = self.off_cache {
2055            if dest_of(op) == Some(state.idx) {
2056                self.off_cache = None;
2057            }
2058        }
2059    }
2060
2061    /// The hoisted register holding `frame[ptr_slot]` for an ACTIVE hoist of this
2062    /// ptr slot, or `None` (use the per-access frame reload). A ptr slot is the
2063    /// address base, so we key on it; the entry's `len_reg` is consulted via
2064    /// [`Gen::hoisted_len`]. Only entries whose span is active at the current op
2065    /// (recorded in `active_hoists`) are eligible — outside the span the register
2066    /// may hold a stale value (a different loop's array, or the slot was rewritten
2067    /// at the outer level), so it must not be read.
2068    fn hoisted_ptr(&self, ptr_slot: Slot) -> Option<Reg> {
2069        self.active_hoists
2070            .iter()
2071            .map(|&k| self.hoists[k])
2072            .find(|e| e.plan.ptr_slot == ptr_slot)
2073            .map(|e| e.ptr_reg)
2074    }
2075
2076    /// The hoisted register holding `frame[len_slot]` for an ACTIVE hoist whose
2077    /// `ptr_slot` matches (the array is identified by its ptr base), or `None`.
2078    /// `None` when the access is unchecked-only-hoisted (no `len_reg` reserved) —
2079    /// the checked path then reloads `len` from the frame as before.
2080    fn hoisted_len(&self, ptr_slot: Slot) -> Option<Reg> {
2081        self.active_hoists
2082            .iter()
2083            .map(|&k| self.hoists[k])
2084            .find(|e| e.plan.ptr_slot == ptr_slot)
2085            .and_then(|e| e.len_reg)
2086    }
2087}
2088
2089impl Gen<'_> {
2090    /// Spill the per-call-site live-after caller-saved residents (GP + XMM) for
2091    /// the call op at index `idx` to their frame slots before a SysV call: the
2092    /// callee clobbers all caller-saved registers. Reloaded by
2093    /// [`Gen::reload_volatiles_at`] after the call so loop-carried values survive.
2094    /// The `call_gp`/`call_xmm` lists are the LIVE-AFTER subset (a resident dead
2095    /// after the call is read by no later op and not observed by a deopt resume,
2096    /// so its spill is elided — bit-identical). The slices live on a separate
2097    /// borrow than `asm`, so this resolves the spill list before mutating the
2098    /// assembler.
2099    fn spill_volatiles_at(&mut self, idx: usize) {
2100        let gp: &[Slot] = self.call_gp.get(idx).map_or(&[], Vec::as_slice);
2101        for &s in gp {
2102            if let Loc::Reg(r) = self.loc[s as usize] {
2103                self.asm.mov_mr(BASE, (s as i32) * 8, r);
2104            }
2105        }
2106        let xmm: &[Slot] = self.call_xmm.get(idx).map_or(&[], Vec::as_slice);
2107        for &s in xmm {
2108            if let Loc::Xmm(x) = self.loc[s as usize] {
2109                self.asm.movsd_mr(BASE, (s as i32) * 8, x);
2110            }
2111        }
2112    }
2113
2114    /// Reload the per-call-site live-after residents for the call op at `idx`.
2115    fn reload_volatiles_at(&mut self, idx: usize) {
2116        let gp: &[Slot] = self.call_gp.get(idx).map_or(&[], Vec::as_slice);
2117        for &s in gp {
2118            if let Loc::Reg(r) = self.loc[s as usize] {
2119                self.asm.mov_rm(r, BASE, (s as i32) * 8);
2120            }
2121        }
2122        let xmm: &[Slot] = self.call_xmm.get(idx).map_or(&[], Vec::as_slice);
2123        for &s in xmm {
2124            if let Loc::Xmm(x) = self.loc[s as usize] {
2125                self.asm.movsd_rm(x, BASE, (s as i32) * 8);
2126            }
2127        }
2128    }
2129}
2130
2131impl<'a> Gen<'a> {
2132    /// Load slot `s` into GP register `r`. An XMM-resident slot is bit-copied
2133    /// via `movq` (defensive — INT-class slots never land in XMM).
2134    fn load(&mut self, r: Reg, s: Slot) {
2135        match self.loc[s as usize] {
2136            Loc::Reg(src) => self.asm.mov_rr(r, src),
2137            Loc::Frame => self.asm.mov_rm(r, BASE, (s as i32) * 8),
2138            Loc::Xmm(x) => self.asm.movq_rx(r, x),
2139        }
2140    }
2141
2142    /// Store GP register `r` into slot `s`. An XMM-resident slot is bit-copied
2143    /// via `movq` (defensive — INT-class slots never land in XMM).
2144    fn store(&mut self, s: Slot, r: Reg) {
2145        match self.loc[s as usize] {
2146            Loc::Xmm(x) => self.asm.movq_xr(x, r),
2147            Loc::Reg(dst) => self.asm.mov_rr(dst, r),
2148            Loc::Frame => self.asm.mov_mr(BASE, (s as i32) * 8, r),
2149        }
2150    }
2151
2152    /// Materialize slot `s` into a register usable as an operand, preferring its
2153    /// resident register (no move) and falling back to scratch `scratch`. Slot
2154    /// must be INT-class or frame-resident (an XMM-resident slot would be a
2155    /// classification bug — caught by `debug_assert`).
2156    fn operand(&mut self, s: Slot, scratch: Reg) -> Reg {
2157        match self.loc[s as usize] {
2158            Loc::Reg(r) => r,
2159            Loc::Frame => {
2160                self.asm.mov_rm(scratch, BASE, (s as i32) * 8);
2161                scratch
2162            }
2163            Loc::Xmm(_) => {
2164                debug_assert!(false, "int operand on an XMM-resident slot {s}");
2165                self.asm.mov_rm(scratch, BASE, (s as i32) * 8);
2166                scratch
2167            }
2168        }
2169    }
2170
2171    /// Load f64 slot `s` into XMM register `x`.
2172    fn fload(&mut self, x: Xmm, s: Slot) {
2173        match self.loc[s as usize] {
2174            Loc::Xmm(src) => self.asm.movsd_rr(x, src),
2175            Loc::Frame => self.asm.movsd_rm(x, BASE, (s as i32) * 8),
2176            Loc::Reg(r) => self.asm.movq_xr(x, r), // a Mixed slot can never be here; defensive bit-copy.
2177        }
2178    }
2179
2180    /// Store XMM register `x` into f64 slot `s`.
2181    fn fstore(&mut self, s: Slot, x: Xmm) {
2182        match self.loc[s as usize] {
2183            Loc::Xmm(dst) => self.asm.movsd_rr(dst, x),
2184            Loc::Frame => self.asm.movsd_mr(BASE, (s as i32) * 8, x),
2185            Loc::Reg(r) => self.asm.movq_rx(r, x), // defensive (Mixed never lands here).
2186        }
2187    }
2188
2189    /// Materialize f64 slot `s` into an XMM operand, preferring its resident XMM
2190    /// register and falling back to scratch `scratch`.
2191    fn foperand(&mut self, s: Slot, scratch: Xmm) -> Xmm {
2192        match self.loc[s as usize] {
2193            Loc::Xmm(x) => x,
2194            Loc::Frame => {
2195                self.asm.movsd_rm(scratch, BASE, (s as i32) * 8);
2196                scratch
2197            }
2198            Loc::Reg(r) => {
2199                self.asm.movq_xr(scratch, r);
2200                scratch
2201            }
2202        }
2203    }
2204}
2205
2206/// Compile a region of micro-ops into ONE contiguous register-allocated x86-64
2207/// function, callable through the [`crate::buffer::JitChain`] ABI. Returns
2208/// `None` (caller falls back to the stencil tier) when the region contains an
2209/// unsupported op or has no terminating `Return`/`Jump`.
2210///
2211/// A REGION never contains a call, so this gates on the call-free `supported`
2212/// subset and emits no self-call machinery.
2213///
2214/// `live_out` names the frame slots the caller reads after the chain returns
2215/// (the VM's write-back registers, a region-return flag and value). Every exit
2216/// flushes the resident-written slots to the frame, so a slot named here must
2217/// hold its step-semantics value at every exit, and no rewrite may give it a
2218/// value the program's path to that exit never assigned.
2219pub fn compile_region_regalloc(
2220    ops: &[MicroOp],
2221    shared_status: Option<std::sync::Arc<AtomicI64>>,
2222    live_out: &[Slot],
2223) -> Option<CompiledChain> {
2224    compile_impl(ops, shared_status, false, 0, None, live_out)
2225}
2226
2227/// Compile a PRECISE REGION — the in-place-array-mutation shape that ALSO does a
2228/// reallocating `ArrPush` (the fannkuch permutation rebuild, the graph_bfs BFS
2229/// frontier) — into ONE contiguous register-allocated x86-64 region with PRECISE
2230/// deopt. Returns `None` (caller falls back to the per-piece precise stencil
2231/// tier) on any unsupported op or a missing terminator.
2232///
2233/// A precise region is the keystone Wave 13 (`ArrPush` in NON-precise regions)
2234/// and Wave 15 (PRECISE deopt for in-place-mutating recursion) each handled HALF
2235/// of: a `ListPush` that REALLOCS the pinned buffer coexisting with an in-place
2236/// `SetIndex` whose replay-from-head would double-apply. Under the classic
2237/// discard-replay deopt the truncate rolls the pushes back but the in-place
2238/// write persists, so the region must instead resume AT the faulting op (no
2239/// replay). [`compile_region_regalloc`] handles the reallocating push (the
2240/// helper refreshes the pinned ptr/len in the frame after a possible realloc),
2241/// but only with the CLASSIC deopt; this entry adds the per-op PRECISE deopt
2242/// codes so the push+SetIndex region is sound.
2243///
2244/// SOUNDNESS of the deopt resume (no double-apply, grown-array materialization):
2245/// every checked op's side exit stores its encoded resume pc `(pc << 2) | 3`
2246/// (depth in the high bits) through the shared status cell and the precise
2247/// epilogue FLUSHES every resident-written scalar to its frame slot — so the
2248/// VM's region precise resume reads each scalar from the frame and re-boxes it
2249/// by kind. The grown array needs NO materialization step: the push helper grew
2250/// the `Vec` IN PLACE inside the same `Rc<RefCell<…>>` the VM register still
2251/// holds, so the VM keeps that register's live value (the precise re-box kind is
2252/// `None` for a pinned array) and it already reflects the post-push buffer +
2253/// length. The resume pc is AFTER the push, so the bytecode never re-runs it —
2254/// no double-apply, no lost appended element. (The VM's per-array entry snapshot
2255/// / truncate rollback is gated on a CLASSIC `Deopt`, never a precise `DeoptAt`,
2256/// so completed pushes stand.)
2257///
2258/// `deopt_codes` is the per-op resume table the region adapter built (parallel
2259/// to `ops`): a plain `1` keeps the op on the ordinary deopt terminal; any other
2260/// value is the precise tag emitted on that op's side exit. `depth_addr` is the
2261/// live-depth cell whose value rides the resume tag's high 32 bits. `live_out`
2262/// is as for [`compile_region_regalloc`].
2263pub fn compile_region_regalloc_precise(
2264    ops: &[MicroOp],
2265    shared_status: Option<std::sync::Arc<AtomicI64>>,
2266    depth_addr: i64,
2267    deopt_codes: &[i64],
2268    live_out: &[Slot],
2269) -> Option<CompiledChain> {
2270    if deopt_codes.len() != ops.len() {
2271        return None;
2272    }
2273    // A precise region always needs the status channel — every checked op's side
2274    // exit stores its tagged resume value through it.
2275    if shared_status.is_none() {
2276        return None;
2277    }
2278    compile_impl(ops, shared_status, false, depth_addr, Some(deopt_codes), live_out)
2279}
2280
2281/// Compile a recursive FUNCTION's micro-op stream into ONE contiguous
2282/// register-allocated x86-64 function — including its DIRECT self-calls
2283/// (`CallSelf`/`CallSelfCopy`) — callable through the [`crate::buffer::JitChain`]
2284/// ABI. Returns `None` (caller falls back to the per-piece stencil tier) on any
2285/// unsupported op (a cross-function `Call`, list/map ops, byte arrays, …) or a
2286/// missing terminator.
2287///
2288/// The self-call is a REAL SysV `call` to this same chain's entry. The entry
2289/// address is unknown until the code is mapped, so it rides an `Arc<AtomicI64>`
2290/// ENTRY CELL whose address is baked into every call site (`mov rax,[cell];
2291/// call rax`) and which is written with `chain.base()` AFTER mapping — mirroring
2292/// `logos_stencil_call_self`'s patched-entry word (an unpatched `0` deopts). The
2293/// cell is kept alive by the returned [`CompiledChain`].
2294///
2295/// `depth_addr` is the live-depth cell's address (the caller's `ctx.depth`),
2296/// matching the function tier's wiring; the self-call increments/decrements it
2297/// and side-exits (status = 5) at `SELF_CALL_DEPTH_LIMIT`.
2298pub fn compile_function_regalloc(
2299    ops: &[MicroOp],
2300    shared_status: Option<std::sync::Arc<AtomicI64>>,
2301    depth_addr: i64,
2302) -> Option<CompiledChain> {
2303    // A function with no self-call is just a region; route it through the
2304    // call-free path (no entry cell, no spill machinery) for uniformity.
2305    let has_self_call = ops
2306        .iter()
2307        .any(|op| matches!(op, MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }));
2308    if !has_self_call {
2309        return compile_impl(ops, shared_status, true, depth_addr, None, &[]);
2310    }
2311    // A self-call always needs the status channel (its guards write it).
2312    if shared_status.is_none() {
2313        return None;
2314    }
2315    compile_impl(ops, shared_status, true, depth_addr, None, &[])
2316}
2317
2318/// Compile a LIST-PARAMETER recursive FUNCTION — one that mutates a
2319/// SHARED pinned array in place and may self-call — into ONE contiguous
2320/// register-allocated x86-64 function with PRECISE deopt. Returns `None`
2321/// (caller falls back to the per-piece stencil tier) on any unsupported op.
2322///
2323/// Where [`compile_function_regalloc`] uses CLASSIC deopt (a side exit replays
2324/// the whole function from its boundary args — sound only when every effect is
2325/// confined to the private frame, the scalar mode-A case), a list-param
2326/// function's in-place array writes land in SHARED state, so a replay would
2327/// DOUBLE-APPLY them. This entry instead emits PRECISE deopt: every checked op
2328/// and the self-call's guards side-exit through the shared status cell with the
2329/// op's ENCODED resume value (`(bytecode_pc << 2) | 3 | (depth << 32)`), exactly
2330/// as `logos_stencil_deopt_at` / `logos_stencil_call_precise` do, so the VM
2331/// materializes the native call chain and resumes interpreting AT the faulting
2332/// op — every prior in-place mutation intact, never re-applied.
2333///
2334/// `deopt_codes` is the per-op resume table the function adapter built (parallel
2335/// to `ops`): a plain `1` keeps the op on the ordinary deopt terminal; any other
2336/// value is the precise tag emitted on that op's side exit.
2337///
2338/// SOUNDNESS: the precise contract requires that on a side exit the native
2339/// frame mirror the tree-walker's full register state. The backend therefore
2340/// keeps every precise-path machinery slot (the plant window/resume/dst, the pin
2341/// triples, the disjoint callee window) FRAME-RESIDENT, every `ListTriple`
2342/// HANDLE slot frame-resident (the helper reads/writes the frame), and FLUSHES
2343/// every resident-written VM register to its frame slot at every precise side
2344/// exit (so `materialize` reads the correct value). All slots at or above the
2345/// function's register count `rc` are precise-path machinery and stay frame-resident.
2346pub fn compile_function_regalloc_precise(
2347    ops: &[MicroOp],
2348    shared_status: Option<std::sync::Arc<AtomicI64>>,
2349    depth_addr: i64,
2350    deopt_codes: &[i64],
2351) -> Option<CompiledChain> {
2352    if deopt_codes.len() != ops.len() {
2353        return None;
2354    }
2355    // A precise function always needs the status channel (its checked ops and
2356    // self-call guards write the tagged value through it).
2357    if shared_status.is_none() {
2358        return None;
2359    }
2360    compile_impl(ops, shared_status, true, depth_addr, Some(deopt_codes), &[])
2361}
2362
2363/// The VM register count `rc` of a precise function, INFERRED from the
2364/// op stream: the prologue's plant-window invalidation is `LoadConst { dst:
2365/// rc + 2, value: -1 }` (the adapter's first micro). Every slot `>= rc` is
2366/// precise-path machinery (plant slots, pin triples, the disjoint callee window) and
2367/// must stay frame-resident. Returns `None` if the stream does not open with
2368/// that recognizable prologue (then the precise path declines and the caller
2369/// falls back).
2370fn infer_mode_b_rc(ops: &[MicroOp]) -> Option<u16> {
2371    match ops.first() {
2372        Some(MicroOp::LoadConst { dst, value: -1 }) if *dst >= 2 => Some(dst - 2),
2373        _ => None,
2374    }
2375}
2376
2377/// The shared codegen core for both the region and the function backends.
2378/// `is_function` selects the op-support gate ([`supported_function`] adds the
2379/// self-call ops); `depth_addr` is the live-depth cell (function backend only).
2380/// `live_out` is the region's caller-read frame slots; a function's frame dies
2381/// with its return, so the function entries pass none.
2382fn compile_impl(
2383    ops: &[MicroOp],
2384    shared_status: Option<std::sync::Arc<AtomicI64>>,
2385    is_function: bool,
2386    depth_addr: i64,
2387    precise: Option<&[i64]>,
2388    live_out: &[Slot],
2389) -> Option<CompiledChain> {
2390    if ops.is_empty() {
2391        return None;
2392    }
2393    // SIMD: a recognized pure element-wise map region compiles to a 2-wide packed
2394    // loop. It has NO deopt paths (the recognizer requires `checked:false` Oracle-
2395    // proven-in-bounds accesses and pure float arithmetic), so it runs to
2396    // Completed and the VM resumes at the stored exit_pc — independent of the
2397    // `precise` mode-B machinery. Bit-identical to the scalar region (each lane is
2398    // the scalar op on that index); the differential gate certifies it. Default
2399    // OFF (`LOGOS_SIMD=1`).
2400    if !is_function && simd_enabled() {
2401        if let Some(plan) = crate::vectorize::recognize_elementwise_map(ops) {
2402            if let Some(code) =
2403                crate::vectorize::emit_map_kernel(&ops[plan.body_start..plan.body_end], &plan)
2404            {
2405                let chain = JitChain::from_code(&code, ops.len()).ok()?;
2406                return Some(CompiledChain::from_chain(chain, None));
2407            }
2408        }
2409    }
2410    // The PRECISE mode-B FUNCTION path needs the function's VM register count
2411    // `rc` to know which slots are machinery (the plant window/resume/dst, pin
2412    // triples, the disjoint callee window — every slot `>= rc`). Infer it from
2413    // the adapter's prologue micro; decline (fall back) if the stream does not
2414    // open with it. A precise REGION has NO mode-B machinery (no self-call plant
2415    // window — its in-place mutation + reallocating push flow through the
2416    // enclosing frame's pinned arrays, and the precise epilogue flushes every
2417    // resident-written scalar back to the frame for materialization), so it
2418    // leaves `mode_b_rc = None` and its scalars are register-allocated freely.
2419    // The classic paths also leave `mode_b_rc = None`.
2420    let mode_b_rc: Option<u16> = if precise.is_some() && is_function {
2421        Some(infer_mode_b_rc(ops)?)
2422    } else {
2423        None
2424    };
2425    let gate: fn(&MicroOp) -> bool = match (is_function, precise.is_some()) {
2426        (true, true) => supported_function_precise,
2427        (true, false) => supported_function,
2428        // Precise regions use the same Call/Host/list-machinery lowering as
2429        // precise functions. The mode-B frame layout above remains
2430        // function-only; sharing this capability gate merely prevents an
2431        // already-supported precise region from silently falling back to the
2432        // per-piece stencil tier.
2433        (false, true) => supported_function_precise,
2434        (false, false) => supported,
2435    };
2436    if !ops.iter().all(gate)
2437        || ops.iter().any(|op| {
2438            matches!(op,
2439            MicroOp::Host { src, count, .. } if src.checked_add(*count).is_none())
2440        })
2441    {
2442        return None;
2443    }
2444    if !matches!(
2445        ops.last(),
2446        Some(MicroOp::Return { .. }) | Some(MicroOp::Jump { .. })
2447    ) {
2448        return None;
2449    }
2450
2451    let has_self_call = ops
2452        .iter()
2453        .any(|op| matches!(op, MicroOp::CallSelf { .. } | MicroOp::CallSelfCopy { .. }));
2454    // The mode-B precise self-call is a REAL SysV call through the entry table.
2455    let has_precise_call = ops.iter().any(|op| matches!(op, MicroOp::Call { .. }));
2456
2457    // A list-mutation / list-machinery op (`ArrPush`/`ListClear`/`NewList`/
2458    // `ListTriple`) is a HELPER CALL into the JIT runtime — a real SysV `call`,
2459    // so it clobbers the caller-saved registers exactly like a self-call and
2460    // needs the same spill/reload machinery (the `gp_volatile`/`xmm_volatile`
2461    // lists + the stack-alignment pad). Treat ANY such helper call, not just a
2462    // self-call, as requiring the call ABI.
2463    let has_list_call = ops.iter().any(|op| {
2464        matches!(
2465            op,
2466            MicroOp::NewList { .. }
2467                | MicroOp::ArrPush { .. }
2468                | MicroOp::ListClear { .. }
2469                | MicroOp::ListTriple { .. }
2470                | MicroOp::StrAppend { .. }
2471                | MicroOp::Host { .. }
2472        )
2473    });
2474    let has_call = has_self_call || has_list_call || has_precise_call;
2475
2476    // The vec/ptr/len handle TRIPLE of every list-mutation op MUST stay
2477    // FRAME-resident: the helper reads `frame[vec_slot]` and WRITES
2478    // `frame[ptr_slot]`/`frame[len_slot]` (refreshing them after a possible
2479    // realloc). A register-resident handle slot would be stale after the call
2480    // (the helper updates the frame, not the register) and would feed a wrong
2481    // pointer/length into the next access — the exact realloc-coherence trap.
2482    // Forcing the triple frame-resident makes the helper's frame writes the
2483    // single source of truth, so the next access reads the fresh pointer.
2484    let mut force_frame_set: std::collections::HashSet<Slot> = std::collections::HashSet::new();
2485    for op in ops {
2486        match *op {
2487            // `NewList` allocates a registry-owned fresh buffer and WRITES its
2488            // vec/ptr/len triple through the frame (the helper indexes the frame);
2489            // the same realloc-coherence rule as `ArrPush` requires the triple be
2490            // frame-resident so the helper's writes are the single source of
2491            // truth and every later push/load reads the fresh pointer/length.
2492            MicroOp::NewList {
2493                vec_slot,
2494                ptr_slot,
2495                len_slot,
2496                ..
2497            }
2498            | MicroOp::ArrPush {
2499                vec_slot,
2500                ptr_slot,
2501                len_slot,
2502                ..
2503            }
2504            | MicroOp::ListClear {
2505                vec_slot,
2506                ptr_slot,
2507                len_slot,
2508                ..
2509            } => {
2510                force_frame_set.insert(vec_slot);
2511                force_frame_set.insert(ptr_slot);
2512                force_frame_set.insert(len_slot);
2513            }
2514            // A triple-plant's HANDLE slot is read by the helper FROM THE FRAME,
2515            // and its vec/ptr/len triple is WRITTEN to the frame — all four must
2516            // be frame-resident so the helper's view and the next access agree.
2517            MicroOp::ListTriple {
2518                handle_slot,
2519                vec_slot,
2520                ptr_slot,
2521                len_slot,
2522                ..
2523            } => {
2524                force_frame_set.insert(handle_slot);
2525                force_frame_set.insert(vec_slot);
2526                force_frame_set.insert(ptr_slot);
2527                force_frame_set.insert(len_slot);
2528            }
2529            // The str-append's handle slot (a `*mut Value`) is read by the helper
2530            // FROM THE FRAME, so it must stay frame-resident (a register-resident
2531            // handle would not be seen by the SysV call). The accumulator itself
2532            // lives in the VM register file, off-frame — nothing else here needs
2533            // forcing.
2534            MicroOp::StrAppend {
2535                text_handle_slot, ..
2536            } => {
2537                force_frame_set.insert(text_handle_slot);
2538            }
2539            // Host helpers read their input window and write dst through the frame.
2540            MicroOp::Host {
2541                dst, src, count, ..
2542            } => {
2543                force_frame_set.insert(dst);
2544                force_frame_set.extend(src..src + count);
2545            }
2546            _ => {}
2547        }
2548    }
2549
2550    // The callee-window staging slots (`args_start..`) of a self-call MUST stay
2551    // FRAME-resident: the callee reads its parameters from its own frame window,
2552    // and the codegen stages them by writing those frame cells. A `CallSelfCopy`
2553    // also carries `frame_size` (the callee's full frame, = limit_slot + 1); the
2554    // window therefore spans `args_start .. args_start + frame_size`. Force every
2555    // slot at or above the lowest such window base to the frame.
2556    let mut force_frame_above: Option<u16> = None;
2557    for op in ops {
2558        let args_start = match *op {
2559            MicroOp::CallSelf { args_start, .. }
2560            | MicroOp::CallSelfCopy { args_start, .. }
2561            | MicroOp::Call { args_start, .. } => args_start,
2562            _ => continue,
2563        };
2564        // The callee window starts at args_start; everything at/above it stages
2565        // a callee frame slot and must stay frame-resident.
2566        force_frame_above = Some(force_frame_above.map_or(args_start, |a| a.min(args_start)));
2567    }
2568    // PRECISE (mode-B): EVERY slot at or above the VM register count `rc` is
2569    // machinery — the plant window/resume/dst, the pin triples and the disjoint
2570    // callee window. All must stay FRAME-resident: the precise-deopt walk
2571    // (`ChainFn::materialize`) reads each ancestor frame's plant slots and pin
2572    // handles straight from the frame, so a register copy would be stale. This
2573    // subsumes (and is stricter than) the per-call window forcing above.
2574    if let Some(rc) = mode_b_rc {
2575        force_frame_above = Some(force_frame_above.map_or(rc, |a| a.min(rc)));
2576    }
2577
2578    // Whether the program has any checked op needing a deopt channel (divisor
2579    // check, a checked array bounds check, or a self-call guard). When one is
2580    // present but the caller passed no shared cell, allocate a private one —
2581    // exactly what the stencil compilers do (`has_checked` ⇒ `unwrap_or_else`).
2582    let needs_status = ops.iter().any(needs_deopt);
2583    let status: Option<std::sync::Arc<AtomicI64>> = if needs_status {
2584        Some(shared_status.unwrap_or_else(|| std::sync::Arc::new(AtomicI64::new(0))))
2585    } else {
2586        shared_status
2587    };
2588
2589    // The largest slot index — sizes every per-slot vector below (loc / written
2590    // / liveness). It covers each self-call window's full extent because the
2591    // frame indexing allocates against it.
2592    let max_slot = max_slot_of(ops);
2593
2594    // LS1 — linear-scan register allocation gate. Enabled for NO-CALL classic
2595    // regions (the precise mode-B path is excluded). A CHECKED op (bounds/divisor)
2596    // is allowed: its classic side-exit replays from the head with prefix-
2597    // idempotence (native_tier.rs), so the deopt flush must hold each slot's value
2598    // AT the faulting op. Linear scan keeps that true by WRITING THROUGH every
2599    // REUSED slot to its frame home on each write (so the shared epilogue, which
2600    // skips it, finds the current value in the frame); NON-reused slots keep a
2601    // fixed register for their whole range and are flushed by the epilogue from
2602    // that register. Register reuse is confined to straight-line gaps
2603    // (`linscan_assign`), so no reassignment crosses a control join.
2604    let linscan_active = linear_scan_enabled() && !has_call && precise.is_none();
2605
2606    // Backward liveness, computed ONCE when the region has a SysV call and reused
2607    // by both the call-weight ranking (below) and the per-call-site spill-elision
2608    // pass (further down). `None` for a call-free region: there are no calls to
2609    // survive, so no bonus and no spill machinery. Computing it before the
2610    // ranking is what lets the ranking SEE which slots are live across each call.
2611    let live_after: Option<Vec<Vec<bool>>> = has_call.then(|| liveness_after(ops, max_slot));
2612
2613    // Rank slots by LOOP-WEIGHTED reference count, with CALL-LOCALITY as a
2614    // SECONDARY tie-break; assign the hottest to physical registers. A raw count
2615    // under-prices loop-carried values: a slot touched once per iteration of a
2616    // hot loop costs a memory round-trip on EVERY iteration, whereas a slot
2617    // touched many times in straight-line setup code costs a round-trip only that
2618    // once. The linear-scan loop weight (each reference at loop depth `d` worth
2619    // `LOOP_WEIGHT_BASE^d`) closes this so a back-edge value (nbody's dx/dy/dist,
2620    // mandelbrot's zr/zi) outranks colder slots and STAYS RESIDENT across
2621    // iterations. This PRIMARY key — and the resident-vs-spilled boundary it
2622    // induces — is identical to the pre-Fix-1 ranking.
2623    //
2624    // The call-weight breaks TIES among equal-primary-weight slots toward those
2625    // LIVE ACROSS a SysV call. Combined with the `has_call` pool order
2626    // (callee-saved first), a call-survivor wins a callee-saved register over a
2627    // call-dead slot of equal weight and pays NO per-call spill/reload — only a
2628    // one-time prologue push/pop, the dominant cost in a recursion-heavy loop
2629    // (fib / binary_trees / coins). Because it is only a tie-break it can never
2630    // evict a hotter loop slot, so it adds the steering without the spill-boundary
2631    // perturbation an additive bonus would cause.
2632    //
2633    // Ranking is semantically inert: it changes only WHICH register a resident
2634    // slot occupies (and, on a primary-key tie, which equally-cold slot spills). A
2635    // slot still lives in exactly one place for the whole function and its value
2636    // never changes, so the result is bit-identical to any other ranking.
2637    //
2638    // The base/cap mirror the per-piece tier's `select_pins` loop weight
2639    // (`BASE=16`, depth capped at 4) so both backends rank loop-carried slots on
2640    // the SAME frequency model. Every weight is `u64` and saturating, so even a
2641    // pathologically deep/large region cannot overflow the ranking key (a
2642    // saturated tie falls back to the call-survival then deterministic slot-index
2643    // order).
2644    const LOOP_WEIGHT_BASE: u64 = 16;
2645    const LOOP_DEPTH_CAP: u32 = 4;
2646    const CALL_WEIGHT: u64 = 4;
2647    // A zero call-weight zeroes the secondary key, reducing `rank_slots` to the
2648    // pure loop-weighted ranking — the kill-switch is exactly pre-Fix-1 behavior.
2649    let call_weight = if call_weight_enabled() {
2650        CALL_WEIGHT
2651    } else {
2652        0
2653    };
2654    let (order, _) = rank_slots(
2655        ops,
2656        LOOP_WEIGHT_BASE,
2657        LOOP_DEPTH_CAP,
2658        call_weight,
2659        live_after.as_deref(),
2660    );
2661
2662    // Classify each slot. INT-class slots compete for GP registers, FLOAT-class
2663    // slots for XMM registers; MIXED slots (used by both classes) stay frame-
2664    // resident. The two pools are disjoint, so the assignment is sound: a slot
2665    // is always in exactly one place, of the right class, for the whole function.
2666    let class = classify_slots(ops, max_slot);
2667
2668    // Register-pool ORDER. Pool order is semantically inert — it only decides
2669    // WHICH physical register a slot occupies, never where (a slot is still in
2670    // exactly one place for the whole function), so every ordering is
2671    // bit-identical. But it changes the prologue/epilogue and per-call spill
2672    // bill, so we order by what is cheapest for THIS region's call shape:
2673    //
2674    //  - CALL-FREE region: a caller-saved register costs NOTHING (no prologue
2675    //    push/pop, no spill — nothing clobbers it). A callee-saved register
2676    //    costs a prologue `push` + epilogue `pop` (and a stack-alignment pad
2677    //    risk). So prefer CALLER-SAVED first: a hot scalar loop (primes,
2678    //    pi_leibniz, fib_iterative, the matrix/histogram inner loops) pays no
2679    //    callee-save prologue/epilogue at all when it fits the 6 caller-saved
2680    //    GP regs.
2681    //  - region/function WITH a SysV call (self-call or list-mutation helper):
2682    //    a caller-saved resident is clobbered by every call, so it is
2683    //    spilled+reloaded around each one (gp_volatile below) — a pair of
2684    //    memory ops per call. A callee-saved resident survives the call for the
2685    //    one-time prologue/epilogue push/pop. In a call-heavy loop (fib /
2686    //    binary_trees / coins recursion) the per-call spill pair dominates the
2687    //    one-time save, so prefer CALLEE-SAVED first.
2688    let mut pool: Vec<Reg> = Vec::new();
2689    if has_call {
2690        pool.extend_from_slice(&CALLEE_SAVED);
2691        pool.extend_from_slice(&CALLER_SAVED);
2692    } else {
2693        pool.extend_from_slice(&CALLER_SAVED);
2694        pool.extend_from_slice(&CALLEE_SAVED);
2695    }
2696
2697    // SCALED-INDEX CSE register reservation (Wave 26). A region with array
2698    // accesses RESERVES up to two CALLER-SAVED registers OUT of the resident
2699    // pool — held for the run-shared `im1 = idx - 1` (and, with the second, its
2700    // scaled byte offset `im1 * 8`). Reserving up front (rather than scavenging a
2701    // register the scan happened to leave free) is what makes the CSE fire in the
2702    // HIGH-PRESSURE loops it targets — nbody/matrix touch many co-indexed
2703    // arrays, whose ptr/len handle slots would otherwise consume every GP
2704    // register and leave none free. The cost is that the one or two
2705    // LOWEST-ranked int slots spill to the frame instead of a register — a good
2706    // trade in an array-heavy loop, where eliminating the per-access index
2707    // recompute across N arrays dominates one extra frame round-trip on a cold
2708    // scalar. CALLER-SAVED registers need no prologue save, and the cache is
2709    // dropped across every SysV call, so a call's clobber of them is harmless.
2710    // The reserved registers are removed from `pool`, so the linear scan never
2711    // assigns them to a resident — they are exclusively the CSE cache's.
2712    // Reserve ONLY when the region actually has a reusable run — two or more
2713    // array accesses sharing one index slot with no intervening invalidation.
2714    // Without a shared-index run the CSE never fires, so reserving a register
2715    // (spilling a hot scalar) would be a pure cost — exactly the matrix_mult
2716    // inner loop, whose three accesses use THREE different indices (`i*n+k`,
2717    // `k*n+j`, `i*n+j`) and so must NOT pay the reservation. The static check
2718    // mirrors the runtime cache invalidation precisely.
2719    let (off_im1_reg, off_scaled_reg) = if off_cse_enabled() && has_shared_index_run(ops) {
2720        // The reservable caller-saved registers still in the pool, in pool order;
2721        // take from the END so residents keep the higher-priority (earlier)
2722        // registers and only the coldest int slots lose a register.
2723        let mut reservable: Vec<Reg> = pool
2724            .iter()
2725            .copied()
2726            .filter(|r| CALLER_SAVED.contains(r))
2727            .collect();
2728        // Leave at least one register for residents when the pool can spare it;
2729        // reserve TWO only when ≥ 2 caller-saved remain beyond that margin (so
2730        // the loop's index/counter still gets a register). With a tiny pool a
2731        // single reservation (a pure array-copy loop with no other live int) is
2732        // still sound — the reserved register is the cache's alone.
2733        let want = if reservable.len() >= 3 {
2734            2
2735        } else {
2736            usize::from(!reservable.is_empty())
2737        };
2738        let mut reserved = Vec::new();
2739        for _ in 0..want {
2740            if let Some(r) = reservable.pop() {
2741                reserved.push(r);
2742            }
2743        }
2744        // Remove the reserved registers from the resident pool.
2745        pool.retain(|r| !reserved.contains(r));
2746        (reserved.first().copied(), reserved.get(1).copied())
2747    } else {
2748        (None, None)
2749    };
2750
2751    // LOOP-INVARIANT PTR/LEN HOIST register reservation (Wave 27a). Reserve
2752    // CALLEE-SAVED registers for each invariant-array plan and load the handle(s)
2753    // ONCE at the loop pre-header (`g.load(reg, slot)` copies whatever the slot's
2754    // current home holds — a register or a frame cell — so the pre-header captures
2755    // the value the OUTER context just set). Callee-saved registers SURVIVE the
2756    // SysV calls (the `ArrPush`/`ListClear` helpers, a self-call) inside the
2757    // loop, so a handle that the linear scan would otherwise put in a CALLER-saved
2758    // register — spilled + reloaded around EVERY in-loop call — instead stays live
2759    // for a one-time prologue push/pop; and a handle that would land in the FRAME
2760    // (forced by `force_frame_set`, or out of registers under pressure) avoids its
2761    // per-access reload. The reserved registers are removed from the resident pool
2762    // (so the scan never assigns them) and added to `used_callee` (prologue
2763    // save/restore), always leaving at least one callee-saved register for the
2764    // scan's own call-surviving residents.
2765    let mut used_callee: Vec<Reg> = Vec::new();
2766    let mut hoists: Vec<HoistEntry> = Vec::new();
2767    if ptr_hoist_enabled() {
2768        // The callee-saved registers still in the pool, reservable for hoisting.
2769        // We take from the FRONT (callee-saved lead the pool in a call-heavy
2770        // region) but always leave AT LEAST ONE callee-saved register for the
2771        // scan's call-surviving residents — a loop-carried scalar live across the
2772        // push wants a callee-saved home too. With fewer than two callee-saved
2773        // available, no hoist is reserved (the trade would starve the loop).
2774        let mut reservable_callee: Vec<Reg> = pool
2775            .iter()
2776            .copied()
2777            .filter(|r| CALLEE_SAVED.contains(r))
2778            .collect();
2779        let mut reserved_for_hoist: Vec<Reg> = Vec::new();
2780        let plans = loop_invariant_array_hoists(ops);
2781        for plan in plans {
2782            // Hoist only when it amortizes: either the array is accessed at least
2783            // twice in the span (each access otherwise reloads/uses the handle), or
2784            // the span contains a SysV call (a register-resident handle is then
2785            // spilled+reloaded around every call — a callee-saved hoist survives
2786            // it). A single un-called access has nothing to amortize → skip.
2787            let span_calls = ops[plan.head..=plan.back].iter().any(is_sysv_call);
2788            if plan.accesses < 2 && !span_calls {
2789                continue;
2790            }
2791            let need = 1 + usize::from(plan.needs_len);
2792            // Reserve from the available callee-saved, leaving one for the scan.
2793            if reservable_callee.len().saturating_sub(need) < 1 {
2794                continue;
2795            }
2796            let ptr_reg = reservable_callee.remove(0);
2797            reserved_for_hoist.push(ptr_reg);
2798            let len_reg = if plan.needs_len {
2799                let r = reservable_callee.remove(0);
2800                reserved_for_hoist.push(r);
2801                Some(r)
2802            } else {
2803                None
2804            };
2805            hoists.push(HoistEntry {
2806                plan,
2807                ptr_reg,
2808                len_reg,
2809            });
2810        }
2811        // Remove the reserved registers from the resident pool and record them for
2812        // the prologue/epilogue callee-saved save (deterministic order).
2813        pool.retain(|r| !reserved_for_hoist.contains(r));
2814        for r in reserved_for_hoist {
2815            used_callee.push(r);
2816        }
2817    }
2818
2819    let mut loc = vec![Loc::Frame; max_slot + 1];
2820    {
2821        let mut pi = 0usize; // GP pool cursor
2822        let mut fi = 0usize; // XMM pool cursor
2823        for (s, _) in &order {
2824            // Force callee-window staging slots to the frame (the callee reads them
2825            // from its frame; a register-resident window slot would never reach it).
2826            if let Some(thresh) = force_frame_above {
2827                if *s >= thresh {
2828                    continue;
2829                }
2830            }
2831            // Force list-mutation handle slots (vec/ptr/len) to the frame — the
2832            // helper reads/writes them there, so a register copy would go stale.
2833            if force_frame_set.contains(s) {
2834                continue;
2835            }
2836            match class[*s as usize] {
2837                Class::Int => {
2838                    if pi >= pool.len() {
2839                        continue;
2840                    }
2841                    let r = pool[pi];
2842                    pi += 1;
2843                    loc[*s as usize] = Loc::Reg(r);
2844                    if CALLEE_SAVED.contains(&r) {
2845                        used_callee.push(r);
2846                    }
2847                }
2848                Class::Float => {
2849                    if fi >= FLOAT_REGS.len() {
2850                        continue;
2851                    }
2852                    loc[*s as usize] = Loc::Xmm(FLOAT_REGS[fi]);
2853                    fi += 1;
2854                }
2855                Class::Mixed => {} // frame-resident only.
2856            }
2857        }
2858    }
2859
2860    // LS1 — linear-scan register REUSE for FLOAT slots only. The integer side
2861    // keeps the classic per-slot assignment above plus its GP-only optimizations
2862    // (scaled-index CSE, ptr/const hoists), which the XMM file never touches — so
2863    // the two compose. This OVERRIDES the float locs with a live-range allocation
2864    // that reuses an XMM register across disjoint float temporaries, reclaiming
2865    // the frame spills the whole-region model leaves under XMM pressure (nbody's
2866    // 47 floats / 14 registers / 33 spilled — but only ~10 live at once).
2867    if linscan_active {
2868        let gp_all: Vec<Reg> = CALLER_SAVED
2869            .iter()
2870            .chain(CALLEE_SAVED.iter())
2871            .copied()
2872            .collect();
2873        let scan = linscan_assign(ops, max_slot, &class, &gp_all, &FLOAT_REGS);
2874        for s in 0..=max_slot {
2875            if class[s] == Class::Float {
2876                let forced = force_frame_set.contains(&(s as u16))
2877                    || force_frame_above.is_some_and(|t| s as u16 >= t);
2878                loc[s] = if forced { Loc::Frame } else { scan[s] };
2879            }
2880        }
2881    }
2882
2883    // LS1 per-point schedule: each slot's loop-aware [start,end] and whether its
2884    // register is SHARED with another slot. A shared-register slot is WRITTEN
2885    // THROUGH to its frame home on each write and set `Frame` at its range end —
2886    // because at any region exit (or mid-region deopt) the physical register may
2887    // hold a DIFFERENT member of the share-group, so the slot's authoritative
2888    // value must live in the frame, not be read back from the register by the
2889    // flush. A slot in a register all to itself (the common case) needs neither:
2890    // the register always holds exactly its value, so the exit flush is correct.
2891    // Empty unless `linscan_active`.
2892    let (ls_range, ls_shared): (Vec<Option<(usize, usize)>>, Vec<bool>) = if linscan_active {
2893        let ranges = live_ranges(ops, max_slot);
2894        let mut shared = vec![false; max_slot + 1];
2895        for a in 0..=max_slot {
2896            if matches!(loc[a], Loc::Frame) || ranges[a].is_none() {
2897                continue;
2898            }
2899            for b in 0..=max_slot {
2900                if a != b && loc[b] == loc[a] && ranges[b].is_some() {
2901                    shared[a] = true;
2902                    break;
2903                }
2904            }
2905        }
2906        (ranges, shared)
2907    } else {
2908        (Vec::new(), Vec::new())
2909    };
2910
2911    if linscan_active && std::env::var_os("LOGOS_DUMP_LS").is_some() {
2912        eprintln!("LS-REGION ops={} max_slot={}", ops.len(), max_slot);
2913        for (i, op) in ops.iter().enumerate() {
2914            eprintln!("  op{i:>3}: {op:?}");
2915        }
2916        for s in 0..=max_slot {
2917            if let Some((a, b)) = ls_range[s] {
2918                eprintln!(
2919                    "  slot{s:>3} [{a:>3},{b:>3}] {:?} shared={}",
2920                    loc[s], ls_shared[s]
2921                );
2922            }
2923        }
2924    }
2925
2926    // Diagnostic class+placement histogram (LOGOS_DUMP_CLASS=1). Only for regions
2927    // that touch a float, so the float-cluster investigation isn't drowned in
2928    // scalar regions. Reports how many Float-class slots actually won an XMM
2929    // register vs spilled to the frame under pressure, and which slots are Mixed
2930    // (frame-resident class-ambiguous) — the empirical signal that decides whether
2931    // the float wall is a Mixed-class problem (K1) or an XMM-pressure problem (K2).
2932    if dump_class_enabled() {
2933        let (mut n_int, mut n_float, mut n_mixed) = (0usize, 0usize, 0usize);
2934        let (mut f_xmm, mut f_frame) = (0usize, 0usize);
2935        let mut mixed_slots: Vec<u16> = Vec::new();
2936        for s in 0..=max_slot {
2937            match class[s] {
2938                Class::Int => n_int += 1,
2939                Class::Float => {
2940                    n_float += 1;
2941                    match loc[s] {
2942                        Loc::Xmm(_) => f_xmm += 1,
2943                        _ => f_frame += 1,
2944                    }
2945                }
2946                Class::Mixed => {
2947                    n_mixed += 1;
2948                    mixed_slots.push(s as u16);
2949                }
2950            }
2951        }
2952        // Max SIMULTANEOUSLY-LIVE float/int slots = the true register pressure in
2953        // the live-interval sense. If max-live-float <= 14 (the XMM pool), a
2954        // linear-scan allocator that reuses a register once a slot's range ends
2955        // fits every float with ZERO spill — even though the whole-region per-slot
2956        // model spills `frame` of them. This is the number that decides whether
2957        // interval allocation is the lever.
2958        let la = liveness_after(ops, max_slot);
2959        let (mut max_live_f, mut max_live_i) = (0usize, 0usize);
2960        for row in &la {
2961            let (mut lf, mut li) = (0usize, 0usize);
2962            for s in 0..=max_slot {
2963                if s < row.len() && row[s] {
2964                    match class[s] {
2965                        Class::Float => lf += 1,
2966                        Class::Int => li += 1,
2967                        Class::Mixed => {}
2968                    }
2969                }
2970            }
2971            max_live_f = max_live_f.max(lf);
2972            max_live_i = max_live_i.max(li);
2973        }
2974        // Linear-scan SIMULATION: how many float/int slots a simple interval
2975        // allocator (the lever we'd build) would spill, given the same XMM pool
2976        // (14) and the actual GP `pool` this region has after CSE/hoist
2977        // reservations. Compare `lsF`/`lsI` against `frame=`: the gap is the spill
2978        // the whole-region per-slot model leaves on the table.
2979        let intervals = live_intervals(ops, max_slot);
2980        let ls_float = linscan_spills(&intervals, &class, Class::Float, FLOAT_REGS.len());
2981        let ls_int = linscan_spills(&intervals, &class, Class::Int, pool.len());
2982        if n_float > 0 || n_mixed > 0 {
2983            eprintln!(
2984                "DUMP-CLASS region ops={} max_slot={} int={} float={} (xmm={} frame={}) mixed={} maxLiveF={} maxLiveI={} lsF={} lsI={} mixed_slots={:?}",
2985                ops.len(), max_slot, n_int, n_float, f_xmm, f_frame, n_mixed, max_live_f, max_live_i, ls_float, ls_int, mixed_slots
2986            );
2987        }
2988    }
2989
2990    // The caller-saved residents (GP + XMM) that a SysV call CLOBBERS — a
2991    // self-call OR a list-mutation helper call both trash the caller-saved
2992    // registers per the ABI. This is the UNIVERSE; the per-call-site lists below
2993    // intersect it with each call's live-after set. Callee-saved residents
2994    // (rbx/r12/r13/r14, BASE=r15) survive a call automatically and need no spill.
2995    let (gp_volatile, xmm_volatile): (Vec<Slot>, Vec<Slot>) = if has_call {
2996        let mut gp = Vec::new();
2997        let mut xmm = Vec::new();
2998        for s in 0..=max_slot as u16 {
2999            match loc[s as usize] {
3000                Loc::Reg(r) if CALLER_SAVED.contains(&r) => gp.push(s),
3001                Loc::Xmm(_) => xmm.push(s),
3002                _ => {}
3003            }
3004        }
3005        (gp, xmm)
3006    } else {
3007        (Vec::new(), Vec::new())
3008    };
3009
3010    // Slots that are resident AND written somewhere must be flushed to the
3011    // frame on exit. (A resident read-only slot was loaded from the frame at
3012    // entry, never changed, so the frame is already correct.)
3013    let mut written: Vec<bool> = vec![false; max_slot + 1];
3014    for op in ops {
3015        if let Some(d) = dest_of(op) {
3016            written[d as usize] = true;
3017        }
3018    }
3019
3020    // PER-CALL-SITE spill liveness. A caller-saved resident is spilled+reloaded
3021    // around a call iff its value must survive the call's register clobber. That
3022    // is true exactly when the slot is either:
3023    //   - WRITTEN somewhere (so it is flushed to the frame at EVERY region exit —
3024    //     `Return` and every deopt side-exit — which the broader VM may read; its
3025    //     last-written value MUST be preserved through the clobbering call), OR
3026    //   - LIVE AFTER this call (read by some later op in the region).
3027    // A caller-saved resident that is READ-ONLY (never written) AND dead after
3028    // the call is the ONLY case we elide: its frame cell already holds the value
3029    // loaded at entry (it never changed), it is read by no later op, and being
3030    // unwritten it is never flushed at exit — so eliding its spill/reload is
3031    // bit-identical to the full-frame stencil tier (verified by the
3032    // `*_matches_stencil` post-frame differentials). This removes the redundant
3033    // spill/reload of cold read-only operands (e.g. a constant or bound consulted
3034    // only before the call) from call-heavy loops. For a non-call op the lists
3035    // are empty. When `has_call` is false the liveness pass is skipped entirely.
3036    let (call_gp, call_xmm): (Vec<Vec<Slot>>, Vec<Vec<Slot>>) =
3037        if let Some(live_after) = live_after.as_deref() {
3038            let keep = |s: Slot, la: &[bool]| -> bool {
3039                written.get(s as usize).copied().unwrap_or(true)
3040                    || la.get(s as usize).copied().unwrap_or(true)
3041            };
3042            let mut cgp: Vec<Vec<Slot>> = vec![Vec::new(); ops.len()];
3043            let mut cxmm: Vec<Vec<Slot>> = vec![Vec::new(); ops.len()];
3044            for idx in 0..ops.len() {
3045                let la = &live_after[idx];
3046                cgp[idx] = gp_volatile
3047                    .iter()
3048                    .copied()
3049                    .filter(|&s| keep(s, la))
3050                    .collect();
3051                cxmm[idx] = xmm_volatile
3052                    .iter()
3053                    .copied()
3054                    .filter(|&s| keep(s, la))
3055                    .collect();
3056            }
3057            (cgp, cxmm)
3058        } else {
3059            (Vec::new(), Vec::new())
3060        };
3061
3062    // One label per op (jump targets) plus the deopt epilogue label and the
3063    // self-call deopt-PROPAGATION (bare flush+return, no status write) label.
3064    let mut asm = Asm::new();
3065    let op_labels: Vec<LabelId> = (0..ops.len()).map(|_| asm.new_label()).collect();
3066    // The plain (classic) deopt epilogue is still needed for any precise op whose
3067    // code is the plain marker `1` (a deoptable op the adapter chose not to make
3068    // precise) and for every classic checked op.
3069    let deopt_label = if needs_status {
3070        Some(asm.new_label())
3071    } else {
3072        None
3073    };
3074    // A PROPAGATION epilogue (bare flush+return) is needed when ANY real SysV
3075    // self-call is present — the classic self-call OR the mode-B precise call —
3076    // because the inner exit code (already in the status cell) must not be
3077    // overwritten on the way out.
3078    let propagate_label = (has_self_call || has_precise_call).then(|| asm.new_label());
3079
3080    // PRECISE (mode-B) deopt machinery: a shared precise epilogue plus one
3081    // out-of-line tag-staging block per DISTINCT non-plain code (deterministic,
3082    // first-use order). Each block stages its tag in `S1` and jumps to the
3083    // epilogue, which reads the live depth, ORs it into the high 32 bits, writes
3084    // the status cell, flushes every resident-written slot, and returns. This is
3085    // the contiguous-codegen analog of the stencil tier's `ST_DEOPT_AT` family.
3086    let mut code_blocks: std::collections::HashMap<i64, LabelId> = std::collections::HashMap::new();
3087    let precise_epilogue = if precise.is_some() {
3088        Some(asm.new_label())
3089    } else {
3090        None
3091    };
3092    if let Some(codes) = precise {
3093        for &c in codes {
3094            if c != 1 {
3095                code_blocks.entry(c).or_insert_with(|| asm.new_label());
3096            }
3097        }
3098    }
3099
3100    // Stack-pointer alignment: at function entry RSP ≡ 8 (mod 16) (the caller's
3101    // `call` pushed the return address). After `push BASE` + K callee-saved
3102    // pushes, RSP ≡ 8 + 8*(1+K) (mod 16). A SysV `call` requires RSP ≡ 0 (mod
3103    // 16) at the call instruction. Pad with one 8-byte slot when (1+K) is even
3104    // so RSP is 16-aligned at every call (self-call OR list-mutation helper);
3105    // undo it in every epilogue. (No calls ⇒ no padding needed, none emitted.)
3106    let pushes = 1 + used_callee.len();
3107    let stack_pad: i32 = if has_call && pushes % 2 == 0 { 8 } else { 0 };
3108
3109    // Prologue: save callee-saved regs, move base (rdi) into r15, apply the
3110    // alignment pad, then load every resident slot from the frame.
3111    asm.push(BASE);
3112    for &r in &used_callee {
3113        asm.push(r);
3114    }
3115    asm.mov_rr(BASE, Reg::Rdi);
3116    if stack_pad != 0 {
3117        asm.sub_ri(Reg::Rsp, stack_pad);
3118    }
3119    {
3120        // Load resident slots in slot order for determinism. GP-resident slots
3121        // load via `mov`; XMM-resident (float) slots via `movsd`.
3122        for s in 0..=max_slot as u16 {
3123            // LS1: under linear scan, load a resident slot at entry iff it is
3124            // ENTRY-LIVE (live range starts at op 0 — an input/loop-carried value
3125            // read before written) OR it has a register to ITSELF (non-shared, so
3126            // the load can't clobber a co-tenant; loading a write-first temp is
3127            // harmless — its def overwrites it, and the entry value preserves a
3128            // conditionally-written slot on the paths it isn't written). Skip only
3129            // a SHARED write-first temp: loading it would clobber the entry-live or
3130            // earlier member sharing its one register.
3131            if linscan_active {
3132                let shared = ls_shared.get(s as usize).copied().unwrap_or(false);
3133                let entry_live =
3134                    matches!(ls_range.get(s as usize).copied().flatten(), Some((0, _)));
3135                if shared && !entry_live {
3136                    continue;
3137                }
3138            }
3139            match loc.get(s as usize) {
3140                Some(Loc::Reg(r)) => asm.mov_rm(*r, BASE, (s as i32) * 8),
3141                Some(Loc::Xmm(x)) => asm.movsd_rm(*x, BASE, (s as i32) * 8),
3142                _ => {}
3143            }
3144        }
3145    }
3146
3147    let status_addr = status
3148        .as_ref()
3149        .map(|c| c.as_ref() as *const AtomicI64 as i64)
3150        .unwrap_or(0);
3151
3152    // The self-call ENTRY CELL: an `Arc<AtomicI64>` whose address is baked into
3153    // every direct self-call site and which is written with `chain.base()` after
3154    // mapping. A mode-B `MicroOp::Call` instead dispatches through its own
3155    // per-callee function-table slot; using this self-entry cell there would
3156    // recursively call the caller instead of the requested helper.
3157    let entry_cell: Option<std::sync::Arc<AtomicI64>> =
3158        has_self_call.then(|| std::sync::Arc::new(AtomicI64::new(0)));
3159    let entry_addr = entry_cell
3160        .as_ref()
3161        .map(|c| c.as_ref() as *const AtomicI64 as i64)
3162        .unwrap_or(0);
3163
3164    let self_call = propagate_label.map(|pl| SelfCall {
3165        propagate_label: pl,
3166    });
3167    let precise_ctx = precise.map(|codes| Precise {
3168        codes,
3169        code_blocks: &code_blocks,
3170    });
3171
3172    let mut g = Gen {
3173        asm,
3174        loc: loc.clone(),
3175        op_labels: &op_labels,
3176        deopt_label,
3177        stack_pad,
3178        self_call,
3179        call_gp: &call_gp,
3180        call_xmm: &call_xmm,
3181        precise: precise_ctx,
3182        off_im1_reg,
3183        off_scaled_reg,
3184        off_cache: None,
3185        hoists: &hoists,
3186        active_hoists: Vec::new(),
3187    };
3188
3189    // Jump-target indices: an op reached by some transfer's `target` is a control
3190    // join, so the scaled-index cache must be DROPPED on entry to it (a stale
3191    // reserved register from the fall-through predecessor must not be reused when
3192    // control arrives from the branch). Computed once; consulted in the loop.
3193    let mut is_jump_target = vec![false; ops.len()];
3194    for op in ops {
3195        if let Some(t) = op_target(op) {
3196            if let Some(slot) = is_jump_target.get_mut(t) {
3197                *slot = true;
3198            }
3199        }
3200    }
3201
3202    // LOOP-INVARIANT CONSTANT HOIST (Wave 28). A `LoadConst` whose `dst` is the
3203    // span's sole writer and lands in a GP REGISTER is materialized ONCE in the
3204    // loop pre-header instead of every iteration. `const_hoist_by_op[i] =
3205    // Some(head)` marks the op `i` to (a) SKIP in the body and (b) materialize at
3206    // `head`'s pre-header.
3207    //
3208    // FLOAT (XMM-resident) consts are EXCLUDED, and the exclusion is empirical,
3209    // not incidental. mandelbrot's hot inner loop re-materializes `2.0`/`4.0`
3210    // every iteration through a GP→XMM bridge; hoisting them into resident XMM
3211    // registers held across the loop is bit-identical but measured ~8% SLOWER (n
3212    // =2000: 480ms vs 443ms, reproducible across independent processes; GP-only
3213    // hoisting is at parity). The XMM register file is SATURATED (14/14 resident
3214    // in mandelbrot), and holding an invariant float in an XMM register that the
3215    // float dependency chain repeatedly reads serializes worse than the
3216    // per-iteration re-materialization, whose independent `movabs;movq` the
3217    // out-of-order engine overlaps with the float chain — the copy-and-patch /
3218    // contiguous backend is throughput-bound here, so removing the "redundant"
3219    // float loads loses free ILP. Frame-resident dsts are also filtered (no
3220    // register to keep resident — the body would still touch the frame). The
3221    // structural detection is purely over the op stream; residency is decided
3222    // here against `loc`.
3223    let mut const_hoist_by_op: Vec<Option<usize>> = vec![None; ops.len()];
3224    let mut const_hoist_at_head: Vec<Vec<usize>> = vec![Vec::new(); ops.len()];
3225    if const_hoist_enabled() {
3226        for h in loop_invariant_const_hoists(ops, live_out) {
3227            if matches!(loc[h.dst as usize], Loc::Reg(_)) {
3228                const_hoist_by_op[h.op] = Some(h.head);
3229                const_hoist_at_head[h.head].push(h.op);
3230            }
3231        }
3232    }
3233
3234    for (idx, op) in ops.iter().enumerate() {
3235        // LOOP PRE-HEADER for any hoist whose loop head is THIS op: load the
3236        // invariant ptr (and len) into the reserved callee-saved register(s) ONCE,
3237        // BEFORE binding the head's label. The loop's back-edge targets the bound
3238        // label, so it SKIPS this load (the register stays live across iterations);
3239        // only the entry fall-through executes it. The entry-discipline guard in
3240        // `loop_invariant_array_hoists` ensures the head is entered ONLY via this
3241        // fall-through, so the register is always loaded before the first access.
3242        for k in 0..g.hoists.len() {
3243            let e = g.hoists[k];
3244            if e.plan.head == idx {
3245                g.load(e.ptr_reg, e.plan.ptr_slot);
3246                if let Some(lr) = e.len_reg {
3247                    g.load(lr, e.plan.len_slot);
3248                }
3249            }
3250        }
3251        // LOOP PRE-HEADER for any loop-invariant CONSTANT whose head is THIS op:
3252        // materialize the raw bits ONCE into the dst register, BEFORE binding the
3253        // head's label, so the back-edge (which jumps to the bound label) skips it
3254        // and the register stays resident across iterations. Mirrors the body
3255        // `LoadConst` emit exactly (a float dst bridges GP→XMM via `movq`), so the
3256        // register holds the same bits the per-iteration load would have.
3257        for ci in 0..const_hoist_at_head[idx].len() {
3258            let op_i = const_hoist_at_head[idx][ci];
3259            if let MicroOp::LoadConst { dst, value } = ops[op_i] {
3260                g.asm.mov_ri(S0, value);
3261                if let Loc::Xmm(_) = g.loc[dst as usize] {
3262                    g.asm.movq_xr(FS0, S0);
3263                    g.fstore(dst, FS0);
3264                } else {
3265                    g.store(dst, S0);
3266                }
3267            }
3268        }
3269        g.asm.bind(op_labels[idx]);
3270        // The hoists ACTIVE at this op: those whose span `[head, back]` contains
3271        // `idx`. Inside the span `emit_arr_addr` reads the hoisted register;
3272        // outside it falls back to the per-access frame reload (the register may
3273        // hold a stale value from a different loop or a since-rewritten slot).
3274        g.active_hoists.clear();
3275        for k in 0..g.hoists.len() {
3276            let p = g.hoists[k].plan;
3277            if (p.head..=p.back).contains(&idx) {
3278                g.active_hoists.push(k);
3279            }
3280        }
3281        // Drop the scaled-index cache at a control join: control could reach this
3282        // op from a branch where the reserved register holds a different (or no)
3283        // index, so the next array access here must recompute.
3284        if is_jump_target[idx] {
3285            g.invalidate_off_cache();
3286        }
3287        // A hoisted loop-invariant `LoadConst`: the pre-header already
3288        // materialized its register, which stays resident across the back-edge —
3289        // SKIP the per-iteration re-materialization (the body label is still bound
3290        // above so any transfer to it lands here correctly). The post-match
3291        // off-cache invalidation below is still honored: a `LoadConst` is never a
3292        // SysV call, and `invalidate_off_cache_if_writes_idx` recomputes a cache
3293        // keyed off this slot — harmless here (the invariant value is unchanged).
3294        let hoisted_const = const_hoist_by_op[idx].is_some();
3295        if !hoisted_const {
3296            match op {
3297                MicroOp::CallSelf {
3298                    dst,
3299                    args_start,
3300                    limit_slot,
3301                    frame_size,
3302                    ..
3303                } => {
3304                    emit_self_call(
3305                        &mut g,
3306                        idx,
3307                        *dst,
3308                        *args_start,
3309                        None,
3310                        *limit_slot,
3311                        *frame_size,
3312                        status_addr,
3313                        depth_addr,
3314                        entry_addr,
3315                    );
3316                }
3317                MicroOp::CallSelfCopy {
3318                    dst,
3319                    args_start,
3320                    src_start,
3321                    arg_count,
3322                    limit_slot,
3323                    frame_size,
3324                    ..
3325                } => {
3326                    emit_self_call(
3327                        &mut g,
3328                        idx,
3329                        *dst,
3330                        *args_start,
3331                        Some((*src_start, *arg_count)),
3332                        *limit_slot,
3333                        *frame_size,
3334                        status_addr,
3335                        depth_addr,
3336                        entry_addr,
3337                    );
3338                }
3339                // A mode-B precise `Call`: arguments are staged in the disjoint
3340                // window at `args_start`; the callee entry and published frame size
3341                // come from this op's function-table slot. The per-op code drives
3342                // precise guard exits.
3343                MicroOp::Call {
3344                    dst,
3345                    args_start,
3346                    table_addr,
3347                    limit_slot,
3348                    ..
3349                } => {
3350                    let code = g
3351                        .precise
3352                        .as_ref()
3353                        .map(|p| p.codes[idx])
3354                        .expect("a precise Call requires precise codes");
3355                    emit_precise_call(
3356                        &mut g,
3357                        idx,
3358                        *dst,
3359                        *args_start,
3360                        *limit_slot,
3361                        status_addr,
3362                        depth_addr,
3363                        *table_addr,
3364                        code,
3365                    );
3366                }
3367                _ => emit_op(&mut g, op, idx, &written, &used_callee)?,
3368            }
3369        }
3370        // A SysV call (self-call, precise call, or a list/string-mutation helper)
3371        // clobbers the caller-saved reserved register(s) during the call, so the
3372        // cache cannot survive it. A write to the cached index slot makes the held
3373        // `im1` stale. Either drops the cache so a later access recomputes.
3374        if is_sysv_call(op) {
3375            g.invalidate_off_cache();
3376        } else {
3377            g.invalidate_off_cache_if_writes_idx(op);
3378        }
3379        // LS1 SPILL-AT-END: when a SHARED-register slot's range ends, store it to
3380        // its frame home and set it `Frame`, freeing the register for the next
3381        // member. Only the Completed exit flush reads these cells (a classic Deopt
3382        // DISCARDS the private frame and replays from the VM's own registers —
3383        // machine.rs — so no per-write write-through is needed). A slot in a
3384        // register all to itself needs nothing: the register always holds exactly
3385        // its value, so the exit flush reads it correctly. The reuse start is
3386        // strictly after this end (`linscan_assign`), so the register still holds
3387        // THIS slot now — never a successor's value.
3388        if linscan_active {
3389            for s in 0..=max_slot {
3390                if ls_shared[s] && matches!(ls_range[s], Some((_, e)) if e == idx) {
3391                    match g.loc[s] {
3392                        Loc::Reg(r) => g.asm.mov_mr(BASE, (s as i32) * 8, r),
3393                        Loc::Xmm(x) => g.asm.movsd_mr(BASE, (s as i32) * 8, x),
3394                        Loc::Frame => {}
3395                    }
3396                    g.loc[s] = Loc::Frame;
3397                }
3398            }
3399        }
3400    }
3401
3402    // Deopt epilogue (only if some op can side-exit): store 1 to the status
3403    // cell, flush resident-written slots, restore callee-saved regs, return 0.
3404    if let Some(dl) = deopt_label {
3405        g.asm.bind(dl);
3406        // mov rax, status_addr; mov qword [rax], 1
3407        g.asm.mov_ri(S0, status_addr);
3408        g.asm.mov_ri(S1, 1);
3409        g.asm.mov_mr(S0, 0, S1);
3410        emit_flush_and_return(&mut g, &written, &used_callee, None);
3411    }
3412
3413    // Self-call deopt-PROPAGATION epilogue: the status cell ALREADY holds the
3414    // inner exit code (5/9/precise/1), so flush and return WITHOUT touching it.
3415    if let Some(pl) = propagate_label {
3416        g.asm.bind(pl);
3417        emit_flush_and_return(&mut g, &written, &used_callee, None);
3418    }
3419
3420    // PRECISE (mode-B) deopt epilogue + per-code tag-staging blocks. Each block
3421    // stages its tag in S1, then falls through (or jumps) to the shared epilogue,
3422    // which combines the live depth into the high 32 bits, writes the status
3423    // cell, flushes every resident-written slot, and returns — bit-identical to
3424    // `logos_stencil_deopt_at` (`status = (pc<<2 | 3) | (depth << 32)`).
3425    if let Some(ep) = precise_epilogue {
3426        // The blocks (deterministic order by code value for a stable layout),
3427        // each `mov S1, code; jmp epilogue`.
3428        let mut codes_sorted: Vec<(i64, LabelId)> =
3429            code_blocks.iter().map(|(&c, &l)| (c, l)).collect();
3430        codes_sorted.sort_by_key(|(c, _)| *c);
3431        for (c, lbl) in codes_sorted {
3432            g.asm.bind(lbl);
3433            g.asm.mov_ri(S1, c);
3434            g.asm.jmp(ep);
3435        }
3436        // The shared epilogue: S1 = tag; rax = *depth; rax <<= 32; rax |= S1;
3437        // *status = rax; flush; return.
3438        g.asm.bind(ep);
3439        g.asm.mov_ri(S0, depth_addr);
3440        g.asm.mov_rm(S0, S0, 0); // S0 = *depth
3441        g.asm.shl_ri(S0, 32);
3442        g.asm.or_rr(S0, S1); // S0 = (depth << 32) | tag
3443        g.asm.mov_ri(SC, status_addr);
3444        g.asm.mov_mr(SC, 0, S0); // *status = S0
3445        emit_flush_and_return(&mut g, &written, &used_callee, None);
3446    }
3447
3448    let code = g.asm.resolve();
3449    let chain = JitChain::from_code(&code, ops.len()).ok()?;
3450
3451    // Patch the entry cell with the mapped base, so every self-call reaches this
3452    // very function. An unpatched (0) cell would deopt (matching the stencil's
3453    // unpatched-entry guard), but we patch it here, before the chain ever runs.
3454    if let Some(cell) = entry_cell {
3455        cell.store(chain.base() as i64, std::sync::atomic::Ordering::SeqCst);
3456        return Some(CompiledChain::from_chain_keepalive(
3457            chain,
3458            status,
3459            vec![cell],
3460        ));
3461    }
3462    Some(CompiledChain::from_chain(chain, status))
3463}
3464
3465/// The destination slot an op writes, if any.
3466fn dest_of(op: &MicroOp) -> Option<Slot> {
3467    match *op {
3468        MicroOp::Move { dst, .. }
3469        | MicroOp::LoadConst { dst, .. }
3470        | MicroOp::Add { dst, .. }
3471        | MicroOp::Sub { dst, .. }
3472        | MicroOp::Mul { dst, .. }
3473        | MicroOp::Lt { dst, .. }
3474        | MicroOp::Gt { dst, .. }
3475        | MicroOp::LtEq { dst, .. }
3476        | MicroOp::GtEq { dst, .. }
3477        | MicroOp::Eq { dst, .. }
3478        | MicroOp::Neq { dst, .. }
3479        | MicroOp::BitAnd { dst, .. }
3480        | MicroOp::BitOr { dst, .. }
3481        | MicroOp::BitXor { dst, .. }
3482        | MicroOp::Shl { dst, .. }
3483        | MicroOp::Shr { dst, .. }
3484        | MicroOp::Ushr { dst, .. }
3485        | MicroOp::Rotate { dst, .. }
3486        | MicroOp::NotInt { dst, .. }
3487        | MicroOp::Popcnt { dst, .. }
3488        | MicroOp::Lzcnt { dst, .. }
3489        | MicroOp::Tzcnt { dst, .. }
3490        | MicroOp::Utf8Len { dst, .. }
3491        | MicroOp::ChrGuard { dst, .. }
3492        | MicroOp::FloorToInt { dst, .. }
3493        | MicroOp::CeilToInt { dst, .. }
3494        | MicroOp::RoundToInt { dst, .. }
3495        | MicroOp::NotBool { dst, .. }
3496        | MicroOp::Div { dst, .. }
3497        | MicroOp::Mod { dst, .. }
3498        | MicroOp::ArrLoad { dst, .. }
3499        | MicroOp::DivPow2 { dst, .. }
3500        | MicroOp::MagicDivU { dst, .. }
3501        | MicroOp::AddF { dst, .. }
3502        | MicroOp::SubF { dst, .. }
3503        | MicroOp::MulF { dst, .. }
3504        | MicroOp::DivF { dst, .. }
3505        | MicroOp::SqrtF { dst, .. }
3506        | MicroOp::IntToFloat { dst, .. }
3507        | MicroOp::FmaF { dst, .. }
3508        | MicroOp::LtF { dst, .. }
3509        | MicroOp::GtF { dst, .. }
3510        | MicroOp::LtEqF { dst, .. }
3511        | MicroOp::GtEqF { dst, .. }
3512        | MicroOp::EqF { dst, .. }
3513        | MicroOp::NeqF { dst, .. }
3514        // A self-call writes its result into `dst` (after a successful return).
3515        | MicroOp::CallSelf { dst, .. }
3516        | MicroOp::CallSelfCopy { dst, .. }
3517        // The mode-B precise self-call also stores its result handle into `dst`.
3518        | MicroOp::Call { dst, .. }
3519        | MicroOp::Host { dst, .. } => Some(dst),
3520        // `ArrStore` writes the BUFFER (through the pinned pointer), not a frame
3521        // slot, so it has no `dest_of` — its effect is outside the frame.
3522        _ => None,
3523    }
3524}
3525
3526/// Flush every resident-written slot back to the frame, restore callee-saved
3527/// registers, and `ret`. When `ret_slot` is `Some`, the return value (slot's
3528/// value) is loaded into `rax` AFTER flushing; when `None` (deopt), `rax` is
3529/// already the status-write scratch and the returned value is irrelevant (the
3530/// status cell signals the side-exit).
3531fn emit_flush_and_return(
3532    g: &mut Gen,
3533    written: &[bool],
3534    used_callee: &[Reg],
3535    ret_slot: Option<Slot>,
3536) {
3537    // Flush resident-written slots in slot order. GP slots flush via `mov`,
3538    // XMM (float) slots via `movsd` — both leave the frame consistent with the
3539    // tree-walker's full frame state (so the region can resume / deopt).
3540    for s in 0..g.loc.len() {
3541        if written[s] {
3542            match g.loc[s] {
3543                Loc::Reg(r) => g.asm.mov_mr(BASE, (s as i32) * 8, r),
3544                Loc::Xmm(x) => g.asm.movsd_mr(BASE, (s as i32) * 8, x),
3545                Loc::Frame => {}
3546            }
3547        }
3548    }
3549    if let Some(rs) = ret_slot {
3550        // Load the return value bits into rax from its (now frame-consistent)
3551        // home. A float return slot lives in an XMM reg — bit-copy via `movq`;
3552        // the chain ABI returns the raw i64 bits either way.
3553        match g.loc[rs as usize] {
3554            Loc::Reg(r) => g.asm.mov_rr(S0, r),
3555            Loc::Xmm(x) => g.asm.movq_rx(S0, x),
3556            Loc::Frame => g.asm.mov_rm(S0, BASE, (rs as i32) * 8),
3557        }
3558    }
3559    // Undo the prologue's stack-alignment pad (if any) before restoring regs.
3560    if g.stack_pad != 0 {
3561        g.asm.add_ri(Reg::Rsp, g.stack_pad);
3562    }
3563    // Restore callee-saved regs in reverse push order, then base.
3564    for &r in used_callee.iter().rev() {
3565        g.asm.pop(r);
3566    }
3567    g.asm.pop(BASE);
3568    g.asm.ret();
3569}
3570
3571/// Lower a DIRECT self-call (`CallSelf` / `CallSelfCopy`) — a REAL SysV call to
3572/// THIS chain's own entry. Bit-identical to `logos_stencil_call_self`(`_copy`):
3573///
3574/// 1. entry-cell load + zero guard (status = 1, the unpatched-entry marker);
3575/// 2. live-depth guard `depth >= MAX` (status = 5);
3576/// 3. arena-bound guard `callee_base + frame_size*8 > arena_end` (status = 9),
3577///    where `arena_end = frame[limit_slot]` and `callee_base = BASE + args*8`;
3578/// 4. (`CallSelfCopy`) stage `arg_count` scalar args from `src_start..` into the
3579///    callee window `callee_base[0..]` — read from wherever the source slots
3580///    live (register or frame), so a register-resident arg is staged correctly;
3581/// 5. plant `arena_end` into the callee's own limit slot
3582///    (`callee_base[frame_size-1]`);
3583/// 6. `*depth += 1`; spill caller-saved residents; `call [entry]`;
3584/// 7. `*depth -= 1`; if `*status != 0` → PROPAGATE (bare flush+return, the inner
3585///    exit code is already in the cell); else reload residents and store the
3586///    result into `dst`.
3587///
3588/// Every side exit writes its marker (or leaves the propagated code) and jumps
3589/// to the self-call PROPAGATION epilogue, which flushes the frame and returns
3590/// WITHOUT overwriting the status cell.
3591#[allow(clippy::too_many_arguments)]
3592fn emit_self_call(
3593    g: &mut Gen,
3594    idx: usize,
3595    dst: Slot,
3596    args_start: Slot,
3597    copy: Option<(Slot, u16)>,
3598    limit_slot: Slot,
3599    frame_size: i64,
3600    status_addr: i64,
3601    depth_addr: i64,
3602    entry_addr: i64,
3603) {
3604    let propagate = g
3605        .self_call
3606        .as_ref()
3607        .expect("self-call without SelfCall context")
3608        .propagate_label;
3609
3610    // A small helper: on a failed guard, write `marker` to the status cell, then
3611    // jump to the propagation epilogue (which flushes + returns, no further
3612    // status write). Emitted as an out-of-line block reached by a jcc.
3613    let entry_zero = g.asm.new_label();
3614    let depth_bad = g.asm.new_label();
3615    let arena_bad = g.asm.new_label();
3616
3617    // ---- 1. entry-cell load + zero guard ----
3618    // S0 = *entry_cell (the patched base, or 0 if somehow unpatched).
3619    g.asm.mov_ri(S0, entry_addr);
3620    g.asm.mov_rm(S0, S0, 0);
3621    g.asm.test_rr(S0, S0);
3622    g.asm.jcc(Cond::Eq, entry_zero);
3623
3624    // ---- 2. depth guard: *depth >= MAX ----
3625    // S1 = *depth.
3626    g.asm.mov_ri(S1, depth_addr);
3627    g.asm.mov_rm(S1, S1, 0);
3628    g.asm.cmp_ri(S1, SELF_CALL_DEPTH_LIMIT as i32);
3629    g.asm.jcc(Cond::Ge, depth_bad);
3630
3631    // ---- 3. arena-bound guard ----
3632    // SC = callee_base = BASE + args_start*8.
3633    g.asm.mov_rr(SC, BASE);
3634    g.asm.add_ri(SC, (args_start as i32) * 8);
3635    // S0 = arena_end = frame[limit_slot].
3636    g.asm.mov_rm(S0, BASE, (limit_slot as i32) * 8);
3637    // S1 = callee_base + frame_size*8.
3638    g.asm.mov_rr(S1, SC);
3639    g.asm.add_ri(S1, (frame_size as i32) * 8);
3640    g.asm.cmp_rr(S1, S0); // (callee_base + fs*8) - arena_end
3641    g.asm.jcc(Cond::Gt, arena_bad); // > arena_end → OOB
3642
3643    // ---- 4. argument staging (CallSelfCopy) ----
3644    // SC holds callee_base; S0 holds arena_end (kept for step 5). Stage each
3645    // source arg through S1, reading the source slot from wherever it lives.
3646    if let Some((src_start, arg_count)) = copy {
3647        for j in 0..arg_count {
3648            g.load(S1, src_start + j); // S1 = frame-or-reg[src_start+j]
3649            g.asm.mov_mr(SC, (j as i32) * 8, S1); // callee_base[j] = arg
3650        }
3651    }
3652
3653    // ---- 5. plant arena_end into the callee's own limit slot ----
3654    g.asm.mov_mr(SC, ((frame_size - 1) as i32) * 8, S0); // callee_base[fs-1] = arena_end
3655
3656    // ---- 6a. *depth += 1 ----
3657    g.asm.mov_ri(SC, depth_addr);
3658    g.asm.mov_rm(S0, SC, 0);
3659    g.asm.add_ri(S0, 1);
3660    g.asm.mov_mr(SC, 0, S0);
3661
3662    // ---- 6b. spill caller-saved residents to their frame slots ----
3663    g.spill_volatiles_at(idx);
3664
3665    // ---- 6c. set up the SysV call args and CALL ----
3666    // rdi = callee_base = BASE + args_start*8 (recompute — SC was reused above).
3667    g.asm.mov_rr(Reg::Rdi, BASE);
3668    g.asm.add_ri(Reg::Rdi, (args_start as i32) * 8);
3669    // rsi = sp = 0 (the contiguous backend never reads the operand stack).
3670    g.asm.mov_ri(Reg::Rsi, 0);
3671    // rdx/rcx/r8/r9 = 0 (threaded register args enter zeroed; the callee's
3672    // prologue reloads its pinned registers from its frame).
3673    g.asm.mov_ri(Reg::Rdx, 0);
3674    g.asm.mov_ri(Reg::Rcx, 0);
3675    g.asm.mov_ri(Reg::R8, 0);
3676    g.asm.mov_ri(Reg::R9, 0);
3677    // call [entry_cell]: rax = *entry_cell; call rax.
3678    g.asm.mov_ri(S0, entry_addr);
3679    g.asm.mov_rm(S0, S0, 0);
3680    g.asm.call_r(S0); // result -> rax (S0)
3681
3682    // ---- 7a. *depth -= 1 (uses rcx; rax holds the result) ----
3683    g.asm.mov_ri(SC, depth_addr);
3684    g.asm.mov_rm(S1, SC, 0);
3685    g.asm.sub_ri(S1, 1);
3686    g.asm.mov_mr(SC, 0, S1);
3687
3688    // ---- 7b. status check: if *status != 0 propagate (rax irrelevant) ----
3689    g.asm.mov_ri(S1, status_addr);
3690    g.asm.mov_rm(S1, S1, 0);
3691    g.asm.test_rr(S1, S1);
3692    g.asm.jcc(Cond::Ne, propagate);
3693
3694    // ---- 7c. reload caller-saved residents (their pre-call loop-carried
3695    // values, spilled in 6b — the callee never touches the caller's frame
3696    // slots). Reloads write the resident register directly (no scratch), so
3697    // rax (the result) survives. Only the LIVE-AFTER subset is reloaded (a
3698    // resident dead after the call is read by no later op). ----
3699    g.reload_volatiles_at(idx);
3700
3701    // ---- 7d. store the result into dst (AFTER reloading, so a volatile-
3702    // resident dst gets the result, not its stale reloaded value). ----
3703    g.store(dst, S0);
3704
3705    // ---- out-of-line guard-failure blocks (write marker, then propagate) ----
3706    let after = g.asm.new_label();
3707    g.asm.jmp(after);
3708
3709    g.asm.bind(entry_zero);
3710    emit_marker_then_propagate(g, status_addr, 1, propagate);
3711    g.asm.bind(depth_bad);
3712    emit_marker_then_propagate(g, status_addr, 5, propagate);
3713    g.asm.bind(arena_bad);
3714    emit_marker_then_propagate(g, status_addr, 9, propagate);
3715
3716    g.asm.bind(after);
3717}
3718
3719/// Write `marker` to the status cell, then jump to the self-call propagation
3720/// epilogue (bare flush + return). Used by the pre-call self-call guards
3721/// (unpatched entry = 1, depth limit = 5, arena bound = 9) — the same distinct
3722/// markers `logos_stencil_call_self` writes.
3723fn emit_marker_then_propagate(g: &mut Gen, status_addr: i64, marker: i64, propagate: LabelId) {
3724    g.asm.mov_ri(S0, status_addr);
3725    g.asm.mov_ri(S1, marker);
3726    g.asm.mov_mr(S0, 0, S1);
3727    g.asm.jmp(propagate);
3728}
3729
3730/// Lower a PRECISE `Call` (a REAL SysV call through the program's
3731/// entry table) — bit-identical to `logos_stencil_call_precise`:
3732///
3733/// 1. callee table-entry load + zero guard (precise-tag exit);
3734/// 2. live-depth guard `depth >= MAX` (precise-tag exit);
3735/// 3. arena-bound guard `callee_base + (regc+3)*8 > arena_end` (precise-tag exit),
3736///    where `arena_end = frame[limit_slot]`, `callee_base = BASE + args_start*8`,
3737///    and `regc` is read from the callee's published table slot;
3738/// 4. plant `arena_end` into the callee's own limit slot
3739///    (`callee_base[regc+2]`);
3740/// 5. `*depth += 1`; spill caller-saved residents; `call [entry]`;
3741/// 6. `*depth -= 1`; if `*status != 0` → PRECISE PROPAGATE (bare flush+return,
3742///    the inner exit code — already a precise tag — stays in the cell); else
3743///    reload residents and store the result handle into `dst`.
3744///
3745/// Unlike the classic self-call, the args are PRE-STAGED by `Move` micros into
3746/// the disjoint callee window (`args_start = frame_size`) before this op, and the
3747/// plant window/resume/dst slots were written by the preceding `LoadConst`
3748/// micros (all frame-resident), so the precise-deopt walk can chain frames. On
3749/// ANY guard failure the precise epilogue writes `code | (*depth << 32)`.
3750#[allow(clippy::too_many_arguments)]
3751fn emit_precise_call(
3752    g: &mut Gen,
3753    idx: usize,
3754    dst: Slot,
3755    args_start: Slot,
3756    limit_slot: Slot,
3757    status_addr: i64,
3758    depth_addr: i64,
3759    table_addr: i64,
3760    code: i64,
3761) {
3762    let propagate = g
3763        .self_call
3764        .as_ref()
3765        .expect("precise call without a propagate epilogue")
3766        .propagate_label;
3767    let fail = g
3768        .precise
3769        .as_ref()
3770        .map(|p| p.code_blocks[&code])
3771        .expect("precise call without a code block");
3772
3773    // ---- 1. callee table-entry load + zero guard ----
3774    g.asm.mov_ri(S0, table_addr);
3775    g.asm.mov_rm(S0, S0, 0);
3776    g.asm.test_rr(S0, S0);
3777    g.asm.jcc(Cond::Eq, fail);
3778
3779    // ---- 2. depth guard: *depth >= MAX ----
3780    g.asm.mov_ri(S1, depth_addr);
3781    g.asm.mov_rm(S1, S1, 0);
3782    g.asm.cmp_ri(S1, SELF_CALL_DEPTH_LIMIT as i32);
3783    g.asm.jcc(Cond::Ge, fail);
3784
3785    // ---- 3. arena-bound guard ----
3786    // SC = callee_base = BASE + args_start*8.
3787    g.asm.mov_rr(SC, BASE);
3788    g.asm.add_ri(SC, (args_start as i32) * 8);
3789    // S0 = arena_end = frame[limit_slot].
3790    g.asm.mov_rm(S0, BASE, (limit_slot as i32) * 8);
3791    // S1 = callee_base + (published regcount + 3) * 8.
3792    g.asm.mov_ri(S1, table_addr);
3793    g.asm.mov_rm(S1, S1, 8);
3794    g.asm.shl_ri(S1, 3);
3795    g.asm.add_rr(S1, SC);
3796    g.asm.add_ri(S1, 3 * 8);
3797    g.asm.cmp_rr(S1, S0);
3798    g.asm.jcc(Cond::Gt, fail);
3799
3800    // ---- 4. plant arena_end into the callee's own limit slot ----
3801    // S1 = callee_base + published_regcount * 8, then +2 slots.
3802    g.asm.mov_ri(S1, table_addr);
3803    g.asm.mov_rm(S1, S1, 8);
3804    g.asm.shl_ri(S1, 3);
3805    g.asm.add_rr(S1, SC);
3806    g.asm.mov_mr(S1, 2 * 8, S0);
3807
3808    // ---- 5a. *depth += 1 ----
3809    g.asm.mov_ri(SC, depth_addr);
3810    g.asm.mov_rm(S0, SC, 0);
3811    g.asm.add_ri(S0, 1);
3812    g.asm.mov_mr(SC, 0, S0);
3813
3814    // ---- 5b. spill the LIVE-AFTER caller-saved residents ----
3815    // A resident dead after this precise call is read by no later op AND is not
3816    // observed by a precise resume at this call's PC (the resume reads live-IN
3817    // slots, a subset of these live-after residents plus the frame-resident
3818    // args/limit) — so eliding its spill/reload is bit-identical.
3819    g.spill_volatiles_at(idx);
3820
3821    // ---- 5c. SysV call args + CALL ----
3822    g.asm.mov_rr(Reg::Rdi, BASE);
3823    g.asm.add_ri(Reg::Rdi, (args_start as i32) * 8);
3824    g.asm.mov_ri(Reg::Rsi, 0);
3825    g.asm.mov_ri(Reg::Rdx, 0);
3826    g.asm.mov_ri(Reg::Rcx, 0);
3827    g.asm.mov_ri(Reg::R8, 0);
3828    g.asm.mov_ri(Reg::R9, 0);
3829    g.asm.mov_ri(S0, table_addr);
3830    g.asm.mov_rm(S0, S0, 0);
3831    g.asm.call_r(S0); // result -> rax (S0)
3832
3833    // ---- 6a. *depth -= 1 (rcx scratch; rax holds the result) ----
3834    g.asm.mov_ri(SC, depth_addr);
3835    g.asm.mov_rm(S1, SC, 0);
3836    g.asm.sub_ri(S1, 1);
3837    g.asm.mov_mr(SC, 0, S1);
3838
3839    // ---- 6b. status check: if *status != 0 propagate (rax irrelevant) ----
3840    g.asm.mov_ri(S1, status_addr);
3841    g.asm.mov_rm(S1, S1, 0);
3842    g.asm.test_rr(S1, S1);
3843    g.asm.jcc(Cond::Ne, propagate);
3844
3845    // Preserve the callee result across resident reloads. `S0` is RAX, and a
3846    // live caller slot may itself be allocated to RAX; reloading it first would
3847    // silently replace the return value (the SHA region exposed this once
3848    // precise Call support was enabled there).
3849    g.asm.mov_mr(BASE, (dst as i32) * 8, S0);
3850
3851    // ---- 6c. reload the LIVE-AFTER caller-saved residents ----
3852    g.reload_volatiles_at(idx);
3853
3854    // ---- 6d. store the result handle into dst ----
3855    g.asm.mov_rm(S0, BASE, (dst as i32) * 8);
3856    g.store(dst, S0);
3857}
3858
3859/// Lower one supported op.
3860fn emit_op(
3861    g: &mut Gen,
3862    op: &MicroOp,
3863    idx: usize,
3864    written: &[bool],
3865    used_callee: &[Reg],
3866) -> Option<()> {
3867    match *op {
3868        MicroOp::LoadConst { dst, value } => {
3869            // Materialize the raw bits in a GP scratch; if the dst is XMM-
3870            // resident (a float const like `0.0`), bridge through `movq`.
3871            g.asm.mov_ri(S0, value);
3872            if let Loc::Xmm(_) = g.loc[dst as usize] {
3873                g.asm.movq_xr(FS0, S0);
3874                g.fstore(dst, FS0);
3875            } else {
3876                g.store(dst, S0);
3877            }
3878        }
3879        MicroOp::Move { dst, src } => {
3880            // A raw-bits copy. If EITHER end is XMM-resident, route through an
3881            // XMM scratch (fload/fstore bit-preserve across all locations);
3882            // otherwise the GP path (a direct reg move when both resident).
3883            if matches!(g.loc[dst as usize], Loc::Xmm(_))
3884                || matches!(g.loc[src as usize], Loc::Xmm(_))
3885            {
3886                let x = g.foperand(src, FS0);
3887                g.fstore(dst, x);
3888            } else {
3889                let r = g.operand(src, S0);
3890                g.store(dst, r);
3891            }
3892        }
3893        MicroOp::Add { dst, lhs, rhs } => emit_commutative(g, dst, lhs, rhs, AsmBinop::Add, idx),
3894        MicroOp::Sub { dst, lhs, rhs } => emit_sub(g, dst, lhs, rhs, idx),
3895        MicroOp::Mul { dst, lhs, rhs } => emit_commutative(g, dst, lhs, rhs, AsmBinop::Mul, idx),
3896        MicroOp::BitAnd { dst, lhs, rhs } => emit_commutative(g, dst, lhs, rhs, AsmBinop::And, idx),
3897        MicroOp::BitOr { dst, lhs, rhs } => emit_commutative(g, dst, lhs, rhs, AsmBinop::Or, idx),
3898        MicroOp::BitXor { dst, lhs, rhs } => emit_commutative(g, dst, lhs, rhs, AsmBinop::Xor, idx),
3899        MicroOp::Lt { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Lt),
3900        MicroOp::Gt { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Gt),
3901        MicroOp::LtEq { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Le),
3902        MicroOp::GtEq { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Ge),
3903        MicroOp::Eq { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Eq),
3904        MicroOp::Neq { dst, lhs, rhs } => emit_compare(g, dst, lhs, rhs, Cond::Ne),
3905        MicroOp::NotInt { dst, src } => {
3906            g.load(S0, src);
3907            g.asm.not_r(S0);
3908            g.store(dst, S0);
3909        }
3910        MicroOp::Popcnt { dst, src } => {
3911            g.load(S0, src);
3912            g.asm.popcnt_rr(S0, S0);
3913            g.store(dst, S0);
3914        }
3915        MicroOp::Lzcnt { dst, src } => {
3916            g.load(S0, src);
3917            g.asm.lzcnt_rr(S0, S0);
3918            g.store(dst, S0);
3919        }
3920        MicroOp::Tzcnt { dst, src } => {
3921            g.load(S0, src);
3922            g.asm.tzcnt_rr(S0, S0);
3923            g.store(dst, S0);
3924        }
3925        // Float→Int rounding: round the float src (in an XMM) to an integral f64, then `cvttsd2si` it to
3926        // the GP dst. roundsd mode 1 = floor (−∞), 2 = ceil (+∞); the cvttsd2si truncation is exact on the
3927        // already-integral result.
3928        MicroOp::FloorToInt { dst, src } => {
3929            let s = g.foperand(src, FS1);
3930            g.asm.roundsd_rri(FS0, s, 1);
3931            g.asm.cvttsd2si_rr(S0, FS0);
3932            g.store(dst, S0);
3933        }
3934        MicroOp::CeilToInt { dst, src } => {
3935            let s = g.foperand(src, FS1);
3936            g.asm.roundsd_rri(FS0, s, 2);
3937            g.asm.cvttsd2si_rr(S0, FS0);
3938            g.store(dst, S0);
3939        }
3940        MicroOp::NotBool { dst, src } => {
3941            // dst = src ^ 1
3942            g.load(S0, src);
3943            g.asm.mov_ri(S1, 1);
3944            g.asm.xor_rr(S0, S1);
3945            g.store(dst, S0);
3946        }
3947        MicroOp::Shl { dst, lhs, rhs } => emit_shift(g, dst, lhs, rhs, ShiftKind::Left),
3948        MicroOp::Shr { dst, lhs, rhs } => emit_shift(g, dst, lhs, rhs, ShiftKind::Right),
3949        MicroOp::Ushr { dst, lhs, rhs } => emit_shift(g, dst, lhs, rhs, ShiftKind::LogicalRight),
3950        MicroOp::Rotate {
3951            dst,
3952            lhs,
3953            rhs,
3954            width32,
3955            left,
3956        } => emit_rotate(g, dst, lhs, rhs, width32, left),
3957        MicroOp::DivPow2 { dst, lhs, k } => emit_div_pow2(g, dst, lhs, k),
3958        MicroOp::MagicDivU {
3959            dst,
3960            lhs,
3961            magic,
3962            more,
3963            mul_back,
3964        } => emit_magic_div(g, dst, lhs, magic, more, mul_back),
3965        MicroOp::Div { dst, lhs, rhs } => {
3966            let dl = g.checked_exit(idx).expect("Div without a deopt label");
3967            emit_div_mod(g, dst, lhs, rhs, true, dl);
3968        }
3969        MicroOp::Mod { dst, lhs, rhs } => {
3970            let dl = g.checked_exit(idx).expect("Mod without a deopt label");
3971            emit_div_mod(g, dst, lhs, rhs, false, dl);
3972        }
3973        MicroOp::Branch {
3974            cmp,
3975            lhs,
3976            rhs,
3977            target,
3978        } => {
3979            // Transfer to `target` when cmp(lhs, rhs) is FALSE; fall through
3980            // when TRUE. So jump on the NEGATED condition.
3981            let a = g.operand(lhs, S0);
3982            let b = g.operand(rhs, S1);
3983            g.asm.cmp_rr(a, b);
3984            let neg = cond_of(cmp.negated());
3985            g.asm.jcc(neg, g.op_labels[target]);
3986        }
3987        MicroOp::Jump { target } => {
3988            if target != idx + 1 {
3989                g.asm.jmp(g.op_labels[target]);
3990            }
3991        }
3992        MicroOp::JumpIfFalse { cond, target } => {
3993            let r = g.operand(cond, S0);
3994            g.asm.test_rr(r, r);
3995            g.asm.jcc(Cond::Eq, g.op_labels[target]); // ZF set => value == 0
3996        }
3997        MicroOp::JumpIfTrue { cond, target } => {
3998            let r = g.operand(cond, S0);
3999            g.asm.test_rr(r, r);
4000            g.asm.jcc(Cond::Ne, g.op_labels[target]); // ZF clear => value != 0
4001        }
4002        MicroOp::ArrLoad {
4003            dst,
4004            idx: idx_slot,
4005            ptr_slot,
4006            len_slot,
4007            byte: false,
4008            narrow32: true,
4009            checked,
4010        } => {
4011            let dl = g.checked_exit(idx);
4012            emit_arr_load_i32(g, dst, idx_slot, ptr_slot, len_slot, checked, dl);
4013        }
4014        MicroOp::ArrStore {
4015            src,
4016            idx: idx_slot,
4017            ptr_slot,
4018            len_slot,
4019            byte: false,
4020            narrow32: true,
4021            checked,
4022        } => {
4023            let dl = g.checked_exit(idx);
4024            emit_arr_store_i32(g, src, idx_slot, ptr_slot, len_slot, checked, dl);
4025        }
4026        MicroOp::ArrLoad {
4027            dst,
4028            idx: idx_slot,
4029            ptr_slot,
4030            len_slot,
4031            byte: false,
4032            narrow32: false,
4033            checked,
4034        } => {
4035            // The exit label is only consulted for a CHECKED access; an unchecked
4036            // load needs none (and a region with no checked op has no label).
4037            let dl = g.checked_exit(idx);
4038            emit_arr_load(g, dst, idx_slot, ptr_slot, len_slot, checked, dl);
4039        }
4040        MicroOp::ArrStore {
4041            src,
4042            idx: idx_slot,
4043            ptr_slot,
4044            len_slot,
4045            byte: false,
4046            narrow32: false,
4047            checked,
4048        } => {
4049            let dl = g.checked_exit(idx);
4050            emit_arr_store(g, src, idx_slot, ptr_slot, len_slot, checked, dl);
4051        }
4052        MicroOp::ArrLoad {
4053            dst,
4054            idx: idx_slot,
4055            ptr_slot,
4056            len_slot,
4057            byte: true,
4058            narrow32: _,
4059            checked,
4060        } => {
4061            let dl = g.checked_exit(idx);
4062            emit_arr_load_byte(g, dst, idx_slot, ptr_slot, len_slot, checked, dl);
4063        }
4064        MicroOp::ArrStore {
4065            src,
4066            idx: idx_slot,
4067            ptr_slot,
4068            len_slot,
4069            byte: true,
4070            narrow32: _,
4071            checked,
4072        } => {
4073            let dl = g.checked_exit(idx);
4074            emit_arr_store_byte(g, src, idx_slot, ptr_slot, len_slot, checked, dl);
4075        }
4076        // ---- LIST MUTATION (wave 13) — helper calls into the JIT runtime. ----
4077        MicroOp::ArrPush {
4078            src,
4079            vec_slot,
4080            ptr_slot,
4081            len_slot,
4082            helper_addr,
4083            byte,
4084            narrow32,
4085        } => {
4086            emit_list_push(
4087                g,
4088                idx,
4089                src,
4090                vec_slot,
4091                ptr_slot,
4092                len_slot,
4093                helper_addr,
4094                byte,
4095                narrow32,
4096            );
4097        }
4098        MicroOp::ListClear {
4099            vec_slot,
4100            ptr_slot,
4101            len_slot,
4102            helper_addr,
4103        } => {
4104            emit_list_clear(g, idx, vec_slot, ptr_slot, len_slot, helper_addr);
4105        }
4106        MicroOp::StrAppend {
4107            text_handle_slot,
4108            src,
4109            helper_addr,
4110        } => {
4111            emit_str_append(g, idx, text_handle_slot, src, helper_addr);
4112        }
4113        MicroOp::Host {
4114            dst,
4115            src,
4116            count,
4117            imm,
4118            helper_addr,
4119        } => {
4120            g.spill_volatiles_at(idx);
4121            g.asm.mov_rr(Reg::Rdi, BASE);
4122            g.asm.mov_ri(Reg::Rsi, dst as i64);
4123            g.asm.mov_ri(Reg::Rdx, src as i64);
4124            g.asm.mov_ri(Reg::Rcx, count as i64);
4125            g.asm.mov_ri(Reg::R8, imm);
4126            g.asm.mov_ri(S0, helper_addr);
4127            g.asm.call_r(S0);
4128            // Reload before the precise exit materializes resident values.
4129            // These MOVs preserve the helper-result test's condition flags.
4130            g.asm.test_rr(Reg::Rax, Reg::Rax);
4131            g.reload_volatiles_at(idx);
4132            let exit = g.checked_exit(idx).expect("Host without a deopt label");
4133            g.asm.jcc(Cond::Eq, exit);
4134        }
4135        // ---- MODE-B list machinery (precise path). The fresh-list-RETURN
4136        // recursion shape (mergesort): `NewList` allocates a registry-owned fresh
4137        // buffer and plants its pin triple, `ArrPush` (above) appends with a
4138        // realloc refresh, and `ListTriple` refreshes a triple from a live handle
4139        // (a self-call's returned list). ----
4140        MicroOp::NewList {
4141            vec_slot,
4142            ptr_slot,
4143            len_slot,
4144            helper_addr,
4145        } => {
4146            emit_new_list(g, idx, vec_slot, ptr_slot, len_slot, helper_addr);
4147        }
4148        MicroOp::ListTriple {
4149            handle_slot,
4150            vec_slot,
4151            ptr_slot,
4152            len_slot,
4153            helper_addr,
4154        } => {
4155            emit_list_triple(
4156                g,
4157                idx,
4158                handle_slot,
4159                vec_slot,
4160                ptr_slot,
4161                len_slot,
4162                helper_addr,
4163            );
4164        }
4165        // ---- FLOAT (f64 / XMM) ops. IEEE; no FMA; no reassociation. ----
4166        MicroOp::AddF { dst, lhs, rhs } => emit_fbinop(g, dst, lhs, rhs, FBinop::Add),
4167        MicroOp::SubF { dst, lhs, rhs } => emit_fbinop(g, dst, lhs, rhs, FBinop::Sub),
4168        MicroOp::MulF { dst, lhs, rhs } => emit_fbinop(g, dst, lhs, rhs, FBinop::Mul),
4169        MicroOp::DivF { dst, lhs, rhs } => {
4170            let dl = g.checked_exit(idx).expect("DivF without a deopt label");
4171            emit_fdiv(g, dst, lhs, rhs, dl);
4172        }
4173        MicroOp::SqrtF { dst, src } => {
4174            let s = g.foperand(src, FS1);
4175            g.asm.sqrtsd_rr(FS0, s);
4176            g.fstore(dst, FS0);
4177        }
4178        MicroOp::IntToFloat { dst, src } => {
4179            // cvtsi2sd needs a GP source; materialize the int into S0.
4180            let r = g.operand(src, S0);
4181            g.asm.cvtsi2sd(FS0, r);
4182            g.fstore(dst, FS0);
4183        }
4184        MicroOp::FmaF { dst, a, b, c } => {
4185            // TWO IEEE roundings (mulsd THEN addsd), bit-identical to the
4186            // reference `(a*b) + c`. NEVER a fused `vfmadd` (one rounding).
4187            g.fload(FS0, a); // FS0 = a
4188            let bv = g.foperand(b, FS1);
4189            g.asm.mulsd_rr(FS0, bv); // FS0 = a*b (rounded once)
4190            let cv = g.foperand(c, FS1);
4191            g.asm.addsd_rr(FS0, cv); // FS0 = (a*b) + c (rounded again)
4192            g.fstore(dst, FS0);
4193        }
4194        MicroOp::LtF { dst, lhs, rhs } => emit_fcompare(g, dst, lhs, rhs, FCmp::Lt),
4195        MicroOp::GtF { dst, lhs, rhs } => emit_fcompare(g, dst, lhs, rhs, FCmp::Gt),
4196        MicroOp::LtEqF { dst, lhs, rhs } => emit_fcompare(g, dst, lhs, rhs, FCmp::Le),
4197        MicroOp::GtEqF { dst, lhs, rhs } => emit_fcompare(g, dst, lhs, rhs, FCmp::Ge),
4198        MicroOp::EqF { dst, lhs, rhs } => emit_feq(g, dst, lhs, rhs, false),
4199        MicroOp::NeqF { dst, lhs, rhs } => emit_feq(g, dst, lhs, rhs, true),
4200        MicroOp::BranchF {
4201            cmp,
4202            lhs,
4203            rhs,
4204            target,
4205        } => {
4206            emit_branchf(g, cmp, lhs, rhs, g.op_labels[target]);
4207        }
4208        MicroOp::Return { src } => {
4209            emit_flush_and_return(g, written, used_callee, Some(src));
4210        }
4211        _ => return None,
4212    }
4213    Some(())
4214}
4215
4216/// Compute the 1-based array element address into [`S0`], side-exiting to the
4217/// deopt epilogue on a CHECKED out-of-bounds index — bit-identical to the
4218/// `ST_ARRLD`/`ST_ARRLDB`/`ST_ARRST`/`ST_ARRSTB` stencils: `im1 = idx - 1`
4219/// (wrapping); a checked access exits when `(im1 as u64) >= (len as u64)` (the
4220/// unsigned compare catches both the 0/negative index — `im1` wraps huge — and
4221/// the over-length case); `addr = ptr + im1 * stride`, where `stride` is 8 for
4222/// 8-byte int/float elements (`byte == false`) and 1 for 1-byte `Seq of Bool`
4223/// elements (`byte == true`). After this returns the address is in `S0` and the
4224/// length/pointer scratch (`S1`) is dead.
4225fn emit_arr_addr(
4226    g: &mut Gen,
4227    idx: Slot,
4228    ptr_slot: Slot,
4229    len_slot: Slot,
4230    checked: bool,
4231    byte: bool,
4232    dl: Option<LabelId>,
4233) {
4234    // SCALED-INDEX CSE FAST PATH. When the reserved register already holds the
4235    // 0-based index `im1 = frame[idx] - 1` for THIS index slot at THIS element
4236    // stride (a hit established by an earlier access in this straight-line run),
4237    // skip the index reload + decrement. The bounds check still runs PER ACCESS
4238    // (each array has its own length) against the cached TRUE `im1`, so an
4239    // out-of-bounds index — including the wrapped huge value a 0/negative index
4240    // produces — side-exits identically; only the `idx - 1` (and, with the second
4241    // reserved register, the `* 8` scaling) arithmetic is shared.
4242    if let (Some(im1_reg), Some(state)) = (g.off_im1_reg, g.off_cache) {
4243        if state.idx == idx && state.byte == byte {
4244            if checked {
4245                let dl = dl.expect("checked array op without a deopt label");
4246                // The invariant length: a hoisted len register (loop pre-header
4247                // load) when active, else the per-access frame reload.
4248                let len = g
4249                    .hoisted_len(ptr_slot)
4250                    .unwrap_or_else(|| g.operand(len_slot, S1));
4251                g.asm.cmp_rr(im1_reg, len); // im1 - len
4252                g.asm.jcc(Cond::AeU, dl); // (im1 as u64) >= (len as u64) → OOB
4253            }
4254            // addr = ptr + im1 * stride, reusing the cached index. A byte stride
4255            // is `im1` itself; an 8-byte stride reuses the cached scaled offset
4256            // (second register) or re-shifts the cached `im1` (one register).
4257            if byte {
4258                g.asm.mov_rr(S0, im1_reg);
4259            } else if let Some(scaled_reg) = g.off_scaled_reg {
4260                g.asm.mov_rr(S0, scaled_reg); // S0 = im1 * 8 (cached)
4261            } else {
4262                g.asm.mov_rr(S0, im1_reg);
4263                g.asm.shl_ri(S0, 3); // im1 * 8
4264            }
4265            // The invariant base pointer: the hoisted ptr register when active,
4266            // else the per-access frame reload.
4267            let ptr = g
4268                .hoisted_ptr(ptr_slot)
4269                .unwrap_or_else(|| g.operand(ptr_slot, S1));
4270            g.asm.add_rr(S0, ptr); // S0 = ptr + im1*stride
4271            return;
4272        }
4273    }
4274
4275    // COMPUTE PATH (cache miss or CSE disabled): the literal per-access lowering,
4276    // additionally populating the reserved register(s) so the next access in the
4277    // run hits the fast path above. Bit-identical to the stencil tier.
4278    // S0 = idx; S0 -= 1  → im1.
4279    g.load(S0, idx);
4280    g.asm.sub_ri(S0, 1);
4281    // Cache the freshly computed `im1` (the 0-based index) for reuse.
4282    if let Some(im1_reg) = g.off_im1_reg {
4283        g.asm.mov_rr(im1_reg, S0);
4284        g.off_cache = Some(OffCacheState { idx, byte });
4285    }
4286    if checked {
4287        let dl = dl.expect("checked array op without a deopt label");
4288        let len = g
4289            .hoisted_len(ptr_slot)
4290            .unwrap_or_else(|| g.operand(len_slot, S1));
4291        g.asm.cmp_rr(S0, len); // im1 - len
4292        g.asm.jcc(Cond::AeU, dl); // (im1 as u64) >= (len as u64) → OOB
4293    }
4294    // addr = ptr + im1 * stride. Byte (Bool) elements are 1-byte: no scaling.
4295    if !byte {
4296        g.asm.shl_ri(S0, 3); // im1 * 8 (8-byte i64/f64 elements)
4297                             // Cache the scaled offset too (second register), so a reused 8-byte
4298                             // access skips the shift as well.
4299        if g.off_im1_reg.is_some() {
4300            if let Some(scaled_reg) = g.off_scaled_reg {
4301                g.asm.mov_rr(scaled_reg, S0);
4302            }
4303        }
4304    }
4305    let ptr = g
4306        .hoisted_ptr(ptr_slot)
4307        .unwrap_or_else(|| g.operand(ptr_slot, S1));
4308    g.asm.add_rr(S0, ptr); // S0 = ptr + im1*stride
4309}
4310
4311/// `frame[dst] = buffer[frame[idx] - 1]` (8-byte int element). The loaded value
4312/// goes through scratch `S1` so a resident `dst` is written with a register move.
4313/// A CHECKED out-of-bounds index jumps to `dl` (the classic deopt epilogue or, in
4314/// the precise path, this op's tag-staging block).
4315fn emit_arr_load(
4316    g: &mut Gen,
4317    dst: Slot,
4318    idx: Slot,
4319    ptr_slot: Slot,
4320    len_slot: Slot,
4321    checked: bool,
4322    dl: Option<LabelId>,
4323) {
4324    emit_arr_addr(g, idx, ptr_slot, len_slot, checked, false, dl);
4325    g.asm.mov_rm(S1, S0, 0); // S1 = *addr
4326    g.store(dst, S1);
4327}
4328
4329/// `frame[dst] = buffer[frame[idx] - 1] as i64` over 1-BYTE (`Seq of Bool`)
4330/// elements — bit-identical to `logos_stencil_arrldb`: a zero-extended 1-byte
4331/// load (`movzx`), so the loaded `u8` (0..=255, in practice 0/1) widens to a
4332/// NON-NEGATIVE i64. The loaded value goes through scratch `S1` so a resident
4333/// `dst` is written with a register move; OOB side-exit is identical to the
4334/// 8-byte path (same `im1`/length unsigned guard).
4335fn emit_arr_load_byte(
4336    g: &mut Gen,
4337    dst: Slot,
4338    idx: Slot,
4339    ptr_slot: Slot,
4340    len_slot: Slot,
4341    checked: bool,
4342    dl: Option<LabelId>,
4343) {
4344    emit_arr_addr(g, idx, ptr_slot, len_slot, checked, true, dl);
4345    g.asm.movzx_rm8(S1, S0, 0); // S1 = *(u8*)addr (zero-extended)
4346    g.store(dst, S1);
4347}
4348
4349/// `buffer[frame[idx] - 1] = frame[src]` (8 raw bytes). The stored value is the
4350/// slot's raw bits, so a FLOAT-resident (XMM) source is bit-copied to a GP
4351/// register via `movq` first — the buffer holds the same 8 bytes either way. A
4352/// CHECKED store side-exits BEFORE the write (to `dl`), so an out-of-bounds store
4353/// leaves the buffer untouched (the reference and stencil contract).
4354fn emit_arr_store(
4355    g: &mut Gen,
4356    src: Slot,
4357    idx: Slot,
4358    ptr_slot: Slot,
4359    len_slot: Slot,
4360    checked: bool,
4361    dl: Option<LabelId>,
4362) {
4363    emit_arr_addr(g, idx, ptr_slot, len_slot, checked, false, dl);
4364    // The address is in S0 and the pointer scratch S1 is dead. Materialize the
4365    // source bits into a GP reg that cannot collide with the address: SC (rcx)
4366    // for a GP/frame source, or S1 (the dead pointer scratch) for an XMM source.
4367    let v = match g.loc[src as usize] {
4368        Loc::Xmm(x) => {
4369            g.asm.movq_rx(S1, x);
4370            S1
4371        }
4372        _ => g.operand(src, SC),
4373    };
4374    g.asm.mov_mr(S0, 0, v); // *addr = value
4375}
4376
4377/// `buffer[frame[idx] - 1] = (frame[src] != 0) as u8` over 1-BYTE (`Seq of Bool`)
4378/// elements — bit-identical to `logos_stencil_arrstb`: the stored byte is the
4379/// BOOLEAN NORMALIZATION of the value (1 when nonzero, else 0), NOT its raw low
4380/// byte. A CHECKED store side-exits BEFORE the write (to `dl`), so an
4381/// out-of-bounds store leaves the buffer untouched.
4382///
4383/// The normalization is `test v, v; setne S1l` — `S1` (rdx) is the dead pointer
4384/// scratch after the address is in `S0`, and its low byte `dl` is REX-free
4385/// addressable. Only that low byte is then stored. An XMM-resident source is
4386/// bit-copied to `SC` (rcx) first so its full 64 bits feed the zero test (a
4387/// nonzero f64 bit pattern — incl. `-0.0` and NaN — stores 1, matching `!= 0`).
4388fn emit_arr_store_byte(
4389    g: &mut Gen,
4390    src: Slot,
4391    idx: Slot,
4392    ptr_slot: Slot,
4393    len_slot: Slot,
4394    checked: bool,
4395    dl: Option<LabelId>,
4396) {
4397    emit_arr_addr(g, idx, ptr_slot, len_slot, checked, true, dl);
4398    // Materialize the source value into a GP reg distinct from the address (S0).
4399    // SC (rcx) for a GP/frame source; for an XMM source, bit-copy to SC.
4400    let v = match g.loc[src as usize] {
4401        Loc::Xmm(x) => {
4402            g.asm.movq_rx(SC, x);
4403            SC
4404        }
4405        _ => g.operand(src, SC),
4406    };
4407    // (v != 0) → S1's low byte via test + setne; store that one byte.
4408    g.asm.test_rr(v, v);
4409    g.asm.setcc8(Cond::Ne, S1);
4410    g.asm.mov_mr8(S0, 0, S1); // *(u8*)addr = (v != 0) as u8
4411}
4412
4413/// Address machinery for a 4-byte (`IntsI32`) element: `S0 = ptr + (idx-1)*4`,
4414/// with the same unsigned over-length OOB guard as [`emit_arr_addr`]. A literal
4415/// per-access lowering (no scaled-index CSE — the half-width lane is rare and
4416/// the index reuse is the dominant cost, already covered by the loop's other
4417/// accesses); after this the address is in `S0` and the scratch `S1` is dead.
4418fn emit_arr_addr_i32(
4419    g: &mut Gen,
4420    idx: Slot,
4421    ptr_slot: Slot,
4422    len_slot: Slot,
4423    checked: bool,
4424    dl: Option<LabelId>,
4425) {
4426    g.load(S0, idx);
4427    g.asm.sub_ri(S0, 1); // im1 = idx - 1
4428    if checked {
4429        let dl = dl.expect("checked array op without a deopt label");
4430        let len = g
4431            .hoisted_len(ptr_slot)
4432            .unwrap_or_else(|| g.operand(len_slot, S1));
4433        g.asm.cmp_rr(S0, len); // im1 - len
4434        g.asm.jcc(Cond::AeU, dl); // (im1 as u64) >= (len as u64) → OOB
4435    }
4436    g.asm.shl_ri(S0, 2); // im1 * 4 (4-byte i32 elements)
4437    let ptr = g
4438        .hoisted_ptr(ptr_slot)
4439        .unwrap_or_else(|| g.operand(ptr_slot, S1));
4440    g.asm.add_rr(S0, ptr); // S0 = ptr + im1*4
4441}
4442
4443/// `frame[dst] = buffer[frame[idx] - 1] as i64` over 4-byte SIGN-EXTENDED
4444/// (`IntsI32`) elements — bit-identical to `logos_stencil_arrld_i32`: a
4445/// `movsxd` widening the stored `i32` to a full i64. Through scratch `S1` so a
4446/// resident `dst` is written with a register move; OOB side-exit identical to
4447/// the 8-byte path. A half-width access drops the scaled-index CSE cache (its
4448/// stride differs from any cached 8-byte run).
4449fn emit_arr_load_i32(
4450    g: &mut Gen,
4451    dst: Slot,
4452    idx: Slot,
4453    ptr_slot: Slot,
4454    len_slot: Slot,
4455    checked: bool,
4456    dl: Option<LabelId>,
4457) {
4458    g.invalidate_off_cache();
4459    emit_arr_addr_i32(g, idx, ptr_slot, len_slot, checked, dl);
4460    g.asm.movsxd_rm(S1, S0, 0); // S1 = *(i32*)addr (sign-extended)
4461    g.store(dst, S1);
4462}
4463
4464/// `buffer[frame[idx] - 1] = frame[src] as i32` over 4-byte (`IntsI32`)
4465/// elements — bit-identical to `logos_stencil_arrst_i32`: a truncating 4-byte
4466/// store (lossless under the narrowing proof). A CHECKED store side-exits
4467/// BEFORE the write. An XMM-resident source is bit-copied to a GP reg first.
4468fn emit_arr_store_i32(
4469    g: &mut Gen,
4470    src: Slot,
4471    idx: Slot,
4472    ptr_slot: Slot,
4473    len_slot: Slot,
4474    checked: bool,
4475    dl: Option<LabelId>,
4476) {
4477    g.invalidate_off_cache();
4478    emit_arr_addr_i32(g, idx, ptr_slot, len_slot, checked, dl);
4479    let v = match g.loc[src as usize] {
4480        Loc::Xmm(x) => {
4481            g.asm.movq_rx(S1, x);
4482            S1
4483        }
4484        _ => g.operand(src, SC),
4485    };
4486    g.asm.mov_mr32(S0, 0, v); // *(i32*)addr = value as i32 (low 4 bytes)
4487}
4488
4489/// Lower a pinned-list PUSH (`ArrPush`) with an INLINE FAST PATH plus a cold
4490/// realloc helper call — the V8-style array-push lowering.
4491///
4492/// The common case (the appended element fits the current capacity) runs ENTIRELY
4493/// in scratch registers, with NO SysV call and NO caller-saved spill/reload:
4494///
4495/// ```text
4496///     vec = frame[vec_slot]            // the live *mut Vec
4497///     len = frame[len_slot]            // the mirrored length
4498///     if (len as u64) < (*(vec+cap_off) as u64):    // spare capacity?
4499///         ptr = frame[ptr_slot]
4500///         ptr[len] = value             // store (8-byte raw, or (v!=0) byte)
4501///         len += 1
4502///         frame[len_slot] = len        // refresh the mirror
4503///         *(vec+len_off) = len         //   AND the real Vec::len field
4504///         goto join
4505///     // else fall through to the cold realloc path:
4506///     <spill caller-saved>; helper(frame, vec, ptr, len, value); <reload>
4507///   join:
4508/// ```
4509///
4510/// SOUNDNESS — bit-identical to `logos_rt_push_*` (and thus to `Vec::push` and the
4511/// tree-walker) in every case:
4512/// * The capacity test uses the SAME `cap`/`len` the helper would (`(*vec).len() <
4513///   (*vec).capacity()` is exactly `Vec::push`'s "no grow" condition), read from
4514///   the LIVE `Vec` at PROBED field offsets ([`vec_layout`]) — never a hardcoded
4515///   layout — so it is correct on this exact binary.
4516/// * On the fast path the buffer does NOT move, so `frame[ptr_slot]` stays valid
4517///   (the helper would not refresh it either) and the store lands at the identical
4518///   address `ptr + len*stride` the helper's `(*vec).push` writes.
4519/// * BOTH the mirrored `frame[len_slot]` AND the real `Vec::len` field are bumped,
4520///   so a later non-fast access (a subsequent realloc helper push, a deopt that
4521///   materializes/keeps the live `Rc<Vec>`, or the `Vec`'s eventual drop) observes
4522///   the appended element exactly as after `Vec::push`.
4523/// * The cold path is the ORIGINAL helper-call lowering verbatim: on a realloc
4524///   (`len == cap`) the helper reallocates and refreshes `frame[ptr_slot]` /
4525///   `frame[len_slot]` (and the real `Vec` fields), so the next access reads the
4526///   fresh pointer — the realloc-coherence contract is unchanged.
4527/// * The fast path touches ONLY the reserved scratch registers `S0`/`S1`/`SC`
4528///   (`rax`/`rdx`/`rcx`), which are NEVER assigned to a resident slot, so it
4529///   clobbers no loop-carried value and needs no spill/reload. The cold path keeps
4530///   the full caller-saved spill discipline.
4531/// * The vec/ptr/len triple is forced FRAME-resident (`force_frame_set`), so both
4532///   paths read/write the same frame cells and the helper's view agrees.
4533fn emit_list_push(
4534    g: &mut Gen,
4535    idx: usize,
4536    src: Slot,
4537    vec_slot: Slot,
4538    ptr_slot: Slot,
4539    len_slot: Slot,
4540    helper_addr: i64,
4541    byte: bool,
4542    narrow32: bool,
4543) {
4544    // Kill-switch / A-B toggle: fall back to the always-call helper lowering.
4545    if !inline_push_enabled() {
4546        g.spill_volatiles_at(idx);
4547        g.load(Reg::R8, src);
4548        g.asm.mov_rr(Reg::Rdi, BASE);
4549        g.asm.mov_ri(Reg::Rsi, vec_slot as i64);
4550        g.asm.mov_ri(Reg::Rdx, ptr_slot as i64);
4551        g.asm.mov_ri(Reg::Rcx, len_slot as i64);
4552        g.asm.mov_ri(S0, helper_addr);
4553        g.asm.call_r(S0);
4554        g.reload_volatiles_at(idx);
4555        return;
4556    }
4557
4558    let layout = vec_layout();
4559    let cold = g.asm.new_label();
4560    let join = g.asm.new_label();
4561
4562    // ---- FAST PATH ---- (scratch-only; no spill, no call when len < cap)
4563    // S0 = vec handle (kept live for the real-len writeback); S1 = len; SC = cap.
4564    g.asm.mov_rm(S0, BASE, (vec_slot as i32) * 8);
4565    g.asm.mov_rm(S1, BASE, (len_slot as i32) * 8);
4566    g.asm.mov_rm(SC, S0, layout.cap_off); // SC = (*vec).capacity
4567    g.asm.cmp_rr(S1, SC); // len - cap
4568    g.asm.jcc(Cond::AeU, cold); // (len as u64) >= (cap as u64) -> realloc (cold)
4569
4570    // Materialize the pushed value into SC (cap is dead). An XMM-resident
4571    // float-list value is bit-copied via movq — the raw 8 bytes travel to the
4572    // buffer exactly as the helper's `f64::from_bits(...).push(...)` round-trip.
4573    match g.loc[src as usize] {
4574        Loc::Xmm(x) => g.asm.movq_rx(SC, x),
4575        _ => {
4576            let v = g.operand(src, SC);
4577            if v != SC {
4578                g.asm.mov_rr(SC, v);
4579            }
4580        }
4581    }
4582    // addr = ptr + len*stride, computed into S0 (vec dead now; reloaded below for
4583    // the real-len writeback). S1 still holds `len`.
4584    g.asm.mov_rm(S0, BASE, (ptr_slot as i32) * 8); // S0 = ptr
4585    if narrow32 {
4586        g.asm.shl_ri(S1, 2); // len * 4 (4-byte i32 elements)
4587    } else if !byte {
4588        g.asm.shl_ri(S1, 3); // len * 8 (8-byte i64/f64 elements)
4589    }
4590    g.asm.add_rr(S0, S1); // S0 = ptr + len*stride  (S1 now dead)
4591    if byte {
4592        // 1-byte (`Seq of Bool`) store: the BOOLEAN NORMALIZATION (v != 0) as u8,
4593        // matching `logos_rt_push_bool`'s `(*vec).push(value != 0)`.
4594        g.asm.test_rr(SC, SC);
4595        g.asm.setcc8(Cond::Ne, S1);
4596        g.asm.mov_mr8(S0, 0, S1); // *(u8*)addr = (value != 0) as u8
4597    } else if narrow32 {
4598        // 4-byte (`IntsI32`) store: TRUNCATE the value to its low 4 bytes
4599        // (lossless under the narrowing proof), matching `logos_rt_push_i32`.
4600        g.asm.mov_mr32(S0, 0, SC); // *(i32*)addr = value as i32
4601    } else {
4602        g.asm.mov_mr(S0, 0, SC); // *addr = value (8 raw bytes)
4603    }
4604    // Bump the length: new_len = old_len + 1. Refresh BOTH the mirrored frame
4605    // slot AND the real `Vec::len` field so every later view is coherent.
4606    g.asm.mov_rm(S1, BASE, (len_slot as i32) * 8); // reload old len
4607    g.asm.add_ri(S1, 1); // new_len
4608    g.asm.mov_mr(BASE, (len_slot as i32) * 8, S1); // frame[len_slot] = new_len
4609    g.asm.mov_rm(S0, BASE, (vec_slot as i32) * 8); // reload vec handle
4610    g.asm.mov_mr(S0, layout.len_off, S1); // (*vec).len = new_len
4611    g.asm.jmp(join);
4612
4613    // ---- COLD PATH ---- (realloc: the original helper-call lowering verbatim).
4614    g.asm.bind(cold);
4615    // Spill the LIVE-AFTER caller-saved residents to their frame slots FIRST (the
4616    // helper clobbers them). This must precede touching any arg register: the arg
4617    // registers (rdi/rsi/rdx/rcx/r8) are themselves in the caller-saved pool, so a
4618    // live resident may sit in one of them. Spilling reads each resident's
4619    // register (still intact) into the frame; only AFTER that is it safe to
4620    // overwrite those registers with call args.
4621    g.spill_volatiles_at(idx);
4622    // Materialize the pushed value into the value-arg register (r8) AFTER the
4623    // spill (so no resident's value is lost). XMM-resident floats bit-copy.
4624    g.load(Reg::R8, src);
4625    g.asm.mov_rr(Reg::Rdi, BASE);
4626    g.asm.mov_ri(Reg::Rsi, vec_slot as i64);
4627    g.asm.mov_ri(Reg::Rdx, ptr_slot as i64);
4628    g.asm.mov_ri(Reg::Rcx, len_slot as i64);
4629    g.asm.mov_ri(S0, helper_addr);
4630    g.asm.call_r(S0);
4631    g.reload_volatiles_at(idx);
4632
4633    g.asm.bind(join);
4634}
4635
4636/// Lower a pinned-list in-place CLEAR (`ListClear`) as a SysV call to
4637/// `logos_rt_clear_*(frame, vec_slot, ptr_slot, len_slot)`: truncate the
4638/// SOLE-OWNED buffer to empty (keep its capacity) and refresh
4639/// `frame[ptr_slot]`/`frame[len_slot]` (length → 0). The buffer-reuse
4640/// alias-safety is established UPSTREAM in the micro-op lowering (a
4641/// `Op::NewEmptyList` whose handle escapes via a live `Move` declines to emit
4642/// `ListClear`), so a `ListClear` reaching here is provably unaliased. Same
4643/// frame-resident-triple + caller-saved spill discipline as the push, minus the
4644/// value argument.
4645fn emit_list_clear(
4646    g: &mut Gen,
4647    idx: usize,
4648    vec_slot: Slot,
4649    ptr_slot: Slot,
4650    len_slot: Slot,
4651    helper_addr: i64,
4652) {
4653    g.spill_volatiles_at(idx);
4654    g.asm.mov_rr(Reg::Rdi, BASE);
4655    g.asm.mov_ri(Reg::Rsi, vec_slot as i64);
4656    g.asm.mov_ri(Reg::Rdx, ptr_slot as i64);
4657    g.asm.mov_ri(Reg::Rcx, len_slot as i64);
4658    g.asm.mov_ri(S0, helper_addr);
4659    g.asm.call_r(S0);
4660    g.reload_volatiles_at(idx);
4661}
4662
4663/// Lower a fresh-list ALLOCATION (`NewList`, precise path) as a SysV call to
4664/// `logos_rt_alloc_list_i64(frame, vec_slot, ptr_slot, len_slot)`: the helper
4665/// `Box`-allocates a fresh empty `Vec`, REGISTERS it in the thread-local
4666/// allocation registry (so a deopt drains it and a `Return` detaches it), and
4667/// plants the pin triple — writing `frame[vec_slot]` (the live `*mut Vec`),
4668/// `frame[ptr_slot]` (its buffer pointer) and `frame[len_slot]` (0). The triple
4669/// is forced FRAME-resident (so the helper's frame writes are the single source
4670/// of truth and every later push/load reads the fresh pointer/length); the call
4671/// takes no value argument. Same caller-saved spill discipline as the push/clear
4672/// helpers — bit-identical to the per-piece tier's `ST_ALLOCLIST` stencil.
4673fn emit_new_list(
4674    g: &mut Gen,
4675    idx: usize,
4676    vec_slot: Slot,
4677    ptr_slot: Slot,
4678    len_slot: Slot,
4679    helper_addr: i64,
4680) {
4681    g.spill_volatiles_at(idx);
4682    g.asm.mov_rr(Reg::Rdi, BASE);
4683    g.asm.mov_ri(Reg::Rsi, vec_slot as i64);
4684    g.asm.mov_ri(Reg::Rdx, ptr_slot as i64);
4685    g.asm.mov_ri(Reg::Rcx, len_slot as i64);
4686    g.asm.mov_ri(S0, helper_addr);
4687    g.asm.call_r(S0);
4688    g.reload_volatiles_at(idx);
4689}
4690
4691/// Lower a triple-plant (`ListTriple`, precise path) as a SysV call to
4692/// `logos_rt_list_triple(frame, handle_slot, vec_slot, ptr_slot, len_slot)`: read
4693/// `frame[handle_slot]` (a live `*mut Vec`) and refresh the pin triple. The
4694/// handle and triple slots are all forced FRAME-resident (so the helper's frame
4695/// view is the source of truth). Same caller-saved spill discipline; the handle
4696/// slot rides the fifth SysV arg (`r8`).
4697fn emit_list_triple(
4698    g: &mut Gen,
4699    idx: usize,
4700    handle_slot: Slot,
4701    vec_slot: Slot,
4702    ptr_slot: Slot,
4703    len_slot: Slot,
4704    helper_addr: i64,
4705) {
4706    g.spill_volatiles_at(idx);
4707    g.asm.mov_rr(Reg::Rdi, BASE);
4708    g.asm.mov_ri(Reg::Rsi, handle_slot as i64);
4709    g.asm.mov_ri(Reg::Rdx, vec_slot as i64);
4710    g.asm.mov_ri(Reg::Rcx, ptr_slot as i64);
4711    g.asm.mov_ri(Reg::R8, len_slot as i64);
4712    g.asm.mov_ri(S0, helper_addr);
4713    g.asm.call_r(S0);
4714    g.reload_volatiles_at(idx);
4715}
4716
4717/// Lower a pinned MUTABLE-Text append (`StrAppend`) as a SysV call to the runtime
4718/// helper `logos_rt_str_append(frame, handle_slot, src, src_len)`: the helper
4719/// reads `frame[handle_slot]` (a live `*mut Value` to the VM accumulator cell)
4720/// and grows the accumulator with EXACTLY the VM's `add_assign` (in-place when
4721/// sole-owned, copy-on-write otherwise) semantics. The handle slot is forced
4722/// FRAME-resident (the helper indexes it). The source is either a 1-char frame
4723/// BYTE — read AFTER the spill into the value-arg register `rdx`, with `rcx` =
4724/// `-1` flagging the byte form — or a baked constant byte slice (`rdx` = the
4725/// `'static` pointer, `rcx` = its length). Same caller-saved spill discipline as
4726/// the list-push helper.
4727fn emit_str_append(
4728    g: &mut Gen,
4729    idx: usize,
4730    handle_slot: Slot,
4731    src: crate::jit::StrSrc,
4732    helper_addr: i64,
4733) {
4734    // Spill the LIVE-AFTER caller-saved residents FIRST (the helper clobbers
4735    // them; the arg registers are themselves caller-saved). The byte-form value
4736    // is read AFTER the spill (so no resident is lost) but BEFORE the arg
4737    // registers overwrite the register the source might still occupy.
4738    g.spill_volatiles_at(idx);
4739    match src {
4740        crate::jit::StrSrc::Byte(s) => {
4741            g.load(Reg::Rdx, s);
4742            g.asm.mov_ri(Reg::Rcx, -1);
4743        }
4744        crate::jit::StrSrc::Int(s) => {
4745            g.load(Reg::Rdx, s);
4746            g.asm.mov_ri(Reg::Rcx, -2);
4747        }
4748        crate::jit::StrSrc::Const { ptr, len } => {
4749            g.asm.mov_ri(Reg::Rdx, ptr);
4750            g.asm.mov_ri(Reg::Rcx, len);
4751        }
4752    }
4753    g.asm.mov_rr(Reg::Rdi, BASE);
4754    g.asm.mov_ri(Reg::Rsi, handle_slot as i64);
4755    g.asm.mov_ri(S0, helper_addr);
4756    g.asm.call_r(S0);
4757    g.reload_volatiles_at(idx);
4758}
4759
4760#[derive(Clone, Copy)]
4761enum AsmBinop {
4762    Add,
4763    Mul,
4764    And,
4765    Or,
4766    Xor,
4767}
4768
4769/// `dst = lhs OP rhs` for a commutative op. Compute in S0 to avoid clobbering a
4770/// resident operand that may be read again later. Integer `add`/`imul` SIDE-EXIT
4771/// on signed overflow (`jo` → this op's deopt label) BEFORE the store, so the
4772/// exact tier recomputes and promotes to BigInt; bitwise ops cannot overflow.
4773fn emit_commutative(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, op: AsmBinop, idx: usize) {
4774    g.load(S0, lhs);
4775    let b = g.operand(rhs, S1);
4776    match op {
4777        AsmBinop::Add => g.asm.add_rr(S0, b),
4778        AsmBinop::Mul => g.asm.imul_rr(S0, b),
4779        AsmBinop::And => g.asm.and_rr(S0, b),
4780        AsmBinop::Or => g.asm.or_rr(S0, b),
4781        AsmBinop::Xor => g.asm.xor_rr(S0, b),
4782    }
4783    if matches!(op, AsmBinop::Add | AsmBinop::Mul) {
4784        if let Some(dl) = g.checked_exit(idx) {
4785            g.asm.jcc(Cond::Overflow, dl);
4786        }
4787    }
4788    g.store(dst, S0);
4789}
4790
4791/// `dst = lhs - rhs` (non-commutative). lhs into S0, then `sub S0, rhs`; `jo` →
4792/// deopt on signed overflow (before the store) so the exact tier promotes.
4793fn emit_sub(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, idx: usize) {
4794    g.load(S0, lhs);
4795    let b = g.operand(rhs, S1);
4796    g.asm.sub_rr(S0, b);
4797    if let Some(dl) = g.checked_exit(idx) {
4798        g.asm.jcc(Cond::Overflow, dl);
4799    }
4800    g.store(dst, S0);
4801}
4802
4803/// `dst = (lhs CMP rhs) as i64` — `cmp` then `setcc`/`movzx`.
4804fn emit_compare(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, cond: Cond) {
4805    let a = g.operand(lhs, S0);
4806    let b = g.operand(rhs, S1);
4807    g.asm.cmp_rr(a, b);
4808    g.asm.setcc_movzx(cond, S0);
4809    g.store(dst, S0);
4810}
4811
4812#[derive(Clone, Copy)]
4813enum FBinop {
4814    Add,
4815    Sub,
4816    Mul,
4817}
4818
4819/// `dst = lhs OP rhs` for an f64 arithmetic op (`addsd`/`subsd`/`mulsd`).
4820///
4821/// The instruction order is ALWAYS the source order — `OP target, second`
4822/// computes `target OP second` — so a non-commutative `subsd` keeps `lhs - rhs`
4823/// and the result is bit-identical to the reference regardless of which fast
4824/// path fires. No reassociation, no FMA.
4825///
4826/// When `dst` is XMM-resident we compute IN PLACE in `dst`, avoiding the
4827/// `fload`→FS0 + `fstore`→dst scratch round-trip (two extra `movsd`s) that the
4828/// scratch path pays every iteration on a loop-carried accumulator (nbody's
4829/// dx/dy/dz/dist, mandelbrot's zr/zi):
4830/// - `dst == lhs` (in-place `x = x OP rhs`): just `OP dst, rhs` — no moves;
4831/// - `dst != lhs` and `dst != rhs`: `movsd dst, lhs; OP dst, rhs` — the result
4832///   lands in `dst` directly (one move, no store).
4833/// The remaining case (`dst` resident, `dst == rhs`, `dst != lhs`) cannot write
4834/// `dst` first without clobbering `rhs`, so it falls through to FS0 staging.
4835fn emit_fbinop(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, op: FBinop) {
4836    let apply = |asm: &mut Asm, target: Xmm, second: Xmm| match op {
4837        FBinop::Add => asm.addsd_rr(target, second),
4838        FBinop::Sub => asm.subsd_rr(target, second),
4839        FBinop::Mul => asm.mulsd_rr(target, second),
4840    };
4841    if let Loc::Xmm(d) = g.loc[dst as usize] {
4842        // Resolve rhs to a concrete register first (its own resident XMM, or
4843        // FS1 if frame-resident). FS1 is scratch and never a slot's residence,
4844        // so a frame-resident rhs never collides with `d`.
4845        let b = g.foperand(rhs, FS1);
4846        if g.loc[lhs as usize] == Loc::Xmm(d) {
4847            // In-place accumulate: dst and lhs ARE the same register.
4848            apply(&mut g.asm, d, b);
4849            return;
4850        }
4851        if d != b {
4852            // Materialize lhs into dst, then op against rhs — result in dst.
4853            g.fload(d, lhs);
4854            apply(&mut g.asm, d, b);
4855            return;
4856        }
4857        // d == b (dst aliases rhs, dst != lhs): writing dst first would lose
4858        // rhs; fall through to the scratch path, which reads rhs (b == d) before
4859        // overwriting dst.
4860        g.fload(FS0, lhs);
4861        apply(&mut g.asm, FS0, b);
4862        g.fstore(dst, FS0);
4863        return;
4864    }
4865    g.fload(FS0, lhs);
4866    let b = g.foperand(rhs, FS1);
4867    apply(&mut g.asm, FS0, b);
4868    g.fstore(dst, FS0);
4869}
4870
4871/// `dst = lhs / rhs` (f64), side-EXITING to the deopt epilogue when the divisor
4872/// is `0.0` — bit-identical to the reference (`b == 0.0 -> None`). The IEEE
4873/// `0.0 == -0.0` makes BOTH zeros trip it: the divisor bits are compared to 0.0
4874/// via `ucomisd`, and `ucomisd -0.0, 0.0` sets ZF (equal), so `je deopt` fires
4875/// for `-0.0` too. NaN divisor is NOT zero (ucomisd sets PF, ZF — but `je` on a
4876/// NaN-vs-0 compare: NaN is unordered → ZF=1 → would wrongly deopt). Guard the
4877/// NaN case: only deopt when the unordered flag is CLEAR (an ordered equality).
4878fn emit_fdiv(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, dl: LabelId) {
4879    // Zero-divisor side-exit: compare rhs to 0.0. Build 0.0 in FS1 (xorps would
4880    // need a new encoder; instead movq from a zeroed GP reg).
4881    let b = g.foperand(rhs, FS1);
4882    // FS0 = 0.0 via movq from a zeroed GP scratch.
4883    g.asm.mov_ri(S0, 0);
4884    g.asm.movq_xr(FS0, S0);
4885    g.asm.ucomisd_rr(b, FS0); // compare rhs, 0.0
4886                              // An ORDERED equality (rhs == 0.0, incl -0.0) sets ZF=1, PF=0. A NaN divisor
4887                              // is unordered: ZF=1, PF=1 — must NOT deopt (NaN/x is a valid IEEE result).
4888                              // So skip the deopt when PF=1 (unordered), then `je` on the ordered equal.
4889    let not_zero = g.asm.new_label();
4890    g.asm.jcc(Cond::ParityEven, not_zero); // unordered (NaN) -> not a zero divisor
4891    g.asm.jcc(Cond::Eq, dl); // ordered equal to 0.0 -> side-exit
4892    g.asm.bind(not_zero);
4893    // Normal divide: FS0 = lhs; FS0 /= rhs.
4894    g.fload(FS0, lhs);
4895    let b2 = g.foperand(rhs, FS1);
4896    g.asm.divsd_rr(FS0, b2);
4897    g.fstore(dst, FS0);
4898}
4899
4900#[derive(Clone, Copy)]
4901enum FCmp {
4902    Lt,
4903    Gt,
4904    Le,
4905    Ge,
4906}
4907
4908/// `dst = (lhs CMP rhs) as i64` for an f64 ORDERING compare, exact IEEE: a NaN
4909/// operand makes the result FALSE (0). Implemented via `ucomisd` + an UNSIGNED
4910/// setcc — for `>`/`>=` directly (`a` then `b`), for `<`/`<=` by SWAPPING the
4911/// operands (so `a < b` ≡ `b > a`). The unordered (NaN) case sets ZF=CF=1, which
4912/// the `seta`/`setae` family reads as FALSE, matching the reference.
4913fn emit_fcompare(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, cmp: FCmp) {
4914    // Decide operand order + the unsigned condition.
4915    let (a, b, cond) = match cmp {
4916        FCmp::Gt => (lhs, rhs, Cond::AU),  // a > b   : ucomisd a,b ; seta
4917        FCmp::Ge => (lhs, rhs, Cond::AeU), // a >= b  : ucomisd a,b ; setae
4918        FCmp::Lt => (rhs, lhs, Cond::AU),  // a < b ≡ b > a : ucomisd b,a ; seta
4919        FCmp::Le => (rhs, lhs, Cond::AeU), // a <= b ≡ b >= a : ucomisd b,a ; setae
4920    };
4921    let xa = g.foperand(a, FS0);
4922    let xb = g.foperand(b, FS1);
4923    g.asm.ucomisd_rr(xa, xb);
4924    g.asm.setcc_movzx(cond, S0);
4925    g.store(dst, S0);
4926}
4927
4928/// `dst = (lhs == rhs) as i64` (when `neg` is false) or `(lhs != rhs)` (`neg`
4929/// true) — IEEE float equality via `ucomisd`: ordered-equal ⟺ ZF=1 && PF=0
4930/// (PF=1 ⟺ unordered, i.e. a NaN operand, which must yield false for `==`
4931/// and true for `!=`) — bit-identical to the reference's `a == b`.
4932fn emit_feq(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, neg: bool) {
4933    let xa = g.foperand(lhs, FS0);
4934    let xb = g.foperand(rhs, FS1);
4935    g.asm.ucomisd_rr(xa, xb);
4936    if neg {
4937        // neq = ZF==0 || PF==1 (`setne` | `setp`).
4938        g.asm.setcc_movzx(Cond::Ne, S0);
4939        g.asm.setcc_movzx(Cond::ParityEven, S1);
4940        g.asm.or_rr(S0, S1);
4941    } else {
4942        // eq = ZF==1 && PF==0 (`sete` & `setnp`).
4943        g.asm.setcc_movzx(Cond::Eq, S0);
4944        g.asm.setcc_movzx(Cond::ParityOdd, S1);
4945        g.asm.and_rr(S0, S1);
4946    }
4947    g.store(dst, S0);
4948}
4949
4950/// Fused f64 compare-and-branch: transfer to `target` when `cmp(lhs, rhs)` is
4951/// FALSE — which, under IEEE, includes every NaN-unordered comparison (the
4952/// reference's `BranchF`). Ordering compares use `ucomisd` + the negated
4953/// unsigned jcc; epsilon (Eq/NotEq) reuses the `emit_feq` value then tests it.
4954fn emit_branchf(g: &mut Gen, cmp: Cmp, lhs: Slot, rhs: Slot, target: LabelId) {
4955    match cmp {
4956        Cmp::Lt | Cmp::Gt | Cmp::LtEq | Cmp::GtEq => {
4957            // For each, pick (a, b) and the "FALSE" unsigned jcc. The branch is
4958            // taken when the comparison is FALSE; NaN (unordered: CF=ZF=1) must
4959            // TAKE the false branch.
4960            //   a > b  true = seta(CF=0&&ZF=0) ; false = jbe(CF=1||ZF=1)
4961            //   a >= b true = setae(CF=0)       ; false = jb (CF=1)
4962            let (a, b, false_cond) = match cmp {
4963                Cmp::Gt => (lhs, rhs, Cond::BeU),  // !(a>b)
4964                Cmp::GtEq => (lhs, rhs, Cond::BU), // !(a>=b)
4965                Cmp::Lt => (rhs, lhs, Cond::BeU),  // a<b ≡ b>a ; !(b>a)
4966                Cmp::LtEq => (rhs, lhs, Cond::BU), // a<=b ≡ b>=a ; !(b>=a)
4967                _ => unreachable!(),
4968            };
4969            let xa = g.foperand(a, FS0);
4970            let xb = g.foperand(b, FS1);
4971            g.asm.ucomisd_rr(xa, xb);
4972            g.asm.jcc(false_cond, target);
4973        }
4974        Cmp::Eq | Cmp::NotEq => {
4975            // IEEE (in)equality; branch when the comparison is FALSE.
4976            let xa = g.foperand(lhs, FS0);
4977            let xb = g.foperand(rhs, FS1);
4978            g.asm.ucomisd_rr(xa, xb);
4979            if matches!(cmp, Cmp::Eq) {
4980                // truth = ordered-equal; FALSE = ZF==0 || PF==1 — two direct
4981                // jumps, and a NaN (PF=1) takes the false branch.
4982                g.asm.jcc(Cond::Ne, target);
4983                g.asm.jcc(Cond::ParityEven, target);
4984                return;
4985            }
4986            // truth = (a != b); FALSE = ordered-equal (ZF==1 && PF==0).
4987            // Materialize the IEEE neq exactly like `emit_feq`, then branch
4988            // on zero.
4989            g.asm.setcc_movzx(Cond::Ne, S0);
4990            g.asm.setcc_movzx(Cond::ParityEven, S1);
4991            g.asm.or_rr(S0, S1);
4992            g.asm.test_rr(S0, S0);
4993            g.asm.jcc(Cond::Eq, target); // truth == 0 → jump (false branch)
4994        }
4995    }
4996}
4997
4998#[derive(Clone, Copy)]
4999enum ShiftKind {
5000    Left,
5001    Right,
5002    /// LOGICAL (unsigned) shift right — zero-fill, for `Ushr` (Word64 `word64Shr`/rotate substrate).
5003    LogicalRight,
5004}
5005
5006/// `dst = lhs <</>> rhs` with the kernel's shift spec: the count is the low
5007/// bits of `rhs` (x86 masks the count mod 64 for 64-bit operands, matching
5008/// `wrapping_shl`/`wrapping_shr`'s `as u32 % 64`). The value goes in S0, the
5009/// count in `cl` (rcx).
5010fn emit_shift(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, kind: ShiftKind) {
5011    g.load(S0, lhs);
5012    g.load(SC, rhs);
5013    match kind {
5014        ShiftKind::Left => g.asm.shl_cl(S0),
5015        ShiftKind::Right => g.asm.sar_cl(S0),
5016        ShiftKind::LogicalRight => g.asm.shr_cl(S0),
5017    }
5018    g.store(dst, S0);
5019}
5020
5021/// `dst = rotate(lhs, rhs)` in one x86 instruction. The count is read through
5022/// CL; x86 masks it to 5 or 6 bits according to operand width, exactly matching
5023/// Word32/Word64 LOGOS semantics. A 32-bit register write also zero-extends the
5024/// Word32 result, so no trailing mask is needed.
5025fn emit_rotate(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, width32: bool, left: bool) {
5026    g.load(S0, lhs);
5027    g.load(SC, rhs);
5028    if left {
5029        g.asm.rol_cl(S0, width32);
5030    } else {
5031        g.asm.ror_cl(S0, width32);
5032    }
5033    g.store(dst, S0);
5034}
5035
5036/// `dst = lhs / 2^k` (signed, round toward zero) via the sign-correcting shift,
5037/// bit-exact with `reference_eval`'s `DivPow2`:
5038/// `(x + ((x >> 63) & ((1<<k)-1))) >> k`.
5039fn emit_div_pow2(g: &mut Gen, dst: Slot, lhs: Slot, k: u32) {
5040    g.load(S0, lhs); // x
5041                     // S1 = x >> 63 (sign mask, arithmetic).
5042    g.asm.mov_rr(S1, S0);
5043    g.asm.mov_ri(SC, 63);
5044    g.asm.sar_cl(S1);
5045    // S1 &= (1<<k) - 1
5046    let mask = (1i64 << k) - 1;
5047    g.asm.mov_ri(SC, mask);
5048    g.asm.and_rr(S1, SC);
5049    // S0 = x + S1
5050    g.asm.add_rr(S0, S1);
5051    // S0 >>= k (arithmetic)
5052    g.asm.mov_ri(SC, k as i64);
5053    g.asm.sar_cl(S0);
5054    g.store(dst, S0);
5055}
5056
5057/// `dst = lhs / c` (`mul_back == 0`) or `dst = lhs % c` (`mul_back == c`) via the
5058/// Granlund–Montgomery / libdivide UNSIGNED magic reciprocal — bit-exact with
5059/// `reference_eval`'s `MagicDivU` and the VM's `magic_eval`. Emitted only for a
5060/// proven non-negative dividend, so the unsigned arithmetic equals the signed
5061/// truncating result.
5062///
5063/// Register choreography: RAX/RDX/RCX (S0/S1/SC) are reserved scratch — no slot
5064/// is ever resident there, so `mul`'s implicit RDX:RAX clobber is safe. The
5065/// dividend's home slot (`lhs`) is never written, so it is RELOADED whenever the
5066/// add-fixup or the remainder needs `x` again.
5067///
5068/// Quotient: `q_hi = mulhi_u(magic, x)`; with the add-marker path
5069/// `q = ((x - q_hi) >> 1 + q_hi) >> shift`, else `q = q_hi >> shift`. The
5070/// quotient lands in S0 (RAX). Remainder: `r = x - q*c` (S0 ← x - q*c).
5071fn emit_magic_div(g: &mut Gen, dst: Slot, lhs: Slot, magic: u64, more: u8, mul_back: i64) {
5072    const SHIFT_MASK: u8 = 0x3F;
5073    const ADD_MARKER: u8 = 0x40;
5074    const SHIFT_PATH: u8 = 0x80;
5075    let shift = (more & SHIFT_MASK) as u8;
5076
5077    if more & SHIFT_PATH != 0 {
5078        // Pure power-of-two path (never emitted by the compiler for the non-pow2
5079        // gate, but executed identically here for completeness): q = x >> shift,
5080        // LOGICAL — sound because x is non-negative.
5081        g.load(S0, lhs);
5082        if shift != 0 {
5083            g.asm.shr_ri(S0, shift);
5084        }
5085        finish_magic(g, dst, lhs, mul_back);
5086        return;
5087    }
5088
5089    // q_hi = high 64 bits of the UNSIGNED product magic * x.
5090    g.asm.mov_ri(SC, magic as i64); // RCX = magic
5091    g.load(S0, lhs); // RAX = x
5092    g.asm.mul_r(SC); // RDX:RAX = x * magic; RDX = q_hi
5093
5094    if more & ADD_MARKER != 0 {
5095        // q = ((x - q_hi) >> 1).wrapping_add(q_hi) >> shift.
5096        g.load(SC, lhs); // RCX = x (reload; lhs home is untouched)
5097        g.asm.sub_rr(SC, S1); // RCX = x - q_hi
5098        g.asm.shr_ri(SC, 1); // RCX = (x - q_hi) >> 1  (logical)
5099        g.asm.add_rr(SC, S1); // RCX = t
5100        if shift != 0 {
5101            g.asm.shr_ri(SC, shift); // RCX = q
5102        }
5103        g.asm.mov_rr(S0, SC); // RAX = q
5104    } else {
5105        // q = q_hi >> shift.
5106        if shift != 0 {
5107            g.asm.shr_ri(S1, shift); // RDX = q
5108        }
5109        g.asm.mov_rr(S0, S1); // RAX = q
5110    }
5111    finish_magic(g, dst, lhs, mul_back);
5112}
5113
5114/// Common tail: the quotient is in S0 (RAX). For division store it; for modulo
5115/// compute `r = x - q*c` (`mul_back == c`) and store that.
5116fn finish_magic(g: &mut Gen, dst: Slot, lhs: Slot, mul_back: i64) {
5117    if mul_back == 0 {
5118        g.store(dst, S0); // quotient
5119    } else {
5120        // r = x - q*c.  RAX holds q.
5121        g.asm.mov_ri(SC, mul_back); // RCX = c
5122        g.asm.imul_rr(S0, SC); // RAX = q * c (low 64 bits suffice)
5123        g.load(SC, lhs); // RCX = x (reload)
5124        g.asm.sub_rr(SC, S0); // RCX = x - q*c
5125        g.store(dst, SC); // remainder
5126    }
5127}
5128
5129/// `dst = lhs / rhs` (quotient) or `lhs % rhs` (remainder), with a zero-divisor
5130/// SIDE-EXIT before any effect and the kernel's `MIN op -1` overflow handling
5131/// (no `#DE` trap): if `rhs == -1` then quotient = `0 - lhs` (== MIN for MIN)
5132/// and remainder = 0.
5133fn emit_div_mod(g: &mut Gen, dst: Slot, lhs: Slot, rhs: Slot, is_div: bool, dl: LabelId) {
5134    // Load divisor into S1 (rdx is overwritten by cqo, so keep divisor in a
5135    // register that survives; use SC=rcx for the divisor instead).
5136    g.load(SC, rhs); // divisor in rcx
5137                     // Zero check: side-exit if rcx == 0.
5138    g.asm.test_rr(SC, SC);
5139    g.asm.jcc(Cond::Eq, dl);
5140    // Overflow guard: if divisor == -1, avoid #DE. quotient = -lhs, rem = 0.
5141    let neg_one = g.asm.new_label();
5142    let done = g.asm.new_label();
5143    g.asm.mov_ri(S1, -1);
5144    g.asm.cmp_rr(SC, S1); // compare divisor with -1
5145    g.asm.jcc(Cond::Eq, neg_one);
5146    // Normal path: rax = lhs; cqo; idiv rcx.
5147    g.load(S0, lhs);
5148    g.asm.cqo();
5149    g.asm.idiv_r(SC); // quotient -> rax, remainder -> rdx
5150    if is_div {
5151        // result already in rax (S0)
5152    } else {
5153        g.asm.mov_rr(S0, S1); // remainder rdx -> rax
5154    }
5155    g.asm.jmp(done);
5156    // divisor == -1 path.
5157    g.asm.bind(neg_one);
5158    if is_div {
5159        // quotient = -lhs — EXCEPT `i64::MIN`, whose negation overflows:
5160        // side-exit so the exact tier recomputes (and promotes to BigInt).
5161        g.load(S0, lhs);
5162        g.asm.mov_ri(S1, i64::MIN);
5163        g.asm.cmp_rr(S0, S1);
5164        g.asm.jcc(Cond::Eq, dl);
5165        g.asm.neg_r(S0);
5166    } else {
5167        // remainder = 0
5168        g.asm.mov_ri(S0, 0);
5169    }
5170    g.asm.bind(done);
5171    g.store(dst, S0);
5172}
5173
5174#[cfg(test)]
5175#[path = "../../logicaffeine_tests/unit/logicaffeine_forge/regalloc/tests.rs"]
5176mod tests;