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            let func_config = if params.is_some()
119                || params_f32.is_some()
120                || params_f64.is_some()
121                || !func.block_arity.is_empty()
122                || declared_params.is_some()
123                || ret_f32
124                || ret_f64
125            {
126                Some(CompileConfig {
127                    current_func_params_i64: params.cloned().unwrap_or_default(),
128                    current_func_params_f32: params_f32.cloned().unwrap_or_default(),
129                    current_func_params_f64: params_f64.cloned().unwrap_or_default(),
130                    current_func_ret_f32: ret_f32,
131                    current_func_ret_f64: ret_f64,
132                    current_func_block_arity: func.block_arity.clone(),
133                    current_func_param_count: declared_params,
134                    ..config.clone()
135                })
136            } else {
137                None
138            };
139            let cfg = func_config.as_ref().unwrap_or(config);
140            let compiled = self.compile_function(&name, &func.ops, cfg)?;
141            functions.push(compiled);
142        }
143
144        Ok(CompilationResult {
145            functions,
146            elf: None,
147            backend_name: self.name().to_string(),
148        })
149    }
150
151    fn compile_function(
152        &self,
153        name: &str,
154        ops: &[WasmOp],
155        config: &CompileConfig,
156    ) -> Result<CompiledFunction, BackendError> {
157        let (code, relocations, line_map, branch_map, final_instrs) =
158            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
159
160        // #778: derive the SOUND static WCET intermediate from the final Thumb-2
161        // stream. Only present for the Thumb-2 path; the core class (from the
162        // triple) decides whether the bound is sound (M3/M4) or declined (M7).
163        // Phase 2: any --wcet-hints entry for THIS function is verified (never
164        // trusted) by the loop analyzer. Phase 3: the intermediate carries the
165        // own-body cycles + direct call sites; the module driver composes it across
166        // the call graph. `wcet` here is the SINGLE-FUNCTION view (unresolved direct
167        // calls decline `call`) — a valid standalone answer, overwritten by the
168        // composed result when the driver runs the second pass.
169        let wcet_intermediate = final_instrs.as_ref().map(|instrs| {
170            let hints = config
171                .wcet_hints
172                .as_ref()
173                .and_then(|h| h.functions.get(name));
174            let self_label = config.current_func_index.map(|i| format!("func_{i}"));
175            crate::wcet::function_wcet_intermediate(
176                name,
177                instrs,
178                &config.target.triple,
179                hints,
180                self_label.as_deref(),
181            )
182        });
183        // The SINGLE-FUNCTION standalone view (unresolved direct calls decline
184        // `call`). Kept as a per-function fallback for any consumer that reads a
185        // lone `CompiledFunction` without running the module composer; the CLI
186        // `--emit-wcet` path IGNORES this and composes `wcet_intermediate` across
187        // the whole call graph instead (its result overwrites the report).
188        let wcet = final_instrs.map(|instrs| {
189            let hints = config
190                .wcet_hints
191                .as_ref()
192                .and_then(|h| h.functions.get(name));
193            crate::wcet::function_wcet_with_hints(name, &instrs, &config.target.triple, hints)
194        });
195
196        Ok(CompiledFunction {
197            name: name.to_string(),
198            code,
199            wasm_ops: ops.to_vec(),
200            relocations,
201            line_map,
202            branch_map,
203            wcet,
204            wcet_intermediate,
205        })
206    }
207
208    fn is_available(&self) -> bool {
209        true // Always available — it's a library backend
210    }
211}
212
213/// Count the number of function parameters by analyzing LocalGet patterns
214fn count_params(wasm_ops: &[WasmOp]) -> u32 {
215    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
216    for op in wasm_ops {
217        match op {
218            WasmOp::LocalGet(idx) => {
219                first_access.entry(*idx).or_insert(true);
220            }
221            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
222                first_access.entry(*idx).or_insert(false);
223            }
224            _ => {}
225        }
226    }
227
228    first_access
229        .iter()
230        .filter_map(
231            |(&idx, &is_read_first)| {
232                if is_read_first { Some(idx + 1) } else { None }
233            },
234        )
235        .max()
236        .unwrap_or(0)
237}
238
239/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
240/// Moved to `synth_core::rewrite_memory_grow_zero` (#242, VCR-SEL-005) so the
241/// ARM and RISC-V backends share ONE implementation and cannot drift; re-export
242/// here keeps the existing `rewrite_memory_grow_zero(...)` call sites working.
243use synth_core::rewrite_memory_grow_zero;
244
245/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
246/// value — i.e. one targeting a result-typed block/if (forward edge with
247/// results > 0) or a parameterized loop header (backward edge with loop
248/// params > 0)?
249///
250/// The optimized path's wasm→IR lowering drops the carried value on such
251/// edges (the taken arm returns the fall-through result — same class as the
252/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
253/// #507 — the shape is detected on the raw op stream and routed to the direct
254/// selector, whose #509 designated-result-register lowering lands the value
255/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
256/// side-table; when it is empty (hand-built op streams) every block reads as
257/// void and this never fires, keeping the optimized path byte-identical for
258/// every existing caller. Frozen-safe for the same reason as #507: the frozen
259/// fixtures compile `--relocatable` (already direct), and no optimized-path
260/// fixture branches to a result-typed block.
261fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
262    // Open control constructs: (is_loop, params, results), innermost last.
263    let mut open: Vec<(bool, u8, u8)> = Vec::new();
264    let mut ctrl_ord = 0usize;
265    // A branch edge carries a value when its target is a result-typed forward
266    // join (block/if) or a parameterized loop header.
267    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
268        let Some(&(is_loop, params, results)) = open
269            .len()
270            .checked_sub(1 + depth as usize)
271            .and_then(|i| open.get(i))
272        else {
273            return false; // function-level target — handled by Return lowering
274        };
275        if is_loop { params > 0 } else { results > 0 }
276    };
277    for op in wasm_ops {
278        match op {
279            WasmOp::Block | WasmOp::If => {
280                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
281                ctrl_ord += 1;
282                open.push((false, p, r));
283            }
284            WasmOp::Loop => {
285                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
286                ctrl_ord += 1;
287                open.push((true, p, r));
288            }
289            WasmOp::End => {
290                open.pop(); // None only at the function-level end — harmless
291            }
292            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
293            WasmOp::BrTable { targets, default }
294                if targets
295                    .iter()
296                    .chain(std::iter::once(default))
297                    .any(|d| carries(&open, *d)) =>
298            {
299                return true;
300            }
301            _ => {}
302        }
303    }
304    false
305}
306
307/// Core compilation: WASM ops → ARM machine code bytes + relocations
308///
309/// Returns (code_bytes, relocations) where relocations record BL instructions
310/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
311type CompileArmOutput = (
312    Vec<u8>,
313    Vec<CodeRelocation>,
314    LineMap,
315    synth_core::backend::BranchMap,
316    // #778: the SOUND static WCET result over the final Thumb-2 stream, computed
317    // by `compile_function` (which knows the function name); `None` for the A32
318    // path. Purely additive metadata — does not touch `code`.
319    Option<Vec<synth_synthesis::ArmInstruction>>,
320);
321
322fn compile_wasm_to_arm(
323    wasm_ops: &[WasmOp],
324    config: &CompileConfig,
325) -> Result<CompileArmOutput, String> {
326    // #539: `memory.grow(0)` must return the CURRENT page count, not the
327    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
328    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
329    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
330    // is semantically identical to `memory.size`, which the backend already
331    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
332    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
333    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
334    // cannot grow); a runtime delta that happens to be 0 is the documented
335    // follow-up.
336    let rewritten = rewrite_memory_grow_zero(wasm_ops);
337    // #494 phase 2b: the fact-spec guard-elision marks are keyed by op index
338    // into the stream the DRIVER handed us. The memory.grow(0) fold above can
339    // only shift indices AT OR AFTER a `memory.grow` — an op the fact-spec
340    // walk never crosses (it stops at the first untracked op, so no mark can
341    // follow one). Defense in depth: if the fold fired at all, drop the marks
342    // loudly rather than risk keying a guard elision to the wrong op.
343    //
344    // VCR-MEM-004 (#901): scry's externally-proven bounds-guard marks ride the
345    // SAME defensive gate for the SAME reason — they are op-index keyed, so an
346    // index shift would strip the guard off the wrong access. They are unioned
347    // with #494's certificate-discharged marks here (one consumption point,
348    // two authorities; `CompileConfig` keeps them separate so the attestation
349    // can say which one covered each site).
350    let (fact_div_zero_elide, fact_div_ovf_elide, mem_bounds_elide): (
351        &[usize],
352        &[usize],
353        Vec<usize>,
354    ) = if rewritten.len() == wasm_ops.len() {
355        let mut mem = config.fact_mem_bounds_elide.clone();
356        mem.extend_from_slice(&config.proven_safe_mem_elide);
357        mem.sort_unstable();
358        mem.dedup();
359        (&config.fact_div_zero_elide, &config.fact_div_ovf_elide, mem)
360    } else {
361        if !config.fact_div_zero_elide.is_empty()
362            || !config.fact_div_ovf_elide.is_empty()
363            || !config.fact_mem_bounds_elide.is_empty()
364        {
365            eprintln!(
366                "fact-spec: DECLINE guard elision marks dropped — the                      memory.grow(0) fold shifted op indices (#494 defensive gate);                      general lowering emitted"
367            );
368        }
369        if !config.proven_safe_mem_elide.is_empty() {
370            eprintln!(
371                "proven-safe: DECLINE {} bounds-guard elision mark(s) dropped — the \
372                 memory.grow(0) fold shifted op indices, so the (func, pc) keys no longer \
373                 name the accesses scry proved (VCR-MEM-004 defensive gate, #901); every \
374                 guard is retained",
375                config.proven_safe_mem_elide.len()
376            );
377        }
378        (&[], &[], Vec::new())
379    };
380    let wasm_ops: &[WasmOp] = &rewritten;
381
382    // #457: `count_params` INFERS the param count from access patterns (a local
383    // whose first access is a read is assumed to be a param), so a
384    // read-before-write NON-PARAM local — which WASM zero-initializes — was
385    // indistinguishable from a param: it got homed in a parameter register and
386    // read caller garbage instead of 0. When the driver supplied the DECLARED
387    // count (`current_func_param_count`, from the module's type section), cap
388    // the inference with it. `min` (not a plain override) keeps every function
389    // whose inference is <= declared byte-identical: the inferred count can only
390    // EXCEED the declared one via a read-first local index >= the declared count
391    // — i.e. exactly the read-before-write locals this issue is about.
392    let inferred_params = count_params(wasm_ops);
393    let num_params = match config.current_func_param_count {
394        Some(declared) => inferred_params.min(declared),
395        None => inferred_params,
396    };
397    // A read-before-write non-param local exists iff the capped count dropped.
398    // Such locals need the wasm-mandated zero-init, which only the direct
399    // selector emits — the optimized path's `ir_to_arm` maps a non-param
400    // local's vreg onto an r4+ temp with no initialization (caller garbage).
401    let has_rbw_local = num_params < inferred_params;
402
403    let bounds_config = match config.effective_safety_bounds() {
404        SafetyBounds::None => BoundsCheckConfig::None,
405        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
406        SafetyBounds::Software => BoundsCheckConfig::Software,
407        SafetyBounds::Mask => {
408            // #651 (mirroring the RISC-V backend's compile-time decline):
409            // index masking wraps `ea & (size-1)` — a modulo only when the
410            // linear-memory size is a power of two. With a non-power-of-two
411            // size the AND would silently REMAP in-bounds addresses (e.g.
412            // 0x18000 & 0x2FFFF = 0x8000 for a 192 KiB memory). Decline
413            // loudly rather than miscompile. `linear_memory_bytes == 0`
414            // means "unknown" (plain per-function path, no module context)
415            // — the startup default of one 64 KiB page is a power of two.
416            let bytes = config.linear_memory_bytes;
417            if bytes != 0 && !bytes.is_power_of_two() {
418                return Err(format!(
419                    "--safety-bounds mask requires a power-of-two linear-memory \
420                     size, got {bytes} bytes — switch to --safety-bounds software \
421                     for the deterministic check (#651)"
422                ));
423            }
424            BoundsCheckConfig::Masking
425        }
426    };
427
428    // The non-optimized (direct) instruction-selection path. Handles f32 via
429    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
430    // when the optimized path declines a module (see issue #120 below).
431    //
432    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
433    // `spill_on_exhaustion` set only on the retry — the first pass is the
434    // unmodified default, so every function that compiles today is selected by
435    // exactly the code that compiled it yesterday (bit-identity is structural,
436    // not behavioural).
437    let select_direct_attempt = |spill_on_exhaustion: bool,
438                                 param_backing_on_exhaustion: bool,
439                                 local_promote: bool,
440                                 i64_spill_slots: Option<usize>,
441                                 vfp_spill_on_exhaustion: bool|
442     -> Result<Vec<ArmInstruction>, synth_core::Error> {
443        let db = RuleDatabase::with_standard_rules();
444        let mut selector =
445            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
446        selector.set_target(config.target.fpu, &config.target.triple);
447        if config.num_imports > 0 {
448            selector.set_num_imports(config.num_imports);
449        }
450        // #195: plumb the callee argument-count tables so the direct selector can
451        // marshal call arguments into R0–R3 per AAPCS.
452        selector.set_func_arg_counts(
453            config.func_arg_counts.clone(),
454            config.type_arg_counts.clone(),
455        );
456        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
457        // imports (rewritten to the wasm field name by build_relocatable_elf)
458        // instead of `__meld_dispatch_import`.
459        selector.set_relocatable(config.relocatable);
460        // #642: call_indirect guard inputs (compile-time table size for the
461        // bounds guard + closed-world type verdicts). Without them, every
462        // call_indirect lowering declines loudly.
463        selector.set_call_indirect_guards(config.call_indirect_guards.clone());
464        // #275: on the self-contained image path (NOT --relocatable) the R11
465        // funcref-table dispatch is a silent miscompile — the region is only
466        // populated by an external runtime, which a self-contained ELF does
467        // not have, so the dispatch would read function pointers from
468        // linear-memory data. Two outcomes:
469        //  - the Thumb-2 `--cortex-m` image path (CLI-flagged: the builder
470        //    that emits and patches the flash-resident funcref table will
471        //    run) lowers call_indirect through that table, PC-relative,
472        //    never via R11;
473        //  - every OTHER self-contained configuration (A32/Cortex-R5, the
474        //    simple-ELF builder, imports present) keeps the loud decline.
475        // The host-linked (--relocatable) path keeps the guarded R11
476        // dispatch: there a runtime places the table region at R11.
477        let self_contained_table = config.self_contained_funcref_table
478            && matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
479        selector
480            .set_reject_self_contained_call_indirect(!config.relocatable && !self_contained_table);
481        selector.set_self_contained_funcref_table(self_contained_table);
482        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
483        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
484        // VCR-MEM-002 phase 1 (#406): per-memory initial page counts — enables
485        // the multi-memory arms (memory-0 lowering never reads it; empty ⇒
486        // every multi-memory op declines loudly).
487        selector.set_memory_pages(config.memory_pages.clone());
488        // #311: i64 call results are register PAIRS — tag them.
489        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
490        // #359: declared param widths of THIS function, so the AAPCS stack-arg
491        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
492        selector.set_params_i64(config.current_func_params_i64.clone());
493        // GI-FPU-002 (#619/#369): declared f32-param mask — home hard-float f32
494        // args in S0..S15 (AAPCS-VFP) instead of the R0..R3 integer path.
495        selector.set_params_f32(config.current_func_params_f32.clone());
496        // GI-FPU-002 phase 2 (#369): declared f64-param mask — hard-float
497        // targets decline f64-param functions loudly (no D-register homing yet).
498        selector.set_params_f64(config.current_func_params_f64.clone());
499        // GI-FPU-002 phase 2 (#719/#369): THIS function's f32/f64 return flag, so
500        // the epilogue loudly declines a float result reaching it in a core
501        // register (never a silent integer R0 return where a caller reads S0/D0).
502        selector.set_ret_float(config.current_func_ret_f32, config.current_func_ret_f64);
503        // GI-FPU-002 phase 3 (#369): per-callee float-signature tables. `Call`
504        // marshals the AAPCS-VFP boundary from these (float args into S0../D0..,
505        // float results out of S0/D0); `CallIndirect` still declines a
506        // float-returning static type loudly.
507        selector.set_float_call_signatures(
508            config.func_ret_f32.clone(),
509            config.func_ret_f64.clone(),
510            config.type_ret_f32.clone(),
511            config.type_ret_f64.clone(),
512            config.func_params_f32.clone(),
513            config.func_params_f64.clone(),
514        );
515        // #509: blocktype-arity side-table of THIS function, so value-carrying
516        // br/br_if/br_table land the carried value in the target block's
517        // designated result register instead of dropping it. Empty ⇒ legacy
518        // void-block lowering.
519        selector.set_block_arity(config.current_func_block_arity.clone());
520        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
521        // gating here keeps every non-native compile (all frozen fixtures) on the
522        // legacy R9 globals-table path, bit-identical.
523        if config.native_pointer_abi
524            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
525        {
526            selector.set_native_pointer_stack(sp_idx, sp_init);
527        }
528        // #643: per-global slot widths — i64/f64 globals occupy 8-byte slots
529        // (register-pair store/load) and shift every later global's offset.
530        // Empty for i32-only modules ⇒ the legacy `idx * 4` layout, unchanged.
531        selector.set_global_widths(config.global_widths.clone());
532        selector.set_spill_on_exhaustion(spill_on_exhaustion);
533        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
534        // #881 (VCR-RA-004): VFP register-file spilling, set ONLY on the retry
535        // after an attempt failed with a GI-FPU-002 exhaustion Err — functions
536        // that compile without it keep byte-identical output by construction.
537        selector.set_vfp_spill_on_exhaustion(vfp_spill_on_exhaustion);
538        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
539        // retry after an attempt failed with the slot-pool-exhausted Err —
540        // functions that compile with the default pool keep their frame
541        // byte-identical by construction.
542        if let Some(slots) = i64_spill_slots {
543            selector.set_i64_spill_slots(slots);
544        }
545        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
546        // in callee-saved registers instead of frame slots — the structural lever
547        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
548        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
549        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
550        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
551        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
552        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
553        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
554        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
555        // which on a dense function leaves the spill allocator with nothing to
556        // free → the frame-slot path is the escape that restores compilability).
557        selector.set_local_promote(local_promote);
558        // #494 phase 2b: certificate-discharged div/rem trap-guard elision
559        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
560        selector
561            .set_fact_div_guard_elisions(fact_div_zero_elide.to_vec(), fact_div_ovf_elide.to_vec());
562        // #494 bounds-elision + VCR-MEM-004 (#901): per-site memory
563        // bounds-guard marks, unioned above. Empty in every compile without
564        // SYNTH_FACT_SPEC + facts or --proven-safe.
565        selector.set_fact_mem_bounds_elisions(mem_bounds_elide.clone());
566        selector.select_with_stack(wasm_ops, num_params)
567    };
568    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
569        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
570        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
571        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
572        // The full exhaustion-recovery ladder, parameterized on whether local
573        // promotion is enabled. Each rung is reached only when the previous one
574        // returned a recoverable register-exhaustion Err, so a function that
575        // compiles on the first attempt is untouched by the later rungs. Returns
576        // the result AND which rung produced it (for the #242 measurement below).
577        let recovery_ladder = |promote: bool,
578                               i64_spill_slots: Option<usize>,
579                               vfp_spill: bool|
580         -> (
581            Result<Vec<ArmInstruction>, synth_core::Error>,
582            &'static str,
583        ) {
584            let mut attempt =
585                select_direct_attempt(false, false, promote, i64_spill_slots, vfp_spill);
586            let mut rung = "base";
587            // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
588            // hard-fail is recoverable — retry with spill-on-exhaustion, which
589            // reserves the spill area and spills the deepest stack value when
590            // the pool is full.
591            if let Err(e) = &attempt
592                && e.to_string().contains(SINGLE_EXHAUSTION)
593            {
594                attempt = select_direct_attempt(true, false, promote, i64_spill_slots, vfp_spill);
595                rung = "spill";
596            }
597            // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
598            // exhaustion is recoverable too — not by stack spilling (the pair
599            // allocator already spills stack values, #171) but by frame-backing
600            // the params (#204) so they stop pinning R0-R3, with spill kept on.
601            if let Err(e) = &attempt
602                && e.to_string().contains(PAIR_EXHAUSTION)
603            {
604                attempt = select_direct_attempt(true, true, promote, i64_spill_slots, vfp_spill);
605                rung = "param-backing";
606            }
607            (attempt, rung)
608        };
609        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
610        // must never be the reason a function fails to compile. Run the full ladder
611        // with promotion first (so every function that compiles today is
612        // bit-identical), and if it still ends in register exhaustion, fall back to
613        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
614        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
615        // pins r4-r8 for the locals; on a dense function that leaves the allocator
616        // with nothing to free, so dropping it restores compilability. The fallback
617        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
618        // output is untouched by construction (frozen byte gate stays green).
619        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
620        // The full pre-#587 recovery sequence (promotion-on ladder, then the
621        // #474 promotion-off fallback), parameterized on the pool size so the
622        // pool-grow retry below reruns it verbatim.
623        let full_sequence = |slots: Option<usize>,
624                             vfp_spill: bool|
625         -> (
626            Result<Vec<ArmInstruction>, synth_core::Error>,
627            &'static str,
628            bool,
629        ) {
630            let (mut attempt, mut rung) = recovery_ladder(promote, slots, vfp_spill);
631            let mut promotion_dropped = false;
632            if promote
633                && attempt
634                    .as_ref()
635                    .err()
636                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
637            {
638                let (rescued, off_rung) = recovery_ladder(false, slots, vfp_spill);
639                if rescued.is_ok() {
640                    attempt = rescued;
641                    rung = off_rung;
642                    promotion_dropped = true;
643                }
644            }
645            (attempt, rung, promotion_dropped)
646        };
647        let (mut attempt, mut rung, mut promotion_dropped) = full_sequence(None, false);
648        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
649        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
650        // an i64-dense function simply has more values simultaneously live than
651        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
652        // modes) with the pool sized from a conservative operand-stack-depth
653        // bound: the number of simultaneously spilled values can never exceed
654        // the operand-stack depth, plus a few transient slots (the arg-move
655        // cycle resolver and call-result parking each borrow one). The selector
656        // clamps the request to its 12-bit-friendly cap; a function that still
657        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
658        // promotion-off fallback — so any function that compiled yesterday
659        // (through any rung or fallback) is produced by exactly yesterday's
660        // path, byte-identical; the grown pool only ever fires for functions
661        // whose every existing escape ended in the slot-pool Err.
662        if attempt
663            .as_ref()
664            .err()
665            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
666        {
667            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
668            let (grown, _, grown_dropped) = full_sequence(Some(depth.saturating_add(4)), false);
669            if grown.is_ok() {
670                attempt = grown;
671                rung = "pool-grow";
672                promotion_dropped = grown_dropped;
673            }
674        }
675        // #881 (VCR-RA-004): the GI-FPU-002 VFP register-file exhaustion is
676        // recoverable too — retry the ENTIRE sequence with VFP spilling
677        // enabled (the pre-op pressure guard spills the deepest segment-local
678        // f32/f64 stack value into the shared spill area and reloads spilled
679        // operands before their consumers). Deliberately LAST, after every
680        // integer rung, so any function that compiled yesterday is produced
681        // by exactly yesterday's path; the VFP rung only ever fires for
682        // functions whose every existing escape ended in a GI-FPU-002
683        // exhaustion Err (previously an unconditional loud skip). A VFP-
684        // spilling function can in turn exhaust the shared slot pool — the
685        // #587 pool-grow retry composes inside the rung.
686        const VFP_S_EXHAUSTION: &str = "VFP register file exhausted";
687        const VFP_D_EXHAUSTION: &str = "VFP D-register file exhausted";
688        if attempt.as_ref().err().is_some_and(|e| {
689            let msg = e.to_string();
690            msg.contains(VFP_S_EXHAUSTION) || msg.contains(VFP_D_EXHAUSTION)
691        }) {
692            let (vfp, vfp_rung, vfp_dropped) = full_sequence(None, true);
693            let (vfp, vfp_rung, vfp_dropped) = if vfp.as_ref().err().is_some_and(|e| {
694                let msg = e.to_string();
695                msg.contains(SLOT_EXHAUSTION) || msg.contains("spilling the VFP register file")
696            }) {
697                let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
698                let (grown, grown_rung, grown_dropped) =
699                    full_sequence(Some(depth.saturating_add(4)), true);
700                if grown.is_ok() {
701                    (grown, grown_rung, grown_dropped)
702                } else {
703                    (vfp, vfp_rung, vfp_dropped)
704                }
705            } else {
706                (vfp, vfp_rung, vfp_dropped)
707            };
708            if vfp.is_ok() {
709                attempt = vfp;
710                rung = match vfp_rung {
711                    "base" => "vfp-spill",
712                    _ => "vfp-spill+int",
713                };
714                promotion_dropped = vfp_dropped;
715            }
716        }
717        // VCR-RA measurement (#242): log which recovery rung produced the result,
718        // so the per-rung distribution across a corpus can be measured — the size
719        // of the failure surface a verified allocator must subsume (see
720        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
721        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
722        if std::env::var("SYNTH_RECOVERY_STATS").is_ok() {
723            eprintln!(
724                "[recovery-stats] rung={rung}{} result={}",
725                if promotion_dropped {
726                    " promotion-off"
727                } else {
728                    ""
729                },
730                if attempt.is_ok() { "ok" } else { "exhausted" },
731            );
732        }
733        attempt.map_err(|e| format!("instruction selection failed: {}", e))
734    };
735
736    // Instruction selection: optimized or direct.
737    //
738    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
739    // optimized path materializes an absolute linmem base (0x20000100) and does
740    // not preserve caller-saved registers across calls — both wrong for a
741    // host-linked object, where the linmem base arrives via `fp` at runtime and
742    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
743    // #171) handles fp-relative memory + caller-saved preservation correctly.
744    //
745    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
746    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
747    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
748    // SILENT miscompile (every input hits the last arm). The selector value isn't
749    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
750    // to fall back on; detect it on the raw wasm op stream here and force the
751    // direct selector (`select_with_stack` lowers `br_table` correctly as a
752    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
753    // contract as the issue-#120 f32 decline: the function still compiles
754    // correctly, just without IR-level optimization. Frozen-safe: the frozen
755    // fixtures compile `--relocatable` (already direct), and no optimized-path
756    // fixture (control_step, flight_algo) contains `br_table`.
757    let has_br_table = wasm_ops
758        .iter()
759        .any(|op| matches!(op, WasmOp::BrTable { .. }));
760    // #509: the optimized path also drops the value carried by a `br`/`br_if`
761    // to a result-typed block (the taken edge returns the wrong arm's value —
762    // same silent-miscompile class as the #507 br_table drop). Route the shape
763    // to the direct selector, whose designated-result-register lowering (#509)
764    // lands the carried value at the join. Never fires for void-block control
765    // flow (all frozen/optimized fixtures), so those stay byte-identical.
766    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
767    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
768    // direct selector. The optimized path's param homing is width-naive — its
769    // #518 decline covers only functions that READ an i64 param (an `I64Load`
770    // from a param index), so a function that reads an i32 param whose AAPCS
771    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
772    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
773    // silently miscompiled rather than falling back. The direct selector's
774    // `aapcs_param_layout` homing handles every such shape (i64-param READS
775    // already fell back to it via the ir_to_arm Err, so those functions emit
776    // the same bytes as before). `num_params` counts read-first locals, so a
777    // function that never touches any param keeps the optimized path.
778    let has_wide_param = config
779        .current_func_params_i64
780        .iter()
781        .take(num_params as usize)
782        .any(|&w| w);
783    // #782(b): a HARD-float (FPU) target passes f32 args in VFP S-registers
784    // and returns floats in S0/D0 (AAPCS-VFP) — but the optimized path's
785    // param/return homing is float-naive (integer R0..R3 args, R0 return). A
786    // function whose ops ALL lower on the optimized path but whose SIGNATURE
787    // carries a float — e.g. the pure value-pick
788    // `(param f32 f32 i32) (result f32) select`, no float OP to trip the
789    // issue-#120 ir_to_arm fallback — was silently compiled with the integer
790    // ABI: callers marshal S0/S1, the body reads R0/R1. Route every
791    // float-signature function to the direct selector (AAPCS-VFP homing, or
792    // an honest decline). Soft-float targets (no FPU) keep the optimized
793    // path: the integer treatment IS the ABI there — byte-identical. (f64
794    // params already route direct via `has_wide_param`; this adds f32 params
795    // and f32/f64 returns.)
796    let has_float_sig = config.target.fpu.is_some()
797        && (config.current_func_ret_f32
798            || config.current_func_ret_f64
799            || config
800                .current_func_params_f32
801                .iter()
802                .take(num_params as usize)
803                .any(|&f| f)
804            || config
805                .current_func_params_f64
806                .iter()
807                .take(num_params as usize)
808                .any(|&f| f));
809    // #494 phase 2b: div/rem guard-elision marks are consumed by the DIRECT
810    // selector only — the optimized path's IR passes (const-fold/CSE/DCE)
811    // renumber instructions, so an op-index-keyed mark cannot soundly survive
812    // them. Route marked functions direct (the #507/#509 honest-degradation
813    // pattern). Never fires without SYNTH_FACT_SPEC + facts + a discharged
814    // obligation, so every existing compile keeps its path byte-identical.
815    let has_fact_div_elide = !fact_div_zero_elide.is_empty()
816        || !fact_div_ovf_elide.is_empty()
817        // #494 bounds-elision + VCR-MEM-004 (#901): memory bounds-guard marks
818        // are direct-selector keyed for the same reason (IR passes renumber
819        // instructions). This is ALSO why the optimized path's
820        // `push_software_bounds_guard` sites never need mark plumbing: a
821        // marked function is routed away from that path entirely.
822        || !mem_bounds_elide.is_empty();
823    // #643: the optimized path's global lowering is width-naive — `GlobalGet`/
824    // `GlobalSet` are single-word `[R9, idx*4]` accesses, which (a) silently
825    // dropped the high word of every i64 global and (b) mis-address every
826    // global whose offset an earlier wide (i64/f64) slot shifted. When the
827    // module has any wide global, route every global-touching function to the
828    // direct selector, whose type-aware summed layout pairs the access (or
829    // declines loudly). Modules with only 4-byte globals — every existing
830    // fixture — keep the optimized path byte-identical.
831    let has_wide_global_module = config.global_widths.iter().any(|&w| w > 4);
832    let has_global_access = has_wide_global_module
833        && wasm_ops
834            .iter()
835            .any(|op| matches!(op, WasmOp::GlobalGet(_) | WasmOp::GlobalSet(_)));
836    // VCR-VER-001 (#242): `post_exhaust` scopes the post-exhaustion cleanup
837    // extensions to functions whose bytes the #580 spill-on-exhaustion
838    // machinery actually shaped (bridge-reported). Everything else — the
839    // direct path, non-exhausted optimized functions — stays byte-identical
840    // flag-on (the `vcr_ver_001_gate_242` lock's contract).
841    let (arm_instrs, post_exhaust) = if config.no_optimize
842        || config.relocatable
843        || has_br_table
844        || has_value_carry
845        || has_wide_param
846        || has_float_sig
847        || has_global_access
848        || has_fact_div_elide
849        // #457: route read-before-write non-param locals to the direct
850        // selector, whose prologue zero-init lands the wasm-mandated 0.
851        || has_rbw_local
852    {
853        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
854            eprintln!("[path-debug] direct (pre-gate)");
855        }
856        (select_direct()?, false)
857    } else {
858        let opt_config = if config.loom_compat {
859            OptimizationConfig::loom_compat()
860        } else {
861            OptimizationConfig::all()
862        };
863
864        let mut bridge = OptimizerBridge::with_config(opt_config);
865        // #188: tell the bridge how many imports there are so it declines only
866        // LOCAL calls (and leaves import calls on the optimized path, keeping
867        // the #173 field-name relocation rewrite intact).
868        bridge.set_num_imports(config.num_imports);
869        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
870        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
871        // levers — base-CSE (#468) excludes any access inside a marked range
872        // from its fold set, and the bridge-level const-CSE declines wholesale
873        // while any range is marked. Empty (the default) ⇒ byte-identical.
874        bridge.set_volatile_segments(config.volatile_segments.clone());
875        // #377: thread `--safety-bounds` to the bridge. Pre-fix the optimized
876        // path ignored it — `software`/`mask` were SILENT NO-OPS on the path
877        // that lowers the bulk of a flight loop's i32 loads/stores (byte-
878        // identical to `none`, while the safety manifest claimed otherwise).
879        // `Software` now emits the inline guard per access; `Masking` declines
880        // memory-accessing functions to the direct selector; `None`/`Mpu` are
881        // byte-identical to before.
882        bridge.set_bounds_check(bounds_config);
883        // #687: thread the absolute linear-memory base the optimized path
884        // materializes. Defaults to 0x2000_0100 (byte-identical);
885        // `--stack-layout=low` shifts it up by the reserved stack size so
886        // const-address accesses follow the moved linear memory.
887        bridge.set_linmem_base(config.linmem_base);
888        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
889        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
890        // `optimize_full` failure: fall back to the direct selector rather
891        // than propagating, so the function still compiles correctly.
892        match bridge
893            .optimize_full(wasm_ops)
894            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
895        {
896            Ok(arm_ops) => {
897                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
898                    eprintln!("[path-debug] optimized (ir_to_arm ok)");
899                }
900                (
901                    arm_ops
902                        .into_iter()
903                        .map(|op| ArmInstruction {
904                            op,
905                            source_line: None,
906                        })
907                        .collect(),
908                    bridge.spill_on_exhaust_fired(),
909                )
910            }
911            // Issue #120: the optimized path declines modules it cannot lower
912            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
913            // back to the direct instruction selector, which handles f32 via
914            // VFP/FPU. This is honest degradation: the function still compiles
915            // correctly, just without IR-level optimization.
916            Err(e) => {
917                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
918                    eprintln!("[path-debug] direct (fallback: {e})");
919                }
920                (select_direct()?, false)
921            }
922        }
923    };
924
925    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
926    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
927    // fully tested), but it is **register-allocation-coupled**: over the current
928    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
929    // extends the live ranges of the mul inputs to the mla point, and the added
930    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
931    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
932    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
933    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
934    // registers, at which point it becomes net-positive (per #272's plan and the
935    // wiring design note). Lesson (#277): a register-pressure-affecting transform
936    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
937    // can default on.
938
939    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
940    // LAST, after the immediate-folds — see the apply_const_cse call below
941    // (#242). Earlier it ran here (before range-realloc and the folds), which is
942    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
943    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
944    // would otherwise have absorbed the constant. Running CSE-last makes those
945    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
946    // redundant materializations.
947
948    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
949    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
950    // segment over the R0-R8 pool with value ranges as the allocation unit
951    // (segment inputs + per-register live-outs pinned to their original
952    // registers, reserved R9-R12/SP identity-assigned — each segment is
953    // independently sound, no cross-segment liveness assumed). Renames
954    // registers only: never adds, removes, or reorders instructions, so
955    // labels/branch offsets are unaffected.
956    //
957    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
958    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
959    // flat_flight/controller/control_step, fires on the filter family with
960    // zero cycle delta and a small size win, all selfchecks green on silicon.
961    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
962    // `SYNTH_REALLOC_STATS=1`.
963    //
964    // The companion dead callee-saved-save elimination (gale's "next
965    // consequential lever", same issue comment) then shrinks the prologue
966    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
967    // registers the re-allocated body still touches (leaf-only,
968    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
969    // ~12 cycles of pure save/restore overhead removed on small leaves.
970    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
971    let arm_instrs = if realloc_on {
972        use synth_synthesis::rules::Reg;
973        const POOL: [Reg; 9] = [
974            Reg::R0,
975            Reg::R1,
976            Reg::R2,
977            Reg::R3,
978            Reg::R4,
979            Reg::R5,
980            Reg::R6,
981            Reg::R7,
982            Reg::R8,
983        ];
984        // VCR-DEC-001 (epic #242, the North Star's first foothold): the
985        // SYNTH_GRAPH_ALLOC graph-colouring allocator SPIKE. When enabled it
986        // replaces STEP 1 of the re-allocation (the segment-based
987        // `reallocate_function`) with a whole-function Chaitin/Briggs colouring
988        // (`graph_alloc::reallocate`) built against the SAME acceptance oracle
989        // (`validate_segment_rewrite` trace-equality); the later dead-frame /
990        // callee-saved-prologue / shrink passes still run on its output, so a
991        // value it homes in R4-R8 still gets its callee-saved push (the
992        // invariant the unconditional VCR-RA-003 validator guards). It is
993        // BOUNDED to whole straight-line functions and DECLINES (returns None)
994        // to the shipping `reallocate_function` on any control flow, spill, or
995        // unmodeled op — never a hard-fail. Flag-OFF (`SYNTH_GRAPH_ALLOC` unset)
996        // never enters this branch, so the shipping bytes are byte-identical
997        // (the GOLDEN trick — frozen fixtures unchanged). NO default flip: the
998        // spike ships flag-off; the flip is a later, evidence-gated step.
999        //
1000        // VCR-VER-001 (#242): on a function the spill-on-exhaustion machinery
1001        // shaped, the terminal segment gets relaxed live-out pinning (only
1002        // R0/R1 are observable past `bx lr` at this pre-prologue position) so
1003        // the colourer can lower R4-R8-homed tails into caller-saved R0-R3 —
1004        // shrinking the `push {r4-r8,lr}` the #580 exhaustion shapes pay for.
1005        // `post_exhaust == false` selects the shipping pass bit for bit.
1006        let (out, stats) = if synth_synthesis::graph_alloc::enabled() {
1007            match synth_synthesis::graph_alloc::reallocate(&arm_instrs, &POOL) {
1008                Some(new) => {
1009                    if std::env::var("SYNTH_GRAPH_ALLOC_STATS").is_ok() {
1010                        eprintln!("[graph-alloc] whole-function colouring APPLIED (validated)");
1011                    }
1012                    (new, synth_synthesis::liveness::ReallocStats::default())
1013                }
1014                None => {
1015                    if std::env::var("SYNTH_GRAPH_ALLOC_STATS").is_ok() {
1016                        eprintln!("[graph-alloc] DECLINED → shipping reallocate_function");
1017                    }
1018                    synth_synthesis::liveness::reallocate_function_post_exhaust(
1019                        &arm_instrs,
1020                        &POOL,
1021                        post_exhaust,
1022                    )
1023                }
1024            }
1025        } else {
1026            synth_synthesis::liveness::reallocate_function_post_exhaust(
1027                &arm_instrs,
1028                &POOL,
1029                post_exhaust,
1030            )
1031        };
1032        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
1033            eprintln!(
1034                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
1035                stats.segments,
1036                stats.reallocated,
1037                stats.declined,
1038                stats.validator_rejects,
1039                stats.needs_spill
1040            );
1041        }
1042        // VCR-VER-004 AUDIT (#242) — report-only, opt-in, never gating.
1043        //
1044        // The ABI observable-contract validator is a GATE on the flag-off
1045        // graph-colouring spike. This hook asks the same question of the
1046        // SHIPPING allocator's rewrite, so the answer is a MEASUREMENT rather
1047        // than a claim: how much of the shipping path can a value-level,
1048        // ABI-anchored check actually see today? Report-only DELIBERATELY —
1049        // making it gate here would risk a false rejection on the default
1050        // path, and the honest sequence is measure first, flip on evidence.
1051        // `SYNTH_ABI_CONTRACT_AUDIT=1` prints one verdict per function.
1052        if std::env::var_os("SYNTH_ABI_CONTRACT_AUDIT").is_some() {
1053            eprintln!(
1054                "[abi-contract-audit] {:?}",
1055                synth_synthesis::abi_contract::validate_abi_contract(&arm_instrs, &out)
1056            );
1057        }
1058        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
1059        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
1060        // that promotion homed in registers, never accessed). Removing it saves
1061        // the two instructions AND restores the SP-untouched precondition that
1062        // `shrink_callee_saved_saves` requires — so it must run FIRST.
1063        // DEFAULT-ON (#242 flag audit flip-wave, #592 audit item): evidence
1064        // basis was the 2-path × repro-corpus sweep — 0 functions grow, 58
1065        // shrink (flight_seam controller_step 250→242 −8 / filter_step 180→168
1066        // −12, native_pointer frame_roundtrip 46→34 −12), locked by the
1067        // `dead_frame_elim_no_grow_corpus_242` cargo gate; execution
1068        // differentials re-run green on the new default bytes BEFORE the
1069        // frozen ARM anchors were re-pinned (leaf_dead_frame, flight_seam,
1070        // frame_slot_dce — see the flip PR). Escape hatch:
1071        // `SYNTH_DEAD_FRAME_ELIM=0` opts out and restores the pre-flip bytes
1072        // (CI-gated in `frozen_codegen_bytes.rs`).
1073        let out = if !std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok_and(|v| v == "0") {
1074            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
1075        } else {
1076            out
1077        };
1078        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
1079        // promoted locals but emits no prologue, silently clobbering a caller's
1080        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
1081        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
1082        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
1083        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
1084        // (next) then trims it to the used set. No-op on the direct path (it
1085        // already has its own prologue) and on callee-saved-free leaves.
1086        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
1087        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
1088    } else {
1089        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
1090        // must preserve the callee-saved registers it clobbers (#490). No shrink
1091        // (it is coupled to the realloc lever), so the conservative full save
1092        // stays — correct, just not minimised in this debug configuration.
1093        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
1094    };
1095
1096    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
1097    // the selected stream and LOG what it finds — without changing a single
1098    // emitted byte. This is the measure-only bridge between the built analysis
1099    // layer and the eventual virtual-register wiring: it shows, per real
1100    // function, whether the allocator can colour it within the R0–R8 pool and
1101    // how much const-CSE / rematerialization headroom exists (#209). Enable with
1102    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
1103    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
1104        use synth_synthesis::liveness::{
1105            AllocationOutcome, allocate_function, function_peak_pressure,
1106        };
1107        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
1108        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
1109        let precolored = std::collections::BTreeMap::from([
1110            (synth_synthesis::rules::Reg::R9, 9usize),
1111            (synth_synthesis::rules::Reg::R10, 10),
1112            (synth_synthesis::rules::Reg::R11, 11),
1113            (synth_synthesis::rules::Reg::R12, 12),
1114        ]);
1115        // True VALUE pressure (one node per value, not per reused physical reg):
1116        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
1117        // function fits once virtually allocated.
1118        let peak = function_peak_pressure(&arm_instrs);
1119        match allocate_function(&arm_instrs, 9, &precolored) {
1120            AllocationOutcome::Allocated {
1121                remat_opportunities,
1122                coloring,
1123            } => eprintln!(
1124                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
1125                coloring.len(),
1126                peak,
1127                remat_opportunities
1128            ),
1129            AllocationOutcome::NeedsSpill(s) => eprintln!(
1130                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
1131                s, peak
1132            ),
1133            AllocationOutcome::Declined => {
1134                eprintln!(
1135                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
1136                )
1137            }
1138        }
1139    }
1140
1141    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
1142    // lowers a `select` whose condition is a comparison to a *materialize then
1143    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
1144    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
1145    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
1146    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
1147    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
1148    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
1149    //
1150    // Run LATE: after range re-allocation (so the dead-D proof sees final register
1151    // identities) and before encode. Removal-only + rename-only ⇒ no spill
1152    // regression and labels/branch offsets are unaffected. Each fusion is proven
1153    // sound (flags reused only when nothing clobbers them in the window; the
1154    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
1155    //
1156    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
1157    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
1158    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
1159    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
1160    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
1161    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
1162    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
1163    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
1164    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
1165    // check is a tracked post-ship follow-up (gale owns it).
1166    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
1167        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
1168        // the extra `two_move` count is diagnostic only (the fusion census /
1169        // blast-radius datum — #7 made that arm reachable).
1170        let (out, fused, two_move) =
1171            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
1172        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1173            let in_place = fused - two_move;
1174            eprintln!(
1175                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
1176                 ({two_move} two-move, {in_place} in-place)"
1177            );
1178        }
1179        out
1180    } else {
1181        arm_instrs
1182    };
1183
1184    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
1185    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
1186    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
1187    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
1188    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
1189    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
1190    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
1191    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
1192    // execution differential — the same gated path cmp→select took to default-on in
1193    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
1194    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
1195    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
1196    let arm_instrs = if stack_fwd {
1197        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
1198        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1199            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
1200        }
1201        out
1202    } else {
1203        arm_instrs
1204    };
1205
1206    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
1207    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
1208    // them is a dead store — its slot is never loaded again. Remove it. Pairs
1209    // with (and only pays after) stack-reload forwarding, so it shares the flag.
1210    let arm_instrs = if stack_fwd {
1211        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
1212        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1213            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
1214        }
1215        out
1216    } else {
1217        arm_instrs
1218    };
1219
1220    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
1221    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
1222    // `forward_stack_reloads` (above) forwards only from a spill store's
1223    // SOURCE register, so when register pressure clobbers that source its
1224    // reloads survive; this stage tracks which registers provably still hold
1225    // a frame slot's value (through earlier reloads and reg-reg moves) and
1226    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
1227    // already holds the value). Stage 2 (the Belady re-choice): where NO
1228    // register still holds the value — the genuine-spill case, flat_flight's
1229    // peak-11 hot segment — the value was usually evicted while a dead
1230    // register existed; the clobbering def(s) are renamed onto a provably-dead
1231    // register (`spill_rechoice_segment`) so the value stays resident and the
1232    // reload dissolves outright. A dissolved reload can leave the feeding
1233    // store dead, so the frame-slot DCE sweep runs once more behind the same
1234    // flag. Per-segment commit gates: executable same-value-flow trace
1235    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
1236    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
1237    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
1238    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
1239    // see other segments); `eliminate_unread_frame_stores` walks the whole
1240    // function (labels/branches/loops, SP-displacement tracked) and drops a
1241    // store whose slot NO reachable instruction can read — flat_flight's two
1242    // surviving stores (#576), completing Belady's 0-load side with a 0-store
1243    // side. Same flag: the three stages are one lever, flipped together.
1244    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
1245    // Belady spilling ships by default. Evidence basis for the flip: three
1246    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
1247    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
1248    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
1249    // guards, and the unicorn-vs-wasmtime execution differentials re-run
1250    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
1251    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
1252    // control_step_decide vs wasmtime; control_step's .text is byte-identical
1253    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
1254    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
1255    // and restores the pre-flip bytes (CI-gated by
1256    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
1257    // other value (or unset) runs the pass.
1258    // VCR-VER-001 post-exhaustion extensions (#242, the PR #659 verdict): with
1259    // `SYNTH_SPILL_ON_EXHAUST` active the #580 allocation-time Belady spill
1260    // keeps exhausted functions on the optimized path, and its slots present
1261    // shapes the shipping pass structurally cannot fire on (fresh-monotonic
1262    // slots defeat the overwrite-only DCE; the eviction store's source is
1263    // redefined immediately, defeating store→reload forwarding; R2/R3 are
1264    // never touched again, so the rename-target deadness proof declines them).
1265    // `post_exhaust` (bridge-scoped, see above) enables const
1266    // rematerialization of spilled constants, R2/R3 exit-dead rename targets,
1267    // and per-pair pressure commit — see `apply_spill_realloc_post_exhaust`.
1268    // Flag off (the default): `false` selects the shipping behavior bit for
1269    // bit.
1270    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
1271        let (out, n) =
1272            synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&arm_instrs, post_exhaust);
1273        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
1274        let (mut out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
1275        let (mut tn, mut td, mut tu) = (n, d, u);
1276        // Post-exhaustion only: iterate the triple to a bounded fixpoint. Each
1277        // dissolved spill pair frees registers and removes stores, exposing
1278        // rename windows and holder chains the previous iteration could not
1279        // prove — the allocation-time Belady slots (#580) routinely need two
1280        // or three rounds where the shipping single round suffices for the
1281        // default path's slots. Every iteration is individually gate-proven
1282        // (value-trace equality, pool pressure, strict shrink), so iterating
1283        // composes soundly; the bound keeps compile time deterministic.
1284        if post_exhaust {
1285            let mut progress = n + d + u > 0;
1286            for _ in 0..3 {
1287                if !progress {
1288                    break;
1289                }
1290                let (o, n) =
1291                    synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&out, true);
1292                let (o, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&o);
1293                let (o, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&o);
1294                progress = n + d + u > 0;
1295                (tn, td, tu) = (tn + n, td + d, tu + u);
1296                out = o;
1297            }
1298            // The cleanup can leave the spill frame with zero surviving
1299            // accesses (every reload rematerialized/dissolved, every store
1300            // swept) — the balanced `sub sp,#K`/`add sp,#K` is then pure
1301            // overhead. `elide_dead_frame` proves that and removes the pair;
1302            // its early run (post-realloc) could not, because the spill
1303            // traffic was still in the stream at that point.
1304            out = synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out);
1305        }
1306        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1307            eprintln!(
1308                "[spill-realloc] {tn} reload(s) forwarded/eliminated, {td} newly-dead frame store(s) removed, {tu} unread-slot store(s) removed"
1309            );
1310        }
1311        out
1312    } else {
1313        arm_instrs
1314    };
1315
1316    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
1317    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
1318    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
1319    // instruction, −1 live register. Removal-only (offset-neutral before branch
1320    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
1321    // bit-identical results + a net cycle win on the dissolved hot path (−2
1322    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
1323    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
1324        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
1325        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1326            eprintln!(
1327                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
1328            );
1329        }
1330        out
1331    } else {
1332        arm_instrs
1333    };
1334
1335    // #686: elide the #682 mod-32 shift-amount mask (`and r12,rK,#31` before
1336    // every register-controlled i32 shl/shr) when the amount is STATICALLY
1337    // provable < 32 — a const amount folds to the immediate-shift form
1338    // (reduced mod 32, so >= 32 shrinks too), and an already-masked amount
1339    // (`rK = rX & c`, c < 32) drops the redundant re-mask. gale measured the
1340    // unconditional mask at ~12% cyc/call (+14 B) on gust_mix, whose Q8
1341    // fixed-point shifts are all constants (#686). The mask stays wherever
1342    // the bound is unproven — elision is an optimization, the mask is the
1343    // sound default (`liveness::elide_shift_masks` has the proof
1344    // obligations). Runs after `fold_immediate_shifts` (whose movw→shift
1345    // window the #682 mask intercepts, so it declines every masked const
1346    // shift) and before branch resolution (removal/rewrite-only ⇒
1347    // offset-neutral).
1348    //
1349    // DEFAULT-ON since v0.50.1 (opt-out via `SYNTH_SHIFT_MASK_ELIDE=0`; #846).
1350    // gale's gpio-thin driver regressed +44 B / +9% on synth 0.49 — its pin
1351    // bit-arithmetic (`pin & 31` then a register shift) emits the source
1352    // `and rN,#0x1f` IMMEDIATELY followed by the #682 mod-32 re-mask
1353    // `and r12,rN,#0x1f`; the second is provably redundant (Pattern B: an
1354    // operand produced by `and X,#c`, c<32, is already in [0,31]), so the
1355    // pass drops it. Flipping default-on is a deliberate byte-changing
1356    // refreeze: the elision also moves the frozen anchors (const-amount
1357    // shifts fold back to the immediate form) — control_step −20 B,
1358    // flight_seam −166 B, flight_seam_flat −168 B — all size DECREASES with
1359    // the mask soundly kept for every unproven amount. All differentials were
1360    // re-run on the new bytes and the goldens re-pinned (see #846 PR /
1361    // `frozen_codegen_bytes.rs`). `SYNTH_SHIFT_MASK_ELIDE=0` restores the
1362    // pre-flip bytes (opt-out gate in `shift_mask_elide_686.rs`).
1363    let arm_instrs = if std::env::var("SYNTH_SHIFT_MASK_ELIDE").is_ok_and(|v| v == "0") {
1364        arm_instrs
1365    } else {
1366        let (out, elisions) = synth_synthesis::liveness::elide_shift_masks(&arm_instrs);
1367        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1368            eprintln!(
1369                "[shift-mask-elide] {elisions} provably-<32 shift-amount mask(s) elided (#686)"
1370            );
1371        }
1372        out
1373    };
1374
1375    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
1376    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
1377    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
1378    // modified immediates so the selector materializes them into a register; the
1379    // dedicated zero-extend expresses the same masking inline. Removal-only +
1380    // rewrite-in-place (offset-neutral). DEFAULT-ON (#242 flag audit flip-wave,
1381    // #592 audit item): evidence basis was the 2-path × repro-corpus sweep —
1382    // 0 functions grow, 13 shrink (control_step 300→294 −6, gust_mix 38→32 −6,
1383    // uxth_fold pack 36→24 −12), locked by the `uxth_fold_no_grow_corpus_242`
1384    // cargo gate; execution differentials re-run green on the new default
1385    // bytes BEFORE the frozen ARM anchors were re-pinned (uxth_fold,
1386    // control_step — see the flip PR). Escape hatch: `SYNTH_UXTH_FOLD=0` opts
1387    // out and restores the pre-flip bytes (CI-gated in
1388    // `frozen_codegen_bytes.rs`).
1389    let arm_instrs = if !std::env::var("SYNTH_UXTH_FOLD").is_ok_and(|v| v == "0") {
1390        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
1391        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1392            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
1393        }
1394        out
1395    } else {
1396        arm_instrs
1397    };
1398
1399    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
1400    // `movw`/`mov #imm` that re-materializes a constant already resident in
1401    // another register and retargets the reads — every rewrite proven by the
1402    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
1403    // range-realloc, but BEFORE branch resolution/encoding (it removes
1404    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
1405    // fix: the folds have already absorbed every foldable constant, so CSE can no
1406    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
1407    // size-guards each segment via the byte-estimator — it commits a segment's
1408    // rewrites only if they do not grow its estimated size — so a retarget that
1409    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
1410    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
1411    // template): const-CSE ships by default. The flip prerequisites recorded in
1412    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
1413    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
1414    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
1415    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
1416    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
1417    // 236→148 B), total −536 B — and the execution differentials re-run green
1418    // on the new default bytes BEFORE the frozen goldens were re-pinned
1419    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
1420    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
1421    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
1422    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
1423    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
1424    //
1425    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
1426    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
1427    // cannot be classified as address-vs-data (a retargeted read may be a
1428    // memory-access base carrying a per-use immediate offset), so the
1429    // conservative stance for statically-unknown addressing is to decline every
1430    // aliasing rewrite — each constant is re-materialized at each occurrence,
1431    // the documented volatile contract (`CompileConfig::volatile_segments`).
1432    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
1433        && config.volatile_segments.is_empty()
1434    {
1435        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
1436        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1437            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
1438        }
1439        out
1440    } else {
1441        arm_instrs
1442    };
1443
1444    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
1445    // Per straight-line segment, the frame-slot traffic actually emitted vs the
1446    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
1447    // pool would need — the measured headroom for the full spill-choice rewrite.
1448    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
1449    // reports the greedy baseline and a flag-on run reports what remains.
1450    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
1451        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
1452            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
1453                eprintln!(
1454                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
1455                    seg.start,
1456                    seg.len,
1457                    seg.peak_pressure,
1458                    seg.actual_reloads,
1459                    seg.actual_spill_stores,
1460                    seg.belady_reloads,
1461                    seg.belady_spill_stores
1462                );
1463            }
1464        }
1465    }
1466
1467    // ISA feature gate: validate that all generated instructions are supported
1468    // by the target. This catches FPU instructions on no-FPU targets, double-precision
1469    // instructions on single-precision targets, etc.
1470    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
1471        .map_err(|e| format!("ISA validation failed: {}", e))?;
1472
1473    // VCR-RA-003 (epic #242): UNCONDITIONAL per-compilation register-allocation
1474    // validation. The register allocator is the last major unverified codegen
1475    // component; this whole-function checker proves — by construction, on the
1476    // EXACT emitted stream about to be encoded — that the allocation preserves
1477    // FOUR invariants whose reference lives in the stream (or the ABI): (1)
1478    // callee-saved preservation (#490), (2) spill-slot non-aliasing (#331), and
1479    // — PHASE 2 (#49), extending past straight-line — (3) caller-saved
1480    // preservation across calls (a value in R2/R3/R12 live across a `bl` the
1481    // AAPCS boundary destroys), and (4) value availability across control-flow
1482    // joins (a live-in to a join must be defined on every incoming edge). It runs
1483    // on every ARM compile in the DEFAULT shipping build (NOT behind
1484    // `--features verify`; a verify-gated check would be dormant in exactly the
1485    // build that ships — the #757 / VCR-VER-003 lesson) and hard-errors the
1486    // compile on a VIOLATION. A `NotAttempted` verdict (the join check declines
1487    // on an unmodeled-CF function: numeric branch, `BrTable`, etc.) is NON-FATAL
1488    // — the compile proceeds; the other three invariants were still checked and
1489    // held. This is the decline>guess doctrine applied to the checker itself: it
1490    // never claims join coherence it cannot prove, but it also never blocks a
1491    // correct compile for a construct it simply doesn't model yet. Frozen-safe:
1492    // it emits nothing, so `.text` is byte-identical (proven by the frozen suite).
1493    match synth_synthesis::liveness::validate_final_allocation(&arm_instrs) {
1494        synth_synthesis::liveness::RaFinalVerdict::Violation(v) => {
1495            return Err(format!(
1496                "VCR-RA-003: register-allocation validation FAILED — {v:?}. \
1497                 The emitted stream violates a register-allocation invariant \
1498                 (callee-saved preservation #490 / spill-slot non-aliasing #331 \
1499                 / caller-saved-across-call / join-value-availability / the #881 \
1500                 VFP twins); this is a \
1501                 compiler bug, not a program error. Refusing to emit a \
1502                 miscompiled object."
1503            ));
1504        }
1505        // Loud honest decline (join reasoning skipped for an unmodeled-CF
1506        // function). Non-fatal — the straight-line / callee-saved / across-call
1507        // invariants still ran and held; only the across-JOIN availability
1508        // reasoning is skipped. Since the #819 redo the optimized path's
1509        // pre-resolved NUMERIC branches are modeled too (build_join_cfg_numeric
1510        // + the PRESERVED entry-availability discriminator), so this fires only
1511        // on genuinely unmodeled shapes: BrTable, computed Bx, mixed
1512        // label+numeric streams, off-boundary numeric targets.
1513        // Surfaced only under `SYNTH_RA003_VERBOSE` so a production compile stays
1514        // quiet: emitting it unconditionally would print on every branchy
1515        // optimized-path compile (new stderr noise phase 1 never produced), yet
1516        // it must remain observable on demand for the honest-scope audit.
1517        synth_synthesis::liveness::RaFinalVerdict::NotAttempted { reason } => {
1518            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
1519                eprintln!(
1520                    "VCR-RA-003: across-join validation NOT ATTEMPTED ({reason}) — \
1521                     straight-line / callee-saved / across-call invariants held; \
1522                     join-availability reasoning declined on this control-flow shape."
1523                );
1524            }
1525        }
1526        synth_synthesis::liveness::RaFinalVerdict::Consistent => {
1527            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
1528                eprintln!("VCR-RA-003: Consistent");
1529            }
1530        }
1531    }
1532
1533    // Encode to binary — use Thumb-2 for Cortex-M targets
1534    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
1535
1536    let encoder = if use_thumb2 {
1537        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1538    } else {
1539        ArmEncoder::new_arm32()
1540    };
1541
1542    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
1543    // offsets before encoding. `select_with_stack` emits them as label
1544    // placeholders and never resolves them — without this they encode as
1545    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
1546    // sits between the branch and its target (UsageFault on real hardware).
1547    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
1548    let arm_instrs = if use_thumb2 {
1549        resolve_label_branches(arm_instrs, &encoder)?
1550    } else {
1551        arm_instrs
1552    };
1553
1554    // #778: capture the FINAL Thumb-2 instruction stream (post label-resolution,
1555    // the exact list the encode loop below consumes) so `compile_function` can
1556    // derive the sound WCET bound. Cheap clone; frozen-safe (the WCET walk is a
1557    // pure observation and never touches `code`). Only the Thumb-2 path — the A32
1558    // (Cortex-R5) cycle model is a follow-up.
1559    let final_instrs_for_wcet: Option<Vec<synth_synthesis::ArmInstruction>> = if use_thumb2 {
1560        Some(arm_instrs.clone())
1561    } else {
1562        None
1563    };
1564
1565    let mut code = Vec::new();
1566    let mut relocations = Vec::new();
1567
1568    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
1569    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
1570    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
1571    // and patch the PC-relative offset once the pool position is known.
1572    struct PendingLiteral {
1573        ldr_offset: u32,
1574        symbol: String,
1575        addend: i32,
1576    }
1577    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1578
1579    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1580    // here because `code.len()` immediately before `encode()` is the final
1581    // machine offset of the instruction within this function's `.text` — nothing
1582    // after the loop shifts earlier instructions (the literal pool is appended at
1583    // the end; the LDR patch below is in-place/length-preserving). Purely
1584    // additive: it does not touch `code`, so `.text` is byte-identical.
1585    let mut line_map: LineMap = Vec::new();
1586    // VCR-DEC-003 (#396): object-branch class per emitted instruction, parallel
1587    // to `line_map`. Cheap, additive, does not touch `code`.
1588    let mut branch_map: synth_core::backend::BranchMap = Vec::new();
1589
1590    for instr in &arm_instrs {
1591        // Record a relocation for every BL: the encoder emits `bl #0` and
1592        // relies on a relocation to patch the target. This covers BOTH import
1593        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1594        // (`func_N`, defined in this object). Previously only `__meld_*` was
1595        // recorded, so internal `BL func_N` calls were left as unpatched
1596        // `bl #0` placeholders branching to a garbage address (#167).
1597        if let ArmOp::Bl { label } = &instr.op {
1598            relocations.push(CodeRelocation {
1599                offset: code.len() as u32,
1600                symbol: label.clone(),
1601                kind: synth_core::backend::RelocKind::ThmCall,
1602            });
1603        }
1604        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1605        // addressing). The encoder writes the addend in place; record the matching
1606        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1607        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1608            relocations.push(CodeRelocation {
1609                offset: code.len() as u32,
1610                symbol: symbol.clone(),
1611                kind: synth_core::backend::RelocKind::MovwAbs,
1612            });
1613        }
1614        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1615            relocations.push(CodeRelocation {
1616                offset: code.len() as u32,
1617                symbol: symbol.clone(),
1618                kind: synth_core::backend::RelocKind::MovtAbs,
1619            });
1620        }
1621        // #345: defer the literal-pool word + reloc + offset patch to the
1622        // post-loop pass (the pool address is not yet known).
1623        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1624            pending_literals.push(PendingLiteral {
1625                ldr_offset: code.len() as u32,
1626                symbol: symbol.clone(),
1627                addend: *addend,
1628            });
1629        }
1630
1631        // The machine offset of this instruction is the current code length,
1632        // captured before the bytes are appended.
1633        line_map.push((code.len() as u32, instr.source_line));
1634        branch_map.push((code.len() as u32, classify_arm_branch(&instr.op)));
1635
1636        let encoded = encoder
1637            .encode(&instr.op)
1638            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1639        code.extend_from_slice(&encoded);
1640    }
1641
1642    // #345: place the literal pool at the end of this function's `.text`. Gated on
1643    // there being at least one `LdrSym` — functions without one are byte-identical
1644    // to before (no trailing padding, so downstream `func_offsets` are unchanged
1645    // and the frozen differential fixtures stay bit-for-bit equal).
1646    if !pending_literals.is_empty() {
1647        if !use_thumb2 {
1648            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1649        }
1650        // 4-byte align the pool start (Thumb-2 word loads require it, and
1651        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
1652        while code.len() % 4 != 0 {
1653            code.push(0x00);
1654        }
1655        // One distinct pooled word per LdrSym (no dedup: different sites carry
1656        // different addends, and the REL addend lives in the word).
1657        for lit in &pending_literals {
1658            let word_offset = code.len() as u32;
1659
1660            // REL semantics: the linker computes `S + A`, where A is the in-place
1661            // value of the relocated word. Initialize the word to the addend so
1662            // the final loaded address is `symbol + addend`.
1663            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
1664            relocations.push(CodeRelocation {
1665                offset: word_offset,
1666                symbol: lit.symbol.clone(),
1667                kind: synth_core::backend::RelocKind::Abs32,
1668            });
1669
1670            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
1671            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
1672            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
1673            let pc = lit.ldr_offset + 4;
1674            let aligned_pc = pc & !3u32;
1675            let imm12 = word_offset - aligned_pc;
1676            if imm12 > 0xFFF {
1677                // Wide LDR-literal range is ±4 KB; these function bodies are far
1678                // smaller, but fail cleanly rather than miscompile if exceeded.
1679                return Err(format!(
1680                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
1681                     for symbol {}",
1682                    imm12, lit.symbol
1683                ));
1684            }
1685            let hw2_off = (lit.ldr_offset + 2) as usize;
1686            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
1687            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
1688            let hw2_bytes = hw2.to_le_bytes();
1689            code[hw2_off] = hw2_bytes[0];
1690            code[hw2_off + 1] = hw2_bytes[1];
1691        }
1692    }
1693
1694    Ok((
1695        code,
1696        relocations,
1697        line_map,
1698        branch_map,
1699        final_instrs_for_wcet,
1700    ))
1701}
1702
1703/// VCR-DEC-003 (#396): classify one emitted `ArmOp` into its object-level
1704/// control-flow role for the `synth-provenance-v1` map. Conditional branches are
1705/// the object decision points MC/DC must reconcile; `SelectMove` is the folded
1706/// (IT-block) predicated form the cmp→select fuse produces — a decision with no
1707/// branch.
1708fn classify_arm_branch(op: &ArmOp) -> synth_core::backend::BranchClass {
1709    use synth_core::backend::BranchClass;
1710    match op {
1711        ArmOp::Bcc { .. } | ArmOp::Bhs { .. } | ArmOp::Blo { .. } | ArmOp::BCondOffset { .. } => {
1712            BranchClass::CondBranch
1713        }
1714        ArmOp::B { .. } | ArmOp::BOffset { .. } => BranchClass::UncondBranch,
1715        ArmOp::SelectMove { .. } => BranchClass::Predicated,
1716        _ => BranchClass::Other,
1717    }
1718}
1719
1720/// Resolve local label branches to byte-accurate offsets (#202).
1721///
1722/// `select_with_stack` emits conditional/unconditional branches as label
1723/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
1724/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
1725/// this path only ran for `--no-optimize`/declined functions, so the latent bug
1726/// stayed hidden — routing relocatable code through it surfaced branches that
1727/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
1728/// instruction sits between the branch and its target.
1729///
1730/// This pass encodes each instruction to learn its real byte length (so 16- vs
1731/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
1732/// to its byte position, and rewrites every label branch to the displacement
1733/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
1734/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
1735/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
1736/// the optimized path carry no label and are left untouched.
1737fn resolve_label_branches(
1738    arm_instrs: Vec<ArmInstruction>,
1739    encoder: &ArmEncoder,
1740) -> Result<Vec<ArmInstruction>, String> {
1741    use std::collections::HashMap;
1742    use synth_synthesis::Condition;
1743
1744    enum BKind {
1745        Cond(Condition),
1746        Uncond,
1747    }
1748    // Record each label branch ONCE — indices are stable across iterations.
1749    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
1750    for (i, instr) in arm_instrs.iter().enumerate() {
1751        match &instr.op {
1752            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
1753            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
1754            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
1755            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
1756            _ => {}
1757        }
1758    }
1759    if branches.is_empty() {
1760        return Ok(arm_instrs);
1761    }
1762
1763    let mut resolved = arm_instrs;
1764    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
1765    for _ in 0..16 {
1766        // 1. Byte position of each instruction (Label encodes to 0 bytes).
1767        let mut positions = Vec::with_capacity(resolved.len());
1768        let mut pos: i64 = 0;
1769        for instr in &resolved {
1770            positions.push(pos);
1771            pos += encoder
1772                .encode(&instr.op)
1773                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
1774                .len() as i64;
1775        }
1776        // 2. Label name -> byte position (owned keys so the borrow ends here).
1777        let mut labels: HashMap<String, i64> = HashMap::new();
1778        for (i, instr) in resolved.iter().enumerate() {
1779            if let ArmOp::Label { name } = &instr.op {
1780                labels.insert(name.clone(), positions[i]);
1781            }
1782        }
1783        // 3. Rewrite each branch to its byte-accurate offset.
1784        let mut changed = false;
1785        for (idx, kind, label) in &branches {
1786            // A label not defined locally is an EXTERNAL target (e.g.
1787            // `Trap_Handler` resolved by a relocation / the vector table). Leave
1788            // such branches as their placeholder for the existing relocation
1789            // path — only local control-flow labels are byte-resolved here.
1790            let Some(&target) = labels.get(label) else {
1791                continue;
1792            };
1793            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
1794            // Positions are always even, so this division is exact.
1795            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
1796            let new_op = match kind {
1797                BKind::Cond(c) => ArmOp::BCondOffset {
1798                    cond: *c,
1799                    offset: halfword_offset,
1800                },
1801                BKind::Uncond => ArmOp::BOffset {
1802                    offset: halfword_offset,
1803                },
1804            };
1805            if resolved[*idx].op != new_op {
1806                resolved[*idx].op = new_op;
1807                changed = true;
1808            }
1809        }
1810        if !changed {
1811            break;
1812        }
1813    }
1814    Ok(resolved)
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819    use super::*;
1820
1821    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
1822    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
1823    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
1824    /// byte-identical.
1825    #[test]
1826    fn test_rewrite_memory_grow_zero_539() {
1827        // the idiom -> memory.size
1828        assert_eq!(
1829            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
1830            vec![WasmOp::MemorySize(0)]
1831        );
1832        // const non-zero delta: NOT folded
1833        assert_eq!(
1834            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
1835            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
1836        );
1837        // runtime delta (no preceding const): NOT folded
1838        assert_eq!(
1839            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
1840            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
1841        );
1842        // a bare const-0 not feeding a grow is untouched
1843        assert_eq!(
1844            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
1845            vec![WasmOp::I32Const(0), WasmOp::I32Add]
1846        );
1847        // fold is local: surrounding ops preserved, indices past the fold intact
1848        assert_eq!(
1849            rewrite_memory_grow_zero(&[
1850                WasmOp::LocalGet(0),
1851                WasmOp::I32Const(0),
1852                WasmOp::MemoryGrow(0),
1853                WasmOp::I32Add,
1854            ]),
1855            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
1856        );
1857    }
1858
1859    #[test]
1860    fn test_arm_backend_name() {
1861        let backend = ArmBackend::new();
1862        assert_eq!(backend.name(), "arm");
1863        assert!(backend.is_available());
1864    }
1865
1866    #[test]
1867    fn test_arm_backend_capabilities() {
1868        let backend = ArmBackend::new();
1869        let caps = backend.capabilities();
1870        assert!(!caps.produces_elf);
1871        assert!(caps.supports_rule_verification);
1872        assert!(!caps.is_external);
1873    }
1874
1875    #[test]
1876    fn test_compile_add_function() {
1877        let backend = ArmBackend::new();
1878        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1879        let config = CompileConfig::default();
1880
1881        let result = backend.compile_function("add", &ops, &config);
1882        assert!(result.is_ok());
1883
1884        let func = result.unwrap();
1885        assert_eq!(func.name, "add");
1886        assert!(!func.code.is_empty());
1887        assert_eq!(func.wasm_ops, ops);
1888    }
1889
1890    /// VCR-DBG-001: the per-instruction source map must cover the function with
1891    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
1892    /// code (it is captured at encode time, never serialized here).
1893    #[test]
1894    fn test_line_map_is_wellformed_dbg001() {
1895        let backend = ArmBackend::new();
1896        let ops = vec![
1897            WasmOp::LocalGet(0),
1898            WasmOp::LocalGet(1),
1899            WasmOp::I32Add,
1900            WasmOp::End,
1901        ];
1902        let config = CompileConfig::default();
1903        let func = backend.compile_function("add", &ops, &config).unwrap();
1904
1905        // Non-empty, and the first instruction starts at machine offset 0.
1906        assert!(
1907            !func.line_map.is_empty(),
1908            "a non-trivial function captures a source map"
1909        );
1910        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
1911
1912        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
1913        // bytes) and every mapped offset lies inside the emitted `.text`.
1914        for w in func.line_map.windows(2) {
1915            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
1916            assert!(
1917                w[1].0 - w[0].0 >= 2,
1918                "each ARM/Thumb instruction is >= 2 bytes"
1919            );
1920        }
1921        let last = func.line_map.last().unwrap().0 as usize;
1922        assert!(
1923            last < func.code.len(),
1924            "every mapped offset lies inside .text"
1925        );
1926
1927        // The side-table is additive: recompiling is deterministic and the map is
1928        // consistent with that exact code (capturing it does not alter output).
1929        let again = backend.compile_function("add", &ops, &config).unwrap();
1930        assert_eq!(
1931            again.code, func.code,
1932            "compilation deterministic; map is additive"
1933        );
1934        assert_eq!(again.line_map, func.line_map);
1935    }
1936
1937    #[test]
1938    fn test_count_params() {
1939        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1940        assert_eq!(count_params(&ops), 2);
1941
1942        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
1943        assert_eq!(count_params(&no_params), 0);
1944    }
1945
1946    /// #457: the declared param count caps the access-pattern inference. The
1947    /// repro shape `(param i32)(local i32) → p0 + local1` reads local 1 before
1948    /// any write, so `count_params` infers 2 — with the declared count (1) the
1949    /// local is reclassified onto the zero-inited frame path instead of being
1950    /// read from R1 (caller garbage).
1951    #[test]
1952    fn declared_param_count_caps_inference_457() {
1953        let ops = vec![
1954            WasmOp::LocalGet(0),
1955            WasmOp::LocalGet(1),
1956            WasmOp::I32Add,
1957            WasmOp::End,
1958        ];
1959        // The inference alone still says 2 (the misclassification this caps).
1960        assert_eq!(count_params(&ops), 2);
1961
1962        let backend = ArmBackend::new();
1963        let inferred = backend
1964            .compile_function("rbw", &ops, &CompileConfig::default())
1965            .unwrap();
1966        let declared = backend
1967            .compile_function(
1968                "rbw",
1969                &ops,
1970                &CompileConfig {
1971                    current_func_param_count: Some(1),
1972                    ..CompileConfig::default()
1973                },
1974            )
1975            .unwrap();
1976        // The cap is consumed: the declared-count compile reclassifies local 1
1977        // and must emit different code than the param-misclassified one.
1978        assert_ne!(
1979            inferred.code, declared.code,
1980            "declared param count must reach the selector"
1981        );
1982        // The zero-init is present: a 16-bit Thumb `movs rN, #0`
1983        // (0x2000 | rd<<8 → LE bytes [0x00, 0x20+rd]) somewhere in the body.
1984        let has_movs_zero = declared
1985            .code
1986            .chunks_exact(2)
1987            .any(|h| h[0] == 0x00 && (0x20..=0x27).contains(&h[1]));
1988        assert!(
1989            has_movs_zero,
1990            "declared-count compile must zero-init the read-before-write local; code: {:02x?}",
1991            declared.code
1992        );
1993        // A declared count that matches (or exceeds) the inference changes
1994        // nothing — byte-identity for every function without rbw locals.
1995        let matching = backend
1996            .compile_function(
1997                "rbw",
1998                &ops,
1999                &CompileConfig {
2000                    current_func_param_count: Some(2),
2001                    ..CompileConfig::default()
2002                },
2003            )
2004            .unwrap();
2005        assert_eq!(
2006            matching.code, inferred.code,
2007            "declared >= inferred must stay byte-identical"
2008        );
2009    }
2010
2011    #[test]
2012    fn test_arm_backend_register() {
2013        let mut registry = synth_core::BackendRegistry::new();
2014        registry.register(Box::new(ArmBackend::new()));
2015        assert!(registry.get("arm").is_some());
2016        assert_eq!(registry.available().len(), 1);
2017    }
2018
2019    #[test]
2020    fn test_compile_import_call_produces_relocations() {
2021        let backend = ArmBackend::new();
2022        // Simulate a WASM module where func index 0 is an import.
2023        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
2024        let ops = vec![WasmOp::Call(0)];
2025        let config = CompileConfig {
2026            num_imports: 1,
2027            no_optimize: true, // Direct instruction selection to preserve Call semantics
2028            ..CompileConfig::default()
2029        };
2030
2031        let result = backend.compile_function("caller", &ops, &config);
2032        assert!(result.is_ok());
2033
2034        let func = result.unwrap();
2035        assert!(!func.code.is_empty());
2036        assert_eq!(func.relocations.len(), 1);
2037        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
2038        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
2039        assert!(func.relocations[0].offset > 0);
2040    }
2041
2042    /// Regression test for #197: in `relocatable` mode, an import call must
2043    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
2044    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
2045    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
2046    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
2047    #[test]
2048    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
2049        let backend = ArmBackend::new();
2050        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
2051        let config = CompileConfig {
2052            num_imports: 1,
2053            relocatable: true,
2054            ..CompileConfig::default()
2055        };
2056
2057        let func = backend
2058            .compile_function("caller", &ops, &config)
2059            .expect("relocatable import call compiles");
2060
2061        assert_eq!(func.relocations.len(), 1);
2062        assert_eq!(
2063            func.relocations[0].symbol, "func_0",
2064            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
2065        );
2066    }
2067
2068    #[test]
2069    fn test_compile_no_imports_no_relocations() {
2070        let backend = ArmBackend::new();
2071        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
2072        let config = CompileConfig::default();
2073
2074        let func = backend.compile_function("add", &ops, &config).unwrap();
2075        assert!(func.relocations.is_empty());
2076    }
2077
2078    /// Regression test for #167: a call to an INTERNAL function
2079    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
2080    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
2081    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
2082    /// to a garbage address — making the object non-linkable. This test
2083    /// would have caught that regression.
2084    #[test]
2085    fn test_compile_internal_call_produces_relocation_167() {
2086        let backend = ArmBackend::new();
2087        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
2088        let ops = vec![WasmOp::Call(2)];
2089        let config = CompileConfig {
2090            num_imports: 1,
2091            no_optimize: true,
2092            ..CompileConfig::default()
2093        };
2094
2095        let func = backend
2096            .compile_function("caller", &ops, &config)
2097            .expect("internal call compiles");
2098
2099        assert_eq!(
2100            func.relocations.len(),
2101            1,
2102            "an internal call must emit exactly one relocation (#167)"
2103        );
2104        assert_eq!(
2105            func.relocations[0].symbol, "func_2",
2106            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
2107        );
2108    }
2109
2110    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
2111
2112    #[test]
2113    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
2114        // Mpu mode must not introduce any inline check on ARM — the MPU
2115        // handles faults via hardware. The encoded bytes for an i32.load
2116        // should be identical between None and Mpu.
2117        let backend = ArmBackend::new();
2118        let ops = vec![
2119            WasmOp::LocalGet(0),
2120            WasmOp::I32Load {
2121                offset: 0,
2122                align: 2,
2123            },
2124        ];
2125        let cfg_none = CompileConfig {
2126            no_optimize: true,
2127            ..Default::default()
2128        };
2129        let cfg_mpu = CompileConfig {
2130            no_optimize: true,
2131            safety_bounds: SafetyBounds::Mpu,
2132            ..Default::default()
2133        };
2134        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
2135        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
2136        assert_eq!(
2137            n.code, m.code,
2138            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
2139        );
2140    }
2141
2142    #[test]
2143    fn arm_legacy_bounds_check_still_emits_software_check() {
2144        // Legacy CLI users with `--bounds-check` should keep getting the
2145        // software path even though the new SafetyBounds field defaults to None.
2146        let backend = ArmBackend::new();
2147        let ops = vec![
2148            WasmOp::LocalGet(0),
2149            WasmOp::I32Load {
2150                offset: 0,
2151                align: 2,
2152            },
2153        ];
2154        let cfg_legacy = CompileConfig {
2155            no_optimize: true,
2156            bounds_check: true,
2157            ..Default::default()
2158        };
2159        let cfg_software = CompileConfig {
2160            no_optimize: true,
2161            safety_bounds: SafetyBounds::Software,
2162            ..Default::default()
2163        };
2164        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
2165        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
2166        assert_eq!(
2167            l.code, s.code,
2168            "--bounds-check should produce the same bytes as --safety-bounds=software"
2169        );
2170    }
2171
2172    /// #377: `--safety-bounds software` must be enforced on the OPTIMIZED path
2173    /// too. Pre-fix, `software` was byte-identical to `none` there (a silent
2174    /// no-op while the safety manifest claimed enforcement). The compiled
2175    /// bytes must now (a) differ from `none` and (b) contain the inline
2176    /// `CMP ip, sl` + `UDF` guard.
2177    #[test]
2178    fn arm_safety_bounds_software_enforced_on_optimized_path_377() {
2179        let backend = ArmBackend::new();
2180        // Dynamic-address store+load: the optimized path accepts this shape
2181        // (no calls, no i64 params, ≤4 params).
2182        let ops = vec![
2183            WasmOp::LocalGet(0),
2184            WasmOp::LocalGet(1),
2185            WasmOp::I32Store {
2186                offset: 4,
2187                align: 2,
2188            },
2189            WasmOp::LocalGet(0),
2190            WasmOp::I32Load {
2191                offset: 0,
2192                align: 2,
2193            },
2194        ];
2195        // no_optimize NOT set — this exercises the optimized path.
2196        let cfg_none = CompileConfig::default();
2197        let cfg_sw = CompileConfig {
2198            safety_bounds: SafetyBounds::Software,
2199            ..Default::default()
2200        };
2201        let n = backend.compile_function("st", &ops, &cfg_none).unwrap();
2202        let s = backend.compile_function("st", &ops, &cfg_sw).unwrap();
2203        assert_ne!(
2204            n.code, s.code,
2205            "#377: software bounds must CHANGE optimized-path codegen (was a silent no-op)"
2206        );
2207        // Thumb-2 `UDF #0` is 0xDE00 (LE bytes: 00 DE); the #752
2208        // wraparound-safe guard's borrow check `CMP sl, ip` (16-bit
2209        // high-reg form) is 0x45E2 (LE: E2 45). Both must appear — one
2210        // guard per access, traps inline.
2211        let has_udf = s.code.windows(2).any(|w| w == [0x00, 0xDE]);
2212        let has_cmp_sl_ip = s.code.windows(2).any(|w| w == [0xE2, 0x45]);
2213        assert!(has_udf, "#377: inline UDF trap missing from optimized path");
2214        assert!(
2215            has_cmp_sl_ip,
2216            "#377/#752: CMP sl, ip bounds borrow-check missing from optimized path"
2217        );
2218        // And `none` must contain NO UDF (the function has no other trap).
2219        assert!(
2220            !n.code.windows(2).any(|w| w == [0x00, 0xDE]),
2221            "none must not contain a UDF for this function"
2222        );
2223    }
2224
2225    /// #377: `mpu` on the optimized path is codegen-passthrough — identical
2226    /// bytes to `none` on BOTH paths (hardware enforcement is target-level;
2227    /// synth does not emit MPU region programming — tracked separately in
2228    /// #377's fix-direction discussion). This pins path-parity for `mpu`.
2229    #[test]
2230    fn arm_safety_bounds_mpu_optimized_path_parity_377() {
2231        let backend = ArmBackend::new();
2232        let ops = vec![
2233            WasmOp::LocalGet(0),
2234            WasmOp::I32Load {
2235                offset: 0,
2236                align: 2,
2237            },
2238        ];
2239        let cfg_none = CompileConfig::default();
2240        let cfg_mpu = CompileConfig {
2241            safety_bounds: SafetyBounds::Mpu,
2242            ..Default::default()
2243        };
2244        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
2245        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
2246        assert_eq!(
2247            n.code, m.code,
2248            "Mpu and None must produce identical bytes on the optimized path too"
2249        );
2250    }
2251
2252    /// #377: `mask` on the optimized path declines to the direct selector
2253    /// (honest degradation) — the compiled function must equal the
2254    /// `--no-optimize` masking bytes, i.e. the flag is honored, never dropped.
2255    #[test]
2256    fn arm_safety_bounds_mask_optimized_path_declines_to_direct_377() {
2257        let backend = ArmBackend::new();
2258        let ops = vec![
2259            WasmOp::LocalGet(0),
2260            WasmOp::LocalGet(1),
2261            WasmOp::I32Store {
2262                offset: 0,
2263                align: 2,
2264            },
2265        ];
2266        let cfg_mask_opt = CompileConfig {
2267            safety_bounds: SafetyBounds::Mask,
2268            ..Default::default()
2269        };
2270        let cfg_mask_direct = CompileConfig {
2271            no_optimize: true,
2272            safety_bounds: SafetyBounds::Mask,
2273            ..Default::default()
2274        };
2275        let o = backend.compile_function("st", &ops, &cfg_mask_opt).unwrap();
2276        let d = backend
2277            .compile_function("st", &ops, &cfg_mask_direct)
2278            .unwrap();
2279        assert_eq!(
2280            o.code, d.code,
2281            "#377: mask on the optimized path must fall back to the direct selector's masking"
2282        );
2283    }
2284
2285    // ========================================================================
2286    // ISA feature gate tests — ensure the compiler never emits unsupported
2287    // instructions for a given target
2288    // ========================================================================
2289
2290    #[test]
2291    fn test_f32_rejected_on_cortex_m3_no_fpu() {
2292        let backend = ArmBackend::new();
2293        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
2294        let config = CompileConfig {
2295            target: TargetSpec::cortex_m3(),
2296            no_optimize: true,
2297            ..CompileConfig::default()
2298        };
2299
2300        let result = backend.compile_function("fadd", &ops, &config);
2301        assert!(
2302            result.is_err(),
2303            "f32 operations should fail on Cortex-M3 (no FPU)"
2304        );
2305    }
2306
2307    #[test]
2308    fn test_f32_accepted_on_cortex_m4f() {
2309        let backend = ArmBackend::new();
2310        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
2311        let config = CompileConfig {
2312            target: TargetSpec::cortex_m4f(),
2313            no_optimize: true,
2314            ..CompileConfig::default()
2315        };
2316
2317        let result = backend.compile_function("fadd", &ops, &config);
2318        assert!(
2319            result.is_ok(),
2320            "f32 operations should succeed on Cortex-M4F, got: {:?}",
2321            result.unwrap_err()
2322        );
2323    }
2324
2325    #[test]
2326    fn test_i32_works_on_all_targets() {
2327        let backend = ArmBackend::new();
2328        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
2329
2330        // Cortex-M3 (no FPU)
2331        let config_m3 = CompileConfig {
2332            target: TargetSpec::cortex_m3(),
2333            no_optimize: true,
2334            ..CompileConfig::default()
2335        };
2336        assert!(
2337            backend.compile_function("add", &ops, &config_m3).is_ok(),
2338            "i32 ops should work on Cortex-M3"
2339        );
2340
2341        // Cortex-M4F (single FPU)
2342        let config_m4f = CompileConfig {
2343            target: TargetSpec::cortex_m4f(),
2344            no_optimize: true,
2345            ..CompileConfig::default()
2346        };
2347        assert!(
2348            backend.compile_function("add", &ops, &config_m4f).is_ok(),
2349            "i32 ops should work on Cortex-M4F"
2350        );
2351
2352        // Cortex-M7DP (double FPU)
2353        let config_m7dp = CompileConfig {
2354            target: TargetSpec::cortex_m7dp(),
2355            no_optimize: true,
2356            ..CompileConfig::default()
2357        };
2358        assert!(
2359            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
2360            "i32 ops should work on Cortex-M7DP"
2361        );
2362    }
2363
2364    #[test]
2365    fn test_f32_rejected_on_cortex_m4_no_fpu() {
2366        // Cortex-M4 (without F suffix) has no FPU
2367        let backend = ArmBackend::new();
2368        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
2369        let config = CompileConfig {
2370            target: TargetSpec::cortex_m4(),
2371            no_optimize: true,
2372            ..CompileConfig::default()
2373        };
2374
2375        let result = backend.compile_function("fmul", &ops, &config);
2376        assert!(
2377            result.is_err(),
2378            "f32 operations should fail on Cortex-M4 (no FPU)"
2379        );
2380    }
2381
2382    // ========================================================================
2383    // Issue #120 — f32 ops in the optimized lowering path
2384    //
2385    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
2386    // value-producing float op fell through to `Opcode::Nop`, leaving a
2387    // downstream consumer with an unmapped vreg and tripping the PR #101
2388    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
2389    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
2390    // module.
2391    //
2392    // Fix: `optimize_full` declines float modules with a typed `Err`;
2393    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
2394    // path, which handles f32 via VFP/FPU. These tests use the *default*
2395    // (optimized) config — `no_optimize` is NOT set — which is the exact
2396    // configuration that panicked pre-fix.
2397    // ========================================================================
2398
2399    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
2400    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
2401    /// the module and the backend falls back to direct selection, producing a
2402    /// non-empty f32.div lowering on a Cortex-M4F.
2403    #[test]
2404    fn test_issue120_f32_div_compiles_via_optimized_default() {
2405        let backend = ArmBackend::new();
2406        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
2407        let config = CompileConfig {
2408            target: TargetSpec::cortex_m4f(),
2409            // no_optimize NOT set — this exercises the optimized path that
2410            // panicked in issue #120, then the fallback to direct selection.
2411            // GI-FPU-002: the f32 params must be declared so the direct
2412            // selector homes them in S0/S1 (AAPCS-VFP) rather than declining.
2413            current_func_params_f32: vec![true, true],
2414            ..CompileConfig::default()
2415        };
2416
2417        let result = backend.compile_function("fdiv", &ops, &config);
2418        assert!(
2419            result.is_ok(),
2420            "f32.div must compile on Cortex-M4F via the optimized->direct \
2421             fallback (issue #120), got: {:?}",
2422            result.as_ref().err()
2423        );
2424        assert!(
2425            !result.unwrap().code.is_empty(),
2426            "f32.div must produce non-empty machine code"
2427        );
2428    }
2429
2430    /// A spread of f32 ops, all through the optimized (default) config, must
2431    /// compile via the fallback on an FPU target without panicking.
2432    #[test]
2433    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
2434        let backend = ArmBackend::new();
2435        let config = CompileConfig {
2436            target: TargetSpec::cortex_m4f(),
2437            // GI-FPU-002: declare the two f32 params for AAPCS-VFP homing.
2438            current_func_params_f32: vec![true, true],
2439            ..CompileConfig::default()
2440        };
2441
2442        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
2443            (
2444                "fadd",
2445                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
2446            ),
2447            (
2448                "fmul",
2449                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
2450            ),
2451            (
2452                "fsub",
2453                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
2454            ),
2455        ];
2456
2457        for (name, ops) in cases {
2458            let result = backend.compile_function(name, &ops, &config);
2459            assert!(
2460                result.is_ok(),
2461                "{name} must compile via the optimized->direct fallback \
2462                 (issue #120), got: {:?}",
2463                result.as_ref().err()
2464            );
2465            assert!(
2466                !result.unwrap().code.is_empty(),
2467                "{name} must produce non-empty machine code"
2468            );
2469        }
2470    }
2471
2472    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
2473    /// target must fail cleanly (not panic) even on the optimized path.
2474    #[test]
2475    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
2476        let backend = ArmBackend::new();
2477        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
2478        let config = CompileConfig {
2479            target: TargetSpec::cortex_m3(),
2480            ..CompileConfig::default()
2481        };
2482
2483        let result = backend.compile_function("fdiv", &ops, &config);
2484        assert!(
2485            result.is_err(),
2486            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
2487        );
2488    }
2489
2490    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
2491    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
2492    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
2493    /// real cmp-chain instead of silently dropping it (which left all arms in
2494    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
2495    /// selector compare). Execution correctness is gated by
2496    /// `scripts/repro/br_table_507_differential.py`.
2497    #[test]
2498    fn test_507_br_table_declines_to_direct() {
2499        let backend = ArmBackend::new();
2500        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
2501        let ops = vec![
2502            WasmOp::Block,
2503            WasmOp::Block,
2504            WasmOp::Block,
2505            WasmOp::LocalGet(0),
2506            WasmOp::BrTable {
2507                targets: vec![0, 1, 2],
2508                default: 2,
2509            },
2510            WasmOp::End,
2511            WasmOp::I32Const(0),
2512            WasmOp::I32Const(10),
2513            WasmOp::I32Store {
2514                offset: 0,
2515                align: 2,
2516            },
2517            WasmOp::Return,
2518            WasmOp::End,
2519            WasmOp::I32Const(0),
2520            WasmOp::I32Const(20),
2521            WasmOp::I32Store {
2522                offset: 0,
2523                align: 2,
2524            },
2525            WasmOp::Return,
2526            WasmOp::End,
2527            WasmOp::I32Const(0),
2528            WasmOp::I32Const(30),
2529            WasmOp::I32Store {
2530                offset: 0,
2531                align: 2,
2532            },
2533        ];
2534        let opt = CompileConfig {
2535            target: TargetSpec::cortex_m4(),
2536            ..CompileConfig::default()
2537        };
2538        let direct = CompileConfig {
2539            target: TargetSpec::cortex_m4(),
2540            no_optimize: true,
2541            ..CompileConfig::default()
2542        };
2543        let a = backend
2544            .compile_function("dispatch", &ops, &opt)
2545            .expect("optimized-default must compile br_table (via decline)");
2546        let b = backend
2547            .compile_function("dispatch", &ops, &direct)
2548            .expect("direct must compile br_table");
2549        assert_eq!(
2550            a.code, b.code,
2551            "#507: optimized-default br_table output must be byte-identical to the \
2552             direct selector (i.e. declined to direct), not a dropped dispatch"
2553        );
2554    }
2555
2556    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
2557    /// FFI-return hi32 extract pattern. Compiles two near-identical
2558    /// functions — one with the optimized shift-by-32, one with a generic
2559    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
2560    #[test]
2561    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
2562        let backend = ArmBackend::new();
2563        let config = CompileConfig {
2564            target: TargetSpec::cortex_m4f(),
2565            ..CompileConfig::default()
2566        };
2567
2568        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
2569        // path now declines i64-param functions to the direct selector (it homed
2570        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
2571        // byte-size-only assertion masked). The canonical #94 case is a u64 from
2572        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
2573        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
2574        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
2575        // still exercised on CORRECT code.
2576        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
2577        let ops_hi32 = vec![
2578            WasmOp::LocalGet(0), // i32 param in R0
2579            WasmOp::I64ExtendI32S,
2580            WasmOp::I64Const(32),
2581            WasmOp::I64ShrU,
2582            WasmOp::I32WrapI64,
2583        ];
2584        let func_hi32 = backend
2585            .compile_function("hi32_extract", &ops_hi32, &config)
2586            .unwrap();
2587
2588        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
2589        // is not a multiple of 32, so it falls through to the runtime shift.
2590        let ops_generic = vec![
2591            WasmOp::LocalGet(0),
2592            WasmOp::I64ExtendI32S,
2593            WasmOp::I64Const(7),
2594            WasmOp::I64ShrU,
2595            WasmOp::I32WrapI64,
2596        ];
2597        let func_generic = backend
2598            .compile_function("generic_shr", &ops_generic, &config)
2599            .unwrap();
2600
2601        let bytes_hi32 = func_hi32.code.len();
2602        let bytes_generic = func_generic.code.len();
2603        println!(
2604            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
2605            bytes_hi32,
2606            bytes_generic,
2607            bytes_generic.saturating_sub(bytes_hi32)
2608        );
2609        let hex: String = func_hi32
2610            .code
2611            .iter()
2612            .map(|b| format!("{:02x}", b))
2613            .collect::<Vec<_>>()
2614            .join(" ");
2615        println!("[issue #94] hi32 bytes: {}", hex);
2616        // We expect the optimized form to be at least 30 bytes smaller than
2617        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
2618        assert!(
2619            bytes_hi32 + 30 <= bytes_generic,
2620            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
2621             expected optimized form to be at least 30 bytes smaller",
2622            bytes_hi32,
2623            bytes_generic,
2624        );
2625    }
2626}