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, 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            let compiled = self.compile_function(&name, &func.ops, config)?;
79            functions.push(compiled);
80        }
81
82        Ok(CompilationResult {
83            functions,
84            elf: None,
85            backend_name: self.name().to_string(),
86        })
87    }
88
89    fn compile_function(
90        &self,
91        name: &str,
92        ops: &[WasmOp],
93        config: &CompileConfig,
94    ) -> Result<CompiledFunction, BackendError> {
95        let (code, relocations) =
96            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
97
98        Ok(CompiledFunction {
99            name: name.to_string(),
100            code,
101            wasm_ops: ops.to_vec(),
102            relocations,
103        })
104    }
105
106    fn is_available(&self) -> bool {
107        true // Always available — it's a library backend
108    }
109}
110
111/// Count the number of function parameters by analyzing LocalGet patterns
112fn count_params(wasm_ops: &[WasmOp]) -> u32 {
113    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
114    for op in wasm_ops {
115        match op {
116            WasmOp::LocalGet(idx) => {
117                first_access.entry(*idx).or_insert(true);
118            }
119            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
120                first_access.entry(*idx).or_insert(false);
121            }
122            _ => {}
123        }
124    }
125
126    first_access
127        .iter()
128        .filter_map(
129            |(&idx, &is_read_first)| {
130                if is_read_first { Some(idx + 1) } else { None }
131            },
132        )
133        .max()
134        .unwrap_or(0)
135}
136
137/// Core compilation: WASM ops → ARM machine code bytes + relocations
138///
139/// Returns (code_bytes, relocations) where relocations record BL instructions
140/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
141fn compile_wasm_to_arm(
142    wasm_ops: &[WasmOp],
143    config: &CompileConfig,
144) -> Result<(Vec<u8>, Vec<CodeRelocation>), String> {
145    let num_params = count_params(wasm_ops);
146
147    let bounds_config = match config.effective_safety_bounds() {
148        SafetyBounds::None => BoundsCheckConfig::None,
149        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
150        SafetyBounds::Software => BoundsCheckConfig::Software,
151        SafetyBounds::Mask => BoundsCheckConfig::Masking,
152    };
153
154    // The non-optimized (direct) instruction-selection path. Handles f32 via
155    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
156    // when the optimized path declines a module (see issue #120 below).
157    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
158        let db = RuleDatabase::with_standard_rules();
159        let mut selector =
160            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
161        selector.set_target(config.target.fpu, &config.target.triple);
162        if config.num_imports > 0 {
163            selector.set_num_imports(config.num_imports);
164        }
165        // #195: plumb the callee argument-count tables so the direct selector can
166        // marshal call arguments into R0–R3 per AAPCS.
167        selector.set_func_arg_counts(
168            config.func_arg_counts.clone(),
169            config.type_arg_counts.clone(),
170        );
171        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
172        // imports (rewritten to the wasm field name by build_relocatable_elf)
173        // instead of `__meld_dispatch_import`.
174        selector.set_relocatable(config.relocatable);
175        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
176        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
177        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
178        // gating here keeps every non-native compile (all frozen fixtures) on the
179        // legacy R9 globals-table path, bit-identical.
180        if config.native_pointer_abi
181            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
182        {
183            selector.set_native_pointer_stack(sp_idx, sp_init);
184        }
185        selector
186            .select_with_stack(wasm_ops, num_params)
187            .map_err(|e| format!("instruction selection failed: {}", e))
188    };
189
190    // Instruction selection: optimized or direct.
191    //
192    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
193    // optimized path materializes an absolute linmem base (0x20000100) and does
194    // not preserve caller-saved registers across calls — both wrong for a
195    // host-linked object, where the linmem base arrives via `fp` at runtime and
196    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
197    // #171) handles fp-relative memory + caller-saved preservation correctly.
198    let arm_instrs = if config.no_optimize || config.relocatable {
199        select_direct()?
200    } else {
201        let opt_config = if config.loom_compat {
202            OptimizationConfig::loom_compat()
203        } else {
204            OptimizationConfig::all()
205        };
206
207        let mut bridge = OptimizerBridge::with_config(opt_config);
208        // #188: tell the bridge how many imports there are so it declines only
209        // LOCAL calls (and leaves import calls on the optimized path, keeping
210        // the #173 field-name relocation rewrite intact).
211        bridge.set_num_imports(config.num_imports);
212        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
213        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
214        // `optimize_full` failure: fall back to the direct selector rather
215        // than propagating, so the function still compiles correctly.
216        match bridge
217            .optimize_full(wasm_ops)
218            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
219        {
220            Ok(arm_ops) => arm_ops
221                .into_iter()
222                .map(|op| ArmInstruction {
223                    op,
224                    source_line: None,
225                })
226                .collect(),
227            // Issue #120: the optimized path declines modules it cannot lower
228            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
229            // back to the direct instruction selector, which handles f32 via
230            // VFP/FPU. This is honest degradation: the function still compiles
231            // correctly, just without IR-level optimization.
232            Err(_) => select_direct()?,
233        }
234    };
235
236    // ISA feature gate: validate that all generated instructions are supported
237    // by the target. This catches FPU instructions on no-FPU targets, double-precision
238    // instructions on single-precision targets, etc.
239    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
240        .map_err(|e| format!("ISA validation failed: {}", e))?;
241
242    // Encode to binary — use Thumb-2 for Cortex-M targets
243    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
244
245    let encoder = if use_thumb2 {
246        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
247    } else {
248        ArmEncoder::new_arm32()
249    };
250
251    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
252    // offsets before encoding. `select_with_stack` emits them as label
253    // placeholders and never resolves them — without this they encode as
254    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
255    // sits between the branch and its target (UsageFault on real hardware).
256    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
257    let arm_instrs = if use_thumb2 {
258        resolve_label_branches(arm_instrs, &encoder)?
259    } else {
260        arm_instrs
261    };
262
263    let mut code = Vec::new();
264    let mut relocations = Vec::new();
265
266    for instr in &arm_instrs {
267        // Record a relocation for every BL: the encoder emits `bl #0` and
268        // relies on a relocation to patch the target. This covers BOTH import
269        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
270        // (`func_N`, defined in this object). Previously only `__meld_*` was
271        // recorded, so internal `BL func_N` calls were left as unpatched
272        // `bl #0` placeholders branching to a garbage address (#167).
273        if let ArmOp::Bl { label } = &instr.op {
274            relocations.push(CodeRelocation {
275                offset: code.len() as u32,
276                symbol: label.clone(),
277                kind: synth_core::backend::RelocKind::ThmCall,
278            });
279        }
280        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
281        // addressing). The encoder writes the addend in place; record the matching
282        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
283        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
284            relocations.push(CodeRelocation {
285                offset: code.len() as u32,
286                symbol: symbol.clone(),
287                kind: synth_core::backend::RelocKind::MovwAbs,
288            });
289        }
290        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
291            relocations.push(CodeRelocation {
292                offset: code.len() as u32,
293                symbol: symbol.clone(),
294                kind: synth_core::backend::RelocKind::MovtAbs,
295            });
296        }
297
298        let encoded = encoder
299            .encode(&instr.op)
300            .map_err(|e| format!("ARM encoding failed: {}", e))?;
301        code.extend_from_slice(&encoded);
302    }
303
304    Ok((code, relocations))
305}
306
307/// Resolve local label branches to byte-accurate offsets (#202).
308///
309/// `select_with_stack` emits conditional/unconditional branches as label
310/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
311/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
312/// this path only ran for `--no-optimize`/declined functions, so the latent bug
313/// stayed hidden — routing relocatable code through it surfaced branches that
314/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
315/// instruction sits between the branch and its target.
316///
317/// This pass encodes each instruction to learn its real byte length (so 16- vs
318/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
319/// to its byte position, and rewrites every label branch to the displacement
320/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
321/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
322/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
323/// the optimized path carry no label and are left untouched.
324fn resolve_label_branches(
325    arm_instrs: Vec<ArmInstruction>,
326    encoder: &ArmEncoder,
327) -> Result<Vec<ArmInstruction>, String> {
328    use std::collections::HashMap;
329    use synth_synthesis::Condition;
330
331    enum BKind {
332        Cond(Condition),
333        Uncond,
334    }
335    // Record each label branch ONCE — indices are stable across iterations.
336    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
337    for (i, instr) in arm_instrs.iter().enumerate() {
338        match &instr.op {
339            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
340            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
341            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
342            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
343            _ => {}
344        }
345    }
346    if branches.is_empty() {
347        return Ok(arm_instrs);
348    }
349
350    let mut resolved = arm_instrs;
351    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
352    for _ in 0..16 {
353        // 1. Byte position of each instruction (Label encodes to 0 bytes).
354        let mut positions = Vec::with_capacity(resolved.len());
355        let mut pos: i64 = 0;
356        for instr in &resolved {
357            positions.push(pos);
358            pos += encoder
359                .encode(&instr.op)
360                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
361                .len() as i64;
362        }
363        // 2. Label name -> byte position (owned keys so the borrow ends here).
364        let mut labels: HashMap<String, i64> = HashMap::new();
365        for (i, instr) in resolved.iter().enumerate() {
366            if let ArmOp::Label { name } = &instr.op {
367                labels.insert(name.clone(), positions[i]);
368            }
369        }
370        // 3. Rewrite each branch to its byte-accurate offset.
371        let mut changed = false;
372        for (idx, kind, label) in &branches {
373            // A label not defined locally is an EXTERNAL target (e.g.
374            // `Trap_Handler` resolved by a relocation / the vector table). Leave
375            // such branches as their placeholder for the existing relocation
376            // path — only local control-flow labels are byte-resolved here.
377            let Some(&target) = labels.get(label) else {
378                continue;
379            };
380            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
381            // Positions are always even, so this division is exact.
382            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
383            let new_op = match kind {
384                BKind::Cond(c) => ArmOp::BCondOffset {
385                    cond: *c,
386                    offset: halfword_offset,
387                },
388                BKind::Uncond => ArmOp::BOffset {
389                    offset: halfword_offset,
390                },
391            };
392            if resolved[*idx].op != new_op {
393                resolved[*idx].op = new_op;
394                changed = true;
395            }
396        }
397        if !changed {
398            break;
399        }
400    }
401    Ok(resolved)
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    #[test]
409    fn test_arm_backend_name() {
410        let backend = ArmBackend::new();
411        assert_eq!(backend.name(), "arm");
412        assert!(backend.is_available());
413    }
414
415    #[test]
416    fn test_arm_backend_capabilities() {
417        let backend = ArmBackend::new();
418        let caps = backend.capabilities();
419        assert!(!caps.produces_elf);
420        assert!(caps.supports_rule_verification);
421        assert!(!caps.is_external);
422    }
423
424    #[test]
425    fn test_compile_add_function() {
426        let backend = ArmBackend::new();
427        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
428        let config = CompileConfig::default();
429
430        let result = backend.compile_function("add", &ops, &config);
431        assert!(result.is_ok());
432
433        let func = result.unwrap();
434        assert_eq!(func.name, "add");
435        assert!(!func.code.is_empty());
436        assert_eq!(func.wasm_ops, ops);
437    }
438
439    #[test]
440    fn test_count_params() {
441        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
442        assert_eq!(count_params(&ops), 2);
443
444        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
445        assert_eq!(count_params(&no_params), 0);
446    }
447
448    #[test]
449    fn test_arm_backend_register() {
450        let mut registry = synth_core::BackendRegistry::new();
451        registry.register(Box::new(ArmBackend::new()));
452        assert!(registry.get("arm").is_some());
453        assert_eq!(registry.available().len(), 1);
454    }
455
456    #[test]
457    fn test_compile_import_call_produces_relocations() {
458        let backend = ArmBackend::new();
459        // Simulate a WASM module where func index 0 is an import.
460        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
461        let ops = vec![WasmOp::Call(0)];
462        let config = CompileConfig {
463            num_imports: 1,
464            no_optimize: true, // Direct instruction selection to preserve Call semantics
465            ..CompileConfig::default()
466        };
467
468        let result = backend.compile_function("caller", &ops, &config);
469        assert!(result.is_ok());
470
471        let func = result.unwrap();
472        assert!(!func.code.is_empty());
473        assert_eq!(func.relocations.len(), 1);
474        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
475        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
476        assert!(func.relocations[0].offset > 0);
477    }
478
479    /// Regression test for #197: in `relocatable` mode, an import call must
480    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
481    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
482    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
483    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
484    #[test]
485    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
486        let backend = ArmBackend::new();
487        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
488        let config = CompileConfig {
489            num_imports: 1,
490            relocatable: true,
491            ..CompileConfig::default()
492        };
493
494        let func = backend
495            .compile_function("caller", &ops, &config)
496            .expect("relocatable import call compiles");
497
498        assert_eq!(func.relocations.len(), 1);
499        assert_eq!(
500            func.relocations[0].symbol, "func_0",
501            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
502        );
503    }
504
505    #[test]
506    fn test_compile_no_imports_no_relocations() {
507        let backend = ArmBackend::new();
508        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
509        let config = CompileConfig::default();
510
511        let func = backend.compile_function("add", &ops, &config).unwrap();
512        assert!(func.relocations.is_empty());
513    }
514
515    /// Regression test for #167: a call to an INTERNAL function
516    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
517    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
518    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
519    /// to a garbage address — making the object non-linkable. This test
520    /// would have caught that regression.
521    #[test]
522    fn test_compile_internal_call_produces_relocation_167() {
523        let backend = ArmBackend::new();
524        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
525        let ops = vec![WasmOp::Call(2)];
526        let config = CompileConfig {
527            num_imports: 1,
528            no_optimize: true,
529            ..CompileConfig::default()
530        };
531
532        let func = backend
533            .compile_function("caller", &ops, &config)
534            .expect("internal call compiles");
535
536        assert_eq!(
537            func.relocations.len(),
538            1,
539            "an internal call must emit exactly one relocation (#167)"
540        );
541        assert_eq!(
542            func.relocations[0].symbol, "func_2",
543            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
544        );
545    }
546
547    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
548
549    #[test]
550    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
551        // Mpu mode must not introduce any inline check on ARM — the MPU
552        // handles faults via hardware. The encoded bytes for an i32.load
553        // should be identical between None and Mpu.
554        let backend = ArmBackend::new();
555        let ops = vec![
556            WasmOp::LocalGet(0),
557            WasmOp::I32Load {
558                offset: 0,
559                align: 2,
560            },
561        ];
562        let cfg_none = CompileConfig {
563            no_optimize: true,
564            ..Default::default()
565        };
566        let cfg_mpu = CompileConfig {
567            no_optimize: true,
568            safety_bounds: SafetyBounds::Mpu,
569            ..Default::default()
570        };
571        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
572        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
573        assert_eq!(
574            n.code, m.code,
575            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
576        );
577    }
578
579    #[test]
580    fn arm_legacy_bounds_check_still_emits_software_check() {
581        // Legacy CLI users with `--bounds-check` should keep getting the
582        // software path even though the new SafetyBounds field defaults to None.
583        let backend = ArmBackend::new();
584        let ops = vec![
585            WasmOp::LocalGet(0),
586            WasmOp::I32Load {
587                offset: 0,
588                align: 2,
589            },
590        ];
591        let cfg_legacy = CompileConfig {
592            no_optimize: true,
593            bounds_check: true,
594            ..Default::default()
595        };
596        let cfg_software = CompileConfig {
597            no_optimize: true,
598            safety_bounds: SafetyBounds::Software,
599            ..Default::default()
600        };
601        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
602        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
603        assert_eq!(
604            l.code, s.code,
605            "--bounds-check should produce the same bytes as --safety-bounds=software"
606        );
607    }
608
609    // ========================================================================
610    // ISA feature gate tests — ensure the compiler never emits unsupported
611    // instructions for a given target
612    // ========================================================================
613
614    #[test]
615    fn test_f32_rejected_on_cortex_m3_no_fpu() {
616        let backend = ArmBackend::new();
617        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
618        let config = CompileConfig {
619            target: TargetSpec::cortex_m3(),
620            no_optimize: true,
621            ..CompileConfig::default()
622        };
623
624        let result = backend.compile_function("fadd", &ops, &config);
625        assert!(
626            result.is_err(),
627            "f32 operations should fail on Cortex-M3 (no FPU)"
628        );
629    }
630
631    #[test]
632    fn test_f32_accepted_on_cortex_m4f() {
633        let backend = ArmBackend::new();
634        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
635        let config = CompileConfig {
636            target: TargetSpec::cortex_m4f(),
637            no_optimize: true,
638            ..CompileConfig::default()
639        };
640
641        let result = backend.compile_function("fadd", &ops, &config);
642        assert!(
643            result.is_ok(),
644            "f32 operations should succeed on Cortex-M4F, got: {:?}",
645            result.unwrap_err()
646        );
647    }
648
649    #[test]
650    fn test_i32_works_on_all_targets() {
651        let backend = ArmBackend::new();
652        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
653
654        // Cortex-M3 (no FPU)
655        let config_m3 = CompileConfig {
656            target: TargetSpec::cortex_m3(),
657            no_optimize: true,
658            ..CompileConfig::default()
659        };
660        assert!(
661            backend.compile_function("add", &ops, &config_m3).is_ok(),
662            "i32 ops should work on Cortex-M3"
663        );
664
665        // Cortex-M4F (single FPU)
666        let config_m4f = CompileConfig {
667            target: TargetSpec::cortex_m4f(),
668            no_optimize: true,
669            ..CompileConfig::default()
670        };
671        assert!(
672            backend.compile_function("add", &ops, &config_m4f).is_ok(),
673            "i32 ops should work on Cortex-M4F"
674        );
675
676        // Cortex-M7DP (double FPU)
677        let config_m7dp = CompileConfig {
678            target: TargetSpec::cortex_m7dp(),
679            no_optimize: true,
680            ..CompileConfig::default()
681        };
682        assert!(
683            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
684            "i32 ops should work on Cortex-M7DP"
685        );
686    }
687
688    #[test]
689    fn test_f32_rejected_on_cortex_m4_no_fpu() {
690        // Cortex-M4 (without F suffix) has no FPU
691        let backend = ArmBackend::new();
692        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
693        let config = CompileConfig {
694            target: TargetSpec::cortex_m4(),
695            no_optimize: true,
696            ..CompileConfig::default()
697        };
698
699        let result = backend.compile_function("fmul", &ops, &config);
700        assert!(
701            result.is_err(),
702            "f32 operations should fail on Cortex-M4 (no FPU)"
703        );
704    }
705
706    // ========================================================================
707    // Issue #120 — f32 ops in the optimized lowering path
708    //
709    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
710    // value-producing float op fell through to `Opcode::Nop`, leaving a
711    // downstream consumer with an unmapped vreg and tripping the PR #101
712    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
713    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
714    // module.
715    //
716    // Fix: `optimize_full` declines float modules with a typed `Err`;
717    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
718    // path, which handles f32 via VFP/FPU. These tests use the *default*
719    // (optimized) config — `no_optimize` is NOT set — which is the exact
720    // configuration that panicked pre-fix.
721    // ========================================================================
722
723    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
724    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
725    /// the module and the backend falls back to direct selection, producing a
726    /// non-empty f32.div lowering on a Cortex-M4F.
727    #[test]
728    fn test_issue120_f32_div_compiles_via_optimized_default() {
729        let backend = ArmBackend::new();
730        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
731        let config = CompileConfig {
732            target: TargetSpec::cortex_m4f(),
733            // no_optimize NOT set — this exercises the optimized path that
734            // panicked in issue #120, then the fallback to direct selection.
735            ..CompileConfig::default()
736        };
737
738        let result = backend.compile_function("fdiv", &ops, &config);
739        assert!(
740            result.is_ok(),
741            "f32.div must compile on Cortex-M4F via the optimized->direct \
742             fallback (issue #120), got: {:?}",
743            result.as_ref().err()
744        );
745        assert!(
746            !result.unwrap().code.is_empty(),
747            "f32.div must produce non-empty machine code"
748        );
749    }
750
751    /// A spread of f32 ops, all through the optimized (default) config, must
752    /// compile via the fallback on an FPU target without panicking.
753    #[test]
754    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
755        let backend = ArmBackend::new();
756        let config = CompileConfig {
757            target: TargetSpec::cortex_m4f(),
758            ..CompileConfig::default()
759        };
760
761        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
762            (
763                "fadd",
764                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
765            ),
766            (
767                "fmul",
768                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
769            ),
770            (
771                "fsub",
772                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
773            ),
774        ];
775
776        for (name, ops) in cases {
777            let result = backend.compile_function(name, &ops, &config);
778            assert!(
779                result.is_ok(),
780                "{name} must compile via the optimized->direct fallback \
781                 (issue #120), got: {:?}",
782                result.as_ref().err()
783            );
784            assert!(
785                !result.unwrap().code.is_empty(),
786                "{name} must produce non-empty machine code"
787            );
788        }
789    }
790
791    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
792    /// target must fail cleanly (not panic) even on the optimized path.
793    #[test]
794    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
795        let backend = ArmBackend::new();
796        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
797        let config = CompileConfig {
798            target: TargetSpec::cortex_m3(),
799            ..CompileConfig::default()
800        };
801
802        let result = backend.compile_function("fdiv", &ops, &config);
803        assert!(
804            result.is_err(),
805            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
806        );
807    }
808
809    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
810    /// FFI-return hi32 extract pattern. Compiles two near-identical
811    /// functions — one with the optimized shift-by-32, one with a generic
812    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
813    #[test]
814    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
815        let backend = ArmBackend::new();
816        let config = CompileConfig {
817            target: TargetSpec::cortex_m4f(),
818            ..CompileConfig::default()
819        };
820
821        // Optimized path: `(local.get 0) >>> 32; wrap_i64`
822        let ops_hi32 = vec![
823            WasmOp::LocalGet(0), // i64 param in R0:R1
824            WasmOp::I64Const(32),
825            WasmOp::I64ShrU,
826            WasmOp::I32WrapI64,
827        ];
828        let func_hi32 = backend
829            .compile_function("hi32_extract", &ops_hi32, &config)
830            .unwrap();
831
832        // Generic path: `(local.get 0) >>> 7; wrap_i64` — same shape, but the
833        // shift amount is not a multiple of 32, so it falls through to the
834        // 38-byte runtime shift.
835        let ops_generic = vec![
836            WasmOp::LocalGet(0),
837            WasmOp::I64Const(7),
838            WasmOp::I64ShrU,
839            WasmOp::I32WrapI64,
840        ];
841        let func_generic = backend
842            .compile_function("generic_shr", &ops_generic, &config)
843            .unwrap();
844
845        let bytes_hi32 = func_hi32.code.len();
846        let bytes_generic = func_generic.code.len();
847        println!(
848            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
849            bytes_hi32,
850            bytes_generic,
851            bytes_generic.saturating_sub(bytes_hi32)
852        );
853        let hex: String = func_hi32
854            .code
855            .iter()
856            .map(|b| format!("{:02x}", b))
857            .collect::<Vec<_>>()
858            .join(" ");
859        println!("[issue #94] hi32 bytes: {}", hex);
860        // We expect the optimized form to be at least 30 bytes smaller than
861        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
862        assert!(
863            bytes_hi32 + 30 <= bytes_generic,
864            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
865             expected optimized form to be at least 30 bytes smaller",
866            bytes_hi32,
867            bytes_generic,
868        );
869    }
870}