Skip to main content

synth_core/
backend.rs

1//! Backend trait and registry for multi-backend compilation
2//!
3//! Every compiler backend (ARM, aWsm, wasker, w2c2) implements the `Backend`
4//! trait, allowing the CLI and verification framework to treat them uniformly.
5
6use crate::target::TargetSpec;
7use crate::wasm_decoder::DecodedModule;
8use crate::wasm_op::WasmOp;
9use std::collections::HashMap;
10use thiserror::Error;
11
12/// Errors from backend compilation
13#[derive(Debug, Error)]
14pub enum BackendError {
15    #[error("compilation failed: {0}")]
16    CompilationFailed(String),
17
18    #[error("backend not available: {0}")]
19    NotAvailable(String),
20
21    #[error("unsupported configuration: {0}")]
22    UnsupportedConfig(String),
23
24    #[error("external tool error: {0}")]
25    ExternalToolError(String),
26}
27
28/// Memory-bounds safety strategy. Phase 1 of `docs/binary-safety-design.md` §3.1.
29///
30/// - `Mpu`/PMP: rely on hardware (ARM MPU or RV32 PMP) — no inline check.
31/// - `Software`: emit a `CMP/BHS Trap_Handler` (ARM) or `bgeu addr, mem_size, ebreak` (RV32)
32///   before every load/store.
33/// - `Mask`: emit `AND addr, addr, #(mem_size - 1)` — only valid when memory size
34///   is a power of two. Wraps on OOB rather than trapping (fuzz-profile semantics).
35/// - `None`: no bounds enforcement.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum SafetyBounds {
38    /// No bounds check (caller assumes the WASM module is trusted)
39    #[default]
40    None,
41    /// ARM MPU / RV32 PMP — hardware enforcement, no inline guard
42    Mpu,
43    /// Software CMP/BHS (ARM) or BGEU+EBREAK (RV32) per access
44    Software,
45    /// AND-mask, requires power-of-two memory size
46    Mask,
47}
48
49impl SafetyBounds {
50    /// Parse the `--safety-bounds` argument value.
51    pub fn parse(s: &str) -> std::result::Result<Self, String> {
52        match s {
53            "none" => Ok(SafetyBounds::None),
54            "mpu" | "pmp" => Ok(SafetyBounds::Mpu),
55            "software" | "soft" => Ok(SafetyBounds::Software),
56            "mask" | "masking" => Ok(SafetyBounds::Mask),
57            other => Err(format!(
58                "unknown --safety-bounds value '{}'; expected one of: none, mpu, software, mask",
59                other
60            )),
61        }
62    }
63
64    /// String form used in the safety manifest.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            SafetyBounds::None => "none",
68            SafetyBounds::Mpu => "mpu",
69            SafetyBounds::Software => "software",
70            SafetyBounds::Mask => "mask",
71        }
72    }
73}
74
75/// Configuration for a compilation run
76#[derive(Debug, Clone)]
77pub struct CompileConfig {
78    /// Optimization level (0 = none, 1 = fast, 2 = default, 3 = aggressive)
79    pub opt_level: u8,
80    /// Target specification
81    pub target: TargetSpec,
82    /// Legacy: enable software bounds checking for memory operations.
83    /// Deprecated in favor of `safety_bounds`. When set, equivalent to
84    /// `SafetyBounds::Software`. Kept for backwards compatibility with
85    /// callers that haven't migrated yet.
86    pub bounds_check: bool,
87    /// Phase-1 unified safety-bounds knob. If `bounds_check` is `true` and
88    /// this is `None`, the legacy field wins (back-compat). If both are set,
89    /// `safety_bounds` wins.
90    pub safety_bounds: SafetyBounds,
91    /// Hardware profile name (e.g. "nrf52840", "stm32f407")
92    pub hardware: String,
93    /// Skip optimization passes (direct instruction selection)
94    pub no_optimize: bool,
95    /// Use Loom-compatible optimization preset
96    pub loom_compat: bool,
97    /// Number of imported functions (calls to indices below this use Meld dispatch)
98    pub num_imports: u32,
99    /// AAPCS integer-argument count per function, indexed by full WASM function
100    /// index (imports first, then locals). Lets `Call` marshal the right number
101    /// of operand-stack values into R0–R3 (issue #195). Empty = pass no args
102    /// (pre-#195 behaviour).
103    pub func_arg_counts: Vec<u32>,
104    /// AAPCS integer-argument count per function type, indexed by type index.
105    /// Used by `call_indirect` (issue #195).
106    pub type_arg_counts: Vec<u32>,
107    /// Produce relocatable (ET_REL) host-link output. When set, the backend
108    /// uses the direct instruction selector (`select_with_stack`) rather than
109    /// the optimized path: the optimizer materializes an *absolute* linear-
110    /// memory base (0x20000100) and does not preserve caller-saved registers
111    /// across calls, both wrong for a host-linked object where the linmem base
112    /// is supplied via `fp` at runtime and callees follow AAPCS. Imports are
113    /// also emitted as direct `func_N` BLs (resolved to the wasm field name)
114    /// instead of `__meld_dispatch_import`. (#197 — follow-up to #188/#171.)
115    pub relocatable: bool,
116
117    /// #237: emit wasm function-static data as a base-independent `.data`
118    /// section (`__synth_wasm_data`) addressed via MOVW/MOVT symbol relocations,
119    /// so a host-pointer drop-in (linmem base = 0 for native `*ptr` derefs)
120    /// doesn't mis-resolve the statics. Off by default — only the leaves'
121    /// base-relative `[R11+const]` path is used unless explicitly requested.
122    pub native_pointer_abi: bool,
123
124    /// #237: wasm linear-memory minimum size in bytes — the full static-data
125    /// extent (initialized `(data)` segments plus the zero-init/BSS region).
126    /// Under `native_pointer_abi`, a const memory address below this is a wasm
127    /// static → symbol-relative; any address beyond it is a runtime host pointer
128    /// → `[R11=0 + addr]`.
129    pub linear_memory_bytes: u32,
130
131    /// #237: the wasm stack-pointer global as `(index, init_value)`, if the
132    /// module has one. Under `native_pointer_abi` the backend register-promotes
133    /// it: `global.get` materializes `__synth_wasm_data + init` (the real stack
134    /// top) and the init value doubles as the static-data base that separates
135    /// pointer consts (`>= init`) from frame-size scalars (`< init`).
136    pub stack_pointer_global: Option<(u32, i32)>,
137    /// #311: per-function (full index) / per-type "returns i64" — the call
138    /// lowering must tag i64 results as a register pair or the hi half is
139    /// invisible to liveness.
140    pub func_ret_i64: Vec<bool>,
141    pub type_ret_i64: Vec<bool>,
142    /// #359: declared parameter widths per *function* (full index, imports
143    /// first): `func_params_i64[f][k]` is true when param `k` of function `f` is
144    /// i64/f64. The AAPCS stack-argument path needs the *declared* widths
145    /// (op-stream inference can't see an unused i64 param that still shifts the
146    /// incoming-stack layout). The source of truth — a per-function driver loop
147    /// (`compile_module` / the CLI loop) indexes it by `func.index` and copies
148    /// the slice into [`current_func_params_i64`] before each `compile_function`.
149    /// Empty → every param assumed i32 (the legacy path; keeps every function
150    /// with <=4 params, or all-i32 params, byte-identical).
151    pub func_params_i64: Vec<Vec<bool>>,
152    /// #359: declared parameter widths of the function CURRENTLY being compiled
153    /// — `current_func_params_i64[k]` is true when param `k` is i64/f64. Set per
154    /// function (a cheap clone of the config) from [`func_params_i64`] by the
155    /// driver loop, because `compile_function` is shared across backends and
156    /// carries no function index. Empty → assume i32.
157    pub current_func_params_i64: Vec<bool>,
158    /// #509: blocktype-arity side-table of the function CURRENTLY being compiled
159    /// — `(param_count, result_count)` of the k-th `Block`/`Loop`/`If` in its op
160    /// stream (ordinal-keyed; see [`FunctionOps::block_arity`]). Set per function
161    /// by the driver loop (like [`current_func_params_i64`]). The direct selector
162    /// uses it to land a value carried by `br`/`br_if`/`br_table` in the target
163    /// block's designated result register instead of dropping it. Empty → every
164    /// block treated as void (the legacy lowering; hand-built op streams).
165    ///
166    /// [`FunctionOps::block_arity`]: crate::wasm_decoder::FunctionOps::block_arity
167    pub current_func_block_arity: Vec<(u8, u8)>,
168
169    /// #543 Phase 1 — integrator-marked volatile linear-memory segments (the DMA
170    /// transfer window). Each range `[base, base+len)` names a region of the fused
171    /// linear memory that an EXTERNAL agent (the DMA engine, modelled by gale as a
172    /// Component-Model `own<buffer>` handoff — gale decision `DD-DMA-REGION-001`,
173    /// gale#124) rewrites out-of-band. Loads and stores whose address falls inside
174    /// a marked range must eventually be treated as VOLATILE: not cached, hoisted,
175    /// or reordered across the transfer boundary.
176    ///
177    /// PHASE-2 CONTRACT (implemented — issue #543): the optimizer's
178    /// address-caching passes HONOR these ranges. Consumption points:
179    ///  - the #468 base-CSE / const-address-fold
180    ///    (`optimizer_bridge::plan_base_cse`, DEFAULT-ON, opt-out
181    ///    `SYNTH_BASE_CSE=0`): a const-address access whose 4-byte window
182    ///    intersects a marked range is EXCLUDED from the fold set — it keeps
183    ///    its verbatim per-access materialize-and-access codegen, while
184    ///    accesses outside the range still fold;
185    ///  - const-CSE (`liveness::apply_const_cse` wired in `arm_backend.rs`,
186    ///    DEFAULT-ON, opt-out `SYNTH_CONST_CSE=0`; the former bridge-level
187    ///    inline cache is retired, #242): declines WHOLESALE while any range is
188    ///    marked — a cached constant cannot be classified address-vs-data at
189    ///    that level, so the conservative stance for statically-unknown
190    ///    addressing is to re-materialize every constant at each occurrence.
191    ///
192    /// Passes that only touch SP-relative frame slots (stack-reload forwarding,
193    /// frame-slot DCE, spill re-choice) are unaffected by design: these ranges
194    /// are LINEAR-MEMORY addresses, and frame slots are never linmem. Nothing on
195    /// the pipeline deletes, forwards, or reorders a linear-memory access (IR CSE
196    /// deliberately never CSEs `MemLoad`s; DCE removes only unreachable blocks),
197    /// so every marked access is issued verbatim, in program order.
198    ///
199    /// Empty (the default): zero behavior change by construction — every gate
200    /// reduces to the pre-#543 path, so the emitted `.text` is byte-identical
201    /// with or without this code (the frozen-codegen gate holds). See rivet
202    /// `VCR-DMA-001`.
203    pub volatile_segments: Vec<VolatileRange>,
204}
205
206/// #543 — an integrator-marked volatile linear-memory segment (the DMA transfer
207/// window): the half-open byte range `[base, base + len)` of the fused linear
208/// memory that an external agent rewrites out-of-band. Parsed from the CLI
209/// `--volatile-segment <base>:<len>` flag. See [`CompileConfig::volatile_segments`]
210/// for the Phase-1/Phase-2 split.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct VolatileRange {
213    /// Start address of the volatile region, in linear-memory bytes.
214    pub base: u32,
215    /// Length of the volatile region, in bytes. The region is `[base, base+len)`.
216    pub len: u32,
217}
218
219impl CompileConfig {
220    /// Resolve the effective safety-bounds setting, honouring the legacy
221    /// `bounds_check` field as a fallback. Used by backends to pick the
222    /// inline-check shape.
223    pub fn effective_safety_bounds(&self) -> SafetyBounds {
224        match (self.safety_bounds, self.bounds_check) {
225            (SafetyBounds::None, true) => SafetyBounds::Software,
226            (s, _) => s,
227        }
228    }
229}
230
231impl Default for CompileConfig {
232    fn default() -> Self {
233        Self {
234            opt_level: 2,
235            target: TargetSpec::cortex_m4(),
236            bounds_check: false,
237            safety_bounds: SafetyBounds::None,
238            hardware: String::new(),
239            no_optimize: false,
240            loom_compat: false,
241            num_imports: 0,
242            func_arg_counts: Vec::new(),
243            type_arg_counts: Vec::new(),
244            relocatable: false,
245            native_pointer_abi: false,
246            linear_memory_bytes: 0,
247            stack_pointer_global: None,
248            func_ret_i64: Vec::new(),
249            type_ret_i64: Vec::new(),
250            func_params_i64: Vec::new(),
251            current_func_params_i64: Vec::new(),
252            // #509: empty ⇒ legacy void-block lowering (unit tests / hand-built
253            // op streams); the driver loops fill it per function.
254            current_func_block_arity: Vec::new(),
255            // #543 Phase 1: no volatile segments unless the CLI flag names them.
256            // Empty ⇒ inert ⇒ emitted bytes unchanged.
257            volatile_segments: Vec::new(),
258        }
259    }
260}
261
262/// A relocation entry produced during compilation
263///
264/// Records that a BL instruction at `offset` bytes into the function's code
265/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
266/// resolves these when combining the Synth object with the Kiln bridge.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum RelocKind {
269    /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
270    ThmCall,
271    /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
272    MovwAbs,
273    /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
274    MovtAbs,
275    /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
276    /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
277    /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
278    /// the data word at link time (`S + A`, the addend living in the word, REL
279    /// semantics), which survives placement into a large multi-object image —
280    /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
281    Abs32,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct CodeRelocation {
286    /// Byte offset within the function's machine code where the reloc applies
287    pub offset: u32,
288    /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
289    pub symbol: String,
290    /// Which ARM relocation type to emit for this site.
291    pub kind: RelocKind,
292}
293
294/// VCR-DBG-001: a per-instruction source map — `(machine_offset_within_code,
295/// wasm_op_index)` pairs, one per emitted machine instruction. A `None` op-index
296/// marks an instruction with no originating wasm op (prologue/epilogue, literal
297/// pool). Consumed by the DWARF `.debug_line` emitter; empty when no source map
298/// was produced.
299pub type LineMap = Vec<(u32, Option<usize>)>;
300
301/// A single compiled function
302#[derive(Debug, Clone)]
303pub struct CompiledFunction {
304    /// Function name (from WASM export or generated)
305    pub name: String,
306    /// Raw machine code bytes
307    pub code: Vec<u8>,
308    /// Original WASM ops (retained for verification)
309    pub wasm_ops: Vec<WasmOp>,
310    /// Relocations for external symbol references (BL to bridge functions)
311    pub relocations: Vec<CodeRelocation>,
312    /// VCR-DBG-001: per-instruction source map for DWARF `.debug_line` emission —
313    /// `(machine_offset_within_code, wasm_op_index)` captured at encode time, one
314    /// entry per emitted machine instruction. A `None` op-index marks an
315    /// instruction with no originating wasm op (prologue/epilogue, literal-pool
316    /// word). This is purely additive metadata: it is never serialized unless
317    /// `.debug_line` emission is requested, so the emitted `.text` is
318    /// byte-identical with or without it. Empty for backends/paths that do not
319    /// yet produce a source map (RISC-V, the optimized ARM path).
320    pub line_map: LineMap,
321}
322
323/// Result of compiling a full module
324#[derive(Debug)]
325pub struct CompilationResult {
326    /// Compiled functions
327    pub functions: Vec<CompiledFunction>,
328    /// Complete ELF binary (if backend produces one directly)
329    pub elf: Option<Vec<u8>>,
330    /// Name of the backend that produced this result
331    pub backend_name: String,
332}
333
334/// What a backend can and cannot do
335#[derive(Debug, Clone)]
336pub struct BackendCapabilities {
337    /// Backend produces complete ELF files (external backends like aWsm)
338    pub produces_elf: bool,
339    /// Backend supports per-rule verification (only our custom ARM backend)
340    pub supports_rule_verification: bool,
341    /// Backend supports binary-level verification (all backends via disassembly)
342    pub supports_binary_verification: bool,
343    /// Backend is an external tool (not a library)
344    pub is_external: bool,
345}
346
347/// Trait that every compilation backend implements
348pub trait Backend: Send + Sync {
349    /// Human-readable backend name
350    fn name(&self) -> &str;
351
352    /// What this backend can do
353    fn capabilities(&self) -> BackendCapabilities;
354
355    /// Which targets this backend supports
356    fn supported_targets(&self) -> Vec<TargetSpec>;
357
358    /// Compile an entire decoded WASM module
359    fn compile_module(
360        &self,
361        module: &DecodedModule,
362        config: &CompileConfig,
363    ) -> std::result::Result<CompilationResult, BackendError>;
364
365    /// Compile a single function from WASM ops to machine code
366    fn compile_function(
367        &self,
368        name: &str,
369        ops: &[WasmOp],
370        config: &CompileConfig,
371    ) -> std::result::Result<CompiledFunction, BackendError>;
372
373    /// Check if this backend is available (external tools installed, etc.)
374    fn is_available(&self) -> bool;
375}
376
377/// Registry of available backends
378pub struct BackendRegistry {
379    backends: HashMap<String, Box<dyn Backend>>,
380}
381
382impl BackendRegistry {
383    pub fn new() -> Self {
384        Self {
385            backends: HashMap::new(),
386        }
387    }
388
389    /// Register a backend under its name
390    pub fn register(&mut self, backend: Box<dyn Backend>) {
391        let name = backend.name().to_string();
392        self.backends.insert(name, backend);
393    }
394
395    /// Get a backend by name
396    pub fn get(&self, name: &str) -> Option<&dyn Backend> {
397        self.backends.get(name).map(|b| b.as_ref())
398    }
399
400    /// List all registered backends
401    pub fn list(&self) -> Vec<&dyn Backend> {
402        self.backends.values().map(|b| b.as_ref()).collect()
403    }
404
405    /// List backends that are actually available (installed and working)
406    pub fn available(&self) -> Vec<&dyn Backend> {
407        self.backends
408            .values()
409            .filter(|b| b.is_available())
410            .map(|b| b.as_ref())
411            .collect()
412    }
413}
414
415impl Default for BackendRegistry {
416    fn default() -> Self {
417        Self::new()
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn test_registry_empty() {
427        let reg = BackendRegistry::new();
428        assert!(reg.list().is_empty());
429        assert!(reg.available().is_empty());
430        assert!(reg.get("arm").is_none());
431    }
432
433    #[test]
434    fn test_compile_config_default() {
435        let config = CompileConfig::default();
436        assert_eq!(config.opt_level, 2);
437        assert!(!config.bounds_check);
438        assert_eq!(config.safety_bounds, SafetyBounds::None);
439        assert!(!config.no_optimize);
440    }
441
442    #[test]
443    fn safety_bounds_parse_round_trip() {
444        for s in ["none", "mpu", "software", "mask"] {
445            let sb = SafetyBounds::parse(s).unwrap();
446            assert_eq!(sb.as_str(), s);
447        }
448        assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
449        assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
450        assert!(SafetyBounds::parse("nonsense").is_err());
451    }
452
453    #[test]
454    fn effective_safety_bounds_legacy_promotes_to_software() {
455        let cfg = CompileConfig {
456            bounds_check: true,
457            ..Default::default()
458        };
459        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
460    }
461
462    #[test]
463    fn effective_safety_bounds_new_field_wins() {
464        let cfg = CompileConfig {
465            bounds_check: true,
466            safety_bounds: SafetyBounds::Mpu,
467            ..Default::default()
468        };
469        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
470    }
471}