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