use std::collections::HashMap;
use vlk_ir::ir::{BinOp, Expr, FunctionIr, Stmt};
pub fn simplify(ir: &mut FunctionIr) {
crate::passes::checked("passes::simplify::simplify", ir, simplify_unchecked)
}
fn simplify_unchecked(ir: &mut FunctionIr) {
let starts: std::collections::HashSet<_> = if ir.isa == vlk_base::target::Isa::Arm32 {
ir.blocks.iter().map(|block| block.start).collect()
} else {
std::collections::HashSet::new()
};
for block in &mut ir.blocks {
let mut constants: HashMap<u16, u64> = HashMap::new();
for stmt in &mut block.stmts {
simplify_stmt(stmt, &mut constants);
if let Stmt::BrIndirect {
target: Expr::Const(target),
at,
} = stmt
&& starts.contains(&vlk_arch::arch::code_address(ir.isa, *target))
{
*stmt = Stmt::Br {
target: Some(vlk_arch::arch::code_address(ir.isa, *target)),
at: *at,
};
}
}
}
}
fn simplify_stmt(stmt: &mut Stmt, constants: &mut HashMap<u16, u64>) {
match stmt {
Stmt::Assign { dest, value, .. } => {
let simplified = simplify_expr(value.clone(), constants);
if let Expr::Const(value) = simplified {
constants.insert(
dest.index,
value & vlk_ir::ir::semantics::mask(u32::from(dest.width)),
);
} else {
constants.remove(&dest.index);
}
*value = simplified;
}
Stmt::Store {
addr, value, width, ..
} => {
*addr = simplify_expr(addr.clone(), constants);
*value = simplify_expr(value.clone(), constants);
let kept = vlk_ir::ir::semantics::mask(u32::from(*width) * 8);
if let Expr::Bin {
op: BinOp::Or,
lhs,
rhs,
} = value
{
let register_bits = |part: &Expr| {
matches!(part,
Expr::Bin { op: BinOp::And, lhs, rhs }
if matches!(lhs.as_ref(), Expr::Reg { .. })
&& matches!(rhs.as_ref(), Expr::Const(_)))
};
if let Some(low) = outside_mask(lhs, rhs, kept)
.filter(|_| register_bits(lhs))
.or_else(|| outside_mask(rhs, lhs, kept).filter(|_| register_bits(rhs)))
.cloned()
{
*value = low;
}
}
while let Expr::Bin {
op: vlk_ir::ir::BinOp::And,
lhs,
rhs,
} = value
&& let Expr::Const(mask) = rhs.as_ref()
&& mask & kept == kept
{
*value = lhs.as_ref().clone();
}
}
Stmt::Brif { cond, lhs, rhs, .. } => {
let before = vlk_ir::ir::semantics::operand_width(lhs, rhs);
let original = (lhs.clone(), rhs.clone());
*lhs = simplify_expr(lhs.clone(), constants);
*rhs = simplify_expr(rhs.clone(), constants);
if let Some(width) =
vlk_ir::ir::visit::expr_width(lhs).or_else(|| vlk_ir::ir::visit::expr_width(rhs))
{
cancel_round_trip(lhs, width);
cancel_round_trip(rhs, width);
}
if vlk_ir::ir::semantics::operand_width(lhs, rhs) != before
&& !super::copies::comparison_preserved(*cond, before, lhs, rhs)
&& !widen_compared_constant(lhs, rhs, before)
&& !widen_compared_constant(rhs, lhs, before)
{
(*lhs, *rhs) = original;
}
let bits = vlk_ir::ir::semantics::operand_width(lhs, rhs);
if bits < 64 {
for side in [&mut *lhs, &mut *rhs] {
if let Expr::Const(value) = side {
*value &= vlk_ir::ir::semantics::mask(bits);
}
}
}
if matches!(cond, vlk_ir::ir::Cond::Eq | vlk_ir::ir::Cond::Ne) {
move_offset_across(lhs, rhs);
}
}
Stmt::BrIndirect { target, .. } => {
*target = simplify_expr(target.clone(), constants);
}
Stmt::Switch { index, .. } => {
*index = simplify_expr(index.clone(), constants);
}
Stmt::Ret { value, .. } => {
*value = simplify_expr(value.clone(), constants);
}
Stmt::Call { through, args, .. } => {
if let Some(through) = through {
*through = simplify_expr(through.clone(), constants);
}
for arg in args.iter_mut().flatten() {
*arg = simplify_expr(arg.clone(), constants);
}
constants.clear();
}
Stmt::Machine {
inputs, outputs, ..
} => {
for input in inputs {
*input = simplify_expr(input.clone(), constants);
}
for output in outputs {
constants.remove(&output.index);
}
}
Stmt::Unsupported { .. } => {
constants.clear();
}
Stmt::Br { .. } | Stmt::BrifFlags { .. } | Stmt::Trap { .. } => {}
}
}
fn outside_mask<'e>(kept: &Expr, other: &'e Expr, mask: u64) -> Option<&'e Expr> {
(crate::ssa::ranges::of(kept).possible() & mask == 0).then_some(other)
}
fn cancel_round_trip(expr: &mut Expr, width: u8) {
use vlk_ir::ir::BinOp;
let Expr::Bin { op, lhs, rhs } = &*expr else {
return;
};
let inverse = match op {
BinOp::Add => BinOp::Sub,
BinOp::Sub => BinOp::Add,
_ => return,
};
let mut inner = lhs.as_ref();
if width <= 32
&& let Expr::Bin {
op: BinOp::And,
lhs: masked,
rhs: mask,
} = inner
&& matches!(mask.as_ref(), Expr::Const(0xffff_ffff))
{
inner = masked;
}
if let Expr::Bin {
op: inner_op,
lhs: original,
rhs: offset,
} = inner
&& *inner_op == inverse
&& offset == rhs
{
*expr = original.as_ref().clone();
}
}
fn move_offset_across(lhs: &mut Expr, rhs: &mut Expr) {
let (
Expr::Bin {
op,
lhs: inner,
rhs: offset,
},
Expr::Const(k),
) = (&*lhs, &*rhs)
else {
return;
};
let Expr::Const(displacement) = offset.as_ref() else {
return;
};
let moved = match op {
vlk_ir::ir::BinOp::Add => k.wrapping_sub(*displacement),
vlk_ir::ir::BinOp::Sub => k.wrapping_add(*displacement),
_ => return,
};
let Some(width) = vlk_ir::ir::visit::expr_width(inner) else {
return;
};
let mask = if width >= 64 {
u64::MAX
} else {
(1u64 << width) - 1
};
*rhs = Expr::Const(moved & mask);
*lhs = inner.as_ref().clone();
}
fn simplify_expr(expr: Expr, constants: &HashMap<u16, u64>) -> Expr {
match expr {
Expr::Reg { index, width } => match constants.get(&index) {
Some(value) if width >= 64 => Expr::constant(*value),
Some(value) => Expr::constant(*value & ((1u64 << width) - 1)),
None => Expr::Reg { index, width },
},
Expr::Const(_) => expr,
Expr::Bin { op, lhs, rhs } => {
let bits = vlk_ir::ir::semantics::operand_width(&lhs, &rhs);
let original = matches!(op, BinOp::Sar | BinOp::DivS | BinOp::ModS)
.then(|| (lhs.clone(), rhs.clone()));
let mut simplified_lhs = simplify_expr(*lhs, constants);
let mut simplified_rhs = simplify_expr(*rhs, constants);
if let Some((lhs, rhs)) = original
&& vlk_ir::ir::semantics::operand_width(&simplified_lhs, &simplified_rhs) != bits
{
(simplified_lhs, simplified_rhs) = (*lhs, *rhs);
}
fold_offsets(algebraic(Expr::bin(op, simplified_lhs, simplified_rhs)))
}
Expr::Load {
addr,
width,
signed,
} => Expr::Load {
addr: Box::new(simplify_expr(*addr, constants)),
width,
signed,
},
Expr::SignExtend { value, width } => {
let value = simplify_expr(*value, constants);
let low = vlk_ir::ir::semantics::mask(u32::from(width) * 8);
let value = match &value {
Expr::Bin {
op: vlk_ir::ir::BinOp::Or,
lhs: a,
rhs: b,
} => outside_mask(a, b, low)
.or_else(|| outside_mask(b, a, low))
.cloned()
.unwrap_or(value),
_ => value,
};
let value = match value {
Expr::Bin {
op: vlk_ir::ir::BinOp::And,
lhs,
rhs,
} => match rhs.as_ref() {
Expr::Const(mask)
if *mask == vlk_ir::ir::semantics::mask(u32::from(width) * 8) =>
{
lhs.as_ref().clone()
}
_ => Expr::Bin {
op: vlk_ir::ir::BinOp::And,
lhs,
rhs,
},
},
other => other,
};
Expr::SignExtend {
value: Box::new(value),
width,
}
}
Expr::Select {
cond,
lhs,
rhs,
then,
els,
} => {
let bits = vlk_ir::ir::semantics::operand_width(&lhs, &rhs);
let original = (*lhs.clone(), *rhs.clone());
let mut lhs = simplify_expr(*lhs, constants);
let mut rhs = simplify_expr(*rhs, constants);
let then = simplify_expr(*then, constants);
let els = simplify_expr(*els, constants);
let known = match (&lhs, &rhs) {
(Expr::Const(a), Expr::Const(b)) => {
Some(vlk_ir::ir::semantics::holds(cond, *a, *b, bits))
}
_ if lhs == rhs && matches!(lhs, Expr::Reg { .. }) => {
Some(vlk_ir::ir::semantics::holds(cond, 0, 0, bits))
}
_ => None,
};
if known.is_none()
&& !super::copies::comparison_preserved(cond, bits, &lhs, &rhs)
&& !widen_compared_constant(&lhs, &mut rhs, bits)
&& !widen_compared_constant(&rhs, &mut lhs, bits)
{
(lhs, rhs) = original;
}
match known {
Some(true) => then,
Some(false) => els,
None => Expr::Select {
cond,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
then: Box::new(then),
els: Box::new(els),
},
}
}
Expr::Apply { op, args } => {
let args: Vec<Expr> = args
.into_iter()
.map(|arg| simplify_expr(arg, constants))
.collect();
if let (vlk_ir::ir::Operation::Lanes(lane, _), [a, b]) = (op, args.as_slice())
&& a == b
&& !vlk_ir::ir::visit::reads_memory(a)
&& !vlk_ir::ir::visit::faults(a)
{
use vlk_ir::ir::LaneOp;
match lane {
LaneOp::Equal | LaneOp::GreaterEqualSigned | LaneOp::GreaterEqualUnsigned => {
return Expr::constant(u64::MAX);
}
LaneOp::Sub | LaneOp::GreaterSigned | LaneOp::GreaterUnsigned => {
return Expr::constant(0);
}
_ => {}
}
}
let values: Option<Vec<u64>> = args
.iter()
.map(|arg| match arg {
Expr::Const(value) => Some(*value),
_ => None,
})
.collect();
match values.and_then(|values| vlk_ir::ir::semantics::fold(op, &values)) {
Some(value) => Expr::constant(value),
None => {
let applied = Expr::Apply { op, args };
counted_bits(&applied).unwrap_or(applied)
}
}
}
}
}
fn reassembled(expr: &Expr) -> Option<Expr> {
use vlk_ir::ir::BinOp;
let mut terms = Vec::new();
let mut work = vec![expr];
while let Some(term) = work.pop() {
match term {
Expr::Bin {
op: BinOp::Or,
lhs,
rhs,
} => work.extend([lhs.as_ref(), rhs.as_ref()]),
other => terms.push(other),
}
}
if terms.len() < 2 {
return None;
}
let run = |mask: u64| -> Option<(u32, u32)> {
if mask == 0 {
return None;
}
let low = mask.trailing_zeros();
let ones = (mask >> low).trailing_ones();
(ones == 64 || (mask >> low) >> ones == 0).then_some((low, ones))
};
let field = |term: &Expr| -> Option<(Expr, u32, u32)> {
match term {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} => {
let Expr::Const(mask) = rhs.as_ref() else {
return None;
};
let Some((low, ones)) = run(*mask) else {
return None;
};
Some((lhs.as_ref().clone(), low, ones))
}
Expr::Bin {
op: BinOp::Shl,
lhs,
rhs,
} => {
let (
Expr::Const(up),
Expr::Bin {
op: BinOp::And,
lhs: inner,
rhs: mask,
},
) = (rhs.as_ref(), lhs.as_ref())
else {
return None;
};
let (
Expr::Const(mask),
Expr::Bin {
op: BinOp::Shr,
lhs: source,
rhs: down,
},
) = (mask.as_ref(), inner.as_ref())
else {
return None;
};
let Some((0, ones)) = run(*mask) else {
return None;
};
(matches!(down.as_ref(), Expr::Const(down) if down == up) && *up < 64).then(|| {
(
source.as_ref().clone(),
*up as u32,
ones.min(64 - *up as u32),
)
})
}
_ => None,
}
};
let Some(fields) = terms
.into_iter()
.map(field)
.collect::<Option<Vec<(Expr, u32, u32)>>>()
else {
return None;
};
let source = fields[0].0.clone();
if fields.iter().any(|(value, ..)| *value != source) {
return None;
}
let mut ranges: Vec<(u32, u32)> = fields.iter().map(|(_, low, ones)| (*low, *ones)).collect();
ranges.sort_unstable();
let mut covered = 0;
for (low, ones) in ranges {
if low != covered {
return None;
}
covered += ones;
}
Some(if covered >= 64 {
source
} else {
Expr::bin(BinOp::And, source, Expr::constant((1 << covered) - 1))
})
}
fn counted_bits(expr: &Expr) -> Option<Expr> {
use vlk_ir::ir::{LaneOp, Operation};
let Expr::Apply {
op: Operation::SumLanesLong {
bits: 8,
signed: false,
},
args,
} = expr
else {
return None;
};
let mut counts = Vec::new();
for half in args {
match half {
Expr::Const(0) => {}
Expr::Apply {
op: Operation::Lanes(LaneOp::PopCount, 8),
args,
} => counts.push(Expr::apply(Operation::PopCount(64), vec![args[0].clone()])),
_ => return None,
}
}
counts
.into_iter()
.reduce(|sum, count| Expr::bin(vlk_ir::ir::BinOp::Add, sum, count))
}
fn low32(expr: &Expr) -> &Expr {
match expr {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) && fits32(lhs) => lhs,
other => other,
}
}
fn fits32(expr: &Expr) -> bool {
crate::ssa::ranges::of(expr).hi <= 0xffff_ffff
}
fn magic_divisor(magic: u64, shift: u64) -> Option<u64> {
if magic == 0 || magic > 0xffff_ffff || !(32..64).contains(&shift) {
return None;
}
let power = 1u128 << shift;
let estimate = power / u128::from(magic);
(estimate..=estimate + 1).find_map(|divisor| {
let product = u128::from(magic) * divisor;
(divisor >= 2 && product >= power && product - power <= 1u128 << (shift - 32))
.then_some(divisor as u64)
})
}
fn scaled_register(expr: &Expr) -> Option<(&Expr, u64)> {
match expr {
Expr::Reg { .. } => Some((expr, 1)),
Expr::Bin { op, lhs, rhs } => {
let (value, factor) = match (op, lhs.as_ref(), rhs.as_ref()) {
(BinOp::Mul, value, Expr::Const(factor))
| (BinOp::Mul, Expr::Const(factor), value) => (value, *factor),
(BinOp::Shl, value, Expr::Const(amount)) => (value, 1u64 << (amount & 63)),
_ => return None,
};
let Some((register, scale)) = scaled_register(value) else {
return None;
};
Some((register, scale.wrapping_mul(factor)))
}
_ => None,
}
}
pub fn algebraic(expr: Expr) -> Expr {
if let Expr::Bin {
op: BinOp::Add | BinOp::Sub,
lhs,
rhs,
} = &expr
&& let (Some((left, a)), Some((right, b))) = (scaled_register(lhs), scaled_register(rhs))
&& left == right
{
let scale = if matches!(&expr, Expr::Bin { op: BinOp::Add, .. }) {
a.wrapping_add(b)
} else {
a.wrapping_sub(b)
};
return Expr::bin(BinOp::Mul, left.clone(), Expr::Const(scale));
}
if let Expr::Bin {
op: BinOp::Mul | BinOp::Shl,
lhs,
..
} = &expr
&& matches!(lhs.as_ref(), Expr::Bin { .. })
&& let Some((register, scale)) = scaled_register(&expr)
{
return Expr::bin(BinOp::Mul, register.clone(), Expr::Const(scale));
}
if let Expr::Bin { op, lhs, rhs } = &expr {
let undefined = |expr: &Expr| {
matches!(
expr,
Expr::Apply {
op: vlk_ir::ir::Operation::Undefined,
..
}
)
};
match op {
BinOp::And if undefined(lhs) || undefined(rhs) => {
return Expr::apply(vlk_ir::ir::Operation::Undefined, Vec::new());
}
BinOp::Shl | BinOp::Shr | BinOp::Sar if undefined(lhs) => return lhs.as_ref().clone(),
BinOp::Or if undefined(lhs) => return rhs.as_ref().clone(),
BinOp::Or if undefined(rhs) => return lhs.as_ref().clone(),
_ => {}
}
}
if let Expr::Bin {
op: BinOp::Shr,
lhs,
rhs,
} = &expr
&& let (
Expr::Bin {
op: BinOp::Mul,
lhs: value,
rhs: magic,
},
Expr::Const(shift),
) = (lhs.as_ref(), rhs.as_ref())
&& let Expr::Const(magic) = magic.as_ref()
&& fits32(value)
&& let Some(divisor) = magic_divisor(*magic, *shift)
{
return Expr::bin(BinOp::DivU, value.as_ref().clone(), Expr::Const(divisor));
}
if let Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} = &expr
&& let Expr::Bin {
op: BinOp::Shl,
lhs: shifted,
rhs: amount,
} = rhs.as_ref()
&& let Expr::Const(amount @ 1..=31) = amount.as_ref()
&& low32(shifted) == low32(lhs)
&& matches!(
low32(lhs),
Expr::Bin {
op: BinOp::DivU,
..
}
)
&& fits32(low32(lhs))
{
return Expr::bin(
BinOp::Mul,
low32(lhs).clone(),
Expr::Const((1 << amount) + 1),
);
}
if let Expr::Bin {
op: BinOp::Sub,
lhs,
rhs,
} = &expr
&& let Expr::Bin {
op: BinOp::Mul,
lhs: quotient,
rhs: times,
} = low32(rhs)
&& let Expr::Bin {
op: BinOp::DivU,
lhs: dividend,
rhs: divisor,
} = low32(quotient)
&& times == divisor
&& low32(dividend) == low32(lhs)
{
return Expr::bin(BinOp::ModU, low32(lhs).clone(), divisor.as_ref().clone());
}
if let Expr::Bin {
op: BinOp::Sub,
lhs,
rhs,
} = &expr
&& let Expr::Bin {
op: BinOp::Mul,
lhs: quotient,
rhs: times,
} = rhs.as_ref()
&& let Expr::Bin {
op: op @ (BinOp::DivS | BinOp::DivU),
lhs: dividend,
rhs: divisor,
} = quotient.as_ref()
&& times == divisor
&& dividend == lhs
&& vlk_ir::ir::semantics::width(lhs) == 64
{
let remainder = if *op == BinOp::DivS {
BinOp::ModS
} else {
BinOp::ModU
};
return Expr::bin(remainder, lhs.as_ref().clone(), divisor.as_ref().clone());
}
if let Some(whole) = reassembled(&expr)
&& vlk_ir::ir::semantics::width(&whole) == vlk_ir::ir::semantics::width(&expr)
{
return whole;
}
if let Expr::Bin {
op: BinOp::Or,
lhs,
rhs,
} = &expr
&& let Expr::Bin {
op: BinOp::Shl,
lhs: masked,
rhs: back,
} = rhs.as_ref()
&& let Expr::Bin {
op: BinOp::And,
lhs: shifted,
rhs: mask,
} = masked.as_ref()
&& matches!(mask.as_ref(), Expr::Const(_))
&& let Expr::Bin {
op: BinOp::Shr,
lhs: value,
rhs: out,
} = shifted.as_ref()
&& out == back
{
if value == lhs {
return lhs.as_ref().clone();
}
if let (
Expr::Bin {
op: BinOp::And,
lhs: low_value,
rhs: low,
},
Expr::Const(shift),
Expr::Const(high),
) = (lhs.as_ref(), back.as_ref(), mask.as_ref())
&& let Expr::Const(low) = low.as_ref()
&& *shift > 0
&& *shift < 64
&& low_value == value
&& *low == (1u64 << shift) - 1
&& (high << shift) | low == u64::MAX
{
return value.as_ref().clone();
}
}
let Expr::Bin { op, lhs, rhs } = &expr else {
return expr;
};
let zero = |value: &Expr| matches!(value, Expr::Const(0));
match op {
vlk_ir::ir::BinOp::Sub if zero(lhs) => {
if let Expr::Bin {
op: vlk_ir::ir::BinOp::Sub,
lhs: inner,
rhs: inner_rhs,
} = rhs.as_ref()
&& zero(inner)
{
return inner_rhs.as_ref().clone();
}
expr
}
vlk_ir::ir::BinOp::Sub if zero(rhs) => lhs.as_ref().clone(),
vlk_ir::ir::BinOp::Add if zero(rhs) => lhs.as_ref().clone(),
vlk_ir::ir::BinOp::And
if let (
Expr::Load {
width,
signed: false,
..
},
Expr::Const(mask),
) = (lhs.as_ref(), rhs.as_ref())
&& *mask == vlk_ir::ir::semantics::mask(u32::from(*width) * 8) =>
{
lhs.as_ref().clone()
}
vlk_ir::ir::BinOp::And
if let (
Expr::Const(outer),
Expr::Bin {
op: vlk_ir::ir::BinOp::And,
lhs: inner,
rhs: inner_mask,
},
) = (rhs.as_ref(), lhs.as_ref())
&& let Expr::Const(inner_mask) = inner_mask.as_ref() =>
{
Expr::bin(
vlk_ir::ir::BinOp::And,
inner.as_ref().clone(),
Expr::Const(outer & inner_mask),
)
}
vlk_ir::ir::BinOp::And
if let Expr::Const(mask) = rhs.as_ref()
&& let Expr::Bin {
op: vlk_ir::ir::BinOp::Or,
lhs: a,
rhs: b,
} = lhs.as_ref()
&& let Some(value) =
outside_mask(a, b, *mask).or_else(|| outside_mask(b, a, *mask)) =>
{
Expr::bin(vlk_ir::ir::BinOp::And, value.clone(), Expr::Const(*mask))
}
vlk_ir::ir::BinOp::And if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => {
let Expr::Bin {
op: inner,
lhs: a,
rhs: b,
} = lhs.as_ref()
else {
return expr;
};
use vlk_ir::ir::BinOp;
if !matches!(
inner,
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor
) {
return expr;
}
let low = |operand: &Expr| match operand {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
&& !matches!(lhs.as_ref(), Expr::Reg { .. }) =>
{
lhs.as_ref().clone()
}
other => other.clone(),
};
Expr::bin(
BinOp::And,
Expr::bin(*inner, low(a), low(b)),
Expr::Const(0xffff_ffff),
)
}
_ => expr,
}
}
fn fold_offsets(expr: Expr) -> Expr {
let Expr::Bin { op, lhs, rhs } = expr else {
return expr;
};
let Expr::Const(delta) = rhs.as_ref() else {
return Expr::Bin { op, lhs, rhs };
};
let Expr::Bin {
op: inner_op,
lhs: base,
rhs: inner,
} = lhs.as_ref()
else {
return Expr::Bin { op, lhs, rhs };
};
let Expr::Const(offset) = inner.as_ref() else {
return Expr::Bin { op, lhs, rhs };
};
let outer = match op {
vlk_ir::ir::BinOp::Add => *delta,
vlk_ir::ir::BinOp::Sub => delta.wrapping_neg(),
_ => return Expr::Bin { op, lhs, rhs },
};
let total = match inner_op {
vlk_ir::ir::BinOp::Add => offset.wrapping_add(outer),
vlk_ir::ir::BinOp::Sub => outer.wrapping_sub(*offset),
_ => return Expr::Bin { op, lhs, rhs },
};
Expr::bin(
vlk_ir::ir::BinOp::Add,
base.as_ref().clone(),
Expr::constant(total),
)
}
fn widen_compared_constant(value: &Expr, constant: &mut Expr, bits: u32) -> bool {
let narrow = match value {
Expr::Load {
width,
signed: true,
..
}
| Expr::SignExtend { width, .. } => u32::from(*width) * 8,
_ => return false,
};
let Expr::Const(constant_value) = constant else {
return false;
};
if narrow >= bits || *constant_value & vlk_ir::ir::semantics::mask(bits) != *constant_value {
return false;
}
*constant_value = vlk_ir::ir::semantics::sign_extend(*constant_value, bits) as u64;
true
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod magic_tests {
use super::magic_divisor;
#[test]
fn magic_multiply_divides_selected_32_bit_values() {
for (magic, shift, divisor) in [
(0xaaaa_aaab, 33, 3),
(0xcccc_cccd, 34, 5),
(0xcccc_cccd, 35, 10),
] {
assert_eq!(magic_divisor(magic, shift), Some(divisor));
for x in [
0u64,
1,
2,
divisor - 1,
divisor,
0x7fff_ffff,
0xffff_fffe,
0xffff_ffff,
] {
assert_eq!((x * magic) >> shift, x / divisor, "{x} / {divisor}");
}
}
}
#[test]
fn smt_accepted_magic_numbers_divide_every_32_bit_value() {
use vlk_smt::smt::Proofs;
if !Proofs::available() {
return;
}
let mut proofs = Proofs::default();
for shift in 32..64u32 {
let power = 1u128 << shift;
let slack = 1u128 << (shift - 32);
let accepted = format!(
"(and (>= d 2) (>= m 1) (<= m 4294967295) (<= {power} (* m d)) (<= (* m d) (+ {power} {slack})))"
);
let x = "(+ (* q d) r)";
let domain = format!("(and (>= q 0) (>= r 0) (< r d) (< {x} 4294967296))");
let exact =
format!("(and (<= (* q {power}) (* {x} m)) (< (* {x} m) (* (+ q 1) {power})))");
proofs.predicate(
format!("magic divisor at shift {shift}"),
"true",
&format!("(forall ((m Int) (d Int)) (=> (and {accepted} {domain}) {exact}))"),
);
}
proofs.counterexample(
"magic divisor without the error bound",
"true",
"(forall ((m Int) (d Int)) (=> (and (>= d 2) (>= m 1) (<= m 4294967295) (<= 8589934592 (* m d)) (>= q 0) (>= r 0) (< r d) (< (+ (* q d) r) 4294967296)) (and (<= (* q 8589934592) (* (+ (* q d) r) m)) (< (* (+ (* q d) r) m) (* (+ q 1) 8589934592)))))",
);
proofs.check();
}
}
#[cfg(test)]
mod select_tests {
use super::*;
use vlk_ir::ir::Cond;
#[test]
fn selects_fold_constant_and_identical_comparisons_at_the_original_width() {
for cond in [
Cond::Eq,
Cond::Ne,
Cond::Cs,
Cond::Cc,
Cond::Hi,
Cond::Ls,
Cond::Ge,
Cond::Lt,
Cond::Gt,
Cond::Le,
Cond::Mi,
Cond::Pl,
Cond::Vs,
Cond::Vc,
] {
for (lhs, rhs, constants, a, b, bits) in [
(Expr::Const(1), Expr::Const(2), HashMap::new(), 1, 2, 64),
(
Expr::reg(0, 8),
Expr::Const(255),
HashMap::from([(0, 127)]),
127,
255,
8,
),
(Expr::reg(0, 32), Expr::reg(0, 32), HashMap::new(), 0, 0, 32),
] {
let value = Expr::Select {
cond,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
then: Box::new(Expr::Const(11)),
els: Box::new(Expr::Const(22)),
};
let expected = if vlk_ir::ir::semantics::holds(cond, a, b, bits) {
11
} else {
22
};
assert_eq!(simplify_expr(value, &constants), Expr::Const(expected));
}
}
}
}