vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Whether a function without debug information returns a float.

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,
    }
}

/// Whether, without debug info, the function returns a float, and which:
/// every path to a return writes the float return register, and either
/// some path leaves the integer one as it came in, or every path writes it
/// before the float one. On x86-64 an untouched integer register means
/// nothing, and on `AArch64` it is the first argument, which a function
/// returning a float does not return. A float is a single when the last
/// write on every path that says computes or loads one.
#[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)
}

/// As `float_result`, for the function at `addr`. On MIPS the integer
/// return register is also the first a compiler takes for a value it needs
/// for a moment, so a function may write it after its float result is
/// set. There, a function is taken to return a float when a caller reads
/// the float return register after a call to it, before writing it: what
/// the caller reads is what the function left, as long as the function
/// writes that register or calls something, and so does not just keep
/// the caller's own value in it.
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)
}

/// The functions some caller reads the float return register after,
/// before the caller writes it or calls again, and the functions those
/// end by jumping to, which return for them.
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;
                };
                // A write of one half of the register keeps the other and
                // so reads it: that is no use of what the call left.
                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;
        }
    }
}

/// What the paths to a point of the function have written of its return
/// registers.
#[derive(Clone, Copy, Default, PartialEq)]
struct Written {
    /// Whether every path wrote the float return register.
    float: bool,
    /// Whether every path wrote the integer return register.
    int: bool,
    /// Whether every path wrote the float register after the integer one.
    float_last: bool,
    /// The precision the last write to the float register shows, when the
    /// paths agree.
    precision: Option<Precision>,
}

impl Written {
    /// What holds after both `self` and `other`.
    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
            },
        }
    }
}

/// The precision of the float the call `stmt` returns, when its prototype
/// or `callee_float` says it returns one.
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,
        },
    }
}

/// What has been written of the return registers at each return a path
/// from the entry reaches. `slot` is the float return register.
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());
    // A push of the integer return register on entry, which only aligns
    // the stack: the pop that undoes it gives the register what it had.
    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;
                    }
                    // A callee known to return a float gives this one.
                    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
}

/// `float_result`, also taking the function to return a float when
/// `read_by_callers` and it writes the float return register or calls
/// something.
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));
    // What a caller reads is the function's own when it writes the
    // register or calls something that may.
    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
    })
}

/// The precision of the float a write to the vector register `slot` puts
/// in its low half: what an operation computes or a load reads. x86 merges
/// a single into the register's other bits, and `AArch64` clears them.
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,
    }
}