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