Skip to main content

synth_backend/
arm_backend.rs

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