Skip to main content

synth_backend/
arm_backend.rs

1//! ARM Backend — wraps the instruction selector + optimizer + encoder as a Backend
2//!
3//! This is Synth's custom ARM compiler targeting Cortex-M (Thumb-2).
4//! It's the only backend that supports per-rule formal verification (ASIL D path).
5
6use crate::ArmEncoder;
7use synth_core::backend::{
8    Backend, BackendCapabilities, BackendError, CodeRelocation, CompilationResult, CompileConfig,
9    CompiledFunction, LineMap, SafetyBounds,
10};
11use synth_core::target::{IsaVariant, TargetSpec};
12use synth_core::wasm_decoder::DecodedModule;
13use synth_core::wasm_op::WasmOp;
14use synth_synthesis::{
15    ArmInstruction, ArmOp, BoundsCheckConfig, InstructionSelector, OptimizationConfig,
16    OptimizerBridge, RuleDatabase, validate_instructions,
17};
18
19/// ARM Cortex-M backend using Synth's custom compiler pipeline
20pub struct ArmBackend;
21
22impl ArmBackend {
23    pub fn new() -> Self {
24        Self
25    }
26}
27
28impl Default for ArmBackend {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Backend for ArmBackend {
35    fn name(&self) -> &str {
36        "arm"
37    }
38
39    fn capabilities(&self) -> BackendCapabilities {
40        BackendCapabilities {
41            produces_elf: false,
42            supports_rule_verification: true,
43            supports_binary_verification: true,
44            is_external: false,
45        }
46    }
47
48    fn supported_targets(&self) -> Vec<TargetSpec> {
49        vec![
50            TargetSpec::cortex_m3(),
51            TargetSpec::cortex_m4(),
52            TargetSpec::cortex_m4f(),
53            TargetSpec::cortex_m7(),
54            TargetSpec::cortex_m7dp(),
55        ]
56    }
57
58    fn compile_module(
59        &self,
60        module: &DecodedModule,
61        config: &CompileConfig,
62    ) -> Result<CompilationResult, BackendError> {
63        let exports: Vec<_> = module
64            .functions
65            .iter()
66            .filter(|f| f.export_name.is_some())
67            .collect();
68
69        if exports.is_empty() {
70            return Err(BackendError::CompilationFailed(
71                "no exported functions found".into(),
72            ));
73        }
74
75        let mut functions = Vec::new();
76        for func in &exports {
77            let name = func.export_name.clone().unwrap();
78            // #359: copy THIS function's declared param widths into the config so
79            // `compile_function` (which carries no function index) can refuse a
80            // 64-bit param on the AAPCS stack-argument path. Cheap clone only when
81            // a signature table is present and this function has a width entry —
82            // otherwise reuse the shared config (every existing module unchanged).
83            // #509: same per-function pattern for the blocktype-arity side-table
84            // (value-carrying-branch lowering).
85            let params = config
86                .func_params_i64
87                .get(func.index as usize)
88                .filter(|p| !p.is_empty());
89            // #457: THIS function's DECLARED param count (imports-first full
90            // index), so the backend can cap the access-pattern inference that
91            // mistook a read-before-write local for a param. `None` when the
92            // driver supplied no arg-count table (hand-built modules).
93            let declared_params = config.func_arg_counts.get(func.index as usize).copied();
94            // GI-FPU-002 (#619/#369): THIS function's declared f32-param mask.
95            let params_f32 = config
96                .func_params_f32
97                .get(func.index as usize)
98                .filter(|p| !p.is_empty());
99            // GI-FPU-002 phase 2 (#369): THIS function's declared f64-param
100            // mask (hard-float targets decline f64 params loudly).
101            let params_f64 = config
102                .func_params_f64
103                .get(func.index as usize)
104                .filter(|p| !p.is_empty());
105            // GI-FPU-002 phase 2 (#719/#369): THIS function's declared f32/f64
106            // return flag, so the epilogue soundness guard fires on every driver
107            // path (not only the CLI loops).
108            let ret_f32 = config
109                .func_ret_f32
110                .get(func.index as usize)
111                .copied()
112                .unwrap_or(false);
113            let ret_f64 = config
114                .func_ret_f64
115                .get(func.index as usize)
116                .copied()
117                .unwrap_or(false);
118            // #1214: THIS function's declared-i64-local side-table. Guarded by
119            // `.any(i64)`, not `!is_empty()` — every function with ANY declared
120            // local (i32 included) has a non-empty vector, and that would
121            // widen this memoization guard to nearly every function for no
122            // reason; only a function that actually declares an i64 local
123            // needs the extra clone.
124            let declared_i64_locals = &func.declared_i64_locals;
125            let func_config = if params.is_some()
126                || params_f32.is_some()
127                || params_f64.is_some()
128                || !func.block_arity.is_empty()
129                || declared_params.is_some()
130                || ret_f32
131                || ret_f64
132                || declared_i64_locals.iter().any(|&b| b)
133            {
134                Some(CompileConfig {
135                    current_func_params_i64: params.cloned().unwrap_or_default(),
136                    current_func_params_f32: params_f32.cloned().unwrap_or_default(),
137                    current_func_params_f64: params_f64.cloned().unwrap_or_default(),
138                    current_func_ret_f32: ret_f32,
139                    current_func_ret_f64: ret_f64,
140                    current_func_block_arity: func.block_arity.clone(),
141                    current_func_declared_i64_locals: declared_i64_locals.clone(),
142                    current_func_param_count: declared_params,
143                    ..config.clone()
144                })
145            } else {
146                None
147            };
148            let cfg = func_config.as_ref().unwrap_or(config);
149            let compiled = self.compile_function(&name, &func.ops, cfg)?;
150            functions.push(compiled);
151        }
152
153        Ok(CompilationResult {
154            functions,
155            elf: None,
156            backend_name: self.name().to_string(),
157        })
158    }
159
160    fn compile_function(
161        &self,
162        name: &str,
163        ops: &[WasmOp],
164        config: &CompileConfig,
165    ) -> Result<CompiledFunction, BackendError> {
166        let (code, relocations, line_map, branch_map, final_instrs) =
167            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
168
169        // #778: derive the SOUND static WCET intermediate from the final Thumb-2
170        // stream. Only present for the Thumb-2 path; the core class (from the
171        // triple) decides whether the bound is sound (M3/M4) or declined (M7).
172        // Phase 2: any --wcet-hints entry for THIS function is verified (never
173        // trusted) by the loop analyzer. Phase 3: the intermediate carries the
174        // own-body cycles + direct call sites; the module driver composes it across
175        // the call graph. `wcet` here is the SINGLE-FUNCTION view (unresolved direct
176        // calls decline `call`) — a valid standalone answer, overwritten by the
177        // composed result when the driver runs the second pass.
178        let wcet_intermediate = final_instrs.as_ref().map(|instrs| {
179            let hints = config
180                .wcet_hints
181                .as_ref()
182                .and_then(|h| h.functions.get(name));
183            let self_label = config.current_func_index.map(|i| format!("func_{i}"));
184            crate::wcet::function_wcet_intermediate(
185                name,
186                instrs,
187                &config.target.triple,
188                hints,
189                self_label.as_deref(),
190            )
191        });
192        // The SINGLE-FUNCTION standalone view (unresolved direct calls decline
193        // `call`). Kept as a per-function fallback for any consumer that reads a
194        // lone `CompiledFunction` without running the module composer; the CLI
195        // `--emit-wcet` path IGNORES this and composes `wcet_intermediate` across
196        // the whole call graph instead (its result overwrites the report).
197        // RQ-71-STACKDEPTH (#1341): the native-stack profile, from the SAME
198        // final stream. Unconditional and cheap (one linear walk); the CLI
199        // decides whether to report it. It is NOT gated on the WCET decline —
200        // a data-dependent loop is WCET-unbounded and stack-bounded.
201        let stack_frame = final_instrs
202            .as_ref()
203            .map(|instrs| crate::stack_depth::analyze_function(name, instrs));
204        let wcet = final_instrs.map(|instrs| {
205            let hints = config
206                .wcet_hints
207                .as_ref()
208                .and_then(|h| h.functions.get(name));
209            crate::wcet::function_wcet_with_hints(name, &instrs, &config.target.triple, hints)
210        });
211
212        Ok(CompiledFunction {
213            name: name.to_string(),
214            code,
215            wasm_ops: ops.to_vec(),
216            relocations,
217            line_map,
218            branch_map,
219            wcet,
220            wcet_intermediate,
221            stack_frame,
222        })
223    }
224
225    fn is_available(&self) -> bool {
226        true // Always available — it's a library backend
227    }
228}
229
230/// Count the number of function parameters by analyzing LocalGet patterns
231/// RQ-58-MIRRORS (#242): was a private copy of the read-before-write param
232/// heuristic, byte-equivalent to the other two backends'. Now the ONE shared
233/// definition in `synth-core`, so a correction reaches every backend.
234fn count_params(wasm_ops: &[WasmOp]) -> u32 {
235    synth_core::count_params_heuristic(wasm_ops)
236}
237
238/// #457/#970: the parameter count the selector is given.
239///
240/// With a DECLARED count from the driver the bound is
241/// `min(`[`synth_core::referenced_locals`]`(ops), declared)` — the highest
242/// local index the body touches, clamped by the signature. That is exact in
243/// both directions: the clamp stops a read-before-write NON-PARAM local (which
244/// WASM zero-initializes) from being homed in an argument register and reading
245/// caller garbage (#457), and taking the max over ALL accesses — writes as well
246/// as reads — stops a PARAM from being demoted to a local.
247///
248/// The previous rule capped [`count_params`] (a READ-FIRST heuristic) with the
249/// declared count, which got the second direction wrong: a param written on ONE
250/// arm of an `if` is "written first" in linear op order, so it was demoted, and
251/// because the demoted local's first access is a WRITE the #457 zero-init
252/// skipped it too. The arm that does NOT write it then read an UNINITIALISED
253/// frame slot — measured under unicorn with the sub-SP stack poisoned,
254/// `cond_write_param(0, 42)` returned the poison word, i.e. previous-frame
255/// bytes rather than 42 (#970; the aarch64 instance was #851).
256///
257/// `min` rather than a plain `declared` override preserves the leniency for a
258/// body that only touches the first few of many declared params.
259///
260/// `None` (no declared signature: hand-built op streams, direct
261/// `compile_function` callers) keeps the legacy pure inference — see the
262/// residual documented on [`CompileConfig::current_func_param_count`].
263fn effective_num_params(wasm_ops: &[WasmOp], config: &CompileConfig) -> u32 {
264    match config.current_func_param_count {
265        Some(declared) => synth_core::referenced_locals(wasm_ops).min(declared),
266        None => count_params(wasm_ops),
267    }
268}
269
270/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
271/// Moved to `synth_core::rewrite_memory_grow_zero` (#242, VCR-SEL-005) so the
272/// ARM and RISC-V backends share ONE implementation and cannot drift; re-export
273/// here keeps the existing `rewrite_memory_grow_zero(...)` call sites working.
274use synth_core::rewrite_memory_grow_zero;
275
276/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
277/// value — i.e. one targeting a result-typed block/if (forward edge with
278/// results > 0) or a parameterized loop header (backward edge with loop
279/// params > 0)?
280///
281/// The optimized path's wasm→IR lowering drops the carried value on such
282/// edges (the taken arm returns the fall-through result — same class as the
283/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
284/// #507 — the shape is detected on the raw op stream and routed to the direct
285/// selector, whose #509 designated-result-register lowering lands the value
286/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
287/// side-table; when it is empty (hand-built op streams) every block reads as
288/// void and this never fires, keeping the optimized path byte-identical for
289/// every existing caller. Frozen-safe for the same reason as #507: the frozen
290/// fixtures compile `--relocatable` (already direct), and no optimized-path
291/// fixture branches to a result-typed block.
292fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
293    // Open control constructs: (is_loop, params, results), innermost last.
294    let mut open: Vec<(bool, u8, u8)> = Vec::new();
295    let mut ctrl_ord = 0usize;
296    // A branch edge carries a value when its target is a result-typed forward
297    // join (block/if) or a parameterized loop header.
298    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
299        let Some(&(is_loop, params, results)) = open
300            .len()
301            .checked_sub(1 + depth as usize)
302            .and_then(|i| open.get(i))
303        else {
304            return false; // function-level target — handled by Return lowering
305        };
306        if is_loop { params > 0 } else { results > 0 }
307    };
308    for op in wasm_ops {
309        match op {
310            WasmOp::Block | WasmOp::If => {
311                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
312                ctrl_ord += 1;
313                open.push((false, p, r));
314            }
315            WasmOp::Loop => {
316                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
317                ctrl_ord += 1;
318                open.push((true, p, r));
319            }
320            WasmOp::End => {
321                open.pop(); // None only at the function-level end — harmless
322            }
323            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
324            WasmOp::BrTable { targets, default }
325                if targets
326                    .iter()
327                    .chain(std::iter::once(default))
328                    .any(|d| carries(&open, *d)) =>
329            {
330                return true;
331            }
332            _ => {}
333        }
334    }
335    false
336}
337
338/// Core compilation: WASM ops → ARM machine code bytes + relocations
339///
340/// Returns (code_bytes, relocations) where relocations record BL instructions
341/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
342type CompileArmOutput = (
343    Vec<u8>,
344    Vec<CodeRelocation>,
345    LineMap,
346    synth_core::backend::BranchMap,
347    // #778: the SOUND static WCET result over the final Thumb-2 stream, computed
348    // by `compile_function` (which knows the function name); `None` for the A32
349    // path. Purely additive metadata — does not touch `code`.
350    Option<Vec<synth_synthesis::ArmInstruction>>,
351);
352
353/// RQ-71-STACKDEPTH/#345: one deferred `LdrSym` — where its placeholder LDR
354/// sits, and what word the pool must carry for it.
355struct PendingLiteral {
356    ldr_offset: u32,
357    symbol: String,
358    addend: i32,
359}
360
361/// RQ-72-ISLANDS (#345, cpetig via #1331): emit ONE constant island — the
362/// pooled words, optionally preceded by a branch over them — and patch each
363/// pending LDR's `imm12` in place.
364///
365/// SINGLE SOURCE for both placements. The inline island and the
366/// end-of-function pool differ in exactly one thing: whether execution can
367/// fall into the words. That is `branch_over`. Writing the patch arithmetic
368/// twice is how the two would drift, which is the failure this repo's North
369/// Star correction is about.
370///
371/// THE REFUSAL IS PRESERVED, DELIBERATELY. If a literal is out of range even
372/// from here, this still returns the #345 error rather than patching a wrong
373/// offset. Islands widen WHERE a pool may sit; they do not widen the Thumb-2
374/// LDR-literal encoding, which is a 12-bit unsigned field and always will be.
375fn emit_literal_pool(
376    code: &mut Vec<u8>,
377    relocations: &mut Vec<CodeRelocation>,
378    pending: &[PendingLiteral],
379    branch_over: Option<&ArmEncoder>,
380) -> Result<(), String> {
381    if pending.is_empty() {
382        return Ok(());
383    }
384    // A mid-stream island sits in the instruction stream, so execution must be
385    // carried over it. The end-of-function pool needs no branch: those bytes
386    // are past the final return and are never reached.
387    if let Some(enc) = branch_over {
388        let n = pending.len();
389        // The branch's own size decides the distance it must cover, and the
390        // distance decides the size (B.N is 2 bytes, B.W is 4). Iterate to the
391        // fixed point rather than assuming one — the same shape
392        // `resolve_label_branches` already uses for label branches.
393        let (bytes, _pad) = island_branch_over(code.len(), n, enc)?;
394        code.extend_from_slice(&bytes);
395    }
396    // 4-byte align the pool start (Thumb-2 word loads require it, and
397    // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
398    while !code.len().is_multiple_of(4) {
399        code.push(0x00);
400    }
401    // One distinct pooled word per LdrSym (no dedup: different sites carry
402    // different addends, and the REL addend lives in the word).
403    for lit in pending {
404        let word_offset = code.len() as u32;
405
406        // REL semantics: the linker computes `S + A`, where A is the in-place
407        // value of the relocated word. Initialize the word to the addend so
408        // the final loaded address is `symbol + addend`.
409        code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
410        relocations.push(CodeRelocation {
411            offset: word_offset,
412            symbol: lit.symbol.clone(),
413            kind: synth_core::backend::RelocKind::Abs32,
414        });
415
416        // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
417        // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
418        // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
419        let pc = lit.ldr_offset + 4;
420        let aligned_pc = pc & !3u32;
421        let imm12 = word_offset.wrapping_sub(aligned_pc);
422        if word_offset < aligned_pc || imm12 > 0xFFF {
423            return Err(format!(
424                "LdrSym literal pool out of range (#345): imm12={} > 4095 \
425                 for symbol {}",
426                imm12, lit.symbol
427            ));
428        }
429        let hw2_off = (lit.ldr_offset + 2) as usize;
430        let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
431        hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
432        let hw2_bytes = hw2.to_le_bytes();
433        code[hw2_off] = hw2_bytes[0];
434        code[hw2_off + 1] = hw2_bytes[1];
435    }
436    Ok(())
437}
438
439fn compile_wasm_to_arm(
440    wasm_ops: &[WasmOp],
441    config: &CompileConfig,
442) -> Result<CompileArmOutput, String> {
443    // #1093: a PARAMETER-taking block type (`if`/`block`/`loop (param ..)`,
444    // wasm multi-value) declines LOUDLY here — the single choke point BOTH
445    // ARM codegen paths pass through, so neither the optimized route nor the
446    // #197 direct route can reach the selectors' frame-entry stack
447    // checkpoints, which cannot represent params consumed below them (the
448    // `split_off` panic with an `else`; a silently-wrong false-path value
449    // without one — see `find_param_block_type`). This is the aarch64
450    // VCR-A64-CF-001 frame-open refusal ported, NOT multi-value support.
451    // Checked on the driver's ORIGINAL stream, which is what the ordinal
452    // side-table was built against. Empty side-table (hand-built op streams)
453    // ⇒ never fires ⇒ byte-identical for every existing caller.
454    //
455    // RQ-64-MVLOWER (#1093): the guard is relaxed PER CONSTRUCT and PER PATH,
456    // from the one policy in synth-core (`arm_param_block_lowering`), on the
457    // configuration the #1097 oracle executes — `--relocatable`. The
458    // self-contained image path keeps the full decline: no oracle leg
459    // executes its images, so there is no evidence to relax on.
460    let lowered = synth_core::arm_param_block_lowering(config.relocatable);
461    if let Some((what, ord, arity)) = synth_core::find_unlowered_param_block_type(
462        wasm_ops,
463        &config.current_func_block_arity,
464        lowered,
465    ) {
466        return Err(synth_core::param_block_decline_msg(
467            if config.relocatable {
468                "the ARM direct selector (--relocatable)"
469            } else {
470                "the ARM selector (self-contained image path — no #1097 oracle \
471                 leg executes it)"
472            },
473            what,
474            ord,
475            arity,
476        ));
477    }
478    // #539: `memory.grow(0)` must return the CURRENT page count, not the
479    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
480    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
481    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
482    // is semantically identical to `memory.size`, which the backend already
483    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
484    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
485    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
486    // cannot grow); a runtime delta that happens to be 0 is the documented
487    // follow-up.
488    let rewritten = rewrite_memory_grow_zero(wasm_ops);
489    // #494 phase 2b: the fact-spec guard-elision marks are keyed by op index
490    // into the stream the DRIVER handed us. The memory.grow(0) fold above can
491    // only shift indices AT OR AFTER a `memory.grow` — an op the fact-spec
492    // walk never crosses (it stops at the first untracked op, so no mark can
493    // follow one). Defense in depth: if the fold fired at all, drop the marks
494    // loudly rather than risk keying a guard elision to the wrong op.
495    //
496    // VCR-MEM-004 (#901): scry's externally-proven bounds-guard marks ride the
497    // SAME defensive gate for the SAME reason — they are op-index keyed, so an
498    // index shift would strip the guard off the wrong access. They are unioned
499    // with #494's certificate-discharged marks here (one consumption point,
500    // two authorities; `CompileConfig` keeps them separate so the attestation
501    // can say which one covered each site).
502    let (fact_div_zero_elide, fact_div_ovf_elide, mem_bounds_elide): (
503        &[usize],
504        &[usize],
505        Vec<usize>,
506    ) = if rewritten.len() == wasm_ops.len() {
507        let mut mem = config.fact_mem_bounds_elide.clone();
508        mem.extend_from_slice(&config.proven_safe_mem_elide);
509        mem.sort_unstable();
510        mem.dedup();
511        (&config.fact_div_zero_elide, &config.fact_div_ovf_elide, mem)
512    } else {
513        if !config.fact_div_zero_elide.is_empty()
514            || !config.fact_div_ovf_elide.is_empty()
515            || !config.fact_mem_bounds_elide.is_empty()
516        {
517            eprintln!(
518                "fact-spec: DECLINE guard elision marks dropped — the                      memory.grow(0) fold shifted op indices (#494 defensive gate);                      general lowering emitted"
519            );
520        }
521        if !config.proven_safe_mem_elide.is_empty() {
522            eprintln!(
523                "proven-safe: DECLINE {} bounds-guard elision mark(s) dropped — the \
524                 memory.grow(0) fold shifted op indices, so the (func, pc) keys no longer \
525                 name the accesses scry proved (VCR-MEM-004 defensive gate, #901); every \
526                 guard is retained",
527                config.proven_safe_mem_elide.len()
528            );
529        }
530        (&[], &[], Vec::new())
531    };
532    let wasm_ops: &[WasmOp] = &rewritten;
533
534    // #457: `count_params` INFERS the param count from access patterns (a local
535    // whose first access is a read is assumed to be a param), so a
536    // read-before-write NON-PARAM local — which WASM zero-initializes — was
537    // indistinguishable from a param: it got homed in a parameter register and
538    // read caller garbage instead of 0. The driver supplies the DECLARED count
539    // (`current_func_param_count`, from the module's type section) to settle it.
540    //
541    // #970 (RQ-57-CONDPARAM): see [`effective_num_params`] for the bound and
542    // why the read-first inference is not it.
543    let inferred_params = count_params(wasm_ops);
544    let num_params = effective_num_params(wasm_ops, config);
545    // A read-before-write non-param local exists iff the ACCESS-PATTERN
546    // inference overshot the declared count — the read-first rule can only
547    // exceed it via a read-first index >= the declared count, which is exactly
548    // such a local. (Unchanged by #970: `referenced >= inferred` always, so
549    // `num_params < inferred_params` still holds iff `inferred > declared`;
550    // stated directly here rather than left to that algebra.)
551    let has_rbw_local = match config.current_func_param_count {
552        Some(declared) => inferred_params > declared,
553        None => false,
554    };
555
556    let bounds_config = match config.effective_safety_bounds() {
557        SafetyBounds::None => BoundsCheckConfig::None,
558        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
559        SafetyBounds::Software => BoundsCheckConfig::Software,
560        SafetyBounds::Mask => {
561            // #651 (mirroring the RISC-V backend's compile-time decline):
562            // index masking wraps `ea & (size-1)` — a modulo only when the
563            // linear-memory size is a power of two. With a non-power-of-two
564            // size the AND would silently REMAP in-bounds addresses (e.g.
565            // 0x18000 & 0x2FFFF = 0x8000 for a 192 KiB memory). Decline
566            // loudly rather than miscompile.
567            //
568            // RQ-57-SENTINEL (#953 sibling): `bytes == 0` used to be EXEMPT
569            // from this check, because 0 was read as "unknown — plain
570            // per-function path, no module context". But 0 is also exactly
571            // what a module declaring `(memory 0)` produces, and for that
572            // module the emitted guard (`SUB R12, R10, #1; AND addr, R12`,
573            // R10 = 0 baked by the startup) computes `0 - 1 = 0xFFFFFFFF` —
574            // an IDENTITY mask. Every access then executes unmasked at
575            // `[R11 + addr]` for any 32-bit addr: an unbounded OOB read/write
576            // in the mode whose purpose is bounding. Same sentinel/value
577            // collision as #932/#953, third backend-mode instance.
578            //
579            // 0 now means what #953 made it mean everywhere: a zero-byte
580            // memory. No mask can bound an access into a memory with no bytes
581            // (wasm semantics: every access traps), and wrap-not-trap has
582            // nothing to wrap into — refuse. Callers with no module context
583            // must state the size (the #953 contract; the CLI single-function
584            // path now threads the module's declared size for all backends).
585            let bytes = config.linear_memory_bytes;
586            if bytes == 0 {
587                return Err("--safety-bounds mask: the linear memory has ZERO bytes \
588                     (`(memory 0)`, or a driver that did not state the size) — \
589                     every access is out of bounds and a mask cannot express a \
590                     trap. Use --safety-bounds software (traps every access) \
591                     or declare a non-zero memory (RQ-57-SENTINEL, #953)"
592                    .to_string());
593            }
594            if !bytes.is_power_of_two() {
595                return Err(format!(
596                    "--safety-bounds mask requires a power-of-two linear-memory \
597                     size, got {bytes} bytes — switch to --safety-bounds software \
598                     for the deterministic check (#651)"
599                ));
600            }
601            BoundsCheckConfig::Masking
602        }
603    };
604
605    // The non-optimized (direct) instruction-selection path. Handles f32 via
606    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
607    // when the optimized path declines a module (see issue #120 below).
608    //
609    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
610    // `spill_on_exhaustion` set only on the retry — the first pass is the
611    // unmodified default, so every function that compiles today is selected by
612    // exactly the code that compiled it yesterday (bit-identity is structural,
613    // not behavioural).
614    // #1321: the allocator spill areas the direct selector reserved for the
615    // attempt that actually produced the returned stream, as
616    // `(frame_size, areas)`. Written only on a SUCCESSFUL selection, so after
617    // the recovery ladder it holds the rung that won. Left `None` on the
618    // optimized path, which supplies no layout — and `None` means "police every
619    // offset", i.e. exactly today's behaviour.
620    let selected_spill_areas: std::cell::RefCell<Option<(i32, Vec<std::ops::Range<i32>>)>> =
621        std::cell::RefCell::new(None);
622    // RQ-71-VFPALIAS (#881/#1069): the companion record — the PERMANENT frame
623    // homes of frame-resident f32/f64 locals. Kept beside the spill areas rather
624    // than folded into them because it is a different KIND of fact: the areas say
625    // where the allocator's slots live, this says which offsets inside that same
626    // pool are a wasm local's own home and carry no single-value obligation.
627    let selected_vfp_frame_homes: std::cell::RefCell<Option<(i32, Vec<i32>)>> =
628        std::cell::RefCell::new(None);
629    let select_direct_attempt = |spill_on_exhaustion: bool,
630                                 param_backing_on_exhaustion: bool,
631                                 local_promote: bool,
632                                 i64_spill_slots: Option<usize>,
633                                 vfp_spill_on_exhaustion: bool,
634                                 vfp_frame_home_locals: bool,
635                                 vfp_wide_file: bool|
636     -> Result<Vec<ArmInstruction>, synth_core::Error> {
637        let db = RuleDatabase::with_standard_rules();
638        let mut selector =
639            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
640        selector.set_target(config.target.fpu, &config.target.triple);
641        if config.num_imports > 0 {
642            selector.set_num_imports(config.num_imports);
643        }
644        // #195: plumb the callee argument-count tables so the direct selector can
645        // marshal call arguments into R0–R3 per AAPCS.
646        selector.set_func_arg_counts(
647            config.func_arg_counts.clone(),
648            config.type_arg_counts.clone(),
649        );
650        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
651        // imports (rewritten to the wasm field name by build_relocatable_elf)
652        // instead of `__meld_dispatch_import`.
653        selector.set_relocatable(config.relocatable);
654        // #642: call_indirect guard inputs (compile-time table size for the
655        // bounds guard + closed-world type verdicts). Without them, every
656        // call_indirect lowering declines loudly.
657        selector.set_call_indirect_guards(config.call_indirect_guards.clone());
658        // #275: on the self-contained image path (NOT --relocatable) the R11
659        // funcref-table dispatch is a silent miscompile — the region is only
660        // populated by an external runtime, which a self-contained ELF does
661        // not have, so the dispatch would read function pointers from
662        // linear-memory data. Two outcomes:
663        //  - the Thumb-2 `--cortex-m` image path (CLI-flagged: the builder
664        //    that emits and patches the flash-resident funcref table will
665        //    run) lowers call_indirect through that table, PC-relative,
666        //    never via R11;
667        //  - every OTHER self-contained configuration (A32/Cortex-R5, the
668        //    simple-ELF builder, imports present) keeps the loud decline.
669        // The host-linked (--relocatable) path keeps the guarded R11
670        // dispatch: there a runtime places the table region at R11.
671        let self_contained_table = config.self_contained_funcref_table
672            && matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
673        selector
674            .set_reject_self_contained_call_indirect(!config.relocatable && !self_contained_table);
675        selector.set_self_contained_funcref_table(self_contained_table);
676        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
677        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
678        // VCR-MEM-002 phase 1 (#406): per-memory initial page counts — enables
679        // the multi-memory arms (memory-0 lowering never reads it; empty ⇒
680        // every multi-memory op declines loudly).
681        selector.set_memory_pages(config.memory_pages.clone());
682        selector.set_memory0_page_log2(config.memory0_page_log2);
683        // #311: i64 call results are register PAIRS — tag them.
684        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
685        // #1210: per-function result COUNT (0 = void) — `func_ret_i64` alone
686        // cannot tell a void callee from an i32-returning one.
687        selector.set_func_result_counts(config.func_result_counts.clone());
688        // #359: declared param widths of THIS function, so the AAPCS stack-arg
689        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
690        selector.set_params_i64(config.current_func_params_i64.clone());
691        // GI-FPU-002 (#619/#369): declared f32-param mask — home hard-float f32
692        // args in S0..S15 (AAPCS-VFP) instead of the R0..R3 integer path.
693        selector.set_params_f32(config.current_func_params_f32.clone());
694        // GI-FPU-002 phase 2 (#369): declared f64-param mask — hard-float
695        // targets decline f64-param functions loudly (no D-register homing yet).
696        selector.set_params_f64(config.current_func_params_f64.clone());
697        // GI-FPU-002 phase 2 (#719/#369): THIS function's f32/f64 return flag, so
698        // the epilogue loudly declines a float result reaching it in a core
699        // register (never a silent integer R0 return where a caller reads S0/D0).
700        selector.set_ret_float(config.current_func_ret_f32, config.current_func_ret_f64);
701        // GI-FPU-002 phase 3 (#369): per-callee float-signature tables. `Call`
702        // marshals the AAPCS-VFP boundary from these (float args into S0../D0..,
703        // float results out of S0/D0); `CallIndirect` still declines a
704        // float-returning static type loudly.
705        selector.set_float_call_signatures(
706            config.func_ret_f32.clone(),
707            config.func_ret_f64.clone(),
708            config.type_ret_f32.clone(),
709            config.type_ret_f64.clone(),
710            config.func_params_f32.clone(),
711            config.func_params_f64.clone(),
712        );
713        // #509: blocktype-arity side-table of THIS function, so value-carrying
714        // br/br_if/br_table land the carried value in the target block's
715        // designated result register instead of dropping it. Empty ⇒ legacy
716        // void-block lowering.
717        selector.set_block_arity(config.current_func_block_arity.clone());
718        // #1214: THIS function's declared-i64-local side-table — see
719        // `compute_local_layout`'s use of it. Empty ⇒ exactly the prior
720        // dataflow-only width inference.
721        selector.set_declared_i64_locals(config.current_func_declared_i64_locals.clone());
722        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
723        // gating here keeps every non-native compile (all frozen fixtures) on the
724        // legacy R9 globals-table path, bit-identical.
725        if config.native_pointer_abi
726            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
727        {
728            selector.set_native_pointer_stack(sp_idx, sp_init);
729        }
730        // #643: per-global slot widths — i64/f64 globals occupy 8-byte slots
731        // (register-pair store/load) and shift every later global's offset.
732        // Empty for i32-only modules ⇒ the legacy `idx * 4` layout, unchanged.
733        selector.set_global_widths(config.global_widths.clone());
734        selector.set_spill_on_exhaustion(spill_on_exhaustion);
735        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
736        // #881 (VCR-RA-004): VFP register-file spilling, set ONLY on the retry
737        // after an attempt failed with a GI-FPU-002 exhaustion Err — functions
738        // that compile without it keep byte-identical output by construction.
739        selector.set_vfp_spill_on_exhaustion(vfp_spill_on_exhaustion);
740        // #1069: LAST-resort residence lever — set ONLY by the final VFP
741        // retry below, after the plain #881 rung also exhausted, so every
742        // function that compiles through base path or plain rung is produced
743        // by exactly yesterday's path (byte-identity is structural).
744        selector.set_vfp_frame_home_locals(vfp_frame_home_locals);
745        // RQ-67-VFPREACH (#1267): the AAPCS callee-saved VFP half.
746        selector.set_vfp_wide_file(vfp_wide_file);
747        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
748        // retry after an attempt failed with the slot-pool-exhausted Err —
749        // functions that compile with the default pool keep their frame
750        // byte-identical by construction.
751        if let Some(slots) = i64_spill_slots {
752            selector.set_i64_spill_slots(slots);
753        }
754        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
755        // in callee-saved registers instead of frame slots — the structural lever
756        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
757        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
758        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
759        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
760        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
761        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
762        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
763        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
764        // which on a dense function leaves the spill allocator with nothing to
765        // free → the frame-slot path is the escape that restores compilability).
766        selector.set_local_promote(local_promote);
767        // #494 phase 2b: certificate-discharged div/rem trap-guard elision
768        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
769        selector
770            .set_fact_div_guard_elisions(fact_div_zero_elide.to_vec(), fact_div_ovf_elide.to_vec());
771        // #494 bounds-elision + VCR-MEM-004 (#901): per-site memory
772        // bounds-guard marks, unioned above. Empty in every compile without
773        // SYNTH_FACT_SPEC + facts or --proven-safe.
774        selector.set_fact_mem_bounds_elisions(mem_bounds_elide.clone());
775        let selected = selector.select_with_stack(wasm_ops, num_params);
776        if selected.is_ok() {
777            // #1321: only a SUCCESSFUL attempt's layout describes the stream we
778            // return; a failed rung's frame is discarded with it.
779            *selected_spill_areas.borrow_mut() = selector.frame_spill_areas().cloned();
780            *selected_vfp_frame_homes.borrow_mut() = selector.vfp_frame_home_halves().cloned();
781        }
782        selected
783    };
784    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
785        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
786        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
787        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
788        // The full exhaustion-recovery ladder, parameterized on whether local
789        // promotion is enabled. Each rung is reached only when the previous one
790        // returned a recoverable register-exhaustion Err, so a function that
791        // compiles on the first attempt is untouched by the later rungs. Returns
792        // the result AND which rung produced it (for the #242 measurement below).
793        let recovery_ladder =
794            |promote: bool,
795             i64_spill_slots: Option<usize>,
796             vfp_spill: bool,
797             vfp_frame: bool,
798             vfp_wide: bool|
799             -> (Result<Vec<ArmInstruction>, synth_core::Error>, &'static str) {
800                let mut attempt = select_direct_attempt(
801                    false,
802                    false,
803                    promote,
804                    i64_spill_slots,
805                    vfp_spill,
806                    vfp_frame,
807                    vfp_wide,
808                );
809                let mut rung = "base";
810                // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
811                // hard-fail is recoverable — retry with spill-on-exhaustion, which
812                // reserves the spill area and spills the deepest stack value when
813                // the pool is full.
814                if let Err(e) = &attempt
815                    && e.to_string().contains(SINGLE_EXHAUSTION)
816                {
817                    attempt = select_direct_attempt(
818                        true,
819                        false,
820                        promote,
821                        i64_spill_slots,
822                        vfp_spill,
823                        vfp_frame,
824                        vfp_wide,
825                    );
826                    rung = "spill";
827                }
828                // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
829                // exhaustion is recoverable too — not by stack spilling (the pair
830                // allocator already spills stack values, #171) but by frame-backing
831                // the params (#204) so they stop pinning R0-R3, with spill kept on.
832                if let Err(e) = &attempt
833                    && e.to_string().contains(PAIR_EXHAUSTION)
834                {
835                    attempt = select_direct_attempt(
836                        true,
837                        true,
838                        promote,
839                        i64_spill_slots,
840                        vfp_spill,
841                        vfp_frame,
842                        vfp_wide,
843                    );
844                    rung = "param-backing";
845                }
846                (attempt, rung)
847            };
848        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
849        // must never be the reason a function fails to compile. Run the full ladder
850        // with promotion first (so every function that compiles today is
851        // bit-identical), and if it still ends in register exhaustion, fall back to
852        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
853        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
854        // pins r4-r8 for the locals; on a dense function that leaves the allocator
855        // with nothing to free, so dropping it restores compilability. The fallback
856        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
857        // output is untouched by construction (frozen byte gate stays green).
858        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
859        // RQ-69-FALCON (#1318): per-rung reporting, because the summary line
860        // below CANNOT distinguish the two failures it is asked about. `rung`
861        // is only assigned when an attempt SUCCEEDS, so a function that climbs
862        // the whole ladder and exhausts every rung prints `rung=base
863        // result=exhausted` — identical to one that never climbed at all. Worse,
864        // the Err the caller finally reports is stage 2's, so a stage-3
865        // (wide-file) failure is invisible even in the user-facing message:
866        // #1318's `step` reports the #1069 slot-pool message while the wide-file
867        // rung it also failed says nothing. Measured on the reporter's module
868        // before this was written; reading the source was the only way to tell
869        // which of the two had happened.
870        //
871        // Logging only, behind the same env var, so emitted bytes are unchanged
872        // and the frozen byte gate is unaffected.
873        let stats = std::env::var("SYNTH_RECOVERY_STATS").is_ok();
874        // Every rung's Err, in attempt order (#1318). The ladder keeps the
875        // EARLIER attempt's Err whenever a later rung also fails — stage 3
876        // falls back to stage 2's `fh`, each pool-grow falls back to its
877        // ungrown attempt — so the reporter of #1318 was told "spill-slot pool
878        // exhausted" while the wall three of the four rungs actually hit was
879        // the VSTR/VLDR [sp,#imm] window. Reporting the LAST rung's Err is no
880        // better: the last rung attempted is the wide-file one, whose Err is
881        // the pool message again. So report what was actually tried, deduped.
882        // Control flow is untouched — every rung still runs exactly when it
883        // ran before, and the substrings other code matches on are all still
884        // present in the joined message.
885        let tried: std::cell::RefCell<Vec<(String, String)>> = std::cell::RefCell::new(Vec::new());
886        let note = |name: &str, r: &Result<Vec<ArmInstruction>, synth_core::Error>| {
887            if let Err(e) = r {
888                let m = e.to_string();
889                let first = m.lines().next().unwrap_or("").to_string();
890                tried.borrow_mut().push((name.to_string(), first));
891            }
892            if stats {
893                match r {
894                    Ok(_) => eprintln!("[recovery-stats]   tried rung={name} -> ok"),
895                    Err(e) => {
896                        let m = e.to_string();
897                        let first = m
898                            .lines()
899                            .next()
900                            .unwrap_or("")
901                            .chars()
902                            .take(140)
903                            .collect::<String>();
904                        eprintln!("[recovery-stats]   tried rung={name} -> exhausted: {first}");
905                    }
906                }
907            }
908        };
909        // The full pre-#587 recovery sequence (promotion-on ladder, then the
910        // #474 promotion-off fallback), parameterized on the pool size so the
911        // pool-grow retry below reruns it verbatim.
912        let full_sequence = |slots: Option<usize>,
913                             vfp_spill: bool,
914                             vfp_frame: bool,
915                             vfp_wide: bool|
916         -> (
917            Result<Vec<ArmInstruction>, synth_core::Error>,
918            &'static str,
919            bool,
920        ) {
921            let (mut attempt, mut rung) =
922                recovery_ladder(promote, slots, vfp_spill, vfp_frame, vfp_wide);
923            let mut promotion_dropped = false;
924            if promote
925                && attempt
926                    .as_ref()
927                    .err()
928                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
929            {
930                let (rescued, off_rung) =
931                    recovery_ladder(false, slots, vfp_spill, vfp_frame, vfp_wide);
932                if rescued.is_ok() {
933                    attempt = rescued;
934                    rung = off_rung;
935                    promotion_dropped = true;
936                }
937            }
938            (attempt, rung, promotion_dropped)
939        };
940        let (mut attempt, mut rung, mut promotion_dropped) =
941            full_sequence(None, false, false, false);
942        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
943        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
944        // an i64-dense function simply has more values simultaneously live than
945        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
946        // modes) with the pool sized from a conservative operand-stack-depth
947        // bound: the number of simultaneously spilled values can never exceed
948        // the operand-stack depth, plus a few transient slots (the arg-move
949        // cycle resolver and call-result parking each borrow one). The selector
950        // clamps the request to its 12-bit-friendly cap; a function that still
951        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
952        // promotion-off fallback — so any function that compiled yesterday
953        // (through any rung or fallback) is produced by exactly yesterday's
954        // path, byte-identical; the grown pool only ever fires for functions
955        // whose every existing escape ended in the slot-pool Err.
956        if attempt
957            .as_ref()
958            .err()
959            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
960        {
961            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
962            let (grown, _, grown_dropped) =
963                full_sequence(Some(depth.saturating_add(4)), false, false, false);
964            note("pool-grow", &grown);
965            if grown.is_ok() {
966                attempt = grown;
967                rung = "pool-grow";
968                promotion_dropped = grown_dropped;
969            }
970        }
971        // #881 (VCR-RA-004): the GI-FPU-002 VFP register-file exhaustion is
972        // recoverable too — retry the ENTIRE sequence with VFP spilling
973        // enabled (the pre-op pressure guard spills the deepest segment-local
974        // f32/f64 stack value into the shared spill area and reloads spilled
975        // operands before their consumers). Deliberately LAST, after every
976        // integer rung, so any function that compiled yesterday is produced
977        // by exactly yesterday's path; the VFP rung only ever fires for
978        // functions whose every existing escape ended in a GI-FPU-002
979        // exhaustion Err (previously an unconditional loud skip). A VFP-
980        // spilling function can in turn exhaust the shared slot pool — the
981        // #587 pool-grow retry composes inside the rung.
982        const VFP_S_EXHAUSTION: &str = "VFP register file exhausted";
983        const VFP_D_EXHAUSTION: &str = "VFP D-register file exhausted";
984        if attempt.as_ref().err().is_some_and(|e| {
985            let msg = e.to_string();
986            msg.contains(VFP_S_EXHAUSTION) || msg.contains(VFP_D_EXHAUSTION)
987        }) {
988            // Stage 1 — the plain #881 rung, exactly yesterday's path
989            // (sequence, pool sizing and all): any function it rescues is
990            // byte-identical to what it shipped yesterday, by construction.
991            let (vfp, vfp_rung, vfp_dropped) = full_sequence(None, true, false, false);
992            note("vfp-spill", &vfp);
993            let (vfp, vfp_rung, vfp_dropped) = if vfp.as_ref().err().is_some_and(|e| {
994                let msg = e.to_string();
995                msg.contains(SLOT_EXHAUSTION) || msg.contains("spilling the VFP register file")
996            }) {
997                let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
998                let (grown, grown_rung, grown_dropped) =
999                    full_sequence(Some(depth.saturating_add(4)), true, false, false);
1000                note("vfp-spill+pool-grow", &grown);
1001                if grown.is_ok() {
1002                    (grown, grown_rung, grown_dropped)
1003                } else {
1004                    (vfp, vfp_rung, vfp_dropped)
1005                }
1006            } else {
1007                (vfp, vfp_rung, vfp_dropped)
1008            };
1009            if vfp.is_ok() {
1010                attempt = vfp;
1011                rung = match vfp_rung {
1012                    "base" => "vfp-spill",
1013                    _ => "vfp-spill+int",
1014                };
1015                promotion_dropped = vfp_dropped;
1016            } else {
1017                // Stage 2 (#1069, RQ-60-VFPPRESSURE increment 2) — LAST
1018                // resort: the plain rung ALSO failed, i.e. the pressure is
1019                // not (only) operand-stack values but PINNED LOCAL HOMES,
1020                // which the #881 victim search rightly never touches (a home
1021                // lives for the function's extent). Rerun the entire
1022                // sequence with frame-homed overflow locals: a fresh
1023                // f32/f64 local whose home grant would pin above the S7/D3
1024                // cap lives in the frame from its first def. Reached ONLY by
1025                // functions that failed every prior escape, so nothing that
1026                // compiles today moves a byte.
1027                let (fh, fh_rung, fh_dropped) = full_sequence(None, true, true, false);
1028                note("vfp-frame-locals", &fh);
1029                let (fh, fh_rung, fh_dropped) = if fh.as_ref().err().is_some_and(|e| {
1030                    let msg = e.to_string();
1031                    // The frame-homed-local slot demand (a PERMANENT slot per
1032                    // frame-resident float local) is a third way the shared
1033                    // pool exhausts — its trigger substring is the selector's
1034                    // own pub const, not a second copy that could drift (the
1035                    // #881 substring-is-control-flow lesson, pinned red-first
1036                    // by the live24 fixture test).
1037                    msg.contains(SLOT_EXHAUSTION)
1038                        || msg.contains("spilling the VFP register file")
1039                        || msg.contains(
1040                            synth_synthesis::instruction_selector::VFP_FRAME_HOME_SLOT_EXHAUSTION,
1041                        )
1042                }) {
1043                    let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
1044                    // Frame-homed locals hold their slots for the function's
1045                    // extent, OUTSIDE the operand-stack depth bound — size
1046                    // the grown pool for both. Distinct `local.set`/
1047                    // `local.tee` targets over-approximate the frame-homed
1048                    // local count; the selector clamps the request to its
1049                    // cap, and a function that still exhausts stays an
1050                    // honest loud skip.
1051                    let local_targets: std::collections::HashSet<u32> = wasm_ops
1052                        .iter()
1053                        .filter_map(|op| match op {
1054                            synth_synthesis::WasmOp::LocalSet(i)
1055                            | synth_synthesis::WasmOp::LocalTee(i) => Some(*i),
1056                            _ => None,
1057                        })
1058                        .collect();
1059                    let (grown, grown_rung, grown_dropped) = full_sequence(
1060                        Some(depth.saturating_add(local_targets.len()).saturating_add(4)),
1061                        true,
1062                        true,
1063                        false,
1064                    );
1065                    note(
1066                        &format!(
1067                            "vfp-frame-locals+pool-grow({})",
1068                            depth.saturating_add(local_targets.len()).saturating_add(4)
1069                        ),
1070                        &grown,
1071                    );
1072                    if grown.is_ok() {
1073                        (grown, grown_rung, grown_dropped)
1074                    } else {
1075                        (fh, fh_rung, fh_dropped)
1076                    }
1077                } else {
1078                    (fh, fh_rung, fh_dropped)
1079                };
1080                if fh.is_ok() {
1081                    attempt = fh;
1082                    rung = match fh_rung {
1083                        "base" => "vfp-frame-locals",
1084                        _ => "vfp-frame-locals+int",
1085                    };
1086                    promotion_dropped = fh_dropped;
1087                } else {
1088                    // Stage 3 (#1267, RQ-67-VFPREACH) — THE LAST RESORT, and the
1089                    // reach half of #1204's root shape. Every escape above has
1090                    // now ended in GI-FPU-002, so this function DECLINES today.
1091                    //
1092                    // It declines against HALF the register file: synth
1093                    // allocates S0-S15/D0-D7 because S16-S31/D8-D15 are AAPCS
1094                    // CALLEE-saved and, until this release, nothing could save
1095                    // them — VPUSH/VPOP did not exist in the encoder. Every FPU
1096                    // target synth supports actually has D0-D15 = S0-S31.
1097                    //
1098                    // Reached ONLY here, so a function that compiles today is
1099                    // produced by exactly today's path and cannot move a byte —
1100                    // the #881 rung discipline, measured over the corpus rather
1101                    // than asserted. The selector emits the VPUSH/VPOP pair and
1102                    // REFUSES functions with stack-passed params (#1273), so a
1103                    // failure here stays the honest loud decline it already was.
1104                    let (wide, wide_rung, wide_dropped) = full_sequence(None, true, true, true);
1105                    note("vfp-wide-file", &wide);
1106                    if wide.is_ok() {
1107                        attempt = wide;
1108                        rung = match wide_rung {
1109                            "base" => "vfp-wide-file",
1110                            _ => "vfp-wide-file+int",
1111                        };
1112                        promotion_dropped = wide_dropped;
1113                    } else {
1114                        attempt = fh;
1115                        promotion_dropped = fh_dropped;
1116                    }
1117                }
1118            }
1119        }
1120        // VCR-RA measurement (#242): log which recovery rung produced the result,
1121        // so the per-rung distribution across a corpus can be measured — the size
1122        // of the failure surface a verified allocator must subsume (see
1123        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
1124        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
1125        if stats {
1126            // `rung` holds the last SUCCESSFUL rung; on total exhaustion it is
1127            // still "base", which said nothing about how far the ladder climbed
1128            // (#1318). Report it as `none` and let the per-rung lines above
1129            // carry the detail.
1130            let rung = if attempt.is_ok() { rung } else { "none" };
1131            eprintln!(
1132                "[recovery-stats] rung={rung}{} result={}",
1133                if promotion_dropped {
1134                    " promotion-off"
1135                } else {
1136                    ""
1137                },
1138                if attempt.is_ok() { "ok" } else { "exhausted" },
1139            );
1140        }
1141        attempt.map_err(|e| {
1142            // The kept Err first (so every substring any caller or test matches
1143            // on is exactly where it was), then the rungs that were tried and
1144            // what each one hit. Deduped by message: three rungs reporting one
1145            // wall should say so once, and name the three (#1318).
1146            let base = format!("instruction selection failed: {}", e);
1147            let rungs = tried.borrow();
1148            if rungs.len() < 2 {
1149                return base;
1150            }
1151            let mut by_msg: Vec<(String, Vec<String>)> = Vec::new();
1152            for (rung, msg) in rungs.iter() {
1153                match by_msg.iter_mut().find(|(m, _)| m == msg) {
1154                    Some((_, names)) => names.push(rung.clone()),
1155                    None => by_msg.push((msg.clone(), vec![rung.clone()])),
1156                }
1157            }
1158            let detail = by_msg
1159                .iter()
1160                .map(|(msg, names)| format!("{} -> {}", names.join(" + "), msg))
1161                .collect::<Vec<_>>()
1162                .join(" | ");
1163            format!("{base} [every recovery rung failed: {detail}]")
1164        })
1165    };
1166
1167    // Instruction selection: optimized or direct.
1168    //
1169    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
1170    // optimized path materializes an absolute linmem base (0x20000100) and does
1171    // not preserve caller-saved registers across calls — both wrong for a
1172    // host-linked object, where the linmem base arrives via `fp` at runtime and
1173    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
1174    // #171) handles fp-relative memory + caller-saved preservation correctly.
1175    //
1176    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
1177    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
1178    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
1179    // SILENT miscompile (every input hits the last arm). The selector value isn't
1180    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
1181    // to fall back on; detect it on the raw wasm op stream here and force the
1182    // direct selector (`select_with_stack` lowers `br_table` correctly as a
1183    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
1184    // contract as the issue-#120 f32 decline: the function still compiles
1185    // correctly, just without IR-level optimization. Frozen-safe: the frozen
1186    // fixtures compile `--relocatable` (already direct), and no optimized-path
1187    // fixture (control_step, flight_algo) contains `br_table`.
1188    let has_br_table = wasm_ops
1189        .iter()
1190        .any(|op| matches!(op, WasmOp::BrTable { .. }));
1191    // #509: the optimized path also drops the value carried by a `br`/`br_if`
1192    // to a result-typed block (the taken edge returns the wrong arm's value —
1193    // same silent-miscompile class as the #507 br_table drop). Route the shape
1194    // to the direct selector, whose designated-result-register lowering (#509)
1195    // lands the carried value at the join. Never fires for void-block control
1196    // flow (all frozen/optimized fixtures), so those stay byte-identical.
1197    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
1198    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
1199    // direct selector. The optimized path's param homing is width-naive — its
1200    // #518 decline covers only functions that READ an i64 param (an `I64Load`
1201    // from a param index), so a function that reads an i32 param whose AAPCS
1202    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
1203    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
1204    // silently miscompiled rather than falling back. The direct selector's
1205    // `aapcs_param_layout` homing handles every such shape (i64-param READS
1206    // already fell back to it via the ir_to_arm Err, so those functions emit
1207    // the same bytes as before). `num_params` counts read-first locals, so a
1208    // function that never touches any param keeps the optimized path.
1209    let has_wide_param = config
1210        .current_func_params_i64
1211        .iter()
1212        .take(num_params as usize)
1213        .any(|&w| w);
1214    // #782(b): a HARD-float (FPU) target passes f32 args in VFP S-registers
1215    // and returns floats in S0/D0 (AAPCS-VFP) — but the optimized path's
1216    // param/return homing is float-naive (integer R0..R3 args, R0 return). A
1217    // function whose ops ALL lower on the optimized path but whose SIGNATURE
1218    // carries a float — e.g. the pure value-pick
1219    // `(param f32 f32 i32) (result f32) select`, no float OP to trip the
1220    // issue-#120 ir_to_arm fallback — was silently compiled with the integer
1221    // ABI: callers marshal S0/S1, the body reads R0/R1. Route every
1222    // float-signature function to the direct selector (AAPCS-VFP homing, or
1223    // an honest decline). Soft-float targets (no FPU) keep the optimized
1224    // path: the integer treatment IS the ABI there — byte-identical. (f64
1225    // params already route direct via `has_wide_param`; this adds f32 params
1226    // and f32/f64 returns.)
1227    let has_float_sig = config.target.fpu.is_some()
1228        && (config.current_func_ret_f32
1229            || config.current_func_ret_f64
1230            || config
1231                .current_func_params_f32
1232                .iter()
1233                .take(num_params as usize)
1234                .any(|&f| f)
1235            || config
1236                .current_func_params_f64
1237                .iter()
1238                .take(num_params as usize)
1239                .any(|&f| f));
1240    // #494 phase 2b: div/rem guard-elision marks are consumed by the DIRECT
1241    // selector only — the optimized path's IR passes (const-fold/CSE/DCE)
1242    // renumber instructions, so an op-index-keyed mark cannot soundly survive
1243    // them. Route marked functions direct (the #507/#509 honest-degradation
1244    // pattern). Never fires without SYNTH_FACT_SPEC + facts + a discharged
1245    // obligation, so every existing compile keeps its path byte-identical.
1246    let has_fact_div_elide = !fact_div_zero_elide.is_empty()
1247        || !fact_div_ovf_elide.is_empty()
1248        // #494 bounds-elision + VCR-MEM-004 (#901): memory bounds-guard marks
1249        // are direct-selector keyed for the same reason (IR passes renumber
1250        // instructions). This is ALSO why the optimized path's
1251        // `push_software_bounds_guard` sites never need mark plumbing: a
1252        // marked function is routed away from that path entirely.
1253        || !mem_bounds_elide.is_empty();
1254    // #643: the optimized path's global lowering is width-naive — `GlobalGet`/
1255    // `GlobalSet` are single-word `[R9, idx*4]` accesses, which (a) silently
1256    // dropped the high word of every i64 global and (b) mis-address every
1257    // global whose offset an earlier wide (i64/f64) slot shifted. When the
1258    // module has any wide global, route every global-touching function to the
1259    // direct selector, whose type-aware summed layout pairs the access (or
1260    // declines loudly). Modules with only 4-byte globals — every existing
1261    // fixture — keep the optimized path byte-identical.
1262    let has_wide_global_module = config.global_widths.iter().any(|&w| w > 4);
1263    let has_global_access = has_wide_global_module
1264        && wasm_ops
1265            .iter()
1266            .any(|op| matches!(op, WasmOp::GlobalGet(_) | WasmOp::GlobalSet(_)));
1267    // VCR-VER-001 (#242): `post_exhaust` scopes the post-exhaustion cleanup
1268    // extensions to functions whose bytes the #580 spill-on-exhaustion
1269    // machinery actually shaped (bridge-reported). Everything else — the
1270    // direct path, non-exhausted optimized functions — stays byte-identical
1271    // flag-on (the `vcr_ver_001_gate_242` lock's contract).
1272    let (arm_instrs, post_exhaust) = if config.no_optimize
1273        || config.relocatable
1274        || has_br_table
1275        || has_value_carry
1276        || has_wide_param
1277        || has_float_sig
1278        || has_global_access
1279        || has_fact_div_elide
1280        // #457: route read-before-write non-param locals to the direct
1281        // selector, whose prologue zero-init lands the wasm-mandated 0.
1282        || has_rbw_local
1283    {
1284        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1285            // RQ-65-PARITY (#197): name WHICH pre-gate predicate diverted the
1286            // function and which function it was, so the selector-parity
1287            // oracle can record every "only one path accepted this" case with
1288            // its reason instead of a bare count. The leading text is kept
1289            // verbatim — the #377/#1021 harnesses match on it.
1290            let reasons: Vec<&str> = [
1291                (config.no_optimize, "no-optimize"),
1292                (config.relocatable, "relocatable"),
1293                (has_br_table, "br-table"),
1294                (has_value_carry, "value-carry"),
1295                (has_wide_param, "wide-param"),
1296                (has_float_sig, "float-sig"),
1297                (has_global_access, "wide-global-access"),
1298                (has_fact_div_elide, "fact-elide"),
1299                (has_rbw_local, "rbw-local"),
1300            ]
1301            .iter()
1302            .filter(|(on, _)| *on)
1303            .map(|(_, name)| *name)
1304            .collect();
1305            eprintln!(
1306                "[path-debug] direct (pre-gate) func={} reasons={}",
1307                config
1308                    .current_func_index
1309                    .map_or("?".to_string(), |i| i.to_string()),
1310                reasons.join(",")
1311            );
1312        }
1313        (select_direct()?, false)
1314    } else {
1315        let opt_config = if config.loom_compat {
1316            OptimizationConfig::loom_compat()
1317        } else {
1318            OptimizationConfig::all()
1319        };
1320
1321        let mut bridge = OptimizerBridge::with_config(opt_config);
1322        // #188: tell the bridge how many imports there are so it declines only
1323        // LOCAL calls (and leaves import calls on the optimized path, keeping
1324        // the #173 field-name relocation rewrite intact).
1325        bridge.set_num_imports(config.num_imports);
1326        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
1327        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
1328        // levers — base-CSE (#468) excludes any access inside a marked range
1329        // from its fold set, and the bridge-level const-CSE declines wholesale
1330        // while any range is marked. Empty (the default) ⇒ byte-identical.
1331        bridge.set_volatile_segments(config.volatile_segments.clone());
1332        // #377: thread `--safety-bounds` to the bridge. Pre-fix the optimized
1333        // path ignored it — `software`/`mask` were SILENT NO-OPS on the path
1334        // that lowers the bulk of a flight loop's i32 loads/stores (byte-
1335        // identical to `none`, while the safety manifest claimed otherwise).
1336        // `Software` now emits the inline guard per access; `Masking` declines
1337        // memory-accessing functions to the direct selector; `None`/`Mpu` are
1338        // byte-identical to before.
1339        bridge.set_bounds_check(bounds_config);
1340        // #687: thread the absolute linear-memory base the optimized path
1341        // materializes. Defaults to 0x2000_0100 (byte-identical);
1342        // `--stack-layout=low` shifts it up by the reserved stack size so
1343        // const-address accesses follow the moved linear memory.
1344        bridge.set_linmem_base(config.linmem_base);
1345        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
1346        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
1347        // `optimize_full` failure: fall back to the direct selector rather
1348        // than propagating, so the function still compiles correctly.
1349        match bridge
1350            .optimize_full(wasm_ops)
1351            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
1352        {
1353            Ok(arm_ops) => {
1354                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1355                    eprintln!(
1356                        "[path-debug] optimized (ir_to_arm ok) func={}",
1357                        config
1358                            .current_func_index
1359                            .map_or("?".to_string(), |i| i.to_string())
1360                    );
1361                }
1362                (
1363                    arm_ops
1364                        .into_iter()
1365                        .map(|op| ArmInstruction {
1366                            op,
1367                            source_line: None,
1368                        })
1369                        .collect(),
1370                    bridge.spill_on_exhaust_fired(),
1371                )
1372            }
1373            // Issue #120: the optimized path declines modules it cannot lower
1374            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
1375            // back to the direct instruction selector, which handles f32 via
1376            // VFP/FPU. This is honest degradation: the function still compiles
1377            // correctly, just without IR-level optimization.
1378            Err(e) => {
1379                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1380                    eprintln!(
1381                        "[path-debug] direct (fallback: {e}) func={}",
1382                        config
1383                            .current_func_index
1384                            .map_or("?".to_string(), |i| i.to_string())
1385                    );
1386                }
1387                (select_direct()?, false)
1388            }
1389        }
1390    };
1391
1392    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
1393    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
1394    // fully tested), but it is **register-allocation-coupled**: over the current
1395    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
1396    // extends the live ranges of the mul inputs to the mla point, and the added
1397    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
1398    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
1399    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
1400    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
1401    // registers, at which point it becomes net-positive (per #272's plan and the
1402    // wiring design note). Lesson (#277): a register-pressure-affecting transform
1403    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
1404    // can default on.
1405
1406    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
1407    // LAST, after the immediate-folds — see the apply_const_cse call below
1408    // (#242). Earlier it ran here (before range-realloc and the folds), which is
1409    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
1410    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
1411    // would otherwise have absorbed the constant. Running CSE-last makes those
1412    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
1413    // redundant materializations.
1414
1415    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
1416    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
1417    // segment over the R0-R8 pool with value ranges as the allocation unit
1418    // (segment inputs + per-register live-outs pinned to their original
1419    // registers, reserved R9-R12/SP identity-assigned — each segment is
1420    // independently sound, no cross-segment liveness assumed). Renames
1421    // registers only: never adds, removes, or reorders instructions, so
1422    // labels/branch offsets are unaffected.
1423    //
1424    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
1425    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
1426    // flat_flight/controller/control_step, fires on the filter family with
1427    // zero cycle delta and a small size win, all selfchecks green on silicon.
1428    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
1429    // `SYNTH_REALLOC_STATS=1`.
1430    //
1431    // The companion dead callee-saved-save elimination (gale's "next
1432    // consequential lever", same issue comment) then shrinks the prologue
1433    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
1434    // registers the re-allocated body still touches (leaf-only,
1435    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
1436    // ~12 cycles of pure save/restore overhead removed on small leaves.
1437    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
1438    let (arm_instrs, ran_realloc) = if realloc_on {
1439        use synth_synthesis::rules::Reg;
1440        const POOL: [Reg; 9] = synth_synthesis::reg_contract::ALLOCATABLE;
1441        // VCR-DEC-001 (epic #242, the North Star's first foothold): the
1442        // SYNTH_GRAPH_ALLOC graph-colouring allocator SPIKE. When enabled it
1443        // replaces STEP 1 of the re-allocation (the segment-based
1444        // `reallocate_function`) with a whole-function Chaitin/Briggs colouring
1445        // (`graph_alloc::reallocate`) built against the SAME acceptance oracle
1446        // (`validate_segment_rewrite` trace-equality); the later dead-frame /
1447        // callee-saved-prologue / shrink passes still run on its output, so a
1448        // value it homes in R4-R8 still gets its callee-saved push (the
1449        // invariant the unconditional VCR-RA-003 validator guards). It is
1450        // BOUNDED to whole straight-line functions and DECLINES (returns None)
1451        // to the shipping `reallocate_function` on any control flow, spill, or
1452        // unmodeled op — never a hard-fail. Flag-OFF (`SYNTH_GRAPH_ALLOC` unset)
1453        // never enters this branch, so the shipping bytes are byte-identical
1454        // (the GOLDEN trick — frozen fixtures unchanged). NO default flip: the
1455        // spike ships flag-off; the flip is a later, evidence-gated step.
1456        //
1457        // VCR-VER-001 (#242): on a function the spill-on-exhaustion machinery
1458        // shaped, the terminal segment gets relaxed live-out pinning (only
1459        // R0/R1 are observable past `bx lr` at this pre-prologue position) so
1460        // the colourer can lower R4-R8-homed tails into caller-saved R0-R3 —
1461        // shrinking the `push {r4-r8,lr}` the #580 exhaustion shapes pay for.
1462        // `post_exhaust == false` selects the shipping pass bit for bit.
1463        let (out, stats) = if synth_synthesis::graph_alloc::enabled() {
1464            // RQ-60-RACOST increment 2 (#242): the colourer prices every
1465            // colour choice in REAL-ENCODER bytes. The sizer is the same
1466            // encoder family the emit loop below constructs — Thumb-2 (with
1467            // the target's FPU) or A32 — asked per candidate instruction, so
1468            // there is no hand size table to drift (#936). On the fixed-width
1469            // A32 ISA every candidate ties and the cost model degenerates to
1470            // the identity hint (zero churn).
1471            let sizing_encoder =
1472                if matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb) {
1473                    ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1474                } else {
1475                    ArmEncoder::new_arm32()
1476                };
1477            let enc = |op: &synth_synthesis::rules::ArmOp| {
1478                sizing_encoder.encode(op).ok().map(|b| b.len())
1479            };
1480            let stats_on = std::env::var("SYNTH_GRAPH_ALLOC_STATS").is_ok();
1481            match synth_synthesis::graph_alloc::reallocate(&arm_instrs, &POOL, &enc) {
1482                // SYNTH_GRAPH_ALLOC_FORCE (test seam, RQ-60-RACOST
1483                // increment 2): ship every validated candidate WITHOUT the
1484                // final-byte arbiter — the pre-arbiter behaviour. Used by
1485                // `vcr_dec_001_join_alloc_execution_differential.py` so the
1486                // unicorn-vs-wasmtime oracle executes the colourer's
1487                // proposals on EVERY reachable shape (call, i64-pair,
1488                // shift-expansion), not only the ones the arbiter lets ship —
1489                // an arbiter-declined candidate is still a candidate a future
1490                // change could promote, and the execution teeth must stay
1491                // ahead of that. Never set in production; the arbiter is the
1492                // shipping behaviour.
1493                Some(candidate)
1494                    if std::env::var("SYNTH_GRAPH_ALLOC_FORCE").is_ok_and(|v| v != "0") =>
1495                {
1496                    if stats_on {
1497                        eprintln!(
1498                            "[graph-alloc] whole-function colouring APPLIED \
1499                             (validated; FORCED — arbiter bypassed)"
1500                        );
1501                    }
1502                    (
1503                        candidate,
1504                        synth_synthesis::liveness::ReallocStats::default(),
1505                    )
1506                }
1507                Some(candidate) => {
1508                    // FINAL-BYTE ARBITER (RQ-60-RACOST increment 2). A
1509                    // colour-time cost model — however faithful its byte sizes
1510                    // — cannot price DOWNSTREAM PASS INTERACTIONS: measured on
1511                    // const_cse.wat::spill12, an identity-shaped colouring
1512                    // that merely PRESERVED the greedy allocator's register
1513                    // rotation defeated const-CSE's canonicalization and grew
1514                    // the function 148 -> 244 B (+96), with not one occurrence
1515                    // priced differently at colour time. So the candidate is
1516                    // sized through the REAL downstream pipeline
1517                    // (`finish_allocated_stream` — the exact passes the
1518                    // shipped stream runs, not a mirror) plus label resolution
1519                    // and the REAL encoder, against the shipping allocator's
1520                    // stream sized identically, and it ships only when it is
1521                    // STRICTLY smaller. A tie or a refusal keeps the shipping
1522                    // bytes — growth on an applied function is structurally
1523                    // impossible, which is exactly the wired
1524                    // vcr_dec_001_graph_alloc_differential no-growth
1525                    // assertion, promoted from a gate into a construction.
1526                    let ship = synth_synthesis::liveness::reallocate_function_post_exhaust(
1527                        &arm_instrs,
1528                        &POOL,
1529                        post_exhaust,
1530                    );
1531                    let size_of = |stream: &[synth_synthesis::ArmInstruction]| -> Option<usize> {
1532                        let finished = match finish_allocated_stream(
1533                            stream.to_vec(),
1534                            config,
1535                            post_exhaust,
1536                            true,
1537                            selected_spill_areas.borrow().as_ref(),
1538                            selected_vfp_frame_homes.borrow().as_ref(),
1539                        ) {
1540                            Ok(f) => f,
1541                            Err(e) => {
1542                                if stats_on {
1543                                    // The differential greps for the RA-003
1544                                    // hard-error string to detect a SHIPPED
1545                                    // violation; a candidate refused during
1546                                    // sizing is a decline, not a shipped
1547                                    // violation, so that marker is rewritten.
1548                                    let e = e.replace(
1549                                        "register-allocation validation FAILED",
1550                                        "register-allocation validation refused the candidate",
1551                                    );
1552                                    eprintln!(
1553                                        "[graph-alloc] arbiter: stream refused by the \
1554                                         pipeline/validators: {e}"
1555                                    );
1556                                }
1557                                return None;
1558                            }
1559                        };
1560                        let finished = if matches!(
1561                            config.target.isa,
1562                            IsaVariant::Thumb2 | IsaVariant::Thumb
1563                        ) {
1564                            resolve_label_branches(finished, &sizing_encoder).ok()?
1565                        } else {
1566                            finished
1567                        };
1568                        let mut total = 0usize;
1569                        let mut literals = 0usize;
1570                        for ins in &finished {
1571                            total += sizing_encoder.encode(&ins.op).ok()?.len();
1572                            if matches!(ins.op, synth_synthesis::rules::ArmOp::LdrSym { .. }) {
1573                                literals += 1;
1574                            }
1575                        }
1576                        if literals > 0 {
1577                            // The emit loop 4-aligns the literal pool and
1578                            // appends one word per LdrSym (no dedup — each
1579                            // site carries its own addend).
1580                            total += (4 - total % 4) % 4 + 4 * literals;
1581                        }
1582                        Some(total)
1583                    };
1584                    match (size_of(&candidate), size_of(&ship.0)) {
1585                        (Some(cand), Some(base)) if cand < base => {
1586                            if stats_on {
1587                                eprintln!(
1588                                    "[graph-alloc] whole-function colouring APPLIED \
1589                                     (validated; arbiter: {cand} B < shipping {base} B)"
1590                                );
1591                            }
1592                            (
1593                                candidate,
1594                                synth_synthesis::liveness::ReallocStats::default(),
1595                            )
1596                        }
1597                        (cand, base) => {
1598                            if stats_on {
1599                                eprintln!(
1600                                    "[graph-alloc] arbiter kept shipping bytes \
1601                                     (candidate {cand:?} B vs shipping {base:?} B) → \
1602                                     shipping reallocate_function"
1603                                );
1604                            }
1605                            ship
1606                        }
1607                    }
1608                }
1609                None => {
1610                    if stats_on {
1611                        eprintln!("[graph-alloc] DECLINED → shipping reallocate_function");
1612                    }
1613                    synth_synthesis::liveness::reallocate_function_post_exhaust(
1614                        &arm_instrs,
1615                        &POOL,
1616                        post_exhaust,
1617                    )
1618                }
1619            }
1620        } else {
1621            synth_synthesis::liveness::reallocate_function_post_exhaust(
1622                &arm_instrs,
1623                &POOL,
1624                post_exhaust,
1625            )
1626        };
1627        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
1628            eprintln!(
1629                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
1630                stats.segments,
1631                stats.reallocated,
1632                stats.declined,
1633                stats.validator_rejects,
1634                stats.needs_spill
1635            );
1636        }
1637        // VCR-VER-004 AUDIT (#242) — report-only, opt-in, never gating.
1638        //
1639        // The ABI observable-contract validator is a GATE on the flag-off
1640        // graph-colouring spike. This hook asks the same question of the
1641        // SHIPPING allocator's rewrite, so the answer is a MEASUREMENT rather
1642        // than a claim: how much of the shipping path can a value-level,
1643        // ABI-anchored check actually see today? Report-only DELIBERATELY —
1644        // making it gate here would risk a false rejection on the default
1645        // path, and the honest sequence is measure first, flip on evidence.
1646        // `SYNTH_ABI_CONTRACT_AUDIT=1` prints one verdict per function.
1647        if std::env::var_os("SYNTH_ABI_CONTRACT_AUDIT").is_some() {
1648            eprintln!(
1649                "[abi-contract-audit] {:?}",
1650                synth_synthesis::abi_contract::validate_abi_contract(&arm_instrs, &out)
1651            );
1652        }
1653        (out, true)
1654    } else {
1655        (arm_instrs, false)
1656    };
1657    // RQ-60-RACOST increment 2 (#242): every rewrite pass between the chosen
1658    // allocation and the encoder now lives in `finish_allocated_stream`, so
1659    // the SYNTH_GRAPH_ALLOC final-byte arbiter can size a candidate through
1660    // the REAL pipeline. Flag-off this is the exact pre-extraction sequence,
1661    // called once, in the same place.
1662    let arm_instrs = finish_allocated_stream(
1663        arm_instrs,
1664        config,
1665        post_exhaust,
1666        ran_realloc,
1667        selected_spill_areas.borrow().as_ref(),
1668        selected_vfp_frame_homes.borrow().as_ref(),
1669    )?;
1670
1671    // Encode to binary — use Thumb-2 for Cortex-M targets
1672    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
1673
1674    let encoder = if use_thumb2 {
1675        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1676    } else {
1677        ArmEncoder::new_arm32()
1678    };
1679
1680    // RQ-72-ISLANDS (#345): the documented opt-out. With islands disabled the
1681    // pool is emitted exactly where it always was — one block at the end — so
1682    // the two legs of `litpool_islands_345_differential.py` are a real
1683    // differential and not two names for the same path. Read HERE, above the
1684    // fixed point, because the placement decision is now part of it.
1685    let islands_disabled = std::env::var_os("SYNTH_NO_LITPOOL_ISLANDS").is_some();
1686
1687    // #202 / RQ-73-ISLANDPASS (#1331): resolve local label branches
1688    // (Bcc/B/Bhs/Blo) to byte-accurate offsets AND decide literal-island
1689    // placements, in ONE fixed point. `select_with_stack` emits branches as
1690    // label placeholders and never resolves them — without this they encode as
1691    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
1692    // sits between the branch and its target (UsageFault on real hardware).
1693    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
1694    //
1695    // `planned_islands` maps an instruction index to the number of pooled words
1696    // to flush immediately BEFORE it. The emit loop obeys it rather than
1697    // re-deciding, so the offsets branches were resolved against and the
1698    // offsets the stream actually gets are the same numbers by construction.
1699    let (arm_instrs, planned_islands) = if use_thumb2 {
1700        let (resolved, islands) =
1701            place_literal_islands_fixedpoint(arm_instrs, &encoder, !islands_disabled)?;
1702        // SC-5 (#740/#930): hard-gate every branch target onto the
1703        // instruction-start set of the final stream — both codegen paths
1704        // funnel through here. See `validate_branch_targets`.
1705        validate_branch_targets(&resolved, &encoder, !islands_disabled)?;
1706        (resolved, islands)
1707    } else {
1708        (arm_instrs, std::collections::BTreeMap::new())
1709    };
1710
1711    // #778: capture the FINAL Thumb-2 instruction stream (post label-resolution,
1712    // the exact list the encode loop below consumes) so `compile_function` can
1713    // derive the sound WCET bound. Cheap clone; frozen-safe (the WCET walk is a
1714    // pure observation and never touches `code`). Only the Thumb-2 path — the A32
1715    // (Cortex-R5) cycle model is a follow-up.
1716    let final_instrs_for_wcet: Option<Vec<synth_synthesis::ArmInstruction>> = if use_thumb2 {
1717        Some(arm_instrs.clone())
1718    } else {
1719        None
1720    };
1721
1722    let mut code = Vec::new();
1723    let mut relocations = Vec::new();
1724
1725    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
1726    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
1727    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
1728    // and patch the PC-relative offset once the pool position is known.
1729    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1730    // RQ-73-ISLANDPASS (#1331): the span guard and its decline are GONE, and
1731    // their absence is the deliverable. v0.72 computed `branch_spans` in
1732    // PRE-ISLAND coordinates and refused any placement that separated a branch
1733    // from its target, because the branch offsets had already been baked. The
1734    // fixed point above resolves branches against ISLAND-INCLUSIVE positions,
1735    // so there is no stale coordinate system left to invalidate — a spanning
1736    // placement is now correct rather than refused.
1737
1738    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1739    // here because `code.len()` immediately before `encode()` is the final
1740    // machine offset of the instruction within this function's `.text` — nothing
1741    // after the loop shifts earlier instructions (the literal pool is appended at
1742    // the end; the LDR patch below is in-place/length-preserving). Purely
1743    // additive: it does not touch `code`, so `.text` is byte-identical.
1744    let mut line_map: LineMap = Vec::new();
1745    // VCR-DEC-003 (#396): object-branch class per emitted instruction, parallel
1746    // to `line_map`. Cheap, additive, does not touch `code`.
1747    let mut branch_map: synth_core::backend::BranchMap = Vec::new();
1748
1749    for (instr_index, instr) in arm_instrs.iter().enumerate() {
1750        // ORDER IS LOAD-BEARING, and getting it wrong was a SILENT MISCOMPILE.
1751        //
1752        // Encoding and the island decision happen FIRST, before anything below
1753        // records a `code.len()`. The v0.72 round-2 cold review found the
1754        // previous order — record, then encode, then maybe insert an island —
1755        // shifting the instruction forward by the island's size while its
1756        // ALREADY-RECORDED offset stayed put. Measured, both rc=0, on objects
1757        // v0.71 had refused loudly:
1758        //
1759        //   an `R_ARM_THM_CALL` recorded at 0x1014, which after the flush holds
1760        //   the island's own `b.n +8`; the real BL sits at 0x101c. The linker
1761        //   writes a BL over the branch-over and execution falls into a pooled
1762        //   address word as instructions.
1763        //
1764        //   an `LdrSym` whose `ldr_offset` pointed INTO the island, so the
1765        //   imm12 patch landed there and the real LDR kept imm12=0 — loading
1766        //   CODE as a pointer.
1767        //
1768        // Four sites record an offset (`Bl`, `MovwSym`, `MovtSym`, `LdrSym`)
1769        // and all four were wrong the same way. Hoisting the flush above them
1770        // makes `code.len()` FINAL for this instruction at every one.
1771        //
1772        // "A pool can never precede the LDR it serves" is PRESERVED, and is now
1773        // structural rather than arithmetic: this instruction's own `LdrSym` is
1774        // pushed BELOW, so `pending_literals` cannot contain it here.
1775        // Encode BEFORE deciding whether to flush, so the island trigger below
1776        // works from this instruction's EXACT size rather than an upper bound.
1777        // An over-estimate here would flush early (merely wasteful); an
1778        // under-estimate would let the 4 KB window close and patch a wrong
1779        // `imm12` — a MISCOMPILE, which is the defect #1341/#345 exist to
1780        // prevent. Knowing the real length removes the estimate entirely.
1781        let encoded = encoder
1782            .encode(&instr.op)
1783            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1784
1785        // RQ-72-ISLANDS (#345): flush the pool INLINE, before the window closes.
1786        //
1787        // WHY INLINE AND NOT A POST-PASS THAT INSERTS: `line_map` and
1788        // `branch_map` are (offset, _) PAIRS captured as `code.len()` just
1789        // below, so appending here leaves every later pair correct, while
1790        // inserting into an already-built `code` would silently desynchronise
1791        // all of them — and `.text` byte-identity on modules that need no
1792        // island would not notice.
1793        //
1794        // If `instr` is itself the `LdrSym` just pushed, its `ldr_offset`
1795        // equals `code.len()`, so the computed distance is ~0 and this cannot
1796        // fire before the LDR it serves. That is the ordering that would
1797        // otherwise place a pool BEFORE its own load.
1798        // RQ-73-ISLANDPASS (#1331): OBEY the plan, do not re-derive it. The
1799        // flush rule now lives in `island_walk`, which is also what the branch
1800        // offsets were resolved against. Deciding again here would be a second
1801        // source of truth for "where does a pool go", and the two could
1802        // disagree by exactly the amount that mis-targets every branch over the
1803        // placement — the v0.72 defect, reintroduced one layer up.
1804        if let Some(&planned_n) = planned_islands.get(&instr_index) {
1805            // DRIFT GUARD, and it is the reason obeying a plan is safe. The
1806            // walk predicted this flush would carry `planned_n` words; if the
1807            // emit loop has a different number pending, the two walks have
1808            // diverged and every offset resolved against the prediction is
1809            // wrong. Refuse rather than emit a stream nobody checked.
1810            if pending_literals.len() != planned_n {
1811                return Err(format!(
1812                    "literal-island plan drift (#1331): the fixed point placed an \
1813                     island of {} pooled word(s) before instruction {}, but {} \
1814                     literal(s) are pending there. Branch offsets were resolved \
1815                     against the plan, so emitting this stream would mis-target \
1816                     every branch spanning the placement.",
1817                    planned_n,
1818                    instr_index,
1819                    pending_literals.len()
1820                ));
1821            }
1822            emit_literal_pool(
1823                &mut code,
1824                &mut relocations,
1825                &pending_literals,
1826                Some(&encoder),
1827            )?;
1828            pending_literals.clear();
1829        }
1830
1831        // Record a relocation for every BL: the encoder emits `bl #0` and
1832        // relies on a relocation to patch the target. This covers BOTH import
1833        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1834        // (`func_N`, defined in this object). Previously only `__meld_*` was
1835        // recorded, so internal `BL func_N` calls were left as unpatched
1836        // `bl #0` placeholders branching to a garbage address (#167).
1837        if let ArmOp::Bl { label } = &instr.op {
1838            // #1040: the relocation type is ISA-STATE-dependent and this is the
1839            // only site that knows the state. An A32 (Cortex-R) `bl` is
1840            // R_ARM_CALL (28); a Thumb `bl` is R_ARM_THM_CALL (10). Emitting
1841            // the Thumb type for an A32 word made any consumer that trusts the
1842            // declared type patch Thumb halfwords into an ARM-state
1843            // instruction. Decided here rather than in the ELF emitter, where
1844            // `config.target` is no longer in scope and the ISA would have to
1845            // be re-derived — the shape that produced the bug.
1846            let kind = if config.target.isa == synth_core::target::IsaVariant::Arm32 {
1847                synth_core::backend::RelocKind::ArmCall
1848            } else {
1849                synth_core::backend::RelocKind::ThmCall
1850            };
1851            relocations.push(CodeRelocation {
1852                offset: code.len() as u32,
1853                symbol: label.clone(),
1854                kind,
1855            });
1856        }
1857        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1858        // addressing). The encoder writes the addend in place; record the matching
1859        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1860        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1861            relocations.push(CodeRelocation {
1862                offset: code.len() as u32,
1863                symbol: symbol.clone(),
1864                kind: synth_core::backend::RelocKind::MovwAbs,
1865            });
1866        }
1867        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1868            relocations.push(CodeRelocation {
1869                offset: code.len() as u32,
1870                symbol: symbol.clone(),
1871                kind: synth_core::backend::RelocKind::MovtAbs,
1872            });
1873        }
1874        // #345: defer the literal-pool word + reloc + offset patch to the
1875        // post-loop pass (the pool address is not yet known).
1876        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1877            pending_literals.push(PendingLiteral {
1878                ldr_offset: code.len() as u32,
1879                symbol: symbol.clone(),
1880                addend: *addend,
1881            });
1882        }
1883
1884        // The machine offset of this instruction is the current code length,
1885        // captured before the bytes are appended (and AFTER any island above,
1886        // so the recorded offset is where the instruction really lands).
1887        line_map.push((code.len() as u32, instr.source_line));
1888        branch_map.push((code.len() as u32, classify_arm_branch(&instr.op)));
1889
1890        code.extend_from_slice(&encoded);
1891    }
1892
1893    // #345: place any REMAINING literals at the end of this function's `.text`.
1894    // Gated on there being at least one un-flushed `LdrSym` — functions without
1895    // one are byte-identical to before (no trailing padding, so downstream
1896    // `func_offsets` are unchanged and the frozen differential fixtures stay
1897    // bit-for-bit equal). No branch is emitted: these bytes sit past the final
1898    // return and are never executed.
1899    if !pending_literals.is_empty() {
1900        if !use_thumb2 {
1901            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1902        }
1903        // RQ-73-ISLANDPASS (#1331): the `island_declined_for_branch` wrapper
1904        // that used to sit here is GONE. It explained that a placement had been
1905        // refused because it fell between a branch and its target, and ended
1906        // "serving this shape needs branch resolution and island placement in
1907        // one fixed point". That fixed point now exists, so the refusal it
1908        // described is unreachable and an explanation of it would be a false
1909        // statement. What remains is the genuine out-of-range case: a pool that
1910        // no placement can bring within the 12-bit window.
1911        emit_literal_pool(&mut code, &mut relocations, &pending_literals, None)?;
1912    }
1913
1914    // RQ-73-ISLANDPASS (#1331): every planned island must have been emitted.
1915    // The plan is what branch offsets were resolved against, so a placement the
1916    // emit loop skipped leaves every branch over it pointing past bytes that
1917    // were never written. `instr_index` only ever advances, so a key beyond the
1918    // last instruction would be silently ignored without this.
1919    if let Some((&last, _)) = planned_islands.iter().next_back()
1920        && last >= arm_instrs.len()
1921    {
1922        return Err(format!(
1923            "literal-island plan drift (#1331): an island was planned before \
1924                 instruction {}, but the stream has only {} instruction(s).",
1925            last,
1926            arm_instrs.len()
1927        ));
1928    }
1929
1930    Ok((
1931        code,
1932        relocations,
1933        line_map,
1934        branch_map,
1935        final_instrs_for_wcet,
1936    ))
1937}
1938
1939/// RQ-60-RACOST increment 2 (#242): every rewrite pass between a CHOSEN
1940/// register allocation and the encoder, as ONE reusable sequence.
1941///
1942/// Extracted VERBATIM from `compile_wasm_to_arm` (pure code motion) so the
1943/// `SYNTH_GRAPH_ALLOC` final-byte arbiter can size a candidate allocation
1944/// through the REAL downstream pipeline — the same passes, in the same order,
1945/// reading the same flags — rather than through a hand-mirrored predicate of
1946/// them (the #936 drift class: a hand mirror of the encoder's offset-fold
1947/// threshold was UNSOUND at authoring; a hand mirror of eleven rewrite passes
1948/// would be worse). Flag-off behaviour is byte-identical: the shipping path
1949/// calls this exactly once, on the same stream, in the same place it always
1950/// ran.
1951///
1952/// `ran_realloc` selects the historical branch: the dead-frame /
1953/// callee-saved-prologue / shrink trio runs only downstream of the range
1954/// re-allocation lever (`SYNTH_RANGE_REALLOC` on), exactly as before the
1955/// extraction. Diagnostics inside (SYNTH_FUSE_STATS, SYNTH_SHADOW_ALLOC,
1956/// SYNTH_SPILL_REPORT) print once per CALL, so an arbiter sizing run repeats
1957/// them — measurement noise under two opt-in flags, never a byte change.
1958fn finish_allocated_stream(
1959    arm_instrs: Vec<synth_synthesis::ArmInstruction>,
1960    config: &CompileConfig,
1961    post_exhaust: bool,
1962    ran_realloc: bool,
1963    // #1321: `(frame_size, areas)` recorded by the direct selector for the
1964    // attempt that produced this stream — the frame regions that are genuinely
1965    // allocator SPILL slots. Used to scope VCR-RA-003's #331 check, and ONLY
1966    // after `frame_size` is re-proven against this stream (see the use site).
1967    // `None` on the optimized path and whenever no area was reserved.
1968    recorded_spill_areas: Option<&(i32, Vec<std::ops::Range<i32>>)>,
1969    // RQ-71-VFPALIAS (#881/#1069): the permanent VFP frame homes from that same
1970    // attempt, proven against this stream by the identical `frame_size` test.
1971    // `None` on the optimized path and whenever selection granted no home.
1972    recorded_vfp_frame_homes: Option<&(i32, Vec<i32>)>,
1973) -> Result<Vec<synth_synthesis::ArmInstruction>, String> {
1974    let arm_instrs = if ran_realloc {
1975        let out = arm_instrs;
1976        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
1977        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
1978        // that promotion homed in registers, never accessed). Removing it saves
1979        // the two instructions AND restores the SP-untouched precondition that
1980        // `shrink_callee_saved_saves` requires — so it must run FIRST.
1981        // DEFAULT-ON (#242 flag audit flip-wave, #592 audit item): evidence
1982        // basis was the 2-path × repro-corpus sweep — 0 functions grow, 58
1983        // shrink (flight_seam controller_step 250→242 −8 / filter_step 180→168
1984        // −12, native_pointer frame_roundtrip 46→34 −12), locked by the
1985        // `dead_frame_elim_no_grow_corpus_242` cargo gate; execution
1986        // differentials re-run green on the new default bytes BEFORE the
1987        // frozen ARM anchors were re-pinned (leaf_dead_frame, flight_seam,
1988        // frame_slot_dce — see the flip PR). Escape hatch:
1989        // `SYNTH_DEAD_FRAME_ELIM=0` opts out and restores the pre-flip bytes
1990        // (CI-gated in `frozen_codegen_bytes.rs`).
1991        let out = if !std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok_and(|v| v == "0") {
1992            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
1993        } else {
1994            out
1995        };
1996        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
1997        // promoted locals but emits no prologue, silently clobbering a caller's
1998        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
1999        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
2000        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
2001        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
2002        // (next) then trims it to the used set. No-op on the direct path (it
2003        // already has its own prologue) and on callee-saved-free leaves.
2004        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
2005        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
2006    } else {
2007        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
2008        // must preserve the callee-saved registers it clobbers (#490). No shrink
2009        // (it is coupled to the realloc lever), so the conservative full save
2010        // stays — correct, just not minimised in this debug configuration.
2011        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
2012    };
2013    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
2014    // the selected stream and LOG what it finds — without changing a single
2015    // emitted byte. This is the measure-only bridge between the built analysis
2016    // layer and the eventual virtual-register wiring: it shows, per real
2017    // function, whether the allocator can colour it within the R0–R8 pool and
2018    // how much const-CSE / rematerialization headroom exists (#209). Enable with
2019    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
2020    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
2021        use synth_synthesis::liveness::{
2022            AllocationOutcome, allocate_function, function_peak_pressure,
2023        };
2024        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
2025        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
2026        let precolored = std::collections::BTreeMap::from([
2027            (synth_synthesis::rules::Reg::R9, 9usize),
2028            (synth_synthesis::rules::Reg::R10, 10),
2029            (synth_synthesis::rules::Reg::R11, 11),
2030            (synth_synthesis::rules::Reg::R12, 12),
2031        ]);
2032        // True VALUE pressure (one node per value, not per reused physical reg):
2033        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
2034        // function fits once virtually allocated.
2035        let peak = function_peak_pressure(&arm_instrs);
2036        match allocate_function(&arm_instrs, 9, &precolored) {
2037            AllocationOutcome::Allocated {
2038                remat_opportunities,
2039                coloring,
2040            } => eprintln!(
2041                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
2042                coloring.len(),
2043                peak,
2044                remat_opportunities
2045            ),
2046            AllocationOutcome::NeedsSpill(s) => eprintln!(
2047                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
2048                s, peak
2049            ),
2050            AllocationOutcome::Declined => {
2051                eprintln!(
2052                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
2053                )
2054            }
2055        }
2056    }
2057
2058    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
2059    // lowers a `select` whose condition is a comparison to a *materialize then
2060    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
2061    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
2062    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
2063    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
2064    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
2065    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
2066    //
2067    // Run LATE: after range re-allocation (so the dead-D proof sees final register
2068    // identities) and before encode. Removal-only + rename-only ⇒ no spill
2069    // regression and labels/branch offsets are unaffected. Each fusion is proven
2070    // sound (flags reused only when nothing clobbers them in the window; the
2071    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
2072    //
2073    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
2074    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
2075    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
2076    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
2077    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
2078    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
2079    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
2080    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
2081    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
2082    // check is a tracked post-ship follow-up (gale owns it).
2083    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
2084        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
2085        // the extra `two_move` count is diagnostic only (the fusion census /
2086        // blast-radius datum — #7 made that arm reachable).
2087        let (out, fused, two_move) =
2088            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
2089        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2090            let in_place = fused - two_move;
2091            eprintln!(
2092                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
2093                 ({two_move} two-move, {in_place} in-place)"
2094            );
2095        }
2096        out
2097    } else {
2098        arm_instrs
2099    };
2100
2101    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
2102    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
2103    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
2104    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
2105    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
2106    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
2107    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
2108    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
2109    // execution differential — the same gated path cmp→select took to default-on in
2110    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
2111    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
2112    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
2113    let arm_instrs = if stack_fwd {
2114        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
2115        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2116            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
2117        }
2118        out
2119    } else {
2120        arm_instrs
2121    };
2122
2123    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
2124    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
2125    // them is a dead store — its slot is never loaded again. Remove it. Pairs
2126    // with (and only pays after) stack-reload forwarding, so it shares the flag.
2127    let arm_instrs = if stack_fwd {
2128        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
2129        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2130            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
2131        }
2132        out
2133    } else {
2134        arm_instrs
2135    };
2136
2137    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
2138    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
2139    // `forward_stack_reloads` (above) forwards only from a spill store's
2140    // SOURCE register, so when register pressure clobbers that source its
2141    // reloads survive; this stage tracks which registers provably still hold
2142    // a frame slot's value (through earlier reloads and reg-reg moves) and
2143    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
2144    // already holds the value). Stage 2 (the Belady re-choice): where NO
2145    // register still holds the value — the genuine-spill case, flat_flight's
2146    // peak-11 hot segment — the value was usually evicted while a dead
2147    // register existed; the clobbering def(s) are renamed onto a provably-dead
2148    // register (`spill_rechoice_segment`) so the value stays resident and the
2149    // reload dissolves outright. A dissolved reload can leave the feeding
2150    // store dead, so the frame-slot DCE sweep runs once more behind the same
2151    // flag. Per-segment commit gates: executable same-value-flow trace
2152    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
2153    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
2154    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
2155    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
2156    // see other segments); `eliminate_unread_frame_stores` walks the whole
2157    // function (labels/branches/loops, SP-displacement tracked) and drops a
2158    // store whose slot NO reachable instruction can read — flat_flight's two
2159    // surviving stores (#576), completing Belady's 0-load side with a 0-store
2160    // side. Same flag: the three stages are one lever, flipped together.
2161    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
2162    // Belady spilling ships by default. Evidence basis for the flip: three
2163    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
2164    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
2165    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
2166    // guards, and the unicorn-vs-wasmtime execution differentials re-run
2167    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
2168    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
2169    // control_step_decide vs wasmtime; control_step's .text is byte-identical
2170    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
2171    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
2172    // and restores the pre-flip bytes (CI-gated by
2173    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
2174    // other value (or unset) runs the pass.
2175    // VCR-VER-001 post-exhaustion extensions (#242, the PR #659 verdict): with
2176    // `SYNTH_SPILL_ON_EXHAUST` active the #580 allocation-time Belady spill
2177    // keeps exhausted functions on the optimized path, and its slots present
2178    // shapes the shipping pass structurally cannot fire on (fresh-monotonic
2179    // slots defeat the overwrite-only DCE; the eviction store's source is
2180    // redefined immediately, defeating store→reload forwarding; R2/R3 are
2181    // never touched again, so the rename-target deadness proof declines them).
2182    // `post_exhaust` (bridge-scoped, see above) enables const
2183    // rematerialization of spilled constants, R2/R3 exit-dead rename targets,
2184    // and per-pair pressure commit — see `apply_spill_realloc_post_exhaust`.
2185    // Flag off (the default): `false` selects the shipping behavior bit for
2186    // bit.
2187    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
2188        let (out, n) =
2189            synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&arm_instrs, post_exhaust);
2190        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
2191        let (mut out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
2192        let (mut tn, mut td, mut tu) = (n, d, u);
2193        // Post-exhaustion only: iterate the triple to a bounded fixpoint. Each
2194        // dissolved spill pair frees registers and removes stores, exposing
2195        // rename windows and holder chains the previous iteration could not
2196        // prove — the allocation-time Belady slots (#580) routinely need two
2197        // or three rounds where the shipping single round suffices for the
2198        // default path's slots. Every iteration is individually gate-proven
2199        // (value-trace equality, pool pressure, strict shrink), so iterating
2200        // composes soundly; the bound keeps compile time deterministic.
2201        if post_exhaust {
2202            let mut progress = n + d + u > 0;
2203            for _ in 0..3 {
2204                if !progress {
2205                    break;
2206                }
2207                let (o, n) =
2208                    synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&out, true);
2209                let (o, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&o);
2210                let (o, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&o);
2211                progress = n + d + u > 0;
2212                (tn, td, tu) = (tn + n, td + d, tu + u);
2213                out = o;
2214            }
2215            // The cleanup can leave the spill frame with zero surviving
2216            // accesses (every reload rematerialized/dissolved, every store
2217            // swept) — the balanced `sub sp,#K`/`add sp,#K` is then pure
2218            // overhead. `elide_dead_frame` proves that and removes the pair;
2219            // its early run (post-realloc) could not, because the spill
2220            // traffic was still in the stream at that point.
2221            out = synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out);
2222        }
2223        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2224            eprintln!(
2225                "[spill-realloc] {tn} reload(s) forwarded/eliminated, {td} newly-dead frame store(s) removed, {tu} unread-slot store(s) removed"
2226            );
2227        }
2228        out
2229    } else {
2230        arm_instrs
2231    };
2232
2233    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
2234    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
2235    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
2236    // instruction, −1 live register. Removal-only (offset-neutral before branch
2237    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
2238    // bit-identical results + a net cycle win on the dissolved hot path (−2
2239    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
2240    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
2241        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
2242        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2243            eprintln!(
2244                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
2245            );
2246        }
2247        out
2248    } else {
2249        arm_instrs
2250    };
2251
2252    // #686: elide the #682 mod-32 shift-amount mask (`and r12,rK,#31` before
2253    // every register-controlled i32 shl/shr) when the amount is STATICALLY
2254    // provable < 32 — a const amount folds to the immediate-shift form
2255    // (reduced mod 32, so >= 32 shrinks too), and an already-masked amount
2256    // (`rK = rX & c`, c < 32) drops the redundant re-mask. gale measured the
2257    // unconditional mask at ~12% cyc/call (+14 B) on gust_mix, whose Q8
2258    // fixed-point shifts are all constants (#686). The mask stays wherever
2259    // the bound is unproven — elision is an optimization, the mask is the
2260    // sound default (`liveness::elide_shift_masks` has the proof
2261    // obligations). Runs after `fold_immediate_shifts` (whose movw→shift
2262    // window the #682 mask intercepts, so it declines every masked const
2263    // shift) and before branch resolution (removal/rewrite-only ⇒
2264    // offset-neutral).
2265    //
2266    // DEFAULT-ON since v0.50.1 (opt-out via `SYNTH_SHIFT_MASK_ELIDE=0`; #846).
2267    // gale's gpio-thin driver regressed +44 B / +9% on synth 0.49 — its pin
2268    // bit-arithmetic (`pin & 31` then a register shift) emits the source
2269    // `and rN,#0x1f` IMMEDIATELY followed by the #682 mod-32 re-mask
2270    // `and r12,rN,#0x1f`; the second is provably redundant (Pattern B: an
2271    // operand produced by `and X,#c`, c<32, is already in [0,31]), so the
2272    // pass drops it. Flipping default-on is a deliberate byte-changing
2273    // refreeze: the elision also moves the frozen anchors (const-amount
2274    // shifts fold back to the immediate form) — control_step −20 B,
2275    // flight_seam −166 B, flight_seam_flat −168 B — all size DECREASES with
2276    // the mask soundly kept for every unproven amount. All differentials were
2277    // re-run on the new bytes and the goldens re-pinned (see #846 PR /
2278    // `frozen_codegen_bytes.rs`). `SYNTH_SHIFT_MASK_ELIDE=0` restores the
2279    // pre-flip bytes (opt-out gate in `shift_mask_elide_686.rs`).
2280    let arm_instrs = if std::env::var("SYNTH_SHIFT_MASK_ELIDE").is_ok_and(|v| v == "0") {
2281        arm_instrs
2282    } else {
2283        let (out, elisions) = synth_synthesis::liveness::elide_shift_masks(&arm_instrs);
2284        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2285            eprintln!(
2286                "[shift-mask-elide] {elisions} provably-<32 shift-amount mask(s) elided (#686)"
2287            );
2288        }
2289        out
2290    };
2291
2292    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
2293    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
2294    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
2295    // modified immediates so the selector materializes them into a register; the
2296    // dedicated zero-extend expresses the same masking inline. Removal-only +
2297    // rewrite-in-place (offset-neutral). DEFAULT-ON (#242 flag audit flip-wave,
2298    // #592 audit item): evidence basis was the 2-path × repro-corpus sweep —
2299    // 0 functions grow, 13 shrink (control_step 300→294 −6, gust_mix 38→32 −6,
2300    // uxth_fold pack 36→24 −12), locked by the `uxth_fold_no_grow_corpus_242`
2301    // cargo gate; execution differentials re-run green on the new default
2302    // bytes BEFORE the frozen ARM anchors were re-pinned (uxth_fold,
2303    // control_step — see the flip PR). Escape hatch: `SYNTH_UXTH_FOLD=0` opts
2304    // out and restores the pre-flip bytes (CI-gated in
2305    // `frozen_codegen_bytes.rs`).
2306    let arm_instrs = if !std::env::var("SYNTH_UXTH_FOLD").is_ok_and(|v| v == "0") {
2307        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
2308        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2309            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
2310        }
2311        out
2312    } else {
2313        arm_instrs
2314    };
2315
2316    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
2317    // `movw`/`mov #imm` that re-materializes a constant already resident in
2318    // another register and retargets the reads — every rewrite proven by the
2319    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
2320    // range-realloc, but BEFORE branch resolution/encoding (it removes
2321    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
2322    // fix: the folds have already absorbed every foldable constant, so CSE can no
2323    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
2324    // size-guards each segment via the byte-estimator — it commits a segment's
2325    // rewrites only if they do not grow its estimated size — so a retarget that
2326    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
2327    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
2328    // template): const-CSE ships by default. The flip prerequisites recorded in
2329    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
2330    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
2331    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
2332    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
2333    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
2334    // 236→148 B), total −536 B — and the execution differentials re-run green
2335    // on the new default bytes BEFORE the frozen goldens were re-pinned
2336    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
2337    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
2338    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
2339    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
2340    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
2341    //
2342    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
2343    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
2344    // cannot be classified as address-vs-data (a retargeted read may be a
2345    // memory-access base carrying a per-use immediate offset), so the
2346    // conservative stance for statically-unknown addressing is to decline every
2347    // aliasing rewrite — each constant is re-materialized at each occurrence,
2348    // the documented volatile contract (`CompileConfig::volatile_segments`).
2349    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
2350        && config.volatile_segments.is_empty()
2351    {
2352        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
2353        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2354            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
2355        }
2356        out
2357    } else {
2358        arm_instrs
2359    };
2360
2361    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
2362    // Per straight-line segment, the frame-slot traffic actually emitted vs the
2363    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
2364    // pool would need — the measured headroom for the full spill-choice rewrite.
2365    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
2366    // reports the greedy baseline and a flag-on run reports what remains.
2367    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
2368        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
2369            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
2370                eprintln!(
2371                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
2372                    seg.start,
2373                    seg.len,
2374                    seg.peak_pressure,
2375                    seg.actual_reloads,
2376                    seg.actual_spill_stores,
2377                    seg.belady_reloads,
2378                    seg.belady_spill_stores
2379                );
2380            }
2381        }
2382    }
2383
2384    // ISA feature gate: validate that all generated instructions are supported
2385    // by the target. This catches FPU instructions on no-FPU targets, double-precision
2386    // instructions on single-precision targets, etc.
2387    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
2388        .map_err(|e| format!("ISA validation failed: {}", e))?;
2389
2390    // VCR-RA-003 (epic #242): UNCONDITIONAL per-compilation register-allocation
2391    // validation. The register allocator is the last major unverified codegen
2392    // component; this whole-function checker proves — by construction, on the
2393    // EXACT emitted stream about to be encoded — that the allocation preserves
2394    // FOUR invariants whose reference lives in the stream (or the ABI): (1)
2395    // callee-saved preservation (#490), (2) spill-slot non-aliasing (#331), and
2396    // — PHASE 2 (#49), extending past straight-line — (3) caller-saved
2397    // preservation across calls (a value in R2/R3/R12 live across a `bl` the
2398    // AAPCS boundary destroys), and (4) value availability across control-flow
2399    // joins (a live-in to a join must be defined on every incoming edge). It runs
2400    // on every ARM compile in the DEFAULT shipping build (NOT behind
2401    // `--features verify`; a verify-gated check would be dormant in exactly the
2402    // build that ships — the #757 / VCR-VER-003 lesson) and hard-errors the
2403    // compile on a VIOLATION. A `NotAttempted` verdict (the join check declines
2404    // on an unmodeled-CF function: numeric branch, `BrTable`, etc.) is NON-FATAL
2405    // — the compile proceeds; the other three invariants were still checked and
2406    // held. This is the decline>guess doctrine applied to the checker itself: it
2407    // never claims join coherence it cannot prove, but it also never blocks a
2408    // correct compile for a construct it simply doesn't model yet. Frozen-safe:
2409    // it emits nothing, so `.text` is byte-identical (proven by the frozen suite).
2410    // #1321: scope the #331 spill-slot check to the frame regions the allocator
2411    // actually hands out as spill slots — but ONLY while the record provably
2412    // still describes THIS stream. Between selection and here the stream passes
2413    // through re-allocation, dead-frame elimination and prologue shrink, any of
2414    // which can re-lay or remove the frame. A stale area list would narrow the
2415    // check over the wrong offsets — the silent weakening this lane exists to
2416    // avoid — so the areas are used only if the final stream still allocates
2417    // EXACTLY the frame they were computed for. On any mismatch (re-laid frame,
2418    // eliminated frame, optimized path, no record) we pass `None` and every
2419    // `[sp,#N]` offset is policed, bit for bit as before. The fix can go stale;
2420    // it cannot go wrong.
2421    // The staleness proof, shared by both records: this stream still allocates
2422    // EXACTLY the frame they were computed for. Factored into one closure so the
2423    // spill areas and the VFP frame homes cannot drift apart — they come from
2424    // the same selection and must stand or fall together.
2425    let frame_still_matches = |frame_size: &i32| {
2426        arm_instrs.iter().any(|ins| {
2427            matches!(
2428                &ins.op,
2429                synth_synthesis::rules::ArmOp::Sub {
2430                    rd: synth_synthesis::rules::Reg::SP,
2431                    rn: synth_synthesis::rules::Reg::SP,
2432                    op2: synth_synthesis::rules::Operand2::Imm(n),
2433                } if n == frame_size
2434            )
2435        })
2436    };
2437    let spill_areas: Option<&[std::ops::Range<i32>]> = match recorded_spill_areas {
2438        Some((frame_size, areas)) if frame_still_matches(frame_size) => Some(areas.as_slice()),
2439        _ => None,
2440    };
2441    // RQ-71-VFPALIAS (#881/#1069): same gate, same failure direction. A stale or
2442    // absent home set means the #881 twin polices every VFP `[sp,#N]` offset,
2443    // which is what it did before this narrowing existed.
2444    let vfp_frame_homes: Option<&[i32]> = match recorded_vfp_frame_homes {
2445        Some((frame_size, halves)) if frame_still_matches(frame_size) => Some(halves.as_slice()),
2446        _ => None,
2447    };
2448    match synth_synthesis::liveness::validate_final_allocation_in_areas_with_vfp_homes(
2449        &arm_instrs,
2450        spill_areas,
2451        vfp_frame_homes,
2452    ) {
2453        synth_synthesis::liveness::RaFinalVerdict::Violation(v) => {
2454            return Err(format!(
2455                "VCR-RA-003: register-allocation validation FAILED — {v:?}. \
2456                 The emitted stream violates a register-allocation invariant \
2457                 (callee-saved preservation #490 / spill-slot non-aliasing #331 \
2458                 / caller-saved-across-call / join-value-availability / the #881 \
2459                 VFP twins); this is a \
2460                 compiler bug, not a program error. Refusing to emit a \
2461                 miscompiled object."
2462            ));
2463        }
2464        // Loud honest decline (join reasoning skipped for an unmodeled-CF
2465        // function). Non-fatal — the straight-line / callee-saved / across-call
2466        // invariants still ran and held; only the across-JOIN availability
2467        // reasoning is skipped. Since the #819 redo the optimized path's
2468        // pre-resolved NUMERIC branches are modeled too (build_join_cfg_numeric
2469        // + the PRESERVED entry-availability discriminator), so this fires only
2470        // on genuinely unmodeled shapes: BrTable, computed Bx, mixed
2471        // label+numeric streams, off-boundary numeric targets.
2472        // Surfaced only under `SYNTH_RA003_VERBOSE` so a production compile stays
2473        // quiet: emitting it unconditionally would print on every branchy
2474        // optimized-path compile (new stderr noise phase 1 never produced), yet
2475        // it must remain observable on demand for the honest-scope audit.
2476        synth_synthesis::liveness::RaFinalVerdict::NotAttempted { reason } => {
2477            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2478                eprintln!(
2479                    "VCR-RA-003: across-join validation NOT ATTEMPTED ({reason}) — \
2480                     straight-line / callee-saved / across-call invariants held; \
2481                     join-availability reasoning declined on this control-flow shape."
2482                );
2483            }
2484        }
2485        synth_synthesis::liveness::RaFinalVerdict::Consistent => {
2486            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2487                eprintln!("VCR-RA-003: Consistent");
2488            }
2489        }
2490    }
2491    Ok(arm_instrs)
2492}
2493
2494/// VCR-DEC-003 (#396): classify one emitted `ArmOp` into its object-level
2495/// control-flow role for the `synth-provenance-v1` map. Conditional branches are
2496/// the object decision points MC/DC must reconcile; `SelectMove` is the folded
2497/// (IT-block) predicated form the cmp→select fuse produces — a decision with no
2498/// branch.
2499fn classify_arm_branch(op: &ArmOp) -> synth_core::backend::BranchClass {
2500    use synth_core::backend::BranchClass;
2501    match op {
2502        ArmOp::Bcc { .. } | ArmOp::Bhs { .. } | ArmOp::Blo { .. } | ArmOp::BCondOffset { .. } => {
2503            BranchClass::CondBranch
2504        }
2505        ArmOp::B { .. } | ArmOp::BOffset { .. } => BranchClass::UncondBranch,
2506        ArmOp::SelectMove { .. } => BranchClass::Predicated,
2507        _ => BranchClass::Other,
2508    }
2509}
2510
2511/// The branch-over for a literal island at `at`, and the alignment padding
2512/// after it. SINGLE SOURCE for the island's byte length (#1331).
2513///
2514/// `emit_literal_pool` needs the BYTES; `island_walk` needs the LENGTH before
2515/// any bytes exist. Both call this, so the "how big is an island" question has
2516/// exactly one answer. A second copy is what the v0.72 header means by drift.
2517///
2518/// The branch's own size decides the distance it must cover, and the distance
2519/// decides the size (B.N is 2 bytes, B.W is 4), so this iterates to its own
2520/// small fixed point rather than assuming one.
2521fn island_branch_over(at: usize, n: usize, enc: &ArmEncoder) -> Result<(Vec<u8>, usize), String> {
2522    let mut branch_len = 2usize;
2523    loop {
2524        let pad = (4 - ((at + branch_len) % 4)) % 4;
2525        let skip = branch_len + pad + 4 * n;
2526        // `BOffset` takes the halfword displacement (target - branch - 4)/2.
2527        // `at` is even at any Thumb instruction boundary and `branch_len` is
2528        // even, so `pad` is even and `skip` is even.
2529        let off = ((skip as i32) - 4) / 2;
2530        let e = enc
2531            .encode(&ArmOp::BOffset { offset: off })
2532            .map_err(|x| format!("island branch encoding failed: {}", x))?;
2533        if e.len() == branch_len {
2534            return Ok((e, pad));
2535        }
2536        branch_len = e.len();
2537        if branch_len > 4 {
2538            return Err(format!(
2539                "literal-pool island (#345): branch over {} pooled word(s) \
2540                 would need {} bytes, which is not a Thumb-2 B encoding",
2541                n, branch_len
2542            ));
2543        }
2544    }
2545}
2546
2547/// One left-to-right walk that decides island placements AND the byte position
2548/// of every instruction, in the SAME coordinates (#1331).
2549///
2550/// An island only moves code that comes AFTER it, so placements can be decided
2551/// in a single pass: by the time this reaches instruction `i`, every island
2552/// before it is already counted in `pos`. That is why the outer fixed point
2553/// below iterates over BRANCH SIZES only — the island decision is not itself
2554/// circular, the branch encodings are.
2555///
2556/// The flush rule is the one the emit loop used to apply inline, moved here
2557/// unchanged: if the LAST pooled word would fall outside the 12-bit unsigned
2558/// `LDR(literal)` window measured from the FIRST pending LDR, the pool must be
2559/// flushed before this instruction.
2560///
2561/// Returns (position of each instruction, instruction index -> pooled words
2562/// flushed immediately before it).
2563fn island_walk(
2564    instrs: &[ArmInstruction],
2565    encoder: &ArmEncoder,
2566    enabled: bool,
2567) -> Result<(Vec<usize>, std::collections::BTreeMap<usize, usize>), String> {
2568    let mut positions = Vec::with_capacity(instrs.len());
2569    let mut islands = std::collections::BTreeMap::new();
2570    let mut pending: Vec<usize> = Vec::new();
2571    let mut pos: usize = 0;
2572
2573    for (i, instr) in instrs.iter().enumerate() {
2574        let size = encoder
2575            .encode(&instr.op)
2576            .map_err(|e| format!("island-walk size probe failed: {}", e))?
2577            .len();
2578
2579        if enabled && !pending.is_empty() {
2580            // Worst case if we DON'T flush now: this instruction lands, then a
2581            // branch (<= 4 B) and alignment (<= 3 B) precede the words. Same
2582            // arithmetic the emit loop used, in the same coordinates.
2583            let start = pos + size + 4;
2584            let pad = (4 - (start % 4)) % 4;
2585            let last_word = (start + pad + 4 * (pending.len() - 1)) as u32;
2586            let aligned_pc = ((pending[0] + 4) & !3usize) as u32;
2587            if last_word.saturating_sub(aligned_pc) > 0xFFF {
2588                let n = pending.len();
2589                let (b, pad2) = island_branch_over(pos, n, encoder)?;
2590                islands.insert(i, n);
2591                pos += b.len() + pad2 + 4 * n;
2592                pending.clear();
2593            }
2594        }
2595
2596        positions.push(pos);
2597        // The LDR this instruction IS registers only AFTER the decision above,
2598        // exactly as the emit loop pushes it below the flush. That ordering is
2599        // what makes "a pool can never precede the LDR it serves" structural.
2600        if matches!(instr.op, ArmOp::LdrSym { .. }) {
2601            pending.push(pos);
2602        }
2603        pos += size;
2604    }
2605    Ok((positions, islands))
2606}
2607
2608/// RQ-73-ISLANDPASS (#1331): ONE fixed point over branch offsets AND literal
2609/// island placement.
2610///
2611/// THE DEFECT THIS CLOSES. Branch offsets used to be byte-resolved BEFORE the
2612/// encode loop, and islands were then inserted DURING it. An island between a
2613/// branch and its target moves the target and not the branch, by exactly the
2614/// island's size. v0.72 could only REFUSE such placements (loudly, which was
2615/// right) — so a 4 KB+ function with any control flow spanning its pool did not
2616/// compile at all. That is cpetig's #1331.
2617///
2618/// WHY IT NEEDS A FIXED POINT AND NOT AN ADJUSTMENT. Islands change sizes,
2619/// which change positions, which change which branches need 32-bit encodings,
2620/// which change sizes again. That is LLVM's `ARMConstantIslandPass` shape.
2621/// Note what is and is NOT circular here: an island only moves code AFTER it,
2622/// so `island_walk` decides every placement in ONE left-to-right pass. The
2623/// iteration below exists for the BRANCH ENCODINGS, exactly as it always did —
2624/// the loop is unchanged in kind, it just now walks island-inclusive positions.
2625///
2626/// Returns the resolved stream and `instruction index -> pooled words to flush
2627/// immediately before it`. The emit loop CONSUMES that map instead of deciding
2628/// anything itself, which is what makes one answer rather than two.
2629fn place_literal_islands_fixedpoint(
2630    arm_instrs: Vec<ArmInstruction>,
2631    encoder: &ArmEncoder,
2632    islands_enabled: bool,
2633) -> Result<
2634    (
2635        Vec<ArmInstruction>,
2636        std::collections::BTreeMap<usize, usize>,
2637    ),
2638    String,
2639> {
2640    use std::collections::HashMap;
2641    use synth_synthesis::Condition;
2642
2643    enum BKind {
2644        Cond(Condition),
2645        Uncond,
2646    }
2647    // Record each label branch ONCE — indices are stable across iterations.
2648    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
2649    for (i, instr) in arm_instrs.iter().enumerate() {
2650        match &instr.op {
2651            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
2652            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
2653            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
2654            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
2655            _ => {}
2656        }
2657    }
2658    if branches.is_empty() {
2659        // No label branches, but islands may still be needed — a 4 KB+
2660        // straight-line function is exactly the #345 case. Walk once.
2661        let (_, islands) = island_walk(&arm_instrs, encoder, islands_enabled)?;
2662        return Ok((arm_instrs, islands));
2663    }
2664
2665    let mut resolved = arm_instrs;
2666    let mut islands = std::collections::BTreeMap::new();
2667    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
2668    // The cap is now load-bearing in a second way: with islands in the loop a
2669    // pathological oscillation is conceivable, and a NON-converging placement
2670    // must be a loud error rather than whatever the last iteration happened to
2671    // hold. `converged` below is that guard.
2672    let mut converged = false;
2673    for _ in 0..16 {
2674        // 1. Byte position of each instruction, ISLAND-INCLUSIVE. This is the
2675        //    whole change: the positions branches are resolved against are the
2676        //    ones the emitted stream will actually have.
2677        let (pos_usize, islands_now) = island_walk(&resolved, encoder, islands_enabled)?;
2678        let positions: Vec<i64> = pos_usize.iter().map(|&p| p as i64).collect();
2679        islands = islands_now;
2680        // 2. Label name -> byte position (owned keys so the borrow ends here).
2681        let mut labels: HashMap<String, i64> = HashMap::new();
2682        for (i, instr) in resolved.iter().enumerate() {
2683            if let ArmOp::Label { name } = &instr.op {
2684                labels.insert(name.clone(), positions[i]);
2685            }
2686        }
2687        // 3. Rewrite each branch to its byte-accurate offset.
2688        let mut changed = false;
2689        for (idx, kind, label) in &branches {
2690            // A label not defined locally is an EXTERNAL target (e.g.
2691            // `Trap_Handler` resolved by a relocation / the vector table). Leave
2692            // such branches as their placeholder for the existing relocation
2693            // path — only local control-flow labels are byte-resolved here.
2694            let Some(&target) = labels.get(label) else {
2695                continue;
2696            };
2697            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
2698            // Positions are always even, so this division is exact.
2699            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
2700            let new_op = match kind {
2701                BKind::Cond(c) => ArmOp::BCondOffset {
2702                    cond: *c,
2703                    offset: halfword_offset,
2704                },
2705                BKind::Uncond => ArmOp::BOffset {
2706                    offset: halfword_offset,
2707                },
2708            };
2709            if resolved[*idx].op != new_op {
2710                resolved[*idx].op = new_op;
2711                changed = true;
2712            }
2713        }
2714        if !changed {
2715            converged = true;
2716            break;
2717        }
2718    }
2719    if !converged {
2720        return Err(
2721            "literal-island placement (#1331) did not reach a fixed point in 16 \
2722             iterations — branch sizes and island positions are oscillating. \
2723             Refusing to emit a stream whose branch offsets were never stable."
2724                .to_string(),
2725        );
2726    }
2727    Ok((resolved, islands))
2728}
2729
2730/// The pre-#1331 entry point, preserved for callers that only want branch
2731/// resolution. Delegates with islands OFF so there is ONE implementation of the
2732/// branch fixed point rather than two that can drift.
2733fn resolve_label_branches(
2734    arm_instrs: Vec<ArmInstruction>,
2735    encoder: &ArmEncoder,
2736) -> Result<Vec<ArmInstruction>, String> {
2737    Ok(place_literal_islands_fixedpoint(arm_instrs, encoder, false)?.0)
2738}
2739
2740/// SC-5 branch-target boundary gate (#740, #930): every emitted branch target
2741/// must be a member of the instruction-start set of the final stream.
2742///
2743/// "Branch offset calculation shall account for Thumb instruction alignment
2744/// and variable instruction widths" (`safety/stpa/system-constraints.yaml`
2745/// SC-5). Thumb-2 mixes 16- and 32-bit encodings, so an off-by-one-halfword
2746/// target lands on the SECOND halfword of a wide instruction and the CPU
2747/// executes a halfword that was never an instruction — silent garbage, exit 0
2748/// (#930: the skipped `movw` left the `br_if` condition register at its reset
2749/// value). Both known escapes of that sentence were of this class: #740
2750/// (`B<cond>.W` T3 offset halved) and #930 (inner-block end label never
2751/// emitted, `b #0` placeholder). The encoder knows where every instruction
2752/// starts, so a target outside that set is a hard error here rather than
2753/// silent garbage on target.
2754///
2755/// Runs on the FINAL Thumb-2 stream for BOTH codegen paths — the direct
2756/// (`select_with_stack`, label branches byte-resolved above) and the optimized
2757/// (`optimizer_bridge`, numeric `BOffset`/`BCondOffset` pre-resolved inline) —
2758/// since both funnel through this encode pipeline. Two checks, jointly total
2759/// over local control flow:
2760///
2761/// 1. every numeric branch target is in the instruction-start set;
2762/// 2. no LOCAL (`.L`-prefixed) label branch survives unresolved — the resolver
2763///    deliberately skips labels it cannot find because an external target
2764///    (`Trap_Handler`, `func_N`) is legitimately absent and patched by
2765///    relocation, but a `.L` label is only ever defined in this same stream,
2766///    so an unresolved one is a dropped label (#930), not an external.
2767///
2768/// A32 (Cortex-R5) is fixed-width, so the mid-instruction class needs no gate
2769/// there (and its branches do not flow through the Thumb-2 resolver).
2770fn validate_branch_targets(
2771    instrs: &[ArmInstruction],
2772    encoder: &ArmEncoder,
2773    islands_enabled: bool,
2774) -> Result<(), String> {
2775    use std::collections::HashSet;
2776
2777    // Byte position of each element (`Label` encodes to 0 bytes, so a label's
2778    // position is exactly the start of the instruction that follows it).
2779    //
2780    // RQ-73-ISLANDPASS (#1331): ISLAND-INCLUSIVE, via the same walk the branch
2781    // offsets were resolved against. This gate previously sized the stream
2782    // itself, island-free, and that is not a coordinate system the emitted
2783    // object ever has once a pool is placed inline — it FALSE-REJECTED a
2784    // correctly-resolved spanning branch ("targets 0x26c2, which is not an
2785    // instruction start"). A gate and the thing it gates must measure in the
2786    // same units; sharing `island_walk` is what guarantees they do.
2787    let (pos_usize, _) = island_walk(instrs, encoder, islands_enabled)?;
2788    let positions: Vec<i64> = pos_usize.iter().map(|&p| p as i64).collect();
2789    let starts: HashSet<i64> = positions.iter().copied().collect();
2790
2791    for (i, instr) in instrs.iter().enumerate() {
2792        let offset = match &instr.op {
2793            ArmOp::BOffset { offset } => *offset,
2794            ArmOp::BCondOffset { offset, .. } => *offset,
2795            ArmOp::B { label }
2796            | ArmOp::Bcc { label, .. }
2797            | ArmOp::Bhs { label }
2798            | ArmOp::Blo { label }
2799                if label.starts_with(".L") =>
2800            {
2801                return Err(format!(
2802                    "SC-5 branch-target gate: local branch label '{}' is not \
2803                     defined anywhere in the emitted stream (branch at byte \
2804                     offset 0x{:x}). A `.L` label is only ever defined locally, \
2805                     so this is a dropped label (the #930 class) — the branch \
2806                     would encode as a `b #0` placeholder and land \
2807                     mid-instruction. Refusing to emit a miscompiled object.",
2808                    label, positions[i]
2809                ));
2810            }
2811            _ => continue,
2812        };
2813        // Thumb branch semantics: target = branch_pc + 4 + 2*offset.
2814        let target = positions[i] + 4 + 2 * offset as i64;
2815        if !starts.contains(&target) {
2816            return Err(format!(
2817                "SC-5 branch-target gate: branch at byte offset 0x{:x} targets \
2818                 0x{:x}, which is not an instruction boundary (instruction-start \
2819                 set violation — the target lands mid-instruction, the \
2820                 #740/#930 class). Refusing to emit a miscompiled object.",
2821                positions[i], target
2822            ));
2823        }
2824    }
2825    Ok(())
2826}
2827
2828#[cfg(test)]
2829mod tests {
2830    use super::*;
2831    use synth_synthesis::{Operand2, Reg};
2832
2833    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
2834    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
2835    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
2836    /// byte-identical.
2837    #[test]
2838    fn test_rewrite_memory_grow_zero_539() {
2839        // the idiom -> memory.size
2840        assert_eq!(
2841            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
2842            vec![WasmOp::MemorySize(0)]
2843        );
2844        // const non-zero delta: NOT folded
2845        assert_eq!(
2846            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
2847            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
2848        );
2849        // runtime delta (no preceding const): NOT folded
2850        assert_eq!(
2851            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
2852            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
2853        );
2854        // a bare const-0 not feeding a grow is untouched
2855        assert_eq!(
2856            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
2857            vec![WasmOp::I32Const(0), WasmOp::I32Add]
2858        );
2859        // fold is local: surrounding ops preserved, indices past the fold intact
2860        assert_eq!(
2861            rewrite_memory_grow_zero(&[
2862                WasmOp::LocalGet(0),
2863                WasmOp::I32Const(0),
2864                WasmOp::MemoryGrow(0),
2865                WasmOp::I32Add,
2866            ]),
2867            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
2868        );
2869    }
2870
2871    /// SC-5 (#740/#930): the branch-target boundary gate. Every emitted branch
2872    /// target must be a member of the instruction-start set of the final
2873    /// Thumb-2 stream; a `.L`-local label branch surviving unresolved is a
2874    /// dropped label. Red-first: both rejection arms were written against the
2875    /// exact #930 stream shape (a `b #0` placeholder whose pc+4 target falls
2876    /// on the second halfword of a 32-bit `movw`) and fail without the gate.
2877    #[test]
2878    fn test_validate_branch_targets_sc5_930() {
2879        let enc = ArmEncoder::new_thumb2();
2880        let ins = |op: ArmOp| ArmInstruction {
2881            op,
2882            source_line: None,
2883        };
2884
2885        // 1. Boundary-valid stream: b over a wide movw onto the mov — OK.
2886        //    positions: 0 BOffset(2B), 2 Movw(4B), 6 Mov(2B)
2887        //    target = 0 + 4 + 2*1 = 6 = start of Mov.
2888        let good = vec![
2889            ins(ArmOp::BOffset { offset: 1 }),
2890            ins(ArmOp::Movw {
2891                rd: Reg::R3,
2892                imm16: 1,
2893            }),
2894            ins(ArmOp::Mov {
2895                rd: Reg::R0,
2896                op2: Operand2::Reg(Reg::R3),
2897            }),
2898        ];
2899        assert!(validate_branch_targets(&good, &enc, false).is_ok());
2900
2901        // 2. The exact #930 shape: `b #0` (offset 0) -> target = pc+4 = 4,
2902        //    the SECOND halfword of the 4-byte movw spanning 2..6. Hard error.
2903        let mid = vec![
2904            ins(ArmOp::BOffset { offset: 0 }),
2905            ins(ArmOp::Movw {
2906                rd: Reg::R3,
2907                imm16: 1,
2908            }),
2909            ins(ArmOp::Mov {
2910                rd: Reg::R0,
2911                op2: Operand2::Reg(Reg::R3),
2912            }),
2913        ];
2914        let err = validate_branch_targets(&mid, &enc, false).unwrap_err();
2915        assert!(err.contains("SC-5"), "boundary violation names SC-5: {err}");
2916        assert!(err.contains("not an instruction boundary"), "{err}");
2917
2918        // 3. Conditional form of the same violation.
2919        let mid_cond = vec![
2920            ins(ArmOp::BCondOffset {
2921                cond: synth_synthesis::Condition::NE,
2922                offset: 0,
2923            }),
2924            ins(ArmOp::Movw {
2925                rd: Reg::R3,
2926                imm16: 1,
2927            }),
2928            ins(ArmOp::Mov {
2929                rd: Reg::R0,
2930                op2: Operand2::Reg(Reg::R3),
2931            }),
2932        ];
2933        assert!(validate_branch_targets(&mid_cond, &enc, false).is_err());
2934
2935        // 4. A `.L`-local label branch that was never resolved (the dropped
2936        //    end label, #930's mechanism) is a hard error even though it
2937        //    would encode as a well-formed placeholder.
2938        let dropped = vec![
2939            ins(ArmOp::B {
2940                label: ".Lblock_end_3".to_string(),
2941            }),
2942            ins(ArmOp::Movw {
2943                rd: Reg::R3,
2944                imm16: 1,
2945            }),
2946        ];
2947        let err = validate_branch_targets(&dropped, &enc, false).unwrap_err();
2948        assert!(err.contains(".Lblock_end_3"), "{err}");
2949        assert!(err.contains("dropped label"), "{err}");
2950
2951        // 5. An EXTERNAL label branch (no `.L` prefix) is legitimately absent
2952        //    (patched via relocation / vector table) and must NOT trip the
2953        //    gate — the carve-out that used to swallow #930 stays for real
2954        //    externals only.
2955        let external = vec![
2956            ins(ArmOp::B {
2957                label: "Trap_Handler".to_string(),
2958            }),
2959            ins(ArmOp::Movw {
2960                rd: Reg::R3,
2961                imm16: 1,
2962            }),
2963        ];
2964        assert!(validate_branch_targets(&external, &enc, false).is_ok());
2965
2966        // 6. Labels are zero-width: a target on a Label position is the start
2967        //    of the instruction that follows it — OK.
2968        let labeled = vec![
2969            ins(ArmOp::BOffset { offset: 1 }),
2970            ins(ArmOp::Movw {
2971                rd: Reg::R3,
2972                imm16: 1,
2973            }),
2974            ins(ArmOp::Label {
2975                name: ".Lend".to_string(),
2976            }),
2977            ins(ArmOp::Mov {
2978                rd: Reg::R0,
2979                op2: Operand2::Reg(Reg::R3),
2980            }),
2981        ];
2982        assert!(validate_branch_targets(&labeled, &enc, false).is_ok());
2983    }
2984
2985    /// SC-5 (#930) end-to-end at the backend seam: the labels.wast `br_if2`
2986    /// shape — a `br_if` exiting an enclosing block from inside an `if`, its
2987    /// value operand a block-that-branches — must COMPILE (the pre-fix
2988    /// selector dropped the inner block's end label, which the SC-5 gate now
2989    /// turns into a hard error, so compile success proves the label was
2990    /// emitted) and every branch in the emitted bytes must land on an
2991    /// instruction boundary (re-derived from the encoded halfwords, not from
2992    /// the resolver's own bookkeeping).
2993    #[test]
2994    fn test_930_brif2_shape_compiles_and_targets_boundaries() {
2995        let backend = ArmBackend::new();
2996        let ops = vec![
2997            WasmOp::Block, // $l0 (result i32)
2998            WasmOp::I32Const(1),
2999            WasmOp::If,
3000            WasmOp::Block, // $l1 (result i32)
3001            WasmOp::I32Const(1),
3002            WasmOp::Br(0), // br $l1
3003            WasmOp::End,
3004            WasmOp::I32Const(1),
3005            WasmOp::BrIf(1), // br_if $l0
3006            WasmOp::Drop,
3007            WasmOp::End, // end if
3008            WasmOp::I32Const(0),
3009            WasmOp::End, // end $l0
3010            WasmOp::End,
3011        ];
3012        let config = CompileConfig::default();
3013        let func = backend
3014            .compile_function("t", &ops, &config)
3015            .expect("#930 shape must compile (SC-5 gate passes)");
3016
3017        // Walk the encoded halfwords: collect instruction starts, then check
3018        // every narrow/wide B / B<cond> target is a member.
3019        let code = &func.code;
3020        let mut starts = std::collections::HashSet::new();
3021        let mut widths = Vec::new();
3022        let mut off = 0usize;
3023        while off + 2 <= code.len() {
3024            starts.insert(off as i64);
3025            let hw = u16::from_le_bytes([code[off], code[off + 1]]);
3026            let wide = (hw & 0xF800) >= 0xE800; // 0b11101/0b11110/0b11111
3027            widths.push((off, hw, wide));
3028            off += if wide { 4 } else { 2 };
3029        }
3030        for (off, hw, wide) in widths {
3031            let target = if !wide && (hw & 0xF800) == 0xE000 {
3032                // T2 B: imm11, halfwords
3033                let imm = ((hw & 0x7FF) as i32) << 21 >> 21;
3034                Some(off as i64 + 4 + 2 * imm as i64)
3035            } else if !wide && (hw & 0xF000) == 0xD000 && (hw & 0x0F00) < 0x0E00 {
3036                // T1 B<cond>: imm8, halfwords
3037                let imm = ((hw & 0xFF) as i32) << 24 >> 24;
3038                Some(off as i64 + 4 + 2 * imm as i64)
3039            } else {
3040                None
3041            };
3042            if let Some(t) = target {
3043                assert!(
3044                    starts.contains(&t),
3045                    "branch at 0x{off:x} (hw 0x{hw:04x}) targets 0x{t:x}, \
3046                     not an instruction boundary — the #930 miscompile shape"
3047                );
3048            }
3049        }
3050    }
3051
3052    #[test]
3053    fn test_arm_backend_name() {
3054        let backend = ArmBackend::new();
3055        assert_eq!(backend.name(), "arm");
3056        assert!(backend.is_available());
3057    }
3058
3059    #[test]
3060    fn test_arm_backend_capabilities() {
3061        let backend = ArmBackend::new();
3062        let caps = backend.capabilities();
3063        assert!(!caps.produces_elf);
3064        assert!(caps.supports_rule_verification);
3065        assert!(!caps.is_external);
3066    }
3067
3068    #[test]
3069    fn test_compile_add_function() {
3070        let backend = ArmBackend::new();
3071        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3072        let config = CompileConfig::default();
3073
3074        let result = backend.compile_function("add", &ops, &config);
3075        assert!(result.is_ok());
3076
3077        let func = result.unwrap();
3078        assert_eq!(func.name, "add");
3079        assert!(!func.code.is_empty());
3080        assert_eq!(func.wasm_ops, ops);
3081    }
3082
3083    /// VCR-DBG-001: the per-instruction source map must cover the function with
3084    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
3085    /// code (it is captured at encode time, never serialized here).
3086    #[test]
3087    fn test_line_map_is_wellformed_dbg001() {
3088        let backend = ArmBackend::new();
3089        let ops = vec![
3090            WasmOp::LocalGet(0),
3091            WasmOp::LocalGet(1),
3092            WasmOp::I32Add,
3093            WasmOp::End,
3094        ];
3095        let config = CompileConfig::default();
3096        let func = backend.compile_function("add", &ops, &config).unwrap();
3097
3098        // Non-empty, and the first instruction starts at machine offset 0.
3099        assert!(
3100            !func.line_map.is_empty(),
3101            "a non-trivial function captures a source map"
3102        );
3103        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
3104
3105        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
3106        // bytes) and every mapped offset lies inside the emitted `.text`.
3107        for w in func.line_map.windows(2) {
3108            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
3109            assert!(
3110                w[1].0 - w[0].0 >= 2,
3111                "each ARM/Thumb instruction is >= 2 bytes"
3112            );
3113        }
3114        let last = func.line_map.last().unwrap().0 as usize;
3115        assert!(
3116            last < func.code.len(),
3117            "every mapped offset lies inside .text"
3118        );
3119
3120        // The side-table is additive: recompiling is deterministic and the map is
3121        // consistent with that exact code (capturing it does not alter output).
3122        let again = backend.compile_function("add", &ops, &config).unwrap();
3123        assert_eq!(
3124            again.code, func.code,
3125            "compilation deterministic; map is additive"
3126        );
3127        assert_eq!(again.line_map, func.line_map);
3128    }
3129
3130    #[test]
3131    fn test_count_params() {
3132        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3133        assert_eq!(count_params(&ops), 2);
3134
3135        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
3136        assert_eq!(count_params(&no_params), 0);
3137    }
3138
3139    /// #457: the declared param count caps the access-pattern inference. The
3140    /// repro shape `(param i32)(local i32) → p0 + local1` reads local 1 before
3141    /// any write, so `count_params` infers 2 — with the declared count (1) the
3142    /// local is reclassified onto the zero-inited frame path instead of being
3143    /// read from R1 (caller garbage).
3144    #[test]
3145    fn declared_param_count_caps_inference_457() {
3146        let ops = vec![
3147            WasmOp::LocalGet(0),
3148            WasmOp::LocalGet(1),
3149            WasmOp::I32Add,
3150            WasmOp::End,
3151        ];
3152        // The inference alone still says 2 (the misclassification this caps).
3153        assert_eq!(count_params(&ops), 2);
3154
3155        let backend = ArmBackend::new();
3156        let inferred = backend
3157            .compile_function("rbw", &ops, &CompileConfig::default())
3158            .unwrap();
3159        let declared = backend
3160            .compile_function(
3161                "rbw",
3162                &ops,
3163                &CompileConfig {
3164                    current_func_param_count: Some(1),
3165                    ..CompileConfig::default()
3166                },
3167            )
3168            .unwrap();
3169        // The cap is consumed: the declared-count compile reclassifies local 1
3170        // and must emit different code than the param-misclassified one.
3171        assert_ne!(
3172            inferred.code, declared.code,
3173            "declared param count must reach the selector"
3174        );
3175        // The zero-init is present: a 16-bit Thumb `movs rN, #0`
3176        // (0x2000 | rd<<8 → LE bytes [0x00, 0x20+rd]) somewhere in the body.
3177        let has_movs_zero = declared
3178            .code
3179            .as_chunks::<2>()
3180            .0
3181            .iter()
3182            .any(|h| h[0] == 0x00 && (0x20..=0x27).contains(&h[1]));
3183        assert!(
3184            has_movs_zero,
3185            "declared-count compile must zero-init the read-before-write local; code: {:02x?}",
3186            declared.code
3187        );
3188        // A declared count that matches (or exceeds) the inference changes
3189        // nothing — byte-identity for every function without rbw locals.
3190        let matching = backend
3191            .compile_function(
3192                "rbw",
3193                &ops,
3194                &CompileConfig {
3195                    current_func_param_count: Some(2),
3196                    ..CompileConfig::default()
3197                },
3198            )
3199            .unwrap();
3200        assert_eq!(
3201            matching.code, inferred.code,
3202            "declared >= inferred must stay byte-identical"
3203        );
3204    }
3205
3206    /// #970: a CONDITIONALLY-written param must stay a param.
3207    ///
3208    /// The read-first heuristic sees `LocalSet(1)` before any `LocalGet(1)` in
3209    /// LINEAR op order and demotes index 1 — even though the `if` means the
3210    /// write may not execute at all. `min(referenced, declared)` keeps it.
3211    /// The RED symptom this pins is not a wrong constant: the demoted local's
3212    /// first access is a WRITE, so the #457 zero-init skips it and the
3213    /// fall-through arm reads an UNINITIALISED frame slot (executed evidence:
3214    /// `scripts/repro/cond_write_param_970_arm_differential.py`).
3215    #[test]
3216    fn conditionally_written_param_stays_a_param_970() {
3217        // (param i32 i32): if (local.get 0) { local.set 1 = 5 }; local.get 1
3218        let ops = vec![
3219            WasmOp::LocalGet(0),
3220            WasmOp::If,
3221            WasmOp::I32Const(5),
3222            WasmOp::LocalSet(1),
3223            WasmOp::End,
3224            WasmOp::LocalGet(1),
3225            WasmOp::End,
3226        ];
3227        let declared = CompileConfig {
3228            current_func_param_count: Some(2),
3229            ..CompileConfig::default()
3230        };
3231        // The old rule: index 1 is written before it is read, so it is not
3232        // counted — this is the undercount that produced the miscompile.
3233        assert_eq!(
3234            count_params(&ops),
3235            1,
3236            "the read-first heuristic must still undercount (this is the defect)"
3237        );
3238        assert_eq!(
3239            effective_num_params(&ops, &declared),
3240            2,
3241            "a conditionally-written param must be counted as a param"
3242        );
3243        // The #457 direction is untouched: a genuine non-param local is still
3244        // clamped away by the declared count.
3245        let rbw = vec![
3246            WasmOp::LocalGet(0),
3247            WasmOp::LocalGet(1),
3248            WasmOp::I32Add,
3249            WasmOp::End,
3250        ];
3251        assert_eq!(
3252            effective_num_params(
3253                &rbw,
3254                &CompileConfig {
3255                    current_func_param_count: Some(1),
3256                    ..CompileConfig::default()
3257                }
3258            ),
3259            1,
3260            "#457: a read-before-write non-param local must NOT become a param"
3261        );
3262        // Leniency: a body touching only the first few of many declared params
3263        // still lowers with the small count (the selector homes at most 4 in
3264        // registers; `min` is what keeps this from becoming `declared`).
3265        assert_eq!(
3266            effective_num_params(
3267                &rbw,
3268                &CompileConfig {
3269                    current_func_param_count: Some(12),
3270                    ..CompileConfig::default()
3271                }
3272            ),
3273            2,
3274            "declared >> referenced must stay at the referenced count"
3275        );
3276        // No declared count: the legacy inference, unchanged (honest residual).
3277        assert_eq!(
3278            effective_num_params(&ops, &CompileConfig::default()),
3279            count_params(&ops)
3280        );
3281    }
3282
3283    #[test]
3284    fn test_arm_backend_register() {
3285        let mut registry = synth_core::BackendRegistry::new();
3286        registry.register(Box::new(ArmBackend::new()));
3287        assert!(registry.get("arm").is_some());
3288        assert_eq!(registry.available().len(), 1);
3289    }
3290
3291    #[test]
3292    fn test_compile_import_call_produces_relocations() {
3293        let backend = ArmBackend::new();
3294        // Simulate a WASM module where func index 0 is an import.
3295        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
3296        let ops = vec![WasmOp::Call(0)];
3297        let config = CompileConfig {
3298            num_imports: 1,
3299            no_optimize: true, // Direct instruction selection to preserve Call semantics
3300            ..CompileConfig::default()
3301        };
3302
3303        let result = backend.compile_function("caller", &ops, &config);
3304        assert!(result.is_ok());
3305
3306        let func = result.unwrap();
3307        assert!(!func.code.is_empty());
3308        assert_eq!(func.relocations.len(), 1);
3309        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
3310        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
3311        assert!(func.relocations[0].offset > 0);
3312    }
3313
3314    /// Regression test for #197: in `relocatable` mode, an import call must
3315    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
3316    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
3317    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
3318    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
3319    #[test]
3320    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
3321        let backend = ArmBackend::new();
3322        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
3323        let config = CompileConfig {
3324            num_imports: 1,
3325            relocatable: true,
3326            ..CompileConfig::default()
3327        };
3328
3329        let func = backend
3330            .compile_function("caller", &ops, &config)
3331            .expect("relocatable import call compiles");
3332
3333        assert_eq!(func.relocations.len(), 1);
3334        assert_eq!(
3335            func.relocations[0].symbol, "func_0",
3336            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
3337        );
3338    }
3339
3340    #[test]
3341    fn test_compile_no_imports_no_relocations() {
3342        let backend = ArmBackend::new();
3343        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3344        let config = CompileConfig::default();
3345
3346        let func = backend.compile_function("add", &ops, &config).unwrap();
3347        assert!(func.relocations.is_empty());
3348    }
3349
3350    /// Regression test for #167: a call to an INTERNAL function
3351    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
3352    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
3353    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
3354    /// to a garbage address — making the object non-linkable. This test
3355    /// would have caught that regression.
3356    #[test]
3357    fn test_compile_internal_call_produces_relocation_167() {
3358        let backend = ArmBackend::new();
3359        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
3360        let ops = vec![WasmOp::Call(2)];
3361        let config = CompileConfig {
3362            num_imports: 1,
3363            no_optimize: true,
3364            ..CompileConfig::default()
3365        };
3366
3367        let func = backend
3368            .compile_function("caller", &ops, &config)
3369            .expect("internal call compiles");
3370
3371        assert_eq!(
3372            func.relocations.len(),
3373            1,
3374            "an internal call must emit exactly one relocation (#167)"
3375        );
3376        assert_eq!(
3377            func.relocations[0].symbol, "func_2",
3378            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
3379        );
3380    }
3381
3382    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
3383
3384    #[test]
3385    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
3386        // Mpu mode must not introduce any inline check on ARM — the MPU
3387        // handles faults via hardware. The encoded bytes for an i32.load
3388        // should be identical between None and Mpu.
3389        let backend = ArmBackend::new();
3390        let ops = vec![
3391            WasmOp::LocalGet(0),
3392            WasmOp::I32Load {
3393                offset: 0,
3394                align: 2,
3395            },
3396        ];
3397        let cfg_none = CompileConfig {
3398            no_optimize: true,
3399            ..Default::default()
3400        };
3401        let cfg_mpu = CompileConfig {
3402            no_optimize: true,
3403            safety_bounds: SafetyBounds::Mpu,
3404            ..Default::default()
3405        };
3406        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3407        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3408        assert_eq!(
3409            n.code, m.code,
3410            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
3411        );
3412    }
3413
3414    #[test]
3415    fn arm_legacy_bounds_check_still_emits_software_check() {
3416        // Legacy CLI users with `--bounds-check` should keep getting the
3417        // software path even though the new SafetyBounds field defaults to None.
3418        let backend = ArmBackend::new();
3419        let ops = vec![
3420            WasmOp::LocalGet(0),
3421            WasmOp::I32Load {
3422                offset: 0,
3423                align: 2,
3424            },
3425        ];
3426        let cfg_legacy = CompileConfig {
3427            no_optimize: true,
3428            bounds_check: true,
3429            ..Default::default()
3430        };
3431        let cfg_software = CompileConfig {
3432            no_optimize: true,
3433            safety_bounds: SafetyBounds::Software,
3434            ..Default::default()
3435        };
3436        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
3437        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
3438        assert_eq!(
3439            l.code, s.code,
3440            "--bounds-check should produce the same bytes as --safety-bounds=software"
3441        );
3442    }
3443
3444    /// #377: `--safety-bounds software` must be enforced on the OPTIMIZED path
3445    /// too. Pre-fix, `software` was byte-identical to `none` there (a silent
3446    /// no-op while the safety manifest claimed enforcement). The compiled
3447    /// bytes must now (a) differ from `none` and (b) contain the inline
3448    /// `CMP ip, sl` + `UDF` guard.
3449    #[test]
3450    fn arm_safety_bounds_software_enforced_on_optimized_path_377() {
3451        let backend = ArmBackend::new();
3452        // Dynamic-address store+load: the optimized path accepts this shape
3453        // (no calls, no i64 params, ≤4 params).
3454        let ops = vec![
3455            WasmOp::LocalGet(0),
3456            WasmOp::LocalGet(1),
3457            WasmOp::I32Store {
3458                offset: 4,
3459                align: 2,
3460            },
3461            WasmOp::LocalGet(0),
3462            WasmOp::I32Load {
3463                offset: 0,
3464                align: 2,
3465            },
3466        ];
3467        // no_optimize NOT set — this exercises the optimized path.
3468        let cfg_none = CompileConfig::default();
3469        let cfg_sw = CompileConfig {
3470            safety_bounds: SafetyBounds::Software,
3471            ..Default::default()
3472        };
3473        let n = backend.compile_function("st", &ops, &cfg_none).unwrap();
3474        let s = backend.compile_function("st", &ops, &cfg_sw).unwrap();
3475        assert_ne!(
3476            n.code, s.code,
3477            "#377: software bounds must CHANGE optimized-path codegen (was a silent no-op)"
3478        );
3479        // Thumb-2 `UDF #0` is 0xDE00 (LE bytes: 00 DE); the #752
3480        // wraparound-safe guard's borrow check `CMP sl, ip` (16-bit
3481        // high-reg form) is 0x45E2 (LE: E2 45). Both must appear — one
3482        // guard per access, traps inline.
3483        let has_udf = s.code.windows(2).any(|w| w == [0x00, 0xDE]);
3484        let has_cmp_sl_ip = s.code.windows(2).any(|w| w == [0xE2, 0x45]);
3485        assert!(has_udf, "#377: inline UDF trap missing from optimized path");
3486        assert!(
3487            has_cmp_sl_ip,
3488            "#377/#752: CMP sl, ip bounds borrow-check missing from optimized path"
3489        );
3490        // And `none` must contain NO UDF (the function has no other trap).
3491        assert!(
3492            !n.code.windows(2).any(|w| w == [0x00, 0xDE]),
3493            "none must not contain a UDF for this function"
3494        );
3495    }
3496
3497    /// #377: `mpu` on the optimized path is codegen-passthrough — identical
3498    /// bytes to `none` on BOTH paths (hardware enforcement is target-level;
3499    /// synth does not emit MPU region programming — tracked separately in
3500    /// #377's fix-direction discussion). This pins path-parity for `mpu`.
3501    #[test]
3502    fn arm_safety_bounds_mpu_optimized_path_parity_377() {
3503        let backend = ArmBackend::new();
3504        let ops = vec![
3505            WasmOp::LocalGet(0),
3506            WasmOp::I32Load {
3507                offset: 0,
3508                align: 2,
3509            },
3510        ];
3511        let cfg_none = CompileConfig::default();
3512        let cfg_mpu = CompileConfig {
3513            safety_bounds: SafetyBounds::Mpu,
3514            ..Default::default()
3515        };
3516        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3517        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3518        assert_eq!(
3519            n.code, m.code,
3520            "Mpu and None must produce identical bytes on the optimized path too"
3521        );
3522    }
3523
3524    /// #377: `mask` on the optimized path declines to the direct selector
3525    /// (honest degradation) — the compiled function must equal the
3526    /// `--no-optimize` masking bytes, i.e. the flag is honored, never dropped.
3527    #[test]
3528    fn arm_safety_bounds_mask_optimized_path_declines_to_direct_377() {
3529        let backend = ArmBackend::new();
3530        let ops = vec![
3531            WasmOp::LocalGet(0),
3532            WasmOp::LocalGet(1),
3533            WasmOp::I32Store {
3534                offset: 0,
3535                align: 2,
3536            },
3537        ];
3538        // RQ-57-SENTINEL: mask now requires a STATED non-zero power-of-two
3539        // size (0 = zero-byte memory = refused), so the test states one —
3540        // exactly what the #953 fix required of the rv32 driver test.
3541        let cfg_mask_opt = CompileConfig {
3542            safety_bounds: SafetyBounds::Mask,
3543            linear_memory_bytes: 64 * 1024,
3544            ..Default::default()
3545        };
3546        let cfg_mask_direct = CompileConfig {
3547            no_optimize: true,
3548            safety_bounds: SafetyBounds::Mask,
3549            linear_memory_bytes: 64 * 1024,
3550            ..Default::default()
3551        };
3552        let o = backend.compile_function("st", &ops, &cfg_mask_opt).unwrap();
3553        let d = backend
3554            .compile_function("st", &ops, &cfg_mask_direct)
3555            .unwrap();
3556        assert_eq!(
3557            o.code, d.code,
3558            "#377: mask on the optimized path must fall back to the direct selector's masking"
3559        );
3560    }
3561
3562    /// RQ-57-SENTINEL (#953 sibling): `--safety-bounds mask` with a ZERO-byte
3563    /// linear memory must REFUSE at compile time. Before this fix, `bytes == 0`
3564    /// was exempt from the power-of-two gate ("0 means unknown"), and the
3565    /// emitted `SUB R12, R10, #1; AND` guard degenerated to an IDENTITY mask
3566    /// at runtime (R10 = 0 baked by the startup for a `(memory 0)` module):
3567    /// an unbounded OOB access in the mode whose purpose is bounding.
3568    /// Red-first: pre-fix this compile SUCCEEDED (verified on the v0.56.1
3569    /// tree: exit 0, `movw r10, #0x0` in the reset handler, AND-masked body).
3570    #[test]
3571    fn arm_safety_bounds_mask_zero_size_refused_rq57() {
3572        let backend = ArmBackend::new();
3573        let ops = vec![
3574            WasmOp::LocalGet(0),
3575            WasmOp::I32Load {
3576                offset: 0,
3577                align: 2,
3578            },
3579        ];
3580        let cfg = CompileConfig {
3581            safety_bounds: SafetyBounds::Mask,
3582            linear_memory_bytes: 0,
3583            ..Default::default()
3584        };
3585        let err = backend
3586            .compile_function("ld", &ops, &cfg)
3587            .expect_err("mask over a zero-byte memory must refuse, not emit an identity mask");
3588        let msg = format!("{err}");
3589        assert!(
3590            msg.contains("ZERO bytes"),
3591            "refusal must name the zero-byte cause, got: {msg}"
3592        );
3593    }
3594
3595    // ========================================================================
3596    // ISA feature gate tests — ensure the compiler never emits unsupported
3597    // instructions for a given target
3598    // ========================================================================
3599
3600    #[test]
3601    fn test_f32_rejected_on_cortex_m3_no_fpu() {
3602        let backend = ArmBackend::new();
3603        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3604        let config = CompileConfig {
3605            target: TargetSpec::cortex_m3(),
3606            no_optimize: true,
3607            ..CompileConfig::default()
3608        };
3609
3610        let result = backend.compile_function("fadd", &ops, &config);
3611        assert!(
3612            result.is_err(),
3613            "f32 operations should fail on Cortex-M3 (no FPU)"
3614        );
3615    }
3616
3617    #[test]
3618    fn test_f32_accepted_on_cortex_m4f() {
3619        let backend = ArmBackend::new();
3620        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3621        let config = CompileConfig {
3622            target: TargetSpec::cortex_m4f(),
3623            no_optimize: true,
3624            ..CompileConfig::default()
3625        };
3626
3627        let result = backend.compile_function("fadd", &ops, &config);
3628        assert!(
3629            result.is_ok(),
3630            "f32 operations should succeed on Cortex-M4F, got: {:?}",
3631            result.unwrap_err()
3632        );
3633    }
3634
3635    #[test]
3636    fn test_i32_works_on_all_targets() {
3637        let backend = ArmBackend::new();
3638        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3639
3640        // Cortex-M3 (no FPU)
3641        let config_m3 = CompileConfig {
3642            target: TargetSpec::cortex_m3(),
3643            no_optimize: true,
3644            ..CompileConfig::default()
3645        };
3646        assert!(
3647            backend.compile_function("add", &ops, &config_m3).is_ok(),
3648            "i32 ops should work on Cortex-M3"
3649        );
3650
3651        // Cortex-M4F (single FPU)
3652        let config_m4f = CompileConfig {
3653            target: TargetSpec::cortex_m4f(),
3654            no_optimize: true,
3655            ..CompileConfig::default()
3656        };
3657        assert!(
3658            backend.compile_function("add", &ops, &config_m4f).is_ok(),
3659            "i32 ops should work on Cortex-M4F"
3660        );
3661
3662        // Cortex-M7DP (double FPU)
3663        let config_m7dp = CompileConfig {
3664            target: TargetSpec::cortex_m7dp(),
3665            no_optimize: true,
3666            ..CompileConfig::default()
3667        };
3668        assert!(
3669            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
3670            "i32 ops should work on Cortex-M7DP"
3671        );
3672    }
3673
3674    #[test]
3675    fn test_f32_rejected_on_cortex_m4_no_fpu() {
3676        // Cortex-M4 (without F suffix) has no FPU
3677        let backend = ArmBackend::new();
3678        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
3679        let config = CompileConfig {
3680            target: TargetSpec::cortex_m4(),
3681            no_optimize: true,
3682            ..CompileConfig::default()
3683        };
3684
3685        let result = backend.compile_function("fmul", &ops, &config);
3686        assert!(
3687            result.is_err(),
3688            "f32 operations should fail on Cortex-M4 (no FPU)"
3689        );
3690    }
3691
3692    // ========================================================================
3693    // Issue #120 — f32 ops in the optimized lowering path
3694    //
3695    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
3696    // value-producing float op fell through to `Opcode::Nop`, leaving a
3697    // downstream consumer with an unmapped vreg and tripping the PR #101
3698    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
3699    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
3700    // module.
3701    //
3702    // Fix: `optimize_full` declines float modules with a typed `Err`;
3703    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
3704    // path, which handles f32 via VFP/FPU. These tests use the *default*
3705    // (optimized) config — `no_optimize` is NOT set — which is the exact
3706    // configuration that panicked pre-fix.
3707    // ========================================================================
3708
3709    /// RQ-65-DECLINE (#1208 / #1213 / #1205): a shape the optimized path
3710    /// used to lower WRONG must now reach the direct selector through the
3711    /// fallback, so the DEFAULT configuration is byte-identical to
3712    /// `--no-optimize` on it — the selector-parity property
3713    /// (`selector_parity_197_differential.py`), asserted at the unit level
3714    /// for one instance of each declined class.
3715    #[test]
3716    fn test_rq65_declined_shapes_default_equals_no_optimize() {
3717        let backend = ArmBackend::new();
3718        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3719            (
3720                "ld8u",
3721                vec![
3722                    WasmOp::LocalGet(0),
3723                    WasmOp::I64Load8U {
3724                        offset: 0,
3725                        align: 0,
3726                    },
3727                ],
3728            ),
3729            (
3730                "st16",
3731                vec![
3732                    WasmOp::LocalGet(0),
3733                    WasmOp::I64Const(7),
3734                    WasmOp::I64Store16 {
3735                        offset: 0,
3736                        align: 1,
3737                    },
3738                ],
3739            ),
3740            (
3741                "sel64",
3742                vec![
3743                    WasmOp::I64Const(1),
3744                    WasmOp::I64Const(0),
3745                    WasmOp::LocalGet(0),
3746                    WasmOp::Select,
3747                    WasmOp::I32WrapI64,
3748                ],
3749            ),
3750            (
3751                "vif",
3752                vec![
3753                    WasmOp::LocalGet(0),
3754                    WasmOp::LocalGet(1),
3755                    WasmOp::I32GtS,
3756                    WasmOp::If,
3757                    WasmOp::I32Const(7),
3758                    WasmOp::Else,
3759                    WasmOp::I32Const(9),
3760                    WasmOp::End,
3761                ],
3762            ),
3763        ];
3764        for (name, ops) in cases {
3765            let default = backend
3766                .compile_function(name, &ops, &CompileConfig::default())
3767                .unwrap_or_else(|e| {
3768                    panic!("{name}: default config must compile via the fallback: {e}")
3769                });
3770            let direct = backend
3771                .compile_function(
3772                    name,
3773                    &ops,
3774                    &CompileConfig {
3775                        no_optimize: true,
3776                        ..CompileConfig::default()
3777                    },
3778                )
3779                .unwrap_or_else(|e| panic!("{name}: --no-optimize must compile: {e}"));
3780            assert_eq!(
3781                default.code, direct.code,
3782                "{name}: the declined shape must be the direct selector's bytes"
3783            );
3784            assert!(default.code.len() > 2, "{name}: not the #1208 empty body");
3785        }
3786    }
3787
3788    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
3789    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
3790    /// the module and the backend falls back to direct selection, producing a
3791    /// non-empty f32.div lowering on a Cortex-M4F.
3792    #[test]
3793    fn test_issue120_f32_div_compiles_via_optimized_default() {
3794        let backend = ArmBackend::new();
3795        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3796        let config = CompileConfig {
3797            target: TargetSpec::cortex_m4f(),
3798            // no_optimize NOT set — this exercises the optimized path that
3799            // panicked in issue #120, then the fallback to direct selection.
3800            // GI-FPU-002: the f32 params must be declared so the direct
3801            // selector homes them in S0/S1 (AAPCS-VFP) rather than declining.
3802            current_func_params_f32: vec![true, true],
3803            ..CompileConfig::default()
3804        };
3805
3806        let result = backend.compile_function("fdiv", &ops, &config);
3807        assert!(
3808            result.is_ok(),
3809            "f32.div must compile on Cortex-M4F via the optimized->direct \
3810             fallback (issue #120), got: {:?}",
3811            result.as_ref().err()
3812        );
3813        assert!(
3814            !result.unwrap().code.is_empty(),
3815            "f32.div must produce non-empty machine code"
3816        );
3817    }
3818
3819    /// A spread of f32 ops, all through the optimized (default) config, must
3820    /// compile via the fallback on an FPU target without panicking.
3821    #[test]
3822    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
3823        let backend = ArmBackend::new();
3824        let config = CompileConfig {
3825            target: TargetSpec::cortex_m4f(),
3826            // GI-FPU-002: declare the two f32 params for AAPCS-VFP homing.
3827            current_func_params_f32: vec![true, true],
3828            ..CompileConfig::default()
3829        };
3830
3831        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3832            (
3833                "fadd",
3834                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
3835            ),
3836            (
3837                "fmul",
3838                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
3839            ),
3840            (
3841                "fsub",
3842                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
3843            ),
3844        ];
3845
3846        for (name, ops) in cases {
3847            let result = backend.compile_function(name, &ops, &config);
3848            assert!(
3849                result.is_ok(),
3850                "{name} must compile via the optimized->direct fallback \
3851                 (issue #120), got: {:?}",
3852                result.as_ref().err()
3853            );
3854            assert!(
3855                !result.unwrap().code.is_empty(),
3856                "{name} must produce non-empty machine code"
3857            );
3858        }
3859    }
3860
3861    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
3862    /// target must fail cleanly (not panic) even on the optimized path.
3863    #[test]
3864    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
3865        let backend = ArmBackend::new();
3866        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3867        let config = CompileConfig {
3868            target: TargetSpec::cortex_m3(),
3869            ..CompileConfig::default()
3870        };
3871
3872        let result = backend.compile_function("fdiv", &ops, &config);
3873        assert!(
3874            result.is_err(),
3875            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
3876        );
3877    }
3878
3879    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
3880    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
3881    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
3882    /// real cmp-chain instead of silently dropping it (which left all arms in
3883    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
3884    /// selector compare). Execution correctness is gated by
3885    /// `scripts/repro/br_table_507_differential.py`.
3886    #[test]
3887    fn test_507_br_table_declines_to_direct() {
3888        let backend = ArmBackend::new();
3889        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
3890        let ops = vec![
3891            WasmOp::Block,
3892            WasmOp::Block,
3893            WasmOp::Block,
3894            WasmOp::LocalGet(0),
3895            WasmOp::BrTable {
3896                targets: vec![0, 1, 2],
3897                default: 2,
3898            },
3899            WasmOp::End,
3900            WasmOp::I32Const(0),
3901            WasmOp::I32Const(10),
3902            WasmOp::I32Store {
3903                offset: 0,
3904                align: 2,
3905            },
3906            WasmOp::Return,
3907            WasmOp::End,
3908            WasmOp::I32Const(0),
3909            WasmOp::I32Const(20),
3910            WasmOp::I32Store {
3911                offset: 0,
3912                align: 2,
3913            },
3914            WasmOp::Return,
3915            WasmOp::End,
3916            WasmOp::I32Const(0),
3917            WasmOp::I32Const(30),
3918            WasmOp::I32Store {
3919                offset: 0,
3920                align: 2,
3921            },
3922        ];
3923        let opt = CompileConfig {
3924            target: TargetSpec::cortex_m4(),
3925            ..CompileConfig::default()
3926        };
3927        let direct = CompileConfig {
3928            target: TargetSpec::cortex_m4(),
3929            no_optimize: true,
3930            ..CompileConfig::default()
3931        };
3932        let a = backend
3933            .compile_function("dispatch", &ops, &opt)
3934            .expect("optimized-default must compile br_table (via decline)");
3935        let b = backend
3936            .compile_function("dispatch", &ops, &direct)
3937            .expect("direct must compile br_table");
3938        assert_eq!(
3939            a.code, b.code,
3940            "#507: optimized-default br_table output must be byte-identical to the \
3941             direct selector (i.e. declined to direct), not a dropped dispatch"
3942        );
3943    }
3944
3945    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
3946    /// FFI-return hi32 extract pattern. Compiles two near-identical
3947    /// functions — one with the optimized shift-by-32, one with a generic
3948    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
3949    #[test]
3950    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
3951        let backend = ArmBackend::new();
3952        let config = CompileConfig {
3953            target: TargetSpec::cortex_m4f(),
3954            ..CompileConfig::default()
3955        };
3956
3957        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
3958        // path now declines i64-param functions to the direct selector (it homed
3959        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
3960        // byte-size-only assertion masked). The canonical #94 case is a u64 from
3961        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
3962        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
3963        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
3964        // still exercised on CORRECT code.
3965        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
3966        let ops_hi32 = vec![
3967            WasmOp::LocalGet(0), // i32 param in R0
3968            WasmOp::I64ExtendI32S,
3969            WasmOp::I64Const(32),
3970            WasmOp::I64ShrU,
3971            WasmOp::I32WrapI64,
3972        ];
3973        let func_hi32 = backend
3974            .compile_function("hi32_extract", &ops_hi32, &config)
3975            .unwrap();
3976
3977        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
3978        // is not a multiple of 32, so it falls through to the runtime shift.
3979        let ops_generic = vec![
3980            WasmOp::LocalGet(0),
3981            WasmOp::I64ExtendI32S,
3982            WasmOp::I64Const(7),
3983            WasmOp::I64ShrU,
3984            WasmOp::I32WrapI64,
3985        ];
3986        let func_generic = backend
3987            .compile_function("generic_shr", &ops_generic, &config)
3988            .unwrap();
3989
3990        let bytes_hi32 = func_hi32.code.len();
3991        let bytes_generic = func_generic.code.len();
3992        println!(
3993            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
3994            bytes_hi32,
3995            bytes_generic,
3996            bytes_generic.saturating_sub(bytes_hi32)
3997        );
3998        let hex: String = func_hi32
3999            .code
4000            .iter()
4001            .map(|b| format!("{:02x}", b))
4002            .collect::<Vec<_>>()
4003            .join(" ");
4004        println!("[issue #94] hi32 bytes: {}", hex);
4005        // We expect the optimized form to be at least 30 bytes smaller than
4006        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
4007        assert!(
4008            bytes_hi32 + 30 <= bytes_generic,
4009            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
4010             expected optimized form to be at least 30 bytes smaller",
4011            bytes_hi32,
4012            bytes_generic,
4013        );
4014    }
4015}