1use 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
19pub 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 }
109}
110
111fn 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
137fn 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 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 selector.set_func_arg_counts(
168 config.func_arg_counts.clone(),
169 config.type_arg_counts.clone(),
170 );
171 selector.set_relocatable(config.relocatable);
175 selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
177 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 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 bridge.set_num_imports(config.num_imports);
212 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 Err(_) => select_direct()?,
233 }
234 };
235
236 validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
254 .map_err(|e| format!("ISA validation failed: {}", e))?;
255
256 let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
258
259 let encoder = if use_thumb2 {
260 ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
261 } else {
262 ArmEncoder::new_arm32()
263 };
264
265 let arm_instrs = if use_thumb2 {
272 resolve_label_branches(arm_instrs, &encoder)?
273 } else {
274 arm_instrs
275 };
276
277 let mut code = Vec::new();
278 let mut relocations = Vec::new();
279
280 for instr in &arm_instrs {
281 if let ArmOp::Bl { label } = &instr.op {
288 relocations.push(CodeRelocation {
289 offset: code.len() as u32,
290 symbol: label.clone(),
291 kind: synth_core::backend::RelocKind::ThmCall,
292 });
293 }
294 if let ArmOp::MovwSym { symbol, .. } = &instr.op {
298 relocations.push(CodeRelocation {
299 offset: code.len() as u32,
300 symbol: symbol.clone(),
301 kind: synth_core::backend::RelocKind::MovwAbs,
302 });
303 }
304 if let ArmOp::MovtSym { symbol, .. } = &instr.op {
305 relocations.push(CodeRelocation {
306 offset: code.len() as u32,
307 symbol: symbol.clone(),
308 kind: synth_core::backend::RelocKind::MovtAbs,
309 });
310 }
311
312 let encoded = encoder
313 .encode(&instr.op)
314 .map_err(|e| format!("ARM encoding failed: {}", e))?;
315 code.extend_from_slice(&encoded);
316 }
317
318 Ok((code, relocations))
319}
320
321fn resolve_label_branches(
339 arm_instrs: Vec<ArmInstruction>,
340 encoder: &ArmEncoder,
341) -> Result<Vec<ArmInstruction>, String> {
342 use std::collections::HashMap;
343 use synth_synthesis::Condition;
344
345 enum BKind {
346 Cond(Condition),
347 Uncond,
348 }
349 let mut branches: Vec<(usize, BKind, String)> = Vec::new();
351 for (i, instr) in arm_instrs.iter().enumerate() {
352 match &instr.op {
353 ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
354 ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
355 ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
356 ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
357 _ => {}
358 }
359 }
360 if branches.is_empty() {
361 return Ok(arm_instrs);
362 }
363
364 let mut resolved = arm_instrs;
365 for _ in 0..16 {
367 let mut positions = Vec::with_capacity(resolved.len());
369 let mut pos: i64 = 0;
370 for instr in &resolved {
371 positions.push(pos);
372 pos += encoder
373 .encode(&instr.op)
374 .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
375 .len() as i64;
376 }
377 let mut labels: HashMap<String, i64> = HashMap::new();
379 for (i, instr) in resolved.iter().enumerate() {
380 if let ArmOp::Label { name } = &instr.op {
381 labels.insert(name.clone(), positions[i]);
382 }
383 }
384 let mut changed = false;
386 for (idx, kind, label) in &branches {
387 let Some(&target) = labels.get(label) else {
392 continue;
393 };
394 let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
397 let new_op = match kind {
398 BKind::Cond(c) => ArmOp::BCondOffset {
399 cond: *c,
400 offset: halfword_offset,
401 },
402 BKind::Uncond => ArmOp::BOffset {
403 offset: halfword_offset,
404 },
405 };
406 if resolved[*idx].op != new_op {
407 resolved[*idx].op = new_op;
408 changed = true;
409 }
410 }
411 if !changed {
412 break;
413 }
414 }
415 Ok(resolved)
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421
422 #[test]
423 fn test_arm_backend_name() {
424 let backend = ArmBackend::new();
425 assert_eq!(backend.name(), "arm");
426 assert!(backend.is_available());
427 }
428
429 #[test]
430 fn test_arm_backend_capabilities() {
431 let backend = ArmBackend::new();
432 let caps = backend.capabilities();
433 assert!(!caps.produces_elf);
434 assert!(caps.supports_rule_verification);
435 assert!(!caps.is_external);
436 }
437
438 #[test]
439 fn test_compile_add_function() {
440 let backend = ArmBackend::new();
441 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
442 let config = CompileConfig::default();
443
444 let result = backend.compile_function("add", &ops, &config);
445 assert!(result.is_ok());
446
447 let func = result.unwrap();
448 assert_eq!(func.name, "add");
449 assert!(!func.code.is_empty());
450 assert_eq!(func.wasm_ops, ops);
451 }
452
453 #[test]
454 fn test_count_params() {
455 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
456 assert_eq!(count_params(&ops), 2);
457
458 let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
459 assert_eq!(count_params(&no_params), 0);
460 }
461
462 #[test]
463 fn test_arm_backend_register() {
464 let mut registry = synth_core::BackendRegistry::new();
465 registry.register(Box::new(ArmBackend::new()));
466 assert!(registry.get("arm").is_some());
467 assert_eq!(registry.available().len(), 1);
468 }
469
470 #[test]
471 fn test_compile_import_call_produces_relocations() {
472 let backend = ArmBackend::new();
473 let ops = vec![WasmOp::Call(0)];
476 let config = CompileConfig {
477 num_imports: 1,
478 no_optimize: true, ..CompileConfig::default()
480 };
481
482 let result = backend.compile_function("caller", &ops, &config);
483 assert!(result.is_ok());
484
485 let func = result.unwrap();
486 assert!(!func.code.is_empty());
487 assert_eq!(func.relocations.len(), 1);
488 assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
489 assert!(func.relocations[0].offset > 0);
491 }
492
493 #[test]
499 fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
500 let backend = ArmBackend::new();
501 let ops = vec![WasmOp::Call(0)]; let config = CompileConfig {
503 num_imports: 1,
504 relocatable: true,
505 ..CompileConfig::default()
506 };
507
508 let func = backend
509 .compile_function("caller", &ops, &config)
510 .expect("relocatable import call compiles");
511
512 assert_eq!(func.relocations.len(), 1);
513 assert_eq!(
514 func.relocations[0].symbol, "func_0",
515 "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
516 );
517 }
518
519 #[test]
520 fn test_compile_no_imports_no_relocations() {
521 let backend = ArmBackend::new();
522 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
523 let config = CompileConfig::default();
524
525 let func = backend.compile_function("add", &ops, &config).unwrap();
526 assert!(func.relocations.is_empty());
527 }
528
529 #[test]
536 fn test_compile_internal_call_produces_relocation_167() {
537 let backend = ArmBackend::new();
538 let ops = vec![WasmOp::Call(2)];
540 let config = CompileConfig {
541 num_imports: 1,
542 no_optimize: true,
543 ..CompileConfig::default()
544 };
545
546 let func = backend
547 .compile_function("caller", &ops, &config)
548 .expect("internal call compiles");
549
550 assert_eq!(
551 func.relocations.len(),
552 1,
553 "an internal call must emit exactly one relocation (#167)"
554 );
555 assert_eq!(
556 func.relocations[0].symbol, "func_2",
557 "internal call must relocate against the callee's func_{{index}} symbol (#167)"
558 );
559 }
560
561 #[test]
564 fn arm_safety_bounds_mpu_emits_same_code_as_none() {
565 let backend = ArmBackend::new();
569 let ops = vec![
570 WasmOp::LocalGet(0),
571 WasmOp::I32Load {
572 offset: 0,
573 align: 2,
574 },
575 ];
576 let cfg_none = CompileConfig {
577 no_optimize: true,
578 ..Default::default()
579 };
580 let cfg_mpu = CompileConfig {
581 no_optimize: true,
582 safety_bounds: SafetyBounds::Mpu,
583 ..Default::default()
584 };
585 let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
586 let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
587 assert_eq!(
588 n.code, m.code,
589 "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
590 );
591 }
592
593 #[test]
594 fn arm_legacy_bounds_check_still_emits_software_check() {
595 let backend = ArmBackend::new();
598 let ops = vec![
599 WasmOp::LocalGet(0),
600 WasmOp::I32Load {
601 offset: 0,
602 align: 2,
603 },
604 ];
605 let cfg_legacy = CompileConfig {
606 no_optimize: true,
607 bounds_check: true,
608 ..Default::default()
609 };
610 let cfg_software = CompileConfig {
611 no_optimize: true,
612 safety_bounds: SafetyBounds::Software,
613 ..Default::default()
614 };
615 let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
616 let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
617 assert_eq!(
618 l.code, s.code,
619 "--bounds-check should produce the same bytes as --safety-bounds=software"
620 );
621 }
622
623 #[test]
629 fn test_f32_rejected_on_cortex_m3_no_fpu() {
630 let backend = ArmBackend::new();
631 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
632 let config = CompileConfig {
633 target: TargetSpec::cortex_m3(),
634 no_optimize: true,
635 ..CompileConfig::default()
636 };
637
638 let result = backend.compile_function("fadd", &ops, &config);
639 assert!(
640 result.is_err(),
641 "f32 operations should fail on Cortex-M3 (no FPU)"
642 );
643 }
644
645 #[test]
646 fn test_f32_accepted_on_cortex_m4f() {
647 let backend = ArmBackend::new();
648 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
649 let config = CompileConfig {
650 target: TargetSpec::cortex_m4f(),
651 no_optimize: true,
652 ..CompileConfig::default()
653 };
654
655 let result = backend.compile_function("fadd", &ops, &config);
656 assert!(
657 result.is_ok(),
658 "f32 operations should succeed on Cortex-M4F, got: {:?}",
659 result.unwrap_err()
660 );
661 }
662
663 #[test]
664 fn test_i32_works_on_all_targets() {
665 let backend = ArmBackend::new();
666 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
667
668 let config_m3 = CompileConfig {
670 target: TargetSpec::cortex_m3(),
671 no_optimize: true,
672 ..CompileConfig::default()
673 };
674 assert!(
675 backend.compile_function("add", &ops, &config_m3).is_ok(),
676 "i32 ops should work on Cortex-M3"
677 );
678
679 let config_m4f = CompileConfig {
681 target: TargetSpec::cortex_m4f(),
682 no_optimize: true,
683 ..CompileConfig::default()
684 };
685 assert!(
686 backend.compile_function("add", &ops, &config_m4f).is_ok(),
687 "i32 ops should work on Cortex-M4F"
688 );
689
690 let config_m7dp = CompileConfig {
692 target: TargetSpec::cortex_m7dp(),
693 no_optimize: true,
694 ..CompileConfig::default()
695 };
696 assert!(
697 backend.compile_function("add", &ops, &config_m7dp).is_ok(),
698 "i32 ops should work on Cortex-M7DP"
699 );
700 }
701
702 #[test]
703 fn test_f32_rejected_on_cortex_m4_no_fpu() {
704 let backend = ArmBackend::new();
706 let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
707 let config = CompileConfig {
708 target: TargetSpec::cortex_m4(),
709 no_optimize: true,
710 ..CompileConfig::default()
711 };
712
713 let result = backend.compile_function("fmul", &ops, &config);
714 assert!(
715 result.is_err(),
716 "f32 operations should fail on Cortex-M4 (no FPU)"
717 );
718 }
719
720 #[test]
742 fn test_issue120_f32_div_compiles_via_optimized_default() {
743 let backend = ArmBackend::new();
744 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
745 let config = CompileConfig {
746 target: TargetSpec::cortex_m4f(),
747 ..CompileConfig::default()
750 };
751
752 let result = backend.compile_function("fdiv", &ops, &config);
753 assert!(
754 result.is_ok(),
755 "f32.div must compile on Cortex-M4F via the optimized->direct \
756 fallback (issue #120), got: {:?}",
757 result.as_ref().err()
758 );
759 assert!(
760 !result.unwrap().code.is_empty(),
761 "f32.div must produce non-empty machine code"
762 );
763 }
764
765 #[test]
768 fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
769 let backend = ArmBackend::new();
770 let config = CompileConfig {
771 target: TargetSpec::cortex_m4f(),
772 ..CompileConfig::default()
773 };
774
775 let cases: Vec<(&str, Vec<WasmOp>)> = vec![
776 (
777 "fadd",
778 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
779 ),
780 (
781 "fmul",
782 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
783 ),
784 (
785 "fsub",
786 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
787 ),
788 ];
789
790 for (name, ops) in cases {
791 let result = backend.compile_function(name, &ops, &config);
792 assert!(
793 result.is_ok(),
794 "{name} must compile via the optimized->direct fallback \
795 (issue #120), got: {:?}",
796 result.as_ref().err()
797 );
798 assert!(
799 !result.unwrap().code.is_empty(),
800 "{name} must produce non-empty machine code"
801 );
802 }
803 }
804
805 #[test]
808 fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
809 let backend = ArmBackend::new();
810 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
811 let config = CompileConfig {
812 target: TargetSpec::cortex_m3(),
813 ..CompileConfig::default()
814 };
815
816 let result = backend.compile_function("fdiv", &ops, &config);
817 assert!(
818 result.is_err(),
819 "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
820 );
821 }
822
823 #[test]
828 fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
829 let backend = ArmBackend::new();
830 let config = CompileConfig {
831 target: TargetSpec::cortex_m4f(),
832 ..CompileConfig::default()
833 };
834
835 let ops_hi32 = vec![
837 WasmOp::LocalGet(0), WasmOp::I64Const(32),
839 WasmOp::I64ShrU,
840 WasmOp::I32WrapI64,
841 ];
842 let func_hi32 = backend
843 .compile_function("hi32_extract", &ops_hi32, &config)
844 .unwrap();
845
846 let ops_generic = vec![
850 WasmOp::LocalGet(0),
851 WasmOp::I64Const(7),
852 WasmOp::I64ShrU,
853 WasmOp::I32WrapI64,
854 ];
855 let func_generic = backend
856 .compile_function("generic_shr", &ops_generic, &config)
857 .unwrap();
858
859 let bytes_hi32 = func_hi32.code.len();
860 let bytes_generic = func_generic.code.len();
861 println!(
862 "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
863 bytes_hi32,
864 bytes_generic,
865 bytes_generic.saturating_sub(bytes_hi32)
866 );
867 let hex: String = func_hi32
868 .code
869 .iter()
870 .map(|b| format!("{:02x}", b))
871 .collect::<Vec<_>>()
872 .join(" ");
873 println!("[issue #94] hi32 bytes: {}", hex);
874 assert!(
877 bytes_hi32 + 30 <= bytes_generic,
878 "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
879 expected optimized form to be at least 30 bytes smaller",
880 bytes_hi32,
881 bytes_generic,
882 );
883 }
884}