1use super::{
7 ConstraintContext, HashMap, MAX_LOCAL_ANALYSIS_NODES, SymBinOp, SymBoolExpr, SymBoolExprKind,
8 SymCmpOp, SymExpr, SymExprKind, U256, WordInterval, euclidean_sum_dividend,
9 word_division_operands,
10};
11
12struct RoundingBounds<'a> {
14 anchor: &'a SymExpr,
15 below: U256,
16 above: U256,
17}
18
19impl ConstraintContext {
20 pub(super) fn rounded_product_operands(expr: &SymExpr) -> Option<(&SymExpr, U256)> {
22 let (quotient, factor) = Self::constant_mul_operands(expr)?;
23 let (dividend, divisor) = quotient.udiv_operands()?;
24 (divisor.as_const() == Some(factor) && !factor.is_zero()).then_some((dividend, factor))
25 }
26
27 fn rounding_bounds<'a>(
31 &self,
32 expr: &'a SymExpr,
33 anchor: Option<&SymExpr>,
34 ) -> Option<RoundingBounds<'a>> {
35 let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
36 self.rounding_bounds_cached(expr, anchor, &mut HashMap::default(), &mut remaining)
37 }
38
39 fn rounding_bounds_cached<'a>(
40 &self,
41 expr: &'a SymExpr,
42 anchor: Option<&SymExpr>,
43 intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
44 remaining: &mut usize,
45 ) -> Option<RoundingBounds<'a>> {
46 let (dividend, divisor) = Self::rounded_product_operands(expr)?;
47 let width = divisor - U256::ONE;
50 let raw = RoundingBounds { anchor: dividend, below: width, above: U256::ZERO };
51 if anchor == Some(dividend) {
52 return Some(raw);
53 }
54 let offset = match dividend.kind() {
55 SymExprKind::BinOp(SymBinOp::Add, anchor, bias)
56 if let Some(bias) = bias.as_const()
57 && bias <= width =>
58 {
59 Some((anchor, bias, bias))
60 }
61 SymExprKind::BinOp(SymBinOp::Sub, sum, one)
62 if one.as_const() == Some(U256::ONE)
63 && let SymExprKind::BinOp(SymBinOp::Add, anchor, bias) = sum.kind()
64 && bias.as_const() == Some(divisor) =>
65 {
66 Some((anchor, width, divisor))
68 }
69 _ => None,
70 };
71 if let Some((anchor, bias, addition)) = offset
72 && self
73 .interval_cached(anchor, intervals, remaining)
74 .is_some_and(|range| range.max.checked_add(addition).is_some())
75 {
76 return Some(RoundingBounds { anchor, below: width - bias, above: bias });
78 }
79 Some(raw)
82 }
83
84 pub(super) fn quotient_of_rounded_product<'a>(&self, expr: &'a SymExpr) -> Option<&'a SymExpr> {
86 let (numerator, divisor) = expr.udiv_operands()?;
87 let bounds = self.rounding_bounds(numerator, None)?;
88 let minimum =
89 divisor.as_const().or_else(|| self.unsigned_lower_bounds.get(divisor).copied())?;
90 if !bounds.below.is_zero() || bounds.above >= minimum {
91 return None;
92 }
93 let SymExprKind::BinOp(SymBinOp::Mul, left, right) = bounds.anchor.kind() else {
94 return None;
95 };
96 let value = if left == divisor {
97 right
98 } else if right == divisor {
99 left
100 } else {
101 return None;
102 };
103 self.mul_cannot_overflow_256(value, divisor).then_some(value)
106 }
107
108 pub(super) fn rounding_comparison_value(&self, expr: &SymBoolExpr) -> Option<bool> {
109 if let SymBoolExprKind::Not(inner) = expr.kind() {
110 return self.rounding_comparison_value(inner).map(|value| !value);
111 }
112 let SymBoolExprKind::Cmp(op, left, right) = expr.kind() else { return None };
113 for (rounded, anchor, op) in [
114 (left, right, *op),
115 (
116 right,
117 left,
118 match op {
119 SymCmpOp::Ult => SymCmpOp::Ugt,
120 SymCmpOp::Ule => SymCmpOp::Uge,
121 SymCmpOp::Ugt => SymCmpOp::Ult,
122 SymCmpOp::Uge => SymCmpOp::Ule,
123 other => *other,
124 },
125 ),
126 ] {
127 if let Some(bounds) = self.rounding_bounds(rounded, Some(anchor))
128 && bounds.anchor == anchor
129 {
130 match op {
131 SymCmpOp::Uge if bounds.below.is_zero() => return Some(true),
132 SymCmpOp::Ult if bounds.below.is_zero() => return Some(false),
133 SymCmpOp::Ule if bounds.above.is_zero() => return Some(true),
134 SymCmpOp::Ugt if bounds.above.is_zero() => return Some(false),
135 _ => {}
136 }
137 }
138 }
139 None
140 }
141
142 pub(super) fn division_comparison_value(&self, expr: &SymBoolExpr) -> Option<bool> {
154 if let SymBoolExprKind::Not(inner) = expr.kind() {
155 return self.division_comparison_value(inner).map(|value| !value);
156 }
157 let SymBoolExprKind::Cmp(op, left, right) = expr.kind() else { return None };
158 let mut intervals = HashMap::default();
159 let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
160 let mut order = |small, large| {
161 self.division_order(small, large, &mut intervals, &mut remaining).or_else(|| {
162 self.asserts_scaled_order(small, large, &mut intervals, &mut remaining)
163 .then_some(false)
164 })
165 };
166 if let Some(strict) = order(left, right) {
167 return match op {
168 SymCmpOp::Ule => Some(true),
169 SymCmpOp::Ugt => Some(false),
170 SymCmpOp::Ult if strict => Some(true),
171 SymCmpOp::Uge if strict => Some(false),
172 _ => None,
173 };
174 }
175 if let Some(strict) = order(right, left) {
176 return match op {
177 SymCmpOp::Uge => Some(true),
178 SymCmpOp::Ult => Some(false),
179 SymCmpOp::Ugt if strict => Some(true),
180 SymCmpOp::Ule if strict => Some(false),
181 _ => None,
182 };
183 }
184 None
185 }
186
187 fn division_order(
192 &self,
193 small: &SymExpr,
194 large: &SymExpr,
195 intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
196 remaining: &mut usize,
197 ) -> Option<bool> {
198 if let SymExprKind::Not(base) = large.kind()
202 && (euclidean_sum_dividend(base, small).is_some()
203 || self.shares_whole(base, small, None, intervals, remaining).is_some())
204 {
205 return Some(false);
206 }
207 if let SymExprKind::BinOp(SymBinOp::Add, first, second) = small.kind()
209 && self.shares_whole(first, second, Some(large), intervals, remaining).is_some()
210 {
211 return Some(false);
212 }
213 let mut interval = |expr: &SymExpr| self.interval_cached(expr, intervals, remaining);
214 let nonzero = |range: Option<WordInterval>| range.is_some_and(|range| !range.min.is_zero());
215 match small.kind() {
216 SymExprKind::BinOp(SymBinOp::URem, dividend, divisor) => {
217 if dividend == large {
218 return Some(false);
219 }
220 (divisor == large && nonzero(interval(divisor))).then_some(true)
221 }
222 SymExprKind::BinOp(SymBinOp::UDiv, dividend, divisor) => {
223 if dividend == large {
224 return nonzero(interval(divisor)).then_some(false);
225 }
226 let ceiling = match large.kind() {
230 SymExprKind::Ite(condition, value, zero)
232 if zero.as_const() == Some(U256::ZERO)
233 && let SymBoolExprKind::Not(inner) = condition.kind()
234 && inner.zero_check_operand() == Some(dividend) =>
235 {
236 value
237 }
238 _ => large,
239 };
240 if let SymExprKind::BinOp(SymBinOp::Add, quotient, increment) = ceiling.kind()
241 && increment.as_const() == Some(U256::ONE)
242 && let Some((predecessor, other)) = quotient.udiv_operands()
243 && other == divisor
244 && let SymExprKind::BinOp(SymBinOp::Sub, value, decrement) = predecessor.kind()
245 && decrement.as_const() == Some(U256::ONE)
246 && value == dividend
247 {
248 return nonzero(interval(divisor)).then_some(false);
249 }
250 if let SymExprKind::BinOp(SymBinOp::Mul, left, right) = dividend.kind()
254 && let SymExprKind::BinOp(SymBinOp::Add, a, b) = divisor.kind()
255 && let Some(other) = [(left, right), (right, left)]
256 .into_iter()
257 .find_map(|(x, y)| (x == large).then_some(y))
258 && let Some(rest) =
259 [(a, b), (b, a)].into_iter().find_map(|(y, z)| (y == other).then_some(z))
260 && let Some(other) = interval(other)
261 && let Some(rest) = interval(rest)
262 && other.max.checked_add(rest.max).is_some()
263 && nonzero(interval(divisor))
264 {
265 return Some(nonzero(interval(large)) && !rest.min.is_zero());
266 }
267 let mut bounded = |dividend: &SymExpr, addend: Option<&SymExpr>| {
270 let SymExprKind::BinOp(SymBinOp::Mul, left, right) = dividend.kind() else {
271 return false;
272 };
273 let other = if left == large {
274 right
275 } else if right == large {
276 left
277 } else {
278 return false;
279 };
280 let Some(range) = interval(divisor).filter(|range| !range.min.is_zero()) else {
281 return false;
282 };
283 addend.is_none_or(|addend| {
284 matches!(addend.kind(), SymExprKind::BinOp(SymBinOp::Sub, value, one)
285 if value == divisor && one.as_const() == Some(U256::ONE))
286 || interval(addend).is_some_and(|addend| addend.max < range.min)
287 }) && (other == divisor
288 || interval(other).is_some_and(|other| other.max <= range.min)
289 || self.asserts_less_or_equal(other, divisor))
290 && self.mul_cannot_overflow_256(left, right)
291 };
292 let peeled = match dividend.kind() {
295 SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
296 [(left, right), (right, left)].into_iter().find_map(|(quotient, factor)| {
297 word_division_operands(quotient)
298 .and_then(|(n, t)| (t == factor).then_some(n))
299 })
300 }
301 _ => None,
302 };
303 let rounded_up = match dividend.kind() {
304 SymExprKind::BinOp(SymBinOp::Add, a, b) => [(a, b), (b, a)]
305 .into_iter()
306 .any(|(product, addend)| bounded(product, Some(addend))),
307 SymExprKind::BinOp(SymBinOp::Sub, sum, one)
310 if one.as_const() == Some(U256::ONE)
311 && let SymExprKind::BinOp(SymBinOp::Add, a, b) = sum.kind()
312 && let Some(product) =
313 (a == divisor).then_some(b).or((b == divisor).then_some(a)) =>
314 {
315 bounded(product, None)
316 }
317 _ => false,
318 };
319 (rounded_up
320 || peeled.is_some_and(|peeled| bounded(peeled, None))
321 || bounded(dividend, None))
322 .then_some(false)
323 }
324 SymExprKind::BinOp(SymBinOp::Mul, left, right) => [(left, right), (right, left)]
327 .into_iter()
328 .any(|(quotient, factor)| {
329 quotient.udiv_operands().is_some_and(|(dividend, divisor)| {
330 dividend == large
331 && (factor == divisor
332 || interval(factor)
333 .zip(interval(divisor))
334 .is_some_and(|(factor, divisor)| factor.max <= divisor.min))
335 })
336 })
337 .then_some(false),
338 _ => None,
339 }
340 }
341
342 fn asserts_scaled_order(
348 &self,
349 small: &SymExpr,
350 large: &SymExpr,
351 intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
352 remaining: &mut usize,
353 ) -> bool {
354 let factor = |product: &'_ SymExpr, operand: &SymExpr| match product.kind() {
355 SymExprKind::BinOp(SymBinOp::Mul, left, right) if left == operand => {
356 Some(right.clone())
357 }
358 SymExprKind::BinOp(SymBinOp::Mul, left, right) if right == operand => {
359 Some(left.clone())
360 }
361 _ => None,
362 };
363 self.facts.iter().any(|fact| {
364 let (scaled_small, scaled_large) = match fact.kind() {
365 SymBoolExprKind::Cmp(SymCmpOp::Ult | SymCmpOp::Ule, left, right) => (left, right),
366 SymBoolExprKind::Not(inner) => match inner.kind() {
367 SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) => (right, left),
368 _ => return false,
369 },
370 _ => return false,
371 };
372 let (Some(k), Some(l)) = (factor(scaled_small, small), factor(scaled_large, large))
373 else {
374 return false;
375 };
376 self.interval_cached(&k, intervals, remaining)
377 .zip(self.interval_cached(&l, intervals, remaining))
378 .is_some_and(|(k, l)| !k.min.is_zero() && l.max <= k.min)
379 && self.mul_cannot_overflow_256(small, &k)
380 })
381 }
382
383 fn shares_whole<'a>(
387 &self,
388 first: &'a SymExpr,
389 second: &'a SymExpr,
390 whole: Option<&SymExpr>,
391 intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
392 remaining: &mut usize,
393 ) -> Option<&'a SymExpr> {
394 let (first, divisor) = first.udiv_operands()?;
395 let (second, other_divisor) = second.udiv_operands()?;
396 if divisor != other_divisor {
397 return None;
398 }
399 let (SymExprKind::BinOp(SymBinOp::Mul, w1, a1), SymExprKind::BinOp(SymBinOp::Mul, w2, b2)) =
400 (first.kind(), second.kind())
401 else {
402 return None;
403 };
404 let (found, a, b) =
405 [(w1, a1, w2, b2), (w1, a1, b2, w2), (a1, w1, w2, b2), (a1, w1, b2, w2)]
406 .into_iter()
407 .find_map(|(found, a, other, b)| {
408 (found == other && whole.is_none_or(|whole| whole == found))
409 .then_some((found, a, b))
410 })?;
411 let min = self.interval_cached(divisor, intervals, remaining)?.min;
412 if min.is_zero() {
413 return None;
414 }
415 let asserted = |accept: &dyn Fn(&SymExpr, &SymExpr) -> bool| {
417 self.facts.iter().any(|fact| match fact.kind() {
418 SymBoolExprKind::Cmp(SymCmpOp::Ult | SymCmpOp::Ule, left, right) => {
419 accept(left, right)
420 }
421 SymBoolExprKind::Not(inner) => matches!(
422 inner.kind(),
423 SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) if accept(right, left)
424 ),
425 _ => false,
426 })
427 };
428 let sum_max = self
431 .interval_cached(a, intervals, remaining)
432 .and_then(|a| a.max.checked_add(self.interval_cached(b, intervals, remaining)?.max));
433 let complement =
434 |x: &SymExpr, y: &SymExpr| matches!(y.kind(), SymExprKind::Not(inner) if inner == x);
435 if sum_max.is_none()
436 && !asserted(&|x, y| (x == b && complement(a, y)) || (x == a && complement(b, y)))
437 {
438 return None;
439 }
440 let is_sum = |expr: &SymExpr| {
441 matches!(expr.kind(), SymExprKind::BinOp(SymBinOp::Add, x, y)
442 if (x == a && y == b) || (x == b && y == a))
443 };
444 (sum_max.is_some_and(|max| max <= min)
445 || is_sum(divisor)
446 || asserted(&|x, y| is_sum(x) && y == divisor))
447 .then_some(found)
448 }
449
450 fn asserts_less_or_equal(&self, small: &SymExpr, large: &SymExpr) -> bool {
454 if self.asserted_upper_bounds(small).contains(large) {
455 return true;
456 }
457 let SymExprKind::BinOp(SymBinOp::Sub, end, start) = small.kind() else { return false };
458 self.asserted_upper_bounds(start).contains(end)
459 && self.asserted_upper_bounds(end).iter().any(|sum| {
460 matches!(sum.kind(), SymExprKind::BinOp(SymBinOp::Add, a, b)
461 if (a == large && b == start) || (a == start && b == large))
462 })
463 }
464
465 pub(super) fn rounding_error_interval(
467 &self,
468 left: &SymExpr,
469 right: &SymExpr,
470 intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
471 remaining: &mut usize,
472 ) -> Option<WordInterval> {
473 if let Some(bounds) = self.rounding_bounds_cached(left, Some(right), intervals, remaining)
474 && bounds.anchor == right
475 && bounds.below.is_zero()
476 {
477 return Some(WordInterval { min: U256::ZERO, max: bounds.above });
478 }
479 if let Some(bounds) = self.rounding_bounds_cached(right, Some(left), intervals, remaining)
480 && bounds.anchor == left
481 && bounds.above.is_zero()
482 {
483 return Some(WordInterval { min: U256::ZERO, max: bounds.below });
484 }
485 if self.division_order(right, left, intervals, remaining).is_some()
487 && let Some(left) = self.interval_cached(left, intervals, remaining)
488 {
489 return Some(WordInterval { min: U256::ZERO, max: left.max });
490 }
491 None
492 }
493}