use super::{coalesce_copies, coalesce_render_copies};
use std::collections::BTreeMap;
use vlk_base::target::Isa;
use vlk_ir::ir::{BinOp, Block, Cond, Expr, FunctionIr, RegRef, Stmt, VARIABLE_BASE};
use vlk_types::types::CType;
fn assign(index: u16, value: Expr) -> Stmt {
Stmt::Assign {
dest: RegRef { index, width: 64 },
value,
at: None,
}
}
fn shifting_loop() -> FunctionIr {
let (v1, v4, v5) = (VARIABLE_BASE, VARIABLE_BASE + 3, VARIABLE_BASE + 4);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
assign(
v1,
Expr::Load {
addr: Box::new(Expr::reg(7, 64)),
width: 4,
signed: false,
},
),
assign(v4, Expr::reg(v1, 64)),
],
);
ir.blocks.push(Block {
start: 0x10,
stmts: vec![
assign(v4, Expr::bin(BinOp::Shr, Expr::reg(v4, 64), Expr::Const(4))),
assign(
v5,
Expr::bin(BinOp::And, Expr::reg(v1, 64), Expr::Const(0xf)),
),
assign(v1, Expr::reg(v4, 64)),
Stmt::Brif {
cond: Cond::Ne,
lhs: Expr::reg(v4, 64),
rhs: Expr::Const(0),
target: 0x10,
at: None,
},
],
});
ir.blocks.push(Block {
start: 0x20,
stmts: vec![Stmt::Ret {
value: Expr::reg(v5, 64),
at: None,
}],
});
ir
}
#[test]
fn a_loop_value_and_its_next_one_become_one_variable() {
let mut ir = shifting_loop();
coalesce_copies(&mut ir);
let text = ir.render();
let copies = ir
.blocks
.iter()
.flat_map(|block| &block.stmts)
.filter(|stmt| {
matches!(
stmt,
Stmt::Assign {
value: Expr::Reg { .. },
..
}
)
})
.count();
assert_eq!(copies, 0, "{text}");
let body = &ir.blocks[1].stmts;
assert!(
matches!(
&body[0],
Stmt::Assign {
value: Expr::Bin { op: BinOp::And, .. },
..
}
),
"{text}"
);
}
#[test]
fn variables_holding_different_values_at_once_stay_apart() {
let (v1, v2) = (VARIABLE_BASE, VARIABLE_BASE + 1);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
assign(v1, Expr::reg(7, 64)),
assign(v2, Expr::reg(v1, 64)),
assign(v1, Expr::bin(BinOp::Add, Expr::reg(v1, 64), Expr::Const(1))),
Stmt::Ret {
value: Expr::bin(BinOp::Add, Expr::reg(v1, 64), Expr::reg(v2, 64)),
at: None,
},
],
);
coalesce_copies(&mut ir);
assert!(
ir.blocks[0].stmts.iter().any(
|stmt| matches!(stmt, Stmt::Assign { dest, value: Expr::Reg { index, .. }, .. }
if dest.index == v2 && *index == v1)
),
"{}",
ir.render()
);
}
#[test]
fn renderer_copy_coalescing_preserves_the_returned_value_smt() {
if !vlk_smt::smt::Proofs::available() {
return;
}
let (source, copy, next, last, result) = (
VARIABLE_BASE,
VARIABLE_BASE + 1,
VARIABLE_BASE + 2,
VARIABLE_BASE + 3,
VARIABLE_BASE + 4,
);
let before = [
assign(source, Expr::reg(7, 64)),
assign(copy, Expr::reg(source, 64)),
assign(next, Expr::reg(copy, 64)),
assign(last, Expr::reg(next, 64)),
assign(
result,
Expr::bin(BinOp::Add, Expr::reg(last, 64), Expr::Const(0x101)),
),
Stmt::Ret {
value: Expr::reg(result, 64),
at: None,
},
];
let mut after = FunctionIr::single_block(Isa::X86_64, before.to_vec());
let types = BTreeMap::from([
(source, CType::U64),
(copy, CType::U64),
(next, CType::U64),
(last, CType::U64),
(result, CType::U64),
]);
let Some(removable) = coalesce_render_copies(&mut after, &types) else {
panic!("the copy must be a renderer candidate");
};
assert!(
removable[0].iter().any(|remove| *remove),
"the copies must be coalesced"
);
let after = after.blocks[0]
.stmts
.iter()
.zip(&removable[0])
.filter_map(|(stmt, remove)| (!remove).then_some(stmt.clone()))
.collect::<Vec<_>>();
let mut proofs = vlk_smt::smt::Proofs::default();
proofs.program("renderer copy coalescing".to_owned(), &before, &after);
for bits in [8, 16, 32, 64] {
let mask = if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
};
let before = [
assign(source, Expr::reg(7, bits)),
assign(
copy,
Expr::bin(BinOp::And, Expr::reg(source, 64), Expr::Const(mask)),
),
assign(next, Expr::reg(copy, 64)),
assign(last, Expr::reg(next, 64)),
assign(
result,
Expr::bin(BinOp::Add, Expr::reg(last, 64), Expr::Const(0x101)),
),
Stmt::Ret {
value: Expr::reg(result, 64),
at: None,
},
];
let mut after = FunctionIr::single_block(Isa::X86_64, before.to_vec());
let types = BTreeMap::from([
(source, CType::U64),
(copy, CType::U64),
(next, CType::U64),
(last, CType::U64),
(result, CType::U64),
]);
let Some(removable) = coalesce_render_copies(&mut after, &types) else {
panic!("the masked copies must be renderer candidates");
};
assert!(
removable[0].iter().any(|remove| *remove),
"the masked copies must be coalesced at {bits} bits"
);
let after = after.blocks[0]
.stmts
.iter()
.zip(&removable[0])
.filter_map(|(stmt, remove)| (!remove).then_some(stmt.clone()))
.collect::<Vec<_>>();
proofs.program(
format!("renderer masked copy coalescing at {bits} bits"),
&before,
&after,
);
}
proofs.check();
}
#[test]
fn a_narrow_read_of_a_wider_value_is_no_copy() {
let (v1, v2) = (VARIABLE_BASE, VARIABLE_BASE + 1);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
assign(v1, Expr::reg(7, 64)),
assign(
v2,
Expr::bin(BinOp::And, Expr::reg(v1, 64), Expr::Const(0xffff_ffff)),
),
Stmt::Ret {
value: Expr::reg(v2, 64),
at: None,
},
],
);
coalesce_copies(&mut ir);
assert_eq!(ir.blocks[0].stmts.len(), 3, "{}", ir.render());
}
#[test]
fn values_a_register_held_one_after_another_become_one_variable() {
let (v1, v2, v3) = (VARIABLE_BASE, VARIABLE_BASE + 1, VARIABLE_BASE + 2);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
assign(v1, Expr::bin(BinOp::Add, Expr::reg(7, 64), Expr::Const(1))),
assign(v2, Expr::bin(BinOp::Mul, Expr::reg(v1, 64), Expr::Const(2))),
assign(v3, Expr::bin(BinOp::Add, Expr::reg(6, 64), Expr::Const(3))),
Stmt::Ret {
value: Expr::bin(BinOp::Add, Expr::reg(v2, 64), Expr::reg(v3, 64)),
at: None,
},
],
);
ir.variable_registers = [(v1, 0), (v2, 1), (v3, 0)].into_iter().collect();
let mut addressed = ir.clone();
coalesce_copies(&mut ir);
let written: Vec<u16> = ir.blocks[0]
.stmts
.iter()
.filter_map(|stmt| match stmt {
Stmt::Assign { dest, .. } => Some(dest.index),
_ => None,
})
.collect();
assert_eq!(written, [v1, v2, v1], "{}", ir.render());
addressed.blocks[0].stmts[3] = Stmt::Ret {
value: Expr::Load {
addr: Box::new(Expr::reg(v3, 64)),
width: 8,
signed: false,
},
at: None,
};
coalesce_copies(&mut addressed);
assert!(
matches!(&addressed.blocks[0].stmts[2], Stmt::Assign { dest, .. } if dest.index == v3),
"{}",
addressed.render()
);
}
#[test]
fn a_register_reused_for_a_pointer_copy_keeps_the_values_apart() {
let (v1, v2, v3, v4) = (
VARIABLE_BASE,
VARIABLE_BASE + 1,
VARIABLE_BASE + 2,
VARIABLE_BASE + 3,
);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
assign(v1, Expr::bin(BinOp::Add, Expr::reg(7, 64), Expr::Const(1))),
assign(v2, Expr::bin(BinOp::Mul, Expr::reg(v1, 64), Expr::Const(2))),
assign(v3, Expr::bin(BinOp::Add, Expr::reg(6, 64), Expr::Const(3))),
assign(v4, Expr::reg(v3, 64)),
Stmt::Ret {
value: Expr::bin(
BinOp::Add,
Expr::Load {
addr: Box::new(Expr::reg(v4, 64)),
width: 8,
signed: false,
},
Expr::reg(v2, 64),
),
at: None,
},
],
);
ir.variable_registers = [(v1, 0), (v2, 1), (v3, 0), (v4, 2)].into_iter().collect();
coalesce_copies(&mut ir);
let written: Vec<u16> = ir.blocks[0]
.stmts
.iter()
.filter_map(|stmt| match stmt {
Stmt::Assign { dest, .. } => Some(dest.index),
_ => None,
})
.collect();
assert_eq!(written, [v1, v2, v3], "{}", ir.render());
}
#[test]
fn coalesces_every_call_output_without_renaming_physical_sources() {
let output_registers = [32, 34, 36, 38];
let mut outputs =
vlk_ir::ir::fallback_call_outputs(vlk_types::types::Convention::Aapcs64, None);
outputs.retain(|output| matches!(output.register, 32 | 34));
outputs.extend([36, 38].into_iter().map(|register| vlk_ir::ir::CallOutput {
register,
dest: RegRef {
index: register,
width: 64,
},
}));
for (index, output) in outputs.iter_mut().enumerate() {
output.dest.index = VARIABLE_BASE + 4 + index as u16;
}
let mut stmts = vec![Stmt::Call {
kind: vlk_types::types::CallKind::Invoke,
target: Some(0x1000),
through: None,
convention: vlk_types::types::Convention::Aapcs64,
args: Some(Vec::new()),
floats_named: true,
abi: None,
clobbers: None,
outputs,
via: None,
at: None,
}];
for index in 0..4u16 {
stmts.push(Stmt::Assign {
dest: RegRef {
index: VARIABLE_BASE + index,
width: 64,
},
value: Expr::reg(VARIABLE_BASE + 4 + index, 64),
at: None,
});
}
for index in 0..4u16 {
stmts.push(Stmt::Store {
addr: Expr::Const(0x1000 + u64::from(index) * 8),
value: Expr::reg(VARIABLE_BASE + index, 64),
width: 8,
at: None,
});
}
stmts.push(Stmt::Ret {
value: Expr::Const(0),
at: None,
});
let mut ir = FunctionIr::single_block(Isa::AArch64, stmts);
let before = ir.clone();
coalesce_copies(&mut ir);
assert_eq!(ir.blocks[0].stmts.len(), 6, "{}", ir.render());
assert_eq!(
ir.blocks[0].stmts[0]
.call_outputs()
.iter()
.map(|output| output.register)
.collect::<Vec<_>>(),
output_registers
);
assert_eq!(
ir.blocks[0].stmts[0]
.call_outputs()
.iter()
.map(|output| output.dest.index)
.collect::<Vec<_>>(),
[
VARIABLE_BASE,
VARIABLE_BASE + 1,
VARIABLE_BASE + 2,
VARIABLE_BASE + 3
]
);
for seed in [0, 1, 0x1234_5678] {
let setup = vlk_eval::eval::Setup {
seed,
convention: vlk_eval::eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: &[],
memory: &[],
step_limit: 64,
};
let expected = vlk_eval::eval::run(&before, &setup);
assert!(
matches!(&expected, vlk_eval::eval::Outcome::Return { memory, .. } if memory.len() == 32)
);
assert_eq!(vlk_eval::eval::run(&ir, &setup), expected);
}
}