isa, decoder, shader, scripts: split the semantic registry per family and add encoding variants (#215) (#300)

* 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>

* 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>

* 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>

* 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>

* 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>

* 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>

* 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_<family>_word and
<family>_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>

* isa, scripts: review fixes for the registry split and encoding variants (#215)

- Includes must be `<root stem>/<family>.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>

* 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>

* 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>

* 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>

* 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>

* 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>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
elforeign authored and GitHub committed 2026-11-24 08:37:03 -06:00
1 parent eb85731d5d
commit a2cc14d223
27 files changed
+2885 -1789

No files matched your search

+1
View File
@@ -33,6 +33,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`.
+20 -14
View File
@@ -4,13 +4,14 @@ 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,
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 +41,7 @@ const fn concat_forms<const N: usize>() -> [(&'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 +55,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 +327,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) = VectorAluVop3Op::from_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 +746,25 @@ 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<Instruction, DecodeErrorKind> {
/// 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: VectorAluVop3Op,
first: u32,
second: u32,
) -> Result<Instruction, DecodeErrorKind> {
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.assembly_name(),
"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,
+13 -4
View File
@@ -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::{
@@ -43,7 +44,8 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
(
20,
8,
Instruction::AddNoCarryU32 {
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst: 1,
src0: 1,
src1: 2,
@@ -373,7 +375,13 @@ 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: VectorAluVop3Op::AddNcU32,
dst,
src0,
src1,
} => Op::Add(dst, src0, src1),
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: VectorAluVop3Op::AddNcU32,
dst: 1,
src0: 0,
src1: 0
+360 -11
View File
@@ -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
@@ -36,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",
@@ -221,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",
@@ -286,6 +299,33 @@ 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,
# 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.
"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",
# The generated enum of this rule's variants; base() maps to "enum".
"variant_enum": "VectorAluVop3Op",
},
"vop2_vgpr": {
"rust": "Vop2Vgpr",
"enum": "VectorAluOp",
@@ -315,10 +355,96 @@ 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."""
# An include names a family file as `<root stem>/<lower-case family>.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"}
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")
# Family files live directly in the directory named after the root
# (rdna2.toml -> rdna2/), as `<stem>/<family>.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}/<family>.toml"
)
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", [])
# 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
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}/")
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)
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")
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)
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
def load_snapshot(path=SNAPSHOT):
@@ -415,9 +541,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"]]
@@ -615,6 +739,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"]:
@@ -629,6 +755,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):
@@ -636,9 +765,122 @@ 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 _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, base=None):
"""The base form re-encoded: its declaration with the variant's identity."""
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"],
)
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", [])}
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)
if missing:
errors.append(f"{label}: incomplete encoding variant, missing {missing}")
if extra:
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")
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 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.
# 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
# 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"])))
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 _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):
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):
operands = form.get("operands")
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
@@ -658,10 +900,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"])):
@@ -697,9 +945,18 @@ 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", [])
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, variant_positions)
# 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:
@@ -745,6 +1002,94 @@ def render(registry, snapshot):
return "\n".join(out)
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"]
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")
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} {{",
" /// 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<Self> {",
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,",
" }",
" }",
"",
" /// The form this encodes, whose declaration it inherits.",
f" pub const fn base(self) -> {base_enum} {{",
" match self {",
]
out += [
f" Self::{variant_of[variant['of']]} => {base_enum}::{variant_of[variant['of']]},"
for variant in variants
]
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
def _render_enum(rule_name, forms, snapshot, positions):
enum = OPERAND_RULES[rule_name]["enum"]
kind = OPERAND_RULES[rule_name]["kind"]
@@ -1018,7 +1363,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:
File diff suppressed because it is too large. Load diff
+238
View File
@@ -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"]
+647
View File
@@ -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"]
+269
View File
@@ -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"]
+225
View File
@@ -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"]
+39
View File
@@ -0,0 +1,39 @@
# 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
# 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",
]
# 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"
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"]
+360
View File
@@ -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"]
+13 -5
View File
@@ -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.
@@ -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: VectorAluVop3Op,
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,7 @@ 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.assembly_name(),
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
@@ -328,7 +334,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 }
+4
View File
@@ -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.
+73 -3
View File
@@ -1872,8 +1872,56 @@ impl VectorCompareOp {
}
}
/// Identity of every registry form, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 84] = [
/// 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<Self> {
if word & 0xfc00_0000 != 0xd400_0000 {
return None;
}
match (word >> 16) & 0x3ff {
293 => Some(Self::AddNcU32),
_ => None,
}
}
/// The form this encodes, whose declaration it inherits.
pub const fn base(self) -> VectorAluOp {
match self {
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.
pub const FORM_IDS: [(&str, EncodingFamily); 85] = [
("S_ADD_U32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_ADD_I32", EncodingFamily::Sop2),
@@ -1958,10 +2006,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 +3775,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],
},
];
+40 -1
View File
@@ -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]
@@ -160,3 +161,41 @@ 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 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!(
(
base.operation,
base.signedness,
base.scc,
base.vcc,
base.exec
),
(row.operation, row.signedness, row.scc, row.vcc, row.exec)
);
assert_eq!(row.swap_sources, base.swap_sources);
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
}
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
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
);
}
}
+27 -9
View File
@@ -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, VectorAluVop3Op, 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<Vec<(usize, O
if let Some((_, _, before)) = &region {
let dst = match instruction.instruction {
Instruction::MoveB32 { dst, .. }
| Instruction::AddNoCarryU32 { dst, .. }
// Of the VOP3 variants, the contract admits only v_add_nc_u32_e64.
| Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst,
..
}
| Instruction::VectorLshlrevB32 { dst, .. }
| Instruction::VectorLshrrevB32 { dst, .. }
| Instruction::VectorAshrrevI32 { dst, .. }
@@ -723,7 +727,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
if exec == 0 {
match instruction.instruction {
Instruction::MoveB32 { .. }
| Instruction::AddNoCarryU32 { .. }
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorLshlrevB32 { .. }
| Instruction::VectorLshrrevB32 { .. }
| Instruction::VectorAshrrevI32 { .. }
@@ -830,8 +834,22 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Some(dst),
Op::Constant(read_scalar(ScalarSource::Register(register))?),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?))
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => {
let op = op.base();
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),
+1 -1
View File
@@ -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
+3 -2
View File
@@ -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` |
+59 -2
View File
@@ -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/<family>.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. |
@@ -20,9 +21,65 @@ 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.*]`, `[[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/<lower-case family>.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
families therefore never edits the same registry file. To add a family, create
`rdna2/<family>.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 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 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
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 top of the file holds:
The root file holds:
- `schema`: must be `1`.
- `architecture`: must be `"gfx1030"`.
+1 -1
View File
@@ -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.
+38 -2
View File
@@ -142,6 +142,24 @@ def parse_generated(source):
raise ValueError(f"{GENERATED}: unterminated FORM_IDS")
def load_registry(path):
"""The root registry with its family files merged, by the generator's loader.
One loader for every consumer, so the family-file guards (one family per
file, include paths, duplicates) apply here too.
"""
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):
if type(registry.get("schema")) is not int or registry["schema"] != 1:
raise ValueError(f"{REGISTRY}: expected schema 1")
@@ -161,7 +179,25 @@ 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.
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)
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 string family, of and operands"
" and an integer opcode"
)
variants = [
{"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"],
"operands": variant["operands"]}
for variant in raw_variants
]
for form in registry["form"] + variants:
key = (form["family"], form["name"])
if key not in identified:
raise ValueError(f"{REGISTRY}: unknown form {key}")
@@ -294,7 +330,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"))
+12 -2
View File
@@ -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] = []
+12 -2
View File
@@ -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)
@@ -198,6 +200,12 @@ def classify_unsupported(
registry = data["registry"]
rules = data["rules"]
ops = _declared_ops(registry)
# 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 = {
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", []):
@@ -219,7 +227,9 @@ 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]
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}")
+49
View File
@@ -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()
+20
View File
@@ -66,6 +66,26 @@ 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 = {
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 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)
with tempfile.TemporaryDirectory() as tmp:
@@ -1,4 +1,6 @@
import tempfile
import unittest
from pathlib import Path
from audit import semantic_coverage as coverage
@@ -66,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"
@@ -113,5 +120,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()
@@ -10,6 +10,8 @@ snapshot are only read, never edited. Run from the repository root:
import copy
import importlib.util
import os
import shutil
import subprocess
import sys
import tempfile
@@ -166,11 +168,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,
}
@@ -265,6 +290,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"] += [
@@ -783,6 +827,155 @@ 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_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 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()
# 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), [])
# 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):
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 = (
("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):
reg = variants()
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_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
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)
self.assertIn("pub const fn from_word(word: u32) -> Option<Self> {", 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::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.
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"
@@ -1037,6 +1230,135 @@ 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_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)
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)))
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', {
"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_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/<family>.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_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")
(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")
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 +1394,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"