From 544ee8de83611007b821504b758d315f029a1370 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:33:50 -0600 Subject: [PATCH 01/19] isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215) The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now registry data under a new vopc_vcc operand rule (SRC0 a vector_source, VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them through the generated VectorCompareOp instead of a hand-written opcode table, and the hand-written VectorCompareOp struct in xenora-isa is gone. No behaviour change: goldens, known answers and the LLVM oracle are unchanged. The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule and required to account for the XML's implicit VCC output, and wave = "wave32", now allowed exactly for that rule (its one entry point is the Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay unchanged, so v_cmpx cannot be declared. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/decoder/src/lib.rs | 44 +- crates/decoder/tests/gfx1030.rs | 4 +- crates/isa/generate_semantics.py | 95 ++- crates/isa/semantics/rdna2.toml | 273 ++++++- crates/isa/src/lib.rs | 67 +- crates/isa/src/semantics.rs | 10 +- crates/isa/src/semantics_gen.rs | 694 +++++++++++++++++- crates/isa/tests/semantics.rs | 59 +- crates/shader/src/lib.rs | 6 +- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 16 +- docs/shaders/vector-compare.md | 3 + .../test_generate_semantics.py | 105 ++- 13 files changed, 1245 insertions(+), 136 deletions(-) diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 8896435..d259189 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -9,10 +9,8 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32, - V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32, - V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32, - V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO, + V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, + V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO, }; use xenora_isa::meta::EncodingFamily; @@ -42,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -59,18 +57,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [ ("V_ADD_NC_U32", EncodingFamily::Vop3), ("V_AND_B32", EncodingFamily::Vop2), ("V_ASHRREV_I32", EncodingFamily::Vop2), - ("V_CMP_EQ_I32", EncodingFamily::Vopc), - ("V_CMP_EQ_U32", EncodingFamily::Vopc), - ("V_CMP_GE_I32", EncodingFamily::Vopc), - ("V_CMP_GE_U32", EncodingFamily::Vopc), - ("V_CMP_GT_I32", EncodingFamily::Vopc), - ("V_CMP_GT_U32", EncodingFamily::Vopc), - ("V_CMP_LE_I32", EncodingFamily::Vopc), - ("V_CMP_LE_U32", EncodingFamily::Vopc), - ("V_CMP_LT_I32", EncodingFamily::Vopc), - ("V_CMP_LT_U32", EncodingFamily::Vopc), - ("V_CMP_NE_I32", EncodingFamily::Vopc), - ("V_CMP_NE_U32", EncodingFamily::Vopc), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), ("V_INTERP_P2_F32", EncodingFamily::Vintrp), ("V_LSHLREV_B32", EncodingFamily::Vop2), @@ -338,26 +324,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if V_MOV_B32.matches(first) { return move_b32(first, bytes); } - { - use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual}; - for (opcode, relation, signed) in [ - (V_CMP_LT_I32, Less, true), - (V_CMP_EQ_I32, Equal, true), - (V_CMP_LE_I32, LessOrEqual, true), - (V_CMP_GT_I32, Greater, true), - (V_CMP_NE_I32, NotEqual, true), - (V_CMP_GE_I32, GreaterOrEqual, true), - (V_CMP_LT_U32, Less, false), - (V_CMP_EQ_U32, Equal, false), - (V_CMP_LE_U32, LessOrEqual, false), - (V_CMP_GT_U32, Greater, false), - (V_CMP_NE_U32, NotEqual, false), - (V_CMP_GE_U32, GreaterOrEqual, false), - ] { - if opcode.matches(first) { - return vector_compare(VectorCompareOp { relation, signed }, first, bytes); - } - } + if let Some(op) = VectorCompareOp::from_word(first) { + return vector_compare(op, first, bytes); } if V_ADD_NC_U32.matches(first) { let len = V_ADD_NC_U32.byte_len(); @@ -715,7 +683,7 @@ fn vector_compare( bytes: &[u8], ) -> Result<(Instruction, u8), DecodeErrorKind> { let src1 = ((first >> 9) & 0xff) as u8; - let (src0, len) = vector_src0(first, bytes, op.mnemonic())?; + let (src0, len) = vector_src0(first, bytes, op.assembly_name())?; Ok((Instruction::VectorCompare { op, src0, src1 }, len)) } diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 3fa797f..257ee62 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -454,7 +454,7 @@ fn reference_op(instruction: Instruction) -> Op { Instruction::VectorCompare { op, src0, src1 } => Op::Compare( Comparison { - offset: match op.relation { + offset: match op.relation() { CompareRelation::Less => 1, CompareRelation::Equal => 2, CompareRelation::LessOrEqual => 3, @@ -462,7 +462,7 @@ fn reference_op(instruction: Instruction) -> Op { CompareRelation::NotEqual => 5, CompareRelation::GreaterOrEqual => 6, }, - signed: op.signed, + signed: op.signed(), }, match src0 { VectorSource::Register(reg) => CompareSource::Vector(reg), diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 2d16376..4612a69 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -113,11 +113,16 @@ SCC = { "relation": "Relation", "selected_src0": "SelectedSrc0", } -MASK = {"unchanged": "Unchanged"} +# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes +# such as v_cmpx have no contract yet, so exec must stay unchanged). +MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"} WAVE = {"any": "Any", "wave32": "Wave32"} -# The decoder has no wave-size input at the registry dispatch yet, so a Wave32 -# restriction could be declared but not enforced. Reject it until it can be. -ENFORCED_WAVES = {"any"} +# Which wave declaration each operand-rule kind must make. The decoder has no +# wave-size input, so "wave32" is only true where the caller's ABI fixes the +# wave size: the lane-mask compares, whose one entry point is the Wave32 +# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other +# kind must be "any". +WAVE_BY_KIND = {"vector_compare": "wave32"} EVIDENCE = { "reference": "Reference", "independent": "Independent", @@ -253,6 +258,25 @@ OPERAND_RULES = { "unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"}, "kind": "unary", }, + "vopc_vcc": { + "rust": "VopcVcc", + "enum": "VectorCompareOp", + "shape": { + "family": "VOPC", + "src": [ + {"field": "SRC0", "class": "vector_source"}, + {"field": "VSRC1", "class": "vgpr"}, + ], + "max_literals": 1, + }, + # The destination is implicitly vcc_lo; the decoder rejects these SRC0 + # selectors (the same vector_source as VOP2). + "unsupported": { + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", + "src_special", + }, + "kind": "vector_compare", + }, "vop2_vgpr": { "rust": "Vop2Vgpr", "enum": "VectorAluOp", @@ -364,8 +388,12 @@ def _check_xml(form, rule, snapshot, errors): operands[field] = (data_format, size, is_input, is_output) else: implicit.add(kind) - # The vocabulary can state only SCC effects (vcc and exec are "unchanged"), - # so any other implicit XML operand, such as VCC, is undeclared. + # The vocabulary states SCC effects and a lane-mask VCC write; any other + # implicit XML operand (such as an EXEC write) is undeclared. + if form["vcc"] == "lane_mask": + if "OPR_VCC" not in implicit: + errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output") + implicit.discard("OPR_VCC") if implicit: errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared") if scc_in != (form["carry_in"] == "scc"): @@ -471,8 +499,17 @@ def validate(registry, snapshot): errors.append(f"{label}: variant {form['variant']!r} is reserved") if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX: errors.append(f"{label}: invalid opcode") - if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES: - errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet") + wave = WAVE_BY_KIND.get(_rule_kind(form), "any") + if form["wave"] in WAVE and form["wave"] != wave: + errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})") + lane_mask = _rule_kind(form) == "vector_compare" + if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask: + errors.append( + f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} " + f"(requires {'lane_mask' if lane_mask else 'unchanged'})" + ) + if form["exec"] != "unchanged": + errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)") if type(form["width"]) is not int or form["width"] not in WIDTHS: errors.append(f"{label}: width {form['width']} is not supported") for key, value in ( @@ -527,11 +564,13 @@ def validate(registry, snapshot): errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}") elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES: errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") - if form["scc"] != "relation": - errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)") + # SOPC compares write SCC; VOPC compares write VCC and leave SCC. + scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" + if form["scc"] != scc: + errors.append(f"{label}: scc {form['scc']} contradicts compare (requires {scc})") if form["carry_in"] != "none": errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare") - primitive = ("relation", None, False) + primitive = (scc, None, False) elif _rule_kind(form) == "vector": if RELATION_KEY in form: errors.append(f"{label}: {RELATION_KEY} on a non-compare operation") @@ -558,7 +597,8 @@ 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"] != ( - "compare" if form["operation"] == "compare" + ("vector_compare" if _rule_kind(form) == "vector_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 "alu" @@ -707,10 +747,11 @@ def _render_enum(rule_name, forms, snapshot, positions): ] for form in forms: carry = " plus SCC" if form["carry_in"] == "scc" else "" - what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"] + what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"] + effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}" out += [ f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): " - f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.", + f"{form['signedness']} {what}{carry}, {effect}.", f" {form['variant']},", ] by_opcode = {form["opcode"]: form["variant"] for form in forms} @@ -834,7 +875,29 @@ def _render_enum(rule_name, forms, snapshot, positions): ] out += [" }", " }", "}"] return out - if kind == "compare": + if kind == "vector_compare": + out += [ + "", + " /// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it.", + " pub const fn assembly_name(self) -> &'static str {", + " match self {", + ] + out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms] + out += [ + " }", + " }", + "", + " /// Whether the operands compare as two's-complement values.", + " pub const fn signed(self) -> bool {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => {'true' if form['signedness'] == 'signed' else 'false'}," + for form in forms + ] + out += [" }", " }"] + if kind in ("compare", "vector_compare"): + result = "SCC" if kind == "compare" else "per-lane result" out += [ "", " /// The relation tested, with S0 on the left.", @@ -849,7 +912,7 @@ def _render_enum(rule_name, forms, snapshot, positions): " }", " }", "", - " /// The new SCC: whether the relation holds for S0 and S1.", + f" /// The {result}: whether the relation holds for S0 and S1.", " pub const fn test(self, src0: u32, src1: u32) -> bool {", " match self {", ] diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 2b05269..eba44be 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -54,8 +54,8 @@ unsupported = [ # carry_in none | scc (scc for unsigned add/sub carry and the cselect condition) # width operand and result width in bits # scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0 -# vcc, exec unchanged (stated, not implied) -# wave any | wave32 +# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare) +# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares) # operands a key of [operand_rules] # spec references; at least one guide section with a page # verify evidence required before the form counts as verified @@ -1409,3 +1409,272 @@ wave = "any" operands = "vop2_vgpr" spec = [{ document = "guide", section = "12.7", page = 134 }] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- +# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; +# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's +# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), +# the VOP3 encoding and Wave64 stay unsupported. +[operand_rules.vopc_vcc] +family = "VOPC" +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_CMP_LT_I32" +family = "VOPC" +opcode = 129 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_I32" +family = "VOPC" +opcode = 130 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_I32" +family = "VOPC" +opcode = 131 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_I32" +family = "VOPC" +opcode = 132 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_I32" +family = "VOPC" +opcode = 133 +variant = "CmpNeI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_I32" +family = "VOPC" +opcode = 134 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LT_U32" +family = "VOPC" +opcode = 193 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_U32" +family = "VOPC" +opcode = 194 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_U32" +family = "VOPC" +opcode = 195 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_U32" +family = "VOPC" +opcode = 196 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_U32" +family = "VOPC" +opcode = 197 +variant = "CmpNeU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_U32" +family = "VOPC" +opcode = 198 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 160e3c0..a9269db 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -18,7 +18,9 @@ pub use rdna2::{ V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; -pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp}; +pub use semantics_gen::{ + ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp, +}; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. pub const VCC_LO: u8 = 106; @@ -93,7 +95,8 @@ impl fmt::Display for ScalarSource { } } -/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1. +/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on +/// the left. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CompareRelation { /// S0 < S1 (opcode offset 1). @@ -110,64 +113,6 @@ pub enum CompareRelation { GreaterOrEqual, } -/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands. -/// -/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and -/// the pinned XML descriptions. VCC and EXEC rules are in -/// docs/shaders/vector-compare.md. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct VectorCompareOp { - /// The tested relation. - pub relation: CompareRelation, - /// `_i32` (two's complement) when true, `_u32` when false. - pub signed: bool, -} - -impl VectorCompareOp { - /// Lower-case mnemonic of the 32-bit VOPC encoding. - pub fn mnemonic(self) -> &'static str { - const SIGNED: [&str; 6] = [ - "v_cmp_lt_i32_e32", - "v_cmp_eq_i32_e32", - "v_cmp_le_i32_e32", - "v_cmp_gt_i32_e32", - "v_cmp_ne_i32_e32", - "v_cmp_ge_i32_e32", - ]; - const UNSIGNED: [&str; 6] = [ - "v_cmp_lt_u32_e32", - "v_cmp_eq_u32_e32", - "v_cmp_le_u32_e32", - "v_cmp_gt_u32_e32", - "v_cmp_ne_u32_e32", - "v_cmp_ge_u32_e32", - ]; - let index = self.relation as usize; - if self.signed { - SIGNED[index] - } else { - UNSIGNED[index] - } - } - - /// The per-lane test result for operand bits S0 and S1. - pub fn test(self, src0: u32, src1: u32) -> bool { - let ordering = if self.signed { - (src0 as i32).cmp(&(src1 as i32)) - } else { - src0.cmp(&src1) - }; - match self.relation { - CompareRelation::Less => ordering.is_lt(), - CompareRelation::Equal => ordering.is_eq(), - CompareRelation::LessOrEqual => ordering.is_le(), - CompareRelation::Greater => ordering.is_gt(), - CompareRelation::NotEqual => ordering.is_ne(), - CompareRelation::GreaterOrEqual => ordering.is_ge(), - } - } -} - /// Output targeted by a supported uncompressed four-component export. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ExportTarget { @@ -327,7 +272,7 @@ impl Instruction { Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), Self::ScalarCompare { op, .. } => op.mnemonic(), - Self::VectorCompare { op, .. } => op.mnemonic(), + Self::VectorCompare { op, .. } => op.assembly_name(), Self::VectorAlu { op, .. } => op.assembly_name(), Self::BranchSccZero { .. } => "s_cbranch_scc0", Self::BranchExecZero { .. } => "s_cbranch_execz", diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index cd76804..ff67cb6 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -160,11 +160,15 @@ pub enum SccEffect { SelectedSrc0, } -/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged. +/// What a form writes to VCC or EXEC. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum MaskEffect { /// Not written. Unchanged, + /// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n + /// exists) & test(lane n), fully written; `VCC_HI` has no known value after + /// it (docs/shaders/vector-compare.md section 3). + LaneMask, } /// Wave-size restriction. @@ -188,6 +192,10 @@ 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, + /// 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. + VopcVcc, /// VOP2 vector: VDST is v0-v255; 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 1d35de2..0366a2b 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1179,7 +1179,7 @@ impl ScalarCompareOp { } } - /// The new SCC: whether the relation holds for S0 and S1. + /// The SCC: whether the relation holds for S0 and S1. pub const fn test(self, src0: u32, src1: u32) -> bool { match self { Self::CmpEqI32 => primitive::eq_b32(src0, src1), @@ -1412,8 +1412,432 @@ impl VectorAluOp { } } +/// VOPC operations declared in the semantic registry (operand rule `vopc_vcc`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorCompareOp { + /// `v_cmp_lt_i32` (VOPC opcode 129): signed compare lt, VCC = lane_mask. + CmpLtI32, + /// `v_cmp_eq_i32` (VOPC opcode 130): signed compare eq, VCC = lane_mask. + CmpEqI32, + /// `v_cmp_le_i32` (VOPC opcode 131): signed compare le, VCC = lane_mask. + CmpLeI32, + /// `v_cmp_gt_i32` (VOPC opcode 132): signed compare gt, VCC = lane_mask. + CmpGtI32, + /// `v_cmp_ne_i32` (VOPC opcode 133): signed compare lg, VCC = lane_mask. + CmpNeI32, + /// `v_cmp_ge_i32` (VOPC opcode 134): signed compare ge, VCC = lane_mask. + CmpGeI32, + /// `v_cmp_lt_u32` (VOPC opcode 193): unsigned compare lt, VCC = lane_mask. + CmpLtU32, + /// `v_cmp_eq_u32` (VOPC opcode 194): unsigned compare eq, VCC = lane_mask. + CmpEqU32, + /// `v_cmp_le_u32` (VOPC opcode 195): unsigned compare le, VCC = lane_mask. + CmpLeU32, + /// `v_cmp_gt_u32` (VOPC opcode 196): unsigned compare gt, VCC = lane_mask. + CmpGtU32, + /// `v_cmp_ne_u32` (VOPC opcode 197): unsigned compare lg, VCC = lane_mask. + CmpNeU32, + /// `v_cmp_ge_u32` (VOPC opcode 198): unsigned compare ge, VCC = lane_mask. + CmpGeU32, +} + +/// VectorCompareOp by VOPC OP field value; `None` for undeclared opcodes. +const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorCompareOp::CmpLtI32), + Some(VectorCompareOp::CmpEqI32), + Some(VectorCompareOp::CmpLeI32), + Some(VectorCompareOp::CmpGtI32), + Some(VectorCompareOp::CmpNeI32), + Some(VectorCompareOp::CmpGeI32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorCompareOp::CmpLtU32), + Some(VectorCompareOp::CmpEqU32), + Some(VectorCompareOp::CmpLeU32), + Some(VectorCompareOp::CmpGtU32), + Some(VectorCompareOp::CmpNeU32), + Some(VectorCompareOp::CmpGeU32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl VectorCompareOp { + /// Every operation, in registry order. + pub const ALL: [Self; 12] = [ + Self::CmpLtI32, + Self::CmpEqI32, + Self::CmpLeI32, + Self::CmpGtI32, + Self::CmpNeI32, + Self::CmpGeI32, + Self::CmpLtU32, + Self::CmpEqU32, + Self::CmpLeU32, + Self::CmpGtU32, + Self::CmpNeU32, + Self::CmpGeU32, + ]; + + /// Selects the operation from a first instruction word: the VOPC encoding + /// bits (mask 0xfe00_0000) and then the OP field (bits 17-24). + pub const fn from_word(word: u32) -> Option { + if word & 0xfe00_0000 != 0x7c00_0000 { + return None; + } + VECTOR_COMPARE_OP_BY_OPCODE[((word >> 17) & 0xff) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::CmpLtI32 => "v_cmp_lt_i32", + Self::CmpEqI32 => "v_cmp_eq_i32", + Self::CmpLeI32 => "v_cmp_le_i32", + Self::CmpGtI32 => "v_cmp_gt_i32", + Self::CmpNeI32 => "v_cmp_ne_i32", + Self::CmpGeI32 => "v_cmp_ge_i32", + Self::CmpLtU32 => "v_cmp_lt_u32", + Self::CmpEqU32 => "v_cmp_eq_u32", + Self::CmpLeU32 => "v_cmp_le_u32", + Self::CmpGtU32 => "v_cmp_gt_u32", + Self::CmpNeU32 => "v_cmp_ne_u32", + Self::CmpGeU32 => "v_cmp_ge_u32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::CmpLtI32 => 68, + Self::CmpEqI32 => 69, + Self::CmpLeI32 => 70, + Self::CmpGtI32 => 71, + Self::CmpNeI32 => 72, + Self::CmpGeI32 => 73, + Self::CmpLtU32 => 74, + Self::CmpEqU32 => 75, + Self::CmpLeU32 => 76, + Self::CmpGtU32 => 77, + Self::CmpNeU32 => 78, + Self::CmpGeU32 => 79, + }] + } + + /// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::CmpLtI32 => "v_cmp_lt_i32_e32", + Self::CmpEqI32 => "v_cmp_eq_i32_e32", + Self::CmpLeI32 => "v_cmp_le_i32_e32", + Self::CmpGtI32 => "v_cmp_gt_i32_e32", + Self::CmpNeI32 => "v_cmp_ne_i32_e32", + Self::CmpGeI32 => "v_cmp_ge_i32_e32", + Self::CmpLtU32 => "v_cmp_lt_u32_e32", + Self::CmpEqU32 => "v_cmp_eq_u32_e32", + Self::CmpLeU32 => "v_cmp_le_u32_e32", + Self::CmpGtU32 => "v_cmp_gt_u32_e32", + Self::CmpNeU32 => "v_cmp_ne_u32_e32", + Self::CmpGeU32 => "v_cmp_ge_u32_e32", + } + } + + /// Whether the operands compare as two's-complement values. + pub const fn signed(self) -> bool { + match self { + Self::CmpLtI32 => true, + Self::CmpEqI32 => true, + Self::CmpLeI32 => true, + Self::CmpGtI32 => true, + Self::CmpNeI32 => true, + Self::CmpGeI32 => true, + Self::CmpLtU32 => false, + Self::CmpEqU32 => false, + Self::CmpLeU32 => false, + Self::CmpGtU32 => false, + Self::CmpNeU32 => false, + Self::CmpGeU32 => false, + } + } + + /// The relation tested, with S0 on the left. + pub const fn relation(self) -> CompareRelation { + match self { + Self::CmpLtI32 => CompareRelation::Less, + Self::CmpEqI32 => CompareRelation::Equal, + Self::CmpLeI32 => CompareRelation::LessOrEqual, + Self::CmpGtI32 => CompareRelation::Greater, + Self::CmpNeI32 => CompareRelation::NotEqual, + Self::CmpGeI32 => CompareRelation::GreaterOrEqual, + Self::CmpLtU32 => CompareRelation::Less, + Self::CmpEqU32 => CompareRelation::Equal, + Self::CmpLeU32 => CompareRelation::LessOrEqual, + Self::CmpGtU32 => CompareRelation::Greater, + Self::CmpNeU32 => CompareRelation::NotEqual, + Self::CmpGeU32 => CompareRelation::GreaterOrEqual, + } + } + + /// The per-lane result: whether the relation holds for S0 and S1. + pub const fn test(self, src0: u32, src1: u32) -> bool { + match self { + Self::CmpLtI32 => primitive::lt_i32(src0, src1), + Self::CmpEqI32 => primitive::eq_b32(src0, src1), + Self::CmpLeI32 => primitive::le_i32(src0, src1), + Self::CmpGtI32 => primitive::gt_i32(src0, src1), + Self::CmpNeI32 => primitive::ne_b32(src0, src1), + Self::CmpGeI32 => primitive::ge_i32(src0, src1), + Self::CmpLtU32 => primitive::lt_u32(src0, src1), + Self::CmpEqU32 => primitive::eq_b32(src0, src1), + Self::CmpLeU32 => primitive::le_u32(src0, src1), + Self::CmpGtU32 => primitive::gt_u32(src0, src1), + Self::CmpNeU32 => primitive::ne_b32(src0, src1), + Self::CmpGeU32 => primitive::ge_u32(src0, src1), + } + } +} + /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 68] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1482,10 +1906,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 68] = [ ("V_ADD_NC_U32", EncodingFamily::Vop2), ("V_SUB_NC_U32", EncodingFamily::Vop2), ("V_SUBREV_NC_U32", EncodingFamily::Vop2), + ("V_CMP_LT_I32", EncodingFamily::Vopc), + ("V_CMP_EQ_I32", EncodingFamily::Vopc), + ("V_CMP_LE_I32", EncodingFamily::Vopc), + ("V_CMP_GT_I32", EncodingFamily::Vopc), + ("V_CMP_NE_I32", EncodingFamily::Vopc), + ("V_CMP_GE_I32", EncodingFamily::Vopc), + ("V_CMP_LT_U32", EncodingFamily::Vopc), + ("V_CMP_EQ_U32", EncodingFamily::Vopc), + ("V_CMP_LE_U32", EncodingFamily::Vopc), + ("V_CMP_GT_U32", EncodingFamily::Vopc), + ("V_CMP_NE_U32", EncodingFamily::Vopc), + ("V_CMP_GE_U32", EncodingFamily::Vopc), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 68] = [ +pub static FORMS: [FormSemantics; 80] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -2914,4 +3350,256 @@ pub static FORMS: [FormSemantics; 68] = [ spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 134 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_CMP_LT_I32", + family: EncodingFamily::Vopc, + opcode: 129, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_I32", + family: EncodingFamily::Vopc, + opcode: 130, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_I32", + family: EncodingFamily::Vopc, + opcode: 131, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_I32", + family: EncodingFamily::Vopc, + opcode: 132, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_I32", + family: EncodingFamily::Vopc, + opcode: 133, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_I32", + family: EncodingFamily::Vopc, + opcode: 134, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LT_U32", + family: EncodingFamily::Vopc, + opcode: 193, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_U32", + family: EncodingFamily::Vopc, + opcode: 194, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_U32", + family: EncodingFamily::Vopc, + opcode: 195, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_U32", + family: EncodingFamily::Vopc, + opcode: 196, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_U32", + family: EncodingFamily::Vopc, + opcode: 197, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_U32", + family: EncodingFamily::Vopc, + opcode: 198, + 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::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index fb3de7f..b46b692 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -1,8 +1,12 @@ //! Ties the generated semantic registry tables to the independent XML metadata table. use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS}; -use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect}; -use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp}; +use xenora_isa::semantics::{ + CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave, +}; +use xenora_isa::{ + CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp, +}; #[test] fn generated_tables_match_the_schema_and_the_metadata_forms() { @@ -103,3 +107,54 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() { VectorAluOp::from_word(word).map(|op| op.semantics().name) }); } + +#[test] +fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { + const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff]; + for op in VectorCompareOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Vopc); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic())); + assert_eq!(row.relation, Some(op.relation())); + assert_eq!(op.signed(), row.signedness == Signedness::Signed); + assert_eq!( + (row.scc, row.vcc, row.exec, row.wave), + ( + SccEffect::Unchanged, + MaskEffect::LaneMask, + MaskEffect::Unchanged, + Wave::Wave32 + ) + ); + // The per-lane test is the declared relation over the declared + // signedness, with SRC0 on the left. + for src0 in OPERANDS { + for src1 in OPERANDS { + let ordering = if op.signed() { + (src0 as i32).cmp(&(src1 as i32)) + } else { + src0.cmp(&src1) + }; + let expected = match op.relation() { + CompareRelation::Less => ordering.is_lt(), + CompareRelation::Equal => ordering.is_eq(), + CompareRelation::LessOrEqual => ordering.is_le(), + CompareRelation::Greater => ordering.is_gt(), + CompareRelation::NotEqual => ordering.is_ne(), + CompareRelation::GreaterOrEqual => ordering.is_ge(), + }; + assert_eq!( + op.test(src0, src1), + expected, + "{} {src0:#x} {src1:#x}", + row.name + ); + } + } + } + // v_cmpx, F/T and the 16-, 64-bit and float compares must not be dispatched. + dispatch_selects_exactly(EncodingFamily::Vopc, |word| { + VectorCompareOp::from_word(word).map(|op| op.semantics().name) + }); +} diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index bd41abe..50a8130 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -195,7 +195,7 @@ impl Op { fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { use xenora_decoder::CompareRelation; - let symbol = match op.relation { + let symbol = match op.relation() { CompareRelation::Less => "<", CompareRelation::Equal => "==", CompareRelation::LessOrEqual => "<=", @@ -203,7 +203,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { CompareRelation::NotEqual => "!=", CompareRelation::GreaterOrEqual => ">=", }; - if op.signed { + if op.signed() { format!("as_type({left}) {symbol} as_type({right})") } else { format!("{left} {symbol} {right}") @@ -485,7 +485,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result= S1 | `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. +The forms are declared in the semantic registry +(`crates/isa/semantics/rdna2.toml`, operand rule `vopc_vcc`); the decoder +dispatches them from the generated `VectorCompareOp`. Operand order matters (S0 is SRC0): lt with swapped operands is gt. SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5), diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 5384ffb..71b39f5 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -144,9 +144,31 @@ def snapshot(): "instruction": name, "encoding": "ENC_VOP2", "opcode": opcode, "operands": vector(data_format), } + vopc = { + "name": "ENC_VOPC", + "bits": 32, + "fields": [ + ["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["OP", [[17, 8]]], ["ENCODING", [[25, 7]]], + ], + "identifier_mask": 0xFFFE0000, + "identifiers": [0x7C000000 | (op << 17) for op in (129, 197)], + } + for name, opcode, data_format in (("V_CMP_LT_I32", 129, I32), ("V_CMP_NE_U32", 197, U32)): + variants[(name, "ENC_VOPC")] = { + "instruction": name, "encoding": "ENC_VOPC", "opcode": opcode, + # Values copied from the AMD XML snapshot: an implicit 64-bit VCC output. + "operands": [ + ["", "FMT_NUM_M64", "OPR_VCC", 64, False, True, False, False], + ["SRC0", data_format, "OPR_SRC", 32, True, False, False, True], + ["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True], + ], + } return { "source": {"sha256": SHA}, - "encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2}, + "encodings": { + "ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2, + "ENC_VOPC": vopc, + }, "variants": variants, } @@ -217,6 +239,27 @@ def vectors(): return reg +def vector_compares(): + reg = registry() + rule = copy.deepcopy(gen.OPERAND_RULES["vopc_vcc"]["shape"]) + rule["unsupported"] = sorted(gen.OPERAND_RULES["vopc_vcc"]["unsupported"]) + reg["operand_rules"]["vopc_vcc"] = rule + + def compare(name, opcode, variant, relation, signedness): + form = _form(name, opcode, variant, "compare", signedness, "unchanged") + form.update( + family="VOPC", relation=relation, operands="vopc_vcc", vcc="lane_mask", wave="wave32" + ) + return form + + reg["form"] += [ + # The same variant name as a SOPC form: variants are per enum. + compare("V_CMP_LT_I32", 129, "CmpLtI32", "lt", "signed"), + compare("V_CMP_NE_U32", 197, "CmpNeU32", "lg", "unsigned"), + ] + return reg + + def compares(): reg = registry() reg["form"] += [ @@ -738,7 +781,65 @@ class Validate(unittest.TestCase): def test_rejects_an_unenforced_wave_restriction(self): reg = registry() reg["form"][0]["wave"] = "wave32" - self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet") + self.rejects(reg, "S_ADD_U32: wave wave32 is not enforced for this rule (requires any)") + + # ---- VOPC lane-mask compares ---- + + def test_accepts_vector_compares(self): + self.assertEqual(self.errors(vector_compares()), []) + + def test_rejects_a_vector_compare_declared_for_any_wave(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["wave"] = "any" + self.rejects(reg, "V_CMP_LT_I32: wave any is not enforced for this rule (requires wave32)") + + def test_rejects_a_vector_compare_without_its_vcc_write(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged" + self.rejects(reg, "V_CMP_LT_I32: vcc unchanged contradicts rule vopc_vcc (requires lane_mask)") + # The XML VCC output is then undeclared as well. + self.rejects(reg, "V_CMP_LT_I32: XML implicit operands ['OPR_VCC'] are not declared") + + def test_rejects_a_lane_mask_outside_vopc(self): + reg = registry() + reg["form"][0]["vcc"] = "lane_mask" + self.rejects(reg, "S_ADD_U32: vcc lane_mask contradicts rule sop2_sgpr (requires unchanged)") + self.rejects(reg, "S_ADD_U32: vcc lane_mask but the XML has no implicit VCC output") + + def test_rejects_an_exec_write(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["exec"] = "lane_mask" + self.rejects(reg, "V_CMP_LT_I32: exec lane_mask has no contract (requires unchanged)") + + def test_rejects_a_vector_compare_that_writes_scc(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["scc"] = "relation" + self.rejects(reg, "V_CMP_LT_I32: scc relation contradicts compare (requires unchanged)") + + def test_rejects_a_vector_compare_without_a_relation(self): + reg = vector_compares() + del form(reg, "V_CMP_NE_U32")["relation"] + self.rejects(reg, "V_CMP_NE_U32: unknown or missing relation None") + + def test_rejects_a_vector_compare_under_a_scalar_rule(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["operands"] = "sopc_scalar" + self.rejects(reg, "V_CMP_LT_I32: operand rule sopc_scalar is for SOPC") + + def test_rejects_a_vector_compare_signedness_against_the_xml(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["signedness"] = "unsigned" + self.rejects(reg, "V_CMP_LT_I32: signedness unsigned contradicts XML format FMT_NUM_I32") + + def test_renders_vector_compare_dispatch(self): + text = gen.render(vector_compares(), snapshot()) + self.assertIn("pub enum VectorCompareOp {", text) + self.assertIn("if word & 0xfe00_0000 != 0x7c00_0000 {", text) + self.assertIn('Self::CmpNeU32 => "v_cmp_ne_u32_e32",', text) + self.assertIn("Self::CmpLtI32 => true,", text.split("fn signed", 1)[1]) + self.assertIn("Self::CmpNeU32 => primitive::ne_b32(src0, src1),", text) + self.assertIn("vcc: MaskEffect::LaneMask,", text) + self.assertIn("wave: Wave::Wave32,", text) def test_rejects_a_reserved_variant(self): reg = registry() From 1ac4f82d7a9fe4013746ba684da37adeff4a41ee Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:34:38 -0600 Subject: [PATCH 02/19] test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215) The registry stage adds the four constant 32-bit integer VOPC compares, which nothing could check: the reference and the second interpreter both rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61: D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the #239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F writes 0, and sources keep the allowlist and initialization rules. vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both edges and the rejections; the native Metal part is ignored until the translator side lands. known_answers no longer expects F and T to be rejected. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/ref/src/lib.rs | 12 +- tests/validation/independent_ref.rs | 14 +- tests/validation/known_answers.rs | 10 +- tests/validation/tests/vopc_f_t.rs | 649 ++++++++++++++++++++++++++++ 4 files changed, 670 insertions(+), 15 deletions(-) create mode 100644 tests/validation/tests/vopc_f_t.rs diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index 59f171a..e391d45 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -79,10 +79,10 @@ pub enum Op { /// /// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset /// for signed and 192 + offset for unsigned 32-bit operands, with offsets -/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6. +/// F 0, LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6, T 7. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Comparison { - /// Opcode offset 1-6 within the 32-bit integer group. + /// Opcode offset 0-7 within the 32-bit integer group. pub offset: u8, /// Whether the operands are two's-complement integers. pub signed: bool, @@ -100,12 +100,16 @@ impl Comparison { }; let (s0, s1) = (widen(s0), widen(s1)); match self.offset { + // Table 61: V_CMP_F_{I,U}32 `D[threadId] = 0`. + 0 => false, 1 => s0 < s1, 2 => s0 == s1, 3 => s0 <= s1, 4 => s0 > s1, 5 => s0 != s1, - _ => s0 >= s1, + 6 => s0 >= s1, + // Table 61: V_CMP_T_{I,U}32 `D[threadId] = 1`. + _ => true, } } } @@ -579,7 +583,7 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { [lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..] if matches!( (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1), - 129..=134 | 193..=198 + 128..=135 | 192..=199 ) => { let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1); diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index 8076a9a..f4fc5f2 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -27,7 +27,7 @@ //! production operator. SOP2 arithmetic runs through a bit-serial ripple //! adder (subtraction as addition of the complement), not host integer ops. //! -//! Wave32 VOPC integer compares (`v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`, +//! Wave32 VOPC integer compares (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i32,u32}_e32`, //! contract `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution //! runs lockstep waves of 32 consecutive dispatch indices with wave-uniform //! scalar state and per-lane vector state. A lane-local failure stops only that @@ -75,7 +75,7 @@ enum Insn { VMovFromSgpr(u8, u8), /// `v_mov_b32_e32 vD, vcc_lo`. VMovFromVcc(u8), - /// VOPC compare into VCC_LO: relation 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge. + /// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t. VCmp { relation: u8, signed: bool, @@ -585,13 +585,17 @@ fn compare( } else { (a, b) }; + // Guide 12.9 Table 59 offsets; F (0) and T (7) ignore the operand + // values but still read them (contract 5: sources are validated). let pass = match relation { + 0 => false, 1 => a < b, 2 => a == b, 3 => a <= b, 4 => a > b, 5 => a != b, - _ => a >= b, + 6 => a >= b, + _ => true, }; mask |= u32::from(pass) << n; } @@ -1039,8 +1043,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { if first >> 25 == 0b011_1110 { let opcode = (first >> 17) & 0xff; let (signed, relation) = match opcode { - 129..=134 => (true, opcode - 128), - 193..=198 => (false, opcode - 192), + 128..=135 => (true, opcode - 128), + 192..=199 => (false, opcode - 192), _ => return Err(fail("unsupported VOPC opcode")), }; let (src0, len) = vector_src0(code, offset, first, "VOPC")?; diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index ca406d9..6aa3cd3 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -1802,12 +1802,10 @@ mod review { let mut code = base.clone(); code[0x14..0x18].copy_from_slice(&vopc(129, 256 + 1, 9).to_le_bytes()); rejected_at(&code, 0x14); - // v_cmpx (writes EXEC), F and T forms, and the VOP3 encoding. - for word in [vopc(210, 257, 3), vopc(128, 257, 3), vopc(135, 257, 3)] { - let mut code = base.clone(); - code[0x14..0x18].copy_from_slice(&word.to_le_bytes()); - rejected_at(&code, 0x14); - } + // v_cmpx (writes EXEC) and the VOP3 encoding. + let mut code = base.clone(); + code[0x14..0x18].copy_from_slice(&vopc(210, 257, 3).to_le_bytes()); + rejected_at(&code, 0x14); let mut e64 = base[..0x14].to_vec(); e64.extend(words(&[0xd481_006a, 0x0002_0701])); e64.extend_from_slice(&base[0x18..]); diff --git a/tests/validation/tests/vopc_f_t.rs b/tests/validation/tests/vopc_f_t.rs new file mode 100644 index 0000000..53b74b1 --- /dev/null +++ b/tests/validation/tests/vopc_f_t.rs @@ -0,0 +1,649 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Independent per-lane expected values for the four constant Wave32 VOPC +//! integer compares (#215): `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and +//! `v_cmp_t_u32`, `_e32` only, under the contract in +//! `docs/shaders/vector-compare.md` (sections 2-7). +//! +//! The expectations are written below from the public AMD "RDNA 2" Instruction +//! Set Architecture Reference Guide only: section 12.9 "VOPC Instructions" +//! (Table 59 "Eight Compare Operations" and Table 61 "VOPC Compare Opcodes"), +//! section 3.9 "Vector Compares: VCC and VCCZ", and the VOPC word layout of +//! section 13.3.3. 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. +//! +//! Readings of the guide (not hardware evidence): +//! - Table 61: F is `D[threadId] = 0`, T is `D[threadId] = 1`, with "D = VCC in +//! VOPC encoding"; Table 59 gives the same as offsets F 0 and TRU 7. +//! - Section 3.9: `V_CMP_* => VCC[n] = EXEC[n] & (test passed for thread[n])` +//! and "VCC is fully written; there are no partial mask updates". So T writes +//! EXEC_LO masked to the lanes that exist, F writes 0 even for active lanes, +//! and stale VCC bits never survive either. +//! - Section 3.9: in wave32 only VCC_LO contributes to VCCZ, so +//! `s_cbranch_vccz` after F is taken, after T with EXEC_LO != 0 it is not, +//! and after T with EXEC_LO = 0 it is. +//! - The guide does not say that F and T skip their sources. They keep the +//! SRC0 allowlist and the contract section 5 rule: with EXEC_LO != 0 every +//! source must be valid and initialized; with EXEC_LO = 0 the encoding is +//! validated and no source is read. A lane-derived VCC_LO stays +//! lane-derived even though F's value is always 0 (contract section 5). + +#[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, CompileError, compile}; + +/// The four forms with their ENC_VOPC opcodes (guide 12.9, Table 61). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Form { + FI32 = 128, + TI32 = 135, + FU32 = 192, + TU32 = 199, +} + +const FORMS: [(Form, &str); 4] = [ + (Form::FI32, "v_cmp_f_i32"), + (Form::TI32, "v_cmp_t_i32"), + (Form::FU32, "v_cmp_f_u32"), + (Form::TU32, "v_cmp_t_u32"), +]; + +/// The per-lane test. The operands are taken so every call site names them, +/// but neither form depends on them. +fn test(form: Form, _s0: u32, _s1: u32) -> bool { + match form { + // 128 V_CMP_F_I32 / 192 V_CMP_F_U32: D[threadId] = 0. + Form::FI32 | Form::FU32 => false, + // 135 V_CMP_T_I32 / 199 V_CMP_T_U32: D[threadId] = 1. + Form::TI32 | Form::TU32 => true, + } +} + +/// Section 3.9 and contract section 3: VCC_LO = OR over the lanes n that +/// exist (`present`) of (EXEC[n] & test(n)) << n, with S0 and S1 of lane n +/// from `operands(n)`. +fn vcc(form: Form, exec: u32, present: u32, operands: impl Fn(usize) -> (u32, u32)) -> u32 { + (0..32) + .filter(|&n| (present & exec) >> n & 1 == 1) + .filter(|&n| { + let (s0, s1) = operands(n); + test(form, s0, s1) + }) + .fold(0, |mask, n| mask | 1 << n) +} + +/// Boundary operands. +const VALUES: [u32; 8] = [ + 0, + 1, + 0x1234_5678, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fffe, + 0xffff_ffff, +]; +/// Per-lane inputs: the boundary values first, then 24 more, all different. +const MORE_LANES: [u32; 24] = [ + 2, + 0x0000_00ff, + 0x0000_ffff, + 0x00ff_ffff, + 0x0f0f_0f0f, + 0x4000_0000, + 0x5555_5555, + 0x7fff_fffe, + 0x8765_4321, + 0xaaaa_aaaa, + 0xc000_0000, + 0xf0f0_f0f0, + 0xff00_0000, + 0xffff_0000, + 0xffff_ff00, + 0xffff_fff0, + 3, + 16, + 64, + 65, + 0x0000_0100, + 0x00c0_ffee, + 0x1fff_ffff, + 0xdead_beef, +]; +const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX]; +const SGPR_VALUES: [u32; 3] = [0, 0x8000_0000, u32::MAX]; +/// The last one is set explicitly, as a full EXEC written by `s_mov_b32`. +const EXEC_MASKS: [u32; 7] = [ + 0, + 0x5555_5555, + 0xaaaa_aaaa, + 0x8000_0001, + 0x0000_ffff, + 0x7fff_fffe, + u32::MAX, +]; +/// VCC_LO before the compare in the EXEC cases: bits inside and outside every +/// mask above, so a partial VCC update would show. +const STALE_VCC: u32 = 0xa5a5_c33c; + +const COUNTS: [(&str, usize); 11] = [ + ("vopc domain", 4 * 8 * 2), + ("vopc aliasing", 4 * 2), + ("vopc inline integer", 4 * 81), + ("vopc literal", 4 * 5), + ("vopc sgpr source", 4 * 2 * 3), + ("vopc vcc_lo source", 4 * 4), + ("vopc max register", 4 * 3), + ("vopc exec", 4 * (7 + 2)), + ("vopc empty exec reads nothing", 4 * 3), + ("vopc partial wave", 4 * 3), + ("vopc vccz branch", 4 * 3), +]; +/// Per form: 4 uninitialized sources, a missing literal, 9 float inline +/// constants, 9 other special SRC0 selectors, a float constant under empty +/// EXEC, SDWA, DPP16 and two DPP8 forms, the VOP3 `_e64` form, the matching +/// `v_cmpx`, and a lane-derived F result branching over a scalar instruction. +const REJECTIONS: usize = 4 * (4 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); + +const LITERAL: u32 = 255; +const VCC_LO: u32 = 106; +const EXEC_LO: u32 = 126; + +/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8 (guide +/// 13.3.3); SRC0 256 + n is VGPR n. +fn vopc(op: u32, src0: u32, vsrc1: u32) -> u32 { + 0b011_1110 << 25 | op << 17 | vsrc1 << 9 | src0 +} + +const fn vgpr(n: u32) -> u32 { + 256 + n +} + +/// `v_mov_b32 v, literal` (VOP1 opcode 1). +fn vmov(reg: u32, value: u32) -> [u32; 2] { + [0x7e00_02ff | reg << 17, value] +} + +/// `s_mov_b32 s, literal` (SOP1 opcode 3). +fn smov(reg: u32, value: u32) -> [u32; 2] { + [0xbe80_03ff | reg << 16, value] +} + +/// `s_mov_b32 exec_lo, -1`. +const FULL_EXEC: u32 = 0xbefe_03c1; +/// `v_mov_b32 v2, vcc_lo`. +const READ_VCC: u32 = 0x7e04_026a; +/// `v_cmp_lt_u32 vcc_lo, v1, v3`: a supported compare, so VCC_LO becomes +/// lane-derived from v1 < v3. +const LT_U32_V1_V3: u32 = 0x7d82_0701; +/// `s_cbranch_vccz` over one word (SOPP opcode 6, SIMM16 = 1). +const VCCZ_OVER_ONE: u32 = 0xbf86_0001; +/// `v_xor_b32 v2, v1, v2` (VOP2 opcode 29), the skipped region. +const XOR_V2_V1: u32 = 29 << 25 | 2 << 17 | 2 << 9 | (256 + 1); + +const PREFIX: [u32; 3] = [0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; +const STORE_V2: [u32; 4] = [0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]; + +/// Load v1 = lane input, `setup`, EXEC_LO = `exec` (unless `None`), the compare +/// words, EXEC_LO = -1 again, v2 = vcc_lo, `tail`, then store v2. Returns the +/// program and the compare's byte offset. +fn program(setup: &[u32], exec: Option, compare: &[u32], tail: &[u32]) -> (Vec, usize) { + let mut code = PREFIX.to_vec(); + code.extend(setup); + if let Some(exec) = exec { + code.extend(smov(EXEC_LO, exec)); + } + let offset = 4 * code.len(); + code.extend(compare); + if exec.is_some() { + code.push(FULL_EXEC); + } + code.push(READ_VCC); + code.extend(tail); + code.extend(STORE_V2); + (words(&code), offset) +} + +fn lanes() -> Vec { + VALUES.iter().chain(&MORE_LANES).copied().collect() +} + +/// The lanes of each wave of `input` that exist, as a mask per dispatch index. +fn present(input: &[u32], n: usize) -> u32 { + let in_wave = (input.len() - n / 32 * 32).min(32); + if in_wave == 32 { + u32::MAX + } else { + (1 << in_wave) - 1 + } +} + +/// A case whose lane `n` (dispatch index) of `input` expects +/// `lane(n, x, present-lane mask of its wave)`. +fn case( + (_, name): (Form, &'static str), + family: &'static str, + label: String, + code: Vec, + input: Vec, + lane: impl Fn(usize, u32, u32) -> u32, +) -> Case { + let expected = input + .iter() + .enumerate() + .map(|(n, &x)| lane(n, x, present(&input, n))) + .collect(); + Case { + form: name, + family, + label: format!("{name} {label}"), + code, + input, + expected, + } +} + +fn inline_integer(selector: u32) -> u32 { + match selector { + 128..=192 => selector - 128, + 193..=208 => (-((selector - 192) as i32)) as u32, + _ => unreachable!("not an integer inline constant"), + } +} + +/// The expected lane output under full EXEC: VCC_LO of the lane's wave. +fn full(form: Form, operands: impl Fn(usize) -> (u32, u32)) -> impl Fn(usize, u32, u32) -> u32 { + move |_, _, present| vcc(form, u32::MAX, present, &operands) +} + +fn cases() -> Vec { + let mut cases = Vec::new(); + let input = lanes(); + // S0/S1 for lane n of a wave of `input`, with v1 = input. + let v1 = |n: usize| input[n % 32]; + for entry @ (form, _) in FORMS { + let op = form as u32; + // Every boundary value against all 32 lane inputs, in each slot. + for b in VALUES { + let setup = vmov(3, b); + let (code, _) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); + let label = format!("v1, {b:#x}"); + let f = full(form, |n| (v1(n), b)); + cases.push(case(entry, "vopc domain", label, code, lanes(), f)); + let (code, _) = program(&setup, None, &[vopc(op, vgpr(3), 1)], &[]); + let label = format!("{b:#x}, v1"); + let f = full(form, |n| (b, v1(n))); + cases.push(case(entry, "vopc domain", label, code, lanes(), f)); + } + // Both sources the same register. + let b = 0x8000_0000; + let family = "vopc aliasing"; + let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(1), 1)], &[]); + let f = full(form, |n| (v1(n), v1(n))); + cases.push(case(entry, family, "v1, v1".into(), code, lanes(), f)); + let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(3), 3)], &[]); + let f = full(form, |_| (b, b)); + cases.push(case(entry, family, "v3, v3".into(), code, lanes(), f)); + // Every integer inline constant (-16..64) as SRC0. + for selector in 128..=208 { + let value = inline_integer(selector); + let (code, _) = program(&[], None, &[vopc(op, selector, 1)], &[]); + let label = format!("inline {selector} ({value:#x}), v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, "vopc inline integer", label, code, lanes(), f)); + } + // One literal dword after the VOPC word as SRC0. + for literal in LITERALS { + let (code, _) = program(&[], None, &[vopc(op, LITERAL, 1), literal], &[]); + let label = format!("literal {literal:#x}, v1"); + let f = full(form, |n| (literal, v1(n))); + cases.push(case(entry, "vopc literal", label, code, lanes(), f)); + } + // SGPR SRC0: s8 and s105, the highest SGPR. + for reg in [8, 105] { + for value in SGPR_VALUES { + let (code, _) = program(&smov(reg, value), None, &[vopc(op, reg, 1)], &[]); + let label = format!("s{reg} = {value:#x}, v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, "vopc sgpr source", label, code, lanes(), f)); + } + } + // vcc_lo SRC0: known (three values), and lane-derived from a supported + // compare; the old VCC_LO is read before the new value is written. + let family = "vopc vcc_lo source"; + for value in SGPR_VALUES { + let (code, _) = program(&smov(VCC_LO, value), None, &[vopc(op, VCC_LO, 1)], &[]); + let label = format!("vcc_lo = {value:#x}, v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, family, label, code, lanes(), f)); + } + let b = 0x8000_0000; + let mut setup = vmov(3, b).to_vec(); + setup.push(LT_U32_V1_V3); + let (code, _) = program(&setup, None, &[vopc(op, VCC_LO, 1)], &[]); + // The earlier v_cmp_lt_u32 result, from its own guide relation. + let old = (0..32) + .filter(|&n| v1(n) < b) + .fold(0u32, |mask, n| mask | 1 << n); + let f = full(form, |n| (old, v1(n))); + let label = "vcc_lo lane-derived (v1 < 0x80000000), v1".into(); + cases.push(case(entry, family, label, code, lanes(), f)); + // v255, the highest VGPR, in each slot and both. + let b = 0x7fff_ffff; + let family = "vopc max register"; + let setup = vmov(255, b); + for (src0, vsrc1, label) in [ + (vgpr(255), 1, "v255, v1"), + (vgpr(1), 255, "v1, v255"), + (vgpr(255), 255, "v255, v255"), + ] { + let (code, _) = program(&setup, None, &[vopc(op, src0, vsrc1)], &[]); + let f = full(form, |n| { + let pick = |is_v255: bool| if is_v255 { b } else { v1(n) }; + (pick(src0 == vgpr(255)), pick(vsrc1 == 255)) + }); + cases.push(case(entry, family, label.into(), code, lanes(), f)); + } + // EXEC around the compare, with a stale VCC_LO: inactive lanes' bits + // are cleared, active lanes take the test. + let family = "vopc exec"; + let b = 0x0f0f_0f0f; + let mut setup = vmov(3, b).to_vec(); + setup.extend(smov(VCC_LO, STALE_VCC)); + for exec in EXEC_MASKS { + let (code, _) = program(&setup, Some(exec), &[vopc(op, vgpr(1), 3)], &[]); + let label = format!("exec {exec:#x}, vcc_lo was {STALE_VCC:#x}, v1, {b:#x}"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, exec, p, |n| (v1(n), b)) + })); + } + // A literal SRC0 under partial and empty EXEC: its dword is consumed. + for exec in [0x00f0_0f00, 0] { + let compare = [vopc(op, LITERAL, 3), 0x8000_0000]; + let (code, _) = program(&setup, Some(exec), &compare, &[]); + let label = format!("exec {exec:#x}, literal 0x80000000, v3"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, exec, p, |_| (0x8000_0000, b)) + })); + } + // EXEC_LO = 0: no source is read, so uninitialized ones are accepted + // (contract section 5) and VCC_LO becomes 0. + let family = "vopc empty exec reads nothing"; + for (src0, vsrc1, label) in [ + (20, 1, "s20 (unknown), v1"), + (VCC_LO, 1, "vcc_lo (uninitialized), v1"), + (vgpr(9), 9, "v9, v9 (uninitialized)"), + ] { + let (code, _) = program(&[], Some(0), &[vopc(op, src0, vsrc1)], &[]); + let label = format!("exec 0, {label}"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, 0, p, |_| (0, 0)) + })); + } + // A final wave with absent lanes: 7 lanes, and 45 lanes (one full wave + // and 13 lanes), also with partial EXEC in both waves. + let family = "vopc partial wave"; + let long: Vec = lanes() + .into_iter() + .chain(lanes().into_iter().take(13)) + .collect(); + // Lane k of the wave holding dispatch index n; `vcc` asks only for + // lanes that exist. + let wave_lane = |input: &[u32], n: usize, k: usize| input[n / 32 * 32 + k]; + let short = lanes()[..7].to_vec(); + for (exec, input, label) in [ + (u32::MAX, short, "7 lanes".to_string()), + (u32::MAX, long.clone(), "45 lanes".to_string()), + (0x5555_5555, long, "45 lanes, exec 0x55555555".to_string()), + ] { + let exec_word = (exec != u32::MAX).then_some(exec); + let (code, _) = program(&vmov(3, 5), exec_word, &[vopc(op, vgpr(1), 3)], &[]); + let copy = input.clone(); + cases.push(case(entry, family, label, code, input, |n, _, p| { + vcc(form, exec, p, |k| (wave_lane(©, n, k), 5)) + })); + } + // s_cbranch_vccz after the compare (guide 3.9: VCCZ = VCC_LO == 0 in + // wave32). Taken: v2 = VCC_LO (0). Not taken: v2 = VCC_LO ^ v1. + let family = "vopc vccz branch"; + for exec in [u32::MAX, 0x0000_8000, 0] { + let (code, _) = program( + &vmov(3, 5), + Some(exec), + &[vopc(op, vgpr(1), 3)], + &[VCCZ_OVER_ONE, XOR_V2_V1], + ); + let label = format!("exec {exec:#x}, then s_cbranch_vccz"); + cases.push(case(entry, family, label, code, lanes(), |_, x, p| { + let mask = vcc(form, exec, p, |n| (v1(n), 5)); + if mask == 0 { 0 } else { mask ^ x } + })); + } + } + cases +} + +/// Programs both interpreters must refuse, with the refusing byte offset. +fn rejections() -> Vec<(String, Vec, usize)> { + let setup = vmov(3, 7); + let mut all = Vec::new(); + for (form, name) in FORMS { + let op = form as u32; + let mut reject = |label: String, (code, offset): (Vec, usize)| { + all.push((format!("{name} {label}"), code, offset)); + }; + // Uninitialized sources under nonzero EXEC (contract sections 4 and 5). + for (src0, vsrc1, label) in [ + (20, 3, "s20 unknown"), + (VCC_LO, 3, "vcc_lo uninitialized"), + (vgpr(9), 3, "v9 uninitialized as SRC0"), + (vgpr(1), 9, "v9 uninitialized as VSRC1"), + ] { + reject( + label.into(), + program(&setup, None, &[vopc(op, src0, vsrc1)], &[]), + ); + } + // A literal SRC0 with no literal dword: the program ends at the word. + let mut code = PREFIX.to_vec(); + code.extend(setup); + let offset = 4 * code.len(); + code.push(vopc(op, LITERAL, 3)); + reject("missing literal".into(), (words(&code), offset)); + // Float inline constants 240-248, VCC_HI, TTMP-adjacent and special + // selectors outside the allowlist (contract section 2). + for src0 in (240..=248).chain([107, 124, 125, 126, 127, 251, 252, 253, 254]) { + let label = format!("src0 {src0}"); + reject(label, program(&setup, None, &[vopc(op, src0, 3)], &[])); + } + // Rejected at decode independent of EXEC. + let label = "src0 240 under empty exec".into(); + reject(label, program(&setup, Some(0), &[vopc(op, 240, 3)], &[])); + // SDWA (249), DPP16 (250), DPP8 (233) and DPP8FI (234) with SRC0 v1. + for (src0, extension) in [ + (249, 0x0606_0601), + (250, 0xff00_e401), + (233, 0xfac6_8801), + (234, 0xfac6_8801), + ] { + let label = format!("src0 {src0} extension"); + reject( + label, + program(&setup, None, &[vopc(op, src0, 3), extension], &[]), + ); + } + // The VOP3 `_e64` form (ENCODING 0b110101, OP = the VOPC opcode, + // SDST vcc_lo): v_cmp vcc_lo, v1, v3. + let vop3 = [0xd400_0000 | op << 16 | VCC_LO, vgpr(1) | vgpr(3) << 9]; + reject("_e64".into(), program(&setup, None, &vop3, &[])); + // The matching v_cmpx (writes EXEC): opcode + 16 (Table 61: 144, 151, + // 208, 215). + let label = format!("v_cmpx opcode {}", op + 16); + reject( + label, + program(&setup, None, &[vopc(op + 16, vgpr(1), 3)], &[]), + ); + // F under nonzero EXEC is lane-derived even though its value is 0, so + // a vccz branch over `s_mov_b32 s8, 0` is refused at that word. + // Layout: compare, v2 = vcc_lo, branch, then the s_mov at +12. + let tail = [VCCZ_OVER_ONE, 0xbe88_0380]; + let (code, compare) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &tail); + reject("lane-derived vccz over s_mov".into(), (code, compare + 12)); + } + all +} + +fn assert_rejected_at(label: &str, code: &[u8], offset: usize, input: &[u32]) { + match xenora_ref::execute(code, input) { + Ok(_) => panic!("reference accepted {label}"), + Err(error) => assert_eq!( + error.offset, offset, + "reference rejected {label} elsewhere: {error:?}" + ), + } + 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}" + ), + } +} + +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:x?}, expected {:x?}", 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 +} + +#[test] +fn expectations_follow_the_guide_examples() { + // Worked by hand from section 3.9 and Table 61. + for (form, exec, present, mask) in [ + (Form::TI32, u32::MAX, u32::MAX, u32::MAX), + (Form::TU32, 0x5555_5555, u32::MAX, 0x5555_5555), + (Form::TI32, u32::MAX, 0x7f, 0x7f), + (Form::TU32, 0xf0f0_f0f0, 0x1fff, 0x10f0), + (Form::TI32, 0, u32::MAX, 0), + (Form::FI32, u32::MAX, u32::MAX, 0), + (Form::FU32, 0x8000_0001, u32::MAX, 0), + ] { + assert_eq!( + vcc(form, exec, present, |_| (0, 0)), + mask, + "{form:?} {exec:#x}" + ); + } +} + +#[test] +fn vopc_f_t_match_the_guide_on_the_reference() { + let cases = checked_cases(); + let failed = failures(&cases, |code, input| { + xenora_ref::execute(code, input).map_err(|error| format!("{error:?}")) + }); + assert!( + failed.is_empty(), + "reference disagrees with the guide:\n{}", + failed.join("\n") + ); + eprintln!("vopc_f_t: {} reference cases", cases.len()); + for (form, n) in tally(&cases, |case| case.form) { + eprintln!(" form {form}: {n}"); + } +} + +#[test] +fn vopc_f_t_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!("vopc_f_t: {} independent-interpreter cases", cases.len()); +} + +#[test] +fn vopc_f_t_outside_the_contract_are_rejected() { + let rejections = rejections(); + assert_eq!(rejections.len(), REJECTIONS); + for (label, code, offset) in &rejections { + assert_rejected_at(label, code, *offset, &lanes()); + } + eprintln!("vopc_f_t: {} rejections", rejections.len()); +} + +#[test] +fn other_constant_compares_stay_unsupported() { + // F and T/TRU of the float, 64-bit and v_cmpx groups (Table 61): + // V_CMP_F_F32 0, V_CMP_TRU_F32 15, V_CMPX_F_F32 16, V_CMPX_TRU_F32 31, + // V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183, + // V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247. + let setup = vmov(3, 7); + for op in [0, 15, 16, 31, 160, 167, 176, 183, 224, 231, 240, 247] { + let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); + assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes()); + } +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation, and the translator's F/T forms"] +fn vopc_f_t_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, offset) in rejections() { + let at = match compile(Architecture::Gfx1030, &code) { + Err(CompileError::Decode(error)) => error.offset, + Err(CompileError::Verify { offset, .. }) => offset, + other => panic!("compiler did not reject {label}: {other:?}"), + }; + assert_eq!(at, offset, "compiler rejected {label} elsewhere"); + } + let cases = checked_cases(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!( + "vopc_f_t: {} Metal cases in {programs} programs", + cases.len() + ); +} From e3bbc955bcdf1d04e4072643ebdd914098ac025e Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:38:18 +0530 Subject: [PATCH 03/19] ffi: share one Metal device and queue across frame-loop sessions (#290) Each frame-loop session opened its own Metal command queue. The GPU driver allocates a per-queue working set on the first command buffer (about 45 MiB on an Apple M5 with validation) and frees it asynchronously 10-50 ms after the queue is released, so the footprint read right after a session ended swung by about 50 MiB and the repeated-sessions footprint test failed intermittently (5 of 30 runs). There was no leak. Sessions now share one process-wide NativeCompute, which is Send + Sync, so the working set is allocated once and kept. Remove the settled_footprint wait added in #292: the original test measures the immediate footprint again. Add a 50-session regression test (completion, pause and resume, destroy while running) and a concurrent two-session test for shared-queue correctness and session isolation. Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/ffi/src/frame_loop.rs | 27 +++++- crates/ffi/tests/frame_loop.rs | 160 ++++++++++++++++++++++++++++----- 3 files changed, 163 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01c019c..f56e089 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -196,6 +196,7 @@ remains unsupported. ### Fixed +- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix. - Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile. - Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame. - Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect. diff --git a/crates/ffi/src/frame_loop.rs b/crates/ffi/src/frame_loop.rs index 8357944..1f85a9a 100644 --- a/crates/ffi/src/frame_loop.rs +++ b/crates/ffi/src/frame_loop.rs @@ -10,7 +10,7 @@ //! the guest leaves its loop and halts. use std::cell::RefCell; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; use std::thread::JoinHandle; use xenora_loader::startup::{StartupLayout, run_synthetic_startup}; @@ -171,8 +171,8 @@ impl FrameLoop { include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"), ) .map_err(|e| format!("shader translation: {e}"))?; - let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?; - // The session's GPU resources live on the guest thread, where the import runs. + let gpu = shared_gpu()?; + // The import runs on the guest thread, so the session's shader lives there too. GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl))); let shared = Arc::clone(self); @@ -268,7 +268,26 @@ impl FrameLoop { } thread_local! { - static GPU: RefCell> = const { RefCell::new(None) }; + static GPU: RefCell> = const { RefCell::new(None) }; +} + +/// One Metal device and command queue shared by every frame-loop session (#290). +/// +/// The first command buffer submitted on a queue makes the GPU driver allocate a +/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the +/// driver frees that memory asynchronously, 10–50 ms after the queue is released. +/// A queue per session therefore allocated and freed it once per session, and the +/// process footprint depended on how far that release had progressed. One queue +/// for the process allocates the working set once and keeps it: bounded caching, +/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes +/// `&self`, so concurrent sessions can share it. A device that cannot be opened +/// is reported to every session that asks. +fn shared_gpu() -> Result<&'static NativeCompute, String> { + static SHARED: OnceLock> = OnceLock::new(); + SHARED + .get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}"))) + .as_ref() + .map_err(Clone::clone) } /// Frame `index` is a red strip in column `index % 4` on the clear colour. diff --git a/crates/ffi/tests/frame_loop.rs b/crates/ffi/tests/frame_loop.rs index 6effc58..4e15efd 100644 --- a/crates/ffi/tests/frame_loop.rs +++ b/crates/ffi/tests/frame_loop.rs @@ -82,25 +82,6 @@ fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Statu } } -/// Footprint once it has stopped changing. After a session is destroyed, Metal gives -/// back its memory asynchronously: measured on an Apple M5, a reading taken right after -/// destroy was up to about 45 MiB above the floor it returned to within one second, -/// every time. A single immediate reading therefore mixes in memory that is already on -/// its way out. Read every 50 ms until two consecutive readings agree within 1 MiB -/// (at most 5 s). A genuine leak still settles high, so it is still caught. -fn settled_footprint() -> u64 { - let deadline = Instant::now() + Duration::from_secs(5); - let mut previous = footprint(); - loop { - std::thread::sleep(Duration::from_millis(50)); - let current = footprint(); - if current.abs_diff(previous) < 1 << 20 || Instant::now() >= deadline { - return current; - } - previous = current; - } -} - /// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2). fn footprint() -> u64 { unsafe extern "C" { @@ -264,11 +245,11 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() { // Warm up so one-time allocations (Metal device, shader compiler) are excluded. run(); run(); - let baseline = settled_footprint(); + let baseline = footprint(); for _ in 0..5 { run(); } - let after = settled_footprint(); + let after = footprint(); let growth = after.saturating_sub(baseline); println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}"); assert!( @@ -276,3 +257,140 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() { "footprint grew by {growth} bytes over 5 sessions of 300 frames" ); } + +/// Regression test for #290: the footprint read right after each destroy must stay +/// flat across many sessions. Each session used to open its own Metal command queue, +/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with +/// validation) asynchronously after release, so these readings swung by about 50 MiB +/// from session to session. Sessions now share one queue. The mix of sessions covers +/// normal completion, pause and resume, and destruction while running. +#[test] +fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + let one = |kind: usize| { + let session = session(); + match kind { + 0 => { + assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK); + let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING); + assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100)); + } + 1 => { + assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK); + wait_until(session, "10 frames", |s| s.completed >= 10); + assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK); + assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK); + let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING); + assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100)); + } + _ => { + assert_eq!( + xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES), + XENORA_OK + ); + wait_until(session, "a frame", |s| s.completed >= 1); + } + } + assert_eq!(xenora_session_destroy(session), XENORA_OK); + footprint() + }; + one(0); // the first session allocates the shared queue's working set + let readings: Vec = (0..50).map(|i| one(i % 3)).collect(); + let mib: Vec = readings.iter().map(|r| r >> 20).collect(); + println!("footprint after each destroy (MiB): {mib:?}"); + let median = |values: &[u64]| { + let mut sorted = values.to_vec(); + sorted.sort_unstable(); + sorted[sorted.len() / 2] + }; + // Sustained growth: the typical reading at the end against the start. + let (start, end) = (median(&readings[..10]), median(&readings[40..])); + assert!( + end.saturating_sub(start) < 16 << 20, + "footprint grew from {start} to {end} bytes (median of first and last ten sessions)" + ); + // Per-session churn, the cause fixed in #290: with a queue per session, about half + // of all readings sat some 45 MiB away from the median. With the shared queue, + // a reading is still occasionally caught while the driver frees a batch of + // per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone + // within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such + // readings in 50 keeps a false failure near 1 in 5,000 runs while per-session + // churn would exceed it every time. + let centre = median(&readings); + let outliers: Vec = readings + .iter() + .filter(|&&r| r.abs_diff(centre) >= 16 << 20) + .map(|r| r >> 20) + .collect(); + assert!( + outliers.len() <= 2, + "{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}", + outliers.len(), + centre >> 20 + ); +} + +/// Two sessions render at the same time through the shared Metal queue (#290). Each +/// must keep its own frame sequence and pixels, pausing one must not stop the other, +/// and destroying one mid-run must not disturb the other. +#[test] +fn concurrent_sessions_share_the_queue_but_stay_isolated() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + let (a, b) = (session(), session()); + assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK); + assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK); + wait_until(a, "session A started", |s| s.completed >= 5); + wait_until(b, "session B started", |s| s.completed >= 5); + + // Pausing A holds only A. + assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK); + let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED); + let b_before = status(b).completed; + let b_moving = wait_until(b, "session B progress while A is paused", |s| { + s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING + }); + assert!( + b_moving.completed > b_before, + "B kept rendering while A was paused" + ); + let a_still = status(a); + assert_eq!(a_still.state, XENORA_LOOP_PAUSED); + // At most the frame A was rendering when paused can still complete. + assert!(a_still.completed <= a_held.completed + 1); + assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id)); + assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK); + + // Both finish with their own counts and their own final frames. + let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING); + let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING); + assert_eq!( + (a_done.state, a_done.completed, a_done.frame_id), + (XENORA_LOOP_FINISHED, 400, 399) + ); + assert_eq!( + (b_done.state, b_done.completed, b_done.frame_id), + (XENORA_LOOP_FINISHED, 250, 249) + ); + assert_eq!(a_done.rgba.to_vec(), expected(399)); + assert_eq!(b_done.rgba.to_vec(), expected(249)); + assert_eq!(xenora_session_destroy(a), XENORA_OK); + assert_eq!(xenora_session_destroy(b), XENORA_OK); + + // Destroying one running session leaves the other running to completion. + let (c, d) = (session(), session()); + assert_eq!( + xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES), + XENORA_OK + ); + assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK); + wait_until(c, "session C started", |s| s.completed >= 5); + wait_until(d, "session D started", |s| s.completed >= 5); + assert_eq!(xenora_session_destroy(c), XENORA_OK); + let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING); + assert_eq!( + (d_done.state, d_done.completed, d_done.frame_id), + (XENORA_LOOP_FINISHED, 300, 299) + ); + assert_eq!(d_done.rgba.to_vec(), expected(299)); + assert_eq!(xenora_session_destroy(d), XENORA_OK); +} From b559fb575ca14e453fa4f6a02fabff3b43c360cc Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:38:55 -0600 Subject: [PATCH 04/19] isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215) Adds the four constant Wave32 VOPC compares as registry forms with the relations f and t (guide Table 59 offsets 0 and 7), valid only for the vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the #239 contract: sources are decoded and checked as for every compare, VCC_LO := EXEC & existing lanes & test, fully written, and the mask is lane-derived. Their MSL wave mask reads no operand bits. A new LLVM-assembled fixture covers F clearing a stale VCC, T and F under partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both results; the oracle merged from task/215-vopc-oracle supplies the reference side. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/tests/gfx1030.rs | 9 +- crates/isa/generate_semantics.py | 8 +- crates/isa/semantics/rdna2.toml | 89 +++++++++++ crates/isa/src/lib.rs | 4 + crates/isa/src/primitive.rs | 10 ++ crates/isa/src/semantics_gen.rs | 138 +++++++++++++++++- crates/isa/tests/semantics.rs | 4 +- crates/shader/src/lib.rs | 13 +- crates/shader/tests/compiler.rs | 14 ++ docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 4 + docs/shaders/reference-interpreter.md | 2 +- docs/shaders/semantic-coverage.md | 4 +- docs/shaders/vector-compare.md | 12 +- docs/status.toml | 48 ++++++ fixtures/golden/vector-compare-ft.ir | 28 ++++ fixtures/golden/vector-compare-ft.metal | 76 ++++++++++ fixtures/rdna2/vector-compare-ft.bin | Bin 0 -> 164 bytes fixtures/rdna2/vector-compare-ft.s | 45 ++++++ scripts/assemble-fixture.sh | 2 +- .../test_generate_semantics.py | 16 ++ tests/validation/known_answers.rs | 43 ++++++ 23 files changed, 554 insertions(+), 24 deletions(-) create mode 100644 fixtures/golden/vector-compare-ft.ir create mode 100644 fixtures/golden/vector-compare-ft.metal create mode 100644 fixtures/rdna2/vector-compare-ft.bin create mode 100644 fixtures/rdna2/vector-compare-ft.s diff --git a/CHANGELOG.md b/CHANGELOG.md index acc1736..4efdfe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ remains unsupported. - Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed. - Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues. - Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215. +- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported. - Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215. - Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`. - Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`. diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 257ee62..d9c3f97 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -461,6 +461,8 @@ fn reference_op(instruction: Instruction) -> Op { CompareRelation::Greater => 4, CompareRelation::NotEqual => 5, CompareRelation::GreaterOrEqual => 6, + CompareRelation::False => 0, + CompareRelation::True => 7, }, signed: op.signed(), }, @@ -526,12 +528,13 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"), include_bytes!("../../../fixtures/rdna2/vector-integer.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare.bin"), + include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 100, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 104, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() @@ -596,7 +599,7 @@ fn assemble_matrix() -> Vec { ); // Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo, // inline integers at both ends, inline zero and a literal. - for relation in ["lt", "eq", "le", "gt", "ne", "ge"] { + for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] { for kind in ["i32", "u32"] { for src0 in [ "v255", @@ -744,8 +747,6 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() { let outside_subset: &[&[u32]] = &[ &[0x7e04_026b], // VOP1 VCC_HI source &[0x7da2_0501], // v_cmpx_eq_u32_e32 - &[0x7d00_0501], // v_cmp_f_i32_e32 - &[0x7d0e_0501], // v_cmp_t_i32_e32 &[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64 &[0x8788_0908], // s_and_b64 &[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 4612a69..337b897 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -60,8 +60,10 @@ SOURCE_BITS = {8, 16} RELATION_KEY = "relation" RELATIONS = { "eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual", - "lt": "Less", "le": "LessOrEqual", + "lt": "Less", "le": "LessOrEqual", "f": "False", "t": "True", } +# F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7). +VECTOR_ONLY_RELATIONS = {"f", "t"} # (relation, signedness) -> primitive. Equality does not depend on signedness, # so both declared signednesses of EQ and LG share one primitive. COMPARE_PRIMITIVES = { @@ -71,6 +73,8 @@ COMPARE_PRIMITIVES = { ("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32", ("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32", ("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32", + ("f", "signed"): "false_b32", ("f", "unsigned"): "false_b32", + ("t", "signed"): "true_b32", ("t", "unsigned"): "true_b32", } # Logical operations take untyped bits; arithmetic ones never do. Shifts take # the signedness their primitive names, and their S1 is an unsigned count. @@ -564,6 +568,8 @@ def validate(registry, snapshot): errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}") elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES: errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") + elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare": + errors.append(f"{label}: relation {relation} exists only for VOPC compares") # SOPC compares write SCC; VOPC compares write VCC and leave SCC. scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" if form["scc"] != scc: diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index eba44be..29f678a 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -1678,3 +1678,92 @@ spec = [ { document = "guide", section = "3.9", page = 19 }, ] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- +# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes +# that exist. Sources are still decoded and checked as for the other compares +# (docs/shaders/vector-compare.md section 5). + +[[form]] +name = "V_CMP_F_I32" +family = "VOPC" +opcode = 128 +variant = "CmpFI32" +operation = "compare" +relation = "f" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_I32" +family = "VOPC" +opcode = 135 +variant = "CmpTI32" +operation = "compare" +relation = "t" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_F_U32" +family = "VOPC" +opcode = 192 +variant = "CmpFU32" +operation = "compare" +relation = "f" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_U32" +family = "VOPC" +opcode = 199 +variant = "CmpTU32" +operation = "compare" +relation = "t" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index a9269db..b5edab6 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -111,6 +111,10 @@ pub enum CompareRelation { NotEqual, /// S0 >= S1 (offset 6). GreaterOrEqual, + /// Never holds (VOPC F, offset 0). + False, + /// Always holds (VOPC T, offset 7). + True, } /// Output targeted by a supported uncompressed four-component export. diff --git a/crates/isa/src/primitive.rs b/crates/isa/src/primitive.rs index 3395572..bc4eea8 100644 --- a/crates/isa/src/primitive.rs +++ b/crates/isa/src/primitive.rs @@ -99,6 +99,16 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) { (value, value != 0) } +/// The VOPC F test: false for every operand pair. +pub const fn false_b32(_a: u32, _b: u32) -> bool { + false +} + +/// The VOPC T test: true for every operand pair. +pub const fn true_b32(_a: u32, _b: u32) -> bool { + true +} + /// `a == b` on the raw bits; signedness does not matter for equality. pub const fn eq_b32(a: u32, b: u32) -> bool { a == b diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 0366a2b..8e889fb 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1439,6 +1439,14 @@ pub enum VectorCompareOp { CmpNeU32, /// `v_cmp_ge_u32` (VOPC opcode 198): unsigned compare ge, VCC = lane_mask. CmpGeU32, + /// `v_cmp_f_i32` (VOPC opcode 128): signed compare f, VCC = lane_mask. + CmpFI32, + /// `v_cmp_t_i32` (VOPC opcode 135): signed compare t, VCC = lane_mask. + CmpTI32, + /// `v_cmp_f_u32` (VOPC opcode 192): unsigned compare f, VCC = lane_mask. + CmpFU32, + /// `v_cmp_t_u32` (VOPC opcode 199): unsigned compare t, VCC = lane_mask. + CmpTU32, } /// VectorCompareOp by VOPC OP field value; `None` for undeclared opcodes. @@ -1571,13 +1579,14 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ None, None, None, - None, + Some(VectorCompareOp::CmpFI32), Some(VectorCompareOp::CmpLtI32), Some(VectorCompareOp::CmpEqI32), Some(VectorCompareOp::CmpLeI32), Some(VectorCompareOp::CmpGtI32), Some(VectorCompareOp::CmpNeI32), Some(VectorCompareOp::CmpGeI32), + Some(VectorCompareOp::CmpTI32), None, None, None, @@ -1634,15 +1643,14 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ None, None, None, - None, - None, + Some(VectorCompareOp::CmpFU32), Some(VectorCompareOp::CmpLtU32), Some(VectorCompareOp::CmpEqU32), Some(VectorCompareOp::CmpLeU32), Some(VectorCompareOp::CmpGtU32), Some(VectorCompareOp::CmpNeU32), Some(VectorCompareOp::CmpGeU32), - None, + Some(VectorCompareOp::CmpTU32), None, None, None, @@ -1703,7 +1711,7 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ impl VectorCompareOp { /// Every operation, in registry order. - pub const ALL: [Self; 12] = [ + pub const ALL: [Self; 16] = [ Self::CmpLtI32, Self::CmpEqI32, Self::CmpLeI32, @@ -1716,6 +1724,10 @@ impl VectorCompareOp { Self::CmpGtU32, Self::CmpNeU32, Self::CmpGeU32, + Self::CmpFI32, + Self::CmpTI32, + Self::CmpFU32, + Self::CmpTU32, ]; /// Selects the operation from a first instruction word: the VOPC encoding @@ -1742,6 +1754,10 @@ impl VectorCompareOp { Self::CmpGtU32 => "v_cmp_gt_u32", Self::CmpNeU32 => "v_cmp_ne_u32", Self::CmpGeU32 => "v_cmp_ge_u32", + Self::CmpFI32 => "v_cmp_f_i32", + Self::CmpTI32 => "v_cmp_t_i32", + Self::CmpFU32 => "v_cmp_f_u32", + Self::CmpTU32 => "v_cmp_t_u32", } } @@ -1760,6 +1776,10 @@ impl VectorCompareOp { Self::CmpGtU32 => 77, Self::CmpNeU32 => 78, Self::CmpGeU32 => 79, + Self::CmpFI32 => 80, + Self::CmpTI32 => 81, + Self::CmpFU32 => 82, + Self::CmpTU32 => 83, }] } @@ -1778,6 +1798,10 @@ impl VectorCompareOp { Self::CmpGtU32 => "v_cmp_gt_u32_e32", Self::CmpNeU32 => "v_cmp_ne_u32_e32", Self::CmpGeU32 => "v_cmp_ge_u32_e32", + Self::CmpFI32 => "v_cmp_f_i32_e32", + Self::CmpTI32 => "v_cmp_t_i32_e32", + Self::CmpFU32 => "v_cmp_f_u32_e32", + Self::CmpTU32 => "v_cmp_t_u32_e32", } } @@ -1796,6 +1820,10 @@ impl VectorCompareOp { Self::CmpGtU32 => false, Self::CmpNeU32 => false, Self::CmpGeU32 => false, + Self::CmpFI32 => true, + Self::CmpTI32 => true, + Self::CmpFU32 => false, + Self::CmpTU32 => false, } } @@ -1814,6 +1842,10 @@ impl VectorCompareOp { Self::CmpGtU32 => CompareRelation::Greater, Self::CmpNeU32 => CompareRelation::NotEqual, Self::CmpGeU32 => CompareRelation::GreaterOrEqual, + Self::CmpFI32 => CompareRelation::False, + Self::CmpTI32 => CompareRelation::True, + Self::CmpFU32 => CompareRelation::False, + Self::CmpTU32 => CompareRelation::True, } } @@ -1832,12 +1864,16 @@ impl VectorCompareOp { Self::CmpGtU32 => primitive::gt_u32(src0, src1), Self::CmpNeU32 => primitive::ne_b32(src0, src1), Self::CmpGeU32 => primitive::ge_u32(src0, src1), + Self::CmpFI32 => primitive::false_b32(src0, src1), + Self::CmpTI32 => primitive::true_b32(src0, src1), + Self::CmpFU32 => primitive::false_b32(src0, src1), + Self::CmpTU32 => primitive::true_b32(src0, src1), } } } /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1918,10 +1954,14 @@ pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ ("V_CMP_GT_U32", EncodingFamily::Vopc), ("V_CMP_NE_U32", EncodingFamily::Vopc), ("V_CMP_GE_U32", EncodingFamily::Vopc), + ("V_CMP_F_I32", EncodingFamily::Vopc), + ("V_CMP_T_I32", EncodingFamily::Vopc), + ("V_CMP_F_U32", EncodingFamily::Vopc), + ("V_CMP_T_U32", EncodingFamily::Vopc), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 80] = [ +pub static FORMS: [FormSemantics; 84] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3602,4 +3642,88 @@ pub static FORMS: [FormSemantics; 80] = [ spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_CMP_F_I32", + family: EncodingFamily::Vopc, + opcode: 128, + 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::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_I32", + family: EncodingFamily::Vopc, + opcode: 135, + 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::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_F_U32", + family: EncodingFamily::Vopc, + opcode: 192, + 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::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_U32", + family: EncodingFamily::Vopc, + opcode: 199, + 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::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index b46b692..895b7ff 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -143,6 +143,8 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { CompareRelation::Greater => ordering.is_gt(), CompareRelation::NotEqual => ordering.is_ne(), CompareRelation::GreaterOrEqual => ordering.is_ge(), + CompareRelation::False => false, + CompareRelation::True => true, }; assert_eq!( op.test(src0, src1), @@ -153,7 +155,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { } } } - // v_cmpx, F/T and the 16-, 64-bit and float compares must not be dispatched. + // v_cmpx and the 16-, 64-bit and float compares must not be dispatched. dispatch_selects_exactly(EncodingFamily::Vopc, |word| { VectorCompareOp::from_word(word).map(|op| op.semantics().name) }); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 50a8130..3eae65c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -202,6 +202,9 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { CompareRelation::Greater => ">", CompareRelation::NotEqual => "!=", CompareRelation::GreaterOrEqual => ">=", + // F and T read no operand bits. + CompareRelation::False => return "false".to_owned(), + CompareRelation::True => return "true".to_owned(), }; if op.signed() { format!("as_type({left}) {symbol} as_type({right})") @@ -523,7 +526,15 @@ fn emit_lane_mask( exec: u32, ) { let mut cone = vec![false; index]; - let mut pending = vec![src0, src1]; + // F and T do not depend on the operands, so their lanes compute none. + let mut pending = if matches!( + op.relation(), + xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True + ) { + Vec::new() + } else { + vec![src0, src1] + }; while let Some(value) = pending.pop() { if uniform[value.0] || cone[value.0] { continue; diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index e72291a..6d94175 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -350,6 +350,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() { ); } +#[test] +fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() { + let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"); + let result = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + result.ir, + include_str!("../../../fixtures/golden/vector-compare-ft.ir") + ); + assert_eq!( + result.msl, + include_str!("../../../fixtures/golden/vector-compare-ft.metal") + ); +} + #[test] fn vector_compares_lower_to_per_thread_wave_masks_and_selects() { let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index d5ef3f6..7e30221 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -100 / 100 +104 / 104 Accepted Metal forms · Apple M5 -18 / 100 +18 / 104 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index 448d6bc..d3f72f4 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -89,6 +89,10 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `v_cmp_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_cmp_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_cmp_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D000501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D0E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D800501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D8E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified | | `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified | | `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified | diff --git a/docs/shaders/reference-interpreter.md b/docs/shaders/reference-interpreter.md index 60a3059..9b55af5 100644 --- a/docs/shaders/reference-interpreter.md +++ b/docs/shaders/reference-interpreter.md @@ -12,7 +12,7 @@ | SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. | | SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. | | SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. | -| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). | +| VOPC `V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_{I32,U32}` | Compare widened 64-bit values per active lane (F is false and T true for every lane). VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). | | SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. | | VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. | | VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. | diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index 3b51194..04f437a 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -35,8 +35,8 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| VOPC | 190 | 12 | 12 | 12 | 12 | 12 | 0 | 0 | 7 | -| **Total** | 1465 | 100 | 80 | 104 | 100 | 100 | 18 | 18 | 44 | +| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | +| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 | ## Unsupported operand variants diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index 9d8a8ca..a9b1dec 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -53,6 +53,8 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP: | v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 | | v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 | | v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 | +| v_cmp_f_i32 / v_cmp_f_u32 | false (Table 59 offset 0) | +| v_cmp_t_i32 / v_cmp_t_u32 | true (offset 7) | `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. The forms are declared in the semantic registry @@ -98,7 +100,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned - V_CMPX_* (writes EXEC: divergent execution; needs its own contract). - The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers). -- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class. +- SDWA and DPP forms; 16-bit, 64-bit and float compares; v_cmp_class. - SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs, M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct. - A normal-SGPR SRC0 without a known value, when EXEC_LO != 0. @@ -197,7 +199,7 @@ instructions are pure 32-bit ALU and are evaluated unconditionally. ## 9. Verification `fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM. -It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo` +It uses the twelve relational forms with VGPR, SGPR, inline, literal and `vcc_lo` sources, a compare and a mask move under partial EXEC, a compare under empty EXEC that must clear a stale VCC, SCC kept across compares, and a runtime `s_cbranch_vccz`. Its expected output is written in @@ -205,6 +207,12 @@ EXEC that must clear a stale VCC, SCC kept across compares, and a runtime relation for each row. The test input has a wave whose branch is taken, one whose branch is not, and a final partial wave of 9 lanes. +`fixtures/rdna2/vector-compare-ft.s` does the same for the four F and T +forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading +`vcc_lo`, and runtime `s_cbranch_vccz` on a T result (never taken) and an F +result (always taken). The independent oracle for F and T is +`tests/validation/tests/vopc_f_t.rs`. + The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff, 0x0f0f0f0f), in both operand orders. That is 240 programs, checked against diff --git a/docs/status.toml b/docs/status.toml index f96bee7..01fb189 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -950,6 +950,54 @@ gpu = "local Apple M5 readback passed; acceptance pending" recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "v_cmp_f_i32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written" +representation = "`7D000501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_i32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written" +representation = "`7D0E0501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_f_u32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written" +representation = "`7D800501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_u32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written" +representation = "`7D8E0501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + [[instruction]] form = "s_cbranch_scc0" encoding = "Nonnegative signed dword displacement" diff --git a/fixtures/golden/vector-compare-ft.ir b/fixtures/golden/vector-compare-ft.ir new file mode 100644 index 0000000..f0e68ee --- /dev/null +++ b/fixtures/golden/vector-compare-ft.ir @@ -0,0 +1,28 @@ +0000: t0 = load.u32 input[index] +0014: t1 = const.u32 0x00000000 +0018: t2 = const.u32 0x00000001 +0020: t3 = wave.mask v_cmp_f_i32_e32 t0, t0 exec=0xffffffff +0028: t4 = xor.b32 t1, t3 +002c: t5 = const.u32 0x12345678 +002c: t6 = wave.mask v_cmp_t_i32_e32 t5, t0 exec=0xffffffff +0034: t7 = lshl.b32 t4, t2 +0038: t8 = xor.b32 t7, t6 +0044: t9 = const.u32 0xfffffff9 +0044: t10 = wave.mask v_cmp_t_u32_e32 t9, t0 exec=0x0f0f0f0f +0050: t11 = lshl.b32 t8, t2 +0054: t12 = xor.b32 t11, t10 +0058: t13 = wave.mask v_cmp_t_i32_e32 t0, t0 exec=0xffffffff +0064: t14 = const.u32 0xdeadbeef +0064: t15 = wave.mask v_cmp_f_u32_e32 t14, t0 exec=0x3c3c3c3c +0074: t16 = lshl.b32 t12, t2 +0078: t17 = xor.b32 t16, t15 +007c: t18 = wave.mask v_cmp_t_u32_e32 t15, t0 exec=0xffffffff +0080: branch.vccz t18 -> 0x0088 +0084: t20 = xor.b32 t17, t0 +0088: t21 = join.vccz t18, t20, t17 +0088: t22 = const.u32 0x00000040 +0088: t23 = wave.mask v_cmp_f_i32_e32 t22, t0 exec=0xffffffff +008c: branch.vccz t23 -> 0x0094 +0090: t25 = const.u32 0x00000000 +0094: t26 = join.vccz t23, t25, t21 +0094: store.u32 output[index], t26 diff --git a/fixtures/golden/vector-compare-ft.metal b/fixtures/golden/vector-compare-ft.metal new file mode 100644 index 0000000..b4c83e0 --- /dev/null +++ b/fixtures/golden/vector-compare-ft.metal @@ -0,0 +1,76 @@ +#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 grid [[threads_per_grid]]) { + uint t0 = input[index]; + uint t1 = 0x00000000u; + uint t2 = 0x00000001u; + uint t3 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t3 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t4 = t1 ^ t3; + uint t5 = 0x12345678u; + uint t6 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t6 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t7 = t4 << (t2 & 31u); + uint t8 = t7 ^ t6; + uint t9 = 0xfffffff9u; + uint t10 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t10 |= ((0x0f0f0f0fu >> lane) & pass) << lane; + } + uint t11 = t8 << (t2 & 31u); + uint t12 = t11 ^ t10; + uint t13 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t13 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t14 = 0xdeadbeefu; + uint t15 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t15 |= ((0x3c3c3c3cu >> lane) & pass) << lane; + } + uint t16 = t12 << (t2 & 31u); + uint t17 = t16 ^ t15; + uint t18 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t18 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t20 = t17 ^ t0; + uint t21 = t18 != 0u ? t20 : t17; + uint t22 = 0x00000040u; + uint t23 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t23 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t25 = 0x00000000u; + uint t26 = t23 != 0u ? t25 : t21; + output[index] = t26; +} diff --git a/fixtures/rdna2/vector-compare-ft.bin b/fixtures/rdna2/vector-compare-ft.bin new file mode 100644 index 0000000000000000000000000000000000000000..a12df6665be972abe0f8909240387c255ba5c88b GIT binary patch literal 164 zcmZQjFnGYg$k0$=-?RTebH~1lFcYB$CYHKJCa$`J%&+z_GBea>F>%x}ak5x(F!6!e ztgI|1ApU>mfBX1>;5buX?Li$jny@lD7eZ|4a?F@As{}hpr|IsE?7MZ9fw; ei`4-p1~40BH-kdK0|q9>1_p+|yBQc7_X7Z|oiP9a literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/vector-compare-ft.s b/fixtures/rdna2/vector-compare-ft.s new file mode 100644 index 0000000..7001d86 --- /dev/null +++ b/fixtures/rdna2/vector-compare-ft.s @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original Wave32 VOPC vectors for the F and T compares: both signednesses +// with VGPR, SGPR, inline, literal and vcc_lo sources; F clearing a stale +// VCC; T and F under partial EXEC; and runtime s_cbranch_vccz on a T result +// (never taken) and an F result (always taken). Each wave folds its masks +// into v2 as v2 = (v2 << 1) ^ mask. Expected results come from exact +// definitions in tests/validation/known_answers.rs, not from this file. +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen +s_waitcnt vmcnt(0) +s_mov_b32 s8, 0x12345678 +v_mov_b32_e32 v2, 0 // accumulator +v_mov_b32_e32 v5, 1 // shift count +s_mov_b32 vcc_lo, -1 // stale nonzero mask +v_cmp_f_i32_e32 vcc_lo, v1, v1 // VCC_LO = 0 +v_mov_b32_e32 v4, vcc_lo +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_i32_e32 vcc_lo, s8, v1 // every lane of the wave +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +s_mov_b32 exec_lo, 0x0f0f0f0f +v_cmp_t_u32_e32 vcc_lo, -7, v1 // only the EXEC lanes +s_mov_b32 exec_lo, -1 +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_i32_e32 vcc_lo, v1, v1 // nonzero again before the F +s_mov_b32 exec_lo, 0x3c3c3c3c +v_cmp_f_u32_e32 vcc_lo, 0xdeadbeef, v1 // 0 even in active lanes +s_mov_b32 exec_lo, -1 +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_u32_e32 vcc_lo, vcc_lo, v1 // reads the zero mask; T anyway +s_cbranch_vccz .Lskip // runtime branch, never taken +v_xor_b32_e32 v2, v2, v1 +.Lskip: +v_cmp_f_i32_e32 vcc_lo, 64, v1 +s_cbranch_vccz .Ldone // runtime branch, always taken +v_mov_b32_e32 v2, 0 +.Ldone: +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 eb0a0f8..6109c31 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; 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 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 71b39f5..90eb6fd 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -831,6 +831,22 @@ class Validate(unittest.TestCase): form(reg, "V_CMP_LT_I32")["signedness"] = "unsigned" self.rejects(reg, "V_CMP_LT_I32: signedness unsigned contradicts XML format FMT_NUM_I32") + def test_rejects_f_and_t_outside_vopc(self): + for relation in ("f", "t"): + with self.subTest(relation=relation): + reg = compares() + form(reg, "S_CMP_LT_I32")["relation"] = relation + self.rejects(reg, f"S_CMP_LT_I32: relation {relation} exists only for VOPC compares") + + def test_renders_f_and_t_primitives(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["relation"] = "t" + form(reg, "V_CMP_NE_U32")["relation"] = "f" + self.assertEqual(self.errors(reg), []) + text = gen.render(reg, snapshot()) + self.assertIn("Self::CmpLtI32 => primitive::true_b32(src0, src1),", text) + self.assertIn("Self::CmpNeU32 => CompareRelation::False,", text) + def test_renders_vector_compare_dispatch(self): text = gen.render(vector_compares(), snapshot()) self.assertIn("pub enum VectorCompareOp {", text) diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index 6aa3cd3..b4f1f62 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -1308,6 +1308,21 @@ mod review { // ---- VOPC integer compares (docs/shaders/vector-compare.md) ---- const COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare.bin"); + const COMPARE_FT_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare-ft.bin"); + + /// fixtures/rdna2/vector-compare-ft.s, from its listing and guide 12.9 + /// Table 61 (F: D = 0, T: D = 1) with VCC_LO[n] = EXEC_LO[n] & test: every + /// F mask is 0 and every T mask is EXEC_LO & the lanes that exist, so the + /// T branch is never taken and the F branch always is. + fn compare_ft_expected(input: &[u32]) -> Vec { + let mut output = Vec::new(); + for wave in input.chunks(32) { + let exists = wave_mask(wave, u32::MAX, |_| true); + let folded = ((exists << 1) ^ (exists & 0x0f0f_0f0f)) << 1; + output.extend(wave.iter().map(|&x| folded ^ x)); + } + output + } const COMPARE_VALUES: [u32; 10] = [ 0, 1, @@ -1412,6 +1427,30 @@ mod review { input } + #[test] + fn compare_ft_fixture_matches_exact_definitions() { + // A full wave and a final partial wave of 7 lanes. + let mut input = compare_fixture_input()[..32].to_vec(); + input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]); + let expected = compare_ft_expected(&input); + verify(COMPARE_FT_FIXTURE, &input, Some(&expected)); + // The partial wave's T masks have only its 7 lanes. + assert_eq!(expected[32], ((0x7f << 1) ^ 0x0f) << 1); + let compiled = compile(Architecture::Gfx1030, COMPARE_FT_FIXTURE).unwrap(); + assert_eq!( + compiled.ir.matches("wave.mask").count(), + 7, + "{}", + compiled.ir + ); + assert_eq!( + compiled.ir.matches("join.vccz").count(), + 2, + "{}", + compiled.ir + ); + } + #[test] fn compare_fixture_matches_exact_definitions() { let input = compare_fixture_input(); @@ -1892,6 +1931,10 @@ mod review { assert_eq!(run(&join, &[1, 0, 5, 0]), [0b1010; 4]); assert_eq!(run(&join, &[0, 0, 0, 0]), [0; 4]); programs += 2; + let mut input = compare_fixture_input()[..32].to_vec(); + input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]); + assert_eq!(run(COMPARE_FT_FIXTURE, &input), compare_ft_expected(&input)); + programs += 1; eprintln!("{programs} VOPC programs matched on native Metal"); } } From 8909b99ece218dcf37628f2ce1e50ff924d45fc5 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:39:24 -0600 Subject: [PATCH 05/19] test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215) Review found four ways F/T could be wrong and still pass: clearing EXEC under partial EXEC, treating the empty-EXEC result as lane-derived, ignoring an outstanding load on a source, and decoding opcode 200. Add a case or rejection for each; each was shown failing with that break. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- tests/validation/tests/vopc_f_t.rs | 65 +++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/tests/validation/tests/vopc_f_t.rs b/tests/validation/tests/vopc_f_t.rs index 53b74b1..522ec48 100644 --- a/tests/validation/tests/vopc_f_t.rs +++ b/tests/validation/tests/vopc_f_t.rs @@ -135,8 +135,10 @@ const EXEC_MASKS: [u32; 7] = [ /// VCC_LO before the compare in the EXEC cases: bits inside and outside every /// mask above, so a partial VCC update would show. const STALE_VCC: u32 = 0xa5a5_c33c; +/// XORed with v1 to give every lane its own old v2 before a masked move. +const OLD: u32 = 0x0bad_f00d; -const COUNTS: [(&str, usize); 11] = [ +const COUNTS: [(&str, usize); 12] = [ ("vopc domain", 4 * 8 * 2), ("vopc aliasing", 4 * 2), ("vopc inline integer", 4 * 81), @@ -147,13 +149,14 @@ const COUNTS: [(&str, usize); 11] = [ ("vopc exec", 4 * (7 + 2)), ("vopc empty exec reads nothing", 4 * 3), ("vopc partial wave", 4 * 3), - ("vopc vccz branch", 4 * 3), + ("vopc vccz branch", 4 * 4), + ("vopc exec unchanged", 4 * 2), ]; -/// Per form: 4 uninitialized sources, a missing literal, 9 float inline +/// Per form: 4 uninitialized sources, 2 sources with a load outstanding, a missing literal, 9 float inline /// constants, 9 other special SRC0 selectors, a float constant under empty /// EXEC, SDWA, DPP16 and two DPP8 forms, the VOP3 `_e64` form, the matching /// `v_cmpx`, and a lane-derived F result branching over a scalar instruction. -const REJECTIONS: usize = 4 * (4 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); +const REJECTIONS: usize = 4 * (4 + 2 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); const LITERAL: u32 = 255; const VCC_LO: u32 = 106; @@ -429,6 +432,41 @@ fn cases() -> Vec { if mask == 0 { 0 } else { mask ^ x } })); } + // Under EXEC_LO = 0 the result is a known 0 (contract section 5), so + // the branch is resolved statically and may skip a scalar + // instruction (`s_mov_b32 s8, 0`); it is taken, v2 = 0. + let tail = [VCCZ_OVER_ONE, 0xbe88_0380]; + let (code, _) = program(&vmov(3, 5), Some(0), &[vopc(op, vgpr(1), 3)], &tail); + let label = "exec 0, then s_cbranch_vccz over s_mov".into(); + cases.push(case(entry, family, label, code, lanes(), |_, _, _| 0)); + // EXEC_LO is unchanged by the compare (contract section 3): v2 = + // vcc_lo runs under the compare's partial EXEC, so active lanes take + // VCC_LO and inactive lanes keep their own old v2 = v1 ^ OLD. + let family = "vopc exec unchanged"; + for exec in [0x5555_5555, 0x8000_0001] { + let mut code = PREFIX.to_vec(); + code.extend(vmov(3, 5)); + code.extend(vmov(5, OLD)); + code.push(29 << 25 | 2 << 17 | 1 << 9 | vgpr(5)); // v_xor_b32 v2, v5, v1 + code.extend(smov(EXEC_LO, exec)); + code.extend([vopc(op, vgpr(1), 3), READ_VCC, FULL_EXEC]); + code.extend(STORE_V2); + let label = format!("exec {exec:#x}, v2 = vcc_lo before EXEC is restored"); + cases.push(case( + entry, + family, + label, + words(&code), + lanes(), + |n, x, p| { + if exec >> (n % 32) & 1 == 1 { + vcc(form, exec, p, |k| (v1(k), 5)) + } else { + x ^ OLD + } + }, + )); + } } cases } @@ -454,6 +492,19 @@ fn rejections() -> Vec<(String, Vec, usize)> { program(&setup, None, &[vopc(op, src0, vsrc1)], &[]), ); } + // A source whose VGPR has a load outstanding (no wait after + // `buffer_load_dword v3`): refused at the compare. + for (src0, vsrc1, label) in [(vgpr(1), 3, "VSRC1"), (vgpr(3), 1, "SRC0")] { + let mut code = PREFIX.to_vec(); + code.extend(setup); + code.extend([0xe030_2000, 0x8000_0300]); + let offset = 4 * code.len(); + code.push(vopc(op, src0, vsrc1)); + code.extend([READ_VCC, 0xbf8c_3f70]); + code.extend(STORE_V2); + let label = format!("v3 load outstanding as {label}"); + reject(label, (words(&code), offset)); + } // A literal SRC0 with no literal dword: the program ends at the word. let mut code = PREFIX.to_vec(); code.extend(setup); @@ -620,7 +671,11 @@ fn other_constant_compares_stay_unsupported() { // V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183, // V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247. let setup = vmov(3, 7); - for op in [0, 15, 16, 31, 160, 167, 176, 183, 224, 231, 240, 247] { + // Also the neighbours of the two 32-bit integer groups: 127 and 191 (not + // in Table 61), 136 V_CMP_CLASS_F32 and 200 V_CMP_F_F16. + for op in [ + 0, 15, 16, 31, 127, 136, 160, 167, 176, 183, 191, 200, 224, 231, 240, 247, + ] { let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes()); } From ef90105a265c4cebbd0692b4db69e74add42f850 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:43:08 -0600 Subject: [PATCH 06/19] isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215) Review fixes. A VOPC compare's opcode must equal its group base (128 signed, 192 unsigned) plus its relation's Table 59 offset, so a row such as V_CMP_T_I32 with relation f is rejected instead of lowering to false. A lane_mask form now needs exactly one fieldless XML VCC operand that is written and not read. The generator tests render the real F/T rows, and the vector-compare doc names the file each count comes from. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 19 ++++++- docs/shaders/semantic-registry.md | 4 ++ docs/shaders/vector-compare.md | 9 ++-- .../test_generate_semantics.py | 49 ++++++++++++++++--- 4 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 337b897..0328eb5 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -64,6 +64,11 @@ RELATIONS = { } # F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7). VECTOR_ONLY_RELATIONS = {"f", "t"} +# Guide 12.9 Table 59 and Table 61: a 32-bit integer VOPC compare's opcode is +# its group base (128 for _I32, 192 for _U32) plus its relation's offset. This +# is the guide's opcode layout, not a reading of the mnemonic. +VOPC_INTEGER_BASES = {"signed": 128, "unsigned": 192} +VOPC_RELATION_OFFSETS = {"f": 0, "lt": 1, "eq": 2, "le": 3, "gt": 4, "lg": 5, "ge": 6, "t": 7} # (relation, signedness) -> primitive. Equality does not depend on signedness, # so both declared signednesses of EQ and LG share one primitive. COMPARE_PRIMITIVES = { @@ -384,6 +389,7 @@ def _check_xml(form, rule, snapshot, errors): operands = {} scc_in = scc_out = False implicit = set() + vcc_writes = [] for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]: if kind == "OPR_SSRC_SPECIAL_SCC": scc_in |= is_input @@ -392,10 +398,13 @@ def _check_xml(form, rule, snapshot, errors): operands[field] = (data_format, size, is_input, is_output) else: implicit.add(kind) + if kind == "OPR_VCC": + vcc_writes.append((is_input, is_output)) # The vocabulary states SCC effects and a lane-mask VCC write; any other # implicit XML operand (such as an EXEC write) is undeclared. if form["vcc"] == "lane_mask": - if "OPR_VCC" not in implicit: + # Exactly one fieldless VCC operand, written and not read. + if vcc_writes != [(False, True)]: errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output") implicit.discard("OPR_VCC") if implicit: @@ -570,6 +579,14 @@ 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) == "vector_compare": + base = VOPC_INTEGER_BASES.get(form["signedness"]) + expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation] + if form["opcode"] != expected: + errors.append( + f"{label}: relation {relation}/{form['signedness']} has VOPC opcode " + f"{expected} (guide Table 59), not {form['opcode']}" + ) # SOPC compares write SCC; VOPC compares write VCC and leave SCC. scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" if form["scc"] != scc: diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index f31f5a5..dd706b1 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -127,6 +127,10 @@ vocabularies above, it rejects: - contradictions: a declared `scc` or `carry_in` that the primitive does not have, `bitwise` on an arithmetic operation or the reverse; +- VOPC compares whose opcode is not the group base (128 for `signed`, 192 + for `unsigned`) plus the relation's offset in guide Table 59 (F 0, LT 1, + EQ 2, LE 3, GT 4, LG/NE 5, GE 6, T 7), and a `lane_mask` form whose XML + does not have exactly one implicit VCC operand that is written and not read; - duplicates: the same `name`, the same `(family, opcode)`, or the same `variant` twice in one generated enum; - XML disagreements: a family with no XML encoding, a form with no default XML diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index a9b1dec..56dd577 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -213,7 +213,7 @@ forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading result (always taken). The independent oracle for F and T is `tests/validation/tests/vopc_f_t.rs`. -The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe, +`tests/validation/known_answers.rs` runs each relational form against 10 boundary values (0, 1, 0x7ffffffe, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff, 0x0f0f0f0f), in both operand orders. That is 240 programs, checked against exact i128 differences. It also covers partial and empty EXEC with seeded @@ -221,9 +221,10 @@ destinations, both runtime branch edges in one dispatch, and 32 rejections pinned to their byte offset. The translator, the reference (lockstep waves, compares on widened i64 values) and the second interpreter (sign-bit flip, then an unsigned compare) must all agree. The 9 ordered compare slots in the -fixture each change the result when their signedness is flipped. The same -programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation -(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). +relational fixture each change the result when their signedness is flipped. The same +programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) match on native Metal with API and shader validation +(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). The F/T oracle's own native Metal cases +run in `vopc_f_t_match_the_guide_on_native_metal`. A deliberately broken copy of each implementation fails these tests: the reference with unsigned-only compares or with the EXEC test removed; the diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 90eb6fd..e7c1b5c 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -151,9 +151,12 @@ def snapshot(): ["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["OP", [[17, 8]]], ["ENCODING", [[25, 7]]], ], "identifier_mask": 0xFFFE0000, - "identifiers": [0x7C000000 | (op << 17) for op in (129, 197)], + "identifiers": [0x7C000000 | (op << 17) for op in (129, 135, 192, 197)], } - for name, opcode, data_format in (("V_CMP_LT_I32", 129, I32), ("V_CMP_NE_U32", 197, U32)): + for name, opcode, data_format in ( + ("V_CMP_LT_I32", 129, I32), ("V_CMP_T_I32", 135, I32), ("V_CMP_F_U32", 192, U32), + ("V_CMP_NE_U32", 197, U32), + ): variants[(name, "ENC_VOPC")] = { "instruction": name, "encoding": "ENC_VOPC", "opcode": opcode, # Values copied from the AMD XML snapshot: an implicit 64-bit VCC output. @@ -255,6 +258,8 @@ def vector_compares(): reg["form"] += [ # The same variant name as a SOPC form: variants are per enum. compare("V_CMP_LT_I32", 129, "CmpLtI32", "lt", "signed"), + compare("V_CMP_T_I32", 135, "CmpTI32", "t", "signed"), + compare("V_CMP_F_U32", 192, "CmpFU32", "f", "unsigned"), compare("V_CMP_NE_U32", 197, "CmpNeU32", "lg", "unsigned"), ] return reg @@ -840,12 +845,44 @@ class Validate(unittest.TestCase): def test_renders_f_and_t_primitives(self): reg = vector_compares() - form(reg, "V_CMP_LT_I32")["relation"] = "t" - form(reg, "V_CMP_NE_U32")["relation"] = "f" self.assertEqual(self.errors(reg), []) text = gen.render(reg, snapshot()) - self.assertIn("Self::CmpLtI32 => primitive::true_b32(src0, src1),", text) - self.assertIn("Self::CmpNeU32 => CompareRelation::False,", text) + self.assertIn("Self::CmpTI32 => primitive::true_b32(src0, src1),", text) + self.assertIn("Self::CmpFU32 => CompareRelation::False,", text) + + def test_rejects_a_vopc_relation_that_contradicts_the_opcode(self): + for name, relation, expected in ( + ("V_CMP_T_I32", "f", 128), ("V_CMP_LT_I32", "gt", 132), ("V_CMP_F_U32", "t", 199), + ): + with self.subTest(name=name): + reg = vector_compares() + form(reg, name)["relation"] = relation + signedness = form(reg, name)["signedness"] + self.rejects( + reg, + f"{name}: relation {relation}/{signedness} has VOPC opcode {expected} " + f"(guide Table 59), not {form(reg, name)['opcode']}", + ) + + def test_rejects_an_implicit_vcc_read_as_a_lane_mask_write(self): + for direction in ([True, False], [True, True]): + with self.subTest(direction=direction): + snap = snapshot() + operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"] + operands[0][4:6] = direction + self.rejects( + vector_compares(), + "V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output", + snap, + ) + + def test_rejects_a_second_implicit_vcc_operand(self): + snap = snapshot() + operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"] + operands.append(["", "FMT_NUM_M64", "OPR_VCC", 64, True, False, False, False]) + self.rejects( + vector_compares(), "V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output", snap + ) def test_renders_vector_compare_dispatch(self): text = gen.render(vector_compares(), snapshot()) From 2384bed8b47e9cf8c5ab7018f238838eec06c807 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:49:07 -0600 Subject: [PATCH 07/19] isa: split the semantic registry into one file per encoding family (#215) crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot hash, cited documents and field meanings, and lists the family files under `include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the operand rules and forms of the family it is named after. The generator merges them in include order, and rejects a form or rule of another family, a rule declared twice, root keys in a family file and a missing or repeated include. The merged registry equals the former single file, and semantics_gen.rs is byte-identical (generate_semantics.py --check passes unchanged). The coverage report and the RDNA2 planner read the merged registry; their output is unchanged. Parallel work on different families no longer edits the same file. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 58 +- crates/isa/semantics/rdna2.toml | 1740 +---------------- crates/isa/semantics/rdna2/sop1.toml | 238 +++ crates/isa/semantics/rdna2/sop2.toml | 647 ++++++ crates/isa/semantics/rdna2/sopc.toml | 269 +++ crates/isa/semantics/rdna2/vop2.toml | 225 +++ crates/isa/semantics/rdna2/vopc.toml | 360 ++++ docs/shaders/semantic-registry.md | 19 +- docs/shaders/vector-compare.md | 2 +- scripts/audit/semantic_coverage.py | 19 +- scripts/qa/rdna2_plan.py | 4 +- .../test_generate_semantics.py | 75 + 12 files changed, 1918 insertions(+), 1738 deletions(-) create mode 100644 crates/isa/semantics/rdna2/sop1.toml create mode 100644 crates/isa/semantics/rdna2/sop2.toml create mode 100644 crates/isa/semantics/rdna2/sopc.toml create mode 100644 crates/isa/semantics/rdna2/vop2.toml create mode 100644 crates/isa/semantics/rdna2/vopc.toml diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 0328eb5..7997782 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Validate the declarative gfx1030 semantic registry and generate its Rust tables. - validate check crates/isa/semantics/rdna2.toml against its closed vocabulary + validate check crates/isa/semantics/rdna2.toml (and the family files it + includes) against its closed vocabulary and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl) generate validate, then write crates/isa/src/semantics_gen.rs --check validate and regenerate in memory; exit 1 if the committed file @@ -315,10 +316,55 @@ NAME = re.compile(r"^[A-Z][A-Z0-9_]*$") SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$") +class RegistryError(ValueError): + """A registry file set that cannot be merged into one registry.""" + + +# Keys a family file may hold; everything else lives in the root file. +FAMILY_FILE_KEYS = {"operand_rules", "form"} + + def load_registry(path=REGISTRY): - """Parse the TOML registry into a dict.""" + """Parse the root registry file and merge its family files into one dict. + + The root lists its family files under `include`, in order. Each family file + holds only operand rules and forms of the one encoding family it is named + after (`rdna2/vop2.toml` holds VOP2), so parallel work on different + families never edits the same file. Forms keep the include order, so the + merged registry is the same as one file with the parts concatenated. + """ + path = Path(path) with open(path, "rb") as handle: - return tomllib.load(handle) + registry = tomllib.load(handle) + includes = registry.pop("include", []) + if not isinstance(includes, list) or not all(isinstance(item, str) for item in includes): + raise RegistryError(f"{path.name}: include must be a list of file names") + if len(set(includes)) != len(includes): + raise RegistryError(f"{path.name}: a family file is included twice") + rules = registry.setdefault("operand_rules", {}) + forms = registry.setdefault("form", []) + for include in includes: + part_path = path.parent / include + family = Path(include).stem.upper() + if not part_path.is_file(): + raise RegistryError(f"{path.name}: included family file {include} does not exist") + with open(part_path, "rb") as handle: + part = tomllib.load(handle) + unknown = sorted(set(part) - FAMILY_FILE_KEYS) + if unknown: + raise RegistryError(f"{include}: keys {unknown} belong in the root file") + for name, rule in part.get("operand_rules", {}).items(): + if name in rules: + raise RegistryError(f"{include}: operand rule {name} is declared twice") + if not isinstance(rule, dict) or rule.get("family") != family: + raise RegistryError(f"{include}: operand rule {name} is not a {family} rule") + rules[name] = rule + for index, form in enumerate(part.get("form", [])): + if not isinstance(form, dict) or form.get("family") != family: + label = form.get("name", f"form #{index}") if isinstance(form, dict) else index + raise RegistryError(f"{include}: form {label} is not a {family} form") + forms.append(form) + return registry def load_snapshot(path=SNAPSHOT): @@ -1018,7 +1064,11 @@ def main(): arguments = parser.parse_args() if bool(arguments.mode) == arguments.check: parser.error("choose exactly one of generate, validate or --check") - registry = load_registry(arguments.registry) + try: + registry = load_registry(arguments.registry) + except RegistryError as error: + print(f"error: {error}", file=sys.stderr) + return 1 snapshot = load_snapshot(arguments.snapshot) errors = validate(registry, snapshot) if errors: diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 29f678a..bfe7a4f 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -8,12 +8,21 @@ # per form, never from the mnemonic. See docs/shaders/semantic-registry.md. # # Independence: the reference interpreter (crates/ref) and the second -# interpreter (tests/validation/independent_ref.rs) never read this file. +# interpreter (tests/validation/independent_ref.rs) never read these files. schema = 1 architecture = "gfx1030" # Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl. source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7" +# Family files, in this order (forms keep the order they are listed in; each +# file holds the operand rules and forms of one encoding family, named after it). +include = [ + "rdna2/sop2.toml", + "rdna2/sopc.toml", + "rdna2/sop1.toml", + "rdna2/vop2.toml", + "rdna2/vopc.toml", +] # Named public documents that spec references point at. [documents.guide] @@ -25,26 +34,7 @@ pages = 291 title = "AMD RDNA 2 machine-readable ISA (pinned XML)" file = "amdgpu_isa_rdna2.xml" -# Operand rules shared by a family. A rule names its destination and source -# classes; the decoder implements each rule once (rules are not per opcode). -[operand_rules.sop2_sgpr] -family = "SOP2" -dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } -src = [ - { field = "SSRC0", class = "scalar_source" }, - { field = "SSRC1", class = "scalar_source" }, -] -# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word. -max_literals = 1 -# Encodings this rule rejects, so they stay unsupported rather than guessed. -unsupported = [ - "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", - "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", - "src_special", "two_literals", -] - -# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ---- -# Field meanings: +# Form field meanings (every family file): # name XML instruction name (stable identity) # family encoding family; must match the XML base encoding # opcode XML opcode; must match @@ -59,1711 +49,3 @@ unsupported = [ # operands a key of [operand_rules] # spec references; at least one guide section with a page # verify evidence required before the form counts as verified - -[[form]] -name = "S_ADD_U32" -family = "SOP2" -opcode = 0 -variant = "AddU32" -operation = "add" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 101 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SUB_U32" -family = "SOP2" -opcode = 1 -variant = "SubU32" -operation = "sub" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "borrow" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 101 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ADD_I32" -family = "SOP2" -opcode = 2 -variant = "AddI32" -operation = "add" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "signed_overflow" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 101 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SUB_I32" -family = "SOP2" -opcode = 3 -variant = "SubI32" -operation = "sub" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "signed_overflow" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 101 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ADDC_U32" -family = "SOP2" -opcode = 4 -variant = "AddcU32" -operation = "add" -signedness = "unsigned" -carry_in = "scc" -width = 32 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SUBB_U32" -family = "SOP2" -opcode = 5 -variant = "SubbU32" -operation = "sub" -signedness = "unsigned" -carry_in = "scc" -width = 32 -scc = "borrow" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_AND_B32" -family = "SOP2" -opcode = 14 -variant = "AndB32" -operation = "and" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 102 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_OR_B32" -family = "SOP2" -opcode = 16 -variant = "OrB32" -operation = "or" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 102 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_XOR_B32" -family = "SOP2" -opcode = 18 -variant = "XorB32" -operation = "xor" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 102 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- Stage C: further SOP2 logical and shift forms (#215) ---- -# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode). - -[[form]] -name = "S_ANDN2_B32" -family = "SOP2" -opcode = 20 -variant = "Andn2B32" -operation = "andn2" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 103 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ORN2_B32" -family = "SOP2" -opcode = 22 -variant = "Orn2B32" -operation = "orn2" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 103 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_NAND_B32" -family = "SOP2" -opcode = 24 -variant = "NandB32" -operation = "nand" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_NOR_B32" -family = "SOP2" -opcode = 26 -variant = "NorB32" -operation = "nor" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_XNOR_B32" -family = "SOP2" -opcode = 28 -variant = "XnorB32" -operation = "xnor" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL_B32" -family = "SOP2" -opcode = 30 -variant = "LshlB32" -operation = "lshl" -signedness = "bitwise" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHR_B32" -family = "SOP2" -opcode = 32 -variant = "LshrB32" -operation = "lshr" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ASHR_I32" -family = "SOP2" -opcode = 34 -variant = "AshrI32" -operation = "ashr" -signedness = "signed" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ---- -# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect -# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14). -# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1. - -[[form]] -name = "S_MIN_I32" -family = "SOP2" -opcode = 6 -variant = "MinI32" -operation = "min" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MIN_U32" -family = "SOP2" -opcode = 7 -variant = "MinU32" -operation = "min" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MAX_I32" -family = "SOP2" -opcode = 8 -variant = "MaxI32" -operation = "max" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MAX_U32" -family = "SOP2" -opcode = 9 -variant = "MaxU32" -operation = "max" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 103 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CSELECT_B32" -family = "SOP2" -opcode = 10 -variant = "CselectB32" -operation = "cselect" -signedness = "bitwise" -carry_in = "scc" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 103 }, - { document = "guide", section = "5.5", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFM_B32" -family = "SOP2" -opcode = 36 -variant = "BfmB32" -operation = "bfm" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 104 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_I32" -family = "SOP2" -opcode = 38 -variant = "MulI32" -operation = "mul" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFE_U32" -family = "SOP2" -opcode = 39 -variant = "BfeU32" -operation = "bfe" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFE_I32" -family = "SOP2" -opcode = 40 -variant = "BfeI32" -operation = "bfe" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ABSDIFF_I32" -family = "SOP2" -opcode = 44 -variant = "AbsdiffI32" -operation = "absdiff" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL1_ADD_U32" -family = "SOP2" -opcode = 46 -variant = "Lshl1AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 1 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 105 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL2_ADD_U32" -family = "SOP2" -opcode = 47 -variant = "Lshl2AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 2 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 105 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL3_ADD_U32" -family = "SOP2" -opcode = 48 -variant = "Lshl3AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 3 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL4_ADD_U32" -family = "SOP2" -opcode = 49 -variant = "Lshl4AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 4 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_HI_U32" -family = "SOP2" -opcode = 53 -variant = "MulHiU32" -operation = "mul_hi" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_HI_I32" -family = "SOP2" -opcode = 54 -variant = "MulHiI32" -operation = "mul_hi" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- Stage D: SOPC 32-bit integer compares (#215) ---- -# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4). - -[operand_rules.sopc_scalar] -family = "SOPC" -src = [ - { field = "SSRC0", class = "scalar_source" }, - { field = "SSRC1", class = "scalar_source" }, -] -max_literals = 1 -unsupported = [ - "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", - "src_special", "two_literals", -] - -[[form]] -name = "S_CMP_EQ_I32" -family = "SOPC" -opcode = 0 -variant = "CmpEqI32" -operation = "compare" -relation = "eq" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LG_I32" -family = "SOPC" -opcode = 1 -variant = "CmpLgI32" -operation = "compare" -relation = "lg" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GT_I32" -family = "SOPC" -opcode = 2 -variant = "CmpGtI32" -operation = "compare" -relation = "gt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GE_I32" -family = "SOPC" -opcode = 3 -variant = "CmpGeI32" -operation = "compare" -relation = "ge" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LT_I32" -family = "SOPC" -opcode = 4 -variant = "CmpLtI32" -operation = "compare" -relation = "lt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LE_I32" -family = "SOPC" -opcode = 5 -variant = "CmpLeI32" -operation = "compare" -relation = "le" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_EQ_U32" -family = "SOPC" -opcode = 6 -variant = "CmpEqU32" -operation = "compare" -relation = "eq" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LG_U32" -family = "SOPC" -opcode = 7 -variant = "CmpLgU32" -operation = "compare" -relation = "lg" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GT_U32" -family = "SOPC" -opcode = 8 -variant = "CmpGtU32" -operation = "compare" -relation = "gt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GE_U32" -family = "SOPC" -opcode = 9 -variant = "CmpGeU32" -operation = "compare" -relation = "ge" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LT_U32" -family = "SOPC" -opcode = 10 -variant = "CmpLtU32" -operation = "compare" -relation = "lt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LE_U32" -family = "SOPC" -opcode = 11 -variant = "CmpLeU32" -operation = "compare" -relation = "le" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- SOP1 32-bit unary integer forms (#215) ---- -# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged. -# Searches that find nothing return -1 (guide 12.3). - -[operand_rules.sop1_sgpr] -family = "SOP1" -dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } -src = [{ field = "SSRC0", class = "scalar_source" }] -max_literals = 1 -unsupported = [ - "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", - "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special", -] - -[[form]] -name = "S_NOT_B32" -family = "SOP1" -opcode = 7 -variant = "NotB32" -operation = "not" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BREV_B32" -family = "SOP1" -opcode = 11 -variant = "BrevB32" -operation = "brev" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BCNT0_I32_B32" -family = "SOP1" -opcode = 13 -variant = "Bcnt0I32B32" -operation = "bcnt0" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BCNT1_I32_B32" -family = "SOP1" -opcode = 15 -variant = "Bcnt1I32B32" -operation = "bcnt1" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FF0_I32_B32" -family = "SOP1" -opcode = 17 -variant = "Ff0I32B32" -operation = "ff0" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FF1_I32_B32" -family = "SOP1" -opcode = 19 -variant = "Ff1I32B32" -operation = "ff1" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FLBIT_I32_B32" -family = "SOP1" -opcode = 21 -variant = "FlbitI32B32" -operation = "flbit" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FLBIT_I32" -family = "SOP1" -opcode = 23 -variant = "FlbitI32" -operation = "flbit" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SEXT_I32_I8" -family = "SOP1" -opcode = 25 -variant = "SextI32I8" -operation = "sext" -signedness = "signed" -carry_in = "none" -width = 32 -source_bits = 8 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SEXT_I32_I16" -family = "SOP1" -opcode = 26 -variant = "SextI32I16" -operation = "sext" -signedness = "signed" -carry_in = "none" -width = 32 -source_bits = 16 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ABS_I32" -family = "SOP1" -opcode = 52 -variant = "AbsI32" -operation = "abs" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOP2 32-bit vector integer forms (#215) ---- -# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit -# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high -# forms keep bits 63:32 of the product. SUBREV declares its reversed sources. - -[operand_rules.vop2_vgpr] -family = "VOP2" -dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } -src = [ - { field = "SRC0", class = "vector_source" }, - { field = "VSRC1", class = "vgpr" }, -] -# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word. -max_literals = 1 -unsupported = [ - "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", -] - -[[form]] -name = "V_MUL_I32_I24" -family = "VOP2" -opcode = 9 -variant = "MulI32I24" -operation = "mul24" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 131 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_HI_I32_I24" -family = "VOP2" -opcode = 10 -variant = "MulHiI32I24" -operation = "mul_hi24" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_U32_U24" -family = "VOP2" -opcode = 11 -variant = "MulU32U24" -operation = "mul24" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_HI_U32_U24" -family = "VOP2" -opcode = 12 -variant = "MulHiU32U24" -operation = "mul_hi24" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MIN_I32" -family = "VOP2" -opcode = 17 -variant = "MinI32" -operation = "min" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MAX_I32" -family = "VOP2" -opcode = 18 -variant = "MaxI32" -operation = "max" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MIN_U32" -family = "VOP2" -opcode = 19 -variant = "MinU32" -operation = "min" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MAX_U32" -family = "VOP2" -opcode = 20 -variant = "MaxU32" -operation = "max" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_XNOR_B32" -family = "VOP2" -opcode = 30 -variant = "XnorB32" -operation = "xnor" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_ADD_NC_U32" -family = "VOP2" -opcode = 37 -variant = "AddNcU32" -operation = "add" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_SUB_NC_U32" -family = "VOP2" -opcode = 38 -variant = "SubNcU32" -operation = "sub" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_SUBREV_NC_U32" -family = "VOP2" -opcode = 39 -variant = "SubrevNcU32" -operation = "sub" -signedness = "unsigned" -carry_in = "none" -width = 32 -source_order = "reversed" -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- -# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; -# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's -# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), -# the VOP3 encoding and Wave64 stay unsupported. -[operand_rules.vopc_vcc] -family = "VOPC" -src = [ - { field = "SRC0", class = "vector_source" }, - { field = "VSRC1", class = "vgpr" }, -] -# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. -max_literals = 1 -unsupported = [ - "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", -] - -[[form]] -name = "V_CMP_LT_I32" -family = "VOPC" -opcode = 129 -variant = "CmpLtI32" -operation = "compare" -relation = "lt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_EQ_I32" -family = "VOPC" -opcode = 130 -variant = "CmpEqI32" -operation = "compare" -relation = "eq" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LE_I32" -family = "VOPC" -opcode = 131 -variant = "CmpLeI32" -operation = "compare" -relation = "le" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GT_I32" -family = "VOPC" -opcode = 132 -variant = "CmpGtI32" -operation = "compare" -relation = "gt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_NE_I32" -family = "VOPC" -opcode = 133 -variant = "CmpNeI32" -operation = "compare" -relation = "lg" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GE_I32" -family = "VOPC" -opcode = 134 -variant = "CmpGeI32" -operation = "compare" -relation = "ge" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LT_U32" -family = "VOPC" -opcode = 193 -variant = "CmpLtU32" -operation = "compare" -relation = "lt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_EQ_U32" -family = "VOPC" -opcode = 194 -variant = "CmpEqU32" -operation = "compare" -relation = "eq" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LE_U32" -family = "VOPC" -opcode = 195 -variant = "CmpLeU32" -operation = "compare" -relation = "le" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GT_U32" -family = "VOPC" -opcode = 196 -variant = "CmpGtU32" -operation = "compare" -relation = "gt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_NE_U32" -family = "VOPC" -opcode = 197 -variant = "CmpNeU32" -operation = "compare" -relation = "lg" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GE_U32" -family = "VOPC" -opcode = 198 -variant = "CmpGeU32" -operation = "compare" -relation = "ge" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- -# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes -# that exist. Sources are still decoded and checked as for the other compares -# (docs/shaders/vector-compare.md section 5). - -[[form]] -name = "V_CMP_F_I32" -family = "VOPC" -opcode = 128 -variant = "CmpFI32" -operation = "compare" -relation = "f" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_T_I32" -family = "VOPC" -opcode = 135 -variant = "CmpTI32" -operation = "compare" -relation = "t" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_F_U32" -family = "VOPC" -opcode = 192 -variant = "CmpFU32" -operation = "compare" -relation = "f" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_T_U32" -family = "VOPC" -opcode = 199 -variant = "CmpTU32" -operation = "compare" -relation = "t" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sop1.toml b/crates/isa/semantics/rdna2/sop1.toml new file mode 100644 index 0000000..ec7b75a --- /dev/null +++ b/crates/isa/semantics/rdna2/sop1.toml @@ -0,0 +1,238 @@ +# SOP1 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- SOP1 32-bit unary integer forms (#215) ---- +# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged. +# Searches that find nothing return -1 (guide 12.3). + +[operand_rules.sop1_sgpr] +family = "SOP1" +dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } +src = [{ field = "SSRC0", class = "scalar_source" }] +max_literals = 1 +unsupported = [ + "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special", +] + +[[form]] +name = "S_NOT_B32" +family = "SOP1" +opcode = 7 +variant = "NotB32" +operation = "not" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BREV_B32" +family = "SOP1" +opcode = 11 +variant = "BrevB32" +operation = "brev" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BCNT0_I32_B32" +family = "SOP1" +opcode = 13 +variant = "Bcnt0I32B32" +operation = "bcnt0" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BCNT1_I32_B32" +family = "SOP1" +opcode = 15 +variant = "Bcnt1I32B32" +operation = "bcnt1" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FF0_I32_B32" +family = "SOP1" +opcode = 17 +variant = "Ff0I32B32" +operation = "ff0" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FF1_I32_B32" +family = "SOP1" +opcode = 19 +variant = "Ff1I32B32" +operation = "ff1" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FLBIT_I32_B32" +family = "SOP1" +opcode = 21 +variant = "FlbitI32B32" +operation = "flbit" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FLBIT_I32" +family = "SOP1" +opcode = 23 +variant = "FlbitI32" +operation = "flbit" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SEXT_I32_I8" +family = "SOP1" +opcode = 25 +variant = "SextI32I8" +operation = "sext" +signedness = "signed" +carry_in = "none" +width = 32 +source_bits = 8 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SEXT_I32_I16" +family = "SOP1" +opcode = 26 +variant = "SextI32I16" +operation = "sext" +signedness = "signed" +carry_in = "none" +width = 32 +source_bits = 16 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ABS_I32" +family = "SOP1" +opcode = 52 +variant = "AbsI32" +operation = "abs" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sop2.toml b/crates/isa/semantics/rdna2/sop2.toml new file mode 100644 index 0000000..8452abf --- /dev/null +++ b/crates/isa/semantics/rdna2/sop2.toml @@ -0,0 +1,647 @@ +# SOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ---- + +# Operand rules shared by a family. A rule names its destination and source +# classes; the decoder implements each rule once (rules are not per opcode). +[operand_rules.sop2_sgpr] +family = "SOP2" +dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } +src = [ + { field = "SSRC0", class = "scalar_source" }, + { field = "SSRC1", class = "scalar_source" }, +] +# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word. +max_literals = 1 +# Encodings this rule rejects, so they stay unsupported rather than guessed. +unsupported = [ + "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", + "src_special", "two_literals", +] + + +[[form]] +name = "S_ADD_U32" +family = "SOP2" +opcode = 0 +variant = "AddU32" +operation = "add" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 101 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SUB_U32" +family = "SOP2" +opcode = 1 +variant = "SubU32" +operation = "sub" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "borrow" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 101 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ADD_I32" +family = "SOP2" +opcode = 2 +variant = "AddI32" +operation = "add" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "signed_overflow" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 101 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SUB_I32" +family = "SOP2" +opcode = 3 +variant = "SubI32" +operation = "sub" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "signed_overflow" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 101 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ADDC_U32" +family = "SOP2" +opcode = 4 +variant = "AddcU32" +operation = "add" +signedness = "unsigned" +carry_in = "scc" +width = 32 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SUBB_U32" +family = "SOP2" +opcode = 5 +variant = "SubbU32" +operation = "sub" +signedness = "unsigned" +carry_in = "scc" +width = 32 +scc = "borrow" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_AND_B32" +family = "SOP2" +opcode = 14 +variant = "AndB32" +operation = "and" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 102 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_OR_B32" +family = "SOP2" +opcode = 16 +variant = "OrB32" +operation = "or" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 102 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_XOR_B32" +family = "SOP2" +opcode = 18 +variant = "XorB32" +operation = "xor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 102 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- Stage C: further SOP2 logical and shift forms (#215) ---- +# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode). + +[[form]] +name = "S_ANDN2_B32" +family = "SOP2" +opcode = 20 +variant = "Andn2B32" +operation = "andn2" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 103 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ORN2_B32" +family = "SOP2" +opcode = 22 +variant = "Orn2B32" +operation = "orn2" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 103 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_NAND_B32" +family = "SOP2" +opcode = 24 +variant = "NandB32" +operation = "nand" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_NOR_B32" +family = "SOP2" +opcode = 26 +variant = "NorB32" +operation = "nor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_XNOR_B32" +family = "SOP2" +opcode = 28 +variant = "XnorB32" +operation = "xnor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL_B32" +family = "SOP2" +opcode = 30 +variant = "LshlB32" +operation = "lshl" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHR_B32" +family = "SOP2" +opcode = 32 +variant = "LshrB32" +operation = "lshr" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ASHR_I32" +family = "SOP2" +opcode = 34 +variant = "AshrI32" +operation = "ashr" +signedness = "signed" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ---- +# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect +# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14). +# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1. + +[[form]] +name = "S_MIN_I32" +family = "SOP2" +opcode = 6 +variant = "MinI32" +operation = "min" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MIN_U32" +family = "SOP2" +opcode = 7 +variant = "MinU32" +operation = "min" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MAX_I32" +family = "SOP2" +opcode = 8 +variant = "MaxI32" +operation = "max" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MAX_U32" +family = "SOP2" +opcode = 9 +variant = "MaxU32" +operation = "max" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 103 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CSELECT_B32" +family = "SOP2" +opcode = 10 +variant = "CselectB32" +operation = "cselect" +signedness = "bitwise" +carry_in = "scc" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 103 }, + { document = "guide", section = "5.5", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFM_B32" +family = "SOP2" +opcode = 36 +variant = "BfmB32" +operation = "bfm" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 104 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_I32" +family = "SOP2" +opcode = 38 +variant = "MulI32" +operation = "mul" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFE_U32" +family = "SOP2" +opcode = 39 +variant = "BfeU32" +operation = "bfe" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFE_I32" +family = "SOP2" +opcode = 40 +variant = "BfeI32" +operation = "bfe" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ABSDIFF_I32" +family = "SOP2" +opcode = 44 +variant = "AbsdiffI32" +operation = "absdiff" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL1_ADD_U32" +family = "SOP2" +opcode = 46 +variant = "Lshl1AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 1 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 105 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL2_ADD_U32" +family = "SOP2" +opcode = 47 +variant = "Lshl2AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 2 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 105 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL3_ADD_U32" +family = "SOP2" +opcode = 48 +variant = "Lshl3AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 3 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL4_ADD_U32" +family = "SOP2" +opcode = 49 +variant = "Lshl4AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 4 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_HI_U32" +family = "SOP2" +opcode = 53 +variant = "MulHiU32" +operation = "mul_hi" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_HI_I32" +family = "SOP2" +opcode = 54 +variant = "MulHiI32" +operation = "mul_hi" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sopc.toml b/crates/isa/semantics/rdna2/sopc.toml new file mode 100644 index 0000000..94d7e3b --- /dev/null +++ b/crates/isa/semantics/rdna2/sopc.toml @@ -0,0 +1,269 @@ +# SOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- Stage D: SOPC 32-bit integer compares (#215) ---- +# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4). + +[operand_rules.sopc_scalar] +family = "SOPC" +src = [ + { field = "SSRC0", class = "scalar_source" }, + { field = "SSRC1", class = "scalar_source" }, +] +max_literals = 1 +unsupported = [ + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", + "src_special", "two_literals", +] + +[[form]] +name = "S_CMP_EQ_I32" +family = "SOPC" +opcode = 0 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_I32" +family = "SOPC" +opcode = 1 +variant = "CmpLgI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_I32" +family = "SOPC" +opcode = 2 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_I32" +family = "SOPC" +opcode = 3 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_I32" +family = "SOPC" +opcode = 4 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_I32" +family = "SOPC" +opcode = 5 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_EQ_U32" +family = "SOPC" +opcode = 6 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_U32" +family = "SOPC" +opcode = 7 +variant = "CmpLgU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_U32" +family = "SOPC" +opcode = 8 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_U32" +family = "SOPC" +opcode = 9 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_U32" +family = "SOPC" +opcode = 10 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_U32" +family = "SOPC" +opcode = 11 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/vop2.toml b/crates/isa/semantics/rdna2/vop2.toml new file mode 100644 index 0000000..1ccce38 --- /dev/null +++ b/crates/isa/semantics/rdna2/vop2.toml @@ -0,0 +1,225 @@ +# VOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOP2 32-bit vector integer forms (#215) ---- +# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit +# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high +# forms keep bits 63:32 of the product. SUBREV declares its reversed sources. + +[operand_rules.vop2_vgpr] +family = "VOP2" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_MUL_I32_I24" +family = "VOP2" +opcode = 9 +variant = "MulI32I24" +operation = "mul24" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 131 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_HI_I32_I24" +family = "VOP2" +opcode = 10 +variant = "MulHiI32I24" +operation = "mul_hi24" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_U32_U24" +family = "VOP2" +opcode = 11 +variant = "MulU32U24" +operation = "mul24" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_HI_U32_U24" +family = "VOP2" +opcode = 12 +variant = "MulHiU32U24" +operation = "mul_hi24" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MIN_I32" +family = "VOP2" +opcode = 17 +variant = "MinI32" +operation = "min" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MAX_I32" +family = "VOP2" +opcode = 18 +variant = "MaxI32" +operation = "max" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MIN_U32" +family = "VOP2" +opcode = 19 +variant = "MinU32" +operation = "min" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MAX_U32" +family = "VOP2" +opcode = 20 +variant = "MaxU32" +operation = "max" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_XNOR_B32" +family = "VOP2" +opcode = 30 +variant = "XnorB32" +operation = "xnor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_ADD_NC_U32" +family = "VOP2" +opcode = 37 +variant = "AddNcU32" +operation = "add" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_SUB_NC_U32" +family = "VOP2" +opcode = 38 +variant = "SubNcU32" +operation = "sub" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_SUBREV_NC_U32" +family = "VOP2" +opcode = 39 +variant = "SubrevNcU32" +operation = "sub" +signedness = "unsigned" +carry_in = "none" +width = 32 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/vopc.toml b/crates/isa/semantics/rdna2/vopc.toml new file mode 100644 index 0000000..d3bfe8a --- /dev/null +++ b/crates/isa/semantics/rdna2/vopc.toml @@ -0,0 +1,360 @@ +# VOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- +# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; +# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's +# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), +# the VOP3 encoding and Wave64 stay unsupported. +[operand_rules.vopc_vcc] +family = "VOPC" +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_CMP_LT_I32" +family = "VOPC" +opcode = 129 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_I32" +family = "VOPC" +opcode = 130 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_I32" +family = "VOPC" +opcode = 131 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_I32" +family = "VOPC" +opcode = 132 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_I32" +family = "VOPC" +opcode = 133 +variant = "CmpNeI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_I32" +family = "VOPC" +opcode = 134 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LT_U32" +family = "VOPC" +opcode = 193 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_U32" +family = "VOPC" +opcode = 194 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_U32" +family = "VOPC" +opcode = 195 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_U32" +family = "VOPC" +opcode = 196 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_U32" +family = "VOPC" +opcode = 197 +variant = "CmpNeU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_U32" +family = "VOPC" +opcode = 198 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- +# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes +# that exist. Sources are still decoded and checked as for the other compares +# (docs/shaders/vector-compare.md section 5). + +[[form]] +name = "V_CMP_F_I32" +family = "VOPC" +opcode = 128 +variant = "CmpFI32" +operation = "compare" +relation = "f" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_I32" +family = "VOPC" +opcode = 135 +variant = "CmpTI32" +operation = "compare" +relation = "t" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_F_U32" +family = "VOPC" +opcode = 192 +variant = "CmpFU32" +operation = "compare" +relation = "f" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_U32" +family = "VOPC" +opcode = 199 +variant = "CmpTU32" +operation = "compare" +relation = "t" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index dd706b1..9cb63d4 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -12,7 +12,8 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m | File | Role | | --- | --- | -| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. | +| `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`): that family's operand rules and forms 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. | @@ -20,9 +21,23 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m | `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. | | `tests/semantics_generator/` | Unit tests for the generator. | +## Family files + +The root lists its family files under `include`. The generator merges them in +that order, and forms keep their order within each file, so the merged registry +equals one file with the parts concatenated (splitting the original single file +left `semantics_gen.rs` byte-identical). A family file may hold only +`[operand_rules.*]` and `[[form]]` entries of the family it is named after: +`rdna2/vop2.toml` holds VOP2 rules and forms and nothing else. The loader +rejects a form or rule of another family, a rule declared in two files, root +keys in a family file, and a missing or repeated include. Work on different +families therefore never edits the same registry file. To add a family, create +`rdna2/.toml` and append it to `include`; the generated order (and so +the generated file) changes only where the new file is placed. + ## Fields -The top of the file holds: +The root file holds: - `schema`: must be `1`. - `architecture`: must be `"gfx1030"`. diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index 56dd577..0244694 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -58,7 +58,7 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP: `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. The forms are declared in the semantic registry -(`crates/isa/semantics/rdna2.toml`, operand rule `vopc_vcc`); the decoder +(`crates/isa/semantics/rdna2/vopc.toml`, operand rule `vopc_vcc`); the decoder dispatches them from the generated `VectorCompareOp`. Operand order matters (S0 is SRC0): lt with swapped operands is gt. diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 6a6a614..f9712f3 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -142,6 +142,23 @@ def parse_generated(source): raise ValueError(f"{GENERATED}: unterminated FORM_IDS") +def load_registry(path): + """The root registry with its `include`d family files merged in order. + + Only the merge is done here; crates/isa/generate_semantics.py validates + which family each file may hold. + """ + registry = tomllib.loads(path.read_text(encoding="utf-8")) + for include in registry.pop("include", []): + part = tomllib.loads((path.parent / include).read_text(encoding="utf-8")) + for name, rule in part.get("operand_rules", {}).items(): + if name in registry.setdefault("operand_rules", {}): + raise ValueError(f"{REGISTRY}: operand rule {name} is declared twice") + registry["operand_rules"][name] = rule + registry.setdefault("form", []).extend(part.get("form", [])) + return registry + + def read_declarations(registry, identified): if type(registry.get("schema")) is not int or registry["schema"] != 1: raise ValueError(f"{REGISTRY}: expected schema 1") @@ -294,7 +311,7 @@ def main(): args = parser.parse_args() try: identified = load_snapshot(ROOT) - registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8")) + registry = load_registry(ROOT / REGISTRY) decoder = parse_decoder((ROOT / DECODER).read_text(encoding="utf-8")) | parse_generated( (ROOT / GENERATED).read_text(encoding="utf-8")) status = tomllib.loads((ROOT / STATUS).read_text(encoding="utf-8")) diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index 0e75ed1..f648882 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -67,6 +67,7 @@ class Inventory: # Planning does not claim or edit these paths. DEFAULT_PERMITTED_FILES = ( "crates/isa/semantics/rdna2.toml", + "crates/isa/semantics/rdna2/", "crates/isa/src/semantics_gen.rs", "crates/decoder/src/lib.rs", "crates/shader/", @@ -87,7 +88,8 @@ DEFAULT_ACCEPTANCE = ( def load_inventories(root: Path) -> dict[str, Any]: sc = _load_coverage_module(root) identified = sc["load_snapshot"](root) - registry = tomllib.loads((root / sc["REGISTRY"]).read_text(encoding="utf-8")) + # The root registry includes per-family files; merge them as the coverage report does. + registry = sc["load_registry"](root / sc["REGISTRY"]) decoder = sc["parse_decoder"]((root / sc["DECODER"]).read_text(encoding="utf-8")) generated = sc["parse_generated"]((root / sc["GENERATED"]).read_text(encoding="utf-8")) decoder_forms = set(decoder) | set(generated) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index e7c1b5c..58be8d2 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -10,6 +10,7 @@ snapshot are only read, never edited. Run from the repository root: import copy import importlib.util +import shutil import subprocess import sys import tempfile @@ -1037,6 +1038,79 @@ class Render(unittest.TestCase): self.assertEqual(text, gen.RUST.read_text(encoding="utf-8")) +class LoadRegistry(unittest.TestCase): + """The root file plus its per-family files merge into one registry.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + (self.dir / "rdna2").mkdir() + + def write(self, root_extra, files): + (self.dir / "rdna2.toml").write_text( + "schema = 1\n" + root_extra, encoding="utf-8" + ) + for name, text in files.items(): + (self.dir / "rdna2" / name).write_text(text, encoding="utf-8") + return self.dir / "rdna2.toml" + + RULE = '[operand_rules.{name}]\nfamily = "{family}"\n' + FORM = '[[form]]\nname = "{name}"\nfamily = "{family}"\n' + + def fails(self, root, fragment): + with self.assertRaises(gen.RegistryError) as raised: + gen.load_registry(root) + self.assertIn(fragment, str(raised.exception)) + + def test_the_real_split_registry_equals_one_concatenated_file(self): + registry = gen.load_registry() + self.assertNotIn("include", registry) + families = [form["family"] for form in registry["form"]] + # Each family is one contiguous run, in include order. + runs = [family for index, family in enumerate(families) if index == 0 or families[index - 1] != family] + self.assertEqual(len(runs), len(set(runs))) + for name, rule in registry["operand_rules"].items(): + self.assertIn(rule["family"], runs, name) + + def test_merges_family_files_in_include_order(self): + root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { + "vop2.toml": self.RULE.format(name="v", family="VOP2") + self.FORM.format(name="B", family="VOP2"), + "sop2.toml": self.FORM.format(name="A", family="SOP2") + self.FORM.format(name="C", family="SOP2"), + }) + registry = gen.load_registry(root) + self.assertEqual([form["name"] for form in registry["form"]], ["B", "A", "C"]) + self.assertEqual(list(registry["operand_rules"]), ["v"]) + + def test_rejects_a_form_of_another_family(self): + root = self.write('include = ["rdna2/sop2.toml"]\n', { + "sop2.toml": self.FORM.format(name="V_X", family="VOP2"), + }) + self.fails(root, "rdna2/sop2.toml: form V_X is not a SOP2 form") + + def test_rejects_a_rule_of_another_family(self): + root = self.write('include = ["rdna2/sop2.toml"]\n', { + "sop2.toml": self.RULE.format(name="r", family="SOPC"), + }) + self.fails(root, "rdna2/sop2.toml: operand rule r is not a SOP2 rule") + + def test_rejects_a_rule_declared_in_two_files(self): + root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop1.toml"]\n', { + "sop2.toml": self.RULE.format(name="r", family="SOP2"), + "sop1.toml": self.RULE.format(name="r", family="SOP1"), + }) + self.fails(root, "rdna2/sop1.toml: operand rule r is declared twice") + + def test_rejects_root_keys_in_a_family_file(self): + root = self.write('include = ["rdna2/sop2.toml"]\n', {"sop2.toml": "schema = 1\n"}) + self.fails(root, "rdna2/sop2.toml: keys ['schema'] belong in the root file") + + def test_rejects_a_missing_or_repeated_include(self): + self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist") + root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop2.toml"]\n', {"sop2.toml": ""}) + self.fails(root, "a family file is included twice") + + class CommandLine(unittest.TestCase): def run_cli(self, *arguments): return subprocess.run( @@ -1072,6 +1146,7 @@ class CommandLine(unittest.TestCase): def test_invalid_registry_fails_every_mode_without_writing(self): bad = self.dir / "rdna2.toml" + shutil.copytree(gen.REGISTRY.parent / "rdna2", self.dir / "rdna2") text = gen.REGISTRY.read_text(encoding="utf-8") bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8") output = self.dir / "out.rs" From 516976fb9f599177ce1ec55f66aae65fb23000ba Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:53:50 -0600 Subject: [PATCH 08/19] isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215) An [[encoding_variant]] re-encodes a declared form in another family: it names the form, the family, its opcode there and that encoding's operand rule, and inherits the rest. The XML check runs on the inherited declaration, and the generator rejects variants of undeclared forms, in the form's own family, duplicates, rules that cannot encode the form and forms that use a variant-only rule. It emits from__word and _assembly_name on the base enum and one FORMS row per variant. rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3 encoding of V_ADD_NC_U32. The decoder dispatches it through VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces AddNoCarryU32; the shader lowers it through the VOP2 form's template and still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region. Goldens, known answers and the LLVM oracle are unchanged. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 28 +-- crates/decoder/tests/gfx1030.rs | 15 +- crates/isa/generate_semantics.py | 159 +++++++++++++++++- crates/isa/semantics/rdna2.toml | 1 + crates/isa/semantics/rdna2/vop3.toml | 35 ++++ crates/isa/src/lib.rs | 18 +- crates/isa/src/semantics.rs | 4 + crates/isa/src/semantics_gen.rs | 52 +++++- crates/isa/tests/semantics.rs | 33 ++++ crates/shader/src/lib.rs | 35 +++- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 33 ++++ scripts/audit/semantic_coverage.py | 9 +- .../test_generate_semantics.py | 109 +++++++++++- 15 files changed, 496 insertions(+), 41 deletions(-) create mode 100644 crates/isa/semantics/rdna2/vop3.toml diff --git a/CHANGELOG.md b/CHANGELOG.md index 4efdfe2..bf4468f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ remains unsupported. - Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues. - Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215. - Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported. +- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215). - Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215. - Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`. - Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index d259189..f5e1014 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -9,8 +9,8 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, - V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO, + V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32, + V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO, }; use xenora_isa::meta::EncodingFamily; @@ -40,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -54,7 +54,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ ("S_WAITCNT", EncodingFamily::Sopp), ("S_WAITCNT_VSCNT", EncodingFamily::Sopk), ("V_ADD_F32", EncodingFamily::Vop2), - ("V_ADD_NC_U32", EncodingFamily::Vop3), ("V_AND_B32", EncodingFamily::Vop2), ("V_ASHRREV_I32", EncodingFamily::Vop2), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), @@ -327,10 +326,9 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if let Some(op) = VectorCompareOp::from_word(first) { return vector_compare(op, first, bytes); } - if V_ADD_NC_U32.matches(first) { - let len = V_ADD_NC_U32.byte_len(); - let second = word(bytes, len)?; - return Ok((add_u32(first, second)?, len)); + if let Some(op) = VectorAluOp::from_vop3_word(first) { + let second = word(bytes, 8)?; + return Ok((vop3_vgpr2(op, first, second)?, 8)); } if S_MOV_B32.matches(first) { let dst = ((first >> 16) & 0x7f) as u8; @@ -747,18 +745,22 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi Ok((Instruction::MoveB32 { dst, src }, len)) } -fn add_u32(first: u32, second: u32) -> Result { +/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1 +/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources +/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is +/// the gfx1030 assembler's inline-zero operand encoding. +fn vop3_vgpr2(op: VectorAluOp, first: u32, second: u32) -> Result { let src0 = second & 0x1ff; let src1 = (second >> 9) & 0x1ff; - // All output and input modifiers are clear. The unused third source uses - // the gfx1030 assembler's inline-zero operand encoding. if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 { return Err(unsupported( - "v_add_nc_u32_e64", + op.vop3_assembly_name() + .expect("VOP3 dispatch selects only declared variants"), "expected two VGPR sources and no modifiers", )); } - Ok(Instruction::AddNoCarryU32 { + Ok(Instruction::VectorAluVop3 { + op, dst: first as u8, src0: src0 as u8, src1: src1 as u8, diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index d9c3f97..de9ea49 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -43,7 +43,8 @@ fn decodes_each_fixture_instruction_with_offset_and_length() { ( 20, 8, - Instruction::AddNoCarryU32 { + Instruction::VectorAluVop3 { + op: VectorAluOp::AddNcU32, dst: 1, src0: 1, src1: 2, @@ -373,7 +374,14 @@ fn reference_op(instruction: Instruction) -> Op { reference_scalar(src0), reference_scalar(src1), ), - Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1), + // The reference's VOP3 add; it is the only VOP3 variant so far. + Instruction::VectorAluVop3 { + op: VectorAluOp::AddNcU32, + dst, + src0, + src1, + } => Op::Add(dst, src0, src1), + Instruction::VectorAluVop3 { op, .. } => panic!("no reference VOP3 mapping for {op:?}"), Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)), Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary( match op { @@ -998,7 +1006,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() { let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect(); assert_eq!( decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction, - Instruction::AddNoCarryU32 { + Instruction::VectorAluVop3 { + op: VectorAluOp::AddNcU32, dst: 1, src0: 0, src1: 0 diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 7997782..d9604db 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -37,7 +37,17 @@ FORM_KEYS = { "name", "family", "opcode", "variant", "operation", "signedness", "carry_in", "width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify", } -TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"} +TOP_KEYS = { + "schema", "architecture", "source_sha256", "documents", "operand_rules", "form", + "encoding_variant", +} +# An encoding variant is another encoding of a form already in the registry (for +# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base +# form, the encoding family, its opcode there and the operand rule of that +# encoding. It inherits the base form's operation, signedness and effects. +VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"} +# The assembler suffix LLVM prints for a variant's encoding family. +ASSEMBLY_SUFFIX = {"VOP3": "_e64"} OPERATIONS = { "add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor", @@ -222,7 +232,9 @@ UNSUPPORTED_COMBOS = { } # Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources, # which SOP2 groups under src_vcc and src_special). -ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} +# VOP3 rules also name source classes and encoding fields they refuse. +VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"} +ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS OPERAND_RULES = { "sop2_sgpr": { "rust": "Sop2Sgpr", @@ -287,6 +299,28 @@ OPERAND_RULES = { }, "kind": "vector_compare", }, + "vop3_vgpr2": { + "rust": "Vop3Vgpr2", + "enum": "VectorAluOp", + "shape": { + "family": "VOP3", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [ + {"field": "SRC0", "class": "vgpr"}, + {"field": "SRC1", "class": "vgpr"}, + ], + "max_literals": 0, + }, + # Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and + # SRC2 the assembler's unused inline zero; the decoder rejects the rest. + "unsupported": { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", + }, + "kind": "vector_vop3", + # Only encoding variants of forms whose rule has this kind may use it. + "variant_of": "vector", + }, "vop2_vgpr": { "rust": "Vop2Vgpr", "enum": "VectorAluOp", @@ -321,7 +355,7 @@ class RegistryError(ValueError): # Keys a family file may hold; everything else lives in the root file. -FAMILY_FILE_KEYS = {"operand_rules", "form"} +FAMILY_FILE_KEYS = {"operand_rules", "form", "encoding_variant"} def load_registry(path=REGISTRY): @@ -364,6 +398,11 @@ def load_registry(path=REGISTRY): label = form.get("name", f"form #{index}") if isinstance(form, dict) else index raise RegistryError(f"{include}: form {label} is not a {family} form") forms.append(form) + for index, variant in enumerate(part.get("encoding_variant", [])): + if not isinstance(variant, dict) or variant.get("family") != family: + label = variant.get("of", f"#{index}") if isinstance(variant, dict) else index + raise RegistryError(f"{include}: encoding variant {label} is not a {family} encoding") + registry.setdefault("encoding_variant", []).append(variant) return registry @@ -661,6 +700,8 @@ def validate(registry, snapshot): if form["carry_in"] == "scc" and not takes_carry: errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}") rule = rules.get(form["operands"]) + if _implemented_rule(form) and "variant_of" in _implemented_rule(form): + errors.append(f"{label}: operand rule {form['operands']} is only for encoding variants") if rule is None: errors.append(f"{label}: unknown operand rule {form['operands']!r}") elif rule.get("family") != form["family"]: @@ -682,9 +723,68 @@ def validate(registry, snapshot): if len(set(verify)) != len(verify): errors.append(f"{label}: duplicate verification requirement") _check_xml(form, rule, snapshot, errors) + _check_variants(registry, rules, documents, snapshot, seen, errors) return errors +def variant_row(registry, variant): + """The base form re-encoded: its declaration with the variant's identity.""" + base = next(form for form in registry["form"] if form.get("name") == variant["of"]) + return dict( + base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"], + spec=variant["spec"], verify=variant["verify"], + ) + + +def _check_variants(registry, rules, documents, snapshot, seen, errors): + forms = {form.get("name"): form for form in registry.get("form", [])} + identities = {(form.get("name"), form.get("family")) for form in registry.get("form", [])} + for index, variant in enumerate(registry.get("encoding_variant", [])): + label = f"{variant.get('of', f'variant #{index}')} ({variant.get('family')})" + missing = sorted(VARIANT_KEYS - set(variant)) + extra = sorted(set(variant) - VARIANT_KEYS) + if missing: + errors.append(f"{label}: incomplete encoding variant, missing {missing}") + if extra: + errors.append(f"{label}: unknown keys {extra}") + if missing: + continue + base = forms.get(variant["of"]) + if base is None: + errors.append(f"{label}: encoding variant of an undeclared form") + continue + if type(variant["opcode"]) is not int or not 0 <= variant["opcode"] <= U16_MAX: + errors.append(f"{label}: invalid opcode") + continue + if variant["family"] == base.get("family"): + errors.append(f"{label}: an encoding variant must use another family than its form") + identity = (variant["of"], variant["family"]) + if identity in identities: + errors.append(f"{label}: duplicate encoding of {variant['of']}") + identities.add(identity) + if (variant["family"], variant["opcode"]) in seen["opcode"]: + errors.append(f"{label}: duplicate opcode {(variant['family'], variant['opcode'])}") + seen["opcode"].add((variant["family"], variant["opcode"])) + implemented = OPERAND_RULES.get(variant["operands"]) if isinstance(variant["operands"], str) else None + rule = rules.get(variant["operands"]) + if rule is None or implemented is None: + errors.append(f"{label}: unknown operand rule {variant['operands']!r}") + continue + if rule.get("family") != variant["family"]: + errors.append(f"{label}: operand rule {variant['operands']} is for {rule.get('family')}") + if implemented.get("variant_of") != _rule_kind(base) or implemented["enum"] != _rule_enum(base): + errors.append( + f"{label}: operand rule {variant['operands']} cannot encode a {_rule_kind(base)} form" + ) + _check_spec(label, variant["spec"], documents, errors) + verify = variant["verify"] + if not verify or any(item not in EVIDENCE for item in verify) or len(set(verify)) != len(verify): + errors.append(f"{label}: invalid verification requirements {verify}") + # The XML check runs on the re-encoded declaration, so the variant's + # operands must agree with the base form's widths, signedness and effects. + _check_xml(variant_row(registry, variant), rule, snapshot, errors) + + def _implemented_rule(form): operands = form.get("operands") return OPERAND_RULES.get(operands) if isinstance(operands, str) else None @@ -743,9 +843,15 @@ def render(registry, snapshot): for rule_name in rule_names: selected = [form for form in forms if form["operands"] == rule_name] out += _render_enum(rule_name, selected, snapshot, positions) + variants = registry.get("encoding_variant", []) + for rule_name in sorted({variant["operands"] for variant in variants}): + selected = [variant for variant in variants if variant["operands"] == rule_name] + out += _render_variants(rule_name, selected, registry, snapshot) + # Encoding variants follow the forms, as rows of their own. + forms = forms + [variant_row(registry, variant) for variant in variants] out += [ "", - "/// Identity of every registry form, in registry order.", + "/// Identity of every registry form and encoding variant, in registry order.", f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [", ] for form in forms: @@ -791,6 +897,51 @@ def render(registry, snapshot): return "\n".join(out) +def _render_variants(rule_name, variants, registry, snapshot): + """Dispatch of one operand rule's encoding variants onto the base enum.""" + enum = OPERAND_RULES[rule_name]["enum"] + family = variants[0]["family"] + encoding = snapshot["encodings"][_family_encoding(family)] + (offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"] + op_mask = ((1 << size) - 1) << offset + fixed_mask = encoding["identifier_mask"] & ~op_mask + fixed_bits = encoding["identifiers"][0] & fixed_mask + if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]): + raise ValueError(f"{family}: identifiers do not split into fixed bits and OP") + lower = family.lower() + variant_of = {form["name"]: form["variant"] for form in registry["form"]} + rows = sorted(variants, key=lambda variant: variant["opcode"]) + out = [ + "", + f"impl {enum} {{", + f" /// Selects the operation from the first word of its {family} encoding (operand", + f" /// rule `{rule_name}`): the encoding bits (mask 0x{fixed_mask:09_x}) and then", + f" /// the OP field (bits {offset}-{offset + size - 1}). `None` for undeclared opcodes.", + f" pub const fn from_{lower}_word(word: u32) -> Option {{", + f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{", + " return None;", + " }", + f" match (word >> {offset}) & 0x{(1 << size) - 1:x} {{", + ] + out += [f" {row['opcode']} => Some(Self::{variant_of[row['of']]})," for row in rows] + out += [ + " _ => None,", + " }", + " }", + "", + f" /// Assembler name of the {family} encoding, as LLVM prints it, if declared.", + f" pub const fn {lower}_assembly_name(self) -> Option<&'static str> {{", + " match self {", + ] + out += [ + f" Self::{variant_of[row['of']]} => " + f"Some(\"{row['of'].lower()}{ASSEMBLY_SUFFIX[family]}\")," + for row in variants + ] + out += [" #[allow(unreachable_patterns)]", " _ => None,", " }", " }", "}"] + return out + + def _render_enum(rule_name, forms, snapshot, positions): enum = OPERAND_RULES[rule_name]["enum"] kind = OPERAND_RULES[rule_name]["kind"] diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index bfe7a4f..cf21825 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -22,6 +22,7 @@ include = [ "rdna2/sop1.toml", "rdna2/vop2.toml", "rdna2/vopc.toml", + "rdna2/vop3.toml", ] # Named public documents that spec references point at. diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml new file mode 100644 index 0000000..ecd1a6f --- /dev/null +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -0,0 +1,35 @@ +# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOP3 encoding variants of registry forms (#215) ---- +# An [[encoding_variant]] re-encodes a form declared in another family file: it +# names the form (`of`), this family, the XML opcode here and the operand rule +# of this encoding, and inherits everything else (operation, signedness, +# effects) from the form. The XML must agree with the inherited declaration. + +# Two VGPR sources, VGPR destination, no modifiers (ABS, OP_SEL, CLAMP, OMOD +# and NEG clear) and SRC2 the assembler's unused inline zero. This is the +# subset the decoder accepted for v_add_nc_u32_e64 before the registry. +[operand_rules.vop3_vgpr2] +family = "VOP3" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vgpr" }, + { field = "SRC1", class = "vgpr" }, +] +max_literals = 0 +unsupported = [ + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", +] + +[[encoding_variant]] +of = "V_ADD_NC_U32" +family = "VOP3" +opcode = 293 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 134 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index b5edab6..e55aa8f 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -154,8 +154,14 @@ pub enum Instruction { WaitStore, /// VOP1 unmodified 32-bit vector move. MoveB32 { dst: u8, src: VectorSource }, - /// VOP3 unsigned 32-bit addition with no carry or input/output modifiers. - AddNoCarryU32 { dst: u8, src0: u8, src1: u8 }, + /// VOP3 encoding of a registry VOP2 integer operation (operand rule + /// `vop3_vgpr2`): two VGPR sources and no input or output modifiers. + VectorAluVop3 { + op: VectorAluOp, + dst: u8, + src0: u8, + src1: u8, + }, /// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half. ScalarMoveB32 { dst: u8, src: ScalarSource }, /// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and, @@ -271,7 +277,9 @@ impl Instruction { Self::WaitLoad => "s_waitcnt", Self::WaitStore => "s_waitcnt_vscnt", Self::MoveB32 { .. } => "v_mov_b32_e32", - Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64", + Self::VectorAluVop3 { op, .. } => op + .vop3_assembly_name() + .expect("decoded VOP3 variants have a VOP3 name"), Self::ScalarMoveB32 { .. } => "s_mov_b32", Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), @@ -328,7 +336,9 @@ impl fmt::Display for Instruction { Self::WaitLoad => formatter.write_str(" vmcnt(0)"), Self::WaitStore => formatter.write_str(" null, 0"), Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"), - Self::AddNoCarryU32 { dst, src0, src1 } + Self::VectorAluVop3 { + dst, src0, src1, .. + } | Self::VectorLshlrevB32 { dst, src0, src1 } | Self::VectorLshrrevB32 { dst, src0, src1 } | Self::VectorAshrrevI32 { dst, src0, src1 } diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index ff67cb6..3ef28a0 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -196,6 +196,10 @@ pub enum OperandRule { /// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a /// VGPR. Everything else is rejected as unsupported. VopcVcc, + /// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are + /// VGPRs, no input or output modifiers, SRC2 unused. Everything else is + /// rejected as unsupported. + Vop3Vgpr2, /// VOP2 vector: VDST is v0-v255; 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 8e889fb..94e720b 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1872,8 +1872,32 @@ impl VectorCompareOp { } } -/// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ +impl VectorAluOp { + /// Selects the operation from the first word of its VOP3 encoding (operand + /// rule `vop3_vgpr2`): the encoding bits (mask 0xfc00_0000) and then + /// the OP field (bits 16-25). `None` for undeclared opcodes. + pub const fn from_vop3_word(word: u32) -> Option { + if word & 0xfc00_0000 != 0xd400_0000 { + return None; + } + match (word >> 16) & 0x3ff { + 293 => Some(Self::AddNcU32), + _ => None, + } + } + + /// Assembler name of the VOP3 encoding, as LLVM prints it, if declared. + pub const fn vop3_assembly_name(self) -> Option<&'static str> { + match self { + Self::AddNcU32 => Some("v_add_nc_u32_e64"), + #[allow(unreachable_patterns)] + _ => None, + } + } +} + +/// Identity of every registry form and encoding variant, in registry order. +pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1958,10 +1982,11 @@ pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ ("V_CMP_T_I32", EncodingFamily::Vopc), ("V_CMP_F_U32", EncodingFamily::Vopc), ("V_CMP_T_U32", EncodingFamily::Vopc), + ("V_ADD_NC_U32", EncodingFamily::Vop3), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 84] = [ +pub static FORMS: [FormSemantics; 85] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3726,4 +3751,25 @@ pub static FORMS: [FormSemantics; 84] = [ spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_ADD_NC_U32", + family: EncodingFamily::Vop3, + opcode: 293, + operation: Operation::Add, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 895b7ff..c1aa420 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -160,3 +160,36 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { VectorCompareOp::from_word(word).map(|op| op.semantics().name) }); } + +#[test] +fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() { + for row in FORMS + .iter() + .filter(|row| row.family == EncodingFamily::Vop3) + { + let op = VectorAluOp::ALL + .into_iter() + .find(|op| op.semantics().name == row.name) + .unwrap_or_else(|| panic!("{} has no base VOP2 form", row.name)); + let base = op.semantics(); + // The variant inherits the base declaration; only identity and the + // operand rule differ. + assert_eq!( + ( + base.operation, + base.signedness, + base.scc, + base.vcc, + base.exec + ), + (row.operation, row.signedness, row.scc, row.vcc, row.exec) + ); + assert_eq!( + op.vop3_assembly_name(), + Some(format!("{}_e64", op.mnemonic()).as_str()) + ); + } + dispatch_selects_exactly(EncodingFamily::Vop3, |word| { + VectorAluOp::from_vop3_word(word).map(|op| op.semantics().name) + }); +} diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 3eae65c..c7ee8a8 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ - DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp, - VectorSource, + DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorBinary, + VectorCompareOp, VectorSource, }; /// SGPR index of `vcc_lo`. @@ -215,7 +215,6 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { #[derive(Clone, Copy)] enum Binary { - Add, ShiftLeft, ShiftRight, ArithmeticShiftRight, @@ -224,14 +223,14 @@ enum Binary { Xor, FloatAdd, FloatMul, - /// A registry VOP2 integer operation, lowered by its typed template. + /// A registry VOP2 integer operation (or its VOP3 encoding), lowered by its + /// typed template. Vector(VectorBinary), } impl Binary { fn operator(self) -> (&'static str, &'static str) { match self { - Self::Add => ("add.u32", "+"), Self::ShiftLeft => ("lshl.b32", "<<"), Self::ShiftRight => ("lshr.b32", ">>"), Self::ArithmeticShiftRight => ("ashr.i32", ">>"), @@ -684,7 +683,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Result Result { - (Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?)) + Instruction::VectorAluVop3 { + op, + dst, + src0, + src1, + } => { + let (left, right) = if op.swaps_sources() { + (read(src1)?, read(src0)?) + } else { + (read(src0)?, read(src1)?) + }; + ( + Some(dst), + Op::Binary(Binary::Vector(op.lowering()), left, right), + ) } Instruction::VectorLshlrevB32 { dst, src0, src1 } => ( Some(dst), diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index 04f437a..d759c40 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -32,11 +32,11 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | | VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | | VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 | -| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | +| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 | +| **Total** | 1465 | 104 | 85 | 108 | 104 | 104 | 18 | 18 | 56 | ## Unsupported operand variants @@ -48,4 +48,5 @@ The table counts distinct variant names per family across registry operand rules | 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` | | VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | +| 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` | | VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 9cb63d4..2fb8821 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -35,6 +35,39 @@ families therefore never edits the same registry file. To add a family, create `rdna2/.toml` and append it to `include`; the generated order (and so the generated file) changes only where the new file is placed. +## Encoding variants + +An `[[encoding_variant]]` is another encoding of a form that is already declared, +such as the VOP3 (`_e64`) encoding of a VOP2 form. It is pure data in the family +file of its encoding (`rdna2/vop3.toml`) and has exactly these fields: + +| Field | Meaning | +| --- | --- | +| `of` | The `name` of the declared base form | +| `family` | The encoding family of this variant; must differ from the form's | +| `opcode` | The XML opcode in that family | +| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) | +| `spec`, `verify` | As for a form | + +Everything else (operation, signedness, effects, source order) is inherited +from the base form, and the XML check runs on that inherited declaration with +the variant's family, opcode and operand rule, so the VOP3 operand widths and +formats must agree with it. The generator emits, on the base enum, +`from__word` (encoding bits, then an explicit match on the OP field) and +`_assembly_name`, and one `FORMS` row per variant after the forms. A +variant-only rule (one marked `variant_of` in the generator) cannot be used by a +form. The validator rejects a variant of an undeclared form, one in the form's +own family, a duplicate encoding of a form or a duplicate `(family, opcode)`, a +rule that cannot encode the form, missing or unknown fields, and any XML +disagreement. + +`vop3_vgpr2` is the subset the decoder accepted for `v_add_nc_u32_e64` before +the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and +NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its +first variant; adding the VOP3 encoding of another VOP2 form under this rule is +one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline +sources, legal modifiers) come with the VOP3 batch. + ## Fields The root file holds: diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index f9712f3..c59d444 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -156,6 +156,7 @@ def load_registry(path): raise ValueError(f"{REGISTRY}: operand rule {name} is declared twice") registry["operand_rules"][name] = rule registry.setdefault("form", []).extend(part.get("form", [])) + registry.setdefault("encoding_variant", []).extend(part.get("encoding_variant", [])) return registry @@ -178,7 +179,13 @@ def read_declarations(registry, identified): rules[name] = (family, set(unsupported)) declared = set() - for form in registry["form"]: + # An encoding variant declares its base form in another encoding family. + variants = [ + {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], + "operands": variant["operands"]} + for variant in registry.get("encoding_variant", []) + ] + for form in registry["form"] + variants: key = (form["family"], form["name"]) if key not in identified: raise ValueError(f"{REGISTRY}: unknown form {key}") diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 58be8d2..9b3b505 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -167,11 +167,34 @@ def snapshot(): ["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True], ], } + vop3 = { + "name": "ENC_VOP3", + "bits": 64, + "fields": [ + ["VDST", [[0, 8]]], ["ABS", [[8, 3]]], ["OP_SEL", [[11, 4]]], ["CLAMP", [[15, 1]]], + ["OP", [[16, 10]]], ["ENCODING", [[26, 6]]], ["SRC0", [[32, 9]]], ["SRC1", [[41, 9]]], + ["SRC2", [[50, 9]]], ["OMOD", [[59, 2]]], ["NEG", [[61, 3]]], + ], + "identifier_mask": 0xFFFF0000, + "identifiers": [0xD4000000 | (op << 16) for op in (265, 273, 295)], + } + # Values copied from the AMD XML snapshot: VOP3 encodings of VOP2 forms. + for name, opcode, data_format in ( + ("V_MUL_I32_I24", 265, I32), ("V_MIN_I32", 273, I32), ("V_SUBREV_NC_U32", 295, U32), + ): + variants[(name, "ENC_VOP3")] = { + "instruction": name, "encoding": "ENC_VOP3", "opcode": opcode, + "operands": [ + ["VDST", data_format, "OPR_VGPR", 32, False, True, False, True], + ["SRC0", data_format, "OPR_SRC", 32, True, False, False, True], + ["SRC1", data_format, "OPR_SRC_NOLDS", 32, True, False, False, True], + ], + } return { "source": {"sha256": SHA}, "encodings": { "ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2, - "ENC_VOPC": vopc, + "ENC_VOPC": vopc, "ENC_VOP3": vop3, }, "variants": variants, } @@ -266,6 +289,25 @@ def vector_compares(): return reg +def variants(): + reg = vectors() + rule = copy.deepcopy(gen.OPERAND_RULES["vop3_vgpr2"]["shape"]) + rule["unsupported"] = sorted(gen.OPERAND_RULES["vop3_vgpr2"]["unsupported"]) + reg["operand_rules"]["vop3_vgpr2"] = rule + reg["encoding_variant"] = [ + _variant("V_MIN_I32", 273), _variant("V_SUBREV_NC_U32", 295), + ] + return reg + + +def _variant(of, opcode): + return { + "of": of, "family": "VOP3", "opcode": opcode, "operands": "vop3_vgpr2", + "spec": [{"document": "guide", "section": "12.12", "page": 167}], + "verify": ["reference", "independent"], + } + + def compares(): reg = registry() reg["form"] += [ @@ -784,6 +826,68 @@ class Validate(unittest.TestCase): reg["documents"]["guide"]["file"] = "missing.pdf" self.rejects(reg, "document guide: differs from the pinned public document") + # ---- encoding variants ---- + + def test_accepts_encoding_variants(self): + self.assertEqual(self.errors(variants()), []) + + def test_rejects_a_variant_of_an_undeclared_form(self): + reg = variants() + reg["encoding_variant"].append(_variant("V_MUL_HI_I32_I24", 266)) + self.rejects(reg, "V_MUL_HI_I32_I24 (VOP3): encoding variant of an undeclared form") + + def test_rejects_an_incomplete_or_unknown_variant_field(self): + reg = variants() + del reg["encoding_variant"][0]["spec"] + reg["encoding_variant"][1]["operation"] = "sub" + self.rejects(reg, "V_MIN_I32 (VOP3): incomplete encoding variant, missing ['spec']") + self.rejects(reg, "V_SUBREV_NC_U32 (VOP3): unknown keys ['operation']") + + def test_rejects_a_variant_opcode_that_disagrees_with_the_xml(self): + reg = variants() + reg["encoding_variant"][0]["opcode"] = 265 + self.rejects(reg, "V_MIN_I32: opcode 265 disagrees with the XML opcode 273") + + def test_rejects_a_duplicate_variant_or_opcode(self): + reg = variants() + reg["encoding_variant"].append(_variant("V_MIN_I32", 273)) + self.rejects(reg, "V_MIN_I32 (VOP3): duplicate encoding of V_MIN_I32") + self.rejects(reg, "V_MIN_I32 (VOP3): duplicate opcode ('VOP3', 273)") + + def test_rejects_a_variant_in_its_forms_own_family(self): + reg = variants() + reg["encoding_variant"][0].update(family="VOP2", opcode=17, operands="vop2_vgpr") + self.rejects(reg, "V_MIN_I32 (VOP2): an encoding variant must use another family than its form") + + def test_rejects_a_variant_rule_that_cannot_encode_the_form(self): + reg = variants() + reg["encoding_variant"][0]["operands"] = "sop2_sgpr" + self.rejects(reg, "V_MIN_I32 (VOP3): operand rule sop2_sgpr is for SOP2") + self.rejects(reg, "V_MIN_I32 (VOP3): operand rule sop2_sgpr cannot encode a vector form") + + def test_rejects_a_form_that_uses_a_variant_only_rule(self): + reg = variants() + form(reg, "V_MIN_I32")["operands"] = "vop3_vgpr2" + self.rejects(reg, "V_MIN_I32: operand rule vop3_vgpr2 is only for encoding variants") + + def test_checks_the_variant_xml_against_the_inherited_declaration(self): + snap = snapshot() + for row in snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"]: + row[1] = U32 + self.rejects(variants(), "V_MIN_I32: signedness signed contradicts XML format FMT_NUM_U32", snap) + + def test_renders_variant_dispatch_and_rows(self): + text = gen.render(variants(), snapshot()) + self.assertIn("pub const fn from_vop3_word(word: u32) -> Option {", text) + self.assertIn("if word & 0xfc00_0000 != 0xd400_0000 {", text) + self.assertIn("273 => Some(Self::AddU32),", text) # V_MIN_I32's variant name + self.assertIn('Self::SubrevNcU32 => Some("v_subrev_nc_u32_e64"),', text) + self.assertIn('("V_MIN_I32", EncodingFamily::Vop3),', text) + self.assertIn("operands: OperandRule::Vop3Vgpr2,", text) + # The VOP3 row inherits SUBREV's reversed sources. + row = text.split('name: "V_SUBREV_NC_U32",\n family: EncodingFamily::Vop3,', 1)[1] + self.assertIn("swap_sources: true,", row.split("}", 1)[0]) + def test_rejects_an_unenforced_wave_restriction(self): reg = registry() reg["form"][0]["wave"] = "wave32" @@ -1070,8 +1174,9 @@ class LoadRegistry(unittest.TestCase): # Each family is one contiguous run, in include order. runs = [family for index, family in enumerate(families) if index == 0 or families[index - 1] != family] self.assertEqual(len(runs), len(set(runs))) + declared = set(runs) | {variant["family"] for variant in registry.get("encoding_variant", [])} for name, rule in registry["operand_rules"].items(): - self.assertIn(rule["family"], runs, name) + self.assertIn(rule["family"], declared, name) def test_merges_family_files_in_include_order(self): root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { From 6bc88d6c5161b15f9e6a0e979eb21e6adffd3591 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:01:18 -0600 Subject: [PATCH 09/19] isa, scripts: review fixes for the registry split and encoding variants (#215) - Includes must be `/.toml`, so a family file cannot live outside the registry directory or be aliased past the repeat guard. The coverage report (and through it the RDNA2 planner) now uses the generator's loader, so the family-file guards apply to every consumer. - A variant's explicit XML operand formats, destination included, must equal its base encoding's; malformed variant fields are diagnosed instead of raising. - Variants get their own generated enum (VectorAluVop3Op: from_word, base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot name an undeclared encoding and formatting cannot panic. - The planner no longer counts a variant-only operand rule as a rule that can host new forms of its family (V_FMA_F32 was shown as reuse-ready). - The isa test checks that no first word of another 64-bit family (VOP3B) selects a VOP3 variant; docs describe the variant files. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/decoder/src/lib.rs | 14 ++- crates/decoder/tests/gfx1030.rs | 10 +- crates/isa/generate_semantics.py | 105 +++++++++++++++--- crates/isa/src/lib.rs | 8 +- crates/isa/src/semantics_gen.rs | 44 ++++++-- crates/isa/tests/semantics.rs | 36 +++--- crates/shader/src/lib.rs | 5 +- docs/shaders/scalar-alu.md | 2 +- docs/shaders/semantic-registry.md | 22 ++-- scripts/audit/semantic_coverage.py | 26 ++--- scripts/qa/rdna2_plan.py | 10 +- tests/qa/test_rdna2_plan.py | 14 +++ .../test_semantic_coverage.py | 20 ++++ .../test_generate_semantics.py | 30 ++++- 14 files changed, 263 insertions(+), 83 deletions(-) diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index f5e1014..398a88a 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -4,7 +4,8 @@ use std::fmt; pub use xenora_isa::{ Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, - ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource, + ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, + VectorSource, }; use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, @@ -326,7 +327,7 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if let Some(op) = VectorCompareOp::from_word(first) { return vector_compare(op, first, bytes); } - if let Some(op) = VectorAluOp::from_vop3_word(first) { + if let Some(op) = VectorAluVop3Op::from_word(first) { let second = word(bytes, 8)?; return Ok((vop3_vgpr2(op, first, second)?, 8)); } @@ -749,13 +750,16 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi /// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources /// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is /// the gfx1030 assembler's inline-zero operand encoding. -fn vop3_vgpr2(op: VectorAluOp, first: u32, second: u32) -> Result { +fn vop3_vgpr2( + op: VectorAluVop3Op, + first: u32, + second: u32, +) -> Result { let src0 = second & 0x1ff; let src1 = (second >> 9) & 0x1ff; if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 { return Err(unsupported( - op.vop3_assembly_name() - .expect("VOP3 dispatch selects only declared variants"), + op.assembly_name(), "expected two VGPR sources and no modifiers", )); } diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index de9ea49..ae9f8b9 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -4,7 +4,8 @@ use std::process::{Command, Stdio}; use xenora_decoder::{ Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, - ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at, + ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode, + decode_at, }; use xenora_isa::semantics::Signedness; use xenora_ref::{ @@ -44,7 +45,7 @@ fn decodes_each_fixture_instruction_with_offset_and_length() { 20, 8, Instruction::VectorAluVop3 { - op: VectorAluOp::AddNcU32, + op: VectorAluVop3Op::AddNcU32, dst: 1, src0: 1, src1: 2, @@ -376,12 +377,11 @@ fn reference_op(instruction: Instruction) -> Op { ), // The reference's VOP3 add; it is the only VOP3 variant so far. Instruction::VectorAluVop3 { - op: VectorAluOp::AddNcU32, + op: VectorAluVop3Op::AddNcU32, dst, src0, src1, } => Op::Add(dst, src0, src1), - Instruction::VectorAluVop3 { op, .. } => panic!("no reference VOP3 mapping for {op:?}"), Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)), Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary( match op { @@ -1007,7 +1007,7 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() { assert_eq!( decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction, Instruction::VectorAluVop3 { - op: VectorAluOp::AddNcU32, + op: VectorAluVop3Op::AddNcU32, dst: 1, src0: 0, src1: 0 diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index d9604db..7735cbf 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -320,6 +320,8 @@ OPERAND_RULES = { "kind": "vector_vop3", # Only encoding variants of forms whose rule has this kind may use it. "variant_of": "vector", + # The generated enum of this rule's variants; base() maps to "enum". + "variant_enum": "VectorAluVop3Op", }, "vop2_vgpr": { "rust": "Vop2Vgpr", @@ -354,6 +356,8 @@ class RegistryError(ValueError): """A registry file set that cannot be merged into one registry.""" +# An include names a family file as `/.toml`. +INCLUDE = re.compile(r"^[a-z0-9_]+/[a-z0-9]+\.toml$") # Keys a family file may hold; everything else lives in the root file. FAMILY_FILE_KEYS = {"operand_rules", "form", "encoding_variant"} @@ -373,6 +377,13 @@ def load_registry(path=REGISTRY): includes = registry.pop("include", []) if not isinstance(includes, list) or not all(isinstance(item, str) for item in includes): raise RegistryError(f"{path.name}: include must be a list of file names") + # Family files live directly in the directory named after the root + # (rdna2.toml -> rdna2/), as `/.toml`; nothing else resolves. + for include in includes: + if not INCLUDE.match(include) or include.split("/", 1)[0] != path.stem: + raise RegistryError( + f"{path.name}: include {include!r} is not {path.stem}/.toml" + ) if len(set(includes)) != len(includes): raise RegistryError(f"{path.name}: a family file is included twice") rules = registry.setdefault("operand_rules", {}) @@ -740,7 +751,7 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): forms = {form.get("name"): form for form in registry.get("form", [])} identities = {(form.get("name"), form.get("family")) for form in registry.get("form", [])} for index, variant in enumerate(registry.get("encoding_variant", [])): - label = f"{variant.get('of', f'variant #{index}')} ({variant.get('family')})" + label = f"{variant.get('of', f'variant #{index}')!s} ({variant.get('family')!s})" missing = sorted(VARIANT_KEYS - set(variant)) extra = sorted(set(variant) - VARIANT_KEYS) if missing: @@ -749,6 +760,10 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): errors.append(f"{label}: unknown keys {extra}") if missing: continue + malformed = [key for key in ("of", "family", "operands") if not isinstance(variant[key], str)] + if malformed: + errors.append(f"{label}: {malformed} must be strings") + continue base = forms.get(variant["of"]) if base is None: errors.append(f"{label}: encoding variant of an undeclared form") @@ -783,6 +798,18 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): # The XML check runs on the re-encoded declaration, so the variant's # operands must agree with the base form's widths, signedness and effects. _check_xml(variant_row(registry, variant), rule, snapshot, errors) + # Every explicit operand, destination included, has the base encoding's + # data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3). + base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) + own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"]))) + if base_xml and own_xml: + formats = [ + [row[1] for row in record["operands"] if row[0]] for record in (base_xml, own_xml) + ] + if formats[0] != formats[1]: + errors.append( + f"{label}: XML operand formats {formats[1]} differ from the form's {formats[0]}" + ) def _implemented_rule(form): @@ -844,9 +871,12 @@ def render(registry, snapshot): selected = [form for form in forms if form["operands"] == rule_name] out += _render_enum(rule_name, selected, snapshot, positions) variants = registry.get("encoding_variant", []) + variant_positions = { + (variant["of"], variant["family"]): len(forms) + index for index, variant in enumerate(variants) + } for rule_name in sorted({variant["operands"] for variant in variants}): selected = [variant for variant in variants if variant["operands"] == rule_name] - out += _render_variants(rule_name, selected, registry, snapshot) + out += _render_variants(rule_name, selected, registry, snapshot, variant_positions) # Encoding variants follow the forms, as rows of their own. forms = forms + [variant_row(registry, variant) for variant in variants] out += [ @@ -897,9 +927,10 @@ def render(registry, snapshot): return "\n".join(out) -def _render_variants(rule_name, variants, registry, snapshot): - """Dispatch of one operand rule's encoding variants onto the base enum.""" - enum = OPERAND_RULES[rule_name]["enum"] +def _render_variants(rule_name, variants, registry, snapshot, positions): + """One enum per variant rule: exactly its declared variants, with dispatch.""" + base_enum = OPERAND_RULES[rule_name]["enum"] + enum = OPERAND_RULES[rule_name]["variant_enum"] family = variants[0]["family"] encoding = snapshot["encodings"][_family_encoding(family)] (offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"] @@ -908,16 +939,35 @@ def _render_variants(rule_name, variants, registry, snapshot): fixed_bits = encoding["identifiers"][0] & fixed_mask if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]): raise ValueError(f"{family}: identifiers do not split into fixed bits and OP") - lower = family.lower() variant_of = {form["name"]: form["variant"] for form in registry["form"]} rows = sorted(variants, key=lambda variant: variant["opcode"]) + suffix = ASSEMBLY_SUFFIX[family] out = [ + "", + f"/// {family} encodings of registry forms (operand rule `{rule_name}`).", + "#[derive(Clone, Copy, Debug, Eq, PartialEq)]", + f"pub enum {enum} {{", + ] + for variant in variants: + out += [ + f" /// `{variant['of'].lower()}{suffix}` ({family} opcode {variant['opcode']}).", + f" {variant_of[variant['of']]},", + ] + out += [ + "}", "", f"impl {enum} {{", - f" /// Selects the operation from the first word of its {family} encoding (operand", - f" /// rule `{rule_name}`): the encoding bits (mask 0x{fixed_mask:09_x}) and then", - f" /// the OP field (bits {offset}-{offset + size - 1}). `None` for undeclared opcodes.", - f" pub const fn from_{lower}_word(word: u32) -> Option {{", + " /// Every variant, in registry order.", + f" pub const ALL: [Self; {len(variants)}] = [", + ] + out += [f" Self::{variant_of[variant['of']]}," for variant in variants] + out += [ + " ];", + "", + f" /// Selects the variant from the first word of its {family} encoding: the", + f" /// encoding bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits", + f" /// {offset}-{offset + size - 1}). `None` for undeclared opcodes.", + " pub const fn from_word(word: u32) -> Option {", f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{", " return None;", " }", @@ -929,16 +979,39 @@ def _render_variants(rule_name, variants, registry, snapshot): " }", " }", "", - f" /// Assembler name of the {family} encoding, as LLVM prints it, if declared.", - f" pub const fn {lower}_assembly_name(self) -> Option<&'static str> {{", + " /// The form this encodes, whose declaration it inherits.", + f" pub const fn base(self) -> {base_enum} {{", " match self {", ] out += [ - f" Self::{variant_of[row['of']]} => " - f"Some(\"{row['of'].lower()}{ASSEMBLY_SUFFIX[family]}\")," - for row in variants + f" Self::{variant_of[variant['of']]} => {base_enum}::{variant_of[variant['of']]}," + for variant in variants ] - out += [" #[allow(unreachable_patterns)]", " _ => None,", " }", " }", "}"] + out += [ + " }", + " }", + "", + f" /// Assembler name of the {family} encoding, as LLVM prints it.", + " pub const fn assembly_name(self) -> &'static str {", + " match self {", + ] + out += [ + f" Self::{variant_of[variant['of']]} => \"{variant['of'].lower()}{suffix}\"," + for variant in variants + ] + out += [ + " }", + " }", + "", + " /// The validated registry row of this encoding.", + " pub fn semantics(self) -> &'static FormSemantics {", + " &FORMS[match self {", + ] + out += [ + f" Self::{variant_of[variant['of']]} => {positions[(variant['of'], variant['family'])]}," + for variant in variants + ] + out += [" }]", " }", "}"] return out diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index e55aa8f..aad5376 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -19,7 +19,7 @@ pub use rdna2::{ V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; pub use semantics_gen::{ - ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp, + ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, }; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. @@ -157,7 +157,7 @@ pub enum Instruction { /// VOP3 encoding of a registry VOP2 integer operation (operand rule /// `vop3_vgpr2`): two VGPR sources and no input or output modifiers. VectorAluVop3 { - op: VectorAluOp, + op: VectorAluVop3Op, dst: u8, src0: u8, src1: u8, @@ -277,9 +277,7 @@ impl Instruction { Self::WaitLoad => "s_waitcnt", Self::WaitStore => "s_waitcnt_vscnt", Self::MoveB32 { .. } => "v_mov_b32_e32", - Self::VectorAluVop3 { op, .. } => op - .vop3_assembly_name() - .expect("decoded VOP3 variants have a VOP3 name"), + Self::VectorAluVop3 { op, .. } => op.assembly_name(), Self::ScalarMoveB32 { .. } => "s_mov_b32", Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 94e720b..7f25966 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1872,11 +1872,23 @@ impl VectorCompareOp { } } -impl VectorAluOp { - /// Selects the operation from the first word of its VOP3 encoding (operand - /// rule `vop3_vgpr2`): the encoding bits (mask 0xfc00_0000) and then - /// the OP field (bits 16-25). `None` for undeclared opcodes. - pub const fn from_vop3_word(word: u32) -> Option { +/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorAluVop3Op { + /// `v_add_nc_u32_e64` (VOP3 opcode 293). + AddNcU32, +} + +impl VectorAluVop3Op { + /// Every variant, in registry order. + pub const ALL: [Self; 1] = [ + Self::AddNcU32, + ]; + + /// Selects the variant from the first word of its VOP3 encoding: the + /// encoding bits (mask 0xfc00_0000) and then the OP field (bits + /// 16-25). `None` for undeclared opcodes. + pub const fn from_word(word: u32) -> Option { if word & 0xfc00_0000 != 0xd400_0000 { return None; } @@ -1886,14 +1898,26 @@ impl VectorAluOp { } } - /// Assembler name of the VOP3 encoding, as LLVM prints it, if declared. - pub const fn vop3_assembly_name(self) -> Option<&'static str> { + /// The form this encodes, whose declaration it inherits. + pub const fn base(self) -> VectorAluOp { match self { - Self::AddNcU32 => Some("v_add_nc_u32_e64"), - #[allow(unreachable_patterns)] - _ => None, + Self::AddNcU32 => VectorAluOp::AddNcU32, } } + + /// Assembler name of the VOP3 encoding, as LLVM prints it. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::AddNcU32 => "v_add_nc_u32_e64", + } + } + + /// The validated registry row of this encoding. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::AddNcU32 => 84, + }] + } } /// Identity of every registry form and encoding variant, in registry order. diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index c1aa420..14826d0 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -5,7 +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, VectorCompareOp, + CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, + VectorCompareOp, }; #[test] @@ -163,15 +164,9 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { #[test] fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() { - for row in FORMS - .iter() - .filter(|row| row.family == EncodingFamily::Vop3) - { - let op = VectorAluOp::ALL - .into_iter() - .find(|op| op.semantics().name == row.name) - .unwrap_or_else(|| panic!("{} has no base VOP2 form", row.name)); - let base = op.semantics(); + for op in VectorAluVop3Op::ALL { + let (row, base) = (op.semantics(), op.base().semantics()); + assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3)); // The variant inherits the base declaration; only identity and the // operand rule differ. assert_eq!( @@ -184,12 +179,23 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() { ), (row.operation, row.signedness, row.scc, row.vcc, row.exec) ); - assert_eq!( - op.vop3_assembly_name(), - Some(format!("{}_e64", op.mnemonic()).as_str()) - ); + assert_eq!(row.swap_sources, base.swap_sources); + assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic())); } dispatch_selects_exactly(EncodingFamily::Vop3, |word| { - VectorAluOp::from_vop3_word(word).map(|op| op.semantics().name) + VectorAluVop3Op::from_word(word).map(|op| op.semantics().name) }); + // No first word of the other 64-bit families (VOP3B shares VOP3's + // encoding bits) selects a variant. + for meta in META_FORMS + .iter() + .filter(|form| form.family != EncodingFamily::Vop3 && form.bytes == 8) + { + assert_eq!( + VectorAluVop3Op::from_word(meta.bits as u32), + None, + "{}", + meta.name + ); + } } diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index c7ee8a8..c61a905 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -9,7 +9,7 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ - DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorBinary, + DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, }; @@ -685,7 +685,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Result { + let op = op.base(); let (left, right) = if op.swaps_sources() { (read(src1)?, read(src0)?) } else { diff --git a/docs/shaders/scalar-alu.md b/docs/shaders/scalar-alu.md index 213e896..7a74b12 100644 --- a/docs/shaders/scalar-alu.md +++ b/docs/shaders/scalar-alu.md @@ -33,7 +33,7 @@ ignored. Sources are normal SGPRs, inline integers (-16 to 64) or one literal word. These forms are declared as data in the semantic registry, -`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in, +`crates/isa/semantics/rdna2/sop2.toml`: opcode, operation, signedness, carry-in, SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py` checks each declaration against the pinned AMD XML snapshot and rejects contradictions (for example a carry-in on a bitwise form, or a signed form whose diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 2fb8821..468de39 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`): that family's operand rules and forms only. Data only: every value comes from a closed vocabulary. | +| `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/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. | @@ -27,10 +27,12 @@ The root lists its family files under `include`. The generator merges them in that order, and forms keep their order within each file, so the merged registry equals one file with the parts concatenated (splitting the original single file left `semantics_gen.rs` byte-identical). A family file may hold only -`[operand_rules.*]` and `[[form]]` entries of the family it is named after: -`rdna2/vop2.toml` holds VOP2 rules and forms and nothing else. The loader -rejects a form or rule of another family, a rule declared in two files, root -keys in a family file, and a missing or repeated include. Work on different +`[operand_rules.*]`, `[[form]]` and `[[encoding_variant]]` entries of the family +it is named after: `rdna2/vop2.toml` holds VOP2 rules and forms and nothing else. +Each include must be `rdna2/.toml`. The loader rejects a form, +rule or variant of another family, a rule declared in two files, root keys in a +family file, any other include path, and a missing or repeated include. The +coverage report and the RDNA2 planner use the same loader. Work on different families therefore never edits the same registry file. To add a family, create `rdna2/.toml` and append it to `include`; the generated order (and so the generated file) changes only where the new file is placed. @@ -52,9 +54,13 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields: Everything else (operation, signedness, effects, source order) is inherited from the base form, and the XML check runs on that inherited declaration with the variant's family, opcode and operand rule, so the VOP3 operand widths and -formats must agree with it. The generator emits, on the base enum, -`from__word` (encoding bits, then an explicit match on the OP field) and -`_assembly_name`, and one `FORMS` row per variant after the forms. A +formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for +`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding +bits, then an explicit match on the OP field), `base()` (the inherited form), +`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the +forms. Because the enum has no undeclared members, an instruction cannot name a +VOP3 encoding that does not exist. Every explicit XML operand of the variant, +destination included, must have the base encoding's data format. A variant-only rule (one marked `variant_of` in the generator) cannot be used by a form. The validator rejects a variant of an undeclared form, one in the form's own family, a duplicate encoding of a form or a duplicate `(family, opcode)`, a diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index c59d444..3fca878 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -143,21 +143,21 @@ def parse_generated(source): def load_registry(path): - """The root registry with its `include`d family files merged in order. + """The root registry with its family files merged, by the generator's loader. - Only the merge is done here; crates/isa/generate_semantics.py validates - which family each file may hold. + One loader for every consumer, so the family-file guards (one family per + file, include paths, duplicates) apply here too. """ - registry = tomllib.loads(path.read_text(encoding="utf-8")) - for include in registry.pop("include", []): - part = tomllib.loads((path.parent / include).read_text(encoding="utf-8")) - for name, rule in part.get("operand_rules", {}).items(): - if name in registry.setdefault("operand_rules", {}): - raise ValueError(f"{REGISTRY}: operand rule {name} is declared twice") - registry["operand_rules"][name] = rule - registry.setdefault("form", []).extend(part.get("form", [])) - registry.setdefault("encoding_variant", []).extend(part.get("encoding_variant", [])) - return registry + import importlib.util + + script = ROOT / "crates/isa/generate_semantics.py" + spec = importlib.util.spec_from_file_location("generate_semantics", script) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + try: + return module.load_registry(path) + except module.RegistryError as error: + raise ValueError(f"{REGISTRY}: {error}") from error def read_declarations(registry, identified): diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index f648882..fd29f36 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -200,6 +200,10 @@ def classify_unsupported( registry = data["registry"] rules = data["rules"] ops = _declared_ops(registry) + form_rules = {form.get("operands") for form in registry.get("form", [])} + variant_only_rules = { + variant.get("operands") for variant in registry.get("encoding_variant", []) + } - form_rules family_widths: dict[str, set[int]] = defaultdict(set) family_types: dict[str, set[str]] = defaultdict(set) for form in registry.get("form", []): @@ -221,7 +225,11 @@ def classify_unsupported( continue opcode = identified[(family, name)] reusable = sorted(op for op in ops if op) - family_rule_names = [n for n, (fam, _) in rules.items() if fam == family] + # Rules that only encoding variants use (another encoding of an already + # declared form) cannot host a new form, so they do not count here. + family_rule_names = [ + n for n, (fam, _) in rules.items() if fam == family and n not in variant_only_rules + ] missing_rules = [] if not family_rule_names: missing_rules.append(f"no operand_rules for family {family}") diff --git a/tests/qa/test_rdna2_plan.py b/tests/qa/test_rdna2_plan.py index 1737183..103151d 100644 --- a/tests/qa/test_rdna2_plan.py +++ b/tests/qa/test_rdna2_plan.py @@ -66,6 +66,20 @@ class Rdna2Plan(unittest.TestCase): ranks = [c.priority_rank for c in mixed] self.assertEqual(ranks, sorted(ranks)) + def test_variant_only_rules_do_not_make_a_family_reuse_ready(self): + # A rule that only encoding variants use (vop3_vgpr2 re-encodes declared + # VOP2 forms) cannot host a new VOP3 form such as V_FMA_F32. + variant_rules = { + variant["operands"] for variant in self.data["registry"].get("encoding_variant", []) + } + if not variant_rules: + self.skipTest("no encoding variants declared") + vop3 = classify_unsupported(self.data, families=["VOP3"]) + self.assertTrue(vop3) + for cand in vop3: + self.assertNotIn(cand.operand_layout, variant_rules, cand.name) + self.assertNotEqual(cand.status, "reuse-primitives", cand.name) + def test_manifests_exclude_claims_and_stay_deterministic(self): cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50) with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/semantic_coverage/test_semantic_coverage.py b/tests/semantic_coverage/test_semantic_coverage.py index b8aa5b8..0147cac 100644 --- a/tests/semantic_coverage/test_semantic_coverage.py +++ b/tests/semantic_coverage/test_semantic_coverage.py @@ -1,4 +1,6 @@ +import tempfile import unittest +from pathlib import Path from audit import semantic_coverage as coverage @@ -113,5 +115,23 @@ class SemanticCoverageTests(unittest.TestCase): coverage.parse_decoder(f"{header}\n unknown!(),\n];") +class RegistryLoading(unittest.TestCase): + def test_family_file_guards_apply_to_the_report(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "rdna2.toml" + (Path(tmp) / "rdna2").mkdir() + root.write_text('schema = 1\ninclude = ["rdna2/sop2.toml"]\n', encoding="utf-8") + (Path(tmp) / "rdna2" / "sop2.toml").write_text( + '[[form]]\nname = "V_X"\nfamily = "VOP2"\n', encoding="utf-8" + ) + with self.assertRaisesRegex(ValueError, "form V_X is not a SOP2 form"): + coverage.load_registry(root) + + def test_loads_the_real_split_registry(self): + registry = coverage.load_registry(coverage.ROOT / coverage.REGISTRY) + self.assertNotIn("include", registry) + self.assertGreater(len(registry["form"]), 0) + + if __name__ == "__main__": unittest.main() diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 9b3b505..de461df 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -876,12 +876,31 @@ class Validate(unittest.TestCase): row[1] = U32 self.rejects(variants(), "V_MIN_I32: signedness signed contradicts XML format FMT_NUM_U32", snap) + def test_rejects_a_variant_destination_format_that_differs_from_the_form(self): + snap = snapshot() + snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"][0][1] = "FMT_NUM_F32" + self.rejects( + variants(), + "V_MIN_I32 (VOP3): XML operand formats ['FMT_NUM_F32', 'FMT_NUM_I32', 'FMT_NUM_I32'] " + "differ from the form's ['FMT_NUM_I32', 'FMT_NUM_I32', 'FMT_NUM_I32']", + snap, + ) + + def test_rejects_malformed_variant_fields_without_a_traceback(self): + for key in ("of", "operands", "family"): + with self.subTest(key=key): + reg = variants() + reg["encoding_variant"][0][key] = [] + self.rejects(reg, f"[{key!r}] must be strings") + def test_renders_variant_dispatch_and_rows(self): text = gen.render(variants(), snapshot()) - self.assertIn("pub const fn from_vop3_word(word: u32) -> Option {", text) + self.assertIn("pub enum VectorAluVop3Op {", text) + self.assertIn("pub const fn from_word(word: u32) -> Option {", text.split("pub enum VectorAluVop3Op", 1)[1]) self.assertIn("if word & 0xfc00_0000 != 0xd400_0000 {", text) self.assertIn("273 => Some(Self::AddU32),", text) # V_MIN_I32's variant name - self.assertIn('Self::SubrevNcU32 => Some("v_subrev_nc_u32_e64"),', text) + self.assertIn("Self::AddU32 => VectorAluOp::AddU32,", text) + self.assertIn('Self::SubrevNcU32 => "v_subrev_nc_u32_e64",', text) self.assertIn('("V_MIN_I32", EncodingFamily::Vop3),', text) self.assertIn("operands: OperandRule::Vop3Vgpr2,", text) # The VOP3 row inherits SUBREV's reversed sources. @@ -1210,6 +1229,13 @@ class LoadRegistry(unittest.TestCase): root = self.write('include = ["rdna2/sop2.toml"]\n', {"sop2.toml": "schema = 1\n"}) self.fails(root, "rdna2/sop2.toml: keys ['schema'] belong in the root file") + def test_rejects_includes_outside_the_family_directory(self): + for include in ("../sop2.toml", "./rdna2/sop2.toml", "other/sop2.toml", "rdna2/SOP2.toml", + "rdna2/sub/sop2.toml"): + with self.subTest(include=include): + root = self.write(f'include = ["{include}"]\n', {"sop2.toml": ""}) + self.fails(root, f"include {include!r} is not rdna2/.toml") + def test_rejects_a_missing_or_repeated_include(self): self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist") root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop2.toml"]\n', {"sop2.toml": ""}) From 1c5c3204379b74f3ca8a79333dbdddf2d15f9e1e Mon Sep 17 00:00:00 2001 From: jelly013 <22855910+jelly013@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:02:24 +0100 Subject: [PATCH 10/19] test(loader): x86-64 architectural known answers from the Intel SDM (#155) Add 727 cases and definition-based sweeps for the guest CPU, derived from the Intel SDM (revision 093) before the CPU code was read. The interpreter and the DBT run the same cases. 588 cases are verified, 133 use forms both engines refuse, and four ignored tests state open defects: stale DBT blocks after the guest rewrites code, the address of a page-crossing fault, and the fault class of a non-canonical address and of an instruction over 15 bytes. Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/tests/cpu_known_answers.rs | 5361 ++++++++++++++++++++++ 2 files changed, 5362 insertions(+) create mode 100644 crates/loader/tests/cpu_known_answers.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index acc1736..c2d18b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ remains unsupported. - 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`. - Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`. +- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 727 x86-64 cases whose results, flags, MXCSR state and faults were derived from the Intel SDM before the CPU code was read, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manual's definitions. The interpreter and the DBT both run them, and the DBT route (ARM64 code or Rust helper) of each verified instruction is recorded. 588 cases are verified, 133 use forms both engines refuse, and six, plus a self-modifying-code test, record open defects in four ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review. - Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`. - Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet. - Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware. diff --git a/crates/loader/tests/cpu_known_answers.rs b/crates/loader/tests/cpu_known_answers.rs new file mode 100644 index 0000000..8a22c9c --- /dev/null +++ b/crates/loader/tests/cpu_known_answers.rs @@ -0,0 +1,5361 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Architectural known answers for the guest CPU (issue #155). +//! +//! Every expectation here was derived from the Intel 64 and IA-32 Architectures +//! Software Developer's Manual, revision 093 (September 2026), before the +//! interpreter, the DBT or their existing tests were read. Encodings were +//! produced by Apple clang's x86-64 assembler and read back with `objdump`. +//! Nothing here was compared with x86 hardware. The AMD APM was not consulted. +//! +//! Tests named `defect_*` state what the manual requires where the engines differ +//! today. They are ignored with a reason, so they never count as passed; run them +//! with `--ignored`. +//! +//! # Table format +//! +//! ```text +//! @ assembly text +//! bytes of each instruction, `!` before the one expected to fault +//! SDM volume and section +//! case_name: initial state => final state ! fault +//! ``` +//! +//! Citations read "volume section": `1 4.8.4` is Volume 1, Section 4.8.4 and +//! `2B SHLD` is the SHLD entry of Volume 2B. All numbers are hexadecimal. +//! +//! * `rax=` and so on set a register. `x3=` sets an XMM register by lane, lane 0 +//! first: `b:`, `w:`, `d:`, `q:`, or only its low 32 (`s:`) or 64 (`r:`) bits. +//! * `m10=` is memory at `D+10`; `fs8=` and `gs8=` are relative to the segment +//! bases. Bytes are in address order. +//! * `f=CpAz` lists status flags: upper case set, lower case clear. On the right +//! a flag that is missing is undefined by the manual and is not compared; +//! `f=*` and `keep=` require the initial value. A case without `f=` on the +//! left runs with all flags clear and again with all flags set. +//! * `mx=` is MXCSR; `mx=~20:1b88` ignores the bits in `20`. `=?` ignores a value. +//! * Symbols: `D` writable data, `U` the unmapped page after it, `R` read-only +//! data, `S` stack, `C` code, `FSB` and `GSB` segment bases. +//! * Faults: `DE`, `GP`, `UD`, `XM`, and page faults `PFR`, `PFW`, `PFX` with +//! their linear address. State must be as before the faulting instruction. +//! +//! Anything a case does not mention must keep its initial value. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write as _; +use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags}; +use xenora_loader::dbt::{DbtEngine, is_native}; +use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions}; +use xenora_loader::x86_decode::decode; + +const CODE: u64 = 0x40_0000; +const DATA: u64 = 0x50_0000; +const DATA_LEN: usize = 0x2000; +const UNMAPPED: u64 = DATA + DATA_LEN as u64; +const READ_ONLY: u64 = 0x52_0000; +const STACK_PAGE: u64 = 0x54_0000; +const STACK: u64 = STACK_PAGE + 0x800; +const FS_BASE: u64 = 0x60_0000; +const GS_BASE: u64 = 0x62_0000; +const PAGE: usize = 0x1000; + +const CF: u8 = 1; +const PF: u8 = 2; +const AF: u8 = 4; +const ZF: u8 = 8; +const SF: u8 = 16; +const OF: u8 = 32; +const ALL_FLAGS: u8 = 63; + +const REGISTERS: [&str; 16] = [ + "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", + "r14", "r15", +]; + +// --------------------------------------------------------------------------- +// Case tables +// --------------------------------------------------------------------------- + +const ADD_SUB_FLAGS: &str = r" +@ add al, bl + 00d8 + SDM 2A ADD; 1 3.4.3.1 +add8_signed_overflow: rax=1122334455667f7f rbx=1 => rax=1122334455667f80 f=cpAzSO +add8_wrap_to_zero: rax=11223344556600ff rbx=1 => rax=1122334455660000 f=CPAZso +add8_neg_neg_overflow: rax=80 rbx=80 => rax=0 f=CPaZsO +add8_half_carry_only: rax=0f rbx=1 => rax=10 f=cpAzso +add8_even_parity: rax=1 rbx=2 => rax=3 f=cPazso +add8_both_max_positive: rax=7f rbx=7f => rax=fe f=cpAzSO +add8_carry_and_overflow_to_positive: rax=80 rbx=ff => rax=7f f=CpazsO +@ add ax, bx + 6601d8 + SDM 2A ADD; 1 3.4.1.1 +add16_signed_overflow_preserves_upper48: rax=1122334455667fff rbx=1 => rax=1122334455668000 f=cPAzSO +add16_carry_does_not_enter_bit16: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso +@ add ax, bx + 6601d8 + SDM 2A ADD; 1 3.4.3.1 +add16_parity_is_low_byte_only: rax=100 rbx=0 => rax=100 f=cPazso +@ add eax, ebx + 01d8 + SDM 2A ADD; 1 3.4.1.1 +add32_signed_overflow_zero_extends: rax=ffffffff7fffffff rbx=ffffffff00000001 => rax=80000000 f=cPAzSO +@ add eax, ebx + 01d8 + SDM 2A ADD; 1 3.4.3.1 +add32_two_minimums: rax=ffffffff80000000 rbx=80000000 => rax=0 f=CPaZsO +@ add rax, rbx + 4801d8 + SDM 2A ADD; 1 3.4.3.1 +add64_signed_overflow: rax=7fffffffffffffff rbx=1 => rax=8000000000000000 f=cPAzSO +add64_unsigned_wrap: rax=ffffffffffffffff rbx=1 => rax=0 f=CPAZso +@ add rax, -1 + 4883c0ff + SDM 2A ADD; 2A 2.2.1.5 +add64_imm8_is_sign_extended: rax=0 => rax=ffffffffffffffff f=cPazSo +@ add rax, 0xffffffff80000000 + 480500000080 + SDM 2A ADD; 2A 2.2.1.5 +add64_imm32_is_sign_extended: rax=80000000 => rax=0 f=CPaZso +@ add byte ptr [rdi+1], 0x80 + 80470180 + SDM 2A ADD +add8_memory_destination: rdi=D m0=017f02 => m0=01ff02 f=cPazSo +@ add rax, rax + 4801c0 + SDM 2A ADD +add64_register_aliased_doubles: rax=8000000000000001 => rax=2 f=CpazsO +@ sub al, bl + 28d8 + SDM 2B SUB; 1 3.4.3.1 +sub8_borrow_from_zero: rax=0 rbx=1 => rax=ff f=CPAzSo +sub8_min_minus_one: rax=80 rbx=1 => rax=7f f=cpAzsO +sub8_positive_minus_negative: rax=7f rbx=ff => rax=80 f=CpazSO +sub8_zero_minus_min: rax=0 rbx=80 => rax=80 f=CpazSO +sub8_half_borrow_only: rax=10 rbx=1 => rax=0f f=cPAzso +@ sub ax, bx + 6629d8 + SDM 2B SUB; 1 3.4.1.1 +sub16_borrow_preserves_upper48: rax=1122334455660000 rbx=1 => rax=112233445566ffff f=CPAzSo +@ sub eax, ebx + 29d8 + SDM 2B SUB; 1 3.4.1.1 +sub32_borrow_zero_extends: rax=ffffffff00000000 rbx=1 => rax=ffffffff f=CPAzSo +@ sub rax, rbx + 4829d8 + SDM 2B SUB; 1 3.4.3.1 +sub64_min_minus_one: rax=8000000000000000 rbx=1 => rax=7fffffffffffffff f=cPAzsO +sub64_zero_minus_min: rax=0 rbx=8000000000000000 => rax=8000000000000000 f=CPazSO +@ sub rax, rax + 4829c0 + SDM 2B SUB +sub64_self_is_zero: rax=deadbeefcafef00d => rax=0 f=cPaZso +@ cmp eax, ebx + 39d8 + SDM 2A CMP +cmp32_writes_no_register: rax=ffffffff00000005 rbx=ffffffff00000005 => f=cPaZso +@ cmp ax, -1 + 6683f8ff + SDM 2A CMP +cmp16_imm8_sign_extended: rax=ffff => f=cPaZso +"; + +const CARRY_CHAINS: &str = r" +@ adc al, bl + 10d8 + SDM 2A ADC; 1 3.4.3.1 +adc8_all_ones_plus_carry: rax=ff rbx=ff f=C => rax=ff f=CPAzSo +adc8_carry_alone_overflows: rax=7f rbx=0 f=C => rax=80 f=cpAzSO +@ adc al, 0xff + 14ff + SDM 2A ADC; 1 3.4.3.1 +adc8_source_plus_carry_wraps: rax=0 f=C => rax=0 f=CPAZso +@ adc al, bl + 10d8 + SDM 2A ADC +adc8_without_carry: rax=ff rbx=0 f= => rax=ff f=cPazSo +@ adc ax, bx + 6611d8 + SDM 2A ADC; 1 3.4.1.1 +adc16_carry_wraps: rax=112233445566ffff rbx=0 f=C => rax=1122334455660000 f=CPAZso +@ adc eax, ebx + 11d8 + SDM 2A ADC; 1 3.4.1.1 +adc32_carry_wraps_zero_extends: rax=ffffffffffffffff rbx=0 f=C => rax=0 f=CPAZso +@ adc rax, rbx + 4811d8 + SDM 2A ADC; 1 3.4.3.1 +adc64_max_plus_max_plus_carry: rax=7fffffffffffffff rbx=7fffffffffffffff f=C => rax=ffffffffffffffff f=cPAzSO +@ adc qword ptr [rdi], 0 + 48831700 + SDM 2A ADC +adc64_memory_destination: rdi=D m0=ffffffffffffffff f=C => m0=0000000000000000 f=CPAZso +@ sbb al, bl + 18d8 + SDM 2B SBB; 1 3.4.3.1 +sbb8_zero_minus_ff_minus_borrow: rax=0 rbx=ff f=C => rax=0 f=CPAZso +sbb8_borrow_alone: rax=0 rbx=0 f=C => rax=ff f=CPAzSo +sbb8_borrow_alone_overflows: rax=80 rbx=7f f=C => rax=0 f=cPAZsO +@ sbb eax, eax + 19c0 + SDM 2B SBB; 1 3.4.1.1 +sbb32_self_broadcasts_borrow: rax=ffffffff00001234 f=C => rax=ffffffff f=CPAzSo +@ sbb eax, eax + 19c0 + SDM 2B SBB +sbb32_self_without_borrow: rax=ffffffff00001234 f= => rax=0 f=cPaZso +@ sbb rax, 0 + 4883d800 + SDM 2B SBB; 1 3.4.3.1 +sbb64_min_minus_zero_minus_borrow: rax=8000000000000000 f=C => rax=7fffffffffffffff f=cPAzsO +@ add rax, rcx; adc rdx, rbx + 4801c8 4811da + SDM 2A ADC +add128_carry_into_high_half: rax=ffffffffffffffff rdx=7fffffffffffffff rcx=1 rbx=0 => rax=0 rdx=8000000000000000 f=cPAzSO +@ sub rax, rcx; sbb rdx, rbx + 4829c8 4819da + SDM 2B SBB +sub128_borrow_from_high_half: rax=0 rdx=8000000000000000 rcx=1 rbx=0 => rax=ffffffffffffffff rdx=7fffffffffffffff f=cPAzsO +@ clc; 1: mov rax, [rsi]; adc [rdi], rax; lea rsi, [rsi+8]; lea rdi, [rdi+8]; dec ecx; jnz 1b + f8 488b06 481107 488d7608 488d7f08 ffc9 75ee + SDM 2A ADC; 2A DEC; 2A LEA +add256_loop_dec_preserves_carry: rsi=D+20 rdi=D rcx=4 m0=ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff m20=0100000000000000000000000000000000000000000000000000000000000000 => rsi=D+40 rdi=D+20 rax=0 rcx=0 f=CPaZso m0=0000000000000000000000000000000000000000000000000000000000000000 +@ sub rax, r8; sbb rbx, r9; sbb rcx, r10 + 4c29c0 4c19cb 4c19d1 + SDM 2B SBB +sub192_mixed_borrow_chain: rax=0 rbx=0 rcx=0 r8=1 r9=0 r10=0 => rax=ffffffffffffffff rbx=ffffffffffffffff rcx=ffffffffffffffff f=CPAzSo +@ inc al + fec0 + SDM 2A INC +inc8_overflow_keeps_carry_set: rax=7f f=C => rax=80 f=CpAzSO +inc8_wrap_keeps_carry_clear: rax=ff f= => rax=0 f=cPAZso +@ inc eax + ffc0 + SDM 2A INC; 1 3.4.1.1 +inc32_wrap_zero_extends: rax=ffffffffffffffff f=C => rax=0 f=CPAZso +@ dec al + fec8 + SDM 2A DEC +dec8_overflow_keeps_carry_clear: rax=80 f= => rax=7f f=cpAzsO +@ dec rax + 48ffc8 + SDM 2A DEC +dec64_borrow_keeps_carry_set: rax=0 f=C => rax=ffffffffffffffff f=CPAzSo +@ dec word ptr [rdi] + 66ff0f + SDM 2A DEC +dec16_memory: rdi=D m0=000000 f= => m0=ffff00 f=cPAzSo +@ neg al + f6d8 + SDM 2B NEG +neg8_zero: rax=0 => rax=0 f=cPaZso +neg8_min_overflows: rax=80 => rax=80 f=CpazSO +neg8_one: rax=1 => rax=ff f=CPAzSo +@ neg rax + 48f7d8 + SDM 2B NEG +neg64_min: rax=8000000000000000 => rax=8000000000000000 f=CPazSO +@ neg eax + f7d8 + SDM 2B NEG; 1 3.4.1.1 +neg32_zero_extends: rax=ffffffff00000001 => rax=ffffffff f=CPAzSo +@ not eax + f7d0 + SDM 2B NOT; 1 3.4.1.1 +not32_zero_extends_no_flags: rax=ffffffff0000ffff => rax=ffff0000 f=* +@ not ah + f6d4 + SDM 2B NOT +not8_high_byte: rax=1122334455660f77 => rax=112233445566f077 f=* +@ 1: mov rax, [rsi]; adc [rdi], rax; lea rsi, [rsi+8]; lea rdi, [rdi+8]; dec ecx; jnz 1b + 488b06 481107 488d7608 488d7f08 ffc9 75ee + SDM 2A ADC; 2A DEC; 2A LEA +add256_loop_without_clc: rsi=D+20 rdi=D rcx=4 f=C m0=ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff m20=0000000000000000000000000000000000000000000000000000000000000000 => rsi=D+40 rdi=D+20 rax=0 rcx=0 f=CPaZso m0=0000000000000000000000000000000000000000000000000000000000000000 +"; + +const LOGIC: &str = r" +@ and rax, -16 + 4883e0f0 + SDM 2A AND; 2A 2.2.1.5 +and64_imm8_sign_extended: rax=ffffffffffffffff => rax=fffffffffffffff0 f=cPzSo +@ and eax, 0x80000000 + 2500000080 + SDM 2A AND; 1 3.4.1.1 +and32_imm32_zero_extends: rax=ffffffffffffffff => rax=80000000 f=cPzSo +@ and ax, bx + 6621d8 + SDM 2A AND; 1 3.4.1.1 +and16_preserves_upper48: rax=1122334455668001 rbx=7ffe => rax=1122334455660000 f=cPZso +@ or al, bl + 08d8 + SDM 2B OR +or8_sign: rax=1122334455667700 rbx=81 => rax=1122334455667781 f=cPzSo +@ or rax, 0xffffffff80000000 + 480d00000080 + SDM 2B OR; 2A 2.2.1.5 +or64_imm32_sign_extended: rax=1 => rax=ffffffff80000001 f=cpzSo +@ xor eax, eax + 31c0 + SDM 2B XOR; 1 3.4.1.1 +xor32_self_zeroes_all_64: rax=ffffffffffffffff => rax=0 f=cPZso +@ xor al, bl + 30d8 + SDM 2B XOR +xor8_parity_odd: rax=ff rbx=80 => rax=7f f=cpzso +@ test al, bl + 84d8 + SDM 2B TEST +test8_sign_no_write: rax=ff rbx=80 => f=cpzSo +@ test rax, 0xffffffff80000000 + 48a900000080 + SDM 2B TEST +test64_imm32_sign_extended: rax=4000000000000000 => f=cPzso +@ test eax, 0xffffffff + a9ffffffff + SDM 2B TEST +test32_imm_ignores_upper32: rax=ffffffff00000000 => f=cPZso +"; + +const PARTIAL_REGISTERS: &str = r" +@ mov ah, 0x12 + b412 + SDM 1 3.4.1.1 Table 3-2 +mov_ah_leaves_the_rest: rax=8877665544332211 => rax=8877665544331211 f=* +@ mov spl, 0x12 + 40b412 + SDM 1 3.4.1.1 Table 3-2; 2A 2.2.1.2 +mov_spl_needs_rex_and_is_not_ah: rsp=S => rsp=S+12 f=* +@ mov sil, 0x5a + 40b65a + SDM 1 3.4.1.1 Table 3-2 +mov_sil_is_low_byte_of_rsi: rsi=8877665544332211 => rsi=887766554433225a f=* +@ mov dh, 0x5a + b65a + SDM 1 3.4.1.1 Table 3-2 +mov_dh_without_rex_is_not_sil: rdx=8877665544332211 rsi=0102030405060708 => rdx=8877665544335a11 f=* +@ mov bpl, dil + 4088fd + SDM 1 3.4.1.1 Table 3-2 +mov_bpl_is_low_byte_of_rbp: rbp=8877665544332211 rdi=aabbccddeeff0099 => rbp=8877665544332299 f=* +@ mov ch, bh + 88fd + SDM 1 3.4.1.1 Table 3-2 +mov_ch_without_rex_is_not_bpl: rcx=8877665544332211 rbx=aabbccddeeff0099 => rcx=8877665544330011 f=* +@ mov r8b, r15b + 4588f8 + SDM 1 3.4.1.1 +mov_r8b_preserves_upper56: r8=8877665544332211 r15=aabbccddeeff0099 => r8=8877665544332299 f=* +@ mov r8w, r15w + 664589f8 + SDM 1 3.4.1.1 +mov_r8w_preserves_upper48: r8=8877665544332211 r15=aabbccddeeff0099 => r8=8877665544330099 f=* +@ mov r8d, r15d + 4589f8 + SDM 1 3.4.1.1 +mov_r8d_clears_upper32: r8=8877665544332211 r15=aabbccddeeff0099 => r8=eeff0099 f=* +@ mov eax, eax + 89c0 + SDM 1 3.4.1.1 +mov_eax_eax_clears_upper32: rax=8877665544332211 => rax=44332211 f=* +@ mov rax, 0xffffffff80000000 + 48c7c000000080 + SDM 2B MOV; 2A 2.2.1.5 +mov_rax_imm32_sign_extends: rax=0 => rax=ffffffff80000000 f=* +@ mov eax, 0x80000000 + b800000080 + SDM 2B MOV; 1 3.4.1.1 +mov_eax_imm32_zero_extends: rax=ffffffffffffffff => rax=80000000 f=* +@ movabs rax, 0x8000000000000001 + 48b80100000000000080 + SDM 2B MOV; 2A 2.2.1.5 +movabs_imm64: rax=0 => rax=8000000000000001 f=* +@ xchg ah, al + 86e0 + SDM 2B XCHG; 1 3.4.1.1 Table 3-2 +xchg_ah_al: rax=8877665544332211 => rax=8877665544331122 f=* +@ xchg eax, ebx + 93 + SDM 2B XCHG; 1 3.4.1.1 +xchg_eax_ebx_clears_both_uppers: rax=1111111122222222 rbx=3333333344444444 => rax=44444444 rbx=22222222 f=* +@ xchg r9w, ax + 664191 + SDM 2B XCHG; 1 3.4.1.1 +xchg_ax_r9w_preserves_both_uppers: rax=1111111122222222 r9=3333333344445555 => rax=1111111122225555 r9=3333333344442222 f=* +@ xchg rax, r8 + 4990 + SDM 2B XCHG; 2A 2.2.1 +xchg_rax_r8_is_not_nop: rax=1 r8=2 => rax=2 r8=1 f=* +@ nop + 90 + SDM 2B NOP +nop_leaves_rax_upper_intact: rax=8877665544332211 => f=* +@ xchg [rdi], rax + 488707 + SDM 2B XCHG +xchg_memory: rdi=D rax=0102030405060708 m0=1122334455667788 => rax=8877665544332211 m0=0807060504030201 f=* +@ add bh, cl + 00cf + SDM 2A ADD; 1 3.4.1.1 +add_bh_carry_stays_in_byte: rbx=887766554433ff11 rcx=1 => rbx=8877665544330011 f=CPAZso +@ add ah, al + 00c4 + SDM 2A ADD; 1 3.4.1.1 +add_ah_al_same_register: rax=887766554433807f => rax=887766554433ff7f f=cPazSo +@ movzx eax, bh + 0fb6c7 + SDM 2B MOVZX +movzx_eax_bh: rax=ffffffffffffffff rbx=112233445566f788 => rax=f7 f=* +@ movzx ax, bl + 660fb6c3 + SDM 2B MOVZX; 1 3.4.1.1 +movzx_ax_bl_preserves_upper48: rax=8877665544332211 rbx=ff => rax=88776655443300ff f=* +@ movsx ax, bl + 660fbec3 + SDM 2B MOVSX; 1 3.4.1.1 +movsx_ax_bl_preserves_upper48: rax=8877665544332211 rbx=80 => rax=887766554433ff80 f=* +@ movsx eax, bl + 0fbec3 + SDM 2B MOVSX; 1 3.4.1.1 +movsx_eax_bl_zero_extends_upper32: rax=8877665544332211 rbx=80 => rax=ffffff80 f=* +@ movsx rax, bx + 480fbfc3 + SDM 2B MOVSX +movsx_rax_bx: rax=0 rbx=8000 => rax=ffffffffffff8000 f=* +@ movsxd rax, ebx + 4863c3 + SDM 2B MOVSXD +movsxd_rax_ebx: rax=0 rbx=1111111180000000 => rax=ffffffff80000000 f=* +@ movzx r10d, word ptr [rsi] + 440fb716 + SDM 2B MOVZX +movzx_r10d_word_memory: rsi=D m0=feff r10=ffffffffffffffff => r10=fffe f=* +@ cbw + 6698 + SDM 2A CBW +cbw: rax=1122334455667780 => rax=112233445566ff80 f=* +@ cwde + 98 + SDM 2A CBW; 1 3.4.1.1 +cwde: rax=1122334455668000 => rax=ffff8000 f=* +@ cdqe + 4898 + SDM 2A CBW +cdqe: rax=1122334480000000 => rax=ffffffff80000000 f=* +@ cwd + 6699 + SDM 2A CWD; 1 3.4.1.1 +cwd_preserves_rdx_upper48: rax=8000 rdx=1122334455667788 => rdx=112233445566ffff f=* +@ cdq + 99 + SDM 2A CWD; 1 3.4.1.1 +cdq_zero_extends_rdx: rax=ffffffff80000000 rdx=1122334455667788 => rdx=ffffffff f=* +@ cqo + 4899 + SDM 2A CWD +cqo_positive: rax=7fffffffffffffff rdx=1122334455667788 => rdx=0 f=* +@ bswap eax + 0fc8 + SDM 2A BSWAP; 1 3.4.1.1 +bswap32_zero_extends: rax=ffffffff01020304 => rax=4030201 f=* +@ bswap r15 + 490fcf + SDM 2A BSWAP +bswap64_r15: r15=0102030405060708 => r15=0807060504030201 f=* +@ setc ah + 0f92c4 + SDM 2B SETcc; 1 3.4.1.1 +setc_ah_only_changes_ah: rax=8877665544332211 f=C => rax=8877665544330111 f=* +@ cmovz eax, ebx + 0f44c3 + SDM 2A CMOVcc; 1 3.4.1.1 +cmov32_false_still_zero_extends: rax=ffffffff11112222 rbx=3 f= => rax=11112222 f=* +@ cmovz ax, bx + 660f44c3 + SDM 2A CMOVcc; 1 3.4.1.1 +cmov16_false_changes_nothing: rax=ffffffff11112222 rbx=3 f= => f=* +@ cmovz rax, rbx + 480f44c3 + SDM 2A CMOVcc +cmov64_true: rax=1 rbx=8000000000000000 f=Z => rax=8000000000000000 f=* +@ lea eax, [rbx+rcx] + 8d040b + SDM 2A LEA; 1 3.4.1.1 +lea32_truncates_and_zero_extends: rax=ffffffffffffffff rbx=ffffffff rcx=1 => rax=0 f=* +@ lea ax, [rbx+rcx] + 668d040b + SDM 2A LEA; 1 3.4.1.1 +lea16_preserves_upper48: rax=1122334455667788 rbx=12345 rcx=1 => rax=1122334455662346 f=* +@ lea rax, [ebx+ecx*8+4] + 67488d44cb04 + SDM 2A LEA (Table 3-56 rows 64/32) +lea64_addr32_truncates_effective_address: rax=0 rbx=ffffffffffffffff rcx=1 => rax=0b f=* +@ lea rax, [rbx+rcx*8-128] + 488d44cb80 + SDM 2A LEA; 2A 2.1.5 +lea64_negative_scaled: rbx=100 rcx=ffffffffffffffff => rax=78 f=* +@ lea rax, [rbx+r12*4] + 4a8d04a3 + SDM 2A 2.2.1.2 +lea_r12_index_allowed: rbx=10 r12=3 => rax=1c f=* +@ lea rax, [r13] + 498d4500 + SDM 2A 2.2.1.2 +lea_r13_base_disp0: r13=1234567812345678 => rax=1234567812345678 f=* +@ lea rax, [rip+0x10] + 488d0510000000 + SDM 2A 2.2.1.6 +lea_rip_relative: rax=0 => rax=C+17 f=* +@ mov rax, [rip+0xffff9] + 488b05f9ff0f00 + SDM 2A 2.2.1.6 +load_rip_relative: m0=0102030405060708 => rax=0807060504030201 f=* +@ mov dword ptr [rip+0xffff6], 0x11223344 + c705f6ff0f0044332211 + SDM 2A 2.2.1.6 +store_rip_relative_with_imm32: m0=00 => m0=44332211 f=* +"; + +const EXCHANGE: &str = r" +@ xadd eax, ebx + 0fc1d8 + SDM 2B XADD; 1 3.4.1.1 +xadd32_reg_reg: rax=ffffffff00000001 rbx=ffffffff00000002 => rax=3 rbx=1 f=cPazso +@ xadd al, ah + 0fc0e0 + SDM 2B XADD +xadd8_al_ah: rax=1122334455660180 => rax=1122334455668081 f=cPazSo +@ xadd rax, rax + 480fc1c0 + SDM 2B XADD +xadd64_same_register_doubles: rax=5 => rax=0a f=cPazso +@ lock xadd [rdi], rbx + f0480fc11f + SDM 2B XADD +xadd64_memory: rdi=D rbx=1 m0=ffffffffffffffff => rbx=ffffffffffffffff m0=0000000000000000 f=CPAZso +@ cmpxchg ebx, ecx + 0fb1cb + SDM 2A CMPXCHG; 1 3.4.1.1 +cmpxchg32_equal: rax=ffffffff00000005 rbx=ffffffff00000005 rcx=ffffffff00000009 => rbx=9 f=cPaZso +@ cmpxchg bl, cl + 0fb0cb + SDM 2A CMPXCHG +cmpxchg8_not_equal_loads_al: rax=1122334455667710 rbx=aabbccddeeff0001 rcx=99 => rax=1122334455667701 f=cPAzso +@ lock cmpxchg [rdi], rcx + f0480fb10f + SDM 2A CMPXCHG +cmpxchg64_memory_not_equal: rdi=D rax=1 rcx=7 m0=0200000000000000 => rax=2 f=CPAzSo +@ lock cmpxchg8b [rdi] + f00fc70f + SDM 2A CMPXCHG8B; 1 3.4.1.1 +cmpxchg8b_equal: rdi=D rdx=ffffffff11111111 rax=ffffffff22222222 rcx=33333333 rbx=44444444 m0=2222222211111111 f=CPASO => m0=4444444433333333 f=CPAZSO +cmpxchg8b_not_equal: rdi=D rdx=ffffffff11111111 rax=ffffffff22222222 rcx=33333333 rbx=44444444 m0=2322222211111111 f=Z => rax=22222223 rdx=11111111 f=cpazso +@ lock cmpxchg16b [rdi] + f0480fc70f + SDM 2A CMPXCHG16B +cmpxchg16b_equal: rdi=D rdx=2 rax=1 rcx=4 rbx=3 m0=01000000000000000200000000000000 f= => m0=03000000000000000400000000000000 f=cpaZso +cmpxchg16b_not_equal: rdi=D rdx=2 rax=1 rcx=4 rbx=3 m0=01000000000000000300000000000000 f=ZC => rdx=3 f=Cpazso +@ xadd [rdi], rbx + 480fc11f + SDM 2B XADD +xadd64_memory_without_lock: rdi=D rbx=1 m0=ffffffffffffffff => rbx=ffffffffffffffff m0=0000000000000000 f=CPAZso +@ cmpxchg [rdi], rcx + 480fb10f + SDM 2A CMPXCHG +cmpxchg64_memory_not_equal_without_lock: rdi=D rax=1 rcx=7 m0=0200000000000000 => rax=2 f=CPAzSo +cmpxchg64_memory_equal_without_lock: rdi=D rax=2 rcx=7 m0=0200000000000000 => m0=0700000000000000 f=cPaZso +@ cmpxchg8b [rdi] + 0fc70f + SDM 2A CMPXCHG8B; 1 3.4.1.1 +cmpxchg8b_equal_without_lock: rdi=D rdx=ffffffff11111111 rax=ffffffff22222222 rcx=33333333 rbx=44444444 m0=2222222211111111 f=CPASO => m0=4444444433333333 f=CPAZSO +@ cmpxchg16b [rdi] + 480fc70f + SDM 2A CMPXCHG16B +cmpxchg16b_equal_without_lock: rdi=D rdx=2 rax=1 rcx=4 rbx=3 m0=01000000000000000200000000000000 f= => m0=03000000000000000400000000000000 f=cpaZso +@ cmpxchg16b [rdi+8] + !480fc74f08 + SDM 2A CMPXCHG16B +cmpxchg16b_unaligned_without_lock_is_gp: rdi=D => ! GP +@ .byte 0x87,0xd8 + 87d8 + SDM 2B XCHG (87 /r); 1 3.4.1.1 +xchg_modrm_eax_ebx_clears_both_uppers: rax=1111111122222222 rbx=3333333344444444 => rax=44444444 rbx=22222222 f=* +@ .byte 0x66,0x44,0x87,0xc8 + 664487c8 + SDM 2B XCHG (87 /r); 1 3.4.1.1 +xchg_modrm_ax_r9w_preserves_both_uppers: rax=1111111122222222 r9=3333333344445555 => rax=1111111122225555 r9=3333333344442222 f=* +"; + +const FLAG_MOVES: &str = r" +@ lahf + 9f + SDM 2A LAHF +lahf: rax=8877665544332211 f=CPASO => rax=8877665544339711 f=* +lahf_zero: rax=8877665544332211 f=Z => rax=8877665544334211 f=* +@ sahf; lahf + 9e 9f + SDM 2B SAHF +sahf_ignores_bits_1_3_5: rax=ff00 f=O => rax=d700 f=CPAZSO +@ sahf + 9e + SDM 2B SAHF +sahf_clear_keeps_of: rax=2800 f=OC => f=cpazsO +@ stc + f9 + SDM 2B STC +stc: f=PAZSO => f=CPAZSO +@ clc + f8 + SDM 2A CLC +clc: f=CPAZSO => f=cPAZSO +@ cmc; cmc; cmc + f5 f5 f5 + SDM 2A CMC +cmc: f=CZ => f=cpaZso +@ pushfq; add al, al; popfq + 9c 00c0 9d + SDM 2B PUSHF; 2B POPF +pushfq_popfq_status_round_trip: rax=40 f=CPAZS => rax=80 f=CPAZSo +"; + +const SHIFT_ROTATE: &str = r" +@ shl al, 1 + d0e0 + SDM 2B SAL/SHL +shl8_by1_overflow: rax=1122334455667781 => rax=1122334455667702 f=CpzsO +shl8_by1_sign_change: rax=40 => rax=80 f=cpzSO +shl8_by1_no_overflow: rax=c0 => rax=80 f=CpzSo +@ shl al, 7 + c0e007 + SDM 2B SAL/SHL +shl8_by7_last_bit_out: rax=3 => rax=80 f=CpzS +@ shl al, 8 + c0e008 + SDM 2B SAL/SHL +shl8_by8_result_zero_cf_undefined: rax=11223344556677ff => rax=1122334455667700 f=PZs +@ shl ax, 16 + 66c1e010 + SDM 2B SAL/SHL +shl16_by16_result_zero_cf_undefined: rax=112233445566ffff => rax=1122334455660000 f=PZs +@ shl eax, cl + d3e0 + SDM 2B SAL/SHL; 1 3.4.1.1 +shl32_cl32_is_count_zero: rax=ffffffff80000001 rcx=20 => rax=80000001 f=* +@ shl eax, cl + d3e0 + SDM 2B SAL/SHL +shl32_cl33_is_count_one: rax=80000001 rcx=21 => rax=2 f=CpzsO +@ shl eax, 31 + c1e01f + SDM 2B SAL/SHL +shl32_by31: rax=3 => rax=80000000 f=CPzS +@ shl rax, 63 + 48c1e03f + SDM 2B SAL/SHL +shl64_by63: rax=1 => rax=8000000000000000 f=cPzS +@ shl rax, cl + 48d3e0 + SDM 2B SAL/SHL +shl64_cl64_is_count_zero: rax=8000000000000001 rcx=40 => f=* +shl64_cl65_is_count_one: rax=8000000000000001 rcx=ff41 => rax=2 f=CpzsO +@ shl al, cl + d2e0 + SDM 2B SAL/SHL +shl8_cl_ff_masks_to_31: rax=ff rcx=ff => rax=0 f=PZs +@ shr al, 1 + d0e8 + SDM 2B SHR +shr8_by1_of_is_old_msb: rax=81 => rax=40 f=CpzsO +shr8_by1_positive: rax=7e => rax=3f f=cPzso +@ shr ax, 15 + 66c1e80f + SDM 2B SHR +shr16_by15: rax=112233445566c000 => rax=1122334455660001 f=Cpzs +@ shr eax, 31 + c1e81f + SDM 2B SHR; 1 3.4.1.1 +shr32_by31_zero_extends: rax=ffffffff80000000 => rax=1 f=cpzs +@ shr rax, 63 + 48c1e83f + SDM 2B SHR +shr64_by63_last_bit_out: rax=c000000000000000 => rax=1 f=Cpzs +@ sar al, 1 + d0f8 + SDM 2B SAR +sar8_by1_clears_of: rax=81 => rax=c0 f=CPzSo +@ sar al, 7 + c0f807 + SDM 2B SAR +sar8_by7: rax=80 => rax=ff f=cPzS +@ sar al, 8 + c0f808 + SDM 2B SAR +sar8_by8_cf_is_sign: rax=80 => rax=ff f=CPzS +@ sar al, 31 + c0f81f + SDM 2B SAR +sar8_by31_positive: rax=7f => rax=0 f=cPZs +@ sar ax, 20 + 66c1f814 + SDM 2B SAR +sar16_by20_negative: rax=1122334455668000 => rax=112233445566ffff f=CPzS +@ sar eax, 31 + c1f81f + SDM 2B SAR; 1 3.4.1.1 +sar32_by31_zero_extends: rax=ffffffff80000000 => rax=ffffffff f=cPzS +@ sar rax, 2 + 48c1f802 + SDM 2B SAR (-9 by 2 bits example) +sar64_rounds_to_minus_infinity: rax=fffffffffffffff7 => rax=fffffffffffffffd f=CpzS +@ shl qword ptr [rdi], 1 + 48d127 + SDM 2B SAL/SHL +shl64_memory_by1: rdi=D m0=0000000000000080 => m0=0000000000000000 f=CPZsO +@ rol al, 1 + d0c0 + SDM 2B ROL +rol8_by1: rax=80 => rax=1 f=CO keep=PAZS +@ rol al, 8 + c0c008 + SDM 2B ROL +rol8_by8_identity_updates_cf: rax=81 f= => rax=81 f=Cpazs +@ rol al, 9 + c0c009 + SDM 2B ROL +rol8_by9_is_rotate_by_one_with_of_undefined: rax=81 f= => rax=3 f=Cpazs +@ rol ax, 16 + 66c1c010 + SDM 2B ROL +rol16_by16_identity_updates_cf: rax=1122334455668000 f=C => f=cpazs +@ rol eax, cl + d3c0 + SDM 2B ROL; 1 3.4.1.1 +rol32_cl32_affects_no_flags: rax=ffffffff80000001 rcx=20 => rax=80000001 f=* +@ rol rax, 63 + 48c1c03f + SDM 2B ROL +rol64_by63: rax=1 f= => rax=8000000000000000 f=cpazs +@ ror al, 1 + d0c8 + SDM 2B ROR +ror8_by1: rax=1 => rax=80 f=CO keep=PAZS +ror8_by1_two_top_bits_equal: rax=81 => rax=c0 f=Co keep=PAZS +@ ror al, 8 + c0c808 + SDM 2B ROR +ror8_by8_identity_updates_cf: rax=7f f=C => f=cpazs +@ ror rax, cl + 48d3c8 + SDM 2B ROR +ror64_cl64_affects_no_flags: rax=1 rcx=40 => f=* +ror64_cl65_is_one: rax=1 rcx=41 => rax=8000000000000000 f=CO keep=PAZS +@ rcl al, 1 + d0d0 + SDM 2B RCL +rcl8_by1_clear_carry_in: rax=80 f= => rax=0 f=CpazsO +rcl8_by1_set_carry_in_preserves_szap: rax=80 f=CPAZS => rax=1 f=CPAZSO +@ rcl al, 8 + c0d008 + SDM 2B RCL +rcl8_by8: rax=1 f= => rax=0 f=Cpazs +@ rcl al, 9 + c0d009 + SDM 2B RCL +rcl8_by9_is_identity: rax=a5 f=C => f=Cpazs +@ rcl ax, 17 + 66c1d011 + SDM 2B RCL +rcl16_by17_is_identity: rax=112233445566a5a5 f= => f=cpazs +@ rcl ax, 16 + 66c1d010 + SDM 2B RCL +rcl16_by16: rax=1122334455660001 f=C => rax=1122334455668000 f=Cpazs +@ rcl eax, 31 + c1d01f + SDM 2B RCL +rcl32_by31: rax=ffffffff00000003 f=C => rax=c0000000 f=Cpazs +@ rcl rax, 63 + 48c1d03f + SDM 2B RCL +rcl64_by63: rax=3 f= => rax=8000000000000000 f=Cpazs +@ rcl eax, cl + d3d0 + SDM 2B RCL; 1 3.4.1.1 +rcl32_cl32_affects_nothing_but_extension: rax=ffffffff80000001 rcx=20 => rax=80000001 f=* +@ rcr al, 1 + d0d8 + SDM 2B RCR +rcr8_by1_clear_carry_in: rax=1 f= => rax=0 f=Cpazso +rcr8_by1_set_carry_in: rax=1 f=C => rax=80 f=CpazsO +@ rcr al, 10 + c0d80a + SDM 2B RCR +rcr8_by10_is_by_one_mod_9: rax=2 f=C => rax=81 f=cpazs +@ rcr rax, 1 + 48d1d8 + SDM 2B RCR +rcr64_by1: rax=8000000000000001 f= => rax=4000000000000000 f=CpazsO +@ shr rdx, 1; rcr rax, 1 + 48d1ea 48d1d8 + SDM 2B SHR; 2B RCR +shr_rcr_128bit_right_shift: rdx=3 rax=0 => rdx=1 rax=8000000000000000 +@ shld eax, ebx, 4 + 0fa4d804 + SDM 2B SHLD; 1 3.4.1.1 +shld32_by4: rax=ffffffff12345678 rbx=9abcdef0 => rax=23456789 f=Cpzs +@ shld eax, ebx, 1 + 0fa4d801 + SDM 2B SHLD +shld32_by1_sign_change: rax=40000000 rbx=80000000 => rax=80000001 f=cpzSO +@ shld eax, ebx, cl + 0fa5d8 + SDM 2B SHLD +shld32_cl32_is_count_zero: rax=12345678 rbx=ffffffff rcx=20 => f=* +@ shld rax, rbx, 63 + 480fa4d83f + SDM 2B SHLD +shld64_by63: rax=1 rbx=fffffffffffffffe => rax=ffffffffffffffff f=cPzS +@ shld ax, bx, 16 + 660fa4d810 + SDM 2B SHLD (count equal to size) +shld16_by16_takes_source: rax=1122334455660001 rbx=8002 => rax=1122334455668002 f=CpzS +@ shrd eax, ebx, 8 + 0facd808 + SDM 2B SHRD +shrd32_by8: rax=123456f0 rbx=9abcde77 => rax=77123456 f=CPzs +@ shrd rax, rbx, 1 + 480facd801 + SDM 2B SHRD +shrd64_by1_sign_change: rax=0 rbx=1 => rax=8000000000000000 f=cPzSO +@ shrd rax, rbx, cl + 480fadd8 + SDM 2B SHRD +shrd64_cl64_is_count_zero: rax=5 rbx=1 rcx=40 => f=* +"; + +const MULTIPLY_DIVIDE: &str = r" +@ mul bl + f6e3 + SDM 2B MUL +mul8_max: rax=11223344556600ff rbx=ff => rax=112233445566fe01 f=CO +mul8_fits_clears_co: rax=112233445566ff0f rbx=11 => rax=11223344556600ff f=co +@ mul bx + 66f7e3 + SDM 2B MUL; 1 3.4.1.1 +mul16_preserves_uppers: rax=112233445566ffff rdx=8877665544332211 rbx=ffff => rax=1122334455660001 rdx=887766554433fffe f=CO +@ mul ebx + f7e3 + SDM 2B MUL; 1 3.4.1.1 +mul32_zero_extends_both: rax=ffffffffffffffff rdx=ffffffffffffffff rbx=ffffffff => rax=1 rdx=fffffffe f=CO +@ mul rbx + 48f7e3 + SDM 2B MUL +mul64_max: rax=ffffffffffffffff rbx=ffffffffffffffff => rax=1 rdx=fffffffffffffffe f=CO +@ mul qword ptr [rsi] + 48f726 + SDM 2B MUL +mul64_memory_high_zero: rsi=D rax=4000000000000000 m0=0300000000000000 => rax=c000000000000000 rdx=0 f=co +@ imul bl + f6eb + SDM 2A IMUL +imul8_min_squared: rax=80 rbx=80 => rax=4000 f=CO +imul8_minus_one_squared: rax=aaff rbx=ff => rax=1 f=co +imul8_minus128: rax=80 rbx=1 => rax=ff80 f=co +@ imul rbx + 48f7eb + SDM 2A IMUL +imul64_one_operand_negative: rax=ffffffffffffffff rbx=1 => rax=ffffffffffffffff rdx=ffffffffffffffff f=co +imul64_one_operand_min_times_minus_one: rax=8000000000000000 rbx=ffffffffffffffff => rax=8000000000000000 rdx=0 f=CO +@ imul rax, rbx + 480fafc3 + SDM 2A IMUL +imul64_two_operand_truncates: rax=4000000000000000 rbx=2 => rax=8000000000000000 f=CO +imul64_two_operand_min_fits: rax=4000000000000000 rbx=fffffffffffffffe => rax=8000000000000000 f=co +@ imul eax, ebx, -3 + 6bc3fd + SDM 2A IMUL; 1 3.4.1.1 +imul32_three_operand_imm8: rax=ffffffffffffffff rbx=5 => rax=fffffff1 f=co +@ imul ax, bx, 0x7fff + 6669c3ff7f + SDM 2A IMUL; 1 3.4.1.1 +imul16_three_operand_truncates: rax=1122334455667788 rbx=2 => rax=112233445566fffe f=CO +@ div bl + f6f3 + SDM 2A DIV +div8: rax=1122334455660105 rbx=10 => rax=1122334455660510 +@ div bx + 66f7f3 + SDM 2A DIV +div16: rdx=1122334455660001 rax=1122334455660001 rbx=2 => rax=1122334455668000 rdx=1122334455660001 +@ div ebx + f7f3 + SDM 2A DIV; 1 3.4.1.1 +div32_zero_extends: rdx=ffffffff00000001 rax=ffffffff00000003 rbx=4 => rax=40000000 rdx=3 +@ div rbx + 48f7f3 + SDM 2A DIV +div64_wide_dividend: rdx=1 rax=3 rbx=2 => rax=8000000000000001 rdx=1 +div64_quotient_max: rdx=fffffffffffffffe rax=ffffffffffffffff rbx=ffffffffffffffff => rax=ffffffffffffffff rdx=fffffffffffffffe +@ div rbx + !48f7f3 + SDM 2A DIV; 3A 7.15 Interrupt 0 +div64_quotient_overflow: rdx=2 rax=0 rbx=2 => ! DE +@ mov r8d, 7; div rbx; mov r9d, 8 + 41b807000000 !48f7f3 41b908000000 + SDM 2A DIV; 3A 7.15 Interrupt 0 +div64_by_zero: rdx=0 rax=1 rbx=0 => r8=7 ! DE +@ div bl + !f6f3 + SDM 2A DIV; 3A 7.15 Interrupt 0 +div8_quotient_overflow: rax=1000 rbx=10 => ! DE +@ div dword ptr [rsi] + !f736 + SDM 2A DIV; 3A 7.15 Interrupt 0 +div32_by_zero_memory: rdx=0 rax=1 rsi=D m0=00000000ffffffff => ! DE +@ idiv bl + f6fb + SDM 2A IDIV Table 3-53 +idiv8_minus128_fits: rax=0080 rbx=ff => rax=80 +@ idiv bl + !f6fb + SDM 2A IDIV Table 3-53 +idiv8_plus128_overflows: rax=ff80 rbx=ff => ! DE +@ idiv ebx + f7fb + SDM 2A IDIV; 2B SAR (-9 / 4 example) +idiv32_truncates_toward_zero: rdx=ffffffff rax=fffffff7 rbx=4 => rax=fffffffe rdx=ffffffff +@ idiv rbx + 48f7fb + SDM 2A IDIV +idiv64_positive_by_negative: rdx=0 rax=7 rbx=fffffffffffffffe => rax=fffffffffffffffd rdx=1 +@ idiv rbx + !48f7fb + SDM 2A IDIV; 3A 7.15 Interrupt 0 +idiv64_min_by_minus_one_overflows: rdx=ffffffffffffffff rax=8000000000000000 rbx=ffffffffffffffff => ! DE +@ idiv bx + 66f7fb + SDM 2A IDIV Table 3-53 +idiv16_min_result_fits: rdx=ffff rax=8000 rbx=1 => rax=8000 rdx=0 +@ idiv rbx + 48f7fb + SDM 2A IDIV Table 3-53 +idiv64_wide_min_fits: rdx=ffffffffffffffff rax=0 rbx=2 => rax=8000000000000000 rdx=0 +"; + +const BIT_OPERATIONS: &str = r" +@ bt eax, ebx + 0fa3d8 + SDM 2A BT +bt32_register_offset_is_modulo: rax=80000000 rbx=3f f=Z => f=CZ +@ bt rax, rbx + 480fa3d8 + SDM 2A BT +bt64_register_offset_is_modulo: rax=1 rbx=40 f= => f=Cz +@ bt dword ptr [rsi], eax + 0fa306 + SDM 2A BT; 2A 3.1.1.9 Bit(BitBase,BitOffset) +bt_memory_positive_offset_beyond_operand: rsi=D rax=41 m0=0000000000000000020000 f= => f=Cz +@ bt qword ptr [rsi], rax + 480fa306 + SDM 2A BT; 2A 3.1.1.9 +bt_memory_negative_offset: rsi=D+10 rax=ffffffffffffffff m0=000000000000000000000000000000800000000000000000 f= => f=Cz +@ bts qword ptr [rsi], rax + 480fab06 + SDM 2A BTS; 2A 3.1.1.9 +bts_memory_negative_offset: rsi=D+10 rax=fffffffffffffff8 m0=000000000000000000000000000000000000000000000000 f=CZ => m0=000000000000000000000000000000010000000000000000 f=cZ +@ btr word ptr [rsi], ax + 660fb306 + SDM 2A BTR; 2A 3.1.1.9 +btr16_memory_negative_16bit_offset: rsi=D+2 rax=7fffffffffffffff m0=ffffffff f= => m0=ff7fffff f=Cz +@ .byte 0x0f,0xba,0x26,0x21 + 0fba2621 + SDM 2A BT +bt_imm8_memory_offset_is_masked: rsi=D m0=0200000000000000 f= => f=Cz +@ bts eax, 31 + 0fbae81f + SDM 2A BTS; 1 3.4.1.1 +bts32_register_zero_extends: rax=ffffffff00000000 f= => rax=80000000 f=cz +@ btr rax, 63 + 480fbaf03f + SDM 2A BTR +btr64_register: rax=ffffffffffffffff f=Z => rax=7fffffffffffffff f=CZ +@ btc rax, rbx + 480fbbd8 + SDM 2A BTC +btc64_register: rax=0 rbx=7f f= => rax=8000000000000000 f=cz +@ lock btc dword ptr [rdi], 0 + f00fba3f00 + SDM 2A BTC +lock_btc_memory: rdi=D m0=ffffffff f= => m0=feffffff f=Cz +@ bsf rax, rbx + 480fbcc3 + SDM 2A BSF +bsf64: rax=0 rbx=8000000000000000 => rax=3f f=z +@ bsr rax, rbx + 480fbdc3 + SDM 2A BSR +bsr64: rax=0 rbx=8000000000000001 => rax=3f f=z +@ bsf eax, ebx + 0fbcc3 + SDM 2A BSF; 1 3.4.1.1 +bsf32_zero_extends: rax=ffffffffffffffff rbx=ffffffff00000010 => rax=4 f=z +@ bsf rax, rbx + 480fbcc3 + SDM 2A BSF +bsf64_zero_source_keeps_destination: rax=1234567812345678 rbx=0 => f=Z +@ bsr rax, rbx + 480fbdc3 + SDM 2A BSR +bsr64_zero_source_keeps_destination: rax=1234567812345678 rbx=0 => f=Z +@ popcnt rax, rbx + f3480fb8c3 + SDM 2B POPCNT +popcnt64: rax=0 rbx=ffffffffffffffff => rax=40 f=cpazso +@ popcnt eax, ebx + f30fb8c3 + SDM 2B POPCNT; 1 3.4.1.1 +popcnt32_zero: rax=ffffffffffffffff rbx=ffffffff00000000 => rax=0 f=cpaZso +@ tzcnt rax, rbx + f3480fbcc3 + SDM 2B TZCNT +tzcnt64_zero: rax=0 rbx=0 => rax=40 f=Cz +@ tzcnt eax, ebx + f30fbcc3 + SDM 2B TZCNT; 1 3.4.1.1 +tzcnt32_lsb_set: rax=ffffffffffffffff rbx=1 => rax=0 f=cZ +@ lzcnt eax, ebx + f30fbdc3 + SDM 2A LZCNT; 1 3.4.1.1 +lzcnt32_zero: rax=ffffffffffffffff rbx=ffffffff00000000 => rax=20 f=Cz +@ lzcnt rax, rbx + f3480fbdc3 + SDM 2A LZCNT +lzcnt64_msb_set: rax=1 rbx=8000000000000000 => rax=0 f=cZ +@ crc32 rax, qword ptr [rsi]; crc32 eax, byte ptr [rsi+8]; not eax + f2480f38f106 f20f38f04608 f7d0 + SDM 2A CRC32 (polynomial 11EDC6F41H); check value of the digits 1 to 9 +crc32c_check_string: rax=ffffffff rsi=D m0=313233343536373839 => rax=e3069283 f=* +@ crc32 eax, byte ptr [rsi]; crc32 eax, byte ptr [rsi+1]; crc32 eax, word ptr [rsi+2]; crc32 eax, dword ptr [rsi+4]; crc32 ebx, dword ptr [rsi+4]; crc32 rcx, qword ptr [rsi] + f20f38f006 f20f38f04601 66f20f38f14602 f20f38f14604 f20f38f15e04 f2480f38f10e + SDM 2A CRC32 +crc32c_byte_and_qword_forms_agree: rax=0 rbx=0 rcx=0 rsi=D m0=0000000001000000 => f=* rax=dd45aab8 rbx=dd45aab8 rcx=dd45aab8 +@ btc dword ptr [rdi], 0 + 0fba3f00 + SDM 2A BTC +btc_memory_without_lock: rdi=D m0=ffffffff f= => m0=feffffff f=Cz +"; + +const CONDITIONS: &str = r" +@ cmp rax, rbx; seto [rdi]; setno [rdi+1]; setb [rdi+2]; setae [rdi+3]; sete [rdi+4]; setne [rdi+5]; setbe [rdi+6]; seta [rdi+7]; sets [rdi+8]; setns [rdi+9]; setp [rdi+10]; setnp [rdi+11]; setl [rdi+12]; setge [rdi+13]; setle [rdi+14]; setg [rdi+15] + 4839d8 0f9007 0f914701 0f924702 0f934703 0f944704 0f954705 0f964706 0f974707 0f984708 0f994709 0f9a470a 0f9b470b 0f9c470c 0f9d470d 0f9e470e 0f9f470f + SDM 2B SETcc; 2A CMP +setcc_all_equal: rax=5 rbx=5 rdi=D m0=ffffffffffffffffffffffffffffffff => m0=00010001010001000001010000010100 f=cPaZso +setcc_all_unsigned_below_signed_greater: rax=7fffffffffffffff rbx=8000000000000000 rdi=D m0=ffffffffffffffffffffffffffffffff => m0=01000100000101000100010000010001 f=CPazSO +setcc_all_signed_less_unsigned_above: rax=8000000000000000 rbx=1 rdi=D m0=ffffffffffffffffffffffffffffffff => m0=01000001000100010001010001000100 f=cPAzsO +@ cmp eax, ebx; seto [rdi]; setno [rdi+1]; setb [rdi+2]; setae [rdi+3]; sete [rdi+4]; setne [rdi+5]; setbe [rdi+6]; seta [rdi+7]; sets [rdi+8]; setns [rdi+9]; setp [rdi+10]; setnp [rdi+11]; setl [rdi+12]; setge [rdi+13]; setle [rdi+14]; setg [rdi+15] + 39d8 0f9007 0f914701 0f924702 0f934703 0f944704 0f954705 0f964706 0f974707 0f984708 0f994709 0f9a470a 0f9b470b 0f9c470c 0f9d470d 0f9e470e 0f9f470f + SDM 2B SETcc; 2A CMP +setcc_all_both_less: rax=1 rbx=2 rdi=D m0=ffffffffffffffffffffffffffffffff => m0=00010100000101000100010001000100 f=CPAzSo +@ cmp al, bl; seto [rdi]; setno [rdi+1]; setb [rdi+2]; setae [rdi+3]; sete [rdi+4]; setne [rdi+5]; setbe [rdi+6]; seta [rdi+7]; sets [rdi+8]; setns [rdi+9]; setp [rdi+10]; setnp [rdi+11]; setl [rdi+12]; setge [rdi+13]; setle [rdi+14]; setg [rdi+15] + 38d8 0f9007 0f914701 0f924702 0f934703 0f944704 0f954705 0f964706 0f974707 0f984708 0f994709 0f9a470a 0f9b470b 0f9c470c 0f9d470d 0f9e470e 0f9f470f + SDM 2B SETcc; 2A CMP +setcc_all_both_greater_odd_parity: rax=3 rbx=2 rdi=D m0=ffffffffffffffffffffffffffffffff => m0=00010001000100010001000100010001 f=cpazso +@ cmp rax, rbx; mov ecx, 0; jo 1f; lea ecx, [rcx+1]; 1: jno 1f; lea ecx, [rcx+2]; 1: jb 1f; lea ecx, [rcx+4]; 1: jae 1f; lea ecx, [rcx+8]; 1: je 1f; lea ecx, [rcx+0x10]; 1: jne 1f; lea ecx, [rcx+0x20]; 1: jbe 1f; lea ecx, [rcx+0x40]; 1: ja 1f; lea ecx, [rcx+0x80]; 1: js 1f; lea ecx, [rcx+0x100]; 1: jns 1f; lea ecx, [rcx+0x200]; 1: jp 1f; lea ecx, [rcx+0x400]; 1: jnp 1f; lea ecx, [rcx+0x800]; 1: jl 1f; lea ecx, [rcx+0x1000]; 1: jge 1f; lea ecx, [rcx+0x2000]; 1: jle 1f; lea ecx, [rcx+0x4000]; 1: jg 1f; lea ecx, [rcx+0x8000]; 1: nop + 4839d8 b900000000 7003 8d4901 7103 8d4902 7203 8d4904 7303 8d4908 7403 8d4910 7503 8d4920 7603 8d4940 7706 8d8980000000 7806 8d8900010000 7906 8d8900020000 7a06 8d8900040000 7b06 8d8900080000 7c06 8d8900100000 7d06 8d8900200000 7e06 8d8900400000 7f06 8d8900800000 90 + SDM 2A Jcc; 2A LEA (no flags) +jcc_all_signed_less_unsigned_above: rax=8000000000000000 rbx=1 => rcx=a956 f=cPAzsO +@ cmp rax, rbx; mov ecx, 0; jo 1f; lea ecx, [rcx+1]; 1: jno 1f; lea ecx, [rcx+2]; 1: jb 1f; lea ecx, [rcx+4]; 1: jae 1f; lea ecx, [rcx+8]; 1: je 1f; lea ecx, [rcx+0x10]; 1: jne 1f; lea ecx, [rcx+0x20]; 1: jbe 1f; lea ecx, [rcx+0x40]; 1: ja 1f; lea ecx, [rcx+0x80]; 1: js 1f; lea ecx, [rcx+0x100]; 1: jns 1f; lea ecx, [rcx+0x200]; 1: jp 1f; lea ecx, [rcx+0x400]; 1: jnp 1f; lea ecx, [rcx+0x800]; 1: jl 1f; lea ecx, [rcx+0x1000]; 1: jge 1f; lea ecx, [rcx+0x2000]; 1: jle 1f; lea ecx, [rcx+0x4000]; 1: jg 1f; lea ecx, [rcx+0x8000]; 1: nop + 4839d8 b900000000 7003 8d4901 7103 8d4902 7203 8d4904 7303 8d4908 7403 8d4910 7503 8d4920 7603 8d4940 7706 8d8980000000 7806 8d8900010000 7906 8d8900020000 7a06 8d8900040000 7b06 8d8900080000 7c06 8d8900100000 7d06 8d8900200000 7e06 8d8900400000 7f06 8d8900800000 90 + SDM 2A Jcc +jcc_all_equal: rax=9 rbx=9 => rcx=99a5 f=cPaZso +@ mov ecx, 1; cmp eax, ebx; mov r8d, 0; mov r9d, 0; cmovb r8, rcx; cmova r9, rcx; mov r10d, 0; mov r11d, 0; cmovl r10, rcx; cmovg r11, rcx; mov r12d, 0; mov r13d, 0; cmovo r12, rcx; cmovs r13, rcx + b901000000 39d8 41b800000000 41b900000000 4c0f42c1 4c0f47c9 41ba00000000 41bb00000000 4c0f4cd1 4c0f4fd9 41bc00000000 41bd00000000 4c0f40e1 4c0f48e9 + SDM 2A CMOVcc +cmov_all_unsigned_below_signed_greater: rax=1 rbx=80000000 => rcx=1 r8=1 r9=0 r10=0 r11=1 r12=1 r13=1 f=CpazSO +@ mov eax, 0; jrcxz 1f; mov eax, 1; 1: nop + b800000000 e305 b801000000 90 + SDM 2A Jcc +jrcxz_tests_all_64_bits: rcx=100000000 => rax=1 f=* +@ mov eax, 0; jecxz 1f; mov eax, 1; 1: nop + b800000000 67e305 b801000000 90 + SDM 2A Jcc +jecxz_tests_low_32_bits: rcx=100000000 => rax=0 f=* +@ 1: lea rax, [rax+1]; loop 1b + 488d4001 e2fa + SDM 2A LOOP +loop_decrements_rcx_without_flags: rax=0 rcx=3 => rax=3 rcx=0 f=* +@ 1: lea rax, [rax+1]; loopne 1b + 488d4001 e0fa + SDM 2A LOOP +loopne_stops_on_zero_flag: rax=0 rcx=5 f=Z => rax=1 rcx=4 f=* +"; + +const STACK_AND_CALLS: &str = r" +@ push -2; pop rax + 6afe 58 + SDM 2B PUSH +push_imm8_sign_extends: rax=0 => rax=fffffffffffffffe f=* +@ push rsp; pop rax + 54 58 + SDM 2B PUSH +push_rsp_pushes_old_value: rax=0 => rax=S f=* +@ push rax; pop rsp + 50 5c + SDM 2B POP +pop_rsp_takes_popped_value: rax=S-100 => rsp=S-100 f=* +@ push rax; push 0; pop qword ptr [rsp]; pop rbx + 50 6a00 8f0424 5b + SDM 2B POP +pop_memory_address_uses_incremented_rsp: rax=77 rbx=1 => rbx=0 f=* +@ push rax; push qword ptr [rsp]; pop rbx; pop rcx + 50 ff3424 5b 59 + SDM 2B PUSH +push_memory_address_uses_old_rsp: rax=77 rbx=1 rcx=1 => rbx=77 rcx=77 f=* +@ push ax; lea rbx, [rsp]; pop cx + 6650 488d1c24 6659 + SDM 2B PUSH +push16_moves_rsp_by_two: rax=1234 rcx=1122334455667788 rbx=0 => rbx=S-2 rcx=1122334455661234 f=* +@ call 1f; jmp 2f; 1: mov rax, [rsp]; ret; 2: nop + e802000000 eb05 488b0424 c3 90 + SDM 2A CALL; 2B RET +call_ret_round_trip: rax=0 => rax=C+5 f=* +@ lea rax, [rip+1f]; call rax; jmp 2f; 1: mov ebx, 5; ret; 2: nop + 488d0504000000 ffd0 eb06 bb05000000 c3 90 + SDM 2A CALL +call_indirect_register: rbx=0 => rax=C+0b rbx=5 f=* +@ push 1; push 2; call 1f; jmp 2f; 1: ret 16; 2: nop + 6a01 6a02 e802000000 eb03 c21000 90 + SDM 2B RET +ret_imm16_releases_arguments: => f=* +@ enter 0x20, 0; lea rax, [rsp]; mov rcx, rbp; leave + c8200000 488d0424 4889e9 c9 + SDM 2A ENTER; 2A LEAVE +enter_leave_round_trip: rbp=1234 => rax=S-28 rcx=S-8 f=* +"; + +const STRINGS: &str = r" +@ cld; movsb + fc a4 + SDM 2B MOVS +movsb_forward: rsi=D rdi=D+8 m0=aa m8=00 => rsi=D+1 rdi=D+9 m8=aa f=* +@ cld; rep movsb + fc f3a4 + SDM 2B MOVS; 2B REP +rep_movsq_overlap_propagates: rsi=D rdi=D+1 rcx=4 m0=1122334455 => rsi=D+4 rdi=D+5 rcx=0 m0=1111111111 f=* +@ cld; rep stosd + fc f3ab + SDM 2B STOS; 2B REP +rep_stosd_forward: rdi=D rax=ffffffff11223344 rcx=2 m0=000000000000000000 => rdi=D+8 rcx=0 m0=443322114433221100 f=* +@ std; rep movsw; cld + fd f366a5 fc + SDM 2B MOVS; 1 3.4.3.2 +rep_movsw_backward: rsi=D+2 rdi=D+a rcx=2 m0=11223344 m8=0000000000 => rsi=D-2 rdi=D+6 rcx=0 m8=1122334400 f=* +@ cld; rep movsq + fc f348a5 + SDM 2B REP +rep_movs_zero_count_touches_nothing: rsi=U rdi=U rcx=0 => f=* +@ cld; lodsw + fc 66ad + SDM 2A LODS; 1 3.4.1.1 +lodsw_preserves_upper48: rsi=D rax=1122334455667788 m0=feca => rsi=D+2 rax=112233445566cafe f=* +@ cld; lodsd + fc ad + SDM 2A LODS; 1 3.4.1.1 +lodsd_zero_extends: rsi=D rax=1122334455667788 m0=efbeadde => rsi=D+4 rax=deadbeef f=* +@ cld; repe cmpsb + fc f3a6 + SDM 2A CMPS; 2B REPE +repe_cmpsb_stops_at_difference: rsi=D rdi=D+8 rcx=8 m0=0102030501020304 m8=0102030401020304 => rsi=D+4 rdi=D+c rcx=4 f=cpazso +repe_cmpsb_zero_count_keeps_flags: rsi=U rdi=U rcx=0 => f=* +@ cld; cmpsb + fc a6 + SDM 2A CMPS +cmpsb_is_rsi_minus_rdi: rsi=D rdi=D+8 m0=00 m8=01 => rsi=D+1 rdi=D+9 f=CPAzSo +@ cld; repne scasb + fc f2ae + SDM 2B SCAS; 2B REPNE +repne_scasb_finds_byte: rdi=D rax=33 rcx=8 m0=1122334455667788 => rdi=D+3 rcx=5 f=cPaZso +@ cld; repne scasd + fc f2af + SDM 2B SCAS; 2B REPNE +repne_scasd_exhausts_count: rdi=D rax=2 rcx=2 m0=0100000003000000 => rdi=D+8 rcx=0 f=CPAzSo +@ cld; addr32 rep movsb + fc 67f3a4 + SDM 2B REP; 2B MOVS +rep_movsb_addr32_uses_32bit_registers: rsi=ffffffff00000000+D rdi=ffffffff00000000+D+8 rcx=ffffffff00000002 m0=aabb m8=0000 => rsi=D+2 rdi=D+a rcx=0 m8=aabb f=* +@ cld; rep movsb byte ptr es:[rdi], byte ptr fs:[rsi] + fc f364a4 + SDM 2B MOVS; 3A 3.4.4 +fs_rep_movsb_overrides_source_only: rsi=8 rdi=D rcx=2 fs8=a1a2 m0=0000 => rsi=a rdi=D+2 rcx=0 m0=a1a2 f=* +@ rep movsb + f3a4 + SDM 2B MOVS; 2B REP +rep_movsb_overlap_propagates_df_clear: rsi=D rdi=D+1 rcx=4 m0=1122334455 => rsi=D+4 rdi=D+5 rcx=0 m0=1111111111 f=* +@ rep stosd + f3ab + SDM 2B STOS; 2B REP +rep_stosd_df_clear: rdi=D rax=ffffffff11223344 rcx=2 m0=000000000000000000 => rdi=D+8 rcx=0 m0=443322114433221100 f=* +@ rep movsq + f348a5 + SDM 2B REP +rep_movsq_zero_count_df_clear: rsi=U rdi=U rcx=0 => f=* +@ lodsd + ad + SDM 2A LODS; 1 3.4.1.1 +lodsd_zero_extends_df_clear: rsi=D rax=1122334455667788 m0=efbeadde => rsi=D+4 rax=deadbeef f=* +@ repe cmpsb + f3a6 + SDM 2A CMPS; 2B REPE +repe_cmpsb_stops_at_difference_df_clear: rsi=D rdi=D+8 rcx=8 m0=0102030501020304 m8=0102030401020304 => rsi=D+4 rdi=D+c rcx=4 f=cpazso +@ repne scasb + f2ae + SDM 2B SCAS; 2B REPNE +repne_scasb_finds_byte_df_clear: rdi=D rax=33 rcx=8 m0=1122334455667788 => rdi=D+3 rcx=5 f=cPaZso +@ rep movsb + !f3a4 + SDM 2B REP; 3A 7.5 +rep_movsb_fault_df_clear: rsi=D rdi=U-4 rcx=10 m0=0102030405060708 => rsi=D+4 rdi=U rcx=c m1ffc=01020304 f=* ! PFW U +@ rep stosq + !f348ab + SDM 2B REP; 3A 7.5 +rep_stosq_fault_df_clear: rdi=U-10 rcx=5 rax=1122334455667788 => rdi=U rcx=3 m1ff0=88776655443322118877665544332211 f=* ! PFW U +@ repe cmpsb + !f3a6 + SDM 2B REPE (EFLAGS restored on a fault) +repe_cmpsb_fault_restores_flags_df_clear: rsi=D rdi=U-2 rcx=8 m0=0102 m1ffe=0102 => rsi=D+2 rdi=U rcx=6 f=* ! PFR U +"; + +const FS_GS: &str = r" +@ mov rax, fs:[0x28] + 64488b042528000000 + SDM 3A 3.4.4; 1 3.4.2.1 +fs_load_absolute: rax=0 fs28=0102030405060708 => rax=0807060504030201 f=* +@ mov eax, gs:[rbx+rcx*4+8] + 658b448b08 + SDM 3A 3.4.4 +gs_load_base_index_disp: rax=ffffffffffffffff rbx=10 rcx=2 gs20=78563412 => rax=12345678 f=* +@ mov byte ptr gs:[rbx], 0x5a + 65c6035a + SDM 3A 3.4.4 +gs_store_negative_effective_address_wraps: rbx=fffffffffffffff0 gsbase=GSB+20 gs10=00 => gs10=5a f=* +@ mov rax, fs:[ebx] + 6467488b03 + SDM 3A 3.4.4; 1 3.3.7 +fs_addr32_truncates_before_adding_base: rax=0 rbx=ffffffff00000010 fs10=1122334455667788 => rax=8877665544332211 f=* +@ lea rax, fs:[rbx+4] + 64488d4304 + SDM 2A LEA +lea_ignores_fs_base: rax=0 rbx=10 => rax=14 f=* +@ add dword ptr fs:[rbx], 1 + 64830301 + SDM 3A 3.4.4; 2A ADD +fs_rmw_add: rbx=4 fs4=ffffffff => fs4=00000000 f=CPAZso +@ lock xadd gs:[rbx], ecx + 65f00fc10b + SDM 3A 3.4.4; 2B XADD +gs_lock_xadd: rbx=8 rcx=5 gs8=03000000 => rcx=3 gs8=08000000 f=cpazso +@ movups xmm3, gs:[rbx+1] + 650f105b01 + SDM 3A 3.4.4 +gs_movups_load: rbx=0 gs1=00112233445566778899aabbccddeeff => x3=b:00,11,22,33,44,55,66,77,88,99,aa,bb,cc,dd,ee,ff f=* +@ mov rax, fs:[rsp] + 64488b0424 + SDM 3A 3.4.4 +fs_override_on_rsp_base: rsp=18 rax=0 fs18=efcdab8967452301 => rax=0123456789abcdef f=* +@ mov eax, ds:[rsi] + 3e8b06 + SDM 3A 3.2.4 +ds_override_adds_no_base: rsi=D rax=0 m0=44332211 => rax=11223344 f=* +@ mov eax, cs:[rsi] + 2e8b06 + SDM 3A 3.2.4 +cs_override_adds_no_base: rsi=D rax=0 m0=44332211 => rax=11223344 f=* +@ lea rax, [rip+1f]; mov fs:[0], rax; call fs:[0]; jmp 2f; 1: mov ebx, 5; ret; 2: nop + 488d0513000000 644889042500000000 64ff142500000000 eb06 bb05000000 c3 90 + SDM 2A CALL; 3A 3.4.4 +fs_call_memory_target: rbx=0 fs0=0000000000000000 => rbx=5 rax=C+1a fs0=1a00400000000000 f=* +@ mov rax, fs:[rbx] + !64488b03 + SDM 3A 3.4.4; 3A 7.15 Interrupt 14 +fs_fault_reports_linear_address: rbx=U-FSB => ! PFR U +@ xadd gs:[rbx], ecx + 650fc10b + SDM 3A 3.4.4; 2B XADD +gs_xadd_without_lock: rbx=8 rcx=5 gs8=03000000 => rcx=3 gs8=08000000 f=cpazso +@ rep movsb byte ptr es:[rdi], byte ptr fs:[rsi] + f364a4 + SDM 2B MOVS; 3A 3.4.4 +fs_rep_movsb_overrides_source_only_df_clear: rsi=8 rdi=D rcx=2 fs8=a1a2 m0=0000 => rsi=a rdi=D+2 rcx=0 m0=a1a2 f=* +"; + +const DECODING: &str = r" +@ mov eax, [ebx] + 678b03 + SDM 1 3.3.7 +addr32_load_truncates_effective_address: rbx=ffffffff00000000+D rax=0 m0=44332211 => rax=11223344 f=* +@ mov eax, [ebx+ecx] + 678b040b + SDM 1 3.3.7 +addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=11223344 f=* +@ .byte 0x48,0x66,0x01,0xd8 + 486601d8 + SDM 2A 2.2.1 +rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso +@ .byte 0x66,0x48,0x01,0xd8 + 664801d8 + SDM 2A 2.2.1.2 +rexw_overrides_66: rax=112233445566ffff rbx=1 => rax=1122334455670000 f=cPAzso +@ .byte 0x67,0x64,0xf0,0x48,0x81,0x84,0x58,0x00,0x01,0x00,0x00,0x44,0x33,0x22,0x11 + 6764f0488184580001000044332211 + SDM 2A 2.2.1 (15-byte limit) +fifteen_byte_instruction_executes: rax=ffffffff00000010 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso +@ ud2 + !0f0b + SDM 2B UD; 3A 7.15 Interrupt 6 +ud2: => ! UD +@ .byte 0x06 + !06 + SDM 2B PUSH (PUSH ES invalid in 64-bit mode) +invalid_opcode_06_in_64bit_mode: => ! UD +@ .byte 0xf0,0x01,0xd8 + !f001d8 + SDM 2A LOCK +lock_on_register_destination_is_ud: => ! UD +@ .byte 0xf0,0x89,0x07 + !f08907 + SDM 2A LOCK +lock_on_mov_is_ud: rdi=D => ! UD +@ .byte 0xf0,0x39,0x07 + !f03907 + SDM 2A LOCK +lock_on_cmp_is_ud: rdi=D => ! UD +@ .byte 0x48,0x8d,0xc3 + !488dc3 + SDM 2A LEA +lea_register_source_is_ud: => ! UD +@ movabs rax, [0x500000] + 48a10000500000000000 + SDM 2B MOV; 2A 2.2.1.4 +mov_moffs64_load: rax=0 m0=0102030405060708 => rax=0807060504030201 f=* +@ movabs [0x500003], al + a20300500000000000 + SDM 2B MOV; 2A 2.2.1.4 +mov_moffs8_store: rax=77 m0=00000000 => m0=00000077 f=* +@ add qword ptr fs:[rax+rbx*2+0x100], 0x11223344 + 64488184580001000044332211 + SDM 3A 3.4.4; 2A 2.2.1 +thirteen_byte_fs_add_imm32: rax=10 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso +"; + +const MEMORY_FAULTS: &str = r" +@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2 + 41b801000000 00d8 !488b0e 41b902000000 + SDM 3A 7.5; 3A 7.15 Interrupt 14 +load_unmapped_is_precise: rsi=U rax=7f rbx=1 => r8=1 rax=80 f=cpAzSO ! PFR U +@ mov [rdi], rax + !488907 + SDM 3A 7.15 Interrupt 14 +store_unmapped: rdi=U => ! PFW U +store_readonly_page: rdi=R+8 => ! PFW R+8 +@ add [rdi], rax + !480107 + SDM 3A 7.5 +rmw_readonly_page_keeps_flags: rdi=R+8 rax=1 => ! PFW R+8 +@ inc dword ptr [rdi] + !ff07 + SDM 3A 7.5 +inc_readonly_page_keeps_flags: rdi=R => ! PFW R +@ xchg [rdi], rax + !488707 + SDM 3A 7.5 +xchg_readonly_page_keeps_register: rdi=R rax=5 => ! PFW R +@ cmpxchg [rdi], rcx + !480fb10f + SDM 2A CMPXCHG +cmpxchg_mismatch_still_writes: rdi=R rax=0102030405060709 rcx=1 => ! PFW R +@ xadd [rdi], rcx + !480fc10f + SDM 3A 7.5 +xadd_readonly_page_keeps_register: rdi=R rcx=1 => ! PFW R +@ setz byte ptr [rdi] + !0f9407 + SDM 3A 7.5 +setcc_unmapped: rdi=U => ! PFW U +@ push rax + !50 + SDM 3A 7.5 +push_unmapped_keeps_rsp: rsp=U+8 => ! PFW U +@ pop rax + !58 + SDM 3A 7.5 +pop_unmapped_keeps_rsp: rsp=U => ! PFR U +@ pop qword ptr [rdi] + !8f07 + SDM 3A 7.5; 2B POP +pop_to_readonly_keeps_rsp: rsp=D rdi=R => ! PFW R +@ push qword ptr [rsi] + !ff36 + SDM 3A 7.5 +push_from_unmapped_keeps_rsp: rsi=U => ! PFR U +@ call 1f; 1: mov eax, 1 + !e800000000 b801000000 + SDM 3A 7.5; 2A CALL +call_unmapped_stack_keeps_rip: rsp=U+8 => ! PFW U +@ ret + !c3 + SDM 3A 7.5; 2B RET +ret_unmapped_stack_keeps_rip: rsp=U => ! PFR U +@ cmovz rax, [rsi] + !480f4406 + SDM 2A CMOVcc +cmov_false_still_reads_memory: rsi=U f= => ! PFR U +@ shl qword ptr [rdi], cl + 48d327 + SDM 2B SAL/SHL (read-modify-write of DEST) +shift_zero_count_still_accesses_memory: rdi=D rcx=40 m0=0102030405060708 => f=* +@ mul qword ptr [rsi] + !48f726 + SDM 3A 7.5 +mul_unmapped_keeps_rax_rdx: rsi=U => ! PFR U +@ movaps xmm0, [rsi+1] + !0f284601 + SDM 2B MOVAPS; 1 11.6 / 2A 2.4 (exception type 1) +movaps_load_unaligned_is_gp: rsi=D => ! GP +@ movaps [rdi+8], xmm0 + !0f294708 + SDM 2B MOVAPS +movaps_store_unaligned_is_gp: rdi=D => ! GP +@ movdqa xmm1, [rsi+4] + !660f6f4e04 + SDM 2B MOVDQA +movdqa_load_unaligned_is_gp: rsi=D => ! GP +@ movntdq [rdi+8], xmm0 + !660fe74708 + SDM 2B MOVNTDQ +movntdq_unaligned_is_gp: rdi=D => ! GP +@ paddd xmm0, [rsi+8] + !660ffe4608 + SDM 2B PADDD; 2A 2.4 (type 4) +paddd_memory_unaligned_is_gp: rsi=D => ! GP +@ addps xmm0, [rsi+8] + !0f584608 + SDM 2A ADDPS; 2A 2.4 (type 2) +addps_memory_unaligned_is_gp: rsi=D => ! GP +@ addss xmm0, [rsi+1] + f30f584601 + SDM 2A ADDSS; 2A 2.4 (type 3) +addss_memory_unaligned_is_allowed: rsi=D x0=s:3f800000 m0=000000803f => x0=s:40000000 f=* +@ lock cmpxchg16b [rdi+8] + !f0480fc74f08 + SDM 2A CMPXCHG16B +cmpxchg16b_unaligned_is_gp: rdi=D => ! GP +@ movss [rdi], xmm0 + !f30f1107 + SDM 3A 7.5 +movss_store_readonly: rdi=R+c => ! PFW R+c +@ cld; rep movsb + fc !f3a4 + SDM 2B REP; 3A 7.5 +rep_movsb_fault_stops_at_failing_iteration: rsi=D rdi=U-4 rcx=10 m0=0102030405060708 => rsi=D+4 rdi=U rcx=c m1ffc=01020304 f=* ! PFW U +@ cld; rep stosq + fc !f348ab + SDM 2B REP; 3A 7.5 +rep_stosq_fault_stops_at_failing_iteration: rdi=U-10 rcx=5 rax=1122334455667788 => rdi=U rcx=3 m1ff0=88776655443322118877665544332211 f=* ! PFW U +@ cld; rep lodsb + fc !f3ac + SDM 2B REP; 3A 7.5 +rep_lodsb_source_fault: rsi=U-2 rcx=8 rax=0 m1ffe=aabb => rsi=U rcx=6 rax=bb f=* ! PFR U +@ cld; repe cmpsb + fc !f3a6 + SDM 2B REPE (EFLAGS restored on a fault) +repe_cmpsb_fault_restores_flags: rsi=D rdi=U-2 rcx=8 m0=0102 m1ffe=0102 => rsi=D+2 rdi=U rcx=6 f=* ! PFR U +@ bt qword ptr [rsi], rax + !480fa306 + SDM 2A BT +bt_memory_register_offset_can_fault: rsi=U-8 rax=40 f= => ! PFR U +@ mov eax, 1; jmp rbx + b801000000 ffe3 + SDM 3A 7.15 Interrupt 14 +jump_to_unmapped_faults_at_target: rbx=U => rax=1 rip=U f=* ! PFX U +@ jmp rbx + ffe3 + SDM 3A 5.6 (XD); 3A 7.15 Interrupt 14 +jump_to_data_page_faults_at_target: rbx=D+40 => rip=D+40 f=* ! PFX D+40 +"; + +const DEFECT_STRADDLING_FAULT_ADDRESS: &str = r" +@ mov rcx, [rsi-4] + !488b4efc + SDM 3A 5.7 (the address with no translation); 3A 7.15 Interrupt 14 +load_crossing_into_unmapped_page: rsi=U => ! PFR U +@ mov [rdi-4], rax + !488947fc + SDM 3A 5.7 (the address with no translation); 3A 7.5 +store8_crossing_into_unmapped_page_writes_nothing: rdi=U rax=1122334455667788 => ! PFW U +@ movups xmm0, [rsi-8] + !0f1046f8 + SDM 3A 5.7 (the address with no translation); 3A 7.5 +movups_load_crossing_into_unmapped: rsi=U => ! PFR U +"; + +const DEFECT_NONCANONICAL_ADDRESS: &str = r" +@ mov rax, [rsi] + !488b06 + SDM 1 3.3.7.1; 3A 7.15 Interrupt 13 +noncanonical_load_faults: rsi=100000000000000 => ! GP +@ mov [rdi], rax + !488907 + SDM 1 3.3.7.1; 3A 7.15 Interrupt 13 +noncanonical_store_faults: rdi=7fffffffffffffff => ! GP +"; + +const PACKED_INTEGER_SSE2: &str = r" +@ paddb xmm1, xmm2 + 660ffcca + SDM 2B PADDB +paddb_wraps: x1=b:ff,80,7f,00,01,fe,55,aa,ff,80,7f,00,01,fe,55,aa x2=b:01,80,01,00,ff,03,55,56,02,81,7f,ff,fe,ff,ab,aa => x1=b:00,00,80,00,00,01,aa,00,01,01,fe,ff,ff,fd,00,54 f=* +@ paddw xmm1, xmm2 + 660ffdca + SDM 2B PADDW +paddw_wraps: x1=w:ffff,8000,7fff,00ff,1234,0,fffe,8001 x2=w:1,8000,1,1,edcc,0,3,7fff => x1=w:0,0,8000,100,0,0,1,0 f=* +@ paddd xmm8, xmm15 + 66450ffec7 + SDM 2B PADDD +paddd_no_cross_lane_carry: x8=d:ffffffff,7fffffff,80000000,0 x15=d:1,1,80000000,ffffffff => x8=d:0,80000000,0,ffffffff f=* +@ paddq xmm1, xmm2 + 660fd4ca + SDM 2B PADDQ +paddq_carries_within_quadword: x1=q:ffffffff,ffffffffffffffff x2=q:1,1 => x1=q:100000000,0 f=* +@ psubb xmm1, xmm2 + 660ff8ca + SDM 2B PSUBB +psubb_wraps: x1=b:00,80,7f,00,01,fe,55,aa,0,0,0,0,0,0,0,0 x2=b:01,01,ff,80,01,ff,56,aa,ff,80,7f,01,0,10,f0,aa => x1=b:ff,7f,80,80,00,ff,ff,00,01,80,81,ff,00,f0,10,56 f=* +@ psubw xmm1, xmm2; psubd xmm3, xmm4; psubq xmm5, xmm6 + 660ff9ca 660ffadc 660ffbee + SDM 2B PSUBW/PSUBD; 2B PSUBQ +psubw_psubd_psubq: x1=w:0,8000,7fff,1,ffff,0,0,5 x2=w:1,1,ffff,1,ffff,8000,ffff,3 x3=d:0,80000000,1,5 x4=d:1,1,ffffffff,5 x5=q:0,8000000000000000 x6=q:1,1 => x1=w:ffff,7fff,8000,0,0,8000,1,2 x3=d:ffffffff,7fffffff,2,0 x5=q:ffffffffffffffff,7fffffffffffffff f=* +@ paddsb xmm1, xmm2 + 660fecca + SDM 2B PADDSB +paddsb_saturates: x1=b:7f,80,7f,80,40,c0,01,ff,0,7f,80,70,90,10,f0,64 x2=b:01,ff,7f,80,40,c0,fe,ff,0,ff,01,10,f0,70,90,c8 => x1=b:7f,80,7f,80,7f,80,ff,fe,0,7e,81,7f,80,7f,80,2c f=* +@ paddsw xmm1, xmm2 + 660fedca + SDM 2B PADDSW +paddsw_saturates: x1=w:7fff,8000,7fff,8000,4000,c000,1,ffff x2=w:1,ffff,8000,8000,4000,c000,fffe,ffff => x1=w:7fff,8000,ffff,8000,7fff,8000,ffff,fffe f=* +@ paddusb xmm1, xmm2 + 660fdcca + SDM 2B PADDUSB +paddusb_saturates: x1=b:ff,80,7f,00,01,fe,55,aa,0,0,0,0,0,0,0,0 x2=b:01,80,80,00,ff,01,ab,55,ff,80,7f,0,0,0,0,1 => x1=b:ff,ff,ff,00,ff,ff,ff,ff,ff,80,7f,0,0,0,0,1 f=* +@ paddusw xmm1, xmm2; psubusw xmm3, xmm4 + 660fddca 660fd9dc + SDM 2B PADDUSW; 2B PSUBUSW +paddusw_psubusw_saturate: x1=w:ffff,8000,7fff,1,0,fffe,1234,8001 x2=w:1,8000,8000,1,0,1,1,7fff x3=w:0,1,8000,7fff,ffff,5,1234,0 x4=w:1,1,7fff,8000,1,5,ffff,ffff => x1=w:ffff,ffff,ffff,2,0,ffff,1235,ffff x3=w:0,0,1,0,fffe,0,0,0 f=* +@ psubsb xmm1, xmm2 + 660fe8ca + SDM 2B PSUBSB +psubsb_saturates: x1=b:80,7f,80,7f,00,00,ff,01,0,0,0,0,0,0,0,0 x2=b:01,ff,7f,80,80,7f,ff,01,80,7f,01,ff,0,0,0,0 => x1=b:80,7f,80,7f,7f,81,00,00,7f,81,ff,01,0,0,0,0 f=* +@ psubsw xmm1, xmm2 + 660fe9ca + SDM 2B PSUBSW +psubsw_saturates: x1=w:8000,7fff,0,0,ffff,8000,7fff,1234 x2=w:1,ffff,8000,7fff,ffff,8000,7fff,0234 => x1=w:8000,7fff,7fff,8001,0,0,0,1000 f=* +@ psubusb xmm1, xmm2 + 660fd8ca + SDM 2B PSUBUSB +psubusb_saturates: x1=b:00,01,ff,80,7f,10,20,30,0,0,0,0,ff,ff,ff,ff x2=b:01,01,01,7f,80,0f,21,30,0,1,ff,80,0,1,ff,80 => x1=b:00,00,fe,01,00,01,00,00,0,0,0,0,ff,fe,00,7f f=* +@ pmullw xmm1, xmm2 + 660fd5ca + SDM 2B PMULLW +pmullw_low_half: x1=w:8000,ffff,7fff,100,ffff,1234,8000,3 x2=w:8000,ffff,7fff,100,2,0,2,5 => x1=w:0,1,1,0,fffe,0,0,f f=* +@ pmulhw xmm1, xmm2 + 660fe5ca + SDM 2B PMULHW +pmulhw_signed_high_half: x1=w:8000,ffff,7fff,100,ffff,4000,8000,8000 x2=w:8000,ffff,7fff,100,2,4,7fff,1 => x1=w:4000,0,3fff,1,ffff,1,c000,ffff f=* +@ pmulhuw xmm1, xmm2 + 660fe4ca + SDM 2B PMULHUW +pmulhuw_unsigned_high_half: x1=w:8000,ffff,7fff,100,ffff,4000,8000,8000 x2=w:8000,ffff,7fff,100,2,4,7fff,1 => x1=w:4000,fffe,3fff,1,1,1,3fff,0 f=* +@ pmuludq xmm1, xmm2 + 660ff4ca + SDM 2B PMULUDQ +pmuludq_uses_even_dwords: x1=d:ffffffff,11111111,80000000,22222222 x2=d:ffffffff,33333333,2,44444444 => x1=q:fffffffe00000001,100000000 f=* +@ pmaddwd xmm1, xmm2 + 660ff5ca + SDM 2B PMADDWD +pmaddwd_all_minimums_wrap: x1=w:8000,8000,7fff,7fff,ffff,1,8000,0 x2=w:8000,8000,7fff,7fff,1,ffff,7fff,1234 => x1=d:80000000,7ffe0002,fffffffe,c0008000 f=* +@ psadbw xmm1, xmm2 + 660ff6ca + SDM 2B PSADBW +psadbw: x1=b:ff,0,ff,0,ff,0,ff,0,1,2,3,4,5,6,7,8 x2=b:0,ff,0,ff,0,ff,0,ff,8,7,6,5,4,3,2,1 => x1=q:7f8,20 f=* +@ pavgb xmm1, xmm2; pavgw xmm3, xmm4 + 660fe0ca 660fe3dc + SDM 2B PAVGB/PAVGW +pavgb_pavgw_round_up: x1=b:ff,ff,0,1,fe,80,7f,2,0,0,0,0,0,0,0,0 x2=b:ff,0,1,2,ff,81,80,2,0,0,0,0,0,0,0,1 x3=w:ffff,ffff,0,1,fffe,8000,7fff,2 x4=w:ffff,0,1,2,ffff,8001,8000,2 => x1=b:ff,80,1,2,ff,81,80,2,0,0,0,0,0,0,0,1 x3=w:ffff,8000,1,2,ffff,8001,8000,2 f=* +@ movdqa xmm3, xmm1; pminub xmm1, xmm2; pmaxub xmm3, xmm2; movdqa xmm6, xmm4; pminsw xmm4, xmm5; pmaxsw xmm6, xmm5 + 660f6fd9 660fdaca 660fdeda 660f6ff4 660feae5 660feef5 + SDM 2B PMINUB; 2B PMAXUB; 2B PMINSW; 2B PMAXSW +pmin_pmax_ub_sw: x1=b:80,7f,ff,0,1,fe,0,0,0,0,0,0,0,0,0,0 x2=b:7f,80,0,ff,1,ff,0,0,0,0,0,0,0,0,0,1 x4=w:8000,7fff,ffff,0,1,0,0,0 x5=w:7fff,8000,0,ffff,1,0,0,0 => x1=b:7f,7f,0,0,1,fe,0,0,0,0,0,0,0,0,0,0 x3=b:80,80,ff,ff,1,ff,0,0,0,0,0,0,0,0,0,1 x4=w:8000,8000,ffff,ffff,1,0,0,0 x6=w:7fff,7fff,0,0,1,0,0,0 f=* +@ pcmpeqb xmm1, xmm2; pcmpeqw xmm3, xmm4; pcmpeqd xmm5, xmm6 + 660f74ca 660f75dc 660f76ee + SDM 2B PCMPEQB/W/D +pcmpeqb_w_d: x1=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x2=b:0,0,2,0,4,0,6,0,8,0,a,0,c,0,e,0 x3=w:1,100,ffff,0,8000,7fff,5,6 x4=w:1,1,ffff,0,8000,8000,5,7 x5=d:1,2,80000000,ffffffff x6=d:1,3,80000000,7fffffff => x1=b:ff,0,ff,0,ff,0,ff,0,ff,0,ff,0,ff,0,ff,0 x3=w:ffff,0,ffff,ffff,ffff,0,ffff,0 x5=d:ffffffff,0,ffffffff,0 f=* +@ pcmpgtb xmm1, xmm2; pcmpgtw xmm3, xmm4; pcmpgtd xmm5, xmm6 + 660f64ca 660f65dc 660f66ee + SDM 2B PCMPGTB/W/D +pcmpgt_is_signed: x1=b:7f,80,0,ff,1,0,5,fb,0,0,0,0,0,0,0,0 x2=b:80,7f,ff,0,0,1,5,fa,0,0,0,0,0,0,0,0 x3=w:7fff,8000,0,ffff,1,0,5,0 x4=w:8000,7fff,ffff,0,0,1,5,0 x5=d:7fffffff,80000000,0,1 x6=d:80000000,7fffffff,ffffffff,1 => x1=b:ff,0,ff,0,ff,0,0,ff,0,0,0,0,0,0,0,0 x3=w:ffff,0,ffff,0,ffff,0,0,0 x5=d:ffffffff,0,ffffffff,0 f=* +@ pandn xmm1, xmm2 + 660fdfca + SDM 2B PANDN +pandn_inverts_first_operand: x1=q:ffff0000ffff0000,0 x2=q:ff00ff00ff00ff00,0123456789abcdef => x1=q:0000ff000000ff00,0123456789abcdef f=* +@ pand xmm1, xmm2; por xmm3, xmm2; pxor xmm4, xmm2; pxor xmm5, xmm5 + 660fdbca 660febda 660fefe2 660fefed + SDM 2B PAND; 2B POR; 2B PXOR +pand_por_pxor: x1=q:ffff0000ffff0000,f x2=q:ff00ff00ff00ff00,3 x3=q:00ff000000ff0000,4 x4=q:ffffffffffffffff,3 => x1=q:ff000000ff000000,3 x3=q:ffffff00ffffff00,7 x4=q:00ff00ff00ff00ff,0 x5=q:0,0 f=* +@ psllw xmm1, 15; psllw xmm2, 16; psllw xmm3, 0 + 660f71f10f 660f71f210 660f71f300 + SDM 2B PSLLW +psllw_imm_15_and_16: x1=w:1,2,3,ffff,8000,0,5,6 x2=w:1,2,3,ffff,8000,0,5,6 x3=w:1,2,3,4,5,6,7,8 => x1=w:8000,0,8000,8000,0,0,8000,0 x2=w:0,0,0,0,0,0,0,0 x3=w:1,2,3,4,5,6,7,8 f=* +@ pslld xmm1, 31; pslld xmm2, 32; psllq xmm3, 63; psllq xmm4, 64; psllq xmm5, 255 + 660f72f11f 660f72f220 660f73f33f 660f73f440 660f73f5ff + SDM 2B PSLLD; 2B PSLLQ +pslld_psllq_boundary: x1=d:1,2,3,ffffffff x2=d:1,2,3,ffffffff x3=q:1,2 x4=q:1,ffffffffffffffff x5=q:1,ffffffffffffffff => x1=d:80000000,0,80000000,80000000 x2=q:0,0 x3=q:8000000000000000,0 x4=q:0,0 x5=q:0,0 f=* +@ psllw xmm1, xmm7; pslld xmm2, xmm7; psllq xmm3, xmm7 + 660ff1cf 660ff2d7 660ff3df + SDM 2B PSLLW/PSLLD/PSLLQ +psll_register_count_uses_all_low_64_bits: x1=w:1,2,3,4,5,6,7,8 x2=d:1,2,3,4 x3=q:1,2 x7=q:100000001,0 => x1=q:0,0 x2=q:0,0 x3=q:0,0 f=* +psll_register_count_ignores_high_64_bits: x1=w:1,2,3,4,5,6,7,8 x2=d:1,2,3,4 x3=q:1,8000000000000000 x7=q:1,ffffffffffffffff => x1=w:2,4,6,8,a,c,e,10 x2=d:2,4,6,8 x3=q:2,0 f=* +@ psrlw xmm1, 15; psrlw xmm2, 16; psrld xmm3, 31; psrld xmm4, 32; psrlq xmm5, 63; psrlq xmm6, 64 + 660f71d10f 660f71d210 660f72d31f 660f72d420 660f73d53f 660f73d640 + SDM 2B PSRLW/PSRLD/PSRLQ +psrl_boundary: x1=w:8000,7fff,ffff,0,1,c000,0,ffff x2=q:ffffffffffffffff,ffffffffffffffff x3=d:80000000,7fffffff,ffffffff,1 x4=q:ffffffffffffffff,ffffffffffffffff x5=q:8000000000000000,7fffffffffffffff x6=q:ffffffffffffffff,1 => x1=w:1,0,1,0,0,1,0,1 x2=q:0,0 x3=d:1,0,1,0 x4=q:0,0 x5=q:1,0 x6=q:0,0 f=* +@ psraw xmm1, 16; psraw xmm2, 255; psrad xmm3, 32; psrad xmm4, xmm7 + 660f71e110 660f71e2ff 660f72e320 660fe2e7 + SDM 2B PSRAW/PSRAD +psraw_psrad_fill_with_sign_past_width: x1=w:8000,7fff,ffff,1,c000,0,fffe,4000 x2=w:8000,7fff,ffff,1,c000,0,fffe,4000 x3=d:80000000,7fffffff,ffffffff,1 x4=d:80000000,7fffffff,c0000000,1 x7=q:8000000000000000,0 => x1=w:ffff,0,ffff,0,ffff,0,ffff,0 x2=w:ffff,0,ffff,0,ffff,0,ffff,0 x3=d:ffffffff,0,ffffffff,0 x4=d:ffffffff,0,ffffffff,0 f=* +@ psraw xmm1, 15; psrad xmm2, 1 + 660f71e10f 660f72e201 + SDM 2B PSRAW/PSRAD +psraw_by_15_and_1: x1=w:8000,7fff,ffff,1,c000,0,fffe,4000 x2=d:80000001,7fffffff,ffffffff,1 => x1=w:ffff,0,ffff,0,ffff,0,ffff,0 x2=d:c0000000,3fffffff,ffffffff,0 f=* +@ pslldq xmm1, 1; pslldq xmm2, 15; pslldq xmm3, 16; psrldq xmm4, 1; psrldq xmm5, 15; psrldq xmm6, 255 + 660f73f901 660f73fa0f 660f73fb10 660f73dc01 660f73dd0f 660f73deff + SDM 2B PSLLDQ; 2B PSRLDQ +pslldq_psrldq_boundaries: x1=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 x2=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 x3=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 x4=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 x5=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 x6=b:1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10 => x1=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x2=b:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 x3=q:0,0 x4=b:2,3,4,5,6,7,8,9,a,b,c,d,e,f,10,0 x5=b:10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 x6=q:0,0 f=* +@ packsswb xmm1, xmm2 + 660f63ca + SDM 2B PACKSSWB +packsswb_saturates_signed: x1=w:7f,80,ff80,ff7f,0,7fff,8000,ffff x2=w:1,ffff,100,ff00,7e,81,ff81,fe7f => x1=b:7f,7f,80,80,0,7f,80,ff,1,ff,7f,80,7e,7f,81,80 f=* +@ packuswb xmm1, xmm2 + 660f67ca + SDM 2B PACKUSWB +packuswb_saturates_unsigned: x1=w:ff,100,ffff,8000,7fff,0,1,80 x2=w:fe,101,ff00,0,200,7f,81,ffff => x1=b:ff,ff,0,0,ff,0,1,80,fe,ff,0,0,ff,7f,81,0 f=* +@ packssdw xmm1, xmm1 + 660f6bc9 + SDM 2B PACKSSDW +packssdw_same_register: x1=d:7fff,8000,ffff8000,ffff7fff => x1=w:7fff,7fff,8000,8000,7fff,7fff,8000,8000 f=* +@ movdqa xmm3, xmm1; punpcklbw xmm1, xmm2; punpckhbw xmm3, xmm2 + 660f6fd9 660f60ca 660f68da + SDM 2B PUNPCKLBW; 2B PUNPCKHBW +punpckl_h_bw: x1=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x2=b:10,11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f => x1=b:0,10,1,11,2,12,3,13,4,14,5,15,6,16,7,17 x3=b:8,18,9,19,a,1a,b,1b,c,1c,d,1d,e,1e,f,1f f=* +@ movdqa xmm3, xmm1; movdqa xmm4, xmm1; movdqa xmm5, xmm1; movdqa xmm6, xmm1; movdqa xmm7, xmm1; punpcklwd xmm1, xmm2; punpckhwd xmm3, xmm2; punpckldq xmm4, xmm2; punpckhdq xmm5, xmm2; punpcklqdq xmm6, xmm2; punpckhqdq xmm7, xmm2 + 660f6fd9 660f6fe1 660f6fe9 660f6ff1 660f6ff9 660f61ca 660f69da 660f62e2 660f6aea 660f6cf2 660f6dfa + SDM 2B PUNPCKL*; 2B PUNPCKH* +punpck_wd_dq_qdq: x1=w:0,1,2,3,4,5,6,7 x2=w:10,11,12,13,14,15,16,17 => x1=w:0,10,1,11,2,12,3,13 x3=w:4,14,5,15,6,16,7,17 x4=w:0,1,10,11,2,3,12,13 x5=w:4,5,14,15,6,7,16,17 x6=w:0,1,2,3,10,11,12,13 x7=w:4,5,6,7,14,15,16,17 f=* +@ pshufd xmm1, xmm2, 0x1b; pshuflw xmm3, xmm2, 0x93; pshufhw xmm4, xmm2, 0x39 + 660f70ca1b f20f70da93 f30f70e239 + SDM 2B PSHUFD; 2B PSHUFLW; 2B PSHUFHW +pshufd_pshuflw_pshufhw: x2=w:0,1,2,3,4,5,6,7 => x1=w:6,7,4,5,2,3,0,1 x3=w:3,0,1,2,4,5,6,7 x4=w:0,1,2,3,5,6,7,4 f=* +@ shufps xmm1, xmm2, 0x1b; shufpd xmm3, xmm4, 1; shufps xmm5, xmm5, 0x4e + 0fc6ca1b 660fc6dc01 0fc6ed4e + SDM 2B SHUFPS; 2B SHUFPD +shufps_shufpd: x1=d:a0,a1,a2,a3 x2=d:b0,b1,b2,b3 x3=q:1,2 x4=q:3,4 x5=d:c0,c1,c2,c3 => x1=d:a3,a2,b1,b0 x3=q:2,3 x5=d:c2,c3,c0,c1 f=* +@ movaps xmm3, xmm1; movaps xmm4, xmm1; movaps xmm5, xmm1; unpcklps xmm1, xmm2; unpckhps xmm3, xmm2; unpcklpd xmm4, xmm2; unpckhpd xmm5, xmm2 + 0f28d9 0f28e1 0f28e9 0f14ca 0f15da 660f14e2 660f15ea + SDM 2B UNPCK* +unpcklps_unpckhps_unpcklpd_unpckhpd: x1=d:a0,a1,a2,a3 x2=d:b0,b1,b2,b3 => x1=d:a0,b0,a1,b1 x3=d:a2,b2,a3,b3 x4=d:a0,a1,b0,b1 x5=d:a2,a3,b2,b3 f=* +@ pextrw eax, xmm1, 7; pextrw ecx, xmm1, 0x0a; pinsrw xmm2, ebx, 0x0b + 660fc5c107 660fc5c90a 660fc4d30b + SDM 2B PEXTRW; 2B PINSRW +pextrw_pinsrw_index_mask: x1=w:0,1,f002,3,4,5,6,f007 x2=w:0,0,0,0,0,0,0,0 rax=ffffffffffffffff rcx=ffffffffffffffff rbx=ffff1234 => rax=f007 rcx=f002 x2=w:0,0,0,1234,0,0,0,0 f=* +@ pmovmskb eax, xmm1; movmskps ecx, xmm1; movmskpd edx, xmm1 + 660fd7c1 0f50c9 660f50d1 + SDM 2B PMOVMSKB; 2B MOVMSKPS; 2B MOVMSKPD +pmovmskb_movmskps_movmskpd: x1=b:80,7f,0,ff,0,0,0,80,0,0,0,0,80,0,0,80 rax=ffffffffffffffff rcx=ffffffffffffffff rdx=ffffffffffffffff => rax=9089 rcx=b rdx=3 f=* +@ movd xmm1, eax; movq xmm2, rax; movd ecx, xmm3; movq rdx, xmm3; movq xmm4, xmm3 + 660f6ec8 66480f6ed0 660f7ed9 66480f7eda f30f7ee3 + SDM 2B MOVD/MOVQ +movd_movq_zero_upper_bits: rax=1122334455667788 rcx=ffffffffffffffff x3=q:8877665544332211,5555555555555555 => x1=d:55667788,0,0,0 x2=q:1122334455667788,0 rcx=44332211 rdx=8877665544332211 x4=q:8877665544332211,0 f=* +@ movss xmm1, xmm2; movss xmm3, dword ptr [rsi] + f30f10ca f30f101e + SDM 2B MOVSS +movss_register_merges_memory_zeroes: x1=d:1,2,3,4 x2=d:5,6,7,8 x3=d:9,a,b,c rsi=D m0=44332211 => x1=d:5,2,3,4 x3=d:11223344,0,0,0 f=* +@ movsd xmm1, xmm2; movsd xmm3, qword ptr [rsi] + f20f10ca f20f101e + SDM 2B MOVSD +movsd_register_merges_memory_zeroes: x1=q:1,2 x2=q:3,4 x3=q:5,6 rsi=D m0=8877665544332211 => x1=q:3,2 x3=q:1122334455667788,0 f=* +@ movlps xmm1, [rsi]; movhps xmm2, [rsi]; movhlps xmm3, xmm4; movlhps xmm5, xmm4; movhps [rdi], xmm4 + 0f120e 0f1616 0f12dc 0f16ec 0f1727 + SDM 2B MOVLPS; 2B MOVHPS; 2B MOVHLPS; 2B MOVLHPS +movlps_movhps_movhlps_movlhps: x1=q:1,2 x2=q:3,4 x3=q:5,6 x4=q:7,8 x5=q:9,a rsi=D rdi=D+8 m0=efcdab8967452301 m8=0000000000000000 => x1=q:0123456789abcdef,2 x2=q:3,0123456789abcdef x3=q:8,6 x5=q:9,7 m8=0800000000000000 f=* +@ movdqa [rdi], xmm1; movaps xmm2, [rdi]; movntdq [rdi+0x10], xmm1; movnti [rdi+0x20], rax + 660f7f0f 0f2817 660fe74f10 480fc34720 + SDM 2B MOVDQA; 2B MOVAPS +movdqa_movaps_aligned_store_and_load: x1=q:1122334455667788,99aabbccddeeff00 rdi=D rax=0102030405060708 m0=00 m10=00 m20=00 => x2=q:1122334455667788,99aabbccddeeff00 m0=887766554433221100ffeeddccbbaa99887766554433221100ffeeddccbbaa990807060504030201 f=* +@ maskmovdqu xmm1, xmm2 + 660ff7ca + SDM 2B MASKMOVDQU +maskmovdqu_selects_bytes: x1=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x2=b:80,7f,ff,0,80,0,0,0,0,0,0,0,0,0,0,81 rdi=D+1 m0=ffffffffffffffffffffffffffffffffffff => m0=ff00ff02ff04ffffffffffffffffffff0fff f=* +@ andnps xmm1, xmm2; xorps xmm3, xmm3; orps xmm4, xmm2; andpd xmm5, xmm2 + 0f55ca 0f57db 0f56e2 660f54ea + SDM 2A ANDNPS; 2B XORPS; 2B ORPS +andnps_xorps_orps: x1=q:ffffffff00000000,0 x2=q:123456789abcdef0,7 x4=q:8000000000000000,8 x5=q:ff,5 => x1=q:9abcdef0,7 x3=q:0,0 x4=q:923456789abcdef0,f x5=q:f0,5 f=* +@ paddd xmm9, xmmword ptr [r12+r13*4+0x10] + 66470ffe4cac10 + SDM 2B PADDD; 2A 2.2.1.2 +paddd_memory_source_high_registers: x9=d:1,2,3,4 r12=D r13=4 m20=0a0000000b0000000c0000000d000000 => x9=d:b,d,f,11 f=* +@ movdqa [rdi], xmm1; movaps xmm2, [rdi]; movntdq [rdi+0x10], xmm1 + 660f7f0f 0f2817 660fe74f10 + SDM 2B MOVDQA; 2B MOVAPS; 2B MOVNTDQ +movdqa_movaps_movntdq_round_trip: x1=q:1122334455667788,99aabbccddeeff00 rdi=D m0=00 => x2=q:1122334455667788,99aabbccddeeff00 m0=887766554433221100ffeeddccbbaa99887766554433221100ffeeddccbbaa99 f=* +"; + +const PACKED_INTEGER_BEYOND_SSE2: &str = r" +@ pshufb xmm1, xmm2 + 660f3800ca + SDM 2B PSHUFB +pshufb: x1=b:10,11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f x2=b:f,e,80,0,ff,1,10,1f,7f,81,2,3,4,5,6,7 => x1=b:1f,1e,0,10,0,11,10,1f,1f,0,12,13,14,15,16,17 f=* +@ palignr xmm1, xmm2, 5; palignr xmm3, xmm2, 17; palignr xmm4, xmm2, 32 + 660f3a0fca05 660f3a0fda11 660f3a0fe220 + SDM 2B PALIGNR +palignr: x1=b:10,11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f x2=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x3=b:10,11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f => x1=b:5,6,7,8,9,a,b,c,d,e,f,10,11,12,13,14 x3=b:11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f,0 x4=q:0,0 f=* +@ pabsb xmm1, xmm2; pabsw xmm3, xmm4; pabsd xmm5, xmm6 + 660f381cca 660f381ddc 660f381eee + SDM 2B PABSB/PABSW/PABSD +pabs_min_is_unchanged: x2=b:80,81,7f,ff,0,1,fe,c0,0,0,0,0,0,0,0,0 x4=w:8000,8001,7fff,ffff,0,1,fffe,c000 x6=d:80000000,ffffffff,7fffffff,0 => x1=b:80,7f,7f,1,0,1,2,40,0,0,0,0,0,0,0,0 x3=w:8000,7fff,7fff,1,0,1,2,4000 x5=d:80000000,1,7fffffff,0 f=* +@ phaddw xmm1, xmm2; phaddd xmm3, xmm4; phsubw xmm5, xmm6 + 660f3801ca 660f3802dc 660f3805ee + SDM 2B PHADDW/PHADDD; 2B PHSUBW +phaddw_phaddd_phsubw: x1=w:1,2,7fff,1,ffff,1,8000,8000 x2=w:3,4,5,6,7,8,9,a x3=d:ffffffff,1,7fffffff,1 x4=d:2,3,4,5 x5=w:1,2,8000,1,5,5,0,ffff x6=w:9,1,0,0,0,1,1,0 => x1=w:3,8000,0,0,7,b,f,13 x3=d:0,80000000,5,9 x5=w:ffff,7fff,0,1,8,0,ffff,1 f=* +@ phaddsw xmm1, xmm2; pmaddubsw xmm3, xmm4 + 660f3803ca 660f3804dc + SDM 2B PHADDSW; 2B PMADDUBSW +phaddsw_pmaddubsw_saturate: x1=w:7fff,1,8000,ffff,1,2,0,0 x2=w:4000,4000,c000,bfff,5,6,ffff,ffff x3=b:ff,ff,ff,ff,1,2,80,80,0,0,0,0,0,0,0,0 x4=b:7f,7f,80,80,ff,3,1,ff,0,0,0,0,0,0,0,0 => x1=w:7fff,8000,3,0,7fff,8000,b,fffe x3=w:7fff,8000,5,0,0,0,0,0 f=* +@ pmulhrsw xmm1, xmm2 + 660f380bca + SDM 2B PMULHRSW +pmulhrsw: x1=w:8000,7fff,4000,1,ffff,8000,0,4000 x2=w:8000,7fff,4000,4000,4000,7fff,0,1 => x1=w:8000,7ffe,2000,1,0,8001,0,1 f=* +@ psignb xmm1, xmm2; psignw xmm3, xmm4; psignd xmm5, xmm6 + 660f3808ca 660f3809dc 660f380aee + SDM 2B PSIGNB/PSIGNW/PSIGND +psign: x1=b:80,7f,1,5,0,0,0,0,0,0,0,0,0,0,0,0 x2=b:ff,80,0,1,ff,0,1,0,0,0,0,0,0,0,0,0 x3=w:8000,7fff,1,5,0,0,0,0 x4=w:ffff,8000,0,1,ffff,0,1,0 x5=d:80000000,5,5,5 x6=d:ffffffff,0,80000000,1 => x1=b:80,81,0,5,0,0,0,0,0,0,0,0,0,0,0,0 x3=w:8000,8001,0,5,0,0,0,0 x5=d:80000000,0,fffffffb,5 f=* +@ pmulld xmm1, xmm2; pmuldq xmm3, xmm4 + 660f3840ca 660f3828dc + SDM 2B PMULLD; 2B PMULDQ +pmulld_pmuldq: x1=d:ffffffff,80000000,10000,7fffffff x2=d:ffffffff,2,10000,2 x3=d:ffffffff,11111111,80000000,0 x4=d:2,22222222,80000000,0 => x1=d:1,0,0,fffffffe x3=q:fffffffffffffffe,4000000000000000 f=* +@ pminsb xmm1, xmm0; pmaxsb xmm2, xmm0; pminuw xmm3, xmm0; pmaxuw xmm4, xmm0; pminsd xmm5, xmm0; pmaxud xmm6, xmm0 + 660f3838c8 660f383cd0 660f383ad8 660f383ee0 660f3839e8 660f383ff0 + SDM 2B PMINSB; 2B PMAXSB; 2B PMINUW; 2B PMAXUW; 2B PMINSD; 2B PMAXUD +pmin_pmax_sse41: x0=d:80000000,7fffffff,0,ffffffff x1=q:0,0 x2=q:0,0 x3=q:1000100010001000,1000100010001000 x4=q:1000100010001000,1000100010001000 x5=d:0,0,0,0 x6=d:1,1,1,1 => x1=b:0,0,0,80,ff,ff,ff,0,0,0,0,0,ff,ff,ff,ff x2=b:0,0,0,0,0,0,0,7f,0,0,0,0,0,0,0,0 x3=w:0,1000,1000,1000,0,0,1000,1000 x4=w:1000,8000,ffff,7fff,1000,1000,ffff,ffff x5=d:80000000,0,0,ffffffff x6=d:80000000,7fffffff,1,ffffffff f=* +@ packusdw xmm1, xmm2 + 660f382bca + SDM 2B PACKUSDW +packusdw: x1=d:ffff,10000,ffffffff,0 x2=d:80000000,7fffffff,1,8000 => x1=w:ffff,ffff,0,0,0,ffff,1,8000 f=* +@ pcmpeqq xmm1, xmm2; pcmpgtq xmm3, xmm4 + 660f3829ca 660f3837dc + SDM 2B PCMPEQQ; 2B PCMPGTQ +pcmpeqq_pcmpgtq: x1=q:1,ffffffff00000000 x2=q:1,ffffffff00000001 x3=q:7fffffffffffffff,8000000000000000 x4=q:8000000000000000,7fffffffffffffff => x1=q:ffffffffffffffff,0 x3=q:ffffffffffffffff,0 f=* +@ pmovsxbw xmm1, xmm0; pmovzxbd xmm2, xmm0; pmovsxwq xmm3, xmm0; pmovzxdq xmm4, xmm0; pmovsxdq xmm5, xmm0 + 660f3820c8 660f3831d0 660f3824d8 660f3835e0 660f3825e8 + SDM 2B PMOVSX; 2B PMOVZX +pmovsx_pmovzx: x0=b:80,7f,ff,1,0,80,ff,ff,0,0,0,0,0,0,0,0 => x1=w:ff80,7f,ffff,1,0,ff80,ffff,ffff x2=d:80,7f,ff,1 x3=q:7f80,1ff x4=q:01ff7f80,ffff8000 x5=q:01ff7f80,ffffffffffff8000 f=* +@ pextrb eax, xmm1, 0x1f; pextrd ecx, xmm1, 2; pextrq rdx, xmm1, 1; pinsrb xmm2, ebx, 3; pinsrd xmm3, ebx, 1; pinsrq xmm4, rbx, 1 + 660f3a14c81f 660f3a16c902 66480f3a16ca01 660f3a20d303 660f3a22db01 66480f3a22e301 + SDM 2B PEXTRB/PEXTRD/PEXTRQ; 2B PINSRB/PINSRD/PINSRQ +pextr_pinsr_sse41: x1=q:1,f123456789abcdef x2=q:0,0 x3=q:0,0 x4=q:0,0 rbx=1122334455667788 rax=ffffffffffffffff rcx=ffffffffffffffff => rax=f1 rcx=89abcdef rdx=f123456789abcdef x2=q:88000000,0 x3=q:5566778800000000,0 x4=q:0,1122334455667788 f=* +@ ptest xmm1, xmm2 + 660f3817ca + SDM 2B PTEST +ptest_flags: x1=q:ff00,0 x2=q:00ff,0 => f=cpaZso +ptest_carry_when_source_is_subset: x1=q:ff0f,1 x2=q:0f0f,1 => f=Cpazso +@ pblendvb xmm1, xmm2 + 660f3810ca + SDM 2B PBLENDVB +pblendvb_uses_xmm0_msb: x0=b:80,0,ff,7f,0,0,0,0,0,0,0,0,0,0,0,80 x1=b:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 x2=b:2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 => x1=b:2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2 f=* +@ pblendw xmm1, xmm2, 0x81; blendps xmm3, xmm2, 5 + 660f3a0eca81 660f3a0cda05 + SDM 2B PBLENDW; 2A BLENDPS +pblendw_blendps: x1=w:0,0,0,0,0,0,0,0 x2=w:1,2,3,4,5,6,7,8 x3=d:0,0,0,0 => x1=w:1,0,0,0,0,0,0,8 x3=w:1,2,0,0,5,6,0,0 f=* +@ insertps xmm1, xmm2, 0x98 + 660f3a21ca98 + SDM 2A INSERTPS +insertps_zero_mask: x1=d:1,2,3,4 x2=d:5,6,7,8 => x1=d:1,7,3,0 f=* +@ phminposuw xmm1, xmm2 + 660f3841ca + SDM 2B PHMINPOSUW +phminposuw: x2=w:5,3,ffff,3,9,8,7,6 => x1=w:3,1,0,0,0,0,0,0 f=* +@ mpsadbw xmm1, xmm2, 5 + 660f3a42ca05 + SDM 2B MPSADBW +mpsadbw: x1=b:0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f x2=b:0,0,0,0,4,5,6,7,0,0,0,0,0,0,0,0 => x1=w:0,4,8,c,10,14,18,1c f=* +"; + +const FP_ROUNDING: &str = r" +@ addss xmm1, xmm2 + f30f58ca + SDM 2A ADDSS; 1 4.8.4 Table 4-9 +addss_tie_nearest: x1=s:3f800000 x2=s:33800000 mx=1f80 => x1=s:3f800000 mx=1fa0 f=* +addss_tie_down: x1=s:3f800000 x2=s:33800000 mx=3f80 => x1=s:3f800000 mx=3fa0 f=* +addss_tie_up: x1=s:3f800000 x2=s:33800000 mx=5f80 => x1=s:3f800001 mx=5fa0 f=* +addss_tie_zero: x1=s:3f800000 x2=s:33800000 mx=7f80 => x1=s:3f800000 mx=7fa0 f=* +addss_tie_odd_nearest: x1=s:3f800001 x2=s:33800000 mx=1f80 => x1=s:3f800002 mx=1fa0 f=* +addss_tie_odd_down: x1=s:3f800001 x2=s:33800000 mx=3f80 => x1=s:3f800001 mx=3fa0 f=* +addss_tie_odd_up: x1=s:3f800001 x2=s:33800000 mx=5f80 => x1=s:3f800002 mx=5fa0 f=* +addss_tie_odd_zero: x1=s:3f800001 x2=s:33800000 mx=7f80 => x1=s:3f800001 mx=7fa0 f=* +@ subss xmm1, xmm2 + f30f5cca + SDM 2B SUBSS; 1 4.8.4 Table 4-9 +subss_negative_tie_nearest: x1=s:bf800000 x2=s:33800000 mx=1f80 => x1=s:bf800000 mx=1fa0 f=* +subss_negative_tie_down: x1=s:bf800000 x2=s:33800000 mx=3f80 => x1=s:bf800001 mx=3fa0 f=* +subss_negative_tie_up: x1=s:bf800000 x2=s:33800000 mx=5f80 => x1=s:bf800000 mx=5fa0 f=* +subss_negative_tie_zero: x1=s:bf800000 x2=s:33800000 mx=7f80 => x1=s:bf800000 mx=7fa0 f=* +@ divsd xmm1, xmm2 + f20f5eca + SDM 2A DIVSD; 1 4.8.4 Table 4-9 +divsd_one_third_nearest: x1=r:3ff0000000000000 x2=r:4008000000000000 mx=1f80 => x1=r:3fd5555555555555 mx=1fa0 f=* +divsd_one_third_down: x1=r:3ff0000000000000 x2=r:4008000000000000 mx=3f80 => x1=r:3fd5555555555555 mx=3fa0 f=* +divsd_one_third_up: x1=r:3ff0000000000000 x2=r:4008000000000000 mx=5f80 => x1=r:3fd5555555555556 mx=5fa0 f=* +divsd_one_third_zero: x1=r:3ff0000000000000 x2=r:4008000000000000 mx=7f80 => x1=r:3fd5555555555555 mx=7fa0 f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 2A DIVSS; 1 4.8.4 Table 4-9 +divss_one_third_nearest: x1=s:3f800000 x2=s:40400000 mx=1f80 => x1=s:3eaaaaab mx=1fa0 f=* +divss_one_third_down: x1=s:3f800000 x2=s:40400000 mx=3f80 => x1=s:3eaaaaaa mx=3fa0 f=* +divss_one_third_up: x1=s:3f800000 x2=s:40400000 mx=5f80 => x1=s:3eaaaaab mx=5fa0 f=* +divss_one_third_zero: x1=s:3f800000 x2=s:40400000 mx=7f80 => x1=s:3eaaaaaa mx=7fa0 f=* +@ divsd xmm1, xmm2 + f20f5eca + SDM 2A DIVSD; 1 4.8.4 Table 4-9 +divsd_minus_two_thirds_nearest: x1=r:c000000000000000 x2=r:4008000000000000 mx=1f80 => x1=r:bfe5555555555555 mx=1fa0 f=* +divsd_minus_two_thirds_down: x1=r:c000000000000000 x2=r:4008000000000000 mx=3f80 => x1=r:bfe5555555555556 mx=3fa0 f=* +divsd_minus_two_thirds_up: x1=r:c000000000000000 x2=r:4008000000000000 mx=5f80 => x1=r:bfe5555555555555 mx=5fa0 f=* +divsd_minus_two_thirds_zero: x1=r:c000000000000000 x2=r:4008000000000000 mx=7f80 => x1=r:bfe5555555555555 mx=7fa0 f=* +@ mulsd xmm1, xmm2 + f20f59ca + SDM 2B MULSD; 1 4.8.4 Table 4-9 +mulsd_tenth_squared_nearest: x1=r:3fb999999999999a x2=r:3fb999999999999a mx=1f80 => x1=r:3f847ae147ae147c mx=1fa0 f=* +mulsd_tenth_squared_down: x1=r:3fb999999999999a x2=r:3fb999999999999a mx=3f80 => x1=r:3f847ae147ae147b mx=3fa0 f=* +mulsd_tenth_squared_up: x1=r:3fb999999999999a x2=r:3fb999999999999a mx=5f80 => x1=r:3f847ae147ae147c mx=5fa0 f=* +mulsd_tenth_squared_zero: x1=r:3fb999999999999a x2=r:3fb999999999999a mx=7f80 => x1=r:3f847ae147ae147b mx=7fa0 f=* +@ addsd xmm1, xmm2 + f20f58ca + SDM 2A ADDSD; 1 4.8.4 Table 4-9 +addsd_tenths_nearest: x1=r:3fb999999999999a x2=r:3fc999999999999a mx=1f80 => x1=r:3fd3333333333334 mx=1fa0 f=* +addsd_tenths_down: x1=r:3fb999999999999a x2=r:3fc999999999999a mx=3f80 => x1=r:3fd3333333333333 mx=3fa0 f=* +addsd_tenths_up: x1=r:3fb999999999999a x2=r:3fc999999999999a mx=5f80 => x1=r:3fd3333333333334 mx=5fa0 f=* +addsd_tenths_zero: x1=r:3fb999999999999a x2=r:3fc999999999999a mx=7f80 => x1=r:3fd3333333333333 mx=7fa0 f=* +@ sqrtsd xmm1, xmm2 + f20f51ca + SDM 2B SQRTSD; 1 4.8.4 Table 4-9 +sqrtsd_two_nearest: x2=r:4000000000000000 mx=1f80 => x1=r:3ff6a09e667f3bcd mx=1fa0 f=* +sqrtsd_two_down: x2=r:4000000000000000 mx=3f80 => x1=r:3ff6a09e667f3bcc mx=3fa0 f=* +sqrtsd_two_up: x2=r:4000000000000000 mx=5f80 => x1=r:3ff6a09e667f3bcd mx=5fa0 f=* +sqrtsd_two_zero: x2=r:4000000000000000 mx=7f80 => x1=r:3ff6a09e667f3bcc mx=7fa0 f=* +@ sqrtss xmm1, xmm2 + f30f51ca + SDM 2B SQRTSS; 1 4.8.4 Table 4-9 +sqrtss_three_nearest: x2=s:40400000 mx=1f80 => x1=s:3fddb3d7 mx=1fa0 f=* +sqrtss_three_down: x2=s:40400000 mx=3f80 => x1=s:3fddb3d7 mx=3fa0 f=* +sqrtss_three_up: x2=s:40400000 mx=5f80 => x1=s:3fddb3d8 mx=5fa0 f=* +sqrtss_three_zero: x2=s:40400000 mx=7f80 => x1=s:3fddb3d7 mx=7fa0 f=* +@ subsd xmm1, xmm1 + f20f5cc9 + SDM 2B SUBSD; 1 4.8.3.1 +subsd_exact_zero_sign_nearest: x1=r:3ff0000000000000 mx=1f80 => x1=r:0000000000000000 f=* +subsd_exact_zero_sign_down: x1=r:3ff0000000000000 mx=3f80 => x1=r:8000000000000000 f=* +subsd_exact_zero_sign_up: x1=r:3ff0000000000000 mx=5f80 => x1=r:0000000000000000 f=* +subsd_exact_zero_sign_zero: x1=r:3ff0000000000000 mx=7f80 => x1=r:0000000000000000 f=* +"; + +const FP_OVERFLOW_UNDERFLOW: &str = r" +@ mulss xmm1, xmm2 + f30f59ca + SDM 2B MULSS; 1 4.9.1.4 Table 4-11 +mulss_positive_overflow_nearest: x1=s:7f7fffff x2=s:40000000 mx=1f80 => x1=s:7f800000 mx=1fa8 f=* +mulss_positive_overflow_down: x1=s:7f7fffff x2=s:40000000 mx=3f80 => x1=s:7f7fffff mx=3fa8 f=* +mulss_positive_overflow_up: x1=s:7f7fffff x2=s:40000000 mx=5f80 => x1=s:7f800000 mx=5fa8 f=* +mulss_positive_overflow_zero: x1=s:7f7fffff x2=s:40000000 mx=7f80 => x1=s:7f7fffff mx=7fa8 f=* +mulss_negative_overflow_nearest: x1=s:ff7fffff x2=s:40000000 mx=1f80 => x1=s:ff800000 mx=1fa8 f=* +mulss_negative_overflow_down: x1=s:ff7fffff x2=s:40000000 mx=3f80 => x1=s:ff800000 mx=3fa8 f=* +mulss_negative_overflow_up: x1=s:ff7fffff x2=s:40000000 mx=5f80 => x1=s:ff7fffff mx=5fa8 f=* +mulss_negative_overflow_zero: x1=s:ff7fffff x2=s:40000000 mx=7f80 => x1=s:ff7fffff mx=7fa8 f=* +@ addsd xmm1, xmm2 + f20f58ca + SDM 2A ADDSD; 1 4.9.1.4 Table 4-11 +addsd_overflow_nearest: x1=r:7fefffffffffffff x2=r:7fefffffffffffff mx=1f80 => x1=r:7ff0000000000000 mx=1fa8 f=* +addsd_overflow_down: x1=r:7fefffffffffffff x2=r:7fefffffffffffff mx=3f80 => x1=r:7fefffffffffffff mx=3fa8 f=* +addsd_overflow_up: x1=r:7fefffffffffffff x2=r:7fefffffffffffff mx=5f80 => x1=r:7ff0000000000000 mx=5fa8 f=* +addsd_overflow_zero: x1=r:7fefffffffffffff x2=r:7fefffffffffffff mx=7f80 => x1=r:7fefffffffffffff mx=7fa8 f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 2A ADDSS; 1 4.9.1.4 Table 4-11 +addss_rounds_below_overflow_threshold: x1=s:7f7fffff x2=s:72ffffff => x1=s:7f7fffff mx=1fa0 f=* +addss_rounds_at_overflow_threshold: x1=s:7f7fffff x2=s:73000000 => x1=s:7f800000 mx=1fa8 f=* +@ addss xmm1, xmm2; mulss xmm3, xmm4; divss xmm5, xmm6 + f30f58ca f30f59dc f30f5eee + SDM 1 4.8.3.3 +infinity_arithmetic_is_exact: x1=s:7f800000 x2=s:ff7fffff x3=s:ff800000 x4=s:c0000000 x5=s:3f800000 x6=s:ff800000 => x1=s:7f800000 x3=s:7f800000 x5=s:80000000 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 4.9.1.5; 1 11.5.2.5 +mulss_exact_denormal_sets_no_flags: x1=s:00800000 x2=s:3f000000 => x1=s:00400000 mx=1f80 f=* +mulss_inexact_denormal_nearest: x1=s:00800001 x2=s:3f000000 mx=1f80 => x1=s:00400000 mx=1fb0 f=* +mulss_inexact_denormal_down: x1=s:00800001 x2=s:3f000000 mx=3f80 => x1=s:00400000 mx=3fb0 f=* +mulss_inexact_denormal_up: x1=s:00800001 x2=s:3f000000 mx=5f80 => x1=s:00400001 mx=5fb0 f=* +mulss_inexact_denormal_zero: x1=s:00800001 x2=s:3f000000 mx=7f80 => x1=s:00400000 mx=7fb0 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 4.9.1.5; 1 11.5.2.5; 1 4.9.1.2 +mulss_min_denormal_halved_nearest: x1=s:00000001 x2=s:3f000000 mx=1f80 => x1=s:00000000 mx=1fb2 f=* +mulss_min_denormal_halved_down: x1=s:00000001 x2=s:3f000000 mx=3f80 => x1=s:00000000 mx=3fb2 f=* +mulss_min_denormal_halved_up: x1=s:00000001 x2=s:3f000000 mx=5f80 => x1=s:00000001 mx=5fb2 f=* +mulss_min_denormal_halved_zero: x1=s:00000001 x2=s:3f000000 mx=7f80 => x1=s:00000000 mx=7fb2 f=* +mulss_negative_min_denormal_halved_nearest: x1=s:80000001 x2=s:3f000000 mx=1f80 => x1=s:80000000 mx=1fb2 f=* +mulss_negative_min_denormal_halved_down: x1=s:80000001 x2=s:3f000000 mx=3f80 => x1=s:80000001 mx=3fb2 f=* +mulss_negative_min_denormal_halved_up: x1=s:80000001 x2=s:3f000000 mx=5f80 => x1=s:80000000 mx=5fb2 f=* +mulss_negative_min_denormal_halved_zero: x1=s:80000001 x2=s:3f000000 mx=7f80 => x1=s:80000000 mx=7fb2 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 4.9.1.5; 1 11.5.2.5 Table 4-12 note 1 +mulss_tininess_is_after_rounding_not_tiny_nearest: x1=s:20000400 x2=s:1ffff800 mx=1f80 => x1=s:00800000 mx=1fa0 f=* +mulss_tininess_is_after_rounding_not_tiny_down: x1=s:20000400 x2=s:1ffff800 mx=3f80 => x1=s:007fffff mx=3fb0 f=* +mulss_tininess_is_after_rounding_not_tiny_up: x1=s:20000400 x2=s:1ffff800 mx=5f80 => x1=s:00800000 mx=5fa0 f=* +mulss_tininess_is_after_rounding_not_tiny_zero: x1=s:20000400 x2=s:1ffff800 mx=7f80 => x1=s:007fffff mx=7fb0 f=* +mulss_tiny_rounds_up_to_min_normal_nearest: x1=s:00800000 x2=s:3f7fffff mx=1f80 => x1=s:00800000 mx=1fb0 f=* +mulss_tiny_rounds_up_to_min_normal_down: x1=s:00800000 x2=s:3f7fffff mx=3f80 => x1=s:007fffff mx=3fb0 f=* +mulss_tiny_rounds_up_to_min_normal_up: x1=s:00800000 x2=s:3f7fffff mx=5f80 => x1=s:00800000 mx=5fb0 f=* +mulss_tiny_rounds_up_to_min_normal_zero: x1=s:00800000 x2=s:3f7fffff mx=7f80 => x1=s:007fffff mx=7fb0 f=* +@ subsd xmm1, xmm2 + f20f5cca + SDM 1 4.9.1.5; 1 11.5.2.5 +subsd_exact_denormal_result: x1=r:0010000000000001 x2=r:0010000000000000 => x1=r:0000000000000001 mx=1f80 f=* +@ divsd xmm1, xmm2 + f20f5eca + SDM 1 4.9.1.5; 1 11.5.2.5 +divsd_min_normal_by_three: x1=r:0010000000000000 x2=r:4008000000000000 => x1=r:0005555555555555 mx=1fb0 f=* +"; + +const FP_FTZ_DAZ_DENORMALS: &str = r" +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 10.2.3.3; 1 11.5.2.5 +ftz_flushes_inexact_tiny: x1=s:00800001 x2=s:3f000000 mx=9f80 => x1=s:00000000 mx=9fb0 f=* +ftz_flush_keeps_sign_of_true_result: x1=s:80800001 x2=s:3f000000 mx=9f80 => x1=s:80000000 mx=9fb0 f=* +ftz_round_up_still_flushes_to_zero: x1=s:00800001 x2=s:3f000000 mx=df80 => x1=s:00000000 mx=dfb0 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 10.2.3.3; 1 11.5.2.5; 1 11.5.2.2 +ftz_does_not_flush_denormal_operand: x1=s:00400000 x2=s:40800000 mx=9f80 => x1=s:01000000 mx=9f82 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 10.2.3.3; 1 11.5.2.5 +ftz_result_rounded_to_min_normal_is_kept: x1=s:20000400 x2=s:1ffff800 mx=9f80 => x1=s:00800000 mx=9fa0 f=* +ftz_tiny_that_would_round_to_min_normal_is_flushed: x1=s:00800000 x2=s:3f7fffff mx=9f80 => x1=s:00000000 mx=9fb0 f=* +@ movaps xmm1, xmm2; andps xmm1, xmm2 + 0f28ca 0f54ca + SDM 1 10.2.3.3 +ftz_ignored_by_moves_and_logic: x2=d:1,80000001,00400000,7f800001 mx=9fc0 => x1=d:1,80000001,00400000,7f800001 f=* +@ mulss xmm1, xmm2 + !f30f59ca + SDM 1 10.2.3.3; 1 4.9.1.5 +ftz_ignored_when_underflow_unmasked: x1=s:00800000 x2=s:3f000000 mx=9780 => mx=9790 f=* ! XM +@ mulsd xmm1, xmm2 + f20f59ca + SDM 1 10.2.3.3; 1 11.5.2.5 +ftz_exact_tiny_result_is_zero: x1=r:8010000000000000 x2=r:3fe0000000000000 mx=9f80 => x1=r:8000000000000000 mx=? f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 1 10.2.3.4 +daz_add_denormals: x1=s:00000001 x2=s:007fffff mx=1fc0 => x1=s:00000000 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 10.2.3.4 +daz_keeps_operand_sign: x1=s:80000001 x2=s:3f800000 mx=1fc0 => x1=s:80000000 f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 1 10.2.3.4; 1 11.5.2.3 +daz_divide_by_denormal_is_divide_by_zero: x1=s:3f800000 x2=s:80000001 mx=1fc0 => x1=s:ff800000 mx=1fc4 f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 1 10.2.3.4; 1 11.5.2.1 +daz_denormal_over_denormal_is_invalid: x1=s:00000001 x2=s:00000001 mx=1fc0 => x1=s:ffc00000 mx=1fc1 f=* +@ mulsd xmm1, xmm2 + f20f59ca + SDM 1 10.2.3.4; 1 11.5.2.1 +daz_infinity_times_denormal_is_invalid: x1=r:7ff0000000000000 x2=r:0000000000000001 mx=1fc0 => x1=r:fff8000000000000 mx=1fc1 f=* +@ sqrtss xmm1, xmm2 + f30f51ca + SDM 1 10.2.3.4; 2B SQRTSS +daz_sqrt_negative_denormal_is_negative_zero: x2=s:80000001 mx=1fc0 => x1=s:80000000 f=* +@ comiss xmm1, xmm2 + 0f2fca + SDM 1 10.2.3.4; 2A COMISS +daz_compare_denormal_equals_zero: x1=s:00000001 x2=s:80000000 mx=1fc0 => f=cpaZso +@ minss xmm1, xmm2 + f30f5dca + SDM 1 10.2.3.4; 2B MINSS +daz_min_returns_second_operand_as_zero: x1=s:00000001 x2=s:80000001 mx=1fc0 => x1=s:80000000 f=* +@ cvtss2si eax, xmm1 + f30f2dc1 + SDM 1 10.2.3.4 +daz_cvtss2si_round_up_is_zero: x1=s:00000001 mx=5fc0 => rax=0 f=* +@ cvtss2sd xmm1, xmm2 + f30f5aca + SDM 1 10.2.3.4 +daz_cvtss2sd_is_zero: x2=s:80000001 mx=1fc0 => x1=r:8000000000000000 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 10.2.3.4 +daz_does_not_flush_results: x1=s:00800000 x2=s:3f000000 mx=1fc0 => x1=s:00400000 f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 1 4.9.1.2; 1 11.5.2.2 +denormal_operand_sets_de: x1=s:00000001 x2=s:00000001 => x1=s:00000002 mx=1f82 f=* +denormal_add_to_normal_sets_de_pe: x1=s:3f800000 x2=s:00000001 => x1=s:3f800000 mx=1fa2 f=* +denormal_sum_to_min_normal_is_exact: x1=s:007fffff x2=s:00000001 => x1=s:00800000 mx=1f82 f=* +@ cvtss2si eax, xmm1 + f30f2dc1 + SDM 1 11.5.2.2 +cvtss2si_denormal_no_de: x1=s:00000001 => rax=0 mx=1fa0 f=* +@ cvtss2si eax, xmm1 + f30f2dc1 + SDM 1 11.5.2.2; 2A CVTSS2SI +cvtss2si_denormal_round_up_is_one: x1=s:00000001 mx=5f80 => rax=1 mx=5fa0 f=* +@ cvtss2sd xmm1, xmm2 + f30f5aca + SDM 1 4.9.1.2; 1 11.5.2.2 +cvtss2sd_denormal_is_exact_and_sets_de: x2=s:00000001 => x1=r:36a0000000000000 mx=1f82 f=* +@ rcpss xmm1, xmm2; rsqrtss xmm3, xmm2 + f30f53ca f30f52da + SDM 1 11.5.2.2 +rcpss_rsqrtss_signal_nothing: x2=s:7f800001 => x1=s:7fc00001 x3=s:7fc00001 mx=1f80 f=* +@ rcpps xmm1, xmm2; rsqrtps xmm3, xmm2 + 0f53ca 0f52da + SDM 2B RCPPS Table (0, inf) +rcpps_special_values: x2=d:00000000,80000000,7f800000,7f800000 => x1=d:7f800000,ff800000,00000000,00000000 x3=d:7f800000,ff800000,00000000,00000000 mx=1f80 f=* +@ rcpss xmm1, xmm2; mulss xmm1, xmm2; subss xmm1, xmm3; andps xmm1, xmm4; comiss xmm1, xmm5 + f30f53ca f30f59ca f30f5ccb 0f54cc 0f2fcd + SDM 2B RCPSS ( +rcpss_relative_error_bound: x2=s:40400000 x3=s:3f800000 x4=d:7fffffff,0,0,0 x5=d:39c01000,0,0,0 => x1=? mx=? f=Cpz +@ divss xmm1, xmm2 + f30f5eca + SDM 1 D.4.2.3 Table D-14 (DE not asserted; see the undefined list) +denormal_divided_by_zero_sets_ze: x1=s:00000001 x2=s:80000000 => x1=s:ff800000 mx=~2:1f84 f=* +"; + +const FP_NAN_INVALID_ZERO_DIVIDE: &str = r" +@ addss xmm1, xmm2 + f30f58ca + SDM 1 4.8.3.5 Table 4-8 +addss_qnan_qnan: x1=s:7fc00123 x2=s:ffc00456 => x1=s:7fc00123 mx=1f80 f=* +addss_qnan_snan: x1=s:7fc00123 x2=s:ff800abc => x1=s:7fc00123 mx=1f81 f=* +addss_snan_qnan: x1=s:7f800789 x2=s:ffc00456 => x1=s:7fc00789 mx=1f81 f=* +addss_snan_snan: x1=s:7f800789 x2=s:ff800abc => x1=s:7fc00789 mx=1f81 f=* +addss_qnan_value: x1=s:ffc00456 x2=s:3f800000 => x1=s:ffc00456 mx=1f80 f=* +addss_value_qnan: x1=s:3f800000 x2=s:ffc00456 => x1=s:ffc00456 mx=1f80 f=* +addss_snan_value: x1=s:ff800abc x2=s:3f800000 => x1=s:ffc00abc mx=1f81 f=* +addss_value_snan: x1=s:3f800000 x2=s:7f800789 => x1=s:7fc00789 mx=1f81 f=* +@ subsd xmm1, xmm2 + f20f5cca + SDM 1 4.8.3.5 Table 4-8 +subsd_qnan_snan_returns_first_operand: x1=r:7ff8000000000123 x2=r:fff0000000000456 => x1=r:7ff8000000000123 mx=1f81 f=* +subsd_two_qnans_returns_first_operand: x1=r:fff8000000000123 x2=r:7ff8000000000456 => x1=r:fff8000000000123 f=* +@ mulsd xmm1, xmm2 + f20f59ca + SDM 1 4.8.3.5 Table 4-8 +mulsd_qnan_snan_returns_first_operand: x1=r:7ff8000000000123 x2=r:fff0000000000456 => x1=r:7ff8000000000123 mx=1f81 f=* +mulsd_two_qnans_returns_first_operand: x1=r:fff8000000000123 x2=r:7ff8000000000456 => x1=r:fff8000000000123 f=* +@ divsd xmm1, xmm2 + f20f5eca + SDM 1 4.8.3.5 Table 4-8 +divsd_qnan_snan_returns_first_operand: x1=r:7ff8000000000123 x2=r:fff0000000000456 => x1=r:7ff8000000000123 mx=1f81 f=* +divsd_two_qnans_returns_first_operand: x1=r:fff8000000000123 x2=r:7ff8000000000456 => x1=r:fff8000000000123 f=* +@ sqrtss xmm1, xmm2 + f30f51ca + SDM 1 4.8.3.5 Table 4-8 +sqrtss_snan_is_quieted: x2=s:ff800abc => x1=s:ffc00abc mx=1f81 f=* +@ sqrtsd xmm1, xmm2 + f20f51ca + SDM 1 4.8.3.5 Table 4-8 +sqrtsd_negative_qnan_passes_through: x2=r:fff8000000000abc => x1=r:fff8000000000abc f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 1 4.9.2 +qnan_over_zero_is_not_divide_by_zero: x1=s:7fc00123 x2=s:00000000 => x1=s:7fc00123 f=* +snan_over_zero_is_invalid_only: x1=s:7f800789 x2=s:00000000 => x1=s:7fc00789 mx=1f81 f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 1 4.9.2 (priority 2 before 4) +qnan_with_denormal_sets_no_de: x1=s:7fc00123 x2=s:00000001 => x1=s:7fc00123 f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 1 4.9.2 (priority 1 before 4) +snan_with_denormal_sets_only_ie: x1=s:00000001 x2=s:7f800789 => x1=s:7fc00789 mx=1f81 f=* +@ subss xmm1, xmm2 + f30f5cca + SDM 1 11.5.2.1 Table 11-1; 1 4.8.3.7 +inf_minus_inf_is_default_nan: x1=s:7f800000 x2=s:7f800000 => x1=s:ffc00000 mx=1f81 f=* +@ addss xmm1, xmm2 + f30f58ca + SDM 1 11.5.2.1 Table 11-1; 1 4.8.3.7 +inf_plus_neg_inf_is_default_nan: x1=s:7f800000 x2=s:ff800000 => x1=s:ffc00000 mx=1f81 f=* +@ mulss xmm1, xmm2 + f30f59ca + SDM 1 11.5.2.1 Table 11-1; 1 4.8.3.7 +zero_times_inf_is_default_nan: x1=s:80000000 x2=s:7f800000 => x1=s:ffc00000 mx=1f81 f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 1 11.5.2.1 Table 11-1; 1 4.8.3.7 +zero_over_zero_is_default_nan: x1=s:00000000 x2=s:80000000 => x1=s:ffc00000 mx=1f81 f=* +inf_over_inf_is_default_nan: x1=s:ff800000 x2=s:7f800000 => x1=s:ffc00000 mx=1f81 f=* +@ sqrtsd xmm1, xmm2 + f20f51ca + SDM 1 11.5.2.1 Table 11-1; 1 4.8.3.7 +sqrtsd_negative_is_default_nan: x2=r:bff0000000000000 => x1=r:fff8000000000000 mx=1f81 f=* +@ sqrtsd xmm1, xmm2 + f20f51ca + SDM 2B SQRTSD; 1 11.5.2.1 (except zero) +sqrtsd_negative_zero_is_negative_zero: x2=r:8000000000000000 => x1=r:8000000000000000 f=* +@ divss xmm1, xmm2; divsd xmm3, xmm4 + f30f5eca f20f5edc + SDM 1 4.9.1.3 +divide_by_zero_signs: x1=s:3f800000 x2=s:80000000 x3=r:c000000000000000 x4=r:8000000000000000 => x1=s:ff800000 x3=r:7ff0000000000000 mx=1f84 f=* +@ divss xmm1, xmm2 + f30f5eca + SDM 1 11.5.2.3 (finite non-zero operand only) +infinity_over_zero_is_exact: x1=s:7f800000 x2=s:80000000 => x1=s:ff800000 f=* +"; + +const FP_MIN_MAX_COMPARE: &str = r" +@ minss xmm1, xmm2; maxss xmm3, xmm4; minss xmm5, xmm6; maxss xmm7, xmm8 + f30f5dca f30f5fdc f30f5dee f3410f5ff8 + SDM 2B MINSS; 2B MAXSS; 1 11.5.2.1 Table 11-1 +min_max_zeros_return_second: x1=s:00000000 x2=s:80000000 x3=s:80000000 x4=s:00000000 x5=s:80000000 x6=s:00000000 x7=s:00000000 x8=s:80000000 => x1=s:80000000 x3=s:00000000 x5=s:00000000 x7=s:80000000 f=* +@ minss xmm1, xmm2 + f30f5dca + SDM 2B MINSS; 2B MAXSS; 1 11.5.2.1 Table 11-1 +minss_qnan_first_returns_second: x1=s:7fc00123 x2=s:3f800000 => x1=s:3f800000 mx=1f81 f=* +@ maxss xmm1, xmm2 + f30f5fca + SDM 2B MINSS; 2B MAXSS; 1 11.5.2.1 Table 11-1 +maxss_qnan_second_returns_second: x1=s:3f800000 x2=s:ffc00456 => x1=s:ffc00456 mx=1f81 f=* +maxss_snan_second_is_not_quieted: x1=s:7fc00123 x2=s:7f800789 => x1=s:7f800789 mx=1f81 f=* +@ minpd xmm1, xmm2; maxpd xmm3, xmm2 + 660f5dca 660f5fda + SDM 2B MINPD; 2B MAXPD; 1 11.5.2.1 Table 11-1 +minpd_lanes: x1=q:3ff0000000000000,7ff8000000000001 x2=q:bff0000000000000,4000000000000000 x3=q:3ff0000000000000,7ff0000000000000 => x1=q:bff0000000000000,4000000000000000 x3=q:3ff0000000000000,7ff0000000000000 mx=1f81 f=* +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_greater: x1=s:40000000 x2=s:3f800000 => f=cpazso +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_greater: x1=s:40000000 x2=s:3f800000 => f=cpazso +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_less: x1=s:3f800000 x2=s:40000000 => f=Cpazso +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_less: x1=s:3f800000 x2=s:40000000 => f=Cpazso +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_equal: x1=s:3f800000 x2=s:3f800000 => f=cpaZso +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_equal: x1=s:3f800000 x2=s:3f800000 => f=cpaZso +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_zeros_equal: x1=s:00000000 x2=s:80000000 => f=cpaZso +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_zeros_equal: x1=s:00000000 x2=s:80000000 => f=cpaZso +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_infinities: x1=s:ff800000 x2=s:7f800000 => f=Cpazso +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_infinities: x1=s:ff800000 x2=s:7f800000 => f=Cpazso +@ comiss xmm1, xmm2 + 0f2fca + SDM 2A COMISS; 2B UCOMISS +comiss_qnan_sets_ie: x1=s:7fc00123 x2=s:3f800000 => f=CPaZso mx=1f81 +@ ucomiss xmm1, xmm2 + 0f2eca + SDM 2A COMISS; 2B UCOMISS +ucomiss_qnan_sets_nothing: x1=s:7fc00123 x2=s:3f800000 => f=CPaZso +ucomiss_snan_sets_ie: x1=s:3f800000 x2=s:7f800789 => f=CPaZso mx=1f81 +@ ucomisd xmm1, xmm2 + 660f2eca + SDM 2A COMISD; 2B UCOMISD; 1 4.9.1.2; 1 11.5.2.2 +ucomisd_denormal_sets_de: x1=r:0000000000000001 x2=r:0000000000000000 => f=cpazso mx=1f82 +@ comisd xmm1, xmm2 + !660f2fca + SDM 2A COMISD (EFLAGS not updated) +comisd_qnan_unmasked_invalid_keeps_eflags: x1=r:7ff8000000000001 x2=r:3ff0000000000000 mx=1f00 => mx=1f01 f=* ! XM +@ cmpps xmm1, xmm2, 0 + 0fc2ca00 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_eq_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:0,ffffffff,0,0 mx=1f80 f=* +@ cmpsd xmm1, xmm2, 0 + f20fc2ca00 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_eq_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:0000000000000000 mx=1f81 f=* +@ cmpps xmm1, xmm2, 1 + 0fc2ca01 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_lt_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:ffffffff,0,0,0 mx=1f81 f=* +@ cmpsd xmm1, xmm2, 1 + f20fc2ca01 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_lt_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:0000000000000000 mx=1f81 f=* +@ cmpps xmm1, xmm2, 2 + 0fc2ca02 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_le_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:ffffffff,ffffffff,0,0 mx=1f81 f=* +@ cmpsd xmm1, xmm2, 2 + f20fc2ca02 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_le_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:0000000000000000 mx=1f81 f=* +@ cmpps xmm1, xmm2, 3 + 0fc2ca03 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_unord_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:0,0,0,ffffffff mx=1f80 f=* +@ cmpsd xmm1, xmm2, 3 + f20fc2ca03 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_unord_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:ffffffffffffffff mx=1f81 f=* +@ cmpps xmm1, xmm2, 4 + 0fc2ca04 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_neq_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:ffffffff,0,ffffffff,ffffffff mx=1f80 f=* +@ cmpsd xmm1, xmm2, 4 + f20fc2ca04 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_neq_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:ffffffffffffffff mx=1f81 f=* +@ cmpps xmm1, xmm2, 5 + 0fc2ca05 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_nlt_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:0,ffffffff,ffffffff,ffffffff mx=1f81 f=* +@ cmpsd xmm1, xmm2, 5 + f20fc2ca05 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_nlt_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:ffffffffffffffff mx=1f81 f=* +@ cmpps xmm1, xmm2, 6 + 0fc2ca06 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_nle_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:0,0,ffffffff,ffffffff mx=1f81 f=* +@ cmpsd xmm1, xmm2, 6 + f20fc2ca06 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_nle_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:ffffffffffffffff mx=1f81 f=* +@ cmpps xmm1, xmm2, 7 + 0fc2ca07 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpps_ord_less_equal_greater_qnan: x1=d:3f800000,80000000,40000000,7fc00123 x2=d:40000000,00000000,3f800000,3f800000 => x1=d:ffffffff,ffffffff,ffffffff,0 mx=1f80 f=* +@ cmpsd xmm1, xmm2, 7 + f20fc2ca07 + SDM 2A CMPSS Table 3-1 predicates 0-7; 1 11.5.2.1 +cmpsd_ord_snan_always_invalid: x1=r:3ff0000000000000 x2=r:7ff0000000000001 => x1=r:0000000000000000 mx=1f81 f=* +"; + +const FP_CONVERSIONS: &str = r" +@ cvtss2si eax, xmm1 + f30f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtss2si_3f000000_nearest: x1=s:3f000000 rax=ffffffffffffffff mx=1f80 => rax=0 mx=1fa0 f=* +cvtss2si_3f000000_down: x1=s:3f000000 rax=ffffffffffffffff mx=3f80 => rax=0 mx=3fa0 f=* +cvtss2si_3f000000_up: x1=s:3f000000 rax=ffffffffffffffff mx=5f80 => rax=1 mx=5fa0 f=* +cvtss2si_3f000000_zero: x1=s:3f000000 rax=ffffffffffffffff mx=7f80 => rax=0 mx=7fa0 f=* +cvtss2si_3fc00000_nearest: x1=s:3fc00000 rax=ffffffffffffffff mx=1f80 => rax=2 mx=1fa0 f=* +cvtss2si_3fc00000_down: x1=s:3fc00000 rax=ffffffffffffffff mx=3f80 => rax=1 mx=3fa0 f=* +cvtss2si_3fc00000_up: x1=s:3fc00000 rax=ffffffffffffffff mx=5f80 => rax=2 mx=5fa0 f=* +cvtss2si_3fc00000_zero: x1=s:3fc00000 rax=ffffffffffffffff mx=7f80 => rax=1 mx=7fa0 f=* +cvtss2si_40200000_nearest: x1=s:40200000 rax=ffffffffffffffff mx=1f80 => rax=2 mx=1fa0 f=* +cvtss2si_40200000_down: x1=s:40200000 rax=ffffffffffffffff mx=3f80 => rax=2 mx=3fa0 f=* +cvtss2si_40200000_up: x1=s:40200000 rax=ffffffffffffffff mx=5f80 => rax=3 mx=5fa0 f=* +cvtss2si_40200000_zero: x1=s:40200000 rax=ffffffffffffffff mx=7f80 => rax=2 mx=7fa0 f=* +cvtss2si_bf000000_nearest: x1=s:bf000000 rax=ffffffffffffffff mx=1f80 => rax=0 mx=1fa0 f=* +cvtss2si_bf000000_down: x1=s:bf000000 rax=ffffffffffffffff mx=3f80 => rax=ffffffff mx=3fa0 f=* +cvtss2si_bf000000_up: x1=s:bf000000 rax=ffffffffffffffff mx=5f80 => rax=0 mx=5fa0 f=* +cvtss2si_bf000000_zero: x1=s:bf000000 rax=ffffffffffffffff mx=7f80 => rax=0 mx=7fa0 f=* +cvtss2si_bfc00000_nearest: x1=s:bfc00000 rax=ffffffffffffffff mx=1f80 => rax=fffffffe mx=1fa0 f=* +cvtss2si_bfc00000_down: x1=s:bfc00000 rax=ffffffffffffffff mx=3f80 => rax=fffffffe mx=3fa0 f=* +cvtss2si_bfc00000_up: x1=s:bfc00000 rax=ffffffffffffffff mx=5f80 => rax=ffffffff mx=5fa0 f=* +cvtss2si_bfc00000_zero: x1=s:bfc00000 rax=ffffffffffffffff mx=7f80 => rax=ffffffff mx=7fa0 f=* +@ cvttss2si eax, xmm1; cvttss2si rcx, xmm2 + f30f2cc1 f3480f2cca + SDM 2A CVTTSS2SI; 1 4.8.4.2 +cvttss2si_truncates_regardless_of_rc: x1=s:3fffffff x2=s:bfffffff mx=5f80 => rax=1 rcx=ffffffffffffffff mx=5fa0 f=* +@ cvtss2si eax, xmm1 + f30f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtss2si_two_pow_31_is_indefinite: x1=s:4f000000 rax=ffffffffffffffff => rax=80000000 mx=1f81 f=* +cvtss2si_minus_two_pow_31_is_exact: x1=s:cf000000 => rax=80000000 f=* +@ cvtsd2si eax, xmm1 + f20f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtsd2si_rounds_out_of_range: x1=r:41dfffffffe00000 => rax=80000000 mx=1f81 f=* +@ cvttsd2si eax, xmm1 + f20f2cc1 + SDM 2A CVTTSD2SI +cvttsd2si_same_value_is_in_range: x1=r:41dfffffffe00000 => rax=7fffffff mx=1fa0 f=* +@ cvtsd2si eax, xmm1 + f20f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtsd2si_negative_tie_in_range: x1=r:c1e0000000100000 => rax=80000000 mx=1fa0 f=* +cvtsd2si_negative_round_down_out_of_range: x1=r:c1e0000000100000 mx=3f80 => rax=80000000 mx=3f81 f=* +@ cvttsd2si eax, xmm1 + f20f2cc1 + SDM 2A CVTTSD2SI +cvttsd2si_negative_fraction_in_range: x1=r:c1e00000001fffff => rax=80000000 mx=1fa0 f=* +@ cvttsd2si eax, xmm1; cvttsd2si rcx, xmm1 + f20f2cc1 f2480f2cc9 + SDM 2A CVTTSD2SI +cvttsd2si_minus_two_pow_31_minus_one: x1=r:c1e0000000200000 => rax=80000000 rcx=ffffffff7fffffff mx=1f81 f=* +@ cvtsd2si rax, xmm1 + f2480f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtsd2si64_two_pow_63_is_indefinite: x1=r:43e0000000000000 => rax=8000000000000000 mx=1f81 f=* +@ cvttsd2si rax, xmm1 + f2480f2cc1 + SDM 2A CVTTSD2SI +cvttsd2si64_largest_below_two_pow_63: x1=r:43dfffffffffffff => rax=7ffffffffffffc00 f=* +@ cvtsd2si rax, xmm1 + f2480f2dc1 + SDM 2A CVTSS2SI; 2A CVTSD2SI; 1 4.8.4 +cvtsd2si64_minus_two_pow_63_exact: x1=r:c3e0000000000000 => rax=8000000000000000 f=* +@ cvttss2si rax, xmm1 + f3480f2cc1 + SDM 1 11.5.2.1 Table 11-1 +cvttss2si_qnan_is_indefinite: x1=s:7fc00123 => rax=8000000000000000 mx=1f81 f=* +@ cvtsd2si eax, xmm1 + f20f2dc1 + SDM 1 11.5.2.1 Table 11-1 +cvtsd2si_infinity_is_indefinite: x1=r:7ff0000000000000 rax=ffffffffffffffff => rax=80000000 mx=1f81 f=* +@ cvtsi2ss xmm1, eax + f30f2ac8 + SDM 2A CVTSI2SS; 1 4.8.4 Table 4-9 +cvtsi2ss_16777217_nearest: rax=1000001 mx=1f80 => x1=s:4b800000 mx=1fa0 f=* +cvtsi2ss_16777217_down: rax=1000001 mx=3f80 => x1=s:4b800000 mx=3fa0 f=* +cvtsi2ss_16777217_up: rax=1000001 mx=5f80 => x1=s:4b800001 mx=5fa0 f=* +cvtsi2ss_16777217_zero: rax=1000001 mx=7f80 => x1=s:4b800000 mx=7fa0 f=* +cvtsi2ss_minus_16777219_nearest: rax=12345678fefffffd mx=1f80 => x1=s:cb800002 mx=1fa0 f=* +cvtsi2ss_minus_16777219_down: rax=12345678fefffffd mx=3f80 => x1=s:cb800002 mx=3fa0 f=* +cvtsi2ss_minus_16777219_up: rax=12345678fefffffd mx=5f80 => x1=s:cb800001 mx=5fa0 f=* +cvtsi2ss_minus_16777219_zero: rax=12345678fefffffd mx=7f80 => x1=s:cb800001 mx=7fa0 f=* +@ cvtsi2sd xmm1, rax + f2480f2ac8 + SDM 2A CVTSI2SD; 1 4.8.4 Table 4-9 +cvtsi2sd64_two_pow_53_plus_one_nearest: rax=20000000000001 mx=1f80 => x1=r:4340000000000000 mx=1fa0 f=* +cvtsi2sd64_two_pow_53_plus_one_down: rax=20000000000001 mx=3f80 => x1=r:4340000000000000 mx=3fa0 f=* +cvtsi2sd64_two_pow_53_plus_one_up: rax=20000000000001 mx=5f80 => x1=r:4340000000000001 mx=5fa0 f=* +cvtsi2sd64_two_pow_53_plus_one_zero: rax=20000000000001 mx=7f80 => x1=r:4340000000000000 mx=7fa0 f=* +@ cvtsi2ss xmm1, rax + f3480f2ac8 + SDM 2A CVTSI2SS; 1 4.8.4 Table 4-9 +cvtsi2ss64_int64_max_nearest: rax=7fffffffffffffff mx=1f80 => x1=s:5f000000 mx=1fa0 f=* +cvtsi2ss64_int64_max_down: rax=7fffffffffffffff mx=3f80 => x1=s:5effffff mx=3fa0 f=* +cvtsi2ss64_int64_max_up: rax=7fffffffffffffff mx=5f80 => x1=s:5f000000 mx=5fa0 f=* +cvtsi2ss64_int64_max_zero: rax=7fffffffffffffff mx=7f80 => x1=s:5effffff mx=7fa0 f=* +@ cvtsi2sd xmm1, eax + f20f2ac8 + SDM 2A CVTSI2SD +cvtsi2sd32_min_is_exact: rax=80000000 => x1=r:c1e0000000000000 f=* +@ cvtsi2sd xmm1, rax + f2480f2ac8 + SDM 2A CVTSI2SD +cvtsi2sd_zero_is_positive_zero_in_round_down: rax=0 mx=3f80 => x1=r:0000000000000000 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 2A CVTSD2SS; 1 4.8.4 Table 4-9 +cvtsd2ss_pi_nearest: x2=r:400921fb54442d18 mx=1f80 => x1=s:40490fdb mx=1fa0 f=* +cvtsd2ss_pi_down: x2=r:400921fb54442d18 mx=3f80 => x1=s:40490fda mx=3fa0 f=* +cvtsd2ss_pi_up: x2=r:400921fb54442d18 mx=5f80 => x1=s:40490fdb mx=5fa0 f=* +cvtsd2ss_pi_zero: x2=r:400921fb54442d18 mx=7f80 => x1=s:40490fda mx=7fa0 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 2A CVTSD2SS; 1 4.9.1.4 Table 4-11 +cvtsd2ss_overflow: x2=r:c7f0000000000000 => x1=s:ff800000 mx=1fa8 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 1 4.9.1.5; 1 11.5.2.5 +cvtsd2ss_exact_denormal: x2=r:3800000000000000 => x1=s:00400000 mx=1f80 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 1 10.2.3.3; 1 11.5.2.5 +cvtsd2ss_ftz_tiny: x2=r:b690000000000001 mx=9f80 => x1=s:80000000 mx=9fb0 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 1 4.9.1.2; 1 11.5.2.2; 1 4.9.1.5; 1 11.5.2.5 +cvtsd2ss_double_denormal_sets_de: x2=r:0000000000000001 => x1=s:00000000 mx=1fb2 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 1 D.4.2.2 Table D-12 +cvtsd2ss_snan_is_quieted: x2=r:7ff0000020000000 => x1=s:7fc00001 mx=1f81 f=* +@ cvtss2sd xmm1, xmm2 + f30f5aca + SDM 1 D.4.2.2 Table D-11 +cvtss2sd_snan_is_quieted: x2=s:ff800001 => x1=r:fff8000020000000 mx=1f81 f=* +@ cvtpd2ps xmm1, xmm2 + 660f5aca + SDM 2A CVTPD2PS +cvtpd2ps_zeroes_upper_half: x2=q:3ff0000000000000,c000000000000000 => x1=d:3f800000,c0000000,0,0 f=* +@ cvtps2pd xmm1, xmm2 + 0f5aca + SDM 2A CVTPS2PD +cvtps2pd_uses_low_pair: x2=d:3f800000,c0000000,7f800001,00000001 => x1=q:3ff0000000000000,c000000000000000 mx=1f80 f=* +@ cvtdq2ps xmm1, xmm2 + 0f5bca + SDM 2A CVTDQ2PS +cvtdq2ps_rounds: x2=d:1000001,80000000,7fffffff,ffffffff => x1=d:4b800000,cf000000,4f000000,bf800000 mx=1fa0 f=* +@ cvtdq2pd xmm1, xmm2 + f30fe6ca + SDM 2A CVTDQ2PD +cvtdq2pd_is_exact: x2=d:80000000,7fffffff,1,2 => x1=q:c1e0000000000000,41dfffffffc00000 f=* +@ cvtps2dq xmm1, xmm2 + 660f5bca + SDM 2A CVTPS2DQ +cvtps2dq_mixed: x2=d:40200000,4f000000,7fc00123,bfc00000 => x1=d:2,80000000,80000000,fffffffe mx=1fa1 f=* +@ cvttps2dq xmm1, xmm2 + f30f5bca + SDM 2A CVTTPS2DQ +cvttps2dq_mixed: x2=d:bfc00000,cf000000,ff800000,4effffff => x1=d:ffffffff,80000000,80000000,7fffff80 mx=1fa1 f=* +@ cvtpd2dq xmm1, xmm2 + f20fe6ca + SDM 2A CVTPD2DQ +cvtpd2dq_zeroes_upper_half: x2=q:4004000000000000,c004000000000000 => x1=d:2,fffffffe,0,0 mx=1fa0 f=* +@ cvttpd2dq xmm1, xmm2 + 660fe6ca + SDM 2A CVTTPD2DQ +cvttpd2dq_zeroes_upper_half: x2=q:400fffffffffffff,c1e0000000200000 => x1=d:3,80000000,0,0 mx=1fa1 f=* +@ cvtsd2ss xmm1, xmm2 + f20f5aca + SDM 1 D.4.2.2 Table D-12 +cvtsd2ss_qnan_payload_is_truncated: x2=r:fffc0000ffffffff => x1=s:ffe00007 f=* +@ cvtss2sd xmm1, xmm2 + f30f5aca + SDM 1 D.4.2.2 Table D-11 +cvtss2sd_qnan_payload_is_extended: x2=s:7fc00001 => x1=r:7ff8000020000000 f=* +"; + +const FP_PACKED_AND_STICKY: &str = r" +@ mulps xmm1, xmm2 + 0f59ca + SDM 1 11.5.3.1 Figure 11-9 +mulps_ors_lane_flags: x1=d:00400000,3f800000,7f7fffff,00800001 x2=d:40800000,40000000,40000000,3f000000 => x1=d:01000000,40000000,7f800000,00400000 mx=1fba f=* +@ addps xmm1, xmm2 + 0f58ca + SDM 2A ADDPS +addps_lanes_are_independent: x1=d:3f800000,bf800000,7f800000,00000000 x2=d:3f800000,3f800000,3f800000,80000000 => x1=d:40000000,00000000,7f800000,00000000 f=* +@ divpd xmm1, xmm2 + 660f5eca + SDM 2A DIVPD +divpd_mixed_flags: x1=q:3ff0000000000000,0 x2=q:0,0 => x1=q:7ff0000000000000,fff8000000000000 mx=1f85 f=* +@ sqrtps xmm1, xmm2 + 0f51ca + SDM 2B SQRTPS +sqrtps_lanes: x2=d:40800000,80000000,bf800000,7f800000 => x1=d:40000000,80000000,ffc00000,7f800000 mx=1f81 f=* +@ divss xmm1, xmm2; addss xmm3, xmm4 + f30f5eca f30f58dc + SDM 1 10.2.3.1 +exception_flags_are_sticky: x1=s:3f800000 x2=s:00000000 x3=s:3f800000 x4=s:3f800000 mx=1fa0 => x1=s:7f800000 x3=s:40000000 mx=1fa4 f=* +@ addsd xmm1, xmm2; mulss xmm3, xmm4 + f20f58ca f30f59dc + SDM 2A ADDSD; 2B MULSS +scalar_ops_preserve_upper_lanes: x1=q:3ff0000000000000,7ff0000000000001 x2=q:3ff0000000000000,7ff0000000000001 x3=d:40000000,7f800001,00000001,ffffffff x4=d:40000000,7f800001,00000001,ffffffff => x1=q:4000000000000000,7ff0000000000001 x3=d:40800000,7f800001,00000001,ffffffff mx=1f80 f=* +"; + +const FP_MXCSR_AND_UNMASKED: &str = r" +@ ldmxcsr [rsi]; stmxcsr [rdi] + 0fae16 0fae1f + SDM 2A LDMXCSR; 2B STMXCSR +stmxcsr_after_ldmxcsr: rsi=D rdi=D+8 m0=ffff0000 m8=00000000 => m8=ffff0000 mx=ffff f=* +@ ldmxcsr [rsi] + !0fae16 + SDM 2A LDMXCSR; 1 10.2.3 +ldmxcsr_reserved_bit_is_gp: rsi=D m0=801f0100 => ! GP +@ ldmxcsr [rsi]; addss xmm1, xmm2 + 0fae16 f30f58ca + SDM 1 10.2.3.1; 2A LDMXCSR +ldmxcsr_unmasked_flag_does_not_trap: rsi=D m0=01000000 x1=s:3f800000 x2=s:3f800000 => x1=s:40000000 mx=1 f=* +@ divss xmm1, xmm2; ldmxcsr [rsi]; divss xmm3, xmm2 + f30f5eca 0fae16 f30f5eda + SDM 2A LDMXCSR; 1 4.8.4 Table 4-9 +ldmxcsr_changes_following_rounding: rsi=D m0=803f0000 x1=s:3f800000 x2=s:40400000 x3=s:3f800000 => x1=s:3eaaaaab x3=s:3eaaaaaa mx=3fa0 f=* +@ divss xmm1, xmm2 + !f30f5eca + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_invalid_faults_before_write: x1=s:00000000 x2=s:00000000 mx=1f00 => mx=1f01 f=* ! XM +unmasked_divide_by_zero_faults_before_write: x1=s:3f800000 x2=s:00000000 mx=1d80 => mx=1d84 f=* ! XM +@ addss xmm1, xmm2 + !f30f58ca + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_denormal_faults_before_write: x1=s:00000001 x2=s:3f800000 mx=1e80 => mx=1e82 f=* ! XM +@ divss xmm1, xmm2 + !f30f5eca + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_precision_faults_before_write: x1=s:3f800000 x2=s:40400000 mx=f80 => mx=fa0 f=* ! XM +@ mulss xmm1, xmm2 + !f30f59ca + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_underflow_exact_tiny_faults_before_write: x1=s:00800000 x2=s:3f000000 mx=1780 => mx=1790 f=* ! XM +unmasked_overflow_faults_before_write: x1=s:7f7fffff x2=s:7f7fffff mx=1b80 => mx=~20:1b88 f=* ! XM +@ mov eax, 7; addss xmm3, xmm3; divss xmm1, xmm2; mov ecx, 9 + b807000000 f30f58db !f30f5eca b909000000 + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_fault_is_precise: x1=s:3f800000 x2=s:00000000 x3=s:3f800000 mx=1d80 => rax=7 x3=s:40000000 mx=1d84 f=* ! XM +@ divps xmm1, xmm2 + !0f5eca + SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 +unmasked_packed_lane_leaves_whole_destination: x1=d:3f800000,3f800000,40000000,40800000 x2=d:40000000,00000000,40000000,40000000 mx=1d80 => mx=1d84 f=* ! XM +@ addss xmm1, xmm2 + f30f58ca + SDM 1 11.5.2.1 +masked_qnan_with_invalid_unmasked_does_not_fault: x1=s:7fc00123 x2=s:3f800000 mx=1f00 => x1=s:7fc00123 f=* +@ addss xmm1, xmm2 + !f30f58ca + SDM 1 11.5.3.2 (steps 1-3) +unmasked_pre_exception_hides_post_exceptions: x1=s:3f800000 x2=s:00000001 mx=0e80 => mx=0e82 f=* ! XM +"; + +const FP_BEYOND_SSE2: &str = r" +@ roundss xmm1, xmm5, 0; roundss xmm2, xmm5, 1; roundss xmm3, xmm5, 2; roundss xmm4, xmm5, 3 + 660f3a0acd00 660f3a0ad501 660f3a0add02 660f3a0ae503 + SDM 2B ROUNDSS +roundss_imm_modes: x5=s:c0200000 x1=d:0,0,0,0 x2=d:0,0,0,0 x3=d:0,0,0,0 x4=d:0,0,0,0 => x1=s:c0000000 x2=s:c0400000 x3=s:c0000000 x4=s:c0000000 mx=1fa0 f=* +@ roundsd xmm1, xmm2, 8 + 660f3a0bca08 + SDM 2B ROUNDSD (imm8[3]) +roundsd_suppress_precision: x2=r:bfd0000000000000 => x1=r:8000000000000000 mx=1f80 f=* +@ roundps xmm1, xmm2, 4 + 660f3a08ca04 + SDM 2B ROUNDPS (imm8[2]) +roundps_uses_mxcsr_rc: x2=d:3f000000,bf000000,3fc00000,c0200000 mx=5f80 => x1=d:3f800000,80000000,40000000,c0000000 mx=5fa0 f=* +@ haddps xmm1, xmm2; hsubpd xmm3, xmm4; addsubps xmm5, xmm6 + f20f7cca 660f7ddc f20fd0ee + SDM 2A HADDPS; 2A HSUBPD; 2A ADDSUBPS +haddps_hsubpd_addsubps: x1=d:3f800000,40000000,40400000,40800000 x2=d:40a00000,40c00000,40e00000,41000000 x3=q:4000000000000000,3ff0000000000000 x4=q:4008000000000000,4010000000000000 x5=d:3f800000,3f800000,3f800000,3f800000 x6=d:3f800000,3f800000,40000000,40000000 => x1=d:40400000,40e00000,41300000,41700000 x3=q:3ff0000000000000,bff0000000000000 x5=d:00000000,40000000,bf800000,40400000 f=* +@ dpps xmm1, xmm2, 0x7a + 660f3a40ca7a + SDM 2A DPPS +dpps_mask: x1=d:3f800000,40000000,40400000,40800000 x2=d:3f800000,3f800000,3f800000,3f800000 => x1=d:0,40c00000,0,40c00000 f=* +@ movddup xmm1, xmm2; movsldup xmm3, xmm2; movshdup xmm4, xmm2 + f20f12ca f30f12da f30f16e2 + SDM 2B MOVDDUP; 2B MOVSLDUP; 2B MOVSHDUP +movddup_movsldup_movshdup: x2=d:7f800001,2,3,4 => x1=d:7f800001,2,7f800001,2 x3=d:7f800001,7f800001,3,3 x4=d:2,2,4,4 f=* +"; + +const DEFECT_OVERLONG_INSTRUCTION: &str = r" +@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x01,0xd8 + !666666666666666666666666666601d8 + SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes) +sixteen_byte_redundant_operand_size_prefixes: => ! GP +"; + +const PAGE_CROSSING: &str = r" +@ movups xmm0, [rsi-8]; movups [rdi-5], xmm0 + 0f1046f8 0f1147fb + SDM 2B MOVUPS; 1 4.1.1 (unaligned operands) +movups_crosses_contiguous_pages: rsi=D+1000 rdi=D+1000 mff8=000102030405060708090a0b0c0d0e0f => x0=b:00,01,02,03,04,05,06,07,08,09,0a,0b,0c,0d,0e,0f mffb=000102030405060708090a0b0c0d0e0f f=* +@ add qword ptr [rdi-3], 1 + 488347fd01 + SDM 2A ADD; 1 4.1.1 (unaligned operands) +add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=0000000000000000 f=CPAZso +@ push rax; pop rbx + 50 5b + SDM 2B PUSH; 2B POP +push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=* +"; + +const GROUPS: &[(&str, &str)] = &[ + ("add_sub_flags", ADD_SUB_FLAGS), + ("carry_chains", CARRY_CHAINS), + ("logic", LOGIC), + ("partial_registers", PARTIAL_REGISTERS), + ("exchange", EXCHANGE), + ("flag_moves", FLAG_MOVES), + ("shift_rotate", SHIFT_ROTATE), + ("multiply_divide", MULTIPLY_DIVIDE), + ("bit_operations", BIT_OPERATIONS), + ("conditions", CONDITIONS), + ("stack_and_calls", STACK_AND_CALLS), + ("strings", STRINGS), + ("fs_gs", FS_GS), + ("decoding", DECODING), + ("memory_faults", MEMORY_FAULTS), + ( + "defect_straddling_fault_address", + DEFECT_STRADDLING_FAULT_ADDRESS, + ), + ("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS), + ("packed_integer_sse2", PACKED_INTEGER_SSE2), + ("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2), + ("fp_rounding", FP_ROUNDING), + ("fp_overflow_underflow", FP_OVERFLOW_UNDERFLOW), + ("fp_ftz_daz_denormals", FP_FTZ_DAZ_DENORMALS), + ("fp_nan_invalid_zero_divide", FP_NAN_INVALID_ZERO_DIVIDE), + ("fp_min_max_compare", FP_MIN_MAX_COMPARE), + ("fp_conversions", FP_CONVERSIONS), + ("fp_packed_and_sticky", FP_PACKED_AND_STICKY), + ("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED), + ("fp_beyond_sse2", FP_BEYOND_SSE2), + ("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION), + ("page_crossing", PAGE_CROSSING), +]; + +/// Forms both engines refuse today. They are not verified, only required to be +/// refused before they change guest state. +const UNSUPPORTED: &[&str] = &[ + "addr32_load_truncates_effective_address", + "addr32_sum_wraps_at_32_bits", + "bt_memory_negative_offset", + "bt_memory_positive_offset_beyond_operand", + "bt_memory_register_offset_can_fault", + "btr16_memory_negative_16bit_offset", + "bts_memory_negative_offset", + "cmpsb_is_rsi_minus_rdi", + "cmpxchg16b_equal", + "cmpxchg16b_equal_without_lock", + "cmpxchg16b_not_equal", + "cmpxchg16b_unaligned_is_gp", + "cmpxchg16b_unaligned_without_lock_is_gp", + "cmpxchg32_equal", + "cmpxchg64_memory_equal_without_lock", + "cmpxchg64_memory_not_equal", + "cmpxchg64_memory_not_equal_without_lock", + "cmpxchg8_not_equal_loads_al", + "cmpxchg8b_equal", + "cmpxchg8b_equal_without_lock", + "cmpxchg8b_not_equal", + "cmpxchg_mismatch_still_writes", + "crc32c_byte_and_qword_forms_agree", + "crc32c_check_string", + "dpps_mask", + "enter_leave_round_trip", + "fifteen_byte_instruction_executes", + "fs_addr32_truncates_before_adding_base", + "fs_rep_movsb_overrides_source_only", + "fs_rep_movsb_overrides_source_only_df_clear", + "gs_lock_xadd", + "gs_xadd_without_lock", + "haddps_hsubpd_addsubps", + "insertps_zero_mask", + "jecxz_tests_low_32_bits", + "jrcxz_tests_all_64_bits", + "lahf", + "lahf_zero", + "lea64_addr32_truncates_effective_address", + "lock_btc_memory", + "lodsd_zero_extends", + "lodsd_zero_extends_df_clear", + "lodsw_preserves_upper48", + "loop_decrements_rcx_without_flags", + "loopne_stops_on_zero_flag", + "maskmovdqu_selects_bytes", + "mov_moffs64_load", + "mov_moffs8_store", + "movddup_movsldup_movshdup", + "movdqa_movaps_aligned_store_and_load", + "movsb_forward", + "mpsadbw", + "pabs_min_is_unchanged", + "packusdw", + "palignr", + "pblendvb_uses_xmm0_msb", + "pblendw_blendps", + "pcmpeqq_pcmpgtq", + "pextr_pinsr_sse41", + "phaddsw_pmaddubsw_saturate", + "phaddw_phaddd_phsubw", + "phminposuw", + "pmin_pmax_sse41", + "pmovsx_pmovzx", + "pmulhrsw", + "pmulld_pmuldq", + "pshufb", + "psign", + "ptest_carry_when_source_is_subset", + "ptest_flags", + "push16_moves_rsp_by_two", + "pushfq_popfq_status_round_trip", + "rcl16_by16", + "rcl16_by17_is_identity", + "rcl32_by31", + "rcl32_cl32_affects_nothing_but_extension", + "rcl64_by63", + "rcl8_by1_clear_carry_in", + "rcl8_by1_set_carry_in_preserves_szap", + "rcl8_by8", + "rcl8_by9_is_identity", + "rcpps_special_values", + "rcpss_relative_error_bound", + "rcpss_rsqrtss_signal_nothing", + "rcr64_by1", + "rcr8_by10_is_by_one_mod_9", + "rcr8_by1_clear_carry_in", + "rcr8_by1_set_carry_in", + "rep_lodsb_source_fault", + "rep_movs_zero_count_touches_nothing", + "rep_movsb_addr32_uses_32bit_registers", + "rep_movsb_fault_df_clear", + "rep_movsb_fault_stops_at_failing_iteration", + "rep_movsb_overlap_propagates_df_clear", + "rep_movsq_overlap_propagates", + "rep_movsq_zero_count_df_clear", + "rep_movsw_backward", + "rep_stosd_df_clear", + "rep_stosd_forward", + "rep_stosq_fault_df_clear", + "rep_stosq_fault_stops_at_failing_iteration", + "repe_cmpsb_fault_restores_flags", + "repe_cmpsb_fault_restores_flags_df_clear", + "repe_cmpsb_stops_at_difference", + "repe_cmpsb_stops_at_difference_df_clear", + "repe_cmpsb_zero_count_keeps_flags", + "repne_scasb_finds_byte", + "repne_scasb_finds_byte_df_clear", + "repne_scasd_exhausts_count", + "rex_not_adjacent_to_opcode_is_ignored", + "roundps_uses_mxcsr_rc", + "roundsd_suppress_precision", + "roundss_imm_modes", + "sahf_clear_keeps_of", + "sahf_ignores_bits_1_3_5", + "shld16_by16_takes_source", + "shld32_by1_sign_change", + "shld32_by4", + "shld32_cl32_is_count_zero", + "shld64_by63", + "shr_rcr_128bit_right_shift", + "shrd32_by8", + "shrd64_by1_sign_change", + "shrd64_cl64_is_count_zero", + "xadd32_reg_reg", + "xadd64_memory", + "xadd64_memory_without_lock", + "xadd64_same_register_doubles", + "xadd8_al_ah", + "xadd_readonly_page_keeps_register", + "xchg_ax_r9w_preserves_both_uppers", + "xchg_eax_ebx_clears_both_uppers", + "xchg_rax_r8_is_not_nop", +]; + +// --------------------------------------------------------------------------- +// Table parsing +// --------------------------------------------------------------------------- + +#[derive(Clone)] +struct Case { + name: &'static str, + asm: &'static str, + cite: &'static str, + code: Vec, + /// Offset of each instruction in `code`. + offsets: Vec, + faulting: Option, + input: &'static str, + output: &'static str, + fault: &'static str, +} + +fn hex_bytes(text: &str) -> Vec { + assert_eq!(text.len() % 2, 0, "odd hex {text}"); + (0..text.len()) + .step_by(2) + .map(|at| u8::from_str_radix(&text[at..at + 2], 16).expect("hex byte")) + .collect() +} + +/// Sum of hexadecimal numbers and symbols, such as `D+10` or `U-FSB`. +fn value(text: &str) -> u64 { + let mut total = 0_u64; + let mut rest = text; + let mut negative = false; + loop { + let end = rest.find(['+', '-']).unwrap_or(rest.len()); + let term = match &rest[..end] { + "D" => DATA, + "U" => UNMAPPED, + "R" => READ_ONLY, + "S" => STACK, + "C" => CODE, + "FSB" => FS_BASE, + "GSB" => GS_BASE, + number => u64::from_str_radix(number, 16) + .unwrap_or_else(|_| panic!("bad number {number} in {text}")), + }; + total = if negative { + total.wrapping_sub(term) + } else { + total.wrapping_add(term) + }; + if end == rest.len() { + return total; + } + negative = rest.as_bytes()[end] == b'-'; + rest = &rest[end + 1..]; + } +} + +/// XMM value described by `text`, taking unnamed bits from `base`. +fn xmm_value(text: &str, base: u128) -> u128 { + let (kind, lanes) = text.split_once(':').expect("xmm lane kind"); + let (bits, partial) = match kind { + "b" => (8, false), + "w" => (16, false), + "d" => (32, false), + "q" => (64, false), + "s" => (32, true), + "r" => (64, true), + _ => panic!("xmm lane kind {kind}"), + }; + let lanes: Vec = lanes + .split(',') + .map(|lane| u128::from_str_radix(lane, 16).expect("xmm lane")) + .collect(); + if partial { + assert_eq!(lanes.len(), 1, "{text}"); + let mask = (1_u128 << bits) - 1; + return (base & !mask) | lanes[0]; + } + assert_eq!(lanes.len() * bits, 128, "{text}"); + lanes + .iter() + .rev() + .fold(0, |whole, lane| (whole << bits) | lane) +} + +fn flag_bits(text: &str, upper: bool) -> u8 { + text.chars() + .filter(|letter| letter.is_ascii_uppercase() == upper) + .fold(0, |bits, letter| { + bits | match letter.to_ascii_uppercase() { + 'C' => CF, + 'P' => PF, + 'A' => AF, + 'Z' => ZF, + 'S' => SF, + 'O' => OF, + _ => panic!("flag {letter}"), + } + }) +} + +fn parse(table: &'static str) -> Vec { + let mut cases = Vec::new(); + let mut lines = table.lines().filter(|line| !line.is_empty()); + let (mut asm, mut cite) = ("", ""); + let (mut code, mut offsets, mut faulting) = (Vec::new(), Vec::new(), None); + while let Some(line) = lines.next() { + if let Some(text) = line.strip_prefix("@ ") { + asm = text; + (code, offsets, faulting) = (Vec::new(), Vec::new(), None); + for (index, piece) in lines.next().expect("bytes").split_whitespace().enumerate() { + let bytes = piece.strip_prefix('!').unwrap_or(piece); + if bytes != piece { + faulting = Some(index); + } + offsets.push(code.len()); + code.extend(hex_bytes(bytes)); + } + cite = lines.next().expect("citation").trim(); + assert!(cite.starts_with("SDM "), "{cite}"); + continue; + } + let (name, states) = line.split_once(':').expect("case name"); + let (input, rest) = states.split_once("=>").expect("case arrow"); + let (output, fault) = rest.split_once('!').unwrap_or((rest, "")); + cases.push(Case { + name, + asm, + cite, + code: code.clone(), + offsets: offsets.clone(), + faulting, + input: input.trim(), + output: output.trim(), + fault: fault.trim(), + }); + } + cases +} + +// --------------------------------------------------------------------------- +// Guest state +// --------------------------------------------------------------------------- + +fn pattern(address: u64) -> u8 { + (address as u8).wrapping_mul(29).wrapping_add(0x47) ^ (address >> 8) as u8 +} + +fn region(base: u64, len: usize) -> Vec { + (0..len as u64).map(|at| pattern(base + at)).collect() +} + +/// Memory the cases can observe. Stack bytes below the initial stack pointer +/// are scratch and are not compared. +#[derive(Clone, PartialEq)] +struct Image { + regions: BTreeMap>, +} + +impl Image { + fn new() -> Self { + let mut regions = BTreeMap::new(); + // Two separately mapped pages, so accesses can cross a mapping boundary. + let second = DATA + PAGE as u64; + for base in [DATA, second, READ_ONLY, STACK_PAGE, FS_BASE, GS_BASE] { + regions.insert(base, region(base, PAGE)); + } + Self { regions } + } + + fn set(&mut self, address: u64, bytes: &[u8]) { + for (address, byte) in (address..).zip(bytes) { + let page = self.regions.get_mut(&(address & !0xfff)); + page.expect("mapped address")[address as usize & 0xfff] = *byte; + } + } + + fn load(&self, code: &[u8]) -> GuestMemory { + let mut page = vec![0xcc; PAGE]; + page[..code.len()].copy_from_slice(code); + page[code.len()] = 0xf4; // HLT ends the case. + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(CODE, PAGE, MemoryPermissions::READ_EXECUTE, &page) + .expect("map code"); + for (&base, data) in &self.regions { + let permissions = if base == READ_ONLY { + MemoryPermissions::READ_ONLY + } else { + MemoryPermissions::READ_WRITE + }; + memory + .map_region_with_data(base, data.len(), permissions, data) + .expect("map data"); + } + memory + } + + fn store(memory: &GuestMemory) -> Self { + let mut image = Self::new(); + for (&base, data) in &mut image.regions { + memory.read_bytes(base, data).expect("read back"); + } + image + } + + fn differences(&self, expected: &Self) -> String { + let mut text = String::new(); + for (&base, data) in &self.regions { + let first = if base == STACK_PAGE { + (STACK - STACK_PAGE) as usize + } else { + 0 + }; + let wanted = &expected.regions[&base]; + for at in first..data.len() { + if data[at] != wanted[at] { + let address = base + at as u64; + let _ = write!( + text, + " [{address:x}]={:02x} want {:02x}", + data[at], wanted[at] + ); + } + } + } + text + } +} + +fn initial_cpu() -> CpuState { + let mut cpu = CpuState::new(CODE, STACK); + for (index, register) in cpu.gpr.iter_mut().enumerate() { + if index != 4 { + *register = 0xa55a_c33c_9669_0000 | (index as u64 * 0x0101 + 0x9020); + } + } + for (index, register) in cpu.xmm.iter_mut().enumerate() { + *register = 0x5aa5_3cc3_6996_f00f_7ee7_1881_2442_0000 | (index as u128 * 0x0111 + 0x0203); + } + cpu.fs_base = FS_BASE; + cpu.gs_base = GS_BASE; + cpu +} + +fn set_flags(flags: &mut RFlags, bits: u8) { + flags.cf = bits & CF != 0; + flags.pf = bits & PF != 0; + flags.af = bits & AF != 0; + flags.zf = bits & ZF != 0; + flags.sf = bits & SF != 0; + flags.of = bits & OF != 0; +} + +fn get_flags(flags: &RFlags) -> u8 { + u8::from(flags.cf) + | u8::from(flags.pf) << 1 + | u8::from(flags.af) << 2 + | u8::from(flags.zf) << 3 + | u8::from(flags.sf) << 4 + | u8::from(flags.of) << 5 +} + +fn show_flags(bits: u8, mask: u8) -> String { + "CPAZSO" + .chars() + .enumerate() + .map(|(at, letter)| match (mask >> at & 1, bits >> at & 1) { + (0, _) => '-', + (_, 0) => letter.to_ascii_lowercase(), + _ => letter, + }) + .collect() +} + +/// Final state a case requires, with the parts it leaves open. +struct Expected { + cpu: CpuState, + image: Image, + flag_mask: u8, + mxcsr_mask: u32, + open_gpr: u16, + open_xmm: u16, +} + +/// Apply `text` to a state. `open` collects the parts marked `=?`. +fn apply(text: &str, expected: &mut Expected) { + for token in text.split_whitespace() { + let (key, data) = token.split_once('=').expect("key=value"); + if matches!(key, "f" | "keep") { + continue; + } + if let Some(index) = REGISTERS.iter().position(|name| *name == key) { + if data == "?" { + expected.open_gpr |= 1 << index; + } else { + expected.cpu.gpr[index] = value(data); + } + } else if key == "rip" { + expected.cpu.rip = value(data); + } else if key == "gsbase" { + expected.cpu.gs_base = value(data); + } else if key == "mx" { + if data == "?" { + expected.mxcsr_mask = 0; + } else if let Some(masked) = data.strip_prefix('~') { + let (ignored, bits) = masked.split_once(':').expect("mask:value"); + expected.mxcsr_mask = !(value(ignored) as u32); + expected.cpu.mxcsr = Mxcsr(value(bits) as u32); + } else { + expected.cpu.mxcsr = Mxcsr(value(data) as u32); + } + } else if let Some(index) = key.strip_prefix('x') { + let index: usize = index.parse().expect("xmm index"); + if data == "?" { + expected.open_xmm |= 1 << index; + } else { + expected.cpu.xmm[index] = xmm_value(data, expected.cpu.xmm[index]); + } + } else { + let (base, offset) = if let Some(offset) = key.strip_prefix("fs") { + (FS_BASE, offset) + } else if let Some(offset) = key.strip_prefix("gs") { + (GS_BASE, offset) + } else { + (DATA, key.strip_prefix('m').expect("known key")) + }; + expected.image.set(base + value(offset), &hex_bytes(data)); + } + } +} + +fn initial_state(case: &Case) -> Expected { + let mut start = Expected { + cpu: initial_cpu(), + image: Image::new(), + flag_mask: 0, + mxcsr_mask: !0, + open_gpr: 0, + open_xmm: 0, + }; + apply(case.input, &mut start); + start +} + +fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> { + text.split_whitespace() + .find_map(|token| token.strip_prefix(key)?.strip_prefix('=')) +} + +// --------------------------------------------------------------------------- +// Engines +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Engine { + Interpreter, + Dbt, + /// The second run of a block the engine already translated. + DbtCached, + /// One instruction per dispatch, so every block is cut short. + DbtStepped, +} + +const ENGINES: [Engine; 4] = [ + Engine::Interpreter, + Engine::Dbt, + Engine::DbtCached, + Engine::DbtStepped, +]; +const BUDGET: usize = 1000; +const JIT_CAPACITY: usize = 64 * 1024; + +fn new_dbt() -> DbtEngine { + DbtEngine::new(JIT_CAPACITY).expect("JIT memory") +} + +fn run(engine: Engine, cpu: &CpuState, memory: &mut GuestMemory) -> (CpuState, ExitReason) { + match engine { + Engine::Interpreter => { + let result = Interpreter::new(cpu.clone(), memory, BUDGET).run(); + (result.final_state, result.exit_reason) + } + Engine::Dbt => run_dbt(&mut new_dbt(), cpu, memory, BUDGET), + Engine::DbtCached => { + let mut dbt = new_dbt(); + let mut scratch = memory.clone(); + run_dbt(&mut dbt, cpu, &mut scratch, BUDGET); + run_dbt(&mut dbt, cpu, memory, BUDGET) + } + Engine::DbtStepped => { + let mut dbt = new_dbt(); + let mut state = cpu.clone(); + for _ in 0..BUDGET { + let (next, exit) = run_dbt(&mut dbt, &state, memory, 1); + if exit != ExitReason::StepLimitExceeded { + return (next, exit); + } + state = next; + } + (state, ExitReason::StepLimitExceeded) + } + } +} + +fn run_dbt( + dbt: &mut DbtEngine, + cpu: &CpuState, + memory: &mut GuestMemory, + budget: usize, +) -> (CpuState, ExitReason) { + let mut state = cpu.clone(); + let result = dbt.run(&mut state, memory, budget); + assert_eq!(state, result.final_state, "DBT reported two final states"); + (result.final_state, result.exit_reason) +} + +fn fault_matches(expected: &str, exit: &ExitReason) -> bool { + let mut words = expected.split_whitespace(); + let kind = words.next().expect("fault kind"); + let address = words.next().map(value); + match (kind, exit) { + ("DE", ExitReason::DivideError) + | ("GP", ExitReason::GeneralProtection) + | ("UD", ExitReason::IllegalInstruction(_)) + | ("XM", ExitReason::SimdException) => true, + ("PFR" | "PFW" | "PFX", ExitReason::MemoryFault(MemoryError::UnmappedAddress(at))) => { + Some(*at) == address + } + ( + kind, + ExitReason::MemoryFault(MemoryError::PermissionViolation { + address: at, + required, + }), + ) => { + let access = match kind { + "PFR" => "read", + "PFW" => "write", + "PFX" => "execute", + _ => return false, + }; + Some(*at) == address && *required == access + } + _ => false, + } +} + +/// Every way the case differs from its known answer. +fn check(case: &Case, engine: Engine, initial_flags: u8) -> Result<(), String> { + let mut start = initial_state(case); + set_flags(&mut start.cpu.flags, initial_flags); + let mut memory = start.image.load(&case.code); + + let mut want = Expected { + cpu: start.cpu.clone(), + image: start.image.clone(), + ..start + }; + let faulting = case.faulting.map(|index| case.offsets[index]); + want.cpu.rip = CODE + faulting.unwrap_or(case.code.len() + 1) as u64; + apply(case.output, &mut want); + let mut flags = initial_flags; + want.flag_mask = match field(case.output, "f") { + Some("*") => ALL_FLAGS, + Some(text) => { + let (set, clear) = (flag_bits(text, true), flag_bits(text, false)); + flags = (flags | set) & !clear; + set | clear | field(case.output, "keep").map_or(0, |kept| flag_bits(kept, true)) + } + None if !case.fault.is_empty() => ALL_FLAGS, + None => 0, + }; + + let (cpu, exit) = run(engine, &start.cpu, &mut memory); + let mut text = String::new(); + let expected_exit = if case.fault.is_empty() { + exit == ExitReason::Halt + } else { + fault_matches(case.fault, &exit) + }; + if !expected_exit { + let wanted = if case.fault.is_empty() { + "Halt" + } else { + case.fault + }; + let _ = write!(text, " exit {exit:?} want {wanted};"); + } + for (index, name) in REGISTERS.iter().enumerate() { + if want.open_gpr >> index & 1 == 0 && cpu.gpr[index] != want.cpu.gpr[index] { + let _ = write!( + text, + " {name}={:016x} want {:016x};", + cpu.gpr[index], want.cpu.gpr[index] + ); + } + if want.open_xmm >> index & 1 == 0 && cpu.xmm[index] != want.cpu.xmm[index] { + let _ = write!( + text, + " xmm{index}={:032x} want {:032x};", + cpu.xmm[index], want.cpu.xmm[index] + ); + } + } + if cpu.rip != want.cpu.rip { + let _ = write!(text, " rip={:x} want {:x};", cpu.rip, want.cpu.rip); + } + let got_flags = get_flags(&cpu.flags); + if (got_flags ^ flags) & want.flag_mask != 0 { + let _ = write!( + text, + " flags={} want {};", + show_flags(got_flags, want.flag_mask), + show_flags(flags, want.flag_mask) + ); + } + if (cpu.mxcsr.0 ^ want.cpu.mxcsr.0) & want.mxcsr_mask != 0 { + let _ = write!( + text, + " mxcsr={:x} want {:x} under {:x};", + cpu.mxcsr.0, want.cpu.mxcsr.0, want.mxcsr_mask + ); + } + if (cpu.fs_base, cpu.gs_base) != (want.cpu.fs_base, want.cpu.gs_base) { + text.push_str(" segment base changed;"); + } + let memory_text = Image::store(&memory).differences(&want.image); + if !memory_text.is_empty() { + let _ = write!(text, " memory{memory_text};"); + } + if text.is_empty() { Ok(()) } else { Err(text) } +} + +fn flag_sweep(case: &Case) -> Vec { + match field(case.input, "f") { + Some(text) => vec![flag_bits(text, true)], + None => vec![0, ALL_FLAGS], + } +} + +/// Failures of one case, with engines that fail the same way on one line. +fn failures(case: &Case) -> Vec { + let mut seen: Vec<(String, Vec)> = Vec::new(); + for flags in flag_sweep(case) { + for engine in ENGINES { + if let Err(text) = check(case, engine, flags) { + let who = format!("{engine:?}/{}", show_flags(flags, ALL_FLAGS)); + match seen.iter_mut().find(|(known, _)| *known == text) { + Some((_, engines)) => engines.push(who), + None => seen.push((text, vec![who])), + } + } + } + } + seen.into_iter() + .map(|(text, engines)| { + format!( + "{} [{}] ({})\n {}:{text}", + case.name, + case.asm, + case.cite, + engines.join(", ") + ) + }) + .collect() +} + +fn check_group(table: &'static str) { + let cases = parse(table); + let mut report = Vec::new(); + let mut verified = 0; + for case in cases + .iter() + .filter(|case| !UNSUPPORTED.contains(&case.name)) + { + let found = failures(case); + if found.is_empty() { + verified += 1; + } + report.extend(found); + } + println!("{verified} known answers verified of {}", cases.len()); + assert!( + report.is_empty(), + "{} of {} cases disagree with the manual:\n{}", + report.len(), + cases.len(), + report.join("\n") + ); +} + +#[test] +fn add_sub_flags() { + check_group(ADD_SUB_FLAGS); +} + +#[test] +fn carry_chains() { + check_group(CARRY_CHAINS); +} + +#[test] +fn logic() { + check_group(LOGIC); +} + +#[test] +fn partial_registers() { + check_group(PARTIAL_REGISTERS); +} + +#[test] +fn exchange() { + check_group(EXCHANGE); +} + +#[test] +fn flag_moves() { + check_group(FLAG_MOVES); +} + +#[test] +fn shift_rotate() { + check_group(SHIFT_ROTATE); +} + +#[test] +fn multiply_divide() { + check_group(MULTIPLY_DIVIDE); +} + +#[test] +fn bit_operations() { + check_group(BIT_OPERATIONS); +} + +#[test] +fn conditions() { + check_group(CONDITIONS); +} + +#[test] +fn stack_and_calls() { + check_group(STACK_AND_CALLS); +} + +#[test] +fn strings() { + check_group(STRINGS); +} + +#[test] +fn fs_gs() { + check_group(FS_GS); +} + +#[test] +fn decoding() { + check_group(DECODING); +} + +#[test] +fn memory_faults() { + check_group(MEMORY_FAULTS); +} + +#[test] +#[ignore = "known defect (#155): a page-crossing fault reports the start of the access"] +fn defect_straddling_fault_address() { + check_group(DEFECT_STRADDLING_FAULT_ADDRESS); +} + +#[test] +#[ignore = "known defect (#155): a non-canonical address is a memory fault, not #GP"] +fn defect_noncanonical_address() { + check_group(DEFECT_NONCANONICAL_ADDRESS); +} + +#[test] +fn packed_integer_sse2() { + check_group(PACKED_INTEGER_SSE2); +} + +#[test] +fn packed_integer_beyond_sse2() { + check_group(PACKED_INTEGER_BEYOND_SSE2); +} + +#[test] +fn fp_rounding() { + check_group(FP_ROUNDING); +} + +#[test] +fn fp_overflow_underflow() { + check_group(FP_OVERFLOW_UNDERFLOW); +} + +#[test] +fn fp_ftz_daz_denormals() { + check_group(FP_FTZ_DAZ_DENORMALS); +} + +#[test] +fn fp_nan_invalid_zero_divide() { + check_group(FP_NAN_INVALID_ZERO_DIVIDE); +} + +#[test] +fn fp_min_max_compare() { + check_group(FP_MIN_MAX_COMPARE); +} + +#[test] +fn fp_conversions() { + check_group(FP_CONVERSIONS); +} + +#[test] +fn fp_packed_and_sticky() { + check_group(FP_PACKED_AND_STICKY); +} + +#[test] +fn fp_mxcsr_and_unmasked() { + check_group(FP_MXCSR_AND_UNMASKED); +} + +#[test] +fn fp_beyond_sse2() { + check_group(FP_BEYOND_SSE2); +} + +#[test] +#[ignore = "known defect (#155): an instruction over 15 bytes is illegal, not #GP"] +fn defect_overlong_instruction() { + check_group(DEFECT_OVERLONG_INSTRUCTION); +} + +#[test] +fn page_crossing() { + check_group(PAGE_CROSSING); +} + +fn all_cases() -> Vec<(&'static str, Case)> { + GROUPS + .iter() + .flat_map(|(group, table)| parse(table).into_iter().map(move |case| (*group, case))) + .collect() +} + +#[test] +fn case_names_are_unique_and_listed_exceptions_exist() { + let cases = all_cases(); + let names: BTreeSet<&str> = cases.iter().map(|(_, case)| case.name).collect(); + assert_eq!(names.len(), cases.len(), "duplicate case name"); + for name in UNSUPPORTED { + assert!(names.contains(name), "unknown case {name}"); + } +} + +/// A form outside the supported set must be refused, never approximated. +#[test] +fn unsupported_forms_are_refused_without_changing_state() { + for (_, case) in all_cases() { + if !UNSUPPORTED.contains(&case.name) { + continue; + } + let start = initial_state(&case); + for engine in ENGINES { + let mut memory = start.image.load(&case.code); + let (cpu, exit) = run(engine, &start.cpu, &mut memory); + assert!( + matches!(exit, ExitReason::IllegalInstruction(_)), + "{} on {engine:?}: {exit:?}", + case.name + ); + let offset = (cpu.rip - CODE) as usize; + assert!(case.offsets.contains(&offset), "{}", case.name); + if offset == 0 { + assert_eq!(cpu, start.cpu, "{} on {engine:?}", case.name); + assert_eq!(Image::store(&memory).differences(&start.image), ""); + } + } + } +} + +/// Which route each verified instruction takes in the DBT. The per-instruction +/// answer of `is_native` must agree with the engine's own fallback counter, so +/// helper calls cannot be mistaken for translated code. Run with `--nocapture` +/// for the list. +#[test] +fn dbt_route_of_every_case_is_recorded() { + let mut native: BTreeSet<&str> = BTreeSet::new(); + let mut helper: BTreeSet<&str> = BTreeSet::new(); + let mut counts: BTreeMap<&str, [usize; 3]> = BTreeMap::new(); + for (group, case) in all_cases() { + if UNSUPPORTED.contains(&case.name) { + continue; + } + let start = initial_state(&case); + let memory = start.image.load(&case.code); + let text: Vec<&str> = case.asm.split(';').map(str::trim).collect(); + let mut routes = Vec::new(); + for (index, &offset) in case.offsets.iter().enumerate() { + let Ok(insn) = decode(CODE + offset as u64, |at| memory.fetch_instruction_byte(at)) + else { + continue; + }; + let name = text.get(index).copied().unwrap_or(case.asm); + routes.push(is_native(&insn)); + if is_native(&insn) { + native.insert(name); + } else { + helper.insert(name); + } + } + let kind = match (routes.contains(&true), routes.contains(&false)) { + (true, false) => 0, + (false, true) => 1, + (true, true) => 2, + (false, false) => continue, + }; + counts.entry(group).or_default()[kind] += 1; + if let ([only], 1, true) = (routes.as_slice(), case.offsets.len(), case.fault.is_empty()) { + let mut dbt = new_dbt(); + let mut memory = memory.clone(); + run_dbt(&mut dbt, &start.cpu, &mut memory, BUDGET); + assert_eq!( + dbt.metrics.interpreter_fallbacks, + usize::from(!only), + "{}: {:?}", + case.name, + dbt.metrics + ); + } + } + println!("group: cases with only native code / only helpers / both"); + for (group, [only_native, only_helper, both]) in counts { + println!("{group}: {only_native} / {only_helper} / {both}"); + } + println!("native instructions:"); + native.iter().for_each(|name| println!(" {name}")); + println!("helper instructions:"); + helper.iter().for_each(|name| println!(" {name}")); +} + +// --------------------------------------------------------------------------- +// Sweeps computed from the manual's definitions +// --------------------------------------------------------------------------- + +/// Operands are AL/AX/EAX/RAX and BL/BX/EBX/RBX; shift counts are in CL. +const BINARY: &[(&str, [&str; 4])] = &[ + ("add", ["00d8", "6601d8", "01d8", "4801d8"]), + ("adc", ["10d8", "6611d8", "11d8", "4811d8"]), + ("sub", ["28d8", "6629d8", "29d8", "4829d8"]), + ("sbb", ["18d8", "6619d8", "19d8", "4819d8"]), + ("cmp", ["38d8", "6639d8", "39d8", "4839d8"]), + ("and", ["20d8", "6621d8", "21d8", "4821d8"]), + ("or", ["08d8", "6609d8", "09d8", "4809d8"]), + ("xor", ["30d8", "6631d8", "31d8", "4831d8"]), + ("test", ["84d8", "6685d8", "85d8", "4885d8"]), +]; +const UNARY: &[(&str, [&str; 4])] = &[ + ("inc", ["fec0", "66ffc0", "ffc0", "48ffc0"]), + ("dec", ["fec8", "66ffc8", "ffc8", "48ffc8"]), + ("neg", ["f6d8", "66f7d8", "f7d8", "48f7d8"]), + ("not", ["f6d0", "66f7d0", "f7d0", "48f7d0"]), +]; +const SHIFTS: &[(&str, [&str; 4])] = &[ + ("rol", ["d2c0", "66d3c0", "d3c0", "48d3c0"]), + ("ror", ["d2c8", "66d3c8", "d3c8", "48d3c8"]), + ("rcl", ["d2d0", "66d3d0", "d3d0", "48d3d0"]), + ("rcr", ["d2d8", "66d3d8", "d3d8", "48d3d8"]), + ("shl", ["d2e0", "66d3e0", "d3e0", "48d3e0"]), + ("shr", ["d2e8", "66d3e8", "d3e8", "48d3e8"]), + ("sar", ["d2f8", "66d3f8", "d3f8", "48d3f8"]), +]; +const WIDTHS: [u32; 4] = [8, 16, 32, 64]; + +fn mask(bits: u32) -> u64 { + u64::MAX >> (64 - bits) +} + +fn parity_even(result: u64) -> bool { + (result & 0xff).count_ones().is_multiple_of(2) +} + +fn pack(c: bool, p: bool, a: bool, z: bool, s: bool, o: bool) -> u8 { + u8::from(c) + | u8::from(p) << 1 + | u8::from(a) << 2 + | u8::from(z) << 3 + | u8::from(s) << 4 + | u8::from(o) << 5 +} + +fn signed(value: u64, bits: u32) -> i128 { + let value = i128::from(value); + if value >> (bits - 1) & 1 == 1 { + value - (1_i128 << bits) + } else { + value + } +} + +/// Register value after writing `result` to a `bits`-wide operand +/// (SDM 1 3.4.1.1). +fn written(old: u64, result: u64, bits: u32) -> u64 { + match bits { + 64 => result, + 32 => result, + _ => (old & !mask(bits)) | result, + } +} + +/// Result (`None` when nothing is written), flags and the defined flags, from +/// the status flag definitions of SDM 1 3.4.3.1 and the "Flags Affected" text of +/// each entry in Volume 2. +fn arithmetic(op: &str, a: u64, b: u64, bits: u32, flags: u8) -> (Option, u8, u8) { + let carry = u64::from(flags & CF != 0); + let limit = 1_i128 << bits; + let in_range = |exact: i128| -(limit / 2) <= exact && exact < limit / 2; + let (ua, sa) = (i128::from(a), signed(a, bits)); + let add = |b_value: u64, carry: u64| { + let exact = ua + i128::from(b_value) + i128::from(carry); + let result = (exact % limit) as u64; + let overflow = !in_range(sa + signed(b_value, bits) + i128::from(carry)); + let half = (a & 15) + (b_value & 15) + carry > 15; + (result, exact >= limit, half, overflow) + }; + let subtract = |x: u64, y: u64, borrow: u64| { + let exact = i128::from(x) - i128::from(y) - i128::from(borrow); + let result = exact.rem_euclid(limit) as u64; + let overflow = !in_range(signed(x, bits) - signed(y, bits) - i128::from(borrow)); + let half = (x & 15) < (y & 15) + borrow; + (result, exact < 0, half, overflow) + }; + let finish = |(result, carry_out, half, overflow): (u64, bool, bool, bool)| { + let sign = result >> (bits - 1) & 1 == 1; + let flags = pack( + carry_out, + parity_even(result), + half, + result == 0, + sign, + overflow, + ); + (result, flags) + }; + let logic = |result: u64| { + let (result, flags) = finish((result, false, false, false)); + (result, flags, ALL_FLAGS & !AF) + }; + match op { + "add" => { + let (result, flags) = finish(add(b, 0)); + (Some(result), flags, ALL_FLAGS) + } + "adc" => { + let (result, flags) = finish(add(b, carry)); + (Some(result), flags, ALL_FLAGS) + } + "sub" | "cmp" => { + let (result, flags) = finish(subtract(a, b, 0)); + ((op == "sub").then_some(result), flags, ALL_FLAGS) + } + "sbb" => { + let (result, flags) = finish(subtract(a, b, carry)); + (Some(result), flags, ALL_FLAGS) + } + "and" | "test" => { + let (result, flags, defined) = logic(a & b); + ((op == "and").then_some(result), flags, defined) + } + "or" => { + let (result, flags, defined) = logic(a | b); + (Some(result), flags, defined) + } + "xor" => { + let (result, flags, defined) = logic(a ^ b); + (Some(result), flags, defined) + } + "inc" => { + let (result, new) = finish(add(1, 0)); + (Some(result), new & !CF | flags & CF, ALL_FLAGS) + } + "dec" => { + let (result, new) = finish(subtract(a, 1, 0)); + (Some(result), new & !CF | flags & CF, ALL_FLAGS) + } + "neg" => { + let (result, flags) = finish(subtract(0, a, 0)); + (Some(result), flags, ALL_FLAGS) + } + "not" => (Some(!a & mask(bits)), flags, ALL_FLAGS), + _ => panic!("{op}"), + } +} + +/// The bit loops of SDM 2B "RCL/RCR/ROL/ROR" and "SAL/SAR/SHL/SHR". +fn shift(op: &str, operand: u64, count: u8, bits: u32, flags: u8) -> (u64, u8, u8) { + let masked = u32::from(count) & if bits == 64 { 0x3f } else { 0x1f }; + if masked == 0 { + return (operand, flags, ALL_FLAGS); + } + let msb = |value: u64| value >> (bits - 1) & 1 == 1; + let second = |value: u64| value >> (bits - 2) & 1 == 1; + let turns = match op { + "rcl" | "rcr" if bits < 32 => masked % (bits + 1), + "rol" | "ror" => masked % bits, + _ => masked, + }; + let (mut value, mut carry) = (operand, flags & CF != 0); + let rcr_overflow = msb(operand) != carry; + for _ in 0..turns { + let (high, low) = (msb(value), value & 1 == 1); + let into_low = |value: u64, bit: bool| (value << 1) & mask(bits) | u64::from(bit); + let into_high = |value: u64, bit: bool| value >> 1 | u64::from(bit) << (bits - 1); + (value, carry) = match op { + "rol" => (into_low(value, high), carry), + "ror" => (into_high(value, low), carry), + "rcl" => (into_low(value, carry), high), + "rcr" => (into_high(value, carry), low), + "shl" => (into_low(value, false), high), + "shr" => (into_high(value, false), low), + "sar" => (into_high(value, high), low), + _ => panic!("{op}"), + }; + } + match op { + "rol" => carry = value & 1 == 1, + "ror" => carry = msb(value), + _ => {} + } + let overflow = match op { + "rol" | "rcl" | "shl" => msb(value) != carry, + "ror" => msb(value) != second(value), + "rcr" => rcr_overflow, + "shr" => msb(operand), + "sar" => false, + _ => panic!("{op}"), + }; + let one = if masked == 1 { OF } else { 0 }; + if op.starts_with('r') { + let new = flags & !(CF | OF) | pack(carry, false, false, false, false, overflow); + return (value, new, ALL_FLAGS & !OF | one); + } + let carry_defined = op == "sar" || masked < bits; + let new = pack( + carry, + parity_even(value), + false, + value == 0, + msb(value), + overflow, + ); + let defined = PF | ZF | SF | one | if carry_defined { CF } else { 0 }; + (value, new, defined) +} + +/// Both engines on one instruction, reusing the DBT's translated block. +struct Bench { + memory: GuestMemory, + dbt: DbtEngine, + runs: usize, +} + +impl Bench { + fn new(hex: &str) -> Self { + Self { + memory: Image::new().load(&hex_bytes(hex)), + dbt: new_dbt(), + runs: 0, + } + } + + /// Whether both engines refuse the instruction as unsupported. + fn refused(&mut self) -> bool { + let cpu = initial_cpu(); + let (_, first) = run(Engine::Interpreter, &cpu, &mut self.memory); + let (_, second) = run_dbt(&mut self.dbt, &cpu, &mut self.memory, BUDGET); + assert_eq!(first, second); + matches!(first, ExitReason::IllegalInstruction(_)) + } + + /// Runs with AX/BX/CX-family inputs and compares RAX and the defined flags. + fn expect(&mut self, what: &str, inputs: [u64; 3], flags: u8, rax: u64, want: (u8, u8)) { + let mut cpu = initial_cpu(); + (cpu.gpr[0], cpu.gpr[1], cpu.gpr[3]) = (inputs[0], inputs[2], inputs[1]); + set_flags(&mut cpu.flags, flags); + let mut wanted = cpu.clone(); + wanted.gpr[0] = rax; + wanted.rip = 0; + for engine in [Engine::Interpreter, Engine::Dbt] { + let (mut got, exit) = match engine { + Engine::Interpreter => run(engine, &cpu, &mut self.memory), + _ => run_dbt(&mut self.dbt, &cpu, &mut self.memory, BUDGET), + }; + assert_eq!(exit, ExitReason::Halt, "{what} on {engine:?}"); + let got_flags = get_flags(&got.flags); + assert!( + (got_flags ^ want.0) & want.1 == 0, + "{what} rax={:x} rbx={:x} rcx={:x} flags={} on {engine:?}: flags={} want {}", + inputs[0], + inputs[1], + inputs[2], + show_flags(flags, ALL_FLAGS), + show_flags(got_flags, want.1), + show_flags(want.0, want.1) + ); + got.flags = wanted.flags; + got.rip = 0; + assert_eq!(got, wanted, "{what} on {engine:?}"); + self.runs += 1; + } + } +} + +fn boundary_values(bits: u32) -> Vec { + let top = 1_u64 << (bits - 1); + let mut values = vec![ + 0, + 1, + 2, + 7, + 8, + 0x0f, + 0x10, + 0x55, + 0x7f, + 0x80, + 0xfe, + 0xff, + top - 1, + top, + top + 1, + mask(bits) - 1, + mask(bits), + 0xa5a5_a5a5_a5a5_a5a5 & mask(bits), + ]; + values.sort_unstable(); + values.dedup(); + values +} + +/// Garbage above the operand must not matter and, below 32 bits, must survive. +fn dirty(value: u64, bits: u32) -> u64 { + value | 0xdead_beef_7654_3210 & !mask(bits) +} + +#[test] +fn arithmetic_sweep_matches_status_flag_definitions() { + let mut runs = 0; + for (op, forms) in BINARY { + for (hex, bits) in forms.iter().zip(WIDTHS) { + let mut bench = Bench::new(hex); + for a in boundary_values(bits) { + for b in boundary_values(bits) { + for flags in [0, CF, ALL_FLAGS & !CF, ALL_FLAGS] { + let (result, new, defined) = arithmetic(op, a, b, bits, flags); + let rax = dirty(a, bits); + let want = result.map_or(rax, |result| written(rax, result, bits)); + let what = format!("{op}{bits}"); + bench.expect(&what, [rax, dirty(b, bits), 3], flags, want, (new, defined)); + } + } + } + runs += bench.runs; + } + } + for (op, forms) in UNARY { + for (hex, bits) in forms.iter().zip(WIDTHS) { + let mut bench = Bench::new(hex); + for a in boundary_values(bits) { + for flags in [0, CF, ALL_FLAGS & !CF, ALL_FLAGS] { + let (result, new, defined) = arithmetic(op, a, 0, bits, flags); + let rax = dirty(a, bits); + let want = written(rax, result.expect("unary writes"), bits); + let what = format!("{op}{bits}"); + bench.expect(&what, [rax, 5, 3], flags, want, (new, defined)); + } + } + runs += bench.runs; + } + } + println!("{runs} engine runs"); +} + +/// Every 8-bit operand pair and carry for the additive operations. +#[test] +fn eight_bit_arithmetic_is_exhaustive() { + for (op, forms) in BINARY.iter().take(5) { + let mut bench = Bench::new(forms[0]); + for a in 0..=0xff { + for b in 0..=0xff { + for flags in [0, CF] { + let (result, new, defined) = arithmetic(op, a, b, 8, flags); + let want = result.unwrap_or(a); + bench.expect(op, [a, b, 3], flags, want, (new, defined)); + } + } + } + println!("{op}: {} engine runs", bench.runs); + } +} + +#[test] +fn shift_and_rotate_sweep_matches_operation_pseudocode() { + let mut runs = 0; + let mut refused = Vec::new(); + for (op, forms) in SHIFTS { + for (hex, bits) in forms.iter().zip(WIDTHS) { + let mut bench = Bench::new(hex); + if bench.refused() { + refused.push(format!("{op}{bits}")); + continue; + } + for operand in boundary_values(bits) { + for count in 0..=0xff { + for flags in [0, CF, ALL_FLAGS] { + let (result, new, defined) = shift(op, operand, count, bits, flags); + let rax = dirty(operand, bits); + let want = written(rax, result, bits); + let rcx = 0x1234_5678_9abc_de00 | u64::from(count); + let what = format!("{op}{bits}"); + bench.expect(&what, [rax, 5, rcx], flags, want, (new, defined)); + } + } + } + runs += bench.runs; + } + } + let wanted: Vec = ["rcl", "rcr"] + .iter() + .flat_map(|op| WIDTHS.map(|bits| format!("{op}{bits}"))) + .collect(); + assert_eq!(refused, wanted, "unsupported shift forms changed"); + println!("{runs} engine runs"); +} + +/// SDM 2A Jcc and 2B SETcc conditions against ordinary integer comparison. +#[test] +fn conditions_match_integer_comparison() { + // cmp rax, rbx; then SETcc [rdi+n] for O NO B AE E NE BE A S NS P NP L GE LE G. + const CODE_HEX: &str = "4839d80f90070f9147010f9247020f9347030f9447040f9547050f9647060f9747070f9847080f9947090f9a470a0f9b470b0f9c470c0f9d470d0f9e470e0f9f470f"; + let code = hex_bytes(CODE_HEX); + let mut dbt = new_dbt(); + for a in boundary_values(64) { + for b in boundary_values(64) { + let (x, y) = (a as i64, b as i64); + let difference = a.wrapping_sub(b); + let overflow = x.checked_sub(y).is_none(); + let even = parity_even(difference); + let pairs = [ + overflow, + a < b, + a == b, + a <= b, + (difference as i64) < 0, + even, + x < y, + x <= y, + ]; + let wanted: Vec = pairs + .iter() + .flat_map(|&yes| [u8::from(yes), u8::from(!yes)]) + .collect(); + let mut cpu = initial_cpu(); + (cpu.gpr[0], cpu.gpr[3], cpu.gpr[7]) = (a, b, DATA); + for native in [false, true] { + let mut memory = Image::new().load(&code); + let (_, exit) = if native { + run_dbt(&mut dbt, &cpu, &mut memory, BUDGET) + } else { + run(Engine::Interpreter, &cpu, &mut memory) + }; + assert_eq!(exit, ExitReason::Halt); + let mut got = [0; 16]; + memory.read_bytes(DATA, &mut got).expect("read back"); + assert_eq!(got[..], wanted[..], "cmp {a:x}, {b:x} native={native}"); + } + } + } +} + +/// Deterministic operands: xorshift64* with a fixed seed. +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + /// Lanes drawn half from range ends and half at random. + fn vector(&mut self) -> u128 { + const ENDS: [u64; 8] = [0, 1, 0x7f, 0x80, 0xff, 0x7fff, 0x8000, 0xffff]; + let mut whole = 0; + for _ in 0..8 { + let pick = self.next(); + let lane = if pick & 1 == 0 { + ENDS[(pick >> 8) as usize % ENDS.len()] + } else { + pick >> 16 & 0xffff + }; + whole = whole << 16 | u128::from(lane); + } + whole + } +} + +fn lane(value: u128, bits: u32, index: u32) -> u64 { + (value >> (bits * index)) as u64 & mask(bits) +} + +fn each(bits: u32, f: impl Fn(u32) -> u64) -> u128 { + (0..128 / bits).fold(0, |whole, index| { + whole | u128::from(f(index) & mask(bits)) << (bits * index) + }) +} + +fn clamp(value: i128, low: i128, high: i128) -> u64 { + value.clamp(low, high) as u64 +} + +/// Two-operand SSE2 integer instructions, lane by lane from the Operation text +/// of their entries in SDM 2B. `a` is the destination. +fn packed(op: &str, a: u128, b: u128) -> u128 { + let bits = match op.as_bytes()[op.len() - 1] { + b'b' => 8, + b'w' => 16, + b'd' => 32, + _ => 64, + }; + let ones = |yes: bool| if yes { u64::MAX } else { 0 }; + let wide = |value: u128, n: u32, i: u32| signed(lane(value, n, i), n); + let unsigned = |value: u128, n: u32, i: u32| i128::from(lane(value, n, i)); + let map = |f: &dyn Fn(i128, i128) -> u64| each(bits, |i| f(wide(a, bits, i), wide(b, bits, i))); + let umap = |f: &dyn Fn(i128, i128) -> u64| { + each(bits, |i| f(unsigned(a, bits, i), unsigned(b, bits, i))) + }; + let (low, high) = (-(1_i128 << (bits - 1)), (1_i128 << (bits - 1)) - 1); + let top = i128::from(mask(bits)); + // Shift counts are the whole low quadword of the source. + let count = b as u64; + let shift_right_arithmetic = || { + let by = count.min(u64::from(bits) - 1); + each(bits, |i| (wide(a, bits, i) >> by) as u64) + }; + let shifted = |f: &dyn Fn(u64) -> u64| { + each(bits, |i| { + if count >= u64::from(bits) { + 0 + } else { + f(lane(a, bits, i)) + } + }) + }; + let unpack = + |n: u32, from: u32| each(n, |i| lane(if i % 2 == 0 { a } else { b }, n, from + i / 2)); + let pack_to = |n: u32, low: i128, high: i128| { + let lanes = 128 / (2 * n); + each(n, |i| { + let source = if i < lanes { a } else { b }; + clamp(wide(source, 2 * n, i % lanes), low, high) + }) + }; + match op { + "paddb" | "paddw" | "paddd" | "paddq" => map(&|x, y| (x + y) as u64), + "psubb" | "psubw" | "psubd" | "psubq" => map(&|x, y| (x - y) as u64), + "paddsb" | "paddsw" => map(&|x, y| clamp(x + y, low, high)), + "psubsb" | "psubsw" => map(&|x, y| clamp(x - y, low, high)), + "paddusb" | "paddusw" => umap(&|x, y| clamp(x + y, 0, top)), + "psubusb" | "psubusw" => umap(&|x, y| clamp(x - y, 0, top)), + "pmullw" => map(&|x, y| (x * y) as u64), + "pmulhw" => map(&|x, y| ((x * y) >> 16) as u64), + "pmulhuw" => umap(&|x, y| ((x * y) >> 16) as u64), + "pmuludq" => each(64, |i| lane(a, 32, 2 * i) * lane(b, 32, 2 * i)), + "pmaddwd" => each(32, |i| { + let product = |n| wide(a, 16, n) * wide(b, 16, n); + (product(2 * i) + product(2 * i + 1)) as u64 + }), + "psadbw" => each(64, |i| { + (8 * i..8 * i + 8) + .map(|n| lane(a, 8, n).abs_diff(lane(b, 8, n))) + .sum() + }), + "pavgb" | "pavgw" => umap(&|x, y| ((x + y + 1) >> 1) as u64), + "pminub" => umap(&|x, y| x.min(y) as u64), + "pmaxub" => umap(&|x, y| x.max(y) as u64), + "pminsw" => map(&|x, y| x.min(y) as u64), + "pmaxsw" => map(&|x, y| x.max(y) as u64), + "pcmpeqb" | "pcmpeqw" | "pcmpeqd" => map(&|x, y| ones(x == y)), + "pcmpgtb" | "pcmpgtw" | "pcmpgtd" => map(&|x, y| ones(x > y)), + "pand" => a & b, + "pandn" => !a & b, + "por" => a | b, + "pxor" => a ^ b, + "psllw" | "pslld" | "psllq" => shifted(&|x| x << count), + "psrlw" | "psrld" | "psrlq" => shifted(&|x| x >> count), + "psraw" | "psrad" => shift_right_arithmetic(), + "packsswb" => pack_to(8, -128, 127), + "packssdw" => pack_to(16, -32768, 32767), + "packuswb" => pack_to(8, 0, 255), + "punpcklbw" => unpack(8, 0), + "punpcklwd" => unpack(16, 0), + "punpckldq" => unpack(32, 0), + "punpcklqdq" => unpack(64, 0), + "punpckhbw" => unpack(8, 8), + "punpckhwd" => unpack(16, 4), + "punpckhdq" => unpack(32, 2), + "punpckhqdq" => unpack(64, 1), + _ => panic!("{op}"), + } +} + +/// Immediate shifts and shuffles of SDM 2B. +fn packed_immediate(op: &str, a: u128, b: u128, imm: u8) -> u128 { + let field = |i: u32| u32::from(imm >> (2 * (i % 4)) & 3); + match op { + "pslldq" if imm > 15 => 0, + "psrldq" if imm > 15 => 0, + "pslldq" => a << (8 * u32::from(imm)), + "psrldq" => a >> (8 * u32::from(imm)), + "pshufd" => each(32, |i| lane(b, 32, field(i))), + "pshuflw" => each(16, |i| lane(b, 16, if i < 4 { field(i) } else { i })), + "pshufhw" => each(16, |i| lane(b, 16, if i < 4 { i } else { 4 + field(i) })), + "shufps" => each(32, |i| lane(if i < 2 { a } else { b }, 32, field(i))), + "shufpd" => each(64, |i| { + lane(if i < 1 { a } else { b }, 64, u32::from(imm >> i & 1)) + }), + _ => packed(op, a, u128::from(imm)), + } +} + +/// Runs one XMM1, XMM2 instruction in both engines and compares the whole state. +fn expect_vector(bench: &mut Bench, what: &str, cpu: &CpuState, wanted: &CpuState) { + for engine in [Engine::Interpreter, Engine::Dbt] { + let (mut got, exit) = match engine { + Engine::Interpreter => run(engine, cpu, &mut bench.memory), + _ => run_dbt(&mut bench.dbt, cpu, &mut bench.memory, BUDGET), + }; + assert_eq!(exit, ExitReason::Halt, "{what} on {engine:?}"); + got.rip = wanted.rip; + if got != *wanted { + panic!( + "{what} on {engine:?}: xmm1={:032x} xmm2={:032x} mxcsr={:x}\n got xmm1={:032x} rax={:x} mxcsr={:x} flags={}\nwant xmm1={:032x} rax={:x} mxcsr={:x} flags={}", + cpu.xmm[1], + cpu.xmm[2], + cpu.mxcsr.0, + got.xmm[1], + got.gpr[0], + got.mxcsr.0, + show_flags(get_flags(&got.flags), ALL_FLAGS), + wanted.xmm[1], + wanted.gpr[0], + wanted.mxcsr.0, + show_flags(get_flags(&wanted.flags), ALL_FLAGS), + ); + } + bench.runs += 1; + } +} + +#[test] +fn packed_integer_sweep_matches_lane_definitions() { + let mut runs = 0; + let mut random = Random(0x155); + for (op, distinct, aliased) in PACKED { + let is_shift = op.starts_with("psll") || op.starts_with("psrl") || op.starts_with("psra"); + for (hex, alias) in [(distinct, false), (aliased, true)] { + let mut bench = Bench::new(hex); + for round in 0..400_u64 { + let a = random.vector(); + let mut b = random.vector(); + if is_shift && round % 4 != 0 { + b = b >> 64 << 64 | u128::from(round % 70); + } + let mut cpu = initial_cpu(); + (cpu.xmm[1], cpu.xmm[2]) = (a, b); + let mut wanted = cpu.clone(); + wanted.xmm[1] = packed(op, a, if alias { a } else { b }); + expect_vector(&mut bench, hex, &cpu, &wanted); + } + runs += bench.runs; + } + } + for (op, hex) in PACKED_IMMEDIATE { + for imm in 0..=0xff_u8 { + let mut bench = Bench::new(&format!("{hex}{imm:02x}")); + for _ in 0..4 { + let mut cpu = initial_cpu(); + (cpu.xmm[1], cpu.xmm[2]) = (random.vector(), random.vector()); + let mut wanted = cpu.clone(); + wanted.xmm[1] = packed_immediate(op, cpu.xmm[1], cpu.xmm[2], imm); + expect_vector(&mut bench, &format!("{op} {imm}"), &cpu, &wanted); + } + runs += bench.runs; + } + } + println!("{runs} engine runs"); +} + +const PACKED: &[(&str, &str, &str)] = &[ + ("paddb", "660ffcca", "660ffcc9"), + ("paddw", "660ffdca", "660ffdc9"), + ("paddd", "660ffeca", "660ffec9"), + ("paddq", "660fd4ca", "660fd4c9"), + ("psubb", "660ff8ca", "660ff8c9"), + ("psubw", "660ff9ca", "660ff9c9"), + ("psubd", "660ffaca", "660ffac9"), + ("psubq", "660ffbca", "660ffbc9"), + ("paddsb", "660fecca", "660fecc9"), + ("paddsw", "660fedca", "660fedc9"), + ("paddusb", "660fdcca", "660fdcc9"), + ("paddusw", "660fddca", "660fddc9"), + ("psubsb", "660fe8ca", "660fe8c9"), + ("psubsw", "660fe9ca", "660fe9c9"), + ("psubusb", "660fd8ca", "660fd8c9"), + ("psubusw", "660fd9ca", "660fd9c9"), + ("pmullw", "660fd5ca", "660fd5c9"), + ("pmulhw", "660fe5ca", "660fe5c9"), + ("pmulhuw", "660fe4ca", "660fe4c9"), + ("pmuludq", "660ff4ca", "660ff4c9"), + ("pmaddwd", "660ff5ca", "660ff5c9"), + ("psadbw", "660ff6ca", "660ff6c9"), + ("pavgb", "660fe0ca", "660fe0c9"), + ("pavgw", "660fe3ca", "660fe3c9"), + ("pminub", "660fdaca", "660fdac9"), + ("pmaxub", "660fdeca", "660fdec9"), + ("pminsw", "660feaca", "660feac9"), + ("pmaxsw", "660feeca", "660feec9"), + ("pcmpeqb", "660f74ca", "660f74c9"), + ("pcmpeqw", "660f75ca", "660f75c9"), + ("pcmpeqd", "660f76ca", "660f76c9"), + ("pcmpgtb", "660f64ca", "660f64c9"), + ("pcmpgtw", "660f65ca", "660f65c9"), + ("pcmpgtd", "660f66ca", "660f66c9"), + ("pand", "660fdbca", "660fdbc9"), + ("pandn", "660fdfca", "660fdfc9"), + ("por", "660febca", "660febc9"), + ("pxor", "660fefca", "660fefc9"), + ("psllw", "660ff1ca", "660ff1c9"), + ("pslld", "660ff2ca", "660ff2c9"), + ("psllq", "660ff3ca", "660ff3c9"), + ("psrlw", "660fd1ca", "660fd1c9"), + ("psrld", "660fd2ca", "660fd2c9"), + ("psrlq", "660fd3ca", "660fd3c9"), + ("psraw", "660fe1ca", "660fe1c9"), + ("psrad", "660fe2ca", "660fe2c9"), + ("packsswb", "660f63ca", "660f63c9"), + ("packssdw", "660f6bca", "660f6bc9"), + ("packuswb", "660f67ca", "660f67c9"), + ("punpcklbw", "660f60ca", "660f60c9"), + ("punpcklwd", "660f61ca", "660f61c9"), + ("punpckldq", "660f62ca", "660f62c9"), + ("punpcklqdq", "660f6cca", "660f6cc9"), + ("punpckhbw", "660f68ca", "660f68c9"), + ("punpckhwd", "660f69ca", "660f69c9"), + ("punpckhdq", "660f6aca", "660f6ac9"), + ("punpckhqdq", "660f6dca", "660f6dc9"), +]; +const PACKED_IMMEDIATE: &[(&str, &str)] = &[ + ("psllw", "660f71f1"), + ("pslld", "660f72f1"), + ("psllq", "660f73f1"), + ("psrlw", "660f71d1"), + ("psrld", "660f72d1"), + ("psrlq", "660f73d1"), + ("psraw", "660f71e1"), + ("psrad", "660f72e1"), + ("pslldq", "660f73f9"), + ("psrldq", "660f73d9"), + ("pshufd", "660f70ca"), + ("pshuflw", "f20f70ca"), + ("pshufhw", "f30f70ca"), + ("shufps", "0fc6ca"), + ("shufpd", "660fc6ca"), +]; +const FLOAT: &[(&str, [&str; 2])] = &[ + ("add", ["f30f58ca", "f20f58ca"]), + ("sub", ["f30f5cca", "f20f5cca"]), + ("mul", ["f30f59ca", "f20f59ca"]), + ("div", ["f30f5eca", "f20f5eca"]), + ("sqrt", ["f30f51ca", "f20f51ca"]), + ("min", ["f30f5dca", "f20f5dca"]), + ("max", ["f30f5fca", "f20f5fca"]), +]; + +// --- multiply and divide ----------------------------------------------------- + +const PRODUCTS: &[(&str, [&str; 4])] = &[ + ("mul", ["f6e3", "66f7e3", "f7e3", "48f7e3"]), + ("imul", ["f6eb", "66f7eb", "f7eb", "48f7eb"]), + ("div", ["f6f3", "66f7f3", "f7f3", "48f7f3"]), + ("idiv", ["f6fb", "66f7fb", "f7fb", "48f7fb"]), +]; + +/// RAX and RDX after a double-width result (AX, DX:AX, EDX:EAX or RDX:RAX). +fn write_pair(cpu: &mut CpuState, low: u64, high: u64, bits: u32) { + if bits == 8 { + cpu.gpr[0] = cpu.gpr[0] & !0xffff | low | high << 8; + } else { + cpu.gpr[0] = written(cpu.gpr[0], low, bits); + cpu.gpr[2] = written(cpu.gpr[2], high, bits); + } +} + +#[test] +fn multiply_and_divide_sweep_matches_exact_arithmetic() { + let mut runs = 0; + for (op, forms) in PRODUCTS { + for (hex, bits) in forms.iter().zip(WIDTHS) { + let mut bench = Bench::new(hex); + let values = boundary_values(bits); + let highs: &[u64] = if op.ends_with("div") { &values } else { &[3] }; + for &high in highs { + for &low in &values { + for &source in &values { + let mut cpu = initial_cpu(); + cpu.gpr[3] = dirty(source, bits); + cpu.gpr[0] = dirty(low, bits); + cpu.gpr[2] = dirty(high, bits); + if bits == 8 { + cpu.gpr[0] = dirty(low, 16) & !0xff00 | (high & 0xff) << 8; + } + check_multiply_divide(&mut bench, op, &cpu, [high, low, source], bits); + } + } + } + runs += bench.runs; + } + } + println!("{runs} engine runs"); +} + +/// `None` is #DE: a zero divisor or a quotient outside the destination +/// (SDM 2A DIV, IDIV and Table 3-53). +fn divide(op: &str, [high, low, source]: [u64; 3], bits: u32) -> Option<(u64, u64)> { + if source == 0 { + return None; + } + let dividend = u128::from(high) << bits | u128::from(low); + if op == "div" { + let quotient = dividend / u128::from(source); + let remainder = dividend % u128::from(source); + return (quotient <= u128::from(mask(bits))).then_some((quotient as u64, remainder as u64)); + } + let spare = 128 - 2 * bits; + let dividend = (dividend << spare) as i128 >> spare; + let divisor = signed(source, bits); + let quotient = dividend.checked_div(divisor)?; + let remainder = dividend % divisor; + let limit = 1_i128 << (bits - 1); + (-limit..limit) + .contains("ient) + .then_some((quotient as u64 & mask(bits), remainder as u64 & mask(bits))) +} + +fn check_multiply_divide(bench: &mut Bench, op: &str, cpu: &CpuState, inputs: [u64; 3], bits: u32) { + let [_, low, source] = inputs; + let mut wanted = cpu.clone(); + let mut carry = None; + let mut exit_wanted = ExitReason::Halt; + match op { + "mul" => { + let product = u128::from(low) * u128::from(source); + let (product_low, product_high) = + (product as u64 & mask(bits), (product >> bits) as u64); + write_pair(&mut wanted, product_low, product_high, bits); + carry = Some(product_high != 0); + } + "imul" => { + let product = signed(low, bits) * signed(source, bits); + let product_low = product as u64 & mask(bits); + let product_high = (product >> bits) as u64 & mask(bits); + write_pair(&mut wanted, product_low, product_high, bits); + carry = Some(signed(product_low, bits) != product); + } + _ => match divide(op, inputs, bits) { + Some((quotient, remainder)) => { + write_pair(&mut wanted, quotient, remainder, bits); + } + None => exit_wanted = ExitReason::DivideError, + }, + } + for engine in [Engine::Interpreter, Engine::Dbt] { + let (mut got, exit) = match engine { + Engine::Interpreter => run(engine, cpu, &mut bench.memory), + _ => run_dbt(&mut bench.dbt, cpu, &mut bench.memory, BUDGET), + }; + let what = format!("{op}{bits} {inputs:x?} on {engine:?}"); + assert_eq!(exit, exit_wanted, "{what}"); + if let Some(carry) = carry { + assert_eq!((got.flags.cf, got.flags.of), (carry, carry), "{what}"); + } + if exit_wanted == ExitReason::Halt { + // MUL leaves SF, ZF, AF, PF undefined; DIV leaves all six. + got.flags = wanted.flags; + got.rip = wanted.rip; + } + assert_eq!(got, wanted, "{what}"); + bench.runs += 1; + } +} + +// --- floating point ------------------------------------------------------------ + +const IE: u32 = 1; +const DE: u32 = 2; +const ZE: u32 = 4; +const OE: u32 = 8; +const UE: u32 = 16; +const PE: u32 = 32; +const DAZ: u32 = 0x40; +const FTZ: u32 = 0x8000; +const MASKS: u32 = 0x1f80; + +/// Binary32 or binary64 (SDM 1 4.2.2). +#[derive(Clone, Copy)] +struct Format { + bits: u32, + precision: u32, +} + +const SINGLE: Format = Format { + bits: 32, + precision: 24, +}; +const DOUBLE: Format = Format { + bits: 64, + precision: 53, +}; + +impl Format { + fn fraction_bits(self) -> u32 { + self.precision - 1 + } + fn max_exponent(self) -> i32 { + (1 << (self.bits - self.precision - 1)) - 1 + } + fn min_exponent(self) -> i32 { + 1 - self.max_exponent() + } + fn sign(self) -> u64 { + 1 << (self.bits - 1) + } + fn infinity(self) -> u64 { + mask(self.bits - 1) & !mask(self.fraction_bits()) + } + fn quiet(self) -> u64 { + 1 << (self.fraction_bits() - 1) + } + fn indefinite(self) -> u64 { + self.sign() | self.infinity() | self.quiet() + } + fn magnitude(self, value: u64) -> u64 { + value & !self.sign() + } + fn negative(self, value: u64) -> bool { + value & self.sign() != 0 + } + fn signed(self, negative: bool, magnitude: u64) -> u64 { + magnitude | if negative { self.sign() } else { 0 } + } + fn is_nan(self, value: u64) -> bool { + self.magnitude(value) > self.infinity() + } + fn is_snan(self, value: u64) -> bool { + self.is_nan(value) && value & self.quiet() == 0 + } + fn is_infinite(self, value: u64) -> bool { + self.magnitude(value) == self.infinity() + } + fn is_zero(self, value: u64) -> bool { + self.magnitude(value) == 0 + } + fn is_denormal(self, value: u64) -> bool { + let magnitude = self.magnitude(value); + magnitude != 0 && magnitude <= mask(self.fraction_bits()) + } + /// Finite value as significand times a power of two. + fn split(self, value: u64) -> (u128, i32) { + let magnitude = self.magnitude(value); + let field = (magnitude >> self.fraction_bits()) as i32; + let fraction = u128::from(magnitude & mask(self.fraction_bits())); + let lowest = self.min_exponent() - self.fraction_bits() as i32; + if field == 0 { + (fraction, lowest) + } else { + (fraction | 1 << self.fraction_bits(), lowest + field - 1) + } + } + fn values(self) -> Vec { + let one = (self.max_exponent() as u64) << self.fraction_bits(); + let tiny = 1 << self.fraction_bits(); + let infinity = self.infinity(); + let mut values = vec![ + 0, + 1, + 2, + tiny / 2, + tiny - 1, + tiny, + tiny + 1, + 2 * tiny - 1, + one - tiny, + one - 1, + one, + one + 1, + one + tiny / 2, + one + tiny - 1, + one + tiny, + one + tiny + tiny / 2 + 1, + one + u64::from(self.precision) * tiny, + one - u64::from(self.precision) * tiny, + infinity - tiny - 1, + infinity - 1, + infinity, + infinity | self.quiet() | 5, + infinity | 9, + ]; + let negative: Vec = values.iter().map(|value| value | self.sign()).collect(); + values.extend(negative); + values + } +} + +/// What the manual requires: the result, the flags, and the flags it leaves open. +#[derive(Clone, Copy)] +struct Outcome { + result: u64, + flags: u32, + open: u32, +} + +fn outcome(result: u64, flags: u32) -> Outcome { + Outcome { + result, + flags, + open: 0, + } +} + +/// `significand * 2^exponent`, where `sticky` adds a nonzero amount below the +/// last bit, rounded to the multiple of `2^lowest` the mode selects (SDM 1 4.8.4 +/// Table 4-9). Returns the multiple and whether it is exact. +fn round_to( + significand: u128, + exponent: i32, + sticky: bool, + lowest: i32, + negative: bool, + mode: u32, +) -> (u128, bool) { + let drop = lowest - exponent; + if drop <= 0 { + assert!(!sticky, "too few quotient bits"); + return (significand << -drop, true); + } + let (kept, rest, half) = if drop >= 127 { + (0, significand, 1 << 126 | 1) // Every significand is far below half. + } else { + let kept = significand >> drop; + (kept, significand - (kept << drop), 1 << (drop - 1)) + }; + if rest == 0 && !sticky { + return (kept, true); + } + let up = match mode { + 0 => rest > half || rest == half && (sticky || kept & 1 == 1), + 1 => negative, + 2 => !negative, + _ => false, + }; + (kept + u128::from(up), false) +} + +/// Deliver a nonzero finite exact value (SDM 1 4.9.1.4 to 4.9.1.6, 10.2.3.3). +fn deliver( + format: Format, + negative: bool, + significand: u128, + exponent: i32, + sticky: bool, + mxcsr: u32, +) -> Outcome { + let mode = mxcsr >> 13 & 3; + let precision = format.precision as i32; + let leading = 127 - significand.leading_zeros() as i32 + exponent; + let lowest = leading - precision + 1; + let (unbounded, _) = round_to(significand, exponent, sticky, lowest, negative, mode); + let carried = unbounded >> precision != 0; + let rounded_exponent = leading + i32::from(carried); + let tiny = rounded_exponent < format.min_exponent(); + let floor = format.min_exponent() - precision + 1; + let lowest = lowest.max(floor); + let (mut value, exact) = round_to(significand, exponent, sticky, lowest, negative, mode); + let mut lowest = lowest; + if value >> precision != 0 { + value >>= 1; + lowest += 1; + } + let inexact = if exact { 0 } else { PE }; + if mxcsr & MASKS == 0 && tiny { + // Unmasked underflow is reported for any tiny result. + return Outcome { + result: 0, + flags: UE | inexact, + open: PE, + }; + } + if mxcsr & FTZ != 0 && tiny { + // The flags of an exact tiny result that is flushed are ambiguous. + return Outcome { + result: format.signed(negative, 0), + flags: UE | PE, + open: if exact { UE | PE } else { 0 }, + }; + } + if lowest + precision - 1 > format.max_exponent() { + let to_infinity = match mode { + 0 => true, + 1 => negative, + 2 => !negative, + _ => false, + }; + let magnitude = format.infinity() - u64::from(!to_infinity); + return Outcome { + result: format.signed(negative, magnitude), + flags: OE | PE, + open: if mxcsr & MASKS == 0 { PE } else { 0 }, + }; + } + let field = (lowest - floor) as u64; + let magnitude = (field << format.fraction_bits()) + value as u64; + let underflow = if tiny && !exact { UE } else { 0 }; + outcome(format.signed(negative, magnitude), inexact | underflow) +} + +fn square_root(value: u128) -> u128 { + let mut root = 0_u128; + for bit in (0..64).rev() { + let next = root | 1 << bit; + if next.checked_mul(next).is_some_and(|square| square <= value) { + root = next; + } + } + root +} + +/// ADD, SUB, MUL, DIV, SQRT, MIN and MAX of one lane. +fn float(op: &str, format: Format, a: u64, b: u64, mxcsr: u32) -> Outcome { + let unary = op == "sqrt"; + let flush = |value: u64| { + if mxcsr & DAZ != 0 && format.is_denormal(value) { + value & format.sign() + } else { + value + } + }; + let (a, b) = (flush(a), flush(b)); + let denormal = if format.is_denormal(b) || !unary && format.is_denormal(a) { + DE + } else { + 0 + }; + if matches!(op, "min" | "max") { + // SDM 2B MINSS/MAXSS and 1 11.5.2.1 Table 11-1. + if format.is_nan(a) || format.is_nan(b) { + return outcome(b, IE); + } + let order = |value: u64| { + let magnitude = i128::from(format.magnitude(value)); + if format.negative(value) { + -magnitude + } else { + magnitude + } + }; + let take_first = if op == "min" { + order(a) < order(b) + } else { + order(a) > order(b) + }; + return outcome(if take_first { a } else { b }, denormal); + } + // SDM 1 4.8.3.5 Table 4-8 and D.4.2.2 Tables D-1 and D-10. NaN operands come + // before a denormal operand in the priority list of 4.9.2. + let operands: &[u64] = if unary { &[b] } else { &[a, b] }; + if let Some(&nan) = operands.iter().find(|&&value| format.is_nan(value)) { + let signaling = operands.iter().any(|&value| format.is_snan(value)); + return outcome(nan | format.quiet(), if signaling { IE } else { 0 }); + } + let invalid = outcome(format.indefinite(), IE); + let sign_a = format.negative(a); + let sign_b = format.negative(b) != (op == "sub"); + let product_sign = format.negative(a) != format.negative(b); + let (infinite_a, infinite_b) = (format.is_infinite(a), format.is_infinite(b)); + let (zero_a, zero_b) = (format.is_zero(a), format.is_zero(b)); + let with_denormal = |mut result: Outcome| { + // An unmasked pre-computation exception hides later ones (11.5.3.2). + if mxcsr & MASKS == 0 && denormal != 0 { + result.flags = 0; + result.open = 0; + } + result.flags |= denormal; + result + }; + let (ma, ea) = format.split(a); + let (mb, eb) = format.split(b); + match op { + "add" | "sub" => { + if infinite_a && infinite_b && sign_a != sign_b { + return invalid; + } + if infinite_a || infinite_b { + let negative = if infinite_a { sign_a } else { sign_b }; + return with_denormal(outcome(format.signed(negative, format.infinity()), 0)); + } + // Keep 60 guard bits; anything further down is sticky. + let (high, low) = if (mb == 0 || ea >= eb) && ma != 0 { + ((ma, ea, sign_a), (mb, eb, sign_b)) + } else { + ((mb, eb, sign_b), (ma, ea, sign_a)) + }; + let (guarded, base) = (high.0 << 60, high.1 - 60); + let distance = low.1 - base; + let (aligned, lost) = if low.0 == 0 { + (0, false) + } else if distance >= 0 { + (low.0 << distance, false) + } else if distance > -127 { + let kept = low.0 >> -distance; + (kept, kept << -distance != low.0) + } else { + (0, true) + }; + let (negative, sum, sticky) = if high.2 == low.2 { + (high.2, guarded + aligned, lost) + } else if guarded >= aligned { + // Borrow the sticky remainder from the exact difference. + (high.2, guarded - aligned - u128::from(lost), lost) + } else { + assert!(!lost); + (low.2, aligned - guarded, false) + }; + if sum == 0 && !sticky { + let negative = if zero_a && zero_b && sign_a == sign_b { + sign_a + } else { + mxcsr >> 13 & 3 == 1 + }; + return with_denormal(outcome(format.signed(negative, 0), 0)); + } + with_denormal(deliver(format, negative, sum, base, sticky, mxcsr)) + } + "mul" => { + if infinite_a && zero_b || zero_a && infinite_b { + return invalid; + } + if infinite_a || infinite_b { + return with_denormal(outcome(format.signed(product_sign, format.infinity()), 0)); + } + if zero_a || zero_b { + return with_denormal(outcome(format.signed(product_sign, 0), 0)); + } + with_denormal(deliver( + format, + product_sign, + ma * mb, + ea + eb, + false, + mxcsr, + )) + } + "div" => { + if infinite_a && infinite_b || zero_a && zero_b { + return invalid; + } + if infinite_a { + return with_denormal(outcome(format.signed(product_sign, format.infinity()), 0)); + } + if zero_b { + return Outcome { + result: format.signed(product_sign, format.infinity()), + flags: ZE, + open: DE, + }; + } + if infinite_b || zero_a { + return with_denormal(outcome(format.signed(product_sign, 0), 0)); + } + let up = ma.leading_zeros() as i32 - 2; + let dividend = ma << up; + let exact = dividend.is_multiple_of(mb); + with_denormal(deliver( + format, + product_sign, + dividend / mb, + ea - up - eb, + !exact, + mxcsr, + )) + } + "sqrt" => { + if zero_b { + return outcome(b, 0); + } + if format.negative(b) { + return Outcome { + open: DE, + ..invalid + }; + } + if infinite_b { + return outcome(b, 0); + } + let mut up = mb.leading_zeros() as i32 - 2; + up -= (eb - up) & 1; + let radicand = mb << up; + let root = square_root(radicand); + with_denormal(deliver( + format, + false, + root, + (eb - up) / 2, + root * root != radicand, + mxcsr, + )) + } + _ => panic!("{op}"), + } +} + +/// CVTSD2SS and CVTSS2SD (SDM 1 D.4.2.2 Tables D-11 and D-12). +fn convert_format(from: Format, to: Format, value: u64, mxcsr: u32) -> Outcome { + if from.is_nan(value) { + let fraction = value & mask(from.fraction_bits()); + let moved = if to.bits > from.bits { + fraction << (to.fraction_bits() - from.fraction_bits()) + } else { + fraction >> (from.fraction_bits() - to.fraction_bits()) + }; + let result = to.signed(from.negative(value), to.infinity() | to.quiet() | moved); + return outcome(result, if from.is_snan(value) { IE } else { 0 }); + } + let negative = from.negative(value); + if from.is_infinite(value) { + return outcome(to.signed(negative, to.infinity()), 0); + } + let denormal = from.is_denormal(value); + if from.is_zero(value) || denormal && mxcsr & DAZ != 0 { + return outcome(to.signed(negative, 0), 0); + } + let (significand, exponent) = from.split(value); + let mut result = deliver(to, negative, significand, exponent, false, mxcsr); + if denormal { + if mxcsr & MASKS == 0 { + (result.flags, result.open) = (0, 0); + } + result.flags |= DE; + } + result +} + +/// CVT(T)SS2SI and CVT(T)SD2SI (SDM 2A; no denormal exception, 1 11.5.2.2). +fn convert_integer(format: Format, value: u64, bits: u32, mode: u32, daz: bool) -> Outcome { + let indefinite = outcome(1 << (bits - 1), IE); + if format.is_nan(value) || format.is_infinite(value) { + return indefinite; + } + if format.is_zero(value) || daz && format.is_denormal(value) { + return outcome(0, 0); + } + let negative = format.negative(value); + let (significand, exponent) = format.split(value); + if exponent > 64 { + return indefinite; + } + let (magnitude, exact) = round_to(significand, exponent, false, 0, negative, mode); + let limit = 1_u128 << (bits - 1); + if magnitude > limit - u128::from(!negative) { + return indefinite; + } + let result = if negative { + (magnitude as u64).wrapping_neg() + } else { + magnitude as u64 + }; + outcome(result & mask(bits), if exact { 0 } else { PE }) +} + +/// Whether the manual requires #XM for these flags under `mxcsr`. +fn must_fault(flags: u32, mxcsr: u32) -> bool { + flags & !(mxcsr >> 7) & 0x3f != 0 +} + +/// Compares both engines with `want` for an instruction writing XMM1 or RAX. +fn expect_float( + bench: &mut Bench, + what: &str, + cpu: &CpuState, + want: Outcome, + write: impl Fn(&mut CpuState, u64), +) { + let faults = must_fault(want.flags, cpu.mxcsr.0); + let mut wanted = cpu.clone(); + if !faults { + write(&mut wanted, want.result); + } + let flags = cpu.mxcsr.0 | want.flags; + for engine in [Engine::Interpreter, Engine::Dbt] { + let (mut got, exit) = match engine { + Engine::Interpreter => run(engine, cpu, &mut bench.memory), + _ => run_dbt(&mut bench.dbt, cpu, &mut bench.memory, BUDGET), + }; + let exit_wanted = if faults { + ExitReason::SimdException + } else { + ExitReason::Halt + }; + let seen = got.mxcsr.0; + if !faults { + got.rip = wanted.rip; + } + got.mxcsr = wanted.mxcsr; + if exit != exit_wanted || (seen ^ flags) & !want.open != 0 || got != wanted { + panic!( + "{what} on {engine:?}: xmm1={:x} xmm2={:x} rax={:x} mxcsr={:x}\n got {exit:?} xmm1={:x} rax={:x} rip={:x} mxcsr={seen:x}\nwant {exit_wanted:?} xmm1={:x} rax={:x} rip={:x} mxcsr={flags:x} (open {:x})", + cpu.xmm[1], + cpu.xmm[2], + cpu.gpr[0], + cpu.mxcsr.0, + got.xmm[1], + got.gpr[0], + got.rip, + wanted.xmm[1], + wanted.gpr[0], + wanted.rip, + want.open + ); + } + bench.runs += 1; + } +} + +fn low(format: Format, base: u128, value: u64) -> u128 { + base & !u128::from(mask(format.bits)) | u128::from(value) +} + +/// Every rounding mode with and without FTZ and DAZ, masked and unmasked. +fn mxcsr_values() -> Vec { + let mut values = Vec::new(); + for mode in 0..4 { + for flush in [0, FTZ, DAZ, FTZ | DAZ] { + for masks in [MASKS, 0] { + values.push(masks | mode << 13 | flush); + } + } + } + values +} + +#[test] +fn scalar_float_sweep_matches_exact_rounding() { + let mut runs = 0; + for (op, forms) in FLOAT { + for (hex, format) in forms.iter().zip([SINGLE, DOUBLE]) { + let mut bench = Bench::new(hex); + for a in format.values() { + for b in format.values() { + for mxcsr in mxcsr_values() { + let mut cpu = initial_cpu(); + cpu.mxcsr = Mxcsr(mxcsr); + cpu.xmm[1] = low(format, cpu.xmm[1], a); + cpu.xmm[2] = low(format, cpu.xmm[2], b); + let want = float(op, format, a, b, mxcsr); + let what = format!("{op} {}", format.bits); + expect_float(&mut bench, &what, &cpu, want, |cpu, result| { + cpu.xmm[1] = low(format, cpu.xmm[1], result); + }); + } + } + } + runs += bench.runs; + } + } + println!("{runs} engine runs"); +} + +#[test] +fn float_conversion_sweep_matches_exact_rounding() { + const TO_INTEGER: [(&str, Format, u32, bool); 8] = [ + ("f30f2dc2", SINGLE, 32, false), + ("f3480f2dc2", SINGLE, 64, false), + ("f20f2dc2", DOUBLE, 32, false), + ("f2480f2dc2", DOUBLE, 64, false), + ("f30f2cc2", SINGLE, 32, true), + ("f3480f2cc2", SINGLE, 64, true), + ("f20f2cc2", DOUBLE, 32, true), + ("f2480f2cc2", DOUBLE, 64, true), + ]; + const FROM_INTEGER: [(&str, Format, u32); 4] = [ + ("f30f2ac8", SINGLE, 32), + ("f3480f2ac8", SINGLE, 64), + ("f20f2ac8", DOUBLE, 32), + ("f2480f2ac8", DOUBLE, 64), + ]; + let mut runs = 0; + for (hex, from, to) in [("f20f5aca", DOUBLE, SINGLE), ("f30f5aca", SINGLE, DOUBLE)] { + let mut bench = Bench::new(hex); + let mut values = from.values(); + // Doubles around the ends of the single range and its halfway points. + if from.bits == 64 { + for exponent in [-151, -150, -149, -127, -126, 0, 127, 128] { + let power = ((1023 + exponent) as u64) << 52; + for offset in [ + 0, + 1, + 1 << 28, + 1 << 29, + 3 << 28, + mask(52), + mask(52) - mask(28), + ] { + values.extend([power + offset, (power + offset) | (1 << 63)]); + } + } + } + for value in values { + for mxcsr in mxcsr_values() { + let mut cpu = initial_cpu(); + cpu.mxcsr = Mxcsr(mxcsr); + cpu.xmm[2] = low(from, cpu.xmm[2], value); + let want = convert_format(from, to, value, mxcsr); + expect_float(&mut bench, hex, &cpu, want, |cpu, result| { + cpu.xmm[1] = low(to, cpu.xmm[1], result); + }); + } + } + runs += bench.runs; + } + for (hex, format, bits, truncate) in TO_INTEGER { + let mut bench = Bench::new(hex); + let mut values = format.values(); + let bias = format.max_exponent(); + for exponent in [-1, 0, 1, 30, 31, 32, 51, 52, 62, 63, 64] { + let power = ((bias + exponent) as u64) << format.fraction_bits(); + for offset in [0, 1, mask(format.fraction_bits()), format.quiet()] { + values.extend([power + offset, (power + offset) | format.sign()]); + } + values.extend([power - 1, (power - 1) | format.sign()]); + } + for value in values { + for mxcsr in mxcsr_values() { + let mut cpu = initial_cpu(); + cpu.mxcsr = Mxcsr(mxcsr); + cpu.xmm[2] = low(format, cpu.xmm[2], value); + let mode = if truncate { 3 } else { mxcsr >> 13 & 3 }; + let want = convert_integer(format, value, bits, mode, mxcsr & DAZ != 0); + expect_float(&mut bench, hex, &cpu, want, |cpu, result| { + cpu.gpr[0] = result; + }); + } + } + runs += bench.runs; + } + for (hex, format, bits) in FROM_INTEGER { + let mut bench = Bench::new(hex); + let mut values = boundary_values(bits); + for shift in 20..bits { + for offset in [0, 1, 2, 3] { + let value = (1_u64 << shift | offset) & mask(bits); + values.extend([ + value, + value.wrapping_neg() & mask(bits), + !value & mask(bits), + ]); + } + } + for value in values { + for mxcsr in mxcsr_values() { + let mut cpu = initial_cpu(); + cpu.mxcsr = Mxcsr(mxcsr); + cpu.gpr[0] = dirty(value, bits); + let exact = signed(value, bits); + let want = if exact == 0 { + outcome(0, 0) + } else { + deliver(format, exact < 0, exact.unsigned_abs(), 0, false, mxcsr) + }; + expect_float(&mut bench, hex, &cpu, want, |cpu, result| { + cpu.xmm[1] = low(format, cpu.xmm[1], result); + }); + } + } + runs += bench.runs; + } + println!("{runs} engine runs"); +} + +/// COMISx, UCOMISx and all eight CMPSx predicates. +#[test] +fn float_comparison_sweep_matches_the_manual() { + const ORDERED: [(&str, Format, bool); 4] = [ + ("0f2fca", SINGLE, true), + ("0f2eca", SINGLE, false), + ("660f2fca", DOUBLE, true), + ("660f2eca", DOUBLE, false), + ]; + let mut runs = 0; + let mut programs: Vec<(String, Format, bool, Option)> = ORDERED + .iter() + .map(|&(hex, format, signals)| (hex.to_string(), format, signals, None)) + .collect(); + for predicate in 0..8 { + // LT, LE, NLT and NLE signal on quiet NaNs (SDM 1 11.5.2.1). + let signals = matches!(predicate, 1 | 2 | 5 | 6); + for (hex, format) in [("f30fc2ca", SINGLE), ("f20fc2ca", DOUBLE)] { + let hex = format!("{hex}{predicate:02x}"); + programs.push((hex, format, signals, Some(predicate))); + } + } + for (hex, format, signals, predicate) in programs { + let mut bench = Bench::new(&hex); + for a in format.values() { + for b in format.values() { + for mxcsr in mxcsr_values() { + let mut cpu = initial_cpu(); + cpu.mxcsr = Mxcsr(mxcsr); + cpu.xmm[1] = low(format, cpu.xmm[1], a); + cpu.xmm[2] = low(format, cpu.xmm[2], b); + set_flags(&mut cpu.flags, OF | SF | AF); + let (flags, relation) = compare(format, a, b, signals, mxcsr); + let want = outcome(0, flags); + expect_float(&mut bench, &hex, &cpu, want, |cpu, _| match predicate { + None => set_flags( + &mut cpu.flags, + match relation { + Relation::Unordered => ZF | PF | CF, + Relation::Greater => 0, + Relation::Less => CF, + Relation::Equal => ZF, + }, + ), + Some(predicate) => { + let base = match predicate & 3 { + 0 => relation == Relation::Equal, + 1 => relation == Relation::Less, + 2 => matches!(relation, Relation::Less | Relation::Equal), + _ => relation == Relation::Unordered, + }; + let yes = base != (predicate >= 4); + let lane = if yes { mask(format.bits) } else { 0 }; + cpu.xmm[1] = low(format, cpu.xmm[1], lane); + } + }); + } + } + } + runs += bench.runs; + } + println!("{runs} engine runs"); +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Relation { + Unordered, + Less, + Equal, + Greater, +} + +fn compare(format: Format, a: u64, b: u64, signals: bool, mxcsr: u32) -> (u32, Relation) { + if format.is_nan(a) || format.is_nan(b) { + let invalid = signals || format.is_snan(a) || format.is_snan(b); + return (if invalid { IE } else { 0 }, Relation::Unordered); + } + let daz = mxcsr & DAZ != 0; + let order = |value: u64| { + let magnitude = if daz && format.is_denormal(value) { + 0 + } else { + i128::from(format.magnitude(value)) + }; + if format.negative(value) { + -magnitude + } else { + magnitude + } + }; + let denormal = !daz && (format.is_denormal(a) || format.is_denormal(b)); + let relation = match order(a).cmp(&order(b)) { + std::cmp::Ordering::Less => Relation::Less, + std::cmp::Ordering::Equal => Relation::Equal, + std::cmp::Ordering::Greater => Relation::Greater, + }; + (if denormal { DE } else { 0 }, relation) +} + +// --------------------------------------------------------------------------- +// Instruction fetch +// --------------------------------------------------------------------------- + +/// Places `code` so that it ends where `CODE`'s page does, then runs it. +fn run_at_page_end( + engine: Engine, + code: &[u8], + second_page: Option<(MemoryPermissions, &[u8])>, +) -> (CpuState, ExitReason, u64) { + let start = PAGE - code.len(); + let mut page = vec![0xcc; PAGE]; + page[start..].copy_from_slice(code); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(CODE, PAGE, MemoryPermissions::READ_EXECUTE, &page) + .expect("map code"); + if let Some((permissions, bytes)) = second_page { + memory + .map_region_with_data(CODE + PAGE as u64, PAGE, permissions, bytes) + .expect("map second page"); + } + let mut cpu = initial_cpu(); + cpu.rip = CODE + start as u64; + let (cpu, exit) = run(engine, &cpu, &mut memory); + (cpu, exit, CODE + start as u64) +} + +/// `mov eax, 5` then `mov rbx, imm64` cut off after three bytes. +const TRUNCATED: [u8; 8] = [0xb8, 5, 0, 0, 0, 0x48, 0xbb, 0x11]; + +#[test] +fn instruction_spanning_two_executable_pages_executes() { + // SDM 1 3.2.1: the linear address space is contiguous across pages. + let rest = [0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xf4]; + for engine in ENGINES { + let second = Some((MemoryPermissions::READ_EXECUTE, &rest[..])); + let (cpu, exit, _) = run_at_page_end(engine, &TRUNCATED, second); + assert_eq!(exit, ExitReason::Halt, "{engine:?}"); + assert_eq!(cpu.gpr[0], 5, "{engine:?}"); + assert_eq!(cpu.gpr[3], 0x8877_6655_4433_2211, "{engine:?}"); + } +} + +#[test] +fn fetch_fault_is_precise_and_after_completed_instructions() { + // SDM 3A 7.5 and 7.15 (Interrupt 14, instruction fetch). + let next = CODE + PAGE as u64; + for engine in ENGINES { + let (cpu, exit, start) = run_at_page_end(engine, &TRUNCATED, None); + let unmapped = ExitReason::MemoryFault(MemoryError::UnmappedAddress(next)); + assert_eq!(exit, unmapped, "{engine:?}"); + assert_eq!((cpu.gpr[0], cpu.rip), (5, start + 5), "{engine:?}"); + assert_eq!(cpu.gpr[3], initial_cpu().gpr[3], "{engine:?}"); + + let second = Some((MemoryPermissions::READ_WRITE, &[0x22; 16][..])); + let (cpu, exit, start) = run_at_page_end(engine, &TRUNCATED, second); + let denied = ExitReason::MemoryFault(MemoryError::PermissionViolation { + address: next, + required: "execute", + }); + assert_eq!(exit, denied, "{engine:?}"); + assert_eq!((cpu.gpr[0], cpu.rip), (5, start + 5), "{engine:?}"); + } +} + +/// SDM 3A 11.1.3 option 1: store the new code, jump, then execute it. +fn self_modified_result(engine: Engine) -> (u64, u64, ExitReason) { + // call f; mov ecx, eax; mov byte ptr [f+1], 2; jmp +0; call f; hlt; + // f: mov eax, 1; ret + let code = hex_bytes("e81100000089c1c6050900000002eb00e801000000f4b801000000c3"); + let mut page = vec![0xcc; PAGE]; + page[..code.len()].copy_from_slice(&code); + let mut memory = Image::new().load(&[]); + let base = CODE + 0x10_0000 + 0x8_0000; + memory + .map_region_with_data(base, PAGE, MemoryPermissions::READ_WRITE_EXECUTE, &page) + .expect("map code"); + let mut cpu = initial_cpu(); + cpu.rip = base; + let (cpu, exit) = run(engine, &cpu, &mut memory); + (cpu.gpr[1], cpu.gpr[0], exit) +} + +#[test] +fn interpreter_executes_modified_code_after_a_jump() { + let wanted = (1, 2, ExitReason::Halt); + assert_eq!(self_modified_result(Engine::Interpreter), wanted); +} + +/// Known defect: the DBT keeps running the block it translated before the store. +#[test] +#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"] +fn defect_dbt_executes_modified_code_after_a_jump() { + for engine in [Engine::Dbt, Engine::DbtStepped] { + let wanted = (1, 2, ExitReason::Halt); + assert_eq!(self_modified_result(engine), wanted, "{engine:?}"); + } +} From 846589abce8fb00c593f81a23e1d516985363506 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:06:26 -0600 Subject: [PATCH 11/19] isa, scripts: second round of registry review fixes (#215) - A family file must be a regular file directly in the registry directory: links (and so second names for one file) are rejected. - Variant operand formats are compared by role (destination, then the sources in rule order), not by XML row order. - Malformed spec and verify values are diagnosed instead of raising. - vop3_vgpr2 declares variant_only = true in the data; the planner reads that flag instead of inferring it from which entries use the rule. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 50 +++++++++++++++---- crates/isa/semantics/rdna2/vop3.toml | 2 + docs/shaders/semantic-registry.md | 7 ++- scripts/qa/rdna2_plan.py | 10 ++-- tests/qa/test_rdna2_plan.py | 10 +++- .../test_generate_semantics.py | 41 ++++++++++++++- 6 files changed, 99 insertions(+), 21 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 7735cbf..b09c460 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -310,6 +310,9 @@ OPERAND_RULES = { {"field": "SRC1", "class": "vgpr"}, ], "max_literals": 0, + # Declared in the data, so every reader (the planner too) knows this + # rule only re-encodes declared forms. + "variant_only": True, }, # Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and # SRC2 the assembler's unused inline zero; the decoder rejects the rest. @@ -388,11 +391,16 @@ def load_registry(path=REGISTRY): raise RegistryError(f"{path.name}: a family file is included twice") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) + directory = (path.parent / path.stem).resolve() for include in includes: part_path = path.parent / include family = Path(include).stem.upper() if not part_path.is_file(): raise RegistryError(f"{path.name}: included family file {include} does not exist") + # A family file is a regular file directly in the registry directory, + # not a link to data elsewhere (nor a second name for another include). + if part_path.is_symlink() or part_path.resolve().parent != directory: + raise RegistryError(f"{path.name}: included family file {include} is a link or outside {path.stem}/") with open(part_path, "rb") as handle: part = tomllib.load(handle) unknown = sorted(set(part) - FAMILY_FILE_KEYS) @@ -727,6 +735,9 @@ def validate(registry, snapshot): errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}") _check_spec(label, form["spec"], documents, errors) verify = form["verify"] + if not isinstance(verify, list) or not all(isinstance(item, str) for item in verify): + errors.append(f"{label}: verify must be a list of evidence names") + verify = [] if not verify: errors.append(f"{label}: no verification requirement") if any(item not in EVIDENCE for item in verify): @@ -793,7 +804,11 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): ) _check_spec(label, variant["spec"], documents, errors) verify = variant["verify"] - if not verify or any(item not in EVIDENCE for item in verify) or len(set(verify)) != len(verify): + if ( + not isinstance(verify, list) or not all(isinstance(item, str) for item in verify) + or not verify or any(item not in EVIDENCE for item in verify) + or len(set(verify)) != len(verify) + ): errors.append(f"{label}: invalid verification requirements {verify}") # The XML check runs on the re-encoded declaration, so the variant's # operands must agree with the base form's widths, signedness and effects. @@ -802,14 +817,23 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): # data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3). base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"]))) - if base_xml and own_xml: - formats = [ - [row[1] for row in record["operands"] if row[0]] for record in (base_xml, own_xml) - ] - if formats[0] != formats[1]: - errors.append( - f"{label}: XML operand formats {formats[1]} differ from the form's {formats[0]}" - ) + base_rule = rules.get(base.get("operands")) + if base_xml and own_xml and isinstance(base_rule, dict): + # Operands correspond by role, in rule order: the destination, then + # each source (VSRC1 of VOP2 is SRC1 of VOP3). + def roles(rule, record): + by_field = {row[0]: row[1] for row in record["operands"] if row[0]} + fields = ([rule["dst"]["field"]] if "dst" in rule else []) + fields += [src["field"] for src in rule.get("src", [])] + return [(field, by_field.get(field)) for field in fields] + + pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml))) + for (base_field, base_format), (field, data_format) in pairs: + if base_format != data_format: + errors.append( + f"{label}: XML {field} format {data_format} differs from the form's " + f"{base_field} format {base_format}" + ) def _implemented_rule(form): @@ -831,10 +855,16 @@ def _rule_enum(form): def _check_spec(label, spec, documents, errors): has_guide = False + if not isinstance(spec, list): + errors.append(f"{label}: spec must be a list of references") + return for ref in spec: - if set(ref) != {"document", "section", "page"}: + if not isinstance(ref, dict) or set(ref) != {"document", "section", "page"}: errors.append(f"{label}: spec reference needs exactly document, section, page") continue + if not isinstance(ref["document"], str): + errors.append(f"{label}: spec document must be a name") + continue if ref["document"] not in documents: errors.append(f"{label}: spec cites undeclared document {ref['document']!r}") if not SECTION.match(str(ref["section"])): diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml index ecd1a6f..960e627 100644 --- a/crates/isa/semantics/rdna2/vop3.toml +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -18,6 +18,8 @@ src = [ { field = "SRC1", class = "vgpr" }, ] max_literals = 0 +# Only [[encoding_variant]] entries may use this rule; it hosts no new forms. +variant_only = true unsupported = [ "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", "src_float_inline", "src_special", "src_literal", "modifiers", "src2", diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 468de39..26f94dc 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -29,7 +29,7 @@ equals one file with the parts concatenated (splitting the original single file left `semantics_gen.rs` byte-identical). A family file may hold only `[operand_rules.*]`, `[[form]]` and `[[encoding_variant]]` entries of the family it is named after: `rdna2/vop2.toml` holds VOP2 rules and forms and nothing else. -Each include must be `rdna2/.toml`. The loader rejects a form, +Each include must be `rdna2/.toml`, a regular file in that directory (not a link). The loader rejects a form, rule or variant of another family, a rule declared in two files, root keys in a family file, any other include path, and a missing or repeated include. The coverage report and the RDNA2 planner use the same loader. Work on different @@ -60,7 +60,10 @@ bits, then an explicit match on the OP field), `base()` (the inherited form), `assembly_name()` and `semantics()`, and one `FORMS` row per variant after the forms. Because the enum has no undeclared members, an instruction cannot name a VOP3 encoding that does not exist. Every explicit XML operand of the variant, -destination included, must have the base encoding's data format. A +destination included, must have the data format of the base operand in the same +role (destination, then the sources in rule order). A variant-only rule says so +in the data (`variant_only = true`), so the RDNA2 planner does not count it as a +rule that can host new forms. A variant-only rule (one marked `variant_of` in the generator) cannot be used by a form. The validator rejects a variant of an undeclared form, one in the form's own family, a duplicate encoding of a form or a duplicate `(family, opcode)`, a diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index fd29f36..d878f68 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -200,10 +200,12 @@ def classify_unsupported( registry = data["registry"] rules = data["rules"] ops = _declared_ops(registry) - form_rules = {form.get("operands") for form in registry.get("form", [])} + # A rule declared `variant_only` re-encodes declared forms (for example the + # VOP3 encoding of a VOP2 form) and cannot host a new form of its family. variant_only_rules = { - variant.get("operands") for variant in registry.get("encoding_variant", []) - } - form_rules + name for name, rule in registry.get("operand_rules", {}).items() + if isinstance(rule, dict) and rule.get("variant_only") is True + } family_widths: dict[str, set[int]] = defaultdict(set) family_types: dict[str, set[str]] = defaultdict(set) for form in registry.get("form", []): @@ -225,8 +227,6 @@ def classify_unsupported( continue opcode = identified[(family, name)] reusable = sorted(op for op in ops if op) - # Rules that only encoding variants use (another encoding of an already - # declared form) cannot host a new form, so they do not count here. family_rule_names = [ n for n, (fam, _) in rules.items() if fam == family and n not in variant_only_rules ] diff --git a/tests/qa/test_rdna2_plan.py b/tests/qa/test_rdna2_plan.py index 103151d..2412771 100644 --- a/tests/qa/test_rdna2_plan.py +++ b/tests/qa/test_rdna2_plan.py @@ -70,15 +70,21 @@ class Rdna2Plan(unittest.TestCase): # A rule that only encoding variants use (vop3_vgpr2 re-encodes declared # VOP2 forms) cannot host a new VOP3 form such as V_FMA_F32. variant_rules = { - variant["operands"] for variant in self.data["registry"].get("encoding_variant", []) + name for name, rule in self.data["registry"]["operand_rules"].items() + if rule.get("variant_only") is True } if not variant_rules: - self.skipTest("no encoding variants declared") + self.skipTest("no variant-only operand rules declared") vop3 = classify_unsupported(self.data, families=["VOP3"]) self.assertTrue(vop3) for cand in vop3: self.assertNotIn(cand.operand_layout, variant_rules, cand.name) self.assertNotEqual(cand.status, "reuse-primitives", cand.name) + # The flag, not current usage, decides: without any variant using the + # rule, the family still has no rule for new forms. + data = dict(self.data, registry=dict(self.data["registry"], encoding_variant=[])) + for cand in classify_unsupported(data, families=["VOP3"]): + self.assertNotEqual(cand.status, "reuse-primitives", cand.name) def test_manifests_exclude_claims_and_stay_deterministic(self): cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index de461df..bae5e7e 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -881,11 +881,41 @@ class Validate(unittest.TestCase): snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"][0][1] = "FMT_NUM_F32" self.rejects( variants(), - "V_MIN_I32 (VOP3): XML operand formats ['FMT_NUM_F32', 'FMT_NUM_I32', 'FMT_NUM_I32'] " - "differ from the form's ['FMT_NUM_I32', 'FMT_NUM_I32', 'FMT_NUM_I32']", + "V_MIN_I32 (VOP3): XML VDST format FMT_NUM_F32 differs from the form's VDST format FMT_NUM_I32", snap, ) + def test_compares_variant_formats_by_role_not_row_order(self): + snap = snapshot() + rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] + rows[0], rows[1] = rows[1], rows[0] + self.assertEqual(self.errors(variants(), snap), []) + # A genuine mismatch on the second source is still reported by role. + rows[2][1] = U32 + self.rejects( + variants(), "V_MIN_I32 (VOP3): XML SRC1 format FMT_NUM_U32 differs from the form's VSRC1", snap + ) + + def test_rejects_malformed_spec_and_verify_without_a_traceback(self): + cases = ( + ("spec", 1, "spec must be a list of references"), + ("spec", [[]], "spec reference needs exactly document, section, page"), + ("spec", [{"document": [], "section": "1", "page": 1}], "spec document must be a name"), + ("verify", 1, "invalid verification requirements"), + ("verify", [[]], "invalid verification requirements"), + ) + for key, value, fragment in cases: + with self.subTest(key=key, value=value): + reg = variants() + reg["encoding_variant"][0][key] = value + self.rejects(reg, fragment) + for key, value, fragment in cases: + with self.subTest(form=True, key=key, value=value): + reg = variants() + form(reg, "V_MIN_I32")[key] = value + expected = "verify must be a list of evidence names" if key == "verify" else fragment + self.rejects(reg, expected) + def test_rejects_malformed_variant_fields_without_a_traceback(self): for key in ("of", "operands", "family"): with self.subTest(key=key): @@ -1236,6 +1266,13 @@ class LoadRegistry(unittest.TestCase): root = self.write(f'include = ["{include}"]\n', {"sop2.toml": ""}) self.fails(root, f"include {include!r} is not rdna2/.toml") + def test_rejects_a_family_file_that_is_a_link(self): + outside = self.dir / "outside.toml" + outside.write_text("", encoding="utf-8") + (self.dir / "rdna2" / "sop2.toml").symlink_to(outside) + root = self.write('include = ["rdna2/sop2.toml"]\n', {}) + self.fails(root, "included family file rdna2/sop2.toml is a link or outside rdna2/") + def test_rejects_a_missing_or_repeated_include(self): self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist") root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop2.toml"]\n', {"sop2.toml": ""}) From 06614f2219c4317a6e96a39589f38a405469599f Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:09:16 -0600 Subject: [PATCH 12/19] isa: third round of registry review fixes (#215) - The family directory must not be a link, and two includes must not be hard links to one file. - The role-based format comparison skips malformed rules (they keep their rule diagnostic instead of raising), and its test now reproduces the row-order case the old comparison got wrong. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 19 ++++++++++++++- .../test_generate_semantics.py | 23 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index b09c460..ec4c7f9 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -392,6 +392,9 @@ def load_registry(path=REGISTRY): rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) directory = (path.parent / path.stem).resolve() + if (path.parent / path.stem).is_symlink(): + raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + identities = set() for include in includes: part_path = path.parent / include family = Path(include).stem.upper() @@ -401,6 +404,10 @@ def load_registry(path=REGISTRY): # not a link to data elsewhere (nor a second name for another include). if part_path.is_symlink() or part_path.resolve().parent != directory: raise RegistryError(f"{path.name}: included family file {include} is a link or outside {path.stem}/") + status = part_path.stat() + if (status.st_dev, status.st_ino) in identities: + raise RegistryError(f"{path.name}: included family file {include} is another name for an included file") + identities.add((status.st_dev, status.st_ino)) with open(part_path, "rb") as handle: part = tomllib.load(handle) unknown = sorted(set(part) - FAMILY_FILE_KEYS) @@ -749,6 +756,16 @@ def validate(registry, snapshot): return errors +def _well_formed(rule): + """Whether a rule has the dst/src shape the operand checks read.""" + return ( + isinstance(rule, dict) + and isinstance(rule.get("src"), list) + and all(isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]) + and ("dst" not in rule or (isinstance(rule["dst"], dict) and isinstance(rule["dst"].get("field"), str))) + ) + + def variant_row(registry, variant): """The base form re-encoded: its declaration with the variant's identity.""" base = next(form for form in registry["form"] if form.get("name") == variant["of"]) @@ -818,7 +835,7 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"]))) base_rule = rules.get(base.get("operands")) - if base_xml and own_xml and isinstance(base_rule, dict): + if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule): # Operands correspond by role, in rule order: the destination, then # each source (VSRC1 of VOP2 is SRC1 of VOP3). def roles(rule, record): diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index bae5e7e..13ec5d4 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -10,6 +10,7 @@ snapshot are only read, never edited. Run from the repository root: import copy import importlib.util +import os import shutil import subprocess import sys @@ -887,15 +888,26 @@ class Validate(unittest.TestCase): def test_compares_variant_formats_by_role_not_row_order(self): snap = snapshot() + # Give both encodings an unsigned destination and signed sources, then + # list the VOP3 rows in another order: by role they still match. + snap["variants"][("V_MIN_I32", "ENC_VOP2")]["operands"][0][1] = U32 rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] + rows[0][1] = U32 rows[0], rows[1] = rows[1], rows[0] - self.assertEqual(self.errors(variants(), snap), []) + reg = variants() + errors = [error for error in self.errors(reg, snap) if "differs from the form" in error] + self.assertEqual(errors, []) # A genuine mismatch on the second source is still reported by role. rows[2][1] = U32 self.rejects( variants(), "V_MIN_I32 (VOP3): XML SRC1 format FMT_NUM_U32 differs from the form's VSRC1", snap ) + def test_a_malformed_variant_rule_is_a_diagnostic(self): + reg = variants() + reg["operand_rules"]["vop3_vgpr2"]["src"] = 1 + self.rejects(reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule") + def test_rejects_malformed_spec_and_verify_without_a_traceback(self): cases = ( ("spec", 1, "spec must be a list of references"), @@ -1273,6 +1285,15 @@ class LoadRegistry(unittest.TestCase): root = self.write('include = ["rdna2/sop2.toml"]\n', {}) self.fails(root, "included family file rdna2/sop2.toml is a link or outside rdna2/") + def test_rejects_a_linked_directory_or_a_hard_link_alias(self): + root = self.write('include = ["rdna2/sop2.toml", "rdna2/vop2.toml"]\n', {"sop2.toml": ""}) + os.link(self.dir / "rdna2" / "sop2.toml", self.dir / "rdna2" / "vop2.toml") + self.fails(root, "included family file rdna2/vop2.toml is another name for an included file") + outside = self.dir / "outside" + (self.dir / "rdna2").rename(outside) + (self.dir / "rdna2").symlink_to(outside, target_is_directory=True) + self.fails(root, "the family directory rdna2/ is a link") + def test_rejects_a_missing_or_repeated_include(self): self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist") root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop2.toml"]\n', {"sop2.toml": ""}) From 625e26affc5c0b09c3892377e7759c337515f4f1 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:10:51 -0600 Subject: [PATCH 13/19] isa: fourth round of registry review fixes (#215) A self-referential family-directory link is reported instead of raising, a malformed rule destination field is a rule diagnostic in the XML check too, and the row-order test asserts a fully valid registry so it catches the old row-order comparison. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 9 +++++---- .../test_generate_semantics.py | 17 +++++++++++------ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index ec4c7f9..ed680c8 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -391,9 +391,12 @@ def load_registry(path=REGISTRY): raise RegistryError(f"{path.name}: a family file is included twice") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) - directory = (path.parent / path.stem).resolve() if (path.parent / path.stem).is_symlink(): raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + try: + directory = (path.parent / path.stem).resolve(strict=True) + except (OSError, RuntimeError) as error: + raise RegistryError(f"{path.name}: the family directory {path.stem}/ cannot be read: {error}") identities = set() for include in includes: part_path = path.parent / include @@ -526,9 +529,7 @@ def _check_xml(form, rule, snapshot, errors): errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output") if rule is None: return - if not isinstance(rule.get("src"), list) or not all( - isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"] - ) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])): + if not _well_formed(rule): return # the rule check already reported the malformed shape fields = [(rule["dst"]["field"], False)] if "dst" in rule else [] fields += [(src["field"], True) for src in rule["src"]] diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 13ec5d4..d2be136 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -894,9 +894,7 @@ class Validate(unittest.TestCase): rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] rows[0][1] = U32 rows[0], rows[1] = rows[1], rows[0] - reg = variants() - errors = [error for error in self.errors(reg, snap) if "differs from the form" in error] - self.assertEqual(errors, []) + self.assertEqual(self.errors(variants(), snap), []) # A genuine mismatch on the second source is still reported by role. rows[2][1] = U32 self.rejects( @@ -904,9 +902,13 @@ class Validate(unittest.TestCase): ) def test_a_malformed_variant_rule_is_a_diagnostic(self): - reg = variants() - reg["operand_rules"]["vop3_vgpr2"]["src"] = 1 - self.rejects(reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule") + for key, value in (("src", 1), ("dst", {"field": [], "class": "vgpr", "min": 0, "max": 255})): + with self.subTest(key=key): + reg = variants() + reg["operand_rules"]["vop3_vgpr2"][key] = value + self.rejects( + reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule" + ) def test_rejects_malformed_spec_and_verify_without_a_traceback(self): cases = ( @@ -1293,6 +1295,9 @@ class LoadRegistry(unittest.TestCase): (self.dir / "rdna2").rename(outside) (self.dir / "rdna2").symlink_to(outside, target_is_directory=True) self.fails(root, "the family directory rdna2/ is a link") + (self.dir / "rdna2").unlink() + (self.dir / "rdna2").symlink_to(self.dir / "rdna2", target_is_directory=True) + self.fails(root, "the family directory rdna2/ is a link") def test_rejects_a_missing_or_repeated_include(self): self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist") From 06ded40d549e8639ad2d13f21ed99e60d20ab4f2 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:26:23 -0600 Subject: [PATCH 14/19] isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215) - A standalone registry (no include) no longer needs a family directory. - A variant of an incomplete form reports the form instead of a KeyError. - A non-array encoding_variant, or a non-table entry, is a diagnostic in the loader, the validator and the coverage report. Each case has a test that fails on the previous code. The split-registry test now compares the whole merged result with a hand concatenation, and vop3.toml cites guide 12.7.1 for the VOP3 opcode offset. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 38 +++++++++++++--- crates/isa/semantics/rdna2/vop3.toml | 2 + scripts/audit/semantic_coverage.py | 10 ++++- .../test_semantic_coverage.py | 5 +++ .../test_generate_semantics.py | 45 +++++++++++++++++++ 5 files changed, 92 insertions(+), 8 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index ed680c8..00db2d0 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -389,14 +389,22 @@ def load_registry(path=REGISTRY): ) if len(set(includes)) != len(includes): raise RegistryError(f"{path.name}: a family file is included twice") + for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"), + ("encoding_variant", list, "an array")): + if not isinstance(registry.get(key, kind()), kind): + raise RegistryError(f"{path.name}: {key} must be {name}") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) - if (path.parent / path.stem).is_symlink(): - raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") - try: - directory = (path.parent / path.stem).resolve(strict=True) - except (OSError, RuntimeError) as error: - raise RegistryError(f"{path.name}: the family directory {path.stem}/ cannot be read: {error}") + # A standalone registry (no includes) needs no family directory. + if includes: + if (path.parent / path.stem).is_symlink(): + raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + try: + directory = (path.parent / path.stem).resolve(strict=True) + except (OSError, RuntimeError) as error: + raise RegistryError( + f"{path.name}: the family directory {path.stem}/ cannot be read: {error}" + ) identities = set() for include in includes: part_path = path.parent / include @@ -416,6 +424,10 @@ def load_registry(path=REGISTRY): unknown = sorted(set(part) - FAMILY_FILE_KEYS) if unknown: raise RegistryError(f"{include}: keys {unknown} belong in the root file") + for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"), + ("encoding_variant", list, "an array")): + if not isinstance(part.get(key, kind()), kind): + raise RegistryError(f"{include}: {key} must be {name}") for name, rule in part.get("operand_rules", {}).items(): if name in rules: raise RegistryError(f"{include}: operand rule {name} is declared twice") @@ -779,7 +791,14 @@ def variant_row(registry, variant): def _check_variants(registry, rules, documents, snapshot, seen, errors): forms = {form.get("name"): form for form in registry.get("form", [])} identities = {(form.get("name"), form.get("family")) for form in registry.get("form", [])} - for index, variant in enumerate(registry.get("encoding_variant", [])): + variants = registry.get("encoding_variant", []) + if not isinstance(variants, list): + errors.append("encoding_variant must be an array of tables") + return + for index, variant in enumerate(variants): + if not isinstance(variant, dict): + errors.append(f"encoding variant #{index}: must be a table, got {variant!r}") + continue label = f"{variant.get('of', f'variant #{index}')!s} ({variant.get('family')!s})" missing = sorted(VARIANT_KEYS - set(variant)) extra = sorted(set(variant) - VARIANT_KEYS) @@ -830,6 +849,11 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): errors.append(f"{label}: invalid verification requirements {verify}") # The XML check runs on the re-encoded declaration, so the variant's # operands must agree with the base form's widths, signedness and effects. + # An incomplete base form has its own diagnostic; checking its re-encoding + # would only fail on the missing fields. + if FORM_KEYS - set(base): + errors.append(f"{label}: not checked, its form {variant['of']} is incomplete") + continue _check_xml(variant_row(registry, variant), rule, snapshot, errors) # Every explicit operand, destination included, has the base encoding's # data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3). diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml index 960e627..cffcc80 100644 --- a/crates/isa/semantics/rdna2/vop3.toml +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -25,6 +25,8 @@ unsupported = [ "src_float_inline", "src_special", "src_literal", "modifiers", "src2", ] +# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256 +# = 293; each opcode below is still checked against the pinned XML. [[encoding_variant]] of = "V_ADD_NC_U32" family = "VOP3" diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 3fca878..498a0e9 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -180,10 +180,18 @@ def read_declarations(registry, identified): declared = set() # An encoding variant declares its base form in another encoding family. + raw_variants = registry.get("encoding_variant", []) + if not isinstance(raw_variants, list) or not all( + isinstance(variant, dict) and {"family", "of", "opcode", "operands"} <= set(variant) + for variant in raw_variants + ): + raise ValueError( + f"{REGISTRY}: every encoding_variant needs family, of, opcode and operands" + ) variants = [ {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], "operands": variant["operands"]} - for variant in registry.get("encoding_variant", []) + for variant in raw_variants ] for form in registry["form"] + variants: key = (form["family"], form["name"]) diff --git a/tests/semantic_coverage/test_semantic_coverage.py b/tests/semantic_coverage/test_semantic_coverage.py index 0147cac..bcf019b 100644 --- a/tests/semantic_coverage/test_semantic_coverage.py +++ b/tests/semantic_coverage/test_semantic_coverage.py @@ -68,6 +68,11 @@ class SemanticCoverageTests(unittest.TestCase): # S_ADD_U32 is declared in the registry but absent from the compiled tables. self.assertEqual(self.counts()["Decoder-supported"], 1) + def test_a_variant_without_its_form_is_an_error_not_a_traceback(self): + self.registry["encoding_variant"] = [{"family": "VOP3", "opcode": 1, "operands": "x"}] + with self.assertRaisesRegex(ValueError, "every encoding_variant needs"): + coverage.read_declarations(self.registry, self.identified) + def test_generated_table_parser(self): source = ( "pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n" diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index d2be136..fce2781 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -937,6 +937,22 @@ class Validate(unittest.TestCase): reg["encoding_variant"][0][key] = [] self.rejects(reg, f"[{key!r}] must be strings") + def test_a_variant_of_an_incomplete_form_reports_the_form_not_a_traceback(self): + reg = variants() + base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"]) + del base["width"] + errors = self.errors(reg) + self.assertTrue(any("missing ['width']" in error for error in errors), errors) + self.assertTrue(any("is incomplete" in error for error in errors), errors) + + def test_a_non_array_or_non_table_variant_is_a_diagnostic(self): + reg = variants() + reg["encoding_variant"] = 1 + self.rejects(reg, "encoding_variant must be an array of tables") + reg = variants() + reg["encoding_variant"].append(1) + self.rejects(reg, "must be a table, got 1") + def test_renders_variant_dispatch_and_rows(self): text = gen.render(variants(), snapshot()) self.assertIn("pub enum VectorAluVop3Op {", text) @@ -1230,6 +1246,18 @@ class LoadRegistry(unittest.TestCase): gen.load_registry(root) self.assertIn(fragment, str(raised.exception)) + def test_a_standalone_registry_needs_no_family_directory(self): + (self.dir / "rdna2").rmdir() + root = self.write('[[form]]\nname = "S_ADD_U32"\nfamily = "SOP2"\n', {}) + self.assertEqual(gen.load_registry(root)["form"][0]["name"], "S_ADD_U32") + root.write_text("schema = 1\ninclude = []\n", encoding="utf-8") + self.assertEqual(gen.load_registry(root)["form"], []) + + def test_a_malformed_variant_list_is_a_registry_error(self): + self.fails(self.write("encoding_variant = 1\n", {}), "encoding_variant must be an array") + root = self.write('include = ["rdna2/vop3.toml"]\n', {"vop3.toml": "encoding_variant = 1\n"}) + self.fails(root, "vop3.toml: encoding_variant must be an array") + def test_the_real_split_registry_equals_one_concatenated_file(self): registry = gen.load_registry() self.assertNotIn("include", registry) @@ -1240,6 +1268,23 @@ class LoadRegistry(unittest.TestCase): declared = set(runs) | {variant["family"] for variant in registry.get("encoding_variant", [])} for name, rule in registry["operand_rules"].items(): self.assertIn(rule["family"], declared, name) + # The whole merged result equals the files concatenated by hand: every + # form, rule and variant, in order, with nothing dropped or reordered. + import tomllib + + with open(gen.REGISTRY, "rb") as handle: + expected = tomllib.load(handle) + includes = expected.pop("include") + expected.setdefault("operand_rules", {}) + expected.setdefault("form", []) + for include in includes: + with open(gen.REGISTRY.parent / include, "rb") as handle: + part = tomllib.load(handle) + expected["operand_rules"].update(part.get("operand_rules", {})) + expected["form"] += part.get("form", []) + if "encoding_variant" in part: + expected.setdefault("encoding_variant", []).extend(part["encoding_variant"]) + self.assertEqual(registry, expected) def test_merges_family_files_in_include_order(self): root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { From e1e261ea8275222f3c6d6cd9b09bddac3238bfdf Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:30:54 -0600 Subject: [PATCH 15/19] isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215) v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32 and v_ashrrev_i32 (_e32) are now registry forms under a new operand rule vop2_vgpr2: both sources VGPRs, the subset the hand-written decoder accepted. The rule shares the VectorAluOp enum with vop2_vgpr; the generator renders one enum per shared rule set and an operand_rule() the decoder dispatches on. VectorBinary gains And, Or, Xor and the three shifts with the count masked to S0[4:0]; the shifts declare reversed sources, and the generator now checks the XML count format on SRC0 for reversed forms. The six hand-written Instruction variants, decoder arms and shader Binary variants are removed; the runtime-region allowlist admits exactly the same six forms. No behaviour change: 132,608 VOP2/VOP1/SOP1 words decode to the same text, length and error before and after; the MSL goldens are unchanged. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 64 +---- crates/decoder/tests/gfx1030.rs | 43 +-- crates/isa/generate_semantics.py | 56 +++- crates/isa/semantics/rdna2/vop2.toml | 125 +++++++++ crates/isa/src/lib.rs | 24 -- crates/isa/src/semantics.rs | 15 + crates/isa/src/semantics_gen.rs | 258 ++++++++++++++++-- crates/shader/src/lib.rs | 90 +++--- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 13 +- .../test_generate_semantics.py | 19 ++ 12 files changed, 530 insertions(+), 183 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ada8094..15209cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215. - Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches. - 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. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 398a88a..658bff2 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -10,13 +10,12 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32, - V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO, + V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO, }; use xenora_isa::meta::EncodingFamily; -use xenora_isa::semantics::FORM_IDS; pub use xenora_isa::semantics::VectorBinary; +use xenora_isa::semantics::{FORM_IDS, OperandRule}; /// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one /// operand combination: the hand-written forms below followed by every form of @@ -41,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -55,16 +54,10 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ ("S_WAITCNT", EncodingFamily::Sopp), ("S_WAITCNT_VSCNT", EncodingFamily::Sopk), ("V_ADD_F32", EncodingFamily::Vop2), - ("V_AND_B32", EncodingFamily::Vop2), - ("V_ASHRREV_I32", EncodingFamily::Vop2), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), ("V_INTERP_P2_F32", EncodingFamily::Vintrp), - ("V_LSHLREV_B32", EncodingFamily::Vop2), - ("V_LSHRREV_B32", EncodingFamily::Vop2), ("V_MOV_B32", EncodingFamily::Vop1), ("V_MUL_F32", EncodingFamily::Vop2), - ("V_OR_B32", EncodingFamily::Vop2), - ("V_XOR_B32", EncodingFamily::Vop2), ]; /// A successfully decoded instruction and its location in the input stream. @@ -401,7 +394,14 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco // VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24. let dst = ((first >> 17) & 0xff) as u8; let src1 = ((first >> 9) & 0xff) as u8; - let (src0, len) = vector_src0(first, bytes, op.assembly_name())?; + let (src0, len) = match op.operand_rule() { + // Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511). + OperandRule::Vop2Vgpr2 => { + let (_, src0, _) = vop2_registers(first, op.assembly_name())?; + (VectorSource::Register(src0), 4) + } + _ => vector_src0(first, bytes, op.assembly_name())?, + }; return Ok(( Instruction::VectorAlu { op, @@ -412,48 +412,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco len, )); } - if V_LSHLREV_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?; - return Ok(( - Instruction::VectorLshlrevB32 { dst, src0, src1 }, - V_LSHLREV_B32.byte_len(), - )); - } - if V_ASHRREV_I32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?; - return Ok(( - Instruction::VectorAshrrevI32 { dst, src0, src1 }, - V_ASHRREV_I32.byte_len(), - )); - } - if V_LSHRREV_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?; - return Ok(( - Instruction::VectorLshrrevB32 { dst, src0, src1 }, - V_LSHRREV_B32.byte_len(), - )); - } - if V_AND_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?; - return Ok(( - Instruction::VectorAndB32 { dst, src0, src1 }, - V_AND_B32.byte_len(), - )); - } - if V_OR_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?; - return Ok(( - Instruction::VectorOrB32 { dst, src0, src1 }, - V_OR_B32.byte_len(), - )); - } - if V_XOR_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?; - return Ok(( - Instruction::VectorXorB32 { dst, src0, src1 }, - V_XOR_B32.byte_len(), - )); - } if V_ADD_F32.matches(first) { let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?; return Ok(( diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index ae9f8b9..94a616d 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -432,22 +432,32 @@ fn reference_op(instruction: Instruction) -> Op { target, condition: BranchCondition::Always, }, - Instruction::VectorAndB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::And, dst, src0, src1) - } - Instruction::VectorLshlrevB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1) - } - Instruction::VectorAshrrevI32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1) - } - Instruction::VectorLshrrevB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ShiftRight, dst, src0, src1) - } - Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1), - Instruction::VectorXorB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::Xor, dst, src0, src1) - } + // The six logical and shift forms migrated from hand-written code + // (#215 M27) keep the reference's VGPR-only VectorAlu ops. + Instruction::VectorAlu { + op: + op @ (VectorAluOp::AndB32 + | VectorAluOp::OrB32 + | VectorAluOp::XorB32 + | VectorAluOp::LshlrevB32 + | VectorAluOp::LshrrevB32 + | VectorAluOp::AshrrevI32), + dst, + src0: VectorSource::Register(src0), + src1, + } => Op::Vector( + match op { + VectorAluOp::AndB32 => VectorAlu::And, + VectorAluOp::OrB32 => VectorAlu::Or, + VectorAluOp::XorB32 => VectorAlu::Xor, + VectorAluOp::LshlrevB32 => VectorAlu::ShiftLeft, + VectorAluOp::LshrrevB32 => VectorAlu::ShiftRight, + _ => VectorAlu::ArithmeticShiftRight, + }, + dst, + src0, + src1, + ), Instruction::VectorAddF32 { dst, src0, src1 } => { Op::Vector(VectorAlu::FloatAdd, dst, src0, src1) } @@ -500,6 +510,7 @@ fn reference_op(instruction: Instruction) -> Op { VectorAluOp::AddNcU32 => VectorInteger::Add, VectorAluOp::SubNcU32 => VectorInteger::Subtract, VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse, + _ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"), }, dst, match src0 { diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 00db2d0..055f2c6 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -222,6 +222,12 @@ VECTOR_PRIMITIVES = { ("mul24", "unsigned"): "Mul24Unsigned", ("mul_hi24", "signed"): "MulHi24Signed", ("mul_hi24", "unsigned"): "MulHi24Unsigned", + ("and", "bitwise"): "And", + ("or", "bitwise"): "Or", + ("xor", "bitwise"): "Xor", + ("lshl", "bitwise"): "ShiftLeft", + ("lshr", "bitwise"): "ShiftRight", + ("ashr", "signed"): "ArithmeticShiftRight", } # Operand rules the decoder implements, each exactly once. A registry rule must @@ -346,6 +352,26 @@ OPERAND_RULES = { }, "kind": "vector", }, + "vop2_vgpr2": { + "rust": "Vop2Vgpr2", + "enum": "VectorAluOp", + "shape": { + "family": "VOP2", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [ + {"field": "SRC0", "class": "vgpr"}, + {"field": "VSRC1", "class": "vgpr"}, + ], + "max_literals": 0, + }, + # The subset the hand-written decoder accepted before the registry (#215 + # M27): SRC0 must select a VGPR (256-511); the decoder rejects the rest. + "unsupported": { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", + }, + "kind": "vector", + }, } VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$") @@ -546,7 +572,8 @@ def _check_xml(form, rule, snapshot, errors): fields = [(rule["dst"]["field"], False)] if "dst" in rule else [] fields += [(src["field"], True) for src in rule["src"]] shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1 - count_field = rule["src"][1]["field"] if shift else None + # The shift count is S1, or S0 for a form that reads its sources reversed. + count_field = rule["src"][0 if SOURCE_ORDER_KEY in form else 1]["field"] if shift else None for field, is_source in fields: if field not in operands: errors.append(f"{label}: XML has no operand {field}") @@ -939,8 +966,15 @@ def render(registry, snapshot): "/// Registry schema of the generated tables.", f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};", ] + # Rules that share a generated enum (VOP2 `vop2_vgpr` and `vop2_vgpr2`) render + # it once, with the forms of all of them in registry order. + rendered = set() for rule_name in rule_names: - selected = [form for form in forms if form["operands"] == rule_name] + enum = OPERAND_RULES[rule_name]["enum"] + if enum in rendered: + continue + rendered.add(enum) + selected = [form for form in forms if OPERAND_RULES[form["operands"]]["enum"] == enum] out += _render_enum(rule_name, selected, snapshot, positions) variants = registry.get("encoding_variant", []) variant_positions = { @@ -1090,6 +1124,9 @@ def _render_variants(rule_name, variants, registry, snapshot, positions): def _render_enum(rule_name, forms, snapshot, positions): enum = OPERAND_RULES[rule_name]["enum"] kind = OPERAND_RULES[rule_name]["kind"] + rules = sorted({form["operands"] for form in forms}) + if any(OPERAND_RULES[name]["kind"] != kind for name in rules): + raise ValueError(f"{enum}: operand rules {rules} of one enum differ in kind") table = re.sub(r"(? 1 else ''} {', '.join(f'`{name}`' for name in rules)}).", "#[derive(Clone, Copy, Debug, Eq, PartialEq)]", f"pub enum {enum} {{", ] @@ -1238,6 +1276,18 @@ def _render_enum(rule_name, forms, snapshot, positions): f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'}," for form in forms ] + out += [ + " }", + " }", + "", + " /// The operand rule the decoder applies to the 32-bit encoding.", + " pub const fn operand_rule(self) -> OperandRule {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => OperandRule::{OPERAND_RULES[form['operands']]['rust']}," + for form in forms + ] out += [" }", " }", "}"] return out if kind == "vector_compare": diff --git a/crates/isa/semantics/rdna2/vop2.toml b/crates/isa/semantics/rdna2/vop2.toml index 1ccce38..bd91b2a 100644 --- a/crates/isa/semantics/rdna2/vop2.toml +++ b/crates/isa/semantics/rdna2/vop2.toml @@ -223,3 +223,128 @@ wave = "any" operands = "vop2_vgpr" spec = [{ document = "guide", section = "12.7", page = 134 }] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOP2 logical and shift forms migrated from hand-written code (#215 M27) ---- +# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The shifts read +# their sources reversed: D = S1 shifted by S0[4:0]; ASHRREV fills with S1's sign. +# These keep the subset the hand-written decoder accepted: both sources VGPRs. +[operand_rules.vop2_vgpr2] +family = "VOP2" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vgpr" }, + { field = "VSRC1", class = "vgpr" }, +] +max_literals = 0 +unsupported = [ + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", +] + +[[form]] +name = "V_LSHRREV_B32" +family = "VOP2" +opcode = 22 +variant = "LshrrevB32" +operation = "lshr" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_ASHRREV_I32" +family = "VOP2" +opcode = 24 +variant = "AshrrevI32" +operation = "ashr" +signedness = "signed" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_LSHLREV_B32" +family = "VOP2" +opcode = 26 +variant = "LshlrevB32" +operation = "lshl" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_AND_B32" +family = "VOP2" +opcode = 27 +variant = "AndB32" +operation = "and" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_OR_B32" +family = "VOP2" +opcode = 28 +variant = "OrB32" +operation = "or" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_XOR_B32" +family = "VOP2" +opcode = 29 +variant = "XorB32" +operation = "xor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index aad5376..e902f62 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -209,18 +209,6 @@ pub enum Instruction { BranchVccZero { target: usize }, /// SOPP unconditional jump to a stream byte offset. Branch { target: usize }, - /// VOP2 logical left shift with the count in src0. - VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 logical right shift with the count in src0. - VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 arithmetic right shift with the count in src0. - VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise AND. - VectorAndB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise OR. - VectorOrB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise XOR. - VectorXorB32 { dst: u8, src0: u8, src1: u8 }, /// VOP2 single-precision addition. Execution requires an explicit FP mode. VectorAddF32 { dst: u8, src0: u8, src1: u8 }, /// VOP2 single-precision multiplication. Execution requires an explicit FP mode. @@ -288,12 +276,6 @@ impl Instruction { Self::BranchExecZero { .. } => "s_cbranch_execz", Self::BranchVccZero { .. } => "s_cbranch_vccz", Self::Branch { .. } => "s_branch", - Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32", - Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32", - Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32", - Self::VectorAndB32 { .. } => "v_and_b32_e32", - Self::VectorOrB32 { .. } => "v_or_b32_e32", - Self::VectorXorB32 { .. } => "v_xor_b32_e32", Self::VectorAddF32 { .. } => "v_add_f32_e32", Self::VectorMulF32 { .. } => "v_mul_f32_e32", Self::Export { .. } => "exp", @@ -337,12 +319,6 @@ impl fmt::Display for Instruction { Self::VectorAluVop3 { dst, src0, src1, .. } - | Self::VectorLshlrevB32 { dst, src0, src1 } - | Self::VectorLshrrevB32 { dst, src0, src1 } - | Self::VectorAshrrevI32 { dst, src0, src1 } - | Self::VectorAndB32 { dst, src0, src1 } - | Self::VectorOrB32 { dst, src0, src1 } - | Self::VectorXorB32 { dst, src0, src1 } | Self::VectorAddF32 { dst, src0, src1 } | Self::VectorMulF32 { dst, src0, src1 } => { write!(formatter, " v{dst}, v{src0}, v{src1}") diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index 3ef28a0..4b38981 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -119,6 +119,18 @@ pub enum VectorBinary { MulHi24Signed, /// Bits 63:32 of `a[23:0] * b[23:0]`. MulHi24Unsigned, + /// `a & b`. + And, + /// `a | b`. + Or, + /// `a ^ b`. + Xor, + /// `a << (b & 31)`. + ShiftLeft, + /// Logical `a >> (b & 31)`. + ShiftRight, + /// Arithmetic (sign-filling) `a >> (b & 31)`. + ArithmeticShiftRight, } /// How the operands are interpreted. `Bitwise` exactly when the operation is logical. @@ -204,6 +216,9 @@ pub enum OperandRule { /// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is /// rejected as unsupported. Vop2Vgpr, + /// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs. + /// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported. + Vop2Vgpr2, } /// Evidence a form needs before it counts as verified. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 7f25966..af57a2d 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1198,7 +1198,7 @@ impl ScalarCompareOp { } } -/// VOP2 operations declared in the semantic registry (operand rule `vop2_vgpr`). +/// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`). #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAluOp { /// `v_mul_i32_i24` (VOP2 opcode 9): signed mul24, SCC = unchanged. @@ -1225,6 +1225,18 @@ pub enum VectorAluOp { SubNcU32, /// `v_subrev_nc_u32` (VOP2 opcode 39): unsigned sub, SCC = unchanged. SubrevNcU32, + /// `v_lshrrev_b32` (VOP2 opcode 22): bitwise lshr, SCC = unchanged. + LshrrevB32, + /// `v_ashrrev_i32` (VOP2 opcode 24): signed ashr, SCC = unchanged. + AshrrevI32, + /// `v_lshlrev_b32` (VOP2 opcode 26): bitwise lshl, SCC = unchanged. + LshlrevB32, + /// `v_and_b32` (VOP2 opcode 27): bitwise and, SCC = unchanged. + AndB32, + /// `v_or_b32` (VOP2 opcode 28): bitwise or, SCC = unchanged. + OrB32, + /// `v_xor_b32` (VOP2 opcode 29): bitwise xor, SCC = unchanged. + XorB32, } /// VectorAluOp by VOP2 OP field value; `None` for undeclared opcodes. @@ -1251,14 +1263,14 @@ const VECTOR_ALU_OP_BY_OPCODE: [Option; 64] = [ Some(VectorAluOp::MinU32), Some(VectorAluOp::MaxU32), None, + Some(VectorAluOp::LshrrevB32), None, + Some(VectorAluOp::AshrrevI32), None, - None, - None, - None, - None, - None, - None, + Some(VectorAluOp::LshlrevB32), + Some(VectorAluOp::AndB32), + Some(VectorAluOp::OrB32), + Some(VectorAluOp::XorB32), Some(VectorAluOp::XnorB32), None, None, @@ -1297,7 +1309,7 @@ const VECTOR_ALU_OP_BY_OPCODE: [Option; 64] = [ impl VectorAluOp { /// Every operation, in registry order. - pub const ALL: [Self; 12] = [ + pub const ALL: [Self; 18] = [ Self::MulI32I24, Self::MulHiI32I24, Self::MulU32U24, @@ -1310,6 +1322,12 @@ impl VectorAluOp { Self::AddNcU32, Self::SubNcU32, Self::SubrevNcU32, + Self::LshrrevB32, + Self::AshrrevI32, + Self::LshlrevB32, + Self::AndB32, + Self::OrB32, + Self::XorB32, ]; /// Selects the operation from a first instruction word: the VOP2 encoding @@ -1336,6 +1354,12 @@ impl VectorAluOp { Self::AddNcU32 => "v_add_nc_u32", Self::SubNcU32 => "v_sub_nc_u32", Self::SubrevNcU32 => "v_subrev_nc_u32", + Self::LshrrevB32 => "v_lshrrev_b32", + Self::AshrrevI32 => "v_ashrrev_i32", + Self::LshlrevB32 => "v_lshlrev_b32", + Self::AndB32 => "v_and_b32", + Self::OrB32 => "v_or_b32", + Self::XorB32 => "v_xor_b32", } } @@ -1354,6 +1378,12 @@ impl VectorAluOp { 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, }] } @@ -1372,6 +1402,12 @@ impl VectorAluOp { Self::AddNcU32 => "v_add_nc_u32_e32", Self::SubNcU32 => "v_sub_nc_u32_e32", Self::SubrevNcU32 => "v_subrev_nc_u32_e32", + Self::LshrrevB32 => "v_lshrrev_b32_e32", + Self::AshrrevI32 => "v_ashrrev_i32_e32", + Self::LshlrevB32 => "v_lshlrev_b32_e32", + Self::AndB32 => "v_and_b32_e32", + Self::OrB32 => "v_or_b32_e32", + Self::XorB32 => "v_xor_b32_e32", } } @@ -1390,6 +1426,12 @@ impl VectorAluOp { Self::AddNcU32 => VectorBinary::Add, Self::SubNcU32 => VectorBinary::Sub, Self::SubrevNcU32 => VectorBinary::Sub, + Self::LshrrevB32 => VectorBinary::ShiftRight, + Self::AshrrevI32 => VectorBinary::ArithmeticShiftRight, + Self::LshlrevB32 => VectorBinary::ShiftLeft, + Self::AndB32 => VectorBinary::And, + Self::OrB32 => VectorBinary::Or, + Self::XorB32 => VectorBinary::Xor, } } @@ -1408,6 +1450,36 @@ impl VectorAluOp { Self::AddNcU32 => false, Self::SubNcU32 => false, Self::SubrevNcU32 => true, + Self::LshrrevB32 => true, + Self::AshrrevI32 => true, + Self::LshlrevB32 => true, + Self::AndB32 => false, + Self::OrB32 => false, + Self::XorB32 => false, + } + } + + /// The operand rule the decoder applies to the 32-bit encoding. + pub const fn operand_rule(self) -> OperandRule { + match self { + Self::MulI32I24 => OperandRule::Vop2Vgpr, + Self::MulHiI32I24 => OperandRule::Vop2Vgpr, + Self::MulU32U24 => OperandRule::Vop2Vgpr, + Self::MulHiU32U24 => OperandRule::Vop2Vgpr, + Self::MinI32 => OperandRule::Vop2Vgpr, + Self::MaxI32 => OperandRule::Vop2Vgpr, + Self::MinU32 => OperandRule::Vop2Vgpr, + Self::MaxU32 => OperandRule::Vop2Vgpr, + Self::XnorB32 => OperandRule::Vop2Vgpr, + Self::AddNcU32 => OperandRule::Vop2Vgpr, + Self::SubNcU32 => OperandRule::Vop2Vgpr, + Self::SubrevNcU32 => OperandRule::Vop2Vgpr, + Self::LshrrevB32 => OperandRule::Vop2Vgpr2, + Self::AshrrevI32 => OperandRule::Vop2Vgpr2, + Self::LshlrevB32 => OperandRule::Vop2Vgpr2, + Self::AndB32 => OperandRule::Vop2Vgpr2, + Self::OrB32 => OperandRule::Vop2Vgpr2, + Self::XorB32 => OperandRule::Vop2Vgpr2, } } } @@ -1764,22 +1836,22 @@ impl VectorCompareOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::CmpLtI32 => 68, - Self::CmpEqI32 => 69, - Self::CmpLeI32 => 70, - Self::CmpGtI32 => 71, - Self::CmpNeI32 => 72, - Self::CmpGeI32 => 73, - Self::CmpLtU32 => 74, - Self::CmpEqU32 => 75, - Self::CmpLeU32 => 76, - Self::CmpGtU32 => 77, - Self::CmpNeU32 => 78, - Self::CmpGeU32 => 79, - Self::CmpFI32 => 80, - Self::CmpTI32 => 81, - Self::CmpFU32 => 82, - Self::CmpTU32 => 83, + 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, }] } @@ -1915,13 +1987,13 @@ impl VectorAluVop3Op { /// The validated registry row of this encoding. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::AddNcU32 => 84, + Self::AddNcU32 => 90, }] } } /// Identity of every registry form and encoding variant, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 91] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1990,6 +2062,12 @@ pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ("V_ADD_NC_U32", EncodingFamily::Vop2), ("V_SUB_NC_U32", EncodingFamily::Vop2), ("V_SUBREV_NC_U32", EncodingFamily::Vop2), + ("V_LSHRREV_B32", EncodingFamily::Vop2), + ("V_ASHRREV_I32", EncodingFamily::Vop2), + ("V_LSHLREV_B32", EncodingFamily::Vop2), + ("V_AND_B32", EncodingFamily::Vop2), + ("V_OR_B32", EncodingFamily::Vop2), + ("V_XOR_B32", EncodingFamily::Vop2), ("V_CMP_LT_I32", EncodingFamily::Vopc), ("V_CMP_EQ_I32", EncodingFamily::Vopc), ("V_CMP_LE_I32", EncodingFamily::Vopc), @@ -2010,7 +2088,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 85] = [ +pub static FORMS: [FormSemantics; 91] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3439,6 +3517,132 @@ pub static FORMS: [FormSemantics; 85] = [ spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 134 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_LSHRREV_B32", + family: EncodingFamily::Vop2, + opcode: 22, + operation: Operation::LogicalShiftRight, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_ASHRREV_I32", + family: EncodingFamily::Vop2, + opcode: 24, + operation: Operation::ArithmeticShiftRight, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_LSHLREV_B32", + family: EncodingFamily::Vop2, + opcode: 26, + operation: Operation::ShiftLeft, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_AND_B32", + family: EncodingFamily::Vop2, + opcode: 27, + operation: Operation::And, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_OR_B32", + family: EncodingFamily::Vop2, + opcode: 28, + operation: Operation::Or, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_XOR_B32", + family: EncodingFamily::Vop2, + opcode: 29, + operation: Operation::Xor, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "V_CMP_LT_I32", family: EncodingFamily::Vopc, diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index c61a905..2a1745b 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ - DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluVop3Op, VectorBinary, - VectorCompareOp, VectorSource, + DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op, + VectorBinary, VectorCompareOp, VectorSource, }; /// SGPR index of `vcc_lo`. @@ -156,14 +156,7 @@ impl Op { Binary::FloatAdd | Binary::FloatMul => format!( "as_type(as_type({left}) {symbol} as_type({right}))" ), - Binary::ArithmeticShiftRight => { - format!("as_type(as_type({left}) {symbol} ({right} & 31u))") - } - Binary::ShiftLeft | Binary::ShiftRight => { - format!("{left} {symbol} ({right} & 31u)") - } Binary::Vector(operation) => vector_expression(operation, &left, &right), - _ => format!("{left} {symbol} {right}"), } } Self::MergeLanes { @@ -215,12 +208,6 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { #[derive(Clone, Copy)] enum Binary { - ShiftLeft, - ShiftRight, - ArithmeticShiftRight, - And, - Or, - Xor, FloatAdd, FloatMul, /// A registry VOP2 integer operation (or its VOP3 encoding), lowered by its @@ -231,12 +218,6 @@ enum Binary { impl Binary { fn operator(self) -> (&'static str, &'static str) { match self { - Self::ShiftLeft => ("lshl.b32", "<<"), - Self::ShiftRight => ("lshr.b32", ">>"), - Self::ArithmeticShiftRight => ("ashr.i32", ">>"), - Self::And => ("and.b32", "&"), - Self::Or => ("or.b32", "|"), - Self::Xor => ("xor.b32", "^"), Self::FloatAdd => ("add.f32", "+"), Self::FloatMul => ("mul.f32", "*"), Self::Vector(operation) => ( @@ -252,6 +233,12 @@ impl Binary { VectorBinary::Mul24Unsigned => "mul24.u32", VectorBinary::MulHi24Signed => "mulhi24.i32", VectorBinary::MulHi24Unsigned => "mulhi24.u32", + VectorBinary::And => "and.b32", + VectorBinary::Or => "or.b32", + VectorBinary::Xor => "xor.b32", + VectorBinary::ShiftLeft => "lshl.b32", + VectorBinary::ShiftRight => "lshr.b32", + VectorBinary::ArithmeticShiftRight => "ashr.i32", }, "", ), @@ -286,6 +273,15 @@ fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String format!("as_type(mulhi({}, {}))", i24(left), i24(right)) } VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)), + VectorBinary::And => format!("{left} & {right}"), + VectorBinary::Or => format!("{left} | {right}"), + VectorBinary::Xor => format!("{left} ^ {right}"), + // MSL leaves shifts by 32 or more undefined; the guide reads S0[4:0]. + VectorBinary::ShiftLeft => format!("{left} << ({right} & 31u)"), + VectorBinary::ShiftRight => format!("{left} >> ({right} & 31u)"), + VectorBinary::ArithmeticShiftRight => { + format!("as_type(as_type({left}) >> ({right} & 31u))") + } } } @@ -689,12 +685,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result dst, + // Of the registry VOP2 forms, the contract admits only the six + // logical and shift forms that were hand-written before (#215 M27). + | Instruction::VectorAlu { + op: + VectorAluOp::LshlrevB32 + | VectorAluOp::LshrrevB32 + | VectorAluOp::AshrrevI32 + | VectorAluOp::AndB32 + | VectorAluOp::OrB32 + | VectorAluOp::XorB32, + dst, + .. + } => dst, _ => { return Err(error( "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms", @@ -728,12 +731,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result continue, @@ -851,27 +848,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result ( - Some(dst), - Op::Binary(Binary::ShiftLeft, read(src1)?, read(src0)?), - ), - Instruction::VectorAshrrevI32 { dst, src0, src1 } => ( - Some(dst), - Op::Binary(Binary::ArithmeticShiftRight, read(src1)?, read(src0)?), - ), - Instruction::VectorLshrrevB32 { dst, src0, src1 } => ( - Some(dst), - Op::Binary(Binary::ShiftRight, read(src1)?, read(src0)?), - ), - Instruction::VectorAndB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::And, read(src0)?, read(src1)?)) - } - Instruction::VectorOrB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::Or, read(src0)?, read(src1)?)) - } - Instruction::VectorXorB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::Xor, read(src0)?, read(src1)?)) - } Instruction::ScalarMoveB32 { dst, src } => { let value = read_scalar(src)?; if dst < 8 { @@ -1084,9 +1060,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result KnownBits::constant(bits), - Op::Binary(Binary::And, left, right) => facts[left.0].and(facts[right.0]), - Op::Binary(Binary::Or, left, right) => facts[left.0].or(facts[right.0]), - Op::Binary(Binary::Xor, left, right) => facts[left.0].xor(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::And), left, right) => facts[left.0].and(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::Or), left, right) => facts[left.0].or(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::Xor), left, right) => facts[left.0].xor(facts[right.0]), Op::Binary(operator @ (Binary::FloatAdd | Binary::FloatMul), left, right) => { exact_float_result(operator, facts[left.0], facts[right.0]) .ok_or_else(|| error("FP32 operation is not proven exact for positive normal operands and results"))? diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index d759c40..fa89193 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -31,12 +31,12 @@ acceptance remain outside the verified count. All results concern synthetic fixt | 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 | -| VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 | +| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 | | VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 104 | 85 | 108 | 104 | 104 | 18 | 18 | 56 | +| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 | ## Unsupported operand variants @@ -48,5 +48,6 @@ The table counts distinct variant names per family across registry operand rules | 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` | | 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` | | VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 26f94dc..794f094 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -151,7 +151,9 @@ fixes the `scc` value: | `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no | | `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no | -Vector forms (operand rule `vop2_vgpr`, kind `vector`) use a separate table: +Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both +generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder +which rule a form uses) use a separate table: the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc` must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC): @@ -161,6 +163,15 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC): | `xnor` / `bitwise` | `Xnor` | | `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` | | `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` | +| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` | +| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` | + +`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder +accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32` +and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them +to `vop2_vgpr` would be a behaviour change and needs its own oracle. The three +shifts declare `source_order = "reversed"` (D = S1 shifted by S0[4:0]), so the +generator checks the XML's unsigned count format on SRC0, not VSRC1. VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a `vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index fce2781..6a1ab46 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -371,6 +371,25 @@ class Validate(unittest.TestCase): def test_accepts_the_real_registry(self): self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), []) + def test_a_reversed_shift_takes_its_count_from_src0(self): + # V_ASHRREV_I32: D = S1 >> S0[4:0]; the XML gives SRC0 FMT_NUM_U32 (the + # count) and VSRC1 FMT_NUM_I32. Without the declared reversed order the + # count check lands on VSRC1 and must fail. + reg = gen.load_registry() + form = next(f for f in reg["form"] if f["name"] == "V_ASHRREV_I32") + del form["source_order"] + errors = gen.validate(reg, gen.load_snapshot()) + self.assertIn( + "V_ASHRREV_I32: control operand VSRC1 has XML format FMT_NUM_I32, not FMT_NUM_U32", + errors, + ) + + def test_rules_sharing_an_enum_render_it_once_with_each_forms_rule(self): + text = gen.render(gen.load_registry(), gen.load_snapshot()) + self.assertEqual(text.count("pub enum VectorAluOp {"), 1) + self.assertIn("Self::AndB32 => OperandRule::Vop2Vgpr2,", text) + self.assertIn("Self::MinI32 => OperandRule::Vop2Vgpr,", text) + # ---- top level ---- def test_rejects_wrong_schema(self): From 263284ff4fb91004e66735bd37b3817cf3700947 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:34:00 -0600 Subject: [PATCH 16/19] isa, scripts: two more registry crash paths become diagnostics (#215) - A variant whose first duplicate base form is incomplete: the completeness check and the XML check now use the same base row (no KeyError). - qa rdna2 inventory and rank report a malformed encoding_variant (missing 'of', non-string operands) as an error with exit 2, not a traceback; the coverage reader checks the field types. Each has a test that fails on the previous code. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 9 ++-- scripts/audit/semantic_coverage.py | 8 ++- scripts/qa/__main__.py | 14 +++++- tests/qa/test_rdna2_malformed_registry.py | 49 +++++++++++++++++++ .../test_generate_semantics.py | 9 ++++ 5 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 tests/qa/test_rdna2_malformed_registry.py diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 00db2d0..38bf856 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -779,9 +779,10 @@ def _well_formed(rule): ) -def variant_row(registry, variant): +def variant_row(registry, variant, base=None): """The base form re-encoded: its declaration with the variant's identity.""" - base = next(form for form in registry["form"] if form.get("name") == variant["of"]) + if base is None: + base = next(form for form in registry["form"] if form.get("name") == variant["of"]) return dict( base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"], spec=variant["spec"], verify=variant["verify"], @@ -854,7 +855,9 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): if FORM_KEYS - set(base): errors.append(f"{label}: not checked, its form {variant['of']} is incomplete") continue - _check_xml(variant_row(registry, variant), rule, snapshot, errors) + # The same base row as the completeness check above (with duplicate + # declarations, the dict keeps the last one). + _check_xml(variant_row(registry, variant, base), rule, snapshot, errors) # Every explicit operand, destination included, has the base encoding's # data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3). base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 498a0e9..f7075a2 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -182,11 +182,15 @@ def read_declarations(registry, identified): # An encoding variant declares its base form in another encoding family. raw_variants = registry.get("encoding_variant", []) if not isinstance(raw_variants, list) or not all( - isinstance(variant, dict) and {"family", "of", "opcode", "operands"} <= set(variant) + isinstance(variant, dict) + and {"family", "of", "opcode", "operands"} <= set(variant) + and all(isinstance(variant[key], str) for key in ("family", "of", "operands")) + and type(variant["opcode"]) is int for variant in raw_variants ): raise ValueError( - f"{REGISTRY}: every encoding_variant needs family, of, opcode and operands" + f"{REGISTRY}: every encoding_variant needs string family, of and operands" + " and an integer opcode" ) variants = [ {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], diff --git a/scripts/qa/__main__.py b/scripts/qa/__main__.py index 8876930..aeb0b48 100644 --- a/scripts/qa/__main__.py +++ b/scripts/qa/__main__.py @@ -172,7 +172,12 @@ def main(argv: list[str] | None = None) -> int: if args.command == "rdna2" and args.action == "rank": from .rdna2_rank import run_rank - return run_rank(_root(), args) + try: + return run_rank(_root(), args) + except ValueError as exc: + # A malformed registry is a diagnostic, not a traceback. + print(f"rdna2: {exc}", file=sys.stderr) + return 2 if args.command == "rdna2" and args.no_float: r.error("--no-float requires the rank action") root = _root() @@ -263,7 +268,12 @@ def main(argv: list[str] | None = None) -> int: else: print(json.dumps(payload, indent=2, sort_keys=True)) return 0 - data = load_inventories(root) + try: + data = load_inventories(root) + except ValueError as exc: + # A malformed registry is a diagnostic, not a traceback. + print(f"rdna2: {exc}", file=sys.stderr) + return 2 inv = summarize_inventory(data) exclude_families: list[str] = [] claimed_paths: list[str] = [] diff --git a/tests/qa/test_rdna2_malformed_registry.py b/tests/qa/test_rdna2_malformed_registry.py new file mode 100644 index 0000000..5cae41b --- /dev/null +++ b/tests/qa/test_rdna2_malformed_registry.py @@ -0,0 +1,49 @@ +"""A malformed encoding variant gives the planner a diagnostic, not a traceback.""" + +import contextlib +import io +import unittest +from unittest import mock + +import qa.__main__ as cli +from qa import rdna2_plan +from audit import semantic_coverage as coverage + + +def malformed_loader(variant): + def load(_root): + registry = { + "schema": 1, + "form": [{"family": "SOP2", "name": "S_ADD_U32", "opcode": 0, + "operands": "scalar", "verify": ["reference"]}], + "operand_rules": {"scalar": {"family": "SOP2", "unsupported": ["two_literals"]}}, + "encoding_variant": [variant], + } + # The real reader, as load_inventories uses it. + coverage.read_declarations(registry, {("SOP2", "S_ADD_U32"): 0}) + raise AssertionError("the malformed variant was accepted") + + return load + + +class MalformedVariant(unittest.TestCase): + def test_inventory_and_rank_report_registry_errors(self): + variants = { + "missing of": {"family": "VOP3", "opcode": 1, "operands": "x"}, + "list operands": {"family": "VOP3", "of": "S_ADD_U32", "opcode": 1, "operands": []}, + } + for action in ("inventory", "rank"): + for name, variant in variants.items(): + with self.subTest(action=action, variant=name): + stderr = io.StringIO() + loader = malformed_loader(variant) + with mock.patch.object(cli, "load_inventories", loader), \ + mock.patch.object(rdna2_plan, "load_inventories", loader), \ + contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): + code = cli.main(["rdna2", action]) + self.assertEqual(code, 2) + self.assertIn("encoding_variant needs", stderr.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index fce2781..b2a5a1c 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -945,6 +945,15 @@ class Validate(unittest.TestCase): self.assertTrue(any("missing ['width']" in error for error in errors), errors) self.assertTrue(any("is incomplete" in error for error in errors), errors) + def test_a_variant_of_an_incomplete_first_duplicate_is_a_diagnostic(self): + reg = variants() + base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"]) + incomplete = copy.deepcopy(base) + del incomplete["width"] + reg["form"].insert(reg["form"].index(base), incomplete) + errors = self.errors(reg) + self.assertTrue(any("missing ['width']" in error for error in errors), errors) + def test_a_non_array_or_non_table_variant_is_a_diagnostic(self): reg = variants() reg["encoding_variant"] = 1 From d6b751976d56a6e29c3068d5f25f04dcec4173b5 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:35:00 -0600 Subject: [PATCH 17/19] docs, shader, isa: review fixes for the VOP2 logical and shift move (#215) The registry doc states where a reversed shift takes its count and which side masks it, and that a family may have several operand rules; the runtime-region rejection message and a test comment no longer call the six forms hand-written. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/tests/semantics.rs | 4 ++-- crates/shader/src/lib.rs | 2 +- docs/shaders/semantic-registry.md | 13 +++++++------ 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 14826d0..744f085 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -102,8 +102,8 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() { assert_eq!(op.swaps_sources(), row.swap_sources); assert_eq!(row.scc, SccEffect::Unchanged); } - // The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be - // dispatched here. + // Exactly the registry VOP2 forms are dispatched here; the hand-written + // ones (v_add_f32, v_mul_f32) must not be. dispatch_selects_exactly(EncodingFamily::Vop2, |word| { VectorAluOp::from_word(word).map(|op| op.semantics().name) }); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 2a1745b..4007f67 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -700,7 +700,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result dst, _ => { return Err(error( - "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms", + "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the VOP2 logical and shift forms", )); } }; diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 794f094..a655d01 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -90,12 +90,13 @@ The root file holds: `guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD machine-readable ISA) are allowed, and each must match the title and file pinned in the generator, so a citation cannot point at another file. -- `[operand_rules.]`: an operand rule shared by a whole family. The - decoder implements each rule once, and the generator only accepts a rule - whose declaration matches the decoder's implementation exactly. Today there - is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources +- `[operand_rules.]`: an operand rule of one family, shared by its forms. + The decoder implements each rule once, and the generator only accepts a rule + whose declaration matches the decoder's implementation exactly. A family may + have several rules (VOP2 has `vop2_vgpr` and the VGPR-only `vop2_vgpr2`). For + example `sop2_sgpr` is an SGPR destination `s0`-`s105`, two scalar sources (an SGPR, an inline integer -16 to 64, or a literal word) and at most one - literal. Its `unsupported` list names the encodings the rule rejects, which + literal. A rule's `unsupported` list names the encodings it rejects, which stay unsupported instead of being guessed. The list must name exactly the encodings the decoder rejects. @@ -116,7 +117,7 @@ error. | `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere | | `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 S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere | +| `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` | | `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` | From c586a4a82a2d90a8d678ee586815b1b25ec583a4 Mon Sep 17 00:00:00 2001 From: jelly013 <22855910+jelly013@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:41:20 +0100 Subject: [PATCH 18/19] test(loader): tighten the x86-64 known answers after review (#155) Pin MXCSR for a flushed exact tiny result, PE for unmasked overflow and underflow, and run the sweeps with each exception unmasked alone. Require a refused form to stop at its exact instruction with all state unchanged, assert the cached DBT run hits the cache, and check the fallback counter for every straight-line case. Add a faulting zero-count memory shift. The tighter checks expose one more defect, kept as an ignored test: an exact unmasked overflow sets PE as well as OE. Correct the chronology: 700 table cases were written before the CPU source was read, and the other cases and the sweeps afterwards. The message of 1c5c320 says otherwise. Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com> --- CHANGELOG.md | 2 +- crates/loader/tests/cpu_known_answers.rs | 486 ++++++++++++++--------- 2 files changed, 292 insertions(+), 196 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2d18b7..2063696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ remains unsupported. - 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`. - Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`. -- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 727 x86-64 cases whose results, flags, MXCSR state and faults were derived from the Intel SDM before the CPU code was read, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manual's definitions. The interpreter and the DBT both run them, and the DBT route (ARM64 code or Rust helper) of each verified instruction is recorded. 588 cases are verified, 133 use forms both engines refuse, and six, plus a self-modifying-code test, record open defects in four ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review. +- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review. - Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`. - Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet. - Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware. diff --git a/crates/loader/tests/cpu_known_answers.rs b/crates/loader/tests/cpu_known_answers.rs index 8a22c9c..02367b8 100644 --- a/crates/loader/tests/cpu_known_answers.rs +++ b/crates/loader/tests/cpu_known_answers.rs @@ -2,11 +2,19 @@ //! Architectural known answers for the guest CPU (issue #155). //! -//! Every expectation here was derived from the Intel 64 and IA-32 Architectures -//! Software Developer's Manual, revision 093 (September 2026), before the -//! interpreter, the DBT or their existing tests were read. Encodings were -//! produced by Apple clang's x86-64 assembler and read back with `objdump`. -//! Nothing here was compared with x86 hardware. The AMD APM was not consulted. +//! Expectations were derived from the Intel 64 and IA-32 Architectures Software +//! Developer's Manual, revision 093 (September 2026), not from Xenora. Encodings +//! were produced by Apple clang's x86-64 assembler and read back with `objdump`. +//! Nothing here was compared with x86 hardware. For MXCSR flags that the Intel text +//! states less directly, the AMD64 Architecture Programmer's Manual, Volume 1, +//! revision 3.23 (October 2020) was consulted as well, cited as "APM". +//! +//! Chronology: 700 table cases were written before any Xenora CPU source was +//! opened; one input and a few MXCSR fields were tightened later. The other cases +//! and the sweeps were written after the public interface and small parts of the +//! decoder and DBT had been seen, some of them after the first run. Review +//! follow-ups came after the source behind the first four defects had been read. +//! The author is the same AI model as the author of the code under test. //! //! Tests named `defect_*` state what the manual requires where the engines differ //! today. They are ignored with a reason, so they never count as passed; run them @@ -1410,7 +1418,11 @@ cmov_false_still_reads_memory: rsi=U f= => ! PFR U @ shl qword ptr [rdi], cl 48d327 SDM 2B SAL/SHL (read-modify-write of DEST) -shift_zero_count_still_accesses_memory: rdi=D rcx=40 m0=0102030405060708 => f=* +shift_zero_count_leaves_memory_and_flags: rdi=D rcx=40 m0=0102030405060708 => f=* +@ shl qword ptr [rdi], cl + !48d327 + SDM 2B SAL/SHL (tempDEST := DEST for every count; #PF) +shift_zero_count_still_reads_memory: rdi=U rcx=40 => ! PFR U @ mul qword ptr [rsi] !48f726 SDM 3A 7.5 @@ -1966,8 +1978,8 @@ ftz_ignored_by_moves_and_logic: x2=d:1,80000001,00400000,7f800001 mx=9fc0 => x1= ftz_ignored_when_underflow_unmasked: x1=s:00800000 x2=s:3f000000 mx=9780 => mx=9790 f=* ! XM @ mulsd xmm1, xmm2 f20f59ca - SDM 1 10.2.3.3; 1 11.5.2.5 -ftz_exact_tiny_result_is_zero: x1=r:8010000000000000 x2=r:3fe0000000000000 mx=9f80 => x1=r:8000000000000000 mx=? f=* + SDM 1 10.2.3.3; 1 11.5.2.6; APM 1 4.2.2 (the flush itself is inexact, so UE and PE) +ftz_exact_tiny_result_is_zero: x1=r:8010000000000000 x2=r:3fe0000000000000 mx=9f80 => x1=r:8000000000000000 mx=9fb0 f=* @ addss xmm1, xmm2 f30f58ca SDM 1 10.2.3.4 @@ -2511,9 +2523,12 @@ unmasked_denormal_faults_before_write: x1=s:00000001 x2=s:3f800000 mx=1e80 => mx unmasked_precision_faults_before_write: x1=s:3f800000 x2=s:40400000 mx=f80 => mx=fa0 f=* ! XM @ mulss xmm1, xmm2 !f30f59ca - SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 + SDM 1 4.9.1.6; 1 D.4.2.3 Tables D-16 and D-17; APM 1 4.10.2.8 unmasked_underflow_exact_tiny_faults_before_write: x1=s:00800000 x2=s:3f000000 mx=1780 => mx=1790 f=* ! XM -unmasked_overflow_faults_before_write: x1=s:7f7fffff x2=s:7f7fffff mx=1b80 => mx=~20:1b88 f=* ! XM +unmasked_overflow_faults_before_write: x1=s:7f7fffff x2=s:7f7fffff mx=1b80 => mx=1ba8 f=* ! XM +masked_overflow_with_precision_unmasked_faults: x1=s:7f7fffff x2=s:40000000 mx=f80 => mx=fa8 f=* ! XM +unmasked_underflow_exact_until_denormalized_sets_ue: x1=s:00800001 x2=s:3f000000 mx=1780 => mx=~20:1790 f=* ! XM +unmasked_underflow_inexact_sets_ue_and_pe: x1=s:00800001 x2=s:3f000001 mx=1780 => mx=17b0 f=* ! XM @ mov eax, 7; addss xmm3, xmm3; divss xmm1, xmm2; mov ecx, 9 b807000000 f30f58db !f30f5eca b909000000 SDM 1 11.5.3.2; 3A 7.15 Interrupt 19 @@ -2581,6 +2596,26 @@ add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=00 push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=* "; +const DEFECT_EXACT_UNMASKED_OVERFLOW: &str = r" +@ mulss xmm1, xmm2 + !f30f59ca + SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8 +unmasked_overflow_exact_sets_only_oe: x1=s:7f7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM +unmasked_negative_overflow_exact_sets_only_oe: x1=s:ff7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM +@ addsd xmm1, xmm2 + !f20f58ca + SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8 +unmasked_overflow_exact_addsd: x1=r:7fefffffffffffff x2=r:7fefffffffffffff mx=1b80 => mx=1b88 f=* ! XM +@ divss xmm1, xmm2 + !f30f5eca + SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8 +unmasked_overflow_exact_divss: x1=s:7f7fffff x2=s:3f000000 mx=1b80 => mx=1b88 f=* ! XM +@ cvtsd2ss xmm1, xmm2 + !f20f5aca + SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8 +unmasked_overflow_exact_cvtsd2ss: x2=r:c7f0000000000000 mx=1b80 => mx=1b88 f=* ! XM +"; + const GROUPS: &[(&str, &str)] = &[ ("add_sub_flags", ADD_SUB_FLAGS), ("carry_chains", CARRY_CHAINS), @@ -2614,145 +2649,149 @@ const GROUPS: &[(&str, &str)] = &[ ("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED), ("fp_beyond_sse2", FP_BEYOND_SSE2), ("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION), + ( + "defect_exact_unmasked_overflow", + DEFECT_EXACT_UNMASKED_OVERFLOW, + ), ("page_crossing", PAGE_CROSSING), ]; -/// Forms both engines refuse today. They are not verified, only required to be -/// refused before they change guest state. -const UNSUPPORTED: &[&str] = &[ - "addr32_load_truncates_effective_address", - "addr32_sum_wraps_at_32_bits", - "bt_memory_negative_offset", - "bt_memory_positive_offset_beyond_operand", - "bt_memory_register_offset_can_fault", - "btr16_memory_negative_16bit_offset", - "bts_memory_negative_offset", - "cmpsb_is_rsi_minus_rdi", - "cmpxchg16b_equal", - "cmpxchg16b_equal_without_lock", - "cmpxchg16b_not_equal", - "cmpxchg16b_unaligned_is_gp", - "cmpxchg16b_unaligned_without_lock_is_gp", - "cmpxchg32_equal", - "cmpxchg64_memory_equal_without_lock", - "cmpxchg64_memory_not_equal", - "cmpxchg64_memory_not_equal_without_lock", - "cmpxchg8_not_equal_loads_al", - "cmpxchg8b_equal", - "cmpxchg8b_equal_without_lock", - "cmpxchg8b_not_equal", - "cmpxchg_mismatch_still_writes", - "crc32c_byte_and_qword_forms_agree", - "crc32c_check_string", - "dpps_mask", - "enter_leave_round_trip", - "fifteen_byte_instruction_executes", - "fs_addr32_truncates_before_adding_base", - "fs_rep_movsb_overrides_source_only", - "fs_rep_movsb_overrides_source_only_df_clear", - "gs_lock_xadd", - "gs_xadd_without_lock", - "haddps_hsubpd_addsubps", - "insertps_zero_mask", - "jecxz_tests_low_32_bits", - "jrcxz_tests_all_64_bits", - "lahf", - "lahf_zero", - "lea64_addr32_truncates_effective_address", - "lock_btc_memory", - "lodsd_zero_extends", - "lodsd_zero_extends_df_clear", - "lodsw_preserves_upper48", - "loop_decrements_rcx_without_flags", - "loopne_stops_on_zero_flag", - "maskmovdqu_selects_bytes", - "mov_moffs64_load", - "mov_moffs8_store", - "movddup_movsldup_movshdup", - "movdqa_movaps_aligned_store_and_load", - "movsb_forward", - "mpsadbw", - "pabs_min_is_unchanged", - "packusdw", - "palignr", - "pblendvb_uses_xmm0_msb", - "pblendw_blendps", - "pcmpeqq_pcmpgtq", - "pextr_pinsr_sse41", - "phaddsw_pmaddubsw_saturate", - "phaddw_phaddd_phsubw", - "phminposuw", - "pmin_pmax_sse41", - "pmovsx_pmovzx", - "pmulhrsw", - "pmulld_pmuldq", - "pshufb", - "psign", - "ptest_carry_when_source_is_subset", - "ptest_flags", - "push16_moves_rsp_by_two", - "pushfq_popfq_status_round_trip", - "rcl16_by16", - "rcl16_by17_is_identity", - "rcl32_by31", - "rcl32_cl32_affects_nothing_but_extension", - "rcl64_by63", - "rcl8_by1_clear_carry_in", - "rcl8_by1_set_carry_in_preserves_szap", - "rcl8_by8", - "rcl8_by9_is_identity", - "rcpps_special_values", - "rcpss_relative_error_bound", - "rcpss_rsqrtss_signal_nothing", - "rcr64_by1", - "rcr8_by10_is_by_one_mod_9", - "rcr8_by1_clear_carry_in", - "rcr8_by1_set_carry_in", - "rep_lodsb_source_fault", - "rep_movs_zero_count_touches_nothing", - "rep_movsb_addr32_uses_32bit_registers", - "rep_movsb_fault_df_clear", - "rep_movsb_fault_stops_at_failing_iteration", - "rep_movsb_overlap_propagates_df_clear", - "rep_movsq_overlap_propagates", - "rep_movsq_zero_count_df_clear", - "rep_movsw_backward", - "rep_stosd_df_clear", - "rep_stosd_forward", - "rep_stosq_fault_df_clear", - "rep_stosq_fault_stops_at_failing_iteration", - "repe_cmpsb_fault_restores_flags", - "repe_cmpsb_fault_restores_flags_df_clear", - "repe_cmpsb_stops_at_difference", - "repe_cmpsb_stops_at_difference_df_clear", - "repe_cmpsb_zero_count_keeps_flags", - "repne_scasb_finds_byte", - "repne_scasb_finds_byte_df_clear", - "repne_scasd_exhausts_count", - "rex_not_adjacent_to_opcode_is_ignored", - "roundps_uses_mxcsr_rc", - "roundsd_suppress_precision", - "roundss_imm_modes", - "sahf_clear_keeps_of", - "sahf_ignores_bits_1_3_5", - "shld16_by16_takes_source", - "shld32_by1_sign_change", - "shld32_by4", - "shld32_cl32_is_count_zero", - "shld64_by63", - "shr_rcr_128bit_right_shift", - "shrd32_by8", - "shrd64_by1_sign_change", - "shrd64_cl64_is_count_zero", - "xadd32_reg_reg", - "xadd64_memory", - "xadd64_memory_without_lock", - "xadd64_same_register_doubles", - "xadd8_al_ah", - "xadd_readonly_page_keeps_register", - "xchg_ax_r9w_preserves_both_uppers", - "xchg_eax_ebx_clears_both_uppers", - "xchg_rax_r8_is_not_nop", +/// Forms both engines refuse today, with the index of the refused instruction. +/// They are not verified, only required to be refused without changing state. +const UNSUPPORTED: &[(&str, usize)] = &[ + ("addr32_load_truncates_effective_address", 0), + ("addr32_sum_wraps_at_32_bits", 0), + ("bt_memory_negative_offset", 0), + ("bt_memory_positive_offset_beyond_operand", 0), + ("bt_memory_register_offset_can_fault", 0), + ("btr16_memory_negative_16bit_offset", 0), + ("bts_memory_negative_offset", 0), + ("cmpsb_is_rsi_minus_rdi", 0), + ("cmpxchg16b_equal", 0), + ("cmpxchg16b_equal_without_lock", 0), + ("cmpxchg16b_not_equal", 0), + ("cmpxchg16b_unaligned_is_gp", 0), + ("cmpxchg16b_unaligned_without_lock_is_gp", 0), + ("cmpxchg32_equal", 0), + ("cmpxchg64_memory_equal_without_lock", 0), + ("cmpxchg64_memory_not_equal", 0), + ("cmpxchg64_memory_not_equal_without_lock", 0), + ("cmpxchg8_not_equal_loads_al", 0), + ("cmpxchg8b_equal", 0), + ("cmpxchg8b_equal_without_lock", 0), + ("cmpxchg8b_not_equal", 0), + ("cmpxchg_mismatch_still_writes", 0), + ("crc32c_byte_and_qword_forms_agree", 0), + ("crc32c_check_string", 0), + ("dpps_mask", 0), + ("enter_leave_round_trip", 0), + ("fifteen_byte_instruction_executes", 0), + ("fs_addr32_truncates_before_adding_base", 0), + ("fs_rep_movsb_overrides_source_only", 0), + ("fs_rep_movsb_overrides_source_only_df_clear", 0), + ("gs_lock_xadd", 0), + ("gs_xadd_without_lock", 0), + ("haddps_hsubpd_addsubps", 0), + ("insertps_zero_mask", 0), + ("jecxz_tests_low_32_bits", 1), + ("jrcxz_tests_all_64_bits", 1), + ("lahf", 0), + ("lahf_zero", 0), + ("lea64_addr32_truncates_effective_address", 0), + ("lock_btc_memory", 0), + ("lodsd_zero_extends", 0), + ("lodsd_zero_extends_df_clear", 0), + ("lodsw_preserves_upper48", 0), + ("loop_decrements_rcx_without_flags", 1), + ("loopne_stops_on_zero_flag", 1), + ("maskmovdqu_selects_bytes", 0), + ("mov_moffs64_load", 0), + ("mov_moffs8_store", 0), + ("movddup_movsldup_movshdup", 0), + ("movdqa_movaps_aligned_store_and_load", 3), + ("movsb_forward", 0), + ("mpsadbw", 0), + ("pabs_min_is_unchanged", 0), + ("packusdw", 0), + ("palignr", 0), + ("pblendvb_uses_xmm0_msb", 0), + ("pblendw_blendps", 0), + ("pcmpeqq_pcmpgtq", 0), + ("pextr_pinsr_sse41", 0), + ("phaddsw_pmaddubsw_saturate", 0), + ("phaddw_phaddd_phsubw", 0), + ("phminposuw", 0), + ("pmin_pmax_sse41", 0), + ("pmovsx_pmovzx", 0), + ("pmulhrsw", 0), + ("pmulld_pmuldq", 0), + ("pshufb", 0), + ("psign", 0), + ("ptest_carry_when_source_is_subset", 0), + ("ptest_flags", 0), + ("push16_moves_rsp_by_two", 0), + ("pushfq_popfq_status_round_trip", 0), + ("rcl16_by16", 0), + ("rcl16_by17_is_identity", 0), + ("rcl32_by31", 0), + ("rcl32_cl32_affects_nothing_but_extension", 0), + ("rcl64_by63", 0), + ("rcl8_by1_clear_carry_in", 0), + ("rcl8_by1_set_carry_in_preserves_szap", 0), + ("rcl8_by8", 0), + ("rcl8_by9_is_identity", 0), + ("rcpps_special_values", 0), + ("rcpss_relative_error_bound", 0), + ("rcpss_rsqrtss_signal_nothing", 0), + ("rcr64_by1", 0), + ("rcr8_by10_is_by_one_mod_9", 0), + ("rcr8_by1_clear_carry_in", 0), + ("rcr8_by1_set_carry_in", 0), + ("rep_lodsb_source_fault", 0), + ("rep_movs_zero_count_touches_nothing", 0), + ("rep_movsb_addr32_uses_32bit_registers", 0), + ("rep_movsb_fault_df_clear", 0), + ("rep_movsb_fault_stops_at_failing_iteration", 0), + ("rep_movsb_overlap_propagates_df_clear", 0), + ("rep_movsq_overlap_propagates", 0), + ("rep_movsq_zero_count_df_clear", 0), + ("rep_movsw_backward", 0), + ("rep_stosd_df_clear", 0), + ("rep_stosd_forward", 0), + ("rep_stosq_fault_df_clear", 0), + ("rep_stosq_fault_stops_at_failing_iteration", 0), + ("repe_cmpsb_fault_restores_flags", 0), + ("repe_cmpsb_fault_restores_flags_df_clear", 0), + ("repe_cmpsb_stops_at_difference", 0), + ("repe_cmpsb_stops_at_difference_df_clear", 0), + ("repe_cmpsb_zero_count_keeps_flags", 0), + ("repne_scasb_finds_byte", 0), + ("repne_scasb_finds_byte_df_clear", 0), + ("repne_scasd_exhausts_count", 0), + ("rex_not_adjacent_to_opcode_is_ignored", 0), + ("roundps_uses_mxcsr_rc", 0), + ("roundsd_suppress_precision", 0), + ("roundss_imm_modes", 0), + ("sahf_clear_keeps_of", 0), + ("sahf_ignores_bits_1_3_5", 0), + ("shld16_by16_takes_source", 0), + ("shld32_by1_sign_change", 0), + ("shld32_by4", 0), + ("shld32_cl32_is_count_zero", 0), + ("shld64_by63", 0), + ("shr_rcr_128bit_right_shift", 1), + ("shrd32_by8", 0), + ("shrd64_by1_sign_change", 0), + ("shrd64_cl64_is_count_zero", 0), + ("xadd32_reg_reg", 0), + ("xadd64_memory", 0), + ("xadd64_memory_without_lock", 0), + ("xadd64_same_register_doubles", 0), + ("xadd8_al_ah", 0), + ("xadd_readonly_page_keeps_register", 0), + ("xchg_ax_r9w_preserves_both_uppers", 0), + ("xchg_eax_ebx_clears_both_uppers", 0), + ("xchg_rax_r8_is_not_nop", 0), ]; // --------------------------------------------------------------------------- @@ -3143,7 +3182,16 @@ fn run(engine: Engine, cpu: &CpuState, memory: &mut GuestMemory) -> (CpuState, E let mut dbt = new_dbt(); let mut scratch = memory.clone(); run_dbt(&mut dbt, cpu, &mut scratch, BUDGET); - run_dbt(&mut dbt, cpu, memory, BUDGET) + let warm = dbt.metrics; + let result = run_dbt(&mut dbt, cpu, memory, BUDGET); + // Nothing is cached when the first instruction does not decode. + assert!( + warm.blocks_compiled == 0 || dbt.metrics.cache_hits > warm.cache_hits, + "second run missed the cache: {warm:?} then {:?}", + dbt.metrics + ); + assert_eq!(dbt.metrics.blocks_compiled, warm.blocks_compiled); + result } Engine::DbtStepped => { let mut dbt = new_dbt(); @@ -3327,10 +3375,7 @@ fn check_group(table: &'static str) { let cases = parse(table); let mut report = Vec::new(); let mut verified = 0; - for case in cases - .iter() - .filter(|case| !UNSUPPORTED.contains(&case.name)) - { + for case in cases.iter().filter(|case| refused_at(case.name).is_none()) { let found = failures(case); if found.is_empty() { verified += 1; @@ -3495,6 +3540,12 @@ fn defect_overlong_instruction() { check_group(DEFECT_OVERLONG_INSTRUCTION); } +#[test] +#[ignore = "known defect (#155): an exact unmasked overflow sets PE as well as OE"] +fn defect_exact_unmasked_overflow() { + check_group(DEFECT_EXACT_UNMASKED_OVERFLOW); +} + #[test] fn page_crossing() { check_group(PAGE_CROSSING); @@ -3512,48 +3563,64 @@ fn case_names_are_unique_and_listed_exceptions_exist() { let cases = all_cases(); let names: BTreeSet<&str> = cases.iter().map(|(_, case)| case.name).collect(); assert_eq!(names.len(), cases.len(), "duplicate case name"); - for name in UNSUPPORTED { + for (name, _) in UNSUPPORTED { assert!(names.contains(name), "unknown case {name}"); } } -/// A form outside the supported set must be refused, never approximated. +/// The instruction index at which both engines refuse a case, if they do. +fn refused_at(name: &str) -> Option { + let entry = UNSUPPORTED.iter().find(|(known, _)| *known == name)?; + Some(entry.1) +} + +/// A form outside the supported set must be refused at that instruction, never +/// approximated. The state must be exactly what the instructions before it left: +/// the reference is an interpreter run of only those instructions, and their +/// own results are checked by other cases. #[test] fn unsupported_forms_are_refused_without_changing_state() { for (_, case) in all_cases() { - if !UNSUPPORTED.contains(&case.name) { + let Some(index) = refused_at(case.name) else { continue; - } - let start = initial_state(&case); - for engine in ENGINES { - let mut memory = start.image.load(&case.code); - let (cpu, exit) = run(engine, &start.cpu, &mut memory); - assert!( - matches!(exit, ExitReason::IllegalInstruction(_)), - "{} on {engine:?}: {exit:?}", - case.name - ); - let offset = (cpu.rip - CODE) as usize; - assert!(case.offsets.contains(&offset), "{}", case.name); - if offset == 0 { - assert_eq!(cpu, start.cpu, "{} on {engine:?}", case.name); - assert_eq!(Image::store(&memory).differences(&start.image), ""); + }; + let offset = case.offsets[index]; + for flags in flag_sweep(&case) { + let mut start = initial_state(&case); + set_flags(&mut start.cpu.flags, flags); + let mut before = start.image.load(&case.code[..offset]); + let (mut wanted, exit) = run(Engine::Interpreter, &start.cpu, &mut before); + assert_eq!(exit, ExitReason::Halt, "{} prefix", case.name); + wanted.rip = CODE + offset as u64; + for engine in ENGINES { + let mut memory = start.image.load(&case.code); + let (cpu, exit) = run(engine, &start.cpu, &mut memory); + let what = format!("{} on {engine:?}", case.name); + assert!( + matches!(exit, ExitReason::IllegalInstruction(_)), + "{what}: {exit:?}" + ); + assert_eq!(cpu, wanted, "{what}"); + // Scratch stack included: a refused push must not write it. + let (got, wanted) = (Image::store(&memory), Image::store(&before)); + assert!(got == wanted, "{what}: memory changed"); } } } } /// Which route each verified instruction takes in the DBT. The per-instruction -/// answer of `is_native` must agree with the engine's own fallback counter, so -/// helper calls cannot be mistaken for translated code. Run with `--nocapture` -/// for the list. +/// answer of `is_native` must agree with the engine's own fallback counter for +/// every straight-line case that does not fault; for the others the route is only +/// what `is_native` predicts. Run with `--nocapture` for the list. #[test] fn dbt_route_of_every_case_is_recorded() { let mut native: BTreeSet<&str> = BTreeSet::new(); let mut helper: BTreeSet<&str> = BTreeSet::new(); let mut counts: BTreeMap<&str, [usize; 3]> = BTreeMap::new(); + let (mut counted, mut predicted) = (0, 0); for (group, case) in all_cases() { - if UNSUPPORTED.contains(&case.name) { + if refused_at(case.name).is_some() { continue; } let start = initial_state(&case); @@ -3580,19 +3647,33 @@ fn dbt_route_of_every_case_is_recorded() { (false, false) => continue, }; counts.entry(group).or_default()[kind] += 1; - if let ([only], 1, true) = (routes.as_slice(), case.offsets.len(), case.fault.is_empty()) { + // Straight-line cases run each instruction once, so the counter must equal + // the number of helper instructions. + let labelled = text.iter().any(|piece| { + piece + .split_once(':') + .is_some_and(|(label, _)| label.parse::().is_ok()) + }); + if !labelled && case.fault.is_empty() && routes.len() == case.offsets.len() { let mut dbt = new_dbt(); let mut memory = memory.clone(); run_dbt(&mut dbt, &start.cpu, &mut memory, BUDGET); assert_eq!( dbt.metrics.interpreter_fallbacks, - usize::from(!only), + routes.iter().filter(|native| !**native).count(), "{}: {:?}", case.name, dbt.metrics ); + counted += 1; + } else { + predicted += 1; } } + println!( + "{counted} cases confirmed by the fallback counter; {predicted} cases with branches or \ + faults are only predicted by is_native" + ); println!("group: cases with only native code / only helpers / both"); for (group, [only_native, only_helper, both]) in counts { println!("{group}: {only_native} / {only_helper} / {both}"); @@ -4475,6 +4556,9 @@ const UE: u32 = 16; const PE: u32 = 32; const DAZ: u32 = 0x40; const FTZ: u32 = 0x8000; +const DM: u32 = 0x100; +const OM: u32 = 0x400; +const UM: u32 = 0x800; const MASKS: u32 = 0x1f80; /// Binary32 or binary64 (SDM 1 4.2.2). @@ -4650,7 +4734,8 @@ fn deliver( let precision = format.precision as i32; let leading = 127 - significand.leading_zeros() as i32 + exponent; let lowest = leading - precision + 1; - let (unbounded, _) = round_to(significand, exponent, sticky, lowest, negative, mode); + let (unbounded, unbounded_exact) = + round_to(significand, exponent, sticky, lowest, negative, mode); let carried = unbounded >> precision != 0; let rounded_exponent = leading + i32::from(carried); let tiny = rounded_exponent < format.min_exponent(); @@ -4663,23 +4748,29 @@ fn deliver( lowest += 1; } let inexact = if exact { 0 } else { PE }; - if mxcsr & MASKS == 0 && tiny { - // Unmasked underflow is reported for any tiny result. + // Unmasked overflow and underflow set PE only if rounding to the destination + // precision with an unbounded exponent is inexact (D.4.2.3 Tables D-16, D-17). + let unbounded_inexact = if unbounded_exact { 0 } else { PE }; + if mxcsr & UM == 0 && tiny { + // When only denormalizing would lose bits, D-17 leaves PE clear while + // AMD APM 1 4.10.2.8 can be read as setting it. return Outcome { - result: 0, - flags: UE | inexact, - open: PE, + open: if unbounded_exact && !exact { PE } else { 0 }, + ..outcome(0, UE | unbounded_inexact) }; } if mxcsr & FTZ != 0 && tiny { - // The flags of an exact tiny result that is flushed are ambiguous. - return Outcome { - result: format.signed(negative, 0), - flags: UE | PE, - open: if exact { UE | PE } else { 0 }, - }; + return outcome(format.signed(negative, 0), UE | PE); } if lowest + precision - 1 > format.max_exponent() { + if mxcsr & OM == 0 { + // PE of an exact overflow is `defect_exact_unmasked_overflow`; this + // sweep compares every other bit. + return Outcome { + open: if unbounded_exact { PE } else { 0 }, + ..outcome(0, OE | unbounded_inexact) + }; + } let to_infinity = match mode { 0 => true, 1 => negative, @@ -4687,11 +4778,7 @@ fn deliver( _ => false, }; let magnitude = format.infinity() - u64::from(!to_infinity); - return Outcome { - result: format.signed(negative, magnitude), - flags: OE | PE, - open: if mxcsr & MASKS == 0 { PE } else { 0 }, - }; + return outcome(format.signed(negative, magnitude), OE | PE); } let field = (lowest - floor) as u64; let magnitude = (field << format.fraction_bits()) + value as u64; @@ -4761,7 +4848,7 @@ fn float(op: &str, format: Format, a: u64, b: u64, mxcsr: u32) -> Outcome { let (zero_a, zero_b) = (format.is_zero(a), format.is_zero(b)); let with_denormal = |mut result: Outcome| { // An unmasked pre-computation exception hides later ones (11.5.3.2). - if mxcsr & MASKS == 0 && denormal != 0 { + if mxcsr & DM == 0 && denormal != 0 { result.flags = 0; result.open = 0; } @@ -4917,7 +5004,7 @@ fn convert_format(from: Format, to: Format, value: u64, mxcsr: u32) -> Outcome { let (significand, exponent) = from.split(value); let mut result = deliver(to, negative, significand, exponent, false, mxcsr); if denormal { - if mxcsr & MASKS == 0 { + if mxcsr & DM == 0 { (result.flags, result.open) = (0, 0); } result.flags |= DE; @@ -4966,6 +5053,9 @@ fn expect_float( write: impl Fn(&mut CpuState, u64), ) { let faults = must_fault(want.flags, cpu.mxcsr.0); + if !faults && must_fault(want.open, cpu.mxcsr.0) { + return; // The manual leaves open whether this raises #XM. + } let mut wanted = cpu.clone(); if !faults { write(&mut wanted, want.result); @@ -5010,7 +5100,8 @@ fn low(format: Format, base: u128, value: u64) -> u128 { base & !u128::from(mask(format.bits)) | u128::from(value) } -/// Every rounding mode with and without FTZ and DAZ, masked and unmasked. +/// Every rounding mode with and without FTZ and DAZ, all masked and all unmasked, +/// and each exception unmasked alone. fn mxcsr_values() -> Vec { let mut values = Vec::new(); for mode in 0..4 { @@ -5019,6 +5110,11 @@ fn mxcsr_values() -> Vec { values.push(masks | mode << 13 | flush); } } + for flush in [0, FTZ | DAZ] { + for only in 7..13 { + values.push(MASKS & !(1 << only) | mode << 13 | flush); + } + } } values } From a2a6a562224fc2f8ba34939164744eea026e3bd2 Mon Sep 17 00:00:00 2001 From: Ranveer Soni Date: Tue, 24 Nov 2026 20:17:47 +0530 Subject: [PATCH 19/19] Update README.md --- README.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a6a261d..7e65326 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,8 @@ Xenora is an open-source project written primarily in Rust that builds and verif Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations). -### At a glance - -- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results). -- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9. -- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones). +> [!CAUTION] +> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft, Rockstar Games, Take-Two Interactive, or any other publisher or platform holder. [![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml) @@ -58,8 +55,6 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified. -See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior. - ## Native graphics translation Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language. @@ -376,4 +371,4 @@ See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple. ---- \ No newline at end of file +---