//! Runs RV64GC code through RISC-V Linux and the IR interpreter.
use std::collections::HashSet;
use std::fmt::Write as _;
use std::fs;
use std::path::Path;
use std::process::Command;
use vlk_eval::eval;
use vlk_ir::ir::FunctionIr;
const PLATFORM: &str = "linux/riscv64";
const SYSTEM: &str = "alpine:3.20";
/// Whether the C compiler on PATH can build RISC-V code.
fn compiler_available() -> bool {
let probe = Command::new("clang")
.args([
"--target=riscv64-linux-gnu",
"-march=rv64gc",
"--print-supported-cpus",
])
.output();
match probe {
Ok(output) if output.status.success() => true,
other => {
eprintln!("skipping the RISC-V hardware check: no RISC-V compiler: {other:?}");
false
}
}
}
fn compile(assembly: &Path, executable: &Path) {
let build = Command::new("clang")
.args([
"--target=riscv64-linux-gnu",
"-march=rv64gc",
"-fuse-ld=lld",
"-nostdlib",
"-static",
"-Wl,-e,_start",
])
.arg(assembly)
.arg("-o")
.arg(executable)
.output()
.unwrap();
assert!(
build.status.success(),
"{}",
String::from_utf8_lossy(&build.stderr)
);
}
/// What the processor's result of a case is compared as.
#[derive(Clone, Copy, PartialEq)]
enum Kind {
/// Every bit.
Integer,
/// A double: any two NaNs are alike.
Double,
/// A single in the low half: any two NaNs are alike.
Single,
}
const DOUBLE: &str = "fmv.d.x fa0, a0\nfmv.d.x fa1, a1\n";
const SINGLE: &str = "fmv.w.x fa0, a0\nfmv.w.x fa1, a1\n";
/// The cases: the code of each takes a0 and a1 and leaves its result in a0.
fn cases() -> Vec<(String, Kind)> {
let mut cases: Vec<(String, Kind)> = Vec::new();
let mut integer = |code: &str| cases.push((code.to_owned(), Kind::Integer));
for name in [
"add", "sub", "sll", "slt", "sltu", "xor", "srl", "sra", "or", "and", "mul", "mulh",
"mulhsu", "mulhu", "div", "divu", "rem", "remu", "addw", "subw", "sllw", "srlw", "sraw",
"mulw", "divw", "divuw", "remw", "remuw",
] {
integer(&format!("{name} a0, a0, a1"));
}
for (name, immediate) in [
("addi", "-5"),
("addi", "2047"),
("slti", "-1"),
("slti", "100"),
("sltiu", "1"),
("sltiu", "-1"),
("xori", "-1"),
("xori", "0x555"),
("ori", "0x70f"),
("andi", "0xff"),
("andi", "-16"),
("slli", "1"),
("slli", "13"),
("slli", "63"),
("srli", "1"),
("srli", "32"),
("srai", "7"),
("srai", "63"),
("addiw", "0"),
("addiw", "-1"),
("slliw", "3"),
("slliw", "31"),
("srliw", "4"),
("srliw", "31"),
("sraiw", "9"),
] {
integer(&format!("{name} a0, a0, {immediate}"));
}
integer("lui a0, 0x12345");
integer("lui a0, 0xfffff");
integer("lui a2, 0x80000\nadd a0, a0, a2");
integer("mv a0, a1");
integer("neg a0, a1");
integer("add a0, zero, zero");
integer("add zero, a0, a1");
for (load, width) in [
("lb", "sb"),
("lbu", "sb"),
("lh", "sh"),
("lhu", "sh"),
("lw", "sw"),
("lwu", "sw"),
("ld", "sd"),
] {
integer(&format!(
"addi sp, sp, -32\nsd a1, 8(sp)\n{width} a0, 8(sp)\n{load} a0, 8(sp)\naddi sp, sp, 32"
));
}
for branch in ["beq", "bne", "blt", "bge", "bltu", "bgeu"] {
integer(&format!("{branch} a0, a1, 1f\nli a0, 0\nret\n1:\nli a0, 1"));
}
integer("beqz a0, 1f\nmv a0, a1\n1:");
integer("bgtz a1, 1f\nneg a1, a1\n1:\nadd a0, a0, a1");
integer("jal a2, 1f\n1:\nli a0, 3");
integer(
"2:\nauipc a2, %pcrel_hi(1f)\njalr zero, %pcrel_lo(2b)(a2)\nli a0, 9\n1:\naddi a0, a0, 1",
);
for width in ["w", "d"] {
for name in [
"amoswap", "amoadd", "amoxor", "amoand", "amoor", "amomin", "amomax", "amominu",
"amomaxu",
] {
integer(&format!(
"addi sp, sp, -32\nsd a0, 8(sp)\naddi a2, sp, 8\n{name}.{width} a3, a1, (a2)\nld a0, 8(sp)\nxor a0, a0, a3\naddi sp, sp, 32"
));
integer(&format!(
"addi sp, sp, -32\nsd a0, 8(sp)\naddi a2, sp, 8\n{name}.{width} a0, a1, (a2)\naddi sp, sp, 32"
));
}
}
for (name, suffix) in [
("fcvt.w", ""),
("fcvt.wu", ""),
("fcvt.l", ""),
("fcvt.lu", ""),
] {
for mode in ["rtz", "rne", "rdn", "rup", "rmm"] {
integer(&format!("{DOUBLE}{name}.d{suffix} a0, fa0, {mode}"));
integer(&format!("{SINGLE}{name}.s{suffix} a0, fa0, {mode}"));
}
}
for compare in ["feq", "flt", "fle"] {
integer(&format!("{DOUBLE}{compare}.d a0, fa0, fa1"));
integer(&format!("{SINGLE}{compare}.s a0, fa0, fa1"));
}
integer(&format!("{SINGLE}fmv.x.w a0, fa0"));
integer(&format!("{SINGLE}fmv.x.d a0, fa0"));
integer("addi sp, sp, -16\nfmv.w.x fa0, a0\nfsw fa0, 4(sp)\nlw a0, 4(sp)\naddi sp, sp, 16");
integer("addi sp, sp, -16\nsw a0, 4(sp)\nflw fa0, 4(sp)\nfmv.x.d a0, fa0\naddi sp, sp, 16");
integer("addi sp, sp, -16\nfmv.d.x fa0, a0\nfsd fa0, 8(sp)\nld a0, 8(sp)\naddi sp, sp, 16");
integer("addi sp, sp, -16\nsd a0, 8(sp)\nfld fa0, 8(sp)\nfmv.x.d a0, fa0\naddi sp, sp, 16");
for sign in ["fsgnj", "fsgnjn", "fsgnjx"] {
integer(&format!("{DOUBLE}{sign}.d fa0, fa0, fa1\nfmv.x.d a0, fa0"));
integer(&format!("{SINGLE}{sign}.s fa0, fa0, fa1\nfmv.x.d a0, fa0"));
}
for extreme in ["fmin", "fmax"] {
integer(&format!(
"{DOUBLE}{extreme}.d fa0, fa0, fa1\nfmv.x.d a0, fa0"
));
integer(&format!(
"{SINGLE}{extreme}.s fa0, fa0, fa1\nfmv.x.d a0, fa0"
));
}
integer(&format!("{DOUBLE}fclass.d a0, fa0"));
integer(&format!("{SINGLE}fclass.s a0, fa0"));
integer(&format!("{DOUBLE}fclass.d a0, fa1"));
integer(&format!("{SINGLE}fclass.s a0, fa1"));
for unary in ["fmv", "fneg", "fabs"] {
integer(&format!("{DOUBLE}{unary}.d fa0, fa1\nfmv.x.d a0, fa0"));
integer(&format!("{SINGLE}{unary}.s fa0, fa1\nfmv.x.d a0, fa0"));
}
let mut float = |code: String, kind: Kind| cases.push((code, kind));
for name in ["fadd", "fsub", "fmul", "fdiv"] {
float(
format!("{DOUBLE}{name}.d fa0, fa0, fa1\nfmv.x.d a0, fa0"),
Kind::Double,
);
float(
format!("{SINGLE}{name}.s fa0, fa0, fa1\nfmv.x.d a0, fa0"),
Kind::Single,
);
}
for name in ["fmadd", "fmsub", "fnmsub", "fnmadd"] {
float(
format!("{DOUBLE}fmv.d.x fa2, a0\n{name}.d fa0, fa0, fa1, fa2\nfmv.x.d a0, fa0"),
Kind::Double,
);
float(
format!("{SINGLE}fmv.w.x fa2, a1\n{name}.s fa0, fa0, fa1, fa2\nfmv.x.d a0, fa0"),
Kind::Single,
);
}
float(
format!("{DOUBLE}fsqrt.d fa0, fa0\nfmv.x.d a0, fa0"),
Kind::Double,
);
float(
format!("{SINGLE}fsqrt.s fa0, fa0\nfmv.x.d a0, fa0"),
Kind::Single,
);
float(
format!("{DOUBLE}fcvt.s.d fa0, fa0\nfmv.x.d a0, fa0"),
Kind::Single,
);
float(
format!("{SINGLE}fcvt.d.s fa0, fa0\nfmv.x.d a0, fa0"),
Kind::Double,
);
for source in ["w", "wu", "l", "lu"] {
float(
format!("fcvt.d.{source} fa0, a0\nfmv.x.d a0, fa0"),
Kind::Double,
);
float(
format!("fcvt.s.{source} fa0, a0\nfmv.x.d a0, fa0"),
Kind::Single,
);
}
cases
}
const EDGES: [u64; 40] = [
0,
1,
2,
7,
31,
32,
33,
63,
64,
255,
0x7fff_ffff,
0x8000_0000,
0xffff_ffff,
0x1_0000_0000,
0xffff_ffff_8000_0000,
0x7fff_ffff_ffff_ffff,
0x8000_0000_0000_0000,
0xffff_ffff_ffff_fffe,
u64::MAX,
0x0123_4567_89ab_cdef,
// 1.0, -1.5, 2.5, 0.5, 2^31, 2^63, -2^63, infinities, a NaN and a
// subnormal, as doubles.
0x3ff0_0000_0000_0000,
0xbff8_0000_0000_0000,
0x4004_0000_0000_0000,
0x3fe0_0000_0000_0000,
0x41e0_0000_0000_0000,
0x43e0_0000_0000_0000,
0xc3e0_0000_0000_0000,
0x7ff0_0000_0000_0000,
0xfff0_0000_0000_0000,
0x7ff8_0000_0000_0000,
0x0000_0000_0000_0001,
// A signalling NaN and a negative NaN, as doubles.
0x7ff0_0000_0000_0001,
0xfff8_0000_0000_0000,
// 1.0, -2.5 and 2^31 as singles in the low half; then a signalling
// NaN, a NaN, an infinity and a subnormal.
0x3f80_0000,
0xc020_0000,
0x4f00_0000,
0x7f80_0001,
0x7fc0_0000,
0xff80_0000,
0x0000_0002,
];
#[test]
fn instructions_match_riscv_linux() {
if !compiler_available() || !super::docker_available(PLATFORM, SYSTEM, "riscv64") {
return;
}
let scratch =
Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")).join("target/riscv64-hardware");
fs::create_dir_all(&scratch).unwrap();
let cases = cases();
let size = cases.len() * EDGES.len() * EDGES.len() * 8;
let mut source = format!(
".text\n.global _start\n.type _start, %function\n_start:\n.option push\n.option norelax\nla gp, __global_pointer$\n.option pop\nla s0, cases\nla s1, results\nli s2, {}\n",
cases.len()
);
// Every case runs on every pair of edges; then the results are written
// out, as many bytes as each call takes, and the program exits.
writeln!(
source,
"each_case:\nld s3, 0(s0)\nla s4, edges\nli s5, {count}\neach_left:\nla s6, edges\nli s7, {count}\neach_right:\nld a0, 0(s4)\nld a1, 0(s6)\njalr s3\nsd a0, 0(s1)\naddi s1, s1, 8\naddi s6, s6, 8\naddi s7, s7, -1\nbnez s7, each_right\naddi s4, s4, 8\naddi s5, s5, -1\nbnez s5, each_left\naddi s0, s0, 8\naddi s2, s2, -1\nbnez s2, each_case\nla s1, results\nli s2, {size}\nwrite_more:\nli a0, 1\nmv a1, s1\nmv a2, s2\nli a7, 64\necall\nblez a0, done\nadd s1, s1, a0\nsub s2, s2, a0\nbnez s2, write_more\ndone:\nli a0, 0\nli a7, 93\necall",
count = EDGES.len()
)
.unwrap();
for (index, (code, _)) in cases.iter().enumerate() {
writeln!(
source,
".balign 4\n.type case_{index}, %function\ncase_{index}:\n{code}\nret\n.size case_{index}, .-case_{index}"
)
.unwrap();
}
source.push_str(".section .rodata\n.balign 8\ncases:\n");
for index in 0..cases.len() {
writeln!(source, ".quad case_{index}").unwrap();
}
source.push_str("edges:\n");
for edge in EDGES {
writeln!(source, ".quad {edge:#x}").unwrap();
}
writeln!(source, ".bss\n.balign 8\nresults: .space {size}").unwrap();
let assembly = scratch.join("cases.s");
let executable = scratch.join("cases.elf");
fs::write(&assembly, source).unwrap();
compile(&assembly, &executable);
let output = super::docker_run(PLATFORM, SYSTEM, &scratch, "cases.elf");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(output.stdout.len(), size);
let program = vlk_program::program::Program::new(crate::lift::load(&executable).unwrap());
let (results, remainder) = output.stdout.as_chunks::<8>();
assert!(remainder.is_empty());
let mut results = results.iter();
let mut compared = 0;
let mut undefined = 0;
let mut differences = Vec::new();
for (index, (code, kind)) in cases.iter().enumerate() {
let name = format!("case_{index}");
let function = program
.image
.functions
.values()
.find(|function| function.name.as_deref() == Some(&name))
.unwrap();
let mut ir = FunctionIr::single_block(program.image.isa, Vec::new());
ir.blocks = match super::lift(
&program,
function.addr,
function.size.unwrap(),
&HashSet::new(),
) {
Ok(blocks) => blocks,
Err(error) => panic!("{code}: not lifted: {error}"),
};
assert_eq!(super::unsupported(&ir), None, "{code}: {}", ir.render());
let mut reported = false;
for left in EDGES {
for right in EDGES {
let expected = u64::from_le_bytes(*results.next().unwrap());
let registers = [
(0, left),
(1, right),
(vlk_arch::arch::riscv64::SP, 0x7fff_0000),
];
let same = |value: u64| match kind {
Kind::Integer => value == expected,
Kind::Double => {
value == expected
|| (f64::from_bits(value).is_nan() && f64::from_bits(expected).is_nan())
}
Kind::Single => {
value == expected
|| (f32::from_bits(value as u32).is_nan()
&& f32::from_bits(expected as u32).is_nan()
&& value >> 32 == expected >> 32)
}
};
match eval::run(&ir, &super::setup(®isters)) {
eval::Outcome::Return { value, .. } if same(value) => compared += 1,
eval::Outcome::Unknown("division by zero") => undefined += 1,
outcome => {
if !reported {
reported = true;
differences.push(format!(
"{code}\n ({left:#x}, {right:#x}): processor {expected:#x}, IR {outcome:?}\n{}",
ir.render()
));
}
}
}
}
}
}
assert!(
differences.is_empty(),
"{} cases differ\n\n{}",
differences.len(),
differences.join("\n\n")
);
eprintln!(
"{compared} RISC-V Linux results agree; {undefined} divide by zero, which the IR leaves undefined"
);
}