diff --git a/CHANGELOG.md b/CHANGELOG.md index d35d637..992036a 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 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). - Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 658bff2..16ce957 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -4,8 +4,8 @@ use std::fmt; pub use xenora_isa::{ Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, - ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, - VectorSource, + ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, + VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, }; use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, @@ -362,6 +362,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco len0.max(len1), )); } + if let Some(op) = ScalarImmediateOp::from_word(first) { + // SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal. + let dst = ((first >> 16) & 0x7f) as u8; + if dst > 105 { + return Err(unsupported( + op.mnemonic(), + "expected a normal SGPR destination", + )); + } + let simm16 = first as u16; + return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4)); + } + if let Some(op) = ScalarImmediateCompareOp::from_word(first) { + let src = ((first >> 16) & 0x7f) as u8; + if src > 105 { + return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand")); + } + let simm16 = first as u16; + return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4)); + } if S_BRANCH.matches(first) { let target = branch_target(first, offset, "s_branch")?; return Ok((Instruction::Branch { target }, S_BRANCH.byte_len())); diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 94a616d..1c9ee88 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -4,13 +4,13 @@ use std::process::{Command, Stdio}; use xenora_decoder::{ Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, - ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode, - decode_at, + ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, + VectorSource, decode, decode_at, }; use xenora_isa::semantics::Signedness; use xenora_ref::{ - BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu, - VectorInteger, + BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary, + Source, VectorAlu, VectorInteger, }; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); @@ -416,6 +416,25 @@ fn reference_op(instruction: Instruction) -> Op { ), } } + Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate( + match op { + ScalarImmediateOp::MovkI32 => ScalarImmediate::Move, + ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove, + ScalarImmediateOp::AddkI32 => ScalarImmediate::Add, + ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply, + }, + dst, + simm16, + ), + Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate( + ScalarImmediate::Compare(Comparison { + // The reference's VOPC relation offsets, as for SOPC above. + offset: op.relation() as u8 + 1, + signed: op.semantics().signedness == Signedness::Signed, + }), + src, + simm16, + ), Instruction::BranchSccZero { target } => Op::Branch { target, condition: BranchCondition::SccZero, @@ -545,6 +564,7 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"), include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"), include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"), + include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"), include_bytes!("../../../fixtures/rdna2/vector-integer.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"), @@ -553,7 +573,7 @@ fn compares_fixture_instructions_against_llvm() { ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 104, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 120, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() @@ -611,6 +631,12 @@ fn assemble_matrix() -> Vec { s_or_b32 s103, s3, 0x80000000 s_xor_b32 s102, s104, -16 s_xor_b32 s7, s7, lit(0x1) + s_movk_i32 s105, 0xffff + s_movk_i32 s8, 0 + s_cmovk_i32 s105, 0x8000 + s_addk_i32 s9, 0x7fff + s_addk_i32 s105, 0xffff + s_mulk_i32 s8, 0x8001 v_mov_b32_e32 v255, s105 v_mov_b32_e32 v0, s0 v_mov_b32_e32 v128, vcc_lo @@ -636,6 +662,15 @@ fn assemble_matrix() -> Vec { writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap(); } } + // Every SOPK compare on the lowest and highest readable SGPR. + for relation in ["eq", "lg", "gt", "ge", "lt", "le"] { + for kind in ["i32", "u32"] { + for register in ["s0", "s7", "s8", "s105"] { + writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap(); + } + writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap(); + } + } for value in -16..=64 { writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap(); writeln!(assembly, "s_mov_b32 s105, {value}").unwrap(); @@ -1051,3 +1086,108 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() { }) ); } + +#[test] +fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() { + use xenora_decoder::ScalarImmediateCompareOp; + let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes()); + // Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding). + // s_movk_i32 s8, 0x8000 + let decoded = decode_word(0xb008_8000).unwrap(); + assert_eq!(decoded[0].byte_len, 4); + assert_eq!( + decoded[0].instruction, + Instruction::ScalarImmediate { + op: ScalarImmediateOp::MovkI32, + dst: 8, + simm16: 0x8000 + } + ); + // s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is + // the translator's job, not the decoder's. + assert_eq!( + decode_word(0xb169_ffff).unwrap()[0].instruction, + Instruction::ScalarImmediate { + op: ScalarImmediateOp::CmovkI32, + dst: 105, + simm16: 0xffff + } + ); + // s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7. + assert_eq!( + decode_word(0xb580_1234).unwrap()[0].instruction, + Instruction::ScalarImmediateCompare { + op: ScalarImmediateCompareOp::CmpkGtU32, + src: 0, + simm16: 0x1234 + } + ); + assert_eq!( + decode_word(0xb407_ffff).unwrap()[0].instruction, + Instruction::ScalarImmediateCompare { + op: ScalarImmediateCompareOp::CmpkLeI32, + src: 7, + simm16: 0xffff + } + ); + // s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0 + assert_eq!( + decode_word(0xb789_7fff).unwrap()[0].instruction, + Instruction::ScalarImmediate { + op: ScalarImmediateOp::AddkI32, + dst: 9, + simm16: 0x7fff + } + ); + assert_eq!( + decode_word(0xb869_0000).unwrap()[0].instruction, + Instruction::ScalarImmediate { + op: ScalarImmediateOp::MulkI32, + dst: 105, + simm16: 0 + } + ); + // vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused. + for (word, mnemonic, detail) in [ + ( + 0xb06a_0001, + "s_movk_i32", + "expected a normal SGPR destination", + ), + ( + 0xb07e_0001, + "s_movk_i32", + "expected a normal SGPR destination", + ), + ( + 0xb07d_0001, + "s_movk_i32", + "expected a normal SGPR destination", + ), + ( + 0xb06c_0001, + "s_movk_i32", + "expected a normal SGPR destination", + ), + ( + 0xb1fc_0001, + "s_cmpk_eq_i32", + "expected a normal SGPR operand", + ), + ] { + assert_eq!( + decode_word(word).unwrap_err().kind, + DecodeErrorKind::UnsupportedForm { mnemonic, detail }, + "{word:#010x}" + ); + } + // Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported. + for word in [0xb080_0000u32, 0xb888_0000] { + assert!(decode_word(word).is_err(), "{word:#010x}"); + } + // The fixed store fence is still the one decoded SOPK word outside the registry. + assert_eq!( + decode_word(0xbbfd_0000).unwrap()[0].instruction, + Instruction::WaitStore + ); +} diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 2362748..1e32c6c 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -61,6 +61,7 @@ OPERATIONS = { "mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract", "absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd", "mul24": "Multiply24", "mul_hi24": "MultiplyHigh24", + "mov": "Move", "cmov": "ConditionalMove", } # Unary operations read one source; they need an operand rule of the unary kind. UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"} @@ -106,7 +107,7 @@ SHIFTS = {"lshl", "lshr", "ashr"} # descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness. CONTROL_S1 = SHIFTS | {"bfe"} # Operations that always read SCC: the select condition. They need carry_in scc. -SCC_READERS = {"cselect"} +SCC_READERS = {"cselect", "cmov"} # XML number formats a source may have for each declared signedness. SOURCE_FORMATS = { "signed": {"FMT_NUM_I32"}, @@ -208,6 +209,22 @@ PRIMITIVES = { ("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False), } +# SOPK forms (operation, signedness) -> (SCC effect, primitive, reads SCC). D is +# SDST and the immediate is SIMM16 sign-extended (guide 12.2); `sext_simm16` is +# the sign extension, so a move or conditional move writes it unchanged. +IMMEDIATE_PRIMITIVES = { + ("mov", "signed"): ("unchanged", "sext_simm16", False), + ("cmov", "signed"): ("unchanged", "sext_simm16", True), + ("add", "signed"): ("signed_overflow", "add_overflow_i32", False), + ("mul", "signed"): ("unchanged", "mul_lo_i32", False), +} +# SOPK compares: the opcode is the group base (3 signed, 9 unsigned) plus the +# relation's index in this order (guide 13.1.2). +SOPK_COMPARE_BASES = {"signed": 3, "unsigned": 9} +SOPK_RELATION_ORDER = ["eq", "lg", "gt", "ge", "lt", "le"] +# Operand-rule kinds whose forms have a 16-bit immediate field. +IMMEDIATE_KINDS = {"immediate", "immediate_compare"} + # Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their # MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged. VECTOR_PRIMITIVES = { @@ -286,6 +303,34 @@ OPERAND_RULES = { "unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"}, "kind": "unary", }, + "sopk_sgpr": { + "rust": "SopkSgpr", + "enum": "ScalarImmediateOp", + "shape": { + "family": "SOPK", + "dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105}, + "src": [{"field": "SIMM16", "class": "simm16"}], + "max_literals": 0, + }, + # SOPK never takes a literal dword; the decoder rejects SDST 106-127. + "unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")}, + "kind": "immediate", + }, + "sopk_compare": { + "rust": "SopkCompare", + "enum": "ScalarImmediateCompareOp", + "shape": { + "family": "SOPK", + "src": [ + {"field": "SDST", "class": "sgpr", "min": 0, "max": 105}, + {"field": "SIMM16", "class": "simm16"}, + ], + "max_literals": 0, + }, + # The compared register is SDST (S0); the decoder rejects SDST 106-127. + "unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")}, + "kind": "immediate_compare", + }, "vopc_vcc": { "rust": "VopcVcc", "enum": "VectorCompareOp", @@ -579,6 +624,15 @@ def _check_xml(form, rule, snapshot, errors): errors.append(f"{label}: XML has no operand {field}") continue data_format, size, is_input, is_output = operands[field] + if field == "SIMM16": + # The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign + # extended), unsigned compares as FMT_NUM_U16 (zero extended). + wanted = "FMT_NUM_U16" if form["signedness"] == "unsigned" else "FMT_NUM_I16" + if size != 16 or data_format != wanted: + errors.append(f"{label}: SIMM16 is {size} bits {data_format} in the XML, expected 16 {wanted}") + if (is_input, is_output) != (True, False): + errors.append(f"{label}: {field} direction disagrees with the XML") + continue bits = form.get(SOURCE_BITS_KEY) if is_source else None expected = bits if type(bits) is int else form["width"] if size != expected: @@ -730,6 +784,15 @@ def validate(registry, snapshot): errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare": errors.append(f"{label}: relation {relation} exists only for VOPC compares") + elif _rule_kind(form) == "immediate_compare": + base = SOPK_COMPARE_BASES.get(form["signedness"]) + expected = None if base is None else base + SOPK_RELATION_ORDER.index(relation) \ + if relation in SOPK_RELATION_ORDER else None + if form["opcode"] != expected: + errors.append( + f"{label}: relation {relation}/{form['signedness']} has SOPK opcode " + f"{expected} (guide 13.1.2), not {form['opcode']}" + ) elif _rule_kind(form) == "vector_compare": base = VOPC_INTEGER_BASES.get(form["signedness"]) expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation] @@ -753,7 +816,8 @@ def validate(registry, snapshot): else: if RELATION_KEY in form: errors.append(f"{label}: {RELATION_KEY} on a non-compare operation") - primitive = PRIMITIVES.get((form["operation"], form["signedness"])) + table = IMMEDIATE_PRIMITIVES if _rule_kind(form) == "immediate" else PRIMITIVES + primitive = table.get((form["operation"], form["signedness"])) if primitive is None: errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}") else: @@ -773,10 +837,11 @@ def validate(registry, snapshot): 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"] != ( - ("vector_compare" if _rule_kind(form) == "vector_compare" else "compare") + (_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare") if form["operation"] == "compare" 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" else "alu" ): errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}") @@ -1209,6 +1274,98 @@ def _render_enum(rule_name, forms, snapshot, positions): " }]", " }", ] + if kind == "immediate": + out += [ + "", + " /// Whether the operation reads SCC (the conditional move's condition).", + " pub const fn reads_scc(self) -> bool {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'}," + for form in forms + ] + out += [ + " }", + " }", + "", + " /// Whether the operation writes SCC.", + " pub const fn writes_scc(self) -> bool {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'}," + for form in forms + ] + out += [ + " }", + " }", + "", + " /// Whether the operation always reads the old SDST (`D = D op imm`).", + " pub const fn reads_dst(self) -> bool {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => {'true' if form['operation'] in ('add', 'mul') else 'false'}," + for form in forms + ] + out += [ + " }", + " }", + "", + " /// The new SDST (`None` leaves it unchanged) and, for forms that write it, the", + " /// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by", + " /// forms that do not read it) and `scc_in` the SCC read by the conditional move.", + " pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option, Option) {", + " match self {", + ] + for form in forms: + _, function, _ = IMMEDIATE_PRIMITIVES[(form["operation"], form["signedness"])] + immediate = "primitive::sext_simm16(simm16)" + variant = form["variant"] + if form["operation"] == "mov": + out.append(f" Self::{variant} => (Some({immediate}), None),") + elif form["operation"] == "cmov": + out.append( + f" Self::{variant} => (if scc_in {{ Some({immediate}) }} else {{ None }}, None)," + ) + elif form["scc"] == "unchanged": + out.append(f" Self::{variant} => (Some(primitive::{function}(dst, {immediate})), None),") + else: + out += [ + f" Self::{variant} => {{", + f" let (value, scc) = primitive::{function}(dst, {immediate});", + " (Some(value), Some(scc))", + " }", + ] + out += [" }", " }", "}"] + return out + if kind == "immediate_compare": + out += [ + "", + " /// The relation tested, with SDST (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 SCC: whether the relation holds for SDST and SIMM16, which signed forms", + " /// sign-extend and unsigned forms zero-extend.", + " pub const fn test(self, dst: u32, simm16: u16) -> bool {", + " match self {", + ] + for form in forms: + function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])] + immediate = "primitive::sext_simm16(simm16)" if form["signedness"] == "signed" else "simm16 as u32" + out.append(f" Self::{form['variant']} => primitive::{function}(dst, {immediate}),") + out += [" }", " }", "}"] + return out if kind == "unary": out += [ "", diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index cf21825..678174a 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -19,6 +19,7 @@ source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f include = [ "rdna2/sop2.toml", "rdna2/sopc.toml", + "rdna2/sopk.toml", "rdna2/sop1.toml", "rdna2/vop2.toml", "rdna2/vopc.toml", diff --git a/crates/isa/semantics/rdna2/sopk.toml b/crates/isa/semantics/rdna2/sopk.toml new file mode 100644 index 0000000..e3138e9 --- /dev/null +++ b/crates/isa/semantics/rdna2/sopk.toml @@ -0,0 +1,358 @@ +# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- SOPK 16-bit immediate integer forms (#215) ---- +# SDST is the destination, and the left operand of the compares; SIMM16 is +# sign-extended except by the unsigned compares (guide 12.2). The word never +# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors, +# so the decoder accepts them as compare operands and the translator never +# writes them. + +[operand_rules.sopk_sgpr] +family = "SOPK" +dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } +src = [{ field = "SIMM16", class = "simm16" }] +max_literals = 0 +unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"] + +[operand_rules.sopk_compare] +family = "SOPK" +src = [ + { field = "SDST", class = "sgpr", min = 0, max = 105 }, + { field = "SIMM16", class = "simm16" }, +] +max_literals = 0 +unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"] + +[[form]] +name = "S_MOVK_I32" +family = "SOPK" +opcode = 0 +variant = "MovkI32" +operation = "mov" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_sgpr" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMOVK_I32" +family = "SOPK" +opcode = 2 +variant = "CmovkI32" +operation = "cmov" +signedness = "signed" +carry_in = "scc" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_sgpr" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_EQ_I32" +family = "SOPK" +opcode = 3 +variant = "CmpkEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LG_I32" +family = "SOPK" +opcode = 4 +variant = "CmpkLgI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_GT_I32" +family = "SOPK" +opcode = 5 +variant = "CmpkGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_GE_I32" +family = "SOPK" +opcode = 6 +variant = "CmpkGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LT_I32" +family = "SOPK" +opcode = 7 +variant = "CmpkLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LE_I32" +family = "SOPK" +opcode = 8 +variant = "CmpkLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_EQ_U32" +family = "SOPK" +opcode = 9 +variant = "CmpkEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LG_U32" +family = "SOPK" +opcode = 10 +variant = "CmpkLgU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_GT_U32" +family = "SOPK" +opcode = 11 +variant = "CmpkGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_GE_U32" +family = "SOPK" +opcode = 12 +variant = "CmpkGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LT_U32" +family = "SOPK" +opcode = 13 +variant = "CmpkLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMPK_LE_U32" +family = "SOPK" +opcode = 14 +variant = "CmpkLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_compare" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ADDK_I32" +family = "SOPK" +opcode = 15 +variant = "AddkI32" +operation = "add" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "signed_overflow" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_sgpr" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MULK_I32" +family = "SOPK" +opcode = 16 +variant = "MulkI32" +operation = "mul" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopk_sgpr" +spec = [ + { document = "guide", section = "12.2", page = 106 }, + { document = "guide", section = "13.1.2", page = 240 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index e902f62..a7b9f3b 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -19,7 +19,8 @@ pub use rdna2::{ V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; pub use semantics_gen::{ - ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, + ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp, + VectorAluOp, VectorAluVop3Op, VectorCompareOp, }; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. @@ -185,6 +186,21 @@ pub enum Instruction { src0: ScalarSource, src1: ScalarSource, }, + /// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the + /// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and + /// `s_cmovk_i32` reads it. + ScalarImmediate { + op: ScalarImmediateOp, + dst: u8, + simm16: u16, + }, + /// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit + /// immediate, writing only SCC. + ScalarImmediateCompare { + op: ScalarImmediateCompareOp, + src: u8, + simm16: u16, + }, /// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`. /// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal. VectorCompare { @@ -270,6 +286,8 @@ impl Instruction { Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), Self::ScalarCompare { op, .. } => op.mnemonic(), + Self::ScalarImmediate { op, .. } => op.mnemonic(), + Self::ScalarImmediateCompare { op, .. } => op.mnemonic(), Self::VectorCompare { op, .. } => op.assembly_name(), Self::VectorAlu { op, .. } => op.assembly_name(), Self::BranchSccZero { .. } => "s_cbranch_scc0", @@ -330,6 +348,12 @@ impl fmt::Display for Instruction { dst, src0, src1, .. } => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)), Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"), + Self::ScalarImmediate { dst, simm16, .. } => { + write!(formatter, " s{dst}, {simm16:#x}") + } + Self::ScalarImmediateCompare { src, simm16, .. } => { + write!(formatter, " s{src}, {simm16:#x}") + } 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 bc4eea8..198b2df 100644 --- a/crates/isa/src/primitive.rs +++ b/crates/isa/src/primitive.rs @@ -218,6 +218,11 @@ pub const fn sext_i32(a: u32, bits: u32) -> u32 { (((a << shift) as i32) >> shift) as u32 } +/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2). +pub const fn sext_simm16(simm16: u16) -> u32 { + simm16 as i16 as i32 as u32 +} + /// Two's-complement absolute value (wrapping, so `0x80000000` stays) and /// whether the result is nonzero. pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) { diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index 4b38981..a987466 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -90,6 +90,10 @@ pub enum Operation { Multiply24, /// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed). MultiplyHigh24, + /// SOPK: SDST receives the sign-extended SIMM16. + Move, + /// SOPK: SDST receives the sign-extended SIMM16 when SCC is set. + ConditionalMove, } /// The per-lane integer operation a vector form lowers to. One reusable MSL @@ -204,6 +208,13 @@ pub enum OperandRule { /// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or /// a literal word. Everything else is rejected as unsupported. Sop1Sgpr, + /// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7, + /// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word + /// never takes a literal. Everything else is rejected as unsupported. + SopkSgpr, + /// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right + /// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written. + SopkCompare, /// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR, /// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a /// VGPR. Everything else is rejected as unsupported. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index af57a2d..42aee2b 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -344,17 +344,17 @@ impl ScalarUnaryOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::NotB32 => 45, - Self::BrevB32 => 46, - Self::Bcnt0I32B32 => 47, - Self::Bcnt1I32B32 => 48, - Self::Ff0I32B32 => 49, - Self::Ff1I32B32 => 50, - Self::FlbitI32B32 => 51, - Self::FlbitI32 => 52, - Self::SextI32I8 => 53, - Self::SextI32I16 => 54, - Self::AbsI32 => 55, + Self::NotB32 => 61, + Self::BrevB32 => 62, + Self::Bcnt0I32B32 => 63, + Self::Bcnt1I32B32 => 64, + Self::Ff0I32B32 => 65, + Self::Ff1I32B32 => 66, + Self::FlbitI32B32 => 67, + Self::FlbitI32 => 68, + Self::SextI32I8 => 69, + Self::SextI32I16 => 70, + Self::AbsI32 => 71, }] } @@ -1198,6 +1198,304 @@ impl ScalarCompareOp { } } +/// SOPK operations declared in the semantic registry (operand rule `sopk_compare`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarImmediateCompareOp { + /// `s_cmpk_eq_i32` (SOPK opcode 3): signed compare eq, SCC = relation. + CmpkEqI32, + /// `s_cmpk_lg_i32` (SOPK opcode 4): signed compare lg, SCC = relation. + CmpkLgI32, + /// `s_cmpk_gt_i32` (SOPK opcode 5): signed compare gt, SCC = relation. + CmpkGtI32, + /// `s_cmpk_ge_i32` (SOPK opcode 6): signed compare ge, SCC = relation. + CmpkGeI32, + /// `s_cmpk_lt_i32` (SOPK opcode 7): signed compare lt, SCC = relation. + CmpkLtI32, + /// `s_cmpk_le_i32` (SOPK opcode 8): signed compare le, SCC = relation. + CmpkLeI32, + /// `s_cmpk_eq_u32` (SOPK opcode 9): unsigned compare eq, SCC = relation. + CmpkEqU32, + /// `s_cmpk_lg_u32` (SOPK opcode 10): unsigned compare lg, SCC = relation. + CmpkLgU32, + /// `s_cmpk_gt_u32` (SOPK opcode 11): unsigned compare gt, SCC = relation. + CmpkGtU32, + /// `s_cmpk_ge_u32` (SOPK opcode 12): unsigned compare ge, SCC = relation. + CmpkGeU32, + /// `s_cmpk_lt_u32` (SOPK opcode 13): unsigned compare lt, SCC = relation. + CmpkLtU32, + /// `s_cmpk_le_u32` (SOPK opcode 14): unsigned compare le, SCC = relation. + CmpkLeU32, +} + +/// ScalarImmediateCompareOp by SOPK OP field value; `None` for undeclared opcodes. +const SCALAR_IMMEDIATE_COMPARE_OP_BY_OPCODE: [Option; 32] = [ + None, + None, + None, + Some(ScalarImmediateCompareOp::CmpkEqI32), + Some(ScalarImmediateCompareOp::CmpkLgI32), + Some(ScalarImmediateCompareOp::CmpkGtI32), + Some(ScalarImmediateCompareOp::CmpkGeI32), + Some(ScalarImmediateCompareOp::CmpkLtI32), + Some(ScalarImmediateCompareOp::CmpkLeI32), + Some(ScalarImmediateCompareOp::CmpkEqU32), + Some(ScalarImmediateCompareOp::CmpkLgU32), + Some(ScalarImmediateCompareOp::CmpkGtU32), + Some(ScalarImmediateCompareOp::CmpkGeU32), + Some(ScalarImmediateCompareOp::CmpkLtU32), + Some(ScalarImmediateCompareOp::CmpkLeU32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl ScalarImmediateCompareOp { + /// Every operation, in registry order. + pub const ALL: [Self; 12] = [ + Self::CmpkEqI32, + Self::CmpkLgI32, + Self::CmpkGtI32, + Self::CmpkGeI32, + Self::CmpkLtI32, + Self::CmpkLeI32, + Self::CmpkEqU32, + Self::CmpkLgU32, + Self::CmpkGtU32, + Self::CmpkGeU32, + Self::CmpkLtU32, + Self::CmpkLeU32, + ]; + + /// Selects the operation from a first instruction word: the SOPK encoding + /// bits (mask 0xf000_0000) and then the OP field (bits 23-27). + pub const fn from_word(word: u32) -> Option { + if word & 0xf000_0000 != 0xb000_0000 { + return None; + } + SCALAR_IMMEDIATE_COMPARE_OP_BY_OPCODE[((word >> 23) & 0x1f) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::CmpkEqI32 => "s_cmpk_eq_i32", + Self::CmpkLgI32 => "s_cmpk_lg_i32", + Self::CmpkGtI32 => "s_cmpk_gt_i32", + Self::CmpkGeI32 => "s_cmpk_ge_i32", + Self::CmpkLtI32 => "s_cmpk_lt_i32", + Self::CmpkLeI32 => "s_cmpk_le_i32", + Self::CmpkEqU32 => "s_cmpk_eq_u32", + Self::CmpkLgU32 => "s_cmpk_lg_u32", + Self::CmpkGtU32 => "s_cmpk_gt_u32", + Self::CmpkGeU32 => "s_cmpk_ge_u32", + Self::CmpkLtU32 => "s_cmpk_lt_u32", + Self::CmpkLeU32 => "s_cmpk_le_u32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::CmpkEqI32 => 47, + Self::CmpkLgI32 => 48, + Self::CmpkGtI32 => 49, + Self::CmpkGeI32 => 50, + Self::CmpkLtI32 => 51, + Self::CmpkLeI32 => 52, + Self::CmpkEqU32 => 53, + Self::CmpkLgU32 => 54, + Self::CmpkGtU32 => 55, + Self::CmpkGeU32 => 56, + Self::CmpkLtU32 => 57, + Self::CmpkLeU32 => 58, + }] + } + + /// The relation tested, with SDST (S0) on the left. + pub const fn relation(self) -> CompareRelation { + match self { + Self::CmpkEqI32 => CompareRelation::Equal, + Self::CmpkLgI32 => CompareRelation::NotEqual, + Self::CmpkGtI32 => CompareRelation::Greater, + Self::CmpkGeI32 => CompareRelation::GreaterOrEqual, + Self::CmpkLtI32 => CompareRelation::Less, + Self::CmpkLeI32 => CompareRelation::LessOrEqual, + Self::CmpkEqU32 => CompareRelation::Equal, + Self::CmpkLgU32 => CompareRelation::NotEqual, + Self::CmpkGtU32 => CompareRelation::Greater, + Self::CmpkGeU32 => CompareRelation::GreaterOrEqual, + Self::CmpkLtU32 => CompareRelation::Less, + Self::CmpkLeU32 => CompareRelation::LessOrEqual, + } + } + + /// The SCC: whether the relation holds for SDST and SIMM16, which signed forms + /// sign-extend and unsigned forms zero-extend. + pub const fn test(self, dst: u32, simm16: u16) -> bool { + match self { + Self::CmpkEqI32 => primitive::eq_b32(dst, primitive::sext_simm16(simm16)), + Self::CmpkLgI32 => primitive::ne_b32(dst, primitive::sext_simm16(simm16)), + Self::CmpkGtI32 => primitive::gt_i32(dst, primitive::sext_simm16(simm16)), + Self::CmpkGeI32 => primitive::ge_i32(dst, primitive::sext_simm16(simm16)), + Self::CmpkLtI32 => primitive::lt_i32(dst, primitive::sext_simm16(simm16)), + Self::CmpkLeI32 => primitive::le_i32(dst, primitive::sext_simm16(simm16)), + Self::CmpkEqU32 => primitive::eq_b32(dst, simm16 as u32), + Self::CmpkLgU32 => primitive::ne_b32(dst, simm16 as u32), + Self::CmpkGtU32 => primitive::gt_u32(dst, simm16 as u32), + Self::CmpkGeU32 => primitive::ge_u32(dst, simm16 as u32), + Self::CmpkLtU32 => primitive::lt_u32(dst, simm16 as u32), + Self::CmpkLeU32 => primitive::le_u32(dst, simm16 as u32), + } + } +} + +/// SOPK operations declared in the semantic registry (operand rule `sopk_sgpr`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarImmediateOp { + /// `s_movk_i32` (SOPK opcode 0): signed mov, SCC = unchanged. + MovkI32, + /// `s_cmovk_i32` (SOPK opcode 2): signed cmov plus SCC, SCC = unchanged. + CmovkI32, + /// `s_addk_i32` (SOPK opcode 15): signed add, SCC = signed_overflow. + AddkI32, + /// `s_mulk_i32` (SOPK opcode 16): signed mul, SCC = unchanged. + MulkI32, +} + +/// ScalarImmediateOp by SOPK OP field value; `None` for undeclared opcodes. +const SCALAR_IMMEDIATE_OP_BY_OPCODE: [Option; 32] = [ + Some(ScalarImmediateOp::MovkI32), + None, + Some(ScalarImmediateOp::CmovkI32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(ScalarImmediateOp::AddkI32), + Some(ScalarImmediateOp::MulkI32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl ScalarImmediateOp { + /// Every operation, in registry order. + pub const ALL: [Self; 4] = [ + Self::MovkI32, + Self::CmovkI32, + Self::AddkI32, + Self::MulkI32, + ]; + + /// Selects the operation from a first instruction word: the SOPK encoding + /// bits (mask 0xf000_0000) and then the OP field (bits 23-27). + pub const fn from_word(word: u32) -> Option { + if word & 0xf000_0000 != 0xb000_0000 { + return None; + } + SCALAR_IMMEDIATE_OP_BY_OPCODE[((word >> 23) & 0x1f) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::MovkI32 => "s_movk_i32", + Self::CmovkI32 => "s_cmovk_i32", + Self::AddkI32 => "s_addk_i32", + Self::MulkI32 => "s_mulk_i32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::MovkI32 => 45, + Self::CmovkI32 => 46, + Self::AddkI32 => 59, + Self::MulkI32 => 60, + }] + } + + /// Whether the operation reads SCC (the conditional move's condition). + pub const fn reads_scc(self) -> bool { + match self { + Self::MovkI32 => false, + Self::CmovkI32 => true, + Self::AddkI32 => false, + Self::MulkI32 => false, + } + } + + /// Whether the operation writes SCC. + pub const fn writes_scc(self) -> bool { + match self { + Self::MovkI32 => false, + Self::CmovkI32 => false, + Self::AddkI32 => true, + Self::MulkI32 => false, + } + } + + /// Whether the operation always reads the old SDST (`D = D op imm`). + pub const fn reads_dst(self) -> bool { + match self { + Self::MovkI32 => false, + Self::CmovkI32 => false, + Self::AddkI32 => true, + Self::MulkI32 => true, + } + } + + /// The new SDST (`None` leaves it unchanged) and, for forms that write it, the + /// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by + /// forms that do not read it) and `scc_in` the SCC read by the conditional move. + pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option, Option) { + match self { + Self::MovkI32 => (Some(primitive::sext_simm16(simm16)), None), + Self::CmovkI32 => (if scc_in { Some(primitive::sext_simm16(simm16)) } else { None }, None), + Self::AddkI32 => { + let (value, scc) = primitive::add_overflow_i32(dst, primitive::sext_simm16(simm16)); + (Some(value), Some(scc)) + } + Self::MulkI32 => (Some(primitive::mul_lo_i32(dst, primitive::sext_simm16(simm16))), None), + } + } +} + /// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`). #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAluOp { @@ -1366,24 +1664,24 @@ impl VectorAluOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::MulI32I24 => 56, - Self::MulHiI32I24 => 57, - Self::MulU32U24 => 58, - Self::MulHiU32U24 => 59, - Self::MinI32 => 60, - Self::MaxI32 => 61, - Self::MinU32 => 62, - Self::MaxU32 => 63, - Self::XnorB32 => 64, - Self::AddNcU32 => 65, - Self::SubNcU32 => 66, - Self::SubrevNcU32 => 67, - Self::LshrrevB32 => 68, - Self::AshrrevI32 => 69, - Self::LshlrevB32 => 70, - Self::AndB32 => 71, - Self::OrB32 => 72, - Self::XorB32 => 73, + 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, }] } @@ -1836,22 +2134,22 @@ impl VectorCompareOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::CmpLtI32 => 74, - Self::CmpEqI32 => 75, - Self::CmpLeI32 => 76, - Self::CmpGtI32 => 77, - Self::CmpNeI32 => 78, - Self::CmpGeI32 => 79, - Self::CmpLtU32 => 80, - Self::CmpEqU32 => 81, - Self::CmpLeU32 => 82, - Self::CmpGtU32 => 83, - Self::CmpNeU32 => 84, - Self::CmpGeU32 => 85, - Self::CmpFI32 => 86, - Self::CmpTI32 => 87, - Self::CmpFU32 => 88, - Self::CmpTU32 => 89, + 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, }] } @@ -1987,13 +2285,13 @@ impl VectorAluVop3Op { /// The validated registry row of this encoding. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::AddNcU32 => 90, + Self::AddNcU32 => 106, }] } } /// Identity of every registry form and encoding variant, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 91] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 107] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -2039,6 +2337,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 91] = [ ("S_CMP_GE_U32", EncodingFamily::Sopc), ("S_CMP_LT_U32", EncodingFamily::Sopc), ("S_CMP_LE_U32", EncodingFamily::Sopc), + ("S_MOVK_I32", EncodingFamily::Sopk), + ("S_CMOVK_I32", EncodingFamily::Sopk), + ("S_CMPK_EQ_I32", EncodingFamily::Sopk), + ("S_CMPK_LG_I32", EncodingFamily::Sopk), + ("S_CMPK_GT_I32", EncodingFamily::Sopk), + ("S_CMPK_GE_I32", EncodingFamily::Sopk), + ("S_CMPK_LT_I32", EncodingFamily::Sopk), + ("S_CMPK_LE_I32", EncodingFamily::Sopk), + ("S_CMPK_EQ_U32", EncodingFamily::Sopk), + ("S_CMPK_LG_U32", EncodingFamily::Sopk), + ("S_CMPK_GT_U32", EncodingFamily::Sopk), + ("S_CMPK_GE_U32", EncodingFamily::Sopk), + ("S_CMPK_LT_U32", EncodingFamily::Sopk), + ("S_CMPK_LE_U32", EncodingFamily::Sopk), + ("S_ADDK_I32", EncodingFamily::Sopk), + ("S_MULK_I32", EncodingFamily::Sopk), ("S_NOT_B32", EncodingFamily::Sop1), ("S_BREV_B32", EncodingFamily::Sop1), ("S_BCNT0_I32_B32", EncodingFamily::Sop1), @@ -2088,7 +2402,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 91] = [ ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 91] = [ +pub static FORMS: [FormSemantics; 107] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3034,6 +3348,342 @@ pub static FORMS: [FormSemantics; 91] = [ 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_MOVK_I32", + family: EncodingFamily::Sopk, + opcode: 0, + operation: Operation::Move, + 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::Any, + operands: OperandRule::SopkSgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMOVK_I32", + family: EncodingFamily::Sopk, + opcode: 2, + operation: Operation::ConditionalMove, + signedness: Signedness::Signed, + carry_in: CarryIn::Scc, + 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::Any, + operands: OperandRule::SopkSgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_EQ_I32", + family: EncodingFamily::Sopk, + opcode: 3, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LG_I32", + family: EncodingFamily::Sopk, + opcode: 4, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_GT_I32", + family: EncodingFamily::Sopk, + opcode: 5, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_GE_I32", + family: EncodingFamily::Sopk, + opcode: 6, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LT_I32", + family: EncodingFamily::Sopk, + opcode: 7, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LE_I32", + family: EncodingFamily::Sopk, + opcode: 8, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_EQ_U32", + family: EncodingFamily::Sopk, + opcode: 9, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LG_U32", + family: EncodingFamily::Sopk, + opcode: 10, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_GT_U32", + family: EncodingFamily::Sopk, + opcode: 11, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_GE_U32", + family: EncodingFamily::Sopk, + opcode: 12, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LT_U32", + family: EncodingFamily::Sopk, + opcode: 13, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CMPK_LE_U32", + family: EncodingFamily::Sopk, + opcode: 14, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Relation, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkCompare, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_ADDK_I32", + family: EncodingFamily::Sopk, + opcode: 15, + operation: Operation::Add, + 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::SignedOverflow, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::SopkSgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MULK_I32", + family: EncodingFamily::Sopk, + opcode: 16, + operation: Operation::Multiply, + 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::Any, + operands: OperandRule::SopkSgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "S_NOT_B32", family: EncodingFamily::Sop1, diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 744f085..b1b4655 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -5,8 +5,8 @@ use xenora_isa::semantics::{ CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave, }; use xenora_isa::{ - CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, - VectorCompareOp, + CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, + ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, }; #[test] @@ -78,6 +78,64 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() { }); } +#[test] +fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() { + for op in ScalarImmediateOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Sopk); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc); + assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged); + } + for op in ScalarImmediateCompareOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Sopk); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(row.relation, Some(op.relation())); + } + // The two enums together are the registry's SOPK forms; the fixed + // s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither. + dispatch_selects_exactly(EncodingFamily::Sopk, |word| { + ScalarImmediateOp::from_word(word) + .map(|op| op.semantics().name) + .or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name)) + }); +} + +#[test] +fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() { + // SIMM16 = 0x8000 is -32768 signed and 32768 unsigned. + let d = 0xffff_8000; + assert_eq!( + ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false), + (Some(d), None) + ); + assert_eq!( + ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true), + (Some(d), None) + ); + assert_eq!( + ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false), + (None, None) + ); + assert_eq!( + ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false), + (Some(0x8000_0000), Some(true)) + ); + assert_eq!( + ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false), + (Some(4), Some(false)) + ); + assert_eq!( + ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true), + (Some(0xffff_fffd), None) + ); + assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000)); + assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000)); + assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff)); + assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff)); +} + #[test] fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() { for op in ScalarUnaryOp::ALL { diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index df0a44c..34cb085 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -68,6 +68,8 @@ pub enum Op { /// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing /// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11. ScalarCompare(Comparison, Source, Source), + /// SOPK operation on SGPR `SDST` (s0-s105) and the raw SIMM16. + ScalarImmediate(ScalarImmediate, u8, u16), Branch { target: usize, condition: BranchCondition, @@ -281,6 +283,23 @@ pub enum ScalarUnary { Absolute, } +/// SOPK operations decoded by the reference interpreter (RDNA 2 ISA guide +/// 12.2; SCC per Tables 11, 12, 13 and 14). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarImmediate { + /// 0 `s_movk_i32`: D = signext(SIMM16). + Move, + /// 2 `s_cmovk_i32`: if SCC, D = signext(SIMM16); SCC unchanged. + ConditionalMove, + /// 3-14 `s_cmpk_*`: SCC = (D K), K = signext(SIMM16) for the + /// signed forms 3-8 and SIMM16 zero-extended for the unsigned 9-14. + Compare(Comparison), + /// 15 `s_addk_i32`: D = D + signext(SIMM16), SCC = signed overflow. + Add, + /// 16 `s_mulk_i32`: D = low 32 bits of D * signext(SIMM16); SCC unchanged. + Multiply, +} + /// VOP2 operations decoded by the reference interpreter. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAlu { @@ -589,6 +608,26 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { }; (op, left_length.max(right_length)) } + // SOPK (guide 13.1.2): ENCODING 0b1011 in bits 28-31, OP 23-27, + // SDST 16-22 (s0-s105 only), SIMM16 0-15. The format never takes + // a literal dword (guide 12.2), so the word is always 4 bytes. + [lo, hi, low, high @ 0xb0..=0xb8, ..] + if low & 0x7f <= 105 && matches!((high & 0xf) << 1 | low >> 7, 0 | 2..=16) => + { + let kind = match (high & 0xf) << 1 | low >> 7 { + 0 => ScalarImmediate::Move, + 2 => ScalarImmediate::ConditionalMove, + // EQ, LG, GT, GE, LT, LE as VOPC relation offsets (see SOPC). + op @ 3..=14 => ScalarImmediate::Compare(Comparison { + offset: [2, 5, 4, 6, 1, 3][usize::from((op - 3) % 6)], + signed: op <= 8, + }), + 15 => ScalarImmediate::Add, + _ => ScalarImmediate::Multiply, + }; + let simm16 = u16::from_le_bytes([*lo, *hi]); + (Op::ScalarImmediate(kind, low & 0x7f, simm16), 4) + } // SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0. [left, right, low, high @ 0x80..=0xbf, tail @ ..] if (*left, *right) != (255, 255) @@ -1158,6 +1197,48 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result { scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?)); } + // Guide 12.2: SDST is also the second source; SIMM16 is + // sign-extended except by the unsigned compares. + Op::ScalarImmediate(kind, dst, simm16) => { + let extended = i32::from(simm16 as i16); + if let ScalarImmediate::Compare(comparison) = kind { + let constant = if comparison.signed { + extended as u32 + } else { + u32::from(simm16) + }; + let value = read_scalar(Source::Register(dst))?; + scc = Some(comparison.holds(value, constant)); + } else { + if dst < 8 { + return Err(error(offset, "write to a reserved resource SGPR")); + } + let value = match kind { + ScalarImmediate::ConditionalMove + if !scc + .ok_or_else(|| error(offset, "move on uninitialized SCC"))? => + { + None + } + ScalarImmediate::Add => { + let exact = i64::from(read_scalar(Source::Register(dst))? as i32) + + i64::from(extended); + // SCC = the exact signed sum does not fit in i32. + scc = Some(i32::try_from(exact).is_err()); + Some(exact as u32) + } + ScalarImmediate::Multiply => { + let exact = i64::from(read_scalar(Source::Register(dst))? as i32) + * i64::from(extended); + Some(exact.rem_euclid(1 << 32) as u32) + } + _ => Some(extended as u32), + }; + if let Some(value) = value { + scalars[usize::from(dst)] = Some(value); + } + } + } Op::Scalar(kind, dst, lhs, rhs) => { if dst < 8 { return Err(error(offset, "write to a reserved resource SGPR")); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 4007f67..26c3e58 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -909,6 +909,37 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + if dst < 8 { + return Err(error("scalar immediate would modify a resource descriptor")); + } + let scc_in = if op.reads_scc() { + scc.ok_or_else(|| error("SOPK SCC input reads uninitialized SCC"))? + } else { + false + }; + let slot = scalars + .get_mut(usize::from(dst)) + .ok_or_else(|| error("scalar destination exceeds the fixture register file"))?; + let old = if op.reads_dst() { + slot.ok_or_else(|| error("SOPK reads an uninitialized SGPR"))? + } else { + 0 + }; + let (value, flag) = op.evaluate(old, simm16, scc_in); + if let Some(value) = value { + *slot = Some(value); + } + if let Some(flag) = flag { + scc = Some(flag); + } + continue; + } + Instruction::ScalarImmediateCompare { op, src, simm16 } => { + scc = Some(op.test(read_scalar(ScalarSource::Register(src))?, simm16)); + continue; + } // docs/shaders/vector-compare.md sections 3 and 5. Instruction::VectorCompare { op, src0, src1 } => { if exec == 0 { diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index 6d94175..483c0fa 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -308,6 +308,20 @@ fn scalar_compare_results_resolve_every_branch() { ); } +#[test] +fn scalar_immediate_results_resolve_every_branch() { + let code = include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/scalar-immediate.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/scalar-immediate.metal") + ); +} + #[test] fn scalar_unary_results_reach_the_kernel_as_constants() { let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 7e30221..098ec9e 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 120 of 120. Accepted Metal forms · Apple M5: 18 of 120. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -104 / 104 +120 / 120 Accepted Metal forms · Apple M5 -18 / 104 +18 / 120 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index d3f72f4..75733c3 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -33,6 +33,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `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_movk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged | `B0088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmovk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged | `B1088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_eq_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed) | `B1888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_lg_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed) | `B2088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_gt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed) | `B2888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_ge_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed) | `B3088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_lt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed) | `B3888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_le_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed) | `B4088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_eq_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned) | `B4888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_lg_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned) | `B5088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_gt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned) | `B5888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_ge_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned) | `B6088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_lt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned) | `B6888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_cmpk_le_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned) | `B7088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_addk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow | `B7888000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_mulk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged | `B8088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `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 | diff --git a/docs/shaders/scalar-immediate.md b/docs/shaders/scalar-immediate.md new file mode 100644 index 0000000..eb151eb --- /dev/null +++ b/docs/shaders/scalar-immediate.md @@ -0,0 +1,47 @@ +# SOPK scalar immediate forms + +Xenora decodes and translates sixteen gfx1030 SOPK integer forms through the +semantic registry (`crates/isa/semantics/rdna2/sopk.toml`, operand rules +`sopk_sgpr` and `sopk_compare`). Each is one 32-bit word: SIMM16 in bits 0-15, +SDST in bits 16-22, OP in bits 23-27, ENCODING `0b1011` in bits 28-31 +(guide 13.1.2). The word never takes a literal dword (guide 12.2), so a SIMM16 +whose low byte is `0xff` is an immediate, not a literal marker. + +| Form | Opcode | Operation | SCC | +| --- | ---: | --- | --- | +| `s_movk_i32` | 0 | D = signext(SIMM16) | unchanged | +| `s_cmovk_i32` | 2 | if SCC, D = signext(SIMM16); otherwise D keeps its value | read, unchanged | +| `s_cmpk_{eq,lg,gt,ge,lt,le}_i32` | 3-8 | SCC = (D relation signext(SIMM16)), signed | the relation | +| `s_cmpk_{eq,lg,gt,ge,lt,le}_u32` | 9-14 | SCC = (D relation SIMM16), SIMM16 zero-extended, unsigned | the relation | +| `s_addk_i32` | 15 | D = D + signext(SIMM16) | signed overflow of the sum | +| `s_mulk_i32` | 16 | D = low 32 bits of D * signext(SIMM16) | unchanged | + +## Operands + +SDST is `s0`-`s105`. `s0`-`s7` hold the resource descriptors of the fixture +ABI, so they may be read (the compares) but are never written: the translator +refuses a write there even when `s_cmovk_i32` would not take it. SDST 106-127 +(`vcc`, `ttmp`, `m0`, `null`, `exec`) is rejected at decode. The other SOPK +opcodes stay unsupported, except the fixed store fence `s_waitcnt_vscnt null, +0` (`0xbbfd0000`), which keeps its own decoding. + +## How it runs + +SGPR values are known while translating, so a SOPK instruction folds into the +translator's scalar state exactly like the SOP2 and SOPC forms: no IR node is +emitted. `s_cmpk_*` sets SCC; `s_addk_i32` writes D and SCC; `s_mulk_i32` writes +D; `s_movk_i32` and a taken `s_cmovk_i32` write D. `s_addk_i32`, `s_mulk_i32` +and the compares read D, so an SDST nothing has written is rejected. +`s_cmovk_i32` reads SCC and is rejected when SCC is uninitialized; with SCC clear +it neither reads nor writes D, so an unwritten SDST stays unwritten. + +## Verification + +`tests/validation/tests/sopk.rs` derives its expected values from the guide +alone and runs 4,184 cases on both CPU interpreters and, through the translator, +on native Metal (that test is `#[ignore]`d and runs under `scripts/test-gpu.sh`), +plus 398 rejected programs. `fixtures/rdna2/scalar-immediate.s` (LLVM-assembled, +expected input ^ 0x40008275) uses all sixteen forms, recording each compare's SCC +through an `s_cbranch_scc0`; its IR and MSL are pinned under +`fixtures/golden/scalar-immediate.*`. Agreement with a spec-derived reference is +not agreement with hardware. diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index fa89193..ae178d5 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -27,7 +27,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt | SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 | | SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 | | SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 | -| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | +| 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 | @@ -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 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 | +| **Total** | 1465 | 120 | 107 | 124 | 120 | 120 | 18 | 18 | 65 | ## Unsupported operand variants @@ -47,6 +47,8 @@ The table counts distinct variant names per family across registry operand rules | SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` | | 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` | +| 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` | | 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 a655d01..38c4f34 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -13,7 +13,7 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m | File | Role | | --- | --- | | `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. | -| `crates/isa/semantics/rdna2/.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. | +| `crates/isa/semantics/rdna2/.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sopk.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. | | `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. | | `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. | | `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. | @@ -109,7 +109,7 @@ error. | `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` | | `opcode` | Opcode; must match the XML | non-negative integer | | `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` | -| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries | +| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` and `cmov` (SOPK only), `compare` and the SOP1 unaries | | `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) | | `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) | | `width` | Operand and result width in bits | `32` | @@ -118,7 +118,7 @@ error. | `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` | | `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere | | `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 compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` | +| `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` | | `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` | @@ -150,6 +150,8 @@ fixes the `scc` value: | `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no | | `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no | | `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no | +| `mov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | no | +| `cmov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | required | | `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no | Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both @@ -187,6 +189,19 @@ sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`: one source and an SGPR destination), and a two-source ALU operation `sop2_sgpr`. +SOPK forms (guide 12.2) use two rules. `sopk_sgpr` (kind `immediate`, enum +`ScalarImmediateOp`) has SDST `s0`-`s105` as the destination and SIMM16 as the one +source; it takes `mov`, `cmov` (reads SCC, so `carry_in = "scc"`), `add` (`D = D + +signext(SIMM16)`, `scc = "signed_overflow"`) and `mul` (`scc = "unchanged"`), all +`signed`, and the `add` and `mul` forms read the old SDST. `sopk_compare` (kind +`immediate_compare`, enum `ScalarImmediateCompareOp`) takes `compare` with SDST as +the left operand and the SIMM16 as the right one: sign-extended for `signed`, +zero-extended for `unsigned`. A SOPK compare's opcode must be 3 (`signed`) or 9 +(`unsigned`) plus the relation's index in `eq, lg, gt, ge, lt, le` (guide 13.1.2). +The XML must give SIMM16 as 16-bit `FMT_NUM_I16` (`FMT_NUM_U16` for `unsigned`). +The word never takes a literal dword. The details are in +[scalar-immediate.md](scalar-immediate.md). + Behaviour is chosen only from these declared fields, never from the mnemonic. ## What the validator checks diff --git a/docs/status.toml b/docs/status.toml index 01fb189..5f92851 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -279,6 +279,198 @@ recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "s_movk_i32" +encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged" +representation = "`B0088000`" +lowering = "resolved scalar state" +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_cmovk_i32" +encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged" +representation = "`B1088000`" +lowering = "resolved scalar state" +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_cmpk_eq_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed)" +representation = "`B1888000`" +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_cmpk_lg_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed)" +representation = "`B2088000`" +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_cmpk_gt_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed)" +representation = "`B2888000`" +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_cmpk_ge_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed)" +representation = "`B3088000`" +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_cmpk_lt_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed)" +representation = "`B3888000`" +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_cmpk_le_i32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed)" +representation = "`B4088000`" +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_cmpk_eq_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned)" +representation = "`B4888000`" +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_cmpk_lg_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned)" +representation = "`B5088000`" +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_cmpk_gt_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned)" +representation = "`B5888000`" +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_cmpk_ge_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned)" +representation = "`B6088000`" +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_cmpk_lt_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned)" +representation = "`B6888000`" +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_cmpk_le_u32" +encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned)" +representation = "`B7088000`" +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_addk_i32" +encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow" +representation = "`B7888000`" +lowering = "resolved scalar state and 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_mulk_i32" +encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged" +representation = "`B8088000`" +lowering = "resolved scalar state" +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_eq_i32" encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)" diff --git a/fixtures/golden/scalar-immediate.ir b/fixtures/golden/scalar-immediate.ir new file mode 100644 index 0000000..551c7d3 --- /dev/null +++ b/fixtures/golden/scalar-immediate.ir @@ -0,0 +1,26 @@ +0000: t0 = load.u32 input[index] +0018: branch.uniform 0x0020 taken=false +0024: branch.uniform 0x002c taken=true +0030: branch.uniform 0x0038 taken=false +003c: branch.uniform 0x0044 taken=true +0048: branch.uniform 0x0050 taken=false +0054: branch.uniform 0x005c taken=false +0060: branch.uniform 0x0068 taken=false +006c: branch.uniform 0x0078 taken=true +007c: branch.uniform 0x0088 taken=false +008c: branch.uniform 0x0098 taken=true +009c: branch.uniform 0x00a8 taken=false +00ac: branch.uniform 0x00b8 taken=false +00c8: branch.uniform 0x00d4 taken=false +00d8: branch.uniform 0x00e4 taken=false +00e8: branch.uniform 0x00f4 taken=false +00f8: branch.uniform 0x0104 taken=true +0118: t17 = const.u32 0x00007d75 +011c: t18 = const.u32 0xc000ffff +0120: t19 = xor.b32 t18, t17 +0124: t20 = const.u32 0x7fffffff +0128: t21 = xor.b32 t20, t19 +012c: t22 = const.u32 0xffffff00 +0130: t23 = xor.b32 t22, t21 +0134: t24 = xor.b32 t0, t23 +0138: store.u32 output[index], t24 diff --git a/fixtures/golden/scalar-immediate.metal b/fixtures/golden/scalar-immediate.metal new file mode 100644 index 0000000..590031f --- /dev/null +++ b/fixtures/golden/scalar-immediate.metal @@ -0,0 +1,17 @@ +#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 t17 = 0x00007d75u; + uint t18 = 0xc000ffffu; + uint t19 = t18 ^ t17; + uint t20 = 0x7fffffffu; + uint t21 = t20 ^ t19; + uint t22 = 0xffffff00u; + uint t23 = t22 ^ t21; + uint t24 = t0 ^ t23; + output[index] = t24; +} diff --git a/fixtures/rdna2/scalar-immediate.bin b/fixtures/rdna2/scalar-immediate.bin new file mode 100644 index 0000000..f270c79 Binary files /dev/null and b/fixtures/rdna2/scalar-immediate.bin differ diff --git a/fixtures/rdna2/scalar-immediate.s b/fixtures/rdna2/scalar-immediate.s new file mode 100644 index 0000000..8a20a5e --- /dev/null +++ b/fixtures/rdna2/scalar-immediate.s @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original SOPK vectors: the sixteen 16-bit-immediate integer forms. s8 = +// 0xffff8000 (s_movk_i32 sign-extends 0x8000), so the twelve s_cmpk compares +// split signed (sign-extended SIMM16) from unsigned (zero-extended); an +// s_cbranch_scc0 skips setting that compare's bit in s20. s_addk_i32 sets SCC +// on signed overflow, s_mulk_i32 leaves SCC alone, and s_cmovk_i32 moves only +// while SCC is set. Bits worked out by hand below. +// Expected: input ^ 0x40008275 (s20 ^ s9 ^ s10 ^ s11). +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen +s_waitcnt vmcnt(0) +s_movk_i32 s8, 0x8000 // s8 = 0xffff8000 +s_mov_b32 s20, 0 +s_cmpk_eq_i32 s8, 0x8000 // SCC = 1 (-32768 == -32768) +s_cbranch_scc0 .Lskip0 +s_or_b32 s20, s20, 0x1 +.Lskip0: +s_cmpk_eq_u32 s8, 0x8000 // 0xffff8000 == 0x00008000: SCC = 0 +s_cbranch_scc0 .Lskip1 +s_or_b32 s20, s20, 0x2 +.Lskip1: +s_cmpk_lg_i32 s8, 0x7fff // -32768 != 32767: SCC = 1 +s_cbranch_scc0 .Lskip2 +s_or_b32 s20, s20, 0x4 +.Lskip2: +s_cmpk_gt_i32 s8, 0xffff // -32768 > -1 (0xffff sign-extends): SCC = 0 +s_cbranch_scc0 .Lskip3 +s_or_b32 s20, s20, 0x8 +.Lskip3: +s_cmpk_gt_u32 s8, 0xffff // 0xffff8000 > 0x0000ffff (zero-extends): SCC = 1 +s_cbranch_scc0 .Lskip4 +s_or_b32 s20, s20, 0x10 +.Lskip4: +s_cmpk_ge_i32 s8, 0x8000 // -32768 >= -32768: SCC = 1 +s_cbranch_scc0 .Lskip5 +s_or_b32 s20, s20, 0x20 +.Lskip5: +s_cmpk_lt_i32 s8, 0x1 // -32768 < 1: SCC = 1 +s_cbranch_scc0 .Lskip6 +s_or_b32 s20, s20, 0x40 +.Lskip6: +s_cmpk_lt_u32 s8, 0x1 // 0xffff8000 < 1: SCC = 0 +s_cbranch_scc0 .Lskip7 +s_or_b32 s20, s20, 0x80 +.Lskip7: +s_cmpk_le_i32 s8, 0x8000 // -32768 <= -32768: SCC = 1 +s_cbranch_scc0 .Lskip8 +s_or_b32 s20, s20, 0x100 +.Lskip8: +s_cmpk_le_u32 s8, 0x8000 // 0xffff8000 <= 0x8000: SCC = 0 +s_cbranch_scc0 .Lskip9 +s_or_b32 s20, s20, 0x200 +.Lskip9: +s_cmpk_ge_u32 s8, 0x8000 // 0xffff8000 >= 0x8000: SCC = 1 +s_cbranch_scc0 .Lskip10 +s_or_b32 s20, s20, 0x400 +.Lskip10: +s_cmpk_lg_u32 s8, 0x8000 // 0xffff8000 != 0x8000: SCC = 1 +s_cbranch_scc0 .Lskip11 +s_or_b32 s20, s20, 0x800 +.Lskip11: +s_movk_i32 s9, 0x7fff // s9 = 32767 +s_mov_b32 s10, 0x7fffffff +s_addk_i32 s10, 1 // 0x7fffffff + 1 overflows: s10 = 0x80000000, SCC = 1 +s_cbranch_scc0 .Lskip12 +s_or_b32 s20, s20, 0x1000 +.Lskip12: +s_mulk_i32 s9, 0x8000 // 32767 * -32768: s9 = 0xc0008000, SCC stays 1 +s_cbranch_scc0 .Lskip13 +s_or_b32 s20, s20, 0x2000 +.Lskip13: +s_addk_i32 s10, 0xffff // 0x80000000 + -1 overflows: s10 = 0x7fffffff, SCC = 1 +s_cbranch_scc0 .Lskip14 +s_or_b32 s20, s20, 0x4000 +.Lskip14: +s_addk_i32 s9, 0x7fff // 0xc0008000 + 32767 = 0xc000ffff, no overflow: SCC = 0 +s_cbranch_scc0 .Lskip15 +s_or_b32 s20, s20, 0x8000 +.Lskip15: +s_mov_b32 s11, 0x1111 +s_cmovk_i32 s11, 0xff00 // SCC = 0: s11 stays 0x1111 +s_cmpk_eq_u32 s11, 0x1111 // SCC = 1 +s_cmovk_i32 s11, 0xff00 // SCC = 1: s11 = 0xffffff00 +v_mov_b32_e32 v2, s20 // s20 = 0x00007d75 +v_mov_b32_e32 v3, s9 // s9 = 0xc000ffff +v_xor_b32_e32 v2, v3, v2 +v_mov_b32_e32 v3, s10 // s10 = 0x7fffffff +v_xor_b32_e32 v2, v3, v2 +v_mov_b32_e32 v3, s11 // s11 = 0xffffff00 +v_xor_b32_e32 v2, v3, v2 +v_xor_b32_e32 v2, v1, v2 +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 6109c31..416a52a 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 scalar-compare scalar-unary scalar-arith vector-integer vector-compare-ft; do + x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft; 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 8880d78..d7271b5 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -1429,5 +1429,71 @@ class CommandLine(unittest.TestCase): self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms") +class SopkForms(unittest.TestCase): + """SOPK immediate forms, checked against the real registry and XML snapshot.""" + + @classmethod + def setUpClass(cls): + cls.snapshot = gen.load_snapshot() + + def registry(self): + return gen.load_registry() + + def rejects(self, reg, fragment): + errors = gen.validate(reg, self.snapshot) + self.assertTrue( + any(fragment in error for error in errors), + f"expected an error containing {fragment!r}, got {errors}", + ) + + def test_the_registry_declares_the_sixteen_sopk_forms(self): + names = {item["name"] for item in self.registry()["form"] if item["family"] == "SOPK"} + self.assertEqual(len(names), 16) + self.assertTrue({"S_MOVK_I32", "S_CMOVK_I32", "S_ADDK_I32", "S_MULK_I32"} <= names) + + def test_rejects_a_compare_with_the_wrong_sopk_opcode(self): + reg = self.registry() + form(reg, "S_CMPK_GT_U32")["opcode"] = 10 + self.rejects(reg, "S_CMPK_GT_U32: relation gt/unsigned has SOPK opcode 11") + + def test_rejects_an_unsigned_compare_declared_signed(self): + reg = self.registry() + form(reg, "S_CMPK_GT_U32")["signedness"] = "signed" + self.rejects(reg, "SIMM16 is 16 bits FMT_NUM_U16") + + def test_rejects_addk_without_the_overflow_flag(self): + reg = self.registry() + form(reg, "S_ADDK_I32")["scc"] = "unchanged" + self.rejects(reg, "S_ADDK_I32: scc unchanged contradicts add/signed") + + def test_rejects_cmovk_that_does_not_read_scc(self): + reg = self.registry() + form(reg, "S_CMOVK_I32")["carry_in"] = "none" + self.rejects(reg, "S_CMOVK_I32: carry_in none contradicts the XML SCC input") + + def test_rejects_a_conditional_move_that_does_not_read_scc(self): + # S_MOVK_I32 has no SCC input, so as a cmov it would see SCC = 0 and + # never write D. + reg = self.registry() + form(reg, "S_MOVK_I32")["operation"] = "cmov" + self.rejects(reg, "S_MOVK_I32: operation cmov reads SCC (requires carry_in scc)") + + def test_rejects_a_two_source_operation_on_a_sopk_rule(self): + reg = self.registry() + form(reg, "S_MULK_I32")["operation"] = "and" + form(reg, "S_MULK_I32")["signedness"] = "bitwise" + self.rejects(reg, "S_MULK_I32: no primitive implements and/bitwise") + + def test_rejects_a_move_on_the_compare_rule(self): + reg = self.registry() + form(reg, "S_MOVK_I32")["operands"] = "sopk_compare" + self.rejects(reg, "S_MOVK_I32: operation mov does not fit rule sopk_compare") + + def test_generated_compare_extends_signed_and_unsigned_immediates_differently(self): + text = gen.render(self.registry(), self.snapshot) + self.assertIn("Self::CmpkGtI32 => primitive::gt_i32(dst, primitive::sext_simm16(simm16)),", text) + self.assertIn("Self::CmpkGtU32 => primitive::gt_u32(dst, simm16 as u32),", text) + + if __name__ == "__main__": unittest.main() diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index 57f2839..951985a 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -69,6 +69,8 @@ enum Insn { SAlu(u32, u8, Src, Src), /// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`. SCmp(u32, Src, Src), + /// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16. + SImm(u32, u8, u16), BranchScc0(usize), BranchMaskZero { target: usize, @@ -263,6 +265,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> None }) }), + Insn::SImm(opcode, dst, simm16) => { + scalar_immediate(&mut sgpr, &mut scc, (opcode, dst, simm16), offset).map(|()| None) + } Insn::SAlu(opcode, dst, a, b) => { scalar_alu(&mut sgpr, &mut scc, (opcode, dst, a, b), offset).map(|()| None) } @@ -320,6 +325,65 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string())) } +/// One SOPK instruction, per the operation text of guide 12.2. SDST names +/// the destination and, for every form but the two moves, the first source. +fn scalar_immediate( + sgpr: &mut [Option; 128], + scc: &mut Option, + (opcode, dst, simm16): (u32, u8, u16), + offset: usize, +) -> Result<(), String> { + let d = |sgpr: &[Option; 128]| { + sgpr[dst as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{dst}")) + }; + // signext(SIMM16[15:0]): copy bit 15 into bits 16-31. + let sext = u32::from(simm16) | if simm16 >> 15 == 1 { 0xffff_0000 } else { 0 }; + // The unsigned compares use SIMM16[15:0] as is, zero-extended. + let zext = u32::from(simm16); + if (3..=14).contains(&opcode) { + let s0 = d(sgpr)?; + let (a, k) = (s0 as i32, sext as i32); + *scc = Some(match opcode { + 3 => a == k, + 4 => a != k, + 5 => a > k, + 6 => a >= k, + 7 => a < k, + 8 => a <= k, + 9 => s0 == zext, + 10 => s0 != zext, + 11 => s0 > zext, + 12 => s0 >= zext, + 13 => s0 < zext, + _ => s0 <= zext, + }); + return Ok(()); + } + if dst < 8 { + return Err(format!("{offset:#x}: write to a resource SGPR")); + } + let value = match opcode { + 0 => sext, + 2 => { + if !scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))? { + return Ok(()); + } + sext + } + 15 => { + let tmp = d(sgpr)?; + let sum = tmp.wrapping_add(sext); + // tmp[31] == SIMM16[15] && tmp[31] != D[31]. + *scc = Some(tmp >> 31 == u32::from(simm16 >> 15) && tmp >> 31 != sum >> 31); + sum + } + // 16: the low 32 bits of the product, the same for both signednesses. + _ => d(sgpr)?.wrapping_mul(sext), + }; + sgpr[dst as usize] = Some(value); + Ok(()) +} + fn scalar_alu( sgpr: &mut [Option; 128], scc: &mut Option, @@ -1220,6 +1284,15 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { let (src, len) = scalar_source(code, offset, first as u8)?; return Ok((Insn::SMov(dst, src), len)); } + // SOPK: ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15 + // (guide 13.1.2). Guide 12.2: no literal dword may follow. + if first >> 28 == 0b1011 && matches!((first >> 23) & 0x1f, 0 | 2..=16) { + let dst = ((first >> 16) & 0x7f) as u8; + if dst > 105 { + return Err(fail("unsupported SOPK register")); + } + return Ok((Insn::SImm((first >> 23) & 0x1f, dst, first as u16), 4)); + } // SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22. if first >> 30 == 0b10 && matches!( diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index b4f1f62..2b6cce6 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -774,6 +774,10 @@ mod review { 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; + const SCALAR_IMMEDIATE_FIXTURE: &[u8] = + include_bytes!("../../fixtures/rdna2/scalar-immediate.bin"); + // Hand-derived in fixtures/rdna2/scalar-immediate.s from the guide's 12.2 pseudocode. + const SCALAR_IMMEDIATE_KEY: u32 = 0x4000_8275; const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin"); // Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode. const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5; @@ -964,6 +968,18 @@ mod review { assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64")); } + #[test] + fn scalar_immediate_fixture_records_every_registry_sopk_form() { + let input = [0, 1, u32::MAX, SCALAR_IMMEDIATE_KEY, 0x1234_5678]; + let expected: Vec<_> = input + .iter() + .map(|word| word ^ SCALAR_IMMEDIATE_KEY) + .collect(); + verify(SCALAR_IMMEDIATE_FIXTURE, &input, Some(&expected)); + let compiled = compile(Architecture::Gfx1030, SCALAR_IMMEDIATE_FIXTURE).unwrap(); + assert!(compiled.disassembly.contains("s_cmpk_le_u32 s8, 0x8000")); + } + #[test] fn scalar_unary_fixture_chains_registry_unary_forms() { let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678]; diff --git a/tests/validation/tests/sopk.rs b/tests/validation/tests/sopk.rs new file mode 100644 index 0000000..4785579 --- /dev/null +++ b/tests/validation/tests/sopk.rs @@ -0,0 +1,493 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Independent expected values for the sixteen SOPK integer forms of #215: +//! `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, +//! `s_addk_i32` and `s_mulk_i32`. +//! +//! The expectations are written below from the public AMD "RDNA 2" Instruction +//! Set Architecture Reference Guide only: section 12.2 "SOPK Instructions" for +//! each form's operation (and that no literal dword may follow), section +//! 13.1.2 for the SOPK word and its SDST range, and Tables 11-14 of sections +//! 5.4-5.7 for which forms set SCC. Nothing here comes from the ISA crate, the +//! semantic registry, the decoder or the shader compiler. Every case runs on +//! the reference interpreter `xenora_ref` and on the second interpreter +//! `independent_ref`; the ignored test also runs the translated MSL on native +//! Metal. +//! +//! Supported subset: SDST s0-s105 (s0-s7 are readable but, as resource +//! SGPRs, never written). Refused: SDST 106-127 (VCC, TTMP, M0, NULL, EXEC) +//! and every other SOPK opcode (`s_version`, `s_getreg`, `s_setreg*`, +//! `s_call_b64`, `s_waitcnt_*` other than the fixed `s_waitcnt_vscnt null, 0` +//! store fence, and the subvector loops). + +#[path = "operand_domains/harness.rs"] +#[allow(dead_code)] +mod harness; +#[path = "../independent_ref.rs"] +mod independent_ref; + +use std::collections::BTreeMap; + +use harness::{Case, words}; +use xenora_shader::{Architecture, compile}; + +/// The sixteen forms with their ENC_SOPK opcodes (guide 13.1.2, Table 66). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Form { + MovK = 0, + CmovK = 2, + CmpEqI32 = 3, + CmpLgI32 = 4, + CmpGtI32 = 5, + CmpGeI32 = 6, + CmpLtI32 = 7, + CmpLeI32 = 8, + CmpEqU32 = 9, + CmpLgU32 = 10, + CmpGtU32 = 11, + CmpGeU32 = 12, + CmpLtU32 = 13, + CmpLeU32 = 14, + AddK = 15, + MulK = 16, +} + +const FORMS: [(Form, &str); 16] = [ + (Form::MovK, "s_movk_i32"), + (Form::CmovK, "s_cmovk_i32"), + (Form::CmpEqI32, "s_cmpk_eq_i32"), + (Form::CmpLgI32, "s_cmpk_lg_i32"), + (Form::CmpGtI32, "s_cmpk_gt_i32"), + (Form::CmpGeI32, "s_cmpk_ge_i32"), + (Form::CmpLtI32, "s_cmpk_lt_i32"), + (Form::CmpLeI32, "s_cmpk_le_i32"), + (Form::CmpEqU32, "s_cmpk_eq_u32"), + (Form::CmpLgU32, "s_cmpk_lg_u32"), + (Form::CmpGtU32, "s_cmpk_gt_u32"), + (Form::CmpGeU32, "s_cmpk_ge_u32"), + (Form::CmpLtU32, "s_cmpk_lt_u32"), + (Form::CmpLeU32, "s_cmpk_le_u32"), + (Form::AddK, "s_addk_i32"), + (Form::MulK, "s_mulk_i32"), +]; + +fn is_compare(form: Form) -> bool { + (Form::CmpEqI32 as u32..=Form::CmpLeU32 as u32).contains(&(form as u32)) +} + +/// signext(SIMM16[15:0]) as a 32-bit word. +fn sext(simm16: u16) -> u32 { + i32::from(simm16 as i16) as u32 +} + +/// The guide's (D after, SCC after) for `form` with D = `d` before, SCC = +/// `scc` before and the immediate `k`. +fn expect(form: Form, d: u32, scc: bool, k: u16) -> (u32, bool) { + let (di, ki, ku) = (d as i32, sext(k) as i32, u32::from(k)); + match form { + // 0 S_MOVK_I32: D.i32 = signext(SIMM16[15:0]); Table 14: no SCC. + Form::MovK => (sext(k), scc), + // 2 S_CMOVK_I32: if (SCC) D.i32 = signext(SIMM16[15:0]); Table 12: no SCC. + Form::CmovK => (if scc { sext(k) } else { d }, scc), + // 3-8: SCC = (S0.i32 signext(SIMM16[15:0])), S0 = D. + Form::CmpEqI32 => (d, di == ki), + Form::CmpLgI32 => (d, di != ki), + Form::CmpGtI32 => (d, di > ki), + Form::CmpGeI32 => (d, di >= ki), + Form::CmpLtI32 => (d, di < ki), + Form::CmpLeI32 => (d, di <= ki), + // 9-14: SCC = (S0.u32 SIMM16[15:0]), zero-extended. + Form::CmpEqU32 => (d, d == ku), + Form::CmpLgU32 => (d, d != ku), + Form::CmpGtU32 => (d, d > ku), + Form::CmpGeU32 => (d, d >= ku), + Form::CmpLtU32 => (d, d < ku), + Form::CmpLeU32 => (d, d <= ku), + // 15 S_ADDK_I32: D.i32 = D.i32 + signext(SIMM16), SCC = signed overflow. + Form::AddK => match di.checked_add(ki) { + Some(sum) => (sum as u32, false), + None => (di.wrapping_add(ki) as u32, true), + }, + // 16 S_MULK_I32: D.i32 = D.i32 * signext(SIMM16) (low 32 bits); Table 11: no SCC. + Form::MulK => ((i64::from(di) * i64::from(ki)) as u32, scc), + } +} + +/// SIMM16 values: zero, one, both sides of bit 15, all ones, an all-ones low +/// byte (selector 255 as a register field would mean a literal) and two +/// mixed patterns. +const IMMEDIATES: [u16; 10] = [ + 0, 1, 0x7fff, 0x8000, 0x8001, 0xfffe, 0xffff, 0x00ff, 0x1234, 0xedcb, +]; +/// Signed and unsigned boundaries, and the words the sign- and zero-extended +/// immediates produce. +const VALUES: [u32; 15] = [ + 0, + 1, + 0x7fff_fffe, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fffe, + 0xffff_ffff, + 0x7fff, + 0x8000, + 0xffff, + 0x1_0000, + 0xffff_8000, + 0xffff_7fff, + 0x8001, +]; +/// The value s10 holds throughout. +const MARKER: u32 = 0x0f0f_1234; +const INPUT: [u32; 2] = [0, u32::MAX]; + +const COUNTS: [(&str, usize); 9] = [ + ("sopk movk", 10 * 2), + ("sopk cmovk", 10 * 2 * 2), + ("sopk cmpk", 12 * 15 * 10 * 2), + ("sopk addk", 15 * 10), + ("sopk mulk", 15 * 10 * 2), + ("sopk no literal", 16 * 2), + ("sopk s105", 16), + ("sopk cmovk unwritten sdst", 10), + ("sopk no other write", 16), +]; +/// Per form: SDST 106-127; per writing form: SDST s0-s7; per reading form: an +/// uninitialized SDST. +const REJECTIONS: usize = 16 * 22 + 4 * 8 + 14; + +/// ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15 (guide +/// 13.1.2). +fn sopk(op: u32, sdst: u32, simm16: u16) -> u32 { + 0xb000_0000 | op << 23 | sdst << 16 | u32::from(simm16) +} + +/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and +/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0), +/// run `alu`, then v2 = s, `s_cbranch_scc0` over +/// `v_xor_b32 v2, v1, v2`, and store v2. With the lane input [0, !0] the +/// output is [R, R] when SCC is clear and [R, !R] when it is set. +fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec { + let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; + for &(reg, value) in init.iter().chain(&[(10, MARKER)]) { + code.extend([0xbe80_03ff | reg << 16, value]); + } + let x = if scc { 129 } else { 128 }; + code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x); + code.extend(alu); + code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]); + code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]); + words(&code) +} + +fn case( + name: &'static str, + family: &'static str, + label: String, + code: Vec, + out: (u32, bool), +) -> Case { + let (r, scc) = out; + Case { + form: name, + family, + label: format!("{name} {label}"), + code, + input: INPUT.to_vec(), + expected: vec![r, if scc { !r } else { r }], + } +} + +/// One form on s8 = `d` with SCC = `scc` before; the result is s8. +fn single(form: Form, name: &'static str, family: &'static str, d: u32, scc: bool, k: u16) -> Case { + let code = program(&[(8, d)], scc, &[sopk(form as u32, 8, k)], 8); + let label = format!("s8 {d:#x}, simm16 {k:#06x}, scc before {scc}"); + case(name, family, label, code, expect(form, d, scc, k)) +} + +fn cases() -> Vec { + let mut cases = Vec::new(); + for (form, name) in FORMS { + let op = form as u32; + for k in IMMEDIATES { + match form { + Form::MovK => { + for scc in [false, true] { + cases.push(single(form, name, "sopk movk", 0x5a5a_5a5a, scc, k)); + } + } + Form::CmovK => { + for d in [0x5a5a_5a5a, sext(k)] { + for scc in [false, true] { + cases.push(single(form, name, "sopk cmovk", d, scc, k)); + } + } + } + // SCC before is the opposite of the result, so a missing + // write shows. + Form::AddK => { + for d in VALUES { + let scc = !expect(form, d, false, k).1; + cases.push(single(form, name, "sopk addk", d, scc, k)); + } + } + Form::MulK => { + for d in VALUES { + for scc in [false, true] { + cases.push(single(form, name, "sopk mulk", d, scc, k)); + } + } + } + // Both SCC values before, so neither a missing write nor a + // flip of the old SCC passes. + _ => { + for d in VALUES { + for scc in [false, true] { + cases.push(single(form, name, "sopk cmpk", d, scc, k)); + } + } + } + } + } + // An immediate whose low byte is 0xff (or both bytes) followed by + // `s_movk_i32 s9, 0x42`: had the word taken a literal, the move would + // be consumed and s9 never written. + for k in [0x00ff, 0xffff] { + let (d, scc) = (0x8000_0000, true); + let code = program(&[(8, d)], scc, &[sopk(op, 8, k), sopk(0, 9, 0x42)], 9); + let label = format!("simm16 {k:#06x}, then s_movk_i32 s9"); + let after = expect(form, d, scc, k).1; + cases.push(case(name, "sopk no literal", label, code, (0x42, after))); + } + // s10 (the marker) and s9 keep their values: the form writes only + // SDST s8. The result is s10. + let code = program( + &[(8, 0x8000_0000), (9, 0x9999)], + true, + &[sopk(op, 8, 0x8000)], + 10, + ); + let after = expect(form, 0x8000_0000, true, 0x8000).1; + let label = "s10 after the form on s8".to_string(); + cases.push(case( + name, + "sopk no other write", + label, + code, + (MARKER, after), + )); + if form == Form::CmovK { + // A taken move initializes a never-written SDST: s20 is not read. + for k in IMMEDIATES { + let code = program(&[], true, &[sopk(op, 20, k)], 20); + let label = format!("s20 unwritten, simm16 {k:#06x}"); + let family = "sopk cmovk unwritten sdst"; + cases.push(case(name, family, label, code, (sext(k), true))); + } + } + // The top supported SGPR, s105, as SDST; the result is s105. + let (d, k) = (0x7fff_fff0, 0x0020); + let scc = if is_compare(form) || form == Form::AddK { + !expect(form, d, false, k).1 + } else { + true + }; + let code = program(&[(105, d)], scc, &[sopk(op, 105, k)], 105); + let label = format!("s105 {d:#x}, simm16 {k:#06x}"); + cases.push(case( + name, + "sopk s105", + label, + code, + expect(form, d, scc, k), + )); + } + cases +} + +/// The SOPK word's byte offset in `program` with `init` SGPR moves: three +/// header words, one 8-byte move per init pair and the marker, and the AND. +fn alu_offset(init: usize) -> usize { + 12 + 8 * (init + 1) + 4 +} + +/// Both interpreters must refuse `code` at the SOPK word, not later. +fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) { + let offset = alu_offset(init); + match xenora_ref::execute(code, &INPUT) { + Ok(_) => panic!("reference accepted {label}"), + Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"), + } + match independent_ref::execute(code, &INPUT) { + Ok(_) => panic!("independent accepted {label}"), + Err(error) => assert!( + error.starts_with(&format!("{offset:#x}:")), + "independent rejected {label} elsewhere: {error}" + ), + } +} + +/// Programs both interpreters must refuse at the SOPK word, with the number +/// of init pairs before it. +fn rejections() -> Vec<(String, Vec, usize)> { + let mut all = Vec::new(); + for (form, name) in FORMS { + let op = form as u32; + // VCC_LO/HI, TTMP0-15, M0, NULL, EXEC_LO/HI: outside the subset. + for sdst in 106..=127 { + let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8); + all.push((format!("{name} sdst {sdst}"), code, 1)); + } + if is_compare(form) { + // s20 is never written: the compare reads SDST. + let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8); + all.push((format!("{name} uninitialized s20"), code, 1)); + } else { + for sdst in 0..8 { + let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8); + all.push((format!("{name} write to resource s{sdst}"), code, 1)); + } + if matches!(form, Form::AddK | Form::MulK) { + let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8); + all.push((format!("{name} uninitialized s20"), code, 1)); + } + } + } + all +} + +fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> { + let mut counts = BTreeMap::new(); + for case in cases { + *counts.entry(key(case)).or_default() += 1; + } + counts +} + +/// Runs `execute` on every case and returns one line per failing family: the +/// number of failures and the first one. +fn failures( + cases: &[Case], + execute: impl Fn(&[u8], &[u32]) -> Result, String>, +) -> Vec { + let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new(); + for case in cases { + let output = execute(&case.code, &case.input); + if output.as_deref().ok() != Some(case.expected.as_slice()) { + let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected); + failed.entry(case.family).or_insert((0, first)).0 += 1; + } + } + failed + .into_iter() + .map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}")) + .collect() +} + +fn checked_cases() -> Vec { + let cases = cases(); + assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS)); + cases +} + +fn reference(code: &[u8], input: &[u32]) -> Result, String> { + xenora_ref::execute(code, input).map_err(|error| format!("{error:?}")) +} + +#[test] +fn sopk_forms_match_the_guide_on_the_reference() { + let cases = checked_cases(); + let failed = failures(&cases, reference); + assert!( + failed.is_empty(), + "reference disagrees with the guide:\n{}", + failed.join("\n") + ); + eprintln!("sopk: {} reference cases", cases.len()); + for (form, n) in tally(&cases, |case| case.form) { + eprintln!(" form {form}: {n}"); + } +} + +#[test] +fn sopk_forms_match_the_guide_on_the_independent_interpreter() { + let cases = checked_cases(); + let failed = failures(&cases, independent_ref::execute); + assert!( + failed.is_empty(), + "independent interpreter disagrees with the guide:\n{}", + failed.join("\n") + ); + eprintln!("sopk: {} independent-interpreter cases", cases.len()); +} + +#[test] +fn unsupported_sopk_operands_are_rejected() { + let rejections = rejections(); + assert_eq!(rejections.len(), REJECTIONS); + for (label, code, init) in &rejections { + assert_rejected_at_alu(label, code, *init); + } + eprintln!("sopk: {} rejections", rejections.len()); +} + +#[test] +fn other_sopk_opcodes_stay_unsupported() { + // Table 66: 1 s_version, 18-19 getreg and setreg, 21 setreg_imm32 (its + // literal here would be the next word, refused all the same), 22 call, + // 23-26 waitcnt and 27-28 subvector loops; 17 and 20 are unlisted. 29-31 + // are the SOP1, SOPC and SOPP encodings. With SDST s8, opcode 23 is not + // the `null, 0` store fence either. + for op in [1].into_iter().chain(17..=28) { + let code = program(&[(8, 1)], true, &[sopk(op, 8, 0)], 8); + assert_rejected_at_alu(&format!("opcode {op}"), &code, 1); + } + // `s_waitcnt_vscnt null, 1`: only the zero count is the supported fence. + let code = program(&[(8, 1)], true, &[sopk(23, 125, 1)], 8); + assert_rejected_at_alu("s_waitcnt_vscnt null, 1", &code, 1); +} + +#[test] +fn cmovk_without_scc_is_rejected() { + // The header and the s10 marker move, then `s_cmovk_i32 s8, 1` with SCC + // never written: both interpreters must refuse it at byte 20. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + 0xbe80_03ff | 10 << 16, + MARKER, + sopk(Form::CmovK as u32, 8, 1), + 0x7e04_0208, + 0xe070_2000, + 0x8001_0200, + 0xbbfd_0000, + 0xbf81_0000, + ]); + match xenora_ref::execute(&code, &INPUT) { + Ok(_) => panic!("reference accepted s_cmovk_i32 without SCC"), + Err(error) => assert_eq!(error.offset, 20, "reference rejected it elsewhere"), + } + match independent_ref::execute(&code, &INPUT) { + Ok(_) => panic!("independent accepted s_cmovk_i32 without SCC"), + Err(error) => assert!(error.starts_with("0x14:"), "independent: {error}"), + } +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation"] +fn sopk_forms_match_the_guide_on_native_metal() { + assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1")); + assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1")); + for (label, code, _) in rejections() { + assert!( + compile(Architecture::Gfx1030, &code).is_err(), + "compiler accepted {label}" + ); + } + let cases = checked_cases(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!("sopk: {} Metal cases in {programs} programs", cases.len()); +}