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            let func_config = match config.func_params_i64.get(func.index as usize) {
84                Some(p) if !p.is_empty() => Some(CompileConfig {
85                    current_func_params_i64: p.clone(),
86                    ..config.clone()
87                }),
88                _ => None,
89            };
90            let cfg = func_config.as_ref().unwrap_or(config);
91            let compiled = self.compile_function(&name, &func.ops, cfg)?;
92            functions.push(compiled);
93        }
94
95        Ok(CompilationResult {
96            functions,
97            elf: None,
98            backend_name: self.name().to_string(),
99        })
100    }
101
102    fn compile_function(
103        &self,
104        name: &str,
105        ops: &[WasmOp],
106        config: &CompileConfig,
107    ) -> Result<CompiledFunction, BackendError> {
108        let (code, relocations, line_map) =
109            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
110
111        Ok(CompiledFunction {
112            name: name.to_string(),
113            code,
114            wasm_ops: ops.to_vec(),
115            relocations,
116            line_map,
117        })
118    }
119
120    fn is_available(&self) -> bool {
121        true // Always available — it's a library backend
122    }
123}
124
125/// Count the number of function parameters by analyzing LocalGet patterns
126fn count_params(wasm_ops: &[WasmOp]) -> u32 {
127    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
128    for op in wasm_ops {
129        match op {
130            WasmOp::LocalGet(idx) => {
131                first_access.entry(*idx).or_insert(true);
132            }
133            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
134                first_access.entry(*idx).or_insert(false);
135            }
136            _ => {}
137        }
138    }
139
140    first_access
141        .iter()
142        .filter_map(
143            |(&idx, &is_read_first)| {
144                if is_read_first { Some(idx + 1) } else { None }
145            },
146        )
147        .max()
148        .unwrap_or(0)
149}
150
151/// Core compilation: WASM ops → ARM machine code bytes + relocations
152///
153/// Returns (code_bytes, relocations) where relocations record BL instructions
154/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
155fn compile_wasm_to_arm(
156    wasm_ops: &[WasmOp],
157    config: &CompileConfig,
158) -> Result<(Vec<u8>, Vec<CodeRelocation>, LineMap), String> {
159    let num_params = count_params(wasm_ops);
160
161    let bounds_config = match config.effective_safety_bounds() {
162        SafetyBounds::None => BoundsCheckConfig::None,
163        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
164        SafetyBounds::Software => BoundsCheckConfig::Software,
165        SafetyBounds::Mask => BoundsCheckConfig::Masking,
166    };
167
168    // The non-optimized (direct) instruction-selection path. Handles f32 via
169    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
170    // when the optimized path declines a module (see issue #120 below).
171    //
172    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
173    // `spill_on_exhaustion` set only on the retry — the first pass is the
174    // unmodified default, so every function that compiles today is selected by
175    // exactly the code that compiled it yesterday (bit-identity is structural,
176    // not behavioural).
177    let select_direct_attempt = |spill_on_exhaustion: bool,
178                                 param_backing_on_exhaustion: bool|
179     -> Result<Vec<ArmInstruction>, synth_core::Error> {
180        let db = RuleDatabase::with_standard_rules();
181        let mut selector =
182            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
183        selector.set_target(config.target.fpu, &config.target.triple);
184        if config.num_imports > 0 {
185            selector.set_num_imports(config.num_imports);
186        }
187        // #195: plumb the callee argument-count tables so the direct selector can
188        // marshal call arguments into R0–R3 per AAPCS.
189        selector.set_func_arg_counts(
190            config.func_arg_counts.clone(),
191            config.type_arg_counts.clone(),
192        );
193        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
194        // imports (rewritten to the wasm field name by build_relocatable_elf)
195        // instead of `__meld_dispatch_import`.
196        selector.set_relocatable(config.relocatable);
197        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
198        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
199        // #311: i64 call results are register PAIRS — tag them.
200        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
201        // #359: declared param widths of THIS function, so the AAPCS stack-arg
202        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
203        selector.set_params_i64(config.current_func_params_i64.clone());
204        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
205        // gating here keeps every non-native compile (all frozen fixtures) on the
206        // legacy R9 globals-table path, bit-identical.
207        if config.native_pointer_abi
208            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
209        {
210            selector.set_native_pointer_stack(sp_idx, sp_init);
211        }
212        selector.set_spill_on_exhaustion(spill_on_exhaustion);
213        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
214        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
215        // in callee-saved registers instead of frame slots — the structural lever
216        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
217        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
218        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
219        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
220        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
221        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
222        selector.set_local_promote(std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err());
223        selector.select_with_stack(wasm_ops, num_params)
224    };
225    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
226        // The two recoverable exhaustion classes. NOT retried: the i64
227        // spill-slot-pool Err ("spill-slot pool exhausted") — the honest
228        // remaining bound of the 3b-lite allocator.
229        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
230        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
231        let mut attempt = select_direct_attempt(false, false);
232        // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
233        // hard-fail is recoverable — retry with spill-on-exhaustion, which
234        // reserves the spill area and spills the deepest stack value when the
235        // pool is full. Only functions that FAILED the first pass ever reach
236        // this, so existing output is untouched by construction.
237        if let Err(e) = &attempt
238            && e.to_string().contains(SINGLE_EXHAUSTION)
239        {
240            attempt = select_direct_attempt(true, false);
241        }
242        // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
243        // exhaustion is recoverable too — but not by stack spilling (the pair
244        // allocator already spills stack values, #171): the blockers are the
245        // pinned param home registers. The final retry frame-backs the params
246        // (#204 machinery) so they stop pinning R0-R3, with spill-on-exhaustion
247        // kept on for the single-register pressure the reloads add. Reached
248        // only by functions that failed every earlier pass.
249        if let Err(e) = &attempt
250            && e.to_string().contains(PAIR_EXHAUSTION)
251        {
252            attempt = select_direct_attempt(true, true);
253        }
254        attempt.map_err(|e| format!("instruction selection failed: {}", e))
255    };
256
257    // Instruction selection: optimized or direct.
258    //
259    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
260    // optimized path materializes an absolute linmem base (0x20000100) and does
261    // not preserve caller-saved registers across calls — both wrong for a
262    // host-linked object, where the linmem base arrives via `fp` at runtime and
263    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
264    // #171) handles fp-relative memory + caller-saved preservation correctly.
265    let arm_instrs = if config.no_optimize || config.relocatable {
266        select_direct()?
267    } else {
268        let opt_config = if config.loom_compat {
269            OptimizationConfig::loom_compat()
270        } else {
271            OptimizationConfig::all()
272        };
273
274        let mut bridge = OptimizerBridge::with_config(opt_config);
275        // #188: tell the bridge how many imports there are so it declines only
276        // LOCAL calls (and leaves import calls on the optimized path, keeping
277        // the #173 field-name relocation rewrite intact).
278        bridge.set_num_imports(config.num_imports);
279        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
280        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
281        // `optimize_full` failure: fall back to the direct selector rather
282        // than propagating, so the function still compiles correctly.
283        match bridge
284            .optimize_full(wasm_ops)
285            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
286        {
287            Ok(arm_ops) => arm_ops
288                .into_iter()
289                .map(|op| ArmInstruction {
290                    op,
291                    source_line: None,
292                })
293                .collect(),
294            // Issue #120: the optimized path declines modules it cannot lower
295            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
296            // back to the direct instruction selector, which handles f32 via
297            // VFP/FPU. This is honest degradation: the function still compiles
298            // correctly, just without IR-level optimization.
299            Err(_) => select_direct()?,
300        }
301    };
302
303    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
304    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
305    // fully tested), but it is **register-allocation-coupled**: over the current
306    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
307    // extends the live ranges of the mul inputs to the mla point, and the added
308    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
309    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
310    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
311    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
312    // registers, at which point it becomes net-positive (per #272's plan and the
313    // wiring design note). Lesson (#277): a register-pressure-affecting transform
314    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
315    // can default on.
316
317    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209), the first
318    // allocator-analysis-driven CODEGEN change. Drops `movw` re-materializations
319    // of a constant already resident in another register and retargets the reads
320    // — every rewrite proven by the liveness analysis, and it ONLY removes
321    // materializations (pressure never rises), so unlike the mla fusion (#277) it
322    // cannot regress on-target. Runs on the selected stream before branch
323    // resolution (it removes instructions, shifting byte offsets). Behind
324    // `SYNTH_CONST_CSE=1` while it is validated against the differential oracle +
325    // gale's five on-target baselines; off by default keeps every fixture
326    // bit-identical.
327    let arm_instrs = if std::env::var("SYNTH_CONST_CSE").is_ok() {
328        synth_synthesis::liveness::apply_const_cse(&arm_instrs).0
329    } else {
330        arm_instrs
331    };
332
333    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
334    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
335    // segment over the R0-R8 pool with value ranges as the allocation unit
336    // (segment inputs + per-register live-outs pinned to their original
337    // registers, reserved R9-R12/SP identity-assigned — each segment is
338    // independently sound, no cross-segment liveness assumed). Renames
339    // registers only: never adds, removes, or reorders instructions, so
340    // labels/branch offsets are unaffected.
341    //
342    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
343    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
344    // flat_flight/controller/control_step, fires on the filter family with
345    // zero cycle delta and a small size win, all selfchecks green on silicon.
346    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
347    // `SYNTH_REALLOC_STATS=1`.
348    //
349    // The companion dead callee-saved-save elimination (gale's "next
350    // consequential lever", same issue comment) then shrinks the prologue
351    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
352    // registers the re-allocated body still touches (leaf-only,
353    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
354    // ~12 cycles of pure save/restore overhead removed on small leaves.
355    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
356    let arm_instrs = if realloc_on {
357        use synth_synthesis::rules::Reg;
358        const POOL: [Reg; 9] = [
359            Reg::R0,
360            Reg::R1,
361            Reg::R2,
362            Reg::R3,
363            Reg::R4,
364            Reg::R5,
365            Reg::R6,
366            Reg::R7,
367            Reg::R8,
368        ];
369        let (out, stats) = synth_synthesis::liveness::reallocate_function(&arm_instrs, &POOL);
370        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
371            eprintln!(
372                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
373                stats.segments,
374                stats.reallocated,
375                stats.declined,
376                stats.validator_rejects,
377                stats.needs_spill
378            );
379        }
380        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
381    } else {
382        arm_instrs
383    };
384
385    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
386    // the selected stream and LOG what it finds — without changing a single
387    // emitted byte. This is the measure-only bridge between the built analysis
388    // layer and the eventual virtual-register wiring: it shows, per real
389    // function, whether the allocator can colour it within the R0–R8 pool and
390    // how much const-CSE / rematerialization headroom exists (#209). Enable with
391    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
392    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
393        use synth_synthesis::liveness::{
394            AllocationOutcome, allocate_function, function_peak_pressure,
395        };
396        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
397        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
398        let precolored = std::collections::BTreeMap::from([
399            (synth_synthesis::rules::Reg::R9, 9usize),
400            (synth_synthesis::rules::Reg::R10, 10),
401            (synth_synthesis::rules::Reg::R11, 11),
402            (synth_synthesis::rules::Reg::R12, 12),
403        ]);
404        // True VALUE pressure (one node per value, not per reused physical reg):
405        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
406        // function fits once virtually allocated.
407        let peak = function_peak_pressure(&arm_instrs);
408        match allocate_function(&arm_instrs, 9, &precolored) {
409            AllocationOutcome::Allocated {
410                remat_opportunities,
411                coloring,
412            } => eprintln!(
413                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
414                coloring.len(),
415                peak,
416                remat_opportunities
417            ),
418            AllocationOutcome::NeedsSpill(s) => eprintln!(
419                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
420                s, peak
421            ),
422            AllocationOutcome::Declined => {
423                eprintln!(
424                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
425                )
426            }
427        }
428    }
429
430    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
431    // lowers a `select` whose condition is a comparison to a *materialize then
432    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
433    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
434    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
435    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
436    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
437    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
438    //
439    // Run LATE: after range re-allocation (so the dead-D proof sees final register
440    // identities) and before encode. Removal-only + rename-only ⇒ no spill
441    // regression and labels/branch offsets are unaffected. Each fusion is proven
442    // sound (flags reused only when nothing clobbers them in the window; the
443    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
444    //
445    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
446    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
447    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
448    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
449    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
450    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
451    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
452    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
453    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
454    // check is a tracked post-ship follow-up (gale owns it).
455    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
456        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
457        // the extra `two_move` count is diagnostic only (the fusion census /
458        // blast-radius datum — #7 made that arm reachable).
459        let (out, fused, two_move) =
460            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
461        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
462            let in_place = fused - two_move;
463            eprintln!(
464                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
465                 ({two_move} two-move, {in_place} in-place)"
466            );
467        }
468        out
469    } else {
470        arm_instrs
471    };
472
473    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
474    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
475    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
476    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
477    // new instruction form and no label/offset change. BEHIND `SYNTH_STACK_FWD=1`
478    // (opt-in, off by default ⇒ bit-identical) while it is validated against the
479    // execution differential + gale's G474RE bench — the same gated path the
480    // cmp→select flip took before shipping default-on in v0.13.0.
481    let arm_instrs = if std::env::var("SYNTH_STACK_FWD").is_ok() {
482        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
483        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
484            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
485        }
486        out
487    } else {
488        arm_instrs
489    };
490
491    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
492    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
493    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
494    // instruction, −1 live register. Removal-only (offset-neutral before branch
495    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
496    // bit-identical results + a net cycle win on the dissolved hot path (−2
497    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
498    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
499        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
500        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
501            eprintln!(
502                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
503            );
504        }
505        out
506    } else {
507        arm_instrs
508    };
509
510    // ISA feature gate: validate that all generated instructions are supported
511    // by the target. This catches FPU instructions on no-FPU targets, double-precision
512    // instructions on single-precision targets, etc.
513    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
514        .map_err(|e| format!("ISA validation failed: {}", e))?;
515
516    // Encode to binary — use Thumb-2 for Cortex-M targets
517    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
518
519    let encoder = if use_thumb2 {
520        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
521    } else {
522        ArmEncoder::new_arm32()
523    };
524
525    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
526    // offsets before encoding. `select_with_stack` emits them as label
527    // placeholders and never resolves them — without this they encode as
528    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
529    // sits between the branch and its target (UsageFault on real hardware).
530    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
531    let arm_instrs = if use_thumb2 {
532        resolve_label_branches(arm_instrs, &encoder)?
533    } else {
534        arm_instrs
535    };
536
537    let mut code = Vec::new();
538    let mut relocations = Vec::new();
539
540    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
541    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
542    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
543    // and patch the PC-relative offset once the pool position is known.
544    struct PendingLiteral {
545        ldr_offset: u32,
546        symbol: String,
547        addend: i32,
548    }
549    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
550
551    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
552    // here because `code.len()` immediately before `encode()` is the final
553    // machine offset of the instruction within this function's `.text` — nothing
554    // after the loop shifts earlier instructions (the literal pool is appended at
555    // the end; the LDR patch below is in-place/length-preserving). Purely
556    // additive: it does not touch `code`, so `.text` is byte-identical.
557    let mut line_map: LineMap = Vec::new();
558
559    for instr in &arm_instrs {
560        // Record a relocation for every BL: the encoder emits `bl #0` and
561        // relies on a relocation to patch the target. This covers BOTH import
562        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
563        // (`func_N`, defined in this object). Previously only `__meld_*` was
564        // recorded, so internal `BL func_N` calls were left as unpatched
565        // `bl #0` placeholders branching to a garbage address (#167).
566        if let ArmOp::Bl { label } = &instr.op {
567            relocations.push(CodeRelocation {
568                offset: code.len() as u32,
569                symbol: label.clone(),
570                kind: synth_core::backend::RelocKind::ThmCall,
571            });
572        }
573        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
574        // addressing). The encoder writes the addend in place; record the matching
575        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
576        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
577            relocations.push(CodeRelocation {
578                offset: code.len() as u32,
579                symbol: symbol.clone(),
580                kind: synth_core::backend::RelocKind::MovwAbs,
581            });
582        }
583        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
584            relocations.push(CodeRelocation {
585                offset: code.len() as u32,
586                symbol: symbol.clone(),
587                kind: synth_core::backend::RelocKind::MovtAbs,
588            });
589        }
590        // #345: defer the literal-pool word + reloc + offset patch to the
591        // post-loop pass (the pool address is not yet known).
592        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
593            pending_literals.push(PendingLiteral {
594                ldr_offset: code.len() as u32,
595                symbol: symbol.clone(),
596                addend: *addend,
597            });
598        }
599
600        // The machine offset of this instruction is the current code length,
601        // captured before the bytes are appended.
602        line_map.push((code.len() as u32, instr.source_line));
603
604        let encoded = encoder
605            .encode(&instr.op)
606            .map_err(|e| format!("ARM encoding failed: {}", e))?;
607        code.extend_from_slice(&encoded);
608    }
609
610    // #345: place the literal pool at the end of this function's `.text`. Gated on
611    // there being at least one `LdrSym` — functions without one are byte-identical
612    // to before (no trailing padding, so downstream `func_offsets` are unchanged
613    // and the frozen differential fixtures stay bit-for-bit equal).
614    if !pending_literals.is_empty() {
615        if !use_thumb2 {
616            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
617        }
618        // 4-byte align the pool start (Thumb-2 word loads require it, and
619        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
620        while code.len() % 4 != 0 {
621            code.push(0x00);
622        }
623        // One distinct pooled word per LdrSym (no dedup: different sites carry
624        // different addends, and the REL addend lives in the word).
625        for lit in &pending_literals {
626            let word_offset = code.len() as u32;
627
628            // REL semantics: the linker computes `S + A`, where A is the in-place
629            // value of the relocated word. Initialize the word to the addend so
630            // the final loaded address is `symbol + addend`.
631            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
632            relocations.push(CodeRelocation {
633                offset: word_offset,
634                symbol: lit.symbol.clone(),
635                kind: synth_core::backend::RelocKind::Abs32,
636            });
637
638            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
639            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
640            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
641            let pc = lit.ldr_offset + 4;
642            let aligned_pc = pc & !3u32;
643            let imm12 = word_offset - aligned_pc;
644            if imm12 > 0xFFF {
645                // Wide LDR-literal range is ±4 KB; these function bodies are far
646                // smaller, but fail cleanly rather than miscompile if exceeded.
647                return Err(format!(
648                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
649                     for symbol {}",
650                    imm12, lit.symbol
651                ));
652            }
653            let hw2_off = (lit.ldr_offset + 2) as usize;
654            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
655            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
656            let hw2_bytes = hw2.to_le_bytes();
657            code[hw2_off] = hw2_bytes[0];
658            code[hw2_off + 1] = hw2_bytes[1];
659        }
660    }
661
662    Ok((code, relocations, line_map))
663}
664
665/// Resolve local label branches to byte-accurate offsets (#202).
666///
667/// `select_with_stack` emits conditional/unconditional branches as label
668/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
669/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
670/// this path only ran for `--no-optimize`/declined functions, so the latent bug
671/// stayed hidden — routing relocatable code through it surfaced branches that
672/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
673/// instruction sits between the branch and its target.
674///
675/// This pass encodes each instruction to learn its real byte length (so 16- vs
676/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
677/// to its byte position, and rewrites every label branch to the displacement
678/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
679/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
680/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
681/// the optimized path carry no label and are left untouched.
682fn resolve_label_branches(
683    arm_instrs: Vec<ArmInstruction>,
684    encoder: &ArmEncoder,
685) -> Result<Vec<ArmInstruction>, String> {
686    use std::collections::HashMap;
687    use synth_synthesis::Condition;
688
689    enum BKind {
690        Cond(Condition),
691        Uncond,
692    }
693    // Record each label branch ONCE — indices are stable across iterations.
694    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
695    for (i, instr) in arm_instrs.iter().enumerate() {
696        match &instr.op {
697            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
698            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
699            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
700            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
701            _ => {}
702        }
703    }
704    if branches.is_empty() {
705        return Ok(arm_instrs);
706    }
707
708    let mut resolved = arm_instrs;
709    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
710    for _ in 0..16 {
711        // 1. Byte position of each instruction (Label encodes to 0 bytes).
712        let mut positions = Vec::with_capacity(resolved.len());
713        let mut pos: i64 = 0;
714        for instr in &resolved {
715            positions.push(pos);
716            pos += encoder
717                .encode(&instr.op)
718                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
719                .len() as i64;
720        }
721        // 2. Label name -> byte position (owned keys so the borrow ends here).
722        let mut labels: HashMap<String, i64> = HashMap::new();
723        for (i, instr) in resolved.iter().enumerate() {
724            if let ArmOp::Label { name } = &instr.op {
725                labels.insert(name.clone(), positions[i]);
726            }
727        }
728        // 3. Rewrite each branch to its byte-accurate offset.
729        let mut changed = false;
730        for (idx, kind, label) in &branches {
731            // A label not defined locally is an EXTERNAL target (e.g.
732            // `Trap_Handler` resolved by a relocation / the vector table). Leave
733            // such branches as their placeholder for the existing relocation
734            // path — only local control-flow labels are byte-resolved here.
735            let Some(&target) = labels.get(label) else {
736                continue;
737            };
738            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
739            // Positions are always even, so this division is exact.
740            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
741            let new_op = match kind {
742                BKind::Cond(c) => ArmOp::BCondOffset {
743                    cond: *c,
744                    offset: halfword_offset,
745                },
746                BKind::Uncond => ArmOp::BOffset {
747                    offset: halfword_offset,
748                },
749            };
750            if resolved[*idx].op != new_op {
751                resolved[*idx].op = new_op;
752                changed = true;
753            }
754        }
755        if !changed {
756            break;
757        }
758    }
759    Ok(resolved)
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    #[test]
767    fn test_arm_backend_name() {
768        let backend = ArmBackend::new();
769        assert_eq!(backend.name(), "arm");
770        assert!(backend.is_available());
771    }
772
773    #[test]
774    fn test_arm_backend_capabilities() {
775        let backend = ArmBackend::new();
776        let caps = backend.capabilities();
777        assert!(!caps.produces_elf);
778        assert!(caps.supports_rule_verification);
779        assert!(!caps.is_external);
780    }
781
782    #[test]
783    fn test_compile_add_function() {
784        let backend = ArmBackend::new();
785        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
786        let config = CompileConfig::default();
787
788        let result = backend.compile_function("add", &ops, &config);
789        assert!(result.is_ok());
790
791        let func = result.unwrap();
792        assert_eq!(func.name, "add");
793        assert!(!func.code.is_empty());
794        assert_eq!(func.wasm_ops, ops);
795    }
796
797    /// VCR-DBG-001: the per-instruction source map must cover the function with
798    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
799    /// code (it is captured at encode time, never serialized here).
800    #[test]
801    fn test_line_map_is_wellformed_dbg001() {
802        let backend = ArmBackend::new();
803        let ops = vec![
804            WasmOp::LocalGet(0),
805            WasmOp::LocalGet(1),
806            WasmOp::I32Add,
807            WasmOp::End,
808        ];
809        let config = CompileConfig::default();
810        let func = backend.compile_function("add", &ops, &config).unwrap();
811
812        // Non-empty, and the first instruction starts at machine offset 0.
813        assert!(
814            !func.line_map.is_empty(),
815            "a non-trivial function captures a source map"
816        );
817        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
818
819        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
820        // bytes) and every mapped offset lies inside the emitted `.text`.
821        for w in func.line_map.windows(2) {
822            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
823            assert!(
824                w[1].0 - w[0].0 >= 2,
825                "each ARM/Thumb instruction is >= 2 bytes"
826            );
827        }
828        let last = func.line_map.last().unwrap().0 as usize;
829        assert!(
830            last < func.code.len(),
831            "every mapped offset lies inside .text"
832        );
833
834        // The side-table is additive: recompiling is deterministic and the map is
835        // consistent with that exact code (capturing it does not alter output).
836        let again = backend.compile_function("add", &ops, &config).unwrap();
837        assert_eq!(
838            again.code, func.code,
839            "compilation deterministic; map is additive"
840        );
841        assert_eq!(again.line_map, func.line_map);
842    }
843
844    #[test]
845    fn test_count_params() {
846        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
847        assert_eq!(count_params(&ops), 2);
848
849        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
850        assert_eq!(count_params(&no_params), 0);
851    }
852
853    #[test]
854    fn test_arm_backend_register() {
855        let mut registry = synth_core::BackendRegistry::new();
856        registry.register(Box::new(ArmBackend::new()));
857        assert!(registry.get("arm").is_some());
858        assert_eq!(registry.available().len(), 1);
859    }
860
861    #[test]
862    fn test_compile_import_call_produces_relocations() {
863        let backend = ArmBackend::new();
864        // Simulate a WASM module where func index 0 is an import.
865        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
866        let ops = vec![WasmOp::Call(0)];
867        let config = CompileConfig {
868            num_imports: 1,
869            no_optimize: true, // Direct instruction selection to preserve Call semantics
870            ..CompileConfig::default()
871        };
872
873        let result = backend.compile_function("caller", &ops, &config);
874        assert!(result.is_ok());
875
876        let func = result.unwrap();
877        assert!(!func.code.is_empty());
878        assert_eq!(func.relocations.len(), 1);
879        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
880        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
881        assert!(func.relocations[0].offset > 0);
882    }
883
884    /// Regression test for #197: in `relocatable` mode, an import call must
885    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
886    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
887    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
888    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
889    #[test]
890    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
891        let backend = ArmBackend::new();
892        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
893        let config = CompileConfig {
894            num_imports: 1,
895            relocatable: true,
896            ..CompileConfig::default()
897        };
898
899        let func = backend
900            .compile_function("caller", &ops, &config)
901            .expect("relocatable import call compiles");
902
903        assert_eq!(func.relocations.len(), 1);
904        assert_eq!(
905            func.relocations[0].symbol, "func_0",
906            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
907        );
908    }
909
910    #[test]
911    fn test_compile_no_imports_no_relocations() {
912        let backend = ArmBackend::new();
913        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
914        let config = CompileConfig::default();
915
916        let func = backend.compile_function("add", &ops, &config).unwrap();
917        assert!(func.relocations.is_empty());
918    }
919
920    /// Regression test for #167: a call to an INTERNAL function
921    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
922    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
923    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
924    /// to a garbage address — making the object non-linkable. This test
925    /// would have caught that regression.
926    #[test]
927    fn test_compile_internal_call_produces_relocation_167() {
928        let backend = ArmBackend::new();
929        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
930        let ops = vec![WasmOp::Call(2)];
931        let config = CompileConfig {
932            num_imports: 1,
933            no_optimize: true,
934            ..CompileConfig::default()
935        };
936
937        let func = backend
938            .compile_function("caller", &ops, &config)
939            .expect("internal call compiles");
940
941        assert_eq!(
942            func.relocations.len(),
943            1,
944            "an internal call must emit exactly one relocation (#167)"
945        );
946        assert_eq!(
947            func.relocations[0].symbol, "func_2",
948            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
949        );
950    }
951
952    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
953
954    #[test]
955    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
956        // Mpu mode must not introduce any inline check on ARM — the MPU
957        // handles faults via hardware. The encoded bytes for an i32.load
958        // should be identical between None and Mpu.
959        let backend = ArmBackend::new();
960        let ops = vec![
961            WasmOp::LocalGet(0),
962            WasmOp::I32Load {
963                offset: 0,
964                align: 2,
965            },
966        ];
967        let cfg_none = CompileConfig {
968            no_optimize: true,
969            ..Default::default()
970        };
971        let cfg_mpu = CompileConfig {
972            no_optimize: true,
973            safety_bounds: SafetyBounds::Mpu,
974            ..Default::default()
975        };
976        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
977        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
978        assert_eq!(
979            n.code, m.code,
980            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
981        );
982    }
983
984    #[test]
985    fn arm_legacy_bounds_check_still_emits_software_check() {
986        // Legacy CLI users with `--bounds-check` should keep getting the
987        // software path even though the new SafetyBounds field defaults to None.
988        let backend = ArmBackend::new();
989        let ops = vec![
990            WasmOp::LocalGet(0),
991            WasmOp::I32Load {
992                offset: 0,
993                align: 2,
994            },
995        ];
996        let cfg_legacy = CompileConfig {
997            no_optimize: true,
998            bounds_check: true,
999            ..Default::default()
1000        };
1001        let cfg_software = CompileConfig {
1002            no_optimize: true,
1003            safety_bounds: SafetyBounds::Software,
1004            ..Default::default()
1005        };
1006        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
1007        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
1008        assert_eq!(
1009            l.code, s.code,
1010            "--bounds-check should produce the same bytes as --safety-bounds=software"
1011        );
1012    }
1013
1014    // ========================================================================
1015    // ISA feature gate tests — ensure the compiler never emits unsupported
1016    // instructions for a given target
1017    // ========================================================================
1018
1019    #[test]
1020    fn test_f32_rejected_on_cortex_m3_no_fpu() {
1021        let backend = ArmBackend::new();
1022        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1023        let config = CompileConfig {
1024            target: TargetSpec::cortex_m3(),
1025            no_optimize: true,
1026            ..CompileConfig::default()
1027        };
1028
1029        let result = backend.compile_function("fadd", &ops, &config);
1030        assert!(
1031            result.is_err(),
1032            "f32 operations should fail on Cortex-M3 (no FPU)"
1033        );
1034    }
1035
1036    #[test]
1037    fn test_f32_accepted_on_cortex_m4f() {
1038        let backend = ArmBackend::new();
1039        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1040        let config = CompileConfig {
1041            target: TargetSpec::cortex_m4f(),
1042            no_optimize: true,
1043            ..CompileConfig::default()
1044        };
1045
1046        let result = backend.compile_function("fadd", &ops, &config);
1047        assert!(
1048            result.is_ok(),
1049            "f32 operations should succeed on Cortex-M4F, got: {:?}",
1050            result.unwrap_err()
1051        );
1052    }
1053
1054    #[test]
1055    fn test_i32_works_on_all_targets() {
1056        let backend = ArmBackend::new();
1057        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1058
1059        // Cortex-M3 (no FPU)
1060        let config_m3 = CompileConfig {
1061            target: TargetSpec::cortex_m3(),
1062            no_optimize: true,
1063            ..CompileConfig::default()
1064        };
1065        assert!(
1066            backend.compile_function("add", &ops, &config_m3).is_ok(),
1067            "i32 ops should work on Cortex-M3"
1068        );
1069
1070        // Cortex-M4F (single FPU)
1071        let config_m4f = CompileConfig {
1072            target: TargetSpec::cortex_m4f(),
1073            no_optimize: true,
1074            ..CompileConfig::default()
1075        };
1076        assert!(
1077            backend.compile_function("add", &ops, &config_m4f).is_ok(),
1078            "i32 ops should work on Cortex-M4F"
1079        );
1080
1081        // Cortex-M7DP (double FPU)
1082        let config_m7dp = CompileConfig {
1083            target: TargetSpec::cortex_m7dp(),
1084            no_optimize: true,
1085            ..CompileConfig::default()
1086        };
1087        assert!(
1088            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
1089            "i32 ops should work on Cortex-M7DP"
1090        );
1091    }
1092
1093    #[test]
1094    fn test_f32_rejected_on_cortex_m4_no_fpu() {
1095        // Cortex-M4 (without F suffix) has no FPU
1096        let backend = ArmBackend::new();
1097        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
1098        let config = CompileConfig {
1099            target: TargetSpec::cortex_m4(),
1100            no_optimize: true,
1101            ..CompileConfig::default()
1102        };
1103
1104        let result = backend.compile_function("fmul", &ops, &config);
1105        assert!(
1106            result.is_err(),
1107            "f32 operations should fail on Cortex-M4 (no FPU)"
1108        );
1109    }
1110
1111    // ========================================================================
1112    // Issue #120 — f32 ops in the optimized lowering path
1113    //
1114    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
1115    // value-producing float op fell through to `Opcode::Nop`, leaving a
1116    // downstream consumer with an unmapped vreg and tripping the PR #101
1117    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
1118    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
1119    // module.
1120    //
1121    // Fix: `optimize_full` declines float modules with a typed `Err`;
1122    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
1123    // path, which handles f32 via VFP/FPU. These tests use the *default*
1124    // (optimized) config — `no_optimize` is NOT set — which is the exact
1125    // configuration that panicked pre-fix.
1126    // ========================================================================
1127
1128    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
1129    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
1130    /// the module and the backend falls back to direct selection, producing a
1131    /// non-empty f32.div lowering on a Cortex-M4F.
1132    #[test]
1133    fn test_issue120_f32_div_compiles_via_optimized_default() {
1134        let backend = ArmBackend::new();
1135        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1136        let config = CompileConfig {
1137            target: TargetSpec::cortex_m4f(),
1138            // no_optimize NOT set — this exercises the optimized path that
1139            // panicked in issue #120, then the fallback to direct selection.
1140            ..CompileConfig::default()
1141        };
1142
1143        let result = backend.compile_function("fdiv", &ops, &config);
1144        assert!(
1145            result.is_ok(),
1146            "f32.div must compile on Cortex-M4F via the optimized->direct \
1147             fallback (issue #120), got: {:?}",
1148            result.as_ref().err()
1149        );
1150        assert!(
1151            !result.unwrap().code.is_empty(),
1152            "f32.div must produce non-empty machine code"
1153        );
1154    }
1155
1156    /// A spread of f32 ops, all through the optimized (default) config, must
1157    /// compile via the fallback on an FPU target without panicking.
1158    #[test]
1159    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
1160        let backend = ArmBackend::new();
1161        let config = CompileConfig {
1162            target: TargetSpec::cortex_m4f(),
1163            ..CompileConfig::default()
1164        };
1165
1166        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
1167            (
1168                "fadd",
1169                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
1170            ),
1171            (
1172                "fmul",
1173                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
1174            ),
1175            (
1176                "fsub",
1177                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
1178            ),
1179        ];
1180
1181        for (name, ops) in cases {
1182            let result = backend.compile_function(name, &ops, &config);
1183            assert!(
1184                result.is_ok(),
1185                "{name} must compile via the optimized->direct fallback \
1186                 (issue #120), got: {:?}",
1187                result.as_ref().err()
1188            );
1189            assert!(
1190                !result.unwrap().code.is_empty(),
1191                "{name} must produce non-empty machine code"
1192            );
1193        }
1194    }
1195
1196    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
1197    /// target must fail cleanly (not panic) even on the optimized path.
1198    #[test]
1199    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
1200        let backend = ArmBackend::new();
1201        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1202        let config = CompileConfig {
1203            target: TargetSpec::cortex_m3(),
1204            ..CompileConfig::default()
1205        };
1206
1207        let result = backend.compile_function("fdiv", &ops, &config);
1208        assert!(
1209            result.is_err(),
1210            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
1211        );
1212    }
1213
1214    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
1215    /// FFI-return hi32 extract pattern. Compiles two near-identical
1216    /// functions — one with the optimized shift-by-32, one with a generic
1217    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
1218    #[test]
1219    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
1220        let backend = ArmBackend::new();
1221        let config = CompileConfig {
1222            target: TargetSpec::cortex_m4f(),
1223            ..CompileConfig::default()
1224        };
1225
1226        // Optimized path: `(local.get 0) >>> 32; wrap_i64`
1227        let ops_hi32 = vec![
1228            WasmOp::LocalGet(0), // i64 param in R0:R1
1229            WasmOp::I64Const(32),
1230            WasmOp::I64ShrU,
1231            WasmOp::I32WrapI64,
1232        ];
1233        let func_hi32 = backend
1234            .compile_function("hi32_extract", &ops_hi32, &config)
1235            .unwrap();
1236
1237        // Generic path: `(local.get 0) >>> 7; wrap_i64` — same shape, but the
1238        // shift amount is not a multiple of 32, so it falls through to the
1239        // 38-byte runtime shift.
1240        let ops_generic = vec![
1241            WasmOp::LocalGet(0),
1242            WasmOp::I64Const(7),
1243            WasmOp::I64ShrU,
1244            WasmOp::I32WrapI64,
1245        ];
1246        let func_generic = backend
1247            .compile_function("generic_shr", &ops_generic, &config)
1248            .unwrap();
1249
1250        let bytes_hi32 = func_hi32.code.len();
1251        let bytes_generic = func_generic.code.len();
1252        println!(
1253            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
1254            bytes_hi32,
1255            bytes_generic,
1256            bytes_generic.saturating_sub(bytes_hi32)
1257        );
1258        let hex: String = func_hi32
1259            .code
1260            .iter()
1261            .map(|b| format!("{:02x}", b))
1262            .collect::<Vec<_>>()
1263            .join(" ");
1264        println!("[issue #94] hi32 bytes: {}", hex);
1265        // We expect the optimized form to be at least 30 bytes smaller than
1266        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
1267        assert!(
1268            bytes_hi32 + 30 <= bytes_generic,
1269            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
1270             expected optimized form to be at least 30 bytes smaller",
1271            bytes_hi32,
1272            bytes_generic,
1273        );
1274    }
1275}