use super::{Fin, PassKind, Runner, Step, Stop, finish_within};
use crate::Width;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::prove::{self, Outcome, Unknown};
const MAX_CONE: usize = 512;
const MAX_PROOFS: usize = 2;
const MAX_AIG_NODES: usize = 1 << 15;
const PROPAGATIONS: u64 = 1 << 17;
const MAX_UNDECIDED: u32 = 8;
const PROPAGATION_RATE: u64 = 4;
fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
r.stats.passes.entry(PassKind::Carries.name()).or_default()
}
fn word(op: OpCode) -> bool {
matches!(
op,
OpCode::Add
| OpCode::Sub
| OpCode::Mul
| OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Neg
| OpCode::Not
)
}
fn cone(cx: &Context, n: u32) -> (Vec<u32>, Vec<u16>, bool) {
let mut nodes = vec![n];
let mut seen = crate::hash::IdMap::default();
seen.insert(n, ());
let mut cuts: Vec<u16> = Vec::new();
let mut compares = false;
let mut at = 0;
while at < nodes.len() && nodes.len() < MAX_CONE {
let i = nodes[at];
at += 1;
let node = cx.node(i);
compares |= node.op == OpCode::Ult;
match node.op {
OpCode::Extract => cuts.extend([node.b as u16, node.b as u16 + node.width]),
OpCode::Shl | OpCode::LShr => {
if let Some(k) = cx.const_val(node.b).and_then(|k| k.to_u64()) {
cuts.extend(u16::try_from(k).ok());
}
}
OpCode::And if node.width <= 64 => {
for c in [node.a, node.b] {
if let Some(m) = cx.const_val(c).map(|m| m.limbs()[0]) {
let k = m.trailing_ones();
if k > 0 && k < u32::from(node.width) && m >> k == 0 {
cuts.push(k as u16);
}
}
}
}
_ => {}
}
for c in node.children() {
if seen.insert(c, ()).is_none() {
nodes.push(c);
}
}
}
cuts.retain(|&k| k > 0 && k < 64);
cuts.sort_unstable();
cuts.dedup();
let mut offsets = cuts.clone();
for (x, &a) in cuts.iter().enumerate() {
offsets.extend(cuts[x..].iter().map(|&b| a + b).filter(|&k| k < 64));
}
offsets.sort_unstable();
offsets.dedup();
(nodes, offsets, compares)
}
fn holds_compare(cx: &Context, i: u32, memo: &mut crate::hash::IdMap<u32, bool>) -> bool {
if let Some(&v) = memo.get(&i) {
return v;
}
memo.insert(i, false);
let node = cx.node(i);
let v = node.op == OpCode::Ult || node.children().any(|c| holds_compare(cx, c, memo));
memo.insert(i, v);
v
}
fn proved(
r: &mut Runner<'_, '_>,
cx: &Context,
n: u32,
b: u32,
o: u16,
j: u16,
) -> Result<Result<bool, Fin>, Stop> {
let left = r.meter.left_in(|b| b.pass_work);
let propagations =
PROPAGATIONS.min(left.saturating_sub(MAX_AIG_NODES as u64) / PROPAGATION_RATE);
if propagations == 0 {
return Ok(Err(Fin::capped(crate::engine::Exhausted::PassWork)));
}
let (proofs, undecided) = r.carries.fits;
if undecided >= MAX_UNDECIDED + proofs {
return Ok(Err(Fin::PROVISIONAL));
}
let mut scx = Context::new();
let both = match scx.import(cx, &[cx.handle(n), cx.handle(b)]) {
Ok(both) => both,
Err(crate::Error::Unsupported(_)) => return Ok(Ok(false)),
Err(e) => return Err(Stop::Error(e)),
};
count(r).proofs += 1;
let jw = Width::new(j).map_err(|e| Stop::Error(e.into()))?;
let lhs = scx.extract(both[0], 0, jw).map_err(Stop::Error)?;
let rhs = scx.extract(both[1], o, jw).map_err(Stop::Error)?;
let cfg = prove::Config::default()
.with_simplify(false)
.with_certificate(false)
.with_samples(256)
.with_max_nodes(MAX_AIG_NODES)
.with_max_conflicts(u64::MAX)
.with_max_propagations(propagations);
let mut q = prove::Question::equal(&mut scx, lhs, rhs, &cfg).map_err(Stop::Error)?;
let out = q.solve(&mut scx, cfg.limits()).map_err(Stop::Error)?;
let stats = q.stats();
let nodes = match &out {
Outcome::Unknown(Unknown::TooLarge { nodes }) => *nodes,
_ => stats.nodes,
};
let cost = (nodes as u64)
.saturating_add(stats.propagations.saturating_mul(PROPAGATION_RATE))
.min(left);
r.meter.charge(Counter::PassWork, cost)?;
let c = count(r);
Ok(match out {
Outcome::Proved(_) => {
c.proved += 1;
r.carries.fits.0 += 1;
Ok(true)
}
Outcome::Refuted(_) => {
c.refuted += 1;
Ok(false)
}
Outcome::Unknown(Unknown::Budget { .. }) if propagations < PROPAGATIONS => {
c.unknown += 1;
Err(Fin::capped(crate::engine::Exhausted::PassWork))
}
Outcome::Unknown(_) => {
c.unknown += 1;
r.carries.fits.1 += 1;
Ok(false)
}
})
}
pub(super) fn held(cx: &mut Context, e: u32, w: u16, k: u16) -> Result<u32, crate::Error> {
let e = cx.c_zext(e, w)?;
if k == 0 {
return Ok(e);
}
let by = cx.mk_const(&crate::BitVec::wrapping_from_u64(
Width::new(w)?,
u64::from(k),
))?;
cx.c_bin(crate::ops::BinOp::Shl, e, by)
}
pub(super) fn fitted(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
s: u32,
j: u16,
k: u16,
) -> Result<Result<Step, Fin>, Stop> {
let w = cx.wid(n);
let ws = cx.wid(s);
if j == 0 || j > ws || w > 64 || ws > 64 || r.carries.unfit.contains_key(&n) {
return Ok(Err(Fin::FINAL));
}
let (nodes, offsets, compares) = cone(cx, s);
r.meter.charge(Counter::PassWork, nodes.len() as u64)?;
if !compares {
return Ok(Err(Fin::FINAL));
}
r.sample(cx, s)?;
let jw = Width::new(j).map_err(|e| Stop::Error(e.into()))?;
let own: Vec<_> = r.samples[&s]
.iter()
.map(|v| v.extract(0, jw).ok())
.collect();
let direct = if n == s {
cx.node(n).children().collect::<Vec<_>>()
} else {
vec![s]
};
let mut fits: Vec<(bool, u32, u32, u16)> = Vec::new();
let mut memo = crate::hash::IdMap::default();
for &b in &nodes {
let bw = cx.wid(b);
if b == n || !word(cx.node(b).op) || bw > 64 {
continue;
}
let Some(of) = r.samples.get(&b) else {
continue;
};
for &o in core::iter::once(&0).chain(&offsets) {
if u32::from(o) + u32::from(j) > u32::from(bw) || (o == 0 && direct.contains(&b)) {
continue;
}
if of
.iter()
.zip(&own)
.all(|(v, x)| v.extract(o, jw).ok() == *x)
{
let tree = cx.meta[b as usize].tree;
fits.push((holds_compare(cx, b, &mut memo), tree, b, o));
}
}
}
fits.sort_unstable_by(|x, y| {
(x.0, x.1)
.cmp(&(y.0, y.1))
.then_with(|| cx.order(x.2, y.2))
.then(x.3.cmp(&y.3))
});
let mut fin = Fin::FINAL;
for &(_, _, b, o) in fits.iter().take(MAX_PROOFS) {
match proved(r, cx, s, b, o, j)? {
Ok(true) => {
let before = cx.len() as u32;
let e = r.build(cx, |cx| {
let e = cx.c_extract(b, o, j)?;
held(cx, e, w, k)
})?;
let step = finish_within(r, cx, PassKind::Carries, n, e, before, &[b], fin, 2)?;
return Ok(Ok(step));
}
Ok(false) => {}
Err(more) => fin = fin.and(more),
}
}
if fin.done {
r.carries.unfit.insert(n, ());
}
Ok(Err(fin))
}