synth_verify/fact_spec.rs
1//! Proof-carrying specialization — VCR-PERF-002 / #494 **Phase 2**: the
2//! single-elision prototype (value-range facts ⇒ dead conditional-branch
3//! elision, the `gust_mix` clamp shape).
4//!
5//! Design source of truth: `docs/design/proof-carrying-specialization.md`
6//! ("How synth consumes facts: the per-elision proof obligation"). loom is the
7//! PROVER (its validator discharged the `wsc.facts` invariants upstream);
8//! synth is a CONDITIONAL optimizer: it never re-derives a fact — it proves
9//! the correctness of its OWN transformation *given* the fact, per elision
10//! site, BEFORE emission, through the ordeal-backed [`BvSolver`]
11//! (certificate-checked pure-Rust QF_BV; every `Unsat` verdict carries an
12//! LRAT proof validated by the trusted `ordeal-lrat` checker before it is
13//! reported).
14//!
15//! # The transformation
16//!
17//! Working on the decoded [`WasmOp`] stream (backend-agnostic — the rewritten
18//! stream feeds whichever selector the driver picks), the pass walks the
19//! function top-level with a symbolic state (stack + locals as QF_BV terms via
20//! the existing [`WasmSemantics`] encoder) and, at every no-`else`
21//! `if … end`, discharges the obligation
22//!
23//! ```text
24//! premise P (every value-range fact reached so far, asserted as a hypothesis)
25//! obligation UNSAT( P ∧ cond ≠ 0 )
26//! ```
27//!
28//! `UNSAT(P ∧ cond ≠ 0)` implies the design doc's
29//! `UNSAT(P ∧ general_lowering(x) ≠ specialized_lowering(x))`: a no-`else`
30//! `if` whose condition is 0 on every P-admissible input never executes its
31//! body, and wasm validation forces a no-`else` `if` blocktype to have
32//! identical param/result types, so the not-taken path is the identity — the
33//! general and specialized lowerings agree on every input P admits. The
34//! stronger query is deliberately used because it is decided in the pure
35//! QF_BV fragment with no control-flow encoding.
36//!
37//! - **UNSAT (certificate-checked)** → the elision is ADMITTED: the
38//! condition-producing op slice (proven pure and contiguous) plus the whole
39//! `if … end` region are deleted; the certificate line is logged per
40//! function (the evidence trail).
41//! - **Sat / Unknown / conflict-budget exceeded / any shape outside the
42//! tracked fragment** → **DECLINE LOUDLY**: the general lowering is
43//! emitted. There is no silent wrong-code path; the conservative fallback
44//! is today's codegen.
45//!
46//! # Soundness of the symbolic tracking (over-approximation discipline)
47//!
48//! * Values produced by ops outside the tracked i32 fragment never enter the
49//! state: the walk STOPS at the first untracked op (no further elisions in
50//! the function; everything already admitted was justified independently).
51//! * Locals are seeded as fresh unconstrained variables (a superset of both
52//! parameter values and the zero-init of non-param locals — sound).
53//! * A DECLINED `if` region may or may not execute: every local it assigns
54//! (at any nesting depth) is havocked to a fresh variable, and its block
55//! results are pushed as fresh variables.
56//! * An ADMITTED `if` region provably never executes, so state is unchanged.
57//! * `div`/`rem` (i32 AND i64) are tracked since Phase 2b (#494
58//! divisor-nonzero), but NEVER deleted: they can trap, and a deleted
59//! condition slice must be effect-free under ALL inputs, not just
60//! P-admissible ones — so a div result always carries `start = None`
61//! (non-erasable) and its value is havocked to a fresh variable. What
62//! Phase 2b adds is per-site TRAP-GUARD elision marks consumed by the
63//! direct selector (see "The div/rem guard obligations" below).
64//!
65//! # The div/rem guard obligations (Phase 2b, #494 divisor-nonzero)
66//!
67//! A `div`/`rem` lowering carries up to TWO trap guards, and they fall to two
68//! INDEPENDENT obligations — this is the #633/#634 two-guard distinction:
69//!
70//! ```text
71//! divide-by-zero guard (div_u/div_s/rem_u/rem_s, i32+i64):
72//! UNSAT( P ∧ divisor == 0 )
73//! INT_MIN/-1 overflow guard (div_s ONLY; rem_s(INT_MIN,-1)==0 never traps):
74//! UNSAT( P ∧ dividend == INT_MIN ∧ divisor == -1 )
75//! ```
76//!
77//! A divisor-nonzero fact (kind 3) discharges the first but NOT the second —
78//! `divisor ≠ 0` does not exclude `divisor == -1`, so the overflow guard is
79//! RETAINED unless the premises independently prove the second obligation
80//! (e.g. a value-range fact `divisor ∈ [1, N]` proves both). Each discharged
81//! obligation becomes a per-site elision mark ([`FactSpecResult::elide_div_zero`]
82//! / [`FactSpecResult::elide_div_ovf`], indices into the RETURNED stream);
83//! the driver threads them to the direct selector, which omits exactly that
84//! guard. Sat / Unknown / no-premise ⇒ loud decline, the guard is emitted.
85//!
86//! # The memory bounds-guard obligation (#494 × #390 `guard_bool`)
87//!
88//! Under `--safety-bounds software` every i32 linear-memory access carries a
89//! 4-instruction inline guard (`ADD ip, addr, #(offset+size-1); CMP ip, R10;
90//! BLO +0; UDF #0` — see `generate_load_with_bounds_check`). When a premise
91//! on the INDEX proves the access in-bounds, the guard is provably dead:
92//!
93//! ```text
94//! UNSAT( P ∧ trap_mem_oob(zext64(index) + offset, size, min_memory_bytes) )
95//! ```
96//!
97//! The encoding is [`crate::trap::trap_mem_oob`] (ordeal 0.9.1's shape,
98//! `addr + size >u mem_bound` wraparound-safe), posed at width 64 — the
99//! 32-bit index is ZERO-extended and the static memarg `offset` added at 64
100//! bits, so the `index + offset` sum can never wrap the obligation into a
101//! false Unsat (WASM's effective address is `i + offset` at infinite
102//! precision for a 32-bit memory). `min_memory_bytes` is the module's
103//! DECLARED minimum linear-memory size: the runtime extent (R10) is always
104//! ≥ the declared minimum, so an access proven inside the minimum is inside
105//! every reachable runtime bound. Like div/rem, a memory op can trap, so it
106//! is TRACKED but never DELETED — the discharged obligation becomes a
107//! per-site mark ([`FactSpecResult::elide_mem_bounds`]) the direct selector
108//! consumes by emitting the access WITHOUT the software guard. Sat /
109//! Unknown / no-premise / unknown memory size ⇒ loud decline, the guard is
110//! emitted. Loaded values are havocked to fresh variables (memory contents
111//! are not modeled); stores need no memory model for the same reason.
112//!
113//! # Flag gating
114//!
115//! The driver only invokes this pass when `SYNTH_FACT_SPEC` is set (default
116//! OFF) AND the module carried a parseable `wsc.facts` section. Frozen
117//! fixtures carry no facts section, so every frozen anchor is bit-identical
118//! trivially; with the flag off the pass does not run at all.
119
120use crate::solver::{CheckOutcome, new_solver};
121use crate::term::{BV, Bool};
122use crate::wasm_semantics::WasmSemantics;
123use std::collections::{HashMap, HashSet};
124use synth_core::WasmOp;
125use synth_core::wsc_facts::{FactKind, WscFact};
126
127/// Outcome of specializing one function. `ops`/`block_arity`/`kept` are only
128/// meaningful when [`changed`](Self::changed) — otherwise they echo the input.
129#[derive(Debug)]
130pub struct FactSpecResult {
131 /// The (possibly rewritten) op stream.
132 pub ops: Vec<WasmOp>,
133 /// The blocktype-arity side-table matching `ops` (one entry per
134 /// `Block`/`Loop`/`If` in op order — entries of deleted openers removed).
135 pub block_arity: Vec<(u8, u8)>,
136 /// Indices into the ORIGINAL op stream that were kept, in order. Lets the
137 /// driver filter parallel side-tables (e.g. `op_offsets` for DWARF).
138 pub kept: Vec<usize>,
139 /// One certificate line per ADMITTED elision (logged per function).
140 pub admitted: Vec<String>,
141 /// One line per LOUD DECLINE (the general lowering is emitted for these).
142 pub declined: Vec<String>,
143 /// #494 phase 2b: indices (into the RETURNED `ops` stream) of div/rem
144 /// ops whose divide-by-zero trap guard was certificate-elided
145 /// (`UNSAT(P ∧ divisor == 0)` discharged per site).
146 pub elide_div_zero: Vec<usize>,
147 /// #494 phase 2b: indices (into the RETURNED `ops` stream) of `div_s`
148 /// ops whose `INT_MIN / -1` overflow guard was certificate-elided — a
149 /// SEPARATE obligation (`UNSAT(P ∧ dividend == INT_MIN ∧ divisor == -1)`);
150 /// a divisor-nonzero fact alone never lands here (#633/#634).
151 pub elide_div_ovf: Vec<usize>,
152 /// #494 bounds-elision (#390 `guard_bool`): indices (into the RETURNED
153 /// `ops` stream) of i32 memory accesses whose `--safety-bounds software`
154 /// guard was certificate-elided —
155 /// `UNSAT(P ∧ trap_mem_oob(zext64(index) + offset, size,
156 /// min_memory_bytes))` discharged per site (ordeal 0.9.1 `trap_mem_oob`
157 /// shape, wraparound-safe 64-bit extension).
158 pub elide_mem_bounds: Vec<usize>,
159 /// True when `ops` differs from the input (at least one region deletion).
160 stream_changed: bool,
161}
162
163impl FactSpecResult {
164 /// True when the op STREAM was rewritten (region deletions). Guard-elision
165 /// marks do not rewrite the stream — check
166 /// [`elide_div_zero`](Self::elide_div_zero) /
167 /// [`elide_div_ovf`](Self::elide_div_ovf) separately.
168 pub fn changed(&self) -> bool {
169 self.stream_changed
170 }
171}
172
173/// A symbolic operand-stack slot.
174#[derive(Clone)]
175struct Val {
176 bv: BV,
177 /// Start of the contiguous, side-effect-free op range that produced this
178 /// value — `None` when the producing slice is impure (`local.tee`) or not
179 /// provably contiguous. Only a `Some` slice may be deleted.
180 start: Option<usize>,
181 /// Index of the op that (last) produced this value.
182 created: usize,
183}
184
185/// Specialize one function's op stream against its `wsc.facts` premises.
186///
187/// `block_arity` is the decoder's ordinal side-table (one `(params, results)`
188/// entry per `Block`/`Loop`/`If` in op order); `facts` is the per-function
189/// slice (`CompileConfig::current_func_facts`); `params_i64` is the declared
190/// param-width table (`CompileConfig::current_func_params_i64` — `true` ⇒
191/// param `k` is 64-bit), which fixes the symbolic width of a param
192/// `local.get` (Phase 2b tracks i64 divisors); `linear_memory_bytes` is the
193/// module's DECLARED minimum linear-memory size in bytes
194/// (`CompileConfig::linear_memory_bytes`; `0` = unknown — every memory
195/// bounds-guard obligation then declines loudly). Total: every input yields
196/// a result — inapplicable shapes surface as loud declines, never errors.
197pub fn specialize_function(
198 func_name: &str,
199 ops: &[WasmOp],
200 block_arity: &[(u8, u8)],
201 facts: &[WscFact],
202 params_i64: &[bool],
203 linear_memory_bytes: u32,
204) -> FactSpecResult {
205 let mut pass = Pass::new(
206 func_name,
207 ops,
208 block_arity,
209 facts,
210 params_i64,
211 linear_memory_bytes,
212 );
213 pass.walk();
214 pass.finish()
215}
216
217/// #494 phase 2b RED-TEAM lever (debug builds ONLY): treat a Sat verdict on
218/// the divide-by-zero guard obligation as an admit anyway. Exists so the
219/// differential oracle can DEMONSTRATE the divergence an unsound admit would
220/// cause (wasmtime traps at divisor == 0, the forced build does not) and then
221/// show the Sat-decline restoring the guard byte-identically. Compiled out of
222/// release builds; every forced admit screams in its certificate line.
223#[cfg(debug_assertions)]
224fn force_admit_unsound() -> bool {
225 std::env::var("SYNTH_FACT_SPEC_FORCE_ADMIT").is_ok_and(|v| v != "0")
226}
227
228#[cfg(not(debug_assertions))]
229fn force_admit_unsound() -> bool {
230 false
231}
232
233struct Pass<'a> {
234 func: &'a str,
235 ops: &'a [WasmOp],
236 block_arity: &'a [(u8, u8)],
237 /// op index → ordinal into `block_arity` (for `Block`/`Loop`/`If` ops).
238 opener_ordinal: HashMap<usize, usize>,
239 /// op index → signed range fact attached to that op's result (raw s64
240 /// bounds; clamped to the value's width at attach time).
241 range_facts: HashMap<usize, (i64, i64)>,
242 /// op indices carrying a divisor-nonzero fact (kind 3): `value ≠ 0`.
243 nonzero_facts: HashSet<usize>,
244 /// Declared param widths (`true` ⇒ 64-bit) — fixes `local.get` widths.
245 params_i64: &'a [bool],
246 /// The module's DECLARED minimum linear-memory size in bytes; `0` =
247 /// unknown (bounds-guard obligations decline).
248 mem_bound: u32,
249 sem: WasmSemantics,
250 stack: Vec<Val>,
251 locals: HashMap<u32, BV>,
252 /// Every fresh variable created (name order), for Sat counterexamples.
253 vars: Vec<BV>,
254 fresh: u32,
255 premises: Vec<Bool>,
256 premise_desc: Vec<String>,
257 /// Inclusive op-index ranges to delete (disjoint, ascending).
258 deletions: Vec<(usize, usize)>,
259 admitted: Vec<String>,
260 declined: Vec<String>,
261 /// #494 phase 2b: ORIGINAL op indices marked for zero-guard elision.
262 zero_marks: Vec<usize>,
263 /// #494 phase 2b: ORIGINAL op indices marked for overflow-guard elision.
264 ovf_marks: Vec<usize>,
265 /// #494 bounds-elision: ORIGINAL op indices of memory accesses whose
266 /// software bounds guard was certificate-proven dead.
267 mem_marks: Vec<usize>,
268}
269
270impl<'a> Pass<'a> {
271 fn new(
272 func: &'a str,
273 ops: &'a [WasmOp],
274 block_arity: &'a [(u8, u8)],
275 facts: &'a [WscFact],
276 params_i64: &'a [bool],
277 mem_bound: u32,
278 ) -> Self {
279 let mut opener_ordinal = HashMap::new();
280 let mut ord = 0usize;
281 for (i, op) in ops.iter().enumerate() {
282 if matches!(op, WasmOp::Block | WasmOp::Loop | WasmOp::If) {
283 opener_ordinal.insert(i, ord);
284 ord += 1;
285 }
286 }
287 let mut range_facts = HashMap::new();
288 let mut nonzero_facts = HashSet::new();
289 for f in facts {
290 // Out-of-range value_id is vacuous (encoding doc's rule).
291 if (f.value_id as usize) >= ops.len() {
292 continue;
293 }
294 match f.kind {
295 FactKind::ValueRange { lo, hi } => {
296 // Raw s64 bounds; clamped to the value's width when the
297 // walk attaches the premise. An inverted bound is vacuous.
298 if lo <= hi {
299 range_facts.insert(f.value_id as usize, (lo, hi));
300 }
301 }
302 // #494 phase 2b: divisor-nonzero (kind 3) — `value ≠ 0`.
303 FactKind::DivisorNonZero => {
304 nonzero_facts.insert(f.value_id as usize);
305 }
306 _ => {}
307 }
308 }
309 Self {
310 func,
311 ops,
312 block_arity,
313 opener_ordinal,
314 range_facts,
315 nonzero_facts,
316 params_i64,
317 mem_bound,
318 // No memory model needed: loaded values are havocked to fresh
319 // variables (only the ACCESS BOUND is reasoned about, never the
320 // contents), so stores need no modeling either.
321 sem: WasmSemantics::new_with_memory(Vec::new()),
322 stack: Vec::new(),
323 locals: HashMap::new(),
324 vars: Vec::new(),
325 fresh: 0,
326 premises: Vec::new(),
327 premise_desc: Vec::new(),
328 deletions: Vec::new(),
329 admitted: Vec::new(),
330 declined: Vec::new(),
331 zero_marks: Vec::new(),
332 ovf_marks: Vec::new(),
333 mem_marks: Vec::new(),
334 }
335 }
336
337 fn fresh_var(&mut self, name: String) -> BV {
338 let v = BV::new_const(name, 32);
339 self.vars.push(v.clone());
340 v
341 }
342
343 fn local_bv(&mut self, idx: u32) -> BV {
344 if let Some(bv) = self.locals.get(&idx) {
345 return bv.clone();
346 }
347 // A not-yet-seen local's width comes from the declared param table
348 // (#494 phase 2b tracks i64 divisors); non-param locals default to
349 // 32 bits — an i64 op reading one fails the width check and declines.
350 let width = if self.params_i64.get(idx as usize).copied().unwrap_or(false) {
351 64
352 } else {
353 32
354 };
355 let v = BV::new_const(format!("fs_l{idx}"), width);
356 self.vars.push(v.clone());
357 self.locals.insert(idx, v.clone());
358 v
359 }
360
361 /// Attach the premises of every fact naming op `i`'s result, at the
362 /// value's own width.
363 fn attach_fact(&mut self, i: usize, bv: &BV) {
364 let width = bv.get_size();
365 if let Some(&(lo, hi)) = self.range_facts.get(&i) {
366 // Clamp the s64 bound to the value's width (the phase-2 rule for
367 // 32-bit values; 64-bit values take the bound verbatim). A bound
368 // that inverts after clamping is impossible for a genuine value
369 // of this width — fact validity is loom's obligation (trust
370 // split), so we keep the phase-2 clamp semantics unchanged.
371 let (lo, hi) = if width == 32 {
372 (
373 lo.clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
374 hi.clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
375 )
376 } else {
377 (lo, hi)
378 };
379 let lo_bv = BV::from_i64(lo, width);
380 let hi_bv = BV::from_i64(hi, width);
381 let p = Bool::and(&[&bv.bvsge(&lo_bv), &bv.bvsle(&hi_bv)]);
382 self.premises.push(p);
383 self.premise_desc
384 .push(format!("value(op#{i}) ∈ [{lo}, {hi}] (signed, i{width})"));
385 }
386 if self.nonzero_facts.contains(&i) {
387 // #494 phase 2b: divisor-nonzero (kind 3).
388 let p = bv.ne(BV::from_i64(0, width));
389 self.premises.push(p);
390 self.premise_desc
391 .push(format!("value(op#{i}) ≠ 0 (i{width})"));
392 }
393 }
394
395 fn push(&mut self, bv: BV, start: Option<usize>, created: usize) {
396 self.stack.push(Val { bv, start, created });
397 }
398
399 /// Find the matching `End` for the opener at `i`; also reports whether a
400 /// top-level `Else` occurs. `None` = malformed nesting (stop the walk).
401 fn matching_end(&self, i: usize) -> Option<(usize, bool)> {
402 let mut depth = 0usize;
403 let mut has_else = false;
404 for (j, op) in self.ops.iter().enumerate().skip(i + 1) {
405 match op {
406 WasmOp::Block | WasmOp::Loop | WasmOp::If => depth += 1,
407 WasmOp::Else if depth == 0 => has_else = true,
408 WasmOp::End => {
409 if depth == 0 {
410 return Some((j, has_else));
411 }
412 depth -= 1;
413 }
414 _ => {}
415 }
416 }
417 None
418 }
419
420 /// Continuation after a DECLINED `if` region `[i..=end]`: the body may or
421 /// may not run, so havoc every local it assigns (any depth) and model its
422 /// block results as fresh variables.
423 fn havoc_region(&mut self, i: usize, end: usize, arity: (u8, u8)) {
424 let ops = self.ops;
425 for op in &ops[i + 1..end] {
426 if let WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) = op {
427 let n = self.fresh;
428 self.fresh += 1;
429 let v = self.fresh_var(format!("fs_h{n}"));
430 self.locals.insert(*idx, v);
431 }
432 }
433 for _ in 0..arity.0 {
434 self.stack.pop();
435 }
436 for k in 0..arity.1 {
437 let n = self.fresh;
438 self.fresh += 1;
439 let v = self.fresh_var(format!("fs_r{n}_{k}"));
440 self.push(v, None, end);
441 }
442 }
443
444 fn decline(&mut self, msg: String) {
445 self.declined
446 .push(format!("{}: {} — general lowering emitted", self.func, msg));
447 }
448
449 /// #494 phase 2b: discharge the per-site div/rem trap-guard obligations
450 /// for the op at `i` (`op_name`, operand width `width`, dividend `a`,
451 /// divisor `b`), recording elision marks for the lowering. TWO independent
452 /// obligations (the #633/#634 two-guard distinction):
453 ///
454 /// - zero guard (every div/rem): `UNSAT(P ∧ divisor == 0)`;
455 /// - overflow guard (`div_s` only): `UNSAT(P ∧ dividend == INT_MIN ∧
456 /// divisor == -1)` — divisor-nonzero alone NEVER discharges this.
457 ///
458 /// Sat / Unknown / no-premise ⇒ loud decline; the guard is emitted.
459 fn try_elide_div_guards(&mut self, i: usize, op_name: &str, is_div_s: bool, a: &Val, b: &Val) {
460 let width = b.bv.get_size();
461 if self.premises.is_empty() {
462 self.decline(format!(
463 "op#{i} {op_name} — no premise reaches this site; both trap guards retained"
464 ));
465 return;
466 }
467 // Obligation 1: the divide-by-zero guard.
468 let mut solver = new_solver();
469 for p in &self.premises {
470 solver.assert(p);
471 }
472 solver.assert(&b.bv.eq(BV::from_i64(0, width)));
473 match solver.check() {
474 CheckOutcome::Unsat => {
475 self.zero_marks.push(i);
476 self.admitted.push(format!(
477 "{}: op#{i} {op_name} — divide-by-zero guard elided: UNSAT(P ∧ divisor == 0) via {} (certificate-checked QF_BV; every Unsat carries an LRAT proof validated by ordeal-lrat); P = {{{}}}; divisor = {}",
478 self.func,
479 solver.name(),
480 self.premise_desc.join(" ∧ "),
481 b.bv,
482 ));
483 }
484 CheckOutcome::Sat => {
485 let cex = self.counterexample(solver.as_ref());
486 if force_admit_unsound() {
487 // RED-TEAM lever (debug builds only): admit the Sat site
488 // anyway so the differential oracle can demonstrate the
489 // divergence. Screams, and still logs the model.
490 self.zero_marks.push(i);
491 self.admitted.push(format!(
492 "{}: op#{i} {op_name} — divide-by-zero guard elided by UNSOUND FORCED ADMIT (SYNTH_FACT_SPEC_FORCE_ADMIT, red-team oracle lever, debug builds only) — obligation was Sat (counterexample: {cex}); NEVER use in production",
493 self.func,
494 ));
495 } else {
496 self.decline(format!(
497 "op#{i} {op_name} — zero-guard obligation Sat (divisor can be 0 under P; counterexample: {cex}); guard retained"
498 ));
499 }
500 }
501 CheckOutcome::Unknown(reason) => {
502 self.decline(format!(
503 "op#{i} {op_name} — zero-guard obligation Unknown ({reason}); conservative decline, guard retained"
504 ));
505 }
506 }
507 // Obligation 2: the INT_MIN/-1 overflow guard — div_s only, and a
508 // SEPARATE proof (#633/#634): divisor ≠ 0 does not exclude -1.
509 if !is_div_s {
510 return;
511 }
512 let int_min = if width == 64 {
513 i64::MIN
514 } else {
515 i64::from(i32::MIN)
516 };
517 let mut solver = new_solver();
518 for p in &self.premises {
519 solver.assert(p);
520 }
521 solver.assert(&a.bv.eq(BV::from_i64(int_min, width)));
522 solver.assert(&b.bv.eq(BV::from_i64(-1, width)));
523 match solver.check() {
524 CheckOutcome::Unsat => {
525 self.ovf_marks.push(i);
526 self.admitted.push(format!(
527 "{}: op#{i} {op_name} — INT{width}_MIN/-1 overflow guard elided: UNSAT(P ∧ dividend == INT{width}_MIN ∧ divisor == -1) via {} (certificate-checked QF_BV; every Unsat carries an LRAT proof validated by ordeal-lrat); P = {{{}}}",
528 self.func,
529 solver.name(),
530 self.premise_desc.join(" ∧ "),
531 ));
532 }
533 CheckOutcome::Sat => {
534 let cex = self.counterexample(solver.as_ref());
535 self.decline(format!(
536 "op#{i} {op_name} — overflow-guard obligation Sat (dividend == INT{width}_MIN with divisor == -1 is possible under P; counterexample: {cex}); the #633 overflow guard is RETAINED — a divisor-nonzero premise alone never elides it"
537 ));
538 }
539 CheckOutcome::Unknown(reason) => {
540 self.decline(format!(
541 "op#{i} {op_name} — overflow-guard obligation Unknown ({reason}); conservative decline, the #633 overflow guard is RETAINED"
542 ));
543 }
544 }
545 }
546
547 /// #494 bounds-elision (#390 `guard_bool`): discharge the software
548 /// bounds-guard obligation for the i32 memory access at `i` (`op_name`,
549 /// byte width `access_size`, static memarg `offset`, index value `addr`),
550 /// recording an elision mark for the lowering:
551 ///
552 /// ```text
553 /// UNSAT( P ∧ trap_mem_oob(zext64(addr) + offset, access_size,
554 /// min_memory_bytes) )
555 /// ```
556 ///
557 /// The trap condition is [`crate::trap::trap_mem_oob`] (ordeal 0.9.1's
558 /// `addr + size >u mem_bound`, wraparound-safe), posed at width 64: the
559 /// 32-bit index is ZERO-extended and `offset` added at 64 bits, so the
560 /// effective-address sum cannot wrap into a false Unsat — exactly WASM's
561 /// infinite-precision `i + offset`. Proving the access inside the
562 /// DECLARED minimum memory (`mem_bound`) proves it inside every runtime
563 /// extent R10 can hold (runtime size ≥ declared minimum). Sat / Unknown
564 /// / no-premise / unknown memory size ⇒ loud decline; the guard is
565 /// emitted.
566 fn try_elide_mem_bounds(
567 &mut self,
568 i: usize,
569 op_name: &str,
570 access_size: u32,
571 offset: u32,
572 addr: &Val,
573 ) {
574 if self.mem_bound == 0 {
575 self.decline(format!(
576 "op#{i} {op_name} — linear-memory size unknown (no module memory \
577 context); bounds guard retained"
578 ));
579 return;
580 }
581 if self.premises.is_empty() {
582 self.decline(format!(
583 "op#{i} {op_name} — no premise reaches this site; bounds guard retained"
584 ));
585 return;
586 }
587 // Wraparound-safe width extension: zext the 32-bit index to 64 bits,
588 // add the static offset at 64 bits (no 2^64 wrap is reachable:
589 // index < 2^32, offset < 2^32, size ≤ 8).
590 let ea = addr
591 .bv
592 .zero_ext(32)
593 .bvadd(BV::from_u64(u64::from(offset), 64));
594 let trap = crate::trap::trap_mem_oob(
595 &ea,
596 &BV::from_u64(u64::from(access_size), 64),
597 &BV::from_u64(u64::from(self.mem_bound), 64),
598 );
599 let mut solver = new_solver();
600 for p in &self.premises {
601 solver.assert(p);
602 }
603 solver.assert(&trap);
604 match solver.check() {
605 CheckOutcome::Unsat => {
606 self.mem_marks.push(i);
607 self.admitted.push(format!(
608 "{}: op#{i} {op_name} (offset={offset}, {access_size} B) — software \
609 bounds guard elided: UNSAT(P ∧ trap_mem_oob(zext64(index) + offset, \
610 size, {} B declared-min memory)) via {} (certificate-checked QF_BV; \
611 every Unsat carries an LRAT proof validated by ordeal-lrat); \
612 P = {{{}}}; index = {}",
613 self.func,
614 self.mem_bound,
615 solver.name(),
616 self.premise_desc.join(" ∧ "),
617 addr.bv,
618 ));
619 }
620 CheckOutcome::Sat => {
621 let cex = self.counterexample(solver.as_ref());
622 if force_admit_unsound() {
623 // RED-TEAM lever (debug builds only): admit the Sat site
624 // anyway so the differential oracle can demonstrate the
625 // divergence. Screams, and still logs the model.
626 self.mem_marks.push(i);
627 self.admitted.push(format!(
628 "{}: op#{i} {op_name} — bounds guard elided by UNSOUND FORCED \
629 ADMIT (SYNTH_FACT_SPEC_FORCE_ADMIT, red-team oracle lever, \
630 debug builds only) — obligation was Sat (counterexample: \
631 {cex}); NEVER use in production",
632 self.func,
633 ));
634 } else {
635 self.decline(format!(
636 "op#{i} {op_name} — bounds-guard obligation Sat (the access can \
637 exceed the {} B declared-min memory under P; counterexample: \
638 {cex}); guard retained",
639 self.mem_bound,
640 ));
641 }
642 }
643 CheckOutcome::Unknown(reason) => {
644 self.decline(format!(
645 "op#{i} {op_name} — bounds-guard obligation Unknown ({reason}); \
646 conservative decline, guard retained"
647 ));
648 }
649 }
650 }
651
652 /// Read the model back for an actionable counterexample string.
653 fn counterexample(&self, solver: &dyn crate::solver::BvSolver) -> String {
654 let cex: Vec<String> = self
655 .vars
656 .iter()
657 .filter_map(|v| {
658 let name = format!("{v}");
659 solver.value(v).map(|x| {
660 if v.get_size() == 64 {
661 format!("{name}={}", x as u64 as i64)
662 } else {
663 format!("{name}={}", x as u32 as i32)
664 }
665 })
666 })
667 .collect();
668 if cex.is_empty() {
669 "<no model>".to_string()
670 } else {
671 cex.join(", ")
672 }
673 }
674
675 /// Discharge the per-elision obligation for the no-`else` `if` at `i`
676 /// (matching `End` at `end`, condition `cond`). Returns true iff admitted.
677 fn try_elide(&mut self, i: usize, end: usize, cond: &Val) -> bool {
678 if self.premises.is_empty() {
679 self.decline(format!(
680 "op#{i} `if` — no premise reaches this site (no usable value-range fact)"
681 ));
682 return false;
683 }
684 let mut solver = new_solver();
685 for p in &self.premises {
686 solver.assert(p);
687 }
688 let taken = cond.bv.ne(BV::from_i64(0, 32));
689 solver.assert(&taken);
690 match solver.check() {
691 CheckOutcome::Unsat => {
692 let Some(start) = cond.start else {
693 // Proven dead, but the condition slice has a side effect
694 // (`local.tee`) or is not provably contiguous — deleting
695 // it could drop live work. Conservative: keep everything.
696 self.decline(format!(
697 "op#{i} `if` proven dead (UNSAT) but its condition slice is not \
698 erasable (impure or non-contiguous producer)"
699 ));
700 return false;
701 };
702 self.deletions.push((start, end));
703 self.admitted.push(format!(
704 "{}: op#{i} `if` (+condition slice) — ops [{start}..={end}] elided \
705 ({} ops): UNSAT(P ∧ cond ≠ 0) via {} (certificate-checked QF_BV; \
706 every Unsat carries an LRAT proof validated by ordeal-lrat); \
707 P = {{{}}}; cond = {}",
708 self.func,
709 end - start + 1,
710 solver.name(),
711 self.premise_desc.join(" ∧ "),
712 cond.bv,
713 ));
714 true
715 }
716 CheckOutcome::Sat => {
717 // Read the model back for an actionable counterexample.
718 let cex: Vec<String> = self
719 .vars
720 .iter()
721 .filter_map(|v| {
722 let name = format!("{v}");
723 solver
724 .value(v)
725 .map(|x| format!("{name}={}", x as u32 as i32))
726 })
727 .collect();
728 self.decline(format!(
729 "op#{i} `if` — obligation Sat (branch reachable under P; \
730 counterexample: {})",
731 if cex.is_empty() {
732 "<no model>".to_string()
733 } else {
734 cex.join(", ")
735 }
736 ));
737 false
738 }
739 CheckOutcome::Unknown(reason) => {
740 self.decline(format!(
741 "op#{i} `if` — obligation Unknown ({reason}); conservative decline"
742 ));
743 false
744 }
745 }
746 }
747
748 /// Discharge the select-collapse obligation for the branchless `select`
749 /// at op `i`. The operands are `(val1, val2, cond)` in wasm select order
750 /// (`val1` deepest, `cond` on top); the runtime result is
751 /// `(cond != 0) ? val1 : val2`. When a value-range premise pins the
752 /// condition CONSTANT under `P` the select collapses to one operand — the
753 /// branchless sibling of the Phase-2 no-else `if` elision, and the shape
754 /// gust_mix's `clamp` actually uses (`max`/`min` via `select`).
755 ///
756 /// Two mutually exclusive obligations, both certificate-checked QF_BV.
757 /// `UNSAT(P ∧ cond ≠ 0)` means `cond` is always 0, so the result is `val2`
758 /// (delete `val1`'s producer slice plus the condition-slice-through-
759 /// `select`). `UNSAT(P ∧ cond == 0)` means `cond` is always non-zero, so
760 /// the result is `val1` (delete the `val2`+condition+`select` contiguous
761 /// slice). Anything else (Sat both ways = genuinely non-constant; Unknown;
762 /// an impure/non-contiguous erasable slice) DECLINES LOUDLY and the general
763 /// branchless select stands. Returns the surviving operand's `Val` on
764 /// admit, `None` on decline.
765 fn try_collapse_select(&mut self, i: usize, val1: &Val, val2: &Val, cond: &Val) -> Option<Val> {
766 if self.premises.is_empty() {
767 self.decline(format!(
768 "op#{i} select — no premise reaches this site (no usable value-range fact)"
769 ));
770 return None;
771 }
772 // The condition slice must be a pure, contiguous producer ending
773 // immediately before the `select` — otherwise deleting it could drop
774 // live work (`local.tee`) or leave a gap.
775 let Some(sc) = cond.start else {
776 self.decline(format!(
777 "op#{i} select — condition slice is impure or non-contiguous (not erasable)"
778 ));
779 return None;
780 };
781 if cond.created + 1 != i {
782 self.decline(format!(
783 "op#{i} select — condition is not produced immediately before the select \
784 (non-contiguous)"
785 ));
786 return None;
787 }
788
789 // Obligation B first (the clamp shape: the guard condition is
790 // constant-FALSE, so the identity operand `val2` survives).
791 let mut solver = new_solver();
792 for p in &self.premises {
793 solver.assert(p);
794 }
795 solver.assert(&cond.bv.ne(BV::from_i64(0, 32)));
796 match solver.check() {
797 CheckOutcome::Unsat => {
798 // cond ≡ 0 ⇒ result = val2. Delete val1's slice AND the
799 // condition-slice-through-select. val2 (kept) sits between.
800 let Some(s1) = val1.start else {
801 self.decline(format!(
802 "op#{i} select proven false-arm (UNSAT cond ≠ 0) but the val1 slice \
803 is not erasable (impure/non-contiguous) — collapse declined"
804 ));
805 return None;
806 };
807 if val1.created >= sc {
808 self.decline(format!(
809 "op#{i} select — val1 slice overlaps the condition slice; collapse \
810 declined"
811 ));
812 return None;
813 }
814 self.deletions.push((s1, val1.created));
815 self.deletions.push((sc, i));
816 self.admitted.push(format!(
817 "{}: op#{i} select — collapsed to the false-arm (val2): \
818 UNSAT(P ∧ cond ≠ 0) via {} (certificate-checked QF_BV; every Unsat \
819 carries an LRAT proof validated by ordeal-lrat); deleted val1 slice \
820 [{s1}..={}] + condition/select [{sc}..={i}]; P = {{{}}}; cond = {}",
821 self.func,
822 solver.name(),
823 val1.created,
824 self.premise_desc.join(" ∧ "),
825 cond.bv,
826 ));
827 return Some(val2.clone());
828 }
829 CheckOutcome::Sat => { /* cond can be non-zero — try obligation A */ }
830 CheckOutcome::Unknown(reason) => {
831 self.decline(format!(
832 "op#{i} select — false-arm obligation Unknown ({reason}); conservative \
833 decline"
834 ));
835 return None;
836 }
837 }
838
839 // Obligation A: cond ≡ non-zero ⇒ result = val1. Delete the
840 // val2+condition+select contiguous slice.
841 let mut solver = new_solver();
842 for p in &self.premises {
843 solver.assert(p);
844 }
845 solver.assert(&cond.bv.eq(BV::from_i64(0, 32)));
846 match solver.check() {
847 CheckOutcome::Unsat => {
848 let Some(s2) = val2.start else {
849 self.decline(format!(
850 "op#{i} select proven true-arm (UNSAT cond == 0) but the val2 slice \
851 is not erasable (impure/non-contiguous) — collapse declined"
852 ));
853 return None;
854 };
855 if val2.created + 1 != sc {
856 self.decline(format!(
857 "op#{i} select — val2 slice not adjacent to the condition slice \
858 (non-contiguous); collapse declined"
859 ));
860 return None;
861 }
862 // [s2 ..= i] is one contiguous pure range (val2 + cond + select).
863 self.deletions.push((s2, i));
864 self.admitted.push(format!(
865 "{}: op#{i} select — collapsed to the true-arm (val1): \
866 UNSAT(P ∧ cond == 0) via {} (certificate-checked QF_BV; every Unsat \
867 carries an LRAT proof validated by ordeal-lrat); deleted val2/condition/\
868 select [{s2}..={i}]; P = {{{}}}; cond = {}",
869 self.func,
870 solver.name(),
871 self.premise_desc.join(" ∧ "),
872 cond.bv,
873 ));
874 Some(val1.clone())
875 }
876 CheckOutcome::Sat => {
877 let cex = self.counterexample(solver.as_ref());
878 self.decline(format!(
879 "op#{i} select — condition is not constant under P (both arms reachable; \
880 counterexample: {cex}); branchless select retained"
881 ));
882 None
883 }
884 CheckOutcome::Unknown(reason) => {
885 self.decline(format!(
886 "op#{i} select — true-arm obligation Unknown ({reason}); conservative \
887 decline"
888 ));
889 None
890 }
891 }
892 }
893
894 /// #494 Phase 3+: redundant-mask (narrowing) elision. When the value `a`
895 /// is proven narrow enough that `a & b == a` on every P-admissible input
896 /// (`UNSAT(P ∧ (a & b) ≠ a)`), the `i32.and` is the identity — its mask
897 /// operand `b` and the `and` op itself are deleted and `a` flows through
898 /// unchanged. This is the "known-narrow-value ⇒ drop the mask" class: a
899 /// dissolved primitive gives LLVM no range on the value, so it keeps the
900 /// `and`/`uxtb`; the fact makes the mask provably dead. Only the common
901 /// wasm order (`value ; const-mask ; and`, keep `a`) is handled — anything
902 /// else DECLINES LOUDLY and the general `and` stands. Returns the surviving
903 /// operand's `Val` on admit (deletion recorded), `None` on decline.
904 fn try_elide_mask(&mut self, i: usize, a: &Val, b: &Val, result_bv: &BV) -> Option<Val> {
905 if self.premises.is_empty() {
906 self.decline(format!(
907 "op#{i} i32.and — no premise reaches this site (no usable value-range fact)"
908 ));
909 return None;
910 }
911 // The mask operand `b` must be a pure, contiguous producer sitting
912 // immediately between `a`'s slice and the `and` — otherwise deleting
913 // it could drop live work (`local.tee`) or leave a gap.
914 let Some(sb) = b.start else {
915 self.decline(format!(
916 "op#{i} i32.and — mask slice is impure or non-contiguous (not erasable)"
917 ));
918 return None;
919 };
920 if a.created + 1 != sb || b.created + 1 != i {
921 self.decline(format!(
922 "op#{i} i32.and — mask operand is not produced immediately before the and \
923 (non-contiguous)"
924 ));
925 return None;
926 }
927 let mut solver = new_solver();
928 for p in &self.premises {
929 solver.assert(p);
930 }
931 // UNSAT(P ∧ (value & mask) ≠ value) ⇒ the mask never clears a bit of
932 // the value under P ⇒ the `and` is the identity, so the general and
933 // the specialized lowerings (result = value) agree on every P input.
934 solver.assert(&result_bv.ne(&a.bv));
935 match solver.check() {
936 CheckOutcome::Unsat => {
937 self.deletions.push((sb, i));
938 self.admitted.push(format!(
939 "{}: op#{i} i32.and — redundant mask elided (value proven narrow): \
940 UNSAT(P ∧ (value & mask) ≠ value) via {} (certificate-checked QF_BV; \
941 every Unsat carries an LRAT proof validated by ordeal-lrat); deleted \
942 mask/and [{sb}..={i}]; P = {{{}}}; value = {}",
943 self.func,
944 solver.name(),
945 self.premise_desc.join(" ∧ "),
946 a.bv,
947 ));
948 Some(a.clone())
949 }
950 CheckOutcome::Sat => {
951 let cex = self.counterexample(solver.as_ref());
952 self.decline(format!(
953 "op#{i} i32.and — mask is not redundant under P (value can carry a bit \
954 outside the mask; counterexample: {cex}); general and retained"
955 ));
956 None
957 }
958 CheckOutcome::Unknown(reason) => {
959 self.decline(format!(
960 "op#{i} i32.and — mask-redundancy obligation Unknown ({reason}); \
961 conservative decline, general and retained"
962 ));
963 None
964 }
965 }
966 }
967
968 fn walk(&mut self) {
969 if self.range_facts.is_empty() && self.nonzero_facts.is_empty() {
970 self.decline(
971 "no usable value-range or divisor-nonzero fact targets this function".to_string(),
972 );
973 return;
974 }
975 let ops = self.ops;
976 let mut i = 0usize;
977 while i < ops.len() {
978 let op = &ops[i];
979 match op {
980 WasmOp::Nop => {}
981 WasmOp::I32Const(v) => {
982 let bv = self.sem.encode_op(&WasmOp::I32Const(*v), &[]);
983 self.attach_fact(i, &bv);
984 self.push(bv, Some(i), i);
985 }
986 // #494 phase 2b: tracked so an i64 divisor term can be built
987 // (the i64 fragment is const/local/div-rem only — anything
988 // else stops the walk as before).
989 WasmOp::I64Const(v) => {
990 let bv = self.sem.encode_op(&WasmOp::I64Const(*v), &[]);
991 self.attach_fact(i, &bv);
992 self.push(bv, Some(i), i);
993 }
994 WasmOp::LocalGet(idx) => {
995 let bv = self.local_bv(*idx);
996 self.attach_fact(i, &bv);
997 self.push(bv, Some(i), i);
998 }
999 WasmOp::LocalSet(idx) => {
1000 let Some(v) = self.stack.pop() else {
1001 self.decline(format!("op#{i} local.set on empty symbolic stack"));
1002 return;
1003 };
1004 self.locals.insert(*idx, v.bv);
1005 }
1006 WasmOp::LocalTee(idx) => {
1007 let Some(top) = self.stack.last_mut() else {
1008 self.decline(format!("op#{i} local.tee on empty symbolic stack"));
1009 return;
1010 };
1011 // The tee is a side effect: its slice must never be
1012 // deleted as a "pure condition producer".
1013 top.start = None;
1014 top.created = i;
1015 let bv = top.bv.clone();
1016 self.locals.insert(*idx, bv.clone());
1017 self.attach_fact(i, &bv);
1018 }
1019 WasmOp::Drop => {
1020 if self.stack.pop().is_none() {
1021 self.decline(format!("op#{i} drop on empty symbolic stack"));
1022 return;
1023 }
1024 }
1025 WasmOp::I32Eqz => {
1026 let Some(a) = self.stack.pop() else {
1027 self.decline(format!("op#{i} unary op on empty symbolic stack"));
1028 return;
1029 };
1030 if a.bv.get_size() != 32 {
1031 self.decline(format!("op#{i} i32.eqz on a non-32-bit operand"));
1032 return;
1033 }
1034 let bv = self.sem.encode_op(op, &[a.bv]);
1035 self.attach_fact(i, &bv);
1036 let start = a.start.filter(|_| a.created + 1 == i);
1037 self.push(bv, start, i);
1038 }
1039 // #494 Phase 3+: `i32.and` — tracked like the other trap-free
1040 // binops, but additionally attempts the redundant-mask elision
1041 // (a proven-narrow value makes the mask the identity). A
1042 // NON-eliding `and` pushes the EXACT `(bv, start, i)` the
1043 // general binop arm below produces — so flag-off stays
1044 // byte-identical.
1045 WasmOp::I32And => {
1046 let (Some(b), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
1047 self.decline(format!("op#{i} binop on underflowing symbolic stack"));
1048 return;
1049 };
1050 if a.bv.get_size() != 32 || b.bv.get_size() != 32 {
1051 self.decline(format!("op#{i} i32 binop on a non-32-bit operand"));
1052 return;
1053 }
1054 let bv = self.sem.encode_op(op, &[a.bv.clone(), b.bv.clone()]);
1055 self.attach_fact(i, &bv);
1056 // The general binop arm's contiguity proof, verbatim.
1057 let start = match (a.start, b.start) {
1058 (Some(sa), Some(sb)) if a.created + 1 == sb && b.created + 1 == i => {
1059 Some(sa)
1060 }
1061 _ => None,
1062 };
1063 match self.try_elide_mask(i, &a, &b, &bv) {
1064 // Admitted: the mask/and slice was recorded for
1065 // deletion; the surviving value flows through. `start =
1066 // None` keeps the collapsed result out of any later
1067 // erasable slice (conservative, like select-collapse).
1068 Some(surviving) => self.push(surviving.bv, None, i),
1069 // Declined (loud): the general `and` stands, pushed
1070 // exactly as the general binop arm would.
1071 None => self.push(bv, start, i),
1072 }
1073 }
1074 // Tracked, trap-free i32 binops (div/rem excluded on purpose:
1075 // they can trap, and a deleted slice must be effect-free).
1076 WasmOp::I32Add
1077 | WasmOp::I32Sub
1078 | WasmOp::I32Mul
1079 | WasmOp::I32Or
1080 | WasmOp::I32Xor
1081 | WasmOp::I32Shl
1082 | WasmOp::I32ShrS
1083 | WasmOp::I32ShrU
1084 | WasmOp::I32Rotl
1085 | WasmOp::I32Rotr
1086 | WasmOp::I32Eq
1087 | WasmOp::I32Ne
1088 | WasmOp::I32LtS
1089 | WasmOp::I32LtU
1090 | WasmOp::I32LeS
1091 | WasmOp::I32LeU
1092 | WasmOp::I32GtS
1093 | WasmOp::I32GtU
1094 | WasmOp::I32GeS
1095 | WasmOp::I32GeU => {
1096 let (Some(b), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
1097 self.decline(format!("op#{i} binop on underflowing symbolic stack"));
1098 return;
1099 };
1100 if a.bv.get_size() != 32 || b.bv.get_size() != 32 {
1101 self.decline(format!("op#{i} i32 binop on a non-32-bit operand"));
1102 return;
1103 }
1104 let bv = self.sem.encode_op(op, &[a.bv, b.bv]);
1105 self.attach_fact(i, &bv);
1106 // Contiguity proof for the combined producer slice:
1107 // a's slice, immediately followed by b's, immediately
1108 // followed by this op. Anything else ⇒ not erasable.
1109 let start = match (a.start, b.start) {
1110 (Some(sa), Some(sb)) if a.created + 1 == sb && b.created + 1 == i => {
1111 Some(sa)
1112 }
1113 _ => None,
1114 };
1115 self.push(bv, start, i);
1116 }
1117 // #494 phase 2b: i32/i64 div/rem — TRACKED (upgrading the
1118 // phase-2 hard stop), never DELETED. The op can trap, so its
1119 // result carries `start = None` (it can never sit inside an
1120 // erasable condition slice); the walk instead discharges the
1121 // per-site guard obligations (see the module docs' two-guard
1122 // distinction) and marks the op for the lowering. Downstream
1123 // soundness: if the op traps, nothing after it executes (any
1124 // later admitted elision is vacuous on that path); if it does
1125 // not, its result is havocked to a fresh variable.
1126 WasmOp::I32DivU
1127 | WasmOp::I32DivS
1128 | WasmOp::I32RemU
1129 | WasmOp::I32RemS
1130 | WasmOp::I64DivU
1131 | WasmOp::I64DivS
1132 | WasmOp::I64RemU
1133 | WasmOp::I64RemS => {
1134 let (Some(b), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
1135 self.decline(format!("op#{i} div/rem on underflowing symbolic stack"));
1136 return;
1137 };
1138 let (op_name, expect, is_div_s) = match op {
1139 WasmOp::I32DivU => ("i32.div_u", 32, false),
1140 WasmOp::I32DivS => ("i32.div_s", 32, true),
1141 WasmOp::I32RemU => ("i32.rem_u", 32, false),
1142 WasmOp::I32RemS => ("i32.rem_s", 32, false),
1143 WasmOp::I64DivU => ("i64.div_u", 64, false),
1144 WasmOp::I64DivS => ("i64.div_s", 64, true),
1145 WasmOp::I64RemU => ("i64.rem_u", 64, false),
1146 _ => ("i64.rem_s", 64, false),
1147 };
1148 if a.bv.get_size() != expect || b.bv.get_size() != expect {
1149 self.decline(format!(
1150 "op#{i} {op_name} on operands of unexpected width (symbolic widths {}/{}, expected {expect})",
1151 a.bv.get_size(),
1152 b.bv.get_size()
1153 ));
1154 return;
1155 }
1156 self.try_elide_div_guards(i, op_name, is_div_s, &a, &b);
1157 // Havoc the result; `start = None` keeps a possibly-
1158 // trapping op out of every erasable condition slice.
1159 let n = self.fresh;
1160 self.fresh += 1;
1161 let v = self.fresh_var(format!("fs_d{n}"));
1162 self.attach_fact(i, &v);
1163 self.push(v, None, i);
1164 }
1165 // #494 bounds-elision: i32 memory LOADS — TRACKED, never
1166 // DELETED (an OOB access traps, so the op is not effect-free;
1167 // same discipline as div/rem). The walk discharges the
1168 // per-site software bounds-guard obligation and marks the op
1169 // for the lowering; the loaded value is havocked to a fresh
1170 // variable (memory contents are not modeled) with
1171 // `start = None` (a possibly-trapping op never sits inside an
1172 // erasable condition slice). Downstream soundness: if the
1173 // access traps, nothing after it executes (any later admitted
1174 // elision is vacuous on that path).
1175 WasmOp::I32Load { offset, .. }
1176 | WasmOp::I32Load8S { offset, .. }
1177 | WasmOp::I32Load8U { offset, .. }
1178 | WasmOp::I32Load16S { offset, .. }
1179 | WasmOp::I32Load16U { offset, .. } => {
1180 let Some(a) = self.stack.pop() else {
1181 self.decline(format!("op#{i} memory load on empty symbolic stack"));
1182 return;
1183 };
1184 if a.bv.get_size() != 32 {
1185 self.decline(format!("op#{i} memory load on a non-32-bit index"));
1186 return;
1187 }
1188 let (op_name, size) = match op {
1189 WasmOp::I32Load { .. } => ("i32.load", 4),
1190 WasmOp::I32Load8S { .. } => ("i32.load8_s", 1),
1191 WasmOp::I32Load8U { .. } => ("i32.load8_u", 1),
1192 WasmOp::I32Load16S { .. } => ("i32.load16_s", 2),
1193 _ => ("i32.load16_u", 2),
1194 };
1195 self.try_elide_mem_bounds(i, op_name, size, *offset, &a);
1196 // Havoc the loaded value; `start = None` keeps a possibly-
1197 // trapping op out of every erasable condition slice.
1198 let n = self.fresh;
1199 self.fresh += 1;
1200 let v = self.fresh_var(format!("fs_m{n}"));
1201 self.attach_fact(i, &v);
1202 self.push(v, None, i);
1203 }
1204 // #494 bounds-elision: i32 memory STORES — same obligation
1205 // over the index. No memory model is needed: loads are always
1206 // havocked, so a store's effect on the symbolic state is
1207 // vacuous; only the guard obligation is discharged.
1208 WasmOp::I32Store { offset, .. }
1209 | WasmOp::I32Store8 { offset, .. }
1210 | WasmOp::I32Store16 { offset, .. } => {
1211 let (Some(val), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
1212 self.decline(format!(
1213 "op#{i} memory store on underflowing symbolic stack"
1214 ));
1215 return;
1216 };
1217 if a.bv.get_size() != 32 || val.bv.get_size() != 32 {
1218 self.decline(format!("op#{i} memory store on a non-32-bit operand"));
1219 return;
1220 }
1221 let (op_name, size) = match op {
1222 WasmOp::I32Store { .. } => ("i32.store", 4),
1223 WasmOp::I32Store8 { .. } => ("i32.store8", 1),
1224 _ => ("i32.store16", 2),
1225 };
1226 self.try_elide_mem_bounds(i, op_name, size, *offset, &a);
1227 // Store pushes nothing.
1228 }
1229 WasmOp::If => {
1230 let Some(cond) = self.stack.pop() else {
1231 self.decline(format!("op#{i} `if` on empty symbolic stack"));
1232 return;
1233 };
1234 if cond.bv.get_size() != 32 {
1235 self.decline(format!("op#{i} `if` condition is not 32-bit"));
1236 return;
1237 }
1238 let Some((end, has_else)) = self.matching_end(i) else {
1239 self.decline(format!("op#{i} `if` without matching `end`"));
1240 return;
1241 };
1242 let Some(&ord) = self.opener_ordinal.get(&i) else {
1243 self.decline(format!("op#{i} `if` missing from the opener ordinal map"));
1244 return;
1245 };
1246 let Some(&arity) = self.block_arity.get(ord) else {
1247 self.decline(format!(
1248 "op#{i} `if` has no block_arity entry (side-table desync)"
1249 ));
1250 return;
1251 };
1252 if has_else {
1253 self.decline(format!(
1254 "op#{i} `if`/`else` — only no-else `if` is in Phase-2 scope"
1255 ));
1256 self.havoc_region(i, end, arity);
1257 } else if self.try_elide(i, end, &cond) {
1258 // Region provably never executes: state unchanged
1259 // (params-as-results pass-through is the identity for
1260 // a no-else `if`, whose blocktype has equal
1261 // param/result types by wasm validation).
1262 } else {
1263 self.havoc_region(i, end, arity);
1264 }
1265 i = end + 1;
1266 continue;
1267 }
1268 // #494 Phase 3: branchless `select` — the sibling of the
1269 // Phase-2 no-else `if` elision, and the shape gust_mix's
1270 // clamp actually lowers to (`max`/`min` via select). A
1271 // value-range premise that pins the condition constant
1272 // collapses it to one operand (stream deletion, like `if`).
1273 WasmOp::Select => {
1274 let (Some(cond), Some(val2), Some(val1)) =
1275 (self.stack.pop(), self.stack.pop(), self.stack.pop())
1276 else {
1277 self.decline(format!("op#{i} select on underflowing symbolic stack"));
1278 return;
1279 };
1280 // Only the plain i32 `select` (0x1B) is tracked; a typed
1281 // select over i64/f-operands declines and havocs.
1282 if cond.bv.get_size() != 32
1283 || val1.bv.get_size() != 32
1284 || val2.bv.get_size() != 32
1285 {
1286 self.decline(format!(
1287 "op#{i} select on non-32-bit operand(s) — only i32 select is tracked"
1288 ));
1289 let v = self.fresh_var(format!("fs_sel{i}"));
1290 self.push(v, None, i);
1291 i += 1;
1292 continue;
1293 }
1294 match self.try_collapse_select(i, &val1, &val2, &cond) {
1295 // Admitted: the surviving operand's producer slice
1296 // stays; the other operand + condition slice + the
1297 // `select` were recorded for deletion. `start = None`
1298 // keeps the collapsed result out of any later erasable
1299 // slice (conservative).
1300 Some(surviving) => self.push(surviving.bv, None, i),
1301 // Declined (loud): the branchless select stands. Havoc
1302 // the result — a fresh var means any obligation over it
1303 // downstream is Sat, so it can never seed an unsound
1304 // chained collapse.
1305 None => {
1306 let v = self.fresh_var(format!("fs_sel{i}"));
1307 self.push(v, None, i);
1308 }
1309 }
1310 }
1311 // Function-final `End` (top-level): done.
1312 WasmOp::End => break,
1313 WasmOp::Return => break,
1314 other => {
1315 // First op outside the tracked fragment: stop. Everything
1316 // already admitted was justified independently of what
1317 // follows; declining the REST loudly keeps honesty.
1318 self.decline(format!(
1319 "op#{i} {other:?} is outside the tracked i32 fragment — \
1320 fact tracking stops here (no further elisions in this function)"
1321 ));
1322 return;
1323 }
1324 }
1325 i += 1;
1326 }
1327 }
1328
1329 fn finish(self) -> FactSpecResult {
1330 let Pass {
1331 ops,
1332 block_arity,
1333 deletions,
1334 admitted,
1335 declined,
1336 zero_marks,
1337 ovf_marks,
1338 mem_marks,
1339 ..
1340 } = self;
1341 if deletions.is_empty() {
1342 return FactSpecResult {
1343 ops: ops.to_vec(),
1344 block_arity: block_arity.to_vec(),
1345 kept: (0..ops.len()).collect(),
1346 admitted,
1347 declined,
1348 // No rewrite ⇒ original indices ARE the output indices.
1349 elide_div_zero: zero_marks,
1350 elide_div_ovf: ovf_marks,
1351 elide_mem_bounds: mem_marks,
1352 stream_changed: false,
1353 };
1354 }
1355 let deleted = |i: usize| deletions.iter().any(|&(s, e)| i >= s && i <= e);
1356 let mut out_ops = Vec::with_capacity(ops.len());
1357 let mut out_arity = Vec::with_capacity(block_arity.len());
1358 let mut kept = Vec::with_capacity(ops.len());
1359 let mut ord = 0usize;
1360 for (i, op) in ops.iter().enumerate() {
1361 let is_opener = matches!(op, WasmOp::Block | WasmOp::Loop | WasmOp::If);
1362 if !deleted(i) {
1363 out_ops.push(op.clone());
1364 kept.push(i);
1365 if is_opener && let Some(&a) = block_arity.get(ord) {
1366 out_arity.push(a);
1367 }
1368 }
1369 if is_opener {
1370 ord += 1;
1371 }
1372 }
1373 // Remap the guard-elision marks into the REWRITTEN index space. A
1374 // marked div/rem can never sit inside a deleted range (deleted ranges
1375 // are contiguous PURE condition slices plus proven-dead `if` regions
1376 // the walk skipped over; a div result's `start = None` bars it from
1377 // any erasable slice) — the filter below is defense in depth.
1378 let remap = |marks: Vec<usize>| -> Vec<usize> {
1379 marks
1380 .into_iter()
1381 .filter_map(|m| {
1382 debug_assert!(!deleted(m), "guard mark op#{m} inside a deleted range");
1383 kept.binary_search(&m).ok()
1384 })
1385 .collect()
1386 };
1387 FactSpecResult {
1388 ops: out_ops,
1389 block_arity: out_arity,
1390 elide_div_zero: remap(zero_marks),
1391 elide_div_ovf: remap(ovf_marks),
1392 elide_mem_bounds: remap(mem_marks),
1393 kept,
1394 admitted,
1395 declined,
1396 stream_changed: true,
1397 }
1398 }
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403 use super::*;
1404 use WasmOp::*;
1405
1406 fn fact(value_id: u32, lo: i64, hi: i64) -> WscFact {
1407 WscFact {
1408 func_index: 0,
1409 value_id,
1410 kind: FactKind::ValueRange { lo, hi },
1411 }
1412 }
1413
1414 /// The gust_mix clamp shape: clamp(ch + 476, 1000, 2000) via two
1415 /// no-else `if`s over a local.
1416 fn clamp_ops() -> Vec<WasmOp> {
1417 vec![
1418 LocalGet(0), // 0 ch ← fact target
1419 I32Const(476), // 1
1420 I32Add, // 2 v = ch+476
1421 LocalSet(1), // 3
1422 LocalGet(1), // 4
1423 I32Const(1000), // 5
1424 I32LtS, // 6
1425 If, // 7
1426 I32Const(1000), // 8
1427 LocalSet(1), // 9
1428 End, // 10
1429 LocalGet(1), // 11
1430 I32Const(2000), // 12
1431 I32GtS, // 13
1432 If, // 14
1433 I32Const(2000), // 15
1434 LocalSet(1), // 16
1435 End, // 17
1436 LocalGet(1), // 18
1437 End, // 19
1438 ]
1439 }
1440
1441 const CLAMP_ARITY: &[(u8, u8)] = &[(0, 0), (0, 0)];
1442
1443 #[test]
1444 fn clamp_shape_elides_both_branches_under_the_proven_bound_494() {
1445 let ops = clamp_ops();
1446 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 524, 1524)], &[], 0);
1447 assert_eq!(r.admitted.len(), 2, "declines: {:?}", r.declined);
1448 assert!(r.changed());
1449 assert_eq!(
1450 r.ops,
1451 vec![
1452 LocalGet(0),
1453 I32Const(476),
1454 I32Add,
1455 LocalSet(1),
1456 LocalGet(1),
1457 End
1458 ],
1459 "both clamp comparisons + branches + bodies must be gone"
1460 );
1461 assert_eq!(r.block_arity, vec![], "both If arity entries removed");
1462 assert_eq!(r.kept, vec![0, 1, 2, 3, 18, 19]);
1463 // The certificate evidence trail names the engine and the premise.
1464 for line in &r.admitted {
1465 assert!(line.contains("UNSAT"), "{line}");
1466 assert!(line.contains("certificate-checked"), "{line}");
1467 assert!(line.contains("[524, 1524]"), "{line}");
1468 }
1469 }
1470
1471 #[test]
1472 fn wrong_wide_bound_is_sat_and_declines_loudly_494() {
1473 // ch ∈ [0, 4000] does NOT make the clamp dead (ch=0 → v=476 < 1000):
1474 // the obligation is Sat and BOTH sites decline with a counterexample.
1475 let ops = clamp_ops();
1476 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 0, 4000)], &[], 0);
1477 assert_eq!(r.admitted.len(), 0);
1478 assert!(!r.changed());
1479 assert_eq!(r.ops, ops, "declined ⇒ byte-identical op stream");
1480 assert_eq!(r.block_arity, CLAMP_ARITY.to_vec());
1481 assert!(
1482 r.declined
1483 .iter()
1484 .any(|d| d.contains("Sat") && d.contains("counterexample")),
1485 "declines must be loud and carry a model: {:?}",
1486 r.declined
1487 );
1488 }
1489
1490 #[test]
1491 fn partially_dead_bound_elides_only_the_proven_branch_494() {
1492 // ch ∈ [524, 4000]: v ≥ 1000 so the LOW clamp is dead, but v can
1493 // exceed 2000 so the HIGH clamp must survive.
1494 let ops = clamp_ops();
1495 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 524, 4000)], &[], 0);
1496 assert_eq!(r.admitted.len(), 1, "declines: {:?}", r.declined);
1497 assert_eq!(r.declined.len(), 1);
1498 assert_eq!(
1499 r.ops,
1500 vec![
1501 LocalGet(0),
1502 I32Const(476),
1503 I32Add,
1504 LocalSet(1),
1505 LocalGet(1),
1506 I32Const(2000),
1507 I32GtS,
1508 If,
1509 I32Const(2000),
1510 LocalSet(1),
1511 End,
1512 LocalGet(1),
1513 End,
1514 ]
1515 );
1516 assert_eq!(r.block_arity, vec![(0, 0)], "one If survives");
1517 }
1518
1519 #[test]
1520 fn no_facts_changes_nothing_494() {
1521 let ops = clamp_ops();
1522 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[], &[], 0);
1523 assert!(!r.changed());
1524 assert_eq!(r.ops, ops);
1525 assert!(!r.declined.is_empty(), "the no-fact case is a loud decline");
1526 }
1527
1528 // ---- #494 Phase 3: branchless select-collapse ----
1529
1530 /// gust_mix's clamp lowered branchlessly via `select` (the shape LLVM
1531 /// emits): `max(v,1000)` = `(v<1000)?1000:v`, `min(v,2000)` =
1532 /// `(v>2000)?2000:v`. No `If`/`End` — no block_arity entries.
1533 fn select_clamp_ops() -> Vec<WasmOp> {
1534 vec![
1535 LocalGet(0), // 0 ch ← fact target
1536 I32Const(476), // 1
1537 I32Add, // 2 v = ch+476
1538 LocalSet(1), // 3
1539 I32Const(1000), // 4 val1 (low clamp)
1540 LocalGet(1), // 5 val2 = v
1541 LocalGet(1), // 6 cond slice
1542 I32Const(1000), // 7
1543 I32LtS, // 8 cond = v < 1000
1544 Select, // 9 → max(v,1000)
1545 LocalSet(1), // 10
1546 I32Const(2000), // 11 val1 (high clamp)
1547 LocalGet(1), // 12 val2 = v
1548 LocalGet(1), // 13 cond slice
1549 I32Const(2000), // 14
1550 I32GtS, // 15 cond = v > 2000
1551 Select, // 16 → min(v,2000) = result
1552 End, // 17
1553 ]
1554 }
1555
1556 #[test]
1557 fn select_clamp_collapses_both_selects_under_the_proven_bound_494() {
1558 let ops = select_clamp_ops();
1559 let r = specialize_function("gust_mix", &ops, &[], &[fact(0, 524, 1524)], &[], 0);
1560 assert_eq!(r.admitted.len(), 2, "declines: {:?}", r.declined);
1561 assert!(r.changed());
1562 assert_eq!(
1563 r.ops,
1564 vec![
1565 LocalGet(0),
1566 I32Const(476),
1567 I32Add,
1568 LocalSet(1),
1569 LocalGet(1), // val2 of select 1 (identity survives)
1570 LocalSet(1),
1571 LocalGet(1), // val2 of select 2 (identity survives)
1572 End,
1573 ],
1574 "both branchless clamps must collapse to the identity operand"
1575 );
1576 assert_eq!(r.kept, vec![0, 1, 2, 3, 5, 10, 12, 17]);
1577 for line in &r.admitted {
1578 assert!(line.contains("UNSAT"), "{line}");
1579 assert!(line.contains("certificate-checked"), "{line}");
1580 assert!(line.contains("select"), "{line}");
1581 assert!(line.contains("[524, 1524]"), "{line}");
1582 }
1583 }
1584
1585 #[test]
1586 fn select_clamp_wrong_bound_is_sat_and_declines_byte_identically_494() {
1587 // ch ∈ [0, 4000]: ch=0 → v=476 < 1000 so the low clamp genuinely
1588 // fires; both selects are non-constant ⇒ loud Sat decline, no rewrite.
1589 let ops = select_clamp_ops();
1590 let r = specialize_function("gust_mix", &ops, &[], &[fact(0, 0, 4000)], &[], 0);
1591 assert_eq!(r.admitted.len(), 0);
1592 assert!(!r.changed());
1593 assert_eq!(r.ops, ops, "declined ⇒ byte-identical op stream");
1594 assert!(
1595 r.declined
1596 .iter()
1597 .any(|d| d.contains("not constant") && d.contains("counterexample")),
1598 "declines must be loud and carry a model: {:?}",
1599 r.declined
1600 );
1601 }
1602
1603 #[test]
1604 fn select_collapses_to_true_arm_when_condition_proven_nonzero_494() {
1605 // result = cond ? val1 : val2 with cond ≡ 1 (fact ∈ [1,1]) ⇒ keep val1.
1606 let ops = vec![
1607 I32Const(111), // 0 val1
1608 I32Const(222), // 1 val2
1609 LocalGet(0), // 2 cond ← fact ∈ [1,1] (always non-zero)
1610 Select, // 3 → val1
1611 End, // 4
1612 ];
1613 let r = specialize_function("f", &ops, &[], &[fact(2, 1, 1)], &[], 0);
1614 assert_eq!(r.admitted.len(), 1, "declines: {:?}", r.declined);
1615 assert_eq!(r.ops, vec![I32Const(111), End]);
1616 assert!(
1617 r.admitted[0].contains("true-arm") && r.admitted[0].contains("cond == 0"),
1618 "{}",
1619 r.admitted[0]
1620 );
1621 }
1622
1623 #[test]
1624 fn select_without_constraining_premise_declines_no_false_collapse_494() {
1625 // A TRUE ValueRange fact exists (so the walk runs) but targets val1,
1626 // not the condition; the select's condition carries no premise ⇒
1627 // non-constant ⇒ Sat decline, byte-identical.
1628 let ops = vec![
1629 I32Const(111), // 0 val1 ← fact ∈ [111,111] (true, non-constraining)
1630 I32Const(222), // 1 val2
1631 LocalGet(0), // 2 cond — unconstrained
1632 Select, // 3
1633 End, // 4
1634 ];
1635 let r = specialize_function("f", &ops, &[], &[fact(0, 111, 111)], &[], 0);
1636 assert_eq!(r.admitted.len(), 0);
1637 assert!(!r.changed());
1638 assert_eq!(r.ops, ops);
1639 }
1640
1641 #[test]
1642 fn declined_if_havocs_its_locals_no_false_admit_downstream_494() {
1643 // The FIRST if is undecidable (condition on an unconstrained local),
1644 // and its body rewrites local 1 — so the SECOND if (which would be
1645 // dead under the fact alone) must NOT be admitted: local 1 is
1646 // havocked by the declined region.
1647 let ops = vec![
1648 LocalGet(0), // 0 ← fact ch ∈ [524, 1524]
1649 I32Const(476), // 1
1650 I32Add, // 2
1651 LocalSet(1), // 3
1652 LocalGet(2), // 4 unconstrained
1653 If, // 5
1654 I32Const(-9), // 6
1655 LocalSet(1), // 7 havocs local 1
1656 End, // 8
1657 LocalGet(1), // 9
1658 I32Const(2000), // 10
1659 I32GtS, // 11
1660 If, // 12
1661 I32Const(2000), // 13
1662 LocalSet(1), // 14
1663 End, // 15
1664 LocalGet(1), // 16
1665 End, // 17
1666 ];
1667 let r = specialize_function("f", &ops, CLAMP_ARITY, &[fact(0, 524, 1524)], &[], 0);
1668 assert_eq!(
1669 r.admitted.len(),
1670 0,
1671 "havocked local must block the downstream elision: {:?}",
1672 r.admitted
1673 );
1674 assert_eq!(r.ops, ops);
1675 }
1676
1677 #[test]
1678 fn if_with_else_declines_494() {
1679 let ops = vec![
1680 LocalGet(0), // 0 ← fact forces cond = 0
1681 If, // 1
1682 I32Const(1), // 2
1683 LocalSet(1), // 3
1684 Else, // 4
1685 I32Const(2), // 5
1686 LocalSet(1), // 6
1687 End, // 7
1688 LocalGet(1), // 8
1689 End, // 9
1690 ];
1691 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 0, 0)], &[], 0);
1692 assert_eq!(r.admitted.len(), 0);
1693 assert!(
1694 r.declined.iter().any(|d| d.contains("else")),
1695 "{:?}",
1696 r.declined
1697 );
1698 assert_eq!(r.ops, ops);
1699 }
1700
1701 #[test]
1702 fn nested_opener_inside_elided_body_fixes_block_arity_ordinals_494() {
1703 // A dead outer if contains a nested if: BOTH arity entries vanish and
1704 // the SURVIVING later block keeps its (translated) entry.
1705 let ops = vec![
1706 LocalGet(0), // 0 ← fact [5,5] ⇒ eqz = 0
1707 I32Eqz, // 1
1708 If, // 2 (ordinal 0)
1709 LocalGet(0), // 3
1710 If, // 4 (ordinal 1, nested)
1711 I32Const(7), // 5
1712 LocalSet(1), // 6
1713 End, // 7
1714 End, // 8
1715 Block, // 9 (ordinal 2, survives)
1716 End, // 10
1717 End, // 11
1718 ];
1719 let arity = &[(0, 0), (0, 0), (0, 1)];
1720 let r = specialize_function("f", &ops, arity, &[fact(0, 5, 5)], &[], 0);
1721 assert_eq!(r.admitted.len(), 1, "declines: {:?}", r.declined);
1722 // The condition slice starts at op 0 (LocalGet feeds the eqz), so the
1723 // whole deleted range is [0..=8]; only the trailing block survives.
1724 assert_eq!(r.ops, vec![Block, End, End]);
1725 assert_eq!(r.kept, vec![9, 10, 11]);
1726 assert_eq!(
1727 r.block_arity,
1728 vec![(0, 1)],
1729 "only the surviving Block's entry"
1730 );
1731 }
1732
1733 #[test]
1734 fn tee_condition_slice_is_not_erasable_494() {
1735 // cond built through local.tee: proven dead, but deleting the slice
1736 // would lose the local write ⇒ decline (loud), stream unchanged.
1737 let ops = vec![
1738 LocalGet(0), // 0 ← fact [1,1]
1739 LocalTee(1), // 1 side effect in the slice
1740 I32Eqz, // 2 = 0 under the fact
1741 If, // 3
1742 I32Const(9), // 4
1743 LocalSet(2), // 5
1744 End, // 6
1745 End, // 7
1746 ];
1747 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 1, 1)], &[], 0);
1748 assert_eq!(r.admitted.len(), 0);
1749 assert!(
1750 r.declined
1751 .iter()
1752 .any(|d| d.contains("not") && d.contains("erasable")),
1753 "{:?}",
1754 r.declined
1755 );
1756 assert_eq!(r.ops, ops);
1757 }
1758
1759 #[test]
1760 fn untracked_op_stops_tracking_loudly_494() {
1761 let ops = vec![
1762 LocalGet(0), // 0 ← fact
1763 I64ExtendI32S, // 1 untracked ⇒ stop
1764 Drop, // 2
1765 End, // 3
1766 ];
1767 let r = specialize_function("f", &ops, &[], &[fact(0, 1, 2)], &[], 0);
1768 assert!(!r.changed());
1769 assert!(
1770 r.declined.iter().any(|d| d.contains("outside the tracked")),
1771 "{:?}",
1772 r.declined
1773 );
1774 }
1775
1776 fn nonzero_fact(value_id: u32) -> WscFact {
1777 WscFact {
1778 func_index: 0,
1779 value_id,
1780 kind: FactKind::DivisorNonZero,
1781 }
1782 }
1783
1784 // ================= #494 phase 2b: div/rem trap-guard elision =================
1785
1786 #[test]
1787 fn divisor_range_excluding_zero_elides_zero_guard_all_rem_div_494() {
1788 // div_u, rem_u, rem_s by a param divisor proven ∈ [1, 100]: every
1789 // zero guard falls to UNSAT(P ∧ divisor == 0); the stream itself is
1790 // untouched (marks only).
1791 let ops = vec![
1792 LocalGet(0), // 0 n
1793 LocalGet(1), // 1 d ← fact [1,100]
1794 I32DivU, // 2 → zero mark
1795 Drop, // 3
1796 LocalGet(0), // 4
1797 LocalGet(1), // 5 ← fact [1,100]
1798 I32RemU, // 6 → zero mark
1799 Drop, // 7
1800 LocalGet(0), // 8
1801 LocalGet(1), // 9 ← fact [1,100]
1802 I32RemS, // 10 → zero mark
1803 End, // 11
1804 ];
1805 let facts = [fact(1, 1, 100), fact(5, 1, 100), fact(9, 1, 100)];
1806 let r = specialize_function("f", &ops, &[], &facts, &[], 0);
1807 assert_eq!(
1808 r.elide_div_zero,
1809 vec![2, 6, 10],
1810 "declines: {:?}",
1811 r.declined
1812 );
1813 assert_eq!(
1814 r.elide_div_ovf,
1815 Vec::<usize>::new(),
1816 "no div_s in the stream"
1817 );
1818 assert!(!r.changed(), "guard marks never rewrite the op stream");
1819 assert_eq!(r.ops, ops);
1820 assert_eq!(r.admitted.len(), 3);
1821 for line in &r.admitted {
1822 assert!(line.contains("divide-by-zero guard elided"), "{line}");
1823 assert!(line.contains("UNSAT(P ∧ divisor == 0)"), "{line}");
1824 assert!(line.contains("certificate-checked"), "{line}");
1825 }
1826 }
1827
1828 #[test]
1829 fn nonzero_fact_elides_zero_guard_but_retains_div_s_overflow_guard_494() {
1830 // THE TWO-GUARD DISTINCTION (#633/#634): a divisor-nonzero fact (kind
1831 // 3) discharges UNSAT(P ∧ divisor == 0) but NOT the overflow
1832 // obligation — divisor ≠ 0 still admits divisor == -1 with dividend
1833 // == INT_MIN, so the overflow guard is RETAINED with a loud decline.
1834 let ops = vec![
1835 LocalGet(0), // 0
1836 LocalGet(1), // 1 ← divisor-nonzero fact
1837 I32DivS, // 2
1838 End, // 3
1839 ];
1840 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[], 0);
1841 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1842 assert_eq!(
1843 r.elide_div_ovf,
1844 Vec::<usize>::new(),
1845 "divisor ≠ 0 must NOT elide the INT_MIN/-1 overflow guard"
1846 );
1847 assert!(
1848 r.declined
1849 .iter()
1850 .any(|d| d.contains("overflow-guard obligation Sat") && d.contains("RETAINED")),
1851 "{:?}",
1852 r.declined
1853 );
1854 }
1855
1856 #[test]
1857 fn positive_range_discharges_both_div_s_obligations_494() {
1858 // divisor ∈ [1, 100] excludes BOTH 0 and -1 — the two obligations
1859 // are discharged independently and both guards fall.
1860 let ops = vec![LocalGet(0), LocalGet(1), I32DivS, End];
1861 let r = specialize_function("f", &ops, &[], &[fact(1, 1, 100)], &[], 0);
1862 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1863 assert_eq!(r.elide_div_ovf, vec![2]);
1864 assert_eq!(r.admitted.len(), 2, "one certificate line per obligation");
1865 assert!(
1866 r.admitted
1867 .iter()
1868 .any(|a| a.contains("overflow guard elided")
1869 && a.contains("dividend == INT32_MIN ∧ divisor == -1")),
1870 "{:?}",
1871 r.admitted
1872 );
1873 }
1874
1875 #[test]
1876 fn range_including_zero_is_sat_and_declines_the_zero_guard_494() {
1877 // divisor ∈ [0, 100]: divisor == 0 is P-admissible — the obligation
1878 // is Sat, the decline is loud and carries a model, no mark is set.
1879 let ops = vec![LocalGet(0), LocalGet(1), I32DivU, End];
1880 let r = specialize_function("f", &ops, &[], &[fact(1, 0, 100)], &[], 0);
1881 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1882 assert!(
1883 r.declined
1884 .iter()
1885 .any(|d| d.contains("zero-guard obligation Sat") && d.contains("counterexample")),
1886 "{:?}",
1887 r.declined
1888 );
1889 }
1890
1891 #[test]
1892 fn i64_div_s_nonzero_fact_zero_guard_only_overflow_retained_494() {
1893 // Oracle 5 at the pass level: i64.div_s with an i64 param divisor
1894 // carrying a divisor-nonzero fact — the zero guard is proven dead,
1895 // the INT64_MIN/-1 overflow guard (#633/#634) is RETAINED.
1896 let ops = vec![LocalGet(0), LocalGet(1), I64DivS, End];
1897 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[true, true], 0);
1898 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1899 assert_eq!(
1900 r.elide_div_ovf,
1901 Vec::<usize>::new(),
1902 "i64 overflow guard retained"
1903 );
1904 assert!(
1905 r.declined.iter().any(|d| d.contains("RETAINED")),
1906 "{:?}",
1907 r.declined
1908 );
1909 }
1910
1911 #[test]
1912 fn i64_div_s_positive_range_discharges_both_obligations_494() {
1913 let ops = vec![LocalGet(0), LocalGet(1), I64DivS, End];
1914 let r = specialize_function("f", &ops, &[], &[fact(1, 1, 1000)], &[true, true], 0);
1915 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1916 assert_eq!(r.elide_div_ovf, vec![2]);
1917 }
1918
1919 #[test]
1920 fn i64_div_on_undeclared_width_declines_no_marks_494() {
1921 // Without the params_i64 table the divisor local is symbolically
1922 // 32-bit — the width check declines rather than building a
1923 // wrong-width obligation.
1924 let ops = vec![LocalGet(0), LocalGet(1), I64DivU, End];
1925 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[], 0);
1926 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1927 assert!(
1928 r.declined.iter().any(|d| d.contains("unexpected width")),
1929 "{:?}",
1930 r.declined
1931 );
1932 }
1933
1934 #[test]
1935 fn div_with_no_premise_declines_loudly_494() {
1936 // The function carries a fact, but no premise reaches the divisor —
1937 // the obligation cannot even be posed; both guards stay.
1938 let ops = vec![
1939 LocalGet(0), // 0 ← fact on the DIVIDEND, not the divisor
1940 LocalGet(1), // 1 unconstrained divisor
1941 I32DivU, // 2
1942 End, // 3
1943 ];
1944 // A fact on op 0 (the dividend): premises exist but do not constrain
1945 // the divisor — Sat, decline.
1946 let r = specialize_function("f", &ops, &[], &[fact(0, 1, 5)], &[], 0);
1947 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1948 assert!(
1949 r.declined
1950 .iter()
1951 .any(|d| d.contains("zero-guard obligation Sat")),
1952 "{:?}",
1953 r.declined
1954 );
1955 }
1956
1957 #[test]
1958 fn guard_marks_are_remapped_through_a_clamp_elision_494() {
1959 // A clamp elision rewrites the stream; a downstream div's mark must
1960 // land on the REWRITTEN index (the driver feeds the rewritten stream
1961 // to the selector, which keys guards by its own op index).
1962 let ops = vec![
1963 LocalGet(0), // 0 ← fact [524, 1524]
1964 I32Const(476), // 1
1965 I32Add, // 2
1966 LocalSet(1), // 3
1967 LocalGet(1), // 4 -+ low clamp (elided 4..=10)
1968 I32Const(1000), // 5 |
1969 I32LtS, // 6 |
1970 If, // 7 |
1971 I32Const(1000), // 8 |
1972 LocalSet(1), // 9 |
1973 End, // 10 -+
1974 LocalGet(1), // 11
1975 LocalGet(0), // 12 divisor = ch ∈ [524, 1524] ⇒ nonzero
1976 I32DivU, // 13 → zero mark (rewritten index 6)
1977 End, // 14
1978 ];
1979 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 524, 1524)], &[], 0);
1980 assert!(r.changed(), "declines: {:?}", r.declined);
1981 assert_eq!(r.kept, vec![0, 1, 2, 3, 11, 12, 13, 14]);
1982 assert_eq!(
1983 r.ops,
1984 vec![
1985 LocalGet(0),
1986 I32Const(476),
1987 I32Add,
1988 LocalSet(1),
1989 LocalGet(1),
1990 LocalGet(0),
1991 I32DivU,
1992 End
1993 ]
1994 );
1995 assert_eq!(
1996 r.elide_div_zero,
1997 vec![6],
1998 "mark remapped from original op#13 to rewritten op#6"
1999 );
2000 }
2001
2002 // ============ #494 Phase 3+: redundant-mask (narrowing) elision ============
2003
2004 /// A representative dissolved DSP kernel: pack two proven-11-bit lanes,
2005 /// `lo | (hi << 11)`. Both `& 0x7FF` masks are redundant under the lane
2006 /// bounds — LLVM keeps them (no range on the params); the facts drop them.
2007 fn pack_lanes_ops() -> Vec<WasmOp> {
2008 vec![
2009 LocalGet(0), // 0 lo ← fact [0, 2047]
2010 I32Const(0x7FF), // 1
2011 I32And, // 2 lo & 0x7FF (redundant)
2012 LocalGet(1), // 3 hi ← fact [0, 2047]
2013 I32Const(0x7FF), // 4
2014 I32And, // 5 hi & 0x7FF (redundant)
2015 I32Const(11), // 6
2016 I32Shl, // 7 hi << 11
2017 I32Or, // 8 lo | (hi << 11)
2018 End, // 9
2019 ]
2020 }
2021
2022 #[test]
2023 fn narrow_value_elides_redundant_mask_494() {
2024 // lo, hi ∈ [0, 2047] ⇒ `x & 0x7FF == x`: both masks fall to
2025 // UNSAT(P ∧ (value & mask) ≠ value); each deletes its `const;and` pair.
2026 let ops = pack_lanes_ops();
2027 let r = specialize_function(
2028 "gust_kernel",
2029 &ops,
2030 &[],
2031 &[fact(0, 0, 2047), fact(3, 0, 2047)],
2032 &[],
2033 0,
2034 );
2035 assert_eq!(r.admitted.len(), 2, "declines: {:?}", r.declined);
2036 assert!(r.changed());
2037 assert_eq!(
2038 r.ops,
2039 vec![
2040 LocalGet(0), // lo flows through the elided mask
2041 LocalGet(1), // hi flows through the elided mask
2042 I32Const(11),
2043 I32Shl,
2044 I32Or,
2045 End,
2046 ],
2047 "both redundant masks must be gone, the arithmetic intact"
2048 );
2049 assert_eq!(r.kept, vec![0, 3, 6, 7, 8, 9]);
2050 for line in &r.admitted {
2051 assert!(line.contains("UNSAT(P ∧ (value & mask) ≠ value)"), "{line}");
2052 assert!(line.contains("certificate-checked"), "{line}");
2053 assert!(line.contains("redundant mask elided"), "{line}");
2054 }
2055 }
2056
2057 #[test]
2058 fn wide_bound_makes_mask_live_and_declines_byte_identically_494() {
2059 // lo ∈ [0, 0xFFF]: value 0x800 has bit 11 set, OUTSIDE the 0x7FF mask,
2060 // so `x & 0x7FF != x` is Sat — the mask is genuinely live. BOTH sites
2061 // decline loudly with a counterexample; the stream is byte-identical.
2062 let ops = pack_lanes_ops();
2063 let r = specialize_function(
2064 "gust_kernel",
2065 &ops,
2066 &[],
2067 &[fact(0, 0, 0xFFF), fact(3, 0, 0xFFF)],
2068 &[],
2069 0,
2070 );
2071 assert_eq!(r.admitted.len(), 0);
2072 assert!(!r.changed());
2073 assert_eq!(r.ops, ops, "declined ⇒ byte-identical op stream");
2074 assert!(
2075 r.declined
2076 .iter()
2077 .any(|d| d.contains("not redundant") && d.contains("counterexample")),
2078 "declines must be loud and carry a model: {:?}",
2079 r.declined
2080 );
2081 }
2082
2083 #[test]
2084 fn mask_without_constraining_premise_declines_no_false_elision_494() {
2085 // A TRUE ValueRange fact exists (so the walk runs) but targets the mask
2086 // const, not the value; the masked value carries no premise ⇒ the
2087 // obligation is Sat ⇒ loud decline, byte-identical.
2088 let ops = vec![
2089 LocalGet(0), // 0 value — unconstrained
2090 I32Const(0x7FF), // 1 mask ← fact [0x7FF, 0x7FF] (true, non-constraining)
2091 I32And, // 2
2092 End, // 3
2093 ];
2094 let r = specialize_function("f", &ops, &[], &[fact(1, 0x7FF, 0x7FF)], &[], 0);
2095 assert_eq!(r.admitted.len(), 0);
2096 assert!(!r.changed());
2097 assert_eq!(r.ops, ops);
2098 }
2099
2100 #[test]
2101 fn signed_narrow_bound_that_admits_negative_keeps_the_mask_494() {
2102 // value ∈ [-1, 2047]: -1 is all-ones, so `-1 & 0x7FF = 0x7FF != -1` —
2103 // the obligation is Sat and the mask is (correctly) retained. Guards
2104 // against a naive "hi ≤ mask" shortcut that ignores the sign bit.
2105 let ops = vec![
2106 LocalGet(0), // 0 ← fact [-1, 2047]
2107 I32Const(0x7FF), // 1
2108 I32And, // 2
2109 End, // 3
2110 ];
2111 let r = specialize_function("f", &ops, &[], &[fact(0, -1, 2047)], &[], 0);
2112 assert_eq!(
2113 r.admitted.len(),
2114 0,
2115 "a negative value fails the mask identity"
2116 );
2117 assert!(!r.changed());
2118 assert_eq!(r.ops, ops);
2119 }
2120
2121 #[test]
2122 fn mask_elision_no_facts_changes_nothing_494() {
2123 let ops = pack_lanes_ops();
2124 let r = specialize_function("gust_kernel", &ops, &[], &[], &[], 0);
2125 assert!(!r.changed());
2126 assert_eq!(r.ops, ops);
2127 assert!(!r.declined.is_empty(), "the no-fact case is a loud decline");
2128 }
2129
2130 #[test]
2131 fn out_of_range_value_id_is_vacuous_494() {
2132 let ops = clamp_ops();
2133 let r = specialize_function("f", &ops, CLAMP_ARITY, &[fact(999, 524, 1524)], &[], 0);
2134 assert!(!r.changed());
2135 assert_eq!(r.ops, ops);
2136 }
2137
2138 // ========= #494 bounds-elision (#390 guard_bool): memory bounds guards =========
2139
2140 /// The gust_poll shape: a record array indexed by a proven-bounded slot —
2141 /// `base = slot*16 + 256`, then field loads/stores at static offsets.
2142 fn poll_ops() -> Vec<WasmOp> {
2143 vec![
2144 LocalGet(0), // 0 slot ← fact target
2145 I32Const(4), // 1
2146 I32Shl, // 2 slot*16
2147 I32Const(256), // 3
2148 I32Add, // 4 base
2149 LocalSet(1), // 5
2150 LocalGet(1), // 6
2151 I32Load8U {
2152 offset: 0,
2153 align: 0,
2154 }, // 7 → mark (byte)
2155 LocalGet(1), // 8
2156 I32Load {
2157 offset: 4,
2158 align: 2,
2159 }, // 9 → mark (word)
2160 I32Add, // 10
2161 LocalGet(1), // 11
2162 I32Const(7), // 12
2163 I32Store16 {
2164 offset: 2,
2165 align: 1,
2166 }, // 13 → mark (halfword store)
2167 End, // 14
2168 ]
2169 }
2170
2171 #[test]
2172 fn bounded_index_elides_all_mem_bounds_guards_494() {
2173 // slot ∈ [0, 63] ⇒ base ∈ [256, 1264]; every access's last byte is
2174 // < 65536, so all three obligations fall to
2175 // UNSAT(P ∧ trap_mem_oob(...)). Marks only — the stream is untouched.
2176 let ops = poll_ops();
2177 let r = specialize_function("poll", &ops, &[], &[fact(0, 0, 63)], &[], 65536);
2178 assert_eq!(
2179 r.elide_mem_bounds,
2180 vec![7, 9, 13],
2181 "declines: {:?}",
2182 r.declined
2183 );
2184 assert!(!r.changed(), "guard marks never rewrite the op stream");
2185 assert_eq!(r.ops, ops);
2186 assert_eq!(r.admitted.len(), 3);
2187 for line in &r.admitted {
2188 assert!(line.contains("bounds guard elided"), "{line}");
2189 assert!(line.contains("trap_mem_oob"), "{line}");
2190 assert!(line.contains("certificate-checked"), "{line}");
2191 assert!(line.contains("[0, 63]"), "{line}");
2192 }
2193 }
2194
2195 #[test]
2196 fn oob_admissible_bound_is_sat_and_declines_494() {
2197 // slot ∈ [0, 8192]: slot = 4096 ⇒ base = 65792 > 65536 — the access
2198 // can genuinely escape, the obligation is Sat, the guard stays.
2199 let ops = poll_ops();
2200 let r = specialize_function("poll", &ops, &[], &[fact(0, 0, 8192)], &[], 65536);
2201 assert_eq!(r.elide_mem_bounds, Vec::<usize>::new());
2202 assert_eq!(r.admitted.len(), 0);
2203 assert!(
2204 r.declined
2205 .iter()
2206 .any(|d| d.contains("bounds-guard obligation Sat") && d.contains("counterexample")),
2207 "declines must be loud and carry a model: {:?}",
2208 r.declined
2209 );
2210 }
2211
2212 #[test]
2213 fn unknown_memory_size_declines_mem_bounds_494() {
2214 // linear_memory_bytes == 0 (no module memory context): the bound of
2215 // the obligation does not exist — decline loudly, never guess.
2216 let ops = poll_ops();
2217 let r = specialize_function("poll", &ops, &[], &[fact(0, 0, 63)], &[], 0);
2218 assert_eq!(r.elide_mem_bounds, Vec::<usize>::new());
2219 assert!(
2220 r.declined
2221 .iter()
2222 .any(|d| d.contains("linear-memory size unknown")),
2223 "{:?}",
2224 r.declined
2225 );
2226 }
2227
2228 #[test]
2229 fn unconstrained_index_declines_mem_bounds_494() {
2230 // A TRUE fact exists (so the walk runs) but targets the stored VALUE,
2231 // not the index — the index is unconstrained ⇒ Sat ⇒ loud decline.
2232 let ops = vec![
2233 LocalGet(0), // 0 index — unconstrained
2234 LocalGet(1), // 1 value ← fact (non-constraining)
2235 I32Store {
2236 offset: 0,
2237 align: 2,
2238 }, // 2
2239 End, // 3
2240 ];
2241 let r = specialize_function("f", &ops, &[], &[fact(1, 0, 63)], &[], 65536);
2242 assert_eq!(r.elide_mem_bounds, Vec::<usize>::new());
2243 assert!(
2244 r.declined
2245 .iter()
2246 .any(|d| d.contains("bounds-guard obligation Sat")),
2247 "{:?}",
2248 r.declined
2249 );
2250 }
2251
2252 #[test]
2253 fn wraparound_index_plus_offset_never_falsely_unsat_494() {
2254 // THE WIDTH-EXTENSION GOTCHA: index = -256 (0xFFFFFF00 unsigned) with
2255 // offset = 0x200. A naive 32-bit encoding wraps the effective address
2256 // to 0x104 — "in bounds" — and would falsely elide; WASM's effective
2257 // address is infinite-precision (4294967040 + 512 > 65536 ⇒ TRAPS).
2258 // The 64-bit zero-extension keeps the obligation Sat ⇒ guard retained.
2259 let ops = vec![
2260 LocalGet(0), // 0 ← fact [-256, -256]
2261 I32Load {
2262 offset: 0x200,
2263 align: 2,
2264 }, // 1
2265 End, // 2
2266 ];
2267 let r = specialize_function("f", &ops, &[], &[fact(0, -256, -256)], &[], 65536);
2268 assert_eq!(
2269 r.elide_mem_bounds,
2270 Vec::<usize>::new(),
2271 "a wrapped effective address must NOT elide the guard: {:?}",
2272 r.admitted
2273 );
2274 assert!(
2275 r.declined
2276 .iter()
2277 .any(|d| d.contains("bounds-guard obligation Sat")),
2278 "{:?}",
2279 r.declined
2280 );
2281 }
2282
2283 #[test]
2284 fn access_ending_exactly_at_bound_is_in_bounds_boundary_494() {
2285 // Boundary semantics: a 4-byte load at index 65532 ends exactly AT
2286 // the bound (addr + size == mem_bound) — in bounds per WASM (§4.4.5:
2287 // trap iff ea + size > mem size) and per the guard's `>u`. One past
2288 // (65533) must decline.
2289 let ops = vec![
2290 LocalGet(0), // 0 ← fact
2291 I32Load {
2292 offset: 0,
2293 align: 2,
2294 }, // 1
2295 End, // 2
2296 ];
2297 let ok = specialize_function("f", &ops, &[], &[fact(0, 0, 65532)], &[], 65536);
2298 assert_eq!(ok.elide_mem_bounds, vec![1], "declines: {:?}", ok.declined);
2299 let over = specialize_function("f", &ops, &[], &[fact(0, 0, 65533)], &[], 65536);
2300 assert_eq!(over.elide_mem_bounds, Vec::<usize>::new());
2301 }
2302
2303 #[test]
2304 fn mem_marks_are_remapped_through_a_clamp_elision_494() {
2305 // A clamp elision rewrites the stream; a downstream load's mark must
2306 // land on the REWRITTEN index (the selector keys by its own op index).
2307 let ops = vec![
2308 LocalGet(0), // 0 ← fact [524, 1524]
2309 I32Const(476), // 1
2310 I32Add, // 2
2311 LocalSet(1), // 3
2312 LocalGet(1), // 4 -+ low clamp (elided 4..=10)
2313 I32Const(1000), // 5 |
2314 I32LtS, // 6 |
2315 If, // 7 |
2316 I32Const(1000), // 8 |
2317 LocalSet(1), // 9 |
2318 End, // 10 -+
2319 LocalGet(0), // 11 index = ch ∈ [524, 1524]
2320 I32Load {
2321 offset: 0,
2322 align: 2,
2323 }, // 12 → mark (rewritten index 5)
2324 End, // 13
2325 ];
2326 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 524, 1524)], &[], 65536);
2327 assert!(r.changed(), "declines: {:?}", r.declined);
2328 assert_eq!(r.kept, vec![0, 1, 2, 3, 11, 12, 13]);
2329 assert_eq!(
2330 r.elide_mem_bounds,
2331 vec![5],
2332 "mark remapped from original op#12 to rewritten op#5"
2333 );
2334 }
2335}