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..66ef82c 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"} @@ -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/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/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-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/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/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 8880d78..15ad040 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -1429,5 +1429,64 @@ 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_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/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];