use std::collections::HashSet;
use vlk_arch::arch::mips32::{FP, SP};
use vlk_ir::ir::{BinOp, Expr, Stmt};
pub(crate) fn fold_table_slots(
image: &vlk_loader::loader::Image,
blocks: &mut [vlk_ir::ir::Block],
cases: &HashSet<u64>,
tables: &[(u64, Vec<u64>)],
) -> bool {
if !blocks
.iter()
.any(|block| matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })))
{
return false;
}
let slot = |addr: &Expr| match addr {
Expr::Reg { index: SP, .. } => Some(0u64),
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} => match (lhs.as_ref(), rhs.as_ref()) {
(Expr::Reg { index: SP, .. }, Expr::Const(offset)) => Some(*offset),
_ => None,
},
_ => None,
};
let mut body: Vec<std::ops::Range<usize>> = Vec::with_capacity(blocks.len());
let mut opening = None;
for (index, block) in blocks.iter().enumerate() {
let mut moves = Vec::new();
for (position, stmt) in block.stmts.iter().enumerate() {
match stmt {
Stmt::Assign { dest, value, .. } if dest.index == SP => {
let Expr::Bin { op, lhs, rhs } = value else {
return false;
};
let (Expr::Reg { index: SP, .. }, Expr::Const(amount)) =
(lhs.as_ref(), rhs.as_ref())
else {
return false;
};
let down = (*amount as i64) < 0;
match op {
BinOp::Sub => moves.push((position, !down)),
BinOp::Add => moves.push((position, down)),
_ => return false,
}
}
Stmt::Assign {
dest,
value: Expr::Reg { index: SP, .. },
..
} if dest.index == FP => return false,
_ => {}
}
}
let returns = matches!(block.stmts.last(), Some(Stmt::Ret { .. }))
|| (matches!(moves.last(), Some((last, false)) if last + 1 == block.stmts.len())
&& blocks
.get(index + 1)
.is_some_and(|next| matches!(next.stmts.as_slice(), [Stmt::Ret { .. }])));
body.push(match moves.as_slice() {
[] => 0..block.stmts.len(),
[(opened, true)] if opening.is_none() => {
opening = Some(index);
opened + 1..block.stmts.len()
}
[(closed, false)] if returns => 0..*closed,
_ => return false,
});
}
let Some(opening) = opening else {
return false;
};
let successors: Vec<Vec<usize>> = (0..blocks.len())
.map(|index| vlk_ir::ir::cfg::block_successors(blocks, index))
.collect();
let mut entered = vec![false; blocks.len()];
for next in successors.iter().flatten() {
entered[*next] = true;
}
let landings: Vec<usize> = (1..blocks.len())
.filter(|index| !entered[*index] || cases.contains(&blocks[*index].start))
.collect();
let blocks_start: Vec<u64> = blocks.iter().map(|block| block.start).collect();
let jumps: Vec<usize> = (0..blocks.len())
.filter(|index| matches!(blocks[*index].stmts.last(), Some(Stmt::BrIndirect { .. })))
.collect();
let before_jump = |upper: usize, lower: usize| {
let mut all = successors.clone();
for jump in jumps.iter().filter(|jump| **jump != lower) {
match tables
.iter()
.find(|(start, _)| *start == blocks_start[*jump])
{
Some((_, targets)) => all[*jump].extend(
blocks_start
.iter()
.enumerate()
.filter(|(_, start)| targets.contains(start))
.map(|(index, _)| index),
),
None => all[*jump].extend(&landings),
}
}
let idom = crate::ssa::dom::dominators(&all).idom;
let mut at = lower;
loop {
match idom[at] {
Some(next) if next == upper => return true,
Some(next) if next != at => at = next,
_ => return false,
}
}
};
let idom = crate::ssa::dom::dominators(&successors).idom;
let dominates = |upper: usize, mut lower: usize| {
loop {
match idom[lower] {
Some(next) if next == upper => return true,
Some(next) if next != lower => lower = next,
_ => return false,
}
}
};
let framed = |index: usize| {
index == opening || dominates(opening, index) || (index != 0 && idom[index].is_none())
};
let read_only = |address: u64| {
image
.section_at(address)
.is_some_and(|section| section.read_only && !section.executable)
};
type Known = std::collections::HashMap<u16, u64>;
fn constant(expr: &Expr, known: &Known) -> Option<u64> {
match expr {
Expr::Const(value) => Some(*value),
Expr::Reg { index, .. } => known.get(index).copied(),
Expr::Bin { op, lhs, rhs } => {
let (Some(a), Some(b)) = (constant(lhs, known), constant(rhs, known)) else {
return None;
};
match op {
BinOp::Add => Some(a.wrapping_add(b)),
BinOp::Sub => Some(a.wrapping_sub(b)),
BinOp::And => Some(a & b),
BinOp::Or => Some(a | b),
_ => None,
}
}
_ => None,
}
}
fn step(stmt: &Stmt, known: &mut Known) {
let set = match stmt {
Stmt::Assign {
dest, value: set, ..
} => constant(set, known).map(|value| (dest.index, value)),
_ => None,
};
for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
known.remove(®ister);
}
known.extend(set);
}
let left: Vec<Known> = blocks
.iter()
.map(|block| {
let mut known = Known::new();
for stmt in &block.stmts {
step(stmt, &mut known);
}
known
})
.collect();
let mut entering: Vec<Vec<usize>> = vec![Vec::new(); blocks.len()];
for (index, next) in successors.iter().enumerate() {
for successor in next {
entering[*successor].push(index);
}
}
let mut written: Vec<(u64, u8)> = Vec::new();
let mut constants: Vec<(usize, usize, u64, u64)> = Vec::new();
for (index, block) in blocks.iter().enumerate() {
let mut known = match entering[index].split_first() {
Some((first, rest)) if index != 0 => left[*first]
.iter()
.filter(|(register, value)| {
rest.iter()
.all(|other| left[*other].get(register) == Some(value))
})
.map(|(register, value)| (*register, *value))
.collect(),
_ => Known::new(),
};
for (position, stmt) in block.stmts.iter().enumerate() {
if let Stmt::Store {
addr, value, width, ..
} = stmt
&& let Some(offset) = slot(addr)
{
if !body[index].contains(&position) || !framed(index) {
return false;
}
written.push((offset, *width));
if *width == 4
&& let Some(value) = constant(value, &known).filter(|value| read_only(*value))
{
constants.push((index, position, offset, value));
}
}
step(stmt, &mut known);
}
}
constants.retain(|(_, _, offset, _)| {
written
.iter()
.filter(|(other, width)| *other < offset + 4 && other + u64::from(*width) > *offset)
.count()
== 1
});
if constants.is_empty() {
return false;
}
fn fold(expr: &mut Expr, read: &dyn Fn(&Expr) -> Option<u64>) -> bool {
if let Expr::Load { addr, width: 4, .. } = expr
&& let Some(value) = read(addr)
{
*expr = Expr::Const(value);
return true;
}
let mut folded = false;
for child in vlk_ir::ir::visit::children_mut(expr) {
folded |= fold(child, read);
}
folded
}
let mut folded = false;
for (index, block) in blocks.iter_mut().enumerate() {
if !matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })) {
continue;
}
for (position, stmt) in block.stmts.iter_mut().enumerate() {
if !body[index].contains(&position) {
continue;
}
let read = |addr: &Expr| {
let Some(offset) = slot(addr) else {
return None;
};
constants
.iter()
.find(|(stored, at, slot, _)| {
*slot == offset
&& if *stored == index {
*at < position
} else {
before_jump(*stored, index)
}
})
.map(|(_, _, _, value)| *value)
};
for operand in stmt.operands_mut() {
folded |= fold(operand, &read);
}
}
}
folded
}
pub(crate) fn fold_fixed_entries(
ir: &mut vlk_ir::ir::FunctionIr,
image: &vlk_loader::loader::Image,
) {
fn fold(expr: &mut Expr, image: &vlk_loader::loader::Image) {
for child in vlk_ir::ir::visit::children_mut(expr) {
fold(child, image);
}
if let Expr::Load { addr, width: 4, .. } = expr
&& let Expr::Const(address) = addr.as_ref()
&& let Some(value) = image.fixed_table_entry(*address)
{
*expr = Expr::Const(value);
}
}
for stmt in ir.blocks.iter_mut().flat_map(|block| &mut block.stmts) {
for operand in stmt.operands_mut() {
fold(operand, image);
}
}
}