vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! What a branch out of the function is. It is a tail call only when the
//! stack is back at the height it had on entry and the target is a
//! function's start. Otherwise the code it reaches runs in this function's
//! frame, and is lifted as part of the function: another function's body
//! entered past its start, or a function start the code jumps to with its
//! own frame still set up.

use std::collections::{BTreeMap, HashMap, HashSet};

use crate::lift::{Summaries, tail_call};
use vlk_ir::ir::{BinOp, Block, Expr, Stmt};
use vlk_loader::loader::Image;

/// Code outside the function's extent that its branches continue in, by
/// start and size.
pub(super) type ContinuedCode = BTreeMap<u64, u64>;

/// How a branch out of the function leaves it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Leaving {
    TailCall,
    /// The function goes on in the code at this start and size.
    Continues(u64, u64),
}

/// Lifts each branch out of the function as a tail call: a jump ends its
/// block with it, and a conditional branch goes to a block of its own
/// holding it, so the arguments it passes stay visible to the passes.
/// Returns the code the branches that are no tail call continue in; until
/// that code is lifted with the function, they stay tail calls. When the
/// extent is only estimated, a branch past it may mean the estimate is
/// short, so only a branch to another known function counts. `ends` gives
/// the address of the branch ending each block.
pub(super) fn resolve_exits(
    image: &Image,
    summaries: Summaries<'_>,
    function: u64,
    blocks: &mut Vec<Block>,
    ends: &HashMap<u64, u64>,
) -> ContinuedCode {
    let own = image.functions.get(&function);
    let exact = own.is_some_and(|function| function.size.is_some() && !function.size_estimated);
    let extent = own.and_then(|function| function.size).unwrap_or(0);
    let starts: HashSet<u64> = blocks.iter().map(|block| block.start).collect();
    let heights = stack_heights(blocks, image.isa);
    let mut exits: Vec<u64> = Vec::new();
    let mut continued_code = ContinuedCode::new();
    // The blocks ending in a jump out, which their tail call then ends.
    let mut jumps: Vec<usize> = Vec::new();
    for (index, block) in blocks.iter().enumerate() {
        let (target, jump) = match block.stmts.last() {
            Some(Stmt::Brif { target, .. } | Stmt::BrifFlags { target, .. }) => (*target, false),
            Some(Stmt::Br {
                target: Some(target),
                ..
            }) => (*target, true),
            _ => continue,
        };
        if starts.contains(&target) || !(exact || image.functions.contains_key(&target)) {
            continue;
        }
        // Code running off the end of a part of the function into the next
        // is no branch the code makes, and is taken for a tail call.
        if let Some(pc) = ends.get(&block.start) {
            // The unwind table speaks for this function's own code and the
            // fragments split off it, not for code it continues in elsewhere.
            let at_entry = Some(*pc)
                .filter(|pc| {
                    (function..function.saturating_add(extent)).contains(pc)
                        || image.fragment_at(*pc).is_some()
                })
                .and_then(|pc| image.stack_at_entry(pc))
                .or(heights[index].map(|height| height == 0));
            if let Leaving::Continues(start, size) = leaving(image, function, target, at_entry) {
                continued_code.insert(start, size);
            }
        }
        if jump {
            jumps.push(index);
        } else {
            exits.push(target);
        }
    }
    for index in jumps {
        let stmts = &mut blocks[index].stmts;
        let Some(Stmt::Br { target, at }) = stmts.pop() else {
            unreachable!("a jump ends the block")
        };
        let [call, result] = tail_call(image, summaries, target);
        stmts.push(call.with_origin(at));
        stmts.push(result);
    }
    if exits.is_empty() {
        return continued_code;
    }
    exits.sort_unstable();
    exits.dedup();
    // The last block must not fall through into the exits; past its end
    // is code that a call which does not return never reaches.
    if let Some(last) = blocks.last_mut()
        && !matches!(
            last.stmts.last(),
            Some(
                Stmt::Ret { .. }
                    | Stmt::Br { .. }
                    | Stmt::BrIndirect { .. }
                    | Stmt::Switch { .. }
                    | Stmt::Trap { .. }
            )
        )
    {
        last.stmts.push(Stmt::Trap { at: None });
    }
    for target in exits {
        blocks.push(Block {
            start: target,
            stmts: tail_call(image, summaries, Some(target)).into(),
        });
    }
    continued_code
}

/// A branch to `target`, with the stack as on entry, or not, or unknown, is
/// a tail call when it reaches a function's start with the stack as on
/// entry, or unknown. Into another function's body, or to a start with a
/// frame still set up, it goes on in that code, as far as the function
/// there extends.
fn leaving(image: &Image, function: u64, target: u64, at_entry: Option<bool>) -> Leaving {
    if let Some(callee) = image.functions.get(&target) {
        return match (at_entry, callee.size) {
            (Some(false), Some(size)) => Leaving::Continues(target, size),
            _ => Leaving::TailCall,
        };
    }
    image
        .functions
        .range(..target)
        .next_back()
        .filter(|(start, _)| **start != function)
        .and_then(|(start, function)| {
            let Some(size) = function.size else {
                return None;
            };
            Some(start + size)
        })
        .filter(|end| target < *end)
        .map_or(Leaving::TailCall, |end| {
            Leaving::Continues(target, end - target)
        })
}

/// The offsets from the entry stack pointer that registers hold.
type Offsets = rustc_hash::FxHashMap<u16, i64>;

/// How far the stack pointer stands from where it was on entry at the end
/// of each block, where every path there agrees. Registers that hold an
/// offset from the entry stack pointer, as a frame pointer does, carry it
/// back when the stack pointer is restored from them.
pub(crate) fn stack_heights(blocks: &[Block], isa: vlk_base::target::Isa) -> Vec<Option<i64>> {
    let sp = vlk_arch::arch::stack_pointer(isa);
    let count = blocks.len();
    let successors: Vec<Vec<usize>> = (0..count)
        .map(|index| vlk_ir::ir::cfg::block_successors(blocks, index))
        .collect();
    let mut entry: Vec<Option<Offsets>> = vec![None; count];
    let mut exit: Vec<Option<Offsets>> = vec![None; count];
    if count == 0 {
        return Vec::new();
    }
    let start: Offsets = [(sp, 0)].into_iter().collect();
    // Each round only removes registers or reaches a block, so it settles.
    loop {
        let mut next: Vec<Option<Offsets>> = vec![None; count];
        next[0] = Some(start.clone());
        for (index, out) in exit.iter().enumerate() {
            let Some(out) = out else {
                continue;
            };
            for successor in &successors[index] {
                next[*successor] = Some(match next[*successor].take() {
                    None => out.clone(),
                    Some(mut known) => {
                        known.retain(|register, offset| out.get(register) == Some(offset));
                        known
                    }
                });
            }
        }
        if next == entry {
            break;
        }
        // What a block leaves follows from what it enters with alone.
        for (index, block) in blocks.iter().enumerate() {
            if next[index] == entry[index] {
                continue;
            }
            exit[index] = next[index].clone().map(|mut state| {
                for stmt in &block.stmts {
                    step(stmt, &mut state);
                }
                state
            });
        }
        entry = next;
    }
    exit.into_iter()
        .map(|state| state.and_then(|state| state.get(&sp).copied()))
        .collect()
}

/// The offsets from the entry stack pointer the registers hold after `stmt`.
fn step(stmt: &Stmt, state: &mut Offsets) {
    if let Stmt::Assign { dest, value, .. } = stmt
        && dest.width == 64
    {
        match offset_of(value, state) {
            Some(offset) => state.insert(dest.index, offset),
            None => state.remove(&dest.index),
        };
        return;
    }
    // The state holds a few registers and a call writes many.
    state.retain(|register, _| !vlk_ir::ir::visit::statement_writes_register(stmt, *register));
}

/// The offset from the entry stack pointer `value` computes, when it is
/// `r`, `r + k` or `r - k` for a register holding one.
fn offset_of(value: &Expr, state: &Offsets) -> Option<i64> {
    match value {
        Expr::Reg { index, width: 64 } => state.get(index).copied(),
        Expr::Bin { op, lhs, rhs } => {
            let Expr::Const(by) = rhs.as_ref() else {
                return None;
            };
            let Some(base) = offset_of(lhs, state) else {
                return None;
            };
            match op {
                BinOp::Add => Some(base.wrapping_add(*by as i64)),
                BinOp::Sub => Some(base.wrapping_sub(*by as i64)),
                _ => None,
            }
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests;