Skip to main content

foundry_evm_symbolic/runtime/solver/normalize/
mod.rs

1//! Constraint and expression normalization for solver queries.
2
3use super::*;
4
5mod mul_div;
6mod polynomial;
7mod rounding;
8
9use mul_div::{
10    checked_product_guard_operands, full_mul_div_operands, mul_high_operands,
11    normalize_mul_high_factor_cmp, normalize_quotient_offset_eq, word_division_operands,
12};
13use polynomial::polynomial_identity;
14
15/// Per-expression normalization facts reused across solver queries.
16///
17/// Keys are strong hash-consed handles, so each map is bounded like the SAT cache.
18#[derive(Default)]
19pub(super) struct NormalizationCache {
20    normalized: HashMap<SymBoolExpr, SymBoolExpr>,
21    requires_independent_context: HashMap<SymBoolExpr, bool>,
22}
23
24impl NormalizationCache {
25    pub(super) fn clear(&mut self) {
26        self.normalized.clear();
27        self.requires_independent_context.clear();
28    }
29
30    /// Returns the memoized context-dependence classification of one conjunct.
31    fn requires_independent_context(&mut self, constraint: &SymBoolExpr) -> bool {
32        if let Some(requires) = self.requires_independent_context.get(constraint) {
33            return *requires;
34        }
35        let requires = ConstraintContext::requires_independent_context(constraint);
36        if self.requires_independent_context.len() < SYMBOLIC_SOLVER_SAT_CACHE_MAX_ENTRIES {
37            self.requires_independent_context.insert(constraint.clone(), requires);
38        }
39        requires
40    }
41}
42
43/// Reuses context-free normalization results while retaining per-query contextual rewrites.
44pub(super) fn normalize_constraints_for_solver_cached(
45    cx: &mut SymCx,
46    constraints: &[SymBoolExpr],
47    cache: &mut NormalizationCache,
48) -> Vec<SymBoolExpr> {
49    let mut changed_conjuncts = HashSet::default();
50    let normalized = normalize_constraint_batch(
51        constraints.iter().map(|constraint| {
52            let normalized = if let Some(normalized) = cache.normalized.get(constraint) {
53                normalized.clone()
54            } else {
55                let normalized = normalize_bool_for_solver(cx, constraint.clone());
56                if cache.normalized.len() < SYMBOLIC_SOLVER_SAT_CACHE_MAX_ENTRIES {
57                    cache.normalized.insert(constraint.clone(), normalized.clone());
58                }
59                normalized
60            };
61            if normalized != *constraint {
62                mark_conjuncts(&normalized, &mut changed_conjuncts);
63            }
64            normalized
65        }),
66        constraints.len(),
67    );
68    normalize_contextually(cx, normalized, &changed_conjuncts, |constraint| {
69        cache.requires_independent_context(constraint)
70    })
71}
72
73/// Applies context-dependent rewrites to an already context-free-normalized conjunction.
74fn normalize_contextually(
75    cx: &mut SymCx,
76    normalized: Vec<SymBoolExpr>,
77    changed_conjuncts: &HashSet<SymBoolExpr>,
78    mut requires_independent_context: impl FnMut(&SymBoolExpr) -> bool,
79) -> Vec<SymBoolExpr> {
80    if matches!(normalized.as_slice(), [expr] if expr.as_const() == Some(false)) {
81        return normalized;
82    }
83
84    // Context-dependent rewrites must not contribute facts to the context that proves them. Mark
85    // candidates by syntax rather than by whether the full context happens to prove a rewrite:
86    // contradictory bounds can make an interval unavailable until another candidate is removed.
87    // Classify each conjunct once per query (memoized across queries): the context builder
88    // iterates its input on every propagation round, and classification walks the whole DAG.
89    let retained = normalized
90        .iter()
91        .filter(|constraint| !requires_independent_context(constraint))
92        .collect::<Vec<_>>();
93    let context = ConstraintContext::from_constraints_with_lower_bounds(
94        retained.iter().copied(),
95        retained.len(),
96        false,
97    );
98    let normalized_len = normalized.len();
99    let normalized = normalize_constraint_batch(
100        normalized.into_iter().map(|constraint| {
101            let changed = changed_conjuncts.contains(&constraint);
102            context.normalize_bool(cx, constraint, changed)
103        }),
104        normalized_len,
105    );
106    normalize_bounded_comparisons(cx, normalized)
107}
108
109/// Simplifies predicates using only the other, still-retained conjuncts.
110fn normalize_bounded_comparisons(
111    cx: &mut SymCx,
112    mut constraints: Vec<SymBoolExpr>,
113) -> Vec<SymBoolExpr> {
114    // Later predicates can expose guards needed by earlier ones. Revisit the retained
115    // conjunction, but bound the work; unfinished simplification is still sound SMT input.
116    for _ in 0..MAX_CONTEXTUAL_PASSES {
117        let previous = constraints.clone();
118        let mut index = 0;
119        while index < constraints.len() {
120            let context = ConstraintContext::for_rewrite(cx, &constraints, index);
121            constraints[index] = context.normalize_bool(cx, constraints[index].clone(), false);
122            // Revisit each newly exposed conjunct with the retained supporting facts. Otherwise a
123            // division rewrite can leave a simple contradiction hidden until the SMT fallback.
124            if let SymBoolExprKind::And(terms) = constraints[index].kind() {
125                let terms = terms.to_vec();
126                constraints.splice(index..=index, terms);
127                continue;
128            }
129            match context.bounded_bool_value(&constraints[index]) {
130                Some(false) => return vec![SymBoolExpr::constant(cx, false)],
131                Some(true) => {
132                    constraints.remove(index);
133                }
134                None => index += 1,
135            }
136        }
137        // Contextual rewrites may change sort order or expose a conjunction.
138        let count = constraints.len();
139        constraints = normalize_constraint_batch(constraints, count);
140        if constraints == previous || constraints.iter().any(|c| c.as_const() == Some(false)) {
141            break;
142        }
143    }
144    constraints
145}
146
147fn mark_conjuncts(expr: &SymBoolExpr, out: &mut HashSet<SymBoolExpr>) {
148    let mut pending = vec![expr.clone()];
149    while let Some(expr) = pending.pop() {
150        if !out.insert(expr.clone()) {
151            continue;
152        }
153        if let SymBoolExprKind::And(values) = expr.kind() {
154            pending.extend(values.iter().cloned());
155        }
156    }
157}
158
159fn normalize_constraint_batch(
160    constraints: impl IntoIterator<Item = SymBoolExpr>,
161    capacity: usize,
162) -> Vec<SymBoolExpr> {
163    let mut normalized = Vec::with_capacity(capacity);
164    for constraint in constraints {
165        if constraint.as_const() == Some(false) {
166            return vec![constraint];
167        }
168        constraint.push_normalized_conjuncts(&mut normalized);
169    }
170    sort_dedup_bool_exprs(&mut normalized);
171    normalized
172}
173
174fn sort_dedup_bool_exprs(exprs: &mut Vec<SymBoolExpr>) {
175    // Hash-consing already caches deterministic structural hashes. Only render full structural
176    // keys for the exceedingly rare case where two distinct expressions collide.
177    exprs.sort_unstable_by(bool_expr_cmp);
178    exprs.dedup();
179}
180
181fn bool_expr_cmp(left: &SymBoolExpr, right: &SymBoolExpr) -> std::cmp::Ordering {
182    if left == right {
183        return std::cmp::Ordering::Equal;
184    }
185    left.stable_hash_cmp(right)
186        .then_with(|| bool_structural_key(left).cmp(&bool_structural_key(right)))
187}
188
189fn bool_structural_key(expr: &SymBoolExpr) -> String {
190    let mut key = String::new();
191    write_bool_structural_key(&mut key, expr);
192    key
193}
194
195fn write_bool_structural_key(out: &mut String, expr: &SymBoolExpr) {
196    match expr.kind() {
197        SymBoolExprKind::Const(value) => {
198            let _ = write!(out, "0:{value}");
199        }
200        SymBoolExprKind::Not(value) => {
201            out.push_str("1:");
202            write_bool_structural_key(out, value);
203        }
204        SymBoolExprKind::And(values) => {
205            let _ = write!(out, "2:{}:", values.len());
206            for value in values.iter() {
207                write_bool_structural_key(out, value);
208                out.push(';');
209            }
210        }
211        SymBoolExprKind::Cmp(op, left, right) => {
212            let _ = write!(out, "3:{}:", cmp_op_key(*op));
213            write_expr_structural_key(out, left);
214            out.push(':');
215            write_expr_structural_key(out, right);
216        }
217    }
218}
219
220fn write_expr_structural_key(out: &mut String, expr: &SymExpr) {
221    match expr.kind() {
222        SymExprKind::Const(value) => {
223            let _ = write!(out, "0:{value:064x}");
224        }
225        SymExprKind::Var(name) => {
226            let _ = write!(out, "1:{}", name.id());
227        }
228        SymExprKind::GasLeft(symbol) => {
229            let _ = write!(out, "2:{}", symbol.id());
230        }
231        SymExprKind::Keccak { name, len, bytes } => {
232            let _ = write!(out, "3:{}:", name.id());
233            write_expr_structural_key(out, len);
234            write_exprs_structural_key(out, bytes);
235        }
236        SymExprKind::Hash { name, algorithm, bytes } => {
237            let _ = write!(out, "4:{}:{algorithm}:", name.id());
238            write_exprs_structural_key(out, bytes);
239        }
240        SymExprKind::Not(value) => {
241            out.push_str("5:");
242            write_expr_structural_key(out, value);
243        }
244        SymExprKind::BinOp(op, left, right) => {
245            let _ = write!(out, "6:{}:", expr_binop_key(*op));
246            write_expr_structural_key(out, left);
247            out.push(':');
248            write_expr_structural_key(out, right);
249        }
250        SymExprKind::TernOp(op, left, right, modulus) => {
251            let _ = write!(out, "7:{}:", expr_ternop_key(*op));
252            write_expr_structural_key(out, left);
253            out.push(':');
254            write_expr_structural_key(out, right);
255            out.push(':');
256            write_expr_structural_key(out, modulus);
257        }
258        SymExprKind::Ite(condition, then_expr, else_expr) => {
259            out.push_str("9:");
260            write_bool_structural_key(out, condition);
261            out.push(':');
262            write_expr_structural_key(out, then_expr);
263            out.push(':');
264            write_expr_structural_key(out, else_expr);
265        }
266    }
267}
268
269fn write_exprs_structural_key(out: &mut String, exprs: &[SymExpr]) {
270    let _ = write!(out, "{}:", exprs.len());
271    for expr in exprs {
272        write_expr_structural_key(out, expr);
273        out.push(';');
274    }
275}
276
277const fn cmp_op_key(op: SymCmpOp) -> u8 {
278    match op {
279        SymCmpOp::Eq => 0,
280        SymCmpOp::Ult => 1,
281        SymCmpOp::Ugt => 2,
282        SymCmpOp::Ule => 3,
283        SymCmpOp::Uge => 4,
284        SymCmpOp::Slt => 5,
285        SymCmpOp::Sgt => 6,
286    }
287}
288
289const fn expr_binop_key(op: SymBinOp) -> u8 {
290    match op {
291        SymBinOp::Add => 0,
292        SymBinOp::Sub => 1,
293        SymBinOp::Mul => 2,
294        SymBinOp::UDiv => 3,
295        SymBinOp::URem => 4,
296        SymBinOp::SDiv => 5,
297        SymBinOp::SRem => 6,
298        SymBinOp::And => 7,
299        SymBinOp::Or => 8,
300        SymBinOp::Xor => 9,
301        SymBinOp::Shl => 10,
302        SymBinOp::Shr => 11,
303        SymBinOp::Sar => 12,
304        SymBinOp::MulHigh => 13,
305    }
306}
307
308const fn expr_ternop_key(op: SymTernOp) -> u8 {
309    match op {
310        SymTernOp::AddMod => 0,
311        SymTernOp::MulMod => 1,
312        SymTernOp::MulDiv => 2,
313    }
314}
315
316/// Returns whether canonically ordered normalized constraints contain a direct contradiction.
317pub(super) fn constraints_are_directly_unsat(cx: &mut SymCx, constraints: &[SymBoolExpr]) -> bool {
318    let mut derived = Vec::new();
319    for constraint in constraints {
320        let Some(fact) = bitwise_bool_word_fact(cx, constraint) else {
321            continue;
322        };
323        if let SymBoolExprKind::And(values) = fact.kind() {
324            // A positive conjunction implies each member independently. Retain the aggregate for
325            // exact matches, but expose its members to the direct contradiction check as well.
326            derived.extend(values.iter().cloned());
327        }
328        derived.push(fact);
329    }
330    let contains = |expected: &SymBoolExpr| {
331        constraints.binary_search_by(|candidate| bool_expr_cmp(candidate, expected)).is_ok()
332            || derived.contains(expected)
333    };
334    constraints.iter().chain(&derived).any(|constraint| match constraint.kind() {
335        SymBoolExprKind::Const(false) => true,
336        SymBoolExprKind::Not(inner)
337            if let SymBoolExprKind::And(values) = inner.kind()
338                && values.iter().all(&contains) =>
339        {
340            true
341        }
342        SymBoolExprKind::Not(inner) => contains(inner),
343        _ => {
344            let negated = constraint.clone().not(cx);
345            contains(&negated)
346        }
347    })
348}
349
350fn bitwise_bool_word_fact(cx: &mut SymCx, constraint: &SymBoolExpr) -> Option<SymBoolExpr> {
351    match constraint.kind() {
352        SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
353            if right.as_const().is_some_and(|value| value.is_zero()) =>
354        {
355            left.bitwise_bool_word_condition(cx).map(|condition| condition.not(cx))
356        }
357        SymBoolExprKind::Not(inner) => {
358            let SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) = inner.kind() else {
359                return None;
360            };
361            if !right.as_const().is_some_and(|value| value.is_zero()) {
362                return None;
363            }
364            left.bitwise_bool_word_condition(cx)
365        }
366        _ => None,
367    }
368}
369
370/// Returns whether every expression in `subset` appears in `superset`.
371pub(super) fn sorted_bool_exprs_are_subset(
372    subset: &[SymBoolExpr],
373    superset: &[SymBoolExpr],
374) -> bool {
375    if subset.len() > superset.len() {
376        return false;
377    }
378
379    let superset: HashSet<_> = superset.iter().collect();
380    subset.iter().all(|expected| superset.contains(expected))
381}
382
383/// Normalizes one boolean expression into an equivalent, solver-friendlier form.
384pub(crate) fn normalize_bool_for_solver(cx: &mut SymCx, expr: SymBoolExpr) -> SymBoolExpr {
385    expr.fold(cx, &mut normalize_bool_node_for_solver)
386}
387
388impl SymBoolExpr {
389    fn push_normalized_conjuncts(self, out: &mut Vec<Self>) {
390        match self.kind() {
391            SymBoolExprKind::Const(true) => {}
392            SymBoolExprKind::And(values) => {
393                for value in values.iter().cloned() {
394                    value.push_normalized_conjuncts(out);
395                }
396            }
397            _ => out.push(self),
398        }
399    }
400}
401
402fn normalize_bool_node_for_solver(cx: &mut SymCx, expr: SymBoolExpr) -> SymBoolExpr {
403    if let Some(normalized) = expr.normalize_udiv_for_solver(cx) {
404        return normalized;
405    }
406
407    match expr.kind() {
408        SymBoolExprKind::Not(value) => match value.kind() {
409            SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right)
410                if matches!(left.kind(), SymExprKind::Not(_)) =>
411            {
412                normalize_cmp_for_solver(cx, SymCmpOp::Ule, right.clone(), left.clone())
413            }
414            // The mirror: `!(y <= ~x) => ~x < y`, so both negations share one canonical form.
415            SymBoolExprKind::Cmp(SymCmpOp::Ule, left, right)
416                if matches!(right.kind(), SymExprKind::Not(_)) =>
417            {
418                normalize_cmp_for_solver(cx, SymCmpOp::Ult, right.clone(), left.clone())
419            }
420            _ => expr,
421        },
422        SymBoolExprKind::Cmp(op, left, right) => {
423            let left = normalize_expr_for_solver(cx, left.clone());
424            let right = normalize_expr_for_solver(cx, right.clone());
425            if *op == SymCmpOp::Eq && polynomial_identity(&left, &right) {
426                return SymBoolExpr::constant(cx, true);
427            }
428            if let Some(normalized) = normalize_ite_branch_cmp(cx, *op, &left, &right) {
429                return normalized;
430            }
431            let normalized = normalize_cmp_for_solver(cx, *op, left, right);
432            normalized.normalize_udiv_for_solver(cx).unwrap_or(normalized)
433        }
434        _ => expr,
435    }
436}
437
438/// Compares an `ite` against one of its own branches, as in `ite(c, a, b) < b => c && a < b`.
439/// Fires only when one branch comparison folds to `false`, so the expression never grows; for a
440/// strict comparison the branch equal to the other operand always does. Equality is left to
441/// `SymBoolExpr::ite_eq_arm`.
442fn normalize_ite_branch_cmp(
443    cx: &mut SymCx,
444    op: SymCmpOp,
445    left: &SymExpr,
446    right: &SymExpr,
447) -> Option<SymBoolExpr> {
448    if op == SymCmpOp::Eq {
449        return None;
450    }
451    let (condition, then_value, else_value, ite_on_left) = match (left.kind(), right.kind()) {
452        (SymExprKind::Ite(condition, then_value, else_value), _)
453            if then_value == right || else_value == right =>
454        {
455            (condition, then_value, else_value, true)
456        }
457        (_, SymExprKind::Ite(condition, then_value, else_value))
458            if then_value == left || else_value == left =>
459        {
460            (condition, then_value, else_value, false)
461        }
462        _ => return None,
463    };
464    let mut branch_cmp = |value: &SymExpr| {
465        if ite_on_left {
466            SymBoolExpr::cmp(cx, op, value.clone(), right.clone())
467        } else {
468            SymBoolExpr::cmp(cx, op, left.clone(), value.clone())
469        }
470    };
471    let then_cmp = branch_cmp(then_value);
472    let else_cmp = branch_cmp(else_value);
473    let selected = if then_cmp.as_const() == Some(false) {
474        let not_condition = condition.clone().not(cx);
475        SymBoolExpr::and(cx, vec![not_condition, else_cmp])
476    } else if else_cmp.as_const() == Some(false) {
477        SymBoolExpr::and(cx, vec![condition.clone(), then_cmp])
478    } else {
479        return None;
480    };
481    Some(normalize_bool_for_solver(cx, selected))
482}
483
484fn normalize_cmp_for_solver(
485    cx: &mut SymCx,
486    op: SymCmpOp,
487    left: SymExpr,
488    right: SymExpr,
489) -> SymBoolExpr {
490    if let Some(normalized) = normalize_mul_high_factor_cmp(cx, op, &left, &right) {
491        return normalized;
492    }
493    if op == SymCmpOp::Eq
494        && let Some(normalized) = normalize_quotient_offset_eq(cx, &left, &right)
495    {
496        return normalized;
497    }
498    if op == SymCmpOp::Eq
499        && let Some((a, b)) =
500            mul_high_operands(&left, &right).or_else(|| mul_high_operands(&right, &left))
501    {
502        let high = SymExpr::binop(cx, SymBinOp::MulHigh, a.clone(), b.clone());
503        return SymBoolExpr::eq_word_const(cx, &high, U256::ZERO);
504    }
505    if op == SymCmpOp::Eq {
506        for (quotient, expected) in [(&left, &right), (&right, &left)] {
507            if let Some((denominator, value)) =
508                ConstraintContext::mul_div_identity_operands(quotient, expected)
509                && let Some(factor) = denominator.as_const().filter(|value| !value.is_zero())
510            {
511                // For constant k > 0, (x * k mod 2^256) / k == x iff x <= MAX / k.
512                // The quotient cannot exceed MAX / k; conversely this bound prevents wrapping.
513                // Retain that exact bound instead of asking SMT to solve the overflow check.
514                // `SymExpr::binop` folds a zero factor away, so the non-zero filter is only a
515                // defensive guard against `MAX / 0` should that folding ever change.
516                return SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ule, value, U256::MAX / factor);
517            }
518        }
519        for (quotient, expected) in [(&left, &right), (&right, &left)] {
520            // solc's checked `x * c` guard, `(x * c) / x == c` under `x != 0`, holds exactly when
521            // the product does not wrap: `x <= MAX / c`. Keep that bound instead of the quotient,
522            // which z3 solves slowly when `c` is a power of two, built as a shift.
523            let (guarded, zero_condition) = match quotient.kind() {
524                SymExprKind::Ite(condition, zero, guarded)
525                    if zero.as_const() == Some(U256::ZERO) =>
526                {
527                    (guarded, Some(condition))
528                }
529                _ => (quotient, None),
530            };
531            if let Some(factor) = expected.as_const().filter(|factor| !factor.is_zero())
532                && let Some((denominator, other)) = ConstraintContext::mul_div_operands(guarded)
533                && other.matches(expected)
534                && denominator.as_const().is_none()
535                && zero_condition
536                    .is_none_or(|condition| condition.zero_check_operand() == Some(denominator))
537            {
538                let nonzero = SymBoolExpr::eq_word_const(cx, denominator, U256::ZERO).not(cx);
539                let fits =
540                    SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ule, denominator, U256::MAX / factor);
541                return SymBoolExpr::and(cx, vec![nonzero, fits]);
542            }
543        }
544        if right.as_const().is_some_and(|value| value.is_zero())
545            && let SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) = left.kind()
546        {
547            // Word subtraction is zero exactly when both operands are equal, including at the
548            // modular boundary. Solc commonly lowers optimized equality checks to this shape.
549            return SymBoolExpr::eq(cx, minuend.clone(), subtrahend.clone());
550        }
551        if left.as_const().is_some_and(|value| value.is_zero())
552            && let SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) = right.kind()
553        {
554            return SymBoolExpr::eq(cx, minuend.clone(), subtrahend.clone());
555        }
556    }
557
558    let (left, right) =
559        if matches!(op, SymCmpOp::Ult | SymCmpOp::Ule | SymCmpOp::Ugt | SymCmpOp::Uge) {
560            // Complement reverses unsigned order: ~x = MAX - x. Move it onto
561            // the constant so interval analysis can see Solidity's addition guard.
562            match (left.kind(), right.kind()) {
563                (SymExprKind::Not(value), SymExprKind::Const(limit)) => {
564                    (SymExpr::constant(cx, !*limit), value.clone())
565                }
566                (SymExprKind::Const(limit), SymExprKind::Not(value)) => {
567                    (value.clone(), SymExpr::constant(cx, !*limit))
568                }
569                _ => (left, right),
570            }
571        } else {
572            (left, right)
573        };
574
575    match op {
576        // `a > b => b < a`.
577        SymCmpOp::Ugt => SymBoolExpr::cmp(cx, SymCmpOp::Ult, right, left),
578        // `a >= b => b <= a`.
579        SymCmpOp::Uge => SymBoolExpr::cmp(cx, SymCmpOp::Ule, right, left),
580        // `a >s b => b <s a`.
581        SymCmpOp::Sgt => SymBoolExpr::cmp(cx, SymCmpOp::Slt, right, left),
582        SymCmpOp::Eq | SymCmpOp::Ult | SymCmpOp::Ule | SymCmpOp::Slt => {
583            SymBoolExpr::cmp(cx, op, left, right)
584        }
585    }
586}
587
588/// Simple facts learned from the normalized conjunction currently being queried.
589#[derive(Default)]
590pub(super) struct ConstraintContext {
591    upper_bounds: HashMap<SymExpr, U256>,
592    lower_bounds: HashMap<SymExpr, U256>,
593    unsigned_lower_bounds: HashMap<SymExpr, U256>,
594    exact_values: HashMap<SymExpr, U256>,
595    conflicting_exact_values: HashSet<SymExpr>,
596    non_wrapping_products: HashSet<(SymExpr, SymExpr)>,
597    /// Conjuncts of the context, which decide `ite` conditions they assert or deny.
598    facts: HashSet<SymBoolExpr>,
599    /// The words each word is asserted to be at most, by a `<=` or `<` conjunct.
600    order_facts: HashMap<SymExpr, Vec<SymExpr>>,
601}
602
603#[derive(Clone, Copy)]
604struct WordInterval {
605    min: U256,
606    max: U256,
607}
608
609// These analyses are solver optimizations, so exceeding their local work budget must only make
610// them decline a rewrite. Keeping the bound shared and private prevents deeply nested bytecode
611// expressions from turning a proof shortcut into unbounded Rust recursion.
612const MAX_LOCAL_ANALYSIS_NODES: usize = 256;
613const MAX_CONTEXTUAL_PASSES: usize = 4;
614
615impl WordInterval {
616    fn new(min: U256, max: U256) -> Option<Self> {
617        (min <= max).then_some(Self { min, max })
618    }
619
620    const fn exact(value: U256) -> Self {
621        Self { min: value, max: value }
622    }
623
624    fn with_bounds(self, lower: Option<U256>, upper: Option<U256>) -> Option<Self> {
625        Self::new(
626            self.min.max(lower.unwrap_or(U256::ZERO)),
627            self.max.min(upper.unwrap_or(U256::MAX)),
628        )
629    }
630}
631
632impl ConstraintContext {
633    pub(super) fn new(constraints: &[SymBoolExpr]) -> Self {
634        Self::from_constraints(constraints.iter(), constraints.len())
635    }
636
637    fn from_constraints<'a>(
638        constraints: impl Clone + Iterator<Item = &'a SymBoolExpr>,
639        constraint_count: usize,
640    ) -> Self {
641        Self::from_constraints_with_lower_bounds(constraints, constraint_count, true)
642    }
643
644    /// Builds a rewrite context from the other retained conjuncts, never the predicate itself.
645    fn for_rewrite(cx: &mut SymCx, constraints: &[SymBoolExpr], index: usize) -> Self {
646        let supporting = constraints
647            .iter()
648            .enumerate()
649            .filter_map(|(i, constraint)| (i != index).then_some(constraint));
650        let mut context = Self::from_constraints(supporting.clone(), constraints.len() - 1);
651        // One successful product guard may bound an operand used in another guard.
652        for _ in 0..MAX_CONTEXTUAL_PASSES {
653            let mut changed = false;
654            for constraint in supporting.clone() {
655                changed |= context.record_non_wrapping_product(cx, constraint);
656            }
657            if !changed {
658                break;
659            }
660        }
661        // Product bounds can then turn scaled zero checks into exact operand facts.
662        for constraint in supporting {
663            context.record_scaled_zero_fact(cx, constraint);
664        }
665        context
666    }
667
668    fn from_constraints_with_lower_bounds<'a>(
669        constraints: impl Clone + Iterator<Item = &'a SymBoolExpr>,
670        constraint_count: usize,
671        promote_unsigned_bounds: bool,
672    ) -> Self {
673        let mut context = Self::default();
674        for constraint in constraints.clone() {
675            mark_conjuncts(constraint, &mut context.facts);
676            context.record_exact_value_constraint(constraint);
677            context.record_upper_bound_constraint(constraint);
678            context.record_lower_bound_constraint(constraint);
679            context.record_unsigned_lower_bound_constraint(constraint, promote_unsigned_bounds);
680            context.record_zero_mul_high(constraint);
681        }
682        for fact in &context.facts {
683            let (small, large) = match fact.kind() {
684                SymBoolExprKind::Cmp(SymCmpOp::Ult | SymCmpOp::Ule, left, right) => (left, right),
685                SymBoolExprKind::Not(inner)
686                    if let SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) = inner.kind() =>
687                {
688                    (right, left)
689                }
690                _ => continue,
691            };
692            context.order_facts.entry(small.clone()).or_default().push(large.clone());
693        }
694        // A bounded number of rounds closes ordinary order chains. Relational propagation keeps
695        // strict comparisons weak (`a < b` propagates only `a <= upper(b)`), so inconsistent
696        // cycles cannot tighten a bound one integer at a time across the uint256 domain.
697        for _ in 0..constraint_count {
698            let mut changed = false;
699            for constraint in constraints.clone() {
700                changed |= context.propagate_order_bounds(constraint);
701            }
702            if !changed {
703                break;
704            }
705        }
706        context.propagate_masked_upper_bounds();
707        context
708    }
709
710    /// Transfers `x & low_mask <= k` to `x` once another bound proves `x` fits the mask, so the
711    /// bound survives dropping the mask from `x`.
712    fn propagate_masked_upper_bounds(&mut self) {
713        let transferred = self
714            .upper_bounds
715            .iter()
716            .filter_map(|(masked, bound)| {
717                let SymExprKind::BinOp(SymBinOp::And, value, mask) = masked.kind() else {
718                    return None;
719                };
720                let bits = mask_low_bits(mask.as_const()?)?;
721                (self.upper_bounds.get(value)?.bit_len() <= bits).then(|| (value.clone(), *bound))
722            })
723            .collect::<Vec<_>>();
724        for (value, bound) in transferred {
725            self.record_upper_bound(value, bound);
726        }
727    }
728
729    /// Conservatively identifies every conjunct that path facts may rewrite.
730    fn requires_independent_context(expr: &SymBoolExpr) -> bool {
731        let root_candidate = match expr.kind() {
732            SymBoolExprKind::Cmp(op, left, right) => match op {
733                SymCmpOp::Eq => {
734                    Self::mul_div_identity_operands(left, right).is_some()
735                        || Self::mul_div_identity_operands(right, left).is_some()
736                        || Self::masked_word_side_eq_self_shape(left, right).is_some()
737                        || Self::masked_word_side_eq_self_shape(right, left).is_some()
738                }
739                SymCmpOp::Ult | SymCmpOp::Ule => {
740                    Self::udiv_comparison_operands(*op, left, right).is_some()
741                }
742                SymCmpOp::Slt | SymCmpOp::Sgt => true,
743                SymCmpOp::Ugt | SymCmpOp::Uge => false,
744            },
745            SymBoolExprKind::Not(value) => match value.kind() {
746                SymBoolExprKind::Cmp(op, left, right)
747                    if Self::udiv_comparison_operands(*op, left, right).is_some() =>
748                {
749                    true
750                }
751                SymBoolExprKind::Cmp(SymCmpOp::Slt | SymCmpOp::Sgt, _, _) => true,
752                _ => value.zero_check_operand().is_some_and(|word| {
753                    matches!(word.kind(), SymExprKind::BinOp(SymBinOp::Or, _, _))
754                }),
755            },
756            SymBoolExprKind::Const(_) | SymBoolExprKind::And(_) => false,
757        };
758        root_candidate
759            || expr.contains_udiv()
760            || expr.visit_bool(|word| {
761                matches!(
762                    word.kind(),
763                    SymExprKind::Ite(_, _, _) | SymExprKind::BinOp(SymBinOp::URem, _, _)
764                )
765            })
766    }
767
768    fn normalize_bool(
769        &self,
770        cx: &mut SymCx,
771        expr: SymBoolExpr,
772        context_free_changed: bool,
773    ) -> SymBoolExpr {
774        let may_normalize_word = !self.is_exact_value_constraint(&expr)
775            && expr.visit_bool(|word| self.may_normalize_word(word));
776        let expr = if may_normalize_word {
777            let expr = expr.fold_exprs(cx, &mut |cx, expr| self.normalize_word(cx, expr));
778            normalize_bool_for_solver(cx, expr)
779        } else if context_free_changed {
780            // The first pass can create new Boolean predicates, such as an overflow comparison
781            // while eliminating a division. Normalize those predicates before applying facts.
782            normalize_bool_for_solver(cx, expr)
783        } else {
784            expr
785        };
786        if let Some(normalized) = self.normalize_signed_add_comparison(cx, &expr) {
787            return normalized;
788        }
789        if let Some(value) = self.rounding_comparison_value(&expr) {
790            return SymBoolExpr::constant(cx, value);
791        }
792        if let Some(value) = self.division_comparison_value(&expr) {
793            return SymBoolExpr::constant(cx, value);
794        }
795        if let SymBoolExprKind::Not(value) = expr.kind()
796            && let Some(normalized) = self.normalize_signed_add_comparison(cx, value)
797        {
798            return normalized.not(cx);
799        }
800        if let SymBoolExprKind::Cmp(op, left, right) = expr.kind()
801            && let Some(normalized) = self.normalize_udiv_comparison(cx, *op, left, right)
802        {
803            return normalized;
804        }
805        if let SymBoolExprKind::Not(value) = expr.kind()
806            && let SymBoolExprKind::Cmp(op, left, right) = value.kind()
807            && let Some(normalized) = self.normalize_udiv_comparison(cx, *op, left, right)
808        {
809            return normalized.not(cx);
810        }
811
812        match expr.kind() {
813            SymBoolExprKind::Not(value) if self.unsigned_bool_always_true(value) => {
814                SymBoolExpr::constant(cx, false)
815            }
816            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
817                if self.mul_div_identity(left, right) || self.mul_div_identity(right, left) =>
818            {
819                SymBoolExpr::constant(cx, true)
820            }
821            SymBoolExprKind::Not(value)
822                if matches!(
823                    value.kind(),
824                    SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
825                        if self.mul_div_identity(left, right)
826                            || self.mul_div_identity(right, left)
827                ) =>
828            {
829                SymBoolExpr::constant(cx, false)
830            }
831            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
832                if self.masked_word_eq_self(left, right) =>
833            {
834                // `x & mask == x => true` when the current context proves `x <= mask`.
835                SymBoolExpr::constant(cx, true)
836            }
837            SymBoolExprKind::Not(value) if self.masked_eq_self_condition(value) => {
838                // `x & mask != x => false` when the current context proves `x <= mask`.
839                SymBoolExpr::constant(cx, false)
840            }
841            _ if expr
842                .zero_check_operand()
843                .is_some_and(|left| self.word_bool_always_true(cx, left)) =>
844            {
845                // `always_true_word == 0 => false`.
846                SymBoolExpr::constant(cx, false)
847            }
848            SymBoolExprKind::Not(value)
849                if value
850                    .zero_check_operand()
851                    .is_some_and(|left| self.word_bool_always_true(cx, left)) =>
852            {
853                // `always_true_word != 0 => true`.
854                SymBoolExpr::constant(cx, true)
855            }
856            _ => expr,
857        }
858    }
859
860    fn record_exact_value_constraint(&mut self, constraint: &SymBoolExpr) {
861        let SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) = constraint.kind() else {
862            return;
863        };
864        let Some((expr, value)) = const_side_bound(left, right) else {
865            return;
866        };
867        if !matches!(expr.kind(), SymExprKind::Var(_))
868            || self.conflicting_exact_values.contains(expr)
869        {
870            return;
871        }
872        if self.exact_values.get(expr).is_some_and(|current| *current != value) {
873            self.exact_values.remove(expr);
874            self.conflicting_exact_values.insert(expr.clone());
875        } else {
876            self.exact_values.insert(expr.clone(), value);
877        }
878    }
879
880    fn may_normalize_word(&self, expr: &SymExpr) -> bool {
881        if self.exact_values.contains_key(expr)
882            || Self::mul_div_operands(expr).is_some()
883            || Self::ceil_div_product(expr).is_some()
884            || full_mul_div_operands(expr).is_some()
885        {
886            return true;
887        }
888        match expr.kind() {
889            SymExprKind::Ite(_, _, _) => true,
890            SymExprKind::BinOp(SymBinOp::And, _, mask) => {
891                mask.as_const().and_then(mask_low_bits).is_some()
892            }
893            SymExprKind::BinOp(SymBinOp::Or, left, right) => {
894                left.as_const() == Some(U256::ONE) || right.as_const() == Some(U256::ONE)
895            }
896            SymExprKind::BinOp(SymBinOp::Mul, _, _) => Self::constant_mul_operands(expr)
897                .is_some_and(|(value, _)| Self::constant_mul_operands(value).is_some()),
898            SymExprKind::BinOp(SymBinOp::UDiv, numerator, denominator) => {
899                Self::rounded_product_operands(numerator).is_some()
900                    || (denominator.as_const().is_some_and(|value| !value.is_zero())
901                        && Self::constant_mul_operands(numerator).is_some())
902            }
903            _ => false,
904        }
905    }
906
907    fn normalize_word(&self, cx: &mut SymCx, expr: SymExpr) -> SymExpr {
908        if let Some(value) = self.exact_values.get(&expr).copied() {
909            return SymExpr::constant(cx, value);
910        }
911        if let SymExprKind::Ite(condition, then_value, else_value) = expr.kind() {
912            if let Some(value) = self.bounded_bool_value(condition).or_else(|| {
913                if self.facts.contains(condition) {
914                    Some(true)
915                } else {
916                    self.facts.contains(&condition.clone().not(cx)).then_some(false)
917                }
918            }) {
919                return if value { then_value.clone() } else { else_value.clone() };
920            }
921            if let Some(condition) = self.normalize_signed_add_comparison(cx, condition) {
922                return SymExpr::ite(cx, condition, then_value.clone(), else_value.clone());
923            }
924        }
925        if let Some(value) = self.quotient_of_rounded_product(&expr) {
926            return value.clone();
927        }
928        if let Some(quotient) = self.full_mul_div(cx, &expr) {
929            return quotient;
930        }
931        if let SymExprKind::BinOp(SymBinOp::And, value, mask) = expr.kind()
932            && let Some(bits) = mask.as_const().and_then(mask_low_bits)
933            && self.unsigned_bits(value) <= bits
934        {
935            // `x & low_mask => x` when the current context proves `x` fits the mask.
936            return value.clone();
937        }
938        if let SymExprKind::BinOp(SymBinOp::And, value, mask) = expr.kind()
939            && mask.as_const() == Some(U256::ONE)
940            && value.normalized_bool_word_condition(cx).is_some()
941        {
942            return value.clone();
943        }
944        if let SymExprKind::BinOp(SymBinOp::Or, left, right) = expr.kind()
945            && ((left.as_const() == Some(U256::ONE)
946                && right.normalized_bool_word_condition(cx).is_some())
947                || (right.as_const() == Some(U256::ONE)
948                    && left.normalized_bool_word_condition(cx).is_some()))
949        {
950            return SymExpr::one(cx);
951        }
952        if let Some((value, outer_factor)) = Self::constant_mul_operands(&expr)
953            && let Some((value, inner_factor)) = Self::constant_mul_operands(value)
954        {
955            let factor = SymExpr::constant(cx, inner_factor.wrapping_mul(outer_factor));
956            return SymExpr::binop(cx, SymBinOp::Mul, value.clone(), factor);
957        }
958        if let Some((value, factor)) =
959            self.exact_ceil_div_factor(&expr).or_else(|| self.exact_scaled_div_factor(&expr))
960        {
961            let factor = SymExpr::constant(cx, factor);
962            return SymExpr::binop(cx, SymBinOp::Mul, value.clone(), factor);
963        }
964        if let Some((denominator, other)) = Self::mul_div_operands(&expr)
965            && self.interval(denominator).is_some_and(|interval| !interval.min.is_zero())
966        {
967            let other = match other {
968                MulDivFactor::Expr(other) => other.clone(),
969                MulDivFactor::Const(other) => SymExpr::constant(cx, other),
970            };
971            if self.mul_cannot_overflow_256(denominator, &other) {
972                return other;
973            }
974        }
975        expr
976    }
977
978    fn bounded_bool_value(&self, expr: &SymBoolExpr) -> Option<bool> {
979        match expr.kind() {
980            SymBoolExprKind::Const(value) => Some(*value),
981            SymBoolExprKind::Not(value) => self.bounded_bool_value(value).map(|value| !value),
982            SymBoolExprKind::Cmp(op, left, right) => {
983                let left = self.interval(left)?;
984                let right = self.interval(right)?;
985                if *op == SymCmpOp::Eq {
986                    return if left.max < right.min || right.max < left.min {
987                        Some(false)
988                    } else if left.min == left.max && right.min == right.max {
989                        Some(left.min == right.min)
990                    } else {
991                        None
992                    };
993                }
994                if matches!(op, SymCmpOp::Slt | SymCmpOp::Sgt)
995                    && (left.min.bit(255) != left.max.bit(255)
996                        || right.min.bit(255) != right.max.bit(255))
997                {
998                    return None;
999                }
1000                let (always, possible) =
1001                    if matches!(op, SymCmpOp::Ult | SymCmpOp::Ule | SymCmpOp::Slt) {
1002                        (op.eval(left.max, right.min), op.eval(left.min, right.max))
1003                    } else {
1004                        (op.eval(left.min, right.max), op.eval(left.max, right.min))
1005                    };
1006                if always {
1007                    Some(true)
1008                } else if !possible {
1009                    Some(false)
1010                } else {
1011                    None
1012                }
1013            }
1014            SymBoolExprKind::And(_) => None,
1015        }
1016    }
1017
1018    /// Simplifies signed addition guards once the signs of the summands are established.
1019    fn normalize_signed_add_comparison(
1020        &self,
1021        cx: &mut SymCx,
1022        expr: &SymBoolExpr,
1023    ) -> Option<SymBoolExpr> {
1024        let SymBoolExprKind::Cmp(op, left, right) = expr.kind() else { return None };
1025        let (sum, base) = match op {
1026            SymCmpOp::Slt => (left, right),
1027            SymCmpOp::Sgt => (right, left),
1028            _ => return None,
1029        };
1030        let signed_max = U256::MAX >> 1;
1031        if let Some((_, increment)) = sum.add_with_operand(base) {
1032            let base_range = self.interval(base)?;
1033            let increment_range = self.interval(increment)?;
1034            // Opposite-sign addition cannot overflow: adding a nonnegative value cannot make
1035            // a negative summand smaller, and adding a negative value makes a nonnegative one
1036            // smaller.
1037            if base_range.min > signed_max && increment_range.max <= signed_max {
1038                return Some(SymBoolExpr::constant(cx, false));
1039            }
1040            if base_range.max <= signed_max && increment_range.min > signed_max {
1041                return Some(SymBoolExpr::constant(cx, true));
1042            }
1043        } else if base.as_const() != Some(U256::ZERO) {
1044            return None;
1045        }
1046        if base.as_const() == Some(U256::ZERO)
1047            && let SymExprKind::BinOp(SymBinOp::Add, left, right) = sum.kind()
1048        {
1049            for (positive, negative) in [(left, right), (right, left)] {
1050                if let SymExprKind::BinOp(SymBinOp::Sub, zero, amount) = negative.kind()
1051                    && zero.as_const() == Some(U256::ZERO)
1052                    && self.interval(positive).is_some_and(|range| range.max <= signed_max)
1053                    && self.interval(amount).is_some_and(|range| range.max <= signed_max)
1054                {
1055                    // For a,b in [0, int256::MAX], signed(a + (-b)) < 0 iff a < b.
1056                    return Some(SymBoolExpr::cmp_word_expr(
1057                        cx,
1058                        SymCmpOp::Ult,
1059                        positive,
1060                        amount.clone(),
1061                    ));
1062                }
1063            }
1064        }
1065        // Use the sum's canonical operand order for both the overflow guard and a subsequent
1066        // signed-to-unsigned cast. Their conditions must normalize to the same predicate.
1067        let SymExprKind::BinOp(SymBinOp::Add, increment, base) = sum.kind() else {
1068            return None;
1069        };
1070        if self.interval(base)?.max > signed_max || self.interval(increment)?.max > signed_max {
1071            return None;
1072        }
1073        // With nonnegative summands their unsigned sum cannot wrap. It is signed-less than a
1074        // summand exactly when it crosses the signed maximum; equality (zero increment) is safe.
1075        let limit = SymExpr::constant(cx, signed_max);
1076        let remaining = SymExpr::binop(cx, SymBinOp::Sub, limit, base.clone());
1077        Some(SymBoolExpr::cmp(cx, SymCmpOp::Ult, remaining, increment.clone()))
1078    }
1079
1080    fn exact_ceil_div_factor<'a>(&self, expr: &'a SymExpr) -> Option<(&'a SymExpr, U256)> {
1081        let (product, denominator) = Self::ceil_div_product(expr)?;
1082        let (value, multiplier) = Self::constant_mul_operands(product)?;
1083        self.max_scaled_product(value, multiplier)?.checked_add(denominator)?;
1084        let factor = multiplier.checked_div(denominator)?;
1085        (multiplier % denominator).is_zero().then_some((value, factor))
1086    }
1087
1088    /// Recognizes `(product + scale - 1) / scale` without assuming the arithmetic cannot wrap.
1089    fn ceil_div_product(expr: &SymExpr) -> Option<(&SymExpr, U256)> {
1090        let (numerator, denominator) = expr.udiv_operands()?;
1091        let scale = denominator.as_const().filter(|value| !value.is_zero())?;
1092        if let SymExprKind::BinOp(SymBinOp::Sub, sum, one) = numerator.kind()
1093            && one.as_const() == Some(U256::ONE)
1094            && let SymExprKind::BinOp(SymBinOp::Add, product, rounding) = sum.kind()
1095            && rounding.as_const() == Some(scale)
1096            && matches!(product.kind(), SymExprKind::BinOp(SymBinOp::Mul, _, _))
1097        {
1098            Some((product, scale))
1099        } else {
1100            None
1101        }
1102    }
1103
1104    fn exact_scaled_div_factor<'a>(&self, expr: &'a SymExpr) -> Option<(&'a SymExpr, U256)> {
1105        let (numerator, denominator) = expr.udiv_operands()?;
1106        let denominator = denominator.as_const().filter(|value| !value.is_zero())?;
1107        let (value, multiplier) = Self::constant_mul_operands(numerator)?;
1108        if !(multiplier % denominator).is_zero()
1109            || self.max_scaled_product(value, multiplier).is_none()
1110        {
1111            return None;
1112        }
1113        Some((value, multiplier / denominator))
1114    }
1115
1116    fn max_scaled_product(&self, value: &SymExpr, multiplier: U256) -> Option<U256> {
1117        self.interval(value)?.max.checked_mul(multiplier)
1118    }
1119
1120    fn constant_mul_operands(expr: &SymExpr) -> Option<(&SymExpr, U256)> {
1121        let SymExprKind::BinOp(SymBinOp::Mul, left, right) = expr.kind() else {
1122            return None;
1123        };
1124        const_side_bound(left, right)
1125    }
1126
1127    fn is_exact_value_constraint(&self, constraint: &SymBoolExpr) -> bool {
1128        let SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) = constraint.kind() else {
1129            return false;
1130        };
1131        const_side_bound(left, right)
1132            .is_some_and(|(expr, value)| self.exact_values.get(expr).copied() == Some(value))
1133    }
1134
1135    fn masked_eq_self_condition(&self, expr: &SymBoolExpr) -> bool {
1136        match expr.kind() {
1137            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => {
1138                self.masked_word_eq_self(left, right)
1139            }
1140            _ => false,
1141        }
1142    }
1143
1144    fn masked_word_eq_self(&self, left: &SymExpr, right: &SymExpr) -> bool {
1145        self.masked_word_side_eq_self(left, right) || self.masked_word_side_eq_self(right, left)
1146    }
1147
1148    fn masked_word_side_eq_self(&self, masked: &SymExpr, value: &SymExpr) -> bool {
1149        Self::masked_word_side_eq_self_shape(masked, value)
1150            .is_some_and(|bits| self.unsigned_bits(value) <= bits)
1151    }
1152
1153    fn masked_word_side_eq_self_shape(masked: &SymExpr, value: &SymExpr) -> Option<usize> {
1154        let SymExprKind::BinOp(SymBinOp::And, left, right) = masked.kind() else {
1155            return None;
1156        };
1157        let (source, mask) = const_side_bound(left, right)?;
1158        let bits = mask_low_bits(mask)?;
1159        (source == value).then_some(bits)
1160    }
1161
1162    fn record_upper_bound_constraint(&mut self, constraint: &SymBoolExpr) {
1163        if let Some((expr, bound)) = self.upper_bound_constraint(constraint) {
1164            self.record_upper_bound(expr.clone(), bound);
1165        }
1166    }
1167
1168    fn record_upper_bound(&mut self, expr: SymExpr, bound: U256) -> bool {
1169        match self.upper_bounds.entry(expr) {
1170            alloy_primitives::map::Entry::Occupied(mut entry) if bound < *entry.get() => {
1171                entry.insert(bound);
1172                true
1173            }
1174            alloy_primitives::map::Entry::Vacant(entry) => {
1175                entry.insert(bound);
1176                true
1177            }
1178            alloy_primitives::map::Entry::Occupied(_) => false,
1179        }
1180    }
1181
1182    fn record_lower_bound_constraint(&mut self, constraint: &SymBoolExpr) {
1183        if let Some((expr, bound)) = self.lower_bound_constraint(constraint) {
1184            self.record_lower_bound(expr.clone(), bound);
1185        }
1186    }
1187
1188    fn record_unsigned_lower_bound_constraint(
1189        &mut self,
1190        constraint: &SymBoolExpr,
1191        promote_to_interval: bool,
1192    ) {
1193        if let Some((expr, bound)) = self.unsigned_lower_bound_constraint(constraint) {
1194            let entry = self.unsigned_lower_bounds.entry(expr.clone()).or_default();
1195            *entry = (*entry).max(bound);
1196            // Batch normalization keeps theorem bounds separate from general intervals.
1197            // A rewrite supported only by other retained conjuncts may also use these bounds
1198            // for interval deductions.
1199            if promote_to_interval {
1200                self.record_lower_bound(expr.clone(), bound);
1201            }
1202        }
1203    }
1204
1205    fn unsigned_lower_bound_constraint<'a>(
1206        &self,
1207        constraint: &'a SymBoolExpr,
1208    ) -> Option<(&'a SymExpr, U256)> {
1209        match constraint.kind() {
1210            SymBoolExprKind::Cmp(op, left, right) => match *op {
1211                SymCmpOp::Eq => const_side_bound(left, right),
1212                SymCmpOp::Ult => {
1213                    left.as_const()?.checked_add(U256::ONE).map(|bound| (right, bound))
1214                }
1215                SymCmpOp::Ule => left.as_const().map(|bound| (right, bound)),
1216                SymCmpOp::Ugt => {
1217                    right.as_const()?.checked_add(U256::ONE).map(|bound| (left, bound))
1218                }
1219                SymCmpOp::Uge => right.as_const().map(|bound| (left, bound)),
1220                SymCmpOp::Slt | SymCmpOp::Sgt => None,
1221            },
1222            SymBoolExprKind::Not(value) => match value.kind() {
1223                SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) => {
1224                    right.as_const().map(|bound| (left, bound))
1225                }
1226                SymBoolExprKind::Cmp(SymCmpOp::Ule, left, right) => {
1227                    right.as_const()?.checked_add(U256::ONE).map(|bound| (left, bound))
1228                }
1229                SymBoolExprKind::Cmp(SymCmpOp::Ugt, left, right) => {
1230                    left.as_const().map(|bound| (right, bound))
1231                }
1232                SymBoolExprKind::Cmp(SymCmpOp::Uge, left, right) => {
1233                    left.as_const()?.checked_add(U256::ONE).map(|bound| (right, bound))
1234                }
1235                _ => None,
1236            },
1237            _ => None,
1238        }
1239    }
1240
1241    fn record_lower_bound(&mut self, expr: SymExpr, bound: U256) -> bool {
1242        match self.lower_bounds.entry(expr) {
1243            alloy_primitives::map::Entry::Occupied(mut entry) if bound > *entry.get() => {
1244                entry.insert(bound);
1245                true
1246            }
1247            alloy_primitives::map::Entry::Vacant(entry) => {
1248                entry.insert(bound);
1249                true
1250            }
1251            alloy_primitives::map::Entry::Occupied(_) => false,
1252        }
1253    }
1254
1255    fn propagate_order_bounds(&mut self, constraint: &SymBoolExpr) -> bool {
1256        match constraint.kind() {
1257            SymBoolExprKind::Cmp(op, left, right) => match op {
1258                SymCmpOp::Ult | SymCmpOp::Ule => self.propagate_less_or_equal_bounds(left, right),
1259                SymCmpOp::Ugt | SymCmpOp::Uge => self.propagate_less_or_equal_bounds(right, left),
1260                SymCmpOp::Eq => {
1261                    let changed = self.propagate_less_or_equal_bounds(left, right);
1262                    self.propagate_less_or_equal_bounds(right, left) || changed
1263                }
1264                SymCmpOp::Slt | SymCmpOp::Sgt => false,
1265            },
1266            SymBoolExprKind::Not(value) => match value.kind() {
1267                SymBoolExprKind::Cmp(op, left, right) => match op {
1268                    SymCmpOp::Ult | SymCmpOp::Ule => {
1269                        self.propagate_less_or_equal_bounds(right, left)
1270                    }
1271                    SymCmpOp::Ugt | SymCmpOp::Uge => {
1272                        self.propagate_less_or_equal_bounds(left, right)
1273                    }
1274                    SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => false,
1275                },
1276                _ => false,
1277            },
1278            SymBoolExprKind::Const(_) | SymBoolExprKind::And(_) => false,
1279        }
1280    }
1281
1282    /// Propagates interval bounds through the known unsigned relation `left <= right`.
1283    fn propagate_less_or_equal_bounds(&mut self, left: &SymExpr, right: &SymExpr) -> bool {
1284        let upper = self.upper_bounds.get(right).copied();
1285        let lower = self.lower_bounds.get(left).copied();
1286        let upper_changed = upper.is_some_and(|bound| self.record_upper_bound(left.clone(), bound));
1287        let lower_changed =
1288            lower.is_some_and(|bound| self.record_lower_bound(right.clone(), bound));
1289        upper_changed || lower_changed
1290    }
1291
1292    fn upper_bound_constraint<'a>(
1293        &self,
1294        constraint: &'a SymBoolExpr,
1295    ) -> Option<(&'a SymExpr, U256)> {
1296        match constraint.kind() {
1297            SymBoolExprKind::Cmp(op, left, right) => match *op {
1298                SymCmpOp::Eq => const_side_bound(left, right),
1299                SymCmpOp::Ult => match (left.as_const(), right.as_const()) {
1300                    (_, Some(bound)) => (!bound.is_zero()).then(|| (left, bound - U256::ONE)),
1301                    _ => None,
1302                },
1303                SymCmpOp::Ule => match (left.as_const(), right.as_const()) {
1304                    (_, Some(bound)) => Some((left, bound)),
1305                    _ => None,
1306                },
1307                SymCmpOp::Ugt => match (left.as_const(), right.as_const()) {
1308                    (Some(bound), _) => (!bound.is_zero()).then(|| (right, bound - U256::ONE)),
1309                    _ => None,
1310                },
1311                SymCmpOp::Uge => match (left.as_const(), right.as_const()) {
1312                    (Some(bound), _) => Some((right, bound)),
1313                    _ => None,
1314                },
1315                SymCmpOp::Slt | SymCmpOp::Sgt => None,
1316            },
1317            SymBoolExprKind::Not(value) => match value.kind() {
1318                SymBoolExprKind::Cmp(op, left, right) => match *op {
1319                    SymCmpOp::Ugt => match (left.as_const(), right.as_const()) {
1320                        (_, Some(bound)) => Some((left, bound)),
1321                        _ => None,
1322                    },
1323                    SymCmpOp::Uge => match (left.as_const(), right.as_const()) {
1324                        (_, Some(bound)) => (!bound.is_zero()).then(|| (left, bound - U256::ONE)),
1325                        _ => None,
1326                    },
1327                    SymCmpOp::Ult => match (left.as_const(), right.as_const()) {
1328                        (Some(bound), _) => Some((right, bound)),
1329                        _ => None,
1330                    },
1331                    SymCmpOp::Ule => match (left.as_const(), right.as_const()) {
1332                        (Some(bound), _) => (!bound.is_zero()).then(|| (right, bound - U256::ONE)),
1333                        _ => None,
1334                    },
1335                    // `x != MAX => x <= MAX - 1`; normalized equalities put the constant on the
1336                    // RHS.
1337                    SymCmpOp::Eq => {
1338                        (right.as_const() == Some(U256::MAX)).then(|| (left, U256::MAX - U256::ONE))
1339                    }
1340                    SymCmpOp::Slt | SymCmpOp::Sgt => None,
1341                },
1342                _ => None,
1343            },
1344            SymBoolExprKind::Const(_) | SymBoolExprKind::And(_) => None,
1345        }
1346    }
1347
1348    fn lower_bound_constraint<'a>(
1349        &self,
1350        constraint: &'a SymBoolExpr,
1351    ) -> Option<(&'a SymExpr, U256)> {
1352        match constraint.kind() {
1353            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => const_side_bound(left, right),
1354            SymBoolExprKind::Not(value) => match value.kind() {
1355                SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => {
1356                    if right.as_const().is_some_and(|value| value.is_zero()) {
1357                        Some((left, U256::ONE))
1358                    } else if left.as_const().is_some_and(|value| value.is_zero()) {
1359                        Some((right, U256::ONE))
1360                    } else {
1361                        None
1362                    }
1363                }
1364                _ => None,
1365            },
1366            _ => None,
1367        }
1368    }
1369
1370    fn unsigned_bool_always_true(&self, expr: &SymBoolExpr) -> bool {
1371        match expr.kind() {
1372            SymBoolExprKind::Cmp(op, left, right) => {
1373                self.unsigned_cmp_always_true(*op, left, right)
1374            }
1375            _ => false,
1376        }
1377    }
1378
1379    fn unsigned_cmp_always_true(&self, op: SymCmpOp, left: &SymExpr, right: &SymExpr) -> bool {
1380        if op == SymCmpOp::Eq
1381            && (self.mul_div_identity(left, right) || self.mul_div_identity(right, left))
1382        {
1383            return true;
1384        }
1385        let Some(left) = self.interval(left) else {
1386            return false;
1387        };
1388        let Some(right) = self.interval(right) else {
1389            return false;
1390        };
1391        match op {
1392            SymCmpOp::Ult => left.max < right.min,
1393            SymCmpOp::Ule => left.max <= right.min,
1394            SymCmpOp::Ugt => left.min > right.max,
1395            SymCmpOp::Uge => left.min >= right.max,
1396            SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => false,
1397        }
1398    }
1399
1400    fn mul_div_identity(&self, quotient: &SymExpr, expected: &SymExpr) -> bool {
1401        let Some((denominator, other)) = Self::mul_div_identity_operands(quotient, expected) else {
1402            return false;
1403        };
1404
1405        self.interval(denominator).is_some_and(|interval| !interval.min.is_zero())
1406            && self.mul_cannot_overflow_256(denominator, other)
1407    }
1408
1409    fn mul_div_identity_operands<'a>(
1410        quotient: &'a SymExpr,
1411        expected: &'a SymExpr,
1412    ) -> Option<(&'a SymExpr, &'a SymExpr)> {
1413        let (denominator, other) = Self::mul_div_operands(quotient)?;
1414        other.matches(expected).then_some((denominator, expected))
1415    }
1416
1417    /// Returns the denominator `x` and the other factor of `(x * f) / x`.
1418    pub(super) fn mul_div_operands(quotient: &SymExpr) -> Option<(&SymExpr, MulDivFactor<'_>)> {
1419        let (numerator, denominator) = quotient.udiv_operands()?;
1420        match numerator.kind() {
1421            SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
1422                let other = if left == denominator {
1423                    right
1424                } else if right == denominator {
1425                    left
1426                } else {
1427                    return None;
1428                };
1429                Some((denominator, MulDivFactor::Expr(other)))
1430            }
1431            // Construction rewrites `x * 2**n` to `x << n`, as in solc's checked `x * 2` guard.
1432            SymExprKind::BinOp(SymBinOp::Shl, left, shift) if left == denominator => {
1433                let shift = shift.as_const().filter(|shift| *shift < U256::from(256))?;
1434                Some((denominator, MulDivFactor::Const(U256::ONE << shift.to::<usize>())))
1435            }
1436            _ => None,
1437        }
1438    }
1439
1440    fn udiv_comparison_operands<'a>(
1441        op: SymCmpOp,
1442        left: &'a SymExpr,
1443        right: &'a SymExpr,
1444    ) -> Option<(&'a SymExpr, &'a SymExpr, &'a SymExpr, bool)> {
1445        if !matches!(op, SymCmpOp::Ult | SymCmpOp::Ule) {
1446            return None;
1447        }
1448        if let Some((numerator, denominator)) = left.udiv_operands()
1449            && denominator.as_const().is_some_and(|value| !value.is_zero())
1450            && !right.contains_udiv()
1451        {
1452            return Some((numerator, denominator, right, true));
1453        }
1454        if let Some((numerator, denominator)) = right.udiv_operands()
1455            && denominator.as_const().is_some_and(|value| !value.is_zero())
1456            && !left.contains_udiv()
1457        {
1458            return Some((numerator, denominator, left, false));
1459        }
1460        None
1461    }
1462
1463    fn normalize_udiv_comparison(
1464        &self,
1465        cx: &mut SymCx,
1466        op: SymCmpOp,
1467        left: &SymExpr,
1468        right: &SymExpr,
1469    ) -> Option<SymBoolExpr> {
1470        let (numerator, denominator, threshold, quotient_on_left) =
1471            Self::udiv_comparison_operands(op, left, right)?;
1472        let increment_threshold =
1473            matches!((op, quotient_on_left), (SymCmpOp::Ule, true) | (SymCmpOp::Ult, false));
1474        let threshold = if increment_threshold {
1475            // Prove the successor cannot wrap before constructing the word addition.
1476            self.interval(threshold)?.max.checked_add(U256::ONE)?;
1477            let one = SymExpr::one(cx);
1478            SymExpr::binop(cx, SymBinOp::Add, threshold.clone(), one)
1479        } else {
1480            threshold.clone()
1481        };
1482        if !self.mul_cannot_overflow_256(&threshold, denominator) {
1483            return None;
1484        }
1485
1486        let scaled_threshold = SymExpr::binop(cx, SymBinOp::Mul, threshold, denominator.clone());
1487        Some(if quotient_on_left {
1488            // `n / d < k => n < k * d`; `n / d <= k => n < (k + 1) * d`.
1489            SymBoolExpr::cmp_word_expr(cx, SymCmpOp::Ult, numerator, scaled_threshold)
1490        } else {
1491            // `k <= n / d => k * d <= n`; `k < n / d => (k + 1) * d <= n`.
1492            SymBoolExpr::cmp(cx, SymCmpOp::Ule, scaled_threshold, numerator.clone())
1493        })
1494    }
1495
1496    /// Returns the inclusive unsigned range the context proves for `expr`.
1497    pub(super) fn word_range(&self, expr: &SymExpr) -> Option<(U256, U256)> {
1498        self.interval(expr).map(|interval| (interval.min, interval.max))
1499    }
1500
1501    /// Returns the words that another conjunct asserts `small` is at most, including strict `<`.
1502    fn asserted_upper_bounds(&self, small: &SymExpr) -> &[SymExpr] {
1503        self.order_facts.get(small).map_or(&[], Vec::as_slice)
1504    }
1505
1506    fn interval(&self, expr: &SymExpr) -> Option<WordInterval> {
1507        let mut intervals = HashMap::default();
1508        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
1509        self.interval_cached(expr, &mut intervals, &mut remaining)
1510    }
1511
1512    fn interval_cached(
1513        &self,
1514        expr: &SymExpr,
1515        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
1516        remaining: &mut usize,
1517    ) -> Option<WordInterval> {
1518        if let Some(interval) = intervals.get(expr) {
1519            return *interval;
1520        }
1521
1522        let lower = self.lower_bounds.get(expr).copied();
1523        let upper = self.upper_bounds.get(expr).copied();
1524        let explicit_bounds = || {
1525            if lower.is_none() && upper.is_none() {
1526                return None;
1527            }
1528            WordInterval::new(lower.unwrap_or(U256::ZERO), upper.unwrap_or(U256::MAX))
1529        };
1530        if *remaining == 0 {
1531            let interval = explicit_bounds();
1532            intervals.insert(expr.clone(), interval);
1533            return interval;
1534        }
1535        *remaining -= 1;
1536
1537        let interval =
1538            self.structural_interval(expr, intervals, remaining).or_else(explicit_bounds);
1539        let interval = interval.and_then(|interval| interval.with_bounds(lower, upper));
1540        intervals.insert(expr.clone(), interval);
1541        interval
1542    }
1543
1544    fn structural_interval(
1545        &self,
1546        expr: &SymExpr,
1547        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
1548        remaining: &mut usize,
1549    ) -> Option<WordInterval> {
1550        match expr.kind() {
1551            SymExprKind::Const(value) => Some(WordInterval::exact(*value)),
1552            // `~x == MAX - x`, which reverses unsigned order.
1553            SymExprKind::Not(value) => {
1554                let value = self.interval_cached(value, intervals, remaining)?;
1555                Some(WordInterval { min: !value.max, max: !value.min })
1556            }
1557            SymExprKind::BinOp(SymBinOp::And, value, mask) => {
1558                let mask = mask.as_const()?;
1559                // `x & mask <= min(x, mask)`.
1560                let max = self
1561                    .interval_cached(value, intervals, remaining)
1562                    .map_or(mask, |value| value.max.min(mask));
1563                Some(WordInterval { min: U256::ZERO, max })
1564            }
1565            SymExprKind::BinOp(SymBinOp::Add, left, right) => {
1566                let left = self.interval_cached(left, intervals, remaining)?;
1567                let right = self.interval_cached(right, intervals, remaining)?;
1568                Some(WordInterval {
1569                    min: left.min.checked_add(right.min)?,
1570                    max: left.max.checked_add(right.max)?,
1571                })
1572            }
1573            SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) => {
1574                if let Some(interval) =
1575                    self.rounding_error_interval(minuend, subtrahend, intervals, remaining)
1576                {
1577                    return Some(interval);
1578                }
1579                let left = self.interval_cached(minuend, intervals, remaining)?;
1580                let right = self.interval_cached(subtrahend, intervals, remaining)?;
1581                if left.max < right.min {
1582                    // Every subtraction wraps exactly once, so the unsigned image is contiguous.
1583                    return Some(WordInterval {
1584                        min: left.min.wrapping_sub(right.max),
1585                        max: left.max.wrapping_sub(right.min),
1586                    });
1587                }
1588                if left.min < right.max {
1589                    // An asserted `subtrahend <= minuend` rules out wrapping.
1590                    return self
1591                        .asserted_upper_bounds(subtrahend)
1592                        .contains(minuend)
1593                        .then(|| WordInterval { min: U256::ZERO, max: left.max - right.min });
1594                }
1595                Some(WordInterval {
1596                    min: left.min.checked_sub(right.max)?,
1597                    max: left.max.checked_sub(right.min)?,
1598                })
1599            }
1600            SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
1601                let guarded = self.has_non_wrapping_product(left, right);
1602                let left = self.interval_cached(left, intervals, remaining)?;
1603                let right = self.interval_cached(right, intervals, remaining)?;
1604                Some(WordInterval {
1605                    min: left.min.checked_mul(right.min)?,
1606                    // A retained overflow guard correlates the factors. Their independent
1607                    // maxima can overflow even though every feasible product fits.
1608                    max: left
1609                        .max
1610                        .checked_mul(right.max)
1611                        .or_else(|| guarded.then_some(U256::MAX))?,
1612                })
1613            }
1614            SymExprKind::BinOp(SymBinOp::UDiv, numerator, denominator) => {
1615                // Even an otherwise unbounded numerator is a uint256 word. Division by a
1616                // positive denominator bounds the quotient regardless of numerator wrapping.
1617                let numerator = self
1618                    .interval_cached(numerator, intervals, remaining)
1619                    .unwrap_or(WordInterval { min: U256::ZERO, max: U256::MAX });
1620                let denominator = self.interval_cached(denominator, intervals, remaining)?;
1621                if denominator.min.is_zero() {
1622                    return None;
1623                }
1624                Some(WordInterval {
1625                    min: numerator.min / denominator.max,
1626                    max: numerator.max / denominator.min,
1627                })
1628            }
1629            // `a % d <= a`, and `a % d < d` for a positive `d`.
1630            SymExprKind::BinOp(SymBinOp::URem, dividend, divisor) => {
1631                let dividend = self.interval_cached(dividend, intervals, remaining);
1632                let divisor = self
1633                    .interval_cached(divisor, intervals, remaining)
1634                    .filter(|divisor| !divisor.min.is_zero());
1635                let max = match (dividend, divisor) {
1636                    (Some(dividend), Some(divisor)) => dividend.max.min(divisor.max - U256::ONE),
1637                    (Some(dividend), None) => dividend.max,
1638                    (None, Some(divisor)) => divisor.max - U256::ONE,
1639                    (None, None) => return None,
1640                };
1641                Some(WordInterval { min: U256::ZERO, max })
1642            }
1643            SymExprKind::BinOp(SymBinOp::Shr, value, shift) => {
1644                let shift = shift.as_const()?;
1645                if shift >= U256::from(256) {
1646                    return Some(WordInterval::exact(U256::ZERO));
1647                }
1648                let value = self.interval_cached(value, intervals, remaining)?;
1649                let shift = shift.to::<usize>();
1650                Some(WordInterval { min: value.min >> shift, max: value.max >> shift })
1651            }
1652            SymExprKind::Ite(_, left, right) => {
1653                let left = self.interval_cached(left, intervals, remaining)?;
1654                let right = self.interval_cached(right, intervals, remaining)?;
1655                Some(WordInterval { min: left.min.min(right.min), max: left.max.max(right.max) })
1656            }
1657            _ => None,
1658        }
1659    }
1660}
1661
1662/// The other factor of a `(x * f) / x` quotient: an expression, or the `2**n` of a shift `x << n`.
1663#[derive(Clone, Copy)]
1664pub(super) enum MulDivFactor<'a> {
1665    Expr(&'a SymExpr),
1666    Const(U256),
1667}
1668
1669impl MulDivFactor<'_> {
1670    /// Returns whether the factor is `expected`.
1671    pub(super) fn matches(self, expected: &SymExpr) -> bool {
1672        match self {
1673            Self::Expr(other) => other == expected,
1674            Self::Const(other) => expected.as_const() == Some(other),
1675        }
1676    }
1677}
1678
1679fn const_side_bound<'a>(left: &'a SymExpr, right: &'a SymExpr) -> Option<(&'a SymExpr, U256)> {
1680    right
1681        .as_const()
1682        .map(|value| (left, value))
1683        .or_else(|| left.as_const().map(|value| (right, value)))
1684}
1685
1686/// Normalizes one word expression into an equivalent, solver-friendlier form.
1687pub(crate) fn normalize_expr_for_solver(cx: &mut SymCx, expr: SymExpr) -> SymExpr {
1688    if !expr.contains_ite() {
1689        return expr;
1690    }
1691    // Normalizing an `ite` condition re-normalizes the words inside it, so nested `ite`s would
1692    // otherwise be re-traversed once per enclosing level.
1693    if let Some(normalized) = cx.solver_normalized_word(&expr) {
1694        return normalized;
1695    }
1696    let normalized = expr.fold(cx, &mut normalize_expr_node_for_solver);
1697    cx.record_solver_normalized_word(expr, normalized.clone());
1698    normalized
1699}
1700
1701fn normalize_expr_node_for_solver(cx: &mut SymCx, expr: SymExpr) -> SymExpr {
1702    match expr.kind() {
1703        SymExprKind::Ite(cond, left, right) => {
1704            normalize_ite_expr_for_solver(cx, cond.clone(), left.clone(), right.clone())
1705        }
1706        SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) => {
1707            match mul_high_operands(minuend, subtrahend) {
1708                Some((left, right)) => {
1709                    SymExpr::binop(cx, SymBinOp::MulHigh, left.clone(), right.clone())
1710                }
1711                None => expr,
1712            }
1713        }
1714        _ => expr,
1715    }
1716}
1717
1718fn normalize_ite_expr_for_solver(
1719    cx: &mut SymCx,
1720    cond: SymBoolExpr,
1721    left: SymExpr,
1722    right: SymExpr,
1723) -> SymExpr {
1724    let cond = normalize_bool_for_solver(cx, cond);
1725    if left == right {
1726        // `ite(c, a, a) => a`.
1727        return left;
1728    }
1729    if left.as_const() == Some(U256::ONE)
1730        && right.normalized_bool_word_condition(cx).as_ref() == Some(&cond)
1731    {
1732        // `ite(c, 1, bool_word(c)) => bool_word(c)`.
1733        return right;
1734    }
1735    if right.as_const().is_some_and(|value| value.is_zero())
1736        && left.normalized_bool_word_condition(cx).as_ref() == Some(&cond)
1737    {
1738        // `ite(c, bool_word(c), 0) => bool_word(c)`.
1739        return left;
1740    }
1741    SymExpr::ite(cx, cond, left, right)
1742}
1743
1744impl SymExpr {
1745    fn word_bool_always_true(&self, cx: &mut SymCx) -> bool {
1746        ConstraintContext::default().word_bool_always_true(cx, self)
1747    }
1748}
1749
1750impl SymBoolExpr {
1751    fn normalize_udiv_for_solver(&self, cx: &mut SymCx) -> Option<Self> {
1752        if let SymBoolExprKind::Cmp(op, left, right) = self.kind()
1753            && let Some(normalized) = Self::normalize_const_over_self_udiv_cmp(cx, *op, left, right)
1754        {
1755            return Some(normalized);
1756        }
1757        if let SymBoolExprKind::Not(value) = self.kind()
1758            && let SymBoolExprKind::Cmp(op, left, right) = value.kind()
1759            && let Some(normalized) = Self::normalize_const_over_self_udiv_cmp(cx, *op, left, right)
1760        {
1761            return Some(normalized.not(cx));
1762        }
1763
1764        match self.kind() {
1765            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
1766                if right.as_const().is_some_and(|value| value.is_zero()) =>
1767            {
1768                if let Some(normalized) = left.normalize_bool_selected_eq_zero(cx) {
1769                    return Some(normalized);
1770                }
1771                left.normalized_bool_word_condition(cx).map(|value| value.not(cx)).or_else(|| {
1772                    if left.word_bool_always_true(cx) {
1773                        // `always_true_word == 0 => false`.
1774                        Some(Self::constant(cx, false))
1775                    } else {
1776                        let zero = SymExpr::zero(cx);
1777                        Self::normalize_udiv_eq_zero(cx, left, &zero)
1778                    }
1779                })
1780            }
1781            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
1782                if right.as_const() == Some(U256::ONE) =>
1783            {
1784                // `bool_word(c) == 1 => c`.
1785                left.normalized_bool_word_condition(cx)
1786            }
1787            SymBoolExprKind::Not(value) => match value.kind() {
1788                SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
1789                    if right.as_const().is_some_and(|value| value.is_zero()) =>
1790                {
1791                    if left.word_bool_always_true(cx) {
1792                        // `always_true_word != 0 => true`.
1793                        Some(Self::constant(cx, true))
1794                    } else {
1795                        let zero = SymExpr::zero(cx);
1796                        Self::normalize_udiv_eq_zero(cx, left, &zero).map(|value| value.not(cx))
1797                    }
1798                }
1799                SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => {
1800                    Self::normalize_udiv_eq_zero(cx, left, right).map(|value| value.not(cx))
1801                }
1802                SymBoolExprKind::Cmp(op, left, right) => {
1803                    Self::normalize_add_overflow_cmp(cx, *op, left, right)
1804                        .map(|value| value.not(cx))
1805                        .or_else(|| {
1806                            Self::normalize_udiv_cmp(cx, *op, left, right)
1807                                .map(|value| value.not(cx))
1808                        })
1809                }
1810                _ => None,
1811            },
1812            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => {
1813                Self::normalize_udiv_eq_zero(cx, left, right)
1814            }
1815            SymBoolExprKind::Cmp(op, left, right) => {
1816                Self::normalize_add_overflow_cmp(cx, *op, left, right)
1817                    .or_else(|| Self::normalize_udiv_cmp(cx, *op, left, right))
1818            }
1819            SymBoolExprKind::Const(_) | SymBoolExprKind::And(_) => None,
1820        }
1821    }
1822
1823    fn normalize_add_overflow_cmp(
1824        cx: &mut SymCx,
1825        op: SymCmpOp,
1826        left: &SymExpr,
1827        right: &SymExpr,
1828    ) -> Option<Self> {
1829        if let Some(normalized) = Self::normalize_sub_underflow_cmp(cx, op, left, right) {
1830            return Some(normalized);
1831        }
1832        // Strict forms test overflow and non-strict forms its complement; addition wraps iff the
1833        // increment exceeds `~base`.
1834        let (base, increment, overflow) = match op {
1835            SymCmpOp::Ugt => {
1836                right.add_with_operand(left).map(|(_, increment)| (left, increment, true))
1837            }
1838            SymCmpOp::Ult => {
1839                left.add_with_operand(right).map(|(_, increment)| (right, increment, true))
1840            }
1841            SymCmpOp::Uge => {
1842                left.add_with_operand(right).map(|(_, increment)| (right, increment, false))
1843            }
1844            SymCmpOp::Ule => {
1845                right.add_with_operand(left).map(|(_, increment)| (left, increment, false))
1846            }
1847            SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => None,
1848        }?;
1849        if base.unsigned_bits().max(increment.unsigned_bits()).saturating_add(1) <= 256 {
1850            return Some(Self::constant(cx, !overflow));
1851        }
1852
1853        let limit = match base.kind() {
1854            SymExprKind::BinOp(SymBinOp::Sub, max, value) if max.as_const() == Some(U256::MAX) => {
1855                value.clone()
1856            }
1857            _ => SymExpr::not(cx, base.clone()),
1858        };
1859        Some(if overflow {
1860            Self::cmp(cx, SymCmpOp::Ult, limit, increment.clone())
1861        } else {
1862            Self::cmp_word_expr(cx, SymCmpOp::Ule, increment, limit)
1863        })
1864    }
1865
1866    fn normalize_sub_underflow_cmp(
1867        cx: &mut SymCx,
1868        op: SymCmpOp,
1869        left: &SymExpr,
1870        right: &SymExpr,
1871    ) -> Option<Self> {
1872        let (base, difference, underflow) = match op {
1873            SymCmpOp::Ult => (left, right, true),
1874            SymCmpOp::Ugt => (right, left, true),
1875            SymCmpOp::Ule => (right, left, false),
1876            SymCmpOp::Uge => (left, right, false),
1877            _ => return None,
1878        };
1879        let SymExprKind::BinOp(SymBinOp::Sub, minuend, subtrahend) = difference.kind() else {
1880            return None;
1881        };
1882        if minuend != base {
1883            return None;
1884        }
1885        // Unsigned modular subtraction wraps exactly when the subtrahend exceeds the minuend.
1886        Some(if underflow {
1887            Self::cmp_word_expr(cx, SymCmpOp::Ult, base, subtrahend.clone())
1888        } else {
1889            Self::cmp_word_expr(cx, SymCmpOp::Ule, subtrahend, base.clone())
1890        })
1891    }
1892
1893    fn normalize_udiv_eq_zero(cx: &mut SymCx, left: &SymExpr, right: &SymExpr) -> Option<Self> {
1894        if right.as_const().is_some_and(|value| value.is_zero())
1895            && let Some(condition) = left.normalize_eq_zero_for_solver(cx)
1896        {
1897            // `word_bool(c) == 0 => !c`.
1898            return Some(condition);
1899        }
1900        None
1901    }
1902
1903    fn normalize_udiv_cmp(
1904        cx: &mut SymCx,
1905        op: SymCmpOp,
1906        left: &SymExpr,
1907        right: &SymExpr,
1908    ) -> Option<Self> {
1909        match op {
1910            SymCmpOp::Ugt => match (left.as_const(), right.as_const()) {
1911                // `a > 0 => a != 0`.
1912                (_, Some(value)) if value.is_zero() => left
1913                    .normalize_ne_zero_for_solver(cx)
1914                    .or_else(|| Some(Self::eq_zero(cx, left).not(cx))),
1915                // `1 > a => a == 0`.
1916                (Some(value), _) if value == U256::ONE => right
1917                    .normalize_eq_zero_for_solver(cx)
1918                    .or_else(|| Some(Self::eq_zero(cx, right))),
1919                _ => None,
1920            },
1921            SymCmpOp::Uge => match (left.as_const(), right.as_const()) {
1922                // `a >= 1 => a != 0`.
1923                (_, Some(value)) if value == U256::ONE => left
1924                    .normalize_ne_zero_for_solver(cx)
1925                    .or_else(|| Some(Self::eq_zero(cx, left).not(cx))),
1926                // `0 >= a => a == 0`.
1927                (Some(value), _) if value.is_zero() => right
1928                    .normalize_eq_zero_for_solver(cx)
1929                    .or_else(|| Some(Self::eq_zero(cx, right))),
1930                _ => None,
1931            },
1932            SymCmpOp::Ule => match (left.as_const(), right.as_const()) {
1933                // `a <= 0 => a == 0`.
1934                (_, Some(value)) if value.is_zero() => {
1935                    left.normalize_eq_zero_for_solver(cx).or_else(|| Some(Self::eq_zero(cx, left)))
1936                }
1937                // `1 <= a => a != 0`.
1938                (Some(value), _) if value == U256::ONE => right
1939                    .normalize_ne_zero_for_solver(cx)
1940                    .or_else(|| Some(Self::eq_zero(cx, right).not(cx))),
1941                _ => None,
1942            },
1943            SymCmpOp::Ult => match (left.as_const(), right.as_const()) {
1944                // `a < 1 => a == 0`.
1945                (_, Some(value)) if value == U256::ONE => {
1946                    left.normalize_eq_zero_for_solver(cx).or_else(|| Some(Self::eq_zero(cx, left)))
1947                }
1948                // `0 < a => a != 0`.
1949                (Some(value), _) if value.is_zero() => right
1950                    .normalize_ne_zero_for_solver(cx)
1951                    .or_else(|| Some(Self::eq_zero(cx, right).not(cx))),
1952                _ => None,
1953            },
1954            SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => None,
1955        }
1956    }
1957
1958    fn normalize_const_over_self_udiv_cmp(
1959        cx: &mut SymCx,
1960        op: SymCmpOp,
1961        left: &SymExpr,
1962        right: &SymExpr,
1963    ) -> Option<Self> {
1964        let (value, quotient, complement) = match op {
1965            // `a <= c / a`.
1966            SymCmpOp::Ule => (left, right, false),
1967            // `c / a < a`, the complement of `a <= c / a`.
1968            SymCmpOp::Ult => (right, left, true),
1969            SymCmpOp::Eq | SymCmpOp::Ugt | SymCmpOp::Uge | SymCmpOp::Slt | SymCmpOp::Sgt => {
1970                return None;
1971            }
1972        };
1973        let (numerator, denominator) = match quotient.kind() {
1974            SymExprKind::BinOp(SymBinOp::UDiv, numerator, denominator) => (numerator, denominator),
1975            SymExprKind::Ite(condition, zero, division)
1976                if zero.as_const().is_some_and(|value| value.is_zero()) =>
1977            {
1978                let (numerator, denominator) = division.udiv_operands()?;
1979                if condition.zero_check_operand() != Some(denominator) {
1980                    return None;
1981                }
1982                (numerator, denominator)
1983            }
1984            _ => return None,
1985        };
1986        if denominator != value {
1987            return None;
1988        }
1989
1990        let threshold = numerator.as_const()?.root(2);
1991        let threshold = SymExpr::constant(cx, threshold);
1992        Some(if complement {
1993            Self::cmp(cx, SymCmpOp::Ult, threshold, value.clone())
1994        } else {
1995            Self::cmp_word_expr(cx, SymCmpOp::Ule, value, threshold)
1996        })
1997    }
1998
1999    fn eq_zero(cx: &mut SymCx, expr: &SymExpr) -> Self {
2000        let zero = SymExpr::zero(cx);
2001        Self::eq(cx, expr.clone(), zero)
2002    }
2003}
2004
2005impl SymExpr {
2006    fn normalized_bool_word_condition(&self, cx: &mut SymCx) -> Option<SymBoolExpr> {
2007        self.strip_low_byte_mask()
2008            .bool_word_condition()
2009            .map(|condition| normalize_bool_for_solver(cx, condition))
2010    }
2011
2012    /// Solady's `mul(guard, d) == 0` with the overflow guard `x == 0 || x * y / x == y`:
2013    /// `a * guard(x, y) == 0 => mul_high(x, y) != 0 || a == 0`.
2014    fn normalize_bool_selected_eq_zero(&self, cx: &mut SymCx) -> Option<SymBoolExpr> {
2015        let SymExprKind::BinOp(SymBinOp::Mul, left, right) = self.kind() else { return None };
2016        let (value, (factor, other)) = [(left, right), (right, left)]
2017            .into_iter()
2018            .find_map(|(value, guard)| Some((value, checked_product_guard_operands(guard)?)))?;
2019        let high = Self::binop(cx, SymBinOp::MulHigh, factor.clone(), other.clone());
2020        let overflows = SymBoolExpr::eq_word_const(cx, &high, U256::ZERO).not(cx);
2021        let value = normalize_expr_for_solver(cx, value.clone());
2022        let zero = SymBoolExpr::eq_word_const(cx, &value, U256::ZERO);
2023        Some(SymBoolExpr::or(cx, vec![overflows, zero]))
2024    }
2025
2026    fn add_with_operand<'a>(&'a self, operand: &Self) -> Option<(&'a Self, &'a Self)> {
2027        let SymExprKind::BinOp(SymBinOp::Add, left, right) = self.kind() else {
2028            return None;
2029        };
2030        if left == operand {
2031            Some((left, right))
2032        } else if right == operand {
2033            Some((right, left))
2034        } else {
2035            None
2036        }
2037    }
2038
2039    fn normalize_eq_zero_for_solver(&self, cx: &mut SymCx) -> Option<SymBoolExpr> {
2040        if let Some((numerator, denominator)) = self.udiv_operands() {
2041            // `a / b == 0 => b == 0 || a < b`.
2042            return Some(Self::udiv_zero_condition(cx, numerator, denominator));
2043        }
2044        if let SymExprKind::Ite(condition, then_expr, else_expr) = self.kind() {
2045            let then_zero = then_expr.normalize_eq_zero_for_solver(cx).unwrap_or_else(|| {
2046                let then_expr = normalize_expr_for_solver(cx, then_expr.clone());
2047                let zero = Self::zero(cx);
2048                SymBoolExpr::eq(cx, then_expr, zero)
2049            });
2050            let else_zero = else_expr.normalize_eq_zero_for_solver(cx).unwrap_or_else(|| {
2051                let else_expr = normalize_expr_for_solver(cx, else_expr.clone());
2052                let zero = Self::zero(cx);
2053                SymBoolExpr::eq(cx, else_expr, zero)
2054            });
2055            if then_zero.contains_udiv() || else_zero.contains_udiv() {
2056                return None;
2057            }
2058            // `ite(c, a, b) == 0 => (c && a == 0) || (!c && b == 0)`.
2059            let condition = normalize_bool_for_solver(cx, condition.clone());
2060            let then_condition = SymBoolExpr::and(cx, vec![condition.clone(), then_zero]);
2061            let not_condition = condition.not(cx);
2062            let else_condition = SymBoolExpr::and(cx, vec![not_condition, else_zero]);
2063            return Some(SymBoolExpr::or(cx, vec![then_condition, else_condition]));
2064        }
2065        None
2066    }
2067
2068    fn normalize_ne_zero_for_solver(&self, cx: &mut SymCx) -> Option<SymBoolExpr> {
2069        if let Some((numerator, denominator)) = self.udiv_operands() {
2070            // `a / b != 0 => b != 0 && a >= b`.
2071            return Some(Self::udiv_nonzero_condition(cx, numerator, denominator));
2072        }
2073        if let SymExprKind::Ite(condition, then_expr, else_expr) = self.kind() {
2074            let then_nonzero = then_expr.normalize_ne_zero_for_solver(cx).unwrap_or_else(|| {
2075                let then_expr = normalize_expr_for_solver(cx, then_expr.clone());
2076                let zero = Self::zero(cx);
2077                SymBoolExpr::eq(cx, then_expr, zero).not(cx)
2078            });
2079            let else_nonzero = else_expr.normalize_ne_zero_for_solver(cx).unwrap_or_else(|| {
2080                let else_expr = normalize_expr_for_solver(cx, else_expr.clone());
2081                let zero = Self::zero(cx);
2082                SymBoolExpr::eq(cx, else_expr, zero).not(cx)
2083            });
2084            if then_nonzero.contains_udiv() || else_nonzero.contains_udiv() {
2085                return None;
2086            }
2087            // `ite(c, a, b) != 0 => (c && a != 0) || (!c && b != 0)`.
2088            let condition = normalize_bool_for_solver(cx, condition.clone());
2089            let then_condition = SymBoolExpr::and(cx, vec![condition.clone(), then_nonzero]);
2090            let not_condition = condition.not(cx);
2091            let else_condition = SymBoolExpr::and(cx, vec![not_condition, else_nonzero]);
2092            return Some(SymBoolExpr::or(cx, vec![then_condition, else_condition]));
2093        }
2094        None
2095    }
2096
2097    fn udiv_zero_condition(cx: &mut SymCx, numerator: &Self, denominator: &Self) -> SymBoolExpr {
2098        let numerator = normalize_expr_for_solver(cx, numerator.clone());
2099        let denominator = normalize_expr_for_solver(cx, denominator.clone());
2100        let zero = Self::zero(cx);
2101        let denominator_zero = SymBoolExpr::eq(cx, denominator.clone(), zero);
2102        let below_denominator = SymBoolExpr::cmp(cx, SymCmpOp::Ult, numerator, denominator);
2103        SymBoolExpr::or(cx, vec![denominator_zero, below_denominator])
2104    }
2105
2106    fn udiv_nonzero_condition(cx: &mut SymCx, numerator: &Self, denominator: &Self) -> SymBoolExpr {
2107        let numerator = normalize_expr_for_solver(cx, numerator.clone());
2108        let denominator = normalize_expr_for_solver(cx, denominator.clone());
2109        let zero = Self::zero(cx);
2110        let denominator_nonzero = SymBoolExpr::eq(cx, denominator.clone(), zero).not(cx);
2111        let at_least_denominator = SymBoolExpr::cmp(cx, SymCmpOp::Uge, numerator, denominator);
2112        SymBoolExpr::and(cx, vec![denominator_nonzero, at_least_denominator])
2113    }
2114}
2115
2116impl ConstraintContext {
2117    fn word_bool_always_true(&self, cx: &mut SymCx, expr: &SymExpr) -> bool {
2118        let mut terms = Vec::new();
2119        expr.push_or_terms(&mut terms);
2120        if terms.len() <= 1 {
2121            return false;
2122        }
2123
2124        let bool_terms = terms
2125            .iter()
2126            .filter_map(|term| term.normalized_bool_word_condition(cx))
2127            .collect::<Vec<_>>();
2128        if bool_terms.iter().any(|term| {
2129            let negated = term.clone().not(cx);
2130            bool_terms.contains(&negated)
2131        }) {
2132            // `c || !c => true`.
2133            return true;
2134        }
2135        for zero_term in &bool_terms {
2136            if bool_terms
2137                .iter()
2138                .any(|term| self.checked_mul_guard_for_zero_condition(term, zero_term))
2139            {
2140                // `a == 0 || guarded_mul_div(a) => true`.
2141                return true;
2142            }
2143        }
2144        false
2145    }
2146
2147    /// Records operand facts from independently justified, non-wrapping scaled zero checks.
2148    fn record_scaled_zero_fact(&mut self, cx: &mut SymCx, constraint: &SymBoolExpr) {
2149        let (condition, nonzero) = match constraint.kind() {
2150            SymBoolExprKind::Not(inner) => (inner, true),
2151            _ => (constraint, false),
2152        };
2153        if matches!(condition.kind(), SymBoolExprKind::Cmp(SymCmpOp::Ult, _, _))
2154            && let Some(value) = self.bounded_zero_check_operand(condition).cloned()
2155        {
2156            if nonzero {
2157                self.record_lower_bound(value, U256::ONE);
2158            } else {
2159                self.record_upper_bound(value.clone(), U256::ZERO);
2160                let zero = SymExpr::zero(cx);
2161                let exact = SymBoolExpr::eq(cx, value, zero);
2162                self.record_exact_value_constraint(&exact);
2163            }
2164        }
2165    }
2166
2167    /// Recognizes zero checks exposed by normalizing a scaled balance division.
2168    fn bounded_zero_check_operand<'a>(&self, expr: &'a SymBoolExpr) -> Option<&'a SymExpr> {
2169        if let Some(value) = expr.zero_check_operand() {
2170            return Some(value);
2171        }
2172        let SymBoolExprKind::Cmp(SymCmpOp::Ult, product, limit) = expr.kind() else {
2173            return None;
2174        };
2175        let (value, scale) = Self::constant_mul_operands(product)?;
2176        // x * scale < scale iff x == 0, but only for a positive scale and no wrap.
2177        if scale.is_zero() || limit.as_const() != Some(scale) {
2178            return None;
2179        }
2180        self.max_scaled_product(value, scale)?;
2181        Some(value)
2182    }
2183
2184    /// Checks a zero predicate against the actual divisor of a multiplication guard.
2185    fn zero_check_for_operand(&self, condition: &SymBoolExpr, operand: &SymExpr) -> bool {
2186        if self.bounded_zero_check_operand(condition) == Some(operand) {
2187            return true;
2188        }
2189        // For a positive constant d, n / d == 0 iff n < d. Normalization
2190        // exposes this comparison before the Solidity multiplication guard.
2191        if let Some((numerator, denominator)) = operand.udiv_operands()
2192            && denominator.as_const().is_some_and(|d| !d.is_zero())
2193            && let SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) = condition.kind()
2194        {
2195            return left == numerator && right == denominator;
2196        }
2197        // For a symbolic d, normalization rewrites the zero check of EVM's `div(n, d)` to
2198        // `d == 0 || n < d`, possibly with repeated terms.
2199        if let Some((numerator, denominator)) = word_division_operands(operand) {
2200            return Self::zero_or_condition(condition, denominator, |term| {
2201                matches!(
2202                    term.kind(),
2203                    SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right)
2204                        if left == numerator && right == denominator
2205                )
2206            });
2207        }
2208        // EVM's `mod(n, d)` keeps `n % d == 0` in its zero check `d == 0 || n % d == 0`. SMT
2209        // `bvurem(n, 0)` is `n` but EVM `mod(n, 0)` is 0, so this needs a proven nonzero `d`; a
2210        // bare `URem` only appears once normalization dropped `ite(d == 0, 0, ..)` under that fact.
2211        if let SymExprKind::BinOp(SymBinOp::URem, _, divisor) = operand.kind()
2212            && self.interval(divisor).is_some_and(|range| !range.min.is_zero())
2213        {
2214            return Self::zero_or_condition(condition, divisor, |term| {
2215                term.zero_check_operand() == Some(operand)
2216            });
2217        }
2218        false
2219    }
2220
2221    /// Returns whether `condition` is exactly `divisor == 0 || other`, possibly with repeated
2222    /// terms.
2223    fn zero_or_condition(
2224        condition: &SymBoolExpr,
2225        divisor: &SymExpr,
2226        other: impl Fn(&SymBoolExpr) -> bool,
2227    ) -> bool {
2228        if let SymBoolExprKind::Not(negated) = condition.kind()
2229            && let SymBoolExprKind::And(terms) = negated.kind()
2230        {
2231            let (mut zero, mut matched) = (false, false);
2232            for term in terms.iter() {
2233                let SymBoolExprKind::Not(term) = term.kind() else { return false };
2234                if term.zero_check_operand() == Some(divisor) {
2235                    zero = true;
2236                } else if other(term) {
2237                    matched = true;
2238                } else {
2239                    return false;
2240                }
2241            }
2242            return zero && matched;
2243        }
2244        false
2245    }
2246
2247    fn checked_mul_guard_for_zero_condition(
2248        &self,
2249        expr: &SymBoolExpr,
2250        zero_condition: &SymBoolExpr,
2251    ) -> bool {
2252        let SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) = expr.kind() else {
2253            return false;
2254        };
2255        [(left, right), (right, left)].into_iter().any(|(quotient, expected)| {
2256            matches!(quotient.kind(), SymExprKind::Ite(_, _, _))
2257                && self
2258                    .checked_quotient_factors(quotient, expected, Some(zero_condition))
2259                    .is_some_and(|(left, right)| self.mul_cannot_overflow_256(left, right))
2260        })
2261    }
2262
2263    /// Matches the quotient side shared by multiplication guard proofs and retained guard facts.
2264    fn checked_quotient_factors<'a>(
2265        &self,
2266        quotient: &'a SymExpr,
2267        expected: &'a SymExpr,
2268        zero_condition: Option<&SymBoolExpr>,
2269    ) -> Option<(&'a SymExpr, &'a SymExpr)> {
2270        let (quotient, branch_condition) =
2271            if let SymExprKind::Ite(condition, zero, quotient) = quotient.kind() {
2272                if zero.as_const() != Some(U256::ZERO) || zero_condition.is_none() {
2273                    return None;
2274                }
2275                (quotient, Some(condition))
2276            } else {
2277                (quotient, None)
2278            };
2279        let (divisor, other) = Self::mul_div_identity_operands(quotient, expected)?;
2280        (zero_condition.is_none_or(|condition| self.zero_check_for_operand(condition, divisor))
2281            && branch_condition
2282                .is_none_or(|condition| self.zero_check_for_operand(condition, divisor)))
2283        .then_some((divisor, other))
2284    }
2285
2286    /// Learns multiplication safety from a retained successful overflow guard.
2287    fn record_non_wrapping_product(&mut self, cx: &mut SymCx, constraint: &SymBoolExpr) -> bool {
2288        let fact = bitwise_bool_word_fact(cx, constraint).unwrap_or_else(|| constraint.clone());
2289        let factors = if let Some(factors) = self.checked_product_factors(&fact, None) {
2290            Some(factors)
2291        } else if let Some(factors) = Self::division_guard_factors(&fact) {
2292            Some(factors)
2293        } else if let SymBoolExprKind::Not(inner) = fact.kind()
2294            && let SymBoolExprKind::And(terms) = inner.kind()
2295            && terms.len() == 2
2296        {
2297            // Only the exact two-way disjunction is a multiplication guard. An additional
2298            // alternative would let this predicate hold even when the product wraps.
2299            let first = terms[0].clone().not(cx);
2300            let second = terms[1].clone().not(cx);
2301            self.checked_product_factors(&second, Some(&first))
2302                .or_else(|| self.checked_product_factors(&first, Some(&second)))
2303                .or_else(|| {
2304                    // `y == 0 || x <= MAX / y`, as in Solmate's `mulDivDown`.
2305                    [(&first, &second), (&second, &first)].into_iter().find_map(|(guard, zero)| {
2306                        let (value, factor) = Self::division_guard_factors(guard)?;
2307                        (self.bounded_zero_check_operand(zero) == Some(&factor))
2308                            .then_some((value, factor))
2309                    })
2310                })
2311        } else {
2312            None
2313        };
2314        if let Some((left, right)) = factors {
2315            // A successful product fits in one word. A positive lower bound on either
2316            // factor therefore bounds the other, even if it started as a full-width word.
2317            // The supporting guard remains in the conjunction; it cannot prove itself.
2318            let mut changed = false;
2319            for (value, factor) in [(&left, &right), (&right, &left)] {
2320                if let Some(range) = self.interval(factor)
2321                    && !range.min.is_zero()
2322                {
2323                    changed |= self.record_upper_bound(value.clone(), U256::MAX / range.min);
2324                }
2325            }
2326            self.non_wrapping_products.insert((left, right)) || changed
2327        } else {
2328            false
2329        }
2330    }
2331
2332    /// Returns `(x, y)` for `x <= n / y` with any numerator, as in `x <= MAX / y`, since then
2333    /// `x * y <= (n / y) * y <= n`. The product is zero when `y == 0`, and an EVM division that
2334    /// yields zero only forces `x == 0`.
2335    fn division_guard_factors(predicate: &SymBoolExpr) -> Option<(SymExpr, SymExpr)> {
2336        let SymBoolExprKind::Not(inner) = predicate.kind() else { return None };
2337        let SymBoolExprKind::Cmp(SymCmpOp::Ult, bound, value) = inner.kind() else { return None };
2338        let (_, factor) = word_division_operands(bound)?;
2339        Some((value.clone(), factor.clone()))
2340    }
2341
2342    fn checked_product_factors(
2343        &self,
2344        predicate: &SymBoolExpr,
2345        zero_condition: Option<&SymBoolExpr>,
2346    ) -> Option<(SymExpr, SymExpr)> {
2347        let SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) = predicate.kind() else {
2348            return None;
2349        };
2350        for (quotient, expected) in [(left, right), (right, left)] {
2351            if let Some((divisor, other)) =
2352                self.checked_quotient_factors(quotient, expected, zero_condition)
2353            {
2354                // For divisor > 0, (divisor * other mod 2^256) / divisor == other
2355                // implies the true product fits. For divisor == 0 the product is zero.
2356                return Some((divisor.clone(), other.clone()));
2357            }
2358        }
2359        None
2360    }
2361
2362    fn has_non_wrapping_product(&self, left: &SymExpr, right: &SymExpr) -> bool {
2363        self.non_wrapping_products.contains(&(left.clone(), right.clone()))
2364            || self.non_wrapping_products.contains(&(right.clone(), left.clone()))
2365    }
2366
2367    pub(super) fn mul_cannot_overflow_256(&self, left: &SymExpr, right: &SymExpr) -> bool {
2368        // `(a / d) * d <= a`, and the product is zero when `d == 0`, so it never wraps.
2369        if self.has_non_wrapping_product(left, right)
2370            || rounded_product_operands(left, right).is_some()
2371        {
2372            return true;
2373        }
2374        let mut intervals = HashMap::default();
2375        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
2376        if self
2377            .interval_cached(left, &mut intervals, &mut remaining)
2378            .zip(self.interval_cached(right, &mut intervals, &mut remaining))
2379            .is_some_and(|(left, right)| left.max.checked_mul(right.max).is_some())
2380        {
2381            return true;
2382        }
2383
2384        let mut bit_widths = HashMap::default();
2385        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
2386        self.unsigned_bits_cached(left, &mut bit_widths, &mut remaining)
2387            .zip(self.unsigned_bits_cached(right, &mut bit_widths, &mut remaining))
2388            .is_some_and(|(left, right)| left.saturating_add(right) <= 256)
2389    }
2390
2391    pub(super) fn unsigned_bits(&self, expr: &SymExpr) -> usize {
2392        let mut bit_widths = HashMap::default();
2393        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
2394        self.unsigned_bits_cached(expr, &mut bit_widths, &mut remaining).unwrap_or(256)
2395    }
2396
2397    fn unsigned_bits_cached(
2398        &self,
2399        expr: &SymExpr,
2400        bit_widths: &mut HashMap<SymExpr, usize>,
2401        remaining: &mut usize,
2402    ) -> Option<usize> {
2403        if let Some(bits) = bit_widths.get(expr) {
2404            return Some(*bits);
2405        }
2406        if *remaining == 0 {
2407            return None;
2408        }
2409        *remaining -= 1;
2410
2411        let bits = match expr.kind() {
2412            SymExprKind::Const(value) => value.bit_len().max(1),
2413            SymExprKind::Var(_)
2414            | SymExprKind::GasLeft(_)
2415            | SymExprKind::Keccak { .. }
2416            | SymExprKind::Hash { .. }
2417            | SymExprKind::Not(_) => 256,
2418            SymExprKind::BinOp(SymBinOp::And, left, right) => {
2419                if let Some(mask) = right.as_const() {
2420                    self.unsigned_bits_cached(left, bit_widths, remaining)?.min(mask.bit_len())
2421                } else {
2422                    256
2423                }
2424            }
2425            SymExprKind::BinOp(SymBinOp::Add, left, right) => self
2426                .unsigned_bits_cached(left, bit_widths, remaining)?
2427                .max(self.unsigned_bits_cached(right, bit_widths, remaining)?)
2428                .saturating_add(1)
2429                .min(256),
2430            SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
2431                match rounded_product_operands(left, right) {
2432                    // `(a / d) * d <= a`, so the rounded product fits the dividend.
2433                    Some((dividend, _)) => {
2434                        self.unsigned_bits_cached(dividend, bit_widths, remaining)?
2435                    }
2436                    None => self
2437                        .unsigned_bits_cached(left, bit_widths, remaining)?
2438                        .saturating_add(self.unsigned_bits_cached(right, bit_widths, remaining)?)
2439                        .min(256),
2440                }
2441            }
2442            SymExprKind::BinOp(SymBinOp::UDiv, left, _) => {
2443                self.unsigned_bits_cached(left, bit_widths, remaining)?
2444            }
2445            // `a % d <= a`, and `a % d < d` for a nonzero constant `d`.
2446            SymExprKind::BinOp(SymBinOp::URem, left, right) => {
2447                let bits = self.unsigned_bits_cached(left, bit_widths, remaining)?;
2448                match right.as_const() {
2449                    Some(divisor) if !divisor.is_zero() => bits.min(divisor.bit_len()),
2450                    _ => bits,
2451                }
2452            }
2453            SymExprKind::Ite(_, left, right) => self
2454                .unsigned_bits_cached(left, bit_widths, remaining)?
2455                .max(self.unsigned_bits_cached(right, bit_widths, remaining)?),
2456            _ => 256,
2457        };
2458
2459        let bits = self
2460            .upper_bounds
2461            .get(expr)
2462            .copied()
2463            .map(|bound| bits.min(bound.bit_len().max(1)))
2464            .unwrap_or(bits);
2465        bit_widths.insert(expr.clone(), bits);
2466        Some(bits)
2467    }
2468}