use std::collections::HashSet;
use vlk_ir::ir::{Block, Expr, Stmt};
use vlk_loader::loader::Image;
use vlk_program::program::Program;
use vlk_prototypes::prototypes;
use vlk_types::types::Precision;
use crate::lift;
pub(super) fn float_return_slot(isa: vlk_base::target::Isa) -> Option<u16> {
match isa {
vlk_base::target::Isa::X86_64 => Some(vlk_arch::arch::x86::XMM0),
vlk_base::target::Isa::AArch64 => Some(vlk_arch::arch::aarch64::V0),
vlk_base::target::Isa::RiscV64 => Some(vlk_arch::arch::riscv64::FA0),
vlk_base::target::Isa::Mips32 => Some(vlk_arch::arch::mips32::F0),
vlk_base::target::Isa::Arm32
| vlk_base::target::Isa::I386
| vlk_base::target::Isa::Unsupported => None,
}
}
#[cfg(test)]
pub(super) fn float_result(
blocks: &[Block],
image: &Image,
callee_float: &dyn Fn(u64) -> u8,
) -> Option<Precision> {
float_result_read(blocks, image, callee_float, false)
}
pub(super) fn float_result_of(
blocks: &[Block],
program: &Program,
addr: u64,
callee_float: &dyn Fn(u64) -> u8,
) -> Option<Precision> {
let image = &program.image;
let read = image.isa == vlk_base::target::Isa::Mips32
&& program
.float_readers
.get_or_init(|| float_readers(program))
.contains(&addr);
float_result_read(blocks, image, callee_float, read)
}
pub(super) fn float_readers(program: &Program) -> HashSet<u64> {
let image = &program.image;
let Some(slot) = float_return_slot(image.isa) else {
return HashSet::new();
};
let mut readers = HashSet::new();
let mut forwards: Vec<(u64, u64)> = Vec::new();
for function in image.functions.values() {
let Some(size) = function.size.filter(|size| *size > 0 && *size <= 0x20000) else {
continue;
};
let Ok(blocks) = lift::lift_with(program, function.addr, size, &HashSet::new(), &|_| {
vlk_loader::loader::Summary::default()
}) else {
continue;
};
for block in &blocks {
let mut called = None;
for stmt in &block.stmts {
if let Stmt::Call {
kind,
target,
through: None,
..
} = stmt
{
match (kind, target) {
(vlk_types::types::CallKind::Invoke, Some(target)) => {
called = Some(*target)
}
(vlk_types::types::CallKind::Tail, Some(target)) => {
forwards.push((function.addr, *target));
called = None;
}
_ => called = None,
}
continue;
}
let Some(target) = called else {
continue;
};
if vlk_ir::ir::visit::statement_registers(stmt)
.0
.contains(&slot)
{
called = None;
continue;
}
let mut read = HashSet::new();
for operand in stmt.operands() {
vlk_ir::ir::visit::collect_reads(operand, &mut read);
}
if read.contains(&slot) {
readers.insert(target);
}
}
}
}
loop {
let before = readers.len();
for (from, to) in &forwards {
if readers.contains(from) {
readers.insert(*to);
}
}
if readers.len() == before {
return readers;
}
}
}
#[derive(Clone, Copy, Default, PartialEq)]
struct Written {
float: bool,
int: bool,
float_last: bool,
precision: Option<Precision>,
}
impl Written {
fn join(self, other: Self) -> Self {
Written {
float: self.float && other.float,
int: self.int && other.int,
float_last: self.float_last && other.float_last,
precision: if self.precision == other.precision {
self.precision
} else {
None
},
}
}
}
fn returned_precision(
image: &Image,
stmt: &Stmt,
callee_float: &dyn Fn(u64) -> u8,
) -> Option<Precision> {
match prototypes::called(image, stmt) {
Some(prototype) => prototype.ret.precision(),
None => match stmt {
Stmt::Call {
target: Some(target),
through: None,
..
} => match callee_float(*target) {
4 => Some(Precision::Single),
8 => Some(Precision::Double),
_ => None,
},
_ => None,
},
}
}
fn written_at_returns(
blocks: &[Block],
image: &Image,
slot: u16,
callee_float: &dyn Fn(u64) -> u8,
) -> Vec<Written> {
let mut entry: Vec<Option<Written>> = vec![None; blocks.len()];
entry[0] = Some(Written::default());
let sp = vlk_arch::arch::stack_pointer(image.isa);
let at_stack = |addr: &Expr| matches!(addr, Expr::Reg { index, .. } if *index == sp);
let pushed = blocks[0]
.stmts
.iter()
.take_while(|stmt| !matches!(stmt, Stmt::Call { .. }))
.any(|stmt| {
matches!(stmt, Stmt::Store { addr, value: Expr::Reg { index, .. }, width: 8, .. }
if *index == vlk_arch::arch::RETURN && at_stack(addr))
});
let mut work = vec![0];
let mut returns = Vec::new();
while let Some(index) = work.pop() {
let mut state = entry[index].expect("visited");
for stmt in &blocks[index].stmts {
match stmt {
Stmt::Assign {
dest,
value: Expr::Load { addr, width: 8, .. },
..
} if pushed && dest.index == vlk_arch::arch::RETURN && at_stack(addr) => {}
Stmt::Assign { dest, .. } if dest.index == vlk_arch::arch::RETURN => {
state.int = true;
state.float_last = false;
}
Stmt::Assign { dest, value, .. } if dest.index == slot => {
state.float = true;
state.float_last = true;
state.precision = written_precision(value, slot);
}
Stmt::Call { .. } => {
let written = vlk_ir::ir::visit::statement_registers(stmt).0;
if written.contains(&slot) {
state.float = false;
state.float_last = false;
state.precision = None;
}
if written.contains(&vlk_arch::arch::RETURN) {
state.int = true;
state.float_last = false;
}
let returned = returned_precision(image, stmt, callee_float);
if written.contains(&slot)
&& let Some(precision) = returned
{
state.float = true;
state.float_last = true;
state.precision = Some(precision);
}
}
Stmt::Ret { .. } => returns.push(state),
_ => {}
}
}
for next in vlk_ir::ir::cfg::block_successors(blocks, index) {
let merged = match entry[next] {
Some(old) => old.join(state),
None => state,
};
if entry[next] != Some(merged) {
entry[next] = Some(merged);
work.push(next);
}
}
}
returns
}
fn float_result_read(
blocks: &[Block],
image: &Image,
callee_float: &dyn Fn(u64) -> u8,
read_by_callers: bool,
) -> Option<Precision> {
let Some(slot) = float_return_slot(image.isa) else {
return None;
};
if blocks.is_empty() {
return None;
}
let returns = written_at_returns(blocks, image, slot, callee_float);
let floats = !returns.is_empty() && returns.iter().all(|state| state.float);
let integer_unwritten_or_float_last =
returns.iter().all(|state| !state.int || state.float_last);
let single = returns
.iter()
.any(|state| state.precision == Some(Precision::Single))
&& returns
.iter()
.all(|state| state.precision != Some(Precision::Double));
let left_by_function = read_by_callers
&& !returns.is_empty()
&& blocks.iter().flat_map(|block| &block.stmts).any(|stmt| {
matches!(stmt, Stmt::Call { .. })
|| matches!(stmt, Stmt::Assign { dest, .. } if dest.index == slot)
});
((floats && integer_unwritten_or_float_last) || left_by_function).then_some(if single {
Precision::Single
} else {
Precision::Double
})
}
pub(super) fn written_precision(value: &Expr, slot: u16) -> Option<Precision> {
use vlk_ir::ir::BinOp;
match value {
Expr::Apply { op, .. } => op.result_precision(),
Expr::Load { width: 4, .. } => Some(Precision::Single),
Expr::Load { width: 8, .. } => Some(Precision::Double),
Expr::Bin {
op: BinOp::And | BinOp::Or,
lhs,
rhs,
} => {
let kept = |side: &Expr| match side {
Expr::Const(_) => true,
Expr::Bin { lhs, rhs, .. } => {
matches!(lhs.as_ref(), Expr::Reg { index, .. } if *index == slot)
&& matches!(rhs.as_ref(), Expr::Const(_))
}
_ => false,
};
match (kept(lhs), kept(rhs)) {
(true, false) => written_precision(rhs, slot),
(false, true) => written_precision(lhs, slot),
_ => None,
}
}
_ => None,
}
}