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 crate::wsc_facts::WscFact;
10use std::collections::HashMap;
11use thiserror::Error;
12
13/// Errors from backend compilation
14#[derive(Debug, Error)]
15pub enum BackendError {
16 #[error("compilation failed: {0}")]
17 CompilationFailed(String),
18
19 #[error("backend not available: {0}")]
20 NotAvailable(String),
21
22 #[error("unsupported configuration: {0}")]
23 UnsupportedConfig(String),
24
25 #[error("external tool error: {0}")]
26 ExternalToolError(String),
27}
28
29/// Memory-bounds safety strategy. Phase 1 of `docs/binary-safety-design.md` §3.1.
30///
31/// - `Mpu`/PMP: rely on hardware (ARM MPU or RV32 PMP) — no inline check.
32/// - `Software`: emit a `CMP/BHS Trap_Handler` (ARM) or `bgeu addr, mem_size, ebreak` (RV32)
33/// before every load/store.
34/// - `Mask`: emit `AND addr, addr, #(mem_size - 1)` — only valid when memory size
35/// is a power of two. Wraps on OOB rather than trapping (fuzz-profile semantics).
36/// - `None`: no bounds enforcement.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum SafetyBounds {
39 /// No bounds check (caller assumes the WASM module is trusted)
40 #[default]
41 None,
42 /// ARM MPU / RV32 PMP — hardware enforcement, no inline guard
43 Mpu,
44 /// Software CMP/BHS (ARM) or BGEU+EBREAK (RV32) per access
45 Software,
46 /// AND-mask, requires power-of-two memory size
47 Mask,
48}
49
50impl SafetyBounds {
51 /// Parse the `--safety-bounds` argument value.
52 pub fn parse(s: &str) -> std::result::Result<Self, String> {
53 match s {
54 "none" => Ok(SafetyBounds::None),
55 "mpu" => Ok(SafetyBounds::Mpu),
56 // RQ-69-PMPLIB (#1317): `pmp` was a SILENT ALIAS for `mpu` here.
57 // v0.68 (#1284) made the CLI refuse it on every backend, but this
58 // is `synth-core`, a PUBLISHED crate — a library caller still got
59 // the alias the CLI rejects, and a unit test PINNED that. synth
60 // emits no RV32 PMP programming, so accepting the spelling and
61 // meaning something else is the accepted-and-dropped shape #1284
62 // closed at the outer layer and left open here.
63 //
64 // The WORDING is #1284's, verbatim. Those tests pin what the user
65 // sees; that contract did not change — only the LAYER enforcing it
66 // did. Keeping the phrasing means #1284's tests pass UNEDITED,
67 // which is the evidence that this moved the check without
68 // weakening it.
69 "pmp" => Err(
70 "--safety-bounds pmp is refused on every backend: synth emits no RV32 PMP \
71 programming, and `pmp` is never a silent alias for `mpu`. The \
72 only accepted MPU mode is --safety-bounds mpu --embedder-mpu on an \
73 ARM relocatable object, where YOUR startup programs the MPU \
74 from the region table (#1145, #1284, #1317)"
75 .to_string(),
76 ),
77 "software" | "soft" => Ok(SafetyBounds::Software),
78 "mask" | "masking" => Ok(SafetyBounds::Mask),
79 other => Err(format!(
80 "unknown --safety-bounds value '{}'; expected one of: none, mpu, software, mask",
81 other
82 )),
83 }
84 }
85
86 /// String form used in the safety manifest.
87 pub fn as_str(self) -> &'static str {
88 match self {
89 SafetyBounds::None => "none",
90 SafetyBounds::Mpu => "mpu",
91 SafetyBounds::Software => "software",
92 SafetyBounds::Mask => "mask",
93 }
94 }
95}
96
97/// The absolute SRAM address the OPTIMIZED (non-relocatable) ARM path
98/// materializes as its linear-memory base (`MOVW/MOVT R12, #base` before each
99/// const-address access, and the #468 base-CSE R11 hoist). Historical value:
100/// 256 bytes above the SRAM start — the differential-harness contract for
101/// optimized-path fixtures maps linmem here. `CompileConfig::linmem_base`
102/// defaults to this; `--stack-layout=low` (#687) shifts it up by the reserved
103/// stack size so the moved layout reaches user code, not just the startup.
104pub const OPTIMIZED_LINMEM_BASE: u32 = 0x2000_0100;
105
106/// Configuration for a compilation run
107#[derive(Debug, Clone)]
108pub struct CompileConfig {
109 /// Optimization level (0 = none, 1 = fast, 2 = default, 3 = aggressive)
110 pub opt_level: u8,
111 /// Target specification
112 pub target: TargetSpec,
113 /// Legacy: enable software bounds checking for memory operations.
114 /// Deprecated in favor of `safety_bounds`. When set, equivalent to
115 /// `SafetyBounds::Software`. Kept for backwards compatibility with
116 /// callers that haven't migrated yet.
117 pub bounds_check: bool,
118 /// Phase-1 unified safety-bounds knob. If `bounds_check` is `true` and
119 /// this is `None`, the legacy field wins (back-compat). If both are set,
120 /// `safety_bounds` wins.
121 pub safety_bounds: SafetyBounds,
122 /// Hardware profile name (e.g. "nrf52840", "stm32f407")
123 pub hardware: String,
124 /// Skip optimization passes (direct instruction selection)
125 pub no_optimize: bool,
126 /// Use Loom-compatible optimization preset
127 pub loom_compat: bool,
128 /// Number of imported functions (calls to indices below this use Meld dispatch)
129 pub num_imports: u32,
130 /// AAPCS integer-argument count per function, indexed by full WASM function
131 /// index (imports first, then locals). Lets `Call` marshal the right number
132 /// of operand-stack values into R0–R3 (issue #195). Empty = pass no args
133 /// (pre-#195 behaviour).
134 pub func_arg_counts: Vec<u32>,
135 /// #851: result (return-value) count per function, indexed by full WASM
136 /// function index (imports first). `0` = void, `1` = one value. The AArch64
137 /// direct-`call` lowering needs the 0-vs-1 distinction to decide whether to
138 /// push the `x0` result — `func_ret_i64/f32/f64` carry the result TYPE but
139 /// conflate void and i32. Empty on backends/paths that do not lower calls
140 /// this way (byte-invisible there).
141 pub func_result_counts: Vec<u32>,
142 /// AAPCS integer-argument count per function type, indexed by type index.
143 /// Used by `call_indirect` (issue #195).
144 pub type_arg_counts: Vec<u32>,
145 /// Produce relocatable (ET_REL) host-link output. When set, the backend
146 /// uses the direct instruction selector (`select_with_stack`) rather than
147 /// the optimized path: the optimizer materializes an *absolute* linear-
148 /// memory base (0x20000100) and does not preserve caller-saved registers
149 /// across calls, both wrong for a host-linked object where the linmem base
150 /// is supplied via `fp` at runtime and callees follow AAPCS. Imports are
151 /// also emitted as direct `func_N` BLs (resolved to the wasm field name)
152 /// instead of `__meld_dispatch_import`. (#197 — follow-up to #188/#171.)
153 pub relocatable: bool,
154
155 /// #275: the SELF-CONTAINED Thumb-2 `--cortex-m` image path lowers
156 /// `call_indirect` through a flash-resident funcref table addressed
157 /// PC-RELATIVE (an `LdrSym` literal-pool pointer to
158 /// [`FUNC_TABLE_SYMBOL`]) — NEVER through R11, which is the linear-memory
159 /// base (the v0.42 #717 collision). Set by the CLI ONLY when the image
160 /// builder that emits and patches that table
161 /// (`build_multi_func_cortex_m_elf`) will run: Cortex-M family, not
162 /// `--relocatable`, no imported functions. Every other self-contained
163 /// configuration keeps the loud #275 decline. Default `false`.
164 pub self_contained_funcref_table: bool,
165
166 /// #687 (`--stack-layout=low`): the absolute linear-memory base the
167 /// OPTIMIZED ARM path materializes into user code. Defaults to
168 /// [`OPTIMIZED_LINMEM_BASE`] (`0x2000_0100`, byte-identical to every
169 /// pre-#687 compile). Under the low stack layout the CLI shifts it up by
170 /// the reserved stack size so const-address loads/stores land in the moved
171 /// linear memory instead of the stack region. Only the optimized
172 /// (non-relocatable) path consumes it — the direct selector is R11/fp
173 /// - relative and follows the startup's R11 init instead.
174 pub linmem_base: u32,
175
176 /// #237: emit wasm function-static data as a base-independent `.data`
177 /// section (`__synth_wasm_data`) addressed via MOVW/MOVT symbol relocations,
178 /// so a host-pointer drop-in (linmem base = 0 for native `*ptr` derefs)
179 /// doesn't mis-resolve the statics. Off by default — only the leaves'
180 /// base-relative `[R11+const]` path is used unless explicitly requested.
181 pub native_pointer_abi: bool,
182
183 /// #237: wasm linear-memory minimum size in bytes — the full static-data
184 /// extent (initialized `(data)` segments plus the zero-init/BSS region).
185 /// Under `native_pointer_abi`, a const memory address below this is a wasm
186 /// static → symbol-relative; any address beyond it is a runtime host pointer
187 /// → `[R11=0 + addr]`.
188 pub linear_memory_bytes: u32,
189
190 /// VCR-MEM-002 phase 1 (#406): initial size in 64 KiB pages of EACH linear
191 /// memory, indexed by memory index. Consulted only by the multi-memory
192 /// lowering arms (loads/stores wrapped in `WasmOp::MultiMemory`,
193 /// `memory.size`/`grow` with a non-zero index) — memory-0 lowering never
194 /// reads it, so single-memory output is byte-identical whether it is set
195 /// or empty. Empty (the default) means "no multi-memory context": any
196 /// multi-memory op then declines loudly.
197 pub memory_pages: Vec<u32>,
198
199 /// #237: the wasm stack-pointer global as `(index, init_value)`, if the
200 /// module has one. Under `native_pointer_abi` the backend register-promotes
201 /// it: `global.get` materializes `__synth_wasm_data + init` (the real stack
202 /// top) and the init value doubles as the static-data base that separates
203 /// pointer consts (`>= init`) from frame-size scalars (`< init`).
204 pub stack_pointer_global: Option<(u32, i32)>,
205 /// #311: per-function (full index) / per-type "returns i64" — the call
206 /// lowering must tag i64 results as a register pair or the hi half is
207 /// invisible to liveness.
208 pub func_ret_i64: Vec<bool>,
209 pub type_ret_i64: Vec<bool>,
210 /// #643: byte width of each defined global's storage slot, indexed by
211 /// global index — 4 for i32/f32, 8 for i64/f64, 16 for v128 (from the
212 /// module's global section). The globals table is laid out by SUMMING
213 /// these widths: an i64 global needs a register-PAIR store/load at
214 /// `[R9, off]`/`[R9, off+4]`, and every later global's offset shifts.
215 /// Empty ⇒ every global assumed 4 bytes (the legacy `idx * 4` layout;
216 /// hand-built op streams and i32-only modules are byte-identical).
217 pub global_widths: Vec<u32>,
218 /// #359: declared parameter widths per *function* (full index, imports
219 /// first): `func_params_i64[f][k]` is true when param `k` of function `f` is
220 /// i64/f64. The AAPCS stack-argument path needs the *declared* widths
221 /// (op-stream inference can't see an unused i64 param that still shifts the
222 /// incoming-stack layout). The source of truth — a per-function driver loop
223 /// (`compile_module` / the CLI loop) indexes it by `func.index` and copies
224 /// the slice into [`current_func_params_i64`] before each `compile_function`.
225 /// Empty → every param assumed i32 (the legacy path; keeps every function
226 /// with <=4 params, or all-i32 params, byte-identical).
227 pub func_params_i64: Vec<Vec<bool>>,
228 /// #359: declared parameter widths of the function CURRENTLY being compiled
229 /// — `current_func_params_i64[k]` is true when param `k` is i64/f64. Set per
230 /// function (a cheap clone of the config) from [`func_params_i64`] by the
231 /// driver loop, because `compile_function` is shared across backends and
232 /// carries no function index. Empty → assume i32.
233 pub current_func_params_i64: Vec<bool>,
234 /// GI-FPU-002 (#619/#369): per-function declared f32-param mask (full index,
235 /// imports first). The driver copies `func_params_f32[f]` into
236 /// [`current_func_params_f32`] before each `compile_function`. Empty ⇒
237 /// all-non-f32 (byte-identical to before).
238 pub func_params_f32: Vec<Vec<bool>>,
239 /// GI-FPU-002: declared f32-param mask of the function CURRENTLY being
240 /// compiled — `current_func_params_f32[k]` is true when param `k` is f32.
241 /// Set per function from [`func_params_f32`], mirroring
242 /// [`current_func_params_i64`]. Empty ⇒ no f32 params.
243 pub current_func_params_f32: Vec<bool>,
244 /// GI-FPU-002 phase 2 (#369): per-function declared f64-param mask (full
245 /// index, imports first) and the CURRENT function's slice. Hard-float
246 /// targets decline f64-param functions loudly — the legacy width
247 /// inference treats an f64 param as an i64 CORE-register pair, which
248 /// reads the wrong registers under AAPCS-VFP (the caller put it in a
249 /// D-register). Empty ⇒ no f64 params (byte-identical legacy path).
250 pub func_params_f64: Vec<Vec<bool>>,
251 /// See [`func_params_f64`](Self::func_params_f64).
252 pub current_func_params_f64: Vec<bool>,
253 /// GI-FPU-002 phase 2 (#719/#369): whether the function CURRENTLY being
254 /// compiled returns f32. Set per function from the decoder's `func_ret_f32`.
255 /// The direct selector's epilogue uses it to loudly decline a result that
256 /// reaches the return in a core register instead of an S-register (a call
257 /// that returned f32 as integer-tagged R0 would otherwise be a silent
258 /// miscompile — the AAPCS-VFP caller reads S0). `false` for hand-built op
259 /// streams / non-f32 returns (byte-identical to before).
260 pub current_func_ret_f32: bool,
261 /// GI-FPU-002 phase 2 (#719/#369): whether the function CURRENTLY being
262 /// compiled returns f64 (D0 under AAPCS-VFP). Same epilogue-soundness role.
263 pub current_func_ret_f64: bool,
264 /// GI-FPU-002 phase 2 (#719/#369): per-function (full index, imports first)
265 /// "returns f32/f64" tables. The direct selector declines a `call` to an
266 /// f32/f64-returning callee LOUDLY at the call site — the result arrives in
267 /// S0/D0 (AAPCS-VFP), which this increment does not marshal into the operand
268 /// stack; tagging it as an integer R0 would be a silent miscompile. Also the
269 /// source for [`current_func_ret_f32`]/[`current_func_ret_f64`] in the
270 /// per-function driver loops. Empty ⇒ callees assumed non-float-returning
271 /// (hand-built op streams; byte-identical legacy behaviour).
272 pub func_ret_f32: Vec<bool>,
273 /// See [`func_ret_f32`](Self::func_ret_f32).
274 pub func_ret_f64: Vec<bool>,
275 /// GI-FPU-002 phase 2 (#719/#369): per-type "returns f32/f64" — the
276 /// `call_indirect` analogue of [`func_ret_f32`](Self::func_ret_f32).
277 pub type_ret_f32: Vec<bool>,
278 /// See [`type_ret_f32`](Self::type_ret_f32).
279 pub type_ret_f64: Vec<bool>,
280 /// #457: DECLARED parameter count of the function CURRENTLY being compiled,
281 /// from the module's type section (`func_arg_counts[func.index]`). Set per
282 /// function by the driver loops like [`current_func_params_i64`].
283 ///
284 /// The backends otherwise INFER the param count from local-access patterns
285 /// (`count_params`: a local whose first access is a read is assumed to be a
286 /// param) — which cannot distinguish a param from a read-before-write
287 /// non-param local. WASM zero-initializes non-param locals, so such a local
288 /// must read 0; the inference instead homed it in a parameter register and
289 /// read caller garbage (#457).
290 ///
291 /// When this is `Some(declared)`, every backend uses
292 /// `min(`[`referenced_locals`](crate::referenced_locals)`(ops), declared)`
293 /// — the highest index the body touches, clamped by the signature. That is
294 /// EXACT in both directions: a genuine non-param local can never be
295 /// mistaken for a param (the clamp), and a param can never be demoted to a
296 /// local (the max over ALL accesses, reads and writes alike). The earlier
297 /// rule capped the READ-FIRST inference instead, which demoted a
298 /// conditionally-written param and produced an uninitialised-frame-slot
299 /// read on ARM and RISC-V and a zero-init local on AArch64 (#970/#851).
300 ///
301 /// `None` → declared signature unknown (hand-built op streams, direct
302 /// `compile_function` callers) → pure inference, the legacy behaviour.
303 /// HONEST RESIDUAL (#970, unchanged from #851): on that path a write-first
304 /// index is genuinely AMBIGUOUS — a param whose incoming value is dead, or
305 /// a non-param local — and both readings can be wrong. The read-first rule
306 /// keeps the #457 behaviour rather than reading caller garbage for a
307 /// zero-init local. The CLI always supplies a declared count.
308 pub current_func_param_count: Option<u32>,
309 /// (#778 phase 4 / #49) The WASM index of the function CURRENTLY being compiled,
310 /// so the WCET pass can identify this function's OWN `func_<idx>` self-call label
311 /// (a self-recursive `BL func_N` where N == this index) and prove/decline the
312 /// self-recursion depth. Set per function by the driver loop (like
313 /// [`current_func_params_i64`]). `None` → unknown (hand-built op streams, direct
314 /// `compile_function` callers) → no self-recursion certificate is attempted.
315 pub current_func_index: Option<u32>,
316 /// #509: blocktype-arity side-table of the function CURRENTLY being compiled
317 /// — `(param_count, result_count)` of the k-th `Block`/`Loop`/`If` in its op
318 /// stream (ordinal-keyed; see [`FunctionOps::block_arity`]). Set per function
319 /// by the driver loop (like [`current_func_params_i64`]). The direct selector
320 /// uses it to land a value carried by `br`/`br_if`/`br_table` in the target
321 /// block's designated result register instead of dropping it. Empty → every
322 /// block treated as void (the legacy lowering; hand-built op streams).
323 ///
324 /// [`FunctionOps::block_arity`]: crate::wasm_decoder::FunctionOps::block_arity
325 pub current_func_block_arity: Vec<(u8, u8)>,
326
327 /// #1214: THIS function's declared-i64-local side-table — see
328 /// [`FunctionOps::declared_i64_locals`]. Set per function by the driver
329 /// loop (like [`current_func_block_arity`]). Empty ⇒ no declared-width
330 /// correction (hand-built op streams / unit tests): behavior is exactly
331 /// the prior dataflow-only inference in `infer_i64_locals`.
332 ///
333 /// [`FunctionOps::declared_i64_locals`]: crate::wasm_decoder::FunctionOps::declared_i64_locals
334 pub current_func_declared_i64_locals: Vec<bool>,
335
336 /// #543 Phase 1 — integrator-marked volatile linear-memory segments (the DMA
337 /// transfer window). Each range `[base, base+len)` names a region of the fused
338 /// linear memory that an EXTERNAL agent (the DMA engine, modelled by gale as a
339 /// Component-Model `own<buffer>` handoff — gale decision `DD-DMA-REGION-001`,
340 /// gale#124) rewrites out-of-band. Loads and stores whose address falls inside
341 /// a marked range must eventually be treated as VOLATILE: not cached, hoisted,
342 /// or reordered across the transfer boundary.
343 ///
344 /// PHASE-2 CONTRACT (implemented — issue #543): the optimizer's
345 /// address-caching passes HONOR these ranges. Consumption points:
346 /// - the #468 base-CSE / const-address-fold
347 /// (`optimizer_bridge::plan_base_cse`, DEFAULT-ON, opt-out
348 /// `SYNTH_BASE_CSE=0`): a const-address access whose 4-byte window
349 /// intersects a marked range is EXCLUDED from the fold set — it keeps
350 /// its verbatim per-access materialize-and-access codegen, while
351 /// accesses outside the range still fold;
352 /// - const-CSE (`liveness::apply_const_cse` wired in `arm_backend.rs`,
353 /// DEFAULT-ON, opt-out `SYNTH_CONST_CSE=0`; the former bridge-level
354 /// inline cache is retired, #242): declines WHOLESALE while any range is
355 /// marked — a cached constant cannot be classified address-vs-data at
356 /// that level, so the conservative stance for statically-unknown
357 /// addressing is to re-materialize every constant at each occurrence.
358 ///
359 /// Passes that only touch SP-relative frame slots (stack-reload forwarding,
360 /// frame-slot DCE, spill re-choice) are unaffected by design: these ranges
361 /// are LINEAR-MEMORY addresses, and frame slots are never linmem. Nothing on
362 /// the pipeline deletes, forwards, or reorders a linear-memory access (IR CSE
363 /// deliberately never CSEs `MemLoad`s; DCE removes only unreachable blocks),
364 /// so every marked access is issued verbatim, in program order.
365 ///
366 /// Empty (the default): zero behavior change by construction — every gate
367 /// reduces to the pre-#543 path, so the emitted `.text` is byte-identical
368 /// with or without this code (the frozen-codegen gate holds). See rivet
369 /// `VCR-DMA-001`.
370 pub volatile_segments: Vec<VolatileRange>,
371
372 /// #778 phase 2 — the parsed `--wcet-hints` file (UNTRUSTED per-function
373 /// loop-bound hints, the scry seam). Consulted ONLY by the WCET sidecar
374 /// computation over the final instruction stream; NEVER by codegen — the
375 /// emitted bytes are byte-identical with or without hints. Every hint is
376 /// soundly verified before use and rejected with a machine reason
377 /// otherwise.
378 pub wcet_hints: Option<crate::wcet::WcetHints>,
379
380 /// VCR-PERF-002 Phase 1 (#494) — proven invariants forwarded by loom in
381 /// the `wsc.facts` custom section (encoding:
382 /// `docs/design/wsc-facts-encoding.md`; program:
383 /// `docs/design/proof-carrying-specialization.md`), whole-module table
384 /// keyed by `(func_index, value_id)`. The compile driver copies the
385 /// current function's slice into [`current_func_facts`] (the
386 /// `func_params_i64` → `current_func_params_i64` pattern), because
387 /// `compile_function` carries no function index.
388 ///
389 /// PHASE-1 CONTRACT: threaded but NOT consumed — no codegen path reads
390 /// facts, so emitted bytes are unchanged whether or not the module
391 /// carries the section (locked by `wsc_facts_ingestion_494.rs`). Phase 2
392 /// turns each fact into a premise for a flag-gated (`SYNTH_FACT_SPEC`),
393 /// per-elision ordeal-validated specialization; the facts-absent compile
394 /// stays byte-identical by construction (empty ⇒ every gate vacuous).
395 ///
396 /// [`current_func_facts`]: CompileConfig::current_func_facts
397 pub wsc_facts: Vec<WscFact>,
398 /// VCR-PERF-002 Phase 1 (#494): the `wsc.facts` invariants of the function
399 /// CURRENTLY being compiled (`fact.func_index == func.index`), set per
400 /// function by the driver loops like [`current_func_params_i64`]. This is
401 /// the field a Phase-2 selector pass will read its premises from. Empty →
402 /// no facts → no specialization may ever fire (the fail-safe default).
403 ///
404 /// [`current_func_params_i64`]: CompileConfig::current_func_params_i64
405 pub current_func_facts: Vec<WscFact>,
406 /// VCR-PERF-002 Phase 2b (#494, divisor-nonzero): op indices (into the op
407 /// stream passed to `compile_function`) of `div`/`rem` ops whose
408 /// DIVIDE-BY-ZERO trap guard is proven dead — the fact-spec pass
409 /// discharged `UNSAT(P ∧ divisor == 0)` per site through the
410 /// certificate-checked ordeal solver BEFORE the driver set this field.
411 /// Consumed by the ARM direct selector (`select_with_stack`); every other
412 /// path ignores it (guards stay — sound). Empty (the default) ⇒ every
413 /// guard is emitted, byte-identical to today.
414 pub fact_div_zero_elide: Vec<usize>,
415 /// VCR-PERF-002 Phase 2b (#494): op indices of `div_s` ops whose
416 /// `INT_MIN / -1` OVERFLOW trap guard is proven dead — a SEPARATE
417 /// obligation (`UNSAT(P ∧ dividend == INT_MIN ∧ divisor == -1)`). A
418 /// divisor-nonzero fact alone NEVER lands here: divisor ≠ 0 does not
419 /// exclude -1 (#633/#634 two-guard distinction). Empty ⇒ guard emitted.
420 pub fact_div_ovf_elide: Vec<usize>,
421 /// #494 bounds-elision (#390 `guard_bool`): op indices of i32 memory
422 /// accesses whose `--safety-bounds software` inline guard is proven dead
423 /// — the fact-spec pass discharged
424 /// `UNSAT(P ∧ trap_mem_oob(zext64(index) + offset, size,
425 /// min_memory_bytes))` per site through the certificate-checked ordeal
426 /// solver BEFORE the driver set this field (ordeal 0.9.1 `trap_mem_oob`
427 /// shape, wraparound-safe 64-bit extension). Consumed by the ARM direct
428 /// selector (`select_with_stack`); every other path ignores it (guards
429 /// stay — sound). Empty (the default) ⇒ every guard is emitted,
430 /// byte-identical to today.
431 pub fact_mem_bounds_elide: Vec<usize>,
432 /// VCR-MEM-004 (#901): op indices of linear-memory accesses whose
433 /// `--safety-bounds software` inline guard is elided on an EXTERNAL proof
434 /// — scry's sound abstract interpretation proved the access in-bounds
435 /// against the memory's guaranteed minimum size, and the verdict file
436 /// cleared every fail-closed gate ([`crate::proven_safe::ingest`]:
437 /// `module_sha256` bound to the exact bytes being compiled,
438 /// `memory_min_bytes` equal to this module's declared floor, and each
439 /// entry's `(func, pc)` key validated against the decoded operator at
440 /// that index).
441 ///
442 /// Kept SEPARATE from [`CompileConfig::fact_mem_bounds_elide`] on purpose:
443 /// the two strip the same guard at the same consumption point, but on
444 /// different AUTHORITIES (a per-site ordeal certificate vs a whole-module
445 /// external AI), and the `synth-proven-safe-elisions-v1` attestation
446 /// records which one covered each site. The ARM backend unions them.
447 /// Empty (the default) ⇒ every guard is emitted, byte-identical to today.
448 pub proven_safe_mem_elide: Vec<usize>,
449 /// #642: `call_indirect` guard inputs — the compile-time table size for
450 /// the runtime bounds check and the per-expected-type closed-world type
451 /// verdicts — computed from the decoded module by
452 /// [`crate::wasm_decoder::DecodedModule::call_indirect_guards`] and set by
453 /// the driver loops. The default (`table_size: None`, empty verdicts)
454 /// DECLINES every `call_indirect` lowering: an unchecked indirect branch
455 /// is never emitted (WASM Core §4.4.8 requires OOB/type-mismatch traps).
456 pub call_indirect_guards: crate::wasm_decoder::CallIndirectGuards,
457 /// #851 lane L3: result count per FUNCTION TYPE (see
458 /// [`crate::wasm_decoder::DecodedModule::type_result_counts`]). The aarch64
459 /// `call_indirect` lowering needs the 0-vs-1 result distinction for a callee
460 /// it knows only by its static type.
461 pub type_result_counts: Vec<u32>,
462 /// #851 lane L3: the STRUCTURAL signature class id per function type (see
463 /// [`crate::wasm_decoder::DecodedModule::structural_type_class_ids`]). The
464 /// aarch64 `call_indirect` type check compares this, not the raw type index
465 /// — WASM type equality is structural. Distinct from
466 /// `call_indirect_guards.type_class_ids`, which the ARM path populates only
467 /// when its heterogeneous-table sidecar exists.
468 pub type_class_ids: Vec<u32>,
469 /// #851 lane L3, aarch64 only — the driver has EMITTED the module-level
470 /// substrate the globals and `call_indirect` lowerings address: the `.data`
471 /// globals image (`__synth_globals`) and the `.text` funcref table
472 /// (`__synth_func_table`), both produced by
473 /// `synth_backend_aarch64::substrate::plan`.
474 ///
475 /// FAIL-SAFE BY DEFAULT (`false`): the aarch64 selector LOUD-DECLINES
476 /// `global.get`/`global.set`/`call_indirect` unless this is set, so a driver
477 /// that compiles function bodies but never emits the regions cannot ship
478 /// code addressing a symbol that does not exist. Set only on the two paths
479 /// that call `plan()` and place its output in the object.
480 pub a64_substrate_emitted: bool,
481 /// RQ-63-RVGLOBAL (#242): how many globals the module IMPORTS. The op
482 /// stream's `global.get`/`global.set` index space is imports-FIRST, while
483 /// [`CompileConfig::global_widths`] / [`CompileConfig::global_mutable`]
484 /// are indexed by DEFINED global (the decoder's `WasmGlobal::index`), so a
485 /// backend maps an op index `i` to defined global `i - num_imported_globals`
486 /// and must decline `i < num_imported_globals` (an imported global's value
487 /// arrives at instantiation, which a synth-emitted region cannot bind).
488 pub num_imported_globals: u32,
489 /// RQ-63-RVGLOBAL (#242): per DEFINED global, its declared mutability.
490 /// Indexed like [`CompileConfig::global_widths`]. A validated module never
491 /// `global.set`s an immutable global, but the RV32 lowering declines it
492 /// anyway rather than write through a `const` — defence in depth, since
493 /// the decoder does not run the wasm validator. Empty ⇒ every global is
494 /// treated as mutable (hand-built op streams).
495 pub global_mutable: Vec<bool>,
496 /// RQ-63-RVGLOBAL (#242): whether the driver WILL place the RV32 globals
497 /// region (`__synth_globals`, a synth-emitted `.data` image carrying every
498 /// defined global's decoded initializer — `synth_backend_riscv::globals`)
499 /// in the object it assembles. FAIL-SAFE BY DEFAULT (`false`): the RV32
500 /// selector LOUD-DECLINES `global.get`/`global.set` unless this is set,
501 /// so a driver that compiles function bodies but never emits the region
502 /// cannot ship code relocating against a symbol nothing defines (the
503 /// #1102 dangling-reference class). The aarch64 `a64_substrate_emitted`
504 /// contract, ported.
505 pub rv32_globals_emitted: bool,
506}
507
508/// #543 — an integrator-marked volatile linear-memory segment (the DMA transfer
509/// window): the half-open byte range `[base, base + len)` of the fused linear
510/// memory that an external agent rewrites out-of-band. Parsed from the CLI
511/// `--volatile-segment <base>:<len>` flag. See [`CompileConfig::volatile_segments`]
512/// for the Phase-1/Phase-2 split.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub struct VolatileRange {
515 /// Start address of the volatile region, in linear-memory bytes.
516 pub base: u32,
517 /// Length of the volatile region, in bytes. The region is `[base, base+len)`.
518 pub len: u32,
519}
520
521impl CompileConfig {
522 /// Resolve the effective safety-bounds setting, honouring the legacy
523 /// `bounds_check` field as a fallback. Used by backends to pick the
524 /// inline-check shape.
525 pub fn effective_safety_bounds(&self) -> SafetyBounds {
526 match (self.safety_bounds, self.bounds_check) {
527 (SafetyBounds::None, true) => SafetyBounds::Software,
528 (s, _) => s,
529 }
530 }
531}
532
533impl Default for CompileConfig {
534 fn default() -> Self {
535 Self {
536 opt_level: 2,
537 target: TargetSpec::cortex_m4(),
538 bounds_check: false,
539 safety_bounds: SafetyBounds::None,
540 hardware: String::new(),
541 no_optimize: false,
542 loom_compat: false,
543 num_imports: 0,
544 func_arg_counts: Vec::new(),
545 func_result_counts: Vec::new(),
546 type_arg_counts: Vec::new(),
547 relocatable: false,
548 // #275: self-contained funcref-table dispatch is opt-in by the
549 // CLI's cortex-m image path; everything else keeps the decline.
550 self_contained_funcref_table: false,
551 // #687: the historical optimized-path absolute base — every
552 // default compile stays byte-identical.
553 linmem_base: OPTIMIZED_LINMEM_BASE,
554 native_pointer_abi: false,
555 linear_memory_bytes: 0,
556 // #406: empty ⇒ no multi-memory context ⇒ multi-memory ops decline
557 // loudly; memory-0 lowering never reads it.
558 memory_pages: Vec::new(),
559 stack_pointer_global: None,
560 func_ret_i64: Vec::new(),
561 type_ret_i64: Vec::new(),
562 // #643: empty ⇒ legacy all-4-byte global slots (i32-only modules).
563 global_widths: Vec::new(),
564 func_params_i64: Vec::new(),
565 current_func_params_i64: Vec::new(),
566 func_params_f32: Vec::new(),
567 current_func_params_f32: Vec::new(),
568 // GI-FPU-002 phase 2 (#719/#369): false ⇒ non-float return (or a
569 // hand-built op stream); driver loops set it per function.
570 current_func_ret_f32: false,
571 current_func_ret_f64: false,
572 // GI-FPU-002 phase 2 (#719/#369): empty ⇒ callees assumed
573 // non-float-returning (hand-built op streams).
574 func_params_f64: Vec::new(),
575 current_func_params_f64: Vec::new(),
576 func_ret_f32: Vec::new(),
577 func_ret_f64: Vec::new(),
578 type_ret_f32: Vec::new(),
579 type_ret_f64: Vec::new(),
580 // #457: None ⇒ declared signature unknown ⇒ param-count inference
581 // only (unit tests / hand-built op streams); driver loops fill it.
582 current_func_param_count: None,
583 current_func_index: None,
584 // #509: empty ⇒ legacy void-block lowering (unit tests / hand-built
585 // op streams); the driver loops fill it per function.
586 current_func_block_arity: Vec::new(),
587 // #1214: empty ⇒ no declared-width correction (unit tests /
588 // hand-built op streams); the driver loops fill it per function.
589 current_func_declared_i64_locals: Vec::new(),
590 // #543 Phase 1: no volatile segments unless the CLI flag names them.
591 // Empty ⇒ inert ⇒ emitted bytes unchanged.
592 volatile_segments: Vec::new(),
593 // VCR-PERF-002 Phase 1 (#494): no facts unless the module carries
594 // a parseable `wsc.facts` section. Empty ⇒ inert (and Phase 1 has
595 // no consumer anyway) ⇒ emitted bytes unchanged.
596 wsc_facts: Vec::new(),
597 current_func_facts: Vec::new(),
598 // VCR-PERF-002 Phase 2b (#494): no guard-elision marks unless the
599 // fact-spec pass discharged the per-site obligations. Empty ⇒
600 // every div/rem trap guard is emitted, byte-identical.
601 fact_div_zero_elide: Vec::new(),
602 fact_div_ovf_elide: Vec::new(),
603 fact_mem_bounds_elide: Vec::new(),
604 proven_safe_mem_elide: Vec::new(),
605 // #642: no guard inputs ⇒ every call_indirect lowering declines
606 // loudly (never an unchecked indirect branch). Driver loops fill
607 // this from the decoded module.
608 call_indirect_guards: crate::wasm_decoder::CallIndirectGuards::default(),
609 type_result_counts: Vec::new(),
610 type_class_ids: Vec::new(),
611 a64_substrate_emitted: false,
612 // RQ-63-RVGLOBAL: no imports, every global mutable, and — fail-safe
613 // — NO globals region placed, so the RV32 selector declines.
614 num_imported_globals: 0,
615 global_mutable: Vec::new(),
616 rv32_globals_emitted: false,
617 // #778 phase 2: no --wcet-hints file ⇒ no hints. Consulted ONLY by
618 // the WCET sidecar computation — never by codegen (the emitted
619 // bytes are byte-identical with or without hints).
620 wcet_hints: None,
621 }
622 }
623}
624
625/// #275: the base symbol of the SELF-CONTAINED funcref table — the
626/// flash-resident region `build_multi_func_cortex_m_elf` appends after the
627/// function code: one 4-byte code pointer per table slot across ALL tables in
628/// declaration order (the same contiguous layout the `--relocatable` R11
629/// contract uses — `TableGuards::base_byte_offset` stays valid verbatim),
630/// null slots as ZERO words (#664), followed by the #676 type-id sidecar at
631/// `type_ids_byte_offset` when a heterogeneous table needs it. The dispatch
632/// reaches it through an `LdrSym` literal-pool word (an `Abs32` reloc against
633/// this symbol) that the image builder patches post-layout — never through
634/// R11, which is the linear-memory base (the #717 collision).
635pub const FUNC_TABLE_SYMBOL: &str = "__synth_func_table";
636
637/// A relocation entry produced during compilation
638///
639/// Records that a BL instruction at `offset` bytes into the function's code
640/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
641/// resolves these when combining the Synth object with the Kiln bridge.
642#[derive(Debug, Clone, Copy, PartialEq, Eq)]
643pub enum RelocKind {
644 /// R_ARM_THM_CALL (ELF type 10) — a THUMB BL call site (#167). Correct
645 /// only for a Thumb-state `bl`, whose 32-bit placeholder is `f7ff fffe`
646 /// (branch-to-self, addend -4 for the +4 pipeline bias).
647 ThmCall,
648 /// R_ARM_CALL (ELF type 28) — an ARM-STATE (A32) BL call site (#1040).
649 /// The A32 analogue of [`RelocKind::ThmCall`], exactly as
650 /// [`RelocKind::AArch64Call26`] and [`RelocKind::RiscvCallPlt`] are the
651 /// analogues for their ISAs — the ISA is fixed at the site that KNOWS it,
652 /// never re-derived at the ELF emitter where the information is gone.
653 ///
654 /// Emitting `ThmCall` for an A32 `bl` was #1040: a consumer that trusts
655 /// the declared type patches Thumb halfwords into an ARM-state word (or
656 /// emits an interwork veneer), producing an invalid instruction. The
657 /// matching A32 placeholder is `ebfffffe` (branch-to-self, addend -8 for
658 /// the +8 pipeline bias) — `gas` emits exactly that for `bl <extern>` in
659 /// ARM mode, and `eb000000` (addend 0) lands two instructions past the
660 /// callee entry, the A32 twin of #174.
661 ArmCall,
662 /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
663 MovwAbs,
664 /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
665 MovtAbs,
666 /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
667 /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
668 /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
669 /// the data word at link time (`S + A`, the addend living in the word, REL
670 /// semantics), which survives placement into a large multi-object image —
671 /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
672 Abs32,
673 /// R_AARCH64_CALL26 (ELF type 283) — an AArch64 `BL` call site (#851). The
674 /// AArch64 analogue of [`RelocKind::ThmCall`]: the linker patches the 26-bit
675 /// word-offset immediate of the `bl` at `offset` to reach the target symbol.
676 /// Emitted only by the `EM_AARCH64` backend's `.rela.text`.
677 AArch64Call26,
678 /// R_AARCH64_JUMP26 (ELF type 282) — an AArch64 `B` (tail-branch) site
679 /// (#851 lane L3). Same 26-bit word-offset immediate as
680 /// [`RelocKind::AArch64Call26`], but for a branch that does NOT set `x30`:
681 /// the aarch64 `call_indirect` funcref table is a `.text`-resident array of
682 /// `b func_N` trampolines, so the dispatch's `blr` sets the return address
683 /// and the trampoline tail-branches into the callee (which returns straight
684 /// to the dispatcher).
685 AArch64Jump26,
686 /// R_AARCH64_ADR_PREL_PG_HI21 (ELF type 275) — the `adrp` half of a
687 /// PC-relative symbol address (#851 lane L3). Patches the 21-bit page delta
688 /// (`immlo`[30:29] + `immhi`[23:5]) so `adrp xd, sym` reaches the 4 KiB page
689 /// containing `sym`. Always paired with an
690 /// [`RelocKind::AArch64AddAbsLo12Nc`] on the next instruction. This pair is
691 /// how aarch64 reaches a synth-EMITTED region (the globals `.data` image,
692 /// the funcref table) with NO dedicated base register — so neither feature
693 /// adds an embedder precondition alongside `x28`.
694 AArch64AdrPrelPgHi21,
695 /// R_AARCH64_ADD_ABS_LO12_NC (ELF type 277) — the `add xd, xd, :lo12:sym`
696 /// half of a PC-relative symbol address (#851 lane L3). Patches the 12-bit
697 /// immediate field [21:10] with `(S + A) & 0xFFF`.
698 AArch64AddAbsLo12Nc,
699 /// R_RISCV_CALL_PLT (ELF type 19) — a RISC-V `auipc`+`jalr` call pair
700 /// (#871). The RV32 analogue of [`RelocKind::ThmCall`]: `offset` points at
701 /// the `auipc` of an 8-byte `auipc ra, 0 ; jalr ra, 0(ra)` placeholder and
702 /// the linker patches BOTH instructions' immediates to reach the target
703 /// symbol (the modern form; `R_RISCV_CALL` is deprecated). Emitted only by
704 /// the `EM_RISCV` backend's `.rela.text`.
705 RiscvCallPlt,
706 /// R_RISCV_HI20 (ELF type 26) — the `lui` half of an ABSOLUTE symbol
707 /// address (RQ-63-RVGLOBAL, #242). `offset` points at a `lui rd, 0`
708 /// placeholder whose 20-bit immediate the linker patches to
709 /// `((S + A) + 0x800) >> 12`. Always paired with an
710 /// [`RelocKind::RiscvLo12I`] on the next instruction. This pair is how
711 /// RV32 reaches a synth-EMITTED region (the globals `.data` image,
712 /// `__synth_globals`) with NO dedicated base register — the RV32 twin of
713 /// the aarch64 `adrp`+`add :lo12:` pair, so globals add no embedder
714 /// precondition beside `s11`. Absolute rather than PC-relative because the
715 /// RV32 object is always statically host-linked into a fixed-address
716 /// bare-metal image (the `medlow` code model), which needs no per-site
717 /// local symbol.
718 RiscvHi20,
719 /// R_RISCV_LO12_I (ELF type 27) — the `addi rd, rd, 0` half of an absolute
720 /// symbol address (RQ-63-RVGLOBAL). The linker patches the 12-bit I-type
721 /// immediate with the low bits of `S + A`.
722 RiscvLo12I,
723}
724
725#[derive(Debug, Clone, PartialEq, Eq)]
726pub struct CodeRelocation {
727 /// Byte offset within the function's machine code where the reloc applies
728 pub offset: u32,
729 /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
730 pub symbol: String,
731 /// Which ARM relocation type to emit for this site.
732 pub kind: RelocKind,
733}
734
735/// Symbol BINDING — whether a symbol takes part in cross-object resolution
736/// (#656 ARM, #1180 / RQ-65-FUNCN aarch64).
737///
738/// This is a CONTAINER-INDEPENDENT concept, which is why it lives here and
739/// not in a writer: ELF spells it `STB_LOCAL` / `STB_GLOBAL` / `STB_WEAK` in
740/// `st_info`'s high nibble (the discriminants below are exactly those
741/// values), Mach-O spells `Local` as `N_EXT` CLEAR and `Global` as `N_EXT`
742/// SET on the `nlist_64`. The decision that a synth-invented name — a
743/// `func_N` call label, `__synth_globals`, `__synth_func_table` — is
744/// `Local` while a wasm export or import is `Global` is made ONCE, at the
745/// object PLAN, and every container reads it from there. Two independently
746/// compiled synth objects both define `func_1`; a `Global` binding made
747/// linking them into one program a `duplicate symbol` refusal, in every
748/// container (measured on ELF `ld.lld` and Mach-O Apple `ld`, #1180).
749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
750pub enum SymbolBinding {
751 /// File-local: resolves relocations within its own object (they bind by
752 /// symbol INDEX, not by name) and is invisible to every other object.
753 Local = 0,
754 /// Visible to the link: the name an embedder calls, or the import it
755 /// defines.
756 Global = 1,
757 /// Weak (ELF `STB_WEAK`); no synth writer emits it today.
758 Weak = 2,
759}
760
761/// The locals-first symbol order, computed ONCE for every container that
762/// needs it (#656, #1180).
763///
764/// ELF requires every `STB_LOCAL` symbol to precede every non-local one in
765/// `.symtab`, with the section's `sh_info` = index of the first non-local.
766/// Mach-O's `LC_DYSYMTAB` requires the same partition (locals, then external
767/// defined, then undefined). The ARM ELF32 builder (`synth-backend`,
768/// `ElfBuilder::build`) and the aarch64 object plan (`synth-backend-aarch64`,
769/// `plan_object`) both apply THIS permutation, so the rule is written once —
770/// a second hand-written copy in a second writer is the mirror the North
771/// Star forbids, and the way the two backends diverged in the first place.
772///
773/// The permutation is a STABLE sort on `binding != Local`: with zero locals
774/// it is the identity, which is what keeps every pre-#656 / pre-#1180 object
775/// byte-identical.
776#[derive(Debug, Clone, PartialEq, Eq)]
777pub struct LocalsFirst {
778 /// `order[new] = old`: the symbol emitted at position `new` is the caller's
779 /// symbol `old`.
780 pub order: Vec<usize>,
781 /// `old_to_new[old] = new`: where the caller's symbol `old` landed. Every
782 /// relocation that names a symbol by index is rewritten through this.
783 pub old_to_new: Vec<usize>,
784 /// The number of `Local` symbols — the length of the local prefix. ELF's
785 /// `sh_info` is `local_count + 1` (the null symbol at index 0 counts as
786 /// local); Mach-O's `nlocalsym` is `local_count`.
787 pub local_count: usize,
788}
789
790/// Compute the [`LocalsFirst`] permutation for `bindings` (in the caller's
791/// current order).
792pub fn locals_first(bindings: impl IntoIterator<Item = SymbolBinding>) -> LocalsFirst {
793 let bindings: Vec<SymbolBinding> = bindings.into_iter().collect();
794 let mut order: Vec<usize> = (0..bindings.len()).collect();
795 // Stable: locals keep their relative order, and so do non-locals.
796 order.sort_by_key(|&i| bindings[i] != SymbolBinding::Local);
797 let mut old_to_new = vec![0usize; bindings.len()];
798 for (new, &old) in order.iter().enumerate() {
799 old_to_new[old] = new;
800 }
801 let local_count = bindings
802 .iter()
803 .filter(|b| **b == SymbolBinding::Local)
804 .count();
805 LocalsFirst {
806 order,
807 old_to_new,
808 local_count,
809 }
810}
811
812/// VCR-DBG-001: a per-instruction source map — `(machine_offset_within_code,
813/// wasm_op_index)` pairs, one per emitted machine instruction. A `None` op-index
814/// marks an instruction with no originating wasm op (prologue/epilogue, literal
815/// pool). Consumed by the DWARF `.debug_line` emitter; empty when no source map
816/// was produced.
817pub type LineMap = Vec<(u32, Option<usize>)>;
818
819/// VCR-DEC-003 (#396, witness#130): the object-level control-flow class of one
820/// emitted machine instruction, captured at encode time alongside [`LineMap`].
821/// It is the piece post-hoc CLI derivation cannot recover — `line_map` records
822/// which wasm op an instruction came from, but not whether that instruction IS a
823/// conditional branch, an unconditional branch, or a predicated (IT-block) move.
824/// The `synth-provenance-v1` emitter needs it to enumerate the ACTUAL object
825/// conditional branches (so it can prove "every object branch resolves to a
826/// source condition", not just "every source branch has an object PC").
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
828pub enum BranchClass {
829 /// A conditional branch (`Bcc`/`Blo`/`Bhs`/`BCondOffset`) — an object-level
830 /// decision point MC/DC must account for.
831 CondBranch,
832 /// An unconditional branch (`B`/`BOffset`) — control flow, not a decision.
833 UncondBranch,
834 /// A predicated conditional move (`SelectMove`, the IT-block form the
835 /// cmp→select fuse produces) — a folded decision with no branch.
836 Predicated,
837 /// Anything else (data-processing, load/store, call, prologue/epilogue).
838 Other,
839}
840
841/// VCR-DEC-003: per-instruction object-branch class, parallel to [`LineMap`]
842/// (same length, same order — one entry per emitted machine instruction).
843/// `(machine_offset_within_code, class)`. Empty when provenance is not being
844/// produced (never serialized into `.text`; frozen-safe additive metadata).
845pub type BranchMap = Vec<(u32, BranchClass)>;
846
847/// A single compiled function
848#[derive(Debug, Clone)]
849pub struct CompiledFunction {
850 /// Function name (from WASM export or generated)
851 pub name: String,
852 /// Raw machine code bytes
853 pub code: Vec<u8>,
854 /// Original WASM ops (retained for verification)
855 pub wasm_ops: Vec<WasmOp>,
856 /// Relocations for external symbol references (BL to bridge functions)
857 pub relocations: Vec<CodeRelocation>,
858 /// VCR-DBG-001: per-instruction source map for DWARF `.debug_line` emission —
859 /// `(machine_offset_within_code, wasm_op_index)` captured at encode time, one
860 /// entry per emitted machine instruction. A `None` op-index marks an
861 /// instruction with no originating wasm op (prologue/epilogue, literal-pool
862 /// word). This is purely additive metadata: it is never serialized unless
863 /// `.debug_line` emission is requested, so the emitted `.text` is
864 /// byte-identical with or without it. Empty for backends/paths that do not
865 /// yet produce a source map (RISC-V, the optimized ARM path).
866 pub line_map: LineMap,
867 /// VCR-DEC-003 (#396): per-instruction object-branch class, parallel to
868 /// `line_map`. Lets the `synth-provenance-v1` emitter enumerate the real
869 /// object conditional branches (not just re-walk the wasm branch ops).
870 /// Purely additive metadata: never serialized into `.text`, so emitted bytes
871 /// are byte-identical with or without it. Empty for backends/paths that do
872 /// not produce it (RISC-V, the optimized ARM path).
873 pub branch_map: BranchMap,
874 /// #778 (v0.46): the SOUND static worst-case-cycle bound for this function,
875 /// or a loud decline, computed over the final Thumb-2 instruction stream (see
876 /// [`crate::wcet`]). `Some` only when the ARM backend produced it (the RISC-V
877 /// and AArch64 backends carry no cycle model yet → `None`). Purely additive
878 /// metadata: derived from the already-decided instruction list, never
879 /// serialized into `.text`, so emitted bytes are byte-identical with or
880 /// without it (frozen-safe). Emitted as the `<output>.wcet.json` sidecar only
881 /// under `--emit-wcet`.
882 pub wcet: Option<crate::wcet::WcetFunction>,
883 /// #778 phase 3: the per-function WCET INTERMEDIATE (own-body cycles + direct
884 /// call sites, or a composition-independent decline) BEFORE inter-procedural
885 /// composition. The module driver composes these across the direct call graph
886 /// into the final per-function bounds (a caller's bound = its own body + each
887 /// direct callee's bound × the call site's proven execution count). `Some` only
888 /// on the Thumb-2 path that produced `wcet`. Purely additive, `.text`-invisible
889 /// (frozen-safe) — derived from the already-decided instruction list.
890 pub wcet_intermediate: Option<crate::wcet::WcetIntermediate>,
891}
892
893/// Result of compiling a full module
894#[derive(Debug)]
895pub struct CompilationResult {
896 /// Compiled functions
897 pub functions: Vec<CompiledFunction>,
898 /// Complete ELF binary (if backend produces one directly)
899 pub elf: Option<Vec<u8>>,
900 /// Name of the backend that produced this result
901 pub backend_name: String,
902}
903
904/// What a backend can and cannot do
905#[derive(Debug, Clone)]
906pub struct BackendCapabilities {
907 /// Backend produces complete ELF files (external backends like aWsm)
908 pub produces_elf: bool,
909 /// Backend supports per-rule verification (only our custom ARM backend)
910 pub supports_rule_verification: bool,
911 /// Backend supports binary-level verification (all backends via disassembly)
912 pub supports_binary_verification: bool,
913 /// Backend is an external tool (not a library)
914 pub is_external: bool,
915}
916
917/// Trait that every compilation backend implements
918pub trait Backend: Send + Sync {
919 /// Human-readable backend name
920 fn name(&self) -> &str;
921
922 /// What this backend can do
923 fn capabilities(&self) -> BackendCapabilities;
924
925 /// Which targets this backend supports
926 fn supported_targets(&self) -> Vec<TargetSpec>;
927
928 /// Compile an entire decoded WASM module
929 fn compile_module(
930 &self,
931 module: &DecodedModule,
932 config: &CompileConfig,
933 ) -> std::result::Result<CompilationResult, BackendError>;
934
935 /// Compile a single function from WASM ops to machine code
936 fn compile_function(
937 &self,
938 name: &str,
939 ops: &[WasmOp],
940 config: &CompileConfig,
941 ) -> std::result::Result<CompiledFunction, BackendError>;
942
943 /// Check if this backend is available (external tools installed, etc.)
944 fn is_available(&self) -> bool;
945}
946
947/// Registry of available backends
948pub struct BackendRegistry {
949 backends: HashMap<String, Box<dyn Backend>>,
950}
951
952impl BackendRegistry {
953 pub fn new() -> Self {
954 Self {
955 backends: HashMap::new(),
956 }
957 }
958
959 /// Register a backend under its name
960 pub fn register(&mut self, backend: Box<dyn Backend>) {
961 let name = backend.name().to_string();
962 self.backends.insert(name, backend);
963 }
964
965 /// Get a backend by name
966 pub fn get(&self, name: &str) -> Option<&dyn Backend> {
967 self.backends.get(name).map(|b| b.as_ref())
968 }
969
970 /// List all registered backends
971 pub fn list(&self) -> Vec<&dyn Backend> {
972 self.backends.values().map(|b| b.as_ref()).collect()
973 }
974
975 /// List backends that are actually available (installed and working)
976 pub fn available(&self) -> Vec<&dyn Backend> {
977 self.backends
978 .values()
979 .filter(|b| b.is_available())
980 .map(|b| b.as_ref())
981 .collect()
982 }
983}
984
985impl Default for BackendRegistry {
986 fn default() -> Self {
987 Self::new()
988 }
989}
990
991#[cfg(test)]
992mod tests {
993 use super::*;
994
995 #[test]
996 fn test_registry_empty() {
997 let reg = BackendRegistry::new();
998 assert!(reg.list().is_empty());
999 assert!(reg.available().is_empty());
1000 assert!(reg.get("arm").is_none());
1001 }
1002
1003 #[test]
1004 fn test_compile_config_default() {
1005 let config = CompileConfig::default();
1006 assert_eq!(config.opt_level, 2);
1007 assert!(!config.bounds_check);
1008 assert_eq!(config.safety_bounds, SafetyBounds::None);
1009 assert!(!config.no_optimize);
1010 }
1011
1012 #[test]
1013 fn safety_bounds_parse_round_trip() {
1014 for s in ["none", "mpu", "software", "mask"] {
1015 let sb = SafetyBounds::parse(s).unwrap();
1016 assert_eq!(sb.as_str(), s);
1017 }
1018 // RQ-69-PMPLIB (#1317): this line PINNED the silent alias. Flipped —
1019 // the library refuses `pmp` exactly as the CLI has since v0.68, and
1020 // the message names the issue so a caller can find out why.
1021 let pmp = SafetyBounds::parse("pmp").expect_err("pmp must be refused (#1317)");
1022 assert!(pmp.contains("#1317"), "refusal must name the issue: {pmp}");
1023 assert!(
1024 pmp.contains("never a silent alias"),
1025 "refusal must say what it is not: {pmp}"
1026 );
1027 assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
1028 assert!(SafetyBounds::parse("nonsense").is_err());
1029 }
1030
1031 #[test]
1032 fn effective_safety_bounds_legacy_promotes_to_software() {
1033 let cfg = CompileConfig {
1034 bounds_check: true,
1035 ..Default::default()
1036 };
1037 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
1038 }
1039
1040 #[test]
1041 fn effective_safety_bounds_new_field_wins() {
1042 let cfg = CompileConfig {
1043 bounds_check: true,
1044 safety_bounds: SafetyBounds::Mpu,
1045 ..Default::default()
1046 };
1047 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
1048 }
1049}