Skip to main content

synth_backend/
arm_backend.rs

1//! ARM Backend — wraps the instruction selector + optimizer + encoder as a Backend
2//!
3//! This is Synth's custom ARM compiler targeting Cortex-M (Thumb-2).
4//! It's the only backend that supports per-rule formal verification (ASIL D path).
5
6use crate::ArmEncoder;
7use synth_core::backend::{
8    Backend, BackendCapabilities, BackendError, CodeRelocation, CompilationResult, CompileConfig,
9    CompiledFunction, LineMap, SafetyBounds,
10};
11use synth_core::target::{IsaVariant, TargetSpec};
12use synth_core::wasm_decoder::DecodedModule;
13use synth_core::wasm_op::WasmOp;
14use synth_synthesis::{
15    ArmInstruction, ArmOp, BoundsCheckConfig, InstructionSelector, OptimizationConfig,
16    OptimizerBridge, RuleDatabase, validate_instructions,
17};
18
19/// ARM Cortex-M backend using Synth's custom compiler pipeline
20pub struct ArmBackend;
21
22impl ArmBackend {
23    pub fn new() -> Self {
24        Self
25    }
26}
27
28impl Default for ArmBackend {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Backend for ArmBackend {
35    fn name(&self) -> &str {
36        "arm"
37    }
38
39    fn capabilities(&self) -> BackendCapabilities {
40        BackendCapabilities {
41            produces_elf: false,
42            supports_rule_verification: true,
43            supports_binary_verification: true,
44            is_external: false,
45        }
46    }
47
48    fn supported_targets(&self) -> Vec<TargetSpec> {
49        vec![
50            TargetSpec::cortex_m3(),
51            TargetSpec::cortex_m4(),
52            TargetSpec::cortex_m4f(),
53            TargetSpec::cortex_m7(),
54            TargetSpec::cortex_m7dp(),
55        ]
56    }
57
58    fn compile_module(
59        &self,
60        module: &DecodedModule,
61        config: &CompileConfig,
62    ) -> Result<CompilationResult, BackendError> {
63        let exports: Vec<_> = module
64            .functions
65            .iter()
66            .filter(|f| f.export_name.is_some())
67            .collect();
68
69        if exports.is_empty() {
70            return Err(BackendError::CompilationFailed(
71                "no exported functions found".into(),
72            ));
73        }
74
75        let mut functions = Vec::new();
76        for func in &exports {
77            let name = func.export_name.clone().unwrap();
78            // #359: copy THIS function's declared param widths into the config so
79            // `compile_function` (which carries no function index) can refuse a
80            // 64-bit param on the AAPCS stack-argument path. Cheap clone only when
81            // a signature table is present and this function has a width entry —
82            // otherwise reuse the shared config (every existing module unchanged).
83            // #509: same per-function pattern for the blocktype-arity side-table
84            // (value-carrying-branch lowering).
85            let params = config
86                .func_params_i64
87                .get(func.index as usize)
88                .filter(|p| !p.is_empty());
89            // #457: THIS function's DECLARED param count (imports-first full
90            // index), so the backend can cap the access-pattern inference that
91            // mistook a read-before-write local for a param. `None` when the
92            // driver supplied no arg-count table (hand-built modules).
93            let declared_params = config.func_arg_counts.get(func.index as usize).copied();
94            // GI-FPU-002 (#619/#369): THIS function's declared f32-param mask.
95            let params_f32 = config
96                .func_params_f32
97                .get(func.index as usize)
98                .filter(|p| !p.is_empty());
99            // GI-FPU-002 phase 2 (#369): THIS function's declared f64-param
100            // mask (hard-float targets decline f64 params loudly).
101            let params_f64 = config
102                .func_params_f64
103                .get(func.index as usize)
104                .filter(|p| !p.is_empty());
105            // GI-FPU-002 phase 2 (#719/#369): THIS function's declared f32/f64
106            // return flag, so the epilogue soundness guard fires on every driver
107            // path (not only the CLI loops).
108            let ret_f32 = config
109                .func_ret_f32
110                .get(func.index as usize)
111                .copied()
112                .unwrap_or(false);
113            let ret_f64 = config
114                .func_ret_f64
115                .get(func.index as usize)
116                .copied()
117                .unwrap_or(false);
118            // #1214: THIS function's declared-i64-local side-table. Guarded by
119            // `.any(i64)`, not `!is_empty()` — every function with ANY declared
120            // local (i32 included) has a non-empty vector, and that would
121            // widen this memoization guard to nearly every function for no
122            // reason; only a function that actually declares an i64 local
123            // needs the extra clone.
124            let declared_i64_locals = &func.declared_i64_locals;
125            let func_config = if params.is_some()
126                || params_f32.is_some()
127                || params_f64.is_some()
128                || !func.block_arity.is_empty()
129                || declared_params.is_some()
130                || ret_f32
131                || ret_f64
132                || declared_i64_locals.iter().any(|&b| b)
133            {
134                Some(CompileConfig {
135                    current_func_params_i64: params.cloned().unwrap_or_default(),
136                    current_func_params_f32: params_f32.cloned().unwrap_or_default(),
137                    current_func_params_f64: params_f64.cloned().unwrap_or_default(),
138                    current_func_ret_f32: ret_f32,
139                    current_func_ret_f64: ret_f64,
140                    current_func_block_arity: func.block_arity.clone(),
141                    current_func_declared_i64_locals: declared_i64_locals.clone(),
142                    current_func_param_count: declared_params,
143                    ..config.clone()
144                })
145            } else {
146                None
147            };
148            let cfg = func_config.as_ref().unwrap_or(config);
149            let compiled = self.compile_function(&name, &func.ops, cfg)?;
150            functions.push(compiled);
151        }
152
153        Ok(CompilationResult {
154            functions,
155            elf: None,
156            backend_name: self.name().to_string(),
157        })
158    }
159
160    fn compile_function(
161        &self,
162        name: &str,
163        ops: &[WasmOp],
164        config: &CompileConfig,
165    ) -> Result<CompiledFunction, BackendError> {
166        let (code, relocations, line_map, branch_map, final_instrs) =
167            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
168
169        // #778: derive the SOUND static WCET intermediate from the final Thumb-2
170        // stream. Only present for the Thumb-2 path; the core class (from the
171        // triple) decides whether the bound is sound (M3/M4) or declined (M7).
172        // Phase 2: any --wcet-hints entry for THIS function is verified (never
173        // trusted) by the loop analyzer. Phase 3: the intermediate carries the
174        // own-body cycles + direct call sites; the module driver composes it across
175        // the call graph. `wcet` here is the SINGLE-FUNCTION view (unresolved direct
176        // calls decline `call`) — a valid standalone answer, overwritten by the
177        // composed result when the driver runs the second pass.
178        let wcet_intermediate = final_instrs.as_ref().map(|instrs| {
179            let hints = config
180                .wcet_hints
181                .as_ref()
182                .and_then(|h| h.functions.get(name));
183            let self_label = config.current_func_index.map(|i| format!("func_{i}"));
184            crate::wcet::function_wcet_intermediate(
185                name,
186                instrs,
187                &config.target.triple,
188                hints,
189                self_label.as_deref(),
190            )
191        });
192        // The SINGLE-FUNCTION standalone view (unresolved direct calls decline
193        // `call`). Kept as a per-function fallback for any consumer that reads a
194        // lone `CompiledFunction` without running the module composer; the CLI
195        // `--emit-wcet` path IGNORES this and composes `wcet_intermediate` across
196        // the whole call graph instead (its result overwrites the report).
197        // RQ-71-STACKDEPTH (#1341): the native-stack profile, from the SAME
198        // final stream. Unconditional and cheap (one linear walk); the CLI
199        // decides whether to report it. It is NOT gated on the WCET decline —
200        // a data-dependent loop is WCET-unbounded and stack-bounded.
201        let stack_frame = final_instrs
202            .as_ref()
203            .map(|instrs| crate::stack_depth::analyze_function(name, instrs));
204        let wcet = final_instrs.map(|instrs| {
205            let hints = config
206                .wcet_hints
207                .as_ref()
208                .and_then(|h| h.functions.get(name));
209            crate::wcet::function_wcet_with_hints(name, &instrs, &config.target.triple, hints)
210        });
211
212        Ok(CompiledFunction {
213            name: name.to_string(),
214            code,
215            wasm_ops: ops.to_vec(),
216            relocations,
217            line_map,
218            branch_map,
219            wcet,
220            wcet_intermediate,
221            stack_frame,
222        })
223    }
224
225    fn is_available(&self) -> bool {
226        true // Always available — it's a library backend
227    }
228}
229
230/// Count the number of function parameters by analyzing LocalGet patterns
231/// RQ-58-MIRRORS (#242): was a private copy of the read-before-write param
232/// heuristic, byte-equivalent to the other two backends'. Now the ONE shared
233/// definition in `synth-core`, so a correction reaches every backend.
234fn count_params(wasm_ops: &[WasmOp]) -> u32 {
235    synth_core::count_params_heuristic(wasm_ops)
236}
237
238/// #457/#970: the parameter count the selector is given.
239///
240/// With a DECLARED count from the driver the bound is
241/// `min(`[`synth_core::referenced_locals`]`(ops), declared)` — the highest
242/// local index the body touches, clamped by the signature. That is exact in
243/// both directions: the clamp stops a read-before-write NON-PARAM local (which
244/// WASM zero-initializes) from being homed in an argument register and reading
245/// caller garbage (#457), and taking the max over ALL accesses — writes as well
246/// as reads — stops a PARAM from being demoted to a local.
247///
248/// The previous rule capped [`count_params`] (a READ-FIRST heuristic) with the
249/// declared count, which got the second direction wrong: a param written on ONE
250/// arm of an `if` is "written first" in linear op order, so it was demoted, and
251/// because the demoted local's first access is a WRITE the #457 zero-init
252/// skipped it too. The arm that does NOT write it then read an UNINITIALISED
253/// frame slot — measured under unicorn with the sub-SP stack poisoned,
254/// `cond_write_param(0, 42)` returned the poison word, i.e. previous-frame
255/// bytes rather than 42 (#970; the aarch64 instance was #851).
256///
257/// `min` rather than a plain `declared` override preserves the leniency for a
258/// body that only touches the first few of many declared params.
259///
260/// `None` (no declared signature: hand-built op streams, direct
261/// `compile_function` callers) keeps the legacy pure inference — see the
262/// residual documented on [`CompileConfig::current_func_param_count`].
263fn effective_num_params(wasm_ops: &[WasmOp], config: &CompileConfig) -> u32 {
264    match config.current_func_param_count {
265        Some(declared) => synth_core::referenced_locals(wasm_ops).min(declared),
266        None => count_params(wasm_ops),
267    }
268}
269
270/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
271/// Moved to `synth_core::rewrite_memory_grow_zero` (#242, VCR-SEL-005) so the
272/// ARM and RISC-V backends share ONE implementation and cannot drift; re-export
273/// here keeps the existing `rewrite_memory_grow_zero(...)` call sites working.
274use synth_core::rewrite_memory_grow_zero;
275
276/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
277/// value — i.e. one targeting a result-typed block/if (forward edge with
278/// results > 0) or a parameterized loop header (backward edge with loop
279/// params > 0)?
280///
281/// The optimized path's wasm→IR lowering drops the carried value on such
282/// edges (the taken arm returns the fall-through result — same class as the
283/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
284/// #507 — the shape is detected on the raw op stream and routed to the direct
285/// selector, whose #509 designated-result-register lowering lands the value
286/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
287/// side-table; when it is empty (hand-built op streams) every block reads as
288/// void and this never fires, keeping the optimized path byte-identical for
289/// every existing caller. Frozen-safe for the same reason as #507: the frozen
290/// fixtures compile `--relocatable` (already direct), and no optimized-path
291/// fixture branches to a result-typed block.
292fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
293    // Open control constructs: (is_loop, params, results), innermost last.
294    let mut open: Vec<(bool, u8, u8)> = Vec::new();
295    let mut ctrl_ord = 0usize;
296    // A branch edge carries a value when its target is a result-typed forward
297    // join (block/if) or a parameterized loop header.
298    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
299        let Some(&(is_loop, params, results)) = open
300            .len()
301            .checked_sub(1 + depth as usize)
302            .and_then(|i| open.get(i))
303        else {
304            return false; // function-level target — handled by Return lowering
305        };
306        if is_loop { params > 0 } else { results > 0 }
307    };
308    for op in wasm_ops {
309        match op {
310            WasmOp::Block | WasmOp::If => {
311                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
312                ctrl_ord += 1;
313                open.push((false, p, r));
314            }
315            WasmOp::Loop => {
316                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
317                ctrl_ord += 1;
318                open.push((true, p, r));
319            }
320            WasmOp::End => {
321                open.pop(); // None only at the function-level end — harmless
322            }
323            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
324            WasmOp::BrTable { targets, default }
325                if targets
326                    .iter()
327                    .chain(std::iter::once(default))
328                    .any(|d| carries(&open, *d)) =>
329            {
330                return true;
331            }
332            _ => {}
333        }
334    }
335    false
336}
337
338/// Core compilation: WASM ops → ARM machine code bytes + relocations
339///
340/// Returns (code_bytes, relocations) where relocations record BL instructions
341/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
342type CompileArmOutput = (
343    Vec<u8>,
344    Vec<CodeRelocation>,
345    LineMap,
346    synth_core::backend::BranchMap,
347    // #778: the SOUND static WCET result over the final Thumb-2 stream, computed
348    // by `compile_function` (which knows the function name); `None` for the A32
349    // path. Purely additive metadata — does not touch `code`.
350    Option<Vec<synth_synthesis::ArmInstruction>>,
351);
352
353/// RQ-71-STACKDEPTH/#345: one deferred `LdrSym` — where its placeholder LDR
354/// sits, and what word the pool must carry for it.
355struct PendingLiteral {
356    ldr_offset: u32,
357    symbol: String,
358    addend: i32,
359}
360
361/// RQ-72-ISLANDS (#345, cpetig via #1331): emit ONE constant island — the
362/// pooled words, optionally preceded by a branch over them — and patch each
363/// pending LDR's `imm12` in place.
364///
365/// SINGLE SOURCE for both placements. The inline island and the
366/// end-of-function pool differ in exactly one thing: whether execution can
367/// fall into the words. That is `branch_over`. Writing the patch arithmetic
368/// twice is how the two would drift, which is the failure this repo's North
369/// Star correction is about.
370///
371/// THE REFUSAL IS PRESERVED, DELIBERATELY. If a literal is out of range even
372/// from here, this still returns the #345 error rather than patching a wrong
373/// offset. Islands widen WHERE a pool may sit; they do not widen the Thumb-2
374/// LDR-literal encoding, which is a 12-bit unsigned field and always will be.
375fn emit_literal_pool(
376    code: &mut Vec<u8>,
377    relocations: &mut Vec<CodeRelocation>,
378    pending: &[PendingLiteral],
379    branch_over: Option<&ArmEncoder>,
380) -> Result<(), String> {
381    if pending.is_empty() {
382        return Ok(());
383    }
384    // A mid-stream island sits in the instruction stream, so execution must be
385    // carried over it. The end-of-function pool needs no branch: those bytes
386    // are past the final return and are never reached.
387    if let Some(enc) = branch_over {
388        let n = pending.len();
389        // The branch's own size decides the distance it must cover, and the
390        // distance decides the size (B.N is 2 bytes, B.W is 4). Iterate to the
391        // fixed point rather than assuming one — the same shape
392        // `resolve_label_branches` already uses for label branches.
393        let mut branch_len = 2usize;
394        let bytes = loop {
395            let pad = (4 - ((code.len() + branch_len) % 4)) % 4;
396            let skip = branch_len + pad + 4 * n;
397            // `BOffset` takes the halfword displacement (target - branch - 4)/2.
398            // `code.len()` is even at any Thumb instruction boundary and
399            // `branch_len` is even, so `pad` is even and `skip` is even.
400            let off = ((skip as i32) - 4) / 2;
401            let e = enc
402                .encode(&ArmOp::BOffset { offset: off })
403                .map_err(|x| format!("island branch encoding failed: {}", x))?;
404            if e.len() == branch_len {
405                break e;
406            }
407            branch_len = e.len();
408            if branch_len > 4 {
409                return Err(format!(
410                    "literal-pool island (#345): branch over {} pooled word(s) \
411                     would need {} bytes, which is not a Thumb-2 B encoding",
412                    n, branch_len
413                ));
414            }
415        };
416        code.extend_from_slice(&bytes);
417    }
418    // 4-byte align the pool start (Thumb-2 word loads require it, and
419    // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
420    while !code.len().is_multiple_of(4) {
421        code.push(0x00);
422    }
423    // One distinct pooled word per LdrSym (no dedup: different sites carry
424    // different addends, and the REL addend lives in the word).
425    for lit in pending {
426        let word_offset = code.len() as u32;
427
428        // REL semantics: the linker computes `S + A`, where A is the in-place
429        // value of the relocated word. Initialize the word to the addend so
430        // the final loaded address is `symbol + addend`.
431        code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
432        relocations.push(CodeRelocation {
433            offset: word_offset,
434            symbol: lit.symbol.clone(),
435            kind: synth_core::backend::RelocKind::Abs32,
436        });
437
438        // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
439        // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
440        // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
441        let pc = lit.ldr_offset + 4;
442        let aligned_pc = pc & !3u32;
443        let imm12 = word_offset.wrapping_sub(aligned_pc);
444        if word_offset < aligned_pc || imm12 > 0xFFF {
445            return Err(format!(
446                "LdrSym literal pool out of range (#345): imm12={} > 4095 \
447                 for symbol {}",
448                imm12, lit.symbol
449            ));
450        }
451        let hw2_off = (lit.ldr_offset + 2) as usize;
452        let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
453        hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
454        let hw2_bytes = hw2.to_le_bytes();
455        code[hw2_off] = hw2_bytes[0];
456        code[hw2_off + 1] = hw2_bytes[1];
457    }
458    Ok(())
459}
460
461fn compile_wasm_to_arm(
462    wasm_ops: &[WasmOp],
463    config: &CompileConfig,
464) -> Result<CompileArmOutput, String> {
465    // #1093: a PARAMETER-taking block type (`if`/`block`/`loop (param ..)`,
466    // wasm multi-value) declines LOUDLY here — the single choke point BOTH
467    // ARM codegen paths pass through, so neither the optimized route nor the
468    // #197 direct route can reach the selectors' frame-entry stack
469    // checkpoints, which cannot represent params consumed below them (the
470    // `split_off` panic with an `else`; a silently-wrong false-path value
471    // without one — see `find_param_block_type`). This is the aarch64
472    // VCR-A64-CF-001 frame-open refusal ported, NOT multi-value support.
473    // Checked on the driver's ORIGINAL stream, which is what the ordinal
474    // side-table was built against. Empty side-table (hand-built op streams)
475    // ⇒ never fires ⇒ byte-identical for every existing caller.
476    //
477    // RQ-64-MVLOWER (#1093): the guard is relaxed PER CONSTRUCT and PER PATH,
478    // from the one policy in synth-core (`arm_param_block_lowering`), on the
479    // configuration the #1097 oracle executes — `--relocatable`. The
480    // self-contained image path keeps the full decline: no oracle leg
481    // executes its images, so there is no evidence to relax on.
482    let lowered = synth_core::arm_param_block_lowering(config.relocatable);
483    if let Some((what, ord, arity)) = synth_core::find_unlowered_param_block_type(
484        wasm_ops,
485        &config.current_func_block_arity,
486        lowered,
487    ) {
488        return Err(synth_core::param_block_decline_msg(
489            if config.relocatable {
490                "the ARM direct selector (--relocatable)"
491            } else {
492                "the ARM selector (self-contained image path — no #1097 oracle \
493                 leg executes it)"
494            },
495            what,
496            ord,
497            arity,
498        ));
499    }
500    // #539: `memory.grow(0)` must return the CURRENT page count, not the
501    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
502    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
503    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
504    // is semantically identical to `memory.size`, which the backend already
505    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
506    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
507    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
508    // cannot grow); a runtime delta that happens to be 0 is the documented
509    // follow-up.
510    let rewritten = rewrite_memory_grow_zero(wasm_ops);
511    // #494 phase 2b: the fact-spec guard-elision marks are keyed by op index
512    // into the stream the DRIVER handed us. The memory.grow(0) fold above can
513    // only shift indices AT OR AFTER a `memory.grow` — an op the fact-spec
514    // walk never crosses (it stops at the first untracked op, so no mark can
515    // follow one). Defense in depth: if the fold fired at all, drop the marks
516    // loudly rather than risk keying a guard elision to the wrong op.
517    //
518    // VCR-MEM-004 (#901): scry's externally-proven bounds-guard marks ride the
519    // SAME defensive gate for the SAME reason — they are op-index keyed, so an
520    // index shift would strip the guard off the wrong access. They are unioned
521    // with #494's certificate-discharged marks here (one consumption point,
522    // two authorities; `CompileConfig` keeps them separate so the attestation
523    // can say which one covered each site).
524    let (fact_div_zero_elide, fact_div_ovf_elide, mem_bounds_elide): (
525        &[usize],
526        &[usize],
527        Vec<usize>,
528    ) = if rewritten.len() == wasm_ops.len() {
529        let mut mem = config.fact_mem_bounds_elide.clone();
530        mem.extend_from_slice(&config.proven_safe_mem_elide);
531        mem.sort_unstable();
532        mem.dedup();
533        (&config.fact_div_zero_elide, &config.fact_div_ovf_elide, mem)
534    } else {
535        if !config.fact_div_zero_elide.is_empty()
536            || !config.fact_div_ovf_elide.is_empty()
537            || !config.fact_mem_bounds_elide.is_empty()
538        {
539            eprintln!(
540                "fact-spec: DECLINE guard elision marks dropped — the                      memory.grow(0) fold shifted op indices (#494 defensive gate);                      general lowering emitted"
541            );
542        }
543        if !config.proven_safe_mem_elide.is_empty() {
544            eprintln!(
545                "proven-safe: DECLINE {} bounds-guard elision mark(s) dropped — the \
546                 memory.grow(0) fold shifted op indices, so the (func, pc) keys no longer \
547                 name the accesses scry proved (VCR-MEM-004 defensive gate, #901); every \
548                 guard is retained",
549                config.proven_safe_mem_elide.len()
550            );
551        }
552        (&[], &[], Vec::new())
553    };
554    let wasm_ops: &[WasmOp] = &rewritten;
555
556    // #457: `count_params` INFERS the param count from access patterns (a local
557    // whose first access is a read is assumed to be a param), so a
558    // read-before-write NON-PARAM local — which WASM zero-initializes — was
559    // indistinguishable from a param: it got homed in a parameter register and
560    // read caller garbage instead of 0. The driver supplies the DECLARED count
561    // (`current_func_param_count`, from the module's type section) to settle it.
562    //
563    // #970 (RQ-57-CONDPARAM): see [`effective_num_params`] for the bound and
564    // why the read-first inference is not it.
565    let inferred_params = count_params(wasm_ops);
566    let num_params = effective_num_params(wasm_ops, config);
567    // A read-before-write non-param local exists iff the ACCESS-PATTERN
568    // inference overshot the declared count — the read-first rule can only
569    // exceed it via a read-first index >= the declared count, which is exactly
570    // such a local. (Unchanged by #970: `referenced >= inferred` always, so
571    // `num_params < inferred_params` still holds iff `inferred > declared`;
572    // stated directly here rather than left to that algebra.)
573    let has_rbw_local = match config.current_func_param_count {
574        Some(declared) => inferred_params > declared,
575        None => false,
576    };
577
578    let bounds_config = match config.effective_safety_bounds() {
579        SafetyBounds::None => BoundsCheckConfig::None,
580        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
581        SafetyBounds::Software => BoundsCheckConfig::Software,
582        SafetyBounds::Mask => {
583            // #651 (mirroring the RISC-V backend's compile-time decline):
584            // index masking wraps `ea & (size-1)` — a modulo only when the
585            // linear-memory size is a power of two. With a non-power-of-two
586            // size the AND would silently REMAP in-bounds addresses (e.g.
587            // 0x18000 & 0x2FFFF = 0x8000 for a 192 KiB memory). Decline
588            // loudly rather than miscompile.
589            //
590            // RQ-57-SENTINEL (#953 sibling): `bytes == 0` used to be EXEMPT
591            // from this check, because 0 was read as "unknown — plain
592            // per-function path, no module context". But 0 is also exactly
593            // what a module declaring `(memory 0)` produces, and for that
594            // module the emitted guard (`SUB R12, R10, #1; AND addr, R12`,
595            // R10 = 0 baked by the startup) computes `0 - 1 = 0xFFFFFFFF` —
596            // an IDENTITY mask. Every access then executes unmasked at
597            // `[R11 + addr]` for any 32-bit addr: an unbounded OOB read/write
598            // in the mode whose purpose is bounding. Same sentinel/value
599            // collision as #932/#953, third backend-mode instance.
600            //
601            // 0 now means what #953 made it mean everywhere: a zero-byte
602            // memory. No mask can bound an access into a memory with no bytes
603            // (wasm semantics: every access traps), and wrap-not-trap has
604            // nothing to wrap into — refuse. Callers with no module context
605            // must state the size (the #953 contract; the CLI single-function
606            // path now threads the module's declared size for all backends).
607            let bytes = config.linear_memory_bytes;
608            if bytes == 0 {
609                return Err("--safety-bounds mask: the linear memory has ZERO bytes \
610                     (`(memory 0)`, or a driver that did not state the size) — \
611                     every access is out of bounds and a mask cannot express a \
612                     trap. Use --safety-bounds software (traps every access) \
613                     or declare a non-zero memory (RQ-57-SENTINEL, #953)"
614                    .to_string());
615            }
616            if !bytes.is_power_of_two() {
617                return Err(format!(
618                    "--safety-bounds mask requires a power-of-two linear-memory \
619                     size, got {bytes} bytes — switch to --safety-bounds software \
620                     for the deterministic check (#651)"
621                ));
622            }
623            BoundsCheckConfig::Masking
624        }
625    };
626
627    // The non-optimized (direct) instruction-selection path. Handles f32 via
628    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
629    // when the optimized path declines a module (see issue #120 below).
630    //
631    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
632    // `spill_on_exhaustion` set only on the retry — the first pass is the
633    // unmodified default, so every function that compiles today is selected by
634    // exactly the code that compiled it yesterday (bit-identity is structural,
635    // not behavioural).
636    // #1321: the allocator spill areas the direct selector reserved for the
637    // attempt that actually produced the returned stream, as
638    // `(frame_size, areas)`. Written only on a SUCCESSFUL selection, so after
639    // the recovery ladder it holds the rung that won. Left `None` on the
640    // optimized path, which supplies no layout — and `None` means "police every
641    // offset", i.e. exactly today's behaviour.
642    let selected_spill_areas: std::cell::RefCell<Option<(i32, Vec<std::ops::Range<i32>>)>> =
643        std::cell::RefCell::new(None);
644    // RQ-71-VFPALIAS (#881/#1069): the companion record — the PERMANENT frame
645    // homes of frame-resident f32/f64 locals. Kept beside the spill areas rather
646    // than folded into them because it is a different KIND of fact: the areas say
647    // where the allocator's slots live, this says which offsets inside that same
648    // pool are a wasm local's own home and carry no single-value obligation.
649    let selected_vfp_frame_homes: std::cell::RefCell<Option<(i32, Vec<i32>)>> =
650        std::cell::RefCell::new(None);
651    let select_direct_attempt = |spill_on_exhaustion: bool,
652                                 param_backing_on_exhaustion: bool,
653                                 local_promote: bool,
654                                 i64_spill_slots: Option<usize>,
655                                 vfp_spill_on_exhaustion: bool,
656                                 vfp_frame_home_locals: bool,
657                                 vfp_wide_file: bool|
658     -> Result<Vec<ArmInstruction>, synth_core::Error> {
659        let db = RuleDatabase::with_standard_rules();
660        let mut selector =
661            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
662        selector.set_target(config.target.fpu, &config.target.triple);
663        if config.num_imports > 0 {
664            selector.set_num_imports(config.num_imports);
665        }
666        // #195: plumb the callee argument-count tables so the direct selector can
667        // marshal call arguments into R0–R3 per AAPCS.
668        selector.set_func_arg_counts(
669            config.func_arg_counts.clone(),
670            config.type_arg_counts.clone(),
671        );
672        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
673        // imports (rewritten to the wasm field name by build_relocatable_elf)
674        // instead of `__meld_dispatch_import`.
675        selector.set_relocatable(config.relocatable);
676        // #642: call_indirect guard inputs (compile-time table size for the
677        // bounds guard + closed-world type verdicts). Without them, every
678        // call_indirect lowering declines loudly.
679        selector.set_call_indirect_guards(config.call_indirect_guards.clone());
680        // #275: on the self-contained image path (NOT --relocatable) the R11
681        // funcref-table dispatch is a silent miscompile — the region is only
682        // populated by an external runtime, which a self-contained ELF does
683        // not have, so the dispatch would read function pointers from
684        // linear-memory data. Two outcomes:
685        //  - the Thumb-2 `--cortex-m` image path (CLI-flagged: the builder
686        //    that emits and patches the flash-resident funcref table will
687        //    run) lowers call_indirect through that table, PC-relative,
688        //    never via R11;
689        //  - every OTHER self-contained configuration (A32/Cortex-R5, the
690        //    simple-ELF builder, imports present) keeps the loud decline.
691        // The host-linked (--relocatable) path keeps the guarded R11
692        // dispatch: there a runtime places the table region at R11.
693        let self_contained_table = config.self_contained_funcref_table
694            && matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
695        selector
696            .set_reject_self_contained_call_indirect(!config.relocatable && !self_contained_table);
697        selector.set_self_contained_funcref_table(self_contained_table);
698        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
699        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
700        // VCR-MEM-002 phase 1 (#406): per-memory initial page counts — enables
701        // the multi-memory arms (memory-0 lowering never reads it; empty ⇒
702        // every multi-memory op declines loudly).
703        selector.set_memory_pages(config.memory_pages.clone());
704        // #311: i64 call results are register PAIRS — tag them.
705        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
706        // #1210: per-function result COUNT (0 = void) — `func_ret_i64` alone
707        // cannot tell a void callee from an i32-returning one.
708        selector.set_func_result_counts(config.func_result_counts.clone());
709        // #359: declared param widths of THIS function, so the AAPCS stack-arg
710        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
711        selector.set_params_i64(config.current_func_params_i64.clone());
712        // GI-FPU-002 (#619/#369): declared f32-param mask — home hard-float f32
713        // args in S0..S15 (AAPCS-VFP) instead of the R0..R3 integer path.
714        selector.set_params_f32(config.current_func_params_f32.clone());
715        // GI-FPU-002 phase 2 (#369): declared f64-param mask — hard-float
716        // targets decline f64-param functions loudly (no D-register homing yet).
717        selector.set_params_f64(config.current_func_params_f64.clone());
718        // GI-FPU-002 phase 2 (#719/#369): THIS function's f32/f64 return flag, so
719        // the epilogue loudly declines a float result reaching it in a core
720        // register (never a silent integer R0 return where a caller reads S0/D0).
721        selector.set_ret_float(config.current_func_ret_f32, config.current_func_ret_f64);
722        // GI-FPU-002 phase 3 (#369): per-callee float-signature tables. `Call`
723        // marshals the AAPCS-VFP boundary from these (float args into S0../D0..,
724        // float results out of S0/D0); `CallIndirect` still declines a
725        // float-returning static type loudly.
726        selector.set_float_call_signatures(
727            config.func_ret_f32.clone(),
728            config.func_ret_f64.clone(),
729            config.type_ret_f32.clone(),
730            config.type_ret_f64.clone(),
731            config.func_params_f32.clone(),
732            config.func_params_f64.clone(),
733        );
734        // #509: blocktype-arity side-table of THIS function, so value-carrying
735        // br/br_if/br_table land the carried value in the target block's
736        // designated result register instead of dropping it. Empty ⇒ legacy
737        // void-block lowering.
738        selector.set_block_arity(config.current_func_block_arity.clone());
739        // #1214: THIS function's declared-i64-local side-table — see
740        // `compute_local_layout`'s use of it. Empty ⇒ exactly the prior
741        // dataflow-only width inference.
742        selector.set_declared_i64_locals(config.current_func_declared_i64_locals.clone());
743        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
744        // gating here keeps every non-native compile (all frozen fixtures) on the
745        // legacy R9 globals-table path, bit-identical.
746        if config.native_pointer_abi
747            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
748        {
749            selector.set_native_pointer_stack(sp_idx, sp_init);
750        }
751        // #643: per-global slot widths — i64/f64 globals occupy 8-byte slots
752        // (register-pair store/load) and shift every later global's offset.
753        // Empty for i32-only modules ⇒ the legacy `idx * 4` layout, unchanged.
754        selector.set_global_widths(config.global_widths.clone());
755        selector.set_spill_on_exhaustion(spill_on_exhaustion);
756        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
757        // #881 (VCR-RA-004): VFP register-file spilling, set ONLY on the retry
758        // after an attempt failed with a GI-FPU-002 exhaustion Err — functions
759        // that compile without it keep byte-identical output by construction.
760        selector.set_vfp_spill_on_exhaustion(vfp_spill_on_exhaustion);
761        // #1069: LAST-resort residence lever — set ONLY by the final VFP
762        // retry below, after the plain #881 rung also exhausted, so every
763        // function that compiles through base path or plain rung is produced
764        // by exactly yesterday's path (byte-identity is structural).
765        selector.set_vfp_frame_home_locals(vfp_frame_home_locals);
766        // RQ-67-VFPREACH (#1267): the AAPCS callee-saved VFP half.
767        selector.set_vfp_wide_file(vfp_wide_file);
768        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
769        // retry after an attempt failed with the slot-pool-exhausted Err —
770        // functions that compile with the default pool keep their frame
771        // byte-identical by construction.
772        if let Some(slots) = i64_spill_slots {
773            selector.set_i64_spill_slots(slots);
774        }
775        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
776        // in callee-saved registers instead of frame slots — the structural lever
777        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
778        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
779        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
780        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
781        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
782        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
783        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
784        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
785        // which on a dense function leaves the spill allocator with nothing to
786        // free → the frame-slot path is the escape that restores compilability).
787        selector.set_local_promote(local_promote);
788        // #494 phase 2b: certificate-discharged div/rem trap-guard elision
789        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
790        selector
791            .set_fact_div_guard_elisions(fact_div_zero_elide.to_vec(), fact_div_ovf_elide.to_vec());
792        // #494 bounds-elision + VCR-MEM-004 (#901): per-site memory
793        // bounds-guard marks, unioned above. Empty in every compile without
794        // SYNTH_FACT_SPEC + facts or --proven-safe.
795        selector.set_fact_mem_bounds_elisions(mem_bounds_elide.clone());
796        let selected = selector.select_with_stack(wasm_ops, num_params);
797        if selected.is_ok() {
798            // #1321: only a SUCCESSFUL attempt's layout describes the stream we
799            // return; a failed rung's frame is discarded with it.
800            *selected_spill_areas.borrow_mut() = selector.frame_spill_areas().cloned();
801            *selected_vfp_frame_homes.borrow_mut() = selector.vfp_frame_home_halves().cloned();
802        }
803        selected
804    };
805    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
806        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
807        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
808        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
809        // The full exhaustion-recovery ladder, parameterized on whether local
810        // promotion is enabled. Each rung is reached only when the previous one
811        // returned a recoverable register-exhaustion Err, so a function that
812        // compiles on the first attempt is untouched by the later rungs. Returns
813        // the result AND which rung produced it (for the #242 measurement below).
814        let recovery_ladder =
815            |promote: bool,
816             i64_spill_slots: Option<usize>,
817             vfp_spill: bool,
818             vfp_frame: bool,
819             vfp_wide: bool|
820             -> (Result<Vec<ArmInstruction>, synth_core::Error>, &'static str) {
821                let mut attempt = select_direct_attempt(
822                    false,
823                    false,
824                    promote,
825                    i64_spill_slots,
826                    vfp_spill,
827                    vfp_frame,
828                    vfp_wide,
829                );
830                let mut rung = "base";
831                // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
832                // hard-fail is recoverable — retry with spill-on-exhaustion, which
833                // reserves the spill area and spills the deepest stack value when
834                // the pool is full.
835                if let Err(e) = &attempt
836                    && e.to_string().contains(SINGLE_EXHAUSTION)
837                {
838                    attempt = select_direct_attempt(
839                        true,
840                        false,
841                        promote,
842                        i64_spill_slots,
843                        vfp_spill,
844                        vfp_frame,
845                        vfp_wide,
846                    );
847                    rung = "spill";
848                }
849                // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
850                // exhaustion is recoverable too — not by stack spilling (the pair
851                // allocator already spills stack values, #171) but by frame-backing
852                // the params (#204) so they stop pinning R0-R3, with spill kept on.
853                if let Err(e) = &attempt
854                    && e.to_string().contains(PAIR_EXHAUSTION)
855                {
856                    attempt = select_direct_attempt(
857                        true,
858                        true,
859                        promote,
860                        i64_spill_slots,
861                        vfp_spill,
862                        vfp_frame,
863                        vfp_wide,
864                    );
865                    rung = "param-backing";
866                }
867                (attempt, rung)
868            };
869        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
870        // must never be the reason a function fails to compile. Run the full ladder
871        // with promotion first (so every function that compiles today is
872        // bit-identical), and if it still ends in register exhaustion, fall back to
873        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
874        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
875        // pins r4-r8 for the locals; on a dense function that leaves the allocator
876        // with nothing to free, so dropping it restores compilability. The fallback
877        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
878        // output is untouched by construction (frozen byte gate stays green).
879        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
880        // RQ-69-FALCON (#1318): per-rung reporting, because the summary line
881        // below CANNOT distinguish the two failures it is asked about. `rung`
882        // is only assigned when an attempt SUCCEEDS, so a function that climbs
883        // the whole ladder and exhausts every rung prints `rung=base
884        // result=exhausted` — identical to one that never climbed at all. Worse,
885        // the Err the caller finally reports is stage 2's, so a stage-3
886        // (wide-file) failure is invisible even in the user-facing message:
887        // #1318's `step` reports the #1069 slot-pool message while the wide-file
888        // rung it also failed says nothing. Measured on the reporter's module
889        // before this was written; reading the source was the only way to tell
890        // which of the two had happened.
891        //
892        // Logging only, behind the same env var, so emitted bytes are unchanged
893        // and the frozen byte gate is unaffected.
894        let stats = std::env::var("SYNTH_RECOVERY_STATS").is_ok();
895        // Every rung's Err, in attempt order (#1318). The ladder keeps the
896        // EARLIER attempt's Err whenever a later rung also fails — stage 3
897        // falls back to stage 2's `fh`, each pool-grow falls back to its
898        // ungrown attempt — so the reporter of #1318 was told "spill-slot pool
899        // exhausted" while the wall three of the four rungs actually hit was
900        // the VSTR/VLDR [sp,#imm] window. Reporting the LAST rung's Err is no
901        // better: the last rung attempted is the wide-file one, whose Err is
902        // the pool message again. So report what was actually tried, deduped.
903        // Control flow is untouched — every rung still runs exactly when it
904        // ran before, and the substrings other code matches on are all still
905        // present in the joined message.
906        let tried: std::cell::RefCell<Vec<(String, String)>> = std::cell::RefCell::new(Vec::new());
907        let note = |name: &str, r: &Result<Vec<ArmInstruction>, synth_core::Error>| {
908            if let Err(e) = r {
909                let m = e.to_string();
910                let first = m.lines().next().unwrap_or("").to_string();
911                tried.borrow_mut().push((name.to_string(), first));
912            }
913            if stats {
914                match r {
915                    Ok(_) => eprintln!("[recovery-stats]   tried rung={name} -> ok"),
916                    Err(e) => {
917                        let m = e.to_string();
918                        let first = m
919                            .lines()
920                            .next()
921                            .unwrap_or("")
922                            .chars()
923                            .take(140)
924                            .collect::<String>();
925                        eprintln!("[recovery-stats]   tried rung={name} -> exhausted: {first}");
926                    }
927                }
928            }
929        };
930        // The full pre-#587 recovery sequence (promotion-on ladder, then the
931        // #474 promotion-off fallback), parameterized on the pool size so the
932        // pool-grow retry below reruns it verbatim.
933        let full_sequence = |slots: Option<usize>,
934                             vfp_spill: bool,
935                             vfp_frame: bool,
936                             vfp_wide: bool|
937         -> (
938            Result<Vec<ArmInstruction>, synth_core::Error>,
939            &'static str,
940            bool,
941        ) {
942            let (mut attempt, mut rung) =
943                recovery_ladder(promote, slots, vfp_spill, vfp_frame, vfp_wide);
944            let mut promotion_dropped = false;
945            if promote
946                && attempt
947                    .as_ref()
948                    .err()
949                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
950            {
951                let (rescued, off_rung) =
952                    recovery_ladder(false, slots, vfp_spill, vfp_frame, vfp_wide);
953                if rescued.is_ok() {
954                    attempt = rescued;
955                    rung = off_rung;
956                    promotion_dropped = true;
957                }
958            }
959            (attempt, rung, promotion_dropped)
960        };
961        let (mut attempt, mut rung, mut promotion_dropped) =
962            full_sequence(None, false, false, false);
963        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
964        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
965        // an i64-dense function simply has more values simultaneously live than
966        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
967        // modes) with the pool sized from a conservative operand-stack-depth
968        // bound: the number of simultaneously spilled values can never exceed
969        // the operand-stack depth, plus a few transient slots (the arg-move
970        // cycle resolver and call-result parking each borrow one). The selector
971        // clamps the request to its 12-bit-friendly cap; a function that still
972        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
973        // promotion-off fallback — so any function that compiled yesterday
974        // (through any rung or fallback) is produced by exactly yesterday's
975        // path, byte-identical; the grown pool only ever fires for functions
976        // whose every existing escape ended in the slot-pool Err.
977        if attempt
978            .as_ref()
979            .err()
980            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
981        {
982            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
983            let (grown, _, grown_dropped) =
984                full_sequence(Some(depth.saturating_add(4)), false, false, false);
985            note("pool-grow", &grown);
986            if grown.is_ok() {
987                attempt = grown;
988                rung = "pool-grow";
989                promotion_dropped = grown_dropped;
990            }
991        }
992        // #881 (VCR-RA-004): the GI-FPU-002 VFP register-file exhaustion is
993        // recoverable too — retry the ENTIRE sequence with VFP spilling
994        // enabled (the pre-op pressure guard spills the deepest segment-local
995        // f32/f64 stack value into the shared spill area and reloads spilled
996        // operands before their consumers). Deliberately LAST, after every
997        // integer rung, so any function that compiled yesterday is produced
998        // by exactly yesterday's path; the VFP rung only ever fires for
999        // functions whose every existing escape ended in a GI-FPU-002
1000        // exhaustion Err (previously an unconditional loud skip). A VFP-
1001        // spilling function can in turn exhaust the shared slot pool — the
1002        // #587 pool-grow retry composes inside the rung.
1003        const VFP_S_EXHAUSTION: &str = "VFP register file exhausted";
1004        const VFP_D_EXHAUSTION: &str = "VFP D-register file exhausted";
1005        if attempt.as_ref().err().is_some_and(|e| {
1006            let msg = e.to_string();
1007            msg.contains(VFP_S_EXHAUSTION) || msg.contains(VFP_D_EXHAUSTION)
1008        }) {
1009            // Stage 1 — the plain #881 rung, exactly yesterday's path
1010            // (sequence, pool sizing and all): any function it rescues is
1011            // byte-identical to what it shipped yesterday, by construction.
1012            let (vfp, vfp_rung, vfp_dropped) = full_sequence(None, true, false, false);
1013            note("vfp-spill", &vfp);
1014            let (vfp, vfp_rung, vfp_dropped) = if vfp.as_ref().err().is_some_and(|e| {
1015                let msg = e.to_string();
1016                msg.contains(SLOT_EXHAUSTION) || msg.contains("spilling the VFP register file")
1017            }) {
1018                let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
1019                let (grown, grown_rung, grown_dropped) =
1020                    full_sequence(Some(depth.saturating_add(4)), true, false, false);
1021                note("vfp-spill+pool-grow", &grown);
1022                if grown.is_ok() {
1023                    (grown, grown_rung, grown_dropped)
1024                } else {
1025                    (vfp, vfp_rung, vfp_dropped)
1026                }
1027            } else {
1028                (vfp, vfp_rung, vfp_dropped)
1029            };
1030            if vfp.is_ok() {
1031                attempt = vfp;
1032                rung = match vfp_rung {
1033                    "base" => "vfp-spill",
1034                    _ => "vfp-spill+int",
1035                };
1036                promotion_dropped = vfp_dropped;
1037            } else {
1038                // Stage 2 (#1069, RQ-60-VFPPRESSURE increment 2) — LAST
1039                // resort: the plain rung ALSO failed, i.e. the pressure is
1040                // not (only) operand-stack values but PINNED LOCAL HOMES,
1041                // which the #881 victim search rightly never touches (a home
1042                // lives for the function's extent). Rerun the entire
1043                // sequence with frame-homed overflow locals: a fresh
1044                // f32/f64 local whose home grant would pin above the S7/D3
1045                // cap lives in the frame from its first def. Reached ONLY by
1046                // functions that failed every prior escape, so nothing that
1047                // compiles today moves a byte.
1048                let (fh, fh_rung, fh_dropped) = full_sequence(None, true, true, false);
1049                note("vfp-frame-locals", &fh);
1050                let (fh, fh_rung, fh_dropped) = if fh.as_ref().err().is_some_and(|e| {
1051                    let msg = e.to_string();
1052                    // The frame-homed-local slot demand (a PERMANENT slot per
1053                    // frame-resident float local) is a third way the shared
1054                    // pool exhausts — its trigger substring is the selector's
1055                    // own pub const, not a second copy that could drift (the
1056                    // #881 substring-is-control-flow lesson, pinned red-first
1057                    // by the live24 fixture test).
1058                    msg.contains(SLOT_EXHAUSTION)
1059                        || msg.contains("spilling the VFP register file")
1060                        || msg.contains(
1061                            synth_synthesis::instruction_selector::VFP_FRAME_HOME_SLOT_EXHAUSTION,
1062                        )
1063                }) {
1064                    let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
1065                    // Frame-homed locals hold their slots for the function's
1066                    // extent, OUTSIDE the operand-stack depth bound — size
1067                    // the grown pool for both. Distinct `local.set`/
1068                    // `local.tee` targets over-approximate the frame-homed
1069                    // local count; the selector clamps the request to its
1070                    // cap, and a function that still exhausts stays an
1071                    // honest loud skip.
1072                    let local_targets: std::collections::HashSet<u32> = wasm_ops
1073                        .iter()
1074                        .filter_map(|op| match op {
1075                            synth_synthesis::WasmOp::LocalSet(i)
1076                            | synth_synthesis::WasmOp::LocalTee(i) => Some(*i),
1077                            _ => None,
1078                        })
1079                        .collect();
1080                    let (grown, grown_rung, grown_dropped) = full_sequence(
1081                        Some(depth.saturating_add(local_targets.len()).saturating_add(4)),
1082                        true,
1083                        true,
1084                        false,
1085                    );
1086                    note(
1087                        &format!(
1088                            "vfp-frame-locals+pool-grow({})",
1089                            depth.saturating_add(local_targets.len()).saturating_add(4)
1090                        ),
1091                        &grown,
1092                    );
1093                    if grown.is_ok() {
1094                        (grown, grown_rung, grown_dropped)
1095                    } else {
1096                        (fh, fh_rung, fh_dropped)
1097                    }
1098                } else {
1099                    (fh, fh_rung, fh_dropped)
1100                };
1101                if fh.is_ok() {
1102                    attempt = fh;
1103                    rung = match fh_rung {
1104                        "base" => "vfp-frame-locals",
1105                        _ => "vfp-frame-locals+int",
1106                    };
1107                    promotion_dropped = fh_dropped;
1108                } else {
1109                    // Stage 3 (#1267, RQ-67-VFPREACH) — THE LAST RESORT, and the
1110                    // reach half of #1204's root shape. Every escape above has
1111                    // now ended in GI-FPU-002, so this function DECLINES today.
1112                    //
1113                    // It declines against HALF the register file: synth
1114                    // allocates S0-S15/D0-D7 because S16-S31/D8-D15 are AAPCS
1115                    // CALLEE-saved and, until this release, nothing could save
1116                    // them — VPUSH/VPOP did not exist in the encoder. Every FPU
1117                    // target synth supports actually has D0-D15 = S0-S31.
1118                    //
1119                    // Reached ONLY here, so a function that compiles today is
1120                    // produced by exactly today's path and cannot move a byte —
1121                    // the #881 rung discipline, measured over the corpus rather
1122                    // than asserted. The selector emits the VPUSH/VPOP pair and
1123                    // REFUSES functions with stack-passed params (#1273), so a
1124                    // failure here stays the honest loud decline it already was.
1125                    let (wide, wide_rung, wide_dropped) = full_sequence(None, true, true, true);
1126                    note("vfp-wide-file", &wide);
1127                    if wide.is_ok() {
1128                        attempt = wide;
1129                        rung = match wide_rung {
1130                            "base" => "vfp-wide-file",
1131                            _ => "vfp-wide-file+int",
1132                        };
1133                        promotion_dropped = wide_dropped;
1134                    } else {
1135                        attempt = fh;
1136                        promotion_dropped = fh_dropped;
1137                    }
1138                }
1139            }
1140        }
1141        // VCR-RA measurement (#242): log which recovery rung produced the result,
1142        // so the per-rung distribution across a corpus can be measured — the size
1143        // of the failure surface a verified allocator must subsume (see
1144        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
1145        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
1146        if stats {
1147            // `rung` holds the last SUCCESSFUL rung; on total exhaustion it is
1148            // still "base", which said nothing about how far the ladder climbed
1149            // (#1318). Report it as `none` and let the per-rung lines above
1150            // carry the detail.
1151            let rung = if attempt.is_ok() { rung } else { "none" };
1152            eprintln!(
1153                "[recovery-stats] rung={rung}{} result={}",
1154                if promotion_dropped {
1155                    " promotion-off"
1156                } else {
1157                    ""
1158                },
1159                if attempt.is_ok() { "ok" } else { "exhausted" },
1160            );
1161        }
1162        attempt.map_err(|e| {
1163            // The kept Err first (so every substring any caller or test matches
1164            // on is exactly where it was), then the rungs that were tried and
1165            // what each one hit. Deduped by message: three rungs reporting one
1166            // wall should say so once, and name the three (#1318).
1167            let base = format!("instruction selection failed: {}", e);
1168            let rungs = tried.borrow();
1169            if rungs.len() < 2 {
1170                return base;
1171            }
1172            let mut by_msg: Vec<(String, Vec<String>)> = Vec::new();
1173            for (rung, msg) in rungs.iter() {
1174                match by_msg.iter_mut().find(|(m, _)| m == msg) {
1175                    Some((_, names)) => names.push(rung.clone()),
1176                    None => by_msg.push((msg.clone(), vec![rung.clone()])),
1177                }
1178            }
1179            let detail = by_msg
1180                .iter()
1181                .map(|(msg, names)| format!("{} -> {}", names.join(" + "), msg))
1182                .collect::<Vec<_>>()
1183                .join(" | ");
1184            format!("{base} [every recovery rung failed: {detail}]")
1185        })
1186    };
1187
1188    // Instruction selection: optimized or direct.
1189    //
1190    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
1191    // optimized path materializes an absolute linmem base (0x20000100) and does
1192    // not preserve caller-saved registers across calls — both wrong for a
1193    // host-linked object, where the linmem base arrives via `fp` at runtime and
1194    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
1195    // #171) handles fp-relative memory + caller-saved preservation correctly.
1196    //
1197    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
1198    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
1199    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
1200    // SILENT miscompile (every input hits the last arm). The selector value isn't
1201    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
1202    // to fall back on; detect it on the raw wasm op stream here and force the
1203    // direct selector (`select_with_stack` lowers `br_table` correctly as a
1204    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
1205    // contract as the issue-#120 f32 decline: the function still compiles
1206    // correctly, just without IR-level optimization. Frozen-safe: the frozen
1207    // fixtures compile `--relocatable` (already direct), and no optimized-path
1208    // fixture (control_step, flight_algo) contains `br_table`.
1209    let has_br_table = wasm_ops
1210        .iter()
1211        .any(|op| matches!(op, WasmOp::BrTable { .. }));
1212    // #509: the optimized path also drops the value carried by a `br`/`br_if`
1213    // to a result-typed block (the taken edge returns the wrong arm's value —
1214    // same silent-miscompile class as the #507 br_table drop). Route the shape
1215    // to the direct selector, whose designated-result-register lowering (#509)
1216    // lands the carried value at the join. Never fires for void-block control
1217    // flow (all frozen/optimized fixtures), so those stay byte-identical.
1218    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
1219    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
1220    // direct selector. The optimized path's param homing is width-naive — its
1221    // #518 decline covers only functions that READ an i64 param (an `I64Load`
1222    // from a param index), so a function that reads an i32 param whose AAPCS
1223    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
1224    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
1225    // silently miscompiled rather than falling back. The direct selector's
1226    // `aapcs_param_layout` homing handles every such shape (i64-param READS
1227    // already fell back to it via the ir_to_arm Err, so those functions emit
1228    // the same bytes as before). `num_params` counts read-first locals, so a
1229    // function that never touches any param keeps the optimized path.
1230    let has_wide_param = config
1231        .current_func_params_i64
1232        .iter()
1233        .take(num_params as usize)
1234        .any(|&w| w);
1235    // #782(b): a HARD-float (FPU) target passes f32 args in VFP S-registers
1236    // and returns floats in S0/D0 (AAPCS-VFP) — but the optimized path's
1237    // param/return homing is float-naive (integer R0..R3 args, R0 return). A
1238    // function whose ops ALL lower on the optimized path but whose SIGNATURE
1239    // carries a float — e.g. the pure value-pick
1240    // `(param f32 f32 i32) (result f32) select`, no float OP to trip the
1241    // issue-#120 ir_to_arm fallback — was silently compiled with the integer
1242    // ABI: callers marshal S0/S1, the body reads R0/R1. Route every
1243    // float-signature function to the direct selector (AAPCS-VFP homing, or
1244    // an honest decline). Soft-float targets (no FPU) keep the optimized
1245    // path: the integer treatment IS the ABI there — byte-identical. (f64
1246    // params already route direct via `has_wide_param`; this adds f32 params
1247    // and f32/f64 returns.)
1248    let has_float_sig = config.target.fpu.is_some()
1249        && (config.current_func_ret_f32
1250            || config.current_func_ret_f64
1251            || config
1252                .current_func_params_f32
1253                .iter()
1254                .take(num_params as usize)
1255                .any(|&f| f)
1256            || config
1257                .current_func_params_f64
1258                .iter()
1259                .take(num_params as usize)
1260                .any(|&f| f));
1261    // #494 phase 2b: div/rem guard-elision marks are consumed by the DIRECT
1262    // selector only — the optimized path's IR passes (const-fold/CSE/DCE)
1263    // renumber instructions, so an op-index-keyed mark cannot soundly survive
1264    // them. Route marked functions direct (the #507/#509 honest-degradation
1265    // pattern). Never fires without SYNTH_FACT_SPEC + facts + a discharged
1266    // obligation, so every existing compile keeps its path byte-identical.
1267    let has_fact_div_elide = !fact_div_zero_elide.is_empty()
1268        || !fact_div_ovf_elide.is_empty()
1269        // #494 bounds-elision + VCR-MEM-004 (#901): memory bounds-guard marks
1270        // are direct-selector keyed for the same reason (IR passes renumber
1271        // instructions). This is ALSO why the optimized path's
1272        // `push_software_bounds_guard` sites never need mark plumbing: a
1273        // marked function is routed away from that path entirely.
1274        || !mem_bounds_elide.is_empty();
1275    // #643: the optimized path's global lowering is width-naive — `GlobalGet`/
1276    // `GlobalSet` are single-word `[R9, idx*4]` accesses, which (a) silently
1277    // dropped the high word of every i64 global and (b) mis-address every
1278    // global whose offset an earlier wide (i64/f64) slot shifted. When the
1279    // module has any wide global, route every global-touching function to the
1280    // direct selector, whose type-aware summed layout pairs the access (or
1281    // declines loudly). Modules with only 4-byte globals — every existing
1282    // fixture — keep the optimized path byte-identical.
1283    let has_wide_global_module = config.global_widths.iter().any(|&w| w > 4);
1284    let has_global_access = has_wide_global_module
1285        && wasm_ops
1286            .iter()
1287            .any(|op| matches!(op, WasmOp::GlobalGet(_) | WasmOp::GlobalSet(_)));
1288    // VCR-VER-001 (#242): `post_exhaust` scopes the post-exhaustion cleanup
1289    // extensions to functions whose bytes the #580 spill-on-exhaustion
1290    // machinery actually shaped (bridge-reported). Everything else — the
1291    // direct path, non-exhausted optimized functions — stays byte-identical
1292    // flag-on (the `vcr_ver_001_gate_242` lock's contract).
1293    let (arm_instrs, post_exhaust) = if config.no_optimize
1294        || config.relocatable
1295        || has_br_table
1296        || has_value_carry
1297        || has_wide_param
1298        || has_float_sig
1299        || has_global_access
1300        || has_fact_div_elide
1301        // #457: route read-before-write non-param locals to the direct
1302        // selector, whose prologue zero-init lands the wasm-mandated 0.
1303        || has_rbw_local
1304    {
1305        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1306            // RQ-65-PARITY (#197): name WHICH pre-gate predicate diverted the
1307            // function and which function it was, so the selector-parity
1308            // oracle can record every "only one path accepted this" case with
1309            // its reason instead of a bare count. The leading text is kept
1310            // verbatim — the #377/#1021 harnesses match on it.
1311            let reasons: Vec<&str> = [
1312                (config.no_optimize, "no-optimize"),
1313                (config.relocatable, "relocatable"),
1314                (has_br_table, "br-table"),
1315                (has_value_carry, "value-carry"),
1316                (has_wide_param, "wide-param"),
1317                (has_float_sig, "float-sig"),
1318                (has_global_access, "wide-global-access"),
1319                (has_fact_div_elide, "fact-elide"),
1320                (has_rbw_local, "rbw-local"),
1321            ]
1322            .iter()
1323            .filter(|(on, _)| *on)
1324            .map(|(_, name)| *name)
1325            .collect();
1326            eprintln!(
1327                "[path-debug] direct (pre-gate) func={} reasons={}",
1328                config
1329                    .current_func_index
1330                    .map_or("?".to_string(), |i| i.to_string()),
1331                reasons.join(",")
1332            );
1333        }
1334        (select_direct()?, false)
1335    } else {
1336        let opt_config = if config.loom_compat {
1337            OptimizationConfig::loom_compat()
1338        } else {
1339            OptimizationConfig::all()
1340        };
1341
1342        let mut bridge = OptimizerBridge::with_config(opt_config);
1343        // #188: tell the bridge how many imports there are so it declines only
1344        // LOCAL calls (and leaves import calls on the optimized path, keeping
1345        // the #173 field-name relocation rewrite intact).
1346        bridge.set_num_imports(config.num_imports);
1347        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
1348        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
1349        // levers — base-CSE (#468) excludes any access inside a marked range
1350        // from its fold set, and the bridge-level const-CSE declines wholesale
1351        // while any range is marked. Empty (the default) ⇒ byte-identical.
1352        bridge.set_volatile_segments(config.volatile_segments.clone());
1353        // #377: thread `--safety-bounds` to the bridge. Pre-fix the optimized
1354        // path ignored it — `software`/`mask` were SILENT NO-OPS on the path
1355        // that lowers the bulk of a flight loop's i32 loads/stores (byte-
1356        // identical to `none`, while the safety manifest claimed otherwise).
1357        // `Software` now emits the inline guard per access; `Masking` declines
1358        // memory-accessing functions to the direct selector; `None`/`Mpu` are
1359        // byte-identical to before.
1360        bridge.set_bounds_check(bounds_config);
1361        // #687: thread the absolute linear-memory base the optimized path
1362        // materializes. Defaults to 0x2000_0100 (byte-identical);
1363        // `--stack-layout=low` shifts it up by the reserved stack size so
1364        // const-address accesses follow the moved linear memory.
1365        bridge.set_linmem_base(config.linmem_base);
1366        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
1367        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
1368        // `optimize_full` failure: fall back to the direct selector rather
1369        // than propagating, so the function still compiles correctly.
1370        match bridge
1371            .optimize_full(wasm_ops)
1372            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
1373        {
1374            Ok(arm_ops) => {
1375                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1376                    eprintln!(
1377                        "[path-debug] optimized (ir_to_arm ok) func={}",
1378                        config
1379                            .current_func_index
1380                            .map_or("?".to_string(), |i| i.to_string())
1381                    );
1382                }
1383                (
1384                    arm_ops
1385                        .into_iter()
1386                        .map(|op| ArmInstruction {
1387                            op,
1388                            source_line: None,
1389                        })
1390                        .collect(),
1391                    bridge.spill_on_exhaust_fired(),
1392                )
1393            }
1394            // Issue #120: the optimized path declines modules it cannot lower
1395            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
1396            // back to the direct instruction selector, which handles f32 via
1397            // VFP/FPU. This is honest degradation: the function still compiles
1398            // correctly, just without IR-level optimization.
1399            Err(e) => {
1400                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1401                    eprintln!(
1402                        "[path-debug] direct (fallback: {e}) func={}",
1403                        config
1404                            .current_func_index
1405                            .map_or("?".to_string(), |i| i.to_string())
1406                    );
1407                }
1408                (select_direct()?, false)
1409            }
1410        }
1411    };
1412
1413    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
1414    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
1415    // fully tested), but it is **register-allocation-coupled**: over the current
1416    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
1417    // extends the live ranges of the mul inputs to the mla point, and the added
1418    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
1419    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
1420    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
1421    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
1422    // registers, at which point it becomes net-positive (per #272's plan and the
1423    // wiring design note). Lesson (#277): a register-pressure-affecting transform
1424    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
1425    // can default on.
1426
1427    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
1428    // LAST, after the immediate-folds — see the apply_const_cse call below
1429    // (#242). Earlier it ran here (before range-realloc and the folds), which is
1430    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
1431    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
1432    // would otherwise have absorbed the constant. Running CSE-last makes those
1433    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
1434    // redundant materializations.
1435
1436    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
1437    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
1438    // segment over the R0-R8 pool with value ranges as the allocation unit
1439    // (segment inputs + per-register live-outs pinned to their original
1440    // registers, reserved R9-R12/SP identity-assigned — each segment is
1441    // independently sound, no cross-segment liveness assumed). Renames
1442    // registers only: never adds, removes, or reorders instructions, so
1443    // labels/branch offsets are unaffected.
1444    //
1445    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
1446    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
1447    // flat_flight/controller/control_step, fires on the filter family with
1448    // zero cycle delta and a small size win, all selfchecks green on silicon.
1449    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
1450    // `SYNTH_REALLOC_STATS=1`.
1451    //
1452    // The companion dead callee-saved-save elimination (gale's "next
1453    // consequential lever", same issue comment) then shrinks the prologue
1454    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
1455    // registers the re-allocated body still touches (leaf-only,
1456    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
1457    // ~12 cycles of pure save/restore overhead removed on small leaves.
1458    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
1459    let (arm_instrs, ran_realloc) = if realloc_on {
1460        use synth_synthesis::rules::Reg;
1461        const POOL: [Reg; 9] = synth_synthesis::reg_contract::ALLOCATABLE;
1462        // VCR-DEC-001 (epic #242, the North Star's first foothold): the
1463        // SYNTH_GRAPH_ALLOC graph-colouring allocator SPIKE. When enabled it
1464        // replaces STEP 1 of the re-allocation (the segment-based
1465        // `reallocate_function`) with a whole-function Chaitin/Briggs colouring
1466        // (`graph_alloc::reallocate`) built against the SAME acceptance oracle
1467        // (`validate_segment_rewrite` trace-equality); the later dead-frame /
1468        // callee-saved-prologue / shrink passes still run on its output, so a
1469        // value it homes in R4-R8 still gets its callee-saved push (the
1470        // invariant the unconditional VCR-RA-003 validator guards). It is
1471        // BOUNDED to whole straight-line functions and DECLINES (returns None)
1472        // to the shipping `reallocate_function` on any control flow, spill, or
1473        // unmodeled op — never a hard-fail. Flag-OFF (`SYNTH_GRAPH_ALLOC` unset)
1474        // never enters this branch, so the shipping bytes are byte-identical
1475        // (the GOLDEN trick — frozen fixtures unchanged). NO default flip: the
1476        // spike ships flag-off; the flip is a later, evidence-gated step.
1477        //
1478        // VCR-VER-001 (#242): on a function the spill-on-exhaustion machinery
1479        // shaped, the terminal segment gets relaxed live-out pinning (only
1480        // R0/R1 are observable past `bx lr` at this pre-prologue position) so
1481        // the colourer can lower R4-R8-homed tails into caller-saved R0-R3 —
1482        // shrinking the `push {r4-r8,lr}` the #580 exhaustion shapes pay for.
1483        // `post_exhaust == false` selects the shipping pass bit for bit.
1484        let (out, stats) = if synth_synthesis::graph_alloc::enabled() {
1485            // RQ-60-RACOST increment 2 (#242): the colourer prices every
1486            // colour choice in REAL-ENCODER bytes. The sizer is the same
1487            // encoder family the emit loop below constructs — Thumb-2 (with
1488            // the target's FPU) or A32 — asked per candidate instruction, so
1489            // there is no hand size table to drift (#936). On the fixed-width
1490            // A32 ISA every candidate ties and the cost model degenerates to
1491            // the identity hint (zero churn).
1492            let sizing_encoder =
1493                if matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb) {
1494                    ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1495                } else {
1496                    ArmEncoder::new_arm32()
1497                };
1498            let enc = |op: &synth_synthesis::rules::ArmOp| {
1499                sizing_encoder.encode(op).ok().map(|b| b.len())
1500            };
1501            let stats_on = std::env::var("SYNTH_GRAPH_ALLOC_STATS").is_ok();
1502            match synth_synthesis::graph_alloc::reallocate(&arm_instrs, &POOL, &enc) {
1503                // SYNTH_GRAPH_ALLOC_FORCE (test seam, RQ-60-RACOST
1504                // increment 2): ship every validated candidate WITHOUT the
1505                // final-byte arbiter — the pre-arbiter behaviour. Used by
1506                // `vcr_dec_001_join_alloc_execution_differential.py` so the
1507                // unicorn-vs-wasmtime oracle executes the colourer's
1508                // proposals on EVERY reachable shape (call, i64-pair,
1509                // shift-expansion), not only the ones the arbiter lets ship —
1510                // an arbiter-declined candidate is still a candidate a future
1511                // change could promote, and the execution teeth must stay
1512                // ahead of that. Never set in production; the arbiter is the
1513                // shipping behaviour.
1514                Some(candidate)
1515                    if std::env::var("SYNTH_GRAPH_ALLOC_FORCE").is_ok_and(|v| v != "0") =>
1516                {
1517                    if stats_on {
1518                        eprintln!(
1519                            "[graph-alloc] whole-function colouring APPLIED \
1520                             (validated; FORCED — arbiter bypassed)"
1521                        );
1522                    }
1523                    (
1524                        candidate,
1525                        synth_synthesis::liveness::ReallocStats::default(),
1526                    )
1527                }
1528                Some(candidate) => {
1529                    // FINAL-BYTE ARBITER (RQ-60-RACOST increment 2). A
1530                    // colour-time cost model — however faithful its byte sizes
1531                    // — cannot price DOWNSTREAM PASS INTERACTIONS: measured on
1532                    // const_cse.wat::spill12, an identity-shaped colouring
1533                    // that merely PRESERVED the greedy allocator's register
1534                    // rotation defeated const-CSE's canonicalization and grew
1535                    // the function 148 -> 244 B (+96), with not one occurrence
1536                    // priced differently at colour time. So the candidate is
1537                    // sized through the REAL downstream pipeline
1538                    // (`finish_allocated_stream` — the exact passes the
1539                    // shipped stream runs, not a mirror) plus label resolution
1540                    // and the REAL encoder, against the shipping allocator's
1541                    // stream sized identically, and it ships only when it is
1542                    // STRICTLY smaller. A tie or a refusal keeps the shipping
1543                    // bytes — growth on an applied function is structurally
1544                    // impossible, which is exactly the wired
1545                    // vcr_dec_001_graph_alloc_differential no-growth
1546                    // assertion, promoted from a gate into a construction.
1547                    let ship = synth_synthesis::liveness::reallocate_function_post_exhaust(
1548                        &arm_instrs,
1549                        &POOL,
1550                        post_exhaust,
1551                    );
1552                    let size_of = |stream: &[synth_synthesis::ArmInstruction]| -> Option<usize> {
1553                        let finished = match finish_allocated_stream(
1554                            stream.to_vec(),
1555                            config,
1556                            post_exhaust,
1557                            true,
1558                            selected_spill_areas.borrow().as_ref(),
1559                            selected_vfp_frame_homes.borrow().as_ref(),
1560                        ) {
1561                            Ok(f) => f,
1562                            Err(e) => {
1563                                if stats_on {
1564                                    // The differential greps for the RA-003
1565                                    // hard-error string to detect a SHIPPED
1566                                    // violation; a candidate refused during
1567                                    // sizing is a decline, not a shipped
1568                                    // violation, so that marker is rewritten.
1569                                    let e = e.replace(
1570                                        "register-allocation validation FAILED",
1571                                        "register-allocation validation refused the candidate",
1572                                    );
1573                                    eprintln!(
1574                                        "[graph-alloc] arbiter: stream refused by the \
1575                                         pipeline/validators: {e}"
1576                                    );
1577                                }
1578                                return None;
1579                            }
1580                        };
1581                        let finished = if matches!(
1582                            config.target.isa,
1583                            IsaVariant::Thumb2 | IsaVariant::Thumb
1584                        ) {
1585                            resolve_label_branches(finished, &sizing_encoder).ok()?
1586                        } else {
1587                            finished
1588                        };
1589                        let mut total = 0usize;
1590                        let mut literals = 0usize;
1591                        for ins in &finished {
1592                            total += sizing_encoder.encode(&ins.op).ok()?.len();
1593                            if matches!(ins.op, synth_synthesis::rules::ArmOp::LdrSym { .. }) {
1594                                literals += 1;
1595                            }
1596                        }
1597                        if literals > 0 {
1598                            // The emit loop 4-aligns the literal pool and
1599                            // appends one word per LdrSym (no dedup — each
1600                            // site carries its own addend).
1601                            total += (4 - total % 4) % 4 + 4 * literals;
1602                        }
1603                        Some(total)
1604                    };
1605                    match (size_of(&candidate), size_of(&ship.0)) {
1606                        (Some(cand), Some(base)) if cand < base => {
1607                            if stats_on {
1608                                eprintln!(
1609                                    "[graph-alloc] whole-function colouring APPLIED \
1610                                     (validated; arbiter: {cand} B < shipping {base} B)"
1611                                );
1612                            }
1613                            (
1614                                candidate,
1615                                synth_synthesis::liveness::ReallocStats::default(),
1616                            )
1617                        }
1618                        (cand, base) => {
1619                            if stats_on {
1620                                eprintln!(
1621                                    "[graph-alloc] arbiter kept shipping bytes \
1622                                     (candidate {cand:?} B vs shipping {base:?} B) → \
1623                                     shipping reallocate_function"
1624                                );
1625                            }
1626                            ship
1627                        }
1628                    }
1629                }
1630                None => {
1631                    if stats_on {
1632                        eprintln!("[graph-alloc] DECLINED → shipping reallocate_function");
1633                    }
1634                    synth_synthesis::liveness::reallocate_function_post_exhaust(
1635                        &arm_instrs,
1636                        &POOL,
1637                        post_exhaust,
1638                    )
1639                }
1640            }
1641        } else {
1642            synth_synthesis::liveness::reallocate_function_post_exhaust(
1643                &arm_instrs,
1644                &POOL,
1645                post_exhaust,
1646            )
1647        };
1648        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
1649            eprintln!(
1650                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
1651                stats.segments,
1652                stats.reallocated,
1653                stats.declined,
1654                stats.validator_rejects,
1655                stats.needs_spill
1656            );
1657        }
1658        // VCR-VER-004 AUDIT (#242) — report-only, opt-in, never gating.
1659        //
1660        // The ABI observable-contract validator is a GATE on the flag-off
1661        // graph-colouring spike. This hook asks the same question of the
1662        // SHIPPING allocator's rewrite, so the answer is a MEASUREMENT rather
1663        // than a claim: how much of the shipping path can a value-level,
1664        // ABI-anchored check actually see today? Report-only DELIBERATELY —
1665        // making it gate here would risk a false rejection on the default
1666        // path, and the honest sequence is measure first, flip on evidence.
1667        // `SYNTH_ABI_CONTRACT_AUDIT=1` prints one verdict per function.
1668        if std::env::var_os("SYNTH_ABI_CONTRACT_AUDIT").is_some() {
1669            eprintln!(
1670                "[abi-contract-audit] {:?}",
1671                synth_synthesis::abi_contract::validate_abi_contract(&arm_instrs, &out)
1672            );
1673        }
1674        (out, true)
1675    } else {
1676        (arm_instrs, false)
1677    };
1678    // RQ-60-RACOST increment 2 (#242): every rewrite pass between the chosen
1679    // allocation and the encoder now lives in `finish_allocated_stream`, so
1680    // the SYNTH_GRAPH_ALLOC final-byte arbiter can size a candidate through
1681    // the REAL pipeline. Flag-off this is the exact pre-extraction sequence,
1682    // called once, in the same place.
1683    let arm_instrs = finish_allocated_stream(
1684        arm_instrs,
1685        config,
1686        post_exhaust,
1687        ran_realloc,
1688        selected_spill_areas.borrow().as_ref(),
1689        selected_vfp_frame_homes.borrow().as_ref(),
1690    )?;
1691
1692    // Encode to binary — use Thumb-2 for Cortex-M targets
1693    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
1694
1695    let encoder = if use_thumb2 {
1696        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1697    } else {
1698        ArmEncoder::new_arm32()
1699    };
1700
1701    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
1702    // offsets before encoding. `select_with_stack` emits them as label
1703    // placeholders and never resolves them — without this they encode as
1704    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
1705    // sits between the branch and its target (UsageFault on real hardware).
1706    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
1707    let arm_instrs = if use_thumb2 {
1708        let resolved = resolve_label_branches(arm_instrs, &encoder)?;
1709        // SC-5 (#740/#930): hard-gate every branch target onto the
1710        // instruction-start set of the final stream — both codegen paths
1711        // funnel through here. See `validate_branch_targets`.
1712        validate_branch_targets(&resolved, &encoder)?;
1713        resolved
1714    } else {
1715        arm_instrs
1716    };
1717
1718    // #778: capture the FINAL Thumb-2 instruction stream (post label-resolution,
1719    // the exact list the encode loop below consumes) so `compile_function` can
1720    // derive the sound WCET bound. Cheap clone; frozen-safe (the WCET walk is a
1721    // pure observation and never touches `code`). Only the Thumb-2 path — the A32
1722    // (Cortex-R5) cycle model is a follow-up.
1723    let final_instrs_for_wcet: Option<Vec<synth_synthesis::ArmInstruction>> = if use_thumb2 {
1724        Some(arm_instrs.clone())
1725    } else {
1726        None
1727    };
1728
1729    let mut code = Vec::new();
1730    let mut relocations = Vec::new();
1731
1732    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
1733    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
1734    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
1735    // and patch the PC-relative offset once the pool position is known.
1736    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1737    // RQ-72-ISLANDS (#345): the documented opt-out. With islands disabled the
1738    // pool is emitted exactly where it always was — one block at the end — so
1739    // the two legs of `litpool_islands_345_differential.py` are a real
1740    // differential and not two names for the same path.
1741    let islands_disabled = std::env::var_os("SYNTH_NO_LITPOOL_ISLANDS").is_some();
1742    // Spans of the ALREADY-RESOLVED branches, so an island is never placed
1743    // where it would invalidate one. Computed once, in pre-island coordinates.
1744    let branch_spans = if use_thumb2 && !islands_disabled {
1745        label_branch_spans(&arm_instrs, &encoder)?
1746    } else {
1747        Vec::new()
1748    };
1749    // Bytes of island inserted so far, so `code.len()` can be mapped back to
1750    // the pre-island coordinates `branch_spans` is expressed in.
1751    let mut island_bytes: u32 = 0;
1752    // Set when an island was DECLINED for the reason above, so the refusal the
1753    // end-of-function pool then raises can say WHY islands did not help.
1754    let mut island_declined_for_branch = false;
1755
1756    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1757    // here because `code.len()` immediately before `encode()` is the final
1758    // machine offset of the instruction within this function's `.text` — nothing
1759    // after the loop shifts earlier instructions (the literal pool is appended at
1760    // the end; the LDR patch below is in-place/length-preserving). Purely
1761    // additive: it does not touch `code`, so `.text` is byte-identical.
1762    let mut line_map: LineMap = Vec::new();
1763    // VCR-DEC-003 (#396): object-branch class per emitted instruction, parallel
1764    // to `line_map`. Cheap, additive, does not touch `code`.
1765    let mut branch_map: synth_core::backend::BranchMap = Vec::new();
1766
1767    for instr in &arm_instrs {
1768        // ORDER IS LOAD-BEARING, and getting it wrong was a SILENT MISCOMPILE.
1769        //
1770        // Encoding and the island decision happen FIRST, before anything below
1771        // records a `code.len()`. The v0.72 round-2 cold review found the
1772        // previous order — record, then encode, then maybe insert an island —
1773        // shifting the instruction forward by the island's size while its
1774        // ALREADY-RECORDED offset stayed put. Measured, both rc=0, on objects
1775        // v0.71 had refused loudly:
1776        //
1777        //   an `R_ARM_THM_CALL` recorded at 0x1014, which after the flush holds
1778        //   the island's own `b.n +8`; the real BL sits at 0x101c. The linker
1779        //   writes a BL over the branch-over and execution falls into a pooled
1780        //   address word as instructions.
1781        //
1782        //   an `LdrSym` whose `ldr_offset` pointed INTO the island, so the
1783        //   imm12 patch landed there and the real LDR kept imm12=0 — loading
1784        //   CODE as a pointer.
1785        //
1786        // Four sites record an offset (`Bl`, `MovwSym`, `MovtSym`, `LdrSym`)
1787        // and all four were wrong the same way. Hoisting the flush above them
1788        // makes `code.len()` FINAL for this instruction at every one.
1789        //
1790        // "A pool can never precede the LDR it serves" is PRESERVED, and is now
1791        // structural rather than arithmetic: this instruction's own `LdrSym` is
1792        // pushed BELOW, so `pending_literals` cannot contain it here.
1793        // Encode BEFORE deciding whether to flush, so the island trigger below
1794        // works from this instruction's EXACT size rather than an upper bound.
1795        // An over-estimate here would flush early (merely wasteful); an
1796        // under-estimate would let the 4 KB window close and patch a wrong
1797        // `imm12` — a MISCOMPILE, which is the defect #1341/#345 exist to
1798        // prevent. Knowing the real length removes the estimate entirely.
1799        let encoded = encoder
1800            .encode(&instr.op)
1801            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1802
1803        // RQ-72-ISLANDS (#345): flush the pool INLINE, before the window closes.
1804        //
1805        // WHY INLINE AND NOT A POST-PASS THAT INSERTS: `line_map` and
1806        // `branch_map` are (offset, _) PAIRS captured as `code.len()` just
1807        // below, so appending here leaves every later pair correct, while
1808        // inserting into an already-built `code` would silently desynchronise
1809        // all of them — and `.text` byte-identity on modules that need no
1810        // island would not notice.
1811        //
1812        // If `instr` is itself the `LdrSym` just pushed, its `ldr_offset`
1813        // equals `code.len()`, so the computed distance is ~0 and this cannot
1814        // fire before the LDR it serves. That is the ordering that would
1815        // otherwise place a pool BEFORE its own load.
1816        if use_thumb2 && !islands_disabled && !pending_literals.is_empty() {
1817            let n = pending_literals.len();
1818            // Worst case if we DON'T flush now: this instruction lands, then a
1819            // branch (<= 4 B) and alignment (<= 3 B) precede the words.
1820            let start = code.len() + encoded.len() + 4;
1821            let pad = (4 - (start % 4)) % 4;
1822            let last_word = (start + pad + 4 * (n - 1)) as u32;
1823            let aligned_pc = (pending_literals[0].ldr_offset + 4) & !3u32;
1824            if last_word.saturating_sub(aligned_pc) > 0xFFF {
1825                // THE GUARD. `code.len()` counts islands already inserted;
1826                // `branch_spans` is in pre-island coordinates, so map back
1827                // before comparing. A branch is invalidated exactly when the
1828                // insertion point separates it from its target.
1829                let pre_p = code.len() as u32 - island_bytes;
1830                let spanned = branch_spans
1831                    .iter()
1832                    .any(|&(lo, hi)| lo < pre_p && pre_p <= hi);
1833                if spanned {
1834                    // Refuse the island rather than mis-target the branch.
1835                    // The pool falls through to the end of the function and
1836                    // #345's out-of-range error fires there — loud, which is
1837                    // the whole point.
1838                    island_declined_for_branch = true;
1839                } else {
1840                    let before = code.len();
1841                    emit_literal_pool(
1842                        &mut code,
1843                        &mut relocations,
1844                        &pending_literals,
1845                        Some(&encoder),
1846                    )?;
1847                    island_bytes += (code.len() - before) as u32;
1848                    pending_literals.clear();
1849                }
1850            }
1851        }
1852
1853        // Record a relocation for every BL: the encoder emits `bl #0` and
1854        // relies on a relocation to patch the target. This covers BOTH import
1855        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1856        // (`func_N`, defined in this object). Previously only `__meld_*` was
1857        // recorded, so internal `BL func_N` calls were left as unpatched
1858        // `bl #0` placeholders branching to a garbage address (#167).
1859        if let ArmOp::Bl { label } = &instr.op {
1860            // #1040: the relocation type is ISA-STATE-dependent and this is the
1861            // only site that knows the state. An A32 (Cortex-R) `bl` is
1862            // R_ARM_CALL (28); a Thumb `bl` is R_ARM_THM_CALL (10). Emitting
1863            // the Thumb type for an A32 word made any consumer that trusts the
1864            // declared type patch Thumb halfwords into an ARM-state
1865            // instruction. Decided here rather than in the ELF emitter, where
1866            // `config.target` is no longer in scope and the ISA would have to
1867            // be re-derived — the shape that produced the bug.
1868            let kind = if config.target.isa == synth_core::target::IsaVariant::Arm32 {
1869                synth_core::backend::RelocKind::ArmCall
1870            } else {
1871                synth_core::backend::RelocKind::ThmCall
1872            };
1873            relocations.push(CodeRelocation {
1874                offset: code.len() as u32,
1875                symbol: label.clone(),
1876                kind,
1877            });
1878        }
1879        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1880        // addressing). The encoder writes the addend in place; record the matching
1881        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1882        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1883            relocations.push(CodeRelocation {
1884                offset: code.len() as u32,
1885                symbol: symbol.clone(),
1886                kind: synth_core::backend::RelocKind::MovwAbs,
1887            });
1888        }
1889        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1890            relocations.push(CodeRelocation {
1891                offset: code.len() as u32,
1892                symbol: symbol.clone(),
1893                kind: synth_core::backend::RelocKind::MovtAbs,
1894            });
1895        }
1896        // #345: defer the literal-pool word + reloc + offset patch to the
1897        // post-loop pass (the pool address is not yet known).
1898        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1899            pending_literals.push(PendingLiteral {
1900                ldr_offset: code.len() as u32,
1901                symbol: symbol.clone(),
1902                addend: *addend,
1903            });
1904        }
1905
1906        // The machine offset of this instruction is the current code length,
1907        // captured before the bytes are appended (and AFTER any island above,
1908        // so the recorded offset is where the instruction really lands).
1909        line_map.push((code.len() as u32, instr.source_line));
1910        branch_map.push((code.len() as u32, classify_arm_branch(&instr.op)));
1911
1912        code.extend_from_slice(&encoded);
1913    }
1914
1915    // #345: place any REMAINING literals at the end of this function's `.text`.
1916    // Gated on there being at least one un-flushed `LdrSym` — functions without
1917    // one are byte-identical to before (no trailing padding, so downstream
1918    // `func_offsets` are unchanged and the frozen differential fixtures stay
1919    // bit-for-bit equal). No branch is emitted: these bytes sit past the final
1920    // return and are never executed.
1921    if !pending_literals.is_empty() {
1922        if !use_thumb2 {
1923            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1924        }
1925        emit_literal_pool(&mut code, &mut relocations, &pending_literals, None).map_err(|e| {
1926            if island_declined_for_branch {
1927                format!(
1928                    "{} — an inline literal island WOULD have brought the \
1929                         pool in range, but every candidate placement fell \
1930                         between a local branch and its target, where \
1931                         inserting bytes would silently mis-target the branch \
1932                         (branch offsets are byte-resolved before this loop). \
1933                         Refusing is deliberate: a wrong branch target is a \
1934                         silent miscompile, an out-of-range pool is not. \
1935                         Serving this shape needs branch resolution and island \
1936                         placement in one fixed point.",
1937                    e
1938                )
1939            } else {
1940                e
1941            }
1942        })?;
1943    }
1944
1945    Ok((
1946        code,
1947        relocations,
1948        line_map,
1949        branch_map,
1950        final_instrs_for_wcet,
1951    ))
1952}
1953
1954/// RQ-60-RACOST increment 2 (#242): every rewrite pass between a CHOSEN
1955/// register allocation and the encoder, as ONE reusable sequence.
1956///
1957/// Extracted VERBATIM from `compile_wasm_to_arm` (pure code motion) so the
1958/// `SYNTH_GRAPH_ALLOC` final-byte arbiter can size a candidate allocation
1959/// through the REAL downstream pipeline — the same passes, in the same order,
1960/// reading the same flags — rather than through a hand-mirrored predicate of
1961/// them (the #936 drift class: a hand mirror of the encoder's offset-fold
1962/// threshold was UNSOUND at authoring; a hand mirror of eleven rewrite passes
1963/// would be worse). Flag-off behaviour is byte-identical: the shipping path
1964/// calls this exactly once, on the same stream, in the same place it always
1965/// ran.
1966///
1967/// `ran_realloc` selects the historical branch: the dead-frame /
1968/// callee-saved-prologue / shrink trio runs only downstream of the range
1969/// re-allocation lever (`SYNTH_RANGE_REALLOC` on), exactly as before the
1970/// extraction. Diagnostics inside (SYNTH_FUSE_STATS, SYNTH_SHADOW_ALLOC,
1971/// SYNTH_SPILL_REPORT) print once per CALL, so an arbiter sizing run repeats
1972/// them — measurement noise under two opt-in flags, never a byte change.
1973fn finish_allocated_stream(
1974    arm_instrs: Vec<synth_synthesis::ArmInstruction>,
1975    config: &CompileConfig,
1976    post_exhaust: bool,
1977    ran_realloc: bool,
1978    // #1321: `(frame_size, areas)` recorded by the direct selector for the
1979    // attempt that produced this stream — the frame regions that are genuinely
1980    // allocator SPILL slots. Used to scope VCR-RA-003's #331 check, and ONLY
1981    // after `frame_size` is re-proven against this stream (see the use site).
1982    // `None` on the optimized path and whenever no area was reserved.
1983    recorded_spill_areas: Option<&(i32, Vec<std::ops::Range<i32>>)>,
1984    // RQ-71-VFPALIAS (#881/#1069): the permanent VFP frame homes from that same
1985    // attempt, proven against this stream by the identical `frame_size` test.
1986    // `None` on the optimized path and whenever selection granted no home.
1987    recorded_vfp_frame_homes: Option<&(i32, Vec<i32>)>,
1988) -> Result<Vec<synth_synthesis::ArmInstruction>, String> {
1989    let arm_instrs = if ran_realloc {
1990        let out = arm_instrs;
1991        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
1992        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
1993        // that promotion homed in registers, never accessed). Removing it saves
1994        // the two instructions AND restores the SP-untouched precondition that
1995        // `shrink_callee_saved_saves` requires — so it must run FIRST.
1996        // DEFAULT-ON (#242 flag audit flip-wave, #592 audit item): evidence
1997        // basis was the 2-path × repro-corpus sweep — 0 functions grow, 58
1998        // shrink (flight_seam controller_step 250→242 −8 / filter_step 180→168
1999        // −12, native_pointer frame_roundtrip 46→34 −12), locked by the
2000        // `dead_frame_elim_no_grow_corpus_242` cargo gate; execution
2001        // differentials re-run green on the new default bytes BEFORE the
2002        // frozen ARM anchors were re-pinned (leaf_dead_frame, flight_seam,
2003        // frame_slot_dce — see the flip PR). Escape hatch:
2004        // `SYNTH_DEAD_FRAME_ELIM=0` opts out and restores the pre-flip bytes
2005        // (CI-gated in `frozen_codegen_bytes.rs`).
2006        let out = if !std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok_and(|v| v == "0") {
2007            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
2008        } else {
2009            out
2010        };
2011        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
2012        // promoted locals but emits no prologue, silently clobbering a caller's
2013        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
2014        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
2015        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
2016        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
2017        // (next) then trims it to the used set. No-op on the direct path (it
2018        // already has its own prologue) and on callee-saved-free leaves.
2019        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
2020        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
2021    } else {
2022        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
2023        // must preserve the callee-saved registers it clobbers (#490). No shrink
2024        // (it is coupled to the realloc lever), so the conservative full save
2025        // stays — correct, just not minimised in this debug configuration.
2026        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
2027    };
2028    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
2029    // the selected stream and LOG what it finds — without changing a single
2030    // emitted byte. This is the measure-only bridge between the built analysis
2031    // layer and the eventual virtual-register wiring: it shows, per real
2032    // function, whether the allocator can colour it within the R0–R8 pool and
2033    // how much const-CSE / rematerialization headroom exists (#209). Enable with
2034    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
2035    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
2036        use synth_synthesis::liveness::{
2037            AllocationOutcome, allocate_function, function_peak_pressure,
2038        };
2039        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
2040        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
2041        let precolored = std::collections::BTreeMap::from([
2042            (synth_synthesis::rules::Reg::R9, 9usize),
2043            (synth_synthesis::rules::Reg::R10, 10),
2044            (synth_synthesis::rules::Reg::R11, 11),
2045            (synth_synthesis::rules::Reg::R12, 12),
2046        ]);
2047        // True VALUE pressure (one node per value, not per reused physical reg):
2048        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
2049        // function fits once virtually allocated.
2050        let peak = function_peak_pressure(&arm_instrs);
2051        match allocate_function(&arm_instrs, 9, &precolored) {
2052            AllocationOutcome::Allocated {
2053                remat_opportunities,
2054                coloring,
2055            } => eprintln!(
2056                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
2057                coloring.len(),
2058                peak,
2059                remat_opportunities
2060            ),
2061            AllocationOutcome::NeedsSpill(s) => eprintln!(
2062                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
2063                s, peak
2064            ),
2065            AllocationOutcome::Declined => {
2066                eprintln!(
2067                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
2068                )
2069            }
2070        }
2071    }
2072
2073    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
2074    // lowers a `select` whose condition is a comparison to a *materialize then
2075    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
2076    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
2077    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
2078    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
2079    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
2080    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
2081    //
2082    // Run LATE: after range re-allocation (so the dead-D proof sees final register
2083    // identities) and before encode. Removal-only + rename-only ⇒ no spill
2084    // regression and labels/branch offsets are unaffected. Each fusion is proven
2085    // sound (flags reused only when nothing clobbers them in the window; the
2086    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
2087    //
2088    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
2089    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
2090    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
2091    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
2092    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
2093    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
2094    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
2095    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
2096    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
2097    // check is a tracked post-ship follow-up (gale owns it).
2098    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
2099        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
2100        // the extra `two_move` count is diagnostic only (the fusion census /
2101        // blast-radius datum — #7 made that arm reachable).
2102        let (out, fused, two_move) =
2103            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
2104        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2105            let in_place = fused - two_move;
2106            eprintln!(
2107                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
2108                 ({two_move} two-move, {in_place} in-place)"
2109            );
2110        }
2111        out
2112    } else {
2113        arm_instrs
2114    };
2115
2116    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
2117    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
2118    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
2119    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
2120    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
2121    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
2122    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
2123    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
2124    // execution differential — the same gated path cmp→select took to default-on in
2125    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
2126    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
2127    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
2128    let arm_instrs = if stack_fwd {
2129        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
2130        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2131            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
2132        }
2133        out
2134    } else {
2135        arm_instrs
2136    };
2137
2138    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
2139    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
2140    // them is a dead store — its slot is never loaded again. Remove it. Pairs
2141    // with (and only pays after) stack-reload forwarding, so it shares the flag.
2142    let arm_instrs = if stack_fwd {
2143        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
2144        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2145            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
2146        }
2147        out
2148    } else {
2149        arm_instrs
2150    };
2151
2152    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
2153    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
2154    // `forward_stack_reloads` (above) forwards only from a spill store's
2155    // SOURCE register, so when register pressure clobbers that source its
2156    // reloads survive; this stage tracks which registers provably still hold
2157    // a frame slot's value (through earlier reloads and reg-reg moves) and
2158    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
2159    // already holds the value). Stage 2 (the Belady re-choice): where NO
2160    // register still holds the value — the genuine-spill case, flat_flight's
2161    // peak-11 hot segment — the value was usually evicted while a dead
2162    // register existed; the clobbering def(s) are renamed onto a provably-dead
2163    // register (`spill_rechoice_segment`) so the value stays resident and the
2164    // reload dissolves outright. A dissolved reload can leave the feeding
2165    // store dead, so the frame-slot DCE sweep runs once more behind the same
2166    // flag. Per-segment commit gates: executable same-value-flow trace
2167    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
2168    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
2169    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
2170    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
2171    // see other segments); `eliminate_unread_frame_stores` walks the whole
2172    // function (labels/branches/loops, SP-displacement tracked) and drops a
2173    // store whose slot NO reachable instruction can read — flat_flight's two
2174    // surviving stores (#576), completing Belady's 0-load side with a 0-store
2175    // side. Same flag: the three stages are one lever, flipped together.
2176    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
2177    // Belady spilling ships by default. Evidence basis for the flip: three
2178    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
2179    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
2180    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
2181    // guards, and the unicorn-vs-wasmtime execution differentials re-run
2182    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
2183    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
2184    // control_step_decide vs wasmtime; control_step's .text is byte-identical
2185    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
2186    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
2187    // and restores the pre-flip bytes (CI-gated by
2188    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
2189    // other value (or unset) runs the pass.
2190    // VCR-VER-001 post-exhaustion extensions (#242, the PR #659 verdict): with
2191    // `SYNTH_SPILL_ON_EXHAUST` active the #580 allocation-time Belady spill
2192    // keeps exhausted functions on the optimized path, and its slots present
2193    // shapes the shipping pass structurally cannot fire on (fresh-monotonic
2194    // slots defeat the overwrite-only DCE; the eviction store's source is
2195    // redefined immediately, defeating store→reload forwarding; R2/R3 are
2196    // never touched again, so the rename-target deadness proof declines them).
2197    // `post_exhaust` (bridge-scoped, see above) enables const
2198    // rematerialization of spilled constants, R2/R3 exit-dead rename targets,
2199    // and per-pair pressure commit — see `apply_spill_realloc_post_exhaust`.
2200    // Flag off (the default): `false` selects the shipping behavior bit for
2201    // bit.
2202    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
2203        let (out, n) =
2204            synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&arm_instrs, post_exhaust);
2205        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
2206        let (mut out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
2207        let (mut tn, mut td, mut tu) = (n, d, u);
2208        // Post-exhaustion only: iterate the triple to a bounded fixpoint. Each
2209        // dissolved spill pair frees registers and removes stores, exposing
2210        // rename windows and holder chains the previous iteration could not
2211        // prove — the allocation-time Belady slots (#580) routinely need two
2212        // or three rounds where the shipping single round suffices for the
2213        // default path's slots. Every iteration is individually gate-proven
2214        // (value-trace equality, pool pressure, strict shrink), so iterating
2215        // composes soundly; the bound keeps compile time deterministic.
2216        if post_exhaust {
2217            let mut progress = n + d + u > 0;
2218            for _ in 0..3 {
2219                if !progress {
2220                    break;
2221                }
2222                let (o, n) =
2223                    synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&out, true);
2224                let (o, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&o);
2225                let (o, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&o);
2226                progress = n + d + u > 0;
2227                (tn, td, tu) = (tn + n, td + d, tu + u);
2228                out = o;
2229            }
2230            // The cleanup can leave the spill frame with zero surviving
2231            // accesses (every reload rematerialized/dissolved, every store
2232            // swept) — the balanced `sub sp,#K`/`add sp,#K` is then pure
2233            // overhead. `elide_dead_frame` proves that and removes the pair;
2234            // its early run (post-realloc) could not, because the spill
2235            // traffic was still in the stream at that point.
2236            out = synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out);
2237        }
2238        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2239            eprintln!(
2240                "[spill-realloc] {tn} reload(s) forwarded/eliminated, {td} newly-dead frame store(s) removed, {tu} unread-slot store(s) removed"
2241            );
2242        }
2243        out
2244    } else {
2245        arm_instrs
2246    };
2247
2248    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
2249    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
2250    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
2251    // instruction, −1 live register. Removal-only (offset-neutral before branch
2252    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
2253    // bit-identical results + a net cycle win on the dissolved hot path (−2
2254    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
2255    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
2256        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
2257        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2258            eprintln!(
2259                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
2260            );
2261        }
2262        out
2263    } else {
2264        arm_instrs
2265    };
2266
2267    // #686: elide the #682 mod-32 shift-amount mask (`and r12,rK,#31` before
2268    // every register-controlled i32 shl/shr) when the amount is STATICALLY
2269    // provable < 32 — a const amount folds to the immediate-shift form
2270    // (reduced mod 32, so >= 32 shrinks too), and an already-masked amount
2271    // (`rK = rX & c`, c < 32) drops the redundant re-mask. gale measured the
2272    // unconditional mask at ~12% cyc/call (+14 B) on gust_mix, whose Q8
2273    // fixed-point shifts are all constants (#686). The mask stays wherever
2274    // the bound is unproven — elision is an optimization, the mask is the
2275    // sound default (`liveness::elide_shift_masks` has the proof
2276    // obligations). Runs after `fold_immediate_shifts` (whose movw→shift
2277    // window the #682 mask intercepts, so it declines every masked const
2278    // shift) and before branch resolution (removal/rewrite-only ⇒
2279    // offset-neutral).
2280    //
2281    // DEFAULT-ON since v0.50.1 (opt-out via `SYNTH_SHIFT_MASK_ELIDE=0`; #846).
2282    // gale's gpio-thin driver regressed +44 B / +9% on synth 0.49 — its pin
2283    // bit-arithmetic (`pin & 31` then a register shift) emits the source
2284    // `and rN,#0x1f` IMMEDIATELY followed by the #682 mod-32 re-mask
2285    // `and r12,rN,#0x1f`; the second is provably redundant (Pattern B: an
2286    // operand produced by `and X,#c`, c<32, is already in [0,31]), so the
2287    // pass drops it. Flipping default-on is a deliberate byte-changing
2288    // refreeze: the elision also moves the frozen anchors (const-amount
2289    // shifts fold back to the immediate form) — control_step −20 B,
2290    // flight_seam −166 B, flight_seam_flat −168 B — all size DECREASES with
2291    // the mask soundly kept for every unproven amount. All differentials were
2292    // re-run on the new bytes and the goldens re-pinned (see #846 PR /
2293    // `frozen_codegen_bytes.rs`). `SYNTH_SHIFT_MASK_ELIDE=0` restores the
2294    // pre-flip bytes (opt-out gate in `shift_mask_elide_686.rs`).
2295    let arm_instrs = if std::env::var("SYNTH_SHIFT_MASK_ELIDE").is_ok_and(|v| v == "0") {
2296        arm_instrs
2297    } else {
2298        let (out, elisions) = synth_synthesis::liveness::elide_shift_masks(&arm_instrs);
2299        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2300            eprintln!(
2301                "[shift-mask-elide] {elisions} provably-<32 shift-amount mask(s) elided (#686)"
2302            );
2303        }
2304        out
2305    };
2306
2307    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
2308    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
2309    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
2310    // modified immediates so the selector materializes them into a register; the
2311    // dedicated zero-extend expresses the same masking inline. Removal-only +
2312    // rewrite-in-place (offset-neutral). DEFAULT-ON (#242 flag audit flip-wave,
2313    // #592 audit item): evidence basis was the 2-path × repro-corpus sweep —
2314    // 0 functions grow, 13 shrink (control_step 300→294 −6, gust_mix 38→32 −6,
2315    // uxth_fold pack 36→24 −12), locked by the `uxth_fold_no_grow_corpus_242`
2316    // cargo gate; execution differentials re-run green on the new default
2317    // bytes BEFORE the frozen ARM anchors were re-pinned (uxth_fold,
2318    // control_step — see the flip PR). Escape hatch: `SYNTH_UXTH_FOLD=0` opts
2319    // out and restores the pre-flip bytes (CI-gated in
2320    // `frozen_codegen_bytes.rs`).
2321    let arm_instrs = if !std::env::var("SYNTH_UXTH_FOLD").is_ok_and(|v| v == "0") {
2322        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
2323        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2324            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
2325        }
2326        out
2327    } else {
2328        arm_instrs
2329    };
2330
2331    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
2332    // `movw`/`mov #imm` that re-materializes a constant already resident in
2333    // another register and retargets the reads — every rewrite proven by the
2334    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
2335    // range-realloc, but BEFORE branch resolution/encoding (it removes
2336    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
2337    // fix: the folds have already absorbed every foldable constant, so CSE can no
2338    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
2339    // size-guards each segment via the byte-estimator — it commits a segment's
2340    // rewrites only if they do not grow its estimated size — so a retarget that
2341    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
2342    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
2343    // template): const-CSE ships by default. The flip prerequisites recorded in
2344    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
2345    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
2346    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
2347    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
2348    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
2349    // 236→148 B), total −536 B — and the execution differentials re-run green
2350    // on the new default bytes BEFORE the frozen goldens were re-pinned
2351    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
2352    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
2353    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
2354    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
2355    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
2356    //
2357    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
2358    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
2359    // cannot be classified as address-vs-data (a retargeted read may be a
2360    // memory-access base carrying a per-use immediate offset), so the
2361    // conservative stance for statically-unknown addressing is to decline every
2362    // aliasing rewrite — each constant is re-materialized at each occurrence,
2363    // the documented volatile contract (`CompileConfig::volatile_segments`).
2364    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
2365        && config.volatile_segments.is_empty()
2366    {
2367        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
2368        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2369            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
2370        }
2371        out
2372    } else {
2373        arm_instrs
2374    };
2375
2376    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
2377    // Per straight-line segment, the frame-slot traffic actually emitted vs the
2378    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
2379    // pool would need — the measured headroom for the full spill-choice rewrite.
2380    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
2381    // reports the greedy baseline and a flag-on run reports what remains.
2382    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
2383        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
2384            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
2385                eprintln!(
2386                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
2387                    seg.start,
2388                    seg.len,
2389                    seg.peak_pressure,
2390                    seg.actual_reloads,
2391                    seg.actual_spill_stores,
2392                    seg.belady_reloads,
2393                    seg.belady_spill_stores
2394                );
2395            }
2396        }
2397    }
2398
2399    // ISA feature gate: validate that all generated instructions are supported
2400    // by the target. This catches FPU instructions on no-FPU targets, double-precision
2401    // instructions on single-precision targets, etc.
2402    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
2403        .map_err(|e| format!("ISA validation failed: {}", e))?;
2404
2405    // VCR-RA-003 (epic #242): UNCONDITIONAL per-compilation register-allocation
2406    // validation. The register allocator is the last major unverified codegen
2407    // component; this whole-function checker proves — by construction, on the
2408    // EXACT emitted stream about to be encoded — that the allocation preserves
2409    // FOUR invariants whose reference lives in the stream (or the ABI): (1)
2410    // callee-saved preservation (#490), (2) spill-slot non-aliasing (#331), and
2411    // — PHASE 2 (#49), extending past straight-line — (3) caller-saved
2412    // preservation across calls (a value in R2/R3/R12 live across a `bl` the
2413    // AAPCS boundary destroys), and (4) value availability across control-flow
2414    // joins (a live-in to a join must be defined on every incoming edge). It runs
2415    // on every ARM compile in the DEFAULT shipping build (NOT behind
2416    // `--features verify`; a verify-gated check would be dormant in exactly the
2417    // build that ships — the #757 / VCR-VER-003 lesson) and hard-errors the
2418    // compile on a VIOLATION. A `NotAttempted` verdict (the join check declines
2419    // on an unmodeled-CF function: numeric branch, `BrTable`, etc.) is NON-FATAL
2420    // — the compile proceeds; the other three invariants were still checked and
2421    // held. This is the decline>guess doctrine applied to the checker itself: it
2422    // never claims join coherence it cannot prove, but it also never blocks a
2423    // correct compile for a construct it simply doesn't model yet. Frozen-safe:
2424    // it emits nothing, so `.text` is byte-identical (proven by the frozen suite).
2425    // #1321: scope the #331 spill-slot check to the frame regions the allocator
2426    // actually hands out as spill slots — but ONLY while the record provably
2427    // still describes THIS stream. Between selection and here the stream passes
2428    // through re-allocation, dead-frame elimination and prologue shrink, any of
2429    // which can re-lay or remove the frame. A stale area list would narrow the
2430    // check over the wrong offsets — the silent weakening this lane exists to
2431    // avoid — so the areas are used only if the final stream still allocates
2432    // EXACTLY the frame they were computed for. On any mismatch (re-laid frame,
2433    // eliminated frame, optimized path, no record) we pass `None` and every
2434    // `[sp,#N]` offset is policed, bit for bit as before. The fix can go stale;
2435    // it cannot go wrong.
2436    // The staleness proof, shared by both records: this stream still allocates
2437    // EXACTLY the frame they were computed for. Factored into one closure so the
2438    // spill areas and the VFP frame homes cannot drift apart — they come from
2439    // the same selection and must stand or fall together.
2440    let frame_still_matches = |frame_size: &i32| {
2441        arm_instrs.iter().any(|ins| {
2442            matches!(
2443                &ins.op,
2444                synth_synthesis::rules::ArmOp::Sub {
2445                    rd: synth_synthesis::rules::Reg::SP,
2446                    rn: synth_synthesis::rules::Reg::SP,
2447                    op2: synth_synthesis::rules::Operand2::Imm(n),
2448                } if n == frame_size
2449            )
2450        })
2451    };
2452    let spill_areas: Option<&[std::ops::Range<i32>]> = match recorded_spill_areas {
2453        Some((frame_size, areas)) if frame_still_matches(frame_size) => Some(areas.as_slice()),
2454        _ => None,
2455    };
2456    // RQ-71-VFPALIAS (#881/#1069): same gate, same failure direction. A stale or
2457    // absent home set means the #881 twin polices every VFP `[sp,#N]` offset,
2458    // which is what it did before this narrowing existed.
2459    let vfp_frame_homes: Option<&[i32]> = match recorded_vfp_frame_homes {
2460        Some((frame_size, halves)) if frame_still_matches(frame_size) => Some(halves.as_slice()),
2461        _ => None,
2462    };
2463    match synth_synthesis::liveness::validate_final_allocation_in_areas_with_vfp_homes(
2464        &arm_instrs,
2465        spill_areas,
2466        vfp_frame_homes,
2467    ) {
2468        synth_synthesis::liveness::RaFinalVerdict::Violation(v) => {
2469            return Err(format!(
2470                "VCR-RA-003: register-allocation validation FAILED — {v:?}. \
2471                 The emitted stream violates a register-allocation invariant \
2472                 (callee-saved preservation #490 / spill-slot non-aliasing #331 \
2473                 / caller-saved-across-call / join-value-availability / the #881 \
2474                 VFP twins); this is a \
2475                 compiler bug, not a program error. Refusing to emit a \
2476                 miscompiled object."
2477            ));
2478        }
2479        // Loud honest decline (join reasoning skipped for an unmodeled-CF
2480        // function). Non-fatal — the straight-line / callee-saved / across-call
2481        // invariants still ran and held; only the across-JOIN availability
2482        // reasoning is skipped. Since the #819 redo the optimized path's
2483        // pre-resolved NUMERIC branches are modeled too (build_join_cfg_numeric
2484        // + the PRESERVED entry-availability discriminator), so this fires only
2485        // on genuinely unmodeled shapes: BrTable, computed Bx, mixed
2486        // label+numeric streams, off-boundary numeric targets.
2487        // Surfaced only under `SYNTH_RA003_VERBOSE` so a production compile stays
2488        // quiet: emitting it unconditionally would print on every branchy
2489        // optimized-path compile (new stderr noise phase 1 never produced), yet
2490        // it must remain observable on demand for the honest-scope audit.
2491        synth_synthesis::liveness::RaFinalVerdict::NotAttempted { reason } => {
2492            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2493                eprintln!(
2494                    "VCR-RA-003: across-join validation NOT ATTEMPTED ({reason}) — \
2495                     straight-line / callee-saved / across-call invariants held; \
2496                     join-availability reasoning declined on this control-flow shape."
2497                );
2498            }
2499        }
2500        synth_synthesis::liveness::RaFinalVerdict::Consistent => {
2501            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2502                eprintln!("VCR-RA-003: Consistent");
2503            }
2504        }
2505    }
2506    Ok(arm_instrs)
2507}
2508
2509/// VCR-DEC-003 (#396): classify one emitted `ArmOp` into its object-level
2510/// control-flow role for the `synth-provenance-v1` map. Conditional branches are
2511/// the object decision points MC/DC must reconcile; `SelectMove` is the folded
2512/// (IT-block) predicated form the cmp→select fuse produces — a decision with no
2513/// branch.
2514fn classify_arm_branch(op: &ArmOp) -> synth_core::backend::BranchClass {
2515    use synth_core::backend::BranchClass;
2516    match op {
2517        ArmOp::Bcc { .. } | ArmOp::Bhs { .. } | ArmOp::Blo { .. } | ArmOp::BCondOffset { .. } => {
2518            BranchClass::CondBranch
2519        }
2520        ArmOp::B { .. } | ArmOp::BOffset { .. } => BranchClass::UncondBranch,
2521        ArmOp::SelectMove { .. } => BranchClass::Predicated,
2522        _ => BranchClass::Other,
2523    }
2524}
2525
2526/// Resolve local label branches to byte-accurate offsets (#202).
2527///
2528/// `select_with_stack` emits conditional/unconditional branches as label
2529/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
2530/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
2531/// this path only ran for `--no-optimize`/declined functions, so the latent bug
2532/// stayed hidden — routing relocatable code through it surfaced branches that
2533/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
2534/// instruction sits between the branch and its target.
2535///
2536/// This pass encodes each instruction to learn its real byte length (so 16- vs
2537/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
2538/// to its byte position, and rewrites every label branch to the displacement
2539/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
2540/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
2541/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
2542/// the optimized path carry no label and are left untouched.
2543/// Byte spans of every already-resolved local branch, in PRE-ISLAND
2544/// coordinates: `(min(branch, target), max(branch, target))`.
2545///
2546/// RQ-72-ISLANDS follow-up. `resolve_label_branches` bakes a byte-accurate
2547/// offset into each branch and `validate_branch_targets` gates it onto the
2548/// instruction-start set — both BEFORE the encode loop that inserts inline
2549/// literal islands. Inserting bytes at a point a branch straddles moves the
2550/// target without moving the branch (or the reverse, for a backward branch),
2551/// so the baked offset is wrong by exactly the island's size. Measured: an
2552/// 8-byte island left a `br_if` pointing 8 bytes short, into the middle of the
2553/// block it was supposed to skip.
2554///
2555/// Returned spans let the island placer REFUSE such a point rather than
2556/// silently mis-target the branch. Refusing falls through to the
2557/// end-of-function pool, which raises the original #345 out-of-range error —
2558/// the loud behaviour v0.71 had.
2559fn label_branch_spans(
2560    instrs: &[ArmInstruction],
2561    encoder: &ArmEncoder,
2562) -> Result<Vec<(u32, u32)>, String> {
2563    let mut positions = Vec::with_capacity(instrs.len());
2564    let mut pos: u32 = 0;
2565    for instr in instrs {
2566        positions.push(pos);
2567        pos += encoder
2568            .encode(&instr.op)
2569            .map_err(|e| format!("island span probe failed: {}", e))?
2570            .len() as u32;
2571    }
2572    let mut spans = Vec::new();
2573    for (i, instr) in instrs.iter().enumerate() {
2574        // Only the LOCALLY RESOLVED forms carry a baked byte offset. Label
2575        // forms that survive to here are external and are relocated, so an
2576        // island does not invalidate them.
2577        let off = match &instr.op {
2578            ArmOp::BCondOffset { offset, .. } => *offset,
2579            ArmOp::BOffset { offset } => *offset,
2580            _ => continue,
2581        };
2582        let src = positions[i];
2583        // The encoder consumes the field as (target - branch - 4) / 2.
2584        let target = (src as i64) + 4 + 2 * (off as i64);
2585        if target < 0 {
2586            continue;
2587        }
2588        let t = target as u32;
2589        spans.push((src.min(t), src.max(t)));
2590    }
2591    Ok(spans)
2592}
2593
2594fn resolve_label_branches(
2595    arm_instrs: Vec<ArmInstruction>,
2596    encoder: &ArmEncoder,
2597) -> Result<Vec<ArmInstruction>, String> {
2598    use std::collections::HashMap;
2599    use synth_synthesis::Condition;
2600
2601    enum BKind {
2602        Cond(Condition),
2603        Uncond,
2604    }
2605    // Record each label branch ONCE — indices are stable across iterations.
2606    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
2607    for (i, instr) in arm_instrs.iter().enumerate() {
2608        match &instr.op {
2609            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
2610            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
2611            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
2612            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
2613            _ => {}
2614        }
2615    }
2616    if branches.is_empty() {
2617        return Ok(arm_instrs);
2618    }
2619
2620    let mut resolved = arm_instrs;
2621    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
2622    for _ in 0..16 {
2623        // 1. Byte position of each instruction (Label encodes to 0 bytes).
2624        let mut positions = Vec::with_capacity(resolved.len());
2625        let mut pos: i64 = 0;
2626        for instr in &resolved {
2627            positions.push(pos);
2628            pos += encoder
2629                .encode(&instr.op)
2630                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
2631                .len() as i64;
2632        }
2633        // 2. Label name -> byte position (owned keys so the borrow ends here).
2634        let mut labels: HashMap<String, i64> = HashMap::new();
2635        for (i, instr) in resolved.iter().enumerate() {
2636            if let ArmOp::Label { name } = &instr.op {
2637                labels.insert(name.clone(), positions[i]);
2638            }
2639        }
2640        // 3. Rewrite each branch to its byte-accurate offset.
2641        let mut changed = false;
2642        for (idx, kind, label) in &branches {
2643            // A label not defined locally is an EXTERNAL target (e.g.
2644            // `Trap_Handler` resolved by a relocation / the vector table). Leave
2645            // such branches as their placeholder for the existing relocation
2646            // path — only local control-flow labels are byte-resolved here.
2647            let Some(&target) = labels.get(label) else {
2648                continue;
2649            };
2650            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
2651            // Positions are always even, so this division is exact.
2652            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
2653            let new_op = match kind {
2654                BKind::Cond(c) => ArmOp::BCondOffset {
2655                    cond: *c,
2656                    offset: halfword_offset,
2657                },
2658                BKind::Uncond => ArmOp::BOffset {
2659                    offset: halfword_offset,
2660                },
2661            };
2662            if resolved[*idx].op != new_op {
2663                resolved[*idx].op = new_op;
2664                changed = true;
2665            }
2666        }
2667        if !changed {
2668            break;
2669        }
2670    }
2671    Ok(resolved)
2672}
2673
2674/// SC-5 branch-target boundary gate (#740, #930): every emitted branch target
2675/// must be a member of the instruction-start set of the final stream.
2676///
2677/// "Branch offset calculation shall account for Thumb instruction alignment
2678/// and variable instruction widths" (`safety/stpa/system-constraints.yaml`
2679/// SC-5). Thumb-2 mixes 16- and 32-bit encodings, so an off-by-one-halfword
2680/// target lands on the SECOND halfword of a wide instruction and the CPU
2681/// executes a halfword that was never an instruction — silent garbage, exit 0
2682/// (#930: the skipped `movw` left the `br_if` condition register at its reset
2683/// value). Both known escapes of that sentence were of this class: #740
2684/// (`B<cond>.W` T3 offset halved) and #930 (inner-block end label never
2685/// emitted, `b #0` placeholder). The encoder knows where every instruction
2686/// starts, so a target outside that set is a hard error here rather than
2687/// silent garbage on target.
2688///
2689/// Runs on the FINAL Thumb-2 stream for BOTH codegen paths — the direct
2690/// (`select_with_stack`, label branches byte-resolved above) and the optimized
2691/// (`optimizer_bridge`, numeric `BOffset`/`BCondOffset` pre-resolved inline) —
2692/// since both funnel through this encode pipeline. Two checks, jointly total
2693/// over local control flow:
2694///
2695/// 1. every numeric branch target is in the instruction-start set;
2696/// 2. no LOCAL (`.L`-prefixed) label branch survives unresolved — the resolver
2697///    deliberately skips labels it cannot find because an external target
2698///    (`Trap_Handler`, `func_N`) is legitimately absent and patched by
2699///    relocation, but a `.L` label is only ever defined in this same stream,
2700///    so an unresolved one is a dropped label (#930), not an external.
2701///
2702/// A32 (Cortex-R5) is fixed-width, so the mid-instruction class needs no gate
2703/// there (and its branches do not flow through the Thumb-2 resolver).
2704fn validate_branch_targets(instrs: &[ArmInstruction], encoder: &ArmEncoder) -> Result<(), String> {
2705    use std::collections::HashSet;
2706
2707    // Byte position of each element (`Label` encodes to 0 bytes, so a label's
2708    // position is exactly the start of the instruction that follows it).
2709    let mut positions = Vec::with_capacity(instrs.len());
2710    let mut pos: i64 = 0;
2711    for instr in instrs {
2712        positions.push(pos);
2713        pos += encoder
2714            .encode(&instr.op)
2715            .map_err(|e| format!("SC-5 branch-target gate: size probe failed: {}", e))?
2716            .len() as i64;
2717    }
2718    let starts: HashSet<i64> = positions.iter().copied().collect();
2719
2720    for (i, instr) in instrs.iter().enumerate() {
2721        let offset = match &instr.op {
2722            ArmOp::BOffset { offset } => *offset,
2723            ArmOp::BCondOffset { offset, .. } => *offset,
2724            ArmOp::B { label }
2725            | ArmOp::Bcc { label, .. }
2726            | ArmOp::Bhs { label }
2727            | ArmOp::Blo { label }
2728                if label.starts_with(".L") =>
2729            {
2730                return Err(format!(
2731                    "SC-5 branch-target gate: local branch label '{}' is not \
2732                     defined anywhere in the emitted stream (branch at byte \
2733                     offset 0x{:x}). A `.L` label is only ever defined locally, \
2734                     so this is a dropped label (the #930 class) — the branch \
2735                     would encode as a `b #0` placeholder and land \
2736                     mid-instruction. Refusing to emit a miscompiled object.",
2737                    label, positions[i]
2738                ));
2739            }
2740            _ => continue,
2741        };
2742        // Thumb branch semantics: target = branch_pc + 4 + 2*offset.
2743        let target = positions[i] + 4 + 2 * offset as i64;
2744        if !starts.contains(&target) {
2745            return Err(format!(
2746                "SC-5 branch-target gate: branch at byte offset 0x{:x} targets \
2747                 0x{:x}, which is not an instruction boundary (instruction-start \
2748                 set violation — the target lands mid-instruction, the \
2749                 #740/#930 class). Refusing to emit a miscompiled object.",
2750                positions[i], target
2751            ));
2752        }
2753    }
2754    Ok(())
2755}
2756
2757#[cfg(test)]
2758mod tests {
2759    use super::*;
2760    use synth_synthesis::{Operand2, Reg};
2761
2762    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
2763    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
2764    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
2765    /// byte-identical.
2766    #[test]
2767    fn test_rewrite_memory_grow_zero_539() {
2768        // the idiom -> memory.size
2769        assert_eq!(
2770            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
2771            vec![WasmOp::MemorySize(0)]
2772        );
2773        // const non-zero delta: NOT folded
2774        assert_eq!(
2775            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
2776            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
2777        );
2778        // runtime delta (no preceding const): NOT folded
2779        assert_eq!(
2780            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
2781            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
2782        );
2783        // a bare const-0 not feeding a grow is untouched
2784        assert_eq!(
2785            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
2786            vec![WasmOp::I32Const(0), WasmOp::I32Add]
2787        );
2788        // fold is local: surrounding ops preserved, indices past the fold intact
2789        assert_eq!(
2790            rewrite_memory_grow_zero(&[
2791                WasmOp::LocalGet(0),
2792                WasmOp::I32Const(0),
2793                WasmOp::MemoryGrow(0),
2794                WasmOp::I32Add,
2795            ]),
2796            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
2797        );
2798    }
2799
2800    /// SC-5 (#740/#930): the branch-target boundary gate. Every emitted branch
2801    /// target must be a member of the instruction-start set of the final
2802    /// Thumb-2 stream; a `.L`-local label branch surviving unresolved is a
2803    /// dropped label. Red-first: both rejection arms were written against the
2804    /// exact #930 stream shape (a `b #0` placeholder whose pc+4 target falls
2805    /// on the second halfword of a 32-bit `movw`) and fail without the gate.
2806    #[test]
2807    fn test_validate_branch_targets_sc5_930() {
2808        let enc = ArmEncoder::new_thumb2();
2809        let ins = |op: ArmOp| ArmInstruction {
2810            op,
2811            source_line: None,
2812        };
2813
2814        // 1. Boundary-valid stream: b over a wide movw onto the mov — OK.
2815        //    positions: 0 BOffset(2B), 2 Movw(4B), 6 Mov(2B)
2816        //    target = 0 + 4 + 2*1 = 6 = start of Mov.
2817        let good = vec![
2818            ins(ArmOp::BOffset { offset: 1 }),
2819            ins(ArmOp::Movw {
2820                rd: Reg::R3,
2821                imm16: 1,
2822            }),
2823            ins(ArmOp::Mov {
2824                rd: Reg::R0,
2825                op2: Operand2::Reg(Reg::R3),
2826            }),
2827        ];
2828        assert!(validate_branch_targets(&good, &enc).is_ok());
2829
2830        // 2. The exact #930 shape: `b #0` (offset 0) -> target = pc+4 = 4,
2831        //    the SECOND halfword of the 4-byte movw spanning 2..6. Hard error.
2832        let mid = vec![
2833            ins(ArmOp::BOffset { offset: 0 }),
2834            ins(ArmOp::Movw {
2835                rd: Reg::R3,
2836                imm16: 1,
2837            }),
2838            ins(ArmOp::Mov {
2839                rd: Reg::R0,
2840                op2: Operand2::Reg(Reg::R3),
2841            }),
2842        ];
2843        let err = validate_branch_targets(&mid, &enc).unwrap_err();
2844        assert!(err.contains("SC-5"), "boundary violation names SC-5: {err}");
2845        assert!(err.contains("not an instruction boundary"), "{err}");
2846
2847        // 3. Conditional form of the same violation.
2848        let mid_cond = vec![
2849            ins(ArmOp::BCondOffset {
2850                cond: synth_synthesis::Condition::NE,
2851                offset: 0,
2852            }),
2853            ins(ArmOp::Movw {
2854                rd: Reg::R3,
2855                imm16: 1,
2856            }),
2857            ins(ArmOp::Mov {
2858                rd: Reg::R0,
2859                op2: Operand2::Reg(Reg::R3),
2860            }),
2861        ];
2862        assert!(validate_branch_targets(&mid_cond, &enc).is_err());
2863
2864        // 4. A `.L`-local label branch that was never resolved (the dropped
2865        //    end label, #930's mechanism) is a hard error even though it
2866        //    would encode as a well-formed placeholder.
2867        let dropped = vec![
2868            ins(ArmOp::B {
2869                label: ".Lblock_end_3".to_string(),
2870            }),
2871            ins(ArmOp::Movw {
2872                rd: Reg::R3,
2873                imm16: 1,
2874            }),
2875        ];
2876        let err = validate_branch_targets(&dropped, &enc).unwrap_err();
2877        assert!(err.contains(".Lblock_end_3"), "{err}");
2878        assert!(err.contains("dropped label"), "{err}");
2879
2880        // 5. An EXTERNAL label branch (no `.L` prefix) is legitimately absent
2881        //    (patched via relocation / vector table) and must NOT trip the
2882        //    gate — the carve-out that used to swallow #930 stays for real
2883        //    externals only.
2884        let external = vec![
2885            ins(ArmOp::B {
2886                label: "Trap_Handler".to_string(),
2887            }),
2888            ins(ArmOp::Movw {
2889                rd: Reg::R3,
2890                imm16: 1,
2891            }),
2892        ];
2893        assert!(validate_branch_targets(&external, &enc).is_ok());
2894
2895        // 6. Labels are zero-width: a target on a Label position is the start
2896        //    of the instruction that follows it — OK.
2897        let labeled = vec![
2898            ins(ArmOp::BOffset { offset: 1 }),
2899            ins(ArmOp::Movw {
2900                rd: Reg::R3,
2901                imm16: 1,
2902            }),
2903            ins(ArmOp::Label {
2904                name: ".Lend".to_string(),
2905            }),
2906            ins(ArmOp::Mov {
2907                rd: Reg::R0,
2908                op2: Operand2::Reg(Reg::R3),
2909            }),
2910        ];
2911        assert!(validate_branch_targets(&labeled, &enc).is_ok());
2912    }
2913
2914    /// SC-5 (#930) end-to-end at the backend seam: the labels.wast `br_if2`
2915    /// shape — a `br_if` exiting an enclosing block from inside an `if`, its
2916    /// value operand a block-that-branches — must COMPILE (the pre-fix
2917    /// selector dropped the inner block's end label, which the SC-5 gate now
2918    /// turns into a hard error, so compile success proves the label was
2919    /// emitted) and every branch in the emitted bytes must land on an
2920    /// instruction boundary (re-derived from the encoded halfwords, not from
2921    /// the resolver's own bookkeeping).
2922    #[test]
2923    fn test_930_brif2_shape_compiles_and_targets_boundaries() {
2924        let backend = ArmBackend::new();
2925        let ops = vec![
2926            WasmOp::Block, // $l0 (result i32)
2927            WasmOp::I32Const(1),
2928            WasmOp::If,
2929            WasmOp::Block, // $l1 (result i32)
2930            WasmOp::I32Const(1),
2931            WasmOp::Br(0), // br $l1
2932            WasmOp::End,
2933            WasmOp::I32Const(1),
2934            WasmOp::BrIf(1), // br_if $l0
2935            WasmOp::Drop,
2936            WasmOp::End, // end if
2937            WasmOp::I32Const(0),
2938            WasmOp::End, // end $l0
2939            WasmOp::End,
2940        ];
2941        let config = CompileConfig::default();
2942        let func = backend
2943            .compile_function("t", &ops, &config)
2944            .expect("#930 shape must compile (SC-5 gate passes)");
2945
2946        // Walk the encoded halfwords: collect instruction starts, then check
2947        // every narrow/wide B / B<cond> target is a member.
2948        let code = &func.code;
2949        let mut starts = std::collections::HashSet::new();
2950        let mut widths = Vec::new();
2951        let mut off = 0usize;
2952        while off + 2 <= code.len() {
2953            starts.insert(off as i64);
2954            let hw = u16::from_le_bytes([code[off], code[off + 1]]);
2955            let wide = (hw & 0xF800) >= 0xE800; // 0b11101/0b11110/0b11111
2956            widths.push((off, hw, wide));
2957            off += if wide { 4 } else { 2 };
2958        }
2959        for (off, hw, wide) in widths {
2960            let target = if !wide && (hw & 0xF800) == 0xE000 {
2961                // T2 B: imm11, halfwords
2962                let imm = ((hw & 0x7FF) as i32) << 21 >> 21;
2963                Some(off as i64 + 4 + 2 * imm as i64)
2964            } else if !wide && (hw & 0xF000) == 0xD000 && (hw & 0x0F00) < 0x0E00 {
2965                // T1 B<cond>: imm8, halfwords
2966                let imm = ((hw & 0xFF) as i32) << 24 >> 24;
2967                Some(off as i64 + 4 + 2 * imm as i64)
2968            } else {
2969                None
2970            };
2971            if let Some(t) = target {
2972                assert!(
2973                    starts.contains(&t),
2974                    "branch at 0x{off:x} (hw 0x{hw:04x}) targets 0x{t:x}, \
2975                     not an instruction boundary — the #930 miscompile shape"
2976                );
2977            }
2978        }
2979    }
2980
2981    #[test]
2982    fn test_arm_backend_name() {
2983        let backend = ArmBackend::new();
2984        assert_eq!(backend.name(), "arm");
2985        assert!(backend.is_available());
2986    }
2987
2988    #[test]
2989    fn test_arm_backend_capabilities() {
2990        let backend = ArmBackend::new();
2991        let caps = backend.capabilities();
2992        assert!(!caps.produces_elf);
2993        assert!(caps.supports_rule_verification);
2994        assert!(!caps.is_external);
2995    }
2996
2997    #[test]
2998    fn test_compile_add_function() {
2999        let backend = ArmBackend::new();
3000        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3001        let config = CompileConfig::default();
3002
3003        let result = backend.compile_function("add", &ops, &config);
3004        assert!(result.is_ok());
3005
3006        let func = result.unwrap();
3007        assert_eq!(func.name, "add");
3008        assert!(!func.code.is_empty());
3009        assert_eq!(func.wasm_ops, ops);
3010    }
3011
3012    /// VCR-DBG-001: the per-instruction source map must cover the function with
3013    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
3014    /// code (it is captured at encode time, never serialized here).
3015    #[test]
3016    fn test_line_map_is_wellformed_dbg001() {
3017        let backend = ArmBackend::new();
3018        let ops = vec![
3019            WasmOp::LocalGet(0),
3020            WasmOp::LocalGet(1),
3021            WasmOp::I32Add,
3022            WasmOp::End,
3023        ];
3024        let config = CompileConfig::default();
3025        let func = backend.compile_function("add", &ops, &config).unwrap();
3026
3027        // Non-empty, and the first instruction starts at machine offset 0.
3028        assert!(
3029            !func.line_map.is_empty(),
3030            "a non-trivial function captures a source map"
3031        );
3032        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
3033
3034        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
3035        // bytes) and every mapped offset lies inside the emitted `.text`.
3036        for w in func.line_map.windows(2) {
3037            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
3038            assert!(
3039                w[1].0 - w[0].0 >= 2,
3040                "each ARM/Thumb instruction is >= 2 bytes"
3041            );
3042        }
3043        let last = func.line_map.last().unwrap().0 as usize;
3044        assert!(
3045            last < func.code.len(),
3046            "every mapped offset lies inside .text"
3047        );
3048
3049        // The side-table is additive: recompiling is deterministic and the map is
3050        // consistent with that exact code (capturing it does not alter output).
3051        let again = backend.compile_function("add", &ops, &config).unwrap();
3052        assert_eq!(
3053            again.code, func.code,
3054            "compilation deterministic; map is additive"
3055        );
3056        assert_eq!(again.line_map, func.line_map);
3057    }
3058
3059    #[test]
3060    fn test_count_params() {
3061        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3062        assert_eq!(count_params(&ops), 2);
3063
3064        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
3065        assert_eq!(count_params(&no_params), 0);
3066    }
3067
3068    /// #457: the declared param count caps the access-pattern inference. The
3069    /// repro shape `(param i32)(local i32) → p0 + local1` reads local 1 before
3070    /// any write, so `count_params` infers 2 — with the declared count (1) the
3071    /// local is reclassified onto the zero-inited frame path instead of being
3072    /// read from R1 (caller garbage).
3073    #[test]
3074    fn declared_param_count_caps_inference_457() {
3075        let ops = vec![
3076            WasmOp::LocalGet(0),
3077            WasmOp::LocalGet(1),
3078            WasmOp::I32Add,
3079            WasmOp::End,
3080        ];
3081        // The inference alone still says 2 (the misclassification this caps).
3082        assert_eq!(count_params(&ops), 2);
3083
3084        let backend = ArmBackend::new();
3085        let inferred = backend
3086            .compile_function("rbw", &ops, &CompileConfig::default())
3087            .unwrap();
3088        let declared = backend
3089            .compile_function(
3090                "rbw",
3091                &ops,
3092                &CompileConfig {
3093                    current_func_param_count: Some(1),
3094                    ..CompileConfig::default()
3095                },
3096            )
3097            .unwrap();
3098        // The cap is consumed: the declared-count compile reclassifies local 1
3099        // and must emit different code than the param-misclassified one.
3100        assert_ne!(
3101            inferred.code, declared.code,
3102            "declared param count must reach the selector"
3103        );
3104        // The zero-init is present: a 16-bit Thumb `movs rN, #0`
3105        // (0x2000 | rd<<8 → LE bytes [0x00, 0x20+rd]) somewhere in the body.
3106        let has_movs_zero = declared
3107            .code
3108            .as_chunks::<2>()
3109            .0
3110            .iter()
3111            .any(|h| h[0] == 0x00 && (0x20..=0x27).contains(&h[1]));
3112        assert!(
3113            has_movs_zero,
3114            "declared-count compile must zero-init the read-before-write local; code: {:02x?}",
3115            declared.code
3116        );
3117        // A declared count that matches (or exceeds) the inference changes
3118        // nothing — byte-identity for every function without rbw locals.
3119        let matching = backend
3120            .compile_function(
3121                "rbw",
3122                &ops,
3123                &CompileConfig {
3124                    current_func_param_count: Some(2),
3125                    ..CompileConfig::default()
3126                },
3127            )
3128            .unwrap();
3129        assert_eq!(
3130            matching.code, inferred.code,
3131            "declared >= inferred must stay byte-identical"
3132        );
3133    }
3134
3135    /// #970: a CONDITIONALLY-written param must stay a param.
3136    ///
3137    /// The read-first heuristic sees `LocalSet(1)` before any `LocalGet(1)` in
3138    /// LINEAR op order and demotes index 1 — even though the `if` means the
3139    /// write may not execute at all. `min(referenced, declared)` keeps it.
3140    /// The RED symptom this pins is not a wrong constant: the demoted local's
3141    /// first access is a WRITE, so the #457 zero-init skips it and the
3142    /// fall-through arm reads an UNINITIALISED frame slot (executed evidence:
3143    /// `scripts/repro/cond_write_param_970_arm_differential.py`).
3144    #[test]
3145    fn conditionally_written_param_stays_a_param_970() {
3146        // (param i32 i32): if (local.get 0) { local.set 1 = 5 }; local.get 1
3147        let ops = vec![
3148            WasmOp::LocalGet(0),
3149            WasmOp::If,
3150            WasmOp::I32Const(5),
3151            WasmOp::LocalSet(1),
3152            WasmOp::End,
3153            WasmOp::LocalGet(1),
3154            WasmOp::End,
3155        ];
3156        let declared = CompileConfig {
3157            current_func_param_count: Some(2),
3158            ..CompileConfig::default()
3159        };
3160        // The old rule: index 1 is written before it is read, so it is not
3161        // counted — this is the undercount that produced the miscompile.
3162        assert_eq!(
3163            count_params(&ops),
3164            1,
3165            "the read-first heuristic must still undercount (this is the defect)"
3166        );
3167        assert_eq!(
3168            effective_num_params(&ops, &declared),
3169            2,
3170            "a conditionally-written param must be counted as a param"
3171        );
3172        // The #457 direction is untouched: a genuine non-param local is still
3173        // clamped away by the declared count.
3174        let rbw = vec![
3175            WasmOp::LocalGet(0),
3176            WasmOp::LocalGet(1),
3177            WasmOp::I32Add,
3178            WasmOp::End,
3179        ];
3180        assert_eq!(
3181            effective_num_params(
3182                &rbw,
3183                &CompileConfig {
3184                    current_func_param_count: Some(1),
3185                    ..CompileConfig::default()
3186                }
3187            ),
3188            1,
3189            "#457: a read-before-write non-param local must NOT become a param"
3190        );
3191        // Leniency: a body touching only the first few of many declared params
3192        // still lowers with the small count (the selector homes at most 4 in
3193        // registers; `min` is what keeps this from becoming `declared`).
3194        assert_eq!(
3195            effective_num_params(
3196                &rbw,
3197                &CompileConfig {
3198                    current_func_param_count: Some(12),
3199                    ..CompileConfig::default()
3200                }
3201            ),
3202            2,
3203            "declared >> referenced must stay at the referenced count"
3204        );
3205        // No declared count: the legacy inference, unchanged (honest residual).
3206        assert_eq!(
3207            effective_num_params(&ops, &CompileConfig::default()),
3208            count_params(&ops)
3209        );
3210    }
3211
3212    #[test]
3213    fn test_arm_backend_register() {
3214        let mut registry = synth_core::BackendRegistry::new();
3215        registry.register(Box::new(ArmBackend::new()));
3216        assert!(registry.get("arm").is_some());
3217        assert_eq!(registry.available().len(), 1);
3218    }
3219
3220    #[test]
3221    fn test_compile_import_call_produces_relocations() {
3222        let backend = ArmBackend::new();
3223        // Simulate a WASM module where func index 0 is an import.
3224        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
3225        let ops = vec![WasmOp::Call(0)];
3226        let config = CompileConfig {
3227            num_imports: 1,
3228            no_optimize: true, // Direct instruction selection to preserve Call semantics
3229            ..CompileConfig::default()
3230        };
3231
3232        let result = backend.compile_function("caller", &ops, &config);
3233        assert!(result.is_ok());
3234
3235        let func = result.unwrap();
3236        assert!(!func.code.is_empty());
3237        assert_eq!(func.relocations.len(), 1);
3238        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
3239        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
3240        assert!(func.relocations[0].offset > 0);
3241    }
3242
3243    /// Regression test for #197: in `relocatable` mode, an import call must
3244    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
3245    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
3246    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
3247    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
3248    #[test]
3249    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
3250        let backend = ArmBackend::new();
3251        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
3252        let config = CompileConfig {
3253            num_imports: 1,
3254            relocatable: true,
3255            ..CompileConfig::default()
3256        };
3257
3258        let func = backend
3259            .compile_function("caller", &ops, &config)
3260            .expect("relocatable import call compiles");
3261
3262        assert_eq!(func.relocations.len(), 1);
3263        assert_eq!(
3264            func.relocations[0].symbol, "func_0",
3265            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
3266        );
3267    }
3268
3269    #[test]
3270    fn test_compile_no_imports_no_relocations() {
3271        let backend = ArmBackend::new();
3272        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3273        let config = CompileConfig::default();
3274
3275        let func = backend.compile_function("add", &ops, &config).unwrap();
3276        assert!(func.relocations.is_empty());
3277    }
3278
3279    /// Regression test for #167: a call to an INTERNAL function
3280    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
3281    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
3282    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
3283    /// to a garbage address — making the object non-linkable. This test
3284    /// would have caught that regression.
3285    #[test]
3286    fn test_compile_internal_call_produces_relocation_167() {
3287        let backend = ArmBackend::new();
3288        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
3289        let ops = vec![WasmOp::Call(2)];
3290        let config = CompileConfig {
3291            num_imports: 1,
3292            no_optimize: true,
3293            ..CompileConfig::default()
3294        };
3295
3296        let func = backend
3297            .compile_function("caller", &ops, &config)
3298            .expect("internal call compiles");
3299
3300        assert_eq!(
3301            func.relocations.len(),
3302            1,
3303            "an internal call must emit exactly one relocation (#167)"
3304        );
3305        assert_eq!(
3306            func.relocations[0].symbol, "func_2",
3307            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
3308        );
3309    }
3310
3311    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
3312
3313    #[test]
3314    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
3315        // Mpu mode must not introduce any inline check on ARM — the MPU
3316        // handles faults via hardware. The encoded bytes for an i32.load
3317        // should be identical between None and Mpu.
3318        let backend = ArmBackend::new();
3319        let ops = vec![
3320            WasmOp::LocalGet(0),
3321            WasmOp::I32Load {
3322                offset: 0,
3323                align: 2,
3324            },
3325        ];
3326        let cfg_none = CompileConfig {
3327            no_optimize: true,
3328            ..Default::default()
3329        };
3330        let cfg_mpu = CompileConfig {
3331            no_optimize: true,
3332            safety_bounds: SafetyBounds::Mpu,
3333            ..Default::default()
3334        };
3335        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3336        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3337        assert_eq!(
3338            n.code, m.code,
3339            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
3340        );
3341    }
3342
3343    #[test]
3344    fn arm_legacy_bounds_check_still_emits_software_check() {
3345        // Legacy CLI users with `--bounds-check` should keep getting the
3346        // software path even though the new SafetyBounds field defaults to None.
3347        let backend = ArmBackend::new();
3348        let ops = vec![
3349            WasmOp::LocalGet(0),
3350            WasmOp::I32Load {
3351                offset: 0,
3352                align: 2,
3353            },
3354        ];
3355        let cfg_legacy = CompileConfig {
3356            no_optimize: true,
3357            bounds_check: true,
3358            ..Default::default()
3359        };
3360        let cfg_software = CompileConfig {
3361            no_optimize: true,
3362            safety_bounds: SafetyBounds::Software,
3363            ..Default::default()
3364        };
3365        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
3366        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
3367        assert_eq!(
3368            l.code, s.code,
3369            "--bounds-check should produce the same bytes as --safety-bounds=software"
3370        );
3371    }
3372
3373    /// #377: `--safety-bounds software` must be enforced on the OPTIMIZED path
3374    /// too. Pre-fix, `software` was byte-identical to `none` there (a silent
3375    /// no-op while the safety manifest claimed enforcement). The compiled
3376    /// bytes must now (a) differ from `none` and (b) contain the inline
3377    /// `CMP ip, sl` + `UDF` guard.
3378    #[test]
3379    fn arm_safety_bounds_software_enforced_on_optimized_path_377() {
3380        let backend = ArmBackend::new();
3381        // Dynamic-address store+load: the optimized path accepts this shape
3382        // (no calls, no i64 params, ≤4 params).
3383        let ops = vec![
3384            WasmOp::LocalGet(0),
3385            WasmOp::LocalGet(1),
3386            WasmOp::I32Store {
3387                offset: 4,
3388                align: 2,
3389            },
3390            WasmOp::LocalGet(0),
3391            WasmOp::I32Load {
3392                offset: 0,
3393                align: 2,
3394            },
3395        ];
3396        // no_optimize NOT set — this exercises the optimized path.
3397        let cfg_none = CompileConfig::default();
3398        let cfg_sw = CompileConfig {
3399            safety_bounds: SafetyBounds::Software,
3400            ..Default::default()
3401        };
3402        let n = backend.compile_function("st", &ops, &cfg_none).unwrap();
3403        let s = backend.compile_function("st", &ops, &cfg_sw).unwrap();
3404        assert_ne!(
3405            n.code, s.code,
3406            "#377: software bounds must CHANGE optimized-path codegen (was a silent no-op)"
3407        );
3408        // Thumb-2 `UDF #0` is 0xDE00 (LE bytes: 00 DE); the #752
3409        // wraparound-safe guard's borrow check `CMP sl, ip` (16-bit
3410        // high-reg form) is 0x45E2 (LE: E2 45). Both must appear — one
3411        // guard per access, traps inline.
3412        let has_udf = s.code.windows(2).any(|w| w == [0x00, 0xDE]);
3413        let has_cmp_sl_ip = s.code.windows(2).any(|w| w == [0xE2, 0x45]);
3414        assert!(has_udf, "#377: inline UDF trap missing from optimized path");
3415        assert!(
3416            has_cmp_sl_ip,
3417            "#377/#752: CMP sl, ip bounds borrow-check missing from optimized path"
3418        );
3419        // And `none` must contain NO UDF (the function has no other trap).
3420        assert!(
3421            !n.code.windows(2).any(|w| w == [0x00, 0xDE]),
3422            "none must not contain a UDF for this function"
3423        );
3424    }
3425
3426    /// #377: `mpu` on the optimized path is codegen-passthrough — identical
3427    /// bytes to `none` on BOTH paths (hardware enforcement is target-level;
3428    /// synth does not emit MPU region programming — tracked separately in
3429    /// #377's fix-direction discussion). This pins path-parity for `mpu`.
3430    #[test]
3431    fn arm_safety_bounds_mpu_optimized_path_parity_377() {
3432        let backend = ArmBackend::new();
3433        let ops = vec![
3434            WasmOp::LocalGet(0),
3435            WasmOp::I32Load {
3436                offset: 0,
3437                align: 2,
3438            },
3439        ];
3440        let cfg_none = CompileConfig::default();
3441        let cfg_mpu = CompileConfig {
3442            safety_bounds: SafetyBounds::Mpu,
3443            ..Default::default()
3444        };
3445        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3446        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3447        assert_eq!(
3448            n.code, m.code,
3449            "Mpu and None must produce identical bytes on the optimized path too"
3450        );
3451    }
3452
3453    /// #377: `mask` on the optimized path declines to the direct selector
3454    /// (honest degradation) — the compiled function must equal the
3455    /// `--no-optimize` masking bytes, i.e. the flag is honored, never dropped.
3456    #[test]
3457    fn arm_safety_bounds_mask_optimized_path_declines_to_direct_377() {
3458        let backend = ArmBackend::new();
3459        let ops = vec![
3460            WasmOp::LocalGet(0),
3461            WasmOp::LocalGet(1),
3462            WasmOp::I32Store {
3463                offset: 0,
3464                align: 2,
3465            },
3466        ];
3467        // RQ-57-SENTINEL: mask now requires a STATED non-zero power-of-two
3468        // size (0 = zero-byte memory = refused), so the test states one —
3469        // exactly what the #953 fix required of the rv32 driver test.
3470        let cfg_mask_opt = CompileConfig {
3471            safety_bounds: SafetyBounds::Mask,
3472            linear_memory_bytes: 64 * 1024,
3473            ..Default::default()
3474        };
3475        let cfg_mask_direct = CompileConfig {
3476            no_optimize: true,
3477            safety_bounds: SafetyBounds::Mask,
3478            linear_memory_bytes: 64 * 1024,
3479            ..Default::default()
3480        };
3481        let o = backend.compile_function("st", &ops, &cfg_mask_opt).unwrap();
3482        let d = backend
3483            .compile_function("st", &ops, &cfg_mask_direct)
3484            .unwrap();
3485        assert_eq!(
3486            o.code, d.code,
3487            "#377: mask on the optimized path must fall back to the direct selector's masking"
3488        );
3489    }
3490
3491    /// RQ-57-SENTINEL (#953 sibling): `--safety-bounds mask` with a ZERO-byte
3492    /// linear memory must REFUSE at compile time. Before this fix, `bytes == 0`
3493    /// was exempt from the power-of-two gate ("0 means unknown"), and the
3494    /// emitted `SUB R12, R10, #1; AND` guard degenerated to an IDENTITY mask
3495    /// at runtime (R10 = 0 baked by the startup for a `(memory 0)` module):
3496    /// an unbounded OOB access in the mode whose purpose is bounding.
3497    /// Red-first: pre-fix this compile SUCCEEDED (verified on the v0.56.1
3498    /// tree: exit 0, `movw r10, #0x0` in the reset handler, AND-masked body).
3499    #[test]
3500    fn arm_safety_bounds_mask_zero_size_refused_rq57() {
3501        let backend = ArmBackend::new();
3502        let ops = vec![
3503            WasmOp::LocalGet(0),
3504            WasmOp::I32Load {
3505                offset: 0,
3506                align: 2,
3507            },
3508        ];
3509        let cfg = CompileConfig {
3510            safety_bounds: SafetyBounds::Mask,
3511            linear_memory_bytes: 0,
3512            ..Default::default()
3513        };
3514        let err = backend
3515            .compile_function("ld", &ops, &cfg)
3516            .expect_err("mask over a zero-byte memory must refuse, not emit an identity mask");
3517        let msg = format!("{err}");
3518        assert!(
3519            msg.contains("ZERO bytes"),
3520            "refusal must name the zero-byte cause, got: {msg}"
3521        );
3522    }
3523
3524    // ========================================================================
3525    // ISA feature gate tests — ensure the compiler never emits unsupported
3526    // instructions for a given target
3527    // ========================================================================
3528
3529    #[test]
3530    fn test_f32_rejected_on_cortex_m3_no_fpu() {
3531        let backend = ArmBackend::new();
3532        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3533        let config = CompileConfig {
3534            target: TargetSpec::cortex_m3(),
3535            no_optimize: true,
3536            ..CompileConfig::default()
3537        };
3538
3539        let result = backend.compile_function("fadd", &ops, &config);
3540        assert!(
3541            result.is_err(),
3542            "f32 operations should fail on Cortex-M3 (no FPU)"
3543        );
3544    }
3545
3546    #[test]
3547    fn test_f32_accepted_on_cortex_m4f() {
3548        let backend = ArmBackend::new();
3549        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3550        let config = CompileConfig {
3551            target: TargetSpec::cortex_m4f(),
3552            no_optimize: true,
3553            ..CompileConfig::default()
3554        };
3555
3556        let result = backend.compile_function("fadd", &ops, &config);
3557        assert!(
3558            result.is_ok(),
3559            "f32 operations should succeed on Cortex-M4F, got: {:?}",
3560            result.unwrap_err()
3561        );
3562    }
3563
3564    #[test]
3565    fn test_i32_works_on_all_targets() {
3566        let backend = ArmBackend::new();
3567        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3568
3569        // Cortex-M3 (no FPU)
3570        let config_m3 = CompileConfig {
3571            target: TargetSpec::cortex_m3(),
3572            no_optimize: true,
3573            ..CompileConfig::default()
3574        };
3575        assert!(
3576            backend.compile_function("add", &ops, &config_m3).is_ok(),
3577            "i32 ops should work on Cortex-M3"
3578        );
3579
3580        // Cortex-M4F (single FPU)
3581        let config_m4f = CompileConfig {
3582            target: TargetSpec::cortex_m4f(),
3583            no_optimize: true,
3584            ..CompileConfig::default()
3585        };
3586        assert!(
3587            backend.compile_function("add", &ops, &config_m4f).is_ok(),
3588            "i32 ops should work on Cortex-M4F"
3589        );
3590
3591        // Cortex-M7DP (double FPU)
3592        let config_m7dp = CompileConfig {
3593            target: TargetSpec::cortex_m7dp(),
3594            no_optimize: true,
3595            ..CompileConfig::default()
3596        };
3597        assert!(
3598            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
3599            "i32 ops should work on Cortex-M7DP"
3600        );
3601    }
3602
3603    #[test]
3604    fn test_f32_rejected_on_cortex_m4_no_fpu() {
3605        // Cortex-M4 (without F suffix) has no FPU
3606        let backend = ArmBackend::new();
3607        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
3608        let config = CompileConfig {
3609            target: TargetSpec::cortex_m4(),
3610            no_optimize: true,
3611            ..CompileConfig::default()
3612        };
3613
3614        let result = backend.compile_function("fmul", &ops, &config);
3615        assert!(
3616            result.is_err(),
3617            "f32 operations should fail on Cortex-M4 (no FPU)"
3618        );
3619    }
3620
3621    // ========================================================================
3622    // Issue #120 — f32 ops in the optimized lowering path
3623    //
3624    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
3625    // value-producing float op fell through to `Opcode::Nop`, leaving a
3626    // downstream consumer with an unmapped vreg and tripping the PR #101
3627    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
3628    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
3629    // module.
3630    //
3631    // Fix: `optimize_full` declines float modules with a typed `Err`;
3632    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
3633    // path, which handles f32 via VFP/FPU. These tests use the *default*
3634    // (optimized) config — `no_optimize` is NOT set — which is the exact
3635    // configuration that panicked pre-fix.
3636    // ========================================================================
3637
3638    /// RQ-65-DECLINE (#1208 / #1213 / #1205): a shape the optimized path
3639    /// used to lower WRONG must now reach the direct selector through the
3640    /// fallback, so the DEFAULT configuration is byte-identical to
3641    /// `--no-optimize` on it — the selector-parity property
3642    /// (`selector_parity_197_differential.py`), asserted at the unit level
3643    /// for one instance of each declined class.
3644    #[test]
3645    fn test_rq65_declined_shapes_default_equals_no_optimize() {
3646        let backend = ArmBackend::new();
3647        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3648            (
3649                "ld8u",
3650                vec![
3651                    WasmOp::LocalGet(0),
3652                    WasmOp::I64Load8U {
3653                        offset: 0,
3654                        align: 0,
3655                    },
3656                ],
3657            ),
3658            (
3659                "st16",
3660                vec![
3661                    WasmOp::LocalGet(0),
3662                    WasmOp::I64Const(7),
3663                    WasmOp::I64Store16 {
3664                        offset: 0,
3665                        align: 1,
3666                    },
3667                ],
3668            ),
3669            (
3670                "sel64",
3671                vec![
3672                    WasmOp::I64Const(1),
3673                    WasmOp::I64Const(0),
3674                    WasmOp::LocalGet(0),
3675                    WasmOp::Select,
3676                    WasmOp::I32WrapI64,
3677                ],
3678            ),
3679            (
3680                "vif",
3681                vec![
3682                    WasmOp::LocalGet(0),
3683                    WasmOp::LocalGet(1),
3684                    WasmOp::I32GtS,
3685                    WasmOp::If,
3686                    WasmOp::I32Const(7),
3687                    WasmOp::Else,
3688                    WasmOp::I32Const(9),
3689                    WasmOp::End,
3690                ],
3691            ),
3692        ];
3693        for (name, ops) in cases {
3694            let default = backend
3695                .compile_function(name, &ops, &CompileConfig::default())
3696                .unwrap_or_else(|e| {
3697                    panic!("{name}: default config must compile via the fallback: {e}")
3698                });
3699            let direct = backend
3700                .compile_function(
3701                    name,
3702                    &ops,
3703                    &CompileConfig {
3704                        no_optimize: true,
3705                        ..CompileConfig::default()
3706                    },
3707                )
3708                .unwrap_or_else(|e| panic!("{name}: --no-optimize must compile: {e}"));
3709            assert_eq!(
3710                default.code, direct.code,
3711                "{name}: the declined shape must be the direct selector's bytes"
3712            );
3713            assert!(default.code.len() > 2, "{name}: not the #1208 empty body");
3714        }
3715    }
3716
3717    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
3718    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
3719    /// the module and the backend falls back to direct selection, producing a
3720    /// non-empty f32.div lowering on a Cortex-M4F.
3721    #[test]
3722    fn test_issue120_f32_div_compiles_via_optimized_default() {
3723        let backend = ArmBackend::new();
3724        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3725        let config = CompileConfig {
3726            target: TargetSpec::cortex_m4f(),
3727            // no_optimize NOT set — this exercises the optimized path that
3728            // panicked in issue #120, then the fallback to direct selection.
3729            // GI-FPU-002: the f32 params must be declared so the direct
3730            // selector homes them in S0/S1 (AAPCS-VFP) rather than declining.
3731            current_func_params_f32: vec![true, true],
3732            ..CompileConfig::default()
3733        };
3734
3735        let result = backend.compile_function("fdiv", &ops, &config);
3736        assert!(
3737            result.is_ok(),
3738            "f32.div must compile on Cortex-M4F via the optimized->direct \
3739             fallback (issue #120), got: {:?}",
3740            result.as_ref().err()
3741        );
3742        assert!(
3743            !result.unwrap().code.is_empty(),
3744            "f32.div must produce non-empty machine code"
3745        );
3746    }
3747
3748    /// A spread of f32 ops, all through the optimized (default) config, must
3749    /// compile via the fallback on an FPU target without panicking.
3750    #[test]
3751    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
3752        let backend = ArmBackend::new();
3753        let config = CompileConfig {
3754            target: TargetSpec::cortex_m4f(),
3755            // GI-FPU-002: declare the two f32 params for AAPCS-VFP homing.
3756            current_func_params_f32: vec![true, true],
3757            ..CompileConfig::default()
3758        };
3759
3760        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3761            (
3762                "fadd",
3763                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
3764            ),
3765            (
3766                "fmul",
3767                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
3768            ),
3769            (
3770                "fsub",
3771                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
3772            ),
3773        ];
3774
3775        for (name, ops) in cases {
3776            let result = backend.compile_function(name, &ops, &config);
3777            assert!(
3778                result.is_ok(),
3779                "{name} must compile via the optimized->direct fallback \
3780                 (issue #120), got: {:?}",
3781                result.as_ref().err()
3782            );
3783            assert!(
3784                !result.unwrap().code.is_empty(),
3785                "{name} must produce non-empty machine code"
3786            );
3787        }
3788    }
3789
3790    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
3791    /// target must fail cleanly (not panic) even on the optimized path.
3792    #[test]
3793    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
3794        let backend = ArmBackend::new();
3795        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3796        let config = CompileConfig {
3797            target: TargetSpec::cortex_m3(),
3798            ..CompileConfig::default()
3799        };
3800
3801        let result = backend.compile_function("fdiv", &ops, &config);
3802        assert!(
3803            result.is_err(),
3804            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
3805        );
3806    }
3807
3808    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
3809    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
3810    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
3811    /// real cmp-chain instead of silently dropping it (which left all arms in
3812    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
3813    /// selector compare). Execution correctness is gated by
3814    /// `scripts/repro/br_table_507_differential.py`.
3815    #[test]
3816    fn test_507_br_table_declines_to_direct() {
3817        let backend = ArmBackend::new();
3818        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
3819        let ops = vec![
3820            WasmOp::Block,
3821            WasmOp::Block,
3822            WasmOp::Block,
3823            WasmOp::LocalGet(0),
3824            WasmOp::BrTable {
3825                targets: vec![0, 1, 2],
3826                default: 2,
3827            },
3828            WasmOp::End,
3829            WasmOp::I32Const(0),
3830            WasmOp::I32Const(10),
3831            WasmOp::I32Store {
3832                offset: 0,
3833                align: 2,
3834            },
3835            WasmOp::Return,
3836            WasmOp::End,
3837            WasmOp::I32Const(0),
3838            WasmOp::I32Const(20),
3839            WasmOp::I32Store {
3840                offset: 0,
3841                align: 2,
3842            },
3843            WasmOp::Return,
3844            WasmOp::End,
3845            WasmOp::I32Const(0),
3846            WasmOp::I32Const(30),
3847            WasmOp::I32Store {
3848                offset: 0,
3849                align: 2,
3850            },
3851        ];
3852        let opt = CompileConfig {
3853            target: TargetSpec::cortex_m4(),
3854            ..CompileConfig::default()
3855        };
3856        let direct = CompileConfig {
3857            target: TargetSpec::cortex_m4(),
3858            no_optimize: true,
3859            ..CompileConfig::default()
3860        };
3861        let a = backend
3862            .compile_function("dispatch", &ops, &opt)
3863            .expect("optimized-default must compile br_table (via decline)");
3864        let b = backend
3865            .compile_function("dispatch", &ops, &direct)
3866            .expect("direct must compile br_table");
3867        assert_eq!(
3868            a.code, b.code,
3869            "#507: optimized-default br_table output must be byte-identical to the \
3870             direct selector (i.e. declined to direct), not a dropped dispatch"
3871        );
3872    }
3873
3874    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
3875    /// FFI-return hi32 extract pattern. Compiles two near-identical
3876    /// functions — one with the optimized shift-by-32, one with a generic
3877    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
3878    #[test]
3879    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
3880        let backend = ArmBackend::new();
3881        let config = CompileConfig {
3882            target: TargetSpec::cortex_m4f(),
3883            ..CompileConfig::default()
3884        };
3885
3886        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
3887        // path now declines i64-param functions to the direct selector (it homed
3888        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
3889        // byte-size-only assertion masked). The canonical #94 case is a u64 from
3890        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
3891        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
3892        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
3893        // still exercised on CORRECT code.
3894        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
3895        let ops_hi32 = vec![
3896            WasmOp::LocalGet(0), // i32 param in R0
3897            WasmOp::I64ExtendI32S,
3898            WasmOp::I64Const(32),
3899            WasmOp::I64ShrU,
3900            WasmOp::I32WrapI64,
3901        ];
3902        let func_hi32 = backend
3903            .compile_function("hi32_extract", &ops_hi32, &config)
3904            .unwrap();
3905
3906        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
3907        // is not a multiple of 32, so it falls through to the runtime shift.
3908        let ops_generic = vec![
3909            WasmOp::LocalGet(0),
3910            WasmOp::I64ExtendI32S,
3911            WasmOp::I64Const(7),
3912            WasmOp::I64ShrU,
3913            WasmOp::I32WrapI64,
3914        ];
3915        let func_generic = backend
3916            .compile_function("generic_shr", &ops_generic, &config)
3917            .unwrap();
3918
3919        let bytes_hi32 = func_hi32.code.len();
3920        let bytes_generic = func_generic.code.len();
3921        println!(
3922            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
3923            bytes_hi32,
3924            bytes_generic,
3925            bytes_generic.saturating_sub(bytes_hi32)
3926        );
3927        let hex: String = func_hi32
3928            .code
3929            .iter()
3930            .map(|b| format!("{:02x}", b))
3931            .collect::<Vec<_>>()
3932            .join(" ");
3933        println!("[issue #94] hi32 bytes: {}", hex);
3934        // We expect the optimized form to be at least 30 bytes smaller than
3935        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
3936        assert!(
3937            bytes_hi32 + 30 <= bytes_generic,
3938            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
3939             expected optimized form to be at least 30 bytes smaller",
3940            bytes_hi32,
3941            bytes_generic,
3942        );
3943    }
3944}