use super::{Fin, PassKind, Runner, Step, Stop, disjoint, finish, worth_building};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, Node, OpCode};
use crate::facts::known::count_ones;
use crate::ops::{BinOp, UnOp};
pub(crate) const MAX_TERMS: usize = 64;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Form {
konst: BitVec,
terms: Vec<(u32, BitVec)>,
pub(super) fin: Fin,
}
impl super::forms::Parts for Form {
fn parts(&self) -> (&BitVec, &[(u32, BitVec)], Fin) {
(&self.konst, &self.terms, self.fin)
}
fn from_parts(konst: BitVec, terms: Vec<(u32, BitVec)>, fin: Fin) -> Form {
Form { konst, terms, fin }
}
}
impl super::forms::Sum for Form {
fn join(a: &BitVec, b: &BitVec) -> BitVec {
BitVec::bin_unchecked(BinOp::Add, a, b)
}
fn scale(outer: &BitVec, inner: &BitVec) -> BitVec {
BitVec::bin_unchecked(BinOp::Mul, outer, inner)
}
}
impl Form {
pub(super) fn of(konst: BitVec, terms: &[(u32, BitVec)]) -> Form {
let mut f = Form {
konst,
terms: Vec::new(),
fin: Fin::FINAL,
};
let w = konst.width();
for &(a, k) in terms {
let t = Form {
konst: BitVec::zero(w),
terms: if k.is_zero() {
Vec::new()
} else {
vec![(a, k)]
},
fin: Fin::FINAL,
};
f = f.add(&t);
}
f
}
fn atom(n: u32, w: crate::Width) -> Form {
Form {
konst: BitVec::zero(w),
terms: vec![(n, BitVec::one(w))],
fin: Fin::FINAL,
}
}
pub(super) fn is_atom_of(&self, n: u32) -> bool {
self.konst.is_zero()
&& self.terms.len() == 1
&& self.terms[0].0 == n
&& self.terms[0].1 == BitVec::one(self.konst.width())
}
fn scale(&self, k: &BitVec) -> Form {
let terms = self
.terms
.iter()
.map(|(a, c)| (*a, BitVec::bin_unchecked(BinOp::Mul, c, k)))
.filter(|(_, c)| !c.is_zero())
.collect();
Form {
konst: BitVec::bin_unchecked(BinOp::Mul, &self.konst, k),
terms,
fin: self.fin,
}
}
fn add(&self, o: &Form) -> Form {
let mut terms = Vec::with_capacity(self.terms.len() + o.terms.len());
let (mut i, mut j) = (0, 0);
while i < self.terms.len() || j < o.terms.len() {
let pick = match (self.terms.get(i), o.terms.get(j)) {
(Some(a), Some(b)) if a.0 == b.0 => {
let c = BitVec::bin_unchecked(BinOp::Add, &a.1, &b.1);
i += 1;
j += 1;
(a.0, c)
}
(Some(a), Some(b)) if a.0 < b.0 => {
i += 1;
*a
}
(Some(a), None) => {
i += 1;
*a
}
(_, Some(b)) => {
j += 1;
*b
}
(None, None) => break,
};
if !pick.1.is_zero() {
terms.push(pick);
}
}
Form {
konst: BitVec::bin_unchecked(BinOp::Add, &self.konst, &o.konst),
terms,
fin: self.fin.and(o.fin),
}
}
pub(super) fn reduce(&self, j: crate::Width) -> Form {
let w = self.konst.width();
let low = |v: &BitVec| v.trunc(j).and_then(|t| t.sext(w)).unwrap_or(*v);
let terms: Vec<(u32, BitVec)> = self.terms.iter().map(|&(a, k)| (a, low(&k))).collect();
let mut f = Form::of(low(&self.konst), &terms);
f.fin = self.fin;
f
}
fn neg(&self) -> Form {
let w = self.konst.width();
self.scale(&BitVec::ones(w))
}
}
pub(super) fn estimate(form: &Form) -> u32 {
count(&plan(form, &form.terms))
}
struct Plan {
konst: BitVec,
terms: Vec<(u32, BitVec, bool)>,
not: bool,
}
fn count(plan: &Plan) -> u32 {
let (konst, terms) = (&plan.konst, &plan.terms);
let w = konst.width();
let one = BitVec::one(w);
let t = terms.len() as u32;
let scaled = terms
.iter()
.filter(|(_, k, _)| *k != one && BitVec::un_unchecked(UnOp::Neg, k) != one)
.count() as u32;
let nots = terms.iter().filter(|(_, _, not)| *not).count() as u32;
let minus_one = BitVec::ones(w);
let negation = t > 0 && terms.iter().all(|(_, k, _)| *k == minus_one);
let konst = match (t, konst.is_zero()) {
(0, _) => 1,
(_, true) => u32::from(negation),
_ => 2,
};
2 * scaled + t.saturating_sub(1) + nots + konst + u32::from(plan.not)
}
fn plan(form: &Form, order: &[(u32, BitVec)]) -> Plan {
let w = form.konst.width();
let neg = |k: &BitVec| BitVec::un_unchecked(UnOp::Neg, k);
let one = BitVec::one(w);
let mut konst = form.konst;
let mut terms: Vec<(u32, BitVec, bool)> = order.iter().map(|&(a, k)| (a, k, false)).collect();
let pow2 = !konst.msb() && count_ones(&konst) == 1 && konst != one;
if (konst.msb() || pow2)
&& let Some(t) = terms.iter_mut().find(|(_, k, _)| *k == konst)
{
t.1 = neg(&t.1);
t.2 = true;
konst = BitVec::zero(w);
}
let base = Plan {
konst,
terms,
not: false,
};
let plain: Vec<(u32, BitVec, bool)> = order.iter().map(|&(a, k)| (a, k, false)).collect();
let mut best = base;
let consider = |p: Plan, best: &mut Plan| {
if count(&p) < count(best) {
*best = p;
}
};
if form.konst == one {
if plain.len() >= 2
&& let Some(i) = plain.iter().position(|(_, k, _)| *k == one)
{
let mut t = plain.clone();
t[i] = (t[i].0, neg(&one), true);
consider(
Plan {
konst: BitVec::zero(w),
terms: t,
not: false,
},
&mut best,
);
}
let two = BitVec::wrapping_from_u64(w, 2);
if let Some(i) = plain.iter().position(|(_, k, _)| *k == two) {
let mut t = plain.clone();
let a = t[i].0;
t[i] = (a, one, false);
t.push((a, neg(&one), true));
consider(
Plan {
konst: BitVec::zero(w),
terms: t,
not: false,
},
&mut best,
);
}
}
if form.konst == BitVec::ones(w) && !plain.is_empty() {
consider(
Plan {
konst: BitVec::zero(w),
terms: plain.iter().map(|&(a, k, _)| (a, neg(&k), false)).collect(),
not: true,
},
&mut best,
);
}
best
}
fn linear_op(op: OpCode) -> bool {
matches!(
op,
OpCode::Add
| OpCode::Sub
| OpCode::Neg
| OpCode::Not
| OpCode::Mul
| OpCode::Shl
| OpCode::Or
| OpCode::Xor
| OpCode::Const
| OpCode::Concat
)
}
pub(super) fn form_of(r: &mut Runner<'_, '_>, cx: &mut Context, root: u32) -> Result<Form, Stop> {
let mut stack: Vec<(u32, bool)> = vec![(root, false)];
while let Some((i, expanded)) = stack.pop() {
if r.linear.contains(i) {
continue;
}
let node = cx.node(i);
if !linear_op(node.op) {
r.linear.insert(i, Form::atom(i, cx.width_of(i)));
continue;
}
if !expanded {
stack.push((i, true));
for c in node.children() {
if !r.linear.contains(c) {
stack.push((c, false));
}
}
continue;
}
r.meter.charge(Counter::PassWork, 1)?;
let (f, met) = compute(r, cx, i)?;
if f.terms.len() <= MAX_TERMS {
r.linear.insert(i, f);
continue;
}
r.stats.passes.entry("linear").or_default().atomized += 1;
let atom = Form {
fin: f.fin,
..Form::atom(i, cx.width_of(i))
};
r.linear.insert(i, atom);
let mut read = 0;
r.linear_whole.keep(i, f, met, &mut read);
r.meter.charge(Counter::PassWork, read / MAX_TERMS as u64)?;
}
Ok(r.linear
.get(root)
.expect("the root's form was just computed"))
}
fn compute(r: &mut Runner<'_, '_>, cx: &mut Context, i: u32) -> Result<(Form, bool), Stop> {
let node = cx.node(i);
let w = cx.width_of(i);
let get =
|r: &Runner<'_, '_>, j: u32| r.linear.get(j).expect("operands' forms are computed first");
let form = match node.op {
OpCode::Const => Form {
konst: cx.const_val(i).unwrap_or(BitVec::zero(w)),
terms: Vec::new(),
fin: Fin::FINAL,
},
OpCode::Add => return sum_of(r, cx, &get(r, node.a), &get(r, node.b)),
OpCode::Sub => return sum_of(r, cx, &get(r, node.a), &get(r, node.b).neg()),
OpCode::Neg => get(r, node.a).neg(),
OpCode::Not => {
let mut f = get(r, node.a).neg();
f.konst = BitVec::bin_unchecked(BinOp::Sub, &f.konst, &BitVec::one(w));
f
}
OpCode::Mul => match (cx.const_val(node.a), cx.const_val(node.b)) {
(Some(k), _) => get(r, node.b).scale(&k),
(_, Some(k)) => get(r, node.a).scale(&k),
_ => Form::atom(i, w),
},
OpCode::Shl => match cx.const_val(node.b) {
Some(k) => {
let one = BitVec::one(w);
let scale = BitVec::bin_unchecked(BinOp::Shl, &one, &k);
get(r, node.a).scale(&scale)
}
None => Form::atom(i, w),
},
OpCode::Concat => {
let hi = cx.node(node.a);
match cx.const_val(node.b) {
Some(c) if hi.op == OpCode::Extract && hi.b == 0 && cx.width_of(hi.a) == w => {
let j = u32::from(cx.width_of(node.b).bits());
let scale = crate::facts::known::bv_shl(&BitVec::one(w), j);
let mut f = Form::atom(hi.a, w).scale(&scale);
let lo = c.zext(w).unwrap_or(BitVec::zero(w));
f.konst = BitVec::bin_unchecked(BinOp::Add, &f.konst, &lo);
f
}
_ => Form::atom(i, w),
}
}
OpCode::Or | OpCode::Xor => {
let (disjoint, fina, finb) = disjoint(r, cx, node.a, node.b)?;
if disjoint {
let (mut f, met) = sum_of(r, cx, &get(r, node.a), &get(r, node.b))?;
f.fin = f.fin.and(fina).and(finb);
return Ok((f, met));
}
Form {
fin: fina.and(finb).unchanged(),
..Form::atom(i, w)
}
}
_ => Form::atom(i, w),
};
Ok((form, false))
}
fn sum_of(r: &mut Runner<'_, '_>, cx: &Context, a: &Form, b: &Form) -> Result<(Form, bool), Stop> {
let f = merge(cx, a.add(b));
let met = f.terms.len() < a.terms.len() + b.terms.len();
let mut read = 0;
let whole = r.linear_whole.meeting(a, b, &f, &mut read);
r.meter.charge(Counter::PassWork, read / MAX_TERMS as u64)?;
Ok(match whole {
Some(whole) if whole.terms.len() <= MAX_TERMS => (merge(cx, whole), true),
Some(whole) => (whole, true),
None => (f, met),
})
}
fn merge(cx: &Context, form: Form) -> Form {
merge_fields(cx, merge_complements(cx, merge_signs(cx, form)))
}
fn merge_fields(cx: &Context, form: Form) -> Form {
let w = form.konst.width();
let mut moves = Vec::new();
for &(a, k) in &form.terms {
let n = cx.node(a);
if n.op != OpCode::LShr {
continue;
}
let Some(j) = cx.const_val(n.b).and_then(|j| j.to_u64()) else {
continue;
};
if j == 0 || j >= u64::from(w.bits()) {
continue;
}
let j = j as u32;
let q = crate::facts::known::bv_lshr(&k, j);
if crate::facts::known::bv_shl(&q, j) != k {
continue;
}
let mask = crate::facts::known::low_mask(w, j);
let low = form.terms.iter().map(|t| t.0).find(|&t| {
let m = cx.node(t);
m.op == OpCode::And && m.a == n.a && cx.const_val(m.b) == Some(mask)
});
if let Some(low) = low {
moves.push((a, k, n.a, low, q));
}
}
if moves.is_empty() {
return form;
}
let fin = form.fin;
let mut f = form;
for (a, k, x, low, q) in moves {
let neg = |v: &BitVec| BitVec::un_unchecked(UnOp::Neg, v);
f = f.add(&Form::of(
BitVec::zero(w),
&[(a, neg(&k)), (x, q), (low, neg(&q))],
));
}
f.fin = fin;
f
}
fn merge_signs(cx: &Context, form: Form) -> Form {
let w = form.konst.width();
let mut moves = Vec::new();
for &(a, k) in &form.terms {
let n = cx.node(a);
if n.op == OpCode::Sext
&& cx.width_of(n.a).bits() == 1
&& let Some(z) = cx.find(&Node::new(OpCode::Zext, w.bits(), n.a, 0, 0))
&& form.terms.binary_search_by_key(&z, |t| t.0).is_ok()
{
let minus_k = BitVec::un_unchecked(UnOp::Neg, &k);
moves.push((a, z, minus_k));
}
}
if moves.is_empty() {
return form;
}
let fin = form.fin;
let mut f = form;
for (a, z, minus_k) in moves {
f = f.add(&Form::of(BitVec::zero(w), &[(a, minus_k), (z, minus_k)]));
}
f.fin = fin;
f
}
fn merge_complements(cx: &Context, form: Form) -> Form {
let w = form.konst.width();
let mut moves = Vec::new();
for &(a, k) in &form.terms {
let n = cx.node(a);
if !matches!(n.op, OpCode::Zext | OpCode::Sext) {
continue;
}
let inner = cx.node(n.a);
if inner.op == OpCode::Not
&& let Some(z) = cx.find(&Node::new(n.op, w.bits(), inner.a, 0, 0))
&& form.terms.binary_search_by_key(&z, |t| t.0).is_ok()
{
let c = if n.op == OpCode::Zext {
crate::facts::known::low_mask(w, u32::from(cx.width_of(n.a).bits()))
} else {
BitVec::ones(w)
};
moves.push((a, z, k, c));
}
}
if moves.is_empty() {
return form;
}
let fin = form.fin;
let mut f = form;
for (a, z, k, c) in moves {
let minus_k = BitVec::un_unchecked(UnOp::Neg, &k);
let kc = BitVec::bin_unchecked(BinOp::Mul, &k, &c);
f = f.add(&Form::of(kc, &[(a, minus_k), (z, minus_k)]));
}
f.fin = fin;
f
}
pub(super) fn emit(r: &mut Runner<'_, '_>, cx: &mut Context, form: &Form) -> Result<u32, Stop> {
let mut order = form.terms.clone();
order.sort_by(|a, b| cx.order(a.0, b.0));
let Plan {
konst,
mut terms,
not: complemented,
} = plan(form, &order);
let w = konst.width();
for (a, _, not) in terms.iter_mut() {
if *not {
let x = *a;
*a = r.build(cx, |cx| cx.c_un(UnOp::Not, x))?;
}
}
terms.sort_by(|a, b| cx.order(a.0, b.0));
let (pos, neg): (Vec<_>, Vec<_>) = terms.into_iter().partition(|(_, k, _)| !k.msb());
let term =
|r: &mut Runner<'_, '_>, cx: &mut Context, a: u32, k: &BitVec| -> Result<u32, Stop> {
r.meter.charge(Counter::PassWork, 1)?;
if *k == BitVec::one(w) {
return Ok(a);
}
if crate::facts::known::count_ones(k) == 1 {
let sh = BitVec::apply_un(UnOp::Ctz, k).map_err(|e| Stop::Error(e.into()))?;
return r.build(cx, |cx| {
let s = cx.mk_const(&sh)?;
cx.c_bin(BinOp::Shl, a, s)
});
}
r.build(cx, |cx| {
let c = cx.mk_const(k)?;
cx.c_bin(BinOp::Mul, a, c)
})
};
let mut acc: Option<u32> = None;
for (a, k, _) in &pos {
let t = term(r, cx, *a, k)?;
acc = Some(match acc {
None => t,
Some(x) => r.build(cx, |cx| cx.c_bin(BinOp::Add, x, t))?,
});
}
let mut konst_left = konst;
let mut first = None;
if acc.is_none() && !neg.is_empty() {
if !konst.is_zero() {
acc = Some(r.build(cx, |cx| cx.mk_const(&konst))?);
konst_left = BitVec::zero(w);
} else if let Some(i) = neg.iter().position(|(_, k, _)| *k != BitVec::ones(w)) {
let (a, k, _) = neg[i];
r.meter.charge(Counter::PassWork, 1)?;
acc = Some(r.build(cx, |cx| {
let c = cx.mk_const(&k)?;
cx.c_bin(BinOp::Mul, a, c)
})?);
first = Some(i);
}
}
for (i, (a, k, _)) in neg.iter().enumerate() {
if first == Some(i) {
continue;
}
let nk = BitVec::un_unchecked(UnOp::Neg, k);
let t = term(r, cx, *a, &nk)?;
acc = Some(match acc {
None => r.build(cx, |cx| cx.c_un(UnOp::Neg, t))?,
Some(x) => r.build(cx, |cx| cx.c_bin(BinOp::Sub, x, t))?,
});
}
r.meter.check()?;
let sum = match acc {
None => r.build(cx, |cx| cx.mk_const(&konst_left)),
Some(x) if konst_left.is_zero() => Ok(x),
Some(x) => r.build(cx, |cx| {
let c = cx.mk_const(&konst_left)?;
cx.c_bin(BinOp::Add, x, c)
}),
}?;
if complemented {
r.build(cx, |cx| cx.c_un(UnOp::Not, sum))
} else {
Ok(sum)
}
}
fn leaves<const N: usize>(cx: &Context, n: u32, op: OpCode) -> Option<([u32; N], usize)> {
let mut out = [0; N];
let mut len = 0;
let mut todo = [0; N];
let mut top = 1;
*todo.first_mut()? = n;
while top > 0 {
top -= 1;
let i = todo[top];
let node = cx.node(i);
if node.op == op {
if len + top + 2 > N {
return None;
}
todo[top] = node.b;
todo[top + 1] = node.a;
top += 2;
} else {
out[len] = i;
len += 1;
}
}
Some((out, len))
}
#[derive(Copy, Clone)]
struct Product {
factors: [u32; MAX_PRODUCT_FACTORS],
len: usize,
}
const MAX_PRODUCT_FACTORS: usize = 8;
fn product(cx: &Context, n: u32) -> Option<Product> {
let (factors, len) = leaves(cx, n, OpCode::Mul)?;
Some(Product { factors, len })
}
#[derive(Copy, Clone)]
struct Sum {
terms: [u32; MAX_SUM_TERMS],
len: usize,
}
const MAX_SUM_TERMS: usize = 16;
fn sum(cx: &Context, n: u32) -> Option<Sum> {
let (terms, len) = leaves(cx, n, OpCode::Add)?;
Some(Sum { terms, len })
}
fn common_factor(cx: &Context, products: &[Product]) -> Option<(u32, [usize; MAX_SUM_TERMS])> {
let first = products.first()?;
for constants in [false, true] {
for &factor in &first.factors[..first.len] {
if cx.is_const(factor) != constants {
continue;
}
let mut positions = [0; MAX_SUM_TERMS];
let mut found = true;
for (i, p) in products.iter().enumerate() {
let Some(j) = p.factors[..p.len].iter().position(|&x| x == factor) else {
found = false;
break;
};
positions[i] = j;
}
if found {
return Some((factor, positions));
}
}
}
None
}
fn complementary_products(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
products: &[Product],
) -> Result<Option<Step>, Stop> {
let [left, right] = products else {
return Ok(None);
};
let mut used = [false; MAX_PRODUCT_FACTORS];
let mut common = [0; MAX_PRODUCT_FACTORS];
let mut common_len = 0;
let mut left_only = None;
for &factor in &left.factors[..left.len] {
if let Some(i) = right.factors[..right.len]
.iter()
.enumerate()
.position(|(i, other)| !used[i] && *other == factor)
{
used[i] = true;
common[common_len] = factor;
common_len += 1;
} else if left_only.replace(factor).is_some() {
return Ok(None);
}
}
let mut right_only = None;
for (i, &factor) in right.factors[..right.len].iter().enumerate() {
if !used[i] && right_only.replace(factor).is_some() {
return Ok(None);
}
}
let Some((a, b)) = left_only.zip(right_only) else {
return Ok(None);
};
let complements = (cx.node(a).op == OpCode::Not && cx.node(a).a == b)
|| (cx.node(b).op == OpCode::Not && cx.node(b).a == a);
if !complements {
return Ok(None);
}
let before = cx.len() as u32;
let mut shared = match common[..common_len].split_first() {
Some((&first, rest)) => {
let mut out = first;
for &factor in rest {
out = r.build(cx, |cx| cx.c_bin(BinOp::Mul, out, factor))?;
}
out
}
None => {
let one = BitVec::one(cx.width_of(n));
r.build(cx, |cx| cx.mk_const(&one))?
}
};
shared = r.build(cx, |cx| cx.c_un(UnOp::Neg, shared))?;
let mut atoms = [0; MAX_PRODUCT_FACTORS * 2];
let mut count = 0;
for product in products {
for &factor in &product.factors[..product.len] {
if !atoms[..count].contains(&factor) {
atoms[count] = factor;
count += 1;
}
}
}
Ok(Some(finish(
r,
cx,
PassKind::Linear,
n,
shared,
before,
&atoms[..count],
Fin::FINAL,
)?))
}
fn without_factor(
r: &mut Runner<'_, '_>,
cx: &mut Context,
p: &Product,
skip: usize,
) -> Result<u32, Stop> {
if p.len == 1 {
let one = BitVec::one(cx.width_of(p.factors[0]));
return r.build(cx, |cx| cx.mk_const(&one));
}
let first = usize::from(skip == 0);
let mut out = p.factors[first];
for (i, &f) in p.factors[..p.len].iter().enumerate() {
if i == skip || i == first {
continue;
}
out = r.build(cx, |cx| cx.c_bin(BinOp::Mul, out, f))?;
}
Ok(out)
}
fn factor_sum(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Option<Step>, Stop> {
let Some(sum) = sum(cx, n) else {
return Ok(None);
};
if sum.len < 2 {
return Ok(None);
}
let mut products = [Product {
factors: [0; MAX_PRODUCT_FACTORS],
len: 0,
}; MAX_SUM_TERMS];
for (slot, &term) in products.iter_mut().zip(&sum.terms[..sum.len]) {
let Some(p) = product(cx, term) else {
return Ok(None);
};
*slot = p;
}
let products = &products[..sum.len];
if let Some(step @ Step::To(..)) = complementary_products(r, cx, n, products)? {
return Ok(Some(step));
}
let Some((factor, positions)) = common_factor(cx, products) else {
return Ok(None);
};
let before = cx.len() as u32;
let mut rest = None;
for (i, p) in products.iter().enumerate() {
let q = without_factor(r, cx, p, positions[i])?;
rest = Some(match rest {
None => q,
Some(a) => r.build(cx, |cx| cx.c_bin(BinOp::Add, a, q))?,
});
}
let Some(rest) = rest else {
return Ok(None);
};
let factored = r.build(cx, |cx| cx.c_bin(BinOp::Mul, factor, rest))?;
let mut atoms = [0; MAX_PRODUCT_FACTORS * MAX_SUM_TERMS];
let mut count = 0;
for p in products {
for a in &p.factors[..p.len] {
if !atoms[..count].contains(a) {
atoms[count] = *a;
count += 1;
}
}
}
Ok(Some(finish(
r,
cx,
PassKind::Linear,
n,
factored,
before,
&atoms[..count],
Fin::FINAL,
)?))
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
let op = cx.node(n).op;
if let Some(step @ Step::To(..)) = factor_sum(r, cx, n)? {
return Ok(step);
}
let before = cx.len() as u32;
if let Some((e, f)) = super::cases::split(r, cx, n)?
&& let Step::To(x, fin) = finish(r, cx, PassKind::Linear, n, e, before, &[], f)?
{
return Ok(Step::To(x, fin));
}
if !linear_op(op) || op == OpCode::Const {
return Ok(Step::Normal(Fin::FINAL));
}
let sorted = match op {
OpCode::Mul => match super::sort_chain(r, cx, PassKind::Linear, n)? {
Step::Normal(f) => f,
step => return Ok(step),
},
_ => Fin::FINAL,
};
let form = form_of(r, cx, n)?;
if form.is_atom_of(n) {
return match r.linear_whole.met(n) {
Some(whole) => plain(r, cx, n, whole),
None => Ok(Step::Normal(form.fin.and(sorted))),
};
}
let merged = match super::conditions::step(r, cx, n, &form)? {
Ok(s) => return Ok(s),
Err(f) => f,
};
Ok(match plain(r, cx, n, form)? {
Step::Normal(f) => Step::Normal(f.and(merged)),
s => s,
})
}
fn plain(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32, form: Form) -> Result<Step, Stop> {
let mut atoms: Vec<u32> = form.terms.iter().map(|t| t.0).collect();
atoms.sort_unstable();
let estimate = estimate(&form);
if !form.terms.is_empty()
&& let Some(f) = worth_building(r, cx, n, &atoms, estimate)?
{
r.stats.passes.entry("linear").or_default().rejected_cost += 1;
return Ok(Step::Normal(form.fin.and(f)));
}
let before = cx.len() as u32;
let e = emit(r, cx, &form)?;
r.explain_with(|| crate::engine::Explanation::Linear {
konst: form.konst,
terms: form.terms.iter().map(|&(a, k)| (cx.handle(a), k)).collect(),
});
finish(r, cx, PassKind::Linear, n, e, before, &atoms, form.fin)
}
#[cfg(feature = "mba")]
pub(super) fn by_groups(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
part: &mut impl FnMut(&mut Runner<'_, '_>, &mut Context, u32) -> Result<Option<u32>, Stop>,
) -> Result<Option<Step>, Stop> {
if !matches!(cx.node(n).op, OpCode::Add | OpCode::Sub) {
return Ok(None);
}
let form = form_of(r, cx, n)?;
if form.terms.len() < 3 {
return Ok(None);
}
let mut sets = Vec::with_capacity(form.terms.len());
for &(a, _) in &form.terms {
match bitwise_atoms(cx, a) {
Some(s) => sets.push(s),
None => return Ok(None),
}
}
fn find(up: &mut [usize], mut i: usize) -> usize {
while up[i] != i {
up[i] = up[up[i]];
i = up[i];
}
i
}
let k = sets.len();
let mut up: Vec<usize> = (0..k).collect();
for i in 0..k {
for j in i + 1..k {
if sets[i].iter().any(|l| sets[j].binary_search(l).is_ok()) {
let (a, b) = (find(&mut up, i), find(&mut up, j));
up[a.max(b)] = a.min(b);
}
}
}
let mut groups: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
for i in 0..k {
let g = find(&mut up, i);
groups.entry(g).or_default().push(i);
}
if groups.len() < 2 || groups.values().all(|g| g.len() < 2) {
return Ok(None);
}
let w = form.konst.width();
let before = cx.len() as u32;
let mut total = Form::of(form.konst, &[]);
let mut fin = form.fin;
let mut changed = false;
for idx in groups.values() {
let terms: Vec<(u32, BitVec)> = idx.iter().map(|&i| form.terms[i]).collect();
let mut f = Form::of(BitVec::zero(w), &terms);
if idx.len() >= 2 {
let s = emit(r, cx, &f)?;
if let Some(e) = part(r, cx, s)?
&& e != s
{
f = form_of(r, cx, e)?;
fin = fin.and(f.fin);
changed = true;
}
}
total = total.add(&f);
}
if !changed {
super::discard(r, cx, before);
return Ok(None);
}
let e = emit(r, cx, &total)?;
let mut stops = Vec::new();
let mut seen = crate::hash::IdMap::<u32, ()>::default();
let mut todo = vec![e];
while let Some(i) = todo.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
if i < before {
stops.push(i);
} else {
todo.extend(cx.node(i).children());
}
}
finish(r, cx, PassKind::Mba, n, e, before, &stops, fin).map(Some)
}
#[cfg(feature = "mba")]
fn bitwise_atoms(cx: &Context, e: u32) -> Option<Vec<u32>> {
const MAX_SEEN: usize = 512;
let bitwise = |op: OpCode| matches!(op, OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Not);
if !bitwise(cx.node(e).op) {
return Some(vec![e]);
}
let mut seen = crate::hash::IdMap::<u32, ()>::default();
let mut out = Vec::new();
let mut todo = vec![e];
while let Some(i) = todo.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
if seen.len() > MAX_SEEN {
return None;
}
let node = cx.node(i);
if bitwise(node.op) {
todo.extend(node.children());
} else if node.op != OpCode::Const {
out.push(i);
}
}
out.sort_unstable();
out.dedup();
Some(out)
}
#[cfg(feature = "mba")]
pub(super) fn by_sums(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
part: &mut impl FnMut(&mut Runner<'_, '_>, &mut Context, u32) -> Result<Option<u32>, Stop>,
) -> Result<Option<Step>, Stop> {
if !matches!(cx.node(n).op, OpCode::Add | OpCode::Sub) {
return Ok(None);
}
let form = form_of(r, cx, n)?;
let mut sums: Vec<u32> = Vec::new();
for &(t, _) in &form.terms {
if !matches!(cx.node(t).op, OpCode::And | OpCode::Or | OpCode::Xor) {
continue;
}
for a in bitwise_atoms(cx, t).unwrap_or_default() {
if matches!(cx.node(a).op, OpCode::Add | OpCode::Sub) && !sums.contains(&a) {
sums.push(a);
}
}
}
let w = form.konst.width();
let one = BitVec::one(w);
let minus_one = BitVec::ones(w);
let mut konst = form.konst;
let mut terms = form.terms.clone();
let mut changed = false;
for a in sums {
let fa = form_of(r, cx, a)?;
if fa.terms.len() < 2 || fa.terms.iter().any(|(_, k)| *k != one && *k != minus_one) {
continue;
}
let coeff = |terms: &[(u32, BitVec)], atom: u32| {
terms
.binary_search_by_key(&atom, |t| t.0)
.ok()
.map(|i| terms[i].1)
};
let (t0, k0) = fa.terms[0];
let Some(c0) = coeff(&terms, t0) else {
continue;
};
let c = if k0 == one {
c0
} else {
BitVec::un_unchecked(UnOp::Neg, &c0)
};
let scaled = |k: &BitVec| BitVec::bin_unchecked(BinOp::Mul, &c, k);
if !fa
.terms
.iter()
.all(|(t, k)| coeff(&terms, *t) == Some(scaled(k)))
{
continue;
}
let mut rest: Vec<(u32, BitVec)> = terms
.iter()
.filter(|(t, _)| fa.terms.binary_search_by_key(t, |x| x.0).is_err())
.copied()
.collect();
rest.push((a, c));
konst = BitVec::bin_unchecked(BinOp::Sub, &konst, &scaled(&fa.konst));
let f = Form::of(konst, &rest);
terms = f.terms.clone();
konst = f.konst;
changed = true;
}
if !changed {
return Ok(None);
}
let before = cx.len() as u32;
let s = emit(r, cx, &Form::of(konst, &terms))?;
let e = part(r, cx, s)?.unwrap_or(s);
let mut stops = Vec::new();
let mut seen = crate::hash::IdMap::<u32, ()>::default();
let mut todo = vec![e];
while let Some(i) = todo.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
if i < before {
stops.push(i);
} else {
todo.extend(cx.node(i).children());
}
}
finish(r, cx, PassKind::Mba, n, e, before, &stops, form.fin).map(Some)
}