mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 11:31:11 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dc10ae437 | ||
|
|
16debc8fdb | ||
|
|
ee8347a39f | ||
|
|
6689761db3 | ||
|
|
b041952437 | ||
|
|
ae80d7fd8f | ||
|
|
d57e9c031c | ||
|
|
924d68afbc | ||
|
|
840eca0a29 | ||
|
|
0749330868 | ||
|
|
2ddd2a2485 | ||
|
|
0e7fa4aa93 | ||
|
|
1ee557bdc4 | ||
|
|
fa4d4b9d71 | ||
|
|
bf3cca0718 | ||
|
|
a86100c00d | ||
|
|
044f036ea5 |
No files matched your search
+7
-1
@@ -11,11 +11,16 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
|
||||
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
|
||||
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
|
||||
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
|
||||
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
|
||||
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
|
||||
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: 25 forms have semantic decoding.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
|
||||
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
|
||||
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
@@ -65,6 +70,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
|
||||
execution test above), so the probe reports no blocker for this program.
|
||||
|
||||
@@ -3,15 +3,17 @@
|
||||
use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, ScalarSource,
|
||||
VectorSource,
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
@@ -19,7 +21,7 @@ use xenora_isa::meta::EncodingFamily;
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 34] = [
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
@@ -46,6 +48,18 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 34] = [
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vopc),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
@@ -313,6 +327,27 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
{
|
||||
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
|
||||
for (opcode, relation, signed) in [
|
||||
(V_CMP_LT_I32, Less, true),
|
||||
(V_CMP_EQ_I32, Equal, true),
|
||||
(V_CMP_LE_I32, LessOrEqual, true),
|
||||
(V_CMP_GT_I32, Greater, true),
|
||||
(V_CMP_NE_I32, NotEqual, true),
|
||||
(V_CMP_GE_I32, GreaterOrEqual, true),
|
||||
(V_CMP_LT_U32, Less, false),
|
||||
(V_CMP_EQ_U32, Equal, false),
|
||||
(V_CMP_LE_U32, LessOrEqual, false),
|
||||
(V_CMP_GT_U32, Greater, false),
|
||||
(V_CMP_NE_U32, NotEqual, false),
|
||||
(V_CMP_GE_U32, GreaterOrEqual, false),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
if V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
@@ -646,12 +681,47 @@ fn buffer_operands(
|
||||
Ok((data, index, resource))
|
||||
}
|
||||
|
||||
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
|
||||
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
|
||||
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
|
||||
fn vector_compare(
|
||||
op: VectorCompareOp,
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let base_len = 4;
|
||||
let (src0, len) = match source {
|
||||
0..=106 => (VectorSource::Scalar(source as u8), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
base_len,
|
||||
),
|
||||
255 => {
|
||||
let len = base_len + 4;
|
||||
(VectorSource::Immediate(word(bytes, len)?), len)
|
||||
}
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let dst = (first >> 17) as u8;
|
||||
let source = first & 0x1ff;
|
||||
let base_len = V_MOV_B32.byte_len();
|
||||
let (src, len) = match source {
|
||||
0..=105 => (VectorSource::Scalar(source as u8), base_len),
|
||||
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
|
||||
106 => (VectorSource::Scalar(VCC_LO), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
@@ -667,7 +737,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"v_mov_b32_e32",
|
||||
"expected a VGPR, normal SGPR, inline integer, inline +1.0f or literal",
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,10 +3,10 @@ use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarAluOp,
|
||||
ScalarSource, VectorSource, decode, decode_at,
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, Op, ScalarAlu, Source, VectorAlu};
|
||||
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -97,7 +97,12 @@ fn rejects_other_opcodes_and_noncanonical_operands() {
|
||||
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
|
||||
(&[0xbf8c_3f71], "s_waitcnt"),
|
||||
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
|
||||
(&[0x7e04_026a], "v_mov_b32_e32"), // VCC_LO is outside the SGPR subset.
|
||||
(&[0x7e04_026b], "v_mov_b32_e32"), // VCC_HI is outside the source subset.
|
||||
(&[0x7d02_046b], "v_cmp_lt_i32_e32"), // VCC_HI source.
|
||||
(&[0x7d02_047e], "v_cmp_lt_i32_e32"), // EXEC_LO source.
|
||||
(&[0x7d02_04f0], "v_cmp_lt_i32_e32"), // Inline 0.5 source.
|
||||
(&[0x7d84_04f9, 0x0606_0601], "v_cmp_eq_u32_e32"), // SDWA.
|
||||
(&[0x7d84_04fa, 0], "v_cmp_eq_u32_e32"), // DPP16.
|
||||
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
|
||||
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
|
||||
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
|
||||
@@ -389,6 +394,25 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
offset: match op.relation {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
},
|
||||
signed: op.signed,
|
||||
},
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
@@ -410,12 +434,13 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 30, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -423,6 +448,7 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
}
|
||||
|
||||
fn assemble_matrix() -> Vec<u8> {
|
||||
use std::fmt::Write as _;
|
||||
// Cover register banks and extrema, immediate classes in both scalar
|
||||
// compare positions, zero displacement and branches over literal words.
|
||||
let mut assembly = String::from(
|
||||
@@ -474,9 +500,29 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
",
|
||||
);
|
||||
use std::fmt::Write as _;
|
||||
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
|
||||
// inline integers at both ends, inline zero and a literal.
|
||||
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for src0 in [
|
||||
"v255",
|
||||
"v0",
|
||||
"s0",
|
||||
"s105",
|
||||
"vcc_lo",
|
||||
"-16",
|
||||
"64",
|
||||
"0",
|
||||
"0x80000000",
|
||||
] {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, {src0}, v128").unwrap();
|
||||
}
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
@@ -605,7 +651,11 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
&[0xd516_0001],
|
||||
];
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026a], // VOP1 VCC_LO source
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0x7d00_0501], // v_cmp_f_i32_e32
|
||||
&[0x7d0e_0501], // v_cmp_t_i32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
@@ -674,6 +724,17 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
mnemonic if mnemonic.starts_with("v_cmp_") => {
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[1].parse::<i32>().map_or_else(
|
||||
|_| parts[1].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
format!("{mnemonic} {}", parts.join(", "))
|
||||
}
|
||||
"v_mov_b32_e32" => {
|
||||
let (destination, source) = operands.split_once(", ").unwrap();
|
||||
let normalized = match source {
|
||||
|
||||
@@ -39,10 +39,7 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
inline_only,
|
||||
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
|
||||
);
|
||||
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
|
||||
@@ -39,6 +39,18 @@ VARIANTS = (
|
||||
("V_XOR_B32", "ENC_VOP2"),
|
||||
("V_ADD_F32", "ENC_VOP2"),
|
||||
("V_MUL_F32", "ENC_VOP2"),
|
||||
("V_CMP_LT_I32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_I32", "ENC_VOPC"),
|
||||
("V_CMP_LE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GT_I32", "ENC_VOPC"),
|
||||
("V_CMP_NE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GE_I32", "ENC_VOPC"),
|
||||
("V_CMP_LT_U32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_U32", "ENC_VOPC"),
|
||||
("V_CMP_LE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GT_U32", "ENC_VOPC"),
|
||||
("V_CMP_NE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GE_U32", "ENC_VOPC"),
|
||||
("EXP", "ENC_EXP"),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP"),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP"),
|
||||
|
||||
+95
-3
@@ -10,10 +10,15 @@ pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
/// Selects the instruction encoding independently of the container and execution ABI.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Architecture {
|
||||
@@ -46,7 +51,7 @@ impl Opcode {
|
||||
pub enum VectorSource {
|
||||
/// VGPR index.
|
||||
Register(u8),
|
||||
/// Normal SGPR index (s0-s105), read as a wave-uniform value.
|
||||
/// Normal SGPR index (s0-s105) or `vcc_lo` (106), read as a wave-uniform value.
|
||||
Scalar(u8),
|
||||
/// Inline integer or literal word, represented by its bits.
|
||||
Immediate(u32),
|
||||
@@ -56,6 +61,7 @@ impl fmt::Display for VectorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Register(register) => write!(formatter, "v{register}"),
|
||||
Self::Scalar(VCC_LO) => formatter.write_str("vcc_lo"),
|
||||
Self::Scalar(register) => write!(formatter, "s{register}"),
|
||||
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
|
||||
}
|
||||
@@ -83,6 +89,81 @@ impl fmt::Display for ScalarSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareRelation {
|
||||
/// S0 < S1 (opcode offset 1).
|
||||
Less,
|
||||
/// S0 == S1 (offset 2).
|
||||
Equal,
|
||||
/// S0 <= S1 (offset 3).
|
||||
LessOrEqual,
|
||||
/// S0 > S1 (offset 4).
|
||||
Greater,
|
||||
/// S0 != S1 (offset 5).
|
||||
NotEqual,
|
||||
/// S0 >= S1 (offset 6).
|
||||
GreaterOrEqual,
|
||||
}
|
||||
|
||||
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
|
||||
///
|
||||
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
|
||||
/// the pinned XML descriptions. VCC and EXEC rules are in
|
||||
/// docs/shaders/vector-compare.md.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct VectorCompareOp {
|
||||
/// The tested relation.
|
||||
pub relation: CompareRelation,
|
||||
/// `_i32` (two's complement) when true, `_u32` when false.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
impl VectorCompareOp {
|
||||
/// Lower-case mnemonic of the 32-bit VOPC encoding.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
const SIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_i32_e32",
|
||||
"v_cmp_eq_i32_e32",
|
||||
"v_cmp_le_i32_e32",
|
||||
"v_cmp_gt_i32_e32",
|
||||
"v_cmp_ne_i32_e32",
|
||||
"v_cmp_ge_i32_e32",
|
||||
];
|
||||
const UNSIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_u32_e32",
|
||||
"v_cmp_eq_u32_e32",
|
||||
"v_cmp_le_u32_e32",
|
||||
"v_cmp_gt_u32_e32",
|
||||
"v_cmp_ne_u32_e32",
|
||||
"v_cmp_ge_u32_e32",
|
||||
];
|
||||
let index = self.relation as usize;
|
||||
if self.signed {
|
||||
SIGNED[index]
|
||||
} else {
|
||||
UNSIGNED[index]
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-lane test result for operand bits S0 and S1.
|
||||
pub fn test(self, src0: u32, src1: u32) -> bool {
|
||||
let ordering = if self.signed {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
match self.relation {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SOP2 32-bit integer operations in the supported scalar subset.
|
||||
///
|
||||
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
|
||||
@@ -216,6 +297,13 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
|
||||
VectorCompare {
|
||||
op: VectorCompareOp,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
@@ -296,6 +384,7 @@ impl Instruction {
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
@@ -364,6 +453,9 @@ impl fmt::Display for Instruction {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
|
||||
+12
-2
@@ -355,9 +355,19 @@ pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
|
||||
// An attribute field (XML OPR_ATTR) is not an operand selector: in the
|
||||
// VOP3 interpolation forms SRC0 holds {attr_word, attr_chan, attr}
|
||||
// bit-fields (AMD RDNA 2 ISA guide, section 10.4.2), so 255 there
|
||||
// does not select a literal.
|
||||
trailer.literal = ["SRC0", "SRC1", "SRC2"]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|name| {
|
||||
!form
|
||||
.operands
|
||||
.iter()
|
||||
.any(|operand| operand.field == *name && operand.kind == "OPR_ATTR")
|
||||
})
|
||||
.filter_map(source)
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
|
||||
@@ -155,6 +155,66 @@ pub const V_MUL_F32: Opcode = Opcode {
|
||||
bits: 0x10000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d020000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d040000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d080000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d820000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d840000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d860000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d880000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const EXP: Opcode = Opcode {
|
||||
mask: 0xfc000000,
|
||||
bits: 0xf8000000,
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
from itertools import islice, zip_longest
|
||||
from pathlib import Path
|
||||
import random
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ISA = HERE.parents[1]
|
||||
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
|
||||
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
|
||||
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
|
||||
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
|
||||
# Instruction text, offset, consumed words, then optional trailing text: a
|
||||
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
|
||||
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
|
||||
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
|
||||
|
||||
|
||||
def llvm(executable, *args, source=None):
|
||||
return subprocess.run(
|
||||
[executable, *TARGET, "-show-encoding", *args],
|
||||
input=source, text=True, capture_output=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def encodings(output):
|
||||
for text, bytes_text in ENCODING.findall(output):
|
||||
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
|
||||
|
||||
|
||||
def disassemble_batch(llvm_bin, blobs):
|
||||
"""LLVM's decode of the first instruction of each blob.
|
||||
|
||||
Each blob goes into its own section of one object built from `.byte`
|
||||
directives; llvm-objdump disassembles every section from offset zero and
|
||||
prints the words it consumed. That length is what the decoder read, not the
|
||||
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
|
||||
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
|
||||
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
|
||||
"""
|
||||
source = []
|
||||
for index, blob in enumerate(blobs):
|
||||
source.append(f'.section .text.{index},"ax"')
|
||||
if blob:
|
||||
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
assembly_path = Path(directory) / "probes.s"
|
||||
object_path = Path(directory) / "probes.o"
|
||||
assembly_path.write_text("\n".join(source) + "\n")
|
||||
subprocess.run(
|
||||
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
dump = subprocess.run(
|
||||
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout
|
||||
first = {}
|
||||
section = None
|
||||
for line in dump.splitlines():
|
||||
header = SECTION.match(line)
|
||||
if header:
|
||||
section = int(header.group(1))
|
||||
continue
|
||||
instruction = INSTRUCTION.match(line)
|
||||
if section is None or section in first or not instruction:
|
||||
continue
|
||||
text, offset, words, warning = instruction.groups()
|
||||
if int(offset, 16) != 0:
|
||||
continue
|
||||
if text.startswith((".long", ".short", ".byte")):
|
||||
first[section] = None
|
||||
else:
|
||||
text = " ".join(text.split())
|
||||
warning = warning.strip()
|
||||
if warning.startswith(";"):
|
||||
text += f" [LLVM: {warning.lstrip('; ')}]"
|
||||
first[section] = (text, 4 * len(words.split()))
|
||||
return [first.get(index) for index in range(len(blobs))]
|
||||
|
||||
|
||||
CRASHED = "crashed"
|
||||
|
||||
|
||||
def disassemble_all(llvm_bin, blobs):
|
||||
"""Batches of 128; a batch that crashes llvm-objdump is split until the
|
||||
crashing blobs are isolated, and each of those is reported as CRASHED."""
|
||||
results = []
|
||||
for start in range(0, len(blobs), 128):
|
||||
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
|
||||
return results
|
||||
|
||||
|
||||
def _isolate(llvm_bin, blobs):
|
||||
try:
|
||||
return disassemble_batch(llvm_bin, blobs)
|
||||
except subprocess.CalledProcessError as error:
|
||||
if error.returncode != -11:
|
||||
raise
|
||||
if len(blobs) == 1:
|
||||
return [CRASHED]
|
||||
half = len(blobs) // 2
|
||||
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
|
||||
|
||||
|
||||
def extension(text, length, family):
|
||||
mnemonic = text.split()[0]
|
||||
if "dpp8:" in text:
|
||||
return "dpp8fi" if "fi:1" in text else "dpp8"
|
||||
if mnemonic.endswith("_dpp"):
|
||||
return "dpp16"
|
||||
if mnemonic.endswith("_sdwa"):
|
||||
return "sdwa"
|
||||
base_bytes = 4 if family in BASE_32 else 8
|
||||
if mnemonic.endswith("_e64"):
|
||||
base_bytes = 8
|
||||
extra = length - base_bytes
|
||||
if mnemonic.startswith("image_") and extra > 0:
|
||||
return f"nsa{extra // 4}"
|
||||
# After excluding vector control and image addresses, an extra dword
|
||||
# carrying a numeric operand is the literal (including mandatory literals).
|
||||
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
|
||||
return "literal"
|
||||
if extra > 0:
|
||||
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
|
||||
return "-"
|
||||
|
||||
|
||||
def assembly(executable):
|
||||
source = HERE / "corpus.s"
|
||||
families = [
|
||||
line.split("//", 1)[1].strip()
|
||||
for line in source.read_text().splitlines()
|
||||
if line.split("//", 1)[0].strip()
|
||||
]
|
||||
result = llvm(executable, source)
|
||||
if result.stderr:
|
||||
raise ValueError(result.stderr)
|
||||
decoded = list(encodings(result.stdout))
|
||||
if len(decoded) != len(families):
|
||||
raise ValueError("LLVM must emit exactly one encoding per assembly line")
|
||||
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
|
||||
|
||||
|
||||
def metadata_forms():
|
||||
snapshot = ISA / "data/rdna2.jsonl"
|
||||
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
|
||||
return project(snapshot.read_text())[2]
|
||||
|
||||
|
||||
def probes():
|
||||
# The normalized snapshot stores instruction variants and encoding records
|
||||
# separately. Reuse its projection to obtain identifiers, widths and labels
|
||||
# for coverage. The projected mnemonic and extensions are never consulted.
|
||||
forms = metadata_forms()
|
||||
rng = random.Random(209)
|
||||
for form in forms:
|
||||
width = form["bytes"]
|
||||
# One probe with every non-identifying bit zero (operands s0/v0, no
|
||||
# modifiers), then two with seeded random operand bits.
|
||||
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
|
||||
for _ in range(2):
|
||||
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
|
||||
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
|
||||
|
||||
|
||||
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
|
||||
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
|
||||
# follow the base encoding.
|
||||
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
|
||||
# Instructions whose last dword is a legal control word for each extension;
|
||||
# LLVM assembles them, so the control words are LLVM's own.
|
||||
CONTROL_SOURCES = {
|
||||
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
|
||||
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
|
||||
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
|
||||
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
|
||||
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
|
||||
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
|
||||
}
|
||||
LITERAL = (0x12345678).to_bytes(4, "little")
|
||||
|
||||
|
||||
def controls(executable):
|
||||
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
|
||||
decoded = list(encodings(llvm(executable, source=source).stdout))
|
||||
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
|
||||
|
||||
|
||||
def extension_probes(executable, forms):
|
||||
"""Every form's zero-operand base with each extension selector its family
|
||||
can carry, followed by a legal control dword or literal. LLVM decides which
|
||||
combinations are instructions; the metadata's extension list is not read."""
|
||||
control = controls(executable)
|
||||
for form in forms:
|
||||
family = form["encoding"].upper()
|
||||
base = form["bits"]
|
||||
if family in ("VOP1", "VOP2", "VOPC"):
|
||||
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
|
||||
shift = 0
|
||||
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
|
||||
kinds, shift = ["literal"], 32
|
||||
elif family in ("SOP1", "SOP2", "SOPC"):
|
||||
kinds, shift = ["literal"], 0
|
||||
else:
|
||||
continue
|
||||
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
|
||||
if base & form["mask"] & (field << shift):
|
||||
continue # SRC0/SSRC0 is part of this form's identifier
|
||||
for kind in kinds:
|
||||
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
|
||||
if kind == "literal":
|
||||
trailer = LITERAL
|
||||
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
|
||||
trailer = control[f"sdwa-{family.lower()}"]
|
||||
else:
|
||||
trailer = control[kind]
|
||||
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
|
||||
|
||||
|
||||
def truncations(entries):
|
||||
by_family = defaultdict(list)
|
||||
for entry in entries:
|
||||
by_family[entry[0]].append(entry)
|
||||
groups = [
|
||||
sorted(group, key=lambda entry: -len(entry[2]))
|
||||
for _, group in sorted(by_family.items())
|
||||
]
|
||||
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
|
||||
yield from islice(interleaved, 40)
|
||||
|
||||
|
||||
def decoded_columns(text, length, family):
|
||||
return text.split()[0], str(length), extension(text, length, family)
|
||||
|
||||
|
||||
def generate(llvm_bin):
|
||||
rows = []
|
||||
entries = assembly(llvm_bin / "llvm-mc")
|
||||
for family, text, data in entries:
|
||||
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
|
||||
probe_list = list(probes()) + [
|
||||
(f"ext-{kind}", family, data)
|
||||
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
|
||||
]
|
||||
cut_list = [
|
||||
(family, text, data, data[:size])
|
||||
for family, text, data in truncations(entries)
|
||||
for size in range(0, len(data), 4)
|
||||
]
|
||||
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
|
||||
for (kind, family, data), decoded in zip(probe_list, decoded_all):
|
||||
if decoded is None:
|
||||
columns = ("invalid", "0", "-")
|
||||
note = "LLVM cannot decode offset zero"
|
||||
elif decoded == CRASHED:
|
||||
columns = ("crashed", "0", "-")
|
||||
note = "llvm-objdump crashed (SIGSEGV)"
|
||||
elif "/*Invalid" not in decoded[0]:
|
||||
text, length = decoded
|
||||
columns = decoded_columns(text, length, family)
|
||||
note = text
|
||||
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
|
||||
# LLVM decodes the words (so it knows the opcode and the length)
|
||||
# but flags an operand the instruction cannot take, for example an
|
||||
# SGPR or literal for a VGPR-only source.
|
||||
text, length = decoded
|
||||
mnemonic, *rest = decoded_columns(text, length, family)
|
||||
columns = (f"invalid-operand:{mnemonic}", *rest)
|
||||
note = text
|
||||
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
|
||||
if kind.startswith("ext-"):
|
||||
note = f"{kind[4:]} {note}"
|
||||
rows.append((source, data.hex(), *columns, f"{family} {note}"))
|
||||
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
|
||||
if decoded is None:
|
||||
observed = "cannot decode" if prefix else "no instruction"
|
||||
elif decoded == CRASHED:
|
||||
observed = "crashed (SIGSEGV)"
|
||||
else:
|
||||
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
|
||||
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
|
||||
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
|
||||
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
|
||||
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--llvm-bin", required=True, type=Path)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
data = generate(args.llvm_bin.resolve())
|
||||
output = HERE / "corpus.tsv"
|
||||
if args.check:
|
||||
if output.read_bytes() != data.encode():
|
||||
parser.exit(1, f"{output} differs from the LLVM output\n")
|
||||
else:
|
||||
output.write_bytes(data.encode())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,320 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction identification cases.
|
||||
s_mov_b32 s105, s0 // SOP1
|
||||
s_mov_b32 exec_lo, -16 // SOP1
|
||||
s_mov_b32 m0, 64 // SOP1
|
||||
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
|
||||
s_mov_b64 exec, vcc // SOP1
|
||||
s_mov_b64 vcc, 0x12345678 // SOP1
|
||||
s_not_b32 s0, s105 // SOP1
|
||||
s_not_b64 s[104:105], s[0:1] // SOP1
|
||||
s_brev_b32 s105, m0 // SOP1
|
||||
s_bcnt1_i32_b32 s0, exec_lo // SOP1
|
||||
s_ff1_i32_b32 s105, -16 // SOP1
|
||||
s_flbit_i32_b32 s105, 0x80000100 // SOP1
|
||||
s_sext_i32_i8 s0, s105 // SOP1
|
||||
s_sext_i32_i16 s105, s0 // SOP1
|
||||
s_getpc_b64 s[104:105] // SOP1
|
||||
s_setpc_b64 s[0:1] // SOP1
|
||||
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
|
||||
s_wqm_b64 s[104:105], exec // SOP1
|
||||
s_add_u32 s105, s0, 0x12345678 // SOP2
|
||||
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
|
||||
s_add_i32 s0, -16, 64 // SOP2
|
||||
s_sub_i32 s105, s0, m0 // SOP2
|
||||
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
|
||||
s_min_i32 s105, s104, -16 // SOP2
|
||||
s_max_u32 s0, s105, 64 // SOP2
|
||||
s_cselect_b32 s105, -1, s0 // SOP2
|
||||
s_and_b64 s[104:105], exec, vcc // SOP2
|
||||
s_or_b64 vcc, s[0:1], exec // SOP2
|
||||
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
|
||||
s_nand_b32 s105, m0, vcc_lo // SOP2
|
||||
s_lshl_b32 s0, s105, 31 // SOP2
|
||||
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
|
||||
s_ashr_i32 s105, 0x87654321, 31 // SOP2
|
||||
s_mul_i32 s0, s105, -16 // SOP2
|
||||
s_bfe_u32 s105, s0, 0x0010000f // SOP2
|
||||
s_cmp_eq_i32 s0, s105 // SOPC
|
||||
s_cmp_lg_i32 m0, -16 // SOPC
|
||||
s_cmp_gt_i32 64, s105 // SOPC
|
||||
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
|
||||
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
|
||||
s_cmp_le_u32 vcc_lo, 64 // SOPC
|
||||
s_cmp_eq_u64 s[104:105], vcc // SOPC
|
||||
s_bitcmp0_b32 s105, 31 // SOPC
|
||||
s_bitcmp1_b64 exec, 63 // SOPC
|
||||
s_movk_i32 s0, -32768 // SOPK
|
||||
s_movk_i32 s105, 32767 // SOPK
|
||||
s_movk_i32 m0, -1 // SOPK
|
||||
s_addk_i32 s105, -32768 // SOPK
|
||||
s_mulk_i32 s0, 32767 // SOPK
|
||||
s_cmpk_eq_i32 s105, -32768 // SOPK
|
||||
s_cmpk_lg_u32 s0, 65535 // SOPK
|
||||
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
|
||||
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
|
||||
s_nop 15 // SOPP
|
||||
s_endpgm 0 // SOPP
|
||||
s_branch -32768 // SOPP
|
||||
s_cbranch_scc0 32767 // SOPP
|
||||
s_cbranch_scc1 -1 // SOPP
|
||||
s_cbranch_vccz 0 // SOPP
|
||||
s_cbranch_vccnz 3 // SOPP
|
||||
s_cbranch_execz 7 // SOPP
|
||||
s_cbranch_execnz -7 // SOPP
|
||||
s_barrier // SOPP
|
||||
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
|
||||
s_sleep 127 // SOPP
|
||||
s_trap 255 // SOPP
|
||||
s_load_dword s105, s[0:1], 1048575 // SMEM
|
||||
s_load_dword s0, s[104:105], -1048576 // SMEM
|
||||
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
|
||||
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
|
||||
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
|
||||
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
|
||||
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
|
||||
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
|
||||
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
|
||||
s_memtime s[104:105] // SMEM
|
||||
s_dcache_inv // SMEM
|
||||
v_mov_b32_e32 v255, v0 // VOP1
|
||||
v_mov_b32_e32 v0, s105 // VOP1
|
||||
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
|
||||
v_mov_b32_e32 v0, -16 // VOP1
|
||||
v_mov_b32_e32 v255, 64 // VOP1
|
||||
v_mov_b32_e32 v0, 0.5 // VOP1
|
||||
v_mov_b32_e32 v255, -4.0 // VOP1
|
||||
v_mov_b32_e32 v0, 0.15915494 // VOP1
|
||||
v_cvt_f32_i32_e32 v255, v0 // VOP1
|
||||
v_cvt_f32_u32_e32 v0, v255 // VOP1
|
||||
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
|
||||
v_rcp_f32_e32 v0, v255 // VOP1
|
||||
v_sqrt_f32_e32 v255, v0 // VOP1
|
||||
v_readfirstlane_b32 s105, v255 // VOP1
|
||||
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
|
||||
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
|
||||
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
|
||||
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
|
||||
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
|
||||
v_add_f32_e32 v0, v255, v0 // VOP2
|
||||
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
|
||||
v_subrev_f32_e32 v0, s105, v255 // VOP2
|
||||
v_mul_f32_e32 v255, -4.0, v0 // VOP2
|
||||
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
|
||||
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
|
||||
v_min_f32_e32 v0, 0.5, v255 // VOP2
|
||||
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
|
||||
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
|
||||
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
|
||||
v_or_b32_e32 v0, m0, v255 // VOP2
|
||||
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
|
||||
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
|
||||
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
|
||||
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
|
||||
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
|
||||
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
|
||||
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
|
||||
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
|
||||
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
|
||||
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
|
||||
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
|
||||
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
|
||||
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
|
||||
v_cmpx_eq_u32_e32 64, v255 // VOPC
|
||||
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
|
||||
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
|
||||
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
|
||||
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
|
||||
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
|
||||
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
|
||||
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
|
||||
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
|
||||
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
|
||||
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
|
||||
v_min3_f32 v0, v255, v0, 0.5 // VOP3
|
||||
v_max3_i32 v255, v0, v255, -16 // VOP3
|
||||
v_med3_u32 v0, v255, v0, 64 // VOP3
|
||||
v_bfe_u32 v255, v0, 31, 1 // VOP3
|
||||
v_bfe_i32 v0, v255, 0, 32 // VOP3
|
||||
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
|
||||
v_alignbit_b32 v0, v255, v0, 31 // VOP3
|
||||
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
|
||||
v_readlane_b32 s105, v255, 31 // VOP3
|
||||
v_writelane_b32 v255, s105, 31 // VOP3
|
||||
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
|
||||
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
|
||||
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
|
||||
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
|
||||
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
|
||||
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
|
||||
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
|
||||
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
|
||||
v_pk_sub_i16 v255, v0, -16 // VOP3P
|
||||
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_min_i16 v255, v0, v255 // VOP3P
|
||||
v_pk_max_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
|
||||
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
|
||||
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
|
||||
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
|
||||
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
|
||||
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
|
||||
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
|
||||
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
|
||||
ds_write_b32 v255, v0 offset:65535 // DS
|
||||
ds_read_b32 v0, v255 offset:65535 // DS
|
||||
ds_write_b8 v0, v255 offset:0 // DS
|
||||
ds_write_b16 v255, v0 offset:32768 // DS
|
||||
ds_read_u8 v0, v255 offset:1 // DS
|
||||
ds_read_i16 v255, v0 offset:65534 // DS
|
||||
ds_write_b64 v255, v[254:255] offset:8 // DS
|
||||
ds_read_b64 v[0:1], v255 offset:16 // DS
|
||||
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
|
||||
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
|
||||
ds_add_u32 v255, v0 offset:65535 // DS
|
||||
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
|
||||
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
|
||||
ds_bpermute_b32 v255, v0, v255 // DS
|
||||
ds_permute_b32 v0, v255, v0 // DS
|
||||
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
|
||||
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
|
||||
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
|
||||
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
|
||||
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
|
||||
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
|
||||
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
|
||||
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
|
||||
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
|
||||
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
|
||||
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
|
||||
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
|
||||
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
|
||||
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
|
||||
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
exp mrt0 v255, off, off, v0 done // EXP
|
||||
exp mrt7 off, v255, v0, off // EXP
|
||||
exp pos0 v0, v255, v0, v255 done // EXP
|
||||
exp pos3 v255, v0, v255, v0 // EXP
|
||||
exp param0 v255, off, v0, off // EXP
|
||||
exp param31 v0, v255, off, off // EXP
|
||||
exp null off, off, off, off done // EXP
|
||||
flat_load_dword v255, v[0:1] offset:2047 // FLAT
|
||||
flat_load_dword v0, v[254:255] offset:1024 // FLAT
|
||||
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
|
||||
flat_load_sbyte v0, v[254:255] glc // FLAT
|
||||
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
|
||||
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
|
||||
flat_store_dword v[254:255], v0 offset:2047 // FLAT
|
||||
flat_store_short v[0:1], v255 offset:1 // FLAT
|
||||
flat_atomic_add v255, v[0:1], v255 glc // FLAT
|
||||
flat_atomic_swap v[254:255], v0 // FLAT
|
||||
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
|
||||
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
|
||||
global_load_ubyte v255, v0, s[0:1] // GLOBAL
|
||||
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
|
||||
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
|
||||
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
|
||||
global_store_byte v0, v255, s[0:1] // GLOBAL
|
||||
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
|
||||
global_atomic_add v[254:255], v0, off // GLOBAL
|
||||
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
|
||||
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
|
||||
scratch_load_ushort v255, v0, off // SCRATCH
|
||||
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
|
||||
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
|
||||
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
|
||||
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
|
||||
scratch_store_byte v0, v255, off // SCRATCH
|
||||
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
|
||||
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
|
||||
ds_gws_init v1 offset:65535 gds // DS
|
||||
ds_gws_barrier v1 offset:0 gds // DS
|
||||
ds_gws_sema_v gds // DS
|
||||
ds_gws_sema_br v1 gds // DS
|
||||
ds_gws_sema_p gds // DS
|
||||
ds_gws_sema_release_all gds // DS
|
||||
ds_ordered_count v0, v1 offset:65535 gds // DS
|
||||
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
|
||||
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_store_byte v[0:1], v2 // FLAT
|
||||
flat_store_byte_d16_hi v[0:1], v2 // FLAT
|
||||
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
|
||||
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
|
||||
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
|
||||
flat_store_short_d16_hi v[0:1], v2 // FLAT
|
||||
flat_atomic_add v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_and v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_or v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
|
||||
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
|
||||
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
|
||||
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
|
||||
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
|
||||
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
|
||||
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
|
||||
v_permlane16_b32 v0, v1, s2, s3 // VOP3
|
||||
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
|
||||
v_swaprel_b32 v0, v1 // VOP1
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
|
||||
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
|
||||
# review each change against LLVM.
|
||||
operand_flagged 000000d60000000000000000000000000000000000000000
|
||||
operand_flagged 000000d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000000dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000001d60000000000000000000000000000000000000000
|
||||
operand_flagged 000001d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000008f10000000000000000000000000000000000000000
|
||||
metadata_only 00000cf10000000000000000000000000000000000000000
|
||||
metadata_only 000020dc0000000000000000000000000000000000000000
|
||||
metadata_only 000024dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028f10000000000000000000000000000000000000000
|
||||
metadata_only 00002cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00002cf10000000000000000000000000000000000000000
|
||||
metadata_only 000030dc0000000000000000000000000000000000000000
|
||||
metadata_only 000034dc0000000000000000000000000000000000000000
|
||||
metadata_only 000038dc0000000000000000000000000000000000000000
|
||||
metadata_only 00003cdc0000000000000000000000000000000000000000
|
||||
metadata_only 000040dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000042d70000000000000000000000000000000000000000
|
||||
operand_flagged 000042d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000043d70000000000000000000000000000000000000000
|
||||
operand_flagged 000043d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000044dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048f10000000000000000000000000000000000000000
|
||||
metadata_only 00004cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00004cf10000000000000000000000000000000000000000
|
||||
metadata_only 000054dd0000000000000000000000000000000000000000
|
||||
metadata_only 000058dd0000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad70000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad7ff00000078563412000000000000000000000000
|
||||
metadata_only 00005cdd0000000000000000000000000000000000000000
|
||||
operand_flagged 000060d70000000000000000000000000000000000000000
|
||||
metadata_only 000060d80000000000000000000000000000000000000000
|
||||
metadata_only 000060dc0000000000000000000000000000000000000000
|
||||
metadata_only 000060dd0000000000000000000000000000000000000000
|
||||
metadata_only 000064d80000000000000000000000000000000000000000
|
||||
metadata_only 000064dc0000000000000000000000000000000000000000
|
||||
metadata_only 000064dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068d80000000000000000000000000000000000000000
|
||||
metadata_only 000068dc0000000000000000000000000000000000000000
|
||||
metadata_only 000068dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068f10000000000000000000000000000000000000000
|
||||
metadata_only 00006cd80000000000000000000000000000000000000000
|
||||
metadata_only 00006cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00006cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00006cf10000000000000000000000000000000000000000
|
||||
metadata_only 000070d80000000000000000000000000000000000000000
|
||||
metadata_only 000070dc0000000000000000000000000000000000000000
|
||||
metadata_only 000070dd0000000000000000000000000000000000000000
|
||||
metadata_only 000074d80000000000000000000000000000000000000000
|
||||
metadata_only 000074dc0000000000000000000000000000000000000000
|
||||
metadata_only 000074dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000075d50000000000000000000000000000000000000000
|
||||
operand_flagged 000075d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 000077d70000000000000000000000000000000000000000
|
||||
operand_flagged 000077d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000078d70000000000000000000000000000000000000000
|
||||
operand_flagged 000078d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000078dc0000000000000000000000000000000000000000
|
||||
metadata_only 000078dd0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdd0000000000000000000000000000000000000000
|
||||
oracle_only 000080d5ff00000078563412000000000000000000000000
|
||||
metadata_only 000080dc0000000000000000000000000000000000000000
|
||||
metadata_only 000080dd0000000000000000000000000000000000000000
|
||||
metadata_only 000082d50000000000000000000000000000000000000000
|
||||
metadata_only 000084dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088f10000000000000000000000000000000000000000
|
||||
metadata_only 00008cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00008cf10000000000000000000000000000000000000000
|
||||
metadata_only 000090dc0000000000000000000000000000000000000000
|
||||
metadata_only 000094dc0000000000000000000000000000000000000000
|
||||
oracle_only 00009bd5ff00000078563412000000000000000000000000
|
||||
metadata_only 0000c0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c0f10000000000000000000000000000000000000000
|
||||
oracle_only 0000c1d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 0000c3d50000000000000000000000000000000000000000
|
||||
operand_flagged 0000c4d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c4f10000000000000000000000000000000000000000
|
||||
operand_flagged 0000c8d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccf10000000000000000000000000000000000000000
|
||||
metadata_only 0000d0f10000000000000000000000000000000000000000
|
||||
metadata_only 0000d4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000dcdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000dcf10000000000000000000000000000000000000000
|
||||
metadata_only 0000e0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4f10000000000000000000000000000000000000000
|
||||
metadata_only 0000e8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000ecdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000fcd80000000000000000000000000000000000000000
|
||||
metadata_only 0000fcdc0000000000000000000000000000000000000000
|
||||
operand_flagged 0004007e00000000000000000000000000000000
|
||||
operand_flagged 0086007e00000000000000000000000000000000
|
||||
operand_flagged 0088007e00000000000000000000000000000000
|
||||
operand_flagged 0090007e00000000000000000000000000000000
|
||||
operand_flagged 00ca007e00000000000000000000000000000000
|
||||
operand_flagged 00d0007e00000000000000000000000000000000
|
||||
metadata_only 010098f10000000000000000000000000000000000000000
|
||||
metadata_only 01009cf10000000000000000000000000000000000000000
|
||||
oracle_only e900007e0088c6fa000000000000000000000000
|
||||
oracle_only e936007e0088c6fa000000000000000000000000
|
||||
oracle_only e982007e0088c6fa000000000000000000000000
|
||||
oracle_only ea00007e0088c6fa000000000000000000000000
|
||||
oracle_only ea36007e0088c6fa000000000000000000000000
|
||||
oracle_only ea82007e0088c6fa000000000000000000000000
|
||||
oracle_only f900007e00060600000000000000000000000000
|
||||
oracle_only f936007e00060600000000000000000000000000
|
||||
oracle_only f982007e00060600000000000000000000000000
|
||||
oracle_only fa00007e00e400ff000000000000000000000000
|
||||
oracle_only fa36007e00e400ff000000000000000000000000
|
||||
oracle_only fa82007e00e400ff000000000000000000000000
|
||||
oracle_only ff00007e78563412000000000000000000000000
|
||||
oracle_only ff1f80be78563412000000000000000000000000
|
||||
oracle_only ff2180be78563412000000000000000000000000
|
||||
oracle_only ff36007e78563412000000000000000000000000
|
||||
oracle_only ff4980be78563412000000000000000000000000
|
||||
oracle_only ff82007e78563412000000000000000000000000
|
||||
@@ -99,6 +99,32 @@ fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_interpolation_attribute_fields_never_select_a_literal() {
|
||||
// AMD RDNA 2 ISA guide section 10.4.2: in the VOP3 interpolation forms SRC0
|
||||
// holds {attr_word, attr_chan, attr} bit-fields (XML OPR_ATTR), so SRC0 = 255
|
||||
// is attr 63, channel w (and attr_word 0) and the instruction is 8 bytes.
|
||||
// LLVM 23.1.6 agrees (#235).
|
||||
for (first, name) in [
|
||||
(0xd600_0000, "V_INTERP_P1_F32"),
|
||||
(0xd601_0000, "V_INTERP_P2_F32"),
|
||||
(0xd602_0000, "V_INTERP_MOV_F32"),
|
||||
(0xd742_0000, "V_INTERP_P1LL_F16"),
|
||||
(0xd743_0000, "V_INTERP_P1LV_F16"),
|
||||
(0xd75a_0000, "V_INTERP_P2_F16"),
|
||||
] {
|
||||
let found = identify(&words(&[first, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((found.form.name, found.len), (name, 8));
|
||||
assert!(!found.trailer.literal, "{name}");
|
||||
}
|
||||
// A general VOP3 source with the same selector still takes the literal.
|
||||
let add = identify(&words(&[0xd503_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((add.form.name, add.len), ("V_ADD_F32", 12));
|
||||
// So does a VGPR-only source (LLVM reports these 12 bytes with an invalid operand).
|
||||
let permlane = identify(&words(&[0xd777_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((permlane.form.name, permlane.len), ("V_PERMLANE16_B32", 12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
|
||||
//!
|
||||
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
|
||||
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
|
||||
//! llvm-objdump decodes byte probes built from each metadata form's
|
||||
//! identifying bits (one with every other bit zero, two with seeded random
|
||||
//! operand bits). The expected name, consumed length and extension of every
|
||||
//! row are LLVM's. This test compares `identify` with them and pins what it
|
||||
//! measures: per-source class counts, the exact rows where the two disagree
|
||||
//! for assembled and zero-operand inputs, and a digest of the random-probe
|
||||
//! classification.
|
||||
//!
|
||||
//! Identification is not execution support: a row counted as identified only
|
||||
//! means both agree on which instruction the bytes are and how long it is.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
|
||||
|
||||
const CORPUS: &str = include_str!("llvm/corpus.tsv");
|
||||
|
||||
/// Row classes, in report order.
|
||||
const CLASSES: [&str; 9] = [
|
||||
"identified", // both decode: same name, length and extension
|
||||
"mismatch", // both decode, but name, length or extension differ
|
||||
"oracle_only", // LLVM decodes, identify returns an error
|
||||
"metadata_only", // identify decodes, LLVM cannot
|
||||
"both_reject", // neither decodes
|
||||
"oracle_crash", // llvm-objdump crashed; no oracle answer
|
||||
"truncated", // a proper prefix: identify asks for more bytes
|
||||
"truncation_other",
|
||||
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
|
||||
];
|
||||
const SOURCES: [&str; 5] = [
|
||||
"asm",
|
||||
"probe-zero",
|
||||
"probe-ext",
|
||||
"probe-random",
|
||||
"truncation",
|
||||
];
|
||||
|
||||
fn base_name(mnemonic: &str) -> String {
|
||||
let upper = mnemonic.to_ascii_uppercase();
|
||||
["_E32", "_E64", "_SDWA", "_DPP"]
|
||||
.into_iter()
|
||||
.find_map(|suffix| upper.strip_suffix(suffix))
|
||||
.unwrap_or(&upper)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn extension(found: &Identified) -> String {
|
||||
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
|
||||
let mut parts = Vec::new();
|
||||
if found.trailer.literal {
|
||||
parts.push("literal");
|
||||
}
|
||||
match found.trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) => parts.push("sdwa"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
}) => parts.push("dpp8"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
}) => parts.push("dpp8fi"),
|
||||
Some(VectorControl::Dpp16) => parts.push("dpp16"),
|
||||
None => {}
|
||||
}
|
||||
if found.trailer.nsa_dwords != 0 {
|
||||
parts.push(&nsa);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
"-".into()
|
||||
} else {
|
||||
parts.join("+")
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
source: usize,
|
||||
form: Option<&'static str>,
|
||||
family: &'a str,
|
||||
hex: &'a str,
|
||||
class: usize,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
fn classify(line: &str) -> Row<'_> {
|
||||
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
|
||||
panic!("bad corpus row: {line}");
|
||||
};
|
||||
let source = SOURCES
|
||||
.iter()
|
||||
.position(|s| *s == source)
|
||||
.unwrap_or_else(|| panic!("bad source: {line}"));
|
||||
let (family, text) = note.split_once(' ').unwrap();
|
||||
let bytes: Vec<u8> = (0..hex.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
|
||||
.collect();
|
||||
let len: usize = len.parse().unwrap();
|
||||
let found = identify(&bytes);
|
||||
let answer = match &found {
|
||||
Ok(found) => format!(
|
||||
"{} ({} bytes, {})",
|
||||
found.form.name,
|
||||
found.len,
|
||||
extension(found)
|
||||
),
|
||||
Err(error) => format!("{error:?}"),
|
||||
};
|
||||
let mut differences = Vec::new();
|
||||
// LLVM decoded the words but flagged an operand the instruction cannot
|
||||
// take. identify does not validate operands; it must still agree on the
|
||||
// instruction and its length, or reject the extension outright.
|
||||
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
|
||||
Some(mnemonic) => (true, mnemonic),
|
||||
None => (false, mnemonic),
|
||||
};
|
||||
let class = match (mnemonic, &found) {
|
||||
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
|
||||
("truncated", _) => 7,
|
||||
("crashed", _) => 5,
|
||||
("invalid", Err(_)) => 4,
|
||||
("invalid", Ok(_)) => 3,
|
||||
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
|
||||
(_, Err(_)) => 2,
|
||||
(_, Ok(found)) => {
|
||||
if found.form.name != base_name(mnemonic) {
|
||||
differences.push("name");
|
||||
}
|
||||
if found.len != len {
|
||||
differences.push("length");
|
||||
}
|
||||
if extension(found) != ext {
|
||||
differences.push("extension");
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
1
|
||||
} else if flagged {
|
||||
8
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
};
|
||||
let kind = if differences.is_empty() {
|
||||
CLASSES[class].to_owned()
|
||||
} else {
|
||||
format!("mismatch/{}", differences.join("+"))
|
||||
};
|
||||
Row {
|
||||
source,
|
||||
form: found.ok().map(|found| found.form.name),
|
||||
family,
|
||||
hex,
|
||||
class,
|
||||
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
|
||||
fn digest(lines: &[String]) -> u64 {
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|l| l.bytes().chain(*b"\n"))
|
||||
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
|
||||
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
|
||||
// rows reviewed against LLVM, not an update of these numbers alone.
|
||||
// Rows: one per source, columns in CLASSES order.
|
||||
const COUNTS: [[usize; 9]; 5] = [
|
||||
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
|
||||
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
|
||||
[1398, 0, 21, 0, 752, 0, 0, 0, 8], // probe-ext
|
||||
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
|
||||
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
|
||||
];
|
||||
/// Every assembled, zero-operand or extension-probe row where the two disagree
|
||||
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
|
||||
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
|
||||
/// Digest of the sorted `class hex` lines of the random probes.
|
||||
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
|
||||
|
||||
#[test]
|
||||
fn identification_agrees_with_the_llvm_corpus() {
|
||||
let mut lines = CORPUS.lines();
|
||||
assert_eq!(
|
||||
lines.next(),
|
||||
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
|
||||
);
|
||||
let rows: Vec<_> = lines.map(classify).collect();
|
||||
let mut counts = [[0usize; 9]; 5];
|
||||
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
|
||||
for row in &rows {
|
||||
counts[row.source][row.class] += 1;
|
||||
by_family.entry(row.family).or_default()[row.class] += 1;
|
||||
}
|
||||
println!("{:9} {}", "family", CLASSES.join(" "));
|
||||
for (family, c) in &by_family {
|
||||
print!("{family:9}");
|
||||
for (name, n) in CLASSES.iter().zip(c) {
|
||||
print!(" {n:>w$}", w = name.len());
|
||||
}
|
||||
println!();
|
||||
}
|
||||
for (source, c) in SOURCES.iter().zip(&counts) {
|
||||
println!("{source:13} {c:?}");
|
||||
}
|
||||
let mut disagreements: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
|
||||
.collect();
|
||||
disagreements.sort_unstable_by_key(|r| r.hex);
|
||||
for r in &disagreements {
|
||||
println!("{}", r.detail);
|
||||
}
|
||||
let disagreements: Vec<_> = disagreements
|
||||
.iter()
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
let mut random: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3)
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
random.sort_unstable();
|
||||
let random_digest = digest(&random);
|
||||
println!("random digest {random_digest:#018x}");
|
||||
for r in rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3 && r.class == 1)
|
||||
.take(5)
|
||||
{
|
||||
println!("random example {}", r.detail);
|
||||
}
|
||||
|
||||
// Distinct metadata forms: agreed by LLVM on at least one row, or only
|
||||
// ever decoded by Xenora (LLVM rejected every probe of that form).
|
||||
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
|
||||
for row in &rows {
|
||||
if let Some(form) = row.form {
|
||||
let entry = forms.entry(form).or_default();
|
||||
match row.class {
|
||||
0 | 8 => entry.0 += 1,
|
||||
3 => entry.1 += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
|
||||
let never: Vec<_> = forms
|
||||
.iter()
|
||||
.filter(|(_, (a, m))| *a == 0 && *m > 0)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
println!(
|
||||
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
|
||||
forms.len(),
|
||||
never.len()
|
||||
);
|
||||
println!("never decoded by LLVM: {}", never.join(" "));
|
||||
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
|
||||
all_names.sort_unstable();
|
||||
all_names.dedup();
|
||||
let unseen: Vec<_> = all_names
|
||||
.iter()
|
||||
.filter(|name| !forms.contains_key(*name))
|
||||
.collect();
|
||||
println!(
|
||||
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
|
||||
FORMS.len(),
|
||||
all_names.len(),
|
||||
unseen.len()
|
||||
);
|
||||
assert_eq!(counts, COUNTS, "class counts per source changed");
|
||||
let pinned: Vec<_> = DISAGREEMENTS
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with('#'))
|
||||
.collect();
|
||||
assert_eq!(disagreements, pinned, "disagreeing rows changed");
|
||||
assert_eq!(
|
||||
random_digest, RANDOM_DIGEST,
|
||||
"random-probe classification changed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
|
||||
fn llvm_corpus_is_fresh() {
|
||||
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
|
||||
let status = std::process::Command::new("python3")
|
||||
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
|
||||
.args(["--llvm-bin", &bin, "--check"])
|
||||
.status()
|
||||
.expect("run corpus.py");
|
||||
assert!(
|
||||
status.success(),
|
||||
"corpus.tsv differs from LLVM's current output"
|
||||
);
|
||||
}
|
||||
@@ -276,16 +276,21 @@ impl<'a> Interpreter<'a> {
|
||||
// HLT: Halt execution
|
||||
0xF4 => Ok(Some(ExitReason::Halt)),
|
||||
|
||||
// SYSCALL: 0x0F 0x05
|
||||
0x0F => {
|
||||
let second = self.fetch_u8()?;
|
||||
if second == 0x05 {
|
||||
let syscall_num = self.cpu.get(Register::Rax);
|
||||
Ok(Some(ExitReason::Syscall(syscall_num)))
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(second))
|
||||
0x0F => match self.fetch_u8()? {
|
||||
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
|
||||
op @ 0xC8..=0xCF => {
|
||||
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
|
||||
let value = self.cpu.get(reg);
|
||||
let reversed = if rex_w {
|
||||
value.swap_bytes()
|
||||
} else {
|
||||
u64::from((value as u32).swap_bytes())
|
||||
};
|
||||
self.cpu.set(reg, reversed);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
op => Err(ExitReason::IllegalInstruction(op)),
|
||||
},
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
|
||||
@@ -1077,6 +1077,16 @@ impl DbtEngine {
|
||||
cur_rip += 1;
|
||||
|
||||
match op2 {
|
||||
// BSWAP r32/r64: the register is encoded in the opcode.
|
||||
0xC8..=0xCF => {
|
||||
insn_count += 1;
|
||||
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
|
||||
let offset = u32::from(reg) * 8;
|
||||
asm.ldr_uoff_64(X9, X19, offset);
|
||||
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
|
||||
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
|
||||
asm.str_uoff_64(X9, X19, offset);
|
||||
}
|
||||
// Jcc rel32 (0x0F 0x80..=0x8F)
|
||||
0x80..=0x8F => {
|
||||
insn_count += 1;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
fn check_bswap(native: bool) {
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const INPUT: u64 = 0x1122_3344_5566_7788;
|
||||
for reg in 0_u8..16 {
|
||||
for width in [16, 32, 64] {
|
||||
let wide = width == 64;
|
||||
let mut code = Vec::new();
|
||||
if width == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
|
||||
if rex != 0x40 {
|
||||
code.push(rex);
|
||||
}
|
||||
code.extend([0x0f, 0xc8 + (reg & 7)]);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr.fill(0xdead_beef);
|
||||
cpu.gpr[reg as usize] = INPUT;
|
||||
cpu.flags = RFlags {
|
||||
cf: wide,
|
||||
zf: !wide,
|
||||
sf: wide,
|
||||
of: !wide,
|
||||
};
|
||||
let flags = cpu.flags;
|
||||
let mut expected = cpu.gpr;
|
||||
let result = if native {
|
||||
DbtEngine::new(16 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu, &mut memory, 1)
|
||||
} else {
|
||||
Interpreter::new(cpu, &mut memory, 1).run()
|
||||
};
|
||||
if width == 16 {
|
||||
assert!(matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::IllegalInstruction(_)
|
||||
));
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{code:02x?}"
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 1);
|
||||
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
|
||||
expected[reg as usize] = if wide {
|
||||
0x8877_6655_4433_2211
|
||||
} else {
|
||||
0x8877_6655
|
||||
};
|
||||
}
|
||||
assert_eq!(result.final_state.gpr, expected);
|
||||
assert_eq!(result.final_state.flags, flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_bswap() {
|
||||
check_bswap(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_bswap() {
|
||||
check_bswap(true);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePipeline",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLLibrary",
|
||||
"MTLPixelFormat",
|
||||
|
||||
+101
-14
@@ -23,6 +23,8 @@ use xenora_texture::{
|
||||
#[path = "render.rs"]
|
||||
mod render;
|
||||
|
||||
pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState};
|
||||
|
||||
const MAX_THREADS_PER_GROUP: usize = 64;
|
||||
const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
@@ -551,6 +553,56 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_profiled_words(source, entry, input, None)
|
||||
}
|
||||
|
||||
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
|
||||
///
|
||||
/// The grid still contains one invocation per input word. The requested width
|
||||
/// is passed to Metal even when the grid is smaller or ends in a partial group.
|
||||
/// The trusted-kernel requirements of [`Self::run_words`] apply.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the same errors as [`Self::run_words_profiled`], with dispatch
|
||||
/// bounds evaluated using this width. Zero and widths above the device or
|
||||
/// pipeline limit are rejected.
|
||||
pub fn run_words_with_group_width(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
width: usize,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if source validation, compilation or pipeline setup fails.
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
|
||||
fn run_profiled_words(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
|
||||
return Err(MetalError::new(
|
||||
@@ -559,7 +611,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
));
|
||||
}
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
|
||||
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
|
||||
}
|
||||
|
||||
fn run(
|
||||
@@ -567,6 +619,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: ComputeInput<'_>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
self.run_sized(source, entry, input, None)
|
||||
}
|
||||
|
||||
/// [`Self::run`] with an optional explicit threadgroup width; `None` keeps
|
||||
/// the default sizing.
|
||||
fn run_sized(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: ComputeInput<'_>,
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
let host_start = Instant::now();
|
||||
let options = compile_options()?;
|
||||
@@ -575,22 +639,21 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
|
||||
let width = MAX_THREADS_PER_GROUP
|
||||
.min(input.len())
|
||||
.min(self.device.maxThreadsPerThreadgroup().width)
|
||||
.min(pipeline.maxTotalThreadsPerThreadgroup());
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
Some(width) if (1..=limit).contains(&width) => width,
|
||||
Some(width) => {
|
||||
return Err(MetalError::new(
|
||||
"threadgroup width",
|
||||
format!("expected a nonzero width at most {limit}, got {width}"),
|
||||
));
|
||||
}
|
||||
None => MAX_THREADS_PER_GROUP.min(input.len()).min(limit),
|
||||
};
|
||||
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
|
||||
return Err(MetalError::new(
|
||||
"dispatch bounds",
|
||||
@@ -681,6 +744,30 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_pipeline(
|
||||
&self,
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
&self,
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> usize {
|
||||
self.device
|
||||
.maxThreadsPerThreadgroup()
|
||||
.width
|
||||
.min(pipeline.maxTotalThreadsPerThreadgroup())
|
||||
}
|
||||
|
||||
fn new_buffer(
|
||||
&self,
|
||||
words: &[u32],
|
||||
|
||||
@@ -13,7 +13,10 @@ pub mod sampler;
|
||||
pub mod texture_pipeline;
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
|
||||
pub use compute::{
|
||||
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer,
|
||||
GuestBufferView, MetalError, NativeCompute, RunProfile,
|
||||
};
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use sampler::MetalSampler;
|
||||
|
||||
+496
-3
@@ -2,19 +2,23 @@
|
||||
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
use objc2::sel;
|
||||
use objc2_metal::{
|
||||
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDevice, MTLLoadAction,
|
||||
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction,
|
||||
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction,
|
||||
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
|
||||
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
|
||||
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
|
||||
MTLTextureUsage, MTLViewport,
|
||||
};
|
||||
|
||||
use xenora_texture::{Bc1Subresource, Bc1Upload};
|
||||
|
||||
use super::{
|
||||
MetalError, NativeCompute, compile_options, complete_command, find_function, validate_source,
|
||||
ComputeInput, MetalError, NativeCompute, compile_options, complete_command, find_function,
|
||||
validate_source,
|
||||
};
|
||||
|
||||
const MAX_PIXELS: usize = 4096;
|
||||
@@ -282,3 +286,492 @@ fn verify_render_validation(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEPTH_FORMAT: MTLPixelFormat = MTLPixelFormat::Depth32Float;
|
||||
const MAX_DEPTH_DRAWS: usize = 16;
|
||||
|
||||
const DEPTH_SOURCE: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
vertex float4 depth_vertex(uint id [[vertex_id]],
|
||||
const device float4 *positions [[buffer(0)]]) {
|
||||
return positions[id];
|
||||
}
|
||||
|
||||
fragment float4 depth_flat(constant float4 &color [[buffer(0)]]) {
|
||||
return color;
|
||||
}
|
||||
|
||||
fragment float4 depth_textured(float4 position [[position]],
|
||||
texture2d<float> image [[texture(0)]],
|
||||
constant float2 &extent [[buffer(0)]]) {
|
||||
constexpr sampler nearest(coord::normalized, filter::nearest, address::clamp_to_edge);
|
||||
return image.sample(nearest, position.xy / extent);
|
||||
}
|
||||
";
|
||||
|
||||
const DEPTH_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void read_depth(depth2d<float, access::read> depth [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint width = depth.get_width();
|
||||
output[index] = as_type<uint>(depth.read(uint2(index % width, index / width)));
|
||||
}
|
||||
";
|
||||
|
||||
/// Comparison of a fragment's depth against the stored depth; it passes when
|
||||
/// `fragment <compare> stored` holds.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DepthCompare {
|
||||
Never,
|
||||
Less,
|
||||
Equal,
|
||||
LessEqual,
|
||||
Greater,
|
||||
NotEqual,
|
||||
GreaterEqual,
|
||||
Always,
|
||||
}
|
||||
|
||||
impl DepthCompare {
|
||||
fn metal(self) -> MTLCompareFunction {
|
||||
match self {
|
||||
Self::Never => MTLCompareFunction::Never,
|
||||
Self::Less => MTLCompareFunction::Less,
|
||||
Self::Equal => MTLCompareFunction::Equal,
|
||||
Self::LessEqual => MTLCompareFunction::LessEqual,
|
||||
Self::Greater => MTLCompareFunction::Greater,
|
||||
Self::NotEqual => MTLCompareFunction::NotEqual,
|
||||
Self::GreaterEqual => MTLCompareFunction::GreaterEqual,
|
||||
Self::Always => MTLCompareFunction::Always,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Depth test and write enable of one draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DepthState {
|
||||
pub compare: DepthCompare,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
impl DepthState {
|
||||
/// No depth test and no depth write: the only state allowed without a
|
||||
/// depth attachment.
|
||||
pub const DISABLED: Self = Self {
|
||||
compare: DepthCompare::Always,
|
||||
write: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Colour source of one depth-pass draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DepthFill {
|
||||
/// A constant RGBA8 colour.
|
||||
Flat([u8; 4]),
|
||||
/// The pass's BC1 texture, sampled with nearest filtering at the pixel centre.
|
||||
Bc1Texture,
|
||||
}
|
||||
|
||||
/// One triangle of a depth pass: three clip-space positions, colour and depth state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DepthDraw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: DepthFill,
|
||||
pub depth: DepthState,
|
||||
}
|
||||
|
||||
/// An offscreen pass of up to 16 triangles drawn in order into a cleared
|
||||
/// RGBA8Unorm target with viewport depth range 0..1.
|
||||
///
|
||||
/// With `clear_depth`, the pass has a `Depth32Float` attachment cleared to that
|
||||
/// value and stored after the pass. Without it, the pass has no depth
|
||||
/// attachment and every draw must use [`DepthState::DISABLED`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct DepthPass<'a> {
|
||||
pub extent: [usize; 2],
|
||||
pub clear_color: [u8; 4],
|
||||
pub clear_depth: Option<f32>,
|
||||
pub draws: &'a [DepthDraw],
|
||||
/// A validated BC1 upload whose base level of layer 0 is uploaded to a
|
||||
/// native `BC1_RGBA` texture as the original blocks, without CPU decoding.
|
||||
pub texture: Option<&'a Bc1Upload<'a>>,
|
||||
}
|
||||
|
||||
/// Colour bytes, tightly packed top-to-bottom, and the stored depth values
|
||||
/// when the pass has a depth attachment.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DepthOutput {
|
||||
pub color: Vec<u8>,
|
||||
pub depth: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl NativeCompute {
|
||||
/// Draw a depth-tested offscreen pass and read back colour and depth.
|
||||
///
|
||||
/// Each draw sets its own depth state before drawing, so depth compare,
|
||||
/// clear and write enable act exactly as the pass describes. The stored
|
||||
/// depth is read back by a compute kernel that returns each value as
|
||||
/// the texture read gives it, without numeric conversion.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid extent, too many draws, non-finite
|
||||
/// positions, a depth state without depth attachment, a non-finite clear
|
||||
/// depth or one outside 0..=1, a textured draw without texture, unavailable
|
||||
/// BC compression (operation `supportsBCTextureCompression`), or Metal
|
||||
/// setup or execution failure.
|
||||
pub fn render_depth(&self, pass: &DepthPass<'_>) -> Result<DepthOutput, MetalError> {
|
||||
let [width, height] = pass.extent;
|
||||
let pixels = width
|
||||
.checked_mul(height)
|
||||
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
|
||||
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
|
||||
validate_depth_pass(pass)?;
|
||||
let bc1 = pass
|
||||
.texture
|
||||
.map(|upload| {
|
||||
let level = upload.subresource(0, 0).map_err(|error| {
|
||||
MetalError::new("texture subresource", format!("{error:?}"))
|
||||
})?;
|
||||
self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
self.new_bc1_texture(&level)
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(DEPTH_SOURCE, &options)?;
|
||||
let vertex = find_function(&library, "depth_vertex")?;
|
||||
let depth_format = if pass.clear_depth.is_some() {
|
||||
DEPTH_FORMAT
|
||||
} else {
|
||||
MTLPixelFormat::Invalid
|
||||
};
|
||||
let flat = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_flat")?,
|
||||
depth_format,
|
||||
)?;
|
||||
let textured = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_textured")?,
|
||||
depth_format,
|
||||
)?;
|
||||
let color = self.new_target(
|
||||
PIXEL_FORMAT,
|
||||
width,
|
||||
height,
|
||||
MTLStorageMode::Shared,
|
||||
MTLTextureUsage::RenderTarget,
|
||||
)?;
|
||||
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
|
||||
// SAFETY: Slot zero is the only color attachment for this pass.
|
||||
let attachment = unsafe {
|
||||
pass_descriptor
|
||||
.colorAttachments()
|
||||
.objectAtIndexedSubscript(0)
|
||||
};
|
||||
attachment.setTexture(Some(&color));
|
||||
attachment.setLoadAction(MTLLoadAction::Clear);
|
||||
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
|
||||
attachment.setClearColor(MTLClearColor {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
});
|
||||
attachment.setStoreAction(MTLStoreAction::Store);
|
||||
let depth = pass
|
||||
.clear_depth
|
||||
.map(|clear| {
|
||||
let texture = self.new_target(
|
||||
DEPTH_FORMAT,
|
||||
width,
|
||||
height,
|
||||
MTLStorageMode::Private,
|
||||
MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead,
|
||||
)?;
|
||||
let depth_attachment = pass_descriptor.depthAttachment();
|
||||
depth_attachment.setTexture(Some(&texture));
|
||||
depth_attachment.setLoadAction(MTLLoadAction::Clear);
|
||||
depth_attachment.setClearDepth(f64::from(clear));
|
||||
depth_attachment.setStoreAction(MTLStoreAction::Store);
|
||||
Ok::<_, MetalError>(texture)
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
// A pass without draws still clears and stores both attachments.
|
||||
let words: Vec<u32> = pass
|
||||
.draws
|
||||
.iter()
|
||||
.flat_map(|draw| draw.positions.as_flattened())
|
||||
.map(|value| value.to_bits())
|
||||
.collect();
|
||||
let positions = (!words.is_empty())
|
||||
.then(|| self.new_buffer(&words))
|
||||
.transpose()?;
|
||||
// Everything fallible is resolved before encoding starts, so an
|
||||
// error never leaves an encoder without endEncoding.
|
||||
let states = pass
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| {
|
||||
depth
|
||||
.as_ref()
|
||||
.map(|_| self.depth_state(draw.depth))
|
||||
.transpose()
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let command = self.queue.commandBuffer().ok_or_else(|| {
|
||||
MetalError::new("commandBuffer", "render command buffer creation failed")
|
||||
})?;
|
||||
let encoder = command
|
||||
.renderCommandEncoderWithDescriptor(&pass_descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"renderCommandEncoderWithDescriptor",
|
||||
"render encoder creation failed",
|
||||
)
|
||||
})?;
|
||||
encoder.setViewport(MTLViewport {
|
||||
originX: 0.0,
|
||||
originY: 0.0,
|
||||
width: width as f64,
|
||||
height: height as f64,
|
||||
znear: 0.0,
|
||||
zfar: 1.0,
|
||||
});
|
||||
let extent = [width as f32, height as f32];
|
||||
for (index, (draw, state)) in pass.draws.iter().zip(&states).enumerate() {
|
||||
if let Some(state) = state {
|
||||
encoder.setDepthStencilState(Some(state));
|
||||
}
|
||||
// SAFETY: The position buffer holds three float4s per draw and
|
||||
// the vertex stage reads only this draw's three. Fragment
|
||||
// constants are copied by Metal and match the declared types.
|
||||
// The texture, when bound, is a live BC1 texture of this device.
|
||||
unsafe {
|
||||
encoder.setVertexBuffer_offset_atIndex(positions.as_deref(), index * 48, 0);
|
||||
match draw.fill {
|
||||
DepthFill::Flat(rgba) => {
|
||||
encoder.setRenderPipelineState(&flat);
|
||||
let rgba = rgba.map(|value| f32::from(value) / 255.0);
|
||||
encoder.setFragmentBytes_length_atIndex(
|
||||
NonNull::from(&rgba).cast(),
|
||||
size_of_val(&rgba),
|
||||
0,
|
||||
);
|
||||
}
|
||||
DepthFill::Bc1Texture => {
|
||||
encoder.setRenderPipelineState(&textured);
|
||||
encoder.setFragmentTexture_atIndex(bc1.as_deref(), 0);
|
||||
encoder.setFragmentBytes_length_atIndex(
|
||||
NonNull::from(&extent).cast(),
|
||||
size_of_val(&extent),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
encoder.drawPrimitives_vertexStart_vertexCount(
|
||||
MTLPrimitiveType::Triangle,
|
||||
0,
|
||||
3,
|
||||
);
|
||||
}
|
||||
}
|
||||
encoder.endEncoding();
|
||||
complete_command(&command)?;
|
||||
|
||||
let mut output = vec![0; pixels * 4];
|
||||
// SAFETY: GPU writes have completed, and the initialized output
|
||||
// allocation fits the entire shared texture with tightly packed rows.
|
||||
unsafe {
|
||||
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
|
||||
NonNull::from(output.as_mut_slice()).cast(),
|
||||
width * 4,
|
||||
whole(width, height),
|
||||
0,
|
||||
);
|
||||
}
|
||||
let depth = depth
|
||||
.map(|texture| {
|
||||
self.run(
|
||||
DEPTH_READBACK,
|
||||
"read_depth",
|
||||
ComputeInput::Texture(&texture, pixels),
|
||||
)
|
||||
.map(|profile| profile.output.into_iter().map(f32::from_bits).collect())
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(DepthOutput {
|
||||
color: output,
|
||||
depth,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn depth_pipeline(
|
||||
&self,
|
||||
vertex: &ProtocolObject<dyn MTLFunction>,
|
||||
fragment: &ProtocolObject<dyn MTLFunction>,
|
||||
depth_format: MTLPixelFormat,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, MetalError> {
|
||||
let descriptor = MTLRenderPipelineDescriptor::new();
|
||||
descriptor.setVertexFunction(Some(vertex));
|
||||
descriptor.setFragmentFunction(Some(fragment));
|
||||
// SAFETY: Slot zero is the only color attachment for this pipeline.
|
||||
unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }
|
||||
.setPixelFormat(PIXEL_FORMAT);
|
||||
descriptor.setDepthAttachmentPixelFormat(depth_format);
|
||||
let pipeline = self
|
||||
.device
|
||||
.newRenderPipelineStateWithDescriptor_error(&descriptor)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newRenderPipelineStateWithDescriptor",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
verify_render_validation(&pipeline)?;
|
||||
Ok(pipeline)
|
||||
}
|
||||
|
||||
fn depth_state(
|
||||
&self,
|
||||
state: DepthState,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLDepthStencilState>>, MetalError> {
|
||||
let descriptor = MTLDepthStencilDescriptor::new();
|
||||
descriptor.setDepthCompareFunction(state.compare.metal());
|
||||
descriptor.setDepthWriteEnabled(state.write);
|
||||
self.device
|
||||
.newDepthStencilStateWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"newDepthStencilStateWithDescriptor",
|
||||
"depth state creation failed",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn new_target(
|
||||
&self,
|
||||
format: MTLPixelFormat,
|
||||
width: usize,
|
||||
height: usize,
|
||||
storage: MTLStorageMode,
|
||||
usage: MTLTextureUsage,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, MetalError> {
|
||||
// SAFETY: The nonzero dimensions are bounded by MAX_PIXELS, and both
|
||||
// RGBA8Unorm and Depth32Float are renderable on every Apple GPU family.
|
||||
let descriptor = unsafe {
|
||||
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
|
||||
format, width, height, false,
|
||||
)
|
||||
};
|
||||
descriptor.setStorageMode(storage);
|
||||
descriptor.setUsage(usage);
|
||||
self.device
|
||||
.newTextureWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"newTextureWithDescriptor",
|
||||
"render target allocation failed",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn new_bc1_texture(
|
||||
&self,
|
||||
level: &Bc1Subresource<'_>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, MetalError> {
|
||||
let texture = self.new_target(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
level.width,
|
||||
level.height,
|
||||
MTLStorageMode::Shared,
|
||||
MTLTextureUsage::ShaderRead,
|
||||
)?;
|
||||
// Apple documents a zero stride for a single compressed block row.
|
||||
let bytes_per_row = if level.height <= 4 {
|
||||
0
|
||||
} else {
|
||||
level.row_pitch
|
||||
};
|
||||
// SAFETY: The region spans the whole level. The level comes only from
|
||||
// `Bc1Upload::subresource`, whose layout validation guarantees that the
|
||||
// bytes hold every block row, including partial edge blocks, at this
|
||||
// block-aligned stride.
|
||||
unsafe {
|
||||
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
|
||||
whole(level.width, level.height),
|
||||
0,
|
||||
NonNull::from(level.bytes).cast(),
|
||||
bytes_per_row,
|
||||
);
|
||||
}
|
||||
Ok(texture)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_depth_pass(pass: &DepthPass<'_>) -> Result<(), MetalError> {
|
||||
if pass.draws.len() > MAX_DEPTH_DRAWS {
|
||||
return Err(MetalError::new("depth pass", "expected at most 16 draws"));
|
||||
}
|
||||
if pass
|
||||
.draws
|
||||
.iter()
|
||||
.flat_map(|draw| draw.positions.as_flattened())
|
||||
.any(|value| !value.is_finite())
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"render input",
|
||||
"expected finite vertex data",
|
||||
));
|
||||
}
|
||||
if let Some(clear) = pass.clear_depth
|
||||
&& !(0.0..=1.0).contains(&clear)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"expected a clear depth in 0..=1",
|
||||
));
|
||||
}
|
||||
if pass.clear_depth.is_none()
|
||||
&& pass
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| draw.depth != DepthState::DISABLED)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"a depth test or write needs a depth attachment",
|
||||
));
|
||||
}
|
||||
if pass.texture.is_none()
|
||||
&& pass
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| draw.fill == DepthFill::Bc1Texture)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"textured draw without texture",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn whole(width: usize, height: usize) -> MTLRegion {
|
||||
MTLRegion {
|
||||
origin: MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
size: MTLSize {
|
||||
width,
|
||||
height,
|
||||
depth: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU check: the reference rasteriser agrees with the independently derived
|
||||
//! expectations for every depth case. Runs without a GPU.
|
||||
|
||||
#[path = "support/depth_cases.rs"]
|
||||
mod depth_cases;
|
||||
|
||||
use depth_cases::{BC1_BLOCKS, Fill, SIZE, cases, expected};
|
||||
use xenora_ref::depth::{RefDraw, RefFill, RefTexture, render_depth};
|
||||
|
||||
/// Row-major 8x8 texels decoded block by block with the CPU BC1 decoder.
|
||||
pub fn bc1_texels() -> Vec<[u8; 4]> {
|
||||
let mut texels = vec![[0; 4]; 64];
|
||||
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
|
||||
let decoded = xenora_texture::decode_bc1(*bytes);
|
||||
for (index, texel) in decoded.iter().enumerate() {
|
||||
let x = (block % 2) * 4 + index % 4;
|
||||
let y = (block / 2) * 4 + index / 4;
|
||||
texels[y * 8 + x] = *texel;
|
||||
}
|
||||
}
|
||||
texels
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_independent_expectations() {
|
||||
let texels = bc1_texels();
|
||||
let texture = RefTexture {
|
||||
width: 8,
|
||||
height: 8,
|
||||
texels: &texels,
|
||||
};
|
||||
let expected = expected();
|
||||
let cases = cases();
|
||||
assert_eq!(cases.len(), 30);
|
||||
assert_eq!(expected.len(), cases.len());
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws: Vec<_> = case
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| RefDraw {
|
||||
positions: draw.positions,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => RefFill::Flat(rgba),
|
||||
Fill::Texture => RefFill::Texture,
|
||||
},
|
||||
compare: draw.compare,
|
||||
write: draw.write,
|
||||
})
|
||||
.collect();
|
||||
let (color, depth) = render_depth(
|
||||
[SIZE, SIZE],
|
||||
case.clear_color,
|
||||
case.clear_depth,
|
||||
&draws,
|
||||
Some(texture),
|
||||
)
|
||||
.expect("reference render");
|
||||
assert_eq!(color, want.color, "{} colour", case.name);
|
||||
assert_eq!(depth, want.depth, "{} depth", case.name);
|
||||
}
|
||||
}
|
||||
+1161
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,151 @@
|
||||
use xenora_metal::{DepthCompare, DepthDraw, DepthFill, DepthPass, DepthState};
|
||||
use xenora_ref::depth::CompareFunction;
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
|
||||
|
||||
use super::depth_cases::{BC1_BLOCKS, Case, Fill, GREEN, SIZE, cases, expected};
|
||||
use super::{context, native};
|
||||
|
||||
fn compare(function: CompareFunction) -> DepthCompare {
|
||||
match function {
|
||||
CompareFunction::Never => DepthCompare::Never,
|
||||
CompareFunction::Less => DepthCompare::Less,
|
||||
CompareFunction::Equal => DepthCompare::Equal,
|
||||
CompareFunction::LessEqual => DepthCompare::LessEqual,
|
||||
CompareFunction::Greater => DepthCompare::Greater,
|
||||
CompareFunction::NotEqual => DepthCompare::NotEqual,
|
||||
CompareFunction::GreaterEqual => DepthCompare::GreaterEqual,
|
||||
CompareFunction::Always => DepthCompare::Always,
|
||||
}
|
||||
}
|
||||
|
||||
fn metal_draws(case: &Case) -> Vec<DepthDraw> {
|
||||
case.draws
|
||||
.iter()
|
||||
.map(|draw| DepthDraw {
|
||||
positions: draw.positions,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => DepthFill::Flat(rgba),
|
||||
Fill::Texture => DepthFill::Bc1Texture,
|
||||
},
|
||||
depth: DepthState {
|
||||
compare: compare(draw.compare),
|
||||
write: draw.write,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bc1_upload() -> Bc1Upload<'static> {
|
||||
Bc1Upload::new(
|
||||
&BC1_BLOCKS,
|
||||
Bc1UploadDesc {
|
||||
width: 8,
|
||||
height: 8,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: 16,
|
||||
slice_pitch: 32,
|
||||
},
|
||||
)
|
||||
.expect("valid BC1 upload")
|
||||
}
|
||||
|
||||
/// Each case's native colour and depth must equal the independently derived
|
||||
/// values (which the CPU reference also reproduces in `depth_reference`).
|
||||
/// Colour and depth are compared separately, per pixel.
|
||||
#[test]
|
||||
fn depth_attachment_known_answers() {
|
||||
let gpu = context();
|
||||
let upload = bc1_upload();
|
||||
let expected = expected();
|
||||
let cases = cases();
|
||||
assert_eq!(cases.len(), expected.len());
|
||||
let mut checked = 0;
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws = metal_draws(case);
|
||||
let output = native(
|
||||
gpu.render_depth(&DepthPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: case.clear_color,
|
||||
clear_depth: case.clear_depth,
|
||||
draws: &draws,
|
||||
// Only the textured case needs BC support, so a device without it
|
||||
// fails that case alone, as a capability error.
|
||||
texture: case
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| matches!(draw.fill, Fill::Texture))
|
||||
.then_some(&upload),
|
||||
}),
|
||||
);
|
||||
for (index, (pixel, wanted)) in output
|
||||
.color
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(&want.color)
|
||||
.enumerate()
|
||||
{
|
||||
let (x, y) = (index % SIZE, index / SIZE);
|
||||
assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name);
|
||||
}
|
||||
assert_eq!(output.color.len(), SIZE * SIZE * 4);
|
||||
match (&output.depth, &want.depth) {
|
||||
(Some(depth), Some(wanted)) => {
|
||||
assert_eq!(depth.len(), wanted.len());
|
||||
for (index, (value, wanted)) in depth.iter().zip(wanted).enumerate() {
|
||||
let (x, y) = (index % SIZE, index / SIZE);
|
||||
assert_eq!(
|
||||
value.to_bits(),
|
||||
wanted.to_bits(),
|
||||
"{} depth at ({x}, {y}): {value} vs {wanted}",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
(got, want) => panic!("{}: depth presence {got:?} vs {want:?}", case.name),
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
println!("checked {checked} depth passes of {} pixels", SIZE * SIZE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_state_without_attachment_is_rejected() {
|
||||
let gpu = context();
|
||||
let draw = DepthDraw {
|
||||
positions: [
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
fill: DepthFill::Flat(GREEN),
|
||||
depth: DepthState {
|
||||
compare: DepthCompare::Less,
|
||||
write: false,
|
||||
},
|
||||
};
|
||||
let pass = |clear_depth, draw: DepthDraw| {
|
||||
gpu.render_depth(&DepthPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: [0; 4],
|
||||
clear_depth,
|
||||
draws: &[draw],
|
||||
texture: None,
|
||||
})
|
||||
};
|
||||
let error = pass(None, draw).expect_err("depth test without attachment");
|
||||
assert!(!error.is_capability_unavailable(), "{error}");
|
||||
for clear in [-0.25, 1.5, f32::NAN] {
|
||||
pass(Some(clear), draw).expect_err("clear depth outside 0..=1");
|
||||
}
|
||||
let textured = DepthDraw {
|
||||
fill: DepthFill::Bc1Texture,
|
||||
..draw
|
||||
};
|
||||
pass(Some(1.0), textured).expect_err("textured draw without texture");
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
use xenora_metal::NativeCompute;
|
||||
|
||||
#[path = "native/depth.rs"]
|
||||
mod depth;
|
||||
#[path = "support/depth_cases.rs"]
|
||||
mod depth_cases;
|
||||
#[path = "native/guest_buffer.rs"]
|
||||
mod guest_buffer;
|
||||
#[path = "native/offscreen.rs"]
|
||||
@@ -51,6 +55,165 @@ fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
const MAX_DISPATCH_GROUPS: usize = 64;
|
||||
|
||||
fn mixing_fixture(rounds: u32) -> String {
|
||||
fixture(&format!(
|
||||
"
|
||||
uint value = input[id] ^ (id * 0x9e3779b9u);
|
||||
for (uint round = 0u; round < {rounds}u; ++round) {{
|
||||
value ^= value << 13u;
|
||||
value ^= value >> 17u;
|
||||
value ^= value << 5u;
|
||||
value = value * 0x85ebca6bu + round;
|
||||
}}
|
||||
output[id] = value;
|
||||
"
|
||||
))
|
||||
}
|
||||
|
||||
fn mixing_expectation(input: &[u32], rounds: u32) -> Vec<u32> {
|
||||
(0_u32..)
|
||||
.zip(input)
|
||||
.map(|(id, &word)| {
|
||||
let mut value = word ^ id.wrapping_mul(0x9e37_79b9);
|
||||
for round in 0..rounds {
|
||||
let left = value ^ (value << 13);
|
||||
let right = left ^ (left >> 17);
|
||||
let mixed = right ^ (right << 5);
|
||||
value = mixed.wrapping_mul(0x85eb_ca6b).wrapping_add(round);
|
||||
}
|
||||
value
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mixing_input(words: u32) -> Vec<u32> {
|
||||
(0..words)
|
||||
.map(|id| id.wrapping_mul(0xc2b2_ae35) ^ 0xdead_beef)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threadgroup_widths_give_identical_known_answers() {
|
||||
const WIDTHS: [usize; 16] = [
|
||||
1, 2, 3, 7, 31, 32, 33, 63, 64, 65, 96, 128, 255, 256, 512, 1024,
|
||||
];
|
||||
const GRIDS: [u32; 7] = [1, 63, 64, 65, 1000, 4093, 4096];
|
||||
const ROUNDS: u32 = 37;
|
||||
let context = context();
|
||||
let source = mixing_fixture(ROUNDS);
|
||||
let limit = native(context.max_group_width(&source, "fixture"));
|
||||
let mut checked = 0;
|
||||
let mut skipped = 0;
|
||||
|
||||
for grid in GRIDS {
|
||||
let input = mixing_input(grid);
|
||||
let expected = mixing_expectation(&input, ROUNDS);
|
||||
for width in WIDTHS {
|
||||
if width > limit {
|
||||
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let groups = input.len().div_ceil(width);
|
||||
if groups > MAX_DISPATCH_GROUPS {
|
||||
println!(
|
||||
"skipped grid={grid} width={width}: {groups} groups exceed {MAX_DISPATCH_GROUPS}"
|
||||
);
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let profile =
|
||||
native(context.run_words_with_group_width(&source, "fixture", &input, width));
|
||||
assert_eq!(profile.output, expected, "grid={grid} width={width}");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 0);
|
||||
println!("checked {checked} configurations, skipped {skipped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threadgroup_width_rejections() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id];");
|
||||
let limit = native(context.max_group_width(&source, "fixture"));
|
||||
for width in [0, limit + 1] {
|
||||
let error = context
|
||||
.run_words_with_group_width(&source, "fixture", &[25], width)
|
||||
.expect_err("invalid threadgroup width must fail");
|
||||
assert_eq!(error.operation, "threadgroup width");
|
||||
}
|
||||
let error = context
|
||||
.run_words_with_group_width(&source, "fixture", &[25; MAX_DISPATCH_GROUPS + 1], 1)
|
||||
.expect_err("too many threadgroups must fail");
|
||||
assert_eq!(error.operation, "dispatch bounds");
|
||||
}
|
||||
|
||||
fn timing_summary(samples: &mut [f64]) -> String {
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let count = samples.len();
|
||||
let median = f64::midpoint(samples[(count - 1) / 2], samples[count / 2]);
|
||||
let p95 = samples[(count * 95).div_ceil(100) - 1];
|
||||
format!(
|
||||
"median={:.3} min={:.3} max={:.3} p95={:.3}",
|
||||
median * 1e6,
|
||||
samples[0] * 1e6,
|
||||
samples[count - 1] * 1e6,
|
||||
p95 * 1e6,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual GPU timing run"]
|
||||
fn threadgroup_width_benchmark() {
|
||||
const ROUNDS: u32 = 2000;
|
||||
const WARMUPS: usize = 5;
|
||||
const SAMPLES: usize = 30;
|
||||
let context = context();
|
||||
let device = context.device_name();
|
||||
let source = mixing_fixture(ROUNDS);
|
||||
let input = mixing_input(4096);
|
||||
let expected = mixing_expectation(&input, ROUNDS);
|
||||
let limit = native(context.max_group_width(&source, "fixture"));
|
||||
|
||||
let mut widths = vec![None];
|
||||
for width in [32, 64, 128, 256, 512, 1024] {
|
||||
if width > limit {
|
||||
println!("device={device} skipped width={width}: device/pipeline limit is {limit}");
|
||||
} else if input.len().div_ceil(width) > MAX_DISPATCH_GROUPS {
|
||||
println!("device={device} skipped width={width}: exceeds {MAX_DISPATCH_GROUPS} groups");
|
||||
} else {
|
||||
widths.push(Some(width));
|
||||
}
|
||||
}
|
||||
let mut timings = vec![([0.0; SAMPLES], [0.0; SAMPLES]); widths.len()];
|
||||
for round in 0..WARMUPS + SAMPLES {
|
||||
for (width, (gpu, host)) in widths.iter().zip(&mut timings) {
|
||||
let profile = native(match width {
|
||||
Some(width) => {
|
||||
context.run_words_with_group_width(&source, "fixture", &input, *width)
|
||||
}
|
||||
None => context.run_words_profiled(&source, "fixture", &input),
|
||||
});
|
||||
assert_eq!(profile.output, expected, "width={width:?} round={round}");
|
||||
if round >= WARMUPS {
|
||||
gpu[round - WARMUPS] = profile.gpu_seconds;
|
||||
host[round - WARMUPS] = profile.host_seconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (width, (gpu, host)) in widths.into_iter().zip(&mut timings) {
|
||||
let width = width.map_or_else(|| "default".to_owned(), |width| width.to_string());
|
||||
println!(
|
||||
"device={device} width={width} gpu_us[{}] host_us[{}]",
|
||||
timing_summary(gpu),
|
||||
timing_summary(host),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_multiplication() {
|
||||
let context = context();
|
||||
@@ -203,3 +366,38 @@ fn errors_propagate() {
|
||||
.expect_err("excessive dispatch must fail");
|
||||
assert_eq!(error.operation, "dispatch bounds");
|
||||
}
|
||||
|
||||
/// Identical outputs alone cannot show which width ran, so each thread also
|
||||
/// reports the requested group width, its own group's size and its in-group
|
||||
/// index (11, 11 and 10 bits).
|
||||
#[test]
|
||||
fn requested_threadgroup_width_is_dispatched() {
|
||||
const SOURCE: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void fixture(device const uint *input [[buffer(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint id [[thread_position_in_grid]],
|
||||
uint local [[thread_index_in_threadgroup]],
|
||||
uint group_size [[threads_per_threadgroup]],
|
||||
uint requested [[dispatch_threads_per_threadgroup]]) {
|
||||
output[id] = (requested << 21u) | (group_size << 10u) | local;
|
||||
}
|
||||
";
|
||||
let context = context();
|
||||
let limit = native(context.max_group_width(SOURCE, "fixture"));
|
||||
for (grid, width) in [(1000_usize, 33_usize), (4093, 64), (4096, 256), (65, 1024)] {
|
||||
if width > limit {
|
||||
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
|
||||
continue;
|
||||
}
|
||||
let profile =
|
||||
native(context.run_words_with_group_width(SOURCE, "fixture", &vec![0; grid], width));
|
||||
for (id, word) in profile.output.iter().enumerate() {
|
||||
// dispatchThreads trims the last group to the grid's remainder.
|
||||
let size = width.min(grid - id / width * width);
|
||||
let expected = u32::try_from((width << 21) | (size << 10) | (id % width)).unwrap();
|
||||
assert_eq!(*word, expected, "grid={grid} width={width} id={id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Original depth-pass fixtures shared by the CPU reference check and the
|
||||
//! native Metal test, and the parser for the independently derived
|
||||
//! expectations in `fixtures/depth_expected.txt`.
|
||||
|
||||
use xenora_ref::depth::CompareFunction;
|
||||
|
||||
pub const SIZE: usize = 16;
|
||||
pub const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
pub const GREEN: [u8; 4] = [0, 255, 0, 255];
|
||||
pub const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
const BLACK: [u8; 4] = [0, 0, 0, 255];
|
||||
|
||||
/// Four original BC1 blocks (8x8 texels) using only endpoint and
|
||||
/// transparent selectors, so every decoded texel is exact.
|
||||
pub const BC1_BLOCKS: [u8; 32] = [
|
||||
0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour
|
||||
0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour
|
||||
0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black
|
||||
0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black
|
||||
];
|
||||
|
||||
// Triangles in pixel coordinates; no pixel centre lies on any edge.
|
||||
const FULL: [[f32; 2]; 3] = [[0.0, 16.0], [32.0, 16.0], [0.0, -16.0]];
|
||||
const A: [[f32; 2]; 3] = [[0.0, 0.0], [16.0, 0.0], [0.0, 12.0]];
|
||||
const B: [[f32; 2]; 3] = [[4.0, 3.0], [16.0, 4.0], [6.0, 16.0]];
|
||||
const C: [[f32; 2]; 3] = [[0.0, 8.0], [10.0, 8.0], [0.0, 16.0]];
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Fill {
|
||||
Flat([u8; 4]),
|
||||
Texture,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Draw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: Fill,
|
||||
pub compare: CompareFunction,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Case {
|
||||
pub name: String,
|
||||
pub clear_color: [u8; 4],
|
||||
pub clear_depth: Option<f32>,
|
||||
pub draws: Vec<Draw>,
|
||||
}
|
||||
|
||||
fn draw(tri: [[f32; 2]; 3], z: f32, fill: Fill, compare: CompareFunction, write: bool) -> Draw {
|
||||
Draw {
|
||||
positions: tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, z, 1.0]),
|
||||
fill,
|
||||
compare,
|
||||
write,
|
||||
}
|
||||
}
|
||||
|
||||
fn case(name: &str, clear_color: [u8; 4], clear_depth: Option<f32>, draws: Vec<Draw>) -> Case {
|
||||
Case {
|
||||
name: name.to_owned(),
|
||||
clear_color,
|
||||
clear_depth,
|
||||
draws,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every case, each exercising one feature, in fixture order.
|
||||
pub fn cases() -> Vec<Case> {
|
||||
use CompareFunction::{Always, Less, LessEqual};
|
||||
let red = Fill::Flat(RED);
|
||||
let green = Fill::Flat(GREEN);
|
||||
let blue = Fill::Flat(BLUE);
|
||||
let mut cases = vec![case("clear", [16, 32, 48, 255], Some(0.375), Vec::new())];
|
||||
for compare in CompareFunction::ALL {
|
||||
for z in [0.25, 0.5, 0.75] {
|
||||
cases.push(case(
|
||||
&format!("compare_{compare:?}_{z}"),
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(A, 0.5, red, Always, true),
|
||||
draw(B, z, green, compare, true),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
for (name, write) in [("write_disabled", false), ("write_enabled", true)] {
|
||||
cases.push(case(
|
||||
name,
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(A, 0.5, red, Always, true),
|
||||
draw(B, 0.25, green, Always, write),
|
||||
draw(C, 0.75, blue, LessEqual, true),
|
||||
],
|
||||
));
|
||||
}
|
||||
let painter = |depth| {
|
||||
case(
|
||||
if depth {
|
||||
"disabled_attachment"
|
||||
} else {
|
||||
"no_attachment"
|
||||
},
|
||||
BLACK,
|
||||
depth.then_some(1.0),
|
||||
vec![
|
||||
draw(A, 0.25, red, Always, false),
|
||||
draw(B, 0.75, green, Always, false),
|
||||
],
|
||||
)
|
||||
};
|
||||
cases.push(painter(true));
|
||||
cases.push(painter(false));
|
||||
cases.push(case(
|
||||
"textured",
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(FULL, 0.5, Fill::Texture, Less, true),
|
||||
draw(B, 0.75, green, Less, true),
|
||||
draw(A, 0.25, red, Less, true),
|
||||
],
|
||||
));
|
||||
cases
|
||||
}
|
||||
|
||||
/// Independently derived colour and depth of one case.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Expected {
|
||||
pub name: String,
|
||||
pub color: Vec<[u8; 4]>,
|
||||
pub depth: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
pub fn expected() -> Vec<Expected> {
|
||||
let text = include_str!("../fixtures/depth_expected.txt");
|
||||
let mut out = Vec::new();
|
||||
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
|
||||
while let Some(header) = lines.next() {
|
||||
let name = header.strip_prefix("case ").expect("case line").to_owned();
|
||||
let (mut palette, mut depthkey) = (Vec::new(), Vec::new());
|
||||
let (mut color, mut depth, mut no_depth) = (Vec::new(), Vec::new(), false);
|
||||
for line in lines.by_ref() {
|
||||
let mut words = line.split_whitespace();
|
||||
match words.next().expect("keyword") {
|
||||
"palette" => {
|
||||
let key = words.next().unwrap().chars().next().unwrap();
|
||||
let rgba: Vec<u8> = words.map(|w| w.parse().unwrap()).collect();
|
||||
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
|
||||
}
|
||||
"depthkey" => {
|
||||
let key = words.next().unwrap().chars().next().unwrap();
|
||||
depthkey.push((key, words.next().unwrap().parse::<f32>().unwrap()));
|
||||
}
|
||||
"color" => color.extend(words.next().unwrap().chars().map(|c| {
|
||||
palette
|
||||
.iter()
|
||||
.find(|(k, _)| *k == c)
|
||||
.expect("palette key")
|
||||
.1
|
||||
})),
|
||||
"depth" => match words.next().unwrap() {
|
||||
"none" => no_depth = true,
|
||||
row => depth.extend(
|
||||
row.chars()
|
||||
.map(|c| depthkey.iter().find(|(k, _)| *k == c).expect("depth key").1),
|
||||
),
|
||||
},
|
||||
"end" => break,
|
||||
other => panic!("unexpected fixture line {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
|
||||
assert!(no_depth || depth.len() == SIZE * SIZE, "{name} depth rows");
|
||||
out.push(Expected {
|
||||
name,
|
||||
color,
|
||||
depth: (!no_depth).then_some(depth),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU reference for depth-tested offscreen triangle rendering.
|
||||
//!
|
||||
//! A pixel is covered when its centre lies strictly inside a triangle. Inputs
|
||||
//! whose pixel centres lie exactly on an edge are rejected rather than resolved
|
||||
//! by a fill rule, so the reference never depends on rasteriser tie-breaking.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Depth comparison of the fragment depth against the stored depth.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareFunction {
|
||||
Never,
|
||||
Less,
|
||||
Equal,
|
||||
LessEqual,
|
||||
Greater,
|
||||
NotEqual,
|
||||
GreaterEqual,
|
||||
Always,
|
||||
}
|
||||
|
||||
impl CompareFunction {
|
||||
pub const ALL: [Self; 8] = [
|
||||
Self::Never,
|
||||
Self::Less,
|
||||
Self::Equal,
|
||||
Self::LessEqual,
|
||||
Self::Greater,
|
||||
Self::NotEqual,
|
||||
Self::GreaterEqual,
|
||||
Self::Always,
|
||||
];
|
||||
|
||||
#[must_use]
|
||||
pub fn passes(self, fragment: f32, stored: f32) -> bool {
|
||||
match self {
|
||||
Self::Never => false,
|
||||
Self::Less => fragment < stored,
|
||||
Self::Equal => fragment == stored,
|
||||
Self::LessEqual => fragment <= stored,
|
||||
Self::Greater => fragment > stored,
|
||||
Self::NotEqual => fragment != stored,
|
||||
Self::GreaterEqual => fragment >= stored,
|
||||
Self::Always => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour source of one reference draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum RefFill {
|
||||
Flat([u8; 4]),
|
||||
/// Nearest texel of the pass texture at the pixel centre.
|
||||
Texture,
|
||||
}
|
||||
|
||||
/// One triangle with clip-space positions (`w` must be 1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefDraw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: RefFill,
|
||||
pub compare: CompareFunction,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
/// Decoded RGBA8 texels in row-major order.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RefTexture<'a> {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub texels: &'a [[u8; 4]],
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum DepthRefError {
|
||||
Extent,
|
||||
NonUnitW,
|
||||
/// A position is non-finite or its depth lies outside 0..=1: (draw).
|
||||
Unclipped(usize),
|
||||
/// A pixel centre lies on a triangle edge: (draw, x, y).
|
||||
EdgeTie(usize, usize, usize),
|
||||
MissingTexture,
|
||||
/// Without a depth attachment every draw must be `Always` without writes.
|
||||
DepthStateWithoutAttachment(usize),
|
||||
}
|
||||
|
||||
impl fmt::Display for DepthRefError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DepthRefError {}
|
||||
|
||||
/// Colour (row-major, top row first) and, with an attachment, stored depth.
|
||||
pub type DepthRefOutput = (Vec<[u8; 4]>, Option<Vec<f32>>);
|
||||
|
||||
/// Render `draws` in order over a cleared target with viewport depth range 0..1.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an empty extent, non-unit `w`, a non-finite position
|
||||
/// or depth outside 0..=1, a pixel centre on an edge, a textured draw without texture, or a depth state without attachment.
|
||||
pub fn render_depth(
|
||||
[width, height]: [usize; 2],
|
||||
clear_color: [u8; 4],
|
||||
clear_depth: Option<f32>,
|
||||
draws: &[RefDraw],
|
||||
texture: Option<RefTexture<'_>>,
|
||||
) -> Result<DepthRefOutput, DepthRefError> {
|
||||
let pixels = width.checked_mul(height).filter(|&n| n > 0);
|
||||
let pixels = pixels.ok_or(DepthRefError::Extent)?;
|
||||
if let Some(texture) = texture
|
||||
&& texture.width.checked_mul(texture.height).filter(|&n| n > 0)
|
||||
!= Some(texture.texels.len())
|
||||
{
|
||||
return Err(DepthRefError::Extent);
|
||||
}
|
||||
let mut color = vec![clear_color; pixels];
|
||||
let mut depth = clear_depth.map(|value| vec![value; pixels]);
|
||||
for (index, draw) in draws.iter().enumerate() {
|
||||
if depth.is_none() && (draw.compare != CompareFunction::Always || draw.write) {
|
||||
return Err(DepthRefError::DepthStateWithoutAttachment(index));
|
||||
}
|
||||
if draw.fill == RefFill::Texture && texture.is_none() {
|
||||
return Err(DepthRefError::MissingTexture);
|
||||
}
|
||||
if draw.positions.iter().any(|p| p[3] != 1.0) {
|
||||
return Err(DepthRefError::NonUnitW);
|
||||
}
|
||||
// The reference does not clip, so depth must already lie in the
|
||||
// viewport range 0..=1 (this also rejects non-finite depth).
|
||||
if draw
|
||||
.positions
|
||||
.iter()
|
||||
.any(|p| !p.iter().all(|v| v.is_finite()) || !(0.0..=1.0).contains(&p[2]))
|
||||
{
|
||||
return Err(DepthRefError::Unclipped(index));
|
||||
}
|
||||
// Viewport transform: NDC x, y in -1..1 map to pixels, y down.
|
||||
let screen = draw.positions.map(|[x, y, z, _]| {
|
||||
[
|
||||
(f64::from(x) + 1.0) * 0.5 * width as f64,
|
||||
(1.0 - f64::from(y)) * 0.5 * height as f64,
|
||||
f64::from(z),
|
||||
]
|
||||
});
|
||||
let area = edge(screen[0], screen[1], screen[2]);
|
||||
if area == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let centre = [x as f64 + 0.5, y as f64 + 0.5, 0.0];
|
||||
let weights = [
|
||||
edge(screen[1], screen[2], centre),
|
||||
edge(screen[2], screen[0], centre),
|
||||
edge(screen[0], screen[1], centre),
|
||||
];
|
||||
if weights.contains(&0.0) {
|
||||
let others_inside = weights
|
||||
.iter()
|
||||
.filter(|&&w| w != 0.0)
|
||||
.all(|&w| (w > 0.0) == (area > 0.0));
|
||||
if others_inside {
|
||||
return Err(DepthRefError::EdgeTie(index, x, y));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !weights.iter().all(|&w| (w > 0.0) == (area > 0.0)) {
|
||||
continue;
|
||||
}
|
||||
let z = (weights[0] * screen[0][2]
|
||||
+ weights[1] * screen[1][2]
|
||||
+ weights[2] * screen[2][2])
|
||||
/ area;
|
||||
let z = z as f32;
|
||||
let slot = y * width + x;
|
||||
if let Some(stored) = depth.as_mut() {
|
||||
if !draw.compare.passes(z, stored[slot]) {
|
||||
continue;
|
||||
}
|
||||
if draw.write {
|
||||
stored[slot] = z;
|
||||
}
|
||||
}
|
||||
color[slot] = match (draw.fill, texture) {
|
||||
(RefFill::Flat(rgba), _) => rgba,
|
||||
(RefFill::Texture, Some(t)) => {
|
||||
let u = ((x as f64 + 0.5) / width as f64 * t.width as f64) as usize;
|
||||
let v = ((y as f64 + 0.5) / height as f64 * t.height as f64) as usize;
|
||||
t.texels[v.min(t.height - 1) * t.width + u.min(t.width - 1)]
|
||||
}
|
||||
(RefFill::Texture, None) => return Err(DepthRefError::MissingTexture),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((color, depth))
|
||||
}
|
||||
|
||||
fn edge(a: [f64; 3], b: [f64; 3], p: [f64; 3]) -> f64 {
|
||||
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
fn draw(positions: [[f32; 4]; 3], compare: CompareFunction, write: bool) -> RefDraw {
|
||||
RefDraw {
|
||||
positions,
|
||||
fill: RefFill::Flat(RED),
|
||||
compare,
|
||||
write,
|
||||
}
|
||||
}
|
||||
|
||||
// A 2x2 target; this triangle covers only the centre of pixel (0, 1).
|
||||
const LOWER_LEFT: [[f32; 4]; 3] = [
|
||||
[-1.0, -1.0, 0.25, 1.0],
|
||||
[0.5, -1.0, 0.25, 1.0],
|
||||
[-1.0, 0.5, 0.25, 1.0],
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn covers_by_pixel_centre_and_writes_depth() {
|
||||
let (color, depth) = render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
Some(1.0),
|
||||
&[draw(LOWER_LEFT, CompareFunction::Less, true)],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(color, [[0; 4], [0; 4], RED, [0; 4]]);
|
||||
assert_eq!(depth.unwrap(), [1.0, 1.0, 0.25, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_functions_follow_metal_semantics() {
|
||||
let expect = [false, true, false, true, false, true, false, true];
|
||||
let equal = [false, false, true, true, false, false, true, true];
|
||||
for (function, (&less, &eq)) in CompareFunction::ALL.iter().zip(expect.iter().zip(&equal)) {
|
||||
assert_eq!(function.passes(0.25, 0.5), less, "{function:?} less");
|
||||
assert_eq!(function.passes(0.5, 0.5), eq, "{function:?} equal");
|
||||
assert_eq!(
|
||||
function.passes(0.75, 0.5),
|
||||
!matches!(
|
||||
function,
|
||||
CompareFunction::Never
|
||||
| CompareFunction::Less
|
||||
| CompareFunction::Equal
|
||||
| CompareFunction::LessEqual
|
||||
),
|
||||
"{function:?} greater"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_edge_ties_and_depth_without_attachment() {
|
||||
let tie = [
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[1.0, 1.0, 0.5, 1.0],
|
||||
[-1.0, 1.0, 0.5, 1.0],
|
||||
];
|
||||
assert!(matches!(
|
||||
render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
Some(1.0),
|
||||
&[draw(tie, CompareFunction::Always, true)],
|
||||
None
|
||||
),
|
||||
Err(DepthRefError::EdgeTie(0, _, _))
|
||||
));
|
||||
let mut far = LOWER_LEFT;
|
||||
far[0][2] = 1.25;
|
||||
assert_eq!(
|
||||
render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
Some(1.0),
|
||||
&[draw(far, CompareFunction::Always, true)],
|
||||
None
|
||||
),
|
||||
Err(DepthRefError::Unclipped(0))
|
||||
);
|
||||
assert_eq!(
|
||||
render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
None,
|
||||
&[draw(LOWER_LEFT, CompareFunction::Less, false)],
|
||||
None
|
||||
),
|
||||
Err(DepthRefError::DepthStateWithoutAttachment(0))
|
||||
);
|
||||
}
|
||||
}
|
||||
+296
-59
@@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset and reference sampling.
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling and depth-tested rendering.
|
||||
|
||||
pub mod depth;
|
||||
pub mod texture_sampling;
|
||||
|
||||
use std::fmt;
|
||||
@@ -48,8 +49,10 @@ pub enum Op {
|
||||
Move(u8, Source),
|
||||
Add(u8, u8, u8),
|
||||
ScalarMove(u8, Source),
|
||||
/// VOP1 move of a normal SGPR into a VGPR.
|
||||
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// SOP2 operation writing an SGPR and SCC.
|
||||
Scalar(ScalarAlu, u8, Source, Source),
|
||||
CompareEqual(Source, Source),
|
||||
@@ -61,6 +64,52 @@ pub enum Op {
|
||||
End,
|
||||
}
|
||||
|
||||
/// Relation and operand interpretation of a VOPC integer compare.
|
||||
///
|
||||
/// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset
|
||||
/// for signed and 192 + offset for unsigned 32-bit operands, with offsets
|
||||
/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Comparison {
|
||||
/// Opcode offset 1-6 within the 32-bit integer group.
|
||||
pub offset: u8,
|
||||
/// Whether the operands are two's-complement integers.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
impl Comparison {
|
||||
/// The per-lane result, from an exact comparison of the widened operands.
|
||||
fn holds(self, s0: u32, s1: u32) -> bool {
|
||||
let widen = |bits: u32| {
|
||||
if self.signed {
|
||||
i64::from(bits as i32)
|
||||
} else {
|
||||
i64::from(bits)
|
||||
}
|
||||
};
|
||||
let (s0, s1) = (widen(s0), widen(s1));
|
||||
match self.offset {
|
||||
1 => s0 < s1,
|
||||
2 => s0 == s1,
|
||||
3 => s0 <= s1,
|
||||
4 => s0 > s1,
|
||||
5 => s0 != s1,
|
||||
_ => s0 >= s1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// First source of a VOPC compare.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareSource {
|
||||
/// VGPR index.
|
||||
Vector(u8),
|
||||
/// SGPR index s0-s105, or 106 for `vcc_lo`.
|
||||
Scalar(u8),
|
||||
/// Inline integer or literal bits.
|
||||
Immediate(u32),
|
||||
}
|
||||
|
||||
/// Scalar condition tested by a forward branch.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum BranchCondition {
|
||||
@@ -151,11 +200,13 @@ pub fn execute(code: &[u8], input: &[u32]) -> Result<Vec<u32>, ReferenceError> {
|
||||
{
|
||||
return Err(error(code.len(), "missing s_endpgm"));
|
||||
}
|
||||
input
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, &word)| execute_lane(&program, word, index % 32))
|
||||
.collect()
|
||||
// Waves are consecutive groups of 32 dispatch indices; a final partial
|
||||
// wave has absent lanes, which contribute 0 to compare masks.
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for wave in input.chunks(32) {
|
||||
output.extend(execute_wave(&program, wave)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn error(offset: usize, detail: &'static str) -> ReferenceError {
|
||||
@@ -298,13 +349,45 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let src1 = (middle >> 1) | ((hi & 1) << 7);
|
||||
(Op::Add(*dst, *lo, src1), 8)
|
||||
}
|
||||
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
|
||||
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
|
||||
if matches!(
|
||||
(u16::from(*tag & 1) << 7) | u16::from(*upper >> 1),
|
||||
129..=134 | 193..=198
|
||||
) =>
|
||||
{
|
||||
let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1);
|
||||
let comparison = Comparison {
|
||||
offset: (opcode & 0x3f) as u8,
|
||||
signed: opcode < 192,
|
||||
};
|
||||
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
|
||||
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
|
||||
let (src0, length) = match selector {
|
||||
0..=106 => (CompareSource::Scalar(*lo), 4),
|
||||
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
|
||||
193..=208 => (
|
||||
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
|
||||
4,
|
||||
),
|
||||
255 => {
|
||||
let literal = tail
|
||||
.first_chunk::<4>()
|
||||
.ok_or_else(|| error(offset, "truncated literal"))?;
|
||||
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
|
||||
}
|
||||
256..=511 => (CompareSource::Vector(*lo), 4),
|
||||
_ => return Err(error(offset, "unsupported VOPC source")),
|
||||
};
|
||||
(Op::Compare(comparison, src0, vsrc1), length)
|
||||
}
|
||||
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
|
||||
if packed & 0xfe == 2 && upper & 1 == 0 =>
|
||||
{
|
||||
let dst = (upper >> 1) | ((tag & 1) << 7);
|
||||
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
|
||||
if selector <= 105 {
|
||||
// VOP1 SRC0 0-105 selects a normal SGPR.
|
||||
if selector <= 106 {
|
||||
// VOP1 SRC0 0-105 selects a normal SGPR, 106 vcc_lo.
|
||||
program.push(DecodedInstruction {
|
||||
offset,
|
||||
byte_len: 4,
|
||||
@@ -427,21 +510,26 @@ fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, Refer
|
||||
Ok(result.to_bits())
|
||||
}
|
||||
|
||||
fn execute_lane(
|
||||
program: &[DecodedInstruction],
|
||||
input: u32,
|
||||
lane: usize,
|
||||
) -> Result<u32, ReferenceError> {
|
||||
let mut registers = [None; 256];
|
||||
const VCC_LO: usize = 106;
|
||||
const VCC_HI: usize = 107;
|
||||
const EXEC_LO: usize = 126;
|
||||
|
||||
/// Runs one Wave32 wave in lockstep. Scalar state is shared by the lanes;
|
||||
/// VGPRs, transfers and outputs are per lane.
|
||||
fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32>, ReferenceError> {
|
||||
let lanes = input.len();
|
||||
let mut registers = vec![[None::<u32>; 256]; lanes];
|
||||
let mut scalars = [None; 128];
|
||||
let mut exec = u32::MAX;
|
||||
scalars[126] = Some(exec);
|
||||
scalars[EXEC_LO] = Some(exec);
|
||||
let mut scc = None;
|
||||
// Whether VCC_LO was last written by a compare with nonzero EXEC.
|
||||
let mut lane_derived_vcc = false;
|
||||
let mut target = 0;
|
||||
let mut pending_read = None;
|
||||
let mut pending_write = None;
|
||||
let mut output = None;
|
||||
for &DecodedInstruction { offset, op, .. } in program {
|
||||
let mut pending_write = vec![None; lanes];
|
||||
let mut output = vec![None; lanes];
|
||||
for (position, &DecodedInstruction { offset, op, .. }) in program.iter().enumerate() {
|
||||
if offset < target {
|
||||
continue;
|
||||
}
|
||||
@@ -450,23 +538,29 @@ fn execute_lane(
|
||||
.ok_or_else(|| error(offset, "read from uninitialized SGPR")),
|
||||
Source::Immediate(value) => Ok(value),
|
||||
};
|
||||
let read = |register: u8| {
|
||||
let read = |lane: usize, register: u8| {
|
||||
if register == 0 {
|
||||
return Err(error(offset, "v0 is reserved for the resource index"));
|
||||
}
|
||||
if pending_read == Some(register) {
|
||||
return Err(error(offset, "VGPR read before load wait"));
|
||||
}
|
||||
registers[usize::from(register)]
|
||||
registers[lane][usize::from(register)]
|
||||
.ok_or_else(|| error(offset, "read from uninitialized VGPR"))
|
||||
};
|
||||
// Lanes that execute a vector ALU instruction under the current EXEC.
|
||||
let executes = |lane: usize| exec & (1 << lane) != 0;
|
||||
if exec != u32::MAX {
|
||||
match op {
|
||||
Op::Move(dst, _)
|
||||
| Op::MoveScalar(dst, _)
|
||||
| Op::Add(dst, ..)
|
||||
| Op::Vector(_, dst, ..) => {
|
||||
if exec != 0 && registers[usize::from(dst)].is_none() {
|
||||
if exec != 0
|
||||
&& registers
|
||||
.iter()
|
||||
.any(|lane| lane[usize::from(dst)].is_none())
|
||||
{
|
||||
return Err(error(offset, "partial EXEC requires an initialized VGPR"));
|
||||
}
|
||||
// As in translation, an SGPR source must be known even for an inactive lane.
|
||||
@@ -475,9 +569,6 @@ fn execute_lane(
|
||||
{
|
||||
read_scalar(Source::Register(src))?;
|
||||
}
|
||||
if exec & (1 << lane) == 0 {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Op::Load { .. } | Op::Store { .. } => {
|
||||
return Err(error(offset, "vector memory requires full Wave32 EXEC"));
|
||||
@@ -485,7 +576,9 @@ fn execute_lane(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let set = match op {
|
||||
// Per-lane results of a vector ALU instruction, applied after all lanes read.
|
||||
let mut results: Vec<Option<(u8, u32)>> = vec![None; lanes];
|
||||
match op {
|
||||
Op::Load { data: dst, .. } => {
|
||||
if dst == 0 || pending_read.is_some() {
|
||||
return Err(error(
|
||||
@@ -494,42 +587,72 @@ fn execute_lane(
|
||||
));
|
||||
}
|
||||
pending_read = Some(dst);
|
||||
None
|
||||
}
|
||||
Op::Store { data: src, .. } => {
|
||||
let value = read(src)?;
|
||||
if pending_write.is_some() || output.is_some() {
|
||||
return Err(error(offset, "multiple writes to the output"));
|
||||
for lane in 0..lanes {
|
||||
let value = read(lane, src)?;
|
||||
if pending_write[lane].is_some() || output[lane].is_some() {
|
||||
return Err(error(offset, "multiple writes to the output"));
|
||||
}
|
||||
pending_write[lane] = Some(value);
|
||||
}
|
||||
}
|
||||
Op::WaitRead => {
|
||||
if let Some(dst) = pending_read.take() {
|
||||
for (lane, &word) in input.iter().enumerate() {
|
||||
results[lane] = Some((dst, word));
|
||||
}
|
||||
}
|
||||
pending_write = Some(value);
|
||||
None
|
||||
}
|
||||
Op::WaitRead => pending_read.take().map(|dst| (dst, input)),
|
||||
Op::WaitWrite => {
|
||||
if let Some(value) = pending_write.take() {
|
||||
output = Some(value);
|
||||
for lane in 0..lanes {
|
||||
if let Some(value) = pending_write[lane].take() {
|
||||
output[lane] = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Move(dst, source) => {
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let value = match source {
|
||||
Source::Register(src) => read(lane, src)?,
|
||||
Source::Immediate(value) => value,
|
||||
};
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
}
|
||||
Op::Add(dst, lhs, rhs) => {
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let value = read(lane, lhs)?.wrapping_add(read(lane, rhs)?);
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
}
|
||||
Op::MoveScalar(dst, src) => {
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
results[lane] = Some((dst, read_scalar(Source::Register(src))?));
|
||||
}
|
||||
}
|
||||
Op::Vector(operator, dst, lhs, rhs) => {
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let value = vector_alu(operator, read(lane, lhs)?, read(lane, rhs)?, offset)?;
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
None
|
||||
}
|
||||
Op::Move(dst, Source::Register(src)) => Some((dst, read(src)?)),
|
||||
Op::Move(dst, Source::Immediate(value)) => Some((dst, value)),
|
||||
Op::Add(dst, lhs, rhs) => Some((dst, read(lhs)?.wrapping_add(read(rhs)?))),
|
||||
Op::ScalarMove(dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = read_scalar(src)?;
|
||||
if dst == 126 {
|
||||
if usize::from(dst) == EXEC_LO {
|
||||
exec = value;
|
||||
}
|
||||
if usize::from(dst) == VCC_LO {
|
||||
lane_derived_vcc = false;
|
||||
}
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
None
|
||||
}
|
||||
Op::CompareEqual(lhs, rhs) => {
|
||||
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
|
||||
None
|
||||
}
|
||||
Op::MoveScalar(dst, src) => Some((dst, read_scalar(Source::Register(src))?)),
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -573,48 +696,162 @@ fn execute_lane(
|
||||
let value = exact.rem_euclid(1 << 32) as u32;
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
scc = Some(flag);
|
||||
None
|
||||
}
|
||||
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
|
||||
Op::Compare(comparison, src0, src1) => {
|
||||
let mut mask = 0u32;
|
||||
if exec != 0 {
|
||||
// Sources are checked once for the wave, even if no present lane is active.
|
||||
let check = |register: u8| {
|
||||
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
|
||||
};
|
||||
match src0 {
|
||||
CompareSource::Vector(register) => check(register)?,
|
||||
CompareSource::Scalar(register) => {
|
||||
read_scalar(Source::Register(register))?;
|
||||
}
|
||||
CompareSource::Immediate(_) => {}
|
||||
}
|
||||
check(src1)?;
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let s0 = match src0 {
|
||||
CompareSource::Vector(register) => read(lane, register)?,
|
||||
CompareSource::Scalar(register) => {
|
||||
read_scalar(Source::Register(register))?
|
||||
}
|
||||
CompareSource::Immediate(bits) => bits,
|
||||
};
|
||||
if comparison.holds(s0, read(lane, src1)?) {
|
||||
mask |= 1 << lane;
|
||||
}
|
||||
}
|
||||
}
|
||||
scalars[VCC_LO] = Some(mask);
|
||||
scalars[VCC_HI] = None;
|
||||
lane_derived_vcc = exec != 0;
|
||||
}
|
||||
Op::Branch {
|
||||
target: destination,
|
||||
condition,
|
||||
} => {
|
||||
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
|
||||
return Err(error(offset, "branch with uninitialized VCC_LO"));
|
||||
}
|
||||
if condition == BranchCondition::VccZero && lane_derived_vcc {
|
||||
check_runtime_region(
|
||||
&program[position + 1..],
|
||||
destination,
|
||||
®isters,
|
||||
&scalars,
|
||||
exec,
|
||||
pending_read.is_some(),
|
||||
offset,
|
||||
)?;
|
||||
}
|
||||
let take_branch = match condition {
|
||||
BranchCondition::Always => true,
|
||||
BranchCondition::SccZero => {
|
||||
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
|
||||
}
|
||||
BranchCondition::VccZero => scalars[106] == Some(0),
|
||||
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
|
||||
BranchCondition::ExecZero => exec == 0,
|
||||
};
|
||||
if condition == BranchCondition::VccZero && scalars[106].is_none() {
|
||||
return Err(error(offset, "branch with uninitialized VCC_LO"));
|
||||
}
|
||||
if take_branch {
|
||||
target = destination;
|
||||
}
|
||||
None
|
||||
}
|
||||
Op::Vector(operator, dst, lhs, rhs) => {
|
||||
Some((dst, vector_alu(operator, read(lhs)?, read(rhs)?, offset)?))
|
||||
}
|
||||
Op::End => {
|
||||
if pending_read.is_some() || pending_write.is_some() {
|
||||
if pending_read.is_some() || pending_write.iter().any(Option::is_some) {
|
||||
return Err(error(offset, "outstanding transfer at termination"));
|
||||
}
|
||||
return output.ok_or_else(|| error(offset, "lane did not write its output"));
|
||||
return output
|
||||
.iter()
|
||||
.map(|value| {
|
||||
value.ok_or_else(|| error(offset, "lane did not write its output"))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
};
|
||||
if let Some((dst, value)) = set {
|
||||
if dst == 0 || pending_read == Some(dst) {
|
||||
return Err(error(offset, "write to immutable or pending VGPR"));
|
||||
}
|
||||
for (lane, result) in results.into_iter().enumerate() {
|
||||
if let Some((dst, value)) = result {
|
||||
if dst == 0 || pending_read == Some(dst) {
|
||||
return Err(error(offset, "write to immutable or pending VGPR"));
|
||||
}
|
||||
registers[lane][usize::from(dst)] = Some(value);
|
||||
}
|
||||
registers[usize::from(dst)] = Some(value);
|
||||
}
|
||||
}
|
||||
Err(error(0, "missing decoded termination"))
|
||||
}
|
||||
|
||||
/// docs/shaders/vector-compare.md section 6: code skipped by `s_cbranch_vccz`
|
||||
/// on a lane-derived VCC_LO may hold only integer vector ALU instructions
|
||||
/// whose destinations and sources are ready at the branch. Checked on the
|
||||
/// code itself, whether or not the branch is taken.
|
||||
fn check_runtime_region(
|
||||
following: &[DecodedInstruction],
|
||||
end: usize,
|
||||
registers: &[[Option<u32>; 256]],
|
||||
scalars: &[Option<u32>; 128],
|
||||
exec: u32,
|
||||
load_pending: bool,
|
||||
branch: usize,
|
||||
) -> Result<(), ReferenceError> {
|
||||
if load_pending {
|
||||
return Err(error(branch, "runtime VCC branch with an outstanding load"));
|
||||
}
|
||||
let ready = |register: u8| {
|
||||
register != 0
|
||||
&& registers
|
||||
.iter()
|
||||
.all(|lane| lane[usize::from(register)].is_some())
|
||||
};
|
||||
for instruction in following.iter().take_while(|item| item.offset < end) {
|
||||
let offset = instruction.offset;
|
||||
let (dst, vector_sources, scalar_source) = match instruction.op {
|
||||
Op::Move(dst, Source::Register(src)) => (dst, vec![src], None),
|
||||
Op::Move(dst, Source::Immediate(_)) => (dst, vec![], None),
|
||||
Op::MoveScalar(dst, src) => (dst, vec![], Some(src)),
|
||||
Op::Add(dst, lhs, rhs) => (dst, vec![lhs, rhs], None),
|
||||
Op::Vector(kind, dst, lhs, rhs)
|
||||
if !matches!(kind, VectorAlu::FloatAdd | VectorAlu::FloatMultiply) =>
|
||||
{
|
||||
(dst, vec![lhs, rhs], None)
|
||||
}
|
||||
_ => {
|
||||
return Err(error(
|
||||
offset,
|
||||
"runtime VCC branch skips a non-integer-vector instruction",
|
||||
));
|
||||
}
|
||||
};
|
||||
if !ready(dst) {
|
||||
return Err(error(
|
||||
offset,
|
||||
"runtime VCC branch skips a write to an uninitialized VGPR",
|
||||
));
|
||||
}
|
||||
if exec == 0 {
|
||||
continue;
|
||||
}
|
||||
if vector_sources.into_iter().any(|register| !ready(register)) {
|
||||
return Err(error(
|
||||
offset,
|
||||
"runtime VCC branch skips an unready VGPR read",
|
||||
));
|
||||
}
|
||||
if let Some(register) = scalar_source
|
||||
&& scalars[usize::from(register)].is_none()
|
||||
{
|
||||
return Err(error(
|
||||
offset,
|
||||
"runtime VCC branch skips an unknown SGPR read",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+373
-26
@@ -8,7 +8,14 @@ mod graphics;
|
||||
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::{DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorSource};
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorCompareOp, VectorSource,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`.
|
||||
const VCC_LO: usize = 106;
|
||||
/// SGPR index of `vcc_hi`.
|
||||
const VCC_HI: usize = 107;
|
||||
|
||||
/// Entry point of all kernels produced by this compiler.
|
||||
pub const ENTRY_POINT: &str = "xenora_compute";
|
||||
@@ -94,6 +101,111 @@ enum Op {
|
||||
target: usize,
|
||||
taken: bool,
|
||||
},
|
||||
/// Wave32 VOPC result: bit n is EXEC[n] & (lane n exists) & test(lane n).
|
||||
/// The value is wave-uniform; every thread computes it for its own wave.
|
||||
LaneMask {
|
||||
op: VectorCompareOp,
|
||||
src0: Value,
|
||||
src1: Value,
|
||||
exec: u32,
|
||||
},
|
||||
/// `s_cbranch_vccz` on a lane-derived VCC_LO (IR annotation only).
|
||||
RuntimeBranch {
|
||||
mask: Value,
|
||||
target: usize,
|
||||
},
|
||||
/// Join after a runtime `s_cbranch_vccz`: the fall-through value when the
|
||||
/// mask is nonzero (branch not taken), else the value from before the branch.
|
||||
JoinVccz {
|
||||
mask: Value,
|
||||
fallthrough: Value,
|
||||
taken: Value,
|
||||
},
|
||||
}
|
||||
|
||||
impl Op {
|
||||
fn operands(self) -> Vec<Value> {
|
||||
match self {
|
||||
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
|
||||
Self::Binary(_, left, right) => vec![left, right],
|
||||
Self::MergeLanes {
|
||||
active, inactive, ..
|
||||
} => vec![active, inactive],
|
||||
Self::Store(value) => vec![value],
|
||||
Self::LaneMask { src0, src1, .. } => vec![src0, src1],
|
||||
Self::RuntimeBranch { mask, .. } => vec![mask],
|
||||
Self::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
taken,
|
||||
} => vec![mask, fallthrough, taken],
|
||||
}
|
||||
}
|
||||
|
||||
/// The MSL expression of a per-thread value, with operand names, the
|
||||
/// dispatch index and the lane given by the caller.
|
||||
fn expression(self, name: &dyn Fn(Value) -> String, index: &str, lane: &str) -> String {
|
||||
match self {
|
||||
Self::Load => format!("input[{index}]"),
|
||||
Self::Constant(value) => format!("0x{value:08x}u"),
|
||||
Self::Binary(operator, left, right) => {
|
||||
let (left, right) = (name(left), name(right));
|
||||
let (_, symbol) = operator.operator();
|
||||
match operator {
|
||||
Binary::FloatAdd | Binary::FloatMul => format!(
|
||||
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
|
||||
),
|
||||
Binary::ArithmeticShiftRight => {
|
||||
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
|
||||
}
|
||||
Binary::ShiftLeft | Binary::ShiftRight => {
|
||||
format!("{left} {symbol} ({right} & 31u)")
|
||||
}
|
||||
_ => format!("{left} {symbol} {right}"),
|
||||
}
|
||||
}
|
||||
Self::MergeLanes {
|
||||
mask,
|
||||
active,
|
||||
inactive,
|
||||
} => format!(
|
||||
"((0x{mask:08x}u >> {lane}) & 1u) != 0u ? {} : {}",
|
||||
name(active),
|
||||
name(inactive)
|
||||
),
|
||||
Self::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
taken,
|
||||
} => format!(
|
||||
"{} != 0u ? {} : {}",
|
||||
name(mask),
|
||||
name(fallthrough),
|
||||
name(taken)
|
||||
),
|
||||
Self::Store(_)
|
||||
| Self::ScalarBranch { .. }
|
||||
| Self::LaneMask { .. }
|
||||
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
|
||||
use xenora_decoder::CompareRelation;
|
||||
let symbol = match op.relation {
|
||||
CompareRelation::Less => "<",
|
||||
CompareRelation::Equal => "==",
|
||||
CompareRelation::LessOrEqual => "<=",
|
||||
CompareRelation::Greater => ">",
|
||||
CompareRelation::NotEqual => "!=",
|
||||
CompareRelation::GreaterOrEqual => ">=",
|
||||
};
|
||||
if op.signed {
|
||||
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
|
||||
} else {
|
||||
format!("{left} {symbol} {right}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -239,8 +351,16 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
|
||||
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
|
||||
let mut ir = String::new();
|
||||
let has_mask = operations
|
||||
.iter()
|
||||
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
|
||||
let grid = if has_mask {
|
||||
",\n uint grid [[threads_per_grid]]"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut msl = format!(
|
||||
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]) {{\n"
|
||||
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]{grid}) {{\n"
|
||||
);
|
||||
if operations.iter().any(|(_, operation)| {
|
||||
matches!(
|
||||
@@ -250,36 +370,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
}) {
|
||||
msl.push_str(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)\n");
|
||||
}
|
||||
for (index, (offset, operation)) in operations.into_iter().enumerate() {
|
||||
// Wave-uniform values: identical in every lane of an RDNA wave.
|
||||
let mut uniform = Vec::with_capacity(operations.len());
|
||||
for (index, &(offset, operation)) in operations.iter().enumerate() {
|
||||
let dest = Value(index);
|
||||
uniform.push(match operation {
|
||||
Op::Constant(_) | Op::LaneMask { .. } => true,
|
||||
Op::Load | Op::MergeLanes { .. } => false,
|
||||
_ => operation.operands().iter().all(|value| uniform[value.0]),
|
||||
});
|
||||
let thread = |value: Value| value.to_string();
|
||||
let (step, statement) = match operation {
|
||||
Op::Load => (
|
||||
format!("{dest} = load.u32 input[index]"),
|
||||
format!("uint {dest} = input[index];"),
|
||||
format!(
|
||||
"uint {dest} = {};",
|
||||
operation.expression(&thread, "index", "")
|
||||
),
|
||||
),
|
||||
Op::Constant(value) => (
|
||||
format!("{dest} = const.u32 0x{value:08x}"),
|
||||
format!("uint {dest} = 0x{value:08x}u;"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::Binary(operator, left, right) => (
|
||||
format!("{dest} = {} {left}, {right}", operator.operator().0),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::Binary(operator, left, right) => {
|
||||
let (mnemonic, symbol) = operator.operator();
|
||||
let expression = match operator {
|
||||
Binary::FloatAdd | Binary::FloatMul => format!(
|
||||
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
|
||||
),
|
||||
Binary::ArithmeticShiftRight => {
|
||||
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
|
||||
}
|
||||
Binary::ShiftLeft | Binary::ShiftRight => {
|
||||
format!("{left} {symbol} ({right} & 31u)")
|
||||
}
|
||||
_ => format!("{left} {symbol} {right}"),
|
||||
};
|
||||
(
|
||||
format!("{dest} = {mnemonic} {left}, {right}"),
|
||||
format!("uint {dest} = {expression};"),
|
||||
)
|
||||
}
|
||||
Op::ScalarBranch { target, taken } => {
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
@@ -287,6 +403,10 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Op::RuntimeBranch { mask, target } => {
|
||||
let _ = writeln!(ir, "{offset:04x}: branch.vccz {mask} -> 0x{target:04x}");
|
||||
continue;
|
||||
}
|
||||
Op::MergeLanes {
|
||||
mask,
|
||||
active,
|
||||
@@ -294,9 +414,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
} => (
|
||||
format!("{dest} = merge.lanes mask=0x{mask:08x}, {active}, {inactive}"),
|
||||
format!(
|
||||
"uint {dest} = ((0x{mask:08x}u >> (index & 31u)) & 1u) != 0u ? {active} : {inactive};"
|
||||
"uint {dest} = {};",
|
||||
operation.expression(&thread, "", "(index & 31u)")
|
||||
),
|
||||
),
|
||||
Op::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
taken,
|
||||
} => (
|
||||
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::LaneMask {
|
||||
op,
|
||||
src0,
|
||||
src1,
|
||||
exec,
|
||||
} => {
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
|
||||
op.mnemonic()
|
||||
);
|
||||
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
|
||||
continue;
|
||||
}
|
||||
Op::Store(value) => (
|
||||
format!("store.u32 output[index], {value}"),
|
||||
format!("output[index] = {value};"),
|
||||
@@ -314,6 +457,59 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
})
|
||||
}
|
||||
|
||||
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
|
||||
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
|
||||
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
|
||||
/// Absent lanes of a final partial wave contribute 0.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_lane_mask(
|
||||
msl: &mut String,
|
||||
operations: &[(usize, Op)],
|
||||
uniform: &[bool],
|
||||
index: usize,
|
||||
op: VectorCompareOp,
|
||||
src0: Value,
|
||||
src1: Value,
|
||||
exec: u32,
|
||||
) {
|
||||
let mut cone = vec![false; index];
|
||||
let mut pending = vec![src0, src1];
|
||||
while let Some(value) = pending.pop() {
|
||||
if uniform[value.0] || cone[value.0] {
|
||||
continue;
|
||||
}
|
||||
cone[value.0] = true;
|
||||
pending.extend(operations[value.0].1.operands());
|
||||
}
|
||||
let name = |value: Value| {
|
||||
if cone[value.0] {
|
||||
format!("l{}", value.0)
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
};
|
||||
let dest = Value(index);
|
||||
let _ = writeln!(msl, " uint {dest} = 0u;");
|
||||
let _ = writeln!(
|
||||
msl,
|
||||
" for (uint lane = 0u; lane < 32u; ++lane) {{\n uint lane_index = (index & ~31u) + lane;\n if (lane_index >= grid) {{ break; }}"
|
||||
);
|
||||
for (position, &(_, operation)) in operations[..index].iter().enumerate() {
|
||||
if cone[position] {
|
||||
let _ = writeln!(
|
||||
msl,
|
||||
" uint l{position} = {};",
|
||||
operation.expression(&name, "lane_index", "lane")
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(
|
||||
msl,
|
||||
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
|
||||
compare_expression(op, &name(src0), &name(src1))
|
||||
);
|
||||
}
|
||||
|
||||
fn decode_fixture(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
@@ -326,7 +522,7 @@ fn decode_fixture(
|
||||
|
||||
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
|
||||
let mut operations = Vec::new();
|
||||
let mut registers = [None; 256];
|
||||
let mut registers = [None::<Value>; 256];
|
||||
let mut facts = Vec::<KnownBits>::new();
|
||||
let mut pending_load = None;
|
||||
let mut stored = false;
|
||||
@@ -336,6 +532,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scalars[126] = Some(exec);
|
||||
let mut scc = None;
|
||||
let mut skip_before = 0;
|
||||
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
|
||||
let mut lane_vcc: Option<Value> = None;
|
||||
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
|
||||
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
|
||||
|
||||
// Every decoded instruction must satisfy the fixture layout and binding
|
||||
// contract, even when a known branch skips it.
|
||||
@@ -378,6 +578,70 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
for instruction in decoded {
|
||||
let offset = instruction.offset;
|
||||
let error = |reason| CompileError::Verify { offset, reason };
|
||||
if let Some((end, mask, before)) = region
|
||||
&& offset >= end
|
||||
{
|
||||
region = None;
|
||||
for slot in 0..registers.len() {
|
||||
if let (Some(fallthrough), Some(taken)) = (registers[slot], before[slot])
|
||||
&& fallthrough.0 != taken.0
|
||||
{
|
||||
let next = Value(operations.len());
|
||||
operations.push((
|
||||
end,
|
||||
Op::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
taken,
|
||||
},
|
||||
));
|
||||
let (left, right) = (facts[fallthrough.0], facts[taken.0]);
|
||||
// Keep up to two candidate values when both edges have them.
|
||||
let values = match (left.values, right.values) {
|
||||
(Some([a, b]), Some([c, d])) => {
|
||||
let mut union = vec![a, b, c, d];
|
||||
union.sort_unstable();
|
||||
union.dedup();
|
||||
match union.as_slice() {
|
||||
[only] => Some([*only; 2]),
|
||||
[first, second] => Some([*first, *second]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
facts.push(KnownBits {
|
||||
zero: left.zero & right.zero,
|
||||
one: left.one & right.one,
|
||||
values,
|
||||
});
|
||||
registers[slot] = Some(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
// docs/shaders/vector-compare.md section 6: checked whatever EXEC is.
|
||||
if let Some((_, _, before)) = ®ion {
|
||||
let dst = match instruction.instruction {
|
||||
Instruction::MoveB32 { dst, .. }
|
||||
| Instruction::AddNoCarryU32 { dst, .. }
|
||||
| Instruction::VectorLshlrevB32 { dst, .. }
|
||||
| Instruction::VectorLshrrevB32 { dst, .. }
|
||||
| Instruction::VectorAshrrevI32 { dst, .. }
|
||||
| Instruction::VectorAndB32 { dst, .. }
|
||||
| Instruction::VectorOrB32 { dst, .. }
|
||||
| Instruction::VectorXorB32 { dst, .. } => dst,
|
||||
_ => {
|
||||
return Err(error(
|
||||
"code skipped by a runtime s_cbranch_vccz may contain only integer vector ALU instructions",
|
||||
));
|
||||
}
|
||||
};
|
||||
if before[usize::from(dst)].is_none() {
|
||||
return Err(error(
|
||||
"a VGPR written under a runtime s_cbranch_vccz must be initialized before the branch",
|
||||
));
|
||||
}
|
||||
}
|
||||
let read = |register: u8| {
|
||||
registers[usize::from(register)].ok_or_else(|| {
|
||||
error("source register is uninitialized, pending a load wait, or reserved for indexing")
|
||||
@@ -474,6 +738,28 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
dst,
|
||||
src: VectorSource::Immediate(value),
|
||||
} => (Some(dst), Op::Constant(value)),
|
||||
Instruction::MoveB32 {
|
||||
dst,
|
||||
src: VectorSource::Scalar(register),
|
||||
} if usize::from(register) == VCC_LO
|
||||
&& let Some(mask) = lane_vcc =>
|
||||
{
|
||||
let slot = usize::from(dst);
|
||||
if dst == 0 || pending_load.is_some_and(|(register, _)| register == slot) {
|
||||
return Err(error(
|
||||
"move writes the index register or replaces a pending load",
|
||||
));
|
||||
}
|
||||
registers[slot] = Some(merge_lanes(
|
||||
&mut operations,
|
||||
&mut facts,
|
||||
offset,
|
||||
exec,
|
||||
mask,
|
||||
registers[slot],
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
// SGPR values are wave-uniform and known during translation.
|
||||
Instruction::MoveB32 {
|
||||
dst,
|
||||
@@ -514,6 +800,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
if dst == 126 {
|
||||
exec = value;
|
||||
}
|
||||
if usize::from(dst) == VCC_LO {
|
||||
lane_vcc = None;
|
||||
}
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
@@ -547,6 +836,64 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
if exec == 0 {
|
||||
scalars[VCC_HI] = None;
|
||||
scalars[VCC_LO] = Some(0);
|
||||
lane_vcc = None;
|
||||
continue;
|
||||
}
|
||||
let constant =
|
||||
|operations: &mut Vec<(usize, Op)>, facts: &mut Vec<KnownBits>, bits: u32| {
|
||||
let value = Value(operations.len());
|
||||
operations.push((offset, Op::Constant(bits)));
|
||||
facts.push(KnownBits::constant(bits));
|
||||
value
|
||||
};
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => constant(&mut operations, &mut facts, bits),
|
||||
(None, None) => {
|
||||
return Err(error("compare reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
}
|
||||
VectorSource::Scalar(register) => {
|
||||
let bits = read_scalar(ScalarSource::Register(register))?;
|
||||
constant(&mut operations, &mut facts, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => constant(&mut operations, &mut facts, bits),
|
||||
};
|
||||
let src1 = read(src1)?;
|
||||
let mask = Value(operations.len());
|
||||
operations.push((
|
||||
offset,
|
||||
Op::LaneMask {
|
||||
op,
|
||||
src0,
|
||||
src1,
|
||||
exec,
|
||||
},
|
||||
));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
scalars[VCC_LO] = None;
|
||||
scalars[VCC_HI] = None;
|
||||
lane_vcc = Some(mask);
|
||||
continue;
|
||||
}
|
||||
Instruction::BranchVccZero { target } if let Some(mask) = lane_vcc => {
|
||||
if pending_load.is_some() {
|
||||
return Err(error(
|
||||
"a runtime s_cbranch_vccz requires no outstanding vector load",
|
||||
));
|
||||
}
|
||||
region = Some((target, mask, registers));
|
||||
(None, Op::RuntimeBranch { mask, target })
|
||||
}
|
||||
Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } => {
|
||||
|
||||
@@ -279,3 +279,17 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
|
||||
include_str!("../../../fixtures/golden/scalar-alu.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
let result = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
result.ir,
|
||||
include_str!("../../../fixtures/golden/vector-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
result.msl,
|
||||
include_str!("../../../fixtures/golden/vector-compare.metal")
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
|
||||
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
## Native Metal backend
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 30 of 30. Accepted Metal forms · Apple M5: 18 of 30. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">30 / 30</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">42 / 42</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 30</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 42</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="294.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -15,7 +15,7 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `buffer_load_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL load | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
|
||||
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
|
||||
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
|
||||
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
|
||||
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
@@ -31,6 +31,18 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 > S1), fully written | `7D0802D0` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 != S1), fully written | `7D0A0301` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 >= S1), fully written | `7D0C02FF 80000001` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 < S1), fully written | `7D820701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 == S1), fully written | `7D8402FF 80000000` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 <= S1), fully written | `7D860208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
|
||||
| `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
|
||||
| `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified |
|
||||
@@ -42,21 +54,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_lshrrev_b32_e32` | Two VGPR sources and one VGPR destination | `2DFFFF01` | yes | yes | three-way passed | MSL logical right shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
|
||||
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
<!-- status:instructions:end -->
|
||||
|
||||
## Automated three-way comparison
|
||||
|
||||
LLVM 23.1.6, the production decoder and the independent reference decoder
|
||||
matched 458 instructions across nine streams: the seven synthetic fixtures,
|
||||
matched 650 instructions across ten streams: the eight synthetic fixtures,
|
||||
a high-register sequence and an operand matrix assembled by LLVM.
|
||||
The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic
|
||||
and operands, and the typed reference operation against the production
|
||||
operation. It covers all 30 forms in this document.
|
||||
operation. It covers all 42 compute forms in this document.
|
||||
|
||||
The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and
|
||||
SOP2, forced literals that could otherwise be inline, literal selection in
|
||||
either SOPC or SOP2 operand, every supported SOP2 form, VOP1 SGPR sources, high SGPR and VGPR indices, MUBUF descriptor and index
|
||||
either SOPC or SOP2 operand, every supported SOP2 form, every VOPC compare
|
||||
with VGPR, SGPR, vcc_lo, inline and literal sources, VOP1 SGPR and vcc_lo sources, high SGPR and VGPR indices, MUBUF descriptor and index
|
||||
operands, and zero and nonzero forward branch displacements. The decoder
|
||||
trace exposes MUBUF operands independently of the synthetic execution ABI,
|
||||
which still requires the original index and resource bindings.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Independent gfx1030 CPU reference
|
||||
|
||||
`xenora_ref::execute` reads raw little-endian code bytes and input words without dependencies on the production ISA crate, the compiler or Metal. It accepts at most 1024 instruction bytes and 4096 input words. The synthetic ABI gives every invocation its own input and output word. The indexed load and store forms need no host address arithmetic, and V0 is reserved for that indexing. The reference accepts uniform forward branches driven by scalar register state. Cross-lane register access and wave-mask changes are outside the subset. Floating-point arithmetic is restricted to positive normal inputs and exact normal results.
|
||||
`xenora_ref::execute` reads raw little-endian code bytes and input words without dependencies on the production ISA crate, the compiler or Metal. It accepts at most 1024 instruction bytes and 4096 input words. The synthetic ABI gives every invocation its own input and output word. The indexed load and store forms need no host address arithmetic, and V0 is reserved for that indexing. Dispatch indices form Wave32 waves of 32 consecutive invocations, executed in lockstep with shared scalar state. The reference accepts uniform forward branches driven by scalar register state or by a compare mask in VCC_LO. Cross-lane register access other than compare masks, and EXEC derived from lane data, are outside the subset. Floating-point arithmetic is restricted to positive normal inputs and exact normal results.
|
||||
|
||||
| AMD RDNA 2 ISA guide instruction | Reference operation |
|
||||
|---|---|
|
||||
@@ -10,6 +10,7 @@
|
||||
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
| VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. |
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
# Execution contract: bounded Wave32 VOPC integer compares (issue #186)
|
||||
|
||||
Status: v2, after independent review (codex-contract.log); findings 1-7 addressed. Scope is the Xenora compute-fixture ABI
|
||||
(one input word and one output word per dispatched thread; dispatch index `i`
|
||||
is wave `i / 32`, lane `i % 32`; every wave starts with EXEC_LO = 0xffffffff;
|
||||
scalar state is wave-uniform).
|
||||
|
||||
## 1. Sources (public only)
|
||||
|
||||
- AMD "RDNA 2" Instruction Set Architecture Reference Guide, 30 Nov 2020
|
||||
([public PDF](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)):
|
||||
- S1 §2.1 "Wave32 and Wave64", printed p. 7-8 (PDF p. 15-16): "The upper half
|
||||
of EXEC and VCC are ignored for wave32 waves."
|
||||
- S2 §3.9 "Vector Compares: VCC and VCCZ", printed p. 19-20 (PDF p. 27-28):
|
||||
compares set VCC (1 = pass, 0 = fail); "VCCZ is updated every time VCC is
|
||||
updated: vector compares and scalar writes to VCC"; "V_CMP_* =>
|
||||
VCC[n] = EXEC[n] & (test passed for thread[n])"; "VCC is fully written;
|
||||
there are no partial mask updates"; in wave32 "only the lower 32 bits of
|
||||
VCC contribute to the value of VCCZ".
|
||||
- S3 §4.5 "Manually Inserted Wait States", printed p. 30 (PDF p. 38):
|
||||
"Inserting S_NOP is not required to achieve correct operation."
|
||||
- S3b §3.3 "EXECute Mask", printed p. 13 (PDF p. 21-22): EXEC "does not
|
||||
affect scalar (ALU or memory) execution or branches"; in wave32 EXECZ
|
||||
reflects only the lower 32 bits.
|
||||
- S4 §6.2.2 "Instruction Outputs", printed p. 43 (PDF p. 51): a thread
|
||||
writes a VGPR result only if its EXEC bit is set; V_CMPX writes EXEC.
|
||||
- S4b §6.2 Table 20 (operand selectors), PDF p. 49-50: 106 = VCC_LO.
|
||||
- S5 §12.9 "VOPC Instructions", printed p. 150-152 (PDF p. 158-160): field map
|
||||
SRC0 / VSRC1 / OP; "producing a 1 bit result per lane into VCC or EXEC";
|
||||
Table 59: integer compare offsets LT 1, EQ 2, LE 3, GT 4, LG/NE 5, GE 6.
|
||||
Table 61 "VOPC Compare Opcodes", printed p. 155 and 159 (PDF p. 163, 167):
|
||||
128-135 V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_I32 and 192-199 the _U32 forms,
|
||||
"D = VCC in VOPC encoding". The XML is authoritative for encodings.
|
||||
- AMD RDNA 2 machine-readable ISA XML (pinned SHA-256 `d671ecbc...`, used by
|
||||
`crates/isa/generate_rdna2.py`; see `docs/research/rdna2.md`): ENC_VOPC opcodes V_CMP_{LT,EQ,LE,GT,NE,GE}_I32
|
||||
= 129-134 and V_CMP_{LT,EQ,LE,GT,NE,GE}_U32 = 193-198; descriptions "Set the
|
||||
per-lane condition code to 1 iff the first input is <rel> the second input";
|
||||
SRC0 and VSRC1 data format FMT_NUM_I32 for the _I32 forms and FMT_NUM_U32
|
||||
for the _U32 forms; destination OPR_VCC.
|
||||
- LLVM 23.1.6 AMDGPU (`llvm-mc`, gfx1030, `+wavefrontsize32`) as an encoding
|
||||
oracle only: `compares_fixture_instructions_against_llvm` checks every form
|
||||
with every source class against the decoder and the reference.
|
||||
|
||||
## 2. Supported forms
|
||||
|
||||
The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP:
|
||||
|
||||
| Form | per-lane test, S0 = SRC0, S1 = VSRC1 |
|
||||
| --- | --- |
|
||||
| v_cmp_lt_i32 / v_cmp_lt_u32 | S0 < S1 |
|
||||
| v_cmp_eq_i32 / v_cmp_eq_u32 | S0 == S1 |
|
||||
| v_cmp_le_i32 / v_cmp_le_u32 | S0 <= S1 |
|
||||
| v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 |
|
||||
| v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 |
|
||||
| v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 |
|
||||
|
||||
`_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values.
|
||||
Operand order matters (S0 is SRC0): lt with swapped operands is gt.
|
||||
|
||||
SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5),
|
||||
128-208 (inline integers 0..64 and -1..-16), 255 (one 32-bit literal, which
|
||||
must be present in full after the word), 256-511 (VGPR). Every other selector
|
||||
is rejected at decode, independent of EXEC: TTMPs, M0, NULL, EXEC_LO/HI,
|
||||
VCC_HI, apertures, wave-ID, reserved values, inline floats 240-248, SDWA 249,
|
||||
DPP8 233/234, DPP16 250, VCCZ/EXECZ/SCC 251-253, LDS direct 254. VSRC1 is a
|
||||
VGPR.
|
||||
|
||||
Wave size: the compute fixture ABI is defined as Wave32. A raw instruction
|
||||
stream carries no wave-size declaration (the VOPC word has no wave-size field),
|
||||
so every caller of the translator and the reference establishes Wave32 by
|
||||
using this ABI; there is no Wave64 entry point to reject.
|
||||
|
||||
## 3. Semantics of one supported compare, Wave32
|
||||
|
||||
Let E = EXEC_LO before the instruction and A = the set of lanes that exist in
|
||||
this wave (all 32 except in a final partial wave, see 7). As an unsigned
|
||||
32-bit value,
|
||||
|
||||
VCC_LO := OR over 0 <= n < 32 of ( [n in A] & E[n] & test(S0[n], S1[n]) ) << n
|
||||
|
||||
- VCC_LO is fully written, every time, including bits of inactive or absent
|
||||
lanes, which become 0 (S2). With E = 0 the result is VCC_LO = 0 even if VCC
|
||||
held a nonzero value before.
|
||||
- Inactive lanes (E[n] = 0) read no VGPR source; their bit is 0 regardless of
|
||||
their data.
|
||||
- VCC_HI: S1 says it is ignored in wave32; whether hardware writes it is not
|
||||
settled by the sources. After any supported compare, VCC_HI has no known
|
||||
value. (No supported instruction can read vcc_hi today; this keeps any
|
||||
future reader honest.)
|
||||
- EXEC, SCC, every VGPR and every other SGPR are unchanged.
|
||||
- VCCZ, as read by `s_cbranch_vccz`, is (VCC_LO == 0) (S2, wave32 sentence).
|
||||
- No wait states are needed between the compare and a reader of VCC (S3).
|
||||
|
||||
## 4. Rejected (controlled translation/reference error, never a silent no-op)
|
||||
|
||||
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
|
||||
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
|
||||
- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class.
|
||||
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
|
||||
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
|
||||
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
|
||||
- Wave64 in any form.
|
||||
|
||||
## 5. VCC_LO state and where a compare result may flow
|
||||
|
||||
Both the translator and the reference track VCC_LO in one of three static
|
||||
states, decided by the instruction path alone, never by lane data:
|
||||
- *uninitialized* (program start);
|
||||
- *known*: written by `s_mov_b32 vcc_lo, <known value>`, or by a compare
|
||||
executed while EXEC_LO is statically 0 (result: known 0);
|
||||
- *lane-derived*: written by a compare executed while EXEC_LO != 0. It stays
|
||||
lane-derived even when a particular wave's result happens to be 0 or equal
|
||||
to a constant; acceptance never depends on that value.
|
||||
|
||||
Acceptance rules for one compare:
|
||||
- EXEC_LO = 0 (EXEC is always a known value in this ABI): the encoding is
|
||||
validated, no source is read or checked (not VGPR readiness, SGPR knowledge
|
||||
or VCC state), and VCC_LO becomes known 0.
|
||||
- EXEC_LO != 0: VSRC1 and a VGPR SRC0 must be initialized and not pending a
|
||||
load; a normal-SGPR SRC0 must be known; a `vcc_lo` SRC0 must be known or
|
||||
lane-derived (uninitialized is rejected). VCC_LO becomes lane-derived.
|
||||
|
||||
While VCC_LO is lane-derived it may be read only by:
|
||||
|
||||
1. `s_cbranch_vccz` (6);
|
||||
2. `v_mov_b32_e32 vD, vcc_lo`, which writes the 32-bit mask into vD of active
|
||||
lanes (inactive lanes keep vD, as for any partial-EXEC move);
|
||||
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
|
||||
old VCC_LO in every active lane before the new value is written.
|
||||
|
||||
`v_mov_b32_e32 vD, vcc_lo` follows the usual EXEC rules: with EXEC_LO = 0 it
|
||||
is skipped without reading VCC; otherwise VCC_LO must be known or
|
||||
lane-derived. Every other read of vcc_lo is rejected in any state: the
|
||||
supported scalar instructions (`s_mov_b32`, SOP2, `s_cmp_eq_u32`) do not
|
||||
accept vcc_lo as a source at decode, so `s_mov_b32 exec_lo, vcc_lo` cannot
|
||||
create divergent EXEC. `s_mov_b32 vcc_lo, <known>` makes VCC_LO known again.
|
||||
|
||||
## 6. Branches
|
||||
|
||||
- `s_cbranch_scc0`: unaffected (compares do not touch SCC).
|
||||
- `s_cbranch_execz`: unaffected (compares do not touch EXEC).
|
||||
- `s_cbranch_vccz` with a known VCC_LO: resolved during translation, as today.
|
||||
- `s_cbranch_vccz` with a lane-derived VCC_LO (a *runtime branch*): the whole
|
||||
wave takes it iff VCC_LO == 0. Control flow stays wave-uniform; no lane
|
||||
diverges. Accepted only if the skipped region R (from the end of the branch
|
||||
to the target, exclusive) satisfies all of:
|
||||
- the target is a forward instruction boundary (existing rule);
|
||||
- no vector load is outstanding at the branch;
|
||||
- R contains only these integer vector forms: `v_mov_b32_e32` (from a
|
||||
VGPR, an immediate (inline integer, the inline +1.0f bit pattern or a
|
||||
literal; the move copies bits), a known normal SGPR, or vcc_lo known or
|
||||
lane-derived), `v_add_nc_u32_e64`, `v_lshlrev_b32_e32`,
|
||||
`v_lshrrev_b32_e32`, `v_ashrrev_i32_e32`, `v_and_b32_e32`, `v_or_b32_e32`,
|
||||
`v_xor_b32_e32`. Nothing else: no FP32 form, scalar instruction, compare,
|
||||
branch, wait, memory access or `s_endpgm`;
|
||||
- every VGPR written in R was initialized before the branch;
|
||||
- every source read in R is ready where it is read (the normal rules, as on
|
||||
the fall-through path).
|
||||
These rules are checked on R's instructions whether the branch is taken or
|
||||
not, and whatever EXEC_LO is, so acceptance does not depend on lane data.
|
||||
After R, each VGPR written in R holds its value from R if the branch was not
|
||||
taken, else its value from before the branch; scalar state (SGPRs, SCC,
|
||||
EXEC, VCC state) is the same on both paths. The translator's known-bit
|
||||
facts for a joined VGPR keep only bits known and equal on both inputs, and
|
||||
the union of the candidate values when it has at most two (so an exact
|
||||
FP32 operation after the join is still accepted when both edges allow it).
|
||||
An outstanding store at the branch is allowed: the store already read its
|
||||
data.
|
||||
|
||||
## 7. Wave formation and absent lanes
|
||||
|
||||
Waves are formed from consecutive dispatch indices: wave w is indices
|
||||
32w..32w+31. A final partial wave (input length not a multiple of 32) has
|
||||
absent lanes; they never execute and contribute 0 to every compare result.
|
||||
(The fixture's EXEC_LO still reads 0xffffffff in such a wave; that existing
|
||||
ABI simplification is unchanged and documented as a limitation.)
|
||||
|
||||
## 8. Mapping to Metal (no SIMD-group assumption)
|
||||
|
||||
Metal SIMD groups, threadgroups and RDNA 2 waves are not assumed to coincide.
|
||||
The Metal kernel makes no cross-thread call: no simd_ballot, no threadgroup
|
||||
memory, no barrier. For each compare, every thread recomputes the compare's
|
||||
per-lane operand values for each of the 32 lanes of its own RDNA wave
|
||||
(dispatch indices (index & ~31) + n, bounded by the grid size from
|
||||
`[[threads_per_grid]]`), from those lanes' input words, and assembles VCC_LO
|
||||
itself. All values are pure functions of input words and translation-time
|
||||
constants, so every thread of a wave computes the same VCC_LO. A runtime
|
||||
branch becomes a per-register select on (VCC_LO != 0) at the join; region
|
||||
instructions are pure 32-bit ALU and are evaluated unconditionally.
|
||||
|
||||
## 9. Verification
|
||||
|
||||
`fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM.
|
||||
It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo`
|
||||
sources, a compare and a mask move under partial EXEC, a compare under empty
|
||||
EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
|
||||
`s_cbranch_vccz`. Its expected output is written in
|
||||
`tests/validation/known_answers.rs` from the listing, with an explicit
|
||||
relation for each row. The test input has a wave whose branch is taken, one
|
||||
whose branch is not, and a final partial wave of 9 lanes.
|
||||
|
||||
The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe,
|
||||
0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff,
|
||||
0x0f0f0f0f), in both operand orders. That is 240 programs, checked against
|
||||
exact i128 differences. It also covers partial and empty EXEC with seeded
|
||||
destinations, both runtime branch edges in one dispatch, and 32 rejections
|
||||
pinned to their byte offset. The translator, the reference (lockstep waves,
|
||||
compares on widened i64 values) and the second interpreter (sign-bit flip,
|
||||
then an unsigned compare) must all agree. The 9 ordered compare slots in the
|
||||
fixture each change the result when their signedness is flipped. The same
|
||||
programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation
|
||||
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`).
|
||||
|
||||
A deliberately broken copy of each implementation fails these tests: the
|
||||
reference with unsigned-only compares or with the EXEC test removed; the
|
||||
second interpreter with unsigned-only compares or with no empty-EXEC rule;
|
||||
the translator with a stale VCC under empty EXEC (CPU), and, on Metal, with
|
||||
swapped signedness, without the EXEC mask, without the absent-lane bound
|
||||
(shader validation aborts on the out-of-range read) or with an inverted join.
|
||||
|
||||
Evidence class: agreement with a specification-derived reference, run
|
||||
locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
|
||||
|
||||
## 10. Limitations
|
||||
|
||||
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP, 16-bit, 64-bit or float compares.
|
||||
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
|
||||
is no divergent execution. That needs its own contract.
|
||||
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
|
||||
ALU instructions. Loops, nested runtime branches and scalar state that
|
||||
differs between the two edges are not supported.
|
||||
- Each thread recomputes up to 32 lanes per compare. The cost grows with the
|
||||
compare's dependency chain. That is fine for fixtures, and no performance is
|
||||
claimed.
|
||||
+145
-2
@@ -65,7 +65,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mov_b32_e32"
|
||||
encoding = "VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation) or inline integer or literal source, plus the inline bit pattern for +1.0f"
|
||||
encoding = "VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f"
|
||||
representation = "4 or 8 B"
|
||||
lowering = "constant or register value"
|
||||
reference = "implemented"
|
||||
@@ -255,6 +255,149 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
|
||||
representation = "`7D020701`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_eq_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written"
|
||||
representation = "`7D040280`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_le_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written"
|
||||
representation = "`7D060208`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_gt_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 > S1), fully written"
|
||||
representation = "`7D0802D0`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ne_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 != S1), fully written"
|
||||
representation = "`7D0A0301`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ge_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 >= S1), fully written"
|
||||
representation = "`7D0C02FF 80000001`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 < S1), fully written"
|
||||
representation = "`7D820701`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_eq_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 == S1), fully written"
|
||||
representation = "`7D8402FF 80000000`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_le_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 <= S1), fully written"
|
||||
representation = "`7D860208`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_gt_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written"
|
||||
representation = "`7D8802C0`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ne_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written"
|
||||
representation = "`7D8A026A`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ge_u32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written"
|
||||
representation = "`7D8C0D01`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
[[instruction]]
|
||||
form = "s_cbranch_scc0"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
@@ -391,7 +534,7 @@ llvm = "three-way passed"
|
||||
form = "s_cbranch_vccz"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
representation = "`BF860001`"
|
||||
lowering = "resolved Wave32 VCC_LO zero check"
|
||||
lowering = "resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0018: t1 = const.u32 0x00000000
|
||||
001c: t2 = const.u32 0x00000001
|
||||
0020: t3 = const.u32 0x0f0f0f0f
|
||||
0028: t4 = const.u32 0xa5a5a5a5
|
||||
0030: t5 = const.u32 0xffffffff
|
||||
0034: t6 = wave.mask v_cmp_lt_i32_e32 t0, t5 exec=0xffffffff
|
||||
003c: t7 = lshl.b32 t1, t2
|
||||
0040: t8 = xor.b32 t7, t6
|
||||
0044: t9 = wave.mask v_cmp_lt_u32_e32 t0, t5 exec=0xffffffff
|
||||
004c: t10 = lshl.b32 t8, t2
|
||||
0050: t11 = xor.b32 t10, t9
|
||||
0054: t12 = const.u32 0x00000000
|
||||
0054: t13 = wave.mask v_cmp_eq_i32_e32 t12, t0 exec=0xffffffff
|
||||
005c: t14 = lshl.b32 t11, t2
|
||||
0060: t15 = xor.b32 t14, t13
|
||||
0064: t16 = const.u32 0x80000000
|
||||
0064: t17 = wave.mask v_cmp_eq_u32_e32 t16, t0 exec=0xffffffff
|
||||
0070: t18 = lshl.b32 t15, t2
|
||||
0074: t19 = xor.b32 t18, t17
|
||||
0078: t20 = const.u32 0x7fffffff
|
||||
0078: t21 = wave.mask v_cmp_le_i32_e32 t20, t0 exec=0xffffffff
|
||||
0080: t22 = lshl.b32 t19, t2
|
||||
0084: t23 = xor.b32 t22, t21
|
||||
0088: t24 = const.u32 0x7fffffff
|
||||
0088: t25 = wave.mask v_cmp_le_u32_e32 t24, t0 exec=0xffffffff
|
||||
0090: t26 = lshl.b32 t23, t2
|
||||
0094: t27 = xor.b32 t26, t25
|
||||
0098: t28 = const.u32 0xfffffff0
|
||||
0098: t29 = wave.mask v_cmp_gt_i32_e32 t28, t0 exec=0xffffffff
|
||||
00a0: t30 = lshl.b32 t27, t2
|
||||
00a4: t31 = xor.b32 t30, t29
|
||||
00a8: t32 = const.u32 0x00000040
|
||||
00a8: t33 = wave.mask v_cmp_gt_u32_e32 t32, t0 exec=0xffffffff
|
||||
00b0: t34 = lshl.b32 t31, t2
|
||||
00b4: t35 = xor.b32 t34, t33
|
||||
00b8: t36 = wave.mask v_cmp_ne_i32_e32 t0, t0 exec=0xffffffff
|
||||
00bc: t37 = wave.mask v_cmp_ne_u32_e32 t36, t0 exec=0xffffffff
|
||||
00c4: t38 = lshl.b32 t35, t2
|
||||
00c8: t39 = xor.b32 t38, t37
|
||||
00cc: t40 = const.u32 0x80000001
|
||||
00cc: t41 = wave.mask v_cmp_ge_i32_e32 t40, t0 exec=0xffffffff
|
||||
00d8: t42 = lshl.b32 t39, t2
|
||||
00dc: t43 = xor.b32 t42, t41
|
||||
00e8: t44 = wave.mask v_cmp_ge_u32_e32 t0, t3 exec=0x55555555
|
||||
00ec: t45 = merge.lanes mask=0x55555555, t44, t4
|
||||
00f4: t46 = xor.b32 t43, t45
|
||||
0104: branch.uniform 0x0110 taken=true
|
||||
0114: t48 = const.u32 0x00000000
|
||||
0118: t49 = xor.b32 t46, t48
|
||||
011c: branch.uniform 0x012c taken=false
|
||||
0120: t51 = wave.mask v_cmp_gt_u32_e32 t0, t3 exec=0xffffffff
|
||||
0124: branch.vccz t51 -> 0x012c
|
||||
0128: t53 = xor.b32 t49, t3
|
||||
012c: t54 = join.vccz t51, t53, t49
|
||||
012c: store.u32 output[index], t54
|
||||
@@ -0,0 +1,152 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]],
|
||||
uint grid [[threads_per_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0x00000000u;
|
||||
uint t2 = 0x00000001u;
|
||||
uint t3 = 0x0f0f0f0fu;
|
||||
uint t4 = 0xa5a5a5a5u;
|
||||
uint t5 = 0xffffffffu;
|
||||
uint t6 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) < as_type<int>(t5)) ? 1u : 0u;
|
||||
t6 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t7 = t1 << (t2 & 31u);
|
||||
uint t8 = t7 ^ t6;
|
||||
uint t9 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 < t5) ? 1u : 0u;
|
||||
t9 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t10 = t8 << (t2 & 31u);
|
||||
uint t11 = t10 ^ t9;
|
||||
uint t12 = 0x00000000u;
|
||||
uint t13 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(t12) == as_type<int>(l0)) ? 1u : 0u;
|
||||
t13 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t14 = t11 << (t2 & 31u);
|
||||
uint t15 = t14 ^ t13;
|
||||
uint t16 = 0x80000000u;
|
||||
uint t17 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t16 == l0) ? 1u : 0u;
|
||||
t17 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t18 = t15 << (t2 & 31u);
|
||||
uint t19 = t18 ^ t17;
|
||||
uint t20 = 0x7fffffffu;
|
||||
uint t21 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(t20) <= as_type<int>(l0)) ? 1u : 0u;
|
||||
t21 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t22 = t19 << (t2 & 31u);
|
||||
uint t23 = t22 ^ t21;
|
||||
uint t24 = 0x7fffffffu;
|
||||
uint t25 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t24 <= l0) ? 1u : 0u;
|
||||
t25 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t26 = t23 << (t2 & 31u);
|
||||
uint t27 = t26 ^ t25;
|
||||
uint t28 = 0xfffffff0u;
|
||||
uint t29 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(t28) > as_type<int>(l0)) ? 1u : 0u;
|
||||
t29 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t30 = t27 << (t2 & 31u);
|
||||
uint t31 = t30 ^ t29;
|
||||
uint t32 = 0x00000040u;
|
||||
uint t33 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t32 > l0) ? 1u : 0u;
|
||||
t33 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t34 = t31 << (t2 & 31u);
|
||||
uint t35 = t34 ^ t33;
|
||||
uint t36 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) != as_type<int>(l0)) ? 1u : 0u;
|
||||
t36 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t37 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t36 != l0) ? 1u : 0u;
|
||||
t37 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t38 = t35 << (t2 & 31u);
|
||||
uint t39 = t38 ^ t37;
|
||||
uint t40 = 0x80000001u;
|
||||
uint t41 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(t40) >= as_type<int>(l0)) ? 1u : 0u;
|
||||
t41 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t42 = t39 << (t2 & 31u);
|
||||
uint t43 = t42 ^ t41;
|
||||
uint t44 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 >= t3) ? 1u : 0u;
|
||||
t44 |= ((0x55555555u >> lane) & pass) << lane;
|
||||
}
|
||||
uint t45 = ((0x55555555u >> (index & 31u)) & 1u) != 0u ? t44 : t4;
|
||||
uint t46 = t43 ^ t45;
|
||||
uint t48 = 0x00000000u;
|
||||
uint t49 = t46 ^ t48;
|
||||
uint t51 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 > t3) ? 1u : 0u;
|
||||
t51 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t53 = t49 ^ t3;
|
||||
uint t54 = t51 != 0u ? t53 : t49;
|
||||
output[index] = t54;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,82 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Wave32 VOPC vectors: all twelve 32-bit integer compares with VGPR,
|
||||
// SGPR, inline, literal and vcc_lo sources; a compare under partial EXEC and
|
||||
// a mask move into a seeded VGPR under partial EXEC; a compare under empty
|
||||
// EXEC that must clear a stale VCC; SCC kept across compares; and a runtime
|
||||
// s_cbranch_vccz. Each wave folds its masks into v2 as v2 = (v2 << 1) ^ mask.
|
||||
// Expected results come from exact integer definitions in
|
||||
// tests/validation/known_answers.rs, not from this file.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_cmp_eq_u32 0, 0 // SCC = 1, must survive every compare
|
||||
s_mov_b32 s8, 0x7fffffff
|
||||
v_mov_b32_e32 v2, 0 // accumulator
|
||||
v_mov_b32_e32 v5, 1 // shift count
|
||||
v_mov_b32_e32 v6, 0x0f0f0f0f
|
||||
v_mov_b32_e32 v7, 0xa5a5a5a5 // seeded destination for a partial move
|
||||
v_mov_b32_e32 v3, -1
|
||||
v_cmp_lt_i32_e32 vcc_lo, v1, v3 // signed x < -1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_lt_u32_e32 vcc_lo, v1, v3 // unsigned x < 0xffffffff
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_eq_i32_e32 vcc_lo, 0, v1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_eq_u32_e32 vcc_lo, 0x80000000, v1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_le_i32_e32 vcc_lo, s8, v1 // 0x7fffffff <= x (signed)
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_le_u32_e32 vcc_lo, s8, v1 // 0x7fffffff <= x (unsigned)
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_gt_i32_e32 vcc_lo, -16, v1 // -16 > x (signed)
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_gt_u32_e32 vcc_lo, 64, v1 // 64 > x (unsigned)
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_ne_i32_e32 vcc_lo, v1, v1 // aliased sources: never true
|
||||
v_cmp_ne_u32_e32 vcc_lo, vcc_lo, v1 // reads the previous (zero) mask
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_ge_i32_e32 vcc_lo, 0x80000001, v1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
s_mov_b32 exec_lo, 0x55555555
|
||||
v_cmp_ge_u32_e32 vcc_lo, v1, v6 // only even lanes take part
|
||||
v_mov_b32_e32 v7, vcc_lo // odd lanes keep 0xa5a5a5a5
|
||||
s_mov_b32 exec_lo, -1
|
||||
v_xor_b32_e32 v2, v2, v7
|
||||
s_mov_b32 vcc_lo, -1 // stale nonzero mask
|
||||
s_mov_b32 exec_lo, 0
|
||||
v_cmp_eq_u32_e32 vcc_lo, v1, v1 // empty EXEC: VCC_LO = 0
|
||||
s_cbranch_execz .Lempty
|
||||
s_mov_b32 exec_lo, -1 // reached only if EXECZ were ignored
|
||||
v_mov_b32_e32 v2, 0
|
||||
.Lempty:
|
||||
s_mov_b32 exec_lo, -1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
s_cbranch_scc0 .Ldone // never taken: SCC is still 1
|
||||
v_cmp_gt_u32_e32 vcc_lo, v1, v6 // runtime branch on lane data
|
||||
s_cbranch_vccz .Ldone
|
||||
v_xor_b32_e32 v2, v2, v6
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
+2
-1
@@ -25,6 +25,7 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
|
||||
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU.
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
|
||||
# and VOPC compares.
|
||||
cargo test --locked -p xenora-semantic-review --no-run
|
||||
timeout 60s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
|
||||
+547
-206
@@ -18,6 +18,16 @@
|
||||
//! two rather than with a host signed shift, so the oracle does not share the
|
||||
//! production operator. SOP2 arithmetic runs through a bit-serial ripple
|
||||
//! adder (subtraction as addition of the complement), not host integer ops.
|
||||
//!
|
||||
//! Wave32 VOPC integer compares (`v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`,
|
||||
//! contract `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution
|
||||
//! runs lockstep waves of 32 consecutive dispatch indices with wave-uniform
|
||||
//! scalar state and per-lane vector state. A lane-local failure stops only that
|
||||
//! lane and the lowest-index error is reported, so programs without compares
|
||||
//! fail exactly as independent per-lane runs did. Signed compares flip the sign
|
||||
//! bit of both operands and then compare unsigned. VCC_LO is uninitialized,
|
||||
//! known or lane-derived; a lane-derived VCC_LO feeds `s_cbranch_vccz` only
|
||||
//! after a static check of the skipped region.
|
||||
|
||||
const MAX_CODE_BYTES: usize = 1024;
|
||||
const MAX_INPUT_WORDS: usize = 4096;
|
||||
@@ -28,6 +38,15 @@ enum Src {
|
||||
Imm(u32),
|
||||
}
|
||||
|
||||
/// A VOPC SRC0 operand (contract 2 allowlist).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum CmpSrc {
|
||||
Sgpr(u8),
|
||||
Vcc,
|
||||
Imm(u32),
|
||||
Vgpr(u8),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Insn {
|
||||
SMov(u8, Src),
|
||||
@@ -42,6 +61,15 @@ enum Insn {
|
||||
Branch(usize),
|
||||
VMov(u8, Src),
|
||||
VMovFromSgpr(u8, u8),
|
||||
/// `v_mov_b32_e32 vD, vcc_lo`.
|
||||
VMovFromVcc(u8),
|
||||
/// VOPC compare into VCC_LO: relation 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge.
|
||||
VCmp {
|
||||
relation: u8,
|
||||
signed: bool,
|
||||
src0: CmpSrc,
|
||||
src1: u8,
|
||||
},
|
||||
VAddNc(u8, u8, u8),
|
||||
VAnd(u8, u8, u8),
|
||||
VOr(u8, u8, u8),
|
||||
@@ -67,35 +95,64 @@ pub fn execute(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
return Err("code exceeds limit".to_string());
|
||||
}
|
||||
let program = decode(code)?;
|
||||
input
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, &word)| run_lane(&program, word, index % 32))
|
||||
.collect()
|
||||
let mut output = Vec::with_capacity(input.len());
|
||||
for wave in input.chunks(32) {
|
||||
output.extend(run_wave(&program, wave)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn run_lane(program: &[(usize, Insn)], lane_input: u32, lane: usize) -> Result<u32, String> {
|
||||
let mut vgpr = [None::<u32>; 256];
|
||||
/// Per-lane vector and memory state of one wave lane.
|
||||
struct Lane {
|
||||
input: u32,
|
||||
vgpr: [Option<u32>; 256],
|
||||
pending_read: Option<u8>,
|
||||
pending_write: Option<u32>,
|
||||
written: Option<u32>,
|
||||
/// A lane-local failure; the lane stops executing.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// The lowest-index failed lane's error, in dispatch order.
|
||||
fn first_error(lanes: &[Lane]) -> Option<String> {
|
||||
lanes.iter().find_map(|lane| lane.error.clone())
|
||||
}
|
||||
|
||||
/// Fail every still-running lane with a wave-uniform error and report the
|
||||
/// lowest-index failure, exactly as independent per-lane runs would.
|
||||
fn wave_error(lanes: &mut [Lane], error: String) -> String {
|
||||
for lane in lanes.iter_mut() {
|
||||
lane.error.get_or_insert_with(|| error.clone());
|
||||
}
|
||||
first_error(lanes).unwrap_or(error)
|
||||
}
|
||||
|
||||
fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String> {
|
||||
let mut lanes: Vec<Lane> = wave
|
||||
.iter()
|
||||
.map(|&input| Lane {
|
||||
input,
|
||||
vgpr: [None; 256],
|
||||
pending_read: None,
|
||||
pending_write: None,
|
||||
written: None,
|
||||
error: None,
|
||||
})
|
||||
.collect();
|
||||
// Scalar state is wave-uniform and shared by all lanes.
|
||||
let mut sgpr = [None::<u32>; 128];
|
||||
sgpr[126] = Some(u32::MAX);
|
||||
let mut scc: Option<bool> = None;
|
||||
let mut pending_read: Option<u8> = None;
|
||||
let mut pending_write: Option<u32> = None;
|
||||
let mut written: Option<u32> = None;
|
||||
// sgpr[106] holds VCC_LO's value; this flag marks it lane-derived.
|
||||
let mut vcc_lane_derived = false;
|
||||
let mut pc = 0usize;
|
||||
|
||||
while pc < program.len() {
|
||||
let (offset, insn) = program[pc];
|
||||
let read_v = |reg: u8| -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
}
|
||||
if pending_read == Some(reg) {
|
||||
return Err(format!("{offset:#x}: read before load wait"));
|
||||
}
|
||||
vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
|
||||
};
|
||||
let read_s = |src: Src| -> Result<u32, String> {
|
||||
if lanes.iter().all(|lane| lane.error.is_some()) {
|
||||
break;
|
||||
}
|
||||
let read_s = |sgpr: &[Option<u32>; 128], src: Src| -> Result<u32, String> {
|
||||
match src {
|
||||
Src::Imm(value) => Ok(value),
|
||||
Src::Reg(reg) => {
|
||||
@@ -103,210 +160,459 @@ fn run_lane(program: &[(usize, Insn)], lane_input: u32, lane: usize) -> Result<u
|
||||
}
|
||||
}
|
||||
};
|
||||
let execution_mask = match read_s(&sgpr, Src::Reg(126)) {
|
||||
Ok(mask) => mask,
|
||||
Err(error) => return Err(wave_error(&mut lanes, error)),
|
||||
};
|
||||
|
||||
let execution_mask = read_s(Src::Reg(126))?;
|
||||
if execution_mask.count_ones() < 32 {
|
||||
match insn {
|
||||
Insn::Load(_) | Insn::Store(_) => {
|
||||
return Err(format!(
|
||||
"{offset:#x}: incomplete EXEC on a buffer instruction"
|
||||
));
|
||||
}
|
||||
Insn::VMov(dst, _)
|
||||
| Insn::VMovFromSgpr(dst, _)
|
||||
| Insn::VAddNc(dst, ..)
|
||||
| Insn::VAnd(dst, ..)
|
||||
| Insn::VOr(dst, ..)
|
||||
| Insn::VXor(dst, ..)
|
||||
| Insn::VShiftLeft(dst, ..)
|
||||
| Insn::VShiftRight(dst, ..)
|
||||
| Insn::VShiftRightArithmetic(dst, ..)
|
||||
| Insn::VAddF(dst, ..)
|
||||
| Insn::VMulF(dst, ..) => {
|
||||
if execution_mask != 0 && vgpr[usize::from(dst)].is_none() {
|
||||
return Err(format!("{offset:#x}: partial EXEC on uninitialized VGPR"));
|
||||
}
|
||||
if let (Insn::VMovFromSgpr(_, src), true) = (insn, execution_mask != 0) {
|
||||
read_s(Src::Reg(src))?;
|
||||
}
|
||||
if (execution_mask.rotate_right(lane as u32) & 1) == 0 {
|
||||
pc += 1;
|
||||
continue;
|
||||
let scalar: Result<Option<usize>, String> = match insn {
|
||||
Insn::End => {
|
||||
for lane in lanes.iter_mut().filter(|lane| lane.error.is_none()) {
|
||||
if lane.pending_read.is_some() || lane.pending_write.is_some() {
|
||||
lane.error = Some(format!("{offset:#x}: outstanding transfer at end"));
|
||||
} else if lane.written.is_none() {
|
||||
lane.error = Some(format!("{offset:#x}: missing output store"));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
match insn {
|
||||
Insn::Load(data) => {
|
||||
if data == 0 || pending_read.is_some() {
|
||||
return Err(format!("{offset:#x}: invalid or overlapping load"));
|
||||
if let Some(error) = first_error(&lanes) {
|
||||
return Err(error);
|
||||
}
|
||||
pending_read = Some(data);
|
||||
return Ok(lanes.iter().map(|lane| lane.written.unwrap()).collect());
|
||||
}
|
||||
Insn::Store(data) => {
|
||||
let value = read_v(data)?;
|
||||
if pending_write.is_some() || written.is_some() {
|
||||
return Err(format!("{offset:#x}: multiple output writes"));
|
||||
Insn::VCmp {
|
||||
relation,
|
||||
signed,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
// A compare couples lanes; a failed lane has no defined
|
||||
// contribution, so the wave stops with its error.
|
||||
if let Some(error) = first_error(&lanes) {
|
||||
return Err(error);
|
||||
}
|
||||
pending_write = Some(value);
|
||||
}
|
||||
Insn::WaitRead => {
|
||||
if let Some(dst) = pending_read.take() {
|
||||
vgpr[dst as usize] = Some(lane_input);
|
||||
}
|
||||
}
|
||||
Insn::WaitWrite => {
|
||||
if let Some(value) = pending_write.take() {
|
||||
written = Some(value);
|
||||
}
|
||||
}
|
||||
Insn::VMov(dst, src) => {
|
||||
let value = match src {
|
||||
Src::Imm(value) => value,
|
||||
Src::Reg(reg) => read_v(reg)?,
|
||||
};
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VMovFromSgpr(dst, src) => {
|
||||
let value = read_s(Src::Reg(src))?;
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VAddNc(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let sum = u64::from(read_v(a)?) + u64::from(read_v(b)?);
|
||||
vgpr[dst as usize] = Some(sum as u32);
|
||||
}
|
||||
Insn::VAnd(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let value = read_v(a)? & read_v(b)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VOr(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let value = read_v(a)? | read_v(b)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VShiftLeft(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let factor = 2_u64.pow(read_v(count)? % 32);
|
||||
let product = u64::from(read_v(value)?) * factor;
|
||||
vgpr[dst as usize] = Some((product % (1_u64 << 32)) as u32);
|
||||
}
|
||||
Insn::VShiftRight(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let divisor = 2_u32.pow(read_v(count)? % 32);
|
||||
vgpr[dst as usize] = Some(read_v(value)? / divisor);
|
||||
}
|
||||
Insn::VShiftRightArithmetic(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
// Floor division of the sign-extended value, reduced modulo
|
||||
// 2^32. This is arithmetic shift without using `>>`.
|
||||
let shifted =
|
||||
i64::from(read_v(value)? as i32).div_euclid(1_i64 << (read_v(count)? % 32));
|
||||
vgpr[dst as usize] = Some(shifted.rem_euclid(1_i64 << 32) as u32);
|
||||
}
|
||||
Insn::VXor(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let value = read_v(a)? ^ read_v(b)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VAddF(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let value = exact_float(true, read_v(a)?, read_v(b)?, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::VMulF(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let value = exact_float(false, read_v(a)?, read_v(b)?, offset)?;
|
||||
vgpr[dst as usize] = Some(value);
|
||||
compare(
|
||||
&lanes,
|
||||
&sgpr,
|
||||
execution_mask,
|
||||
(relation, signed, src0, src1),
|
||||
offset,
|
||||
)
|
||||
.map(|mask| {
|
||||
sgpr[106] = Some(mask);
|
||||
// VCC_HI has no known value after a compare (contract 3).
|
||||
sgpr[107] = None;
|
||||
vcc_lane_derived = execution_mask != 0;
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::SMov(dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(format!("{offset:#x}: write to a resource SGPR"));
|
||||
}
|
||||
let value = read_s(src)?;
|
||||
sgpr[dst as usize] = Some(value);
|
||||
}
|
||||
Insn::SCmpEq(a, b) => {
|
||||
scc = Some(read_s(a)? == read_s(b)?);
|
||||
}
|
||||
Insn::SAlu(opcode, dst, a, b) => {
|
||||
if dst < 8 {
|
||||
return Err(format!("{offset:#x}: write to a resource SGPR"));
|
||||
}
|
||||
let (a, b) = (read_s(a)?, read_s(b)?);
|
||||
let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"));
|
||||
let (value, flag) = match opcode {
|
||||
0 => ripple(a, b, false),
|
||||
// RDNA 2 ISA guide 12.1: signed overflow from the sign bits,
|
||||
// add: S0[31] == S1[31] != D[31]; subtract: S0[31] != S1[31] != D[31].
|
||||
2 | 3 => {
|
||||
let value = if opcode == 2 {
|
||||
ripple(a, b, false).0
|
||||
} else {
|
||||
ripple(a, !b, true).0
|
||||
};
|
||||
let sign = |word: u32| word & 0x8000_0000 != 0;
|
||||
let same = sign(a) == sign(b);
|
||||
let overflow =
|
||||
(if opcode == 2 { same } else { !same }) && sign(a) != sign(value);
|
||||
(value, overflow)
|
||||
}
|
||||
4 => ripple(a, b, carry_in()?),
|
||||
// a - b - borrow = a + !b + (1 - borrow); borrow-out = !carry-out.
|
||||
1 | 5 => {
|
||||
let borrow = opcode == 5 && carry_in()?;
|
||||
let (value, carry) = ripple(a, !b, !borrow);
|
||||
(value, !carry)
|
||||
}
|
||||
_ => {
|
||||
let mut value = 0;
|
||||
for bit in 0..32 {
|
||||
let (x, y) = ((a >> bit) & 1 == 1, (b >> bit) & 1 == 1);
|
||||
let set = match opcode {
|
||||
14 => x && y,
|
||||
16 => x || y,
|
||||
_ => x != y,
|
||||
};
|
||||
value |= u32::from(set) << bit;
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
} else {
|
||||
read_s(&sgpr, src).map(|value| {
|
||||
sgpr[dst as usize] = Some(value);
|
||||
if dst == 106 {
|
||||
vcc_lane_derived = false;
|
||||
}
|
||||
(value, value != 0)
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SCmpEq(a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
read_s(&sgpr, b).map(|b| {
|
||||
scc = Some(a == b);
|
||||
None
|
||||
})
|
||||
}),
|
||||
Insn::SAlu(opcode, dst, a, b) => {
|
||||
scalar_alu(&mut sgpr, &mut scc, (opcode, dst, a, b), offset).map(|()| None)
|
||||
}
|
||||
Insn::BranchScc0(target) => scc
|
||||
.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))
|
||||
.and_then(|condition| {
|
||||
if condition {
|
||||
Ok(None)
|
||||
} else {
|
||||
index_of(program, target, offset).map(Some)
|
||||
}
|
||||
};
|
||||
sgpr[dst as usize] = Some(value);
|
||||
scc = Some(flag);
|
||||
}
|
||||
Insn::BranchScc0(target) => {
|
||||
let condition = scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))?;
|
||||
if !condition {
|
||||
pc = index_of(program, target, offset)?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}),
|
||||
Insn::BranchMaskZero { target, register } => {
|
||||
if sgpr[register].ok_or_else(|| format!("{offset:#x}: uninitialized mask"))? == 0 {
|
||||
pc = index_of(program, target, offset)?;
|
||||
continue;
|
||||
if register == 106 && vcc_lane_derived {
|
||||
let live = lanes.iter().find(|lane| lane.error.is_none()).unwrap();
|
||||
check_runtime_region(program, pc, target, live, &sgpr, execution_mask, offset)
|
||||
.and_then(|()| {
|
||||
if sgpr[106] == Some(0) {
|
||||
index_of(program, target, offset).map(Some)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
sgpr[register]
|
||||
.ok_or_else(|| format!("{offset:#x}: uninitialized mask"))
|
||||
.and_then(|mask| {
|
||||
if mask == 0 {
|
||||
index_of(program, target, offset).map(Some)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::Branch(target) => {
|
||||
pc = index_of(program, target, offset)?;
|
||||
continue;
|
||||
}
|
||||
Insn::End => {
|
||||
if pending_read.is_some() || pending_write.is_some() {
|
||||
return Err(format!("{offset:#x}: outstanding transfer at end"));
|
||||
Insn::Branch(target) => index_of(program, target, offset).map(Some),
|
||||
_ => {
|
||||
for (lane_index, lane) in lanes.iter_mut().enumerate() {
|
||||
if lane.error.is_none()
|
||||
&& let Err(error) =
|
||||
lane_step(lane, &sgpr, execution_mask, insn, offset, lane_index)
|
||||
{
|
||||
lane.error = Some(error);
|
||||
}
|
||||
}
|
||||
return written.ok_or_else(|| format!("{offset:#x}: missing output store"));
|
||||
Ok(None)
|
||||
}
|
||||
};
|
||||
match scalar {
|
||||
Ok(Some(next)) => pc = next,
|
||||
Ok(None) => pc += 1,
|
||||
Err(error) => return Err(wave_error(&mut lanes, error)),
|
||||
}
|
||||
pc += 1;
|
||||
}
|
||||
Err("stream ended without s_endpgm".to_string())
|
||||
Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string()))
|
||||
}
|
||||
|
||||
fn scalar_alu(
|
||||
sgpr: &mut [Option<u32>; 128],
|
||||
scc: &mut Option<bool>,
|
||||
(opcode, dst, a, b): (u32, u8, Src, Src),
|
||||
offset: usize,
|
||||
) -> Result<(), String> {
|
||||
if dst < 8 {
|
||||
return Err(format!("{offset:#x}: write to a resource SGPR"));
|
||||
}
|
||||
let read = |src: Src| match src {
|
||||
Src::Imm(value) => Ok(value),
|
||||
Src::Reg(reg) => {
|
||||
sgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))
|
||||
}
|
||||
};
|
||||
let (a, b) = (read(a)?, read(b)?);
|
||||
let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"));
|
||||
let (value, flag) = match opcode {
|
||||
0 => ripple(a, b, false),
|
||||
// RDNA 2 ISA guide 12.1: signed overflow from the sign bits,
|
||||
// add: S0[31] == S1[31] != D[31]; subtract: S0[31] != S1[31] != D[31].
|
||||
2 | 3 => {
|
||||
let value = if opcode == 2 {
|
||||
ripple(a, b, false).0
|
||||
} else {
|
||||
ripple(a, !b, true).0
|
||||
};
|
||||
let sign = |word: u32| word & 0x8000_0000 != 0;
|
||||
let same = sign(a) == sign(b);
|
||||
let overflow = (if opcode == 2 { same } else { !same }) && sign(a) != sign(value);
|
||||
(value, overflow)
|
||||
}
|
||||
4 => ripple(a, b, carry_in()?),
|
||||
// a - b - borrow = a + !b + (1 - borrow); borrow-out = !carry-out.
|
||||
1 | 5 => {
|
||||
let borrow = opcode == 5 && carry_in()?;
|
||||
let (value, carry) = ripple(a, !b, !borrow);
|
||||
(value, !carry)
|
||||
}
|
||||
_ => {
|
||||
let mut value = 0;
|
||||
for bit in 0..32 {
|
||||
let (x, y) = ((a >> bit) & 1 == 1, (b >> bit) & 1 == 1);
|
||||
let set = match opcode {
|
||||
14 => x && y,
|
||||
16 => x || y,
|
||||
_ => x != y,
|
||||
};
|
||||
value |= u32::from(set) << bit;
|
||||
}
|
||||
(value, value != 0)
|
||||
}
|
||||
};
|
||||
sgpr[dst as usize] = Some(value);
|
||||
*scc = Some(flag);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
}
|
||||
if lane.pending_read == Some(reg) {
|
||||
return Err(format!("{offset:#x}: read before load wait"));
|
||||
}
|
||||
lane.vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
|
||||
}
|
||||
|
||||
/// Evaluate one VOPC compare for the whole wave and return the new VCC_LO.
|
||||
fn compare(
|
||||
lanes: &[Lane],
|
||||
sgpr: &[Option<u32>; 128],
|
||||
execution_mask: u32,
|
||||
(relation, signed, src0, src1): (u8, bool, CmpSrc, u8),
|
||||
offset: usize,
|
||||
) -> Result<u32, String> {
|
||||
if execution_mask == 0 {
|
||||
// Encoding already validated; nothing is read (contract 5).
|
||||
return Ok(0);
|
||||
}
|
||||
let scalar_src0 = match src0 {
|
||||
CmpSrc::Sgpr(reg) => {
|
||||
Some(sgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))?)
|
||||
}
|
||||
CmpSrc::Vcc => Some(sgpr[106].ok_or_else(|| format!("{offset:#x}: uninitialized vcc_lo"))?),
|
||||
CmpSrc::Imm(value) => Some(value),
|
||||
CmpSrc::Vgpr(_) => None,
|
||||
};
|
||||
// VGPR readiness is wave-uniform; validate it on every existing lane so
|
||||
// acceptance does not depend on which lanes are active.
|
||||
for lane in lanes {
|
||||
if let CmpSrc::Vgpr(reg) = src0 {
|
||||
read_vgpr(lane, reg, offset)?;
|
||||
}
|
||||
read_vgpr(lane, src1, offset)?;
|
||||
}
|
||||
let mut mask = 0u32;
|
||||
for (n, lane) in lanes.iter().enumerate() {
|
||||
if (execution_mask >> n) & 1 == 0 {
|
||||
continue;
|
||||
}
|
||||
let a = match (scalar_src0, src0) {
|
||||
(Some(value), _) => value,
|
||||
(None, CmpSrc::Vgpr(reg)) => read_vgpr(lane, reg, offset)?,
|
||||
(None, _) => unreachable!(),
|
||||
};
|
||||
let b = read_vgpr(lane, src1, offset)?;
|
||||
// Signed order equals unsigned order after flipping the sign bit.
|
||||
let (a, b) = if signed {
|
||||
(a ^ 0x8000_0000, b ^ 0x8000_0000)
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
let pass = match relation {
|
||||
1 => a < b,
|
||||
2 => a == b,
|
||||
3 => a <= b,
|
||||
4 => a > b,
|
||||
5 => a != b,
|
||||
_ => a >= b,
|
||||
};
|
||||
mask |= u32::from(pass) << n;
|
||||
}
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
/// Static acceptance of the region skipped by a runtime `s_cbranch_vccz`
|
||||
/// (contract 6), independent of lane data, EXEC and the branch outcome.
|
||||
fn check_runtime_region(
|
||||
program: &[(usize, Insn)],
|
||||
pc: usize,
|
||||
target: usize,
|
||||
lane: &Lane,
|
||||
sgpr: &[Option<u32>; 128],
|
||||
execution_mask: u32,
|
||||
offset: usize,
|
||||
) -> Result<(), String> {
|
||||
// Contract 6 forbids an outstanding load; a pending store is waited for later.
|
||||
if lane.pending_read.is_some() {
|
||||
return Err(format!("{offset:#x}: load outstanding at a runtime branch"));
|
||||
}
|
||||
let end = index_of(program, target, offset)?;
|
||||
for &(at, insn) in &program[pc + 1..end] {
|
||||
// (destination, VGPR sources, SGPR source)
|
||||
let (dst, vgprs, scalar): (u8, Vec<u8>, Option<u8>) = match insn {
|
||||
Insn::VMov(dst, Src::Reg(reg)) => (dst, vec![reg], None),
|
||||
Insn::VMov(dst, Src::Imm(_)) => (dst, vec![], None),
|
||||
Insn::VMovFromSgpr(dst, src) => (dst, vec![], Some(src)),
|
||||
Insn::VMovFromVcc(dst) => (dst, vec![], Some(106)),
|
||||
Insn::VAddNc(dst, a, b)
|
||||
| Insn::VAnd(dst, a, b)
|
||||
| Insn::VOr(dst, a, b)
|
||||
| Insn::VXor(dst, a, b)
|
||||
| Insn::VShiftLeft(dst, a, b)
|
||||
| Insn::VShiftRight(dst, a, b)
|
||||
| Insn::VShiftRightArithmetic(dst, a, b) => (dst, vec![a, b], None),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{at:#x}: instruction not allowed in a runtime branch region"
|
||||
));
|
||||
}
|
||||
};
|
||||
if dst == 0 || lane.vgpr[dst as usize].is_none() {
|
||||
return Err(format!(
|
||||
"{at:#x}: runtime branch region writes an uninitialized VGPR"
|
||||
));
|
||||
}
|
||||
// Sources are read only when some lane executes (contract 6).
|
||||
if execution_mask == 0 {
|
||||
continue;
|
||||
}
|
||||
for reg in vgprs {
|
||||
read_vgpr(lane, reg, at)?;
|
||||
}
|
||||
if let Some(reg) = scalar {
|
||||
sgpr[reg as usize].ok_or_else(|| format!("{at:#x}: uninitialized s{reg}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One per-lane vector, memory or wait instruction; behaviour and errors match
|
||||
/// the former independent per-lane interpreter.
|
||||
fn lane_step(
|
||||
lane: &mut Lane,
|
||||
sgpr: &[Option<u32>; 128],
|
||||
execution_mask: u32,
|
||||
insn: Insn,
|
||||
offset: usize,
|
||||
lane_index: usize,
|
||||
) -> Result<(), String> {
|
||||
let read_s = |reg: u8| -> Result<u32, String> {
|
||||
sgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))
|
||||
};
|
||||
let read_vcc = || sgpr[106].ok_or_else(|| format!("{offset:#x}: uninitialized vcc_lo"));
|
||||
if execution_mask.count_ones() < 32 {
|
||||
match insn {
|
||||
Insn::Load(_) | Insn::Store(_) => {
|
||||
return Err(format!(
|
||||
"{offset:#x}: incomplete EXEC on a buffer instruction"
|
||||
));
|
||||
}
|
||||
Insn::VMov(dst, _)
|
||||
| Insn::VMovFromSgpr(dst, _)
|
||||
| Insn::VMovFromVcc(dst)
|
||||
| Insn::VAddNc(dst, ..)
|
||||
| Insn::VAnd(dst, ..)
|
||||
| Insn::VOr(dst, ..)
|
||||
| Insn::VXor(dst, ..)
|
||||
| Insn::VShiftLeft(dst, ..)
|
||||
| Insn::VShiftRight(dst, ..)
|
||||
| Insn::VShiftRightArithmetic(dst, ..)
|
||||
| Insn::VAddF(dst, ..)
|
||||
| Insn::VMulF(dst, ..) => {
|
||||
if execution_mask != 0 && lane.vgpr[usize::from(dst)].is_none() {
|
||||
return Err(format!("{offset:#x}: partial EXEC on uninitialized VGPR"));
|
||||
}
|
||||
if execution_mask != 0 {
|
||||
match insn {
|
||||
Insn::VMovFromSgpr(_, src) => {
|
||||
read_s(src)?;
|
||||
}
|
||||
Insn::VMovFromVcc(_) => {
|
||||
read_vcc()?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if (execution_mask.rotate_right(lane_index as u32) & 1) == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let read_v = |reg: u8| read_vgpr(lane, reg, offset);
|
||||
let pending_read = lane.pending_read;
|
||||
let value = match insn {
|
||||
Insn::Load(data) => {
|
||||
if data == 0 || pending_read.is_some() {
|
||||
return Err(format!("{offset:#x}: invalid or overlapping load"));
|
||||
}
|
||||
lane.pending_read = Some(data);
|
||||
return Ok(());
|
||||
}
|
||||
Insn::Store(data) => {
|
||||
let value = read_v(data)?;
|
||||
if lane.pending_write.is_some() || lane.written.is_some() {
|
||||
return Err(format!("{offset:#x}: multiple output writes"));
|
||||
}
|
||||
lane.pending_write = Some(value);
|
||||
return Ok(());
|
||||
}
|
||||
Insn::WaitRead => {
|
||||
if let Some(dst) = lane.pending_read.take() {
|
||||
lane.vgpr[dst as usize] = Some(lane.input);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Insn::WaitWrite => {
|
||||
if let Some(value) = lane.pending_write.take() {
|
||||
lane.written = Some(value);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Insn::VMov(dst, src) => {
|
||||
let value = match src {
|
||||
Src::Imm(value) => value,
|
||||
Src::Reg(reg) => read_v(reg)?,
|
||||
};
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, value)
|
||||
}
|
||||
Insn::VMovFromSgpr(dst, src) => {
|
||||
let value = read_s(src)?;
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, value)
|
||||
}
|
||||
Insn::VMovFromVcc(dst) => {
|
||||
let value = read_vcc()?;
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, value)
|
||||
}
|
||||
Insn::VAddNc(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let sum = u64::from(read_v(a)?) + u64::from(read_v(b)?);
|
||||
(dst, sum as u32)
|
||||
}
|
||||
Insn::VAnd(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, read_v(a)? & read_v(b)?)
|
||||
}
|
||||
Insn::VOr(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, read_v(a)? | read_v(b)?)
|
||||
}
|
||||
Insn::VShiftLeft(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let factor = 2_u64.pow(read_v(count)? % 32);
|
||||
let product = u64::from(read_v(value)?) * factor;
|
||||
(dst, (product % (1_u64 << 32)) as u32)
|
||||
}
|
||||
Insn::VShiftRight(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let divisor = 2_u32.pow(read_v(count)? % 32);
|
||||
(dst, read_v(value)? / divisor)
|
||||
}
|
||||
Insn::VShiftRightArithmetic(dst, count, value) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
// Floor division of the sign-extended value, reduced modulo
|
||||
// 2^32. This is arithmetic shift without using `>>`.
|
||||
let shifted =
|
||||
i64::from(read_v(value)? as i32).div_euclid(1_i64 << (read_v(count)? % 32));
|
||||
(dst, shifted.rem_euclid(1_i64 << 32) as u32)
|
||||
}
|
||||
Insn::VXor(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, read_v(a)? ^ read_v(b)?)
|
||||
}
|
||||
Insn::VAddF(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, exact_float(true, read_v(a)?, read_v(b)?, offset)?)
|
||||
}
|
||||
Insn::VMulF(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, exact_float(false, read_v(a)?, read_v(b)?, offset)?)
|
||||
}
|
||||
_ => unreachable!("scalar instruction in lane_step"),
|
||||
};
|
||||
lane.vgpr[value.0 as usize] = Some(value.1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bit-serial addition with carry-in; returns the sum and the carry-out.
|
||||
@@ -426,6 +732,9 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
if selector <= 105 {
|
||||
return Ok((Insn::VMovFromSgpr(dst, selector as u8), 4));
|
||||
}
|
||||
if selector == 106 {
|
||||
return Ok((Insn::VMovFromVcc(dst), 4));
|
||||
}
|
||||
let (src, len) = if selector == 255 {
|
||||
(Src::Imm(word(code, offset + 4)?), 8)
|
||||
} else {
|
||||
@@ -436,6 +745,38 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
};
|
||||
return Ok((Insn::VMov(dst, src), len));
|
||||
}
|
||||
// VOPC: bits 31:25 = 0b0111110, OP 24:17, VSRC1 16:9, SRC0 8:0.
|
||||
if first >> 25 == 0b011_1110 {
|
||||
let opcode = (first >> 17) & 0xff;
|
||||
let (signed, relation) = match opcode {
|
||||
129..=134 => (true, opcode - 128),
|
||||
193..=198 => (false, opcode - 192),
|
||||
_ => return Err(fail("unsupported VOPC opcode")),
|
||||
};
|
||||
let selector = first & 0x1ff;
|
||||
let (src0, len) = match selector {
|
||||
0..=105 => (CmpSrc::Sgpr(selector as u8), 4),
|
||||
106 => (CmpSrc::Vcc, 4),
|
||||
128..=192 => (CmpSrc::Imm(selector - 128), 4),
|
||||
193..=208 => (CmpSrc::Imm(192u32.wrapping_sub(selector)), 4),
|
||||
255 => (
|
||||
CmpSrc::Imm(
|
||||
word(code, offset + 4)
|
||||
.map_err(|_| format!("{offset:#x}: truncated VOPC literal"))?,
|
||||
),
|
||||
8,
|
||||
),
|
||||
256..=511 => (CmpSrc::Vgpr(selector as u8), 4),
|
||||
_ => return Err(fail("bad VOPC source")),
|
||||
};
|
||||
let insn = Insn::VCmp {
|
||||
relation: relation as u8,
|
||||
signed,
|
||||
src0,
|
||||
src1: (first >> 9) as u8,
|
||||
};
|
||||
return Ok((insn, len));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xd525_0000 {
|
||||
let second = word(code, offset + 4)?;
|
||||
let src0 = second & 0x1ff;
|
||||
|
||||
@@ -1044,7 +1044,7 @@ mod review {
|
||||
// v2 reads s9, which is valid, so only the SOP2 word can fail.
|
||||
rejected_at(&sop2_program(alu, result, 1, 2, Some(false)), 0x20);
|
||||
}
|
||||
// v_mov_b32 from VCC_LO stays outside the subset.
|
||||
// v_mov_b32 from VCC_LO before anything wrote VCC_LO.
|
||||
let mut code = sop2_program(&[sop2(0, 10, 8, 9)], 10, 1, 2, Some(false));
|
||||
assert_eq!(code[0x24..0x28], 0x7e04_020a_u32.to_le_bytes());
|
||||
code[0x24] = 106;
|
||||
@@ -1100,4 +1100,596 @@ mod review {
|
||||
vectors.len() + 1
|
||||
);
|
||||
}
|
||||
|
||||
// ---- VOPC integer compares (docs/shaders/vector-compare.md) ----
|
||||
|
||||
const COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare.bin");
|
||||
const COMPARE_VALUES: [u32; 10] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fff0,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x0f0f_0f0f,
|
||||
];
|
||||
/// VOPC opcodes 129-134 (`_i32`) and 193-198 (`_u32`), RDNA 2 XML / ISA Table 61.
|
||||
const COMPARE_OPCODES: [u32; 12] = [129, 130, 131, 132, 133, 134, 193, 194, 195, 196, 197, 198];
|
||||
|
||||
/// The test from the opcode's definition: offsets LT, EQ, LE, GT, NE, GE;
|
||||
/// `_i32` compares two's-complement values, `_u32` the unsigned values.
|
||||
fn compare_holds(opcode: u32, s0: u32, s1: u32) -> bool {
|
||||
let (a, b) = if opcode < 192 {
|
||||
(i128::from(s0 as i32), i128::from(s1 as i32))
|
||||
} else {
|
||||
(i128::from(s0), i128::from(s1))
|
||||
};
|
||||
let difference = a - b;
|
||||
match opcode & 0x3f {
|
||||
1 => difference < 0,
|
||||
2 => difference == 0,
|
||||
3 => difference <= 0,
|
||||
4 => difference > 0,
|
||||
5 => difference != 0,
|
||||
6 => difference >= 0,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// VCC_LO for one wave: bit n set iff lane n exists, EXEC[n] and the test pass.
|
||||
fn wave_mask(wave: &[u32], exec: u32, test: impl Fn(u32) -> bool) -> u32 {
|
||||
wave.iter()
|
||||
.enumerate()
|
||||
.filter(|&(lane, &x)| exec >> lane & 1 == 1 && test(x))
|
||||
.fold(0, |mask, (lane, _)| mask | 1 << lane)
|
||||
}
|
||||
|
||||
/// VOPC word: encoding 0b0111110, OP 17-24, VSRC1 9-16, SRC0 0-8.
|
||||
fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
/// The fixture's result, written from its listing with explicit relations.
|
||||
fn compare_fixture_expected(input: &[u32]) -> Vec<u32> {
|
||||
let mut output = Vec::new();
|
||||
for wave in input.chunks(32) {
|
||||
let full = u32::MAX;
|
||||
let rows: [&dyn Fn(u32) -> bool; 10] = [
|
||||
&|x| (x as i32) < -1,
|
||||
&|x| x != u32::MAX,
|
||||
&|x| x == 0,
|
||||
&|x| x == 0x8000_0000,
|
||||
&|x| x == 0x7fff_ffff,
|
||||
&|x| x >= 0x7fff_ffff,
|
||||
&|x| (x as i32) < -16,
|
||||
&|x| x < 64,
|
||||
&|x| x != 0, // ne_u32 against the zero mask of ne_i32 v1, v1
|
||||
&|x| x == 0x8000_0000 || x == 0x8000_0001,
|
||||
];
|
||||
let folded = rows
|
||||
.iter()
|
||||
.fold(0u32, |acc, test| (acc << 1) ^ wave_mask(wave, full, test));
|
||||
let partial = wave_mask(wave, 0x5555_5555, |x| x >= 0x0f0f_0f0f);
|
||||
let runtime = wave_mask(wave, full, |x| x > 0x0f0f_0f0f);
|
||||
for lane in 0..wave.len() {
|
||||
let v7 = if lane % 2 == 0 { partial } else { 0xa5a5_a5a5 };
|
||||
let mut v2 = folded ^ v7;
|
||||
if runtime != 0 {
|
||||
v2 ^= 0x0f0f_0f0f;
|
||||
}
|
||||
output.push(v2);
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// A boundary wave (branch not taken), a wave of small values (VCC_LO = 0
|
||||
/// at the runtime branch, so it is taken) and a final partial wave.
|
||||
fn compare_fixture_input() -> Vec<u32> {
|
||||
let mut input: Vec<u32> = (0..32)
|
||||
.map(|lane| COMPARE_VALUES[lane % 10] ^ (lane as u32 / 10))
|
||||
.collect();
|
||||
input.extend((0..32).map(|lane| (lane * 0x0101_0101) & 0x0f0f_0f0f));
|
||||
// Its only values above 0x0f0f0f0f are negative as i32.
|
||||
input.extend([
|
||||
0x8000_0000,
|
||||
0,
|
||||
u32::MAX,
|
||||
63,
|
||||
64,
|
||||
1,
|
||||
0xffff_ffef,
|
||||
0x8000_0001,
|
||||
16,
|
||||
]);
|
||||
input
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_fixture_matches_exact_definitions() {
|
||||
let input = compare_fixture_input();
|
||||
let expected = compare_fixture_expected(&input);
|
||||
verify(COMPARE_FIXTURE, &input, Some(&expected));
|
||||
// Both runtime branch outcomes occur in this dispatch.
|
||||
assert_ne!(expected[0] ^ expected[32], 0);
|
||||
let compiled = compile(Architecture::Gfx1030, COMPARE_FIXTURE).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir.matches("wave.mask").count(),
|
||||
13,
|
||||
"{}",
|
||||
compiled.ir
|
||||
);
|
||||
assert!(compiled.ir.contains("branch.vccz"), "{}", compiled.ir);
|
||||
assert!(compiled.ir.contains("join.vccz"), "{}", compiled.ir);
|
||||
// No assumption that a Metal SIMD group or threadgroup is an RDNA wave.
|
||||
assert!(compiled.msl.contains("[[threads_per_grid]]"));
|
||||
for forbidden in ["simd_", "threadgroup", "barrier", "quad_"] {
|
||||
assert!(!compiled.msl.contains(forbidden), "{forbidden}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_fixture_inputs_distinguish_signedness_in_every_ordered_slot() {
|
||||
let input = compare_fixture_input();
|
||||
let expected = compare_fixture_expected(&input);
|
||||
let mut flipped = 0;
|
||||
for offset in (0..COMPARE_FIXTURE.len()).step_by(4) {
|
||||
let word = u32::from_le_bytes(COMPARE_FIXTURE[offset..offset + 4].try_into().unwrap());
|
||||
let opcode = word >> 17 & 0xff;
|
||||
// Ordered relations only; eq and ne do not depend on signedness.
|
||||
if word >> 25 != 0x3e || !matches!(opcode & 0x3f, 1 | 3 | 4 | 6) {
|
||||
continue;
|
||||
}
|
||||
let mut code = COMPARE_FIXTURE.to_vec();
|
||||
code[offset + 2] ^= 0x80; // opcode bit 6: _i32 <-> _u32
|
||||
let changed = xenora_ref::execute(&code, &input).unwrap();
|
||||
assert_ne!(changed, expected, "slot at 0x{offset:x}");
|
||||
assert_eq!(independent_ref::execute(&code, &input).unwrap(), changed);
|
||||
flipped += 1;
|
||||
}
|
||||
assert_eq!(flipped, 9);
|
||||
}
|
||||
|
||||
/// v1 = input, v3 = `b`; vcc_lo = form(v1, v3) or form(v3, v1); output vcc_lo.
|
||||
fn compare_program(opcode: u32, b: u32, swapped: bool) -> Vec<u8> {
|
||||
let compare = if swapped {
|
||||
vopc(opcode, 256 + 3, 1)
|
||||
} else {
|
||||
vopc(opcode, 256 + 1, 3)
|
||||
};
|
||||
words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70, // load v1, wait
|
||||
0x7e06_02ff,
|
||||
b, // v_mov_b32 v3, b
|
||||
compare,
|
||||
0x7e04_026a, // v_mov_b32 v2, vcc_lo
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
])
|
||||
}
|
||||
|
||||
fn compare_lanes() -> Vec<u32> {
|
||||
(0..32).map(|lane| COMPARE_VALUES[lane % 10]).collect()
|
||||
}
|
||||
|
||||
fn compare_vectors() -> Vec<(Vec<u8>, Vec<u32>)> {
|
||||
let input = compare_lanes();
|
||||
let mut vectors = Vec::new();
|
||||
for opcode in COMPARE_OPCODES {
|
||||
for b in COMPARE_VALUES {
|
||||
for swapped in [false, true] {
|
||||
let mask = wave_mask(&input, u32::MAX, |x| {
|
||||
if swapped {
|
||||
compare_holds(opcode, b, x)
|
||||
} else {
|
||||
compare_holds(opcode, x, b)
|
||||
}
|
||||
});
|
||||
vectors.push((compare_program(opcode, b, swapped), vec![mask; 32]));
|
||||
}
|
||||
}
|
||||
}
|
||||
vectors
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_compare_form_matches_definitions_on_boundary_operands() {
|
||||
// Checkpoints derived by hand: 0x80000000 is the least i32, the greatest u32 half.
|
||||
assert!(compare_holds(129, 0x8000_0000, 0x7fff_ffff));
|
||||
assert!(!compare_holds(193, 0x8000_0000, 0x7fff_ffff));
|
||||
assert!(compare_holds(132, 0, u32::MAX) && !compare_holds(196, 0, u32::MAX));
|
||||
assert!(compare_holds(131, 5, 5) && compare_holds(198, 5, 5));
|
||||
let vectors = compare_vectors();
|
||||
assert_eq!(vectors.len(), 12 * 10 * 2);
|
||||
let input = compare_lanes();
|
||||
for (code, expected) in &vectors {
|
||||
verify(code, &input, Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
/// v2 = 0xdeadbeef; EXEC_LO = `exec`; compare v1 < 0x10 (unsigned);
|
||||
/// v2 = vcc_lo under the same EXEC; EXEC_LO = -1.
|
||||
fn partial_compare_program(exec: u32) -> Vec<u8> {
|
||||
words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_02ff,
|
||||
0xdead_beef,
|
||||
0xbefe_03ff,
|
||||
exec,
|
||||
vopc(196, 0x90, 1), // v_cmp_gt_u32_e32 vcc_lo, 16, v1
|
||||
0x7e04_026a,
|
||||
0xbefe_03c1,
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_exec_masks_inactive_lanes_and_keeps_their_destinations() {
|
||||
let input: Vec<u32> = (0..32).collect();
|
||||
for exec in [u32::MAX, 0x5555_5555, 0x8000_8001, 1 << 31] {
|
||||
// Lanes 0-15 hold values below 16 and would all pass.
|
||||
let mask = wave_mask(&input, exec, |x| x < 16);
|
||||
let expected: Vec<u32> = (0..32)
|
||||
.map(|lane| {
|
||||
if exec >> lane & 1 == 1 {
|
||||
mask
|
||||
} else {
|
||||
0xdead_beef
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
verify(&partial_compare_program(exec), &input, Some(&expected));
|
||||
}
|
||||
assert_eq!(wave_mask(&input, 0x5555_5555, |x| x < 16), 0x5555);
|
||||
// Empty EXEC: the compare reads nothing, and the move does not run either.
|
||||
verify(
|
||||
&partial_compare_program(0),
|
||||
&input,
|
||||
Some(&[0xdead_beef; 32]),
|
||||
);
|
||||
}
|
||||
|
||||
/// vcc_lo = -1; EXEC_LO = 0; compare; s_cbranch_vccz over a write; EXEC_LO = -1;
|
||||
/// v2 = vcc_lo ^ marker. Hardware writes VCC_LO = 0 even with empty EXEC.
|
||||
fn empty_exec_program(src0: u32) -> Vec<u8> {
|
||||
words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e06_0281, // v_mov_b32 v3, 1
|
||||
0xbeea_03c1, // s_mov_b32 vcc_lo, -1
|
||||
0xbefe_0380, // s_mov_b32 exec_lo, 0
|
||||
vopc(194, src0, 1),
|
||||
0xbf86_0001, // s_cbranch_vccz (known VCC_LO = 0: taken)
|
||||
0xbeea_03c1, // s_mov_b32 vcc_lo, -1 on the wrong path
|
||||
0xbefe_03c1,
|
||||
0x7e04_026a, // v_mov_b32 v2, vcc_lo
|
||||
0x3a04_0702, // v_xor_b32 v2, v2, v3
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_exec_clears_a_stale_mask_without_reading_sources() {
|
||||
let input = [7, 0, u32::MAX];
|
||||
// v1 == v1 everywhere: only the EXEC rule makes the mask zero.
|
||||
verify(&empty_exec_program(256 + 1), &input, Some(&[1; 3]));
|
||||
// Under empty EXEC an unknown SGPR, v9 and even vcc_lo-from-a-compare are not read.
|
||||
verify(&empty_exec_program(20), &input, Some(&[1; 3]));
|
||||
verify(&empty_exec_program(256 + 9), &input, Some(&[1; 3]));
|
||||
let ir = compile(Architecture::Gfx1030, &empty_exec_program(256 + 1))
|
||||
.unwrap()
|
||||
.ir;
|
||||
assert!(
|
||||
!ir.contains("wave.mask") && ir.contains("taken=true"),
|
||||
"{ir}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Compare v1 != 0 (VCC lane-derived), then `s_cbranch_vccz` over `region`.
|
||||
fn runtime_branch_program(region: &[u32], before_branch: &[u32]) -> Vec<u8> {
|
||||
let mut code = vec![
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_0281, // v_mov_b32 v2, 1
|
||||
0x7e06_0282, // v_mov_b32 v3, 2
|
||||
0x7d8a_0280, // v_cmp_ne_u32_e32 vcc_lo, 0, v1
|
||||
];
|
||||
code.extend(before_branch);
|
||||
code.push(0xbf86_0000 | region.len() as u32);
|
||||
code.extend(region);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// Not taken: v2 = (1 + 2) ^ vcc_lo, v3 = vcc_lo. Taken: v2 = 1.
|
||||
const RUNTIME_REGION: [u32; 4] = [
|
||||
0xd525_0002,
|
||||
0x0202_0702, // v_add_nc_u32_e64 v2, v2, v3
|
||||
0x7e06_026a, // v_mov_b32 v3, vcc_lo
|
||||
0x3a04_0702, // v_xor_b32 v2, v2, v3
|
||||
];
|
||||
|
||||
fn runtime_expected(input: &[u32]) -> Vec<u32> {
|
||||
input
|
||||
.chunks(32)
|
||||
.flat_map(|wave| {
|
||||
let mask = wave_mask(wave, u32::MAX, |x| x != 0);
|
||||
let value = if mask == 0 { 1 } else { 3 ^ mask };
|
||||
vec![value; wave.len()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn runtime_input() -> Vec<u32> {
|
||||
// Wave 0 all zero (taken), wave 1 one nonzero lane, wave 2 partial and zero.
|
||||
let mut input = vec![0; 32];
|
||||
input.extend((0..32).map(|lane| u32::from(lane == 17) * 0x8000_0000));
|
||||
input.extend([0; 5]);
|
||||
input
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_vccz_takes_each_edge_from_lane_data_in_one_dispatch() {
|
||||
assert_eq!(vopc(197, 0x80, 1), 0x7d8a_0280);
|
||||
let code = runtime_branch_program(&RUNTIME_REGION, &[]);
|
||||
let mut input = runtime_input();
|
||||
let expected = runtime_expected(&input);
|
||||
assert_eq!(expected[0], 1);
|
||||
assert_eq!(expected[32], 3 ^ 1 << 17);
|
||||
verify(&code, &input, Some(&expected));
|
||||
// One nonzero lane in the final partial wave flips only that wave's edge.
|
||||
input[64 + 4] = 9;
|
||||
let expected = runtime_expected(&input);
|
||||
assert_eq!(expected[64], 3 ^ 1 << 4);
|
||||
verify(&code, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
assert!(compiled.ir.contains("branch.vccz"), "{}", compiled.ir);
|
||||
assert_eq!(
|
||||
compiled.ir.matches("join.vccz").count(),
|
||||
2,
|
||||
"{}",
|
||||
compiled.ir
|
||||
);
|
||||
// A branch on a known VCC_LO is still resolved during translation.
|
||||
let known = runtime_branch_program(&RUNTIME_REGION, &[0xbeea_0380]); // vcc_lo = 0
|
||||
verify(&known, &input, Some(&vec![1; input.len()]));
|
||||
assert!(
|
||||
!compile(Architecture::Gfx1030, &known)
|
||||
.unwrap()
|
||||
.ir
|
||||
.contains("branch.vccz")
|
||||
);
|
||||
}
|
||||
|
||||
/// load v1; v2 = 1; compare v1 != 0; `middle`; v2 = new vcc_lo; store v2.
|
||||
fn mask_chain_program(middle: &[u32]) -> Vec<u8> {
|
||||
let mut code = vec![
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_0281, // v_mov_b32 v2, 1
|
||||
0x7d8a_0280, // v_cmp_ne_u32_e32 vcc_lo, 0, v1
|
||||
];
|
||||
code.extend(middle);
|
||||
code.extend([
|
||||
0x7e04_026a,
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_masks_feed_later_compares_and_lane_varying_joins() {
|
||||
// v_cmp_eq_u32 vcc_lo, vcc_lo, v1: lane n tests old_mask == x_n.
|
||||
let code = mask_chain_program(&[vopc(194, 106, 1)]);
|
||||
let input = [1, 0, 0, 0];
|
||||
// old mask = 0b0001; only lane 0 holds 1 == old mask.
|
||||
verify(&code, &input, Some(&[1; 4]));
|
||||
let input = [0, 2, 3, 0];
|
||||
// old mask = 0b0110 = 6; no lane holds 6.
|
||||
verify(&code, &input, Some(&[0; 4]));
|
||||
let input = [0, 6, 6, 0];
|
||||
verify(&code, &input, Some(&[6; 4]));
|
||||
// A join whose value differs per lane feeds a compare: region v2 = v1,
|
||||
// then v_cmp_eq_u32 vcc_lo, 0, v2.
|
||||
let code = mask_chain_program(&[0xbf86_0001, 0x7e04_0301, vopc(194, 0x80, 2)]);
|
||||
// Not taken (lane 0 nonzero): v2 = x, so the mask marks the zero lanes.
|
||||
verify(&code, &[1, 0, 5, 0], Some(&[0b1010; 4]));
|
||||
// Taken (all zero): v2 keeps 1 everywhere, so no lane is zero.
|
||||
verify(&code, &[0, 0, 0, 0], Some(&[0; 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_regions_follow_exec_store_and_immediate_rules() {
|
||||
// Under empty EXEC a region source is not read, so v9 need not be ready.
|
||||
let code = {
|
||||
let mut words_ = vec![
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_0281, // v_mov_b32 v2, 1
|
||||
0x7d8a_0280, // v_cmp_ne_u32_e32 vcc_lo, 0, v1
|
||||
0xbefe_0380, // s_mov_b32 exec_lo, 0
|
||||
0xbf86_0001, // runtime s_cbranch_vccz over one word
|
||||
0x7e04_0309, // v_mov_b32 v2, v9 (v9 uninitialized, not read)
|
||||
0xbefe_03c1, // s_mov_b32 exec_lo, -1
|
||||
];
|
||||
words_.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&words_)
|
||||
};
|
||||
verify(&code, &[0], Some(&[1]));
|
||||
verify(&code, &[1], Some(&[1]));
|
||||
// A store outstanding at the branch is allowed; its wait follows the target.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_0281, // v_mov_b32 v2, 1
|
||||
0x7d8a_0280, // v_cmp_ne_u32_e32 vcc_lo, 0, v1
|
||||
0xe070_2000,
|
||||
0x8001_0200, // store v2
|
||||
0xbf86_0001,
|
||||
0x7e04_0282, // v_mov_b32 v2, 2 (after the store: not observed)
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
verify(&code, &[0, 7], Some(&[1, 1]));
|
||||
// The inline +1.0f bit pattern is an immediate like any other in a region,
|
||||
// and an exact FP32 add after the join is accepted when both edges allow it.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_02f2, // v_mov_b32 v2, 1.0
|
||||
0x7d8a_0280, // v_cmp_ne_u32_e32 vcc_lo, 0, v1
|
||||
0xbf86_0002,
|
||||
0x7e04_02ff,
|
||||
0x4000_0000, // v_mov_b32 v2, 2.0
|
||||
0x0604_0502, // v_add_f32 v2, v2, v2
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
verify(&code, &[0], Some(&[0x4000_0000]));
|
||||
verify(&code, &[1], Some(&[0x4080_0000]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compares_and_runtime_branches_reject_outside_the_contract() {
|
||||
let base = compare_program(129, 5, false);
|
||||
// The VOPC word is at 0x14; change only its SRC0 selector.
|
||||
let with_src0 = |selector: u32| {
|
||||
let mut code = base.clone();
|
||||
let word = vopc(129, selector, 3);
|
||||
code[0x14..0x18].copy_from_slice(&word.to_le_bytes());
|
||||
code
|
||||
};
|
||||
for selector in [
|
||||
107, 124, 125, 126, 127, 233, 240, 242, 249, 250, 251, 253, 254,
|
||||
] {
|
||||
rejected_at(&with_src0(selector), 0x14);
|
||||
}
|
||||
rejected_at(&with_src0(20), 0x14); // s20 has no known value
|
||||
rejected_at(&with_src0(106), 0x14); // vcc_lo uninitialized
|
||||
rejected_at(&with_src0(256 + 9), 0x14); // v9 uninitialized
|
||||
rejected_at(&with_src0(256), 0x14); // v0 is the resource index
|
||||
// VSRC1 uninitialized.
|
||||
let mut code = base.clone();
|
||||
code[0x14..0x18].copy_from_slice(&vopc(129, 256 + 1, 9).to_le_bytes());
|
||||
rejected_at(&code, 0x14);
|
||||
// v_cmpx (writes EXEC), F and T forms, and the VOP3 encoding.
|
||||
for word in [vopc(210, 257, 3), vopc(128, 257, 3), vopc(135, 257, 3)] {
|
||||
let mut code = base.clone();
|
||||
code[0x14..0x18].copy_from_slice(&word.to_le_bytes());
|
||||
rejected_at(&code, 0x14);
|
||||
}
|
||||
let mut e64 = base[..0x14].to_vec();
|
||||
e64.extend(words(&[0xd481_006a, 0x0002_0701]));
|
||||
e64.extend_from_slice(&base[0x18..]);
|
||||
rejected_at(&e64, 0x14);
|
||||
|
||||
// Runtime s_cbranch_vccz at 0x18; the region starts at 0x1c.
|
||||
let reject_region = |region: &[u32], at: usize| {
|
||||
rejected_at_with(&runtime_branch_program(region, &[]), at, &[0, 1]);
|
||||
};
|
||||
reject_region(&[0xbe88_0380], 0x1c); // s_mov_b32 s8, 0
|
||||
reject_region(&[0x0604_0702], 0x1c); // v_add_f32 v2, v2, v3
|
||||
reject_region(&[0x7c02_0302], 0x1c); // v_cmp_lt_i32 in the region
|
||||
reject_region(&[0xbf82_0000], 0x1c); // s_branch in the region
|
||||
reject_region(&[0x7e0a_0281], 0x1c); // v_mov v5, 1: v5 not initialized
|
||||
reject_region(&[0x7e04_0281, 0x6a04_0b02], 0x20); // second word reads v5
|
||||
reject_region(&[0x7e04_0214], 0x1c); // v_mov v2, s20 (unknown)
|
||||
reject_region(&[0xe070_2000, 0x8001_0200], 0x1c); // store in the region
|
||||
// A load outstanding at the branch (now at 0x20).
|
||||
rejected_at_with(
|
||||
&runtime_branch_program(&RUNTIME_REGION, &[0xe030_2000, 0x8000_0500]),
|
||||
0x20,
|
||||
&[0, 1],
|
||||
);
|
||||
// The same checks hold under empty EXEC and when the branch is taken
|
||||
// (input 0: VCC_LO = 0): s_mov_b32 exec_lo, 0 precedes the branch at 0x1c.
|
||||
let code = runtime_branch_program(&[0x7e0a_0281], &[0xbefe_0380]);
|
||||
rejected_at_with(&code, 0x20, &[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn vector_compare_native_metal_known_answers() {
|
||||
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 metal = xenora_metal::NativeCompute::new().unwrap();
|
||||
let run = |code: &[u8], input: &[u32]| {
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
metal
|
||||
.run_words(&compiled.msl, xenora_shader::ENTRY_POINT, input)
|
||||
.unwrap()
|
||||
};
|
||||
let mut programs = 0;
|
||||
let input = compare_fixture_input();
|
||||
assert_eq!(
|
||||
run(COMPARE_FIXTURE, &input),
|
||||
compare_fixture_expected(&input)
|
||||
);
|
||||
programs += 1;
|
||||
let lanes = compare_lanes();
|
||||
for (code, expected) in compare_vectors() {
|
||||
assert_eq!(run(&code, &lanes), expected);
|
||||
programs += 1;
|
||||
}
|
||||
let counting: Vec<u32> = (0..32).collect();
|
||||
for exec in [u32::MAX, 0x5555_5555, 0x8000_8001, 1 << 31, 0] {
|
||||
let mask = wave_mask(&counting, exec, |x| x < 16);
|
||||
let expected: Vec<u32> = (0..32)
|
||||
.map(|lane| {
|
||||
if exec >> lane & 1 == 1 {
|
||||
mask
|
||||
} else {
|
||||
0xdead_beef
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(run(&partial_compare_program(exec), &counting), expected);
|
||||
programs += 1;
|
||||
}
|
||||
for src0 in [256 + 1, 20, 256 + 9] {
|
||||
assert_eq!(run(&empty_exec_program(src0), &[7, 0, u32::MAX]), [1; 3]);
|
||||
programs += 1;
|
||||
}
|
||||
let code = runtime_branch_program(&RUNTIME_REGION, &[]);
|
||||
let mut input = runtime_input();
|
||||
assert_eq!(run(&code, &input), runtime_expected(&input));
|
||||
input[64 + 4] = 9;
|
||||
assert_eq!(run(&code, &input), runtime_expected(&input));
|
||||
programs += 1;
|
||||
let chain = mask_chain_program(&[vopc(194, 106, 1)]);
|
||||
for (input, mask) in [([1, 0, 0, 0], 1), ([0, 2, 3, 0], 0), ([0, 6, 6, 0], 6)] {
|
||||
assert_eq!(run(&chain, &input), [mask; 4]);
|
||||
}
|
||||
let join = mask_chain_program(&[0xbf86_0001, 0x7e04_0301, vopc(194, 0x80, 2)]);
|
||||
assert_eq!(run(&join, &[1, 0, 5, 0]), [0b1010; 4]);
|
||||
assert_eq!(run(&join, &[0, 0, 0, 0]), [0; 4]);
|
||||
programs += 2;
|
||||
eprintln!("{programs} VOPC programs matched on native Metal");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user