vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Constants a function keeps in its frame or reads from the global offset
//! table, written into the blocks as the values they are.

use std::collections::HashSet;

use vlk_arch::arch::mips32::{FP, SP};
use vlk_ir::ir::{BinOp, Expr, Stmt};

/// Reads the address of a jump table from the frame slot it is kept in:
/// optimized code that runs out of registers stores the address once and
/// loads it before each jump through the table.
///
/// Only a block that ends in a jump through a register is read this way,
/// and only a slot that holds an address of read-only data: no variable of
/// the program is a jump table's address, so the slot is the compiler's
/// own. The slot is at a fixed offset from the stack pointer, which the
/// function moves only as it starts and as it returns, and which it does
/// not copy to a frame pointer. Nothing else is stored over the slot
/// through the stack pointer, and the store comes before the read on
/// every path the code shows.
///
/// `tables` gives, for the jumps through a register whose tables are
/// read, the block each ends and where it goes. Returns whether a slot
/// was read.
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,
    };
    // Where each block's statements have the stack pointer of the body:
    // past the move that opens the frame, before the one that closes it.
    let mut body: Vec<std::ops::Range<usize>> = Vec::with_capacity(blocks.len());
    // The block that opens the frame.
    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;
                    };
                    // Down by a constant opens the frame, up closes it.
                    let down = (*amount as i64) < 0;
                    match op {
                        BinOp::Sub => moves.push((position, !down)),
                        BinOp::Add => moves.push((position, down)),
                        _ => return false,
                    }
                }
                // A frame pointer names the slots too. The address of a
                // local in that register, as in any other, is not one.
                Stmt::Assign {
                    dest,
                    value: Expr::Reg { index: SP, .. },
                    ..
                } if dest.index == FP => return false,
                _ => {}
            }
        }
        // The frame is closed where the function returns: in the block
        // that does, or as the last thing before one that only returns,
        // which a way out that opens no frame shares.
        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();
    // Where a jump through a register may go besides where it is known
    // to: the cases of the tables read so far, and every block no path
    // shown reaches, which is a case of a table not read yet.
    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();
    // Whether the block `upper` comes before the jump through a register
    // that ends `lower` on every way there. The other such jumps may go to
    // any landing; where this one goes is past it.
    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])
            {
                // A jump whose table is read goes where the table says.
                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,
            }
        }
    };
    // The blocks that have the frame: those every path to which opens
    // it, and those no path shown reaches, which are the cases of the
    // tables not yet read, entered from blocks that have it.
    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)
    };
    // Every store through the stack pointer, and those of such addresses.
    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(&register);
        }
        known.extend(set);
    }
    // The constants each block leaves in registers by its own statements
    // alone. An address is often set in two instructions with a block's
    // start between them: a block begins with what every block that comes
    // before it leaves alike.
    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)
            {
                // A store where the frame is not known to be open may be
                // to any slot.
                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
}

/// Reads of the global offset table's fixed entries, once the passes have
/// worked out their addresses, as the addresses the entries hold.
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);
        }
    }
}