vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! The return type of a function that returns what its callees return.

use std::collections::HashSet;

use vlk_ir::ir::{FunctionIr, Stmt};
use vlk_program::program::Program;
use vlk_prototypes::prototypes;

use super::analyze;

/// A function that only ever returns what the functions it calls return
/// returns as wide a value as they do, or nothing when they return nothing;
/// a library function's result, or one a constant moves, is of the type
/// its prototype gives it.
pub(super) fn apply_call_return(ir: &mut FunctionIr, program: &Program) {
    let image = &program.image;
    use vlk_ir::ir::{BinOp, Expr};
    use vlk_types::types::CType;
    if ir.ret_type == CType::Void || vlk_ir::ir::cfg::own_return(&ir.blocks).is_some() {
        return;
    }
    let mut width = None;
    for block in &ir.blocks {
        let [
            ..,
            call @ Stmt::Call { target, .. },
            Stmt::Ret { value, .. },
        ] = block.stmts.as_slice()
        else {
            if matches!(block.stmts.last(), Some(Stmt::Ret { .. })) {
                return;
            }
            continue;
        };
        let prototype = prototypes::called(image, call);
        let returned = match value {
            Expr::Reg { index, .. } => *index,
            Expr::Bin {
                op: BinOp::Add | BinOp::Sub,
                lhs,
                rhs,
            } if matches!(rhs.as_ref(), Expr::Const(_))
                && prototype.is_some_and(|prototype| prototype.ret.integer().is_some()) =>
            {
                match lhs.as_ref() {
                    Expr::Reg { index, .. } => *index,
                    _ => return,
                }
            }
            _ => return,
        };
        let returned_type = match (prototype, target) {
            (Some(prototype), _) => prototype.ret.clone(),
            (None, Some(target)) => match returned_type(program, *target) {
                Some(returned_type) => returned_type,
                None => return,
            },
            (None, None) => return,
        };
        let output = if returned_type == CType::Void {
            call.primary_call_output()
        } else {
            prototypes::scalar_call_output(call, &returned_type)
        };
        let Some(carried) = output.map(|output| output.dest.index) else {
            return;
        };
        if returned != carried || width.as_ref().is_some_and(|width| *width != returned_type) {
            return;
        }
        width = Some(returned_type);
    }
    match (width, &ir.ret_type) {
        // The calls' results go nowhere.
        (Some(CType::Void), _) => {
            ir.ret_type = CType::Void;
            for block in &mut ir.blocks {
                if let [.., Stmt::Call { .. }, Stmt::Ret { value, .. }] = block.stmts.as_mut_slice()
                {
                    *value = Expr::constant(0);
                }
            }
        }
        (Some(CType::Int { bytes, .. }), CType::Int { signed, .. }) => {
            ir.ret_type = CType::int(bytes, *signed);
        }
        (Some(CType::Int { .. }) | None, _) => {}
        (Some(given), _) => ir.ret_type = given,
    }
}

/// What the function at `addr` returns, as its own analysis decides: an
/// integer, or nothing; `None` for anything else, or for a function already
/// being analysed further up, as mutual tail calls are.
pub(super) fn returned_type(program: &Program, addr: u64) -> Option<vlk_types::types::CType> {
    let image = &program.image;
    thread_local! {
        static UNDER_WAY: std::cell::RefCell<HashSet<u64>> = Default::default();
        /// How many times a function already under way was asked for.
        static CUT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    }
    let function = image.functions.get(&addr)?;
    if let Some(known) = program
        .returned_types
        .lock()
        .expect("returned types lock")
        .get(&addr)
    {
        return known.clone();
    }
    if !UNDER_WAY.with(|under_way| under_way.borrow_mut().insert(addr)) {
        CUT.set(CUT.get() + 1);
        return None;
    }
    let cut = CUT.get();
    let analysis = analyze(program, function, None);
    UNDER_WAY.with(|under_way| under_way.borrow_mut().remove(&addr));
    let returned = match analysis.map(|analysis| analysis.ir.ret_type) {
        Ok(vlk_types::types::CType::Int { bytes, .. }) => {
            Some(vlk_types::types::CType::int(bytes, false))
        }
        Ok(vlk_types::types::CType::Void) => Some(vlk_types::types::CType::Void),
        _ => None,
    };
    // An answer made while a function under way was left out holds only
    // below that function, so it is not kept.
    if CUT.get() == cut {
        program
            .returned_types
            .lock()
            .expect("returned types lock")
            .insert(addr, returned.clone());
    }
    returned
}