mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 20:41:11 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb1372cd70 | ||
|
|
3ff9ddde24 | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d |
No files matched your search
@@ -11,6 +11,7 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
|
||||
@@ -170,7 +170,10 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
|
||||
@@ -117,7 +117,10 @@ pub fn apply_relocations(
|
||||
size: reloc_size,
|
||||
})?;
|
||||
|
||||
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
|
||||
if reloc_file_offset
|
||||
.checked_add(reloc_size as usize)
|
||||
.is_none_or(|end| end > bytes.len())
|
||||
{
|
||||
return Err(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
@@ -127,13 +130,20 @@ pub fn apply_relocations(
|
||||
let mut read_bytes = 0usize;
|
||||
let max_read = reloc_size as usize;
|
||||
|
||||
while read_bytes + 8 <= max_read {
|
||||
while read_bytes < max_read {
|
||||
// A partial block header after the last block is malformed, not padding.
|
||||
if max_read - read_bytes < 8 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: reloc_file_offset + read_bytes,
|
||||
});
|
||||
}
|
||||
let block_start = reloc_file_offset + read_bytes;
|
||||
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
|
||||
let block_size =
|
||||
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
|
||||
|
||||
if block_size < 8 {
|
||||
// A block is an 8-byte header followed by whole 2-byte entries.
|
||||
if block_size < 8 || block_size % 2 != 0 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: block_start,
|
||||
});
|
||||
@@ -166,6 +176,15 @@ pub fn apply_relocations(
|
||||
let target_rva = page_rva
|
||||
.checked_add(offset_in_page)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
// The 8-byte target must lie inside the image, not in other mapped memory.
|
||||
if target_rva
|
||||
.checked_add(8)
|
||||
.is_none_or(|end| end > pe.size_of_image)
|
||||
{
|
||||
return Err(RelocationError::TargetOutOfBounds {
|
||||
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
|
||||
});
|
||||
}
|
||||
let target_va = loaded_base
|
||||
.checked_add(target_rva as u64)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
@@ -213,8 +232,8 @@ fn find_reloc_directory(
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -224,10 +243,19 @@ fn find_reloc_directory(
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
|
||||
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
|
||||
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number_of_rva_and_sizes = u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if number_of_rva_and_sizes < 6 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let reloc_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 152..opt_offset + 156]
|
||||
|
||||
+136
-16
@@ -11,6 +11,14 @@ use crate::{
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)?;
|
||||
}
|
||||
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
// Allocate and initialize Win64 TEB (Thread Environment Block)
|
||||
// Layout in TEB:
|
||||
// +0x08: StackBase (highest address)
|
||||
// +0x10: StackLimit (lowest address)
|
||||
// +0x30: Self pointer (TEB linear address)
|
||||
// +0x58: ThreadLocalStoragePointer
|
||||
let teb_base = layout.tls_base.saturating_add(0x10000);
|
||||
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Base relocation regression tests (#81).
|
||||
//!
|
||||
//! Images are built byte by byte from the PE/COFF layout: data directory 5
|
||||
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
|
||||
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
|
||||
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
|
||||
|
||||
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
|
||||
|
||||
const PREFERRED: u64 = 0x1_4000_0000;
|
||||
const RELOC_FILE: usize = 0x400;
|
||||
|
||||
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
|
||||
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
|
||||
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
|
||||
|
||||
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
|
||||
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
|
||||
// .reloc fills the image up to SizeOfImage (0x3000).
|
||||
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
|
||||
];
|
||||
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
|
||||
let h = opt + 240 + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
}
|
||||
|
||||
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
|
||||
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
|
||||
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
|
||||
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
|
||||
pe
|
||||
}
|
||||
|
||||
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
|
||||
let mut b = page_rva.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for e in entries {
|
||||
b.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
|
||||
fn standard_table() -> Vec<u8> {
|
||||
block(0x1000, &[0xA010, 0xA018, 0x0000])
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
|
||||
let pe = ParsedPe::parse(bytes).expect("parse");
|
||||
let mut memory = GuestMemory::new();
|
||||
for s in &pe.sections {
|
||||
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base + u64::from(s.virtual_address),
|
||||
0x200,
|
||||
s.permissions,
|
||||
raw,
|
||||
)
|
||||
.expect("map");
|
||||
}
|
||||
(pe, memory)
|
||||
}
|
||||
|
||||
fn relocate(
|
||||
bytes: &[u8],
|
||||
base: u64,
|
||||
) -> (
|
||||
Result<xenora_loader::RelocationReport, RelocationError>,
|
||||
GuestMemory,
|
||||
) {
|
||||
let (pe, mut memory) = load(bytes, base);
|
||||
let result = apply_relocations(&pe, bytes, base, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_rebase_adds_delta_to_each_dir64_target() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
let report = result.expect("relocate");
|
||||
assert_eq!(report.delta, 0x1_0000_0000);
|
||||
assert_eq!(report.applied_dir64, 2);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.total_entries, 3);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_rebase_subtracts_delta() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = 0x1000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.expect("relocate").delta,
|
||||
base as i64 - PREFERRED as i64
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_base_leaves_targets_unchanged() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, memory) = relocate(&bytes, PREFERRED);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_beyond_declared_count_is_ignored() {
|
||||
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
|
||||
let table = standard_table();
|
||||
let bytes = build(5, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_type_is_rejected() {
|
||||
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::UnsupportedRelocationType(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_block_sizes_are_rejected() {
|
||||
let base = PREFERRED + 0x1000;
|
||||
for size in [0u32, 4, 7, 11] {
|
||||
let mut table = 0x1000u32.to_le_bytes().to_vec();
|
||||
table.extend_from_slice(&size.to_le_bytes());
|
||||
table.extend_from_slice(&[0; 8]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
|
||||
"block size {size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_larger_than_directory_is_rejected() {
|
||||
let table = standard_table(); // 14 bytes
|
||||
let bytes = build(16, &table, 12);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::BlockSizeOutOfBounds {
|
||||
block_size: 14,
|
||||
max_size: 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_partial_block_header_is_rejected() {
|
||||
let mut table = block(0x1000, &[0xA010, 0x0000]);
|
||||
table.extend_from_slice(&[0; 4]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader {
|
||||
offset: RELOC_FILE + 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_past_end_of_file_is_rejected() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::DirectoryOutOfBounds {
|
||||
rva: 0x2000,
|
||||
size: 0x300
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_outside_image_is_rejected_even_if_mapped() {
|
||||
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
|
||||
let table = block(0x3000, &[0xA000, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1000;
|
||||
let (pe, mut memory) = load(&bytes, base);
|
||||
let rw = pe.sections[1].permissions;
|
||||
memory
|
||||
.map_region(base + 0x3000, 0x1000, rw)
|
||||
.expect("adjacent mapping");
|
||||
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
|
||||
let result = apply_relocations(&pe, &bytes, base, &mut memory);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::TargetOutOfBounds {
|
||||
target_va: base + 0x3000
|
||||
}
|
||||
);
|
||||
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rva_at_top_of_address_space_is_rejected() {
|
||||
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RelocationError::TargetOutOfBounds { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Operand-domain verification for the supported SOP2 and VOPC forms (part of
|
||||
//! #215, stage E).
|
||||
//!
|
||||
//! Every case runs three ways: the expected value written out below from the
|
||||
//! public AMD "RDNA 2" Instruction Set Architecture Reference Guide, the
|
||||
//! reference interpreter `xenora_ref`, and the translated MSL on native Metal.
|
||||
//! The expected values come only from `oracle`, which imports nothing from the
|
||||
//! ISA crate, the decoder, the shader compiler or the semantic registry, so a
|
||||
//! mistake there cannot also produce the expectation.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
mod harness;
|
||||
#[path = "operand_domains/oracle.rs"]
|
||||
mod oracle;
|
||||
#[path = "operand_domains/sop2.rs"]
|
||||
mod sop2;
|
||||
#[path = "operand_domains/vopc.rs"]
|
||||
mod vopc;
|
||||
|
||||
use harness::{Case, Rejection};
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut all = sop2::cases();
|
||||
all.extend(vopc::cases());
|
||||
all
|
||||
}
|
||||
|
||||
fn rejections() -> Vec<Rejection> {
|
||||
let mut all = sop2::rejections();
|
||||
all.extend(vopc::rejections());
|
||||
all
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operand_domains_match_the_guide_on_the_reference() {
|
||||
let cases = cases();
|
||||
harness::assert_counts(&cases, sop2::COUNTS.iter().chain(vopc::COUNTS));
|
||||
harness::check_reference(&cases).assert_none("reference disagrees with the guide");
|
||||
eprintln!("operand_domains: {} reference cases", cases.len());
|
||||
harness::print_counts(&cases);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_truncated_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), sop2::REJECTIONS + vopc::REJECTIONS);
|
||||
harness::check_rejected(&rejections).assert_none("not rejected as the guide requires");
|
||||
eprintln!("operand_domains: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn operand_domains_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
let cases = cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"operand_domains: {} native Metal cases ({programs} distinct programs)",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Running a case on the reference and on Metal. The helpers mirror the ones in
|
||||
//! `known_answers.rs` (copied, not shared, so that file stays untouched).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
use xenora_shader::{Architecture, CompileError, ENTRY_POINT, compile};
|
||||
|
||||
/// One program, its lane input and the guide's expected lane output.
|
||||
pub struct Case {
|
||||
pub form: &'static str,
|
||||
pub family: &'static str,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub input: Vec<u32>,
|
||||
pub expected: Vec<u32>,
|
||||
}
|
||||
|
||||
/// A program every implementation must refuse, at byte `offset`: as truncated
|
||||
/// when `truncated`, else as outside the supported subset.
|
||||
pub struct Rejection {
|
||||
pub family: &'static str,
|
||||
pub truncated: bool,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
pub fn words(code: &[u32]) -> Vec<u8> {
|
||||
code.iter().copied().flat_map(u32::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
/// The cases that failed, grouped by family: the count and the first message.
|
||||
#[derive(Default)]
|
||||
pub struct Failures(BTreeMap<&'static str, (usize, String)>);
|
||||
|
||||
impl Failures {
|
||||
fn record(&mut self, family: &'static str, message: String) {
|
||||
let entry = self.0.entry(family).or_insert((0, message));
|
||||
entry.0 += 1;
|
||||
}
|
||||
|
||||
/// Panics with one line per failing family.
|
||||
pub fn assert_none(&self, what: &str) {
|
||||
let lines: Vec<String> = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect();
|
||||
assert!(lines.is_empty(), "{what}:\n{}", lines.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_reference(cases: &[Case]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for case in cases {
|
||||
let compiled = compile(Architecture::Gfx1030, &case.code);
|
||||
let reference = xenora_ref::execute(&case.code, &case.input);
|
||||
if compiled.is_err() {
|
||||
failures.record(case.family, format!("{}: {compiled:?}", case.label));
|
||||
} else if reference.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {reference:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
pub fn check_rejected(rejections: &[Rejection]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for rejection in rejections {
|
||||
if let Err(message) = rejected_at(rejection) {
|
||||
failures.record(rejection.family, format!("{}: {message}", rejection.label));
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
fn rejected_at(rejection: &Rejection) -> Result<(), String> {
|
||||
let (compiler, compiler_truncated) = match compile(Architecture::Gfx1030, &rejection.code) {
|
||||
Ok(_) => return Err("the compiler accepted it".into()),
|
||||
Err(CompileError::Verify { offset, .. }) => (offset, false),
|
||||
// The decoder crate is not a dependency of this package, so its
|
||||
// `DecodeErrorKind::Truncated` variant is recognised by name.
|
||||
Err(CompileError::Decode(decode)) => (
|
||||
decode.offset,
|
||||
format!("{:?}", decode.kind).starts_with("Truncated "),
|
||||
),
|
||||
Err(other) => return Err(format!("{other:?}")),
|
||||
};
|
||||
let reference = match xenora_ref::execute(&rejection.code, &[0, 1]) {
|
||||
Ok(_) => return Err("the reference accepted it".into()),
|
||||
Err(error) => error,
|
||||
};
|
||||
// The reference names a missing word "truncated ..."; its fall-through
|
||||
// "unsupported or truncated ..." does not say which, and counts as unsupported.
|
||||
let reference_truncated = reference.detail.starts_with("truncated");
|
||||
if compiler != rejection.offset || reference.offset != rejection.offset {
|
||||
return Err(format!(
|
||||
"compiler at {compiler:#x}, reference at {:#x}, expected {:#x}",
|
||||
reference.offset, rejection.offset
|
||||
));
|
||||
}
|
||||
if compiler_truncated != rejection.truncated || reference_truncated != rejection.truncated {
|
||||
return Err(format!(
|
||||
"truncated: compiler {compiler_truncated}, reference {reference_truncated} ({}), \
|
||||
expected {}",
|
||||
reference.detail, rejection.truncated
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs every case on Metal. Cases whose translated MSL and input are identical
|
||||
/// are one program, so each distinct program runs once and its output is
|
||||
/// compared with every case that shares it. The programs are spread over
|
||||
/// `THREADS` threads, each with its own device queue, because pipeline
|
||||
/// compilation dominates the run time. Returns the failures and the number of
|
||||
/// programs.
|
||||
pub fn check_metal(cases: &[Case]) -> (Failures, usize) {
|
||||
const THREADS: usize = 4;
|
||||
let mut programs = BTreeSet::new();
|
||||
let mut failures = Failures::default();
|
||||
let mut keys = Vec::with_capacity(cases.len());
|
||||
for case in cases {
|
||||
match compile(Architecture::Gfx1030, &case.code) {
|
||||
Ok(compiled) => {
|
||||
let key = (compiled.msl, case.input.clone());
|
||||
programs.insert(key.clone());
|
||||
keys.push(Some(key));
|
||||
}
|
||||
Err(error) => {
|
||||
failures.record(case.family, format!("{}: {error:?}", case.label));
|
||||
keys.push(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let work: Vec<&(String, Vec<u32>)> = programs.iter().collect();
|
||||
let chunk = work.len().div_ceil(THREADS).max(1);
|
||||
let outputs: HashMap<(String, Vec<u32>), Result<Vec<u32>, String>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = work
|
||||
.chunks(chunk)
|
||||
.map(|part| {
|
||||
s.spawn(move || {
|
||||
let metal = xenora_metal::NativeCompute::new().unwrap();
|
||||
part.iter()
|
||||
.map(|&key| {
|
||||
let output = metal
|
||||
.run_words(&key.0, ENTRY_POINT, &key.1)
|
||||
.map_err(|error| error.to_string());
|
||||
(key.clone(), output)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.flat_map(|handle| handle.join().unwrap())
|
||||
.collect()
|
||||
});
|
||||
for (case, key) in cases.iter().zip(keys) {
|
||||
let Some(key) = key else { continue };
|
||||
match &outputs[&key] {
|
||||
Ok(output) if *output == case.expected => {}
|
||||
Ok(output) => {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {output:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
Err(error) => failures.record(case.family, format!("{}: {error}", case.label)),
|
||||
}
|
||||
}
|
||||
(failures, outputs.len())
|
||||
}
|
||||
|
||||
/// The number of cases in each family, which `expected` lists in full.
|
||||
pub fn assert_counts<'a>(
|
||||
cases: &[Case],
|
||||
expected: impl Iterator<Item = &'a (&'static str, usize)>,
|
||||
) {
|
||||
let expected: BTreeMap<_, _> = expected.map(|&(family, n)| (family, n)).collect();
|
||||
assert_eq!(tally(cases, |case| case.family), expected);
|
||||
}
|
||||
|
||||
pub fn print_counts(cases: &[Case]) {
|
||||
for (name, n) in tally(cases, |case| case.form) {
|
||||
eprintln!(" form {name}: {n}");
|
||||
}
|
||||
for (name, n) in tally(cases, |case| case.family) {
|
||||
eprintln!(" family {name}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Expected results transcribed from the AMD "RDNA 2" Instruction Set
|
||||
//! Architecture Reference Guide (30 November 2020). Section numbers refer to
|
||||
//! that guide. Nothing here comes from Xenora's own decoder, ISA tables,
|
||||
//! compiler or semantic registry.
|
||||
|
||||
/// The SOP2 forms under test with their opcode numbers (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Sop2 {
|
||||
AddU32 = 0,
|
||||
SubU32 = 1,
|
||||
AddI32 = 2,
|
||||
SubI32 = 3,
|
||||
AddcU32 = 4,
|
||||
SubbU32 = 5,
|
||||
AndB32 = 14,
|
||||
OrB32 = 16,
|
||||
XorB32 = 18,
|
||||
}
|
||||
|
||||
pub const SOP2_FORMS: [(Sop2, &str); 9] = [
|
||||
(Sop2::AddU32, "s_add_u32"),
|
||||
(Sop2::SubU32, "s_sub_u32"),
|
||||
(Sop2::AddI32, "s_add_i32"),
|
||||
(Sop2::SubI32, "s_sub_i32"),
|
||||
(Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubbU32, "s_subb_u32"),
|
||||
(Sop2::AndB32, "s_and_b32"),
|
||||
(Sop2::OrB32, "s_or_b32"),
|
||||
(Sop2::XorB32, "s_xor_b32"),
|
||||
];
|
||||
|
||||
fn bit31(value: u32) -> bool {
|
||||
value >> 31 == 1
|
||||
}
|
||||
|
||||
/// D and SCC as guide 12.1 writes them; `scc` is the SCC value before the
|
||||
/// instruction. The `>= 0x100000000ULL` tests are evaluated in 64 bits, as the
|
||||
/// ULL constant says.
|
||||
pub fn sop2(op: Sop2, s0: u32, s1: u32, scc: bool) -> (u32, bool) {
|
||||
let (a, b, c) = (u64::from(s0), u64::from(s1), u64::from(scc));
|
||||
match op {
|
||||
// D.u32 = S0.u32 + S1.u32; SCC = S0.u32 + S1.u32 >= 0x100000000ULL.
|
||||
Sop2::AddU32 => (s0.wrapping_add(s1), a + b >= 0x1_0000_0000),
|
||||
// D.u = S0.u - S1.u; SCC = (S1.u > S0.u).
|
||||
Sop2::SubU32 => (s0.wrapping_sub(s1), s1 > s0),
|
||||
// D.i = S0.i + S1.i; SCC = (S0.u[31] == S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::AddI32 => {
|
||||
let d = s0.wrapping_add(s1);
|
||||
(d, bit31(s0) == bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.i = S0.i - S1.i; SCC = (S0.u[31] != S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::SubI32 => {
|
||||
let d = s0.wrapping_sub(s1);
|
||||
(d, bit31(s0) != bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.u32 = S0.u32 + S1.u32 + SCC; SCC = S0.u32 + S1.u32 + SCC >= 0x100000000ULL.
|
||||
Sop2::AddcU32 => (
|
||||
s0.wrapping_add(s1).wrapping_add(u32::from(scc)),
|
||||
a + b + c >= 0x1_0000_0000,
|
||||
),
|
||||
// D.u = S0.u - S1.u - SCC; SCC = (S1.u + SCC > S0.u), "unsigned overflow".
|
||||
// The guide does not say whether S1.u + SCC wraps at 32 bits. It is read
|
||||
// here at full width: only then does SCC report the borrow out of the
|
||||
// subtraction, which the comment names. This decides only S1 = 0xffffffff
|
||||
// with SCC set; `sop2::cases` keeps those in their own family.
|
||||
Sop2::SubbU32 => (s0.wrapping_sub(s1).wrapping_sub(u32::from(scc)), b + c > a),
|
||||
// D = S0 & S1, S0 | S1, S0 ^ S1; SCC = (D != 0).
|
||||
Sop2::AndB32 => (s0 & s1, s0 & s1 != 0),
|
||||
Sop2::OrB32 => (s0 | s1, s0 | s1 != 0),
|
||||
Sop2::XorB32 => (s0 ^ s1, s0 ^ s1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer inline constants (guide 5.2, scalar source operand table): codes
|
||||
/// 128-192 are 0..=64 and codes 193-208 are -1..=-16.
|
||||
pub fn inline_integer(code: u32) -> Option<u32> {
|
||||
match code {
|
||||
128..=192 => Some(code - 128),
|
||||
193..=208 => Some((192_i32 - code as i32) as u32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Literal constant code: one 32-bit word follows the instruction (guide 5.2).
|
||||
pub const LITERAL: u32 = 255;
|
||||
|
||||
/// The VOPC integer compares (guide 12.9): V_CMP_{LT,EQ,LE,GT,NE,GE}_I32 are
|
||||
/// opcodes 129-134 and the _U32 forms 193-198.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Compare {
|
||||
pub opcode: u32,
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
pub const COMPARES: [Compare; 12] = [
|
||||
Compare {
|
||||
opcode: 129,
|
||||
name: "v_cmp_lt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 130,
|
||||
name: "v_cmp_eq_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 131,
|
||||
name: "v_cmp_le_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 132,
|
||||
name: "v_cmp_gt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 133,
|
||||
name: "v_cmp_ne_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 134,
|
||||
name: "v_cmp_ge_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 193,
|
||||
name: "v_cmp_lt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 194,
|
||||
name: "v_cmp_eq_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 195,
|
||||
name: "v_cmp_le_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 196,
|
||||
name: "v_cmp_gt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 197,
|
||||
name: "v_cmp_ne_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 198,
|
||||
name: "v_cmp_ge_u32",
|
||||
},
|
||||
];
|
||||
|
||||
/// "D[threadId] = (S0 < S1)" and so on (guide 12.9), with I32 operands read as
|
||||
/// two's complement and U32 operands as unsigned (chapter 12 suffix rules).
|
||||
pub fn compare(form: Compare, s0: u32, s1: u32) -> bool {
|
||||
let signed = form.name.ends_with("_i32");
|
||||
let order = if signed {
|
||||
(s0 as i32).cmp(&(s1 as i32))
|
||||
} else {
|
||||
s0.cmp(&s1)
|
||||
};
|
||||
match &form.name[6..8] {
|
||||
"lt" => order.is_lt(),
|
||||
"eq" => order.is_eq(),
|
||||
"le" => order.is_le(),
|
||||
"gt" => order.is_gt(),
|
||||
"ne" => order.is_ne(),
|
||||
"ge" => order.is_ge(),
|
||||
other => unreachable!("{other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// VCC for one Wave32 wave (guide 3.9): "VCC[n] = EXEC[n] & (test passed for
|
||||
/// thread[n])", and "VCC is fully written", so inactive lanes read 0.
|
||||
pub fn vcc(exec: u32, passed: impl Fn(usize) -> bool) -> u32 {
|
||||
(0..32)
|
||||
.filter(|&lane| exec >> lane & 1 == 1 && passed(lane))
|
||||
.fold(0, |mask, lane| mask | 1 << lane)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! SOP2 programs: the operands start in SGPRs (or as inline or literal
|
||||
//! sources), SCC is set or cleared first, and the result reaches the output as
|
||||
//! v2 = D, XORed with the lane input only when SCC is set afterwards. With the
|
||||
//! lane input [0, 0xffffffff] the output is [D, D] or [D, !D].
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{self, LITERAL, SOP2_FORMS, Sop2, sop2 as expect};
|
||||
|
||||
/// Boundary operands: zero, one, signed max/min and min + 1, unsigned max and
|
||||
/// max - 1, and an ordinary pattern.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x1234_5678,
|
||||
];
|
||||
const LITERALS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1234_5678];
|
||||
/// 64-bit operands for add/addc and sub/subb chains.
|
||||
const WIDE: [u64; 6] = [
|
||||
0,
|
||||
1,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x8000_0000_0000_0000,
|
||||
u64::MAX,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("sop2 domain", 9 * 8 * 8 * 2 - 8),
|
||||
("sop2 subb full-width borrow", 8),
|
||||
("sop2 carry chain", 2 * 6 * 6 * 2 * 2),
|
||||
("sop2 aliasing", 9 * 5 * 2),
|
||||
("sop2 inline integer", 9 * 81 * 2),
|
||||
("sop2 literal", 9 * 6 * 2 * 2),
|
||||
("sop2 max register", 9 * 4),
|
||||
];
|
||||
/// Two literals, 21 special destinations, 9 float inline codes in two slots,
|
||||
/// and a missing literal word in two slots, for each of the 9 forms.
|
||||
pub const REJECTIONS: usize = 9 * (1 + 21 + 9 * 2 + 2);
|
||||
/// The SOP2 word's offset: load 8, wait 4, two literal moves 8 each, s_cmp 4.
|
||||
const ALU_OFFSET: usize = 0x20;
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.1).
|
||||
pub fn sop2(op: Sop2, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | (op as u32) << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
|
||||
fn mov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0xbe80_03ff | reg << 16, value]
|
||||
}
|
||||
|
||||
/// The program around `alu`: `init` sets SGPRs, SCC = `scc`, then `alu`, then
|
||||
/// v2 = s<result>, XORed with v1 when SCC is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend(mov(reg, value));
|
||||
}
|
||||
// s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it.
|
||||
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn lanes((d, scc): (u32, bool)) -> Vec<u32> {
|
||||
vec![d, if scc { !d } else { d }]
|
||||
}
|
||||
|
||||
fn case(
|
||||
form: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
Case {
|
||||
form,
|
||||
family,
|
||||
label: format!("{form} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: lanes(out),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (op, name) in SOP2_FORMS {
|
||||
let alu = [sop2(op, 10, 8, 9)];
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let family = if op == Sop2::SubbU32 && b == u32::MAX && scc {
|
||||
"sop2 subb full-width borrow"
|
||||
} else {
|
||||
"sop2 domain"
|
||||
};
|
||||
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
family,
|
||||
format!("{a:#x}, {b:#x}, scc {scc}"),
|
||||
code,
|
||||
expect(op, a, b, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// dst/src aliasing, SCC set: (dst, src0, src1) with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x11), (0x8000_0000, 0x8000_0000)] {
|
||||
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
|
||||
let pick = |reg| if reg == 8 { a } else { b };
|
||||
let code = program(&[(8, a), (9, b)], true, &[sop2(op, dst, src0, src1)], dst);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 aliasing",
|
||||
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant in each source slot, s8 = 0xfffffff0, SCC set.
|
||||
let a = 0xffff_fff0;
|
||||
for code_point in (128..=208).filter_map(|c| oracle::inline_integer(c).map(|v| (c, v))) {
|
||||
let (selector, value) = code_point;
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, selector, 8), expect(op, value, a, true))
|
||||
} else {
|
||||
(sop2(op, 10, 8, selector), expect(op, a, value, true))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], true, &[alu], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 inline integer",
|
||||
format!("inline {selector} ({value:#x}) slot {slot}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// A literal word in each source slot, with SCC clear.
|
||||
for a in [1, 0x8000_0000] {
|
||||
for literal in LITERALS {
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, LITERAL, 8), expect(op, literal, a, false))
|
||||
} else {
|
||||
(sop2(op, 10, 8, LITERAL), expect(op, a, literal, false))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], false, &[alu, literal], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 literal",
|
||||
format!("literal {literal:#x} slot {slot}, s8 {a:#x}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// s105, the highest SGPR a SOP2 operand may name (guide 5.2), as
|
||||
// destination and source; s105 = a, s8 = s9 = b, SCC set.
|
||||
let (a, b) = (0x8000_0001, u32::MAX);
|
||||
for (dst, src0, src1) in [(105, 105, 9), (105, 8, 105), (105, 105, 105), (8, 105, 9)] {
|
||||
let pick = |reg| if reg == 105 { a } else { b };
|
||||
let code = program(
|
||||
&[(105, a), (8, b), (9, b)],
|
||||
true,
|
||||
&[sop2(op, dst, src0, src1)],
|
||||
dst,
|
||||
);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 max register",
|
||||
format!("s{dst} = s{src0}, s{src1}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
cases.extend(chains());
|
||||
cases
|
||||
}
|
||||
|
||||
/// 64-bit add and subtract built from the u32 forms: low word with
|
||||
/// s_add_u32/s_sub_u32, high word with s_addc_u32/s_subb_u32 consuming its
|
||||
/// SCC. SCC is preset both ways first to show the low form overwrites it. Each
|
||||
/// chain runs twice, outputting the low word and then the high word, both with
|
||||
/// the final SCC. The expected words and SCC follow the guide; they are also
|
||||
/// checked against 64-bit arithmetic here.
|
||||
fn chains() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (low, high, name) in [
|
||||
(Sop2::AddU32, Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubU32, Sop2::SubbU32, "s_subb_u32"),
|
||||
] {
|
||||
for x in WIDE {
|
||||
for y in WIDE {
|
||||
for preset in [false, true] {
|
||||
let (xl, xh, yl, yh) = (x as u32, (x >> 32) as u32, y as u32, (y >> 32) as u32);
|
||||
let (d_low, carry) = expect(low, xl, yl, preset);
|
||||
let (d_high, scc) = expect(high, xh, yh, carry);
|
||||
let exact = if low == Sop2::AddU32 {
|
||||
(x.wrapping_add(y), x.checked_add(y).is_none())
|
||||
} else {
|
||||
(x.wrapping_sub(y), y > x)
|
||||
};
|
||||
let joined = u64::from(d_high) << 32 | u64::from(d_low);
|
||||
assert_eq!((joined, scc), exact, "{x:#x} {y:#x}");
|
||||
let alu = [sop2(low, 12, 8, 9), sop2(high, 13, 10, 11)];
|
||||
let init = [(8, xl), (9, yl), (10, xh), (11, yh)];
|
||||
for (word, d) in [("low", d_low), ("high", d_high)] {
|
||||
let result = if word == "low" { 12 } else { 13 };
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 carry chain",
|
||||
format!("{x:#x}, {y:#x}, preset {preset}, {word} word"),
|
||||
program(&init, preset, &alu, result),
|
||||
(d, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
let reject = |family, label: String, alu: &[u32]| Rejection {
|
||||
family,
|
||||
truncated: false,
|
||||
label,
|
||||
code: program(&[(8, 1), (9, 2)], false, alu, 10),
|
||||
offset: ALU_OFFSET,
|
||||
};
|
||||
for (op, name) in SOP2_FORMS {
|
||||
// Both sources select the literal. The guide allows at most one literal
|
||||
// constant per instruction; whether two selectors may share one word is
|
||||
// not stated, and Xenora's subset rejects it.
|
||||
rejections.push(reject(
|
||||
"sop2 two literals",
|
||||
format!("{name} two literals"),
|
||||
&[sop2(op, 10, LITERAL, LITERAL), 3, 3],
|
||||
));
|
||||
// VCC_LO, VCC_HI, TTMP0-15, M0, EXEC_LO, EXEC_HI as destination. The
|
||||
// guide lists these as scalar destinations; Xenora's SOP2 subset writes
|
||||
// only s0-s105, so these are rejections of the subset, not of the guide.
|
||||
for dst in (106..=123).chain([124, 126, 127]) {
|
||||
rejections.push(reject(
|
||||
"sop2 special destination",
|
||||
format!("{name} dst {dst}"),
|
||||
&[sop2(op, dst, 8, 9)],
|
||||
));
|
||||
}
|
||||
// Float inline constants 0.5 .. -4.0 and 1/(2*pi) (codes 240-248). The
|
||||
// guide defines them for every source; Xenora's subset rejects them for
|
||||
// these integer forms.
|
||||
for selector in 240..=248 {
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src0"),
|
||||
&[sop2(op, 10, selector, 8)],
|
||||
));
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src1"),
|
||||
&[sop2(op, 10, 8, selector)],
|
||||
));
|
||||
}
|
||||
// The stream ends where the literal word should be.
|
||||
for (slot, alu) in [(0, sop2(op, 10, LITERAL, 8)), (1, sop2(op, 10, 8, LITERAL))] {
|
||||
let mut code = program(&[(8, 1), (9, 2)], false, &[], 10);
|
||||
code.truncate(ALU_OFFSET);
|
||||
code.extend(alu.to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "sop2 missing literal",
|
||||
truncated: true,
|
||||
label: format!("{name} missing literal slot {slot}"),
|
||||
code,
|
||||
offset: ALU_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! VOPC programs on one Wave32 wave: v1 = lane input, v3 (or v255) = a literal
|
||||
//! `b`, an optional EXEC mask around the compare, then every lane outputs
|
||||
//! VCC_LO. The 32 lane inputs are distinct, so a mask bit landing in the wrong
|
||||
//! lane changes the output.
|
||||
//!
|
||||
//! Not covered: whether a compare also writes EXEC. The supported subset has
|
||||
//! no instruction that reads EXEC back, so the EXEC cases restore it before
|
||||
//! the output move.
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{COMPARES, Compare, LITERAL, compare, inline_integer, vcc};
|
||||
|
||||
/// Boundary operands, also the first ten lane inputs: zero, one, signed max - 1
|
||||
/// and max, signed min and min + 1, -16, unsigned max - 1 and max, and a
|
||||
/// pattern.
|
||||
const VALUES: [u32; 10] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fff0,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x0f0f_0f0f,
|
||||
];
|
||||
/// The other 22 lane inputs: more values near the boundaries and patterns.
|
||||
const MORE_LANES: [u32; 22] = [
|
||||
2,
|
||||
3,
|
||||
15,
|
||||
16,
|
||||
63,
|
||||
64,
|
||||
65,
|
||||
0x7fff_fffd,
|
||||
0x8000_0002,
|
||||
0xffff_fffd,
|
||||
0xffff_ffef,
|
||||
0xffff_fff1,
|
||||
0x4000_0000,
|
||||
0xc000_0000,
|
||||
0x0000_ffff,
|
||||
0xffff_0000,
|
||||
0x1234_5678,
|
||||
0x8765_4321,
|
||||
0x00ff_00ff,
|
||||
0xff00_ff00,
|
||||
0x5555_5555,
|
||||
0xaaaa_aaaa,
|
||||
];
|
||||
const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX];
|
||||
const EXEC_MASKS: [u32; 5] = [0, 0x5555_5555, 0xaaaa_aaaa, 0x8000_0001, 0x0000_ffff];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("vopc domain", 12 * 10 * 2),
|
||||
("vopc aliasing", 12),
|
||||
("vopc inline integer", 12 * 81),
|
||||
("vopc literal", 12 * 5),
|
||||
("vopc sgpr source", 12 * 2 * 2),
|
||||
("vopc max register", 12 * 2),
|
||||
("vopc exec mask", 12 * 5),
|
||||
("vopc vccz", 12 * 11),
|
||||
];
|
||||
/// A missing literal word and 9 float inline codes (defined by the guide, outside
|
||||
/// Xenora's subset for integer compares), for each of the 12 forms.
|
||||
pub const REJECTIONS: usize = 12 * (1 + 9);
|
||||
/// The compare's offset: load 8, wait 4, v_mov with literal 8.
|
||||
const COMPARE_OFFSET: usize = 0x14;
|
||||
|
||||
/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8
|
||||
/// (guide 13.3.3); SRC0 256 + n is VGPR n.
|
||||
fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
const fn vgpr(n: u32) -> u32 {
|
||||
256 + n
|
||||
}
|
||||
|
||||
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
|
||||
fn vmov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0x7e00_02ff | reg << 17, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 vcc_lo, 0xffffffff`, so a compare that leaves bits untouched
|
||||
/// shows up.
|
||||
const SEED_VCC: [u32; 2] = [0xbeea_03ff, u32::MAX];
|
||||
/// `s_mov_b32 exec_lo, literal` and `s_mov_b32 exec_lo, -1`.
|
||||
const SET_EXEC: u32 = 0xbefe_03ff;
|
||||
const FULL_EXEC: u32 = 0xbefe_03c1;
|
||||
/// After v2 = VCC_LO: `s_cbranch_vccz` over `v_xor_b32 v2, v1, v2`.
|
||||
const VCCZ_TAIL: [u32; 2] = [0xbf86_0001, 0x3a04_0501];
|
||||
|
||||
/// Load v1, v<breg> = b, then `before`, the compare words, `after`, and every
|
||||
/// lane outputs VCC_LO.
|
||||
fn program(breg: u32, b: u32, before: &[u32], compare: &[u32], after: &[u32]) -> Vec<u8> {
|
||||
program_with_tail(breg, b, before, compare, after, &[])
|
||||
}
|
||||
|
||||
/// As `program`, with `tail` between the output move and the store.
|
||||
fn program_with_tail(
|
||||
breg: u32,
|
||||
b: u32,
|
||||
before: &[u32],
|
||||
compare: &[u32],
|
||||
after: &[u32],
|
||||
tail: &[u32],
|
||||
) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(vmov(breg, b));
|
||||
code.extend(before);
|
||||
code.extend(compare);
|
||||
code.extend(after);
|
||||
code.push(0x7e04_026a);
|
||||
code.extend(tail);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<u32> {
|
||||
VALUES.iter().chain(&MORE_LANES).copied().collect()
|
||||
}
|
||||
|
||||
fn case(form: Compare, family: &'static str, label: String, code: Vec<u8>, mask: u32) -> Case {
|
||||
Case {
|
||||
form: form.name,
|
||||
family,
|
||||
label: format!("{} {label}", form.name),
|
||||
code,
|
||||
input: lanes(),
|
||||
expected: vec![mask; 32],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let input = lanes();
|
||||
let all = u32::MAX;
|
||||
let mut cases = Vec::new();
|
||||
for form in COMPARES {
|
||||
let op = form.opcode;
|
||||
for b in VALUES {
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(form, "vopc domain", format!("v1, {b:#x}"), code, mask));
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(3), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(form, "vopc domain", format!("{b:#x}, v1"), code, mask));
|
||||
}
|
||||
let code = program(3, 0, &[], &[vopc(op, vgpr(1), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], input[n]));
|
||||
cases.push(case(form, "vopc aliasing", "v1, v1".into(), code, mask));
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector).unwrap();
|
||||
let code = program(3, 0, &[], &[vopc(op, selector, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc inline integer",
|
||||
format!("inline {selector} ({value:#x})"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
for literal in LITERALS {
|
||||
let code = program(3, 0, &[], &[vopc(op, LITERAL, 1), literal], &[]);
|
||||
let mask = vcc(all, |n| compare(form, literal, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc literal",
|
||||
format!("literal {literal:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// SGPR source s8 and s105, the highest SGPR (guide 5.2).
|
||||
for reg in [8, 105] {
|
||||
for value in [0x8000_0000, 0xffff_fff0] {
|
||||
let set = [0xbe80_03ff | reg << 16, value];
|
||||
let code = program(3, 0, &set, &[vopc(op, reg, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc sgpr source",
|
||||
format!("s{reg} = {value:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
}
|
||||
// v255, the highest VGPR, in each slot.
|
||||
let b = 0x8000_0001;
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(1), 255)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v1, v255".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(255), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v255, v1".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
// Partial and empty EXEC around the compare, with VCC_LO = -1 before
|
||||
// it, so inactive lanes must be cleared ("VCC is fully written");
|
||||
// EXEC_LO = -1 again before the output move so every lane stores VCC_LO.
|
||||
let b = 0x8000_0000;
|
||||
for exec in EXEC_MASKS {
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, exec];
|
||||
let code = program(3, b, &before, &[vopc(op, vgpr(1), 3)], &[FULL_EXEC]);
|
||||
let mask = vcc(exec, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc exec mask",
|
||||
format!("exec {exec:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// VCCZ after the compare (guide 3.9: VCCZ is VCC == 0), read with
|
||||
// s_cbranch_vccz: lanes output VCC_LO when it is zero, else input ^ VCC_LO.
|
||||
let vccz = |mask: u32| -> Vec<u32> {
|
||||
if mask == 0 {
|
||||
vec![0; 32]
|
||||
} else {
|
||||
input.iter().map(|lane| lane ^ mask).collect()
|
||||
}
|
||||
};
|
||||
for b in VALUES {
|
||||
let code = program_with_tail(3, b, &[], &[vopc(op, vgpr(1), 3)], &[], &VCCZ_TAIL);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
let mut case = case(form, "vopc vccz", format!("v1, {b:#x}"), code, mask);
|
||||
case.expected = vccz(mask);
|
||||
cases.push(case);
|
||||
}
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, 0];
|
||||
let compare_words = [vopc(op, vgpr(1), 3)];
|
||||
let code = program_with_tail(3, 0, &before, &compare_words, &[FULL_EXEC], &VCCZ_TAIL);
|
||||
let mut case = case(form, "vopc vccz", "exec 0".into(), code, 0);
|
||||
case.expected = vccz(0);
|
||||
cases.push(case);
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
for form in COMPARES {
|
||||
let mut code = program(3, 0, &[], &[], &[]);
|
||||
code.truncate(COMPARE_OFFSET);
|
||||
code.extend(vopc(form.opcode, LITERAL, 1).to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "vopc missing literal",
|
||||
truncated: true,
|
||||
label: format!("{} missing literal", form.name),
|
||||
code,
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
for selector in 240..=248 {
|
||||
rejections.push(Rejection {
|
||||
family: "vopc float inline",
|
||||
truncated: false,
|
||||
label: format!("{} float inline {selector}", form.name),
|
||||
code: program(3, 0, &[], &[vopc(form.opcode, selector, 1)], &[]),
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
Reference in new issue
Block a user