From 947d6e4eafaaa3342182a653f23e37570dd7d7ef Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:41:08 -0600 Subject: [PATCH] isa, decoder, shader: the six VOP1 integer forms through the semantic registry (#215) The B3 oracle (#309) checks v_not_b32, v_bfrev_b32, v_ffbh_u32, v_ffbl_b32, v_ffbh_i32 and v_swap_b32 against the guide on both CPU interpreters, but its native Metal half was skipped because the translator did not accept the forms. This adds the VOP1 registry file and operand rule, decoder dispatch, IR and MSL lowering (v_swap_b32 writes both VGPRs, each merged under EXEC), fixture and goldens, and removes the oracle's skip from scripts/test-gpu.sh. A new CPU test checks that the compiler accepts every case of the oracle and rejects each of its rejections at the same word. v_mov_b32 stays hand-written. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 23 +- crates/decoder/tests/gfx1030.rs | 23 +- crates/isa/generate_semantics.py | 88 ++- crates/isa/semantics/rdna2.toml | 3 +- crates/isa/semantics/rdna2/vop1.toml | 123 ++++ crates/isa/src/lib.rs | 17 +- crates/isa/src/semantics.rs | 21 + crates/isa/src/semantics_gen.rs | 851 +++++++++++++++++++++++-- crates/shader/src/lib.rs | 106 ++- crates/shader/tests/compiler.rs | 14 + docs/README.md | 1 + docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 6 + docs/shaders/semantic-coverage.md | 6 +- docs/shaders/semantic-registry.md | 2 +- docs/shaders/vector-unary.md | 35 + docs/status.toml | 72 +++ fixtures/golden/vector-unary.ir | 12 + fixtures/golden/vector-unary.metal | 19 + fixtures/rdna2/vector-unary.bin | Bin 0 -> 76 bytes fixtures/rdna2/vector-unary.s | 21 + scripts/assemble-fixture.sh | 2 +- scripts/test-gpu.sh | 3 +- tests/validation/tests/vop1_integer.rs | 26 +- 25 files changed, 1392 insertions(+), 91 deletions(-) create mode 100644 crates/isa/semantics/rdna2/vop1.toml create mode 100644 docs/shaders/vector-unary.md create mode 100644 fixtures/golden/vector-unary.ir create mode 100644 fixtures/golden/vector-unary.metal create mode 100644 fixtures/rdna2/vector-unary.bin create mode 100644 fixtures/rdna2/vector-unary.s diff --git a/CHANGELOG.md b/CHANGELOG.md index 992036a..9ae16c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending. - Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215). - Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215. - Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215). diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 16ce957..01c9df5 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -5,7 +5,7 @@ use std::fmt; pub use xenora_isa::{ Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, - VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, + VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp, VectorUnaryOp, }; use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, @@ -14,8 +14,8 @@ use xenora_isa::{ }; use xenora_isa::meta::EncodingFamily; -pub use xenora_isa::semantics::VectorBinary; use xenora_isa::semantics::{FORM_IDS, OperandRule}; +pub use xenora_isa::semantics::{VectorBinary, VectorUnary}; /// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one /// operand combination: the hand-written forms below followed by every form of @@ -317,6 +317,23 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if V_MOV_B32.matches(first) { return move_b32(first, bytes); } + // AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8. + if let Some(op) = VectorUnaryOp::from_word(first) { + let dst = (first >> 17) as u8; + let (src, len) = vector_src0(first, bytes, op.assembly_name())?; + return Ok((Instruction::VectorUnary { op, dst, src }, len)); + } + if let Some(op) = VectorSwapOp::from_word(first) { + if first & 0x100 == 0 { + return Err(unsupported( + op.assembly_name(), + "expected a VGPR SRC0 for writeback", + )); + } + let dst = (first >> 17) as u8; + let src = first as u8; + return Ok((Instruction::VectorSwap { op, dst, src }, 4)); + } if let Some(op) = VectorCompareOp::from_word(first) { return vector_compare(op, first, bytes); } @@ -664,7 +681,7 @@ fn vector_compare( Ok((Instruction::VectorCompare { op, src0, src1 }, len)) } -/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an +/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an /// inline integer -16..64 or a literal word; everything else is unsupported. fn vector_src0( first: u32, diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 1c9ee88..4de6637 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -5,12 +5,12 @@ use std::process::{Command, Stdio}; use xenora_decoder::{ Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, - VectorSource, decode, decode_at, + VectorSource, VectorUnaryOp, decode, decode_at, }; use xenora_isa::semantics::Signedness; use xenora_ref::{ BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary, - Source, VectorAlu, VectorInteger, + Source, VectorAlu, VectorInteger, VectorUnary, }; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); @@ -330,6 +330,22 @@ fn reference_op(instruction: Instruction) -> Op { src: VectorSource::Scalar(src), } => Op::MoveScalar(dst, src), Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)), + Instruction::VectorUnary { op, dst, src } => Op::VectorUnary( + match op { + VectorUnaryOp::NotB32 => VectorUnary::Not, + VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits, + VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb, + VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb, + VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange, + }, + dst, + match src { + VectorSource::Register(reg) => CompareSource::Vector(reg), + VectorSource::Scalar(reg) => CompareSource::Scalar(reg), + VectorSource::Immediate(bits) => CompareSource::Immediate(bits), + }, + ), + Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src), Instruction::ScalarAlu { op, dst, @@ -568,12 +584,13 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/vector-integer.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"), + include_bytes!("../../../fixtures/rdna2/vector-unary.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 120, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 126, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 1e32c6c..91fb975 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -61,7 +61,7 @@ OPERATIONS = { "mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract", "absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd", "mul24": "Multiply24", "mul_hi24": "MultiplyHigh24", - "mov": "Move", "cmov": "ConditionalMove", + "mov": "Move", "cmov": "ConditionalMove", "swap": "Swap", } # Unary operations read one source; they need an operand rule of the unary kind. UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"} @@ -97,7 +97,7 @@ COMPARE_PRIMITIVES = { # the signedness their primitive names, and their S1 is an unsigned count. LOGICAL = { "and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor", - "not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", + "not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap", } ARITHMETIC = { "add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24", @@ -143,7 +143,7 @@ WAVE = {"any": "Any", "wave32": "Wave32"} # wave size: the lane-mask compares, whose one entry point is the Wave32 # compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other # kind must be "any". -WAVE_BY_KIND = {"vector_compare": "wave32"} +WAVE_BY_KIND = {"vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"} EVIDENCE = { "reference": "Reference", "independent": "Independent", @@ -258,7 +258,45 @@ UNSUPPORTED_COMBOS = { # VOP3 rules also name source classes and encoding fields they refuse. VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"} ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS +VECTOR_UNARY_PRIMITIVES = { + ("not", "bitwise"): "Not", + ("brev", "bitwise"): "ReverseBits", + ("flbit", "unsigned"): "FindHighUnsigned", + ("ff1", "bitwise"): "FindLow", + ("flbit", "signed"): "FindHighSigned", +} + OPERAND_RULES = { + "vop1_vgpr": { + "rust": "Vop1Vgpr", + "enum": "VectorUnaryOp", + "shape": { + "family": "VOP1", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [{"field": "SRC0", "class": "vector_source"}], + "max_literals": 1, + }, + "unsupported": { + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", + "src_special", + }, + "kind": "vector_unary", + }, + "vop1_swap": { + "rust": "Vop1Swap", + "enum": "VectorSwapOp", + "shape": { + "family": "VOP1", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [{"field": "SRC0", "class": "vgpr"}], + "max_literals": 0, + }, + "unsupported": { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", + }, + "kind": "vector_swap", + }, "sop2_sgpr": { "rust": "Sop2Sgpr", "enum": "ScalarAluOp", @@ -637,7 +675,10 @@ def _check_xml(form, rule, snapshot, errors): expected = bits if type(bits) is int else form["width"] if size != expected: errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}") - if (is_input, is_output) != (is_source, not is_source): + # The XML marks both swap operands as outputs. Guide 12.8 also + # reads both old values before assigning either result. + direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source) + if (is_input, is_output) != direction: errors.append(f"{label}: {field} direction disagrees with the XML") if field == count_field: if data_format != "FMT_NUM_U32": @@ -808,10 +849,16 @@ def validate(registry, snapshot): if form["carry_in"] != "none": errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare") primitive = (scc, None, False) - elif _rule_kind(form) == "vector": + elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"): if RELATION_KEY in form: errors.append(f"{label}: {RELATION_KEY} on a non-compare operation") - lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"])) + key = (form["operation"], form["signedness"]) + table = { + "vector": VECTOR_PRIMITIVES, + "vector_unary": VECTOR_UNARY_PRIMITIVES, + "vector_swap": {("swap", "bitwise"): "Swap"}, + }[_rule_kind(form)] + lowering = table.get(key) primitive = None if lowering is None else ("unchanged", lowering, False) else: if RELATION_KEY in form: @@ -839,6 +886,8 @@ def validate(registry, snapshot): elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != ( (_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare") if form["operation"] == "compare" + else "vector_swap" if form["operation"] == "swap" + else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY else "unary" if form["operation"] in UNARY else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY else "immediate" if _rule_kind(form) == "immediate" @@ -1027,7 +1076,7 @@ def render(registry, snapshot): "use crate::primitive;", "use crate::semantics::{", " CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,", - " Signedness, SpecRef, VectorBinary, Wave,", + " Signedness, SpecRef, VectorBinary, VectorUnary, Wave,", "};", "use crate::CompareRelation;", "", @@ -1274,6 +1323,31 @@ def _render_enum(rule_name, forms, snapshot, positions): " }]", " }", ] + if kind in ("vector_unary", "vector_swap"): + out += [ + "", + " /// Assembler name of the 32-bit VOP1 encoding.", + " pub const fn assembly_name(self) -> &'static str {", + " match self {", + ] + suffix = "_e32" if kind == "vector_unary" else "" + out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms] + out += [" }", " }"] + if kind == "vector_swap": + return out + ["}"] + if kind == "vector_unary": + out += [ + "", + " /// Per-lane integer operation selected by the registry.", + " pub const fn lowering(self) -> VectorUnary {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => " + f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]}," + for form in forms + ] + return out + [" }", " }", "}"] if kind == "immediate": out += [ "", diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 678174a..e34c7d0 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -21,6 +21,7 @@ include = [ "rdna2/sopc.toml", "rdna2/sopk.toml", "rdna2/sop1.toml", + "rdna2/vop1.toml", "rdna2/vop2.toml", "rdna2/vopc.toml", "rdna2/vop3.toml", @@ -47,7 +48,7 @@ file = "amdgpu_isa_rdna2.xml" # width operand and result width in bits # scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0 # vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare) -# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares) +# wave any | wave32 (wave32 for VOPC compares and VOP1 integer forms) # operands a key of [operand_rules] # spec references; at least one guide section with a page # verify evidence required before the form counts as verified diff --git a/crates/isa/semantics/rdna2/vop1.toml b/crates/isa/semantics/rdna2/vop1.toml new file mode 100644 index 0000000..b27a57d --- /dev/null +++ b/crates/isa/semantics/rdna2/vop1.toml @@ -0,0 +1,123 @@ +# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8. + +[operand_rules.vop1_vgpr] +family = "VOP1" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [{ field = "SRC0", class = "vector_source" }] +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +# Both operands are read and written by swap; SRC0 must select a VGPR. +[operand_rules.vop1_swap] +family = "VOP1" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [{ field = "SRC0", class = "vgpr" }] +max_literals = 0 +unsupported = [ + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", +] + +[[form]] +name = "V_NOT_B32" +family = "VOP1" +opcode = 55 +variant = "NotB32" +operation = "not" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_vgpr" +spec = [{ document = "guide", section = "12.8", page = 143 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_BFREV_B32" +family = "VOP1" +opcode = 56 +variant = "BfrevB32" +operation = "brev" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_vgpr" +spec = [{ document = "guide", section = "12.8", page = 143 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_FFBH_U32" +family = "VOP1" +opcode = 57 +variant = "FfbhU32" +operation = "flbit" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_vgpr" +spec = [{ document = "guide", section = "12.8", page = 143 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_FFBL_B32" +family = "VOP1" +opcode = 58 +variant = "FfblB32" +operation = "ff1" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_vgpr" +spec = [{ document = "guide", section = "12.8", page = 143 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_FFBH_I32" +family = "VOP1" +opcode = 59 +variant = "FfbhI32" +operation = "flbit" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_vgpr" +spec = [{ document = "guide", section = "12.8", page = 144 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_SWAP_B32" +family = "VOP1" +opcode = 101 +variant = "SwapB32" +operation = "swap" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "wave32" +operands = "vop1_swap" +spec = [{ document = "guide", section = "12.8", page = 149 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index a7b9f3b..8a00a01 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -20,7 +20,7 @@ pub use rdna2::{ }; pub use semantics_gen::{ ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp, - VectorAluOp, VectorAluVop3Op, VectorCompareOp, + VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp, }; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. @@ -155,6 +155,14 @@ pub enum Instruction { WaitStore, /// VOP1 unmodified 32-bit vector move. MoveB32 { dst: u8, src: VectorSource }, + /// VOP1 unary integer operation with a single VGPR result. + VectorUnary { + op: VectorUnaryOp, + dst: u8, + src: VectorSource, + }, + /// VOP1 register swap. Both operands are inputs and outputs. + VectorSwap { op: VectorSwapOp, dst: u8, src: u8 }, /// VOP3 encoding of a registry VOP2 integer operation (operand rule /// `vop3_vgpr2`): two VGPR sources and no input or output modifiers. VectorAluVop3 { @@ -281,6 +289,8 @@ impl Instruction { Self::WaitLoad => "s_waitcnt", Self::WaitStore => "s_waitcnt_vscnt", Self::MoveB32 { .. } => "v_mov_b32_e32", + Self::VectorUnary { op, .. } => op.assembly_name(), + Self::VectorSwap { op, .. } => op.assembly_name(), Self::VectorAluVop3 { op, .. } => op.assembly_name(), Self::ScalarMoveB32 { .. } => "s_mov_b32", Self::ScalarUnary { op, .. } => op.mnemonic(), @@ -333,7 +343,10 @@ impl fmt::Display for Instruction { } Self::WaitLoad => formatter.write_str(" vmcnt(0)"), Self::WaitStore => formatter.write_str(" null, 0"), - Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"), + Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => { + write!(formatter, " v{dst}, {src}") + } + Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"), Self::VectorAluVop3 { dst, src0, src1, .. } diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index a987466..143fd30 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -94,6 +94,23 @@ pub enum Operation { Move, /// SOPK: SDST receives the sign-extended SIMM16 when SCC is set. ConditionalMove, + /// Swap the two old per-lane VGPR values (guide 12.8). + Swap, +} + +/// Per-lane integer operation with one input and one result. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorUnary { + /// Bitwise complement. + Not, + /// Reverse bit order. + ReverseBits, + /// Count leading zeros, or return all ones for zero. + FindHighUnsigned, + /// Count trailing zeros, or return all ones for zero. + FindLow, + /// Count leading sign bits, or return all ones if every bit matches. + FindHighSigned, } /// The per-lane integer operation a vector form lowers to. One reusable MSL @@ -230,6 +247,10 @@ pub enum OperandRule { /// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs. /// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported. Vop2Vgpr2, + /// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2. + Vop1Vgpr, + /// VOP1 swap: VDST and SRC0 each read and write a VGPR. + Vop1Swap, } /// Evidence a form needs before it counts as verified. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 42aee2b..97b3e31 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -5,7 +5,7 @@ use crate::meta::EncodingFamily; use crate::primitive; use crate::semantics::{ CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect, - Signedness, SpecRef, VectorBinary, Wave, + Signedness, SpecRef, VectorBinary, VectorUnary, Wave, }; use crate::CompareRelation; @@ -1496,6 +1496,649 @@ impl ScalarImmediateOp { } } +/// VOP1 operations declared in the semantic registry (operand rule `vop1_swap`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorSwapOp { + /// `v_swap_b32` (VOP1 opcode 101): bitwise swap, SCC = unchanged. + SwapB32, +} + +/// VectorSwapOp by VOP1 OP field value; `None` for undeclared opcodes. +const VECTOR_SWAP_OP_BY_OPCODE: [Option; 256] = [ + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorSwapOp::SwapB32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl VectorSwapOp { + /// Every operation, in registry order. + pub const ALL: [Self; 1] = [ + Self::SwapB32, + ]; + + /// Selects the operation from a first instruction word: the VOP1 encoding + /// bits (mask 0xfe00_0000) and then the OP field (bits 9-16). + pub const fn from_word(word: u32) -> Option { + if word & 0xfe00_0000 != 0x7e00_0000 { + return None; + } + VECTOR_SWAP_OP_BY_OPCODE[((word >> 9) & 0xff) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::SwapB32 => "v_swap_b32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::SwapB32 => 77, + }] + } + + /// Assembler name of the 32-bit VOP1 encoding. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::SwapB32 => "v_swap_b32", + } + } +} + +/// VOP1 operations declared in the semantic registry (operand rule `vop1_vgpr`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorUnaryOp { + /// `v_not_b32` (VOP1 opcode 55): bitwise not, SCC = unchanged. + NotB32, + /// `v_bfrev_b32` (VOP1 opcode 56): bitwise brev, SCC = unchanged. + BfrevB32, + /// `v_ffbh_u32` (VOP1 opcode 57): unsigned flbit, SCC = unchanged. + FfbhU32, + /// `v_ffbl_b32` (VOP1 opcode 58): bitwise ff1, SCC = unchanged. + FfblB32, + /// `v_ffbh_i32` (VOP1 opcode 59): signed flbit, SCC = unchanged. + FfbhI32, +} + +/// VectorUnaryOp by VOP1 OP field value; `None` for undeclared opcodes. +const VECTOR_UNARY_OP_BY_OPCODE: [Option; 256] = [ + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorUnaryOp::NotB32), + Some(VectorUnaryOp::BfrevB32), + Some(VectorUnaryOp::FfbhU32), + Some(VectorUnaryOp::FfblB32), + Some(VectorUnaryOp::FfbhI32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl VectorUnaryOp { + /// Every operation, in registry order. + pub const ALL: [Self; 5] = [ + Self::NotB32, + Self::BfrevB32, + Self::FfbhU32, + Self::FfblB32, + Self::FfbhI32, + ]; + + /// Selects the operation from a first instruction word: the VOP1 encoding + /// bits (mask 0xfe00_0000) and then the OP field (bits 9-16). + pub const fn from_word(word: u32) -> Option { + if word & 0xfe00_0000 != 0x7e00_0000 { + return None; + } + VECTOR_UNARY_OP_BY_OPCODE[((word >> 9) & 0xff) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::NotB32 => "v_not_b32", + Self::BfrevB32 => "v_bfrev_b32", + Self::FfbhU32 => "v_ffbh_u32", + Self::FfblB32 => "v_ffbl_b32", + Self::FfbhI32 => "v_ffbh_i32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::NotB32 => 72, + Self::BfrevB32 => 73, + Self::FfbhU32 => 74, + Self::FfblB32 => 75, + Self::FfbhI32 => 76, + }] + } + + /// Assembler name of the 32-bit VOP1 encoding. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::NotB32 => "v_not_b32_e32", + Self::BfrevB32 => "v_bfrev_b32_e32", + Self::FfbhU32 => "v_ffbh_u32_e32", + Self::FfblB32 => "v_ffbl_b32_e32", + Self::FfbhI32 => "v_ffbh_i32_e32", + } + } + + /// Per-lane integer operation selected by the registry. + pub const fn lowering(self) -> VectorUnary { + match self { + Self::NotB32 => VectorUnary::Not, + Self::BfrevB32 => VectorUnary::ReverseBits, + Self::FfbhU32 => VectorUnary::FindHighUnsigned, + Self::FfblB32 => VectorUnary::FindLow, + Self::FfbhI32 => VectorUnary::FindHighSigned, + } + } +} + /// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`). #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAluOp { @@ -1664,24 +2307,24 @@ impl VectorAluOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::MulI32I24 => 72, - Self::MulHiI32I24 => 73, - Self::MulU32U24 => 74, - Self::MulHiU32U24 => 75, - Self::MinI32 => 76, - Self::MaxI32 => 77, - Self::MinU32 => 78, - Self::MaxU32 => 79, - Self::XnorB32 => 80, - Self::AddNcU32 => 81, - Self::SubNcU32 => 82, - Self::SubrevNcU32 => 83, - Self::LshrrevB32 => 84, - Self::AshrrevI32 => 85, - Self::LshlrevB32 => 86, - Self::AndB32 => 87, - Self::OrB32 => 88, - Self::XorB32 => 89, + Self::MulI32I24 => 78, + Self::MulHiI32I24 => 79, + Self::MulU32U24 => 80, + Self::MulHiU32U24 => 81, + Self::MinI32 => 82, + Self::MaxI32 => 83, + Self::MinU32 => 84, + Self::MaxU32 => 85, + Self::XnorB32 => 86, + Self::AddNcU32 => 87, + Self::SubNcU32 => 88, + Self::SubrevNcU32 => 89, + Self::LshrrevB32 => 90, + Self::AshrrevI32 => 91, + Self::LshlrevB32 => 92, + Self::AndB32 => 93, + Self::OrB32 => 94, + Self::XorB32 => 95, }] } @@ -2134,22 +2777,22 @@ impl VectorCompareOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::CmpLtI32 => 90, - Self::CmpEqI32 => 91, - Self::CmpLeI32 => 92, - Self::CmpGtI32 => 93, - Self::CmpNeI32 => 94, - Self::CmpGeI32 => 95, - Self::CmpLtU32 => 96, - Self::CmpEqU32 => 97, - Self::CmpLeU32 => 98, - Self::CmpGtU32 => 99, - Self::CmpNeU32 => 100, - Self::CmpGeU32 => 101, - Self::CmpFI32 => 102, - Self::CmpTI32 => 103, - Self::CmpFU32 => 104, - Self::CmpTU32 => 105, + Self::CmpLtI32 => 96, + Self::CmpEqI32 => 97, + Self::CmpLeI32 => 98, + Self::CmpGtI32 => 99, + Self::CmpNeI32 => 100, + Self::CmpGeI32 => 101, + Self::CmpLtU32 => 102, + Self::CmpEqU32 => 103, + Self::CmpLeU32 => 104, + Self::CmpGtU32 => 105, + Self::CmpNeU32 => 106, + Self::CmpGeU32 => 107, + Self::CmpFI32 => 108, + Self::CmpTI32 => 109, + Self::CmpFU32 => 110, + Self::CmpTU32 => 111, }] } @@ -2285,13 +2928,13 @@ impl VectorAluVop3Op { /// The validated registry row of this encoding. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::AddNcU32 => 106, + Self::AddNcU32 => 112, }] } } /// Identity of every registry form and encoding variant, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 107] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 113] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -2364,6 +3007,12 @@ pub const FORM_IDS: [(&str, EncodingFamily); 107] = [ ("S_SEXT_I32_I8", EncodingFamily::Sop1), ("S_SEXT_I32_I16", EncodingFamily::Sop1), ("S_ABS_I32", EncodingFamily::Sop1), + ("V_NOT_B32", EncodingFamily::Vop1), + ("V_BFREV_B32", EncodingFamily::Vop1), + ("V_FFBH_U32", EncodingFamily::Vop1), + ("V_FFBL_B32", EncodingFamily::Vop1), + ("V_FFBH_I32", EncodingFamily::Vop1), + ("V_SWAP_B32", EncodingFamily::Vop1), ("V_MUL_I32_I24", EncodingFamily::Vop2), ("V_MUL_HI_I32_I24", EncodingFamily::Vop2), ("V_MUL_U32_U24", EncodingFamily::Vop2), @@ -2402,7 +3051,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 107] = [ ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 107] = [ +pub static FORMS: [FormSemantics; 113] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3915,6 +4564,132 @@ pub static FORMS: [FormSemantics; 107] = [ spec: &[SpecRef { document: Document::Guide, section: "12.3", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_NOT_B32", + family: EncodingFamily::Vop1, + opcode: 55, + operation: Operation::Not, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Vgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_BFREV_B32", + family: EncodingFamily::Vop1, + opcode: 56, + operation: Operation::ReverseBits, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Vgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_FFBH_U32", + family: EncodingFamily::Vop1, + opcode: 57, + operation: Operation::FindLastBit, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Vgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_FFBL_B32", + family: EncodingFamily::Vop1, + opcode: 58, + operation: Operation::FindFirstOne, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Vgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_FFBH_I32", + family: EncodingFamily::Vop1, + opcode: 59, + operation: Operation::FindLastBit, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Vgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 144 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_SWAP_B32", + family: EncodingFamily::Vop1, + opcode: 101, + operation: Operation::Swap, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop1Swap, + spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 149 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "V_MUL_I32_I24", family: EncodingFamily::Vop2, diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 26c3e58..1fa2c9b 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -10,7 +10,7 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op, - VectorBinary, VectorCompareOp, VectorSource, + VectorBinary, VectorCompareOp, VectorSource, VectorUnary, }; /// SGPR index of `vcc_lo`. @@ -92,6 +92,7 @@ enum Op { Load, Constant(u32), Binary(Binary, Value, Value), + Unary(VectorUnary, Value), MergeLanes { mask: u32, active: Value, @@ -129,6 +130,7 @@ impl Op { match self { Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(), Self::Binary(_, left, right) => vec![left, right], + Self::Unary(_, source) => vec![source], Self::MergeLanes { active, inactive, .. } => vec![active, inactive], @@ -149,6 +151,21 @@ impl Op { match self { Self::Load => format!("input[{index}]"), Self::Constant(value) => format!("0x{value:08x}u"), + Self::Unary(op, source) => { + let src = name(source); + // AMD guide 12.8: all three scans return -1 if no bit matches. + match op { + VectorUnary::Not => format!("~{src}"), + VectorUnary::ReverseBits => format!("reverse_bits({src})"), + VectorUnary::FindHighUnsigned => { + format!("{src} == 0u ? 0xffffffffu : clz({src})") + } + VectorUnary::FindLow => format!("{src} == 0u ? 0xffffffffu : ctz({src})"), + VectorUnary::FindHighSigned => format!( + "({src} == 0u || {src} == 0xffffffffu) ? 0xffffffffu : clz({src} ^ (0u - ({src} >> 31u)))" + ), + } + } Self::Binary(operator, left, right) => { let (left, right) = (name(left), name(right)); let (_, symbol) = operator.operator(); @@ -440,6 +457,19 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result { + let mnemonic = match operator { + VectorUnary::Not => "not.b32", + VectorUnary::ReverseBits => "brev.b32", + VectorUnary::FindHighUnsigned => "ffbh.u32", + VectorUnary::FindLow => "ffbl.b32", + VectorUnary::FindHighSigned => "ffbh.i32", + }; + ( + format!("{dest} = {mnemonic} {source}"), + format!("uint {dest} = {};", operation.expression(&thread, "", "")), + ) + } Op::Binary(operator, left, right) => ( format!("{dest} = {} {left}, {right}", operator.operator().0), format!("uint {dest} = {};", operation.expression(&thread, "", "")), @@ -726,6 +756,25 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result, facts: &mut Vec<_>| { + Ok(match source { + 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(operations, facts, offset, bits), + (None, None) => { + return Err(error("vector ALU reads uninitialized VCC_LO")); + } + } + } + VectorSource::Scalar(register) => { + let bits = read_scalar(ScalarSource::Register(register))?; + constant(operations, facts, offset, bits) + } + VectorSource::Immediate(bits) => constant(operations, facts, offset, bits), + }) + }; // Scalar instructions and waits still execute when all lanes are inactive. if exec == 0 { match instruction.instruction { @@ -733,7 +782,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result continue, + | Instruction::VectorAlu { .. } + | Instruction::VectorUnary { .. } + | Instruction::VectorSwap { .. } => continue, _ => {} } } @@ -1033,27 +1084,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { - 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, offset, bits) - } - (None, None) => { - return Err(error("vector ALU reads uninitialized VCC_LO")); - } - } - } - VectorSource::Scalar(register) => { - let bits = read_scalar(ScalarSource::Register(register))?; - constant(&mut operations, &mut facts, offset, bits) - } - VectorSource::Immediate(bits) => { - constant(&mut operations, &mut facts, offset, bits) - } - }; + let src0 = read_vector(src0, &mut operations, &mut facts)?; let src1 = read(src1)?; let (left, right) = if op.swaps_sources() { (src1, src0) @@ -1065,6 +1096,35 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + let source = read_vector(src, &mut operations, &mut facts)?; + (Some(dst), Op::Unary(op.lowering(), source)) + } + Instruction::VectorSwap { dst, src, .. } => { + // Guide 12.8: capture both old values before updating either VGPR. + // read() also rejects v0 and registers with outstanding loads. + let old_dst = read(dst)?; + let old_src = read(src)?; + if dst != src { + registers[usize::from(dst)] = Some(merge_lanes( + &mut operations, + &mut facts, + offset, + exec, + old_src, + Some(old_dst), + )?); + registers[usize::from(src)] = Some(merge_lanes( + &mut operations, + &mut facts, + offset, + exec, + old_dst, + Some(old_src), + )?); + } + continue; + } Instruction::VectorAddF32 { dst, src0, src1 } => ( Some(dst), Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?), diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index 483c0fa..7b85d80 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -391,3 +391,17 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() { include_str!("../../../fixtures/golden/vector-compare.metal") ); } + +#[test] +fn vop1_integer_fixture_lowers_unary_and_masked_swap() { + let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/vector-unary.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/vector-unary.metal") + ); +} diff --git a/docs/README.md b/docs/README.md index 1efd494..9cdd4d8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,6 +25,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. - [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms. - [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources. - [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule. +- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits. - [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. diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 098ec9e..6af5a21 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 120 of 120. Accepted Metal forms · Apple M5: 18 of 120. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 126 of 126. Accepted Metal forms · Apple M5: 18 of 126. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -120 / 120 +126 / 126 Accepted Metal forms · Apple M5 -18 / 120 +18 / 126 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index 75733c3..7701e25 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -121,6 +121,12 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `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, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | acceptance pending | +| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | acceptance pending | +| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | acceptance pending | +| `v_ffbl_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero | `7E0A7501` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | acceptance pending | +| `v_ffbh_i32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match | `7E0C7702` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | acceptance pending | +| `v_swap_b32` | VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0 | `7E02CB02` | yes | yes | three-way passed | per-thread exchange of both register values with lane merges under partial EXEC | implemented | local known-answer test passed | acceptance pending | | `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index ae178d5..917bd75 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -30,13 +30,13 @@ acceptance remain outside the verified count. All results concern synthetic fixt | SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 | | SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 | | VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | -| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | +| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 | | VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 | | VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 120 | 107 | 124 | 120 | 120 | 18 | 18 | 65 | +| **Total** | 1465 | 126 | 113 | 130 | 126 | 126 | 18 | 18 | 76 | ## Unsupported operand variants @@ -49,6 +49,8 @@ The table counts distinct variant names per family across registry operand rules | SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` | | SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` | | SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` | +| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | +| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | | VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | | VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 38c4f34..c15a2da 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -120,7 +120,7 @@ error. | `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere | | `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` | | `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) | -| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` | +| `wave` | Wave sizes the form is valid in | `wave32` for VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms | | `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` | | `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 | | `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` | diff --git a/docs/shaders/vector-unary.md b/docs/shaders/vector-unary.md new file mode 100644 index 0000000..018f276 --- /dev/null +++ b/docs/shaders/vector-unary.md @@ -0,0 +1,35 @@ +# Wave32 vector unary integer operations and swap + +Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute +ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8, +the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3. + +| Form | Result in each active lane | +| --- | --- | +| `v_not_b32_e32` | Complement all 32 bits. | +| `v_bfrev_b32_e32` | Reverse the order of the 32 bits. | +| `v_ffbh_u32_e32` | Count leading zeros. Return all ones if the source is zero. | +| `v_ffbl_b32_e32` | Count trailing zeros. Return all ones if the source is zero. | +| `v_ffbh_i32_e32` | Count leading bits equal to the sign bit. Return all ones if all bits match. | +| `v_swap_b32` | Exchange the old values of two vector general-purpose registers (VGPRs). A register swapped with itself keeps its value. | + +The unary forms accept a VGPR, scalar register `s0`–`s105`, `vcc_lo` (the low +half of the vector condition code), inline integer `-16`–`64`, or a literal +word as SRC0. Swap requires a VGPR as SRC0 because it writes both operands. +Both operands of swap must be initialized when EXEC is nonzero. The compute +ABI reserves `v0` for indexing and requires waiting for buffer loads before +using or overwriting their destination. Inactive lanes retain their old +values. The six forms leave EXEC, VCC and the scalar condition code (SCC) +unchanged. + +The compiler emits per-thread Metal Shading Language for unary operations. +For swap it captures both old values in the intermediate representation before +updating either register binding. Under partial EXEC, each register receives +its own lane merge. + +The [guide-derived oracle](../../tests/validation/tests/vop1_integer.rs) checks +752 accepted cases against each CPU interpreter and the compiler, and verifies +that 610 rejected programs fail at the same instruction offset. The +[LLVM-assembled fixture](../../fixtures/rdna2/vector-unary.s) exercises all +six forms with a partial EXEC swap. Native Metal execution and independent +acceptance of the translator are pending. Xbox hardware agreement is unknown. diff --git a/docs/status.toml b/docs/status.toml index 5f92851..385c937 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -1334,6 +1334,78 @@ recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "v_not_b32_e32" +encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement" +representation = "`7E046F01`" +lowering = "per-thread unary integer operation with a lane merge under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_bfrev_b32_e32" +encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order" +representation = "`7E067101`" +lowering = "per-thread unary integer operation with a lane merge under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_ffbh_u32_e32" +encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero" +representation = "`7E087302`" +lowering = "per-thread unary integer operation with a lane merge under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_ffbl_b32_e32" +encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero" +representation = "`7E0A7501`" +lowering = "per-thread unary integer operation with a lane merge under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_ffbh_i32_e32" +encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match" +representation = "`7E0C7702`" +lowering = "per-thread unary integer operation with a lane merge under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_swap_b32" +encoding = "VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0" +representation = "`7E02CB02`" +lowering = "per-thread exchange of both register values with lane merges under partial EXEC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + [[instruction]] form = "v_mul_i32_i24_e32" encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])" diff --git a/fixtures/golden/vector-unary.ir b/fixtures/golden/vector-unary.ir new file mode 100644 index 0000000..51d4800 --- /dev/null +++ b/fixtures/golden/vector-unary.ir @@ -0,0 +1,12 @@ +0000: t0 = load.u32 input[index] +000c: t1 = not.b32 t0 +0018: t2 = merge.lanes mask=0xaaaaaaaa, t1, t0 +0018: t3 = merge.lanes mask=0xaaaaaaaa, t0, t1 +0020: t4 = brev.b32 t2 +0024: t5 = ffbh.u32 t3 +0028: t6 = ffbl.b32 t2 +002c: t7 = ffbh.i32 t3 +0030: t8 = xor.b32 t4, t5 +0034: t9 = xor.b32 t6, t8 +0038: t10 = xor.b32 t7, t9 +003c: store.u32 output[index], t10 diff --git a/fixtures/golden/vector-unary.metal b/fixtures/golden/vector-unary.metal new file mode 100644 index 0000000..bf00db3 --- /dev/null +++ b/fixtures/golden/vector-unary.metal @@ -0,0 +1,19 @@ +#include +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 t0 = input[index]; + uint t1 = ~t0; + uint t2 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t1 : t0; + uint t3 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t0 : t1; + uint t4 = reverse_bits(t2); + uint t5 = t3 == 0u ? 0xffffffffu : clz(t3); + uint t6 = t2 == 0u ? 0xffffffffu : ctz(t2); + uint t7 = (t3 == 0u || t3 == 0xffffffffu) ? 0xffffffffu : clz(t3 ^ (0u - (t3 >> 31u))); + uint t8 = t4 ^ t5; + uint t9 = t6 ^ t8; + uint t10 = t7 ^ t9; + output[index] = t10; +} diff --git a/fixtures/rdna2/vector-unary.bin b/fixtures/rdna2/vector-unary.bin new file mode 100644 index 0000000000000000000000000000000000000000..bb50de9a34ddad799397cd27e7a192967dad371a GIT binary patch literal 76 zcmZQjFnGYg$k0$=-?N`FpQY|U^S^zofPm>VQ{6!zo3W6sj;WZVj