mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:00:43 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97598903e2 | ||
|
|
af68f7da74 | ||
|
|
54506125d4 | ||
|
|
62c933051b |
No files matched your search
@@ -37,6 +37,7 @@ jobs:
|
||||
rustc -vV
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
|
||||
Generated
+2
@@ -153,7 +153,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
name = "xenora"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
|
||||
@@ -9,6 +9,8 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
xenora-decoder = { path = "../decoder" }
|
||||
xenora-isa = { path = "../isa" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-ref = { path = "../ref" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod demo;
|
||||
mod runner;
|
||||
mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -40,6 +41,7 @@ fn main() -> ExitCode {
|
||||
},
|
||||
Some("run") => runner::command(std::env::args_os().skip(2)),
|
||||
Some("imports") => imports_command(std::env::args().skip(2).collect()),
|
||||
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("probe") => {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
@@ -132,7 +134,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports>");
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! `xenora shaders`: instruction inventory and stream inspection.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
|
||||
|
||||
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
|
||||
Some("inspect") => match args.get(1) {
|
||||
Some(path) => inspect(path),
|
||||
None => usage(),
|
||||
},
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn semantic(family: EncodingFamily) -> usize {
|
||||
SEMANTIC_FORMS
|
||||
.iter()
|
||||
.filter(|(_, form_family)| *form_family == family)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
|
||||
/// with their length; "semantic" forms decode into executable instructions.
|
||||
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
|
||||
fn coverage(json: bool) -> ExitCode {
|
||||
let rows: Vec<_> = meta::inventory()
|
||||
.into_iter()
|
||||
.map(|(family, discovered)| (family, discovered, semantic(family)))
|
||||
.collect();
|
||||
let total: usize = rows.iter().map(|row| row.1).sum();
|
||||
let supported: usize = rows.iter().map(|row| row.2).sum();
|
||||
if json {
|
||||
let families: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(family, discovered, semantic)| {
|
||||
format!(
|
||||
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
|
||||
family.name()
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
|
||||
meta::SOURCE_SHA256,
|
||||
families.join(",")
|
||||
);
|
||||
} else {
|
||||
println!("{:<10} {:>10} {:>9}", "family", "discovered", "semantic");
|
||||
for (family, discovered, semantic) in &rows {
|
||||
println!("{:<10} {discovered:>10} {semantic:>9}", family.name());
|
||||
}
|
||||
println!("{:<10} {total:>10} {supported:>9}", "total");
|
||||
println!("Semantic forms decode for the operand subsets in docs/status.toml only.");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn inspect(path: &str) -> ExitCode {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
eprintln!("{path}: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let mut offset = 0;
|
||||
let mut unsupported = 0;
|
||||
let mut count = 0;
|
||||
while offset < bytes.len() {
|
||||
let found = match identify(&bytes[offset..]) {
|
||||
Ok(found) => found,
|
||||
Err(error) => {
|
||||
println!("{offset:#06x} decode failure: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let words: Vec<String> = bytes[offset..offset + found.len]
|
||||
.chunks(4)
|
||||
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
|
||||
.collect();
|
||||
let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) {
|
||||
Ok(_) => "semantic".to_owned(),
|
||||
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
|
||||
format!("unsupported operands: {error}")
|
||||
}
|
||||
Err(_) => "unsupported instruction semantics".to_owned(),
|
||||
};
|
||||
if status != "semantic" {
|
||||
unsupported += 1;
|
||||
}
|
||||
println!(
|
||||
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
|
||||
found.form.family.name(),
|
||||
found.form.name.to_ascii_lowercase(),
|
||||
words.join(" ")
|
||||
);
|
||||
offset += found.len;
|
||||
count += 1;
|
||||
}
|
||||
println!(
|
||||
"{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable",
|
||||
FORMS.len()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -12,6 +12,39 @@ use xenora_isa::{
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("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),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
("V_LSHRREV_B32", EncodingFamily::Vop2),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
("V_OR_B32", EncodingFamily::Vop2),
|
||||
("V_XOR_B32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodedInstruction {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{FORMS, identify};
|
||||
|
||||
#[test]
|
||||
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut decoded = BTreeSet::new();
|
||||
for entry in fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
|
||||
let found = identify(&binary[instruction.offset..]).unwrap();
|
||||
assert_eq!(
|
||||
found.len,
|
||||
usize::from(instruction.byte_len),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
decoded.insert((found.form.name, found.form.family));
|
||||
}
|
||||
}
|
||||
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert!(
|
||||
decoded.is_subset(&declared),
|
||||
"{:?}",
|
||||
decoded.difference(&declared)
|
||||
);
|
||||
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
|
||||
let inline_only: BTreeSet<_> = declared
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
inline_only,
|
||||
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
|
||||
);
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
.iter()
|
||||
.any(|form| form.name == name && form.family == family),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,426 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the complete gfx1030 instruction metadata table.
|
||||
|
||||
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
|
||||
|
||||
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
|
||||
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
|
||||
|
||||
`--check` regenerates in memory and fails when a committed file differs.
|
||||
Only the Python standard library is used. See docs/research/rdna2.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
ARCHITECTURE = "AMD RDNA 2"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
|
||||
SCHEMA = 1
|
||||
|
||||
# Encodings whose default condition defines an instruction's base form. The
|
||||
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
|
||||
BASE_ENCODINGS = {
|
||||
"ENC_SOP1": "Sop1",
|
||||
"ENC_SOP2": "Sop2",
|
||||
"ENC_SOPC": "Sopc",
|
||||
"ENC_SOPK": "Sopk",
|
||||
"ENC_SOPP": "Sopp",
|
||||
"ENC_SMEM": "Smem",
|
||||
"ENC_VOP1": "Vop1",
|
||||
"ENC_VOP2": "Vop2",
|
||||
"ENC_VOPC": "Vopc",
|
||||
"ENC_VOP3": "Vop3",
|
||||
"VOP3_SDST_ENC": "Vop3Sdst",
|
||||
"ENC_VOP3P": "Vop3p",
|
||||
"ENC_VINTRP": "Vintrp",
|
||||
"ENC_DS": "Ds",
|
||||
"ENC_MUBUF": "Mubuf",
|
||||
"ENC_MTBUF": "Mtbuf",
|
||||
"ENC_MIMG": "Mimg",
|
||||
"ENC_EXP": "Exp",
|
||||
"ENC_FLAT": "Flat",
|
||||
"ENC_FLAT_GLBL": "Global",
|
||||
"ENC_FLAT_SCRATCH": "Scratch",
|
||||
}
|
||||
|
||||
# Extension encoding -> (base encoding, extension kind). The XML names the
|
||||
# variant and its operands but gives no expression for when it applies; the
|
||||
# decoder implements those rules by hand (docs/research/rdna2.md).
|
||||
EXTENSIONS = {
|
||||
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
|
||||
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
|
||||
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
|
||||
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
|
||||
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
|
||||
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
|
||||
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
|
||||
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
|
||||
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
|
||||
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
|
||||
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
|
||||
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
|
||||
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
|
||||
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
|
||||
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
|
||||
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
|
||||
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
|
||||
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
|
||||
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
|
||||
}
|
||||
|
||||
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(f"generate_rdna2_meta: {message}")
|
||||
|
||||
|
||||
def text(element, path):
|
||||
value = element.findtext(path)
|
||||
if value is None:
|
||||
fail(f"missing <{path}>")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def boolean(value):
|
||||
if value not in ("TRUE", "FALSE", "true", "false"):
|
||||
fail(f"unexpected boolean {value!r}")
|
||||
return value.lower() == "true"
|
||||
|
||||
|
||||
def snapshot_from_xml(data):
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
fail("RDNA 2 XML does not match the approved input SHA-256")
|
||||
root = ElementTree.fromstring(data)
|
||||
document = root.find("Document")
|
||||
isa = root.find("ISA")
|
||||
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
|
||||
fail("XML is not the RDNA 2 architecture")
|
||||
records = [{
|
||||
"kind": "source",
|
||||
"schema": SCHEMA,
|
||||
"architecture": ARCHITECTURE,
|
||||
"sha256": SOURCE_SHA256,
|
||||
"release": text(document, "ReleaseDate"),
|
||||
"xml_schema": text(document, "SchemaVersion"),
|
||||
"license": text(document, "License"),
|
||||
"copyright": text(document, "Copyright"),
|
||||
}]
|
||||
|
||||
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
|
||||
encodings = {}
|
||||
for encoding in isa.findall("Encodings/Encoding"):
|
||||
name = text(encoding, "EncodingName")
|
||||
if name not in known:
|
||||
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
|
||||
bits = int(text(encoding, "BitCount"))
|
||||
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
|
||||
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
|
||||
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
|
||||
fail(f"{name} identifies instructions beyond the first dword")
|
||||
fields = []
|
||||
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
|
||||
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
|
||||
fields.append([
|
||||
text(field, "FieldName"),
|
||||
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
|
||||
])
|
||||
fields.sort(key=lambda item: (item[1][0][0], item[0]))
|
||||
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
|
||||
records.append({
|
||||
"kind": "encoding",
|
||||
"name": name,
|
||||
"bits": bits,
|
||||
"identifier_mask": mask,
|
||||
"identifiers": identifiers,
|
||||
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
|
||||
"fields": fields,
|
||||
})
|
||||
missing = known - set(encodings)
|
||||
if missing:
|
||||
fail(f"encodings absent from the XML: {sorted(missing)}")
|
||||
|
||||
for operand_type in isa.findall("OperandTypes/OperandType"):
|
||||
values = sorted(
|
||||
[text(value, "Name"), int(text(value, "Value"))]
|
||||
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
|
||||
)
|
||||
records.append({
|
||||
"kind": "operand_type",
|
||||
"name": text(operand_type, "OperandTypeName"),
|
||||
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
|
||||
"values": values,
|
||||
})
|
||||
|
||||
for data_format in isa.findall("DataFormats/DataFormat"):
|
||||
records.append({
|
||||
"kind": "data_format",
|
||||
"name": text(data_format, "DataFormatName"),
|
||||
"data_type": text(data_format, "DataType"),
|
||||
"bits": int(text(data_format, "BitCount")),
|
||||
"components": int(text(data_format, "ComponentCount")),
|
||||
})
|
||||
|
||||
seen = set()
|
||||
for instruction in isa.findall("Instructions/Instruction"):
|
||||
name = text(instruction, "InstructionName")
|
||||
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
|
||||
group = instruction.find("FunctionalGroup")
|
||||
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
|
||||
encoding_name = text(variant, "EncodingName")
|
||||
condition = text(variant, "EncodingCondition")
|
||||
opcode = int(text(variant, "Opcode"))
|
||||
key = (name, encoding_name, condition)
|
||||
if key in seen:
|
||||
fail(f"duplicate variant {key}")
|
||||
seen.add(key)
|
||||
operands = []
|
||||
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
|
||||
operands.append([
|
||||
operand.findtext("FieldName") or "",
|
||||
operand.findtext("DataFormatName") or "",
|
||||
operand.findtext("OperandType") or "",
|
||||
int(operand.findtext("OperandSize") or 0),
|
||||
boolean(operand.attrib["Input"]),
|
||||
boolean(operand.attrib["Output"]),
|
||||
boolean(operand.attrib["IsImplicit"]),
|
||||
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
|
||||
])
|
||||
record = {
|
||||
"kind": "variant",
|
||||
"instruction": name,
|
||||
"encoding": encoding_name,
|
||||
"condition": condition,
|
||||
"opcode": opcode,
|
||||
}
|
||||
# Extension variants keep only what classifies them; their
|
||||
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
|
||||
if encoding_name in BASE_ENCODINGS:
|
||||
record.update({
|
||||
"flags": sorted(flag for flag, value in flags.items() if value),
|
||||
"group": text(group, "Name"),
|
||||
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
|
||||
"operands": operands,
|
||||
})
|
||||
records.append(record)
|
||||
|
||||
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
|
||||
records.sort(key=lambda record: (
|
||||
order[record["kind"]],
|
||||
record.get("name", ""),
|
||||
record.get("encoding", ""),
|
||||
record.get("instruction", ""),
|
||||
record.get("condition", ""),
|
||||
))
|
||||
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
|
||||
|
||||
|
||||
def place(value, ranges):
|
||||
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
|
||||
mask = bits = 0
|
||||
for offset, count in ranges:
|
||||
if offset + count > 64:
|
||||
fail("opcode field extends beyond the second dword")
|
||||
low = (1 << count) - 1
|
||||
bits |= (value & low) << offset
|
||||
mask |= low << offset
|
||||
value >>= count
|
||||
if value:
|
||||
fail("opcode does not fit its field")
|
||||
return mask, bits
|
||||
|
||||
|
||||
def forms_from_snapshot(snapshot):
|
||||
records = [json.loads(line) for line in snapshot.splitlines()]
|
||||
source = records[0]
|
||||
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
|
||||
fail("snapshot header does not match this generator")
|
||||
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
|
||||
variants = [record for record in records if record["kind"] == "variant"]
|
||||
|
||||
extensions = {}
|
||||
for variant in variants:
|
||||
if variant["encoding"] in EXTENSIONS:
|
||||
base, kind = EXTENSIONS[variant["encoding"]]
|
||||
entry = extensions.setdefault((variant["instruction"], base), set())
|
||||
if kind == "literal" and variant["condition"] == "default":
|
||||
entry.add("always_literal")
|
||||
entry.add(kind)
|
||||
|
||||
forms = []
|
||||
for variant in variants:
|
||||
encoding_name = variant["encoding"]
|
||||
if encoding_name not in BASE_ENCODINGS:
|
||||
continue
|
||||
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
|
||||
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
|
||||
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
|
||||
encoding = encodings[encoding_name]
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
prefix_mask, _ = place(0, fields["ENCODING"])
|
||||
prefixes = {identifier & prefix_mask for identifier in encoding["identifiers"]}
|
||||
if len(prefixes) != 1:
|
||||
fail(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
prefix = prefixes.pop()
|
||||
id_mask = encoding["identifier_mask"]
|
||||
opcode = variant["opcode"]
|
||||
if "OP" in fields:
|
||||
op_mask, op_bits = place(opcode, fields["OP"])
|
||||
elif opcode == 0:
|
||||
op_mask = op_bits = 0
|
||||
else:
|
||||
fail(f"{encoding_name} has no OP field for opcode {opcode}")
|
||||
# The identifier mask can add selector bits beyond ENCODING and OP,
|
||||
# such as the FLAT segment field. Take them from the listed identifier.
|
||||
# MTBUF keeps one opcode bit in the second dword, which the
|
||||
# first-dword identifiers cannot express; carry it separately.
|
||||
low = 0xFFFFFFFF
|
||||
candidates = sorted({
|
||||
identifier for identifier in encoding["identifiers"]
|
||||
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
|
||||
})
|
||||
if len(candidates) != 1:
|
||||
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
|
||||
forms.append({
|
||||
"name": variant["instruction"],
|
||||
"encoding": BASE_ENCODINGS[encoding_name],
|
||||
"opcode": opcode,
|
||||
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
|
||||
# still select the instruction.
|
||||
"mask": id_mask | op_mask,
|
||||
"bits": (candidates[0] & id_mask) | op_bits,
|
||||
"bytes": encoding["bits"] // 8,
|
||||
"flags": variant["flags"],
|
||||
"group": variant["group"],
|
||||
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
|
||||
"operands": variant["operands"],
|
||||
})
|
||||
|
||||
by_pattern = {}
|
||||
for form in forms:
|
||||
if form["bits"] & ~form["mask"]:
|
||||
fail(f"{form['name']} has identifying bits outside its mask")
|
||||
key = (form["mask"], form["bits"])
|
||||
if key in by_pattern:
|
||||
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
|
||||
by_pattern[key] = form
|
||||
for left in forms:
|
||||
for right in forms:
|
||||
if left is right or left["mask"] == right["mask"]:
|
||||
continue
|
||||
common = left["mask"] & right["mask"]
|
||||
if (left["bits"] ^ right["bits"]) & common == 0:
|
||||
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
|
||||
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
|
||||
return source, encodings, forms
|
||||
|
||||
|
||||
def rust_from_snapshot(snapshot):
|
||||
source, encodings, forms = forms_from_snapshot(snapshot)
|
||||
out = []
|
||||
emit = out.append
|
||||
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
|
||||
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
|
||||
emit(f"// {source['copyright']}")
|
||||
emit("// SPDX-License-Identifier: MIT")
|
||||
emit("")
|
||||
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
|
||||
emit("")
|
||||
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
|
||||
emit("")
|
||||
|
||||
operand_sets = {}
|
||||
for form in forms:
|
||||
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
|
||||
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
|
||||
for operands_json in operand_sets:
|
||||
operands = json.loads(operands_json)
|
||||
items = ", ".join(
|
||||
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
|
||||
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
|
||||
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
|
||||
for field, data_format, kind, size, i, o, implicit, encoded in operands
|
||||
)
|
||||
emit(f" &[{items}],")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
families = sorted({form["encoding"] for form in forms})
|
||||
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
|
||||
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
|
||||
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
|
||||
for family in families:
|
||||
fields = encodings[reverse[family]]["fields"]
|
||||
items = ", ".join(
|
||||
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
|
||||
for name, ranges in fields
|
||||
)
|
||||
emit(f" (EncodingFamily::{family}, &[{items}]),")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
flag_bits = {
|
||||
"IsBranch": 1,
|
||||
"IsConditionalBranch": 2,
|
||||
"IsIndirectBranch": 4,
|
||||
"IsProgramTerminator": 8,
|
||||
"IsImmediatelyExecuted": 16,
|
||||
}
|
||||
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
|
||||
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
|
||||
emit("pub static FORMS: [Form; %d] = [" % len(forms))
|
||||
for form in forms:
|
||||
flags = sum(flag_bits[flag] for flag in form["flags"])
|
||||
extensions = sum(extension_bits[item] for item in form["extensions"])
|
||||
emit(
|
||||
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
|
||||
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
|
||||
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
|
||||
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
|
||||
)
|
||||
emit("];")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def compare(path, expected):
|
||||
actual = path.read_text() if path.exists() else ""
|
||||
if actual != expected:
|
||||
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
|
||||
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.xml:
|
||||
snapshot = snapshot_from_xml(args.xml.read_bytes())
|
||||
elif SNAPSHOT.exists():
|
||||
snapshot = SNAPSHOT.read_text()
|
||||
else:
|
||||
fail("no snapshot; pass --xml")
|
||||
rust = rust_from_snapshot(snapshot)
|
||||
if args.check:
|
||||
ok = compare(RUST, rust)
|
||||
if args.xml:
|
||||
ok = compare(SNAPSHOT, snapshot) and ok
|
||||
raise SystemExit(0 if ok else 1)
|
||||
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
|
||||
SNAPSHOT.write_text(snapshot)
|
||||
RUST.write_text(rust)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
mod rdna2;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
|
||||
//!
|
||||
//! Identification here establishes an instruction's form and length only. It is
|
||||
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
|
||||
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
|
||||
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
|
||||
//! ISA reference guide (see docs/research/rdna2.md).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
|
||||
|
||||
/// AMD base encoding of an instruction form.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum EncodingFamily {
|
||||
Ds,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Mimg,
|
||||
Mtbuf,
|
||||
Mubuf,
|
||||
Scratch,
|
||||
Smem,
|
||||
Sop1,
|
||||
Sop2,
|
||||
Sopc,
|
||||
Sopk,
|
||||
Sopp,
|
||||
Vintrp,
|
||||
Vop1,
|
||||
Vop2,
|
||||
Vop3,
|
||||
Vop3Sdst,
|
||||
Vop3p,
|
||||
Vopc,
|
||||
}
|
||||
|
||||
impl EncodingFamily {
|
||||
/// Every family, in table order.
|
||||
pub const ALL: [Self; 21] = [
|
||||
Self::Ds,
|
||||
Self::Exp,
|
||||
Self::Flat,
|
||||
Self::Global,
|
||||
Self::Mimg,
|
||||
Self::Mtbuf,
|
||||
Self::Mubuf,
|
||||
Self::Scratch,
|
||||
Self::Smem,
|
||||
Self::Sop1,
|
||||
Self::Sop2,
|
||||
Self::Sopc,
|
||||
Self::Sopk,
|
||||
Self::Sopp,
|
||||
Self::Vintrp,
|
||||
Self::Vop1,
|
||||
Self::Vop2,
|
||||
Self::Vop3,
|
||||
Self::Vop3Sdst,
|
||||
Self::Vop3p,
|
||||
Self::Vopc,
|
||||
];
|
||||
|
||||
/// Lower-case name used in reports.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ds => "ds",
|
||||
Self::Exp => "exp",
|
||||
Self::Flat => "flat",
|
||||
Self::Global => "global",
|
||||
Self::Mimg => "mimg",
|
||||
Self::Mtbuf => "mtbuf",
|
||||
Self::Mubuf => "mubuf",
|
||||
Self::Scratch => "scratch",
|
||||
Self::Smem => "smem",
|
||||
Self::Sop1 => "sop1",
|
||||
Self::Sop2 => "sop2",
|
||||
Self::Sopc => "sopc",
|
||||
Self::Sopk => "sopk",
|
||||
Self::Sopp => "sopp",
|
||||
Self::Vintrp => "vintrp",
|
||||
Self::Vop1 => "vop1",
|
||||
Self::Vop2 => "vop2",
|
||||
Self::Vop3 => "vop3",
|
||||
Self::Vop3Sdst => "vop3-sdst",
|
||||
Self::Vop3p => "vop3p",
|
||||
Self::Vopc => "vopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-flow flags recorded by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormFlags(pub u8);
|
||||
|
||||
impl FormFlags {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
#[allow(missing_docs)]
|
||||
pub const BRANCH: Self = Self(1);
|
||||
#[allow(missing_docs)]
|
||||
pub const CONDITIONAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const INDIRECT: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const TERMINATOR: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const IMMEDIATE: Self = Self(16);
|
||||
|
||||
/// Whether every flag in `other` is set.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension words an instruction form may carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Extensions(pub u8);
|
||||
|
||||
impl Extensions {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
/// A source field may select a trailing 32-bit literal.
|
||||
pub const LITERAL: Self = Self(1);
|
||||
/// The form always carries a trailing 32-bit literal.
|
||||
pub const ALWAYS_LITERAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const SDWA: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP8: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP16: Self = Self(16);
|
||||
/// MIMG non-sequential address dwords.
|
||||
pub const NSA: Self = Self(32);
|
||||
|
||||
/// Whether every extension in `other` is allowed.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FieldLayout {
|
||||
#[allow(missing_docs)]
|
||||
pub name: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
pub pieces: &'static [(u8, u8)],
|
||||
}
|
||||
|
||||
impl FieldLayout {
|
||||
/// Extracts the field from the instruction's first two dwords.
|
||||
pub fn extract(&self, value: u64) -> u32 {
|
||||
let mut result = 0u64;
|
||||
let mut shift = 0;
|
||||
for &(offset, count) in self.pieces {
|
||||
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
|
||||
shift += count;
|
||||
}
|
||||
result as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand as described by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OperandInfo {
|
||||
pub field: &'static str,
|
||||
pub format: &'static str,
|
||||
pub kind: &'static str,
|
||||
pub bits: u16,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
pub implicit: bool,
|
||||
/// Whether the operand occupies microcode bits.
|
||||
pub encoded: bool,
|
||||
}
|
||||
|
||||
/// One instruction in one base encoding.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct Form {
|
||||
pub name: &'static str,
|
||||
pub family: EncodingFamily,
|
||||
pub opcode: u16,
|
||||
/// Identifying bits over the first two dwords (little-endian, first dword low).
|
||||
pub mask: u64,
|
||||
pub bits: u64,
|
||||
/// Base length before literal, SDWA, DPP or NSA words.
|
||||
pub bytes: u8,
|
||||
pub flags: FormFlags,
|
||||
pub extensions: Extensions,
|
||||
pub group: &'static str,
|
||||
pub operands: &'static [OperandInfo],
|
||||
}
|
||||
|
||||
impl Form {
|
||||
/// The base encoding's field layouts.
|
||||
pub fn fields(&self) -> &'static [FieldLayout] {
|
||||
FIELDS
|
||||
.iter()
|
||||
.find(|(family, _)| *family == self.family)
|
||||
.map(|(_, fields)| *fields)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The named field's layout, if the encoding has one.
|
||||
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
|
||||
self.fields().iter().find(|field| field.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which extension words an identified instruction carries.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Trailer {
|
||||
/// A 32-bit literal follows the base encoding.
|
||||
pub literal: bool,
|
||||
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
|
||||
pub vector_control: Option<VectorControl>,
|
||||
/// Extra MIMG address dwords.
|
||||
pub nsa_dwords: u8,
|
||||
}
|
||||
|
||||
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum VectorControl {
|
||||
Sdwa,
|
||||
Dpp8 { fetch_inactive: bool },
|
||||
Dpp16,
|
||||
}
|
||||
|
||||
/// An identified instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identified {
|
||||
/// The matched form.
|
||||
pub form: &'static Form,
|
||||
/// First two dwords; the second is zero for 32-bit encodings.
|
||||
pub raw: u64,
|
||||
/// Total length in bytes, including extension words.
|
||||
pub len: usize,
|
||||
/// Extension words present.
|
||||
pub trailer: Trailer,
|
||||
}
|
||||
|
||||
impl Identified {
|
||||
/// Extracts a named field of the base encoding.
|
||||
pub fn field(&self, name: &str) -> Option<u32> {
|
||||
self.form.field(name).map(|field| field.extract(self.raw))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an instruction could not be identified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IdentifyError {
|
||||
/// Fewer bytes remain than the encoding or its extension words need.
|
||||
Truncated {
|
||||
/// Bytes required from the instruction start.
|
||||
needed: usize,
|
||||
},
|
||||
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
|
||||
Unassigned,
|
||||
/// The bits select an extension the form does not allow.
|
||||
InvalidExtension(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for IdentifyError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
|
||||
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
|
||||
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentifyError {}
|
||||
|
||||
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
|
||||
pub const SRC_LITERAL: u32 = 255;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
|
||||
pub const SRC_SDWA: u32 = 0xf9;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
|
||||
pub const SRC_DPP16: u32 = 0xfa;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
|
||||
pub const SRC_DPP8: u32 = 0xe9;
|
||||
/// DPP8 with fetch-inactive set.
|
||||
pub const SRC_DPP8_FI: u32 = 0xea;
|
||||
|
||||
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
|
||||
let start = index.checked_mul(4)?;
|
||||
let chunk = bytes.get(start..start.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes(chunk.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Finds the form whose identifying bits match.
|
||||
///
|
||||
/// Masks never overlap ambiguously; the generator rejects such tables.
|
||||
pub fn lookup(raw: u64) -> Option<&'static Form> {
|
||||
FORMS.iter().find(|form| raw & form.mask == form.bits)
|
||||
}
|
||||
|
||||
/// Identifies the instruction at the start of `bytes` and computes its length.
|
||||
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
|
||||
let second = read_dword(bytes, 1);
|
||||
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
|
||||
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
|
||||
.or_else(|| {
|
||||
// Distinguish a truncated 64-bit instruction from unassigned bits.
|
||||
FORMS.iter().find(|form| {
|
||||
form.bytes == 8
|
||||
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
|
||||
})
|
||||
})
|
||||
.ok_or(IdentifyError::Unassigned)?;
|
||||
if form.bytes == 8 && second.is_none() {
|
||||
return Err(IdentifyError::Truncated { needed: 8 });
|
||||
}
|
||||
let raw = if form.bytes == 4 {
|
||||
u64::from(first)
|
||||
} else {
|
||||
raw_guess
|
||||
};
|
||||
let mut trailer = Trailer::default();
|
||||
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
|
||||
match form.family {
|
||||
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
|
||||
trailer.literal = [source("SSRC0"), source("SSRC1")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
|
||||
match source("SRC0") {
|
||||
Some(SRC_LITERAL) => trailer.literal = true,
|
||||
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
|
||||
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
|
||||
Some(SRC_DPP8) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
})
|
||||
}
|
||||
Some(SRC_DPP8_FI) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
|
||||
trailer.literal = true;
|
||||
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
|
||||
return Err(IdentifyError::InvalidExtension("literal"));
|
||||
}
|
||||
match trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
|
||||
return Err(IdentifyError::InvalidExtension("sdwa"));
|
||||
}
|
||||
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp8"));
|
||||
}
|
||||
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp16"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
|
||||
return Err(IdentifyError::InvalidExtension("nsa"));
|
||||
}
|
||||
let len = usize::from(form.bytes)
|
||||
+ 4 * usize::from(trailer.literal)
|
||||
+ 4 * usize::from(trailer.vector_control.is_some())
|
||||
+ 4 * usize::from(trailer.nsa_dwords);
|
||||
if bytes.len() < len {
|
||||
return Err(IdentifyError::Truncated { needed: len });
|
||||
}
|
||||
Ok(Identified {
|
||||
form,
|
||||
raw,
|
||||
len,
|
||||
trailer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of forms per encoding family in the metadata.
|
||||
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
|
||||
EncodingFamily::ALL
|
||||
.iter()
|
||||
.map(|&family| {
|
||||
(
|
||||
family,
|
||||
FORMS.iter().filter(|form| form.family == family).count(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
||||
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_isa::meta::{
|
||||
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
|
||||
};
|
||||
|
||||
fn words(values: &[u32]) -> Vec<u8> {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn name_of(values: &[u32]) -> (&'static str, usize) {
|
||||
let found = identify(&words(values)).unwrap();
|
||||
(found.form.name, found.len)
|
||||
}
|
||||
|
||||
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
|
||||
fn source_mnemonics(source: &str) -> Vec<String> {
|
||||
source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap().trim())
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
|
||||
.map(|line| {
|
||||
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
|
||||
mnemonic
|
||||
.trim_end_matches("_E32")
|
||||
.trim_end_matches("_E64")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut checked = 0;
|
||||
for entry in fs::read_dir(&directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
let source = fs::read_to_string(path.with_extension("s")).unwrap();
|
||||
let mut offset = 0;
|
||||
let mut identified = Vec::new();
|
||||
while offset < binary.len() {
|
||||
let found = identify(&binary[offset..])
|
||||
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
|
||||
identified.push(found.form.name.to_owned());
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, binary.len(), "{}", path.display());
|
||||
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 11, "only {checked} fixtures found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_assembled_words_identify() {
|
||||
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
|
||||
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
|
||||
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
|
||||
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
|
||||
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
|
||||
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
|
||||
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
|
||||
// VOP3 v_add_f32_e64 v0, v1, v2: VOP3 opcode 259 = 256 + VOP2 opcode 3.
|
||||
assert_eq!(name_of(&[0xd503_0000, 0x0002_0501]), ("V_ADD_F32", 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
|
||||
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
|
||||
assert!(literal.trailer.literal);
|
||||
// s_add_u32 s0, s1, literal: SSRC1 = 255.
|
||||
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
|
||||
// VOP3 with SRC2 = 255.
|
||||
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
|
||||
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
|
||||
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
|
||||
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
|
||||
assert_eq!(sdwa.len, 8);
|
||||
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
|
||||
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
|
||||
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
|
||||
assert_eq!(
|
||||
dpp8.trailer.vector_control,
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
assert_eq!(
|
||||
identify(&[0x00, 0x00, 0x81]),
|
||||
Err(IdentifyError::Truncated { needed: 4 })
|
||||
);
|
||||
// VOP3 first dword alone.
|
||||
assert_eq!(
|
||||
identify(&words(&[0xd503_0000])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// Literal selected but absent.
|
||||
assert_eq!(
|
||||
identify(&words(&[0x7e00_02ff])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
|
||||
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
|
||||
assert_eq!(
|
||||
identify(&words(&[0xbfff_0000])),
|
||||
Err(IdentifyError::Unassigned)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_outside_a_forms_metadata_are_rejected() {
|
||||
let without_sdwa = FORMS
|
||||
.iter()
|
||||
.find(|form| {
|
||||
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
|
||||
})
|
||||
.expect("a VOP1 form without SDWA");
|
||||
let word = (without_sdwa.bits as u32) | 0xf9;
|
||||
assert_eq!(
|
||||
identify(&words(&[word, 0])),
|
||||
Err(IdentifyError::InvalidExtension("sdwa"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_form_identifies_as_itself() {
|
||||
for form in &FORMS {
|
||||
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
|
||||
assert_eq!(
|
||||
lookup(form.bits).unwrap().family,
|
||||
form.family,
|
||||
"{}",
|
||||
form.name
|
||||
);
|
||||
}
|
||||
let total: usize = inventory().iter().map(|(_, count)| count).sum();
|
||||
assert_eq!(total, FORMS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_word_opcode_table_agrees_with_full_metadata() {
|
||||
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
|
||||
for (opcode, name, family) in [
|
||||
(
|
||||
BUFFER_LOAD_DWORD,
|
||||
"BUFFER_LOAD_DWORD",
|
||||
EncodingFamily::Mubuf,
|
||||
),
|
||||
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
|
||||
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
|
||||
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
|
||||
] {
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == name && form.family == family)
|
||||
.unwrap();
|
||||
assert!(opcode.matches(form.bits as u32), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,38 @@ Run from the checkout root after extracting the approved XML.
|
||||
```sh
|
||||
python3 crates/isa/generate_rdna2.py path/to/amdgpu_isa_rdna2.xml | diff -u crates/isa/src/rdna2.rs -
|
||||
```
|
||||
|
||||
## Complete instruction metadata
|
||||
|
||||
`crates/isa/generate_rdna2_meta.py` reduces the same approved XML to every
|
||||
gfx1030 base instruction form: 1,460 forms in 21 encoding families, with
|
||||
identifying bits, field layouts, operands (field, data format, operand type,
|
||||
width, direction), control-flow flags and allowed extension words. It runs in
|
||||
two stages so regeneration and CI checks need no network and no XML:
|
||||
|
||||
```sh
|
||||
python3 crates/isa/generate_rdna2_meta.py --xml path/to/amdgpu_isa_rdna2.xml # XML -> snapshot -> Rust
|
||||
python3 crates/isa/generate_rdna2_meta.py --check # snapshot -> Rust, compare
|
||||
```
|
||||
|
||||
The snapshot `crates/isa/data/rdna2.jsonl` is sorted, normalised MIT data
|
||||
under the AMD notice in `crates/isa/LICENSE-AMD`. The generator rejects a
|
||||
different XML hash, another architecture, unclassified encodings, duplicate
|
||||
variants, identifying bits outside a mask and overlapping encodings. Two
|
||||
details are not in the identifier masks and are handled explicitly: MIMG
|
||||
opcode bit 7 sits at bit 0, and MTBUF opcode bit 3 sits at bit 53.
|
||||
|
||||
The XML names literal, SDWA, DPP8, DPP16 and NSA variants without a rule for
|
||||
when they apply. `xenora_isa::meta::identify` implements those length rules by
|
||||
hand: a source field equal to 255 (`SRC_LITERAL` in the XML) adds a literal;
|
||||
VOP1, VOP2 and VOPC `SRC0` values 0xF9, 0xFA, 0xE9 and 0xEA add an SDWA, DPP16
|
||||
or DPP8 control dword (from the RDNA 2 ISA guide's SDWA and DPP sections, not
|
||||
the XML); MIMG `NSA` adds that many address dwords. An extension the form does
|
||||
not list is rejected. Every LLVM-assembled fixture identifies with exact
|
||||
boundaries and matching mnemonics. A broader LLVM comparison of the extension
|
||||
rules is still open because it needs the LLVM oracle.
|
||||
|
||||
Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
@@ -1,5 +1,7 @@
|
||||
# gfx1030 instruction coverage
|
||||
|
||||
For counts of every gfx1030 form in AMD's metadata against forms Xenora can execute, run `xenora shaders coverage`. Its "discovered" column is metadata coverage, not execution support.
|
||||
|
||||
The decoder accepts an explicitly tagged, little-endian gfx1030 Wave32
|
||||
stream with 32 lanes per wave under the [synthetic memory ABI](../adr/0003-demo-memory-model.md).
|
||||
Recognition means that the opcode mask matches. Decode additionally checks
|
||||
|
||||
Reference in new issue
Block a user