From cd59e081d94e4a4c2b30c22023fa81de6896dc01 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:16:09 -0600 Subject: [PATCH] isa, decoder: SOPC integer compares through the semantic registry (#215 stage D) Adds a compare operation with a declared relation and the sopc_scalar operand rule, so all twelve s_cmp_*_{i32,u32} forms are registry data. The decoder dispatches them through the generated OP table and the translator resolves SCC with ScalarCompareOp::test; the hand-written s_cmp_eq_u32 path and its opcode constant are gone. A new LLVM-assembled fixture records every compare's SCC, and the separately written oracle from task/215-stage-d-oracle supplies the reference side. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 26 +- crates/decoder/tests/gfx1030.rs | 21 +- crates/isa/generate_rdna2.py | 1 - crates/isa/generate_semantics.py | 115 +++- crates/isa/semantics/rdna2.toml | 267 +++++++++ crates/isa/src/lib.rs | 21 +- crates/isa/src/primitive.rs | 50 ++ crates/isa/src/rdna2.rs | 5 - crates/isa/src/semantics.rs | 12 +- crates/isa/src/semantics_gen.rs | 560 +++++++++++++++++- crates/isa/tests/semantics.rs | 67 ++- crates/shader/src/lib.rs | 4 +- crates/shader/tests/compiler.rs | 14 + docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 11 + docs/shaders/scalar-alu.md | 19 +- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 5 + docs/status.toml | 132 +++++ fixtures/golden/scalar-compare.ir | 16 + fixtures/golden/scalar-compare.metal | 11 + fixtures/rdna2/scalar-compare.bin | Bin 0 -> 212 bytes fixtures/rdna2/scalar-compare.s | 65 ++ scripts/assemble-fixture.sh | 2 +- .../test_generate_semantics.py | 94 ++- tests/validation/known_answers.rs | 16 +- 27 files changed, 1430 insertions(+), 118 deletions(-) create mode 100644 fixtures/golden/scalar-compare.ir create mode 100644 fixtures/golden/scalar-compare.metal create mode 100644 fixtures/rdna2/scalar-compare.bin create mode 100644 fixtures/rdna2/scalar-compare.s diff --git a/CHANGELOG.md b/CHANGELOG.md index 60a7c4c..9448fa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ remains unsupported. ### Added +- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases and 348 rejections on CPU and native Metal with validation, plus a new LLVM-assembled fixture. Two literal selectors stay rejected. Part of #215, stage D. - Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C. - Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family. - Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 40a68c2..4281c93 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -4,15 +4,15 @@ use std::fmt; pub use xenora_isa::{ Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, - ScalarSource, VectorCompareOp, VectorSource, + ScalarCompareOp, ScalarSource, VectorCompareOp, VectorSource, }; use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, - S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, - 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, + S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, 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; @@ -41,7 +41,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [ ("S_CBRANCH_EXECZ", EncodingFamily::Sopp), ("S_CBRANCH_SCC0", EncodingFamily::Sopp), ("S_CBRANCH_VCCZ", EncodingFamily::Sopp), - ("S_CMP_EQ_U32", EncodingFamily::Sopc), ("S_ENDPGM", EncodingFamily::Sopp), ("S_MOV_B32", EncodingFamily::Sop1), ("S_WAITCNT", EncodingFamily::Sopp), @@ -375,19 +374,20 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?; return Ok((Instruction::ScalarMoveB32 { dst, src }, len)); } - if S_CMP_EQ_U32.matches(first) { + if let Some(op) = ScalarCompareOp::from_word(first) { + let mnemonic = op.mnemonic(); let src0_bits = first as u8; let src1_bits = (first >> 8) as u8; if src0_bits == 255 && src1_bits == 255 { return Err(unsupported( - "s_cmp_eq_u32", + mnemonic, "only one source may select a literal", )); } - let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?; - let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?; + let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?; + let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?; return Ok(( - Instruction::ScalarCompareEqU32 { src0, src1 }, + Instruction::ScalarCompare { op, src0, src1 }, len0.max(len1), )); } diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index afbd701..81ca73c 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -6,6 +6,7 @@ use xenora_decoder::{ Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarAluOp, ScalarSource, VectorSource, decode, decode_at, }; +use xenora_isa::semantics::Signedness; use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); @@ -355,8 +356,21 @@ fn reference_op(instruction: Instruction) -> Op { ), Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1), Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)), - Instruction::ScalarCompareEqU32 { src0, src1 } => { - Op::CompareEqual(reference_scalar(src0), reference_scalar(src1)) + Instruction::ScalarCompare { op, src0, src1 } => { + let (src0, src1) = (reference_scalar(src0), reference_scalar(src1)); + // The reference keeps CompareEqual for EQ and uses its VOPC relation + // offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest. + match op.relation() { + CompareRelation::Equal => Op::CompareEqual(src0, src1), + relation => Op::ScalarCompare( + Comparison { + offset: relation as u8 + 1, + signed: op.semantics().signedness == Signedness::Signed, + }, + src0, + src1, + ), + } } Instruction::BranchSccZero { target } => Op::Branch { target, @@ -443,13 +457,14 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/ashr.bin"), include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"), include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"), + include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 50, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 61, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() diff --git a/crates/isa/generate_rdna2.py b/crates/isa/generate_rdna2.py index ddcc80e..8dd0cc0 100644 --- a/crates/isa/generate_rdna2.py +++ b/crates/isa/generate_rdna2.py @@ -17,7 +17,6 @@ VARIANTS = ( ("V_ADD_NC_U32", "ENC_VOP3"), ("S_ENDPGM", "ENC_SOPP"), ("S_MOV_B32", "ENC_SOP1"), - ("S_CMP_EQ_U32", "ENC_SOPC"), ("S_CBRANCH_SCC0", "ENC_SOPP"), ("S_CBRANCH_EXECZ", "ENC_SOPP"), ("S_CBRANCH_VCCZ", "ENC_SOPP"), diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 7882559..a7158a0 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -42,6 +42,23 @@ OPERATIONS = { "add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor", "andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor", "lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight", + "compare": "Compare", +} +# Compares take a relation (S0 on the left) and set SCC to whether it holds. +RELATION_KEY = "relation" +RELATIONS = { + "eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual", + "lt": "Less", "le": "LessOrEqual", +} +# (relation, signedness) -> primitive. Equality does not depend on signedness, +# so both declared signednesses of EQ and LG share one primitive. +COMPARE_PRIMITIVES = { + ("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32", + ("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32", + ("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32", + ("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32", + ("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32", + ("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32", } # Logical operations take untyped bits; arithmetic ones never do. Shifts take # the signedness their primitive names, and their S1 is an unsigned count. @@ -64,6 +81,7 @@ SCC = { "borrow": "Borrow", "signed_overflow": "SignedOverflow", "nonzero": "Nonzero", + "relation": "Relation", } MASK = {"unchanged": "Unchanged"} WAVE = {"any": "Any", "wave32": "Wave32"} @@ -133,6 +151,22 @@ OPERAND_RULES = { }, # Every one of these is rejected by the decoder's SOP2 operand checks. "unsupported": UNSUPPORTED_COMBOS, + "kind": "alu", + }, + "sopc_scalar": { + "rust": "SopcScalar", + "enum": "ScalarCompareOp", + "shape": { + "family": "SOPC", + "src": [ + {"field": "SSRC0", "class": "scalar_source"}, + {"field": "SSRC1", "class": "scalar_source"}, + ], + "max_literals": 1, + }, + # SOPC has no destination field; the decoder rejects these sources. + "unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")}, + "kind": "compare", }, } @@ -228,7 +262,8 @@ def _check_xml(form, rule, snapshot, errors): errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output") if rule is None: return - fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]] + fields = [(rule["dst"]["field"], False)] if "dst" in rule else [] + fields += [(src["field"], True) for src in rule["src"]] count_field = rule["src"][1]["field"] if form["operation"] in SHIFTS else None for field, is_source in fields: if field not in operands: @@ -290,7 +325,7 @@ def validate(registry, snapshot): for index, form in enumerate(forms): label = form.get("name", f"form #{index}") missing = sorted(FORM_KEYS - set(form)) - extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY}) + extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY, RELATION_KEY}) if missing: errors.append(f"{label}: incomplete, missing {missing}") if extra: @@ -337,7 +372,21 @@ def validate(registry, snapshot): ) elif SHIFT_KEY in form: errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation") - primitive = PRIMITIVES.get((form["operation"], form["signedness"])) + if form["operation"] == "compare": + relation = form.get(RELATION_KEY) + if relation not in RELATIONS: + errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}") + elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES: + errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") + if form["scc"] != "relation": + errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)") + if form["carry_in"] != "none": + errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare") + primitive = ("relation", None, False) + else: + if RELATION_KEY in form: + errors.append(f"{label}: {RELATION_KEY} on a non-compare operation") + primitive = PRIMITIVES.get((form["operation"], form["signedness"])) if primitive is None: errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}") else: @@ -354,6 +403,10 @@ def validate(registry, snapshot): errors.append(f"{label}: unknown operand rule {form['operands']!r}") elif rule.get("family") != form["family"]: errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}") + elif form["operands"] in OPERAND_RULES and ( + (OPERAND_RULES[form["operands"]]["kind"] == "compare") != (form["operation"] == "compare") + ): + errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}") _check_spec(label, form["spec"], documents, errors) verify = form["verify"] if not verify: @@ -399,6 +452,7 @@ def render(registry, snapshot): " CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,", " Signedness, SpecRef, Wave,", "};", + "use crate::CompareRelation;", "", "/// Registry schema of the generated tables.", f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};", @@ -436,6 +490,8 @@ def render(registry, snapshot): f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},", f" width: {form['width']},", f" shift_count_bits: {form.get(SHIFT_KEY, 0)},", + " relation: " + + (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"), f" scc: SccEffect::{SCC[form['scc']]},", f" vcc: MaskEffect::{MASK[form['vcc']]},", f" exec: MaskEffect::{MASK[form['exec']]},", @@ -451,6 +507,8 @@ def render(registry, snapshot): def _render_enum(rule_name, forms, snapshot, positions): enum = OPERAND_RULES[rule_name]["enum"] + kind = OPERAND_RULES[rule_name]["kind"] + table = re.sub(r"(?; {1 << size}] = [", + f"const {table}: [Option<{enum}>; {1 << size}] = [", ] out += [ f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None," @@ -505,7 +564,7 @@ def _render_enum(rule_name, forms, snapshot, positions): f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{", " return None;", " }", - f" BY_OPCODE[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]", + f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]", " }", "", " /// Lower-case mnemonic.", @@ -516,6 +575,41 @@ def _render_enum(rule_name, forms, snapshot, positions): out += [ " }", " }", + "", + " /// The validated registry row.", + " pub fn semantics(self) -> &'static FormSemantics {", + " &FORMS[match self {", + ] + out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms] + out += [ + " }]", + " }", + ] + if kind == "compare": + out += [ + "", + " /// The relation tested, with S0 on the left.", + " pub const fn relation(self) -> CompareRelation {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]}," + for form in forms + ] + out += [ + " }", + " }", + "", + " /// The new SCC: whether the relation holds for S0 and S1.", + " pub const fn test(self, src0: u32, src1: u32) -> bool {", + " match self {", + ] + for form in forms: + function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])] + out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),") + out += [" }", " }", "}"] + return out + out += [ "", " /// Whether the operation reads SCC as a carry-in or borrow-in.", " pub const fn reads_scc(self) -> bool {", @@ -529,15 +623,6 @@ def _render_enum(rule_name, forms, snapshot, positions): " }", " }", "", - " /// The validated registry row.", - " pub fn semantics(self) -> &'static FormSemantics {", - " &FORMS[match self {", - ] - out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms] - out += [ - " }]", - " }", - "", " /// The result and the new SCC, with `carry_in` the SCC read by forms that", " /// consume it (ignored by the others).", " pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {", diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 3c28d24..22da183 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -372,3 +372,270 @@ wave = "any" operands = "sop2_sgpr" spec = [{ document = "guide", section = "12.1", page = 104 }] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- Stage D: SOPC 32-bit integer compares (#215) ---- +# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4). + +[operand_rules.sopc_scalar] +family = "SOPC" +src = [ + { field = "SSRC0", class = "scalar_source" }, + { field = "SSRC1", class = "scalar_source" }, +] +max_literals = 1 +unsupported = [ + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", + "src_special", "two_literals", +] + +[[form]] +name = "S_CMP_EQ_I32" +family = "SOPC" +opcode = 0 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_I32" +family = "SOPC" +opcode = 1 +variant = "CmpLgI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_I32" +family = "SOPC" +opcode = 2 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_I32" +family = "SOPC" +opcode = 3 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_I32" +family = "SOPC" +opcode = 4 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_I32" +family = "SOPC" +opcode = 5 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_EQ_U32" +family = "SOPC" +opcode = 6 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_U32" +family = "SOPC" +opcode = 7 +variant = "CmpLgU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_U32" +family = "SOPC" +opcode = 8 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_U32" +family = "SOPC" +opcode = 9 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_U32" +family = "SOPC" +opcode = 10 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_U32" +family = "SOPC" +opcode = 11 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 9106020..c3026fe 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -12,13 +12,13 @@ mod rdna2_meta; mod semantics_gen; pub use rdna2::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, - S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, - 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, + S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, 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, }; -pub use semantics_gen::ScalarAluOp; +pub use semantics_gen::{ScalarAluOp, ScalarCompareOp}; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. pub const VCC_LO: u8 = 106; @@ -216,8 +216,9 @@ pub enum Instruction { src0: ScalarSource, src1: ScalarSource, }, - /// SOPC 32-bit equality comparison writing SCC. - ScalarCompareEqU32 { + /// SOPC 32-bit integer compare writing only SCC. + ScalarCompare { + op: ScalarCompareOp, src0: ScalarSource, src1: ScalarSource, }, @@ -307,7 +308,7 @@ impl Instruction { Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64", Self::ScalarMoveB32 { .. } => "s_mov_b32", Self::ScalarAlu { op, .. } => op.mnemonic(), - Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32", + Self::ScalarCompare { op, .. } => op.mnemonic(), Self::VectorCompare { op, .. } => op.mnemonic(), Self::BranchSccZero { .. } => "s_cbranch_scc0", Self::BranchExecZero { .. } => "s_cbranch_execz", @@ -376,7 +377,7 @@ impl fmt::Display for Instruction { Self::ScalarAlu { dst, src0, src1, .. } => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)), - Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"), + Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"), Self::VectorCompare { src0, src1, .. } => { write!(formatter, " vcc_lo, {src0}, v{src1}") } diff --git a/crates/isa/src/primitive.rs b/crates/isa/src/primitive.rs index 2743ccc..6daef58 100644 --- a/crates/isa/src/primitive.rs +++ b/crates/isa/src/primitive.rs @@ -98,3 +98,53 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) { let value = ((a as i32) >> count) as u32; (value, value != 0) } + +/// `a == b` on the raw bits; signedness does not matter for equality. +pub const fn eq_b32(a: u32, b: u32) -> bool { + a == b +} + +/// `a != b` on the raw bits (the guide's LG, "less or greater"). +pub const fn ne_b32(a: u32, b: u32) -> bool { + a != b +} + +/// Two's-complement `a > b`. +pub const fn gt_i32(a: u32, b: u32) -> bool { + (a as i32) > (b as i32) +} + +/// Two's-complement `a >= b`. +pub const fn ge_i32(a: u32, b: u32) -> bool { + (a as i32) >= (b as i32) +} + +/// Two's-complement `a < b`. +pub const fn lt_i32(a: u32, b: u32) -> bool { + (a as i32) < (b as i32) +} + +/// Two's-complement `a <= b`. +pub const fn le_i32(a: u32, b: u32) -> bool { + (a as i32) <= (b as i32) +} + +/// Unsigned `a > b`. +pub const fn gt_u32(a: u32, b: u32) -> bool { + a > b +} + +/// Unsigned `a >= b`. +pub const fn ge_u32(a: u32, b: u32) -> bool { + a >= b +} + +/// Unsigned `a < b`. +pub const fn lt_u32(a: u32, b: u32) -> bool { + a < b +} + +/// Unsigned `a <= b`. +pub const fn le_u32(a: u32, b: u32) -> bool { + a <= b +} diff --git a/crates/isa/src/rdna2.rs b/crates/isa/src/rdna2.rs index 1745c44..3da3533 100644 --- a/crates/isa/src/rdna2.rs +++ b/crates/isa/src/rdna2.rs @@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode { bits: 0xbe800300, bytes: 4, }; -pub const S_CMP_EQ_U32: Opcode = Opcode { - mask: 0xffff0000, - bits: 0xbf060000, - bytes: 4, -}; pub const S_CBRANCH_SCC0: Opcode = Opcode { mask: 0xffff0000, bits: 0xbf840000, diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index a230da4..ecc40f8 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -9,6 +9,7 @@ //! The reference interpreter (`crates/ref`) and the independent interpreter //! (`tests/validation/independent_ref.rs`) must not use this module. +use crate::CompareRelation; use crate::meta::EncodingFamily; pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA}; @@ -46,6 +47,8 @@ pub enum Operation { LogicalShiftRight, /// Shift S0 right by the masked count in S1, filling with its sign bit. ArithmeticShiftRight, + /// Compare S0 with S1 under the form's relation; writes only SCC. + Compare, } /// How the operands are interpreted. `Bitwise` exactly when the operation is logical. @@ -81,6 +84,8 @@ pub enum SccEffect { SignedOverflow, /// The result is not zero. Nonzero, + /// The compare's relation holds for S0 and S1. + Relation, } /// What a form writes to VCC or EXEC. Stage A forms leave both unchanged. @@ -105,6 +110,9 @@ pub enum OperandRule { /// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64 /// or one literal word. Everything else is rejected as unsupported. Sop2Sgpr, + /// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline + /// integers -16..64 or one literal word). Everything else is rejected. + SopcScalar, } /// Evidence a form needs before it counts as verified. @@ -136,7 +144,7 @@ pub struct SpecRef { pub document: Document, /// Section number, for example `"12.1"`. pub section: &'static str, - /// Page in the document, 0 when not paginated. + /// Page in the document, or 0 when the page has not been recorded. pub page: u16, } @@ -159,6 +167,8 @@ pub struct FormSemantics { pub width: u8, /// Low bits of S1 used as the shift count by shift operations; 0 otherwise. pub shift_count_bits: u8, + /// The relation tested by compares (S0 on the left); `None` otherwise. + pub relation: Option, /// SCC write. pub scc: SccEffect, /// VCC write. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 8776b8a..04d0256 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -7,6 +7,7 @@ use crate::semantics::{ CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect, Signedness, SpecRef, Wave, }; +use crate::CompareRelation; /// Registry schema of the generated tables. pub const GENERATED_SCHEMA: u32 = 1; @@ -51,7 +52,7 @@ pub enum ScalarAluOp { } /// ScalarAluOp by SOP2 OP field value; `None` for undeclared opcodes. -const BY_OPCODE: [Option; 128] = [ +const SCALAR_ALU_OP_BY_OPCODE: [Option; 128] = [ Some(ScalarAluOp::AddU32), Some(ScalarAluOp::SubU32), Some(ScalarAluOp::AddI32), @@ -210,7 +211,7 @@ impl ScalarAluOp { if word & 0xc000_0000 != 0x8000_0000 { return None; } - BY_OPCODE[((word >> 23) & 0x7f) as usize] + SCALAR_ALU_OP_BY_OPCODE[((word >> 23) & 0x7f) as usize] } /// Lower-case mnemonic. @@ -236,29 +237,6 @@ impl ScalarAluOp { } } - /// Whether the operation reads SCC as a carry-in or borrow-in. - pub const fn reads_scc(self) -> bool { - match self { - Self::AddU32 => false, - Self::SubU32 => false, - Self::AddI32 => false, - Self::SubI32 => false, - Self::AddcU32 => true, - Self::SubbU32 => true, - Self::AndB32 => false, - Self::OrB32 => false, - Self::XorB32 => false, - Self::Andn2B32 => false, - Self::Orn2B32 => false, - Self::NandB32 => false, - Self::NorB32 => false, - Self::XnorB32 => false, - Self::LshlB32 => false, - Self::LshrB32 => false, - Self::AshrI32 => false, - } - } - /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { @@ -282,6 +260,29 @@ impl ScalarAluOp { }] } + /// Whether the operation reads SCC as a carry-in or borrow-in. + pub const fn reads_scc(self) -> bool { + match self { + Self::AddU32 => false, + Self::SubU32 => false, + Self::AddI32 => false, + Self::SubI32 => false, + Self::AddcU32 => true, + Self::SubbU32 => true, + Self::AndB32 => false, + Self::OrB32 => false, + Self::XorB32 => false, + Self::Andn2B32 => false, + Self::Orn2B32 => false, + Self::NandB32 => false, + Self::NorB32 => false, + Self::XnorB32 => false, + Self::LshlB32 => false, + Self::LshrB32 => false, + Self::AshrI32 => false, + } + } + /// The result and the new SCC, with `carry_in` the SCC read by forms that /// consume it (ignored by the others). pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) { @@ -307,8 +308,268 @@ impl ScalarAluOp { } } +/// SOPC operations declared in the semantic registry (operand rule `sopc_scalar`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarCompareOp { + /// `s_cmp_eq_i32` (SOPC opcode 0): signed compare eq, SCC = relation. + CmpEqI32, + /// `s_cmp_lg_i32` (SOPC opcode 1): signed compare lg, SCC = relation. + CmpLgI32, + /// `s_cmp_gt_i32` (SOPC opcode 2): signed compare gt, SCC = relation. + CmpGtI32, + /// `s_cmp_ge_i32` (SOPC opcode 3): signed compare ge, SCC = relation. + CmpGeI32, + /// `s_cmp_lt_i32` (SOPC opcode 4): signed compare lt, SCC = relation. + CmpLtI32, + /// `s_cmp_le_i32` (SOPC opcode 5): signed compare le, SCC = relation. + CmpLeI32, + /// `s_cmp_eq_u32` (SOPC opcode 6): unsigned compare eq, SCC = relation. + CmpEqU32, + /// `s_cmp_lg_u32` (SOPC opcode 7): unsigned compare lg, SCC = relation. + CmpLgU32, + /// `s_cmp_gt_u32` (SOPC opcode 8): unsigned compare gt, SCC = relation. + CmpGtU32, + /// `s_cmp_ge_u32` (SOPC opcode 9): unsigned compare ge, SCC = relation. + CmpGeU32, + /// `s_cmp_lt_u32` (SOPC opcode 10): unsigned compare lt, SCC = relation. + CmpLtU32, + /// `s_cmp_le_u32` (SOPC opcode 11): unsigned compare le, SCC = relation. + CmpLeU32, +} + +/// ScalarCompareOp by SOPC OP field value; `None` for undeclared opcodes. +const SCALAR_COMPARE_OP_BY_OPCODE: [Option; 128] = [ + Some(ScalarCompareOp::CmpEqI32), + Some(ScalarCompareOp::CmpLgI32), + Some(ScalarCompareOp::CmpGtI32), + Some(ScalarCompareOp::CmpGeI32), + Some(ScalarCompareOp::CmpLtI32), + Some(ScalarCompareOp::CmpLeI32), + Some(ScalarCompareOp::CmpEqU32), + Some(ScalarCompareOp::CmpLgU32), + Some(ScalarCompareOp::CmpGtU32), + Some(ScalarCompareOp::CmpGeU32), + Some(ScalarCompareOp::CmpLtU32), + Some(ScalarCompareOp::CmpLeU32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + 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 ScalarCompareOp { + /// Every operation, in registry order. + pub const ALL: [Self; 12] = [ + Self::CmpEqI32, + Self::CmpLgI32, + Self::CmpGtI32, + Self::CmpGeI32, + Self::CmpLtI32, + Self::CmpLeI32, + Self::CmpEqU32, + Self::CmpLgU32, + Self::CmpGtU32, + Self::CmpGeU32, + Self::CmpLtU32, + Self::CmpLeU32, + ]; + + /// Selects the operation from a first instruction word: the SOPC encoding + /// bits (mask 0xff80_0000) and then the OP field (bits 16-22). + pub const fn from_word(word: u32) -> Option { + if word & 0xff80_0000 != 0xbf00_0000 { + return None; + } + SCALAR_COMPARE_OP_BY_OPCODE[((word >> 16) & 0x7f) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::CmpEqI32 => "s_cmp_eq_i32", + Self::CmpLgI32 => "s_cmp_lg_i32", + Self::CmpGtI32 => "s_cmp_gt_i32", + Self::CmpGeI32 => "s_cmp_ge_i32", + Self::CmpLtI32 => "s_cmp_lt_i32", + Self::CmpLeI32 => "s_cmp_le_i32", + Self::CmpEqU32 => "s_cmp_eq_u32", + Self::CmpLgU32 => "s_cmp_lg_u32", + Self::CmpGtU32 => "s_cmp_gt_u32", + Self::CmpGeU32 => "s_cmp_ge_u32", + Self::CmpLtU32 => "s_cmp_lt_u32", + Self::CmpLeU32 => "s_cmp_le_u32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::CmpEqI32 => 17, + Self::CmpLgI32 => 18, + Self::CmpGtI32 => 19, + Self::CmpGeI32 => 20, + Self::CmpLtI32 => 21, + Self::CmpLeI32 => 22, + Self::CmpEqU32 => 23, + Self::CmpLgU32 => 24, + Self::CmpGtU32 => 25, + Self::CmpGeU32 => 26, + Self::CmpLtU32 => 27, + Self::CmpLeU32 => 28, + }] + } + + /// The relation tested, with S0 on the left. + pub const fn relation(self) -> CompareRelation { + match self { + Self::CmpEqI32 => CompareRelation::Equal, + Self::CmpLgI32 => CompareRelation::NotEqual, + Self::CmpGtI32 => CompareRelation::Greater, + Self::CmpGeI32 => CompareRelation::GreaterOrEqual, + Self::CmpLtI32 => CompareRelation::Less, + Self::CmpLeI32 => CompareRelation::LessOrEqual, + Self::CmpEqU32 => CompareRelation::Equal, + Self::CmpLgU32 => CompareRelation::NotEqual, + Self::CmpGtU32 => CompareRelation::Greater, + Self::CmpGeU32 => CompareRelation::GreaterOrEqual, + Self::CmpLtU32 => CompareRelation::Less, + Self::CmpLeU32 => CompareRelation::LessOrEqual, + } + } + + /// The new SCC: whether the relation holds for S0 and S1. + pub const fn test(self, src0: u32, src1: u32) -> bool { + match self { + Self::CmpEqI32 => primitive::eq_b32(src0, src1), + Self::CmpLgI32 => primitive::ne_b32(src0, src1), + Self::CmpGtI32 => primitive::gt_i32(src0, src1), + Self::CmpGeI32 => primitive::ge_i32(src0, src1), + Self::CmpLtI32 => primitive::lt_i32(src0, src1), + Self::CmpLeI32 => primitive::le_i32(src0, src1), + Self::CmpEqU32 => primitive::eq_b32(src0, src1), + Self::CmpLgU32 => primitive::ne_b32(src0, src1), + Self::CmpGtU32 => primitive::gt_u32(src0, src1), + Self::CmpGeU32 => primitive::ge_u32(src0, src1), + Self::CmpLtU32 => primitive::lt_u32(src0, src1), + Self::CmpLeU32 => primitive::le_u32(src0, src1), + } + } +} + /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 17] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 29] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -326,10 +587,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 17] = [ ("S_LSHL_B32", EncodingFamily::Sop2), ("S_LSHR_B32", EncodingFamily::Sop2), ("S_ASHR_I32", EncodingFamily::Sop2), + ("S_CMP_EQ_I32", EncodingFamily::Sopc), + ("S_CMP_LG_I32", EncodingFamily::Sopc), + ("S_CMP_GT_I32", EncodingFamily::Sopc), + ("S_CMP_GE_I32", EncodingFamily::Sopc), + ("S_CMP_LT_I32", EncodingFamily::Sopc), + ("S_CMP_LE_I32", EncodingFamily::Sopc), + ("S_CMP_EQ_U32", EncodingFamily::Sopc), + ("S_CMP_LG_U32", EncodingFamily::Sopc), + ("S_CMP_GT_U32", EncodingFamily::Sopc), + ("S_CMP_GE_U32", EncodingFamily::Sopc), + ("S_CMP_LT_U32", EncodingFamily::Sopc), + ("S_CMP_LE_U32", EncodingFamily::Sopc), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 17] = [ +pub static FORMS: [FormSemantics; 29] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -339,6 +612,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::CarryOut, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -356,6 +630,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Borrow, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -373,6 +648,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::SignedOverflow, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -390,6 +666,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::SignedOverflow, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -407,6 +684,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::Scc, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::CarryOut, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -424,6 +702,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::Scc, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Borrow, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -441,6 +720,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -458,6 +738,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -475,6 +756,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -492,6 +774,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -509,6 +792,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -526,6 +810,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -543,6 +828,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -560,6 +846,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -577,6 +864,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -594,6 +882,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -611,6 +900,7 @@ pub static FORMS: [FormSemantics; 17] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + relation: None, scc: SccEffect::Nonzero, vcc: MaskEffect::Unchanged, exec: MaskEffect::Unchanged, @@ -619,4 +909,220 @@ pub static FORMS: [FormSemantics; 17] = [ spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "S_CMP_EQ_I32", + family: EncodingFamily::Sopc, + opcode: 0, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LG_I32", + family: EncodingFamily::Sopc, + opcode: 1, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_GT_I32", + family: EncodingFamily::Sopc, + opcode: 2, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_GE_I32", + family: EncodingFamily::Sopc, + opcode: 3, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LT_I32", + family: EncodingFamily::Sopc, + opcode: 4, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Less), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LE_I32", + family: EncodingFamily::Sopc, + opcode: 5, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_EQ_U32", + family: EncodingFamily::Sopc, + opcode: 6, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LG_U32", + family: EncodingFamily::Sopc, + opcode: 7, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_GT_U32", + family: EncodingFamily::Sopc, + opcode: 8, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_GE_U32", + family: EncodingFamily::Sopc, + opcode: 9, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LT_U32", + family: EncodingFamily::Sopc, + opcode: 10, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::Less), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMP_LE_U32", + family: EncodingFamily::Sopc, + opcode: 11, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopcScalar, + spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index e0e4c15..c8a6ea5 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -1,8 +1,8 @@ //! Ties the generated semantic registry tables to the independent XML metadata table. -use xenora_isa::ScalarAluOp; use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS}; use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA}; +use xenora_isa::{ScalarAluOp, ScalarCompareOp}; #[test] fn generated_tables_match_the_schema_and_the_metadata_forms() { @@ -18,43 +18,56 @@ fn generated_tables_match_the_schema_and_the_metadata_forms() { } } -#[test] -fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() { - assert_eq!(ScalarAluOp::ALL.len(), FORMS.len()); - for op in ScalarAluOp::ALL { - let row = op.semantics(); - assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); - assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc); - } +/// Every word of `family` that the XML metadata identifies selects an operation +/// exactly when the registry declares that form, and no 32-bit word of another +/// family selects one. +fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) { + let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect(); let mut selected = 0; - for meta in META_FORMS - .iter() - .filter(|form| form.family == EncodingFamily::Sop2) - { - let word = meta.bits as u32; - match ScalarAluOp::from_word(word) { - Some(op) => { - assert_eq!(op.semantics().name, meta.name); + for meta in META_FORMS.iter().filter(|form| form.family == family) { + match select(meta.bits as u32) { + Some(name) => { + assert_eq!(name, meta.name); selected += 1; } None => assert!( - FORMS.iter().all(|row| row.name != meta.name), + declared.iter().all(|row| row.name != meta.name), "{} is declared but not dispatched", meta.name ), } } - assert_eq!(selected, FORMS.len()); - // Other encodings never reach the SOP2 dispatch. + assert_eq!(selected, declared.len()); for meta in META_FORMS .iter() - .filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4) + .filter(|form| form.family != family && form.bytes == 4) { - assert_eq!( - ScalarAluOp::from_word(meta.bits as u32), - None, - "{}", - meta.name - ); + assert_eq!(select(meta.bits as u32), None, "{}", meta.name); } } + +#[test] +fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() { + for op in ScalarAluOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Sop2); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc); + } + dispatch_selects_exactly(EncodingFamily::Sop2, |word| { + ScalarAluOp::from_word(word).map(|op| op.semantics().name) + }); +} + +#[test] +fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() { + for op in ScalarCompareOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Sopc); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(row.relation, Some(op.relation())); + } + dispatch_selects_exactly(EncodingFamily::Sopc, |word| { + ScalarCompareOp::from_word(word).map(|op| op.semantics().name) + }); +} diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index a145549..cbd5bdc 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -832,8 +832,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { - scc = Some(read_scalar(src0)? == read_scalar(src1)?); + Instruction::ScalarCompare { op, src0, src1 } => { + scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?)); continue; } // docs/shaders/vector-compare.md sections 3 and 5. diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index 075d368..1ee3d1b 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -294,6 +294,20 @@ fn scalar_logic_results_reach_the_kernel_as_constants() { ); } +#[test] +fn scalar_compare_results_resolve_every_branch() { + let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/scalar-compare.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/scalar-compare.metal") + ); +} + #[test] fn vector_compares_lower_to_per_thread_wave_masks_and_selects() { let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 9f9f767..b35e540 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 50 of 50. Accepted Metal forms · Apple M5: 18 of 50. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 61 of 61. Accepted Metal forms · Apple M5: 18 of 61. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -50 / 50 +61 / 61 Accepted Metal forms · Apple M5 -18 / 50 +18 / 61 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index 1b664e9..a9d39c2 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -22,6 +22,17 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified | | `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified | | `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified | +| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | diff --git a/docs/shaders/scalar-alu.md b/docs/shaders/scalar-alu.md index c505c9b..7db07b1 100644 --- a/docs/shaders/scalar-alu.md +++ b/docs/shaders/scalar-alu.md @@ -78,7 +78,7 @@ the registry. ## How it runs Scalar state in a compute fixture is wave-uniform and known while the code is -translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates +translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the IR and MSL contain the results, not scalar instructions. @@ -118,3 +118,20 @@ runs on all three and on native Metal. and the aliasing and immediate cases on native Metal with API and shader validation. `scripts/test-gpu.sh` runs it. This is local evidence from one Apple M5 Pro; independent acceptance is pending. + +## SOPC compares + +The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` +are declared in the same registry (operand rule `sopc_scalar`). Each sets only +SCC, to whether the relation holds with SSRC0 on the left; LG means not equal. +EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare +two's-complement values for `_i32` and unsigned values for `_u32` (guide section +12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one +literal. Both sources selecting the literal encoding (255) is rejected for SOPC +as for SOP2; whether the guide allows one shared literal there was not settled. + +`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected +values derived from the guide separately from the registry, plus 348 rejected +programs, on both CPU interpreters and, through the translator, on native +Metal. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^ +0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form. diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index c1c88fe..6bc8f73 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -26,7 +26,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt | SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | | SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 | -| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | +| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 | | SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | | SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 | | VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | @@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 | -| **Total** | 1465 | 50 | 17 | 54 | 50 | 50 | 18 | 18 | 12 | +| **Total** | 1465 | 61 | 29 | 65 | 61 | 61 | 18 | 18 | 19 | ## Unsupported operand variants @@ -45,3 +45,4 @@ The table counts distinct variant names per family across registry operand rules | Family | Operand rule | Unsupported variants | | --- | --- | --- | | SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` | +| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 92f43c9..a12ab9b 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -55,6 +55,7 @@ error. | `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, never for `add` and `sub`; shifts take their primitive's signedness) | | `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) | | `width` | Operand and result width in bits | `32` | +| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere | | `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere | | `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` | | `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` | @@ -76,6 +77,10 @@ fixes the `scc` value: | `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no | | `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no | | `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no | +| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no | + +A compare must use an operand rule of the compare kind (`sopc_scalar`: two +sources, no destination), and an ALU operation must not. Behaviour is chosen only from these declared fields, never from the mnemonic. diff --git a/docs/status.toml b/docs/status.toml index 245a8dd..5a1621c 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -147,6 +147,138 @@ recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "s_cmp_eq_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)" +representation = "`BF00C108`" +lowering = "resolved SCC" +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_cmp_lg_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)" +representation = "`BF010908`" +lowering = "resolved SCC" +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_cmp_gt_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)" +representation = "`BF020908`" +lowering = "resolved SCC" +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_cmp_ge_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)" +representation = "`BF030909`" +lowering = "resolved SCC" +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_cmp_lt_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)" +representation = "`BF040908`" +lowering = "resolved SCC" +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_cmp_le_i32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)" +representation = "`BF050809`" +lowering = "resolved SCC" +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_cmp_lg_u32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)" +representation = "`BF07C108`" +lowering = "resolved SCC" +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_cmp_gt_u32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)" +representation = "`BF080908`" +lowering = "resolved SCC" +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_cmp_ge_u32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)" +representation = "`BF090809`" +lowering = "resolved SCC" +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_cmp_lt_u32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)" +representation = "`BF0A0809`" +lowering = "resolved SCC" +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_cmp_le_u32" +encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)" +representation = "`BF0BC009`" +lowering = "resolved SCC" +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_add_u32" encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out" diff --git a/fixtures/golden/scalar-compare.ir b/fixtures/golden/scalar-compare.ir new file mode 100644 index 0000000..860cea4 --- /dev/null +++ b/fixtures/golden/scalar-compare.ir @@ -0,0 +1,16 @@ +0000: t0 = load.u32 input[index] +001c: branch.uniform 0x0024 taken=false +0028: branch.uniform 0x0030 taken=false +0034: branch.uniform 0x003c taken=true +0040: branch.uniform 0x0048 taken=false +004c: branch.uniform 0x0054 taken=false +0058: branch.uniform 0x0060 taken=true +0064: branch.uniform 0x006c taken=false +0070: branch.uniform 0x007c taken=true +0080: branch.uniform 0x008c taken=false +0090: branch.uniform 0x009c taken=true +00a0: branch.uniform 0x00ac taken=false +00b0: branch.uniform 0x00bc taken=false +00bc: t13 = const.u32 0x00000d5b +00c0: t14 = xor.b32 t0, t13 +00c4: store.u32 output[index], t14 diff --git a/fixtures/golden/scalar-compare.metal b/fixtures/golden/scalar-compare.metal new file mode 100644 index 0000000..1ed96d9 --- /dev/null +++ b/fixtures/golden/scalar-compare.metal @@ -0,0 +1,11 @@ +#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 t13 = 0x00000d5bu; + uint t14 = t0 ^ t13; + output[index] = t14; +} diff --git a/fixtures/rdna2/scalar-compare.bin b/fixtures/rdna2/scalar-compare.bin new file mode 100644 index 0000000000000000000000000000000000000000..fe70a6af1471e1445d87d0cf38e1b214a558ecdc GIT binary patch literal 212 zcmYMuy$u2}42Iz^KL<9n8Q?~szJ`@<0+gUDfJ7u4ByZLp| m10be<*B`*dy>;tDZ(Dmk_9nn-dr^a(FwPsaswY2hAmks^Iy}Ds literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/scalar-compare.s b/fixtures/rdna2/scalar-compare.s new file mode 100644 index 0000000..45f0de5 --- /dev/null +++ b/fixtures/rdna2/scalar-compare.s @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original SOPC vectors: each of the twelve 32-bit integer compares sets SCC, +// and an s_cbranch_scc0 skips setting that compare's bit in s20, so s20 +// records every result. -1 and 1 separate signed from unsigned ordering; +// inline and literal operands appear in the second position. +// Expected: input ^ 0x00000d5b (bits worked out by hand below). +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen +s_waitcnt vmcnt(0) +s_mov_b32 s8, -1 +s_mov_b32 s9, 1 +s_mov_b32 s20, 0 +s_cmp_eq_i32 s8, -1 // -1 == -1: SCC = 1 +s_cbranch_scc0 .Lskip0 +s_or_b32 s20, s20, 1 +.Lskip0: +s_cmp_lg_i32 s8, s9 // -1 != 1: SCC = 1 +s_cbranch_scc0 .Lskip1 +s_or_b32 s20, s20, 2 +.Lskip1: +s_cmp_gt_i32 s8, s9 // -1 > 1: SCC = 0 +s_cbranch_scc0 .Lskip2 +s_or_b32 s20, s20, 4 +.Lskip2: +s_cmp_ge_i32 s9, s9 // 1 >= 1: SCC = 1 +s_cbranch_scc0 .Lskip3 +s_or_b32 s20, s20, 8 +.Lskip3: +s_cmp_lt_i32 s8, s9 // -1 < 1: SCC = 1 +s_cbranch_scc0 .Lskip4 +s_or_b32 s20, s20, 16 +.Lskip4: +s_cmp_le_i32 s9, s8 // 1 <= -1: SCC = 0 +s_cbranch_scc0 .Lskip5 +s_or_b32 s20, s20, 32 +.Lskip5: +s_cmp_eq_u32 s9, 1 // 1 == 1: SCC = 1 +s_cbranch_scc0 .Lskip6 +s_or_b32 s20, s20, 64 +.Lskip6: +s_cmp_lg_u32 s8, 0xffffffff // 0xffffffff != 0xffffffff: SCC = 0 +s_cbranch_scc0 .Lskip7 +s_or_b32 s20, s20, 0x80 +.Lskip7: +s_cmp_gt_u32 s8, s9 // 0xffffffff > 1: SCC = 1 +s_cbranch_scc0 .Lskip8 +s_or_b32 s20, s20, 0x100 +.Lskip8: +s_cmp_ge_u32 s9, s8 // 1 >= 0xffffffff: SCC = 0 +s_cbranch_scc0 .Lskip9 +s_or_b32 s20, s20, 0x200 +.Lskip9: +s_cmp_lt_u32 s9, s8 // 1 < 0xffffffff: SCC = 1 +s_cbranch_scc0 .Lskip10 +s_or_b32 s20, s20, 0x400 +.Lskip10: +s_cmp_le_u32 s9, 64 // 1 <= 64: SCC = 1 +s_cbranch_scc0 .Lskip11 +s_or_b32 s20, s20, 0x800 +.Lskip11: +v_mov_b32_e32 v2, s20 +v_xor_b32_e32 v2, v1, v2 // s20 = 0x00000d5b +buffer_store_dword v2, v0, s[4:7], 0 idxen +s_waitcnt_vscnt null, 0 +s_endpgm diff --git a/scripts/assemble-fixture.sh b/scripts/assemble-fixture.sh index 225caf5..9a14fcc 100755 --- a/scripts/assemble-fixture.sh +++ b/scripts/assemble-fixture.sh @@ -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 vector-compare scalar-logic; do + x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-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" diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 6e4e927..5c3ffe6 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -68,7 +68,25 @@ def snapshot(): variants[(name, "ENC_SOP2")] = { "instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands, } - return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants} + sopc = { + "name": "ENC_SOPC", + "bits": 32, + "fields": [ + ["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["OP", [[16, 7]]], ["ENCODING", [[23, 9]]], + ], + "identifier_mask": 0xFFFF0000, + "identifiers": [0xBF000000 | (op << 16) for op in (4, 10)], + } + for name, opcode, data_format in (("S_CMP_LT_I32", 4, I32), ("S_CMP_LT_U32", 10, U32)): + variants[(name, "ENC_SOPC")] = { + "instruction": name, "encoding": "ENC_SOPC", "opcode": opcode, + "operands": _operands(data_format)[1:], + } + return { + "source": {"sha256": SHA}, + "encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc}, + "variants": variants, + } def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"): @@ -82,15 +100,32 @@ def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"): } +def compares(): + reg = registry() + reg["form"] += [ + _compare("S_CMP_LT_I32", 4, "CmpLtI32", "lt", "signed"), + _compare("S_CMP_LT_U32", 10, "CmpLtU32", "lt", "unsigned"), + ] + return reg + + +def _compare(name, opcode, variant, relation, signedness): + form = _form(name, opcode, variant, "compare", signedness, "relation") + form.update(family="SOPC", relation=relation, operands="sopc_scalar") + return form + + def registry(): rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"]) rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS) + compare_rule = copy.deepcopy(gen.OPERAND_RULES["sopc_scalar"]["shape"]) + compare_rule["unsupported"] = sorted(gen.OPERAND_RULES["sopc_scalar"]["unsupported"]) return { "schema": 1, "architecture": "gfx1030", "source_sha256": SHA, "documents": copy.deepcopy(gen.PINNED_DOCUMENTS), - "operand_rules": {"sop2_sgpr": rule}, + "operand_rules": {"sop2_sgpr": rule, "sopc_scalar": compare_rule}, "form": [ _form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"), _form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"), @@ -239,7 +274,9 @@ class Validate(unittest.TestCase): reg = registry() form(reg, "S_ADD_U32")["family"] = "SOPC" self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2") - self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC") + self.rejects(reg, "S_ADD_U32: no default ENC_SOPC variant in the XML snapshot") + form(reg, "S_ADD_U32")["family"] = "SOPK" + self.rejects(reg, "S_ADD_U32: family SOPK has no XML encoding ENC_SOPK") def test_rejects_form_absent_from_the_xml(self): reg = registry() @@ -342,6 +379,53 @@ class Validate(unittest.TestCase): gen.render(registry(), snapshot()), ) + def test_accepts_compares(self): + self.assertEqual(self.errors(compares()), []) + + def test_rejects_a_compare_without_a_relation(self): + reg = compares() + del reg["form"][-1]["relation"] + self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation None") + + def test_rejects_an_unknown_relation(self): + reg = compares() + reg["form"][-1]["relation"] = "ne" + self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation 'ne'") + + def test_rejects_a_relation_on_a_non_compare(self): + reg = compares() + reg["form"][0]["relation"] = "lt" + self.rejects(reg, "S_ADD_U32: relation on a non-compare operation") + + def test_rejects_a_compare_with_another_scc_effect(self): + reg = compares() + reg["form"][-1]["scc"] = "nonzero" + self.rejects(reg, "S_CMP_LT_U32: scc nonzero contradicts compare (requires relation)") + + def test_rejects_a_bitwise_compare(self): + reg = compares() + reg["form"][-1]["signedness"] = "bitwise" + self.rejects(reg, "S_CMP_LT_U32: no primitive implements lt/bitwise") + + def test_rejects_a_compare_whose_signedness_contradicts_the_xml(self): + reg = compares() + reg["form"][-1]["signedness"] = "signed" + self.rejects(reg, "S_CMP_LT_U32: signedness signed contradicts XML format FMT_NUM_U32") + + def test_rejects_a_compare_under_an_alu_rule(self): + reg = compares() + reg["form"][0]["operation"] = "compare" + reg["form"][0]["relation"] = "lt" + reg["form"][0]["scc"] = "relation" + self.rejects(reg, "S_ADD_U32: operation compare does not fit rule sop2_sgpr") + + def test_renders_compare_dispatch_and_relation(self): + text = gen.render(compares(), snapshot()) + self.assertIn("if word & 0xff80_0000 != 0xbf00_0000 {", text) + self.assertIn("Self::CmpLtI32 => primitive::lt_i32(src0, src1),", text) + self.assertIn("Self::CmpLtU32 => primitive::lt_u32(src0, src1),", text) + self.assertIn("relation: Some(CompareRelation::Less),", text) + def test_rejects_an_incomplete_unsupported_list(self): reg = registry() reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals") @@ -482,14 +566,14 @@ class Render(unittest.TestCase): reg = registry() reg["form"].reverse() text = gen.render(reg, snapshot()) - body = text.split("const BY_OPCODE: [Option; 128] = [", 1)[1].split("];", 1)[0] + body = text.split("const SCALAR_ALU_OP_BY_OPCODE: [Option; 128] = [", 1)[1].split("];", 1)[0] rows = [line.strip() for line in body.splitlines() if line.strip()] self.assertEqual(len(rows), 128) declared = {index: row for index, row in enumerate(rows) if row != "None,"} self.assertEqual(sorted(declared), [0, 2, 4, 14, 34]) self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),") self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text) - self.assertIn("BY_OPCODE[((word >> 23) & 0x7f) as usize]", text) + self.assertIn("SCALAR_ALU_OP_BY_OPCODE[((word >> 23) & 0x7f) as usize]", text) def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self): snap = snapshot() diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index 2cd427d..8c194f3 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -771,6 +771,9 @@ mod review { const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin"); // Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode. const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8; + const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin"); + // Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode. + const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b; // SOP2 opcodes of the supported subset (RDNA 2 XML opcode table). const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18]; const SCALAR_VALUES: [u32; 10] = [ @@ -890,6 +893,15 @@ mod review { verify(&nonzero, &input, Some(&[0; 5])); } + #[test] + fn scalar_compare_fixture_records_every_registry_compare() { + let input = [0, 1, u32::MAX, SCALAR_COMPARE_KEY, 0x1234_5678]; + let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect(); + verify(SCALAR_COMPARE_FIXTURE, &input, Some(&expected)); + let compiled = compile(Architecture::Gfx1030, SCALAR_COMPARE_FIXTURE).unwrap(); + assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64")); + } + /// The translator's own folding: v2 = D as a constant, and the SCC-zero edge /// is taken exactly when SCC is clear. fn assert_translated(code: &[u8], expected: &[u32; 2]) { @@ -1112,6 +1124,8 @@ mod review { assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected); let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect(); assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic); + let compares: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect(); + assert_eq!(run(SCALAR_COMPARE_FIXTURE, &input), compares); let mut vectors = sop2_vectors(); vectors.extend(sop2_operand_cases()); vectors.extend(signed_immediate_overflows()); @@ -1120,7 +1134,7 @@ mod review { } eprintln!( "{} SOP2 programs matched on native Metal", - vectors.len() + 2 + vectors.len() + 3 ); }