Skip to main content

logicaffeine_forge/
jit.rs

1//! J1: the straight-line micro-op compiler — bytecode in, native code out.
2//!
3//! [`MicroOp`] is the JIT's input IR: the integer subset of the bytecode VM's
4//! register operations. [`compile_straightline`] lowers each op to a fixed
5//! stencil micro-sequence over the frame/operand-stack machine model and glues
6//! the result into one executable chain:
7//!
8//! ```text
9//! LoadConst{dst,v}  →  const(v); slot_set(dst)
10//! Move{dst,src}     →  slot_get(src); slot_set(dst)
11//! Add{dst,l,r}      →  slot_get(l); slot_get(r); addi; slot_set(dst)
12//! …                    (Sub/Mul/Lt/Eq identical shape)
13//! Gt{dst,l,r}       →  slot_get(r); slot_get(l); lti; slot_set(dst)   (swap)
14//! Return{src}       →  slot_get(src); return
15//! ```
16//!
17//! Anything outside this subset is the caller's tier-up bail (`None` from the
18//! adapter) — the VM keeps running it.
19
20use std::sync::atomic::{AtomicI64, Ordering};
21
22use crate::buffer::{HoleValue, JitBuffer, JitChain};
23use crate::{
24    ST_ADD3, ST_ADDF3, ST_ALLOCLIST, ST_AND3, ST_ARRCONDSWAP_GE, ST_ARRCONDSWAP_GE_U,
25    ST_ARRCONDSWAP_GT, ST_ARRCONDSWAP_GT_U, ST_ARRCONDSWAP_LE, ST_ARRCONDSWAP_LE_U,
26    ST_ARRCONDSWAP_LT, ST_ARRCONDSWAP_LT_U, ST_ARRLD, ST_ARRLD2_ADD, ST_ARRLD2_ADDF,
27    ST_ARRLD2_ADD_U, ST_ARRLD2_MUL, ST_ARRLD2_MULF, ST_ARRLD2_MUL_U, ST_ARRLD2_SUB, ST_ARRLD2_SUBF,
28    ST_ARRLD2_SUB_U, ST_ARRLDAFF_ADD, ST_ARRLDAFF_ADD_U, ST_ARRLDAFF_MUL, ST_ARRLDAFF_MUL_U,
29    ST_ARRLDAFF_NONE, ST_ARRLDAFF_NONE_U, ST_ARRLDAFF_SUB, ST_ARRLDAFF_SUB_U, ST_ARRLDB,
30    ST_ARRLDB_U, ST_ARRLD_I32, ST_ARRLD_I32_U, ST_ARRLD_U, ST_ARRRMW_ADD, ST_ARRRMW_ADDF,
31    ST_ARRRMW_ADDF_U, ST_ARRRMW_ADD_U, ST_ARRRMW_AND, ST_ARRRMW_AND_U, ST_ARRRMW_MUL,
32    ST_ARRRMW_MULF, ST_ARRRMW_MULF_U, ST_ARRRMW_MUL_U, ST_ARRRMW_OR, ST_ARRRMW_OR_U, ST_ARRRMW_SUB,
33    ST_ARRRMW_SUBF, ST_ARRRMW_SUBF_U, ST_ARRRMW_SUB_U, ST_ARRRMW_XOR, ST_ARRRMW_XOR_U, ST_ARRST,
34    ST_ARRSTB, ST_ARRSTB_U, ST_ARRST_I32, ST_ARRST_I32_U, ST_ARRST_U, ST_ARRSWAP, ST_ARRSWAP_U,
35    ST_BREQ, ST_BREQF, ST_BRLEF, ST_BRLT, ST_BRLTF, ST_BRZ, ST_CALL, ST_CALL_PRECISE, ST_CALL_SELF,
36    ST_CALL_SELF_COPY, ST_CEILF2, ST_CHRGUARD, ST_CONSTST, ST_DEOPT, ST_DEOPT_AT, ST_DIV3C,
37    ST_DIVF3C, ST_DIVPOW2, ST_EQ3, ST_EQF3, ST_FLOORF2, ST_FMAF, ST_HOST, ST_I2F2, ST_JUMP, ST_LE3,
38    ST_LEF3, ST_LISTTRIPLE, ST_LIST_CLEAR, ST_LT3, ST_LTF3, ST_LZCNT2, ST_MAGICDIV, ST_MAPHGET,
39    ST_MAPHHAS, ST_MAPHSET, ST_MEMMEM, ST_MOD3C, ST_MOVSS, ST_MUL3, ST_MULF3, ST_NE3, ST_NEF3,
40    ST_NOTB2, ST_NOTI2, ST_OR3, ST_POPCNT2, ST_PUSH, ST_RET2, ST_ROL32_3, ST_ROL64_3, ST_ROR32_3,
41    ST_ROR64_3, ST_ROUNDF2, ST_SHL3, ST_SHR3, ST_SQRTF2, ST_SUB3, ST_SUBF3, ST_TZCNT2, ST_USHR3,
42    ST_UTF8LEN2, ST_XOR3, V_ARRLD_RPTR, V_ARRLD_RPTR_C, V_ARRST_RPTR, V_ARRST_RPTR_C, V_BINOP,
43    V_BRANCH, V_BRANCHF, V_CEILF, V_CHRGUARD, V_CONST, V_DIVF, V_FBINOP, V_FLOORF, V_FMOV, V_I2F,
44    V_LZCNT, V_MOV, V_POPCNT, V_RET, V_ROUNDF, V_SQRTF, V_TZCNT, V_UTF8LEN,
45};
46
47/// Frame slot index (a VM register number).
48pub type Slot = u16;
49
50/// The kernel's locked maximum LOGOS call depth, BAKED into the precise and
51/// self call stencils (their holes are all spoken for, so the limit cannot be
52/// a runtime hole). It mirrors `logicaffeine_compile::semantics::MAX_CALL_DEPTH`
53/// and the matching constant in `stencils/int_stencils.rs`; the callers in the
54/// JIT crate pass that same value, asserted here at stencil selection so a
55/// drift fails loudly instead of silently capping native recursion at the wrong
56/// depth (which would diverge from the kernel's depth-exceeded error).
57pub const BAKED_CALL_DEPTH: i64 = 2_500;
58
59/// Comparison kinds for [`MicroOp::Branch`].
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum Cmp {
62    /// `lhs < rhs`
63    Lt,
64    /// `lhs > rhs`
65    Gt,
66    /// `lhs <= rhs`
67    LtEq,
68    /// `lhs >= rhs`
69    GtEq,
70    /// `lhs == rhs`
71    Eq,
72    /// `lhs != rhs`
73    NotEq,
74}
75
76impl Cmp {
77    /// Evaluate over two i64s.
78    pub fn eval(self, a: i64, b: i64) -> bool {
79        match self {
80            Cmp::Lt => a < b,
81            Cmp::Gt => a > b,
82            Cmp::LtEq => a <= b,
83            Cmp::GtEq => a >= b,
84            Cmp::Eq => a == b,
85            Cmp::NotEq => a != b,
86        }
87    }
88
89    /// The comparison with the opposite truth value.
90    pub fn negated(self) -> Cmp {
91        match self {
92            Cmp::Lt => Cmp::GtEq,
93            Cmp::Gt => Cmp::LtEq,
94            Cmp::LtEq => Cmp::Gt,
95            Cmp::GtEq => Cmp::Lt,
96            Cmp::Eq => Cmp::NotEq,
97            Cmp::NotEq => Cmp::Eq,
98        }
99    }
100}
101
102/// The float binary operation of a fused [`MicroOp::ArrLoad2F`].
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub enum FOp {
105    /// IEEE addition.
106    Add,
107    /// IEEE subtraction.
108    Sub,
109    /// IEEE multiplication.
110    Mul,
111}
112
113impl FOp {
114    /// Apply over two f64s.
115    pub fn eval(self, a: f64, b: f64) -> f64 {
116        match self {
117            FOp::Add => a + b,
118            FOp::Sub => a - b,
119            FOp::Mul => a * b,
120        }
121    }
122}
123
124/// The integer binary operation of a fused two-buffer [`MicroOp::ArrLoad2`]:
125/// `frame[dst] = a[i-1] <op> b[j-1]`, the two elements loaded from two
126/// (possibly distinct) pinned 8-byte int buffers. Add/Mul commute; Sub does
127/// not (it only fuses `a[i] - b[j]`).
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum IOp {
130    /// Wrapping i64 addition.
131    Add,
132    /// Wrapping i64 subtraction.
133    Sub,
134    /// Wrapping i64 multiplication.
135    Mul,
136}
137
138impl IOp {
139    /// Apply over two i64s with the kernel's wrapping semantics.
140    pub fn eval(self, a: i64, b: i64) -> i64 {
141        match self {
142            IOp::Add => a.wrapping_add(b),
143            IOp::Sub => a.wrapping_sub(b),
144            IOp::Mul => a.wrapping_mul(b),
145        }
146    }
147}
148
149/// The index-arithmetic shape folded into a fused [`MicroOp::ArrLoadAffine`].
150/// The computed 1-based index is `(frame[a] OP frame[b]).wrapping_add(c)` for a
151/// two-slot op, or `frame[a].wrapping_add(c)` for [`AffOp::None`] (a single slot
152/// plus a constant). The op wraps with the kernel's exact i64 semantics so the
153/// load is bit-identical to the un-fused index arithmetic + `ArrLoad`.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum AffOp {
156    /// No second slot: `idx = frame[a] + c` (the `w + 1` shape).
157    None,
158    /// `idx = (frame[a] + frame[b]) + c` (the `i*n + j + 1` tail).
159    Add,
160    /// `idx = (frame[a] - frame[b]) + c` (the `w - wi + 1` shape).
161    Sub,
162    /// `idx = (frame[a] * frame[b]) + c`.
163    Mul,
164}
165
166impl AffOp {
167    /// Compute the 1-based index with the kernel's wrapping i64 semantics.
168    pub fn eval(self, a: i64, b: i64, c: i64) -> i64 {
169        match self {
170            AffOp::None => a.wrapping_add(c),
171            AffOp::Add => a.wrapping_add(b).wrapping_add(c),
172            AffOp::Sub => a.wrapping_sub(b).wrapping_add(c),
173            AffOp::Mul => a.wrapping_mul(b).wrapping_add(c),
174        }
175    }
176}
177
178/// The operation of a fused read-modify-write [`MicroOp::ArrRMW`]:
179/// `buf[idx-1] = buf[idx-1] <op> operand`. The INT ops (Add/Sub/Mul wrap as the
180/// kernel's i64 arithmetic; And/Or/Xor bitwise) treat the element and operand as
181/// raw i64; the FLOAT ops (AddF/SubF/MulF) reinterpret both as f64 (the nbody
182/// velocity/position-update idiom). Sub/SubF are the only non-commutative
183/// members — the peephole fuses them only when the loaded element is the LEFT
184/// operand.
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub enum RmwOp {
187    /// Wrapping addition.
188    Add,
189    /// Wrapping subtraction (`buf[i] - operand`).
190    Sub,
191    /// Wrapping multiplication.
192    Mul,
193    /// Bitwise AND.
194    And,
195    /// Bitwise OR.
196    Or,
197    /// Bitwise XOR.
198    Xor,
199    /// IEEE addition (operands reinterpreted as f64).
200    AddF,
201    /// IEEE subtraction (`buf[i] - operand`, as f64).
202    SubF,
203    /// IEEE multiplication (as f64).
204    MulF,
205}
206
207impl RmwOp {
208    /// Whether the op reinterprets its operands as f64.
209    pub fn is_float(self) -> bool {
210        matches!(self, RmwOp::AddF | RmwOp::SubF | RmwOp::MulF)
211    }
212
213    /// Apply over the raw i64 bits of the element and operand — the bit-exact
214    /// spec every stencil must match. Float ops reinterpret the bits as f64,
215    /// compute, and re-encode (copy-and-patch never reassociates, so ordering is
216    /// exact).
217    pub fn eval(self, a: i64, b: i64) -> i64 {
218        match self {
219            RmwOp::Add => a.wrapping_add(b),
220            RmwOp::Sub => a.wrapping_sub(b),
221            RmwOp::Mul => a.wrapping_mul(b),
222            RmwOp::And => a & b,
223            RmwOp::Or => a | b,
224            RmwOp::Xor => a ^ b,
225            RmwOp::AddF => (f64::from_bits(a as u64) + f64::from_bits(b as u64)).to_bits() as i64,
226            RmwOp::SubF => (f64::from_bits(a as u64) - f64::from_bits(b as u64)).to_bits() as i64,
227            RmwOp::MulF => (f64::from_bits(a as u64) * f64::from_bits(b as u64)).to_bits() as i64,
228        }
229    }
230}
231
232/// The source operand appended by a [`MicroOp::StrAppend`] — the right-hand side
233/// of a `Set text to text + <s>` in a pinned mutable-Text build loop.
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub enum StrSrc {
236    /// A single ASCII byte VALUE living in a frame slot (the `Kind::TextByte`
237    /// lane: `text + ch` where `ch` is a 1-char ASCII text). The helper appends
238    /// `byte as char` — bit-identical to the VM concatenating the 1-char `Text`.
239    Byte(Slot),
240    /// A constant ASCII byte slice baked into the chain (`text + "XXXXX"`): a
241    /// `'static` pointer + length. The helper appends the whole slice — identical
242    /// to the VM's `Text + Text` concatenation of the literal.
243    Const {
244        /// `'static` pointer to the constant's bytes.
245        ptr: i64,
246        /// The constant's byte length.
247        len: i64,
248    },
249    /// An `Int` VALUE living in a frame slot (`text + i`): the helper appends its decimal text, exactly the VM's
250    /// `Text + Int`.
251    Int(Slot),
252}
253
254impl StrSrc {
255    /// The frame slot the source reads, if it reads one (a constant is baked into the chain).
256    pub fn slot(self) -> Option<Slot> {
257        match self {
258            StrSrc::Byte(s) | StrSrc::Int(s) => Some(s),
259            StrSrc::Const { .. } => None,
260        }
261    }
262
263    /// [`StrSrc::slot`], for a pass that renames the slots an op reads.
264    pub fn slot_mut(&mut self) -> Option<&mut Slot> {
265        match self {
266            StrSrc::Byte(s) | StrSrc::Int(s) => Some(s),
267            StrSrc::Const { .. } => None,
268        }
269    }
270}
271
272/// The integer straight-line subset the J1 compiler accepts.
273#[derive(Clone, Copy, Debug, PartialEq, Eq)]
274pub enum MicroOp {
275    /// `frame[dst] = value`.
276    LoadConst {
277        /// Destination slot.
278        dst: Slot,
279        /// Immediate value.
280        value: i64,
281    },
282    /// `frame[dst] = frame[src]`.
283    Move {
284        /// Destination slot.
285        dst: Slot,
286        /// Source slot.
287        src: Slot,
288    },
289    /// `frame[dst] = frame[lhs] + frame[rhs]` (wrapping).
290    Add {
291        /// Destination slot.
292        dst: Slot,
293        /// Left operand slot.
294        lhs: Slot,
295        /// Right operand slot.
296        rhs: Slot,
297    },
298    /// `frame[dst] = frame[lhs] - frame[rhs]` (wrapping).
299    Sub {
300        /// Destination slot.
301        dst: Slot,
302        /// Left operand slot.
303        lhs: Slot,
304        /// Right operand slot.
305        rhs: Slot,
306    },
307    /// `frame[dst] = frame[lhs] * frame[rhs]` (wrapping).
308    Mul {
309        /// Destination slot.
310        dst: Slot,
311        /// Left operand slot.
312        lhs: Slot,
313        /// Right operand slot.
314        rhs: Slot,
315    },
316    /// `frame[dst] = (frame[lhs] < frame[rhs]) as i64`.
317    Lt {
318        /// Destination slot.
319        dst: Slot,
320        /// Left operand slot.
321        lhs: Slot,
322        /// Right operand slot.
323        rhs: Slot,
324    },
325    /// `frame[dst] = (frame[lhs] > frame[rhs]) as i64`.
326    Gt {
327        /// Destination slot.
328        dst: Slot,
329        /// Left operand slot.
330        lhs: Slot,
331        /// Right operand slot.
332        rhs: Slot,
333    },
334    /// `frame[dst] = (frame[lhs] == frame[rhs]) as i64`.
335    Eq {
336        /// Destination slot.
337        dst: Slot,
338        /// Left operand slot.
339        lhs: Slot,
340        /// Right operand slot.
341        rhs: Slot,
342    },
343    /// `frame[dst] = frame[lhs] / frame[rhs]` (wrapping; `MIN / -1 = MIN`).
344    /// A zero divisor SIDE-EXITS the chain ([`ChainOutcome::Deopt`]) before
345    /// any effect — the caller replays on bytecode, where the kernel raises
346    /// the exact "Division by zero" error.
347    Div {
348        /// Destination slot.
349        dst: Slot,
350        /// Left operand slot.
351        lhs: Slot,
352        /// Right operand slot.
353        rhs: Slot,
354    },
355    /// `frame[dst] = frame[lhs] / 2^k` (signed, round toward zero) via a
356    /// sign-correcting shift — bit-exact with [`MicroOp::Div`] but with NO
357    /// side-exit (a power-of-two divisor is never `0` or `-1`). Emitted in
358    /// place of `Div` when the divisor is a region-constant power of two and
359    /// the dividend is integer-typed.
360    DivPow2 {
361        /// Destination slot.
362        dst: Slot,
363        /// Dividend slot.
364        lhs: Slot,
365        /// Shift amount `k` (divisor = `2^k`, `1 <= k <= 62`).
366        k: u32,
367    },
368    /// `frame[dst] = frame[lhs] / c` (`mul_back == 0`) or `frame[lhs] % c`
369    /// (`mul_back == c`) by the Granlund–Montgomery / libdivide UNSIGNED
370    /// magic-reciprocal sequence (`mulhi(magic, x)` + add-fixup + shift, then
371    /// `x - q*c` for the remainder) — a `mul`+`shr` (~3 cycles) instead of
372    /// `idiv` (~25). NO side-exit (a literal `c > 0` is never `0` or `-1`).
373    /// Emitted in place of `Div`/`Mod` when the divisor is a compile-time
374    /// constant non-power-of-two and the dividend is proven Int and NON-NEGATIVE
375    /// (the unsigned magic equals the signed truncating result only there). The
376    /// `more` byte is the `logicaffeine_data::LogosDivU64` encoding (low 6 bits
377    /// = shift, `0x40` = the 65-bit add-marker path, `0x80` = pure-shift pow2).
378    MagicDivU {
379        /// Destination slot.
380        dst: Slot,
381        /// Dividend slot.
382        lhs: Slot,
383        /// Precomputed magic multiplier `M`.
384        magic: u64,
385        /// Shift / path encoding (see `logicaffeine_data::LogosDivU64`).
386        more: u8,
387        /// `0` selects the quotient; otherwise the divisor `c` selects the
388        /// remainder `x - (x/c)*c`.
389        mul_back: i64,
390    },
391    /// `frame[dst] = frame[lhs] % frame[rhs]` (wrapping; `MIN % -1 = 0`).
392    /// Zero divisor side-exits exactly like [`MicroOp::Div`].
393    Mod {
394        /// Destination slot.
395        dst: Slot,
396        /// Left operand slot.
397        lhs: Slot,
398        /// Right operand slot.
399        rhs: Slot,
400    },
401    /// `frame[dst] = (frame[lhs] <= frame[rhs]) as i64`.
402    LtEq {
403        /// Destination slot.
404        dst: Slot,
405        /// Left operand slot.
406        lhs: Slot,
407        /// Right operand slot.
408        rhs: Slot,
409    },
410    /// `frame[dst] = (frame[lhs] >= frame[rhs]) as i64`.
411    GtEq {
412        /// Destination slot.
413        dst: Slot,
414        /// Left operand slot.
415        lhs: Slot,
416        /// Right operand slot.
417        rhs: Slot,
418    },
419    /// `frame[dst] = (frame[lhs] != frame[rhs]) as i64`.
420    Neq {
421        /// Destination slot.
422        dst: Slot,
423        /// Left operand slot.
424        lhs: Slot,
425        /// Right operand slot.
426        rhs: Slot,
427    },
428    /// Fused compare-and-branch: transfer to `target` when `cmp(lhs, rhs)` is
429    /// FALSE (the `JumpIfFalse`-on-a-fresh-comparison shape); fall through
430    /// when TRUE. No comparison value is materialized — the adapter proves
431    /// the scratch dead before fusing.
432    Branch {
433        /// The comparison.
434        cmp: Cmp,
435        /// Left operand slot.
436        lhs: Slot,
437        /// Right operand slot.
438        rhs: Slot,
439        /// Micro-op index to transfer to when the comparison is FALSE.
440        target: usize,
441    },
442    /// `frame[dst] = frame[lhs] & frame[rhs]` (bitwise; logical for 0/1 Bools).
443    BitAnd {
444        /// Destination slot.
445        dst: Slot,
446        /// Left operand slot.
447        lhs: Slot,
448        /// Right operand slot.
449        rhs: Slot,
450    },
451    /// `frame[dst] = frame[lhs] | frame[rhs]` (bitwise; logical for 0/1 Bools).
452    BitOr {
453        /// Destination slot.
454        dst: Slot,
455        /// Left operand slot.
456        lhs: Slot,
457        /// Right operand slot.
458        rhs: Slot,
459    },
460    /// `frame[dst] = frame[lhs] ^ frame[rhs]`.
461    BitXor {
462        /// Destination slot.
463        dst: Slot,
464        /// Left operand slot.
465        lhs: Slot,
466        /// Right operand slot.
467        rhs: Slot,
468    },
469    /// `frame[dst] = frame[lhs].wrapping_shl(frame[rhs] as u32)` — the
470    /// kernel's locked shift spec (count truncates to u32, masks mod 64).
471    Shl {
472        /// Destination slot.
473        dst: Slot,
474        /// Left operand slot.
475        lhs: Slot,
476        /// Right operand slot.
477        rhs: Slot,
478    },
479    /// `frame[dst] = frame[lhs].wrapping_shr(frame[rhs] as u32)` (arithmetic).
480    Shr {
481        /// Destination slot.
482        dst: Slot,
483        /// Left operand slot.
484        lhs: Slot,
485        /// Right operand slot.
486        rhs: Slot,
487    },
488    /// `frame[dst] = ((frame[lhs] as u64) >> (frame[rhs] & 63)) as i64` — LOGICAL (unsigned) shift-right.
489    /// Register-threaded through the binop family (`V_BINOP` fam 12) / frame `ST_USHR3`. The Word64 substrate
490    /// for a variable `word64Shr` and the `rotl`/`rotr` composition (`shr` is arithmetic and would sign-extend
491    /// a high-bit-set carrier).
492    Ushr {
493        /// Destination slot.
494        dst: Slot,
495        /// Left operand slot.
496        lhs: Slot,
497        /// Right operand slot.
498        rhs: Slot,
499    },
500    /// Native word rotate. `width32` selects the low-32-bit Word32 operation
501    /// (whose result is zero-extended); otherwise the full Word64 carrier is
502    /// rotated. The hardware masks the count exactly like LOGOS (`& 31` or
503    /// `& 63`), including negative counts after their low bits are taken.
504    Rotate {
505        /// Destination slot.
506        dst: Slot,
507        /// Word value slot.
508        lhs: Slot,
509        /// Rotation-count slot.
510        rhs: Slot,
511        /// `true` for a 32-bit Word32 rotate, `false` for Word64.
512        width32: bool,
513        /// `true` for rotate-left, `false` for rotate-right.
514        left: bool,
515    },
516    /// `frame[dst] = !frame[src]` — bitwise NOT (the kernel's Int `not`).
517    NotInt {
518        /// Destination slot.
519        dst: Slot,
520        /// Source slot.
521        src: Slot,
522    },
523    /// `frame[dst] = (frame[src] as u64).count_ones()` — population count via the `popcnt` stencil
524    /// (`ST_POPCNT2`) / register-form `popcnt_rr`. A unary Int op shaped like [`MicroOp::NotInt`]. Reads
525    /// its source from the frame, so its `src` is kept out of the GP-pin budget (`gp_blocked` in the
526    /// pin selector) — otherwise a register-pinned source (a hot `count_ones(k)` induction variable)
527    /// would be read stale.
528    Popcnt {
529        /// Destination slot.
530        dst: Slot,
531        /// Source slot.
532        src: Slot,
533    },
534    /// `frame[dst] = (frame[src] as u64).leading_zeros()` (64 for 0) via the `lzcnt` stencil (`ST_LZCNT2`)
535    /// / register-form `lzcnt_rr`. Shaped exactly like [`MicroOp::Popcnt`]; its `src` is `gp_blocked` so a
536    /// register-pinned source is never read stale, and the register-form `V_LZCNT` reads the pin directly.
537    Lzcnt {
538        /// Destination slot.
539        dst: Slot,
540        /// Source slot.
541        src: Slot,
542    },
543    /// `frame[dst] = (frame[src] as u64).trailing_zeros()` (64 for 0) via the `tzcnt` stencil (`ST_TZCNT2`)
544    /// / register-form `tzcnt_rr`. Shaped exactly like [`MicroOp::Popcnt`]; its `src` is `gp_blocked` so a
545    /// register-pinned source is never read stale, and the register-form `V_TZCNT` reads the pin directly.
546    Tzcnt {
547        /// Destination slot.
548        dst: Slot,
549        /// Source slot.
550        src: Slot,
551    },
552    /// `frame[dst:Int] = f64::from_bits(frame[src:Float]).floor() as i64` via the `roundsd …,1`+`cvttsd2si`
553    /// stencil (`ST_FLOORF2`) / register-form `V_FLOORF`. A FLOAT source → INT dest: the src is read at its
554    /// XMM pin (`floc`) in the register form, the dst written to a GP pin. Guard the lowering on `sse4.1`.
555    FloorToInt {
556        /// Destination slot (Int).
557        dst: Slot,
558        /// Source slot (Float).
559        src: Slot,
560    },
561    /// `frame[dst:Int] = f64::from_bits(frame[src:Float]).ceil() as i64` via `roundsd …,2`+`cvttsd2si`
562    /// (`ST_CEILF2`) / register-form `V_CEILF`. Same FLOAT→INT shape as [`MicroOp::FloorToInt`].
563    CeilToInt {
564        /// Destination slot (Int).
565        dst: Slot,
566        /// Source slot (Float).
567        src: Slot,
568    },
569    /// `frame[dst:Int] = f64::from_bits(frame[src:Float]).round() as i64` — round-half-AWAY via `roundsd …,3`
570    /// (trunc) + a ties-away adjust + saturating `cvttsd2si` (`ST_ROUNDF2`) / register-form `V_ROUNDF`.
571    /// Same FLOAT→INT shape as [`MicroOp::FloorToInt`]; `roundsd`'s nearest mode ties to EVEN so is unusable.
572    RoundToInt {
573        /// Destination slot (Int).
574        dst: Slot,
575        /// Source slot (Float).
576        src: Slot,
577    },
578    /// `chr(code)` guard: DEOPTABLE. If `frame[src]` is a valid Unicode scalar it is carried to
579    /// `frame[dst]` (a `Kind::CharText` slot re-boxed to a 1-char `Text` at exit); an invalid code takes the
580    /// side-exit (`cont_1`) so the VM re-runs `chr` and traps. Frame stencil `ST_CHRGUARD`, register-form
581    /// `V_CHRGUARD` (reads a pinned code register directly, like `V_POPCNT`). Its `src` is `gp_blocked`.
582    ChrGuard {
583        /// Destination slot (the carried code; `Kind::CharText`).
584        dst: Slot,
585        /// Source slot (the candidate code point, `Int`).
586        src: Slot,
587    },
588    /// `frame[dst] = utf8_len(frame[src] as u32)` — the UTF-8 byte length (1..4) of a Unicode scalar. This is
589    /// how `length of chr(k)` lowers: a `CharText` is carried unboxed as its code point, and its `Length` is
590    /// the byte length of that code point's UTF-8 encoding (a single scalar can be 1–4 bytes, never a constant
591    /// 1), matching the tree-walker's byte-count `Length` over the boxed 1-char `Text`. Frame stencil
592    /// `ST_UTF8LEN`, register-form `V_UTF8LEN` (reads a pinned code register directly, like `V_POPCNT`); its
593    /// `src` is `gp_blocked`. Not deoptable — the code was already validated by the producing [`MicroOp::ChrGuard`].
594    Utf8Len {
595        /// Destination slot (Int).
596        dst: Slot,
597        /// Source slot (the code point, `Kind::CharText` carried as `Int`).
598        src: Slot,
599    },
600    /// `frame[dst] = frame[src] ^ 1` — logical NOT over 0/1 Bools.
601    NotBool {
602        /// Destination slot.
603        dst: Slot,
604        /// Source slot.
605        src: Slot,
606    },
607    /// Float ops: f64 values as raw bits in the i64 slots. Arithmetic is
608    /// IEEE; equality is the kernel's EPSILON rule.
609    AddF {
610        /// Destination slot.
611        dst: Slot,
612        /// Left operand slot.
613        lhs: Slot,
614        /// Right operand slot.
615        rhs: Slot,
616    },
617    /// `bits(f(lhs) - f(rhs))`.
618    SubF {
619        /// Destination slot.
620        dst: Slot,
621        /// Left operand slot.
622        lhs: Slot,
623        /// Right operand slot.
624        rhs: Slot,
625    },
626    /// `bits(f(lhs) * f(rhs))`.
627    MulF {
628        /// Destination slot.
629        dst: Slot,
630        /// Left operand slot.
631        lhs: Slot,
632        /// Right operand slot.
633        rhs: Slot,
634    },
635    /// `bits(f(lhs) / f(rhs))`; divisor `== 0.0` side-exits like [`MicroOp::Div`].
636    DivF {
637        /// Destination slot.
638        dst: Slot,
639        /// Left operand slot.
640        lhs: Slot,
641        /// Right operand slot.
642        rhs: Slot,
643    },
644    /// `(f(lhs) < f(rhs)) as i64` (IEEE, NaN → 0).
645    LtF {
646        /// Destination slot.
647        dst: Slot,
648        /// Left operand slot.
649        lhs: Slot,
650        /// Right operand slot.
651        rhs: Slot,
652    },
653    /// `(f(lhs) > f(rhs)) as i64`.
654    GtF {
655        /// Destination slot.
656        dst: Slot,
657        /// Left operand slot.
658        lhs: Slot,
659        /// Right operand slot.
660        rhs: Slot,
661    },
662    /// `(f(lhs) <= f(rhs)) as i64`.
663    LtEqF {
664        /// Destination slot.
665        dst: Slot,
666        /// Left operand slot.
667        lhs: Slot,
668        /// Right operand slot.
669        rhs: Slot,
670    },
671    /// `(f(lhs) >= f(rhs)) as i64`.
672    GtEqF {
673        /// Destination slot.
674        dst: Slot,
675        /// Left operand slot.
676        lhs: Slot,
677        /// Right operand slot.
678        rhs: Slot,
679    },
680    /// The kernel's epsilon equality as a value.
681    EqF {
682        /// Destination slot.
683        dst: Slot,
684        /// Left operand slot.
685        lhs: Slot,
686        /// Right operand slot.
687        rhs: Slot,
688    },
689    /// Negated epsilon equality as a value.
690    NeqF {
691        /// Destination slot.
692        dst: Slot,
693        /// Left operand slot.
694        lhs: Slot,
695        /// Right operand slot.
696        rhs: Slot,
697    },
698    /// Fused FLOAT compare-and-branch: transfer to `target` when
699    /// `cmp(f(lhs), f(rhs))` is FALSE — which, under IEEE, includes every
700    /// NaN-unordered comparison (matching the kernel's relations exactly).
701    BranchF {
702        /// The comparison.
703        cmp: Cmp,
704        /// Left operand slot.
705        lhs: Slot,
706        /// Right operand slot.
707        rhs: Slot,
708        /// Micro-op index to transfer to when the comparison is FALSE.
709        target: usize,
710    },
711    /// `frame[dst] = bits(frame[src] as f64)` — the kernel's Int→Float
712    /// promotion.
713    IntToFloat {
714        /// Destination slot.
715        dst: Slot,
716        /// Source slot.
717        src: Slot,
718    },
719    /// `frame[dst] = bits(sqrt(f(frame[src])))` — the kernel's Float sqrt
720    /// builtin (IEEE: negative → NaN, no error path).
721    SqrtF {
722        /// Destination slot.
723        dst: Slot,
724        /// Source slot.
725        src: Slot,
726    },
727    /// A runtime helper over the frame: `helper(frame, dst, src, count, imm)` reads the slots `src..src + count`,
728    /// writes the slot `dst`, and answers 0 to side-exit (the VM re-runs the op). One helper per operation the
729    /// stencil set has no shape for — the enum lane builds, tests, reads, retains and releases nodes through it.
730    Host {
731        /// The slot the helper writes.
732        dst: Slot,
733        /// The first slot the helper reads.
734        src: Slot,
735        /// How many consecutive slots from `src` the helper reads.
736        count: Slot,
737        /// An operand the helper interprets (a descriptor address, a field index).
738        imm: i64,
739        /// Runtime helper address (indirect call, no relocation).
740        helper_addr: i64,
741    },
742    /// Map get through the pinned storage: an Int hit lands in `dst`; a
743    /// miss or non-Int value side-exits (the replay raises the kernel's
744    /// exact error or re-runs the boxed path).
745    MapGet {
746        /// Destination slot.
747        dst: Slot,
748        /// Key slot.
749        key: Slot,
750        /// The pinned `*mut MapStorage` slot.
751        map_slot: Slot,
752        /// Runtime helper address (indirect call, no relocation).
753        helper_addr: i64,
754    },
755    /// Map insert (always succeeds; same storage, same iteration order).
756    MapSet {
757        /// Value slot.
758        src: Slot,
759        /// Key slot.
760        key: Slot,
761        /// The pinned `*mut MapStorage` slot.
762        map_slot: Slot,
763        /// Runtime helper address.
764        helper_addr: i64,
765    },
766    /// DIRECT self-call (mode A): entry patched post-layout into the
767    /// literal pool; static frame-size bound; plain replay deopt.
768    CallSelf {
769        /// Caller register receiving the result.
770        dst: Slot,
771        /// First slot of the staged argument window.
772        args_start: Slot,
773        /// Live-depth cell address.
774        depth_addr: i64,
775        /// Shared status cell address.
776        status_addr: i64,
777        /// MY arena-limit slot (the bound source).
778        limit_slot: Slot,
779        /// The callee's (own) full frame size in slots.
780        frame_size: i64,
781    },
782    /// DIRECT self-call with a FUSED argument copy (Lever A: the pinned-arg
783    /// self-call ABI). Same model as [`MicroOp::CallSelf`], but it stages the
784    /// `arg_count` contiguous scalar arguments from `src_start..` into the
785    /// callee window itself rather than relying on `arg_count` separate
786    /// `Move` pieces before the call — one piece replaces `arg_count + 1`.
787    /// Emitted only for all-scalar (Int/Bool/Float) self-calls; list-param
788    /// and pin-triple staging stay on the per-`Move` path.
789    CallSelfCopy {
790        /// Caller register receiving the result.
791        dst: Slot,
792        /// First slot of the staged argument window (the callee frame base).
793        args_start: Slot,
794        /// First slot of the SOURCE argument block in this frame.
795        src_start: Slot,
796        /// Number of contiguous scalar arguments to copy.
797        arg_count: u16,
798        /// Live-depth cell address.
799        depth_addr: i64,
800        /// Shared status cell address.
801        status_addr: i64,
802        /// MY arena-limit slot (the bound source).
803        limit_slot: Slot,
804        /// The callee's (own) full frame size in slots.
805        frame_size: i64,
806    },
807    /// Allocate a registry-owned fresh list and plant its pin triple.
808    NewList {
809        /// Pin handle slot.
810        vec_slot: Slot,
811        /// Pin buffer-pointer slot.
812        ptr_slot: Slot,
813        /// Pin length slot.
814        len_slot: Slot,
815        /// Runtime allocator address.
816        helper_addr: i64,
817    },
818    /// Plant a pin triple from a list handle already in `handle_slot`
819    /// (a self-call's returned list, seen from the caller).
820    ListTriple {
821        /// Slot holding the `*mut Vec<i64>` handle.
822        handle_slot: Slot,
823        /// Pin handle slot.
824        vec_slot: Slot,
825        /// Pin buffer-pointer slot.
826        ptr_slot: Slot,
827        /// Pin length slot.
828        len_slot: Slot,
829        /// Runtime helper address.
830        helper_addr: i64,
831    },
832    /// Map membership into `dst` (0/1).
833    MapHas {
834        /// Destination slot.
835        dst: Slot,
836        /// Key slot.
837        key: Slot,
838        /// The pinned `*mut MapStorage` slot.
839        map_slot: Slot,
840        /// Runtime helper address.
841        helper_addr: i64,
842    },
843    /// Native SELF-CALL through the program's entry table (callee frame
844    /// windowed at `base + args_start` like the VM). Missing entry, a
845    /// MAX_CALL_DEPTH crossing, or arena overflow side-exits the WHOLE
846    /// native stack via the shared status cell.
847    Call {
848        /// Result slot.
849        dst: Slot,
850        /// Callee frame offset within the caller's frame.
851        args_start: Slot,
852        /// Address of the [entry, regcount] table slot pair.
853        table_addr: i64,
854        /// Address of the shared live-depth cell.
855        depth_addr: i64,
856        /// Address of the shared deopt-status cell.
857        status_addr: i64,
858        /// Frame slot holding the arena END address.
859        limit_slot: Slot,
860        /// MAX_CALL_DEPTH.
861        depth_limit: i64,
862    },
863    /// Pinned-array push. The contiguous regalloc backend lowers this to an
864    /// INLINE fast path — `len < cap ? buffer[len++] = v` straight in registers,
865    /// reading the capacity from the live `*mut Vec` (a codegen-probed field
866    /// offset, never a hardcoded layout) — and calls the runtime helper ONLY on
867    /// the cold realloc boundary (`len == cap`), where it reallocates and
868    /// refreshes the pinned pointer/length slots. The per-piece stencil tier
869    /// always calls the helper.
870    ArrPush {
871        /// Value slot.
872        src: Slot,
873        /// Frame slot holding the `*mut Vec` handle.
874        vec_slot: Slot,
875        /// Pinned pointer slot to refresh.
876        ptr_slot: Slot,
877        /// Pinned length slot to refresh.
878        len_slot: Slot,
879        /// The runtime helper's address.
880        helper_addr: i64,
881        /// 1-BYTE (`Seq of Bool`) element: the inline fast-path store writes the
882        /// boolean normalization `(v != 0) as u8` (matching `logos_rt_push_bool`),
883        /// not 8 raw bytes. `false` for Int/Float (8-byte raw bits).
884        byte: bool,
885        /// 4-byte Int element (`ListRepr::IntsI32`): the inline fast-path store
886        /// TRUNCATES the value to its low 4 bytes (lossless under the narrowing
887        /// proof), matching `logos_rt_push_i32`. Mutually exclusive with `byte`.
888        narrow32: bool,
889    },
890    /// Pinned-array in-place clear through a runtime helper: truncate the buffer
891    /// to empty (keep capacity) and refresh the pinned pointer/length slots
892    /// (length → 0). Lowers an in-region `NewEmptyList` on a pinned array; an
893    /// in-place mutation, so a PRECISE region resumes over it soundly.
894    ListClear {
895        /// Frame slot holding the `*mut Vec` handle.
896        vec_slot: Slot,
897        /// Pinned pointer slot to refresh.
898        ptr_slot: Slot,
899        /// Pinned length slot to refresh (set to 0).
900        len_slot: Slot,
901        /// The runtime helper's address.
902        helper_addr: i64,
903    },
904    /// Pinned MUTABLE-Text append (`Set text to text + <s>`) through a runtime
905    /// helper. `text_handle_slot` holds a `*mut Value` to the VM register cell
906    /// holding the accumulator (planted at region entry); the helper grows the
907    /// accumulator THROUGH that cell with EXACTLY the VM's `add_assign`
908    /// semantics — in place when the `Rc<String>` is sole-owned, copy-on-write
909    /// (a fresh `Rc` written back into the cell, the alias untouched) otherwise.
910    /// `src` is the appended operand (a 1-char frame byte, or a baked constant
911    /// slice). Bit-identical to the tree-walker for every alias case. The buffer
912    /// reaches into the VM register file, so — like the other helper calls — it
913    /// clobbers the caller-saved registers (the residents are spilled/reloaded).
914    StrAppend {
915        /// Frame slot holding the `*mut Value` accumulator-cell handle.
916        text_handle_slot: Slot,
917        /// The appended source operand.
918        src: StrSrc,
919        /// The runtime helper's address (`logos_rt_str_append`).
920        helper_addr: i64,
921    },
922    /// COUNT OVERLAPPING SUBSTRING MATCHES through a runtime helper — the whole
923    /// naive-search nest (string_search) collapsed to one piece. The helper
924    /// reads the pinned haystack/needle byte buffers, counts overlapping needle
925    /// occurrences over the outer range `[frame[i_slot], textLen - needleLen + 1]`
926    /// (1-based, matching the nest), ADDS the count into `frame[count_slot]`, and
927    /// advances `frame[i_slot]` to the loop's exit value. On a recoverable
928    /// disagreement (a checked needle index past the needle buffer) it touches
929    /// nothing and takes the deopt continuation, so the VM replays the exact
930    /// nest on bytecode and raises the same error. Holes: 0 = haystack ptr slot,
931    /// 1 = haystack len slot, 2 = needle ptr slot, 3 = needle len slot, 4 =
932    /// needleLen value slot, 5 = i (start) slot, 6 = count accumulator slot,
933    /// 7 = helper address.
934    MemMem {
935        /// Frame slot holding the pinned haystack buffer pointer.
936        h_ptr_slot: Slot,
937        /// Frame slot holding the pinned haystack length.
938        h_len_slot: Slot,
939        /// Frame slot holding the pinned needle buffer pointer.
940        n_ptr_slot: Slot,
941        /// Frame slot holding the pinned needle length.
942        n_len_slot: Slot,
943        /// Frame slot holding the program's `needleLen` value (inner bound).
944        needle_len_slot: Slot,
945        /// Frame slot holding the 1-based outer index `i` (start; written to the
946        /// exit value on success).
947        i_slot: Slot,
948        /// Frame slot holding the running `count` accumulator (added into).
949        count_slot: Slot,
950        /// The runtime helper's address.
951        helper_addr: i64,
952    },
953    /// Pinned-array load: `frame[dst] = buffer[frame[idx] - 1]` (1-based;
954    /// bits regardless of element kind). Out-of-bounds (incl. 0/negative)
955    /// SIDE-EXITS before any effect.
956    ArrLoad {
957        /// Destination slot.
958        dst: Slot,
959        /// Index slot (1-based value).
960        idx: Slot,
961        /// Frame slot holding the pinned buffer pointer.
962        ptr_slot: Slot,
963        /// Frame slot holding the pinned length.
964        len_slot: Slot,
965        /// 1-byte elements (Bool buffers) instead of 8-byte.
966        byte: bool,
967        /// 4-byte SIGN-EXTENDED Int elements (`ListRepr::IntsI32`): the load is a
968        /// `movsxd` widening the stored `i32` to a full i64 (lossless). Mutually
969        /// exclusive with `byte`; both `false` ⇒ the default 8-byte element.
970        narrow32: bool,
971        /// Bounds-checked (`true`) or elided (`false`, the Oracle proved
972        /// the index in range — V8/LLVM bounds-check elimination). Unchecked
973        /// loads have no out-of-bounds continuation.
974        checked: bool,
975    },
976    /// FUSED affine-index load: `frame[dst] = buffer[idx - 1]` where the 1-based
977    /// `idx = (frame[a] OP frame[b]).wrapping_add(const_offset)` (or
978    /// `frame[a] + const_offset` for [`AffOp::None`]) is computed INSIDE the
979    /// stencil — the peephole collapses the index-arithmetic chain
980    /// (`<binop>(t = a OP b); [Add(t2 = t + Kc);] ArrLoad(t2)`, or
981    /// `Add(t = a + Kc); ArrLoad(t)`) plus the load into ONE piece when the
982    /// intermediate index temps are single-use scratch. The dominant indexed
983    /// inner loops (matrix_mult `i*n+k+1`, knapsack `w - wi + 1`, the `w + 1`
984    /// row read) lose worst to V8 precisely on this per-op dispatch; folding the
985    /// 2-3 index ops into the load is a direct dispatch-reduction win. Out of
986    /// bounds (incl. the 0/negative index the wrapping-sub trick catches)
987    /// SIDE-EXITS before any effect, exactly like [`MicroOp::ArrLoad`].
988    ArrLoadAffine {
989        /// Destination slot.
990        dst: Slot,
991        /// First index operand slot.
992        a: Slot,
993        /// The index op (`None` = single slot + const; else two-slot binop).
994        op: AffOp,
995        /// Second index operand slot (ignored for [`AffOp::None`]).
996        b: Slot,
997        /// The constant folded into the index (the trailing `+ Kc`; `0` if none).
998        const_offset: i64,
999        /// Frame slot holding the pinned buffer pointer.
1000        ptr_slot: Slot,
1001        /// Frame slot holding the pinned length.
1002        len_slot: Slot,
1003        /// Bounds-checked (`true`) or elided (`false`, the Oracle proved the
1004        /// computed index in range). Unchecked has no out-of-bounds continuation.
1005        checked: bool,
1006    },
1007    /// FUSED two-load float binop: `frame[dst] = bits(f(buf[i-1]) <op>
1008    /// f(buf[j-1]))`, BOTH elements from the SAME pinned 8-byte buffer (one
1009    /// pointer slot, one length slot). The peephole collapses `ArrLoad(t1 =
1010    /// arr[i]); ArrLoad(t2 = arr[j]); {Add,Sub,Mul}F(dst = t1 OP t2)` when both
1011    /// loads hit the same array and the two scratch loads are single-use — so
1012    /// the two f64s never round-trip through the frame. EITHER index out of
1013    /// bounds SIDE-EXITS before any effect, exactly like [`MicroOp::ArrLoad`].
1014    ArrLoad2F {
1015        /// Destination slot.
1016        dst: Slot,
1017        /// First index slot (1-based value).
1018        i: Slot,
1019        /// Second index slot (1-based value).
1020        j: Slot,
1021        /// Frame slot holding the pinned buffer pointer.
1022        ptr_slot: Slot,
1023        /// Frame slot holding the pinned length.
1024        len_slot: Slot,
1025        /// The float operation applied to the two loaded values.
1026        op: FOp,
1027    },
1028    /// FUSED two-load INTEGER binop: `frame[dst] = a[i-1] <op> b[j-1]`, the two
1029    /// 8-byte elements loaded from TWO (possibly distinct) pinned int buffers
1030    /// (each with its own pointer + length slot). The peephole collapses
1031    /// `ArrLoad(t1 = a[i]); ArrLoad(t2 = b[j]); {Add,Sub,Mul}(dst = t1 OP t2)`
1032    /// — the matrix-multiply / dot-product idiom `c += a[..] * b[..]` — when the
1033    /// two scratch loads are single-use, so the loaded i64s never round-trip the
1034    /// frame and three dispatches collapse to one. EITHER index out of bounds
1035    /// SIDE-EXITS before any effect, exactly like [`MicroOp::ArrLoad`]. The two
1036    /// buffers may be the SAME (one self-referential dot product) or distinct.
1037    ArrLoad2 {
1038        /// Destination slot.
1039        dst: Slot,
1040        /// First index slot (1-based value), addressing buffer `a`.
1041        i: Slot,
1042        /// Second index slot (1-based value), addressing buffer `b`.
1043        j: Slot,
1044        /// Frame slot holding the pinned pointer of the first buffer (`a`).
1045        ptr_a: Slot,
1046        /// Frame slot holding the pinned length of the first buffer (`a`).
1047        len_a: Slot,
1048        /// Frame slot holding the pinned pointer of the second buffer (`b`).
1049        ptr_b: Slot,
1050        /// Frame slot holding the pinned length of the second buffer (`b`).
1051        len_b: Slot,
1052        /// The integer operation applied to the two loaded values.
1053        op: IOp,
1054        /// Bounds-checked (`true`) or elided (`false`, the Oracle proved both
1055        /// indices in range). Unchecked has no out-of-bounds continuation.
1056        checked: bool,
1057    },
1058    /// Pinned-array store: `buffer[frame[idx] - 1] = frame[src]`; bounds
1059    /// side-exit BEFORE the store.
1060    ArrStore {
1061        /// Source slot.
1062        src: Slot,
1063        /// Index slot (1-based value).
1064        idx: Slot,
1065        /// Frame slot holding the pinned buffer pointer.
1066        ptr_slot: Slot,
1067        /// Frame slot holding the pinned length.
1068        len_slot: Slot,
1069        /// 1-byte elements (Bool buffers; stores normalize to 0/1).
1070        byte: bool,
1071        /// 4-byte SIGN-EXTENDED Int elements (`ListRepr::IntsI32`, the VM's
1072        /// `LOGOS_NARROW_VM` half-width buffers): a store TRUNCATES the value to
1073        /// its low 4 bytes (lossless under the narrowing proof). Mutually
1074        /// exclusive with `byte`; both `false` ⇒ the default 8-byte element.
1075        narrow32: bool,
1076        /// Bounds-checked (`true`) or elided (`false`, the Oracle proved
1077        /// the index in range). Unchecked stores have no side-exit.
1078        checked: bool,
1079    },
1080    /// FUSED read-modify-write on a pinned 8-byte int array:
1081    /// `buffer[frame[idx] - 1] = buffer[frame[idx] - 1] <op> frame[operand]`
1082    /// in ONE stencil. The peephole collapses `ArrLoad(t = arr[idx]);
1083    /// <int ALU>(t2 = t OP operand); ArrStore(arr[idx] = t2)` when both array
1084    /// ops hit the SAME pinned buffer + index and the two scratch values
1085    /// (`t`, `t2`) are single-use — so the element never round-trips the frame
1086    /// and ONE bounds check covers the load+store. Out-of-bounds (incl.
1087    /// 0/negative) SIDE-EXITS before any effect, exactly like [`MicroOp::ArrStore`].
1088    ArrRMW {
1089        /// Index slot (1-based value).
1090        idx: Slot,
1091        /// Operand slot (the RHS of the op; `frame[operand]`).
1092        operand: Slot,
1093        /// Frame slot holding the pinned buffer pointer.
1094        ptr_slot: Slot,
1095        /// Frame slot holding the pinned length.
1096        len_slot: Slot,
1097        /// The integer operation applied in place.
1098        op: RmwOp,
1099        /// Bounds-checked (`true`) or elided (`false`). Unchecked has no
1100        /// out-of-bounds continuation.
1101        checked: bool,
1102    },
1103    /// FUSED conditional adjacent swap on a pinned 8-byte int array:
1104    /// `let a = buf[idx1-1]; let b = buf[idx2-1]; if cmp(a, b) { buf[idx1-1] = b;
1105    /// buf[idx2-1] = a }` in ONE stencil. The peephole collapses the sort
1106    /// inner-loop idiom `ArrLoad(a,i1); ArrLoad(b,i2); Branch(cmp,a,b,skip);
1107    /// ArrStore(i1,b); ArrStore(i2,a)` (bubble/insertion/quick sort) — 5 ops → 1,
1108    /// the two loaded values never round-trip the frame, the compare-branch is
1109    /// gone. The swap is ATOMIC (both writes or neither); a checked variant
1110    /// bounds-checks BOTH indices up front and SIDE-EXITS before any effect, the
1111    /// unchecked variant (Oracle-proven indices) has no side-exit.
1112    ArrCondSwap {
1113        /// First index slot (1-based value).
1114        idx1: Slot,
1115        /// Second index slot (1-based value).
1116        idx2: Slot,
1117        /// Frame slot holding the pinned buffer pointer.
1118        ptr_slot: Slot,
1119        /// Frame slot holding the pinned length.
1120        len_slot: Slot,
1121        /// Swap when `cmp(buf[idx1-1], buf[idx2-1])` is TRUE.
1122        cmp: Cmp,
1123        /// Bounds-checked (`true`) or elided (`false`).
1124        checked: bool,
1125    },
1126    /// FUSED unconditional adjacent swap on a pinned 8-byte int array:
1127    /// `let a = buf[idx1-1]; let b = buf[idx2-1]; buf[idx1-1] = b; buf[idx2-1] =
1128    /// a` in ONE stencil. The peephole collapses the `Let tmp = arr[i]; arr[i] =
1129    /// arr[j]; arr[j] = tmp` exchange (quicksort/heap_sort/mergesort partition &
1130    /// sift) — `ArrLoad(a,i); ArrLoad(b,j); ArrStore(i,b); ArrStore(j,a)` — 4 ops
1131    /// → 1. The swap is ATOMIC; a checked variant bounds-checks BOTH indices up
1132    /// front and SIDE-EXITS before any effect.
1133    ArrSwap {
1134        /// First index slot (1-based value).
1135        idx1: Slot,
1136        /// Second index slot (1-based value).
1137        idx2: Slot,
1138        /// Frame slot holding the pinned buffer pointer.
1139        ptr_slot: Slot,
1140        /// Frame slot holding the pinned length.
1141        len_slot: Slot,
1142        /// Bounds-checked (`true`) or elided (`false`).
1143        checked: bool,
1144    },
1145    /// FUSED float multiply-add: `frame[dst] = bits((f(a) * f(b)) + f(c))` — the
1146    /// peephole collapses `MulF(t = a*b); AddF(d = t + c)` (the product `t`
1147    /// single-use) into one stencil, cutting a dispatch on the float arithmetic
1148    /// chains that dominate the float cluster (nbody's `dz*dz + s`, dot
1149    /// products). The product and the add round SEPARATELY (`(a*b)+c`, two
1150    /// roundings) — NOT a hardware single-rounding FMA — so it stays bit-identical
1151    /// to the unfused `MulF`+`AddF`. Mem-form: every operand reads from the frame,
1152    /// so it preserves the threaded XMM pins (the caller only fuses when the
1153    /// operands are frame-resident, keeping it a spill-free win).
1154    FmaF {
1155        /// Destination slot.
1156        dst: Slot,
1157        /// First product operand slot.
1158        a: Slot,
1159        /// Second product operand slot.
1160        b: Slot,
1161        /// Addend slot.
1162        c: Slot,
1163    },
1164    /// Unconditional transfer to the micro-op at `target` (an index into the
1165    /// program; forward or backward).
1166    Jump {
1167        /// Micro-op index to transfer to.
1168        target: usize,
1169    },
1170    /// Transfer to `target` when frame\[cond\] is ZERO; fall through otherwise.
1171    JumpIfFalse {
1172        /// Condition slot (zero = jump).
1173        cond: Slot,
1174        /// Micro-op index to transfer to.
1175        target: usize,
1176    },
1177    /// Transfer to `target` when frame\[cond\] is NONZERO; fall through
1178    /// otherwise (the same brz stencil with swapped continuations).
1179    JumpIfTrue {
1180        /// Condition slot (nonzero = jump).
1181        cond: Slot,
1182        /// Micro-op index to transfer to.
1183        target: usize,
1184    },
1185    /// Terminate the chain, returning frame\[src\].
1186    Return {
1187        /// Slot whose value is returned.
1188        src: Slot,
1189    },
1190}
1191
1192/// Compile errors — structural, found before any code is emitted.
1193#[derive(Debug, PartialEq, Eq)]
1194pub enum JitCompileError {
1195    /// The program is empty.
1196    Empty,
1197    /// Execution can run off the end: the final op must be Return or Jump.
1198    FallsOffTheEnd,
1199    /// A jump target is outside the program.
1200    BadJumpTarget {
1201        /// Index of the offending op.
1202        op_index: usize,
1203        /// The out-of-range target.
1204        target: usize,
1205    },
1206    /// Assembly failed (missing hole/patch/map errors).
1207    Assembly(String),
1208    /// An op the per-piece stencil tier has no lowering for (e.g.
1209    /// [`MicroOp::StrAppend`], which is emitted ONLY for the contiguous regalloc
1210    /// backend). The caller declines (falls back to bytecode), so this is never a
1211    /// hard failure — it just routes around the stencil tier.
1212    Unsupported(&'static str),
1213}
1214
1215impl std::fmt::Display for JitCompileError {
1216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1217        match self {
1218            JitCompileError::Empty => write!(f, "jit: empty program"),
1219            JitCompileError::FallsOffTheEnd => {
1220                write!(f, "jit: the final op must be Return or Jump")
1221            }
1222            JitCompileError::BadJumpTarget { op_index, target } => {
1223                write!(
1224                    f,
1225                    "jit: op {op_index} jumps to {target}, outside the program"
1226                )
1227            }
1228            JitCompileError::Assembly(e) => write!(f, "jit: assembly failed: {e}"),
1229            JitCompileError::Unsupported(name) => {
1230                write!(f, "jit: the stencil tier has no lowering for {name}")
1231            }
1232        }
1233    }
1234}
1235
1236impl std::error::Error for JitCompileError {}
1237
1238/// What one chain run produced.
1239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1240pub enum ChainOutcome {
1241    /// The chain reached its Return; this is the returned value.
1242    Return(i64),
1243    /// A checked op side-exited; the payload is the RAW status-cell value.
1244    /// `1` is the plain marker (replay from the entry state — every effect
1245    /// confined to the private frame). `(pc << 2) | 3` is a PRECISE exit:
1246    /// effects already landed, resume at bytecode `pc`.
1247    Deopt(i64),
1248}
1249
1250impl ChainOutcome {
1251    /// The returned value; panics on [`ChainOutcome::Deopt`] — for tests and
1252    /// callers of chains that contain no checked ops.
1253    pub fn expect_return(self) -> i64 {
1254        match self {
1255            ChainOutcome::Return(v) => v,
1256            ChainOutcome::Deopt(_) => panic!("chain side-exited (deopt) — no return value"),
1257        }
1258    }
1259
1260    /// True when the run side-exited.
1261    pub fn is_deopt(&self) -> bool {
1262        matches!(self, ChainOutcome::Deopt(_))
1263    }
1264}
1265
1266/// A compiled chain plus its side-exit status cell (present only when the
1267/// program contains checked ops). The deopt stencil stores 1 through the
1268/// patched cell address; [`CompiledChain::run_with_frame`] reads-and-resets
1269/// it after every run.
1270#[derive(Debug)]
1271pub struct CompiledChain {
1272    chain: JitChain,
1273    status: Option<std::sync::Arc<AtomicI64>>,
1274    /// Extra cells the chain's machine code reads by baked address and that must
1275    /// therefore outlive the chain (the contiguous FUNCTION backend's self-call
1276    /// ENTRY cell: an `Arc<AtomicI64>` holding this chain's own entry address,
1277    /// loaded by every `CallSelf`/`CallSelfCopy` and written after mapping). The
1278    /// run/deopt contract is unchanged — these are pure keep-alives.
1279    #[allow(dead_code)]
1280    keepalive: Vec<std::sync::Arc<AtomicI64>>,
1281}
1282
1283impl CompiledChain {
1284    /// Wrap a raw `JitChain` (from the contiguous regalloc backend) and its
1285    /// shared status cell as a runnable `CompiledChain` — same run/deopt
1286    /// contract as a stencil chain.
1287    pub(crate) fn from_chain(chain: JitChain, status: Option<std::sync::Arc<AtomicI64>>) -> Self {
1288        CompiledChain {
1289            chain,
1290            status,
1291            keepalive: Vec::new(),
1292        }
1293    }
1294
1295    /// Wrap a `JitChain` plus its status cell AND any extra cells the code reads
1296    /// by baked address (the self-call entry cell), which the `CompiledChain`
1297    /// then keeps alive for the chain's whole lifetime.
1298    pub(crate) fn from_chain_keepalive(
1299        chain: JitChain,
1300        status: Option<std::sync::Arc<AtomicI64>>,
1301        keepalive: Vec<std::sync::Arc<AtomicI64>>,
1302    ) -> Self {
1303        CompiledChain {
1304            chain,
1305            status,
1306            keepalive,
1307        }
1308    }
1309
1310    /// Run over the given frame (slot 0 = VM register 0, …) with a fresh
1311    /// operand stack.
1312    pub fn run_with_frame(&self, frame: &mut [i64]) -> ChainOutcome {
1313        let v = self.chain.run_with_frame(frame);
1314        if let Some(cell) = &self.status {
1315            let raw = cell.swap(0, Ordering::Relaxed);
1316            if raw != 0 {
1317                return ChainOutcome::Deopt(raw);
1318            }
1319        }
1320        ChainOutcome::Return(v)
1321    }
1322
1323    /// The mapped code+pool bytes (diagnostics/tests).
1324    pub fn bytes(&self) -> &[u8] {
1325        self.chain.bytes()
1326    }
1327
1328    /// See [`crate::buffer::JitChain::patch_marked`].
1329    pub fn patch_marked(&self, value: u64) -> Result<(), crate::JitError> {
1330        self.chain.patch_marked(value)
1331    }
1332
1333    /// See [`crate::buffer::JitChain::has_patch_marks`].
1334    pub fn has_patch_marks(&self) -> bool {
1335        self.chain.has_patch_marks()
1336    }
1337
1338    /// The runtime base address (diagnostics/tests).
1339    pub fn base(&self) -> u64 {
1340        self.chain.base()
1341    }
1342
1343    /// Stencil pieces in the chain (diagnostics/tests).
1344    pub fn piece_count(&self) -> usize {
1345        self.chain.piece_count()
1346    }
1347}
1348
1349/// Lower a straight-line micro-op program into one executable stencil chain.
1350///
1351/// Emit ONE memory-form piece (an op outside the variant families) with
1352/// explicit continuation and deopt labels — the pinned compiler's bridge
1353/// to the classic stencils. Pinned operands were spilled before this
1354/// piece and pinned destinations reload after it.
1355/// The fused read-modify-write stencil for an op + bounds-check mode. The
1356/// checked twins side-exit through cont 1 on out-of-bounds; the unchecked `_u`
1357/// twins have no length hole and no out-of-bounds continuation.
1358fn rmw_stencil(op: RmwOp, checked: bool) -> &'static crate::Stencil {
1359    match (op, checked) {
1360        (RmwOp::Add, true) => &ST_ARRRMW_ADD,
1361        (RmwOp::Add, false) => &ST_ARRRMW_ADD_U,
1362        (RmwOp::Sub, true) => &ST_ARRRMW_SUB,
1363        (RmwOp::Sub, false) => &ST_ARRRMW_SUB_U,
1364        (RmwOp::Mul, true) => &ST_ARRRMW_MUL,
1365        (RmwOp::Mul, false) => &ST_ARRRMW_MUL_U,
1366        (RmwOp::And, true) => &ST_ARRRMW_AND,
1367        (RmwOp::And, false) => &ST_ARRRMW_AND_U,
1368        (RmwOp::Or, true) => &ST_ARRRMW_OR,
1369        (RmwOp::Or, false) => &ST_ARRRMW_OR_U,
1370        (RmwOp::Xor, true) => &ST_ARRRMW_XOR,
1371        (RmwOp::Xor, false) => &ST_ARRRMW_XOR_U,
1372        (RmwOp::AddF, true) => &ST_ARRRMW_ADDF,
1373        (RmwOp::AddF, false) => &ST_ARRRMW_ADDF_U,
1374        (RmwOp::SubF, true) => &ST_ARRRMW_SUBF,
1375        (RmwOp::SubF, false) => &ST_ARRRMW_SUBF_U,
1376        (RmwOp::MulF, true) => &ST_ARRRMW_MULF,
1377        (RmwOp::MulF, false) => &ST_ARRRMW_MULF_U,
1378    }
1379}
1380
1381/// The fused two-buffer integer-load binop stencil for an op + bounds-check
1382/// mode. The checked twins side-exit through cont 1 when EITHER index is out of
1383/// bounds; the unchecked `_u` twins have no length holes and no continuation.
1384fn ld2_int_stencil(op: IOp, checked: bool) -> &'static crate::Stencil {
1385    match (op, checked) {
1386        (IOp::Add, true) => &ST_ARRLD2_ADD,
1387        (IOp::Add, false) => &ST_ARRLD2_ADD_U,
1388        (IOp::Sub, true) => &ST_ARRLD2_SUB,
1389        (IOp::Sub, false) => &ST_ARRLD2_SUB_U,
1390        (IOp::Mul, true) => &ST_ARRLD2_MUL,
1391        (IOp::Mul, false) => &ST_ARRLD2_MUL_U,
1392    }
1393}
1394
1395/// The fused affine-index load stencil for an index op + bounds-check mode. The
1396/// checked twins side-exit through cont 1 when the COMPUTED index is out of
1397/// bounds; the unchecked `_u` twins have no length hole and no continuation.
1398/// The pinned-array LOAD stencil for an element width: 1-byte (Bool, zero-ext),
1399/// 4-byte (`IntsI32`, sign-ext), or the default 8-byte (Int/Float raw bits).
1400/// `byte` and `narrow32` are mutually exclusive (the adapter never sets both).
1401fn arrld_stencil(byte: bool, narrow32: bool, checked: bool) -> &'static crate::Stencil {
1402    match (byte, narrow32, checked) {
1403        (true, _, true) => &ST_ARRLDB,
1404        (true, _, false) => &ST_ARRLDB_U,
1405        (_, true, true) => &ST_ARRLD_I32,
1406        (_, true, false) => &ST_ARRLD_I32_U,
1407        (false, false, true) => &ST_ARRLD,
1408        (false, false, false) => &ST_ARRLD_U,
1409    }
1410}
1411
1412/// The pinned-array STORE stencil for an element width (see [`arrld_stencil`]).
1413fn arrst_stencil(byte: bool, narrow32: bool, checked: bool) -> &'static crate::Stencil {
1414    match (byte, narrow32, checked) {
1415        (true, _, true) => &ST_ARRSTB,
1416        (true, _, false) => &ST_ARRSTB_U,
1417        (_, true, true) => &ST_ARRST_I32,
1418        (_, true, false) => &ST_ARRST_I32_U,
1419        (false, false, true) => &ST_ARRST,
1420        (false, false, false) => &ST_ARRST_U,
1421    }
1422}
1423
1424fn affine_stencil(op: AffOp, checked: bool) -> &'static crate::Stencil {
1425    match (op, checked) {
1426        (AffOp::None, true) => &ST_ARRLDAFF_NONE,
1427        (AffOp::None, false) => &ST_ARRLDAFF_NONE_U,
1428        (AffOp::Add, true) => &ST_ARRLDAFF_ADD,
1429        (AffOp::Add, false) => &ST_ARRLDAFF_ADD_U,
1430        (AffOp::Sub, true) => &ST_ARRLDAFF_SUB,
1431        (AffOp::Sub, false) => &ST_ARRLDAFF_SUB_U,
1432        (AffOp::Mul, true) => &ST_ARRLDAFF_MUL,
1433        (AffOp::Mul, false) => &ST_ARRLDAFF_MUL_U,
1434    }
1435}
1436
1437/// The conditional-swap stencil for a comparison + bounds-check mode. The
1438/// peephole only ever emits the four orderings (Eq/NotEq swaps are nonsensical).
1439fn condswap_stencil(cmp: Cmp, checked: bool) -> &'static crate::Stencil {
1440    match (cmp, checked) {
1441        (Cmp::Gt, true) => &ST_ARRCONDSWAP_GT,
1442        (Cmp::Gt, false) => &ST_ARRCONDSWAP_GT_U,
1443        (Cmp::Lt, true) => &ST_ARRCONDSWAP_LT,
1444        (Cmp::Lt, false) => &ST_ARRCONDSWAP_LT_U,
1445        (Cmp::GtEq, true) => &ST_ARRCONDSWAP_GE,
1446        (Cmp::GtEq, false) => &ST_ARRCONDSWAP_GE_U,
1447        (Cmp::LtEq, true) => &ST_ARRCONDSWAP_LE,
1448        (Cmp::LtEq, false) => &ST_ARRCONDSWAP_LE_U,
1449        (Cmp::Eq | Cmp::NotEq, _) => unreachable!("cond-swap peephole never emits Eq/NotEq"),
1450    }
1451}
1452
1453fn emit_mem_form(
1454    buf: &mut JitBuffer,
1455    op: &MicroOp,
1456    next: crate::buffer::Label,
1457    deopt_piece: usize,
1458    status: &Option<std::sync::Arc<AtomicI64>>,
1459) {
1460    match *op {
1461        MicroOp::Div { dst, lhs, rhs } | MicroOp::Mod { dst, lhs, rhs } => {
1462            let stencil = if matches!(op, MicroOp::Div { .. }) {
1463                &ST_DIV3C
1464            } else {
1465                &ST_MOD3C
1466            };
1467            buf.push_stencil(
1468                stencil,
1469                &[
1470                    HoleValue::Const(0, lhs as i64),
1471                    HoleValue::Const(1, rhs as i64),
1472                    HoleValue::Const(2, dst as i64),
1473                    HoleValue::Cont(0, next),
1474                    HoleValue::Cont(1, buf.label(deopt_piece)),
1475                ],
1476            );
1477        }
1478        MicroOp::ChrGuard { dst, src } => {
1479            buf.push_stencil(
1480                &ST_CHRGUARD,
1481                &[
1482                    HoleValue::Const(0, src as i64),
1483                    HoleValue::Const(1, dst as i64),
1484                    HoleValue::Cont(0, next),
1485                    HoleValue::Cont(1, buf.label(deopt_piece)),
1486                ],
1487            );
1488        }
1489        MicroOp::DivPow2 { dst, lhs, k } => {
1490            buf.push_stencil(
1491                &ST_DIVPOW2,
1492                &[
1493                    HoleValue::Const(0, lhs as i64),
1494                    HoleValue::Const(1, k as i64),
1495                    HoleValue::Const(2, (1i64 << k) - 1),
1496                    HoleValue::Const(3, dst as i64),
1497                    HoleValue::Cont(0, next),
1498                ],
1499            );
1500        }
1501        MicroOp::MagicDivU {
1502            dst,
1503            lhs,
1504            magic,
1505            more,
1506            mul_back,
1507        } => {
1508            buf.push_stencil(
1509                &ST_MAGICDIV,
1510                &[
1511                    HoleValue::Const(0, lhs as i64),
1512                    HoleValue::Const(1, magic as i64),
1513                    HoleValue::Const(2, more as i64),
1514                    HoleValue::Const(3, mul_back),
1515                    HoleValue::Const(4, dst as i64),
1516                    HoleValue::Cont(0, next),
1517                ],
1518            );
1519        }
1520        MicroOp::AddF { dst, lhs, rhs }
1521        | MicroOp::SubF { dst, lhs, rhs }
1522        | MicroOp::MulF { dst, lhs, rhs } => {
1523            let stencil = match op {
1524                MicroOp::AddF { .. } => &ST_ADDF3,
1525                MicroOp::SubF { .. } => &ST_SUBF3,
1526                _ => &ST_MULF3,
1527            };
1528            buf.push_stencil(
1529                stencil,
1530                &[
1531                    HoleValue::Const(0, lhs as i64),
1532                    HoleValue::Const(1, rhs as i64),
1533                    HoleValue::Const(2, dst as i64),
1534                    HoleValue::Cont(0, next),
1535                ],
1536            );
1537        }
1538        MicroOp::DivF { dst, lhs, rhs } => {
1539            buf.push_stencil(
1540                &ST_DIVF3C,
1541                &[
1542                    HoleValue::Const(0, lhs as i64),
1543                    HoleValue::Const(1, rhs as i64),
1544                    HoleValue::Const(2, dst as i64),
1545                    HoleValue::Cont(0, next),
1546                    HoleValue::Cont(1, buf.label(deopt_piece)),
1547                ],
1548            );
1549        }
1550        MicroOp::LtF { dst, lhs, rhs }
1551        | MicroOp::LtEqF { dst, lhs, rhs }
1552        | MicroOp::EqF { dst, lhs, rhs }
1553        | MicroOp::NeqF { dst, lhs, rhs } => {
1554            let stencil = match op {
1555                MicroOp::LtF { .. } => &ST_LTF3,
1556                MicroOp::LtEqF { .. } => &ST_LEF3,
1557                MicroOp::EqF { .. } => &ST_EQF3,
1558                _ => &ST_NEF3,
1559            };
1560            buf.push_stencil(
1561                stencil,
1562                &[
1563                    HoleValue::Const(0, lhs as i64),
1564                    HoleValue::Const(1, rhs as i64),
1565                    HoleValue::Const(2, dst as i64),
1566                    HoleValue::Cont(0, next),
1567                ],
1568            );
1569        }
1570        // a > b ⇔ b < a; a >= b ⇔ b <= a (Lever 2a): a VALUE-form float ordering
1571        // compare lowers mem-form by SWAPPING operands and reusing the LtF/LeF
1572        // stencil — IEEE-exact, NaN-false on both sides of the swap, bit-identical
1573        // to the tree-walker. (Float EQUALITY is epsilon-fuzzy and stays on its
1574        // own EqF/NeqF path — never swapped here.) This gives the pinned compiler
1575        // a lowering for `GtF`/`GtEqF`, so a region carrying a value-form float
1576        // `>`/`>=` no longer has to drop ALL its XMM pins.
1577        MicroOp::GtF { dst, lhs, rhs } | MicroOp::GtEqF { dst, lhs, rhs } => {
1578            let stencil = match op {
1579                MicroOp::GtF { .. } => &ST_LTF3,
1580                _ => &ST_LEF3,
1581            };
1582            buf.push_stencil(
1583                stencil,
1584                &[
1585                    HoleValue::Const(0, rhs as i64),
1586                    HoleValue::Const(1, lhs as i64),
1587                    HoleValue::Const(2, dst as i64),
1588                    HoleValue::Cont(0, next),
1589                ],
1590            );
1591        }
1592        MicroOp::NotInt { dst, src }
1593        | MicroOp::NotBool { dst, src }
1594        | MicroOp::Popcnt { dst, src }
1595        | MicroOp::Lzcnt { dst, src }
1596        | MicroOp::Tzcnt { dst, src }
1597        | MicroOp::Utf8Len { dst, src }
1598        | MicroOp::FloorToInt { dst, src }
1599        | MicroOp::CeilToInt { dst, src }
1600        | MicroOp::RoundToInt { dst, src }
1601        | MicroOp::IntToFloat { dst, src }
1602        | MicroOp::SqrtF { dst, src } => {
1603            let stencil = match op {
1604                MicroOp::NotInt { .. } => &ST_NOTI2,
1605                MicroOp::NotBool { .. } => &ST_NOTB2,
1606                MicroOp::Popcnt { .. } => &ST_POPCNT2,
1607                MicroOp::Lzcnt { .. } => &ST_LZCNT2,
1608                MicroOp::Tzcnt { .. } => &ST_TZCNT2,
1609                MicroOp::Utf8Len { .. } => &ST_UTF8LEN2,
1610                MicroOp::FloorToInt { .. } => &ST_FLOORF2,
1611                MicroOp::CeilToInt { .. } => &ST_CEILF2,
1612                MicroOp::RoundToInt { .. } => &ST_ROUNDF2,
1613                MicroOp::SqrtF { .. } => &ST_SQRTF2,
1614                _ => &ST_I2F2,
1615            };
1616            buf.push_stencil(
1617                stencil,
1618                &[
1619                    HoleValue::Const(0, src as i64),
1620                    HoleValue::Const(1, dst as i64),
1621                    HoleValue::Cont(0, next),
1622                ],
1623            );
1624        }
1625        MicroOp::Call {
1626            dst,
1627            args_start,
1628            table_addr,
1629            depth_addr,
1630            status_addr,
1631            limit_slot,
1632            depth_limit,
1633        } => {
1634            debug_assert!(status.is_some(), "calls require the status cell");
1635            buf.push_stencil(
1636                &ST_CALL,
1637                &[
1638                    HoleValue::Const(0, table_addr),
1639                    HoleValue::Const(1, args_start as i64),
1640                    HoleValue::Const(2, dst as i64),
1641                    HoleValue::Const(3, depth_addr),
1642                    HoleValue::Const(4, status_addr),
1643                    HoleValue::Const(5, limit_slot as i64),
1644                    HoleValue::Const(6, depth_limit),
1645                    HoleValue::Cont(0, next),
1646                ],
1647            );
1648        }
1649        MicroOp::MapGet {
1650            dst,
1651            key,
1652            map_slot,
1653            helper_addr,
1654        } => {
1655            buf.push_stencil(
1656                &ST_MAPHGET,
1657                &[
1658                    HoleValue::Const(0, map_slot as i64),
1659                    HoleValue::Const(1, key as i64),
1660                    HoleValue::Const(2, dst as i64),
1661                    HoleValue::Const(3, helper_addr),
1662                    HoleValue::Cont(0, next),
1663                    HoleValue::Cont(1, buf.label(deopt_piece)),
1664                ],
1665            );
1666        }
1667        MicroOp::Host {
1668            dst,
1669            src,
1670            count,
1671            imm,
1672            helper_addr,
1673        } => {
1674            buf.push_stencil(
1675                &ST_HOST,
1676                &[
1677                    HoleValue::Const(0, dst as i64),
1678                    HoleValue::Const(1, src as i64),
1679                    HoleValue::Const(2, count as i64),
1680                    HoleValue::Const(3, imm),
1681                    HoleValue::Const(4, helper_addr),
1682                    HoleValue::Cont(0, next),
1683                    HoleValue::Cont(1, buf.label(deopt_piece)),
1684                ],
1685            );
1686        }
1687        MicroOp::MapSet {
1688            src,
1689            key,
1690            map_slot,
1691            helper_addr,
1692        } => {
1693            buf.push_stencil(
1694                &ST_MAPHSET,
1695                &[
1696                    HoleValue::Const(0, map_slot as i64),
1697                    HoleValue::Const(1, key as i64),
1698                    HoleValue::Const(2, src as i64),
1699                    HoleValue::Const(3, helper_addr),
1700                    HoleValue::Cont(0, next),
1701                ],
1702            );
1703        }
1704        MicroOp::MemMem {
1705            h_ptr_slot,
1706            h_len_slot,
1707            n_ptr_slot,
1708            n_len_slot,
1709            needle_len_slot,
1710            i_slot,
1711            count_slot,
1712            helper_addr,
1713        } => {
1714            debug_assert!(
1715                status.is_some(),
1716                "memmem requires the status cell for its deopt exit"
1717            );
1718            buf.push_stencil(
1719                &ST_MEMMEM,
1720                &[
1721                    HoleValue::Const(0, h_ptr_slot as i64),
1722                    HoleValue::Const(1, h_len_slot as i64),
1723                    HoleValue::Const(2, n_ptr_slot as i64),
1724                    HoleValue::Const(3, n_len_slot as i64),
1725                    HoleValue::Const(4, needle_len_slot as i64),
1726                    HoleValue::Const(5, i_slot as i64),
1727                    HoleValue::Const(6, count_slot as i64),
1728                    HoleValue::Const(7, helper_addr),
1729                    HoleValue::Cont(0, next),
1730                    HoleValue::Cont(1, buf.label(deopt_piece)),
1731                ],
1732            );
1733        }
1734        MicroOp::CallSelf {
1735            dst,
1736            args_start,
1737            depth_addr,
1738            status_addr,
1739            limit_slot,
1740            frame_size,
1741        } => {
1742            buf.push_stencil(
1743                &ST_CALL_SELF,
1744                &[
1745                    HoleValue::Const(0, 0),
1746                    HoleValue::Const(1, args_start as i64),
1747                    HoleValue::Const(2, dst as i64),
1748                    HoleValue::Const(3, depth_addr),
1749                    HoleValue::Const(4, status_addr),
1750                    HoleValue::Const(5, limit_slot as i64),
1751                    HoleValue::Const(6, frame_size),
1752                    HoleValue::Cont(0, next),
1753                ],
1754            );
1755            buf.mark_patch_hole(0);
1756        }
1757        MicroOp::CallSelfCopy {
1758            dst,
1759            args_start,
1760            src_start,
1761            arg_count,
1762            depth_addr,
1763            status_addr,
1764            limit_slot,
1765            frame_size,
1766        } => {
1767            buf.push_stencil(
1768                &ST_CALL_SELF_COPY,
1769                &[
1770                    HoleValue::Const(0, 0),
1771                    HoleValue::Const(1, args_start as i64),
1772                    HoleValue::Const(2, dst as i64),
1773                    HoleValue::Const(3, depth_addr),
1774                    HoleValue::Const(4, status_addr),
1775                    HoleValue::Const(5, limit_slot as i64),
1776                    HoleValue::Const(6, frame_size),
1777                    HoleValue::Const(7, src_start as i64),
1778                    HoleValue::Const(8, arg_count as i64),
1779                    HoleValue::Cont(0, next),
1780                ],
1781            );
1782            buf.mark_patch_hole(0);
1783        }
1784        MicroOp::NewList {
1785            vec_slot,
1786            ptr_slot,
1787            len_slot,
1788            helper_addr,
1789        } => {
1790            buf.push_stencil(
1791                &ST_ALLOCLIST,
1792                &[
1793                    HoleValue::Const(0, vec_slot as i64),
1794                    HoleValue::Const(1, ptr_slot as i64),
1795                    HoleValue::Const(2, len_slot as i64),
1796                    HoleValue::Const(3, helper_addr),
1797                    HoleValue::Cont(0, next),
1798                ],
1799            );
1800        }
1801        MicroOp::ListTriple {
1802            handle_slot,
1803            vec_slot,
1804            ptr_slot,
1805            len_slot,
1806            helper_addr,
1807        } => {
1808            buf.push_stencil(
1809                &ST_LISTTRIPLE,
1810                &[
1811                    HoleValue::Const(0, handle_slot as i64),
1812                    HoleValue::Const(1, vec_slot as i64),
1813                    HoleValue::Const(2, ptr_slot as i64),
1814                    HoleValue::Const(3, len_slot as i64),
1815                    HoleValue::Const(4, helper_addr),
1816                    HoleValue::Cont(0, next),
1817                ],
1818            );
1819        }
1820        MicroOp::MapHas {
1821            dst,
1822            key,
1823            map_slot,
1824            helper_addr,
1825        } => {
1826            buf.push_stencil(
1827                &ST_MAPHHAS,
1828                &[
1829                    HoleValue::Const(0, map_slot as i64),
1830                    HoleValue::Const(1, key as i64),
1831                    HoleValue::Const(2, dst as i64),
1832                    HoleValue::Const(3, helper_addr),
1833                    HoleValue::Cont(0, next),
1834                ],
1835            );
1836        }
1837        // Array load/store: 1-based, bounds-checked. A failed bound jumps to
1838        // the shared deopt terminal (region replay / function side-exit).
1839        // The pinned mem-form path has already spilled the pinned operands
1840        // (idx/ptr/len/src) to the frame, so these read frame slots exactly
1841        // like the unpinned chain.
1842        MicroOp::ArrLoad {
1843            dst,
1844            idx,
1845            ptr_slot,
1846            len_slot,
1847            byte,
1848            narrow32,
1849            checked,
1850        } => {
1851            if checked {
1852                buf.push_stencil(
1853                    arrld_stencil(byte, narrow32, true),
1854                    &[
1855                        HoleValue::Const(0, idx as i64),
1856                        HoleValue::Const(1, ptr_slot as i64),
1857                        HoleValue::Const(2, len_slot as i64),
1858                        HoleValue::Const(3, dst as i64),
1859                        HoleValue::Cont(0, next),
1860                        HoleValue::Cont(1, buf.label(deopt_piece)),
1861                    ],
1862                );
1863            } else {
1864                buf.push_stencil(
1865                    arrld_stencil(byte, narrow32, false),
1866                    &[
1867                        HoleValue::Const(0, idx as i64),
1868                        HoleValue::Const(1, ptr_slot as i64),
1869                        HoleValue::Const(3, dst as i64),
1870                        HoleValue::Cont(0, next),
1871                    ],
1872                );
1873            }
1874        }
1875        MicroOp::ArrLoadAffine {
1876            dst,
1877            a,
1878            op,
1879            b,
1880            const_offset,
1881            ptr_slot,
1882            len_slot,
1883            checked,
1884        } => {
1885            if checked {
1886                buf.push_stencil(
1887                    affine_stencil(op, true),
1888                    &[
1889                        HoleValue::Const(0, a as i64),
1890                        HoleValue::Const(1, b as i64),
1891                        HoleValue::Const(2, const_offset),
1892                        HoleValue::Const(3, ptr_slot as i64),
1893                        HoleValue::Const(4, len_slot as i64),
1894                        HoleValue::Const(5, dst as i64),
1895                        HoleValue::Cont(0, next),
1896                        HoleValue::Cont(1, buf.label(deopt_piece)),
1897                    ],
1898                );
1899            } else {
1900                buf.push_stencil(
1901                    affine_stencil(op, false),
1902                    &[
1903                        HoleValue::Const(0, a as i64),
1904                        HoleValue::Const(1, b as i64),
1905                        HoleValue::Const(2, const_offset),
1906                        HoleValue::Const(3, ptr_slot as i64),
1907                        HoleValue::Const(5, dst as i64),
1908                        HoleValue::Cont(0, next),
1909                    ],
1910                );
1911            }
1912        }
1913        MicroOp::ArrLoad2F {
1914            dst,
1915            i: ix,
1916            j: jx,
1917            ptr_slot,
1918            len_slot,
1919            op,
1920        } => {
1921            let stencil = match op {
1922                FOp::Add => &ST_ARRLD2_ADDF,
1923                FOp::Sub => &ST_ARRLD2_SUBF,
1924                FOp::Mul => &ST_ARRLD2_MULF,
1925            };
1926            buf.push_stencil(
1927                stencil,
1928                &[
1929                    HoleValue::Const(0, ix as i64),
1930                    HoleValue::Const(1, jx as i64),
1931                    HoleValue::Const(2, ptr_slot as i64),
1932                    HoleValue::Const(3, len_slot as i64),
1933                    HoleValue::Const(4, dst as i64),
1934                    HoleValue::Cont(0, next),
1935                    HoleValue::Cont(1, buf.label(deopt_piece)),
1936                ],
1937            );
1938        }
1939        MicroOp::ArrLoad2 {
1940            dst,
1941            i: ix,
1942            j: jx,
1943            ptr_a,
1944            len_a,
1945            ptr_b,
1946            len_b,
1947            op,
1948            checked,
1949        } => {
1950            if checked {
1951                buf.push_stencil(
1952                    ld2_int_stencil(op, true),
1953                    &[
1954                        HoleValue::Const(0, ix as i64),
1955                        HoleValue::Const(1, jx as i64),
1956                        HoleValue::Const(2, ptr_a as i64),
1957                        HoleValue::Const(3, len_a as i64),
1958                        HoleValue::Const(4, ptr_b as i64),
1959                        HoleValue::Const(5, len_b as i64),
1960                        HoleValue::Const(6, dst as i64),
1961                        HoleValue::Cont(0, next),
1962                        HoleValue::Cont(1, buf.label(deopt_piece)),
1963                    ],
1964                );
1965            } else {
1966                buf.push_stencil(
1967                    ld2_int_stencil(op, false),
1968                    &[
1969                        HoleValue::Const(0, ix as i64),
1970                        HoleValue::Const(1, jx as i64),
1971                        HoleValue::Const(2, ptr_a as i64),
1972                        HoleValue::Const(3, ptr_b as i64),
1973                        HoleValue::Const(4, dst as i64),
1974                        HoleValue::Cont(0, next),
1975                    ],
1976                );
1977            }
1978        }
1979        MicroOp::ArrStore {
1980            src,
1981            idx,
1982            ptr_slot,
1983            len_slot,
1984            byte,
1985            narrow32,
1986            checked,
1987        } => {
1988            if checked {
1989                buf.push_stencil(
1990                    arrst_stencil(byte, narrow32, true),
1991                    &[
1992                        HoleValue::Const(0, idx as i64),
1993                        HoleValue::Const(1, ptr_slot as i64),
1994                        HoleValue::Const(2, len_slot as i64),
1995                        HoleValue::Const(3, src as i64),
1996                        HoleValue::Cont(0, next),
1997                        HoleValue::Cont(1, buf.label(deopt_piece)),
1998                    ],
1999                );
2000            } else {
2001                buf.push_stencil(
2002                    arrst_stencil(byte, narrow32, false),
2003                    &[
2004                        HoleValue::Const(0, idx as i64),
2005                        HoleValue::Const(1, ptr_slot as i64),
2006                        HoleValue::Const(3, src as i64),
2007                        HoleValue::Cont(0, next),
2008                    ],
2009                );
2010            }
2011        }
2012        MicroOp::ArrRMW {
2013            idx,
2014            operand,
2015            ptr_slot,
2016            len_slot,
2017            op,
2018            checked,
2019        } => {
2020            if checked {
2021                buf.push_stencil(
2022                    rmw_stencil(op, true),
2023                    &[
2024                        HoleValue::Const(0, idx as i64),
2025                        HoleValue::Const(1, ptr_slot as i64),
2026                        HoleValue::Const(2, len_slot as i64),
2027                        HoleValue::Const(3, operand as i64),
2028                        HoleValue::Cont(0, next),
2029                        HoleValue::Cont(1, buf.label(deopt_piece)),
2030                    ],
2031                );
2032            } else {
2033                buf.push_stencil(
2034                    rmw_stencil(op, false),
2035                    &[
2036                        HoleValue::Const(0, idx as i64),
2037                        HoleValue::Const(1, ptr_slot as i64),
2038                        HoleValue::Const(3, operand as i64),
2039                        HoleValue::Cont(0, next),
2040                    ],
2041                );
2042            }
2043        }
2044        MicroOp::ArrCondSwap {
2045            idx1,
2046            idx2,
2047            ptr_slot,
2048            len_slot,
2049            cmp,
2050            checked,
2051        } => {
2052            if checked {
2053                buf.push_stencil(
2054                    condswap_stencil(cmp, true),
2055                    &[
2056                        HoleValue::Const(0, idx1 as i64),
2057                        HoleValue::Const(1, idx2 as i64),
2058                        HoleValue::Const(2, ptr_slot as i64),
2059                        HoleValue::Const(3, len_slot as i64),
2060                        HoleValue::Cont(0, next),
2061                        HoleValue::Cont(1, buf.label(deopt_piece)),
2062                    ],
2063                );
2064            } else {
2065                buf.push_stencil(
2066                    condswap_stencil(cmp, false),
2067                    &[
2068                        HoleValue::Const(0, idx1 as i64),
2069                        HoleValue::Const(1, idx2 as i64),
2070                        HoleValue::Const(2, ptr_slot as i64),
2071                        HoleValue::Cont(0, next),
2072                    ],
2073                );
2074            }
2075        }
2076        MicroOp::ArrSwap {
2077            idx1,
2078            idx2,
2079            ptr_slot,
2080            len_slot,
2081            checked,
2082        } => {
2083            if checked {
2084                buf.push_stencil(
2085                    &ST_ARRSWAP,
2086                    &[
2087                        HoleValue::Const(0, idx1 as i64),
2088                        HoleValue::Const(1, idx2 as i64),
2089                        HoleValue::Const(2, ptr_slot as i64),
2090                        HoleValue::Const(3, len_slot as i64),
2091                        HoleValue::Cont(0, next),
2092                        HoleValue::Cont(1, buf.label(deopt_piece)),
2093                    ],
2094                );
2095            } else {
2096                buf.push_stencil(
2097                    &ST_ARRSWAP_U,
2098                    &[
2099                        HoleValue::Const(0, idx1 as i64),
2100                        HoleValue::Const(1, idx2 as i64),
2101                        HoleValue::Const(2, ptr_slot as i64),
2102                        HoleValue::Cont(0, next),
2103                    ],
2104                );
2105            }
2106        }
2107        MicroOp::FmaF { dst, a, b, c } => {
2108            buf.push_stencil(
2109                &ST_FMAF,
2110                &[
2111                    HoleValue::Const(0, a as i64),
2112                    HoleValue::Const(1, b as i64),
2113                    HoleValue::Const(2, c as i64),
2114                    HoleValue::Const(3, dst as i64),
2115                    HoleValue::Cont(0, next),
2116                ],
2117            );
2118        }
2119        // Helper-call push; refreshes the pinned ptr/len after a possible
2120        // realloc (the mem-form path reloads them from the frame after).
2121        MicroOp::ArrPush {
2122            src,
2123            vec_slot,
2124            ptr_slot,
2125            len_slot,
2126            helper_addr,
2127            byte: _,
2128            narrow32: _,
2129        } => {
2130            buf.push_stencil(
2131                &ST_PUSH,
2132                &[
2133                    HoleValue::Const(0, src as i64),
2134                    HoleValue::Const(1, vec_slot as i64),
2135                    HoleValue::Const(2, ptr_slot as i64),
2136                    HoleValue::Const(3, len_slot as i64),
2137                    HoleValue::Const(4, helper_addr),
2138                    HoleValue::Cont(0, next),
2139                ],
2140            );
2141        }
2142        ref other => {
2143            unreachable!("emit_mem_form: unsupported op {other:?} (pinned chains exclude it)")
2144        }
2145    }
2146}
2147
2148/// REGISTER-THREADING compilation (EXODIA 3.1): up to four frame slots are
2149/// PINNED into the threaded registers r0..r3 for the whole chain. Pinned
2150/// operands ride registers through the generated location-variant
2151/// stencils; ops outside the variant families (Div, arrays, calls, …)
2152/// spill the pinned operands they read and reload the pinned slots they
2153/// write, so every memory-form piece still sees a coherent frame.
2154///
2155/// Frame-coherence contract: a pinned slot's FRAME cell is stale between
2156/// its spills — callers must only use pinning where nothing outside the
2157/// chain reads the frame mid-run (mode-A functions: replay re-enters from
2158/// the boundary arguments and the result returns by register).
2159pub fn compile_straightline_pinned(
2160    ops: &[MicroOp],
2161    pins: &[u16],
2162) -> Result<CompiledChain, JitCompileError> {
2163    compile_straightline_pinned_with(ops, pins, None)
2164}
2165
2166/// [`compile_straightline_pinned`] with a SHARED status cell (the function
2167/// tier's deopt/call seam). Integer/bool slots only — no XMM float pins.
2168pub fn compile_straightline_pinned_with(
2169    ops: &[MicroOp],
2170    pins: &[u16],
2171    shared_status: Option<std::sync::Arc<AtomicI64>>,
2172) -> Result<CompiledChain, JitCompileError> {
2173    compile_straightline_pinned_float(ops, pins, &[], shared_status)
2174}
2175
2176/// The full register-threading compiler with BOTH integer pins (`pins`,
2177/// threaded through the GP registers r0..r3) and FLOAT pins (`fpins`,
2178/// threaded through the XMM registers f0..f3). The two budgets are
2179/// independent — the threaded ABI carries `fn(base, sp, r0..r3, f0..f3)`, so
2180/// base/sp consume 2 of the 6 GP arg registers (leaving r0..r3) while all
2181/// four XMM pins sit in the 8 free XMM arg registers and never compete with
2182/// the integer pins.
2183///
2184/// A FLOAT slot pinned to `fN` keeps its f64 live in that XMM register across
2185/// every stencil — the pure float arith variants (V_FBINOP) read and write it
2186/// directly, and the mem-form float stencils (sqrt, divf, the float compares,
2187/// array load/store) THREAD f0..f3 unchanged, so any float pin they do not
2188/// themselves touch survives with no frame traffic. The ones a mem-form op
2189/// does read/write are spilled before / reloaded after, exactly like the GP
2190/// pins.
2191pub fn compile_straightline_pinned_float(
2192    ops: &[MicroOp],
2193    pins: &[u16],
2194    fpins: &[u16],
2195    shared_status: Option<std::sync::Arc<AtomicI64>>,
2196) -> Result<CompiledChain, JitCompileError> {
2197    if pins.is_empty() && fpins.is_empty() {
2198        return compile_straightline_coded(ops, shared_status, None, 0);
2199    }
2200    assert!(pins.len() <= 4, "at most four threaded GP registers");
2201    assert!(
2202        fpins.len() <= 6,
2203        "at most six threaded XMM registers (f0..f5)"
2204    );
2205    debug_assert!(
2206        pins.iter().all(|p| !fpins.contains(p)),
2207        "a slot cannot be both GP- and float-pinned"
2208    );
2209    if ops.is_empty() {
2210        return Err(JitCompileError::Empty);
2211    }
2212    if !matches!(
2213        ops.last(),
2214        Some(MicroOp::Return { .. }) | Some(MicroOp::Jump { .. })
2215    ) {
2216        return Err(JitCompileError::FallsOffTheEnd);
2217    }
2218    let loc = |slot: u16| -> usize {
2219        pins.iter()
2220            .position(|&p| p == slot)
2221            .map(|i| i + 1)
2222            .unwrap_or(0)
2223    };
2224    // The XMM-pin location of a slot: 0 = frame, 1..4 = f0..f3.
2225    let floc = |slot: u16| -> usize {
2226        fpins
2227            .iter()
2228            .position(|&p| p == slot)
2229            .map(|i| i + 1)
2230            .unwrap_or(0)
2231    };
2232    // Which pinned registers an op forces through MEMORY (spill before /
2233    // reload after) because it has no variant family.
2234    let mem_form_touch = |op: &MicroOp| -> (Vec<u16>, Vec<u16>) {
2235        let mut reads: Vec<u16> = Vec::new();
2236        let mut writes: Vec<u16> = Vec::new();
2237        match *op {
2238            MicroOp::Div { dst, lhs, rhs } | MicroOp::Mod { dst, lhs, rhs } => {
2239                reads.extend([lhs, rhs]);
2240                writes.push(dst);
2241            }
2242            MicroOp::DivPow2 { dst, lhs, .. } | MicroOp::MagicDivU { dst, lhs, .. } => {
2243                reads.push(lhs);
2244                writes.push(dst);
2245            }
2246            // Float add/sub/mul are register-threaded (V_FBINOP) — NOT
2247            // mem-form. DivF (div-by-zero side-exit) and the float comparisons
2248            // (no variant yet) stay mem-form.
2249            MicroOp::DivF { dst, lhs, rhs }
2250            | MicroOp::LtF { dst, lhs, rhs }
2251            | MicroOp::LtEqF { dst, lhs, rhs }
2252            | MicroOp::GtF { dst, lhs, rhs }
2253            | MicroOp::GtEqF { dst, lhs, rhs }
2254            | MicroOp::EqF { dst, lhs, rhs }
2255            | MicroOp::NeqF { dst, lhs, rhs } => {
2256                reads.extend([lhs, rhs]);
2257                writes.push(dst);
2258            }
2259            MicroOp::NotInt { dst, src }
2260            | MicroOp::NotBool { dst, src }
2261            | MicroOp::IntToFloat { dst, src }
2262            | MicroOp::SqrtF { dst, src }
2263            | MicroOp::ChrGuard { dst, src } => {
2264                reads.push(src);
2265                writes.push(dst);
2266            }
2267            MicroOp::BranchF { lhs, rhs, .. } => reads.extend([lhs, rhs]),
2268            // ptr_slot/len_slot are read DIRECTLY from the frame by the array
2269            // stencil (or, when the array's base pointer is GP-pinned, from its
2270            // register via the RPTR variant) — never through the threaded-pin
2271            // spill path, so they are NOT listed as spill-reads here. (They are
2272            // loop-invariant; the array never moves unless pushed-to, and a
2273            // pushed array is not ptr-pinned.)
2274            MicroOp::ArrLoad { dst, idx, .. } => {
2275                reads.push(idx);
2276                writes.push(dst);
2277            }
2278            MicroOp::ArrLoadAffine { dst, a, op, b, .. } => {
2279                reads.push(a);
2280                if op != AffOp::None {
2281                    reads.push(b);
2282                }
2283                writes.push(dst);
2284            }
2285            MicroOp::ArrLoad2F {
2286                dst, i: ix, j: jx, ..
2287            } => {
2288                reads.extend([ix, jx]);
2289                writes.push(dst);
2290            }
2291            MicroOp::ArrLoad2 {
2292                dst, i: ix, j: jx, ..
2293            } => {
2294                reads.extend([ix, jx]);
2295                writes.push(dst);
2296            }
2297            MicroOp::ArrStore { src, idx, .. } => {
2298                reads.extend([src, idx]);
2299            }
2300            MicroOp::ArrRMW { idx, operand, .. } => {
2301                reads.extend([idx, operand]);
2302            }
2303            MicroOp::ArrCondSwap { idx1, idx2, .. } => {
2304                reads.extend([idx1, idx2]);
2305            }
2306            MicroOp::ArrSwap { idx1, idx2, .. } => {
2307                reads.extend([idx1, idx2]);
2308            }
2309            MicroOp::FmaF { dst, a, b, c } => {
2310                reads.extend([a, b, c]);
2311                writes.push(dst);
2312            }
2313            MicroOp::ArrPush {
2314                src,
2315                vec_slot,
2316                ptr_slot,
2317                len_slot,
2318                ..
2319            } => {
2320                reads.extend([src, vec_slot, ptr_slot, len_slot]);
2321                writes.extend([ptr_slot, len_slot]);
2322            }
2323            MicroOp::MapGet {
2324                dst, key, map_slot, ..
2325            } => {
2326                reads.extend([key, map_slot]);
2327                writes.push(dst);
2328            }
2329            MicroOp::Host {
2330                dst, src, count, ..
2331            } => {
2332                reads.extend(src..src + count);
2333                writes.push(dst);
2334            }
2335            MicroOp::MapSet {
2336                src, key, map_slot, ..
2337            } => {
2338                reads.extend([src, key, map_slot]);
2339            }
2340            MicroOp::MapHas {
2341                dst, key, map_slot, ..
2342            } => {
2343                reads.extend([key, map_slot]);
2344                writes.push(dst);
2345            }
2346            MicroOp::MemMem {
2347                h_ptr_slot,
2348                h_len_slot,
2349                n_ptr_slot,
2350                n_len_slot,
2351                needle_len_slot,
2352                i_slot,
2353                count_slot,
2354                ..
2355            } => {
2356                // The helper reads every input slot from the frame and writes
2357                // `i_slot`/`count_slot` back — so a pinned operand must spill
2358                // first and a pinned destination reload after. (The recognizer
2359                // runs MemMem regions UNPINNED, so in practice these retain to
2360                // empty; kept for correctness if a pin ever survives.)
2361                reads.extend([
2362                    h_ptr_slot,
2363                    h_len_slot,
2364                    n_ptr_slot,
2365                    n_len_slot,
2366                    needle_len_slot,
2367                    i_slot,
2368                    count_slot,
2369                ]);
2370                writes.extend([i_slot, count_slot]);
2371            }
2372            MicroOp::NewList {
2373                vec_slot,
2374                ptr_slot,
2375                len_slot,
2376                ..
2377            } => {
2378                writes.extend([vec_slot, ptr_slot, len_slot]);
2379            }
2380            MicroOp::ListTriple {
2381                handle_slot,
2382                vec_slot,
2383                ptr_slot,
2384                len_slot,
2385                ..
2386            } => {
2387                reads.push(handle_slot);
2388                writes.extend([vec_slot, ptr_slot, len_slot]);
2389            }
2390            MicroOp::Call { dst, .. } | MicroOp::CallSelf { dst, .. } => {
2391                // The callee window was staged through ordinary Moves; the
2392                // result lands in the frame.
2393                writes.push(dst);
2394            }
2395            MicroOp::CallSelfCopy {
2396                dst,
2397                src_start,
2398                arg_count,
2399                ..
2400            } => {
2401                // The fused stencil reads the SOURCE block from the FRAME, so
2402                // any source slot held in a pinned register must spill to its
2403                // frame cell before the copy; the result lands in the frame.
2404                reads.extend((src_start..src_start + arg_count).collect::<Vec<_>>());
2405                writes.push(dst);
2406            }
2407            _ => {}
2408        }
2409        // A touched slot needs spill/reload when it is pinned in EITHER
2410        // budget (GP r0..r3 or XMM f0..f3) — the spill/reload primitives
2411        // dispatch on which.
2412        let pinned = |s: u16| loc(s) != 0 || floc(s) != 0;
2413        reads.retain(|&r| pinned(r));
2414        reads.dedup();
2415        writes.retain(|&w| pinned(w));
2416        writes.dedup();
2417        (reads, writes)
2418    };
2419    let has_variant = |op: &MicroOp| -> bool {
2420        matches!(
2421            op,
2422            MicroOp::Add { .. }
2423                | MicroOp::Sub { .. }
2424                | MicroOp::Mul { .. }
2425                | MicroOp::BitAnd { .. }
2426                | MicroOp::BitOr { .. }
2427                | MicroOp::BitXor { .. }
2428                | MicroOp::Shl { .. }
2429                | MicroOp::Shr { .. }
2430                | MicroOp::Ushr { .. }
2431                | MicroOp::Rotate { .. }
2432                | MicroOp::Lt { .. }
2433                | MicroOp::LtEq { .. }
2434                | MicroOp::Eq { .. }
2435                | MicroOp::Neq { .. }
2436                | MicroOp::Gt { .. }
2437                | MicroOp::GtEq { .. }
2438                | MicroOp::Move { .. }
2439                | MicroOp::LoadConst { .. }
2440                | MicroOp::Return { .. }
2441                | MicroOp::Branch { .. }
2442                // Float add/sub/mul/div + sqrt — register-threaded through the
2443                // XMM-pin variant tables (V_FBINOP / V_DIVF / V_SQRTF), one
2444                // piece each. DivF still side-exits on a zero divisor; its
2445                // variant carries the deopt continuation.
2446                | MicroOp::AddF { .. }
2447                | MicroOp::SubF { .. }
2448                | MicroOp::MulF { .. }
2449                | MicroOp::DivF { .. }
2450                | MicroOp::SqrtF { .. }
2451                | MicroOp::IntToFloat { .. }
2452                | MicroOp::BranchF { .. }
2453                // `chr` validity guard — register-threaded through V_CHRGUARD,
2454                // one piece; like DivF its variant carries the `cont_1` deopt
2455                // for the invalid-code side-exit (surrogate / past-max).
2456                | MicroOp::ChrGuard { .. }
2457                // `utf8_len` — register-threaded through V_UTF8LEN, one piece;
2458                // computes the UTF-8 byte length of a validated code point.
2459                | MicroOp::Utf8Len { .. }
2460        )
2461    };
2462
2463    let n_pin = pins.len() + fpins.len();
2464    // PASS 1: piece index per op (prologue reloads first).
2465    let mut op_piece: Vec<usize> = Vec::with_capacity(ops.len());
2466    let mut next_piece = n_pin;
2467    for op in ops {
2468        op_piece.push(next_piece);
2469        next_piece += match *op {
2470            // EPILOGUE (Phase 2 write-set pinning): a success exit spills every
2471            // pinned slot (GP and XMM) back to its frame cell so the VM's
2472            // write-back sees the loop-carried values — `n_pin` spill pieces +
2473            // the return.
2474            MicroOp::Return { .. } => n_pin + 1,
2475            _ if has_variant(op) => 1,
2476            MicroOp::Jump { .. } => 1,
2477            MicroOp::JumpIfFalse { cond, .. } | MicroOp::JumpIfTrue { cond, .. } => {
2478                if loc(cond) != 0 {
2479                    2
2480                } else {
2481                    1
2482                }
2483            }
2484            _ => {
2485                let (r, w) = mem_form_touch(op);
2486                r.len() + 1 + w.len()
2487            }
2488        };
2489    }
2490    let total_op_pieces = next_piece;
2491    let has_checked = ops.iter().any(|op| {
2492        matches!(
2493            op,
2494            // Integer add/sub/mul side-exit (`cont_1`) on signed overflow so the exact
2495            // tier promotes to BigInt — they need the status cell + deopt terminal.
2496            MicroOp::Add { .. }
2497                | MicroOp::Sub { .. }
2498                | MicroOp::Mul { .. }
2499                | MicroOp::Div { .. }
2500                | MicroOp::Mod { .. }
2501                | MicroOp::DivF { .. }
2502                | MicroOp::ArrLoad { .. }
2503                | MicroOp::ArrLoadAffine { checked: true, .. }
2504                | MicroOp::ArrLoad2F { .. }
2505                | MicroOp::ArrLoad2 { checked: true, .. }
2506                | MicroOp::ArrStore { .. }
2507                | MicroOp::ArrRMW { checked: true, .. }
2508                | MicroOp::ArrCondSwap { checked: true, .. }
2509                | MicroOp::ArrSwap { checked: true, .. }
2510                | MicroOp::Call { .. }
2511                | MicroOp::CallSelf { .. }
2512                | MicroOp::CallSelfCopy { .. }
2513                | MicroOp::MapGet { .. }
2514                | MicroOp::Host { .. }
2515                | MicroOp::MemMem { .. }
2516                // `chr` validity guard side-exits (`cont_1`) on an invalid code
2517                // so the VM re-runs `chr` and traps — needs the deopt terminal.
2518                | MicroOp::ChrGuard { .. }
2519        )
2520    });
2521    let status: Option<std::sync::Arc<AtomicI64>> = if has_checked {
2522        Some(shared_status.unwrap_or_else(|| std::sync::Arc::new(AtomicI64::new(0))))
2523    } else {
2524        None
2525    };
2526    let deopt_piece = total_op_pieces;
2527
2528    // PASS 2: emit.
2529    let mut buf = JitBuffer::new();
2530    // Prologue: reload each pinned slot from the frame — the GP pins into
2531    // r0..r3 (V_MOV), then the float pins into f0..f3 (V_FMOV). The pieces
2532    // are laid out GP-first, so piece index `i` for `i < pins.len()` reloads
2533    // GP pin `i`, and `pins.len() + j` reloads float pin `j`.
2534    for (i, &slot) in pins.iter().enumerate() {
2535        buf.push_stencil(
2536            V_MOV[i + 1][0],
2537            &[
2538                HoleValue::Const(0, slot as i64),
2539                HoleValue::Cont(0, buf.label(i + 1)),
2540            ],
2541        );
2542    }
2543    for (j, &slot) in fpins.iter().enumerate() {
2544        let here = pins.len() + j;
2545        buf.push_stencil(
2546            V_FMOV[j + 1][0],
2547            &[
2548                HoleValue::Const(0, slot as i64),
2549                HoleValue::Cont(0, buf.label(here + 1)),
2550            ],
2551        );
2552    }
2553    // Spill/reload a pinned slot — dispatching on its budget. A GP pin moves
2554    // through V_MOV (r0..r3 ↔ frame i64); a float pin through V_FMOV (f0..f3
2555    // ↔ frame f64 bits). A slot is in exactly one budget.
2556    let spill = |buf: &mut JitBuffer, slot: u16, after: usize| {
2557        if floc(slot) != 0 {
2558            buf.push_stencil(
2559                V_FMOV[0][floc(slot)],
2560                &[
2561                    HoleValue::Const(1, slot as i64),
2562                    HoleValue::Cont(0, buf.label(after)),
2563                ],
2564            );
2565        } else {
2566            buf.push_stencil(
2567                V_MOV[0][loc(slot)],
2568                &[
2569                    HoleValue::Const(1, slot as i64),
2570                    HoleValue::Cont(0, buf.label(after)),
2571                ],
2572            );
2573        }
2574    };
2575    let reload = |buf: &mut JitBuffer, slot: u16, after: usize| {
2576        if floc(slot) != 0 {
2577            buf.push_stencil(
2578                V_FMOV[floc(slot)][0],
2579                &[
2580                    HoleValue::Const(0, slot as i64),
2581                    HoleValue::Cont(0, buf.label(after)),
2582                ],
2583            );
2584        } else {
2585            buf.push_stencil(
2586                V_MOV[loc(slot)][0],
2587                &[
2588                    HoleValue::Const(0, slot as i64),
2589                    HoleValue::Cont(0, buf.label(after)),
2590                ],
2591            );
2592        }
2593    };
2594    // Jump threading: a continuation that lands on an unconditional `Jump`
2595    // follows it straight to the target, so the predecessor branches directly
2596    // and the per-iteration back-edge jmp every loop pays (`…; Jump(top)`) is
2597    // skipped. The Jump piece is still EMITTED (left as unreferenced dead code)
2598    // so piece indices — and every `op_piece[..]` label — stay valid.
2599    let no_thread = std::env::var_os("LOGOS_NOTHREAD").is_some();
2600    let thread = |start: usize| -> usize {
2601        if no_thread {
2602            return start;
2603        }
2604        let mut idx = start;
2605        for _ in 0..=ops.len() {
2606            match ops.get(idx) {
2607                Some(MicroOp::Jump { target }) => idx = *target,
2608                _ => break,
2609            }
2610        }
2611        idx
2612    };
2613    for (i, op) in ops.iter().enumerate() {
2614        let here = op_piece[i];
2615        debug_assert_eq!(
2616            buf.pieces_pushed(),
2617            here,
2618            "PASS1/PASS2 piece divergence before op {i} ({op:?}); pins={pins:?} fpins={fpins:?}"
2619        );
2620        let next_op = op_piece
2621            .get(thread(i + 1))
2622            .copied()
2623            .unwrap_or(total_op_pieces);
2624        let lbl = |t: usize| -> usize { op_piece[thread(t)] };
2625        match *op {
2626            MicroOp::LoadConst { dst, value } => {
2627                let d = loc(dst);
2628                if d == 0 {
2629                    buf.push_stencil(
2630                        &ST_CONSTST,
2631                        &[
2632                            HoleValue::Const(0, value),
2633                            HoleValue::Const(1, dst as i64),
2634                            HoleValue::Cont(0, buf.label(next_op)),
2635                        ],
2636                    );
2637                } else {
2638                    buf.push_stencil(
2639                        V_CONST[d - 1],
2640                        &[
2641                            HoleValue::Const(0, value),
2642                            HoleValue::Cont(0, buf.label(next_op)),
2643                        ],
2644                    );
2645                }
2646            }
2647            MicroOp::Move { dst, src } => {
2648                let (fd, fs) = (floc(dst), floc(src));
2649                if fd != 0 || fs != 0 {
2650                    // FLOAT move: at least one operand rides an XMM pin, so this
2651                    // is an f64 copy — thread it through V_FMOV (register f→f, or
2652                    // a frame↔register half when the other end is frame-resident).
2653                    // A float-pinned slot is never GP-pinned, so `loc` plays no
2654                    // part. Register ends read/write the XMM directly (no hole);
2655                    // a frame end uses hole 0 (src) or hole 1 (dst).
2656                    let mut holes: Vec<HoleValue> = Vec::new();
2657                    if fs == 0 {
2658                        holes.push(HoleValue::Const(0, src as i64));
2659                    }
2660                    if fd == 0 {
2661                        holes.push(HoleValue::Const(1, dst as i64));
2662                    }
2663                    holes.push(HoleValue::Cont(0, buf.label(next_op)));
2664                    buf.push_stencil(V_FMOV[fd][fs], &holes);
2665                } else {
2666                    let (d, sl) = (loc(dst), loc(src));
2667                    if d == 0 && sl == 0 {
2668                        buf.push_stencil(
2669                            &ST_MOVSS,
2670                            &[
2671                                HoleValue::Const(0, src as i64),
2672                                HoleValue::Const(1, dst as i64),
2673                                HoleValue::Cont(0, buf.label(next_op)),
2674                            ],
2675                        );
2676                    } else {
2677                        let mut holes: Vec<HoleValue> = Vec::new();
2678                        if sl == 0 {
2679                            holes.push(HoleValue::Const(0, src as i64));
2680                        }
2681                        if d == 0 {
2682                            holes.push(HoleValue::Const(1, dst as i64));
2683                        }
2684                        holes.push(HoleValue::Cont(0, buf.label(next_op)));
2685                        buf.push_stencil(V_MOV[d][sl], &holes);
2686                    }
2687                }
2688            }
2689            MicroOp::Add { dst, lhs, rhs }
2690            | MicroOp::Sub { dst, lhs, rhs }
2691            | MicroOp::Mul { dst, lhs, rhs }
2692            | MicroOp::BitAnd { dst, lhs, rhs }
2693            | MicroOp::BitOr { dst, lhs, rhs }
2694            | MicroOp::BitXor { dst, lhs, rhs }
2695            | MicroOp::Shl { dst, lhs, rhs }
2696            | MicroOp::Shr { dst, lhs, rhs }
2697            | MicroOp::Ushr { dst, lhs, rhs }
2698            | MicroOp::Rotate { dst, lhs, rhs, .. }
2699            | MicroOp::Lt { dst, lhs, rhs }
2700            | MicroOp::LtEq { dst, lhs, rhs }
2701            | MicroOp::Eq { dst, lhs, rhs }
2702            | MicroOp::Neq { dst, lhs, rhs }
2703            | MicroOp::Gt { dst, lhs, rhs }
2704            | MicroOp::GtEq { dst, lhs, rhs } => {
2705                // Gt/GtEq map onto lt/le with swapped operands; Neq is ne.
2706                let (fam, a, b) = match *op {
2707                    MicroOp::Add { .. } => (0usize, lhs, rhs),
2708                    MicroOp::Sub { .. } => (1, lhs, rhs),
2709                    MicroOp::Mul { .. } => (2, lhs, rhs),
2710                    MicroOp::BitAnd { .. } => (3, lhs, rhs),
2711                    MicroOp::BitOr { .. } => (4, lhs, rhs),
2712                    MicroOp::BitXor { .. } => (5, lhs, rhs),
2713                    MicroOp::Shl { .. } => (6, lhs, rhs),
2714                    MicroOp::Shr { .. } => (7, lhs, rhs),
2715                    MicroOp::Lt { .. } => (8, lhs, rhs),
2716                    MicroOp::Gt { .. } => (8, rhs, lhs),
2717                    MicroOp::LtEq { .. } => (9, lhs, rhs),
2718                    MicroOp::GtEq { .. } => (9, rhs, lhs),
2719                    MicroOp::Eq { .. } => (10, lhs, rhs),
2720                    MicroOp::Neq { .. } => (11, lhs, rhs),
2721                    MicroOp::Ushr { .. } => (12, lhs, rhs),
2722                    MicroOp::Rotate {
2723                        width32: true,
2724                        left: true,
2725                        ..
2726                    } => (13, lhs, rhs),
2727                    MicroOp::Rotate {
2728                        width32: true,
2729                        left: false,
2730                        ..
2731                    } => (14, lhs, rhs),
2732                    MicroOp::Rotate {
2733                        width32: false,
2734                        left: true,
2735                        ..
2736                    } => (15, lhs, rhs),
2737                    MicroOp::Rotate {
2738                        width32: false,
2739                        left: false,
2740                        ..
2741                    } => (16, lhs, rhs),
2742                    _ => unreachable!(),
2743                };
2744                let (d, l, r) = (loc(dst), loc(a), loc(b));
2745                let mut holes: Vec<HoleValue> = Vec::new();
2746                if l == 0 {
2747                    holes.push(HoleValue::Const(0, a as i64));
2748                }
2749                if r == 0 {
2750                    holes.push(HoleValue::Const(1, b as i64));
2751                }
2752                if d == 0 {
2753                    holes.push(HoleValue::Const(2, dst as i64));
2754                }
2755                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2756                // add/sub/mul (fam 0/1/2) are the CHECKED families: their generated
2757                // stencil takes cont_1 to the shared deopt terminal on signed overflow,
2758                // so the exact tier recomputes and promotes to BigInt.
2759                if fam <= 2 {
2760                    holes.push(HoleValue::Cont(1, buf.label(deopt_piece)));
2761                }
2762                buf.push_stencil(V_BINOP[fam][d][l][r], &holes);
2763            }
2764            // FLOAT 3-address (add/sub/mul): same location encoding, float
2765            // variant table.
2766            MicroOp::AddF { dst, lhs, rhs }
2767            | MicroOp::SubF { dst, lhs, rhs }
2768            | MicroOp::MulF { dst, lhs, rhs } => {
2769                let fam = match *op {
2770                    MicroOp::AddF { .. } => 0usize,
2771                    MicroOp::SubF { .. } => 1,
2772                    MicroOp::MulF { .. } => 2,
2773                    _ => unreachable!(),
2774                };
2775                // Float operands are XMM-pinned → index by the FLOAT pin
2776                // location (floc), NOT the GP location (loc). Using loc would
2777                // resolve an XMM-pinned float to frame (location 0) and read a
2778                // STALE frame cell instead of the live f-pin.
2779                let (d, l, r) = (floc(dst), floc(lhs), floc(rhs));
2780                let mut holes: Vec<HoleValue> = Vec::new();
2781                if l == 0 {
2782                    holes.push(HoleValue::Const(0, lhs as i64));
2783                }
2784                if r == 0 {
2785                    holes.push(HoleValue::Const(1, rhs as i64));
2786                }
2787                if d == 0 {
2788                    holes.push(HoleValue::Const(2, dst as i64));
2789                }
2790                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2791                buf.push_stencil(V_FBINOP[fam][d][l][r], &holes);
2792            }
2793            // FLOAT sqrt threaded through XMM pins (no side-exit).
2794            MicroOp::SqrtF { dst, src } => {
2795                let (d, s) = (floc(dst), floc(src));
2796                let mut holes: Vec<HoleValue> = Vec::new();
2797                if s == 0 {
2798                    holes.push(HoleValue::Const(0, src as i64));
2799                }
2800                if d == 0 {
2801                    holes.push(HoleValue::Const(1, dst as i64));
2802                }
2803                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2804                buf.push_stencil(V_SQRTF[d][s], &holes);
2805            }
2806            // Int popcount threaded through the GP pins (`popcnt`, no side-exit). Reading its source at
2807            // the pin LOCATION (`loc`, not the frame) is what fixes a register-pinned induction variable:
2808            // the frame-form stencil would read a stale frame slot for a value that lives in `r0..r3`.
2809            MicroOp::Popcnt { dst, src }
2810            | MicroOp::Lzcnt { dst, src }
2811            | MicroOp::Tzcnt { dst, src }
2812            | MicroOp::Utf8Len { dst, src } => {
2813                let (d, s) = (loc(dst), loc(src));
2814                let table = match op {
2815                    MicroOp::Popcnt { .. } => &V_POPCNT,
2816                    MicroOp::Lzcnt { .. } => &V_LZCNT,
2817                    MicroOp::Tzcnt { .. } => &V_TZCNT,
2818                    _ => &V_UTF8LEN,
2819                };
2820                let mut holes: Vec<HoleValue> = Vec::new();
2821                if s == 0 {
2822                    holes.push(HoleValue::Const(0, src as i64));
2823                }
2824                if d == 0 {
2825                    holes.push(HoleValue::Const(1, dst as i64));
2826                }
2827                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2828                buf.push_stencil(table[d][s], &holes);
2829            }
2830            // `chr` guard threaded through the GP pins — like `popcnt` but DEOPTABLE: an invalid code
2831            // side-exits to the deopt terminal (cont 1) so the VM re-runs `chr` and traps. Reading the code
2832            // at the pin LOCATION (`loc`) makes a register-pinned hot code (`chr(k)`) correct, not stale.
2833            MicroOp::ChrGuard { dst, src } => {
2834                let (d, s) = (loc(dst), loc(src));
2835                let mut holes: Vec<HoleValue> = Vec::new();
2836                if s == 0 {
2837                    holes.push(HoleValue::Const(0, src as i64));
2838                }
2839                if d == 0 {
2840                    holes.push(HoleValue::Const(1, dst as i64));
2841                }
2842                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2843                holes.push(HoleValue::Cont(1, buf.label(deopt_piece)));
2844                buf.push_stencil(V_CHRGUARD[d][s], &holes);
2845            }
2846            // Float→Int rounding: the FLOAT src is read at its XMM pin (`floc`), the INT dst written to
2847            // its GP pin (`loc`). Reading the src via `floc` (not `loc`) is what makes a register-pinned
2848            // hot float — e.g. an `fk += 1.0` accumulator fed to `floor(fk)` — correct rather than stale.
2849            MicroOp::FloorToInt { dst, src }
2850            | MicroOp::CeilToInt { dst, src }
2851            | MicroOp::RoundToInt { dst, src } => {
2852                let (d, s) = (loc(dst), floc(src));
2853                let table = match op {
2854                    MicroOp::FloorToInt { .. } => &V_FLOORF,
2855                    MicroOp::CeilToInt { .. } => &V_CEILF,
2856                    _ => &V_ROUNDF,
2857                };
2858                let mut holes: Vec<HoleValue> = Vec::new();
2859                if s == 0 {
2860                    holes.push(HoleValue::Const(0, src as i64));
2861                }
2862                if d == 0 {
2863                    holes.push(HoleValue::Const(1, dst as i64));
2864                }
2865                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2866                buf.push_stencil(table[d][s], &holes);
2867            }
2868            // FLOAT divide threaded through XMM pins; a zero divisor side-exits
2869            // to the deopt terminal (cont 1), exactly like the mem-form form.
2870            MicroOp::DivF { dst, lhs, rhs } => {
2871                let (d, l, r) = (floc(dst), floc(lhs), floc(rhs));
2872                let mut holes: Vec<HoleValue> = Vec::new();
2873                if l == 0 {
2874                    holes.push(HoleValue::Const(0, lhs as i64));
2875                }
2876                if r == 0 {
2877                    holes.push(HoleValue::Const(1, rhs as i64));
2878                }
2879                if d == 0 {
2880                    holes.push(HoleValue::Const(2, dst as i64));
2881                }
2882                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2883                holes.push(HoleValue::Cont(1, buf.label(deopt_piece)));
2884                buf.push_stencil(V_DIVF[d][l][r], &holes);
2885            }
2886            // Int→Float threaded through XMM pins: int src at GP loc, f64 dst
2887            // at XMM pin.
2888            MicroOp::IntToFloat { dst, src } => {
2889                let (d, s) = (floc(dst), loc(src));
2890                let mut holes: Vec<HoleValue> = Vec::new();
2891                if s == 0 {
2892                    holes.push(HoleValue::Const(0, src as i64));
2893                }
2894                if d == 0 {
2895                    holes.push(HoleValue::Const(1, dst as i64));
2896                }
2897                holes.push(HoleValue::Cont(0, buf.label(next_op)));
2898                buf.push_stencil(V_I2F[d][s], &holes);
2899            }
2900            // FUSED float compare-and-branch threaded through XMM pins. Same
2901            // NaN-correct cmp→family mapping as the unpinned form (brlef for
2902            // <=/>=, never brltf-swapped — NaN makes `a<=b` ≠ `!(b<a)`).
2903            MicroOp::BranchF {
2904                cmp,
2905                lhs,
2906                rhs,
2907                target,
2908            } => {
2909                let t = buf.label(lbl(target));
2910                let n = buf.label(next_op);
2911                let (fam, a, b) = match cmp {
2912                    Cmp::Lt => (0usize, lhs, rhs),
2913                    Cmp::Gt => (0, rhs, lhs),
2914                    Cmp::LtEq => (1, lhs, rhs),
2915                    Cmp::GtEq => (1, rhs, lhs),
2916                    Cmp::Eq => (2, lhs, rhs),
2917                    Cmp::NotEq => (2, lhs, rhs),
2918                };
2919                let (c0, c1) = if cmp == Cmp::NotEq { (t, n) } else { (n, t) };
2920                let (l, r) = (floc(a), floc(b));
2921                let mut holes: Vec<HoleValue> = Vec::new();
2922                if l == 0 {
2923                    holes.push(HoleValue::Const(0, a as i64));
2924                }
2925                if r == 0 {
2926                    holes.push(HoleValue::Const(1, b as i64));
2927                }
2928                holes.push(HoleValue::Cont(0, c0));
2929                holes.push(HoleValue::Cont(1, c1));
2930                buf.push_stencil(V_BRANCHF[fam][l][r], &holes);
2931            }
2932            MicroOp::Branch {
2933                cmp,
2934                lhs,
2935                rhs,
2936                target,
2937            } => {
2938                // TRUE -> fall through (cont 0 of the variant is TAKEN when
2939                // the condition holds; mirror the unpinned mapping: jump
2940                // when FALSE).
2941                let t = buf.label(lbl(target));
2942                let n = buf.label(next_op);
2943                let (fam, a, b, c_true, c_false) = match cmp {
2944                    Cmp::Lt => (0usize, lhs, rhs, n, t),
2945                    Cmp::GtEq => (0, lhs, rhs, t, n),
2946                    Cmp::Gt => (0, rhs, lhs, n, t),
2947                    Cmp::LtEq => (0, rhs, lhs, t, n),
2948                    Cmp::Eq => (2, lhs, rhs, n, t),
2949                    Cmp::NotEq => (2, lhs, rhs, t, n),
2950                };
2951                let (l, r) = (loc(a), loc(b));
2952                let mut holes: Vec<HoleValue> = Vec::new();
2953                if l == 0 {
2954                    holes.push(HoleValue::Const(0, a as i64));
2955                }
2956                if r == 0 {
2957                    holes.push(HoleValue::Const(1, b as i64));
2958                }
2959                holes.push(HoleValue::Cont(0, c_true));
2960                holes.push(HoleValue::Cont(1, c_false));
2961                buf.push_stencil(V_BRANCH[fam][l][r], &holes);
2962            }
2963            MicroOp::Jump { target } => {
2964                buf.push_stencil(&ST_JUMP, &[HoleValue::Cont(0, buf.label(lbl(target)))]);
2965            }
2966            MicroOp::JumpIfFalse { cond, target } | MicroOp::JumpIfTrue { cond, target } => {
2967                let c = loc(cond);
2968                let mut brz_piece = here;
2969                if c != 0 {
2970                    spill(&mut buf, cond, here + 1);
2971                    brz_piece = here + 1;
2972                }
2973                let _ = brz_piece;
2974                let (c0, c1) = if matches!(op, MicroOp::JumpIfFalse { .. }) {
2975                    (buf.label(next_op), buf.label(lbl(target)))
2976                } else {
2977                    (buf.label(lbl(target)), buf.label(next_op))
2978                };
2979                buf.push_stencil(
2980                    &ST_BRZ,
2981                    &[
2982                        HoleValue::Const(0, cond as i64),
2983                        HoleValue::Cont(0, c0),
2984                        HoleValue::Cont(1, c1),
2985                    ],
2986                );
2987            }
2988            MicroOp::Return { src } => {
2989                // EPILOGUE: spill every pinned slot to its frame cell before
2990                // returning, so the VM's success write-back (which reads the
2991                // frame) observes loop-carried values held in registers. Both
2992                // budgets spill — the GP pins through V_MOV, the float pins
2993                // through V_FMOV (the `spill` closure dispatches on which) —
2994                // matching the `n_pin + 1` pieces reserved for this return.
2995                // The deopt terminal is separate and discards the frame, so it
2996                // needs no spill — only this success path does.
2997                let mut cursor = here;
2998                for &slot in pins.iter().chain(fpins.iter()) {
2999                    spill(&mut buf, slot, cursor + 1);
3000                    cursor += 1;
3001                }
3002                let sl = loc(src);
3003                if sl == 0 {
3004                    buf.push_stencil(&ST_RET2, &[HoleValue::Const(0, src as i64)]);
3005                } else {
3006                    buf.push_stencil(V_RET[sl - 1], &[]);
3007                }
3008            }
3009            ref other => {
3010                // Memory-form op: spill pinned reads, run, reload pinned
3011                // writes — emitted as its own piece run.
3012                let (reads, writes) = mem_form_touch(other);
3013                let mut cursor = here;
3014                for &slot in &reads {
3015                    spill(&mut buf, slot, cursor + 1);
3016                    cursor += 1;
3017                }
3018                let after_op = cursor + 1;
3019                let next_for_op = if writes.is_empty() { next_op } else { after_op };
3020                let next_label = buf.label(next_for_op);
3021                // REGISTER-FORM array access: a word array whose base pointer is
3022                // GP-pinned reads the pointer from its register (no per-access
3023                // frame load). The index/length/value stay in the frame exactly
3024                // as the mem-form path, so the spill/reload bookkeeping above is
3025                // unchanged (mem_form_touch excludes ptr/len). Falls back to the
3026                // frame-pointer mem-form for byte arrays / unpinned pointers.
3027                let rptr = |buf: &mut JitBuffer,
3028                            table: &[&'static crate::Stencil; 5],
3029                            n: usize,
3030                            idx: u16,
3031                            vslot: u16,
3032                            len_slot: u16,
3033                            checked: bool| {
3034                    let mut holes = vec![
3035                        HoleValue::Const(0, idx as i64),
3036                        HoleValue::Const(3, vslot as i64),
3037                        HoleValue::Cont(0, next_label),
3038                    ];
3039                    if checked {
3040                        holes.push(HoleValue::Const(2, len_slot as i64));
3041                        holes.push(HoleValue::Cont(1, buf.label(deopt_piece)));
3042                    }
3043                    buf.push_stencil(table[n], &holes);
3044                };
3045                let used_rptr = match *other {
3046                    MicroOp::ArrLoad {
3047                        dst,
3048                        idx,
3049                        ptr_slot,
3050                        len_slot,
3051                        byte: false,
3052                        narrow32: false,
3053                        checked,
3054                    } if loc(ptr_slot) != 0 => {
3055                        let n = loc(ptr_slot);
3056                        let t = if checked {
3057                            &V_ARRLD_RPTR_C
3058                        } else {
3059                            &V_ARRLD_RPTR
3060                        };
3061                        rptr(&mut buf, t, n, idx, dst, len_slot, checked);
3062                        true
3063                    }
3064                    MicroOp::ArrStore {
3065                        src,
3066                        idx,
3067                        ptr_slot,
3068                        len_slot,
3069                        byte: false,
3070                        narrow32: false,
3071                        checked,
3072                    } if loc(ptr_slot) != 0 => {
3073                        let n = loc(ptr_slot);
3074                        let t = if checked {
3075                            &V_ARRST_RPTR_C
3076                        } else {
3077                            &V_ARRST_RPTR
3078                        };
3079                        rptr(&mut buf, t, n, idx, src, len_slot, checked);
3080                        true
3081                    }
3082                    _ => false,
3083                };
3084                if !used_rptr {
3085                    emit_mem_form(&mut buf, other, next_label, deopt_piece, &status);
3086                }
3087                cursor += 1;
3088                for (k, &slot) in writes.iter().enumerate() {
3089                    let after = if k + 1 == writes.len() {
3090                        next_op
3091                    } else {
3092                        cursor + 1
3093                    };
3094                    reload(&mut buf, slot, after);
3095                    cursor += 1;
3096                }
3097            }
3098        }
3099    }
3100    if let Some(cell) = &status {
3101        let addr = cell.as_ref() as *const AtomicI64 as i64;
3102        buf.push_stencil(&ST_DEOPT, &[HoleValue::Const(0, addr)]);
3103    }
3104    let chain = buf
3105        .finish()
3106        .map_err(|e| JitCompileError::Assembly(e.to_string()))?;
3107    Ok(CompiledChain {
3108        chain,
3109        status,
3110        keepalive: Vec::new(),
3111    })
3112}
3113
3114/// The returned chain is run with [`CompiledChain::run_with_frame`]; the
3115/// frame's slots are the program's registers (inputs pre-loaded by the
3116/// caller, outputs visible after the run). Programs containing checked ops
3117/// (Div/Mod) get a status cell and a shared side-exit terminal; their runs
3118/// can report [`ChainOutcome::Deopt`].
3119pub fn compile_straightline(ops: &[MicroOp]) -> Result<CompiledChain, JitCompileError> {
3120    compile_straightline_with(ops, None)
3121}
3122
3123/// [`compile_straightline`] with a caller-supplied (per-program) status
3124/// cell, so every chain of one program — and the call stencils between them
3125/// — share a single side-exit channel. The cell's address is what
3126/// `MicroOp::Call::status_addr` must carry.
3127pub fn compile_straightline_with(
3128    ops: &[MicroOp],
3129    shared_status: Option<std::sync::Arc<AtomicI64>>,
3130) -> Result<CompiledChain, JitCompileError> {
3131    compile_straightline_coded(ops, shared_status, None, 0)
3132}
3133
3134/// Like [`compile_straightline_with`], with an optional per-op DEOPT CODE
3135/// table (parallel to `ops`). An op whose code is not the plain marker `1`
3136/// side-exits through its own terminal piece storing that encoded value —
3137/// the function tier encodes `(bytecode_pc << 2) | 3` so the VM can resume
3138/// precisely. `None` (and code `1`) keep the shared replay terminal.
3139pub fn compile_straightline_coded(
3140    ops: &[MicroOp],
3141    shared_status: Option<std::sync::Arc<AtomicI64>>,
3142    deopt_codes: Option<&[i64]>,
3143    depth_addr: i64,
3144) -> Result<CompiledChain, JitCompileError> {
3145    if ops.is_empty() {
3146        return Err(JitCompileError::Empty);
3147    }
3148    if !matches!(
3149        ops.last(),
3150        Some(MicroOp::Return { .. }) | Some(MicroOp::Jump { .. })
3151    ) {
3152        return Err(JitCompileError::FallsOffTheEnd);
3153    }
3154    for (i, op) in ops.iter().enumerate() {
3155        match *op {
3156            MicroOp::Jump { target }
3157            | MicroOp::JumpIfFalse { target, .. }
3158            | MicroOp::JumpIfTrue { target, .. }
3159            | MicroOp::Branch { target, .. }
3160            | MicroOp::BranchF { target, .. } => {
3161                if target >= ops.len() {
3162                    return Err(JitCompileError::BadJumpTarget {
3163                        op_index: i,
3164                        target,
3165                    });
3166                }
3167            }
3168            _ => {}
3169        }
3170    }
3171
3172    // 3-address lowering: exactly ONE piece per micro-op (piece index ==
3173    // op index), so jump targets need no remapping. Programs with checked
3174    // ops share ONE side-exit terminal placed after every op piece; its
3175    // patched constant is the status cell's address.
3176    let has_checked = ops.iter().any(|op| {
3177        matches!(
3178            op,
3179            // Integer add/sub/mul side-exit (`cont_1`) on signed overflow so the exact
3180            // tier promotes to BigInt — they need the status cell + deopt terminal.
3181            MicroOp::Add { .. }
3182                | MicroOp::Sub { .. }
3183                | MicroOp::Mul { .. }
3184                | MicroOp::Div { .. }
3185                | MicroOp::Mod { .. }
3186                | MicroOp::DivF { .. }
3187                | MicroOp::ArrLoad { .. }
3188                | MicroOp::ArrLoadAffine { checked: true, .. }
3189                | MicroOp::ArrLoad2F { .. }
3190                | MicroOp::ArrLoad2 { checked: true, .. }
3191                | MicroOp::ArrStore { .. }
3192                | MicroOp::ArrRMW { checked: true, .. }
3193                | MicroOp::ArrCondSwap { checked: true, .. }
3194                | MicroOp::ArrSwap { checked: true, .. }
3195                | MicroOp::Call { .. }
3196                | MicroOp::CallSelf { .. }
3197                | MicroOp::CallSelfCopy { .. }
3198                | MicroOp::MapGet { .. }
3199                | MicroOp::Host { .. }
3200                | MicroOp::MemMem { .. }
3201                // `chr` validity guard side-exits (`cont_1`) on an invalid code
3202                // so the VM re-runs `chr` and traps — needs the deopt terminal.
3203                | MicroOp::ChrGuard { .. }
3204        )
3205    });
3206    let status: Option<std::sync::Arc<AtomicI64>> = if has_checked {
3207        Some(shared_status.unwrap_or_else(|| std::sync::Arc::new(AtomicI64::new(0))))
3208    } else {
3209        None
3210    };
3211    let deopt_piece = ops.len();
3212    // Distinct non-plain codes get their own terminal pieces after the
3213    // shared one, in first-use order (deterministic).
3214    let mut code_pieces: Vec<i64> = Vec::new();
3215    if let Some(codes) = deopt_codes {
3216        debug_assert_eq!(codes.len(), ops.len());
3217        for (i, op) in ops.iter().enumerate() {
3218            let coded = matches!(
3219                op,
3220                // add/sub/mul are CHECKED now (overflow → exact promotion): inside a
3221                // region their side-exit must carry the op's PRECISE deopt code so the
3222                // VM resumes with the right rollback, exactly like the other checked
3223                // ops — so their codes need terminal pieces too.
3224                MicroOp::Add { .. }
3225                    | MicroOp::Sub { .. }
3226                    | MicroOp::Mul { .. }
3227                    | MicroOp::Div { .. }
3228                    | MicroOp::Mod { .. }
3229                    | MicroOp::DivF { .. }
3230                    | MicroOp::ArrLoad { .. }
3231                    | MicroOp::ArrLoadAffine { checked: true, .. }
3232                    | MicroOp::ArrLoad2F { .. }
3233                    | MicroOp::ArrLoad2 { checked: true, .. }
3234                    | MicroOp::ArrStore { .. }
3235                    | MicroOp::MapGet { .. }
3236                    | MicroOp::Host { .. }
3237            );
3238            if coded && codes[i] != 1 && !code_pieces.contains(&codes[i]) {
3239                code_pieces.push(codes[i]);
3240            }
3241        }
3242    }
3243    let piece_for = |code: i64| -> usize {
3244        if code == 1 {
3245            deopt_piece
3246        } else {
3247            deopt_piece + 1 + code_pieces.iter().position(|&c| c == code).unwrap()
3248        }
3249    };
3250    let code_at = |i: usize| -> i64 { deopt_codes.map(|c| c[i]).unwrap_or(1) };
3251
3252    let mut buf = JitBuffer::new();
3253    for (i, op) in ops.iter().enumerate() {
3254        let next = buf.label(i + 1);
3255        match *op {
3256            MicroOp::LoadConst { dst, value } => {
3257                buf.push_stencil(
3258                    &ST_CONSTST,
3259                    &[
3260                        HoleValue::Const(0, value),
3261                        HoleValue::Const(1, dst as i64),
3262                        HoleValue::Cont(0, next),
3263                    ],
3264                );
3265            }
3266            MicroOp::Move { dst, src } => {
3267                buf.push_stencil(
3268                    &ST_MOVSS,
3269                    &[
3270                        HoleValue::Const(0, src as i64),
3271                        HoleValue::Const(1, dst as i64),
3272                        HoleValue::Cont(0, next),
3273                    ],
3274                );
3275            }
3276            MicroOp::Add { dst, lhs, rhs }
3277            | MicroOp::Sub { dst, lhs, rhs }
3278            | MicroOp::Mul { dst, lhs, rhs }
3279            | MicroOp::Lt { dst, lhs, rhs }
3280            | MicroOp::LtEq { dst, lhs, rhs }
3281            | MicroOp::Eq { dst, lhs, rhs }
3282            | MicroOp::Neq { dst, lhs, rhs } => {
3283                let stencil = match op {
3284                    MicroOp::Add { .. } => &ST_ADD3,
3285                    MicroOp::Sub { .. } => &ST_SUB3,
3286                    MicroOp::Mul { .. } => &ST_MUL3,
3287                    MicroOp::Lt { .. } => &ST_LT3,
3288                    MicroOp::LtEq { .. } => &ST_LE3,
3289                    MicroOp::Eq { .. } => &ST_EQ3,
3290                    MicroOp::Neq { .. } => &ST_NE3,
3291                    _ => unreachable!(),
3292                };
3293                let mut holes = vec![
3294                    HoleValue::Const(0, lhs as i64),
3295                    HoleValue::Const(1, rhs as i64),
3296                    HoleValue::Const(2, dst as i64),
3297                    HoleValue::Cont(0, next),
3298                ];
3299                // add/sub/mul are CHECKED: their stencil takes cont_1 to this op's
3300                // deopt terminal on signed overflow so the exact tier promotes. The
3301                // comparisons (lt/le/eq/ne) never overflow → cont_0 only.
3302                if matches!(
3303                    op,
3304                    MicroOp::Add { .. } | MicroOp::Sub { .. } | MicroOp::Mul { .. }
3305                ) {
3306                    holes.push(HoleValue::Cont(1, buf.label(piece_for(code_at(i)))));
3307                }
3308                buf.push_stencil(stencil, &holes);
3309            }
3310            // a > b ⇔ b < a; a >= b ⇔ b <= a: swap operands, reuse lt3/le3
3311            // (IEEE-exact for the float twins too — NaN is false on both
3312            // sides of the swap).
3313            MicroOp::Gt { dst, lhs, rhs }
3314            | MicroOp::GtEq { dst, lhs, rhs }
3315            | MicroOp::GtF { dst, lhs, rhs }
3316            | MicroOp::GtEqF { dst, lhs, rhs } => {
3317                let stencil = match op {
3318                    MicroOp::Gt { .. } => &ST_LT3,
3319                    MicroOp::GtEq { .. } => &ST_LE3,
3320                    MicroOp::GtF { .. } => &ST_LTF3,
3321                    _ => &ST_LEF3,
3322                };
3323                buf.push_stencil(
3324                    stencil,
3325                    &[
3326                        HoleValue::Const(0, rhs as i64),
3327                        HoleValue::Const(1, lhs as i64),
3328                        HoleValue::Const(2, dst as i64),
3329                        HoleValue::Cont(0, next),
3330                    ],
3331                );
3332            }
3333            MicroOp::BitAnd { dst, lhs, rhs }
3334            | MicroOp::BitOr { dst, lhs, rhs }
3335            | MicroOp::BitXor { dst, lhs, rhs }
3336            | MicroOp::Shl { dst, lhs, rhs }
3337            | MicroOp::Shr { dst, lhs, rhs }
3338            | MicroOp::Ushr { dst, lhs, rhs }
3339            | MicroOp::AddF { dst, lhs, rhs }
3340            | MicroOp::SubF { dst, lhs, rhs }
3341            | MicroOp::MulF { dst, lhs, rhs }
3342            | MicroOp::LtF { dst, lhs, rhs }
3343            | MicroOp::LtEqF { dst, lhs, rhs }
3344            | MicroOp::EqF { dst, lhs, rhs }
3345            | MicroOp::NeqF { dst, lhs, rhs } => {
3346                let stencil = match op {
3347                    MicroOp::BitAnd { .. } => &ST_AND3,
3348                    MicroOp::BitOr { .. } => &ST_OR3,
3349                    MicroOp::BitXor { .. } => &ST_XOR3,
3350                    MicroOp::Shl { .. } => &ST_SHL3,
3351                    MicroOp::Shr { .. } => &ST_SHR3,
3352                    MicroOp::Ushr { .. } => &ST_USHR3,
3353                    MicroOp::AddF { .. } => &ST_ADDF3,
3354                    MicroOp::SubF { .. } => &ST_SUBF3,
3355                    MicroOp::MulF { .. } => &ST_MULF3,
3356                    MicroOp::LtF { .. } => &ST_LTF3,
3357                    MicroOp::LtEqF { .. } => &ST_LEF3,
3358                    MicroOp::EqF { .. } => &ST_EQF3,
3359                    _ => &ST_NEF3,
3360                };
3361                buf.push_stencil(
3362                    stencil,
3363                    &[
3364                        HoleValue::Const(0, lhs as i64),
3365                        HoleValue::Const(1, rhs as i64),
3366                        HoleValue::Const(2, dst as i64),
3367                        HoleValue::Cont(0, next),
3368                    ],
3369                );
3370            }
3371            MicroOp::Rotate {
3372                dst,
3373                lhs,
3374                rhs,
3375                width32,
3376                left,
3377            } => {
3378                let stencil = match (width32, left) {
3379                    (true, true) => &ST_ROL32_3,
3380                    (true, false) => &ST_ROR32_3,
3381                    (false, true) => &ST_ROL64_3,
3382                    (false, false) => &ST_ROR64_3,
3383                };
3384                buf.push_stencil(
3385                    stencil,
3386                    &[
3387                        HoleValue::Const(0, lhs as i64),
3388                        HoleValue::Const(1, rhs as i64),
3389                        HoleValue::Const(2, dst as i64),
3390                        HoleValue::Cont(0, next),
3391                    ],
3392                );
3393            }
3394            MicroOp::DivF { dst, lhs, rhs } => {
3395                buf.push_stencil(
3396                    &ST_DIVF3C,
3397                    &[
3398                        HoleValue::Const(0, lhs as i64),
3399                        HoleValue::Const(1, rhs as i64),
3400                        HoleValue::Const(2, dst as i64),
3401                        HoleValue::Cont(0, next),
3402                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3403                    ],
3404                );
3405            }
3406            MicroOp::Call {
3407                dst,
3408                args_start,
3409                table_addr,
3410                depth_addr,
3411                status_addr,
3412                limit_slot,
3413                depth_limit,
3414            } => {
3415                let code = code_at(i);
3416                if code != 1 {
3417                    // Precise variant: hole 6 carries the encoded deopt
3418                    // value; the depth limit is BAKED at the kernel's
3419                    // locked MAX_CALL_DEPTH (the adapter verified it).
3420                    debug_assert_eq!(depth_limit, BAKED_CALL_DEPTH);
3421                    buf.push_stencil(
3422                        &ST_CALL_PRECISE,
3423                        &[
3424                            HoleValue::Const(0, table_addr),
3425                            HoleValue::Const(1, args_start as i64),
3426                            HoleValue::Const(2, dst as i64),
3427                            HoleValue::Const(3, depth_addr),
3428                            HoleValue::Const(4, status_addr),
3429                            HoleValue::Const(5, limit_slot as i64),
3430                            HoleValue::Const(6, code),
3431                            HoleValue::Cont(0, next),
3432                        ],
3433                    );
3434                } else {
3435                    buf.push_stencil(
3436                        &ST_CALL,
3437                        &[
3438                            HoleValue::Const(0, table_addr),
3439                            HoleValue::Const(1, args_start as i64),
3440                            HoleValue::Const(2, dst as i64),
3441                            HoleValue::Const(3, depth_addr),
3442                            HoleValue::Const(4, status_addr),
3443                            HoleValue::Const(5, limit_slot as i64),
3444                            HoleValue::Const(6, depth_limit),
3445                            HoleValue::Cont(0, next),
3446                        ],
3447                    );
3448                }
3449            }
3450            MicroOp::CallSelf {
3451                dst,
3452                args_start,
3453                depth_addr,
3454                status_addr,
3455                limit_slot,
3456                frame_size,
3457            } => {
3458                buf.push_stencil(
3459                    &ST_CALL_SELF,
3460                    &[
3461                        HoleValue::Const(0, 0),
3462                        HoleValue::Const(1, args_start as i64),
3463                        HoleValue::Const(2, dst as i64),
3464                        HoleValue::Const(3, depth_addr),
3465                        HoleValue::Const(4, status_addr),
3466                        HoleValue::Const(5, limit_slot as i64),
3467                        HoleValue::Const(6, frame_size),
3468                        HoleValue::Cont(0, next),
3469                    ],
3470                );
3471                buf.mark_patch_hole(0);
3472            }
3473            MicroOp::CallSelfCopy {
3474                dst,
3475                args_start,
3476                src_start,
3477                arg_count,
3478                depth_addr,
3479                status_addr,
3480                limit_slot,
3481                frame_size,
3482            } => {
3483                buf.push_stencil(
3484                    &ST_CALL_SELF_COPY,
3485                    &[
3486                        HoleValue::Const(0, 0),
3487                        HoleValue::Const(1, args_start as i64),
3488                        HoleValue::Const(2, dst as i64),
3489                        HoleValue::Const(3, depth_addr),
3490                        HoleValue::Const(4, status_addr),
3491                        HoleValue::Const(5, limit_slot as i64),
3492                        HoleValue::Const(6, frame_size),
3493                        HoleValue::Const(7, src_start as i64),
3494                        HoleValue::Const(8, arg_count as i64),
3495                        HoleValue::Cont(0, next),
3496                    ],
3497                );
3498                buf.mark_patch_hole(0);
3499            }
3500            MicroOp::NewList {
3501                vec_slot,
3502                ptr_slot,
3503                len_slot,
3504                helper_addr,
3505            } => {
3506                buf.push_stencil(
3507                    &ST_ALLOCLIST,
3508                    &[
3509                        HoleValue::Const(0, vec_slot as i64),
3510                        HoleValue::Const(1, ptr_slot as i64),
3511                        HoleValue::Const(2, len_slot as i64),
3512                        HoleValue::Const(3, helper_addr),
3513                        HoleValue::Cont(0, next),
3514                    ],
3515                );
3516            }
3517            MicroOp::ListTriple {
3518                handle_slot,
3519                vec_slot,
3520                ptr_slot,
3521                len_slot,
3522                helper_addr,
3523            } => {
3524                buf.push_stencil(
3525                    &ST_LISTTRIPLE,
3526                    &[
3527                        HoleValue::Const(0, handle_slot as i64),
3528                        HoleValue::Const(1, vec_slot as i64),
3529                        HoleValue::Const(2, ptr_slot as i64),
3530                        HoleValue::Const(3, len_slot as i64),
3531                        HoleValue::Const(4, helper_addr),
3532                        HoleValue::Cont(0, next),
3533                    ],
3534                );
3535            }
3536            MicroOp::MapGet {
3537                dst,
3538                key,
3539                map_slot,
3540                helper_addr,
3541            } => {
3542                buf.push_stencil(
3543                    &ST_MAPHGET,
3544                    &[
3545                        HoleValue::Const(0, map_slot as i64),
3546                        HoleValue::Const(1, key as i64),
3547                        HoleValue::Const(2, dst as i64),
3548                        HoleValue::Const(3, helper_addr),
3549                        HoleValue::Cont(0, next),
3550                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3551                    ],
3552                );
3553            }
3554            MicroOp::Host {
3555                dst,
3556                src,
3557                count,
3558                imm,
3559                helper_addr,
3560            } => {
3561                buf.push_stencil(
3562                    &ST_HOST,
3563                    &[
3564                        HoleValue::Const(0, dst as i64),
3565                        HoleValue::Const(1, src as i64),
3566                        HoleValue::Const(2, count as i64),
3567                        HoleValue::Const(3, imm),
3568                        HoleValue::Const(4, helper_addr),
3569                        HoleValue::Cont(0, next),
3570                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3571                    ],
3572                );
3573            }
3574            MicroOp::MapSet {
3575                src,
3576                key,
3577                map_slot,
3578                helper_addr,
3579            } => {
3580                buf.push_stencil(
3581                    &ST_MAPHSET,
3582                    &[
3583                        HoleValue::Const(0, map_slot as i64),
3584                        HoleValue::Const(1, key as i64),
3585                        HoleValue::Const(2, src as i64),
3586                        HoleValue::Const(3, helper_addr),
3587                        HoleValue::Cont(0, next),
3588                    ],
3589                );
3590            }
3591            MicroOp::MemMem {
3592                h_ptr_slot,
3593                h_len_slot,
3594                n_ptr_slot,
3595                n_len_slot,
3596                needle_len_slot,
3597                i_slot,
3598                count_slot,
3599                helper_addr,
3600            } => {
3601                buf.push_stencil(
3602                    &ST_MEMMEM,
3603                    &[
3604                        HoleValue::Const(0, h_ptr_slot as i64),
3605                        HoleValue::Const(1, h_len_slot as i64),
3606                        HoleValue::Const(2, n_ptr_slot as i64),
3607                        HoleValue::Const(3, n_len_slot as i64),
3608                        HoleValue::Const(4, needle_len_slot as i64),
3609                        HoleValue::Const(5, i_slot as i64),
3610                        HoleValue::Const(6, count_slot as i64),
3611                        HoleValue::Const(7, helper_addr),
3612                        HoleValue::Cont(0, next),
3613                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3614                    ],
3615                );
3616            }
3617            MicroOp::MapHas {
3618                dst,
3619                key,
3620                map_slot,
3621                helper_addr,
3622            } => {
3623                buf.push_stencil(
3624                    &ST_MAPHHAS,
3625                    &[
3626                        HoleValue::Const(0, map_slot as i64),
3627                        HoleValue::Const(1, key as i64),
3628                        HoleValue::Const(2, dst as i64),
3629                        HoleValue::Const(3, helper_addr),
3630                        HoleValue::Cont(0, next),
3631                    ],
3632                );
3633            }
3634            MicroOp::ArrPush {
3635                src,
3636                vec_slot,
3637                ptr_slot,
3638                len_slot,
3639                helper_addr,
3640                byte: _,
3641                narrow32: _,
3642            } => {
3643                buf.push_stencil(
3644                    &ST_PUSH,
3645                    &[
3646                        HoleValue::Const(0, src as i64),
3647                        HoleValue::Const(1, vec_slot as i64),
3648                        HoleValue::Const(2, ptr_slot as i64),
3649                        HoleValue::Const(3, len_slot as i64),
3650                        HoleValue::Const(4, helper_addr),
3651                        HoleValue::Cont(0, next),
3652                    ],
3653                );
3654            }
3655            MicroOp::ListClear {
3656                vec_slot,
3657                ptr_slot,
3658                len_slot,
3659                helper_addr,
3660            } => {
3661                buf.push_stencil(
3662                    &ST_LIST_CLEAR,
3663                    &[
3664                        HoleValue::Const(0, vec_slot as i64),
3665                        HoleValue::Const(1, ptr_slot as i64),
3666                        HoleValue::Const(2, len_slot as i64),
3667                        HoleValue::Const(3, helper_addr),
3668                        HoleValue::Cont(0, next),
3669                    ],
3670                );
3671            }
3672            MicroOp::ArrLoad {
3673                dst,
3674                idx,
3675                ptr_slot,
3676                len_slot,
3677                byte,
3678                narrow32,
3679                checked,
3680            } => {
3681                if checked {
3682                    buf.push_stencil(
3683                        arrld_stencil(byte, narrow32, true),
3684                        &[
3685                            HoleValue::Const(0, idx as i64),
3686                            HoleValue::Const(1, ptr_slot as i64),
3687                            HoleValue::Const(2, len_slot as i64),
3688                            HoleValue::Const(3, dst as i64),
3689                            HoleValue::Cont(0, next),
3690                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3691                        ],
3692                    );
3693                } else {
3694                    // Bounds-check eliminated (Oracle-proven): no length hole,
3695                    // no out-of-bounds continuation.
3696                    buf.push_stencil(
3697                        arrld_stencil(byte, narrow32, false),
3698                        &[
3699                            HoleValue::Const(0, idx as i64),
3700                            HoleValue::Const(1, ptr_slot as i64),
3701                            HoleValue::Const(3, dst as i64),
3702                            HoleValue::Cont(0, next),
3703                        ],
3704                    );
3705                }
3706            }
3707            MicroOp::ArrLoadAffine {
3708                dst,
3709                a,
3710                op,
3711                b,
3712                const_offset,
3713                ptr_slot,
3714                len_slot,
3715                checked,
3716            } => {
3717                if checked {
3718                    buf.push_stencil(
3719                        affine_stencil(op, true),
3720                        &[
3721                            HoleValue::Const(0, a as i64),
3722                            HoleValue::Const(1, b as i64),
3723                            HoleValue::Const(2, const_offset),
3724                            HoleValue::Const(3, ptr_slot as i64),
3725                            HoleValue::Const(4, len_slot as i64),
3726                            HoleValue::Const(5, dst as i64),
3727                            HoleValue::Cont(0, next),
3728                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3729                        ],
3730                    );
3731                } else {
3732                    buf.push_stencil(
3733                        affine_stencil(op, false),
3734                        &[
3735                            HoleValue::Const(0, a as i64),
3736                            HoleValue::Const(1, b as i64),
3737                            HoleValue::Const(2, const_offset),
3738                            HoleValue::Const(3, ptr_slot as i64),
3739                            HoleValue::Const(5, dst as i64),
3740                            HoleValue::Cont(0, next),
3741                        ],
3742                    );
3743                }
3744            }
3745            MicroOp::ArrStore {
3746                src,
3747                idx,
3748                ptr_slot,
3749                len_slot,
3750                byte,
3751                narrow32,
3752                checked,
3753            } => {
3754                if checked {
3755                    buf.push_stencil(
3756                        arrst_stencil(byte, narrow32, true),
3757                        &[
3758                            HoleValue::Const(0, idx as i64),
3759                            HoleValue::Const(1, ptr_slot as i64),
3760                            HoleValue::Const(2, len_slot as i64),
3761                            HoleValue::Const(3, src as i64),
3762                            HoleValue::Cont(0, next),
3763                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3764                        ],
3765                    );
3766                } else {
3767                    buf.push_stencil(
3768                        arrst_stencil(byte, narrow32, false),
3769                        &[
3770                            HoleValue::Const(0, idx as i64),
3771                            HoleValue::Const(1, ptr_slot as i64),
3772                            HoleValue::Const(3, src as i64),
3773                            HoleValue::Cont(0, next),
3774                        ],
3775                    );
3776                }
3777            }
3778            MicroOp::ArrRMW {
3779                idx,
3780                operand,
3781                ptr_slot,
3782                len_slot,
3783                op,
3784                checked,
3785            } => {
3786                if checked {
3787                    buf.push_stencil(
3788                        rmw_stencil(op, true),
3789                        &[
3790                            HoleValue::Const(0, idx as i64),
3791                            HoleValue::Const(1, ptr_slot as i64),
3792                            HoleValue::Const(2, len_slot as i64),
3793                            HoleValue::Const(3, operand as i64),
3794                            HoleValue::Cont(0, next),
3795                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3796                        ],
3797                    );
3798                } else {
3799                    buf.push_stencil(
3800                        rmw_stencil(op, false),
3801                        &[
3802                            HoleValue::Const(0, idx as i64),
3803                            HoleValue::Const(1, ptr_slot as i64),
3804                            HoleValue::Const(3, operand as i64),
3805                            HoleValue::Cont(0, next),
3806                        ],
3807                    );
3808                }
3809            }
3810            MicroOp::ArrCondSwap {
3811                idx1,
3812                idx2,
3813                ptr_slot,
3814                len_slot,
3815                cmp,
3816                checked,
3817            } => {
3818                if checked {
3819                    buf.push_stencil(
3820                        condswap_stencil(cmp, true),
3821                        &[
3822                            HoleValue::Const(0, idx1 as i64),
3823                            HoleValue::Const(1, idx2 as i64),
3824                            HoleValue::Const(2, ptr_slot as i64),
3825                            HoleValue::Const(3, len_slot as i64),
3826                            HoleValue::Cont(0, next),
3827                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3828                        ],
3829                    );
3830                } else {
3831                    buf.push_stencil(
3832                        condswap_stencil(cmp, false),
3833                        &[
3834                            HoleValue::Const(0, idx1 as i64),
3835                            HoleValue::Const(1, idx2 as i64),
3836                            HoleValue::Const(2, ptr_slot as i64),
3837                            HoleValue::Cont(0, next),
3838                        ],
3839                    );
3840                }
3841            }
3842            MicroOp::ArrSwap {
3843                idx1,
3844                idx2,
3845                ptr_slot,
3846                len_slot,
3847                checked,
3848            } => {
3849                if checked {
3850                    buf.push_stencil(
3851                        &ST_ARRSWAP,
3852                        &[
3853                            HoleValue::Const(0, idx1 as i64),
3854                            HoleValue::Const(1, idx2 as i64),
3855                            HoleValue::Const(2, ptr_slot as i64),
3856                            HoleValue::Const(3, len_slot as i64),
3857                            HoleValue::Cont(0, next),
3858                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3859                        ],
3860                    );
3861                } else {
3862                    buf.push_stencil(
3863                        &ST_ARRSWAP_U,
3864                        &[
3865                            HoleValue::Const(0, idx1 as i64),
3866                            HoleValue::Const(1, idx2 as i64),
3867                            HoleValue::Const(2, ptr_slot as i64),
3868                            HoleValue::Cont(0, next),
3869                        ],
3870                    );
3871                }
3872            }
3873            MicroOp::FmaF { dst, a, b, c } => {
3874                buf.push_stencil(
3875                    &ST_FMAF,
3876                    &[
3877                        HoleValue::Const(0, a as i64),
3878                        HoleValue::Const(1, b as i64),
3879                        HoleValue::Const(2, c as i64),
3880                        HoleValue::Const(3, dst as i64),
3881                        HoleValue::Cont(0, next),
3882                    ],
3883                );
3884            }
3885            MicroOp::ArrLoad2F {
3886                dst,
3887                i: ix,
3888                j: jx,
3889                ptr_slot,
3890                len_slot,
3891                op,
3892            } => {
3893                let stencil = match op {
3894                    FOp::Add => &ST_ARRLD2_ADDF,
3895                    FOp::Sub => &ST_ARRLD2_SUBF,
3896                    FOp::Mul => &ST_ARRLD2_MULF,
3897                };
3898                buf.push_stencil(
3899                    stencil,
3900                    &[
3901                        HoleValue::Const(0, ix as i64),
3902                        HoleValue::Const(1, jx as i64),
3903                        HoleValue::Const(2, ptr_slot as i64),
3904                        HoleValue::Const(3, len_slot as i64),
3905                        HoleValue::Const(4, dst as i64),
3906                        HoleValue::Cont(0, next),
3907                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3908                    ],
3909                );
3910            }
3911            MicroOp::ArrLoad2 {
3912                dst,
3913                i: ix,
3914                j: jx,
3915                ptr_a,
3916                len_a,
3917                ptr_b,
3918                len_b,
3919                op,
3920                checked,
3921            } => {
3922                if checked {
3923                    buf.push_stencil(
3924                        ld2_int_stencil(op, true),
3925                        &[
3926                            HoleValue::Const(0, ix as i64),
3927                            HoleValue::Const(1, jx as i64),
3928                            HoleValue::Const(2, ptr_a as i64),
3929                            HoleValue::Const(3, len_a as i64),
3930                            HoleValue::Const(4, ptr_b as i64),
3931                            HoleValue::Const(5, len_b as i64),
3932                            HoleValue::Const(6, dst as i64),
3933                            HoleValue::Cont(0, next),
3934                            HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
3935                        ],
3936                    );
3937                } else {
3938                    buf.push_stencil(
3939                        ld2_int_stencil(op, false),
3940                        &[
3941                            HoleValue::Const(0, ix as i64),
3942                            HoleValue::Const(1, jx as i64),
3943                            HoleValue::Const(2, ptr_a as i64),
3944                            HoleValue::Const(3, ptr_b as i64),
3945                            HoleValue::Const(4, dst as i64),
3946                            HoleValue::Cont(0, next),
3947                        ],
3948                    );
3949                }
3950            }
3951            MicroOp::NotInt { dst, src }
3952            | MicroOp::NotBool { dst, src }
3953            | MicroOp::Popcnt { dst, src }
3954            | MicroOp::Lzcnt { dst, src }
3955            | MicroOp::Tzcnt { dst, src }
3956            | MicroOp::Utf8Len { dst, src }
3957            | MicroOp::FloorToInt { dst, src }
3958            | MicroOp::CeilToInt { dst, src }
3959            | MicroOp::RoundToInt { dst, src }
3960            | MicroOp::IntToFloat { dst, src }
3961            | MicroOp::SqrtF { dst, src } => {
3962                let stencil = match op {
3963                    MicroOp::NotInt { .. } => &ST_NOTI2,
3964                    MicroOp::NotBool { .. } => &ST_NOTB2,
3965                    MicroOp::Popcnt { .. } => &ST_POPCNT2,
3966                    MicroOp::Lzcnt { .. } => &ST_LZCNT2,
3967                    MicroOp::Tzcnt { .. } => &ST_TZCNT2,
3968                    MicroOp::Utf8Len { .. } => &ST_UTF8LEN2,
3969                    MicroOp::FloorToInt { .. } => &ST_FLOORF2,
3970                    MicroOp::CeilToInt { .. } => &ST_CEILF2,
3971                    MicroOp::RoundToInt { .. } => &ST_ROUNDF2,
3972                    MicroOp::SqrtF { .. } => &ST_SQRTF2,
3973                    _ => &ST_I2F2,
3974                };
3975                buf.push_stencil(
3976                    stencil,
3977                    &[
3978                        HoleValue::Const(0, src as i64),
3979                        HoleValue::Const(1, dst as i64),
3980                        HoleValue::Cont(0, next),
3981                    ],
3982                );
3983            }
3984            MicroOp::BranchF {
3985                cmp,
3986                lhs,
3987                rhs,
3988                target,
3989            } => {
3990                // Jump to target when cmp is FALSE — under IEEE, the false
3991                // path also catches every NaN-unordered pair, so the mapping
3992                // may ONLY swap operands (a>b ⇔ b<a; a>=b ⇔ b<=a), never
3993                // continuations on the truth side.
3994                let t = buf.label(target);
3995                let (stencil, a, b) = match cmp {
3996                    Cmp::Lt => (&ST_BRLTF, lhs, rhs),
3997                    Cmp::Gt => (&ST_BRLTF, rhs, lhs),
3998                    Cmp::LtEq => (&ST_BRLEF, lhs, rhs),
3999                    Cmp::GtEq => (&ST_BRLEF, rhs, lhs),
4000                    Cmp::Eq => (&ST_BREQF, lhs, rhs),
4001                    Cmp::NotEq => (&ST_BREQF, lhs, rhs),
4002                };
4003                let (c0, c1) = if cmp == Cmp::NotEq {
4004                    // NotEq: jump when eps-equal (the TRUE path of breqf).
4005                    (t, next)
4006                } else {
4007                    (next, t)
4008                };
4009                buf.push_stencil(
4010                    stencil,
4011                    &[
4012                        HoleValue::Const(0, a as i64),
4013                        HoleValue::Const(1, b as i64),
4014                        HoleValue::Cont(0, c0),
4015                        HoleValue::Cont(1, c1),
4016                    ],
4017                );
4018            }
4019            MicroOp::Div { dst, lhs, rhs } | MicroOp::Mod { dst, lhs, rhs } => {
4020                let stencil = match op {
4021                    MicroOp::Div { .. } => &ST_DIV3C,
4022                    _ => &ST_MOD3C,
4023                };
4024                buf.push_stencil(
4025                    stencil,
4026                    &[
4027                        HoleValue::Const(0, lhs as i64),
4028                        HoleValue::Const(1, rhs as i64),
4029                        HoleValue::Const(2, dst as i64),
4030                        HoleValue::Cont(0, next),
4031                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
4032                    ],
4033                );
4034            }
4035            MicroOp::ChrGuard { dst, src } => {
4036                buf.push_stencil(
4037                    &ST_CHRGUARD,
4038                    &[
4039                        HoleValue::Const(0, src as i64),
4040                        HoleValue::Const(1, dst as i64),
4041                        HoleValue::Cont(0, next),
4042                        HoleValue::Cont(1, buf.label(piece_for(code_at(i)))),
4043                    ],
4044                );
4045            }
4046            MicroOp::DivPow2 { dst, lhs, k } => {
4047                buf.push_stencil(
4048                    &ST_DIVPOW2,
4049                    &[
4050                        HoleValue::Const(0, lhs as i64),
4051                        HoleValue::Const(1, k as i64),
4052                        HoleValue::Const(2, (1i64 << k) - 1),
4053                        HoleValue::Const(3, dst as i64),
4054                        HoleValue::Cont(0, next),
4055                    ],
4056                );
4057            }
4058            MicroOp::Jump { target } => {
4059                buf.push_stencil(&ST_JUMP, &[HoleValue::Cont(0, buf.label(target))]);
4060            }
4061            MicroOp::JumpIfFalse { cond, target } => {
4062                // brz: nonzero → cont 0 (fall through), zero → cont 1 (target).
4063                buf.push_stencil(
4064                    &ST_BRZ,
4065                    &[
4066                        HoleValue::Const(0, cond as i64),
4067                        HoleValue::Cont(0, next),
4068                        HoleValue::Cont(1, buf.label(target)),
4069                    ],
4070                );
4071            }
4072            MicroOp::JumpIfTrue { cond, target } => {
4073                // Same stencil, swapped continuations: nonzero → target.
4074                buf.push_stencil(
4075                    &ST_BRZ,
4076                    &[
4077                        HoleValue::Const(0, cond as i64),
4078                        HoleValue::Cont(0, buf.label(target)),
4079                        HoleValue::Cont(1, next),
4080                    ],
4081                );
4082            }
4083            MicroOp::Branch {
4084                cmp,
4085                lhs,
4086                rhs,
4087                target,
4088            } => {
4089                // Jump to target when cmp is FALSE; fall through when TRUE.
4090                // brlt/breq put the TRUE outcome on cont 0; operand and
4091                // continuation swaps express all six comparison kinds.
4092                let t = buf.label(target);
4093                let (stencil, a, b, c0, c1) = match cmp {
4094                    Cmp::Lt => (&ST_BRLT, lhs, rhs, next, t),
4095                    Cmp::GtEq => (&ST_BRLT, lhs, rhs, t, next),
4096                    Cmp::Gt => (&ST_BRLT, rhs, lhs, next, t),
4097                    Cmp::LtEq => (&ST_BRLT, rhs, lhs, t, next),
4098                    Cmp::Eq => (&ST_BREQ, lhs, rhs, next, t),
4099                    Cmp::NotEq => (&ST_BREQ, lhs, rhs, t, next),
4100                };
4101                buf.push_stencil(
4102                    stencil,
4103                    &[
4104                        HoleValue::Const(0, a as i64),
4105                        HoleValue::Const(1, b as i64),
4106                        HoleValue::Cont(0, c0),
4107                        HoleValue::Cont(1, c1),
4108                    ],
4109                );
4110            }
4111            MicroOp::Return { src } => {
4112                buf.push_stencil(&ST_RET2, &[HoleValue::Const(0, src as i64)]);
4113            }
4114            // The mutable-Text append has NO per-piece stencil — it is emitted
4115            // ONLY for the contiguous regalloc backend (where it lowers to a
4116            // SysV helper call). Decline so the caller falls back to bytecode,
4117            // which is always correct.
4118            MicroOp::StrAppend { .. } => {
4119                return Err(JitCompileError::Unsupported("StrAppend"));
4120            }
4121            // The magic reciprocal: a single `mul`-high + shift piece (the
4122            // contiguous regalloc backend also lowers it, but the stencil tier
4123            // owns the mixed regions regalloc declines — e.g. a `% c` next to a
4124            // map insert). Holes: 0 = lhs, 1 = magic, 2 = more, 3 = mul_back,
4125            // 4 = dst. No deopt continuation (a literal `c > 0` never faults).
4126            MicroOp::MagicDivU {
4127                dst,
4128                lhs,
4129                magic,
4130                more,
4131                mul_back,
4132            } => {
4133                buf.push_stencil(
4134                    &ST_MAGICDIV,
4135                    &[
4136                        HoleValue::Const(0, lhs as i64),
4137                        HoleValue::Const(1, magic as i64),
4138                        HoleValue::Const(2, more as i64),
4139                        HoleValue::Const(3, mul_back),
4140                        HoleValue::Const(4, dst as i64),
4141                        HoleValue::Cont(0, next),
4142                    ],
4143                );
4144            }
4145        }
4146    }
4147
4148    if let Some(cell) = &status {
4149        let addr = cell.as_ref() as *const AtomicI64 as i64;
4150        buf.push_stencil(&ST_DEOPT, &[HoleValue::Const(0, addr)]);
4151        for &code in &code_pieces {
4152            buf.push_stencil(
4153                &ST_DEOPT_AT,
4154                &[
4155                    HoleValue::Const(0, addr),
4156                    HoleValue::Const(1, code),
4157                    HoleValue::Const(2, depth_addr),
4158                ],
4159            );
4160        }
4161    }
4162
4163    let chain = buf
4164        .finish()
4165        .map_err(|e| JitCompileError::Assembly(e.to_string()))?;
4166    Ok(CompiledChain {
4167        chain,
4168        status,
4169        keepalive: Vec::new(),
4170    })
4171}
4172
4173/// Evaluate the unsigned magic reciprocal for [`MicroOp::MagicDivU`]:
4174/// `x / c` when `mul_back == 0`, else `x % c` (`mul_back == c`). The dividend is
4175/// reinterpreted as `u64`, sound because the op is emitted ONLY for a proven
4176/// non-negative `x` (the i64 bit pattern equals the value, and unsigned and
4177/// signed-truncating `/`/`%` agree there). The remainder is `x - q*c` in
4178/// wrapping i64 (its low 64 bits equal the u64 difference). The `more` encoding
4179/// is the `logicaffeine_data::LogosDivU64` one: low 6 bits = shift, `0x40`
4180/// = the 65-bit add-marker path, `0x80` = the pure-shift power-of-two path.
4181#[inline]
4182pub fn magic_eval(x: i64, magic: u64, more: u8, mul_back: i64) -> i64 {
4183    const SHIFT_MASK: u8 = 0x3F;
4184    const ADD_MARKER: u8 = 0x40;
4185    const SHIFT_PATH: u8 = 0x80;
4186    let n = x as u64;
4187    let q = if more & SHIFT_PATH != 0 {
4188        n >> (more & SHIFT_MASK)
4189    } else {
4190        let hi = (((magic as u128) * (n as u128)) >> 64) as u64;
4191        if more & ADD_MARKER != 0 {
4192            let t = (n.wrapping_sub(hi) >> 1).wrapping_add(hi);
4193            t >> (more & SHIFT_MASK)
4194        } else {
4195            hi >> (more & SHIFT_MASK)
4196        }
4197    };
4198    if mul_back == 0 {
4199        q as i64
4200    } else {
4201        x.wrapping_sub((q as i64).wrapping_mul(mul_back))
4202    }
4203}
4204
4205/// The reference evaluator — the independent model every differential runs
4206/// against. Deliberately the dumbest possible implementation: a pc loop.
4207/// `fuel` bounds the step count (None when caught in a loop that long).
4208/// A zero divisor also yields None — the reference's model of the chain's
4209/// side exit (differentials feed nonzero divisors when comparing values, and
4210/// assert Deopt agreement when not).
4211pub fn reference_eval(ops: &[MicroOp], frame: &mut [i64], mut fuel: u64) -> Option<i64> {
4212    let mut pc = 0usize;
4213    while pc < ops.len() {
4214        if fuel == 0 {
4215            return None;
4216        }
4217        fuel -= 1;
4218        match ops[pc] {
4219            MicroOp::LoadConst { dst, value } => frame[dst as usize] = value,
4220            MicroOp::Move { dst, src } => frame[dst as usize] = frame[src as usize],
4221            // EXACT integer arithmetic: signed overflow returns None — the JIT's
4222            // side-exit (deopt) is the matching signal, so the differential stays
4223            // consistent (overflow ⟺ reference None ⟺ JIT deopt).
4224            MicroOp::Add { dst, lhs, rhs } => {
4225                frame[dst as usize] = frame[lhs as usize].checked_add(frame[rhs as usize])?
4226            }
4227            MicroOp::Sub { dst, lhs, rhs } => {
4228                frame[dst as usize] = frame[lhs as usize].checked_sub(frame[rhs as usize])?
4229            }
4230            MicroOp::Mul { dst, lhs, rhs } => {
4231                frame[dst as usize] = frame[lhs as usize].checked_mul(frame[rhs as usize])?
4232            }
4233            MicroOp::Div { dst, lhs, rhs } => {
4234                let b = frame[rhs as usize];
4235                // Zero divisor AND the `i64::MIN / -1` overflow both deopt —
4236                // the exact tier recomputes (and promotes to BigInt).
4237                if b == 0 || (b == -1 && frame[lhs as usize] == i64::MIN) {
4238                    return None;
4239                }
4240                frame[dst as usize] = frame[lhs as usize].wrapping_div(b)
4241            }
4242            MicroOp::DivPow2 { dst, lhs, k } => {
4243                let x = frame[lhs as usize];
4244                let mask = (1i64 << k) - 1;
4245                frame[dst as usize] = x.wrapping_add((x >> 63) & mask) >> k;
4246            }
4247            MicroOp::MagicDivU {
4248                dst,
4249                lhs,
4250                magic,
4251                more,
4252                mul_back,
4253            } => {
4254                frame[dst as usize] = magic_eval(frame[lhs as usize], magic, more, mul_back);
4255            }
4256            MicroOp::Mod { dst, lhs, rhs } => {
4257                let b = frame[rhs as usize];
4258                if b == 0 {
4259                    return None;
4260                }
4261                frame[dst as usize] = frame[lhs as usize].wrapping_rem(b)
4262            }
4263            MicroOp::Lt { dst, lhs, rhs } => {
4264                frame[dst as usize] = (frame[lhs as usize] < frame[rhs as usize]) as i64
4265            }
4266            MicroOp::Gt { dst, lhs, rhs } => {
4267                frame[dst as usize] = (frame[lhs as usize] > frame[rhs as usize]) as i64
4268            }
4269            MicroOp::LtEq { dst, lhs, rhs } => {
4270                frame[dst as usize] = (frame[lhs as usize] <= frame[rhs as usize]) as i64
4271            }
4272            MicroOp::GtEq { dst, lhs, rhs } => {
4273                frame[dst as usize] = (frame[lhs as usize] >= frame[rhs as usize]) as i64
4274            }
4275            MicroOp::Eq { dst, lhs, rhs } => {
4276                frame[dst as usize] = (frame[lhs as usize] == frame[rhs as usize]) as i64
4277            }
4278            MicroOp::Neq { dst, lhs, rhs } => {
4279                frame[dst as usize] = (frame[lhs as usize] != frame[rhs as usize]) as i64
4280            }
4281            MicroOp::BitAnd { dst, lhs, rhs } => {
4282                frame[dst as usize] = frame[lhs as usize] & frame[rhs as usize]
4283            }
4284            MicroOp::BitOr { dst, lhs, rhs } => {
4285                frame[dst as usize] = frame[lhs as usize] | frame[rhs as usize]
4286            }
4287            MicroOp::BitXor { dst, lhs, rhs } => {
4288                frame[dst as usize] = frame[lhs as usize] ^ frame[rhs as usize]
4289            }
4290            MicroOp::Shl { dst, lhs, rhs } => {
4291                frame[dst as usize] = frame[lhs as usize].wrapping_shl(frame[rhs as usize] as u32)
4292            }
4293            MicroOp::Shr { dst, lhs, rhs } => {
4294                frame[dst as usize] = frame[lhs as usize].wrapping_shr(frame[rhs as usize] as u32)
4295            }
4296            MicroOp::Ushr { dst, lhs, rhs } => {
4297                frame[dst as usize] =
4298                    ((frame[lhs as usize] as u64).wrapping_shr(frame[rhs as usize] as u32)) as i64
4299            }
4300            MicroOp::Rotate {
4301                dst,
4302                lhs,
4303                rhs,
4304                width32,
4305                left,
4306            } => {
4307                let count = frame[rhs as usize] as u32;
4308                frame[dst as usize] = if width32 {
4309                    let word = frame[lhs as usize] as u32;
4310                    (if left {
4311                        word.rotate_left(count)
4312                    } else {
4313                        word.rotate_right(count)
4314                    }) as i64
4315                } else {
4316                    let word = frame[lhs as usize] as u64;
4317                    (if left {
4318                        word.rotate_left(count)
4319                    } else {
4320                        word.rotate_right(count)
4321                    }) as i64
4322                };
4323            }
4324            MicroOp::NotInt { dst, src } => frame[dst as usize] = !frame[src as usize],
4325            MicroOp::Popcnt { dst, src } => {
4326                frame[dst as usize] = (frame[src as usize] as u64).count_ones() as i64
4327            }
4328            MicroOp::Lzcnt { dst, src } => {
4329                frame[dst as usize] = (frame[src as usize] as u64).leading_zeros() as i64
4330            }
4331            MicroOp::Tzcnt { dst, src } => {
4332                frame[dst as usize] = (frame[src as usize] as u64).trailing_zeros() as i64
4333            }
4334            MicroOp::Utf8Len { dst, src } => {
4335                let u = frame[src as usize] as u32;
4336                frame[dst as usize] =
4337                    1 + (u >= 0x80) as i64 + (u >= 0x800) as i64 + (u >= 0x1_0000) as i64
4338            }
4339            MicroOp::FloorToInt { dst, src } => {
4340                frame[dst as usize] = f64::from_bits(frame[src as usize] as u64).floor() as i64
4341            }
4342            MicroOp::CeilToInt { dst, src } => {
4343                frame[dst as usize] = f64::from_bits(frame[src as usize] as u64).ceil() as i64
4344            }
4345            MicroOp::RoundToInt { dst, src } => {
4346                frame[dst as usize] = f64::from_bits(frame[src as usize] as u64).round() as i64
4347            }
4348            // The valid-path behavior — carry the code (the deopt on an invalid code + the Text re-box are
4349            // runtime/boundary concerns not modeled by this pure i64 reference evaluator).
4350            MicroOp::ChrGuard { dst, src } => frame[dst as usize] = frame[src as usize],
4351            MicroOp::NotBool { dst, src } => frame[dst as usize] = frame[src as usize] ^ 1,
4352            MicroOp::AddF { dst, lhs, rhs } => {
4353                let a = f64::from_bits(frame[lhs as usize] as u64);
4354                let b = f64::from_bits(frame[rhs as usize] as u64);
4355                frame[dst as usize] = (a + b).to_bits() as i64
4356            }
4357            MicroOp::SubF { dst, lhs, rhs } => {
4358                let a = f64::from_bits(frame[lhs as usize] as u64);
4359                let b = f64::from_bits(frame[rhs as usize] as u64);
4360                frame[dst as usize] = (a - b).to_bits() as i64
4361            }
4362            MicroOp::MulF { dst, lhs, rhs } => {
4363                let a = f64::from_bits(frame[lhs as usize] as u64);
4364                let b = f64::from_bits(frame[rhs as usize] as u64);
4365                frame[dst as usize] = (a * b).to_bits() as i64
4366            }
4367            MicroOp::DivF { dst, lhs, rhs } => {
4368                let b = f64::from_bits(frame[rhs as usize] as u64);
4369                if b == 0.0 {
4370                    return None;
4371                }
4372                let a = f64::from_bits(frame[lhs as usize] as u64);
4373                frame[dst as usize] = (a / b).to_bits() as i64
4374            }
4375            MicroOp::LtF { dst, lhs, rhs } => {
4376                let a = f64::from_bits(frame[lhs as usize] as u64);
4377                let b = f64::from_bits(frame[rhs as usize] as u64);
4378                frame[dst as usize] = (a < b) as i64
4379            }
4380            MicroOp::GtF { dst, lhs, rhs } => {
4381                let a = f64::from_bits(frame[lhs as usize] as u64);
4382                let b = f64::from_bits(frame[rhs as usize] as u64);
4383                frame[dst as usize] = (a > b) as i64
4384            }
4385            MicroOp::LtEqF { dst, lhs, rhs } => {
4386                let a = f64::from_bits(frame[lhs as usize] as u64);
4387                let b = f64::from_bits(frame[rhs as usize] as u64);
4388                frame[dst as usize] = (a <= b) as i64
4389            }
4390            MicroOp::GtEqF { dst, lhs, rhs } => {
4391                let a = f64::from_bits(frame[lhs as usize] as u64);
4392                let b = f64::from_bits(frame[rhs as usize] as u64);
4393                frame[dst as usize] = (a >= b) as i64
4394            }
4395            // IEEE float equality (`NaN != NaN`) — identical to the
4396            // tree-walker/VM `values_equal` and the compiled backend.
4397            MicroOp::EqF { dst, lhs, rhs } => {
4398                let a = f64::from_bits(frame[lhs as usize] as u64);
4399                let b = f64::from_bits(frame[rhs as usize] as u64);
4400                frame[dst as usize] = (a == b) as i64
4401            }
4402            MicroOp::NeqF { dst, lhs, rhs } => {
4403                let a = f64::from_bits(frame[lhs as usize] as u64);
4404                let b = f64::from_bits(frame[rhs as usize] as u64);
4405                frame[dst as usize] = (a != b) as i64
4406            }
4407            MicroOp::BranchF {
4408                cmp,
4409                lhs,
4410                rhs,
4411                target,
4412            } => {
4413                let a = f64::from_bits(frame[lhs as usize] as u64);
4414                let b = f64::from_bits(frame[rhs as usize] as u64);
4415                let truth = match cmp {
4416                    Cmp::Lt => a < b,
4417                    Cmp::Gt => a > b,
4418                    Cmp::LtEq => a <= b,
4419                    Cmp::GtEq => a >= b,
4420                    Cmp::Eq => a == b,
4421                    Cmp::NotEq => a != b,
4422                };
4423                if !truth {
4424                    pc = target;
4425                    continue;
4426                }
4427            }
4428            MicroOp::IntToFloat { dst, src } => {
4429                frame[dst as usize] = (frame[src as usize] as f64).to_bits() as i64
4430            }
4431            MicroOp::SqrtF { dst, src } => {
4432                frame[dst as usize] =
4433                    f64::from_bits(frame[src as usize] as u64).sqrt().to_bits() as i64
4434            }
4435            // Calls, pushes and map traffic touch live runtime state the
4436            // reference cannot model — VM-level differentials own their
4437            // coverage.
4438            MicroOp::Call { .. }
4439            | MicroOp::CallSelf { .. }
4440            | MicroOp::CallSelfCopy { .. }
4441            | MicroOp::ArrPush { .. }
4442            | MicroOp::ListClear { .. }
4443            | MicroOp::StrAppend { .. }
4444            | MicroOp::MapGet { .. }
4445            | MicroOp::MapSet { .. }
4446            | MicroOp::MapHas { .. }
4447            | MicroOp::Host { .. }
4448            | MicroOp::NewList { .. }
4449            | MicroOp::ListTriple { .. } => return None,
4450            MicroOp::ArrLoad {
4451                dst,
4452                idx,
4453                ptr_slot,
4454                len_slot,
4455                byte,
4456                narrow32,
4457                checked,
4458            } => {
4459                let i = frame[idx as usize];
4460                let len = frame[len_slot as usize];
4461                let im1 = i.wrapping_sub(1);
4462                // The reference keeps the bounds guard either way (an
4463                // unchecked load that the Oracle proved in-bounds is in
4464                // range by hypothesis; refusing OOB here is just safety).
4465                let _ = checked;
4466                if (im1 as u64) >= (len as u64) {
4467                    return None;
4468                }
4469                // SAFETY: differentials pin a live buffer, like the chain.
4470                frame[dst as usize] = unsafe {
4471                    if byte {
4472                        *(frame[ptr_slot as usize] as *const u8).add(im1 as usize) as i64
4473                    } else if narrow32 {
4474                        *(frame[ptr_slot as usize] as *const i32).add(im1 as usize) as i64
4475                    } else {
4476                        *(frame[ptr_slot as usize] as *const i64).add(im1 as usize)
4477                    }
4478                };
4479            }
4480            MicroOp::ArrLoadAffine {
4481                dst,
4482                a,
4483                op,
4484                b,
4485                const_offset,
4486                ptr_slot,
4487                len_slot,
4488                checked,
4489            } => {
4490                let _ = checked;
4491                let idx = op.eval(frame[a as usize], frame[b as usize], const_offset);
4492                let len = frame[len_slot as usize];
4493                let im1 = idx.wrapping_sub(1);
4494                if (im1 as u64) >= (len as u64) {
4495                    return None;
4496                }
4497                // SAFETY: differentials pin a live 8-byte buffer, like the chain.
4498                frame[dst as usize] =
4499                    unsafe { *(frame[ptr_slot as usize] as *const i64).add(im1 as usize) };
4500            }
4501            MicroOp::ArrLoad2F {
4502                dst,
4503                i: ix,
4504                j: jx,
4505                ptr_slot,
4506                len_slot,
4507                op,
4508            } => {
4509                let len = frame[len_slot as usize];
4510                let im1 = frame[ix as usize].wrapping_sub(1);
4511                let jm1 = frame[jx as usize].wrapping_sub(1);
4512                if (im1 as u64) >= (len as u64) || (jm1 as u64) >= (len as u64) {
4513                    return None;
4514                }
4515                // SAFETY: differentials pin a live 8-byte buffer, like the chain.
4516                let (a, b) = unsafe {
4517                    let ptr = frame[ptr_slot as usize] as *const i64;
4518                    (
4519                        f64::from_bits(*ptr.add(im1 as usize) as u64),
4520                        f64::from_bits(*ptr.add(jm1 as usize) as u64),
4521                    )
4522                };
4523                frame[dst as usize] = op.eval(a, b).to_bits() as i64;
4524            }
4525            MicroOp::ArrLoad2 {
4526                dst,
4527                i: ix,
4528                j: jx,
4529                ptr_a,
4530                len_a,
4531                ptr_b,
4532                len_b,
4533                op,
4534                checked,
4535            } => {
4536                let _ = checked;
4537                let lena = frame[len_a as usize];
4538                let lenb = frame[len_b as usize];
4539                let im1 = frame[ix as usize].wrapping_sub(1);
4540                let jm1 = frame[jx as usize].wrapping_sub(1);
4541                if (im1 as u64) >= (lena as u64) || (jm1 as u64) >= (lenb as u64) {
4542                    return None;
4543                }
4544                // SAFETY: differentials pin live 8-byte buffers, like the chain.
4545                let (a, b) = unsafe {
4546                    let pa = frame[ptr_a as usize] as *const i64;
4547                    let pb = frame[ptr_b as usize] as *const i64;
4548                    (*pa.add(im1 as usize), *pb.add(jm1 as usize))
4549                };
4550                frame[dst as usize] = op.eval(a, b);
4551            }
4552            MicroOp::ArrStore {
4553                src,
4554                idx,
4555                ptr_slot,
4556                len_slot,
4557                byte,
4558                narrow32,
4559                checked,
4560            } => {
4561                // The reference always validates — a sound proof never trips it.
4562                let _ = checked;
4563                let i = frame[idx as usize];
4564                let len = frame[len_slot as usize];
4565                let im1 = i.wrapping_sub(1);
4566                if (im1 as u64) >= (len as u64) {
4567                    return None;
4568                }
4569                // SAFETY: see ArrLoad.
4570                unsafe {
4571                    if byte {
4572                        *(frame[ptr_slot as usize] as *mut u8).add(im1 as usize) =
4573                            (frame[src as usize] != 0) as u8;
4574                    } else if narrow32 {
4575                        *(frame[ptr_slot as usize] as *mut i32).add(im1 as usize) =
4576                            frame[src as usize] as i32;
4577                    } else {
4578                        *(frame[ptr_slot as usize] as *mut i64).add(im1 as usize) =
4579                            frame[src as usize];
4580                    }
4581                }
4582            }
4583            MicroOp::ArrRMW {
4584                idx,
4585                operand,
4586                ptr_slot,
4587                len_slot,
4588                op,
4589                checked,
4590            } => {
4591                let _ = checked;
4592                let i = frame[idx as usize];
4593                let len = frame[len_slot as usize];
4594                let im1 = i.wrapping_sub(1);
4595                if (im1 as u64) >= (len as u64) {
4596                    return None;
4597                }
4598                // SAFETY: see ArrLoad — a live 8-byte buffer is pinned.
4599                unsafe {
4600                    let cell = (frame[ptr_slot as usize] as *mut i64).add(im1 as usize);
4601                    *cell = op.eval(*cell, frame[operand as usize]);
4602                }
4603            }
4604            MicroOp::ArrCondSwap {
4605                idx1,
4606                idx2,
4607                ptr_slot,
4608                len_slot,
4609                cmp,
4610                checked,
4611            } => {
4612                let _ = checked;
4613                let len = frame[len_slot as usize];
4614                let m1 = frame[idx1 as usize].wrapping_sub(1);
4615                let m2 = frame[idx2 as usize].wrapping_sub(1);
4616                if (m1 as u64) >= (len as u64) || (m2 as u64) >= (len as u64) {
4617                    return None;
4618                }
4619                // SAFETY: see ArrLoad — a live 8-byte buffer is pinned.
4620                unsafe {
4621                    let ptr = frame[ptr_slot as usize] as *mut i64;
4622                    let a = *ptr.add(m1 as usize);
4623                    let b = *ptr.add(m2 as usize);
4624                    if cmp.eval(a, b) {
4625                        *ptr.add(m1 as usize) = b;
4626                        *ptr.add(m2 as usize) = a;
4627                    }
4628                }
4629            }
4630            MicroOp::ArrSwap {
4631                idx1,
4632                idx2,
4633                ptr_slot,
4634                len_slot,
4635                checked,
4636            } => {
4637                let _ = checked;
4638                let len = frame[len_slot as usize];
4639                let m1 = frame[idx1 as usize].wrapping_sub(1);
4640                let m2 = frame[idx2 as usize].wrapping_sub(1);
4641                if (m1 as u64) >= (len as u64) || (m2 as u64) >= (len as u64) {
4642                    return None;
4643                }
4644                // SAFETY: see ArrLoad — a live 8-byte buffer is pinned.
4645                unsafe {
4646                    let ptr = frame[ptr_slot as usize] as *mut i64;
4647                    let a = *ptr.add(m1 as usize);
4648                    let b = *ptr.add(m2 as usize);
4649                    *ptr.add(m1 as usize) = b;
4650                    *ptr.add(m2 as usize) = a;
4651                }
4652            }
4653            MicroOp::FmaF { dst, a, b, c } => {
4654                let av = f64::from_bits(frame[a as usize] as u64);
4655                let bv = f64::from_bits(frame[b as usize] as u64);
4656                let cv = f64::from_bits(frame[c as usize] as u64);
4657                frame[dst as usize] = ((av * bv) + cv).to_bits() as i64;
4658            }
4659            MicroOp::Jump { target } => {
4660                pc = target;
4661                continue;
4662            }
4663            MicroOp::JumpIfFalse { cond, target } => {
4664                if frame[cond as usize] == 0 {
4665                    pc = target;
4666                    continue;
4667                }
4668            }
4669            MicroOp::JumpIfTrue { cond, target } => {
4670                if frame[cond as usize] != 0 {
4671                    pc = target;
4672                    continue;
4673                }
4674            }
4675            MicroOp::Branch {
4676                cmp,
4677                lhs,
4678                rhs,
4679                target,
4680            } => {
4681                if !cmp.eval(frame[lhs as usize], frame[rhs as usize]) {
4682                    pc = target;
4683                    continue;
4684                }
4685            }
4686            MicroOp::MemMem {
4687                h_ptr_slot,
4688                h_len_slot,
4689                n_ptr_slot,
4690                n_len_slot,
4691                needle_len_slot,
4692                i_slot,
4693                count_slot,
4694                ..
4695            } => {
4696                // Reference model of the naive-search collapse: count overlapping
4697                // matches over `[i, h_len - needle_len + 1]`, add to count, and
4698                // advance `i` to the exit value — the same contract the runtime
4699                // helper implements. A needle index past its buffer would deopt
4700                // (the nest's checked needle `Index`): None, like the divisors.
4701                let h_len = frame[h_len_slot as usize];
4702                let n_buf_len = frame[n_len_slot as usize];
4703                let needle_len = frame[needle_len_slot as usize];
4704                let start = frame[i_slot as usize];
4705                if needle_len > n_buf_len {
4706                    return None;
4707                }
4708                let bound = h_len - needle_len + 1;
4709                let mut count = 0i64;
4710                if needle_len == 0 {
4711                    if start <= bound {
4712                        count = bound - start + 1;
4713                    }
4714                } else {
4715                    // SAFETY: the pinned byte buffers are live for the eval.
4716                    let hay = frame[h_ptr_slot as usize] as *const u8;
4717                    let ndl = frame[n_ptr_slot as usize] as *const u8;
4718                    let mut p = start; // 1-based
4719                    while p <= bound {
4720                        let mut m = true;
4721                        for j in 0..needle_len {
4722                            let hb = unsafe { *hay.add((p + j - 1) as usize) };
4723                            let nb = unsafe { *ndl.add(j as usize) };
4724                            if hb != nb {
4725                                m = false;
4726                                break;
4727                            }
4728                        }
4729                        if m {
4730                            count += 1;
4731                        }
4732                        p += 1;
4733                    }
4734                }
4735                frame[count_slot as usize] += count;
4736                frame[i_slot as usize] = core::cmp::max(start, bound + 1);
4737            }
4738            MicroOp::Return { src } => return Some(frame[src as usize]),
4739        }
4740        pc += 1;
4741    }
4742    unreachable!("validated programs cannot fall off the end")
4743}