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