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