use super::{Fin, Runner, Stop, linear};
use crate::BitVec;
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
use crate::ops::CmpOp;
fn mask_in(cx: &Context, n: u32) -> Option<(u32, Option<u32>)> {
let is_mask = |m: u32| -> Option<(u32, Option<u32>)> {
let node = cx.node(m);
if node.width < 2 {
return None;
}
match node.op {
OpCode::Sext if cx.wid(node.a) == 1 => Some((m, Some(node.a))),
OpCode::Neg => {
let z = cx.node(node.a);
(z.op == OpCode::Zext && cx.wid(z.a) == 1).then_some((m, Some(z.a)))
}
OpCode::AShr => (cx.const_val(node.b).and_then(|v| v.to_u64())
== Some(u64::from(node.width) - 1))
.then_some((m, None)),
_ => None,
}
};
let node = cx.node(n);
for c in node.children() {
if let Some(m) = is_mask(c) {
return Some(m);
}
for g in cx.node(c).children() {
if let Some(m) = is_mask(g) {
return Some(m);
}
}
}
None
}
pub(super) fn split(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
) -> Result<Option<(u32, Fin)>, Stop> {
let node = cx.node(n);
if node.width < 2
|| !matches!(
node.op,
OpCode::Add | OpCode::Sub | OpCode::Xor | OpCode::Or | OpCode::And
)
{
return Ok(None);
}
let Some((m, cond)) = mask_in(cx, n) else {
return Ok(None);
};
let mut fin = Fin::FINAL;
let mut arm = |r: &mut Runner<'_, '_>, cx: &mut Context, v: BitVec| -> Result<u32, Stop> {
let k = r.build(cx, |cx| cx.mk_const(&v))?;
let mut repl: IdMap<u32, u32> = IdMap::default();
repl.insert(m, k);
let e = r.build(cx, |cx| Ok(cx.substitute_ids(&[n], &repl)?[0]))?;
if !matches!(
cx.node(e).op,
OpCode::Add | OpCode::Sub | OpCode::Neg | OpCode::Not | OpCode::Xor | OpCode::Or
) {
return Ok(e);
}
let form = linear::form_of(r, cx, e)?;
fin = fin.and(form.fin);
if form.is_atom_of(e) {
return Ok(e);
}
linear::emit(r, cx, &form)
};
let mw = cx.width_of(m);
let e1 = arm(r, cx, BitVec::ones(mw))?;
let e0 = arm(r, cx, BitVec::zero(mw))?;
let c = match cond {
Some(c) => c,
None => {
let x = cx.node(m).a;
r.build(cx, |cx| {
let z = cx.mk_const(&BitVec::zero(mw))?;
cx.c_cmp(CmpOp::Slt, x, z)
})?
}
};
let s = r.build(cx, |cx| cx.c_select(c, e1, e0))?;
Ok(Some((s, fin)))
}
#[cfg(feature = "mba")]
const CASE_NODES: usize = 48;
#[cfg(feature = "mba")]
const SIDE_DEPTH: u32 = 3;
#[cfg(feature = "mba")]
fn related(cx: &Context, a: u32, b: u32) -> bool {
let below = |root: u32| {
let mut out: Vec<u32> = Vec::new();
let mut stack = vec![(root, 0u32)];
while let Some((i, d)) = stack.pop() {
if cx.const_val(i).is_some() || out.contains(&i) {
continue;
}
out.push(i);
if d < SIDE_DEPTH {
stack.extend(cx.node(i).children().map(|c| (c, d + 1)));
}
}
out
};
let seen = below(a);
below(b).iter().any(|i| seen.contains(i))
}
#[cfg(feature = "mba")]
pub(super) fn by_cases(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
part: &mut impl FnMut(&mut Runner<'_, '_>, &mut Context, u32) -> Result<Option<u32>, Stop>,
) -> Result<Option<super::Step>, Stop> {
let node = cx.node(n);
let scaled_sum = node.op == OpCode::Mul
&& cx.node(node.b).op == OpCode::Const
&& matches!(cx.node(node.a).op, OpCode::Add | OpCode::Sub);
if node.width < 2
|| !(scaled_sum || matches!(
node.op,
OpCode::Add | OpCode::Sub | OpCode::Xor | OpCode::Or | OpCode::And
))
{
return Ok(None);
}
let mut selects: Vec<u32> = Vec::new();
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack: Vec<u32> = node.children().collect();
while let Some(i) = stack.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
if seen.len() > CASE_NODES {
return Ok(None);
}
let m = cx.node(i);
match m.op {
OpCode::Select => selects.push(i),
OpCode::Add
| OpCode::Sub
| OpCode::Neg
| OpCode::Not
| OpCode::And
| OpCode::Or
| OpCode::Xor
| OpCode::Mul
| OpCode::Shl
| OpCode::Zext
| OpCode::Sext
| OpCode::Extract => stack.extend(m.children()),
_ => {}
}
}
let mut found = None;
'pairs: for (i, &s) in selects.iter().enumerate() {
let a = cx.node(s);
for &t in &selects[i + 1..] {
let b = cx.node(t);
if a.a != b.a {
continue;
}
let fixed_then = cx.node(a.b).op == OpCode::Const && cx.node(b.b).op == OpCode::Const;
let fixed_else = cx.node(a.c).op == OpCode::Const && cx.node(b.c).op == OpCode::Const;
if !(fixed_then && fixed_else)
&& (fixed_then || related(cx, a.b, b.b))
&& (fixed_else || related(cx, a.c, b.c))
{
found = Some(a.a);
break 'pairs;
}
}
}
let Some(c) = found else {
return Ok(None);
};
r.meter
.charge(crate::engine::budget::Counter::PassWork, seen.len() as u64)?;
let before = cx.len() as u32;
let mut side =
|r: &mut Runner<'_, '_>, cx: &mut Context, then: bool| -> Result<Option<u32>, Stop> {
let mut repl: IdMap<u32, u32> = IdMap::default();
for &s in &selects {
let m = cx.node(s);
if m.a == c {
repl.insert(s, if then { m.b } else { m.c });
}
}
let e = r.build(cx, |cx| Ok(cx.substitute_ids(&[n], &repl)?[0]))?;
if cx.node(e).op == OpCode::Const {
return Ok(Some(e));
}
part(r, cx, e)
};
let (Some(e1), Some(e0)) = (side(r, cx, true)?, side(r, cx, false)?) else {
super::discard(r, cx, before);
return Ok(None);
};
let e = r.build(cx, |cx| cx.c_select(c, e1, e0))?;
let mut stops = Vec::new();
let mut seen: IdMap<u32, ()> = IdMap::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());
}
}
super::finish(
r,
cx,
super::PassKind::Mba,
n,
e,
before,
&stops,
Fin::FINAL,
)
.map(Some)
}