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
166 .select_with_stack(wasm_ops, num_params)
167 .map_err(|e| format!("instruction selection failed: {}", e))
168 };
169
170 let arm_instrs = if config.no_optimize {
172 select_direct()?
173 } else {
174 let opt_config = if config.loom_compat {
175 OptimizationConfig::loom_compat()
176 } else {
177 OptimizationConfig::all()
178 };
179
180 let bridge = OptimizerBridge::with_config(opt_config);
181 match bridge
186 .optimize_full(wasm_ops)
187 .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
188 {
189 Ok(arm_ops) => arm_ops
190 .into_iter()
191 .map(|op| ArmInstruction {
192 op,
193 source_line: None,
194 })
195 .collect(),
196 Err(_) => select_direct()?,
202 }
203 };
204
205 validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
209 .map_err(|e| format!("ISA validation failed: {}", e))?;
210
211 let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
213
214 let encoder = if use_thumb2 {
215 ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
216 } else {
217 ArmEncoder::new_arm32()
218 };
219
220 let mut code = Vec::new();
221 let mut relocations = Vec::new();
222
223 for instr in &arm_instrs {
224 if let ArmOp::Bl { label } = &instr.op {
231 relocations.push(CodeRelocation {
232 offset: code.len() as u32,
233 symbol: label.clone(),
234 });
235 }
236
237 let encoded = encoder
238 .encode(&instr.op)
239 .map_err(|e| format!("ARM encoding failed: {}", e))?;
240 code.extend_from_slice(&encoded);
241 }
242
243 Ok((code, relocations))
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn test_arm_backend_name() {
252 let backend = ArmBackend::new();
253 assert_eq!(backend.name(), "arm");
254 assert!(backend.is_available());
255 }
256
257 #[test]
258 fn test_arm_backend_capabilities() {
259 let backend = ArmBackend::new();
260 let caps = backend.capabilities();
261 assert!(!caps.produces_elf);
262 assert!(caps.supports_rule_verification);
263 assert!(!caps.is_external);
264 }
265
266 #[test]
267 fn test_compile_add_function() {
268 let backend = ArmBackend::new();
269 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
270 let config = CompileConfig::default();
271
272 let result = backend.compile_function("add", &ops, &config);
273 assert!(result.is_ok());
274
275 let func = result.unwrap();
276 assert_eq!(func.name, "add");
277 assert!(!func.code.is_empty());
278 assert_eq!(func.wasm_ops, ops);
279 }
280
281 #[test]
282 fn test_count_params() {
283 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
284 assert_eq!(count_params(&ops), 2);
285
286 let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
287 assert_eq!(count_params(&no_params), 0);
288 }
289
290 #[test]
291 fn test_arm_backend_register() {
292 let mut registry = synth_core::BackendRegistry::new();
293 registry.register(Box::new(ArmBackend::new()));
294 assert!(registry.get("arm").is_some());
295 assert_eq!(registry.available().len(), 1);
296 }
297
298 #[test]
299 fn test_compile_import_call_produces_relocations() {
300 let backend = ArmBackend::new();
301 let ops = vec![WasmOp::Call(0)];
304 let config = CompileConfig {
305 num_imports: 1,
306 no_optimize: true, ..CompileConfig::default()
308 };
309
310 let result = backend.compile_function("caller", &ops, &config);
311 assert!(result.is_ok());
312
313 let func = result.unwrap();
314 assert!(!func.code.is_empty());
315 assert_eq!(func.relocations.len(), 1);
316 assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
317 assert!(func.relocations[0].offset > 0);
319 }
320
321 #[test]
322 fn test_compile_no_imports_no_relocations() {
323 let backend = ArmBackend::new();
324 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
325 let config = CompileConfig::default();
326
327 let func = backend.compile_function("add", &ops, &config).unwrap();
328 assert!(func.relocations.is_empty());
329 }
330
331 #[test]
338 fn test_compile_internal_call_produces_relocation_167() {
339 let backend = ArmBackend::new();
340 let ops = vec![WasmOp::Call(2)];
342 let config = CompileConfig {
343 num_imports: 1,
344 no_optimize: true,
345 ..CompileConfig::default()
346 };
347
348 let func = backend
349 .compile_function("caller", &ops, &config)
350 .expect("internal call compiles");
351
352 assert_eq!(
353 func.relocations.len(),
354 1,
355 "an internal call must emit exactly one relocation (#167)"
356 );
357 assert_eq!(
358 func.relocations[0].symbol, "func_2",
359 "internal call must relocate against the callee's func_{{index}} symbol (#167)"
360 );
361 }
362
363 #[test]
366 fn arm_safety_bounds_mpu_emits_same_code_as_none() {
367 let backend = ArmBackend::new();
371 let ops = vec![
372 WasmOp::LocalGet(0),
373 WasmOp::I32Load {
374 offset: 0,
375 align: 2,
376 },
377 ];
378 let cfg_none = CompileConfig {
379 no_optimize: true,
380 ..Default::default()
381 };
382 let cfg_mpu = CompileConfig {
383 no_optimize: true,
384 safety_bounds: SafetyBounds::Mpu,
385 ..Default::default()
386 };
387 let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
388 let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
389 assert_eq!(
390 n.code, m.code,
391 "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
392 );
393 }
394
395 #[test]
396 fn arm_legacy_bounds_check_still_emits_software_check() {
397 let backend = ArmBackend::new();
400 let ops = vec![
401 WasmOp::LocalGet(0),
402 WasmOp::I32Load {
403 offset: 0,
404 align: 2,
405 },
406 ];
407 let cfg_legacy = CompileConfig {
408 no_optimize: true,
409 bounds_check: true,
410 ..Default::default()
411 };
412 let cfg_software = CompileConfig {
413 no_optimize: true,
414 safety_bounds: SafetyBounds::Software,
415 ..Default::default()
416 };
417 let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
418 let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
419 assert_eq!(
420 l.code, s.code,
421 "--bounds-check should produce the same bytes as --safety-bounds=software"
422 );
423 }
424
425 #[test]
431 fn test_f32_rejected_on_cortex_m3_no_fpu() {
432 let backend = ArmBackend::new();
433 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
434 let config = CompileConfig {
435 target: TargetSpec::cortex_m3(),
436 no_optimize: true,
437 ..CompileConfig::default()
438 };
439
440 let result = backend.compile_function("fadd", &ops, &config);
441 assert!(
442 result.is_err(),
443 "f32 operations should fail on Cortex-M3 (no FPU)"
444 );
445 }
446
447 #[test]
448 fn test_f32_accepted_on_cortex_m4f() {
449 let backend = ArmBackend::new();
450 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
451 let config = CompileConfig {
452 target: TargetSpec::cortex_m4f(),
453 no_optimize: true,
454 ..CompileConfig::default()
455 };
456
457 let result = backend.compile_function("fadd", &ops, &config);
458 assert!(
459 result.is_ok(),
460 "f32 operations should succeed on Cortex-M4F, got: {:?}",
461 result.unwrap_err()
462 );
463 }
464
465 #[test]
466 fn test_i32_works_on_all_targets() {
467 let backend = ArmBackend::new();
468 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
469
470 let config_m3 = CompileConfig {
472 target: TargetSpec::cortex_m3(),
473 no_optimize: true,
474 ..CompileConfig::default()
475 };
476 assert!(
477 backend.compile_function("add", &ops, &config_m3).is_ok(),
478 "i32 ops should work on Cortex-M3"
479 );
480
481 let config_m4f = CompileConfig {
483 target: TargetSpec::cortex_m4f(),
484 no_optimize: true,
485 ..CompileConfig::default()
486 };
487 assert!(
488 backend.compile_function("add", &ops, &config_m4f).is_ok(),
489 "i32 ops should work on Cortex-M4F"
490 );
491
492 let config_m7dp = CompileConfig {
494 target: TargetSpec::cortex_m7dp(),
495 no_optimize: true,
496 ..CompileConfig::default()
497 };
498 assert!(
499 backend.compile_function("add", &ops, &config_m7dp).is_ok(),
500 "i32 ops should work on Cortex-M7DP"
501 );
502 }
503
504 #[test]
505 fn test_f32_rejected_on_cortex_m4_no_fpu() {
506 let backend = ArmBackend::new();
508 let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
509 let config = CompileConfig {
510 target: TargetSpec::cortex_m4(),
511 no_optimize: true,
512 ..CompileConfig::default()
513 };
514
515 let result = backend.compile_function("fmul", &ops, &config);
516 assert!(
517 result.is_err(),
518 "f32 operations should fail on Cortex-M4 (no FPU)"
519 );
520 }
521
522 #[test]
544 fn test_issue120_f32_div_compiles_via_optimized_default() {
545 let backend = ArmBackend::new();
546 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
547 let config = CompileConfig {
548 target: TargetSpec::cortex_m4f(),
549 ..CompileConfig::default()
552 };
553
554 let result = backend.compile_function("fdiv", &ops, &config);
555 assert!(
556 result.is_ok(),
557 "f32.div must compile on Cortex-M4F via the optimized->direct \
558 fallback (issue #120), got: {:?}",
559 result.as_ref().err()
560 );
561 assert!(
562 !result.unwrap().code.is_empty(),
563 "f32.div must produce non-empty machine code"
564 );
565 }
566
567 #[test]
570 fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
571 let backend = ArmBackend::new();
572 let config = CompileConfig {
573 target: TargetSpec::cortex_m4f(),
574 ..CompileConfig::default()
575 };
576
577 let cases: Vec<(&str, Vec<WasmOp>)> = vec![
578 (
579 "fadd",
580 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
581 ),
582 (
583 "fmul",
584 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
585 ),
586 (
587 "fsub",
588 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
589 ),
590 ];
591
592 for (name, ops) in cases {
593 let result = backend.compile_function(name, &ops, &config);
594 assert!(
595 result.is_ok(),
596 "{name} must compile via the optimized->direct fallback \
597 (issue #120), got: {:?}",
598 result.as_ref().err()
599 );
600 assert!(
601 !result.unwrap().code.is_empty(),
602 "{name} must produce non-empty machine code"
603 );
604 }
605 }
606
607 #[test]
610 fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
611 let backend = ArmBackend::new();
612 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
613 let config = CompileConfig {
614 target: TargetSpec::cortex_m3(),
615 ..CompileConfig::default()
616 };
617
618 let result = backend.compile_function("fdiv", &ops, &config);
619 assert!(
620 result.is_err(),
621 "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
622 );
623 }
624
625 #[test]
630 fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
631 let backend = ArmBackend::new();
632 let config = CompileConfig {
633 target: TargetSpec::cortex_m4f(),
634 ..CompileConfig::default()
635 };
636
637 let ops_hi32 = vec![
639 WasmOp::LocalGet(0), WasmOp::I64Const(32),
641 WasmOp::I64ShrU,
642 WasmOp::I32WrapI64,
643 ];
644 let func_hi32 = backend
645 .compile_function("hi32_extract", &ops_hi32, &config)
646 .unwrap();
647
648 let ops_generic = vec![
652 WasmOp::LocalGet(0),
653 WasmOp::I64Const(7),
654 WasmOp::I64ShrU,
655 WasmOp::I32WrapI64,
656 ];
657 let func_generic = backend
658 .compile_function("generic_shr", &ops_generic, &config)
659 .unwrap();
660
661 let bytes_hi32 = func_hi32.code.len();
662 let bytes_generic = func_generic.code.len();
663 println!(
664 "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
665 bytes_hi32,
666 bytes_generic,
667 bytes_generic.saturating_sub(bytes_hi32)
668 );
669 let hex: String = func_hi32
670 .code
671 .iter()
672 .map(|b| format!("{:02x}", b))
673 .collect::<Vec<_>>()
674 .join(" ");
675 println!("[issue #94] hi32 bytes: {}", hex);
676 assert!(
679 bytes_hi32 + 30 <= bytes_generic,
680 "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
681 expected optimized form to be at least 30 bytes smaller",
682 bytes_hi32,
683 bytes_generic,
684 );
685 }
686}