vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Decoding code into the steps the lifter takes: an instruction with its
//! delay slot, and the pairs of instructions that make one unaligned access.

use std::collections::HashSet;

use super::decode::{self, Alu, Branch, FloatFormat, Instruction, Op};
use super::{Step, text};
use crate::lift::Decoded;

/// The general register an instruction writes, if it writes one.
pub(super) fn written_register(instruction: &Instruction) -> Option<u8> {
    let Instruction { op, rt, rd, .. } = *instruction;
    Some(match op {
        Op::Register(_)
        | Op::Shift(_)
        | Op::MultiplyLow
        | Op::MoveFromHi
        | Op::MoveFromLo
        | Op::MoveIfZero
        | Op::MoveIfNotZero
        | Op::CountLeadingZeros
        | Op::CountLeadingOnes
        | Op::SignExtendByte
        | Op::SignExtendHalf
        | Op::SwapBytesInHalves => rd,
        Op::Immediate(_)
        | Op::Lui
        | Op::Extract
        | Op::Insert
        | Op::Load { .. }
        | Op::LoadLeft
        | Op::LoadRight
        | Op::LoadLinked
        | Op::StoreConditional
        | Op::ReadHardware => rt,
        _ => return None,
    })
}

/// Whether two instructions are the halves of one unaligned word access:
/// the left half, which holds the word's most significant bytes, three
/// bytes past the right on a little-endian processor and three before it
/// on a big-endian one. The access as a whole, at the word's address, in
/// the form of a right half.
pub(super) fn unaligned_pair(
    first: &Instruction,
    second: &Instruction,
    big: bool,
) -> Option<Instruction> {
    let (right, left) = match (first.op, second.op) {
        (Op::LoadRight, Op::LoadLeft) | (Op::StoreRight, Op::StoreLeft) => (first, second),
        (Op::LoadLeft, Op::LoadRight) | (Op::StoreLeft, Op::StoreRight) => (second, first),
        _ => return None,
    };
    let (low, high) = if big { (left, right) } else { (right, left) };
    (right.rs == left.rs
        && right.rt == left.rt
        && high.imm == low.imm + 3
        && (right.rs != right.rt || matches!(right.op, Op::StoreRight)))
    .then_some(Instruction {
        imm: low.imm,
        ..*right
    })
}

/// The pairs of float registers an instruction uses for a double, or
/// whose odd register it names: a bit for each.
pub(super) fn shared_pairs(instruction: &Instruction) -> u16 {
    let Instruction {
        op,
        rs,
        rt,
        rd,
        imm,
        ..
    } = *instruction;
    let (fr, ft, fs, fd) = (i64::from(rs), i64::from(rt), i64::from(rd), imm);
    let operands: &[(i64, bool)] = match op {
        Op::FloatArithmetic { double, .. } => &[(fd, double), (fs, double), (ft, double)],
        Op::FloatMultiplyAdd { double, .. } => {
            &[(fd, double), (fr, double), (fs, double), (ft, double)]
        }
        Op::FloatConvert { from, double } => &[(fd, double), (fs, from == FloatFormat::Double)],
        Op::FloatToWord { double, .. } => &[(fd, false), (fs, double)],
        Op::FloatCompare { double, .. } => &[(fs, double), (ft, double)],
        Op::FloatSelect { double, .. } => &[(fd, double), (fs, double)],
        Op::FloatTransfer { high, .. } => &[(fs, high)],
        Op::FloatLoad { double } | Op::FloatStore { double } => &[(ft, double)],
        Op::FloatLoadIndexed { double } => &[(fd, double)],
        Op::FloatStoreIndexed { double } => &[(fs, double)],
        _ => &[],
    };
    operands
        .iter()
        .filter(|(register, double)| *double || register & 1 == 1)
        .fold(0, |pairs, (register, _)| pairs | 1 << ((register & 31) / 2))
}

/// `sll $zero, $zero, 0`
pub(super) const NOP: Instruction = Instruction {
    op: Op::Shift(Alu::ShiftLeft),
    rs: 0,
    rt: 0,
    rd: 0,
    imm: 0,
    word: 0,
};

/// The bytes a load or store reaches, as offsets from its base register.
pub(super) fn bytes_reached(instruction: &Instruction, big: bool) -> Option<std::ops::Range<i64>> {
    let imm = instruction.imm;
    // The half at the word's lowest address.
    let first = match instruction.op {
        Op::LoadLeft | Op::StoreLeft => big,
        _ => !big,
    };
    match instruction.op {
        Op::Load { bytes, .. } | Op::Store { bytes } => Some(imm..imm + i64::from(bytes)),
        Op::LoadLeft | Op::StoreLeft | Op::LoadRight | Op::StoreRight if first => {
            Some(imm..imm + 4)
        }
        Op::LoadLeft | Op::StoreLeft | Op::LoadRight | Op::StoreRight => Some(imm - 3..imm + 1),
        _ => None,
    }
}

/// How far past one half of an unaligned access its other half is looked
/// for.
pub(super) const PAIR_REACH: usize = 8;

/// The other half of the unaligned access `first`, at `index`, begins,
/// when a few instructions that do not disturb the access lie between the
/// two: its index and the access as a whole. Compilers put the loads of
/// what a call takes between the halves.
pub(super) fn separated_pair(
    at: &impl Fn(usize) -> Option<Instruction>,
    index: usize,
    first: &Instruction,
    big: bool,
) -> Option<(usize, Instruction)> {
    let store = match first.op {
        Op::LoadLeft | Op::LoadRight => false,
        Op::StoreLeft | Op::StoreRight => true,
        _ => return None,
    };
    for other in index + 2..=index + PAIR_REACH {
        let between = at(other - 1)?;
        let registers = [between.rs, between.rt, between.rd];
        // The instruction between must leave the value and the address
        // alone, and the memory too: a load reads nothing a store between
        // could change, and a store is seen by no load between.
        let apart = between.rs == first.rs
            && match (bytes_reached(first, big), bytes_reached(&between, big)) {
                (Some(access), Some(other)) => {
                    access.end <= other.start || other.end <= access.start
                }
                _ => false,
            };
        let quiet = match between.op {
            Op::Register(_) | Op::Immediate(_) | Op::Shift(_) | Op::Lui => true,
            Op::Load { .. } | Op::LoadLeft | Op::LoadRight => !store || apart,
            Op::Store { .. } | Op::StoreLeft | Op::StoreRight => apart,
            _ => false,
        };
        if !quiet
            || (!store && registers.contains(&first.rt))
            || written_register(&between)
                .is_some_and(|written| written != 0 && (written == first.rt || written == first.rs))
        {
            return None;
        }
        if let Some(whole) = unaligned_pair(first, &at(other)?, big) {
            return Some((other, whole));
        }
    }
    None
}

pub(in crate::lift) fn decode(bytes: &[u8], addr: u64) -> (Vec<Decoded<Step>>, Option<String>) {
    decode_ordered(bytes, addr, false)
}

/// `decode` for code stored most significant byte first.
pub(in crate::lift) fn decode_big(bytes: &[u8], addr: u64) -> (Vec<Decoded<Step>>, Option<String>) {
    decode_ordered(bytes, addr, true)
}

pub(super) fn decode_ordered(
    bytes: &[u8],
    addr: u64,
    big: bool,
) -> (Vec<Decoded<Step>>, Option<String>) {
    let mut decoded = Vec::new();
    let words = bytes.as_chunks::<4>().0;
    let at = |index: usize| words.get(index).and_then(|word| decode::decode(word, big));
    // The instructions, by index, that a branch in the code goes to.
    let targets: HashSet<usize> = (0..words.len())
        .filter_map(|index| {
            let pc = addr.wrapping_add(index as u64 * 4);
            let target = text::target(&at(index)?, pc)?;
            usize::try_from(target.checked_sub(addr)? / 4).ok()
        })
        .collect();
    let mut joined: HashSet<usize> = HashSet::new();
    let shared_pairs = (0..words.len())
        .filter_map(&at)
        .fold(0, |pairs, instruction| pairs | shared_pairs(&instruction));
    let mut index = 0;
    // Where the delay slot of a branch that may skip it goes on to.
    let mut then = None;
    while index < words.len() {
        let pc = addr.wrapping_add(index as u64 * 4);
        let Some(instruction) = at(index) else {
            return (
                decoded,
                Some(format!("undecodable instruction at 0x{pc:x}")),
            );
        };
        let after = then.take();
        // The second half of a pair joined at its first half.
        let instruction = if joined.contains(&index) {
            NOP
        } else {
            instruction
        };
        let likely = matches!(
            instruction.op,
            Op::Branch { likely: true, .. } | Op::FloatBranch { likely: true, .. }
        );
        let (step, length) = if instruction.has_delay_slot() && !likely && after.is_none() {
            match at(index + 1) {
                // A transfer in a delay slot is not defined.
                Some(slot) if !slot.has_delay_slot() => (
                    Step {
                        instruction,
                        slot: Some(slot),
                        then: None,
                        unaligned: false,
                        shared_pairs,
                    },
                    2,
                ),
                _ => {
                    return (
                        decoded,
                        Some(format!("no delay slot for the transfer at 0x{pc:x}")),
                    );
                }
            }
        } else if let Some(next) = at(index + 1)
            && after.is_none()
            // A branch to the second half keeps the two apart.
            && !targets.contains(&(index + 1))
            && let Some(joined) = unaligned_pair(&instruction, &next, big)
        {
            (
                Step {
                    instruction: joined,
                    slot: None,
                    then: None,
                    unaligned: true,
                    shared_pairs,
                },
                2,
            )
        } else if after.is_none()
            && let Some((other, whole)) = separated_pair(&at, index, &instruction, big)
            && !targets
                .iter()
                .any(|target| (index + 1..=other).contains(target))
        {
            joined.insert(other);
            (
                Step {
                    instruction: whole,
                    slot: None,
                    then: None,
                    unaligned: true,
                    shared_pairs,
                },
                1,
            )
        } else {
            if likely {
                then = text::target(&instruction, pc);
            }
            (
                Step {
                    instruction,
                    slot: None,
                    then: after,
                    unaligned: false,
                    shared_pairs,
                },
                1,
            )
        };
        let Some(next) = pc.checked_add(length * 4) else {
            return (
                decoded,
                Some(format!("instruction address overflows at 0x{pc:x}")),
            );
        };
        decoded.push(Decoded {
            pc,
            next,
            instruction: step,
        });
        index += length as usize;
    }
    (decoded, None)
}

/// Whether a branch is taken whatever its registers hold: `b` and `bal`,
/// which compare $zero with itself.
pub(super) fn always_taken(instruction: &Instruction) -> bool {
    match instruction.op {
        Op::Branch {
            test: Branch::Equal,
            ..
        } => instruction.rs == 0 && instruction.rt == 0,
        Op::Branch {
            test: Branch::GreaterEqualZero,
            ..
        } => instruction.rs == 0,
        _ => false,
    }
}