vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Constants in registers, followed over the statements of a block and
//! across the blocks of a function.

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

use vlk_ir::ir::{Block, Expr, Stmt};
use vlk_loader::loader::Image;

/// The value each register is known to hold.
pub(super) type Known = HashMap<u16, u64>;

/// A place in the frame: the register that addresses it and the offset
/// from that register.
type Slot = (u16, u64);

/// What is known at a point of the code.
#[derive(Clone, Default, PartialEq)]
pub(super) struct Facts {
    /// The value each register holds.
    pub registers: Known,
    /// The word each frame slot holds.
    slots: HashMap<Slot, u64>,
    /// For each frame register, the lowest offset from it whose address
    /// the code has taken: what lies from there on may be written through
    /// the address.
    taken: HashMap<u16, u64>,
}

impl Facts {
    pub(super) fn of(registers: &Known) -> Self {
        Self {
            registers: registers.clone(),
            ..Self::default()
        }
    }

    fn is_empty(&self) -> bool {
        self.registers.is_empty() && self.slots.is_empty()
    }

    /// Keeps what `other` has alike.
    fn meet(&mut self, other: &Self) {
        self.registers
            .retain(|register, value| other.registers.get(register) == Some(value));
        self.slots
            .retain(|slot, value| other.slots.get(slot) == Some(value));
        for (register, offset) in &other.taken {
            let lowest = self.taken.entry(*register).or_insert(*offset);
            if (*offset as i64) < (*lowest as i64) {
                *lowest = *offset;
            }
        }
    }

    /// Forgets the slots that may be written through an address the code
    /// took.
    fn forget_taken(&mut self) {
        let taken = &self.taken;
        self.slots.retain(|(register, offset), _| {
            taken
                .get(register)
                .is_none_or(|lowest| (*offset as i64) < (*lowest as i64))
        });
    }
}

/// The frame slot `addr` is: a frame register, or one and an offset.
fn slot(frame: &[u16], addr: &Expr) -> Option<Slot> {
    match addr {
        Expr::Reg { index, width: 64 } if frame.contains(index) => Some((*index, 0)),
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, width: 64 }, Expr::Const(offset)) if frame.contains(index) => {
                Some((*index, *offset))
            }
            _ => None,
        },
        _ => None,
    }
}

/// How constants are followed for an instruction set.
#[derive(Clone, Default)]
pub(super) struct Rules {
    /// What the registers hold where the function begins.
    pub at_entry: Known,
    /// Registers that hold one value through a function once its entry code
    /// has set it: a read of one is written as the value, and its reload
    /// from the frame is left out.
    pub fixed: &'static [u16],
    /// The registers that address the frame.
    pub frame: &'static [u16],
    /// Registers a function saves in its frame and reads back: one read
    /// back from the frame is taken to hold what it held before, as a
    /// `fixed` one is.
    pub saved: &'static [u16],
    /// Whether what is known is written into the statements: a known value
    /// assigned as the constant, a load of a word the image fixes as the
    /// word.
    pub folds: bool,
    /// Whether the convention makes its calls through a register, so that
    /// one resolved to its function is no more notable than a direct call.
    pub calls_through_registers: bool,
}

/// `expr` without the mask that keeps a 32-bit register's value to its
/// width.
pub(super) fn word(expr: &Expr) -> &Expr {
    match expr {
        Expr::Bin {
            op: vlk_ir::ir::BinOp::And,
            lhs,
            rhs,
        } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => lhs,
        expr => expr,
    }
}

/// Whether `expr` reads the frame: a load through one of `frame`, or
/// through one of them and an offset.
pub(super) fn frame_load(frame: &[u16], expr: &Expr) -> bool {
    let expr = word(expr);
    let based = |expr: &Expr| matches!(expr, Expr::Reg { index, .. } if frame.contains(index));
    matches!(expr, Expr::Load { addr, .. }
        if based(addr) || matches!(addr.as_ref(), Expr::Bin { lhs, .. } if based(lhs)))
}

/// The constant `expr` computes, where its registers are known. Under
/// rules that fold, a word the image fixes is known too.
pub(super) fn value(known: &Facts, expr: &Expr, image: &Image, rules: &Rules) -> Option<u64> {
    match expr {
        Expr::Const(value) => Some(*value),
        Expr::Reg { index, width } => known.registers.get(index).map(|value| {
            if *width < 64 {
                value & vlk_ir::ir::semantics::mask(u32::from(*width))
            } else {
                *value
            }
        }),
        Expr::Bin { op, lhs, rhs } => match (
            value(known, lhs, image, rules),
            value(known, rhs, image, rules),
        ) {
            (Some(lhs), Some(rhs)) => vlk_ir::ir::semantics::scalar(*op, lhs, rhs, 64),
            _ => None,
        },
        Expr::Load { addr, width: 4, .. } if rules.folds => match slot(rules.frame, addr) {
            Some(slot) => known.slots.get(&slot).copied(),
            None => value(known, addr, image, rules)
                .and_then(|address| image.fixed_table_entry(address)),
        },
        _ => None,
    }
}

/// Follows `stmt`: an assignment of a constant makes its register known,
/// any other write makes it unknown, and a call leaves known what its
/// convention, or its callee's summary, says it does not change. Under
/// rules that fold, a word stored to a frame slot is known there until
/// something may write the slot.
pub(super) fn apply(known: &mut Facts, stmt: &Stmt, image: &Image, rules: &Rules) {
    match stmt {
        Stmt::Assign {
            dest, value: read, ..
        } if (rules.saved.contains(&dest.index) || rules.fixed.contains(&dest.index))
            && frame_load(rules.frame, read)
            && value(known, read, image, rules).is_none() => {}
        Stmt::Assign {
            dest,
            value: assigned,
            ..
        } => {
            // An address in the frame, copied out of the frame registers.
            if rules.folds
                && !rules.frame.contains(&dest.index)
                && let Some((register, offset)) = slot(rules.frame, word(assigned))
            {
                let lowest = known.taken.entry(register).or_insert(offset);
                if (offset as i64) < (*lowest as i64) {
                    *lowest = offset;
                }
            }
            match value(known, assigned, image, rules).filter(|_| dest.width == 64) {
                Some(value) => known.registers.insert(dest.index, value),
                None => known.registers.remove(&dest.index),
            };
            // The slots are named from the register as it was.
            if rules.frame.contains(&dest.index) {
                known
                    .slots
                    .retain(|(register, _), _| *register != dest.index);
                known.taken.remove(&dest.index);
            }
        }
        Stmt::Store {
            addr,
            value: stored,
            width,
            ..
        } if rules.folds => match slot(rules.frame, addr) {
            Some(slot) => {
                match value(known, stored, image, rules).filter(|_| *width == 4) {
                    Some(value) => known.slots.insert(slot, value & 0xffff_ffff),
                    None => known.slots.remove(&slot),
                };
            }
            None if value(known, addr, image, rules).is_none() => known.forget_taken(),
            None => {}
        },
        Stmt::Call {
            convention,
            clobbers,
            outputs,
            ..
        } => {
            for register in convention.clobbered_by(*clobbers) {
                if !rules.fixed.contains(&register) {
                    known.registers.remove(&register);
                }
            }
            for output in outputs {
                if !rules.fixed.contains(&output.dest.index) {
                    known.registers.remove(&output.dest.index);
                }
            }
            known.forget_taken();
        }
        stmt => {
            for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
                known.registers.remove(&register);
            }
        }
    }
}

/// What is known where each block begins and ends, with `kept` in every
/// block that lacks it. None for a block no branch was followed into.
type Reached = Vec<Option<Facts>>;

fn solve(
    image: &Image,
    blocks: &[Block],
    extra_targets: &HashSet<u64>,
    rules: &Rules,
    kept: &Facts,
) -> (Reached, Reached) {
    let predecessors = super::flag_predecessors(blocks);
    let mut begins: Reached = vec![None; blocks.len()];
    let mut ends: Reached = vec![None; blocks.len()];
    let mut changed = true;
    while changed {
        changed = false;
        for (index, block) in blocks.iter().enumerate() {
            let begin = if index == 0 {
                Some(Facts::of(&rules.at_entry))
            } else if extra_targets.contains(&block.start) {
                Some(kept.clone())
            } else {
                let mut reached = predecessors[index]
                    .iter()
                    .filter_map(|before| ends[*before].as_ref());
                reached.next().map(|first| {
                    let mut common = first.clone();
                    for other in reached {
                        common.meet(other);
                    }
                    for (register, value) in &kept.registers {
                        common.registers.entry(*register).or_insert(*value);
                    }
                    for (slot, value) in &kept.slots {
                        common.slots.entry(*slot).or_insert(*value);
                    }
                    common
                })
            };
            let Some(begin) = begin else {
                continue;
            };
            if begins[index].as_ref() == Some(&begin) {
                continue;
            }
            let mut end = begin.clone();
            for stmt in &block.stmts {
                apply(&mut end, stmt, image, rules);
            }
            begins[index] = Some(begin);
            ends[index] = Some(end);
            changed = true;
        }
    }
    (begins, ends)
}

/// What is known where each block begins: what every block before it
/// leaves known alike. A register that keeps one value through the
/// function, where the blocks that set it agree on the value, has it in
/// every block, however the block is reached: also in a jump table's case
/// and in a block no branch leads to. Blocks that begin with nothing known
/// are left out.
pub(super) fn entries(
    image: &Image,
    blocks: &[Block],
    extra_targets: &HashSet<u64>,
    rules: &Rules,
) -> HashMap<u64, Facts> {
    let (begins, ends) = solve(image, blocks, extra_targets, rules, &Facts::default());
    let mut kept = Facts::default();
    for register in rules.fixed {
        let mut values = ends
            .iter()
            .flatten()
            .filter_map(|known| known.registers.get(register));
        if let Some(first) = values.next()
            && values.all(|value| value == first)
        {
            kept.registers.insert(*register, *first);
        }
    }
    // A word the first block stores in the frame stays there where no
    // later block stores to its slot, moves the register that addresses
    // it, or may write it through an address the code took.
    let later = || blocks.iter().skip(1).flat_map(|block| &block.stmts);
    if let Some(Some(first)) = ends.first() {
        for (&(register, offset), value) in &first.slots {
            let moved = later().any(|stmt| {
                matches!(stmt, Stmt::Assign { dest, value, .. }
                    if dest.index == register && !frame_load(rules.frame, value))
            });
            let stored = later().any(|stmt| {
                matches!(stmt, Stmt::Store { addr, .. }
                    if slot(rules.frame, addr) == Some((register, offset)))
            });
            let reached = ends.iter().flatten().any(|known| {
                known
                    .taken
                    .get(&register)
                    .is_some_and(|lowest| (offset as i64) >= (*lowest as i64))
            });
            if !moved && !stored && !reached {
                kept.slots.insert((register, offset), *value);
            }
        }
    }
    let begins = if kept.is_empty() {
        begins
    } else {
        solve(image, blocks, extra_targets, rules, &kept).0
    };
    blocks
        .iter()
        .zip(begins)
        .filter_map(|(block, begin)| {
            Some(begin.unwrap_or_else(|| kept.clone()))
                .filter(|known| !known.is_empty())
                .map(|known| (block.start, known))
        })
        .collect()
}

#[cfg(test)]
mod tests;