vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
use super::*;
use vlk_base::target::Isa;
use vlk_ir::ir::{BinOp, Block, Cond, RegRef};
use vlk_types::types::Param;

fn redundant_copy_candidate(ir: &FunctionIr) -> Option<FunctionIr> {
    let Some(renamed) = redundant_copy_renames(ir) else {
        return None;
    };
    let mut candidate = ir.clone();
    for block in &mut candidate.blocks {
        block.stmts.retain(
            |stmt| !matches!(stmt, Stmt::Assign { dest, .. } if renamed.contains_key(&dest.index)),
        );
        for stmt in &mut block.stmts {
            crate::passes::coalesce::rename(stmt, &renamed);
        }
    }
    Some(candidate)
}

fn copy(dest: u16, source: u16) -> Stmt {
    Stmt::Assign {
        dest: RegRef {
            index: dest,
            width: 64,
        },
        value: Expr::reg(source, 64),
        at: None,
    }
}

fn diamond() -> FunctionIr {
    let (source, dest) = (VARIABLE_BASE, VARIABLE_BASE + 1);
    let mut ir = FunctionIr::single_block(
        Isa::X86_64,
        vec![
            Stmt::Assign {
                dest: RegRef {
                    index: source,
                    width: 64,
                },
                value: Expr::bin(BinOp::Xor, Expr::reg(7, 64), Expr::Const(123)),
                at: None,
            },
            Stmt::Brif {
                cond: vlk_ir::ir::Cond::Eq,
                lhs: Expr::reg(6, 64),
                rhs: Expr::Const(0),
                target: 2,
                at: None,
            },
        ],
    );
    ir.params = vec![
        Param {
            index: 7,
            name: "input".into(),
            ty: CType::U64,
        },
        Param {
            index: 6,
            name: "flag".into(),
            ty: CType::U64,
        },
    ];
    ir.ret_type = CType::U64;
    ir.value_types = [(source, CType::U64), (dest, CType::U64)].into();
    for start in [1, 2] {
        ir.blocks.push(Block {
            start,
            stmts: vec![
                copy(dest, source),
                Stmt::Br {
                    target: Some(3),
                    at: None,
                },
            ],
        });
    }
    ir.blocks.push(Block {
        start: 3,
        stmts: vec![Stmt::Ret {
            value: Expr::bin(BinOp::Add, Expr::reg(dest, 64), Expr::reg(source, 64)),
            at: None,
        }],
    });
    ir
}

#[test]
fn copies_agree_at_joins_and_keep_narrow_reads() {
    let mut ir = diamond();
    ir.blocks[3].stmts[0] = Stmt::Ret {
        value: Expr::bin(
            BinOp::Add,
            Expr::reg(VARIABLE_BASE + 1, 8),
            Expr::bin(
                BinOp::Add,
                Expr::reg(VARIABLE_BASE + 1, 64),
                Expr::reg(VARIABLE_BASE, 64),
            ),
        ),
        at: None,
    };
    let folded = redundant_copy_candidate(&ir).expect("both paths copy the same stable value");
    assert!(
        matches!(&folded.blocks[3].stmts[0], Stmt::Ret { value: Expr::Bin { lhs, .. }, .. }
        if **lhs == Expr::reg(VARIABLE_BASE, 8))
    );
    assert!(
        folded.blocks[1]
            .stmts
            .iter()
            .all(|stmt| !matches!(stmt, Stmt::Assign { .. }))
    );
}

#[test]
fn missing_definitions_and_source_overwrites_keep_snapshots() {
    for case in 0..4 {
        let mut ir = diamond();
        match case {
            0 => {
                ir.blocks[2].stmts.remove(0);
            }
            1 => ir.blocks[2].stmts.insert(1, copy(VARIABLE_BASE, 7)),
            2 => ir.blocks[3].stmts.insert(0, copy(VARIABLE_BASE, 7)),
            _ => ir.blocks[2].stmts[0] = copy(VARIABLE_BASE + 1, 7),
        }
        assert!(redundant_copy_candidate(&ir).is_none(), "case {case}");
    }
}

#[test]
fn loops_must_reestablish_copies_after_source_updates() {
    let mut ir = diamond();
    ir.blocks[3].stmts = vec![
        Stmt::Assign {
            dest: RegRef {
                index: VARIABLE_BASE,
                width: 64,
            },
            value: Expr::bin(BinOp::Add, Expr::reg(VARIABLE_BASE, 64), Expr::Const(1)),
            at: None,
        },
        Stmt::Brif {
            cond: Cond::Ne,
            lhs: Expr::reg(VARIABLE_BASE + 1, 64),
            rhs: Expr::Const(0),
            target: 3,
            at: None,
        },
    ];
    assert!(redundant_copy_candidate(&ir).is_none());
}

#[test]
fn copy_chains_do_not_extend_source_lifetimes() {
    let (source, first, second) = (VARIABLE_BASE, VARIABLE_BASE + 1, VARIABLE_BASE + 2);
    let mut ir = diamond();
    ir.blocks.truncate(1);
    ir.blocks[0].stmts.truncate(1);
    ir.blocks[0].stmts.extend([
        copy(first, source),
        copy(second, first),
        Stmt::Assign {
            dest: RegRef {
                index: source,
                width: 64,
            },
            value: Expr::bin(BinOp::Add, Expr::reg(source, 64), Expr::Const(1)),
            at: None,
        },
        Stmt::Ret {
            value: Expr::bin(BinOp::Add, Expr::reg(second, 64), Expr::reg(source, 64)),
            at: None,
        },
    ]);
    ir.value_types.insert(second, CType::U64);
    let renamed = redundant_copy_renames(&ir).expect("the first copy is redundant");
    assert_eq!(renamed, HashMap::from([(first, source)]));
}