vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! What a lifter implements and the block it writes into.

use std::collections::HashSet;

use vlk_base::target::Isa;
use vlk_ir::ir::visit::{expr_reads, reads_memory};
use vlk_ir::ir::{Block, Expr, FLAG_OPERANDS, RegRef, Stmt};

use super::{constants, flags};

pub(super) struct Decoded<I> {
    pub(super) pc: u64,
    pub(super) next: u64,
    pub(super) instruction: I,
}

pub(super) trait Machine {
    type Instruction;

    fn branch_target(&self, instruction: &Self::Instruction, pc: u64) -> Option<u64>;
    /// Appends the instruction's statements and reports whether it ends the block.
    fn step(&mut self, instruction: &Self::Instruction, pc: u64) -> bool;
    /// The block the lifter writes into.
    fn out(&mut self) -> &mut Emitter;
    /// The address of the instruction a step's statements come from.
    fn origin(&self, _: &Self::Instruction, pc: u64) -> u64 {
        pc
    }
    /// The instruction's name, for the note on one whose operands the
    /// lifter cannot express.
    fn name(&self, _: &Self::Instruction) -> String {
        String::new()
    }
    /// The registers the instruction may write, for a statement that
    /// leaves it unsupported without saying which.
    fn written(&mut self, _: &Self::Instruction) -> Option<Vec<u16>> {
        None
    }
    /// Whether the instruction may change the flags.
    fn sets_flags(&self, _: &Self::Instruction) -> bool {
        false
    }
    /// Whether the instruction only reads the flags, so that leaving it
    /// unsupported leaves them as they were.
    fn reads_flags(&self, _: &Self::Instruction) -> bool {
        false
    }
    /// A block begins: what the lifter remembers of the instructions before
    /// it no longer holds.
    fn enter_block(&mut self) {}
    /// How the driver follows constants while it completes the calls.
    fn rules(&self) -> constants::Rules {
        constants::Rules::default()
    }
    /// Blocks an instruction that loops by itself adds after the one it ends
    /// (an x86 `rep` string instruction's body).
    fn take_extra_blocks(&mut self) -> Vec<(Block, Option<flags::Flags>)> {
        Vec::new()
    }
}

/// What an instruction is about to overwrite.
pub(super) enum Write<'a> {
    /// A register and, when the register then holds exactly it, the value it receives.
    Register(u16, Option<&'a Expr>),
    Memory,
}

/// The block a lifter writes an instruction's statements into, with the
/// flags its code leaves pending.
#[derive(Default)]
pub(super) struct Emitter {
    pub(super) stmts: Vec<Stmt>,
    pub(super) flags: flags::State,
    /// Whether an operand of the instruction being lifted was one the
    /// lifter cannot express, so that its effect would be lost.
    pub(super) incomplete: std::cell::Cell<bool>,
}

impl Emitter {
    /// A block whose flags are pending as given.
    #[cfg(test)]
    pub(super) fn pending(flags: Option<flags::Flags>) -> Self {
        Self {
            stmts: Vec::new(),
            flags: flags::State {
                pending: flags,
                touched: false,
                written: false,
            },
            incomplete: std::cell::Cell::new(false),
        }
    }

    /// The instruction being lifted leaves the flags as `flags` says, or
    /// in a way not known.
    pub(super) fn set_flags(&mut self, flags: Option<flags::Flags>) {
        self.flags.pending = flags;
        self.flags.written = true;
    }

    /// `cond` under the pending flags; flags set in another block are
    /// unknown.
    pub(super) fn test(&self, cond: vlk_ir::ir::Cond, isa: Isa) -> flags::Test {
        self.flags
            .pending
            .as_ref()
            .map_or(flags::Test::Unknown, |flags| flags.test(cond, isa))
    }

    /// Copies `value` into a register of its own and reads it from there.
    pub(super) fn hold(&mut self, value: Expr) -> Expr {
        self.preserve(Write::Register(vlk_ir::ir::EXCHANGE, None));
        self.stmts.push(Stmt::Assign {
            dest: RegRef {
                index: vlk_ir::ir::EXCHANGE,
                width: 64,
            },
            value,
            at: None,
        });
        Expr::reg(vlk_ir::ir::EXCHANGE, 64)
    }

    /// Before a write, keeps the pending compare testing the values its flags
    /// were set from: an operand equal to the value written reads the register
    /// afterwards, the operand of a written sum or difference is recovered from
    /// the register, and any other operand reading what is overwritten moves into
    /// a register of its own.
    pub(super) fn preserve(&mut self, write: Write<'_>) {
        let Some(flags) = &mut self.flags.pending else {
            return;
        };
        let clobbered = |expr: &Expr| match write {
            Write::Register(index, _) => {
                let mut reads = HashSet::new();
                expr_reads(expr, &mut reads);
                reads.contains(&index)
            }
            Write::Memory => reads_memory(expr),
        };
        for (slot, operand) in FLAG_OPERANDS.into_iter().zip(flags.operands_mut()) {
            if !clobbered(operand) {
                continue;
            }
            let width = match vlk_ir::ir::semantics::width(operand) {
                0 => 64,
                bits => bits as u8,
            };
            if let Write::Register(index, Some(value)) = write {
                if operand == value {
                    *operand = Expr::reg(index, width);
                    continue;
                }
                if let Some(recovered) = recover_operand(operand, value, index, width) {
                    *operand = recovered;
                    continue;
                }
            }
            self.stmts.push(Stmt::Assign {
                dest: RegRef {
                    index: slot,
                    width: 64,
                },
                value: operand.clone(),
                at: None,
            });
            *operand = Expr::reg(slot, width);
        }
    }
}

/// `a` from the register that receives `a - b`, `a + b` or `0 - a`, when
/// `b` does not read that register.
pub(super) fn recover_operand(operand: &Expr, value: &Expr, index: u16, width: u8) -> Option<Expr> {
    let Expr::Bin { op, lhs, rhs } = value else {
        return None;
    };
    // A negation is undone by negating the register.
    if *op == vlk_ir::ir::BinOp::Sub && matches!(lhs.as_ref(), Expr::Const(0)) && **rhs == *operand
    {
        return Some(Expr::bin(
            vlk_ir::ir::BinOp::Sub,
            Expr::constant(0),
            Expr::reg(index, width),
        ));
    }
    let inverse = match op {
        vlk_ir::ir::BinOp::Sub => vlk_ir::ir::BinOp::Add,
        vlk_ir::ir::BinOp::Add => vlk_ir::ir::BinOp::Sub,
        _ => return None,
    };
    let mut reads = HashSet::new();
    expr_reads(rhs, &mut reads);
    (**lhs == *operand && !reads.contains(&index))
        .then(|| Expr::bin(inverse, Expr::reg(index, width), rhs.as_ref().clone()))
}

#[cfg(test)]
mod tests;