use crate::engine::budget::Counter;
use crate::hash::IdMap;
use super::{Fin, PassKind, Runner, Step, Stop, finish, known, known_words};
use crate::expr::{Context, OpCode};
use crate::facts::known::{bv_and, bv_not, bv_or, low_mask};
use crate::ops::{BinOp, UnOp};
use crate::{BitVec, Width};
const MAX_VISITS: u32 = 256;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct Key(u32, BitVec);
impl core::hash::Hash for Key {
fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
h.write_u32(self.0);
for &l in self.1.limbs() {
h.write_u64(l);
}
}
}
pub(crate) type Memo = IdMap<Key, u32>;
#[derive(Default)]
pub(crate) struct Same {
map: IdMap<Key, (u32, u32)>,
leaves: Vec<u32>,
carried: IdMap<u32, bool>,
first: IdMap<u32, ()>,
marking: bool,
}
impl Same {
pub(crate) fn clear(&mut self) {
self.map.clear();
self.leaves.clear();
self.carried.clear();
self.first.clear();
self.marking = false;
}
}
const FIRST_HEIGHT: u32 = 64;
fn observed(cx: &Context, n: u32) -> Option<(u32, BitVec)> {
let node = cx.node(n);
let w = cx.width_of(n);
match node.op {
OpCode::And | OpCode::Or => match (cx.const_val(node.a), cx.const_val(node.b)) {
(Some(k), None) | (None, Some(k)) => {
let x = if cx.const_val(node.a).is_some() {
node.b
} else {
node.a
};
let m = if node.op == OpCode::And {
k
} else {
bv_not(&k)
};
Some((x, m))
}
_ => None,
},
OpCode::Extract => {
let wa = cx.width_of(node.a);
let lo = BitVec::wrapping_from_u64(wa, u64::from(node.b));
let m = BitVec::bin_unchecked(BinOp::Shl, &low_mask(wa, u32::from(w.bits())), &lo);
Some((node.a, m))
}
OpCode::Shl | OpCode::LShr => cx.const_val(node.b).map(|k| {
let back = if node.op == OpCode::Shl {
BinOp::LShr
} else {
BinOp::Shl
};
(node.a, BitVec::bin_unchecked(back, &BitVec::ones(w), &k))
}),
_ => None,
}
}
pub(crate) fn asks_first(r: &Runner<'_, '_>, cx: &Context, n: u32) -> bool {
cx.meta[n as usize].height >= FIRST_HEIGHT
&& !r.demanded.same.first.contains_key(&n)
&& observed(cx, n).is_some()
}
pub(crate) fn first(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
) -> Result<Option<(u32, Fin)>, Stop> {
r.demanded.same.first.insert(n, ());
r.demanded.same.marking = true;
let out = super::step(r, cx, PassKind::Demanded, n);
r.demanded.same.marking = false;
Ok(match out? {
Step::To(x, fin) => Some((x, fin)),
Step::Normal(_) => None,
})
}
fn sorted_distinct(v: &mut [u32]) -> usize {
v.sort_unstable();
let mut kept = 0;
for i in 0..v.len() {
if kept == 0 || v[i] != v[kept - 1] {
v[kept] = v[i];
kept += 1;
}
}
kept
}
struct Demand {
memo: Memo,
base: Memo,
whole: Option<Vec<(Key, u32)>>,
whole_sums: bool,
cap: u32,
stops: Vec<u32>,
visits: u32,
fin: Fin,
before: u32,
root: u32,
xors: Vec<(u32, BitVec, BitVec, u32)>,
identities: Vec<(Key, u32, u32)>,
union: IdMap<u32, BitVec>,
ties: bool,
}
impl Demand {
fn note(&mut self, key: Key, v: u32) {
self.memo.insert(key, v);
if self.visits <= self.cap
&& let Some(whole) = &mut self.whole
{
whole.push((key, v));
}
}
}
#[cfg_attr(not(feature = "prove"), allow(dead_code))]
fn reads(cx: &Context, x: u32, m: &BitVec, out: &mut Vec<(u32, BitVec)>) {
out.clear();
if m.is_zero() || cx.const_val(x).is_some() {
return;
}
let node = cx.node(x);
let w = m.width();
let konst = |j: u32| cx.const_val(j);
match node.op {
OpCode::And | OpCode::Or | OpCode::Xor => match (konst(node.a), konst(node.b)) {
(Some(k), _) | (_, Some(k)) => {
let a = if konst(node.a).is_some() {
node.b
} else {
node.a
};
match node.op {
OpCode::And if subset(m, &k) => out.push((a, *m)),
OpCode::And => out.push((a, bv_and(m, &k))),
OpCode::Or if bv_and(m, &k).is_zero() => out.push((a, *m)),
OpCode::Or if subset(m, &k) => {}
OpCode::Or => out.push((a, bv_and(m, &bv_not(&k)))),
_ => out.push((a, *m)),
}
}
_ => out.extend([(node.a, *m), (node.b, *m)]),
},
OpCode::Not => out.push((node.a, *m)),
OpCode::Add | OpCode::Sub | OpCode::Mul => {
let p = low_prefix(m);
out.extend([(node.a, p), (node.b, p)]);
}
OpCode::Neg => out.push((node.a, low_prefix(m))),
OpCode::Shl | OpCode::LShr => {
if let Some(k) = konst(node.b) {
let back = if node.op == OpCode::Shl {
BinOp::LShr
} else {
BinOp::Shl
};
out.push((node.a, BitVec::bin_unchecked(back, m, &k)));
}
}
OpCode::Zext => {
if let Ok(ml) = m.trunc(cx.width_of(node.a)) {
out.push((node.a, ml));
}
}
OpCode::Extract => {
let wa = cx.width_of(node.a);
let lo = BitVec::wrapping_from_u64(wa, u64::from(node.b));
if let Ok(ma) = m.zext(wa) {
out.push((node.a, BitVec::bin_unchecked(BinOp::Shl, &ma, &lo)));
}
}
OpCode::Sext => {
let wa = cx.width_of(node.a);
let above = Width::new(w.bits() - wa.bits())
.ok()
.and_then(|d| m.extract(wa.bits(), d).ok());
if let (Ok(ml), Some(above)) = (m.trunc(wa), above) {
let ml = if above.is_zero() {
ml
} else {
let sign = BitVec::bin_unchecked(
BinOp::Shl,
&BitVec::wrapping_from_u64(wa, 1),
&BitVec::wrapping_from_u64(wa, u64::from(wa.bits() - 1)),
);
bv_or(&ml, &sign)
};
out.push((node.a, ml));
}
}
OpCode::Concat => {
let (wh, wl) = (cx.width_of(node.a), cx.width_of(node.b));
if let (Ok(ml), Ok(mh)) = (m.trunc(wl), m.extract(wl.bits(), wh)) {
out.extend([(node.a, mh), (node.b, ml)]);
}
}
_ => {}
}
}
const SUM_CONSTANTS: usize = 8;
fn same_on(
r: &mut Runner<'_, '_>,
cx: &Context,
key: (u32, u8),
kc: u32,
k: &BitVec,
p: &BitVec,
) -> u32 {
let seen = r.demanded.sum_constants.entry(key).or_default();
for &c in seen.iter() {
if let Some(v) = cx.const_val(c)
&& bv_and(&BitVec::bin_unchecked(BinOp::Xor, &v, k), p).is_zero()
{
return c;
}
}
if seen.len() < SUM_CONSTANTS {
seen.push(kc);
}
kc
}
fn low_prefix(m: &BitVec) -> BitVec {
let w = m.width();
let clz = BitVec::apply_un(UnOp::Clz, m)
.ok()
.and_then(|v| v.to_u64())
.unwrap_or(0) as u32;
low_mask(w, u32::from(w.bits()) - clz)
}
fn by_residues(
r: &mut Runner<'_, '_>,
cx: &mut Context,
x: u32,
m: &BitVec,
) -> Result<Option<u32>, Stop> {
let Some(mv) = m.to_u64() else {
return Ok(None);
};
let k = 64 - mv.leading_zeros();
if k == 0
|| k > RESIDUE_BITS
|| !matches!(cx.node(x).op, OpCode::Mul | OpCode::Add | OpCode::Sub)
{
return Ok(None);
}
if !super::residue::may_fold(r, cx, x, k, mv) {
return Ok(None);
}
let Some(t) = super::residue::residues(r, cx, x, k)? else {
return Ok(None);
};
let first = t.values[0] & mv;
let allowed = r.hooks.is_none_or(|h| h.fold_known(cx, cx.handle(x)));
if allowed && t.values.iter().all(|&v| v & mv == first) {
let c = BitVec::wrapping_from_u64(m.width(), first);
return Ok(Some(r.build(cx, |cx| cx.mk_const(&c))?));
}
Ok((0..t.leaves.len())
.find(|&i| {
t.values
.iter()
.enumerate()
.all(|(c, &v)| v & mv == t.leaf(c, i) & mv)
})
.map(|i| t.leaves[i]))
}
const RESIDUE_BITS: u32 = 4;
fn prefix_residue(c: &BitVec, m: &BitVec) -> Option<BitVec> {
let w = c.width();
let k = crate::facts::known::count_ones(m);
if k == 0 || k >= u32::from(w.bits()) || low_prefix(m) != *m {
return None;
}
let kw = Width::new(k as u16).ok()?;
let t = c.trunc(kw).ok()?;
let (u, s) = (t.zext(w).ok()?, t.sext(w).ok()?);
if t.is_zero() || *c == u || *c == s {
return None;
}
let neg = BitVec::un_unchecked(UnOp::Neg, &t);
if t.msb() && BitVec::cmp_unchecked(crate::CmpOp::Ult, &neg, &t) {
Some(s)
} else {
Some(u)
}
}
fn subset(a: &BitVec, b: &BitVec) -> bool {
bv_and(a, &bv_not(b)).is_zero()
}
fn simplify(
r: &mut Runner<'_, '_>,
cx: &mut Context,
st: &mut Demand,
x: u32,
m: &BitVec,
) -> Result<u32, Stop> {
let wide;
let m = match st.union.get(&x) {
Some(u) if subset(m, u) => {
wide = *u;
&wide
}
_ => m,
};
let w = m.width();
if m.is_zero() {
return r.build(cx, |cx| cx.mk_const(&BitVec::zero(w)));
}
if let Some(&v) = st
.memo
.get(&Key(x, *m))
.or_else(|| st.base.get(&Key(x, *m)))
{
return Ok(v);
}
if let Some(&(from, len)) = r.demanded.same.map.get(&Key(x, *m)) {
let (from, len) = (from as usize, len as usize);
st.stops
.extend_from_slice(&r.demanded.same.leaves[from..from + len]);
st.note(Key(x, *m), x);
return Ok(x);
}
let stops0 = st.stops.len() as u32;
st.visits += 1;
r.meter.charge(Counter::PassWork, 1)?;
r.meter.check()?;
let node = cx.node(x);
let stop = |cx: &Context, st: &mut Demand| -> Result<u32, Stop> {
stop_at(cx, st, x);
Ok(x)
};
if let Some(c) = cx.const_val(x)
&& let Some(c2) = prefix_residue(&c, m)
{
let v = r.build(cx, |cx| cx.mk_const(&c2))?;
st.note(Key(x, *m), v);
return Ok(v);
}
if st.visits > st.cap || cx.const_val(x).is_some() {
let v = stop(cx, st)?;
st.note(Key(x, *m), v);
return Ok(v);
}
let (fold, fin) = if w.bits() <= 64 {
let (k, fin) = known_words(r, cx, x)?;
let mw = m.limbs()[0];
let fold = k.map(|[zero, one]| {
((zero | one) & mw == mw).then(|| BitVec::from_canonical_u64(w, one & mw))
});
(fold, fin)
} else {
let (k, fin) = known(r, cx, x)?;
let fold = k.map(|k| {
let known = bv_and(&bv_or(&k.known_zero(), &k.known_one()), m);
(known == *m).then(|| bv_and(&k.known_one(), m))
});
(fold, fin)
};
st.fin = st.fin.and(fin.unchanged());
if let Some(fold) = fold {
let allowed = r.hooks.is_none_or(|h| h.fold_known(cx, cx.handle(x)));
if let Some(v) = fold.filter(|_| allowed) {
st.fin = st.fin.and(fin);
let c = r.build(cx, |cx| cx.mk_const(&v))?;
st.note(Key(x, *m), c);
return Ok(c);
}
}
if let Some(v) = by_residues(r, cx, x, m)? {
if !cx.is_const(v) {
stop_at(cx, st, v);
}
st.note(Key(x, *m), v);
return Ok(v);
}
let bin = |r: &mut Runner<'_, '_>, cx: &mut Context, op: BinOp, a: u32, b: u32| {
r.build(cx, |cx| cx.c_bin(op, a, b))
};
let konst = |cx: &Context, j: u32| cx.const_val(j);
if x == st.root
&& matches!(node.op, OpCode::Add | OpCode::Sub)
&& let Some(v) = merged(r, cx, st, x, m)?
{
st.note(Key(x, *m), v);
return Ok(v);
}
#[cfg(feature = "prove")]
if st.union.contains_key(&x) && carries(cx, x) {
let j = crate::facts::known::count_ones(&low_prefix(m)) as u16;
if j < w.bits()
&& let Some((e, fin, stops, _)) = super::borrows::expanded(r, cx, x, j, false)?
{
st.fin = st.fin.and(fin);
for s in stops {
stop_at(cx, st, s);
}
let v = r.build(cx, |cx| cx.c_zext(e, w.bits()))?;
st.note(Key(x, *m), v);
return Ok(v);
}
}
#[cfg(feature = "prove")]
if node.op == OpCode::Extract
&& node.b > 0
&& let Some(low) = super::casts::live_word(r, cx, node.a)?
{
let (lo, n, below) = (node.b as u16, node.width, cx.wid(low));
let j = crate::facts::known::count_ones(&low_prefix(m)) as u16;
if lo + j <= below && below < lo + n {
stop_at(cx, st, low);
let v = r.build(cx, |cx| {
let e = cx.c_extract(low, lo, j)?;
cx.c_zext(e, n)
})?;
st.note(Key(x, *m), v);
return Ok(v);
}
}
if matches!(node.op, OpCode::Add | OpCode::Sub)
&& let Some(v) = joined(r, cx, st, x, m)?
{
st.note(Key(x, *m), v);
return Ok(v);
}
let v = match node.op {
OpCode::And => match (konst(cx, node.a), konst(cx, node.b)) {
(Some(k), _) | (_, Some(k)) => {
let a = if konst(cx, node.a).is_some() {
node.b
} else {
node.a
};
if subset(m, &k) {
simplify(r, cx, st, a, m)?
} else {
let a2 = simplify(r, cx, st, a, &bv_and(m, &k))?;
let narrow = bv_and(m, &k);
let k = if a2 != a || (narrow != k && read_once(r, cx, x)?) {
narrow
} else {
k
};
let kc = r.build(cx, |cx| cx.mk_const(&k))?;
bin(r, cx, BinOp::And, a2, kc)?
}
}
_ => {
let a = simplify(r, cx, st, node.a, m)?;
let b = simplify(r, cx, st, node.b, m)?;
match (konst(cx, a), konst(cx, b)) {
(Some(k), None) if subset(m, &k) => b,
(None, Some(k)) if subset(m, &k) => a,
(Some(k), None) | (None, Some(k)) if bv_and(m, &k).is_zero() => {
r.build(cx, |cx| cx.mk_const(&BitVec::zero(w)))?
}
_ => bin(r, cx, BinOp::And, a, b)?,
}
}
},
OpCode::Or => match (konst(cx, node.a), konst(cx, node.b)) {
(Some(k), _) | (_, Some(k)) => {
let a = if konst(cx, node.a).is_some() {
node.b
} else {
node.a
};
if bv_and(m, &k).is_zero() {
simplify(r, cx, st, a, m)?
} else if subset(m, &k) {
r.build(cx, |cx| cx.mk_const(&k))?
} else {
let a2 = simplify(r, cx, st, a, &bv_and(m, &bv_not(&k)))?;
let kc = r.build(cx, |cx| cx.mk_const(&k))?;
bin(r, cx, BinOp::Or, a2, kc)?
}
}
_ => {
let a = simplify(r, cx, st, node.a, m)?;
let b = simplify(r, cx, st, node.b, m)?;
match (konst(cx, a), konst(cx, b)) {
(Some(k), None) if bv_and(m, &k).is_zero() => b,
(None, Some(k)) if bv_and(m, &k).is_zero() => a,
(Some(k), None) if subset(m, &k) => a,
(None, Some(k)) if subset(m, &k) => b,
_ => bin(r, cx, BinOp::Or, a, b)?,
}
}
},
OpCode::Xor => match (konst(cx, node.a), konst(cx, node.b)) {
(Some(k), _) | (_, Some(k)) if bv_and(m, &k).is_zero() || subset(m, &k) => {
let a = if konst(cx, node.a).is_some() {
node.b
} else {
node.a
};
let a2 = simplify(r, cx, st, a, m)?;
if bv_and(m, &k).is_zero() {
a2
} else {
r.build(cx, |cx| cx.c_un(UnOp::Not, a2))?
}
}
(Some(k), _) | (_, Some(k)) => {
let a = if konst(cx, node.a).is_some() {
node.b
} else {
node.a
};
let twin = st.xors.iter().find(|(a1, k1, m1, _)| {
*a1 == a && subset(m, m1) && subset(m, &bv_or(k1, &k)) && {
let both = bv_and(k1, &k);
bv_and(&both, m).is_zero()
}
});
if let Some(&(_, _, _, y)) = twin {
r.build(cx, |cx| cx.c_un(UnOp::Not, y))?
} else {
let a2 = simplify(r, cx, st, a, m)?;
let kc = r.build(cx, |cx| cx.mk_const(&k))?;
let y = bin(r, cx, BinOp::Xor, a2, kc)?;
st.xors.push((a, k, *m, y));
y
}
}
_ => {
let a = simplify(r, cx, st, node.a, m)?;
let b = simplify(r, cx, st, node.b, m)?;
bin(r, cx, BinOp::Xor, a, b)?
}
},
OpCode::Not => {
let a = simplify(r, cx, st, node.a, m)?;
r.build(cx, |cx| cx.c_un(UnOp::Not, a))?
}
OpCode::Add | OpCode::Sub | OpCode::Mul => {
let p = low_prefix(m);
let whole_sum = st.whole_sums && node.op != OpCode::Mul;
let (ka, kb) = (cx.const_val(node.a), cx.const_val(node.b));
let (a, b) = match (whole_sum, ka, kb) {
(true, None, Some(k)) => {
let a = simplify(r, cx, st, node.a, &p)?;
let kind = u8::from(node.op == OpCode::Sub);
(a, same_on(r, cx, (a, kind), node.b, &k, &p))
}
(true, Some(k), None) => {
let b = simplify(r, cx, st, node.b, &p)?;
let kind = if node.op == OpCode::Sub { 2 } else { 0 };
(same_on(r, cx, (b, kind), node.a, &k, &p), b)
}
_ => (
simplify(r, cx, st, node.a, &p)?,
simplify(r, cx, st, node.b, &p)?,
),
};
let op = node.op.as_bin().unwrap_or(BinOp::Add);
let flipped = match (node.op, dropped_constant(cx, node.op, a, b, &p)) {
(OpCode::Mul, _) | (_, Some(_)) => None,
_ => {
let (ta, tb) = (
if cx.const_val(a).is_some() { a } else { node.a },
if cx.const_val(b).is_some() { b } else { node.b },
);
carried(r, cx, st, x, ta, tb, &p)?
}
};
let ones = |j: u32| cx.const_val(j).is_some_and(|k| k.is_ones());
match dropped_constant(cx, node.op, a, b, &p).or(flipped) {
Some(t) => t,
None if node.op == OpCode::Mul && (ones(a) || ones(b)) => {
let t = if ones(a) { b } else { a };
r.build(cx, |cx| cx.c_un(UnOp::Neg, t))?
}
None => bin(r, cx, op, a, b)?,
}
}
OpCode::Neg => {
let a = simplify(r, cx, st, node.a, &low_prefix(m))?;
r.build(cx, |cx| cx.c_un(UnOp::Neg, a))?
}
OpCode::Shl | OpCode::LShr if konst(cx, node.b).is_some() => {
let k = konst(cx, node.b).unwrap_or(BitVec::zero(w));
let (op, back) = if node.op == OpCode::Shl {
(BinOp::Shl, BinOp::LShr)
} else {
(BinOp::LShr, BinOp::Shl)
};
let ma = BitVec::bin_unchecked(back, m, &k);
let a = simplify(r, cx, st, node.a, &ma)?;
let kb = node.b;
bin(r, cx, op, a, kb)?
}
OpCode::Zext => {
let wa = cx.width_of(node.a);
let ml = m.trunc(wa).map_err(|e| Stop::Error(e.into()))?;
let a = simplify(r, cx, st, node.a, &ml)?;
r.build(cx, |cx| cx.c_zext(a, w.bits()))?
}
OpCode::Extract => {
let wa = cx.width_of(node.a);
let lo = BitVec::wrapping_from_u64(wa, u64::from(node.b));
let ma = m.zext(wa).map_err(|e| Stop::Error(e.into()))?;
let ma = BitVec::bin_unchecked(BinOp::Shl, &ma, &lo);
let a = simplify(r, cx, st, node.a, &ma)?;
let (b, c) = (node.b, node.c);
r.build(cx, |cx| cx.rebuild(x, [a, b, c]))?
}
OpCode::Sext => {
let wa = cx.width_of(node.a);
let ml = m.trunc(wa).map_err(|e| Stop::Error(e.into()))?;
let above = m
.extract(
wa.bits(),
Width::new(w.bits() - wa.bits()).map_err(|e| Stop::Error(e.into()))?,
)
.map_err(|e| Stop::Error(e.into()))?;
let ml = if above.is_zero() {
ml
} else {
let sign = BitVec::bin_unchecked(
BinOp::Shl,
&BitVec::wrapping_from_u64(wa, 1),
&BitVec::wrapping_from_u64(wa, u64::from(wa.bits() - 1)),
);
bv_or(&ml, &sign)
};
let a = simplify(r, cx, st, node.a, &ml)?;
r.build(cx, |cx| cx.c_sext(a, w.bits()))?
}
OpCode::Concat => {
let (wh, wl) = (cx.width_of(node.a), cx.width_of(node.b));
let ml = m.trunc(wl).map_err(|e| Stop::Error(e.into()))?;
let mh = m
.extract(wl.bits(), wh)
.map_err(|e| Stop::Error(e.into()))?;
let h = simplify(r, cx, st, node.a, &mh)?;
let l = simplify(r, cx, st, node.b, &ml)?;
r.build(cx, |cx| cx.c_concat(h, l))?
}
_ => stop(cx, st)?,
};
st.note(Key(x, *m), v);
if v == x && x < st.before && r.demanded.same.carried.get(&x) != Some(&true) {
st.identities
.push((Key(x, *m), stops0, st.stops.len() as u32));
}
Ok(v)
}
fn read_once(r: &mut Runner<'_, '_>, cx: &Context, x: u32) -> Result<bool, Stop> {
super::refresh_uses(r, cx)?;
Ok(r.life.live.uses(x) == Some(1) && !r.life.live_roots.contains(&x))
}
fn stop_at(cx: &Context, st: &mut Demand, x: u32) {
if x < st.before {
st.stops.push(x);
return;
}
let mut stack = vec![x];
while let Some(i) = stack.pop() {
if i < st.before {
st.stops.push(i);
} else {
stack.extend(cx.node(i).children());
}
}
}
fn merged(
r: &mut Runner<'_, '_>,
cx: &mut Context,
st: &mut Demand,
x: u32,
m: &BitVec,
) -> Result<Option<u32>, Stop> {
let w = m.width();
let p = low_prefix(m);
let j = crate::facts::known::count_ones(&p);
if j >= u32::from(w.bits()) || !super::conditions::may_merge(cx, x) {
return Ok(None);
}
let form = super::linear::form_of(r, cx, x)?;
let Some((f, _)) = super::conditions::merge(r, cx, &form)? else {
return Ok(None);
};
let jw = crate::Width::new(j as u16).map_err(|e| Stop::Error(e.into()))?;
let f = f.reduce(jw);
st.fin = st.fin.and(f.fin);
let (konst, terms, _) = super::forms::Parts::parts(&f);
let (konst, terms) = (*konst, terms.to_vec());
let mut out = Vec::with_capacity(terms.len());
for (a, k) in terms {
out.push((simplify(r, cx, st, a, &p)?, k));
}
let f = super::linear::Form::of(konst, &out);
Ok(Some(super::linear::emit(r, cx, &f)?))
}
fn joined(
r: &mut Runner<'_, '_>,
cx: &mut Context,
st: &mut Demand,
x: u32,
m: &BitVec,
) -> Result<Option<u32>, Stop> {
let w = m.width();
let p = low_prefix(m);
let j = crate::facts::known::count_ones(&p);
if j >= u32::from(w.bits()) || w.bits() > 64 {
return Ok(None);
}
let form = super::linear::form_of(r, cx, x)?;
let Some((f, _)) = super::limbs::joined(r, cx, &form, j as u16)? else {
return Ok(None);
};
st.fin = st.fin.and(f.fin);
let (konst, terms, _) = super::forms::Parts::parts(&f);
let (konst, terms) = (*konst, terms.to_vec());
let mut out = Vec::with_capacity(terms.len());
for (a, k) in terms {
out.push((simplify(r, cx, st, a, &p)?, k));
}
let f = super::linear::Form::of(konst, &out);
Ok(Some(super::linear::emit(r, cx, &f)?))
}
fn clears_known_zeros(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Result<Option<u32>, Stop> {
let node = cx.node(n);
if node.op != OpCode::And || cx.wid(n) > 64 {
return Ok(None);
}
let (x, k) = match (cx.const_val(node.a), cx.const_val(node.b)) {
(None, Some(k)) => (node.a, k),
(Some(k), None) => (node.b, k),
_ => return Ok(None),
};
let Some(kv) = k.to_u64() else {
return Ok(None);
};
let wbits = u32::from(cx.wid(n));
let all = if wbits >= 64 {
u64::MAX
} else {
(1 << wbits) - 1
};
let cleared = !kv & all;
let bits = 64 - cleared.leading_zeros();
if cleared == 0
|| bits > RESIDUE_BITS
|| !matches!(cx.node(x).op, OpCode::Mul | OpCode::Add | OpCode::Sub)
{
return Ok(None);
}
let Some(t) = super::residue::residues(r, cx, x, bits)? else {
return Ok(None);
};
Ok(t.values.iter().all(|&v| v & cleared == 0).then_some(x))
}
fn carried(
r: &mut Runner<'_, '_>,
cx: &mut Context,
st: &mut Demand,
x: u32,
a: u32,
b: u32,
p: &BitVec,
) -> Result<Option<u32>, Stop> {
let w = p.width();
if w.bits() > 64 {
return Ok(None);
}
let op = cx.node(x).op;
let (t, k, from) = match (op, cx.const_val(a), cx.const_val(b)) {
(OpCode::Add, None, Some(k)) => (a, k, false),
(OpCode::Add, Some(k), None) => (b, k, false),
(OpCode::Sub, None, Some(k)) => (a, BitVec::un_unchecked(UnOp::Neg, &k), false),
(OpCode::Sub, Some(k), None) => (b, k, true),
_ => return Ok(None),
};
let (pw, kw) = (p.limbs()[0], k.limbs()[0]);
let (known, fin) = known_words(r, cx, t)?;
let Some([zero, one]) = known else {
return Ok(None);
};
let n = 64 - pw.leading_zeros();
let (mut carry, mut flips) = (false, 0u64);
for j in 0..n {
let bit = 1u64 << j;
let kj = kw & bit != 0;
if kj != carry {
flips |= bit;
}
let settled = if from { kj != carry } else { kj == carry };
if !settled && j + 1 < n {
if (zero | one) & bit == 0 {
return Ok(None);
}
carry = one & bit != 0;
}
}
if flips & pw == 0 && !from {
return Ok(None);
}
super::refresh_uses(r, cx)?;
if r.life.live.uses(x) != Some(1) || r.life.live_roots.contains(&x) {
return Ok(None);
}
st.fin = st.fin.and(fin);
st.ties = true;
st.stops.push(t);
let kx = BitVec::from_canonical_u64(w, flips & pw);
let c = r.build(cx, |cx| cx.mk_const(&kx))?;
st.stops.push(c);
Ok(Some(r.build(cx, |cx| cx.c_bin(BinOp::Xor, t, c))?))
}
fn dropped_constant(cx: &Context, op: OpCode, a: u32, b: u32, p: &BitVec) -> Option<u32> {
let (t, k) = match (op, cx.const_val(a), cx.const_val(b)) {
(OpCode::Sub, Some(k), None) if cx.node(b).op == OpCode::Not => {
let one = BitVec::one(k.width());
(cx.node(b).a, BitVec::bin_unchecked(BinOp::Add, &k, &one))
}
(OpCode::Add | OpCode::Sub, None, Some(k)) => (a, k),
(OpCode::Add, Some(k), None) => (b, k),
_ => return None,
};
bv_and(&k, p).is_zero().then_some(t)
}
#[cfg(feature = "mba")]
pub(super) fn reduced(
r: &mut Runner<'_, '_>,
cx: &mut Context,
x: u32,
cap: u32,
whole_sums: bool,
) -> Result<u32, Stop> {
let w = cx.width_of(x);
let which = usize::from(whole_sums);
let mut st = Demand {
memo: Memo::default(),
base: std::mem::take(&mut r.demanded.reduced[which]),
whole: Some(Vec::new()),
whole_sums,
cap,
stops: Vec::new(),
visits: 0,
fin: Fin::FINAL,
before: cx.len() as u32,
root: x,
xors: Vec::new(),
identities: Vec::new(),
union: IdMap::default(),
ties: false,
};
let out = simplify(r, cx, &mut st, x, &BitVec::ones(w));
let mut base = std::mem::take(&mut st.base);
if out.is_ok() {
base.extend(st.whole.take().unwrap_or_default());
}
r.demanded.reduced[which] = base;
out
}
#[cfg(feature = "prove")]
const MAX_CONE: usize = 2048;
#[cfg(feature = "prove")]
fn reads_through(cx: &Context, i: u32) -> bool {
let n = cx.node(i);
match n.op {
OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Not
| OpCode::Add
| OpCode::Sub
| OpCode::Mul
| OpCode::Neg
| OpCode::Zext
| OpCode::Sext
| OpCode::Extract
| OpCode::Concat => true,
OpCode::Shl | OpCode::LShr => cx.const_val(n.b).is_some(),
_ => false,
}
}
#[cfg(feature = "prove")]
fn carries(cx: &Context, i: u32) -> bool {
matches!(cx.node(i).op, OpCode::Add | OpCode::Sub)
&& cx.wid(i) <= 64
&& super::borrows::may_expand(cx, i)
}
#[cfg(feature = "prove")]
fn over_carries(r: &mut Runner<'_, '_>, cx: &Context, x: u32) -> Result<bool, Stop> {
let mut stack = vec![(x, false)];
while let Some((i, expanded)) = stack.pop() {
if r.demanded.same.carried.contains_key(&i) {
continue;
}
if carries(cx, i) {
r.demanded.same.carried.insert(i, true);
continue;
}
if !reads_through(cx, i) {
r.demanded.same.carried.insert(i, false);
continue;
}
let node = cx.node(i);
if expanded {
let any = node
.children()
.any(|c| r.demanded.same.carried.get(&c) == Some(&true));
r.demanded.same.carried.insert(i, any);
continue;
}
r.meter.charge(Counter::PassWork, 1)?;
stack.push((i, true));
for c in node.children() {
if !r.demanded.same.carried.contains_key(&c) {
stack.push((c, false));
}
}
}
Ok(r.demanded.same.carried.get(&x) == Some(&true))
}
#[cfg(feature = "prove")]
fn unions(
r: &mut Runner<'_, '_>,
cx: &Context,
st: &mut Demand,
operand: u32,
mask: &BitVec,
) -> Result<(), Stop> {
over_carries(r, cx, operand)?;
let mut order: Vec<u32> = Vec::new();
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![(operand, false)];
while let Some((i, expanded)) = stack.pop() {
if expanded {
order.push(i);
continue;
}
if seen.insert(i, ()).is_some() {
continue;
}
if seen.len() > MAX_CONE {
return Ok(());
}
stack.push((i, true));
if reads_through(cx, i) {
for c in cx.node(i).children() {
if !seen.contains_key(&c) {
stack.push((c, false));
}
}
}
}
r.meter.charge(Counter::PassWork, order.len() as u64)?;
let mut read: IdMap<u32, BitVec> = IdMap::default();
read.insert(operand, *mask);
let mut inside: IdMap<u32, u32> = IdMap::default();
inside.insert(operand, 1);
super::refresh_uses(r, cx)?;
for &x in &order {
for c in cx.node(x).children() {
*inside.entry(c).or_default() += 1;
}
}
let give = |read: &mut IdMap<u32, BitVec>, c: u32, m: BitVec| {
if cx.const_val(c).is_none() && m.width() == cx.width_of(c) {
read.entry(c).and_modify(|v| *v = bv_or(v, &m)).or_insert(m);
}
};
for &x in order.iter().rev() {
if r.life.live.uses(x).unwrap_or(0) > inside.get(&x).copied().unwrap_or(0) {
read.insert(x, BitVec::ones(cx.width_of(x)));
}
if !reads_through(cx, x) {
for c in cx.node(x).children() {
if seen.contains_key(&c) && cx.const_val(c).is_none() {
read.insert(c, BitVec::ones(cx.width_of(c)));
}
}
}
let Some(m) = read.get(&x).copied() else {
continue;
};
if m.is_zero() || !reads_through(cx, x) {
continue;
}
let node = cx.node(x);
let konst = |j: u32| cx.const_val(j);
match node.op {
OpCode::And | OpCode::Or => {
let k = konst(node.a).or(konst(node.b));
let ma = match (node.op, k) {
(OpCode::And, Some(k)) => bv_and(&m, &k),
(_, Some(k)) => bv_and(&m, &bv_not(&k)),
_ => m,
};
give(&mut read, node.a, ma);
give(&mut read, node.b, ma);
}
OpCode::Xor => {
give(&mut read, node.a, m);
give(&mut read, node.b, m);
}
OpCode::Not => give(&mut read, node.a, m),
OpCode::Add | OpCode::Sub | OpCode::Mul => {
let p = low_prefix(&m);
give(&mut read, node.a, p);
give(&mut read, node.b, p);
}
OpCode::Neg => give(&mut read, node.a, low_prefix(&m)),
OpCode::Shl | OpCode::LShr => {
let Some(k) = konst(node.b) else {
continue;
};
let back = if node.op == OpCode::Shl {
BinOp::LShr
} else {
BinOp::Shl
};
give(&mut read, node.a, BitVec::bin_unchecked(back, &m, &k));
}
OpCode::Zext | OpCode::Sext => {
let wa = cx.width_of(node.a);
let Ok(mut ml) = m.trunc(wa) else {
continue;
};
if node.op == OpCode::Sext && ml.zext(m.width()).ok() != Some(m) {
let sign = BitVec::bin_unchecked(
BinOp::Shl,
&BitVec::wrapping_from_u64(wa, 1),
&BitVec::wrapping_from_u64(wa, u64::from(wa.bits() - 1)),
);
ml = bv_or(&ml, &sign);
}
give(&mut read, node.a, ml);
}
OpCode::Extract => {
let wa = cx.width_of(node.a);
let lo = BitVec::wrapping_from_u64(wa, u64::from(node.b));
let Ok(ma) = m.zext(wa) else {
continue;
};
give(
&mut read,
node.a,
BitVec::bin_unchecked(BinOp::Shl, &ma, &lo),
);
}
OpCode::Concat => {
let (wh, wl) = (cx.width_of(node.a), cx.width_of(node.b));
if let (Ok(ml), Ok(mh)) = (m.trunc(wl), m.extract(wl.bits(), wh)) {
give(&mut read, node.a, mh);
give(&mut read, node.b, ml);
}
}
_ => {}
}
}
for &x in &order {
if let Some(m) = read.get(&x) {
st.union.insert(x, *m);
}
}
Ok(())
}
#[cfg(feature = "prove")]
const MAX_WHOLE: usize = 4096;
#[cfg(feature = "prove")]
#[allow(clippy::type_complexity)]
fn demands(
r: &mut Runner<'_, '_>,
cx: &Context,
root: u32,
) -> Result<Option<(Vec<u32>, IdMap<u32, BitVec>)>, Stop> {
let mut order: Vec<u32> = Vec::new();
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![(root, false)];
while let Some((i, expanded)) = stack.pop() {
if expanded {
order.push(i);
continue;
}
if seen.insert(i, ()).is_some() {
continue;
}
if seen.len() > MAX_WHOLE {
return Ok(None);
}
stack.push((i, true));
for c in cx.node(i).children() {
if !seen.contains_key(&c) {
stack.push((c, false));
}
}
}
r.meter.charge(Counter::PassWork, order.len() as u64)?;
let mut read: IdMap<u32, BitVec> = IdMap::default();
read.insert(root, BitVec::ones(cx.width_of(root)));
let mut below = Vec::new();
for &x in order.iter().rev() {
let Some(m) = read.get(&x).copied() else {
continue;
};
if m.is_zero() {
continue;
}
if reads_through(cx, x) {
reads(cx, x, &m, &mut below);
} else {
let node = cx.node(x);
below.clear();
for (s, c) in node.children().enumerate() {
let arm = node.op == OpCode::Select && s > 0;
let whole = BitVec::ones(cx.width_of(c));
below.push((c, if arm { m } else { whole }));
}
}
for (c, cm) in below.drain(..) {
read.entry(c)
.and_modify(|v| *v = bv_or(v, &cm))
.or_insert(cm);
}
}
Ok(Some((order, read)))
}
#[cfg(feature = "prove")]
#[derive(Clone)]
struct Limb {
x: u32,
e: u32,
fin: Fin,
stops: Vec<u32>,
pays: bool,
shared: i64,
tied: bool,
}
#[cfg(feature = "prove")]
fn replaced(
r: &mut Runner<'_, '_>,
cx: &mut Context,
order: &[u32],
root: u32,
limbs: &[Limb],
paying: bool,
) -> Result<(u32, Vec<u32>), Stop> {
let mut to: IdMap<u32, u32> = IdMap::default();
let mut atoms: Vec<u32> = Vec::new();
for l in limbs.iter().filter(|l| l.pays || !paying) {
to.insert(l.x, l.e);
atoms.extend_from_slice(&l.stops);
}
r.meter.charge(Counter::PassWork, order.len() as u64)?;
for &x in order {
if to.contains_key(&x) {
continue;
}
let node = cx.node(x);
let mut kids = [node.a, node.b, node.c];
let arity = node.op.arity();
let mut changed = false;
for k in kids.iter_mut().take(arity) {
if let Some(&t) = to.get(k) {
*k = t;
changed = true;
}
}
if !changed {
continue;
}
for (k, c) in kids.iter().zip(node.children()) {
if *k == c {
atoms.push(c);
}
}
let y = r.build(cx, |cx| cx.rebuild(x, kids))?;
to.insert(x, y);
}
Ok((to.get(&root).copied().unwrap_or(root), atoms))
}
#[cfg(feature = "prove")]
fn lifted(
r: &mut Runner<'_, '_>,
cx: &mut Context,
x: u32,
low: u32,
j: u16,
) -> Result<Option<u32>, Stop> {
let w = cx.width_of(x);
let form = super::linear::form_of(r, cx, x)?;
let (konst, terms, _) = super::forms::Parts::parts(&form);
let (konst, terms) = (*konst, terms.to_vec());
let mut own: Vec<(u32, u32)> = Vec::with_capacity(terms.len());
for &(t, _) in &terms {
if let Some((h, _, _)) = super::casts::narrowed_from(r, cx, t, 0, j)? {
own.push((h, t));
}
}
let read = super::linear::form_of(r, cx, low)?;
let (k2, t2, _) = super::forms::Parts::parts(&read);
let (k2, t2) = (*k2, t2.to_vec());
let wide = |v: &BitVec| v.sext(w).map_err(|e| Stop::Error(e.into()));
let mut out: Vec<(u32, BitVec)> = Vec::with_capacity(t2.len());
let mut kept = false;
for (h, c) in t2 {
let same = own.iter().filter(|&&(n, _)| n == h).map(|&(_, t)| t);
let t = match same.min_by(|a, b| cx.order(*a, *b)) {
Some(t) => {
kept = true;
t
}
None => r.build(cx, |cx| cx.c_zext(h, w.bits()))?,
};
out.push((t, wide(&c)?));
}
if !kept {
return Ok(None);
}
let k = if konst.trunc(k2.width()).ok() == Some(k2) {
konst
} else {
wide(&k2)?
};
let f = super::linear::Form::of(k, &out);
Ok(Some(super::linear::emit(r, cx, &f)?))
}
#[cfg(feature = "prove")]
const MAX_NARROW: usize = 16;
#[cfg(feature = "prove")]
const MAX_FULL: usize = 48;
#[cfg(feature = "prove")]
const MAX_BELOW: usize = 512;
#[cfg(feature = "prove")]
fn holds_any(
r: &mut Runner<'_, '_>,
cx: &Context,
from: u32,
targets: &[u32],
) -> Result<bool, Stop> {
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![from];
let mut found = false;
while let Some(i) = stack.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
if targets.contains(&i) || seen.len() > MAX_BELOW {
found = true;
break;
}
stack.extend(cx.node(i).children());
}
r.meter.charge(Counter::PassWork, seen.len() as u64)?;
Ok(found)
}
#[cfg(feature = "prove")]
fn words(
r: &mut Runner<'_, '_>,
cx: &mut Context,
root: u32,
order: &[u32],
read: &IdMap<u32, BitVec>,
) -> Result<Option<Step>, Stop> {
use super::forms::Parts;
use super::linear::{self, Form};
let konst = |cx: &Context, i: u32| cx.const_val(i).is_some();
let sum = |cx: &Context, i: u32| {
let n = cx.node(i);
n.width <= 64
&& match n.op {
OpCode::Add | OpCode::Sub | OpCode::Neg => true,
OpCode::Mul | OpCode::Shl => konst(cx, n.a) || konst(cx, n.b),
_ => false,
}
};
let mut outer: IdMap<u32, ()> = IdMap::default();
outer.insert(root, ());
for &u in order {
if !sum(cx, u) {
for c in cx.node(u).children() {
outer.insert(c, ());
}
}
}
let mut full: Vec<(u32, u16)> = order
.iter()
.filter(|&&x| sum(cx, x) && outer.contains_key(&x))
.filter_map(|&x| {
let j = crate::facts::known::count_ones(&low_prefix(read.get(&x)?)) as u16;
(j > 0).then_some((x, j))
})
.collect();
if !full.iter().any(|&(x, j)| j < cx.wid(x)) || full.len() < 2 {
return Ok(None);
}
full.sort_by(|a, b| cx.order(a.0, b.0));
let mut narrow: Vec<(u32, u16)> = full.iter().filter(|v| v.1 < cx.wid(v.0)).copied().collect();
narrow.truncate(MAX_NARROW);
full.truncate(MAX_FULL);
let before = cx.len() as u32;
let mut fin = Fin::FINAL;
let mut found: Vec<(u32, u32, u32)> = Vec::new();
for &(x, j) in &narrow {
let w = cx.wid(x);
let jw = Width::new(j).map_err(|e| Stop::Error(e.into()))?;
let full_x = linear::form_of(r, cx, x)?;
let fx = full_x.reduce(jw);
let tx = fx.parts().1.len();
if tx == 0 {
continue;
}
#[allow(clippy::type_complexity)]
let mut best: Option<((usize, bool, u16), u32, bool, Form)> = None;
for &(y, jy) in &full {
if y == x || cx.wid(y) != w || jy < j || (jy == j && !cx.order(y, x).is_lt()) {
continue;
}
r.meter.charge(Counter::PassWork, 16)?;
let whole = linear::form_of(r, cx, y)?;
let fy = whole.reduce(jw);
let ty = fy.parts().1.len();
if ty == 0 {
continue;
}
for minus in [false, true] {
let plain = if minus {
full_x.add(&whole)
} else {
full_x.add(&whole.neg())
};
if plain.parts().1.len() + ty <= tx {
continue;
}
let over = if minus {
fx.add(&fy)
} else {
fx.add(&fy.neg())
};
let over = over.reduce(jw);
let rest = match super::limbs::joined(r, cx, &over, j)? {
Some((f, _)) => f,
None => over,
};
let left = rest.parts().1.len();
if left + ty > tx {
continue;
}
let score = (left, !rest.parts().0.is_zero(), w - jy);
if best.as_ref().is_none_or(|b| score < b.0) && !holds_any(r, cx, y, &[x])? {
best = Some((score, y, minus, rest));
}
}
}
let Some((_, y, minus, rest)) = best else {
continue;
};
fin = fin.and(fx.fin).and(rest.fin);
let (k, terms, _) = rest.parts();
let mut terms = terms.to_vec();
let one = BitVec::one(cx.width_of(x));
terms.push((
y,
if minus {
BitVec::un_unchecked(UnOp::Neg, &one)
} else {
one
},
));
let e = linear::emit(r, cx, &Form::of(*k, &terms))?;
if e != x {
found.push((x, y, e));
}
}
let all: Vec<u32> = found.iter().map(|v| v.0).collect();
let mut kept = Vec::with_capacity(found.len());
for &(x, y, e) in &found {
if !holds_any(r, cx, y, &all)? {
kept.push((x, e));
}
}
if kept.is_empty() {
super::discard(r, cx, before);
return Ok(None);
}
let to: IdMap<u32, u32> = kept.iter().copied().collect();
let mut done: IdMap<u32, u32> = IdMap::default();
let mut atoms: Vec<u32> = Vec::new();
let mut walk = vec![(root, false)];
r.meter.charge(Counter::PassWork, order.len() as u64)?;
while let Some((u, expanded)) = walk.pop() {
if done.contains_key(&u) {
continue;
}
if let Some(&e) = to.get(&u) {
done.insert(u, e);
continue;
}
let node = cx.node(u);
if !expanded {
walk.push((u, true));
walk.extend(node.children().map(|c| (c, false)));
continue;
}
let mut kids = [node.a, node.b, node.c];
let mut changed = false;
for k in kids.iter_mut().take(node.op.arity()) {
if let Some(&t) = done.get(k)
&& t != *k
{
*k = t;
changed = true;
}
}
if !changed {
done.insert(u, u);
continue;
}
for (k, c) in kids.iter().zip(node.children()) {
if *k == c {
atoms.push(c);
}
}
let v = r.build(cx, |cx| cx.rebuild(u, kids))?;
done.insert(u, v);
}
let e = done.get(&root).copied().unwrap_or(root);
if e == root {
super::discard(r, cx, before);
return Ok(None);
}
let below: IdMap<u32, ()> = order.iter().map(|&i| (i, ())).collect();
let mut seen: IdMap<u32, ()> = IdMap::default();
for &(_, e) in &kept {
let mut stack = vec![e];
while let Some(i) = stack.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
r.meter.charge(Counter::PassWork, 1)?;
if below.contains_key(&i) {
atoms.push(i);
} else {
stack.extend(cx.node(i).children());
}
}
}
super::discard_but(r, cx, before, e);
r.explain_with(|| crate::engine::Explanation::Demanded {
operand: cx.handle(root),
mask: BitVec::ones(cx.width_of(root)),
});
let tree = |i: u32| cx.meta[i as usize].tree;
let tie = tree(root) != u32::MAX && tree(e) < tree(root);
Ok(
match super::finish_with(r, cx, PassKind::Demanded, root, e, before, &atoms, fin, tie)? {
Step::To(e, f) => Some(Step::To(e, f)),
Step::Normal(_) => None,
},
)
}
#[cfg(feature = "prove")]
pub(crate) fn whole(
r: &mut Runner<'_, '_>,
cx: &mut Context,
root: u32,
late: bool,
) -> Result<Step, Stop> {
read(r, cx, root, late, false)
}
#[cfg(feature = "prove")]
pub(crate) fn late(r: &mut Runner<'_, '_>, cx: &mut Context, root: u32) -> Result<bool, Stop> {
Ok(matches!(read(r, cx, root, true, true)?, Step::To(..)))
}
#[cfg(feature = "prove")]
fn read(
r: &mut Runner<'_, '_>,
cx: &mut Context,
root: u32,
late: bool,
dry: bool,
) -> Result<Step, Stop> {
let Some((order, read)) = demands(r, cx, root)? else {
return Ok(Step::Normal(Fin::FINAL));
};
if !dry && let Some(step) = words(r, cx, root, &order, &read)? {
return Ok(step);
}
let mut fin = Fin::FINAL;
let mut fin_tied = Fin::FINAL;
let mut limbs: Vec<Limb> = Vec::new();
let mut outer: IdMap<u32, ()> = IdMap::default();
outer.insert(root, ());
for &u in &order {
let node = cx.node(u);
if !matches!(node.op, OpCode::Add | OpCode::Sub | OpCode::Neg) {
for c in node.children() {
outer.insert(c, ());
}
}
}
for &x in &order {
if !carries(cx, x) {
continue;
}
let Some(m) = read.get(&x) else {
continue;
};
let w = cx.wid(x);
let j = crate::facts::known::count_ones(&low_prefix(m)) as u16;
if j == 0 {
continue;
}
let before = cx.len() as u32;
let Some((low, f, stops, tied)) = super::borrows::expanded(r, cx, x, j, late)? else {
continue;
};
let stops = if tied { Vec::new() } else { stops };
if tied {
fin_tied = fin_tied.and(f.unchanged());
} else {
fin = fin.and(f.unchanged());
}
let e = if j < w {
r.build(cx, |cx| cx.c_zext(low, w))?
} else {
low
};
let slack = i64::from(super::carries::slack(cx, x, e, before));
let mut best = super::margins(r, cx, x, e, &stops)?.map(|(s, a)| (e, s, a, slack));
super::discard(r, cx, before);
if j < w
&& let Some(e) = lifted(r, cx, x, low, j)?
{
let slack = i64::from(super::carries::slack(cx, x, e, before));
let m = super::margins(r, cx, x, e, &stops)?;
super::discard(r, cx, before);
if let Some((s, a)) = m
&& best.is_none_or(|(_, bs, ba, bk)| (a + slack > 0, s, a) > (ba + bk > 0, bs, ba))
{
best = Some((e, s, a, slack));
}
}
let Some((e, shared, alone, slack)) = best else {
continue;
};
if e == x || (alone + slack <= 0 && !tied) {
continue;
}
let pays = shared + slack > 0;
if !pays {
if tied {
fin_tied = fin_tied.and(Fin::PROVISIONAL);
} else {
fin = fin.and(Fin::PROVISIONAL);
}
}
limbs.push(Limb {
x,
e,
fin: f,
stops,
pays,
shared,
tied,
});
}
if limbs.iter().all(|l| !l.tied) {
if dry {
return Ok(Step::Normal(fin));
}
return taken(r, cx, &order, &outer, root, limbs, fin, false);
}
if !dry {
let strict: Vec<Limb> = limbs.iter().filter(|l| !l.tied).cloned().collect();
match taken(r, cx, &order, &outer, root, strict, fin, false)? {
Step::Normal(f) => fin = f,
step => return Ok(step),
}
}
taken(r, cx, &order, &outer, root, limbs, fin.and(fin_tied), dry)
}
#[cfg(feature = "prove")]
#[allow(clippy::too_many_arguments)]
fn taken(
r: &mut Runner<'_, '_>,
cx: &mut Context,
order: &[u32],
outer: &IdMap<u32, ()>,
root: u32,
mut limbs: Vec<Limb>,
mut fin: Fin,
dry: bool,
) -> Result<Step, Stop> {
let mut dropped = vec![false; limbs.len()];
let mut stack = Vec::new();
let mut seen: IdMap<u32, ()> = IdMap::default();
for u in 0..limbs.len() {
stack.clear();
seen.clear();
stack.push(limbs[u].x);
while let Some(i) = stack.pop() {
r.meter.charge(Counter::PassWork, 1)?;
for c in cx.node(i).children() {
let sum = matches!(cx.node(c).op, OpCode::Add | OpCode::Sub | OpCode::Neg);
if !sum || outer.contains_key(&c) || seen.insert(c, ()).is_some() {
continue;
}
if let Some(l) = limbs.iter().position(|l| l.x == c) {
let (below, above) = (&limbs[l], &limbs[u]);
let key = |l: &Limb| (!l.tied, l.pays, l.shared);
if key(below) > key(above) {
dropped[u] = true;
} else {
dropped[l] = true;
}
}
stack.push(c);
}
}
}
let mut k = 0;
limbs.retain(|_| {
k += 1;
!dropped[k - 1]
});
if limbs.is_empty() {
return Ok(Step::Normal(fin));
}
let before = cx.len() as u32;
let some = limbs.iter().any(|l| l.pays);
let all = limbs.iter().all(|l| l.pays);
let whole = limbs.iter().any(|l| l.tied);
let given = |atoms: Vec<u32>| if whole { Vec::new() } else { atoms };
let (e, atoms) = replaced(r, cx, order, root, &limbs, false)?;
let atoms = given(atoms);
let every = if e == root {
None
} else {
super::margin(r, cx, root, e, &atoms)?
};
let mut paying = false;
if some && !all {
super::discard(r, cx, before);
let (e, atoms) = replaced(r, cx, order, root, &limbs, true)?;
let atoms = given(atoms);
let few = if e == root {
None
} else {
super::margin(r, cx, root, e, &atoms)?
};
paying = few.is_some_and(|b| every.is_none_or(|a| b > a));
}
super::discard(r, cx, before);
let (e, atoms) = replaced(r, cx, order, root, &limbs, paying)?;
let atoms = given(atoms);
super::discard_but(r, cx, before, e);
for l in limbs.iter().filter(|l| l.pays || !paying) {
fin = fin.and(l.fin);
}
let tree = |i: u32| cx.meta[i as usize].tree;
let tie = tree(root) != u32::MAX && tree(e) < tree(root);
if dry {
let pays = e != root
&& super::margin(r, cx, root, e, &atoms)?.is_some_and(|m| m + i64::from(tie) > 0);
super::discard(r, cx, before);
return Ok(if pays {
Step::To(e, fin)
} else {
Step::Normal(fin)
});
}
r.explain_with(|| crate::engine::Explanation::Demanded {
operand: cx.handle(root),
mask: BitVec::ones(cx.width_of(root)),
});
super::finish_with(r, cx, PassKind::Demanded, root, e, before, &atoms, fin, tie)
}
pub(in crate::engine) fn under_mask(
r: &mut Runner<'_, '_>,
cx: &mut Context,
x: u32,
m: &BitVec,
) -> Result<u32, Stop> {
let mut st = Demand {
memo: Memo::default(),
base: Memo::default(),
whole: None,
whole_sums: false,
cap: MAX_VISITS,
stops: Vec::new(),
visits: 0,
fin: Fin::FINAL,
before: cx.len() as u32,
root: x,
xors: Vec::new(),
identities: Vec::new(),
union: IdMap::default(),
ties: false,
};
simplify(r, cx, &mut st, x, m)
}
fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
r.stats.passes.entry("demanded").or_default()
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let node = cx.node(n);
if let Some(x) = clears_known_zeros(r, cx, n)? {
let before = cx.len() as u32;
return finish(r, cx, PassKind::Demanded, n, x, before, &[x], Fin::FINAL);
}
let Some((operand, mask)) = observed(cx, n) else {
return Ok(Step::Normal(Fin::FINAL));
};
let before = cx.len() as u32;
let mut st = Demand {
base: Memo::default(),
whole: None,
whole_sums: false,
memo: std::mem::take(&mut r.demanded.memo),
cap: MAX_VISITS.min(super::region_cap(r)),
stops: Vec::new(),
visits: 0,
fin: Fin::FINAL,
before,
root: operand,
xors: Vec::new(),
identities: Vec::new(),
union: IdMap::default(),
ties: false,
};
#[cfg(feature = "prove")]
unions(r, cx, &mut st, operand, &mask)?;
let union = std::mem::take(&mut st.union);
let x2 = simplify(r, cx, &mut st, operand, &mask)?;
if r.demanded.same.marking {
for key in st.memo.keys() {
r.demanded.same.first.insert(key.0, ());
}
}
if st.visits <= st.cap {
for &(key, from, to) in &st.identities {
if r.demanded.same.map.contains_key(&key) {
continue;
}
let at = r.demanded.same.leaves.len();
r.demanded
.same
.leaves
.extend_from_slice(&st.stops[from as usize..to as usize]);
let kept = sorted_distinct(&mut r.demanded.same.leaves[at..]);
r.demanded.same.leaves.truncate(at + kept);
r.demanded.same.map.insert(key, (at as u32, kept as u32));
}
}
st.memo.clear();
let capped = st.visits > st.cap;
if capped {
count(r).atomized += 1;
}
let rebuilt = |r: &mut Runner<'_, '_>, cx: &mut Context, x: u32| {
let mut kids = [node.a, node.b, node.c];
for k in kids.iter_mut().take(node.op.arity()) {
if *k == operand {
*k = x;
}
}
r.build(cx, |cx| cx.rebuild(n, kids))
};
let (mut x2, mut fin, mut stops) = (x2, st.fin, std::mem::take(&mut st.stops));
let mut tie = st.ties;
if !union.is_empty() && !capped {
let mut st2 = Demand {
base: Memo::default(),
whole: None,
whole_sums: false,
memo: std::mem::take(&mut st.memo),
cap: st.cap,
stops: Vec::new(),
visits: 0,
fin: Fin::FINAL,
before,
root: operand,
xors: Vec::new(),
identities: Vec::new(),
union,
ties: false,
};
let x3 = simplify(r, cx, &mut st2, operand, &mask)?;
st2.memo.clear();
st.memo = std::mem::take(&mut st2.memo);
if x3 != x2 && st2.visits <= st2.cap {
let (e2, e3) = (rebuilt(r, cx, x2)?, rebuilt(r, cx, x3)?);
let m2 = super::margin(r, cx, n, e2, &stops)?;
let m3 = super::margin(r, cx, n, e3, &st2.stops)?;
if m3.is_some_and(|b| m2.is_none_or(|a| b >= a)) {
(x2, fin, stops, tie) = (x3, st2.fin, st2.stops, st2.ties);
}
}
let keep = rebuilt(r, cx, x2)?;
super::discard_but(r, cx, before, keep);
}
r.demanded.memo = std::mem::take(&mut st.memo);
if x2 == operand {
count(r).noop += 1;
return Ok(Step::Normal(fin));
}
let e = rebuilt(r, cx, x2)?;
r.explain_with(|| crate::engine::Explanation::Demanded {
operand: cx.handle(operand),
mask,
});
super::finish_with(r, cx, PassKind::Demanded, n, e, before, &stops, fin, tie)
}
#[derive(Default)]
pub(crate) struct State {
pub(crate) memo: Memo,
pub(crate) same: Same,
#[cfg(feature = "mba")]
pub(crate) reduced: [Memo; 2],
pub(crate) sum_constants: IdMap<(u32, u8), Vec<u32>>,
}