mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 05:52:50 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db40a1307d | ||
|
|
b174b45bed | ||
|
|
7504a5d48d | ||
|
|
2b858ab7c6 | ||
|
|
076f3e52aa | ||
|
|
e17e3bfc63 | ||
|
|
1915e2374c | ||
|
|
6545a25b7b | ||
|
|
d5514aa9d8 | ||
|
|
7623fde0e7 | ||
|
|
f2e6db03a9 | ||
|
|
3a14bd98ab | ||
|
|
d31b8ef20c | ||
|
|
81cfe69143 | ||
|
|
91fe3f345b | ||
|
|
0a722d2e60 | ||
|
|
0cf4e8a9e9 | ||
|
|
d8c117cdd3 | ||
|
|
9ef9537540 | ||
|
|
081f9c9e06 | ||
|
|
fbe1d3c4d1 | ||
|
|
9e35434f63 | ||
|
|
6e64737021 | ||
|
|
8b0b62a771 | ||
|
|
9500ed17e5 | ||
|
|
547b10250d |
No files matched your search
@@ -15,6 +15,8 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Added
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
|
||||
@@ -9,7 +9,7 @@ Xenora is an open-source project written primarily in Rust that builds and verif
|
||||
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
|
||||
|
||||
> [!CAUTION]
|
||||
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft, Rockstar Games, Take-Two Interactive, or any other publisher or platform holder.
|
||||
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
|
||||
@@ -454,10 +454,16 @@ fn run_imports_sync(
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
let mut lines = csv_text.lines();
|
||||
let has_import_kind = lines
|
||||
.next()
|
||||
.is_some_and(|header| header.ends_with(",import_kind"));
|
||||
let header = lines.next().unwrap_or_default();
|
||||
let has_import_kind = header.ends_with(",import_kind");
|
||||
// Binding does not resolve delay-loaded imports, so the backlog omits them.
|
||||
let table_column = header
|
||||
.split(',')
|
||||
.position(|column| column == "import_table");
|
||||
for line in lines {
|
||||
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
|
||||
continue;
|
||||
}
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn backlog_leaves_out_delay_loaded_imports() {
|
||||
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
|
||||
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
|
||||
let xenora = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
xenora(&["probe", "--pe", fixture]);
|
||||
xenora(&["imports", "sync"]);
|
||||
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
|
||||
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
|
||||
std::fs::remove_dir_all(report).unwrap();
|
||||
|
||||
assert_eq!(listed.matches(",delayed,").count(), 3);
|
||||
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
|
||||
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
|
||||
assert!(!backlog.contains("fixture-delay"), "{backlog}");
|
||||
}
|
||||
@@ -4,8 +4,8 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
VectorSource,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
@@ -362,6 +362,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateOp::from_word(first) {
|
||||
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
"expected a normal SGPR destination",
|
||||
));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
|
||||
let src = ((first >> 16) & 0x7f) as u8;
|
||||
if src > 105 {
|
||||
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
|
||||
@@ -4,13 +4,13 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode,
|
||||
decode_at,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
VectorInteger,
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
|
||||
Source, VectorAlu, VectorInteger,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
@@ -416,6 +416,25 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate(
|
||||
match op {
|
||||
ScalarImmediateOp::MovkI32 => ScalarImmediate::Move,
|
||||
ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove,
|
||||
ScalarImmediateOp::AddkI32 => ScalarImmediate::Add,
|
||||
ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply,
|
||||
},
|
||||
dst,
|
||||
simm16,
|
||||
),
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate(
|
||||
ScalarImmediate::Compare(Comparison {
|
||||
// The reference's VOPC relation offsets, as for SOPC above.
|
||||
offset: op.relation() as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
}),
|
||||
src,
|
||||
simm16,
|
||||
),
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::SccZero,
|
||||
@@ -545,6 +564,7 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
@@ -553,7 +573,7 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 120, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -611,6 +631,12 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
s_or_b32 s103, s3, 0x80000000
|
||||
s_xor_b32 s102, s104, -16
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
s_movk_i32 s105, 0xffff
|
||||
s_movk_i32 s8, 0
|
||||
s_cmovk_i32 s105, 0x8000
|
||||
s_addk_i32 s9, 0x7fff
|
||||
s_addk_i32 s105, 0xffff
|
||||
s_mulk_i32 s8, 0x8001
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
@@ -636,6 +662,15 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
// Every SOPK compare on the lowest and highest readable SGPR.
|
||||
for relation in ["eq", "lg", "gt", "ge", "lt", "le"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for register in ["s0", "s7", "s8", "s105"] {
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap();
|
||||
}
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap();
|
||||
}
|
||||
}
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
@@ -1051,3 +1086,108 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
|
||||
use xenora_decoder::ScalarImmediateCompareOp;
|
||||
let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes());
|
||||
// Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding).
|
||||
// s_movk_i32 s8, 0x8000
|
||||
let decoded = decode_word(0xb008_8000).unwrap();
|
||||
assert_eq!(decoded[0].byte_len, 4);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MovkI32,
|
||||
dst: 8,
|
||||
simm16: 0x8000
|
||||
}
|
||||
);
|
||||
// s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is
|
||||
// the translator's job, not the decoder's.
|
||||
assert_eq!(
|
||||
decode_word(0xb169_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::CmovkI32,
|
||||
dst: 105,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7.
|
||||
assert_eq!(
|
||||
decode_word(0xb580_1234).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkGtU32,
|
||||
src: 0,
|
||||
simm16: 0x1234
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb407_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkLeI32,
|
||||
src: 7,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0
|
||||
assert_eq!(
|
||||
decode_word(0xb789_7fff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::AddkI32,
|
||||
dst: 9,
|
||||
simm16: 0x7fff
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb869_0000).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MulkI32,
|
||||
dst: 105,
|
||||
simm16: 0
|
||||
}
|
||||
);
|
||||
// vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused.
|
||||
for (word, mnemonic, detail) in [
|
||||
(
|
||||
0xb06a_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07e_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07d_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb06c_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb1fc_0001,
|
||||
"s_cmpk_eq_i32",
|
||||
"expected a normal SGPR operand",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
decode_word(word).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail },
|
||||
"{word:#010x}"
|
||||
);
|
||||
}
|
||||
// Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported.
|
||||
for word in [0xb080_0000u32, 0xb888_0000] {
|
||||
assert!(decode_word(word).is_err(), "{word:#010x}");
|
||||
}
|
||||
// The fixed store fence is still the one decoded SOPK word outside the registry.
|
||||
assert_eq!(
|
||||
decode_word(0xbbfd_0000).unwrap()[0].instruction,
|
||||
Instruction::WaitStore
|
||||
);
|
||||
}
|
||||
@@ -61,6 +61,7 @@ OPERATIONS = {
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
"mov": "Move", "cmov": "ConditionalMove",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
@@ -106,7 +107,7 @@ SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
|
||||
CONTROL_S1 = SHIFTS | {"bfe"}
|
||||
# Operations that always read SCC: the select condition. They need carry_in scc.
|
||||
SCC_READERS = {"cselect"}
|
||||
SCC_READERS = {"cselect", "cmov"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
@@ -208,6 +209,22 @@ PRIMITIVES = {
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# SOPK forms (operation, signedness) -> (SCC effect, primitive, reads SCC). D is
|
||||
# SDST and the immediate is SIMM16 sign-extended (guide 12.2); `sext_simm16` is
|
||||
# the sign extension, so a move or conditional move writes it unchanged.
|
||||
IMMEDIATE_PRIMITIVES = {
|
||||
("mov", "signed"): ("unchanged", "sext_simm16", False),
|
||||
("cmov", "signed"): ("unchanged", "sext_simm16", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
}
|
||||
# SOPK compares: the opcode is the group base (3 signed, 9 unsigned) plus the
|
||||
# relation's index in this order (guide 13.1.2).
|
||||
SOPK_COMPARE_BASES = {"signed": 3, "unsigned": 9}
|
||||
SOPK_RELATION_ORDER = ["eq", "lg", "gt", "ge", "lt", "le"]
|
||||
# Operand-rule kinds whose forms have a 16-bit immediate field.
|
||||
IMMEDIATE_KINDS = {"immediate", "immediate_compare"}
|
||||
|
||||
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
|
||||
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
|
||||
VECTOR_PRIMITIVES = {
|
||||
@@ -286,6 +303,34 @@ OPERAND_RULES = {
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"sopk_sgpr": {
|
||||
"rust": "SopkSgpr",
|
||||
"enum": "ScalarImmediateOp",
|
||||
"shape": {
|
||||
"family": "SOPK",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SIMM16", "class": "simm16"}],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# SOPK never takes a literal dword; the decoder rejects SDST 106-127.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
|
||||
"kind": "immediate",
|
||||
},
|
||||
"sopk_compare": {
|
||||
"rust": "SopkCompare",
|
||||
"enum": "ScalarImmediateCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPK",
|
||||
"src": [
|
||||
{"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
{"field": "SIMM16", "class": "simm16"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# The compared register is SDST (S0); the decoder rejects SDST 106-127.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
|
||||
"kind": "immediate_compare",
|
||||
},
|
||||
"vopc_vcc": {
|
||||
"rust": "VopcVcc",
|
||||
"enum": "VectorCompareOp",
|
||||
@@ -579,6 +624,15 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if field == "SIMM16":
|
||||
# The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign
|
||||
# extended), unsigned compares as FMT_NUM_U16 (zero extended).
|
||||
wanted = "FMT_NUM_U16" if form["signedness"] == "unsigned" else "FMT_NUM_I16"
|
||||
if size != 16 or data_format != wanted:
|
||||
errors.append(f"{label}: SIMM16 is {size} bits {data_format} in the XML, expected 16 {wanted}")
|
||||
if (is_input, is_output) != (True, False):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
continue
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if size != expected:
|
||||
@@ -730,6 +784,15 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare":
|
||||
errors.append(f"{label}: relation {relation} exists only for VOPC compares")
|
||||
elif _rule_kind(form) == "immediate_compare":
|
||||
base = SOPK_COMPARE_BASES.get(form["signedness"])
|
||||
expected = None if base is None else base + SOPK_RELATION_ORDER.index(relation) \
|
||||
if relation in SOPK_RELATION_ORDER else None
|
||||
if form["opcode"] != expected:
|
||||
errors.append(
|
||||
f"{label}: relation {relation}/{form['signedness']} has SOPK opcode "
|
||||
f"{expected} (guide 13.1.2), not {form['opcode']}"
|
||||
)
|
||||
elif _rule_kind(form) == "vector_compare":
|
||||
base = VOPC_INTEGER_BASES.get(form["signedness"])
|
||||
expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation]
|
||||
@@ -753,7 +816,8 @@ def validate(registry, snapshot):
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
table = IMMEDIATE_PRIMITIVES if _rule_kind(form) == "immediate" else PRIMITIVES
|
||||
primitive = table.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
@@ -773,10 +837,11 @@ def validate(registry, snapshot):
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
("vector_compare" if _rule_kind(form) == "vector_compare" else "compare")
|
||||
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
|
||||
if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "immediate" if _rule_kind(form) == "immediate"
|
||||
else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
@@ -1209,6 +1274,98 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "immediate":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC (the conditional move's condition).",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation always reads the old SDST (`D = D op imm`).",
|
||||
" pub const fn reads_dst(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['operation'] in ('add', 'mul') else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SDST (`None` leaves it unchanged) and, for forms that write it, the",
|
||||
" /// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by",
|
||||
" /// forms that do not read it) and `scc_in` the SCC read by the conditional move.",
|
||||
" pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option<u32>, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = IMMEDIATE_PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
immediate = "primitive::sext_simm16(simm16)"
|
||||
variant = form["variant"]
|
||||
if form["operation"] == "mov":
|
||||
out.append(f" Self::{variant} => (Some({immediate}), None),")
|
||||
elif form["operation"] == "cmov":
|
||||
out.append(
|
||||
f" Self::{variant} => (if scc_in {{ Some({immediate}) }} else {{ None }}, None),"
|
||||
)
|
||||
elif form["scc"] == "unchanged":
|
||||
out.append(f" Self::{variant} => (Some(primitive::{function}(dst, {immediate})), None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{variant} => {{",
|
||||
f" let (value, scc) = primitive::{function}(dst, {immediate});",
|
||||
" (Some(value), Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "immediate_compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with SDST (S0) on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The SCC: whether the relation holds for SDST and SIMM16, which signed forms",
|
||||
" /// sign-extend and unsigned forms zero-extend.",
|
||||
" pub const fn test(self, dst: u32, simm16: u16) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
immediate = "primitive::sext_simm16(simm16)" if form["signedness"] == "signed" else "simm16 as u32"
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(dst, {immediate}),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
|
||||
@@ -19,6 +19,7 @@ source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f
|
||||
include = [
|
||||
"rdna2/sop2.toml",
|
||||
"rdna2/sopc.toml",
|
||||
"rdna2/sopk.toml",
|
||||
"rdna2/sop1.toml",
|
||||
"rdna2/vop2.toml",
|
||||
"rdna2/vopc.toml",
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOPK 16-bit immediate integer forms (#215) ----
|
||||
# SDST is the destination, and the left operand of the compares; SIMM16 is
|
||||
# sign-extended except by the unsigned compares (guide 12.2). The word never
|
||||
# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors,
|
||||
# so the decoder accepts them as compare operands and the translator never
|
||||
# writes them.
|
||||
|
||||
[operand_rules.sopk_sgpr]
|
||||
family = "SOPK"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SIMM16", class = "simm16" }]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[operand_rules.sopk_compare]
|
||||
family = "SOPK"
|
||||
src = [
|
||||
{ field = "SDST", class = "sgpr", min = 0, max = 105 },
|
||||
{ field = "SIMM16", class = "simm16" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 0
|
||||
variant = "MovkI32"
|
||||
operation = "mov"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 2
|
||||
variant = "CmovkI32"
|
||||
operation = "cmov"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_I32"
|
||||
family = "SOPK"
|
||||
opcode = 3
|
||||
variant = "CmpkEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_I32"
|
||||
family = "SOPK"
|
||||
opcode = 4
|
||||
variant = "CmpkLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 5
|
||||
variant = "CmpkGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 6
|
||||
variant = "CmpkGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 7
|
||||
variant = "CmpkLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 8
|
||||
variant = "CmpkLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_U32"
|
||||
family = "SOPK"
|
||||
opcode = 9
|
||||
variant = "CmpkEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_U32"
|
||||
family = "SOPK"
|
||||
opcode = 10
|
||||
variant = "CmpkLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 11
|
||||
variant = "CmpkGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 12
|
||||
variant = "CmpkGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 13
|
||||
variant = "CmpkLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 14
|
||||
variant = "CmpkLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 15
|
||||
variant = "AddkI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MULK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 16
|
||||
variant = "MulkI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+25
-1
@@ -19,7 +19,8 @@ pub use rdna2::{
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
@@ -185,6 +186,21 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the
|
||||
/// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and
|
||||
/// `s_cmovk_i32` reads it.
|
||||
ScalarImmediate {
|
||||
op: ScalarImmediateOp,
|
||||
dst: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit
|
||||
/// immediate, writing only SCC.
|
||||
ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp,
|
||||
src: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
|
||||
VectorCompare {
|
||||
@@ -270,6 +286,8 @@ impl Instruction {
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediate { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
@@ -330,6 +348,12 @@ impl fmt::Display for Instruction {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarImmediate { dst, simm16, .. } => {
|
||||
write!(formatter, " s{dst}, {simm16:#x}")
|
||||
}
|
||||
Self::ScalarImmediateCompare { src, simm16, .. } => {
|
||||
write!(formatter, " s{src}, {simm16:#x}")
|
||||
}
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
|
||||
@@ -218,6 +218,11 @@ pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2).
|
||||
pub const fn sext_simm16(simm16: u16) -> u32 {
|
||||
simm16 as i16 as i32 as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
|
||||
@@ -90,6 +90,10 @@ pub enum Operation {
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16.
|
||||
Move,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
|
||||
ConditionalMove,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
@@ -204,6 +208,13 @@ pub enum OperandRule {
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
|
||||
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
|
||||
/// never takes a literal. Everything else is rejected as unsupported.
|
||||
SopkSgpr,
|
||||
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
|
||||
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
|
||||
SopkCompare,
|
||||
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
|
||||
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
|
||||
/// VGPR. Everything else is rejected as unsupported.
|
||||
|
||||
+698
-48
@@ -344,17 +344,17 @@ impl ScalarUnaryOp {
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::NotB32 => 45,
|
||||
Self::BrevB32 => 46,
|
||||
Self::Bcnt0I32B32 => 47,
|
||||
Self::Bcnt1I32B32 => 48,
|
||||
Self::Ff0I32B32 => 49,
|
||||
Self::Ff1I32B32 => 50,
|
||||
Self::FlbitI32B32 => 51,
|
||||
Self::FlbitI32 => 52,
|
||||
Self::SextI32I8 => 53,
|
||||
Self::SextI32I16 => 54,
|
||||
Self::AbsI32 => 55,
|
||||
Self::NotB32 => 61,
|
||||
Self::BrevB32 => 62,
|
||||
Self::Bcnt0I32B32 => 63,
|
||||
Self::Bcnt1I32B32 => 64,
|
||||
Self::Ff0I32B32 => 65,
|
||||
Self::Ff1I32B32 => 66,
|
||||
Self::FlbitI32B32 => 67,
|
||||
Self::FlbitI32 => 68,
|
||||
Self::SextI32I8 => 69,
|
||||
Self::SextI32I16 => 70,
|
||||
Self::AbsI32 => 71,
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -1198,6 +1198,304 @@ impl ScalarCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// SOPK operations declared in the semantic registry (operand rule `sopk_compare`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarImmediateCompareOp {
|
||||
/// `s_cmpk_eq_i32` (SOPK opcode 3): signed compare eq, SCC = relation.
|
||||
CmpkEqI32,
|
||||
/// `s_cmpk_lg_i32` (SOPK opcode 4): signed compare lg, SCC = relation.
|
||||
CmpkLgI32,
|
||||
/// `s_cmpk_gt_i32` (SOPK opcode 5): signed compare gt, SCC = relation.
|
||||
CmpkGtI32,
|
||||
/// `s_cmpk_ge_i32` (SOPK opcode 6): signed compare ge, SCC = relation.
|
||||
CmpkGeI32,
|
||||
/// `s_cmpk_lt_i32` (SOPK opcode 7): signed compare lt, SCC = relation.
|
||||
CmpkLtI32,
|
||||
/// `s_cmpk_le_i32` (SOPK opcode 8): signed compare le, SCC = relation.
|
||||
CmpkLeI32,
|
||||
/// `s_cmpk_eq_u32` (SOPK opcode 9): unsigned compare eq, SCC = relation.
|
||||
CmpkEqU32,
|
||||
/// `s_cmpk_lg_u32` (SOPK opcode 10): unsigned compare lg, SCC = relation.
|
||||
CmpkLgU32,
|
||||
/// `s_cmpk_gt_u32` (SOPK opcode 11): unsigned compare gt, SCC = relation.
|
||||
CmpkGtU32,
|
||||
/// `s_cmpk_ge_u32` (SOPK opcode 12): unsigned compare ge, SCC = relation.
|
||||
CmpkGeU32,
|
||||
/// `s_cmpk_lt_u32` (SOPK opcode 13): unsigned compare lt, SCC = relation.
|
||||
CmpkLtU32,
|
||||
/// `s_cmpk_le_u32` (SOPK opcode 14): unsigned compare le, SCC = relation.
|
||||
CmpkLeU32,
|
||||
}
|
||||
|
||||
/// ScalarImmediateCompareOp by SOPK OP field value; `None` for undeclared opcodes.
|
||||
const SCALAR_IMMEDIATE_COMPARE_OP_BY_OPCODE: [Option<ScalarImmediateCompareOp>; 32] = [
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(ScalarImmediateCompareOp::CmpkEqI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLgI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkGtI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkGeI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLtI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLeI32),
|
||||
Some(ScalarImmediateCompareOp::CmpkEqU32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLgU32),
|
||||
Some(ScalarImmediateCompareOp::CmpkGtU32),
|
||||
Some(ScalarImmediateCompareOp::CmpkGeU32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLtU32),
|
||||
Some(ScalarImmediateCompareOp::CmpkLeU32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
];
|
||||
|
||||
impl ScalarImmediateCompareOp {
|
||||
/// Every operation, in registry order.
|
||||
pub const ALL: [Self; 12] = [
|
||||
Self::CmpkEqI32,
|
||||
Self::CmpkLgI32,
|
||||
Self::CmpkGtI32,
|
||||
Self::CmpkGeI32,
|
||||
Self::CmpkLtI32,
|
||||
Self::CmpkLeI32,
|
||||
Self::CmpkEqU32,
|
||||
Self::CmpkLgU32,
|
||||
Self::CmpkGtU32,
|
||||
Self::CmpkGeU32,
|
||||
Self::CmpkLtU32,
|
||||
Self::CmpkLeU32,
|
||||
];
|
||||
|
||||
/// Selects the operation from a first instruction word: the SOPK encoding
|
||||
/// bits (mask 0xf000_0000) and then the OP field (bits 23-27).
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
if word & 0xf000_0000 != 0xb000_0000 {
|
||||
return None;
|
||||
}
|
||||
SCALAR_IMMEDIATE_COMPARE_OP_BY_OPCODE[((word >> 23) & 0x1f) as usize]
|
||||
}
|
||||
|
||||
/// Lower-case mnemonic.
|
||||
pub const fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::CmpkEqI32 => "s_cmpk_eq_i32",
|
||||
Self::CmpkLgI32 => "s_cmpk_lg_i32",
|
||||
Self::CmpkGtI32 => "s_cmpk_gt_i32",
|
||||
Self::CmpkGeI32 => "s_cmpk_ge_i32",
|
||||
Self::CmpkLtI32 => "s_cmpk_lt_i32",
|
||||
Self::CmpkLeI32 => "s_cmpk_le_i32",
|
||||
Self::CmpkEqU32 => "s_cmpk_eq_u32",
|
||||
Self::CmpkLgU32 => "s_cmpk_lg_u32",
|
||||
Self::CmpkGtU32 => "s_cmpk_gt_u32",
|
||||
Self::CmpkGeU32 => "s_cmpk_ge_u32",
|
||||
Self::CmpkLtU32 => "s_cmpk_lt_u32",
|
||||
Self::CmpkLeU32 => "s_cmpk_le_u32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::CmpkEqI32 => 47,
|
||||
Self::CmpkLgI32 => 48,
|
||||
Self::CmpkGtI32 => 49,
|
||||
Self::CmpkGeI32 => 50,
|
||||
Self::CmpkLtI32 => 51,
|
||||
Self::CmpkLeI32 => 52,
|
||||
Self::CmpkEqU32 => 53,
|
||||
Self::CmpkLgU32 => 54,
|
||||
Self::CmpkGtU32 => 55,
|
||||
Self::CmpkGeU32 => 56,
|
||||
Self::CmpkLtU32 => 57,
|
||||
Self::CmpkLeU32 => 58,
|
||||
}]
|
||||
}
|
||||
|
||||
/// The relation tested, with SDST (S0) on the left.
|
||||
pub const fn relation(self) -> CompareRelation {
|
||||
match self {
|
||||
Self::CmpkEqI32 => CompareRelation::Equal,
|
||||
Self::CmpkLgI32 => CompareRelation::NotEqual,
|
||||
Self::CmpkGtI32 => CompareRelation::Greater,
|
||||
Self::CmpkGeI32 => CompareRelation::GreaterOrEqual,
|
||||
Self::CmpkLtI32 => CompareRelation::Less,
|
||||
Self::CmpkLeI32 => CompareRelation::LessOrEqual,
|
||||
Self::CmpkEqU32 => CompareRelation::Equal,
|
||||
Self::CmpkLgU32 => CompareRelation::NotEqual,
|
||||
Self::CmpkGtU32 => CompareRelation::Greater,
|
||||
Self::CmpkGeU32 => CompareRelation::GreaterOrEqual,
|
||||
Self::CmpkLtU32 => CompareRelation::Less,
|
||||
Self::CmpkLeU32 => CompareRelation::LessOrEqual,
|
||||
}
|
||||
}
|
||||
|
||||
/// The SCC: whether the relation holds for SDST and SIMM16, which signed forms
|
||||
/// sign-extend and unsigned forms zero-extend.
|
||||
pub const fn test(self, dst: u32, simm16: u16) -> bool {
|
||||
match self {
|
||||
Self::CmpkEqI32 => primitive::eq_b32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkLgI32 => primitive::ne_b32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkGtI32 => primitive::gt_i32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkGeI32 => primitive::ge_i32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkLtI32 => primitive::lt_i32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkLeI32 => primitive::le_i32(dst, primitive::sext_simm16(simm16)),
|
||||
Self::CmpkEqU32 => primitive::eq_b32(dst, simm16 as u32),
|
||||
Self::CmpkLgU32 => primitive::ne_b32(dst, simm16 as u32),
|
||||
Self::CmpkGtU32 => primitive::gt_u32(dst, simm16 as u32),
|
||||
Self::CmpkGeU32 => primitive::ge_u32(dst, simm16 as u32),
|
||||
Self::CmpkLtU32 => primitive::lt_u32(dst, simm16 as u32),
|
||||
Self::CmpkLeU32 => primitive::le_u32(dst, simm16 as u32),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SOPK operations declared in the semantic registry (operand rule `sopk_sgpr`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarImmediateOp {
|
||||
/// `s_movk_i32` (SOPK opcode 0): signed mov, SCC = unchanged.
|
||||
MovkI32,
|
||||
/// `s_cmovk_i32` (SOPK opcode 2): signed cmov plus SCC, SCC = unchanged.
|
||||
CmovkI32,
|
||||
/// `s_addk_i32` (SOPK opcode 15): signed add, SCC = signed_overflow.
|
||||
AddkI32,
|
||||
/// `s_mulk_i32` (SOPK opcode 16): signed mul, SCC = unchanged.
|
||||
MulkI32,
|
||||
}
|
||||
|
||||
/// ScalarImmediateOp by SOPK OP field value; `None` for undeclared opcodes.
|
||||
const SCALAR_IMMEDIATE_OP_BY_OPCODE: [Option<ScalarImmediateOp>; 32] = [
|
||||
Some(ScalarImmediateOp::MovkI32),
|
||||
None,
|
||||
Some(ScalarImmediateOp::CmovkI32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(ScalarImmediateOp::AddkI32),
|
||||
Some(ScalarImmediateOp::MulkI32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
];
|
||||
|
||||
impl ScalarImmediateOp {
|
||||
/// Every operation, in registry order.
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::MovkI32,
|
||||
Self::CmovkI32,
|
||||
Self::AddkI32,
|
||||
Self::MulkI32,
|
||||
];
|
||||
|
||||
/// Selects the operation from a first instruction word: the SOPK encoding
|
||||
/// bits (mask 0xf000_0000) and then the OP field (bits 23-27).
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
if word & 0xf000_0000 != 0xb000_0000 {
|
||||
return None;
|
||||
}
|
||||
SCALAR_IMMEDIATE_OP_BY_OPCODE[((word >> 23) & 0x1f) as usize]
|
||||
}
|
||||
|
||||
/// Lower-case mnemonic.
|
||||
pub const fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::MovkI32 => "s_movk_i32",
|
||||
Self::CmovkI32 => "s_cmovk_i32",
|
||||
Self::AddkI32 => "s_addk_i32",
|
||||
Self::MulkI32 => "s_mulk_i32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::MovkI32 => 45,
|
||||
Self::CmovkI32 => 46,
|
||||
Self::AddkI32 => 59,
|
||||
Self::MulkI32 => 60,
|
||||
}]
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC (the conditional move's condition).
|
||||
pub const fn reads_scc(self) -> bool {
|
||||
match self {
|
||||
Self::MovkI32 => false,
|
||||
Self::CmovkI32 => true,
|
||||
Self::AddkI32 => false,
|
||||
Self::MulkI32 => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation writes SCC.
|
||||
pub const fn writes_scc(self) -> bool {
|
||||
match self {
|
||||
Self::MovkI32 => false,
|
||||
Self::CmovkI32 => false,
|
||||
Self::AddkI32 => true,
|
||||
Self::MulkI32 => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation always reads the old SDST (`D = D op imm`).
|
||||
pub const fn reads_dst(self) -> bool {
|
||||
match self {
|
||||
Self::MovkI32 => false,
|
||||
Self::CmovkI32 => false,
|
||||
Self::AddkI32 => true,
|
||||
Self::MulkI32 => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The new SDST (`None` leaves it unchanged) and, for forms that write it, the
|
||||
/// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by
|
||||
/// forms that do not read it) and `scc_in` the SCC read by the conditional move.
|
||||
pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option<u32>, Option<bool>) {
|
||||
match self {
|
||||
Self::MovkI32 => (Some(primitive::sext_simm16(simm16)), None),
|
||||
Self::CmovkI32 => (if scc_in { Some(primitive::sext_simm16(simm16)) } else { None }, None),
|
||||
Self::AddkI32 => {
|
||||
let (value, scc) = primitive::add_overflow_i32(dst, primitive::sext_simm16(simm16));
|
||||
(Some(value), Some(scc))
|
||||
}
|
||||
Self::MulkI32 => (Some(primitive::mul_lo_i32(dst, primitive::sext_simm16(simm16))), None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAluOp {
|
||||
@@ -1366,24 +1664,24 @@ impl VectorAluOp {
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::MulI32I24 => 56,
|
||||
Self::MulHiI32I24 => 57,
|
||||
Self::MulU32U24 => 58,
|
||||
Self::MulHiU32U24 => 59,
|
||||
Self::MinI32 => 60,
|
||||
Self::MaxI32 => 61,
|
||||
Self::MinU32 => 62,
|
||||
Self::MaxU32 => 63,
|
||||
Self::XnorB32 => 64,
|
||||
Self::AddNcU32 => 65,
|
||||
Self::SubNcU32 => 66,
|
||||
Self::SubrevNcU32 => 67,
|
||||
Self::LshrrevB32 => 68,
|
||||
Self::AshrrevI32 => 69,
|
||||
Self::LshlrevB32 => 70,
|
||||
Self::AndB32 => 71,
|
||||
Self::OrB32 => 72,
|
||||
Self::XorB32 => 73,
|
||||
Self::MulI32I24 => 72,
|
||||
Self::MulHiI32I24 => 73,
|
||||
Self::MulU32U24 => 74,
|
||||
Self::MulHiU32U24 => 75,
|
||||
Self::MinI32 => 76,
|
||||
Self::MaxI32 => 77,
|
||||
Self::MinU32 => 78,
|
||||
Self::MaxU32 => 79,
|
||||
Self::XnorB32 => 80,
|
||||
Self::AddNcU32 => 81,
|
||||
Self::SubNcU32 => 82,
|
||||
Self::SubrevNcU32 => 83,
|
||||
Self::LshrrevB32 => 84,
|
||||
Self::AshrrevI32 => 85,
|
||||
Self::LshlrevB32 => 86,
|
||||
Self::AndB32 => 87,
|
||||
Self::OrB32 => 88,
|
||||
Self::XorB32 => 89,
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -1836,22 +2134,22 @@ impl VectorCompareOp {
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::CmpLtI32 => 74,
|
||||
Self::CmpEqI32 => 75,
|
||||
Self::CmpLeI32 => 76,
|
||||
Self::CmpGtI32 => 77,
|
||||
Self::CmpNeI32 => 78,
|
||||
Self::CmpGeI32 => 79,
|
||||
Self::CmpLtU32 => 80,
|
||||
Self::CmpEqU32 => 81,
|
||||
Self::CmpLeU32 => 82,
|
||||
Self::CmpGtU32 => 83,
|
||||
Self::CmpNeU32 => 84,
|
||||
Self::CmpGeU32 => 85,
|
||||
Self::CmpFI32 => 86,
|
||||
Self::CmpTI32 => 87,
|
||||
Self::CmpFU32 => 88,
|
||||
Self::CmpTU32 => 89,
|
||||
Self::CmpLtI32 => 90,
|
||||
Self::CmpEqI32 => 91,
|
||||
Self::CmpLeI32 => 92,
|
||||
Self::CmpGtI32 => 93,
|
||||
Self::CmpNeI32 => 94,
|
||||
Self::CmpGeI32 => 95,
|
||||
Self::CmpLtU32 => 96,
|
||||
Self::CmpEqU32 => 97,
|
||||
Self::CmpLeU32 => 98,
|
||||
Self::CmpGtU32 => 99,
|
||||
Self::CmpNeU32 => 100,
|
||||
Self::CmpGeU32 => 101,
|
||||
Self::CmpFI32 => 102,
|
||||
Self::CmpTI32 => 103,
|
||||
Self::CmpFU32 => 104,
|
||||
Self::CmpTU32 => 105,
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -1987,13 +2285,13 @@ impl VectorAluVop3Op {
|
||||
/// The validated registry row of this encoding.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::AddNcU32 => 90,
|
||||
Self::AddNcU32 => 106,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form and encoding variant, in registry order.
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 91] = [
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 107] = [
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
@@ -2039,6 +2337,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 91] = [
|
||||
("S_CMP_GE_U32", EncodingFamily::Sopc),
|
||||
("S_CMP_LT_U32", EncodingFamily::Sopc),
|
||||
("S_CMP_LE_U32", EncodingFamily::Sopc),
|
||||
("S_MOVK_I32", EncodingFamily::Sopk),
|
||||
("S_CMOVK_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_EQ_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LG_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_GT_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_GE_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LT_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LE_I32", EncodingFamily::Sopk),
|
||||
("S_CMPK_EQ_U32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LG_U32", EncodingFamily::Sopk),
|
||||
("S_CMPK_GT_U32", EncodingFamily::Sopk),
|
||||
("S_CMPK_GE_U32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LT_U32", EncodingFamily::Sopk),
|
||||
("S_CMPK_LE_U32", EncodingFamily::Sopk),
|
||||
("S_ADDK_I32", EncodingFamily::Sopk),
|
||||
("S_MULK_I32", EncodingFamily::Sopk),
|
||||
("S_NOT_B32", EncodingFamily::Sop1),
|
||||
("S_BREV_B32", EncodingFamily::Sop1),
|
||||
("S_BCNT0_I32_B32", EncodingFamily::Sop1),
|
||||
@@ -2088,7 +2402,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 91] = [
|
||||
];
|
||||
|
||||
/// One validated row per registry form, in registry order.
|
||||
pub static FORMS: [FormSemantics; 91] = [
|
||||
pub static FORMS: [FormSemantics; 107] = [
|
||||
FormSemantics {
|
||||
name: "S_ADD_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
@@ -3034,6 +3348,342 @@ pub static FORMS: [FormSemantics; 91] = [
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.4", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_MOVK_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 0,
|
||||
operation: Operation::Move,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkSgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMOVK_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 2,
|
||||
operation: Operation::ConditionalMove,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::Scc,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkSgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_EQ_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 3,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LG_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 4,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_GT_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 5,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_GE_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 6,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LT_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 7,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LE_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 8,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_EQ_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 9,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LG_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 10,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_GT_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 11,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_GE_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 12,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LT_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 13,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_CMPK_LE_U32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 14,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Relation,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkCompare,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_ADDK_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 15,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::SignedOverflow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkSgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_MULK_I32",
|
||||
family: EncodingFamily::Sopk,
|
||||
opcode: 16,
|
||||
operation: Operation::Multiply,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: None,
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::SopkSgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.2", page: 106 }, SpecRef { document: Document::Guide, section: "13.1.2", page: 240 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_NOT_B32",
|
||||
family: EncodingFamily::Sop1,
|
||||
|
||||
@@ -5,8 +5,8 @@ use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp,
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -78,6 +78,64 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() {
|
||||
for op in ScalarImmediateOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
for op in ScalarImmediateCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
// The two enums together are the registry's SOPK forms; the fixed
|
||||
// s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither.
|
||||
dispatch_selects_exactly(EncodingFamily::Sopk, |word| {
|
||||
ScalarImmediateOp::from_word(word)
|
||||
.map(|op| op.semantics().name)
|
||||
.or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name))
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() {
|
||||
// SIMM16 = 0x8000 is -32768 signed and 32768 unsigned.
|
||||
let d = 0xffff_8000;
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false),
|
||||
(Some(0x8000_0000), Some(true))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false),
|
||||
(Some(4), Some(false))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true),
|
||||
(Some(0xffff_fffd), None)
|
||||
);
|
||||
assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000));
|
||||
assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
|
||||
@@ -306,6 +306,26 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// RBIT Xd, Xn: reverse the bit order of the source.
|
||||
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// CLZ Xd, Xn: count the leading zero bits of the source.
|
||||
pub fn clz_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
|
||||
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x9ac2_2000
|
||||
| ((u32::from(xm) & 0x1f) << 16)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
|
||||
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
|
||||
/// [`DbtMetrics::interpreter_fallbacks`].
|
||||
pub fn is_native(insn: &Insn) -> bool {
|
||||
let wide = matches!(insn.size, 4 | 8);
|
||||
// The bit scans work on any register or memory source, and the bit test
|
||||
// needs the index in a register.
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
// Only the `0F A3` form has the bit index in a register. The `0F BA`
|
||||
// group form takes an immediate index and may write memory, so it
|
||||
// stays on the shared semantics.
|
||||
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
|
||||
Op::Pop => insn.encoding == Encoding::OpReg,
|
||||
Op::Mov
|
||||
| Op::Movzx
|
||||
@@ -500,6 +508,18 @@ impl Emitter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
|
||||
///
|
||||
/// An operation narrower than the register reads only the low bytes of its
|
||||
/// source, so the bits above them must not take part in a bit scan.
|
||||
fn zero_extend(&mut self, xd: u8, size: u8) {
|
||||
match size {
|
||||
8 => {}
|
||||
4 => self.asm.mov_reg_32(xd, xd),
|
||||
_ => self.asm.uxth_32(xd, xd),
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective address into X1, clobbering X9.
|
||||
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
|
||||
self.load_condition(insn.condition);
|
||||
self.store_rm(insn, X12, completed);
|
||||
}
|
||||
Op::Bsf | Op::Bsr => {
|
||||
// BSF and BSR write the index of the lowest or the highest set
|
||||
// bit of the source into the destination and set the zero flag
|
||||
// when the source is zero (Intel SDM Volume 2B, "BSF" and
|
||||
// "BSR"). A zero source leaves the destination undefined, so
|
||||
// the destination keeps its value, which is the same rule the
|
||||
// interpreter and the reference apply.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
match insn.op {
|
||||
// The lowest set bit is the highest set bit of the
|
||||
// reversed value, so its index is the leading zero count
|
||||
// of the reversed value.
|
||||
Op::Bsf => {
|
||||
self.asm.rbit_64(X10, X9);
|
||||
self.asm.clz_64(X10, X10);
|
||||
}
|
||||
// The highest set bit sits at 63 minus the leading zero
|
||||
// count.
|
||||
_ => {
|
||||
self.asm.clz_64(X10, X9);
|
||||
self.asm.movz_64(X13, 63, 0);
|
||||
self.asm.sub_reg_64(X10, X13, X10);
|
||||
}
|
||||
}
|
||||
self.load_reg(X11, insn.reg);
|
||||
self.asm.tst_reg_64(X9, X9);
|
||||
// CSEL takes the first operand when the condition holds, so
|
||||
// the index is the value that replaces the destination.
|
||||
self.asm.csel_64(X11, X10, X11, Condition::Ne);
|
||||
match insn.size {
|
||||
// A 16-bit destination keeps the bits above it, so the
|
||||
// register is merged rather than replaced.
|
||||
2 => self.store_reg(insn.reg, insn.size, X11),
|
||||
// A 32-bit or 64-bit destination is written in full. The
|
||||
// index has no bits above the operand width, so this
|
||||
// matches the interpreter's 32-bit write, and a zero
|
||||
// source keeps the whole register unchanged.
|
||||
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
|
||||
}
|
||||
if flags {
|
||||
// The zero flag is set when the source is zero. The other
|
||||
// flags are undefined and keep their value.
|
||||
self.asm.cset_32(X12, Condition::Eq);
|
||||
self.asm.strb_uoff(X12, X19, ZF);
|
||||
}
|
||||
}
|
||||
Op::Bt => {
|
||||
// BT sets the carry flag from the tested bit and leaves the
|
||||
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
|
||||
// index comes from the register operand and is masked to the
|
||||
// operand width.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
self.load_reg(X10, insn.reg);
|
||||
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
|
||||
self.asm.and_reg_64(X10, X10, X13);
|
||||
self.asm.load_imm_64(X11, 1);
|
||||
self.asm.lslv_64(X11, X11, X10);
|
||||
self.asm.tst_reg_64(X9, X11);
|
||||
if flags {
|
||||
self.asm.cset_32(X12, Condition::Ne);
|
||||
self.asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
}
|
||||
Op::Cmov => {
|
||||
self.load_rm(X10, insn, completed);
|
||||
self.load_reg(X9, insn.reg);
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
|
||||
//! "The .idata Section"). Binding and static inspection both use it, so they
|
||||
//! agree on which imports an image has and how they are named.
|
||||
//!
|
||||
//! Static inspection also reads the delay-load directory ("Delay-Load Import
|
||||
//! Tables (Image Only)"). Binding does not: the PE format leaves those imports
|
||||
//! to a delay-load helper that runs inside the image on first use.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536;
|
||||
pub const MAX_NAME_LEN: usize = 4096;
|
||||
|
||||
const DESCRIPTOR_LEN: u32 = 20;
|
||||
const DELAY_DESCRIPTOR_LEN: u32 = 32;
|
||||
/// Delay-load attribute bit 0: the descriptor's address fields are RVAs.
|
||||
const DELAY_RVA_BASED: u32 = 1;
|
||||
const ORDINAL_FLAG: u64 = 1 << 63;
|
||||
|
||||
/// How an import names its target. A symbol that happens to be spelled like an
|
||||
@@ -42,6 +49,24 @@ pub struct ImportEntry {
|
||||
pub iat_rva: u32,
|
||||
}
|
||||
|
||||
/// A delay-load descriptor field that must hold an RVA.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DelayField {
|
||||
DllName,
|
||||
AddressTable,
|
||||
NameTable,
|
||||
}
|
||||
|
||||
impl fmt::Display for DelayField {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::DllName => "DLL name",
|
||||
Self::AddressTable => "import address table",
|
||||
Self::NameTable => "import name table",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImportTableError {
|
||||
/// A structure at this RVA is not fully backed by section data.
|
||||
@@ -56,6 +81,25 @@ pub enum ImportTableError {
|
||||
ReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA sets reserved attribute bits.
|
||||
DelayReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier
|
||||
/// form whose address fields are virtual addresses. It is not read.
|
||||
DelayVirtualAddresses {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA leaves a required field zero.
|
||||
DelayFieldMissing {
|
||||
rva: u32,
|
||||
field: DelayField,
|
||||
},
|
||||
/// The declared delay-load directory ends at this RVA before its empty
|
||||
/// descriptor.
|
||||
DelayDirectoryEnd {
|
||||
rva: u32,
|
||||
},
|
||||
TooManyDescriptors,
|
||||
TooManyImports,
|
||||
}
|
||||
@@ -63,7 +107,10 @@ pub enum ImportTableError {
|
||||
impl fmt::Display for ImportTableError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
|
||||
Self::OutOfBounds { rva } => write!(
|
||||
f,
|
||||
"import data at RVA 0x{rva:08x} is truncated or outside the section data"
|
||||
),
|
||||
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
|
||||
Self::ReservedBits { rva } => {
|
||||
write!(
|
||||
@@ -71,6 +118,21 @@ impl fmt::Display for ImportTableError {
|
||||
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
|
||||
)
|
||||
}
|
||||
Self::DelayReservedBits { rva } => write!(
|
||||
f,
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}"
|
||||
),
|
||||
Self::DelayVirtualAddresses { rva } => write!(
|
||||
f,
|
||||
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
|
||||
),
|
||||
Self::DelayFieldMissing { rva, field } => {
|
||||
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
|
||||
}
|
||||
Self::DelayDirectoryEnd { rva } => write!(
|
||||
f,
|
||||
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
|
||||
),
|
||||
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
|
||||
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
|
||||
}
|
||||
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
return Ok(());
|
||||
}
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?;
|
||||
descriptor = descriptor
|
||||
.checked_add(DESCRIPTOR_LEN)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
|
||||
@@ -167,11 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
|
||||
///
|
||||
/// Only descriptors that lie wholly inside the declared directory are read,
|
||||
/// and the directory must hold the empty descriptor that ends the table.
|
||||
/// Each entry's `iat_rva` is its slot in the delay import address table.
|
||||
/// Returns every import before the first problem, and the problem.
|
||||
pub fn parse_delay_imports(
|
||||
bytes: &[u8],
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
rva_to_offset: impl Fn(u32) -> Option<usize>,
|
||||
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
|
||||
let reader = Reader {
|
||||
bytes,
|
||||
rva_to_offset,
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
|
||||
(entries, error)
|
||||
}
|
||||
|
||||
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
let end = directory_rva
|
||||
.checked_add(directory_size)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
|
||||
let mut descriptor = directory_rva;
|
||||
for _ in 0..MAX_DESCRIPTORS {
|
||||
if end - descriptor < DELAY_DESCRIPTOR_LEN {
|
||||
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
|
||||
}
|
||||
let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?;
|
||||
// The table ends with an empty descriptor.
|
||||
if fields == [0; DELAY_DESCRIPTOR_LEN as usize] {
|
||||
return Ok(());
|
||||
}
|
||||
let attributes = reader.u32(descriptor)?;
|
||||
if attributes & !DELAY_RVA_BASED != 0 {
|
||||
return Err(ImportTableError::DelayReservedBits { rva: descriptor });
|
||||
}
|
||||
if attributes & DELAY_RVA_BASED == 0 {
|
||||
return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor });
|
||||
}
|
||||
let name_rva = reader.u32(descriptor + 4)?;
|
||||
let address_rva = reader.u32(descriptor + 12)?;
|
||||
let names_rva = reader.u32(descriptor + 16)?;
|
||||
// All three are required. The address table holds thunk addresses, so
|
||||
// it cannot stand in for a missing name table.
|
||||
for (field, rva) in [
|
||||
(DelayField::DllName, name_rva),
|
||||
(DelayField::AddressTable, address_rva),
|
||||
(DelayField::NameTable, names_rva),
|
||||
] {
|
||||
if rva == 0 {
|
||||
return Err(ImportTableError::DelayFieldMissing {
|
||||
rva: descriptor,
|
||||
field,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Each must also start in section data, whether or not an import uses it.
|
||||
reader.array::<1>(name_rva)?;
|
||||
reader.array::<8>(address_rva)?;
|
||||
reader.array::<8>(names_rva)?;
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
|
||||
// The declared end bounds this sum.
|
||||
descriptor += DELAY_DESCRIPTOR_LEN;
|
||||
}
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
module: &str,
|
||||
lookup_rva: u32,
|
||||
address_rva: u32,
|
||||
slots_on_disk: bool,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
// Without a lookup table the address table holds the same entries on disk.
|
||||
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
return Err(ImportTableError::TooManyImports);
|
||||
}
|
||||
let iat_rva = at(address_rva)?;
|
||||
if slots_on_disk {
|
||||
// A delay-load slot starts out holding its thunk's address.
|
||||
reader.array::<8>(iat_rva)?;
|
||||
}
|
||||
let name = if value & ORDINAL_FLAG != 0 {
|
||||
let ordinal = value & !ORDINAL_FLAG;
|
||||
ImportName::Ordinal(
|
||||
|
||||
+113
-28
@@ -11,7 +11,9 @@
|
||||
//! startup blockers.
|
||||
|
||||
use crate::dbt::{is_native, is_translatable};
|
||||
use crate::import_table::{ImportName, ImportTableError, parse_imports};
|
||||
use crate::import_table::{
|
||||
ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports,
|
||||
};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
|
||||
@@ -678,6 +680,11 @@ pub struct ProbeReport {
|
||||
pub imports: Vec<ImportedSymbol>,
|
||||
/// Why the import table could not be read to its end.
|
||||
pub import_error: Option<ImportTableError>,
|
||||
/// Delay-loaded imports before the first malformed entry, if any. Binding
|
||||
/// does not resolve them, so `imports` and its totals leave them out.
|
||||
pub delayed_imports: Vec<ImportedSymbol>,
|
||||
/// Why the delay-load import tables could not be read to their end.
|
||||
pub delay_import_error: Option<ImportTableError>,
|
||||
pub instruction_records: Vec<InstructionRecord>,
|
||||
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
|
||||
}
|
||||
@@ -822,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// The delay import descriptor is data directory 13. It exists only when
|
||||
// NumberOfRvaAndSizes covers it.
|
||||
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 224
|
||||
&& u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) > 13
|
||||
{
|
||||
(
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 216..opt_offset + 220]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 220..opt_offset + 224]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
@@ -960,35 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
let backed_offset = |rva: u32| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
};
|
||||
let (entries, import_error) = if import_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
parse_imports(bytes, import_dir_rva, |rva| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
})
|
||||
parse_imports(bytes, import_dir_rva, backed_offset)
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
import_name: entry.name,
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
canonical_symbol: binding.map(|service| service.symbol.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
|
||||
};
|
||||
let describe = |entry: ImportEntry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
import_name: entry.name,
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
canonical_symbol: binding.map(|service| service.symbol.clone()),
|
||||
}
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries.into_iter().map(&describe).collect();
|
||||
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
|
||||
|
||||
// 4. Control-Flow-Aware Static Disassembly
|
||||
//
|
||||
@@ -1124,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
tls,
|
||||
imports,
|
||||
import_error,
|
||||
delayed_imports,
|
||||
delay_import_error,
|
||||
instruction_records,
|
||||
first_unsupported_dbt_insn,
|
||||
})
|
||||
@@ -1142,7 +1180,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
|
||||
// 1. imports.csv
|
||||
let mut imports_csv = String::from(
|
||||
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
|
||||
"module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
|
||||
);
|
||||
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n");
|
||||
let mut modules = BTreeSet::new();
|
||||
@@ -1186,7 +1224,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
|
||||
"{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
|
||||
imp.category, imp.is_supported
|
||||
);
|
||||
if !imp.is_supported {
|
||||
@@ -1194,6 +1232,34 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
missing += 1;
|
||||
}
|
||||
}
|
||||
// Delay-loaded imports follow the ordinary rows. Binding does not resolve
|
||||
// them, so they stay out of every ordinary total, the startup clusters and
|
||||
// `missing_imports.csv`.
|
||||
let mut delayed_modules = BTreeSet::new();
|
||||
for imp in &report.delayed_imports {
|
||||
delayed_modules.insert(imp.dll.to_ascii_lowercase());
|
||||
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
|
||||
let import_kind = if is_ordinal { "ordinal" } else { "name" };
|
||||
let module = imp.dll.replace('"', "\"\"");
|
||||
let symbol = imp.symbol.replace('"', "\"\"");
|
||||
let canonical = imp.canonical_module.as_deref().unwrap_or("");
|
||||
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let (priority, cluster) = imp.startup_priority();
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}",
|
||||
imp.iat_rva,
|
||||
imp.category,
|
||||
imp.is_supported,
|
||||
imp.coverage_label()
|
||||
);
|
||||
}
|
||||
let delayed_slots = report.delayed_imports.len();
|
||||
let delayed_dlls = delayed_modules.len();
|
||||
let delay_error = report
|
||||
.delay_import_error
|
||||
.map_or_else(|| "none".to_string(), |error| error.to_string());
|
||||
fs::write(out.join("imports.csv"), imports_csv)?;
|
||||
fs::write(out.join("missing_imports.csv"), missing_csv)?;
|
||||
|
||||
@@ -1250,6 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"stub_slots": {stubs},
|
||||
"recognized_unsupported_slots": {unsupported},
|
||||
"missing_handler_slots": {unknown},
|
||||
"delayed_imports": {delayed_slots},
|
||||
"delayed_imported_dlls_count": {delayed_dlls},
|
||||
"delay_import_error": "{delay_error}",
|
||||
"total_relocations": {},
|
||||
"dir64_relocations": {},
|
||||
"tls_callbacks_count": {},
|
||||
@@ -1381,6 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n"
|
||||
);
|
||||
if let Some(error) = &report.delay_import_error {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n"
|
||||
);
|
||||
}
|
||||
if trusted_runner_slots > 0 {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
@@ -1425,6 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
distinct_imports.len(),
|
||||
unique_symbols.len()
|
||||
);
|
||||
if delayed_slots > 0 {
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document."
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.",
|
||||
|
||||
@@ -251,6 +251,21 @@ impl ServicesState {
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Forget the last-error value of a guest thread that has ended, so a
|
||||
/// later thread given the same TEB address starts at zero. Returns
|
||||
/// whether a nonzero value was dropped.
|
||||
///
|
||||
/// Each service call names its own TEB and the values sit behind one
|
||||
/// lock, so calls for different threads may run concurrently. Retire a
|
||||
/// TEB only once no service call for that thread is still running.
|
||||
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
|
||||
self.last_errors
|
||||
.lock()
|
||||
.expect("guest last-error state")
|
||||
.remove(&teb)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn set_last_error(&self, teb: u64, error: u32) {
|
||||
let mut errors = self.last_errors.lock().expect("guest last-error state");
|
||||
if error == 0 {
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Static probe reports for delay-loaded PE imports.
|
||||
//!
|
||||
//! The expected names and slot RVAs are read off the layout that
|
||||
//! `fixtures/pe/delay-imports.py` writes, not from the parser.
|
||||
//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in
|
||||
//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use xenora_loader::import_table::{DelayField, ImportTableError, parse_delay_imports};
|
||||
use xenora_loader::probe::{
|
||||
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe");
|
||||
|
||||
/// DLL, symbol or ordinal, and import address table slot RVA.
|
||||
type Row = (&'static str, &'static str, u32);
|
||||
|
||||
const ORDINARY: [Row; 2] = [
|
||||
("fixture-ordinary.dll", "OrdinaryByName", 0x2050),
|
||||
("fixture-ordinary.dll", "Ordinal#3", 0x2058),
|
||||
];
|
||||
const DELAYED: [Row; 3] = [
|
||||
("fixture-delay-a.dll", "DelayedAlpha", 0x3000),
|
||||
("fixture-delay-a.dll", "Ordinal#7", 0x3008),
|
||||
("fixture-delay-b.dll", "DelayedBeta", 0x3020),
|
||||
];
|
||||
|
||||
// File offsets in the fixture.
|
||||
const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108;
|
||||
const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216;
|
||||
const DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
|
||||
const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16;
|
||||
/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600.
|
||||
const FIRST_DESCRIPTOR: usize = 0x800;
|
||||
const SECOND_DESCRIPTOR: usize = 0x820;
|
||||
|
||||
fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> {
|
||||
imports
|
||||
.iter()
|
||||
.map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn put(pe: &mut [u8], offset: usize, value: u32) {
|
||||
pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Probe `pe` and return the report with the text files it exports.
|
||||
fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id()));
|
||||
let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap();
|
||||
let files = [
|
||||
"imports.csv",
|
||||
"missing_imports.csv",
|
||||
"candidate_static_report.json",
|
||||
"candidate_static_report.md",
|
||||
"runtime_gap_matrix.md",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap()))
|
||||
.collect();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
(report, files)
|
||||
}
|
||||
|
||||
fn json_field(json: &str, name: &str) -> String {
|
||||
let prefix = format!("\"{name}\": ");
|
||||
json.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(&prefix))
|
||||
.unwrap_or_else(|| panic!("no {name} in the JSON report"))
|
||||
.trim_end_matches(',')
|
||||
.trim_matches('"')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_and_delayed_imports_are_reported_apart() {
|
||||
let (report, files) = export(FIXTURE, "fixture");
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let mut lines = files["imports.csv"].lines();
|
||||
let header = lines.next().unwrap();
|
||||
assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,"));
|
||||
assert!(header.ends_with(",import_kind"));
|
||||
let columns = header.split(',').count();
|
||||
// The first four columns and the last one of every row.
|
||||
let listed: Vec<String> = lines
|
||||
.map(|line| {
|
||||
let fields: Vec<&str> = line.split(',').collect();
|
||||
assert_eq!(fields.len(), columns, "{line}");
|
||||
format!("{},{}", fields[..4].join(","), fields[columns - 1])
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal",
|
||||
"\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name",
|
||||
"\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal",
|
||||
"\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name",
|
||||
]
|
||||
);
|
||||
|
||||
// Neither fixture DLL has a handler, so both ordinary imports are missing.
|
||||
// The delayed ones are not the binder's to resolve and stay off its list.
|
||||
assert_eq!(
|
||||
files["missing_imports.csv"].lines().collect::<Vec<_>>(),
|
||||
[
|
||||
"module,symbol_or_ordinal,iat_rva,import_kind",
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal",
|
||||
]
|
||||
);
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
for (name, expected) in [
|
||||
("total_imports", "2"),
|
||||
("imported_dlls_count", "1"),
|
||||
("unresolved_imports", "2"),
|
||||
("distinct_import_keys", "2"),
|
||||
("delayed_imports", "3"),
|
||||
("delayed_imported_dlls_count", "2"),
|
||||
("delay_import_error", "none"),
|
||||
] {
|
||||
assert_eq!(json_field(json, name), expected, "{name}");
|
||||
}
|
||||
|
||||
let md = &files["candidate_static_report.md"];
|
||||
assert!(md.contains("- **Total Imported Thunks**: `2`"));
|
||||
assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs."));
|
||||
assert!(!md.contains("Delay-load import table is malformed"));
|
||||
assert!(
|
||||
files["runtime_gap_matrix.md"]
|
||||
.contains("The delay-load import tables contain 3 more slots across 2 DLLs.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() {
|
||||
let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap();
|
||||
|
||||
// The entry point is a lone RET at RVA 0x1000. The three delay-load slots
|
||||
// hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching
|
||||
// one would mean the probe followed a slot, so none may be decoded.
|
||||
let decoded: Vec<(u32, &[u8])> = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.map(|record| (record.rva, record.bytes.as_slice()))
|
||||
.collect();
|
||||
assert_eq!(decoded, [(0x1000, &[0xc3][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_without_a_delay_directory_keeps_its_ordinary_imports() {
|
||||
// `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`,
|
||||
// with its slot at RVA 0x2040 and no delay import descriptor.
|
||||
let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let (report, files) = export(runner, "runner");
|
||||
assert_eq!(
|
||||
rows(&report.imports),
|
||||
[("xenora.dll", "fixture_draw", 0x2040)]
|
||||
);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,"));
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "1");
|
||||
assert_eq!(json_field(json, "imported_dlls_count"), "1");
|
||||
assert_eq!(json_field(json, "delayed_imports"), "0");
|
||||
assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0");
|
||||
assert_eq!(json_field(json, "delay_import_error"), "none");
|
||||
assert!(!files["runtime_gap_matrix.md"].contains("delay-load"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_directory_beyond_the_declared_count_is_not_read() {
|
||||
// With 13 data directories the header has no delay import descriptor, so
|
||||
// the bytes at its offset mean nothing.
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
|
||||
type Case = (
|
||||
&'static str,
|
||||
fn(&mut Vec<u8>),
|
||||
usize,
|
||||
ImportTableError,
|
||||
&'static str,
|
||||
);
|
||||
// (name, damage, delayed imports still listed, error, message)
|
||||
let cases: [Case; 13] = [
|
||||
(
|
||||
"directory-out-of-range",
|
||||
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// `.rdata` keeps 0x230 bytes: the first descriptor and half the second.
|
||||
"section-data-ends-inside-descriptor",
|
||||
|pe| put(pe, RDATA_RAW_SIZE, 0x230),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x2220 },
|
||||
"import data at RVA 0x00002220 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The file ends where `.data` and its address tables would begin.
|
||||
"file-ends-before-address-table",
|
||||
|pe| pe.truncate(0xa00),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x3000 },
|
||||
"import data at RVA 0x00003000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"name-table-out-of-range",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"address-table-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The second DLL's name table becomes the empty entry that ends the
|
||||
// first one, at RVA 0x2110, so no import reads the address table.
|
||||
"address-table-out-of-range-without-imports",
|
||||
|pe| {
|
||||
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
|
||||
put(pe, SECOND_DESCRIPTOR + 12, 0x9000);
|
||||
},
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"dll-name-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// RVA 0x2028 is zero padding after the ordinary import directory.
|
||||
"dll-name-empty",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
|
||||
2,
|
||||
ImportTableError::MalformedName { rva: 0x2028 },
|
||||
"malformed import name at RVA 0x00002028",
|
||||
),
|
||||
(
|
||||
"dll-name-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::DllName,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no DLL name",
|
||||
),
|
||||
(
|
||||
"address-table-missing",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
|
||||
0,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2200,
|
||||
field: DelayField::AddressTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002200 has no import address table",
|
||||
),
|
||||
(
|
||||
"name-table-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::NameTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no import name table",
|
||||
),
|
||||
(
|
||||
"reserved-attribute-bit",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR, 3),
|
||||
0,
|
||||
ImportTableError::DelayReservedBits { rva: 0x2200 },
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x00002200",
|
||||
),
|
||||
(
|
||||
"virtual-address-form",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR, 0),
|
||||
2,
|
||||
ImportTableError::DelayVirtualAddresses { rva: 0x2220 },
|
||||
"delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read",
|
||||
),
|
||||
];
|
||||
|
||||
for (name, damage, listed, error, message) in cases {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
damage(&mut pe);
|
||||
let (report, files) = export(&pe, name);
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "{name}");
|
||||
assert_eq!(report.import_error, None, "{name}");
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}");
|
||||
assert_eq!(report.delay_import_error, Some(error), "{name}");
|
||||
assert_eq!(error.to_string(), message, "{name}");
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "2", "{name}");
|
||||
assert_eq!(
|
||||
json_field(json, "delayed_imports"),
|
||||
listed.to_string(),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(json_field(json, "delay_import_error"), message, "{name}");
|
||||
assert!(
|
||||
files["candidate_static_report.md"].contains(&format!(
|
||||
"- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed."
|
||||
)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_directory_size_bounds_the_table() {
|
||||
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
|
||||
// empty one. A descriptor counts only if the declared size holds all of
|
||||
// it, and the size must reach the empty descriptor.
|
||||
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
|
||||
for (size, listed, error) in [
|
||||
(0, 0, end(0x2200)),
|
||||
(31, 0, end(0x221f)),
|
||||
(32, 2, end(0x2220)),
|
||||
(63, 2, end(0x223f)),
|
||||
(64, 3, end(0x2240)),
|
||||
(95, 3, end(0x225f)),
|
||||
(96, 3, None),
|
||||
(97, 3, None),
|
||||
(0x1000, 3, None),
|
||||
// The directory would run past the end of the address space.
|
||||
(
|
||||
u32::MAX,
|
||||
0,
|
||||
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
|
||||
),
|
||||
] {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
|
||||
assert_eq!(
|
||||
rows(&report.delayed_imports),
|
||||
DELAYED[..listed],
|
||||
"size {size}"
|
||||
);
|
||||
assert_eq!(report.delay_import_error, error, "size {size}");
|
||||
}
|
||||
assert_eq!(
|
||||
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
|
||||
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_delay_table_is_refused() {
|
||||
// Every descriptor RVA maps onto the same 32 bytes, so the table never
|
||||
// reaches its empty entry within the megabyte it declares. The descriptor
|
||||
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
|
||||
// address table at RVA 0x3000.
|
||||
let mut bytes = vec![0u8; 48];
|
||||
put(&mut bytes, 0, 1);
|
||||
put(&mut bytes, 4, 0x1000);
|
||||
put(&mut bytes, 12, 0x3000);
|
||||
put(&mut bytes, 16, 0x2000);
|
||||
bytes[32] = b'a';
|
||||
let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, 0x10_0000, |rva| match rva {
|
||||
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
|
||||
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
|
||||
0x3000..0x3008 => Some(40 + (rva - 0x3000) as usize),
|
||||
0x10_0000.. => Some((rva % 32) as usize),
|
||||
_ => None,
|
||||
});
|
||||
assert!(imports.is_empty());
|
||||
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_never_panics_on_a_truncated_delay_fixture() {
|
||||
for len in 1..=FIXTURE.len() {
|
||||
// The probe may reject the file or report unreadable imports, but it
|
||||
// must not panic.
|
||||
let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default());
|
||||
}
|
||||
}
|
||||
@@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
|
||||
}
|
||||
|
||||
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
|
||||
let (registry, clock, _) = standard_with_state(clock);
|
||||
(registry, clock)
|
||||
}
|
||||
|
||||
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let state = Arc::new(ServicesState::new(clock.clone()));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, state.clone());
|
||||
(registry, clock, state)
|
||||
}
|
||||
|
||||
/// A guest whose image imports every generated service from its own library.
|
||||
struct Guest {
|
||||
engine: DbtEngine,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
state: Arc<ServicesState>,
|
||||
teb: u64,
|
||||
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
|
||||
xmm: [u128; 4],
|
||||
@@ -151,7 +158,7 @@ impl Guest {
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
|
||||
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
@@ -162,6 +169,7 @@ impl Guest {
|
||||
engine,
|
||||
memory,
|
||||
clock,
|
||||
state,
|
||||
teb: 0,
|
||||
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
|
||||
}
|
||||
@@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() {
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
}
|
||||
|
||||
/// The last-error code is documented as kept per thread, and most functions
|
||||
/// set it only when they fail (errhandlingapi.h GetLastError).
|
||||
#[test]
|
||||
fn a_successful_call_keeps_another_threads_error_and_its_own() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
|
||||
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
|
||||
guest.teb = 0x20000;
|
||||
guest.call("SetLastError", &[0xFFFF_FFFF]);
|
||||
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
|
||||
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
|
||||
assert_eq!(
|
||||
guest.last_error(),
|
||||
0xFFFF_FFFF,
|
||||
"success keeps a nonzero error"
|
||||
);
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
guest.call("SetLastError", &[998]);
|
||||
guest.teb = 0x20000;
|
||||
guest.call("CloseHandle", &[0x1234]);
|
||||
|
||||
assert!(guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(!guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(
|
||||
!guest.state.retire_thread_last_error(0x30000),
|
||||
"a thread that never failed holds no value"
|
||||
);
|
||||
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
guest.call("SetLastError", &[5]);
|
||||
assert_eq!(guest.last_error(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_is_set_by_failures_and_by_the_guest() {
|
||||
let mut guest = Guest::new();
|
||||
|
||||
@@ -1298,6 +1298,107 @@ fn division_accepts_exactly_the_representable_quotients() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit scans and the bit test keep the destination and the flags where
|
||||
/// the architecture puts them.
|
||||
///
|
||||
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
|
||||
/// BSF writes the index of the lowest set bit of the source and BSR the index
|
||||
/// of the highest set bit, and both set the zero flag when the source is
|
||||
/// zero, in which case the destination is undefined and keeps its value. BT
|
||||
/// sets the carry flag from the tested bit, leaves the other flags alone and
|
||||
/// masks the bit index to the operand width.
|
||||
///
|
||||
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
|
||||
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
|
||||
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
|
||||
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
|
||||
/// 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn bit_scans_and_bit_tests_follow_the_architecture() {
|
||||
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
|
||||
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
|
||||
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
|
||||
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
|
||||
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
|
||||
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
|
||||
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
|
||||
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
|
||||
|
||||
/// A machine with R9 and RBX set and every other register zero.
|
||||
fn machine(source: u64, destination: u64) -> Machine {
|
||||
let mut gpr = [0; 16];
|
||||
gpr[3] = destination;
|
||||
gpr[9] = source;
|
||||
Machine {
|
||||
gpr,
|
||||
flags: Flags::default(),
|
||||
operand: 0,
|
||||
pushed: 0,
|
||||
top: STACK_TOP,
|
||||
}
|
||||
}
|
||||
|
||||
// The lowest set bit of the source is the index BSF writes.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// The highest set bit of the source is the index BSR writes.
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 63);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// A zero source sets the zero flag and leaves the destination alone.
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
|
||||
// A 32-bit destination holds a 32-bit index and clears the half above it.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
|
||||
assert_eq!(state.gpr[3], 31);
|
||||
|
||||
// A 16-bit destination keeps the bits above it.
|
||||
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
|
||||
|
||||
// BT reports the tested bit in the carry flag and leaves the bit string
|
||||
// alone.
|
||||
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
|
||||
assert!(!state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
|
||||
// The bit index is masked to the operand width, so 64 selects bit 0 of a
|
||||
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
|
||||
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
|
||||
assert!(state.flags.cf);
|
||||
|
||||
// The bit scans and the register form of the bit test are lowered to
|
||||
// ARM64 instead of falling back to the shared semantics.
|
||||
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
code.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.expect("decode");
|
||||
assert!(is_native(&insn), "{code:02X?} is not native");
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
|
||||
engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
|
||||
let machine = Random(17).machine();
|
||||
|
||||
@@ -68,6 +68,8 @@ pub enum Op {
|
||||
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
|
||||
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
|
||||
ScalarCompare(Comparison, Source, Source),
|
||||
/// SOPK operation on SGPR `SDST` (s0-s105) and the raw SIMM16.
|
||||
ScalarImmediate(ScalarImmediate, u8, u16),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
@@ -281,6 +283,23 @@ pub enum ScalarUnary {
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// SOPK operations decoded by the reference interpreter (RDNA 2 ISA guide
|
||||
/// 12.2; SCC per Tables 11, 12, 13 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarImmediate {
|
||||
/// 0 `s_movk_i32`: D = signext(SIMM16).
|
||||
Move,
|
||||
/// 2 `s_cmovk_i32`: if SCC, D = signext(SIMM16); SCC unchanged.
|
||||
ConditionalMove,
|
||||
/// 3-14 `s_cmpk_*`: SCC = (D <relation> K), K = signext(SIMM16) for the
|
||||
/// signed forms 3-8 and SIMM16 zero-extended for the unsigned 9-14.
|
||||
Compare(Comparison),
|
||||
/// 15 `s_addk_i32`: D = D + signext(SIMM16), SCC = signed overflow.
|
||||
Add,
|
||||
/// 16 `s_mulk_i32`: D = low 32 bits of D * signext(SIMM16); SCC unchanged.
|
||||
Multiply,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAlu {
|
||||
@@ -589,6 +608,26 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOPK (guide 13.1.2): ENCODING 0b1011 in bits 28-31, OP 23-27,
|
||||
// SDST 16-22 (s0-s105 only), SIMM16 0-15. The format never takes
|
||||
// a literal dword (guide 12.2), so the word is always 4 bytes.
|
||||
[lo, hi, low, high @ 0xb0..=0xb8, ..]
|
||||
if low & 0x7f <= 105 && matches!((high & 0xf) << 1 | low >> 7, 0 | 2..=16) =>
|
||||
{
|
||||
let kind = match (high & 0xf) << 1 | low >> 7 {
|
||||
0 => ScalarImmediate::Move,
|
||||
2 => ScalarImmediate::ConditionalMove,
|
||||
// EQ, LG, GT, GE, LT, LE as VOPC relation offsets (see SOPC).
|
||||
op @ 3..=14 => ScalarImmediate::Compare(Comparison {
|
||||
offset: [2, 5, 4, 6, 1, 3][usize::from((op - 3) % 6)],
|
||||
signed: op <= 8,
|
||||
}),
|
||||
15 => ScalarImmediate::Add,
|
||||
_ => ScalarImmediate::Multiply,
|
||||
};
|
||||
let simm16 = u16::from_le_bytes([*lo, *hi]);
|
||||
(Op::ScalarImmediate(kind, low & 0x7f, simm16), 4)
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
|
||||
if (*left, *right) != (255, 255)
|
||||
@@ -1158,6 +1197,48 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
// Guide 12.2: SDST is also the second source; SIMM16 is
|
||||
// sign-extended except by the unsigned compares.
|
||||
Op::ScalarImmediate(kind, dst, simm16) => {
|
||||
let extended = i32::from(simm16 as i16);
|
||||
if let ScalarImmediate::Compare(comparison) = kind {
|
||||
let constant = if comparison.signed {
|
||||
extended as u32
|
||||
} else {
|
||||
u32::from(simm16)
|
||||
};
|
||||
let value = read_scalar(Source::Register(dst))?;
|
||||
scc = Some(comparison.holds(value, constant));
|
||||
} else {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = match kind {
|
||||
ScalarImmediate::ConditionalMove
|
||||
if !scc
|
||||
.ok_or_else(|| error(offset, "move on uninitialized SCC"))? =>
|
||||
{
|
||||
None
|
||||
}
|
||||
ScalarImmediate::Add => {
|
||||
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
|
||||
+ i64::from(extended);
|
||||
// SCC = the exact signed sum does not fit in i32.
|
||||
scc = Some(i32::try_from(exact).is_err());
|
||||
Some(exact as u32)
|
||||
}
|
||||
ScalarImmediate::Multiply => {
|
||||
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
|
||||
* i64::from(extended);
|
||||
Some(exact.rem_euclid(1 << 32) as u32)
|
||||
}
|
||||
_ => Some(extended as u32),
|
||||
};
|
||||
if let Some(value) = value {
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
|
||||
@@ -909,6 +909,37 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/scalar-immediate.md.
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => {
|
||||
if dst < 8 {
|
||||
return Err(error("scalar immediate would modify a resource descriptor"));
|
||||
}
|
||||
let scc_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("SOPK SCC input reads uninitialized SCC"))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
let old = if op.reads_dst() {
|
||||
slot.ok_or_else(|| error("SOPK reads an uninitialized SGPR"))?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (value, flag) = op.evaluate(old, simm16, scc_in);
|
||||
if let Some(value) = value {
|
||||
*slot = Some(value);
|
||||
}
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => {
|
||||
scc = Some(op.test(read_scalar(ScalarSource::Register(src))?, simm16));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
if exec == 0 {
|
||||
|
||||
@@ -308,6 +308,20 @@ fn scalar_compare_results_resolve_every_branch() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-immediate.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-immediate.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 120 of 120. Accepted Metal forms · Apple M5: 18 of 120. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">104 / 104</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">120 / 120</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 104</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 120</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="84.81" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="73.50" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
+31
-10
@@ -69,16 +69,37 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point
|
||||
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
|
||||
guest memory and the entry execution outcome.
|
||||
|
||||
`xenora probe --mode static` inventories ordinary PE imports without guest
|
||||
execution. `missing_imports.csv` lists unresolved keys with their import address
|
||||
table relative virtual addresses. The full inventory records whether each key is registered, its implementation
|
||||
status, and the canonical module behind API-set aliases. Runtime-loaded modules
|
||||
and services require separate analysis. The coverage matrix groups unresolved
|
||||
imports by shared startup prerequisites. Static imports do not reveal call
|
||||
order. The JSON report counts import slots, DLL and symbol keys, distinct
|
||||
names with DLL-scoped ordinals, and canonical registered handlers separately.
|
||||
The unresolved total includes explicitly tracked unsupported APIs and other
|
||||
missing handlers. Existing stubs remain visible in the full inventory.
|
||||
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
|
||||
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
|
||||
with their import address table relative virtual addresses. The full inventory,
|
||||
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
|
||||
column and records whether each key is registered, its implementation
|
||||
status, and the canonical module behind API-set aliases. Modules and services
|
||||
loaded by other means at run time require separate analysis. The coverage matrix
|
||||
groups unresolved ordinary imports by shared startup prerequisites. Static
|
||||
imports do not reveal call order. The JSON report counts import slots, DLL and
|
||||
symbol keys, distinct names with DLL-scoped ordinals, and canonical registered
|
||||
handlers separately. The unresolved total includes explicitly tracked
|
||||
unsupported APIs and other missing handlers. Existing stubs remain visible in
|
||||
the full inventory.
|
||||
|
||||
Delay-loaded imports come from the PE32+ delay-load directory, data directory
|
||||
13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or
|
||||
ordinal, and slot in the delay import address table, after the ordinary rows.
|
||||
Binding does not resolve them: the PE format leaves that to a delay-load helper
|
||||
inside the image. The totals above and `missing_imports.csv` therefore cover
|
||||
ordinary imports only, and the JSON report counts delayed slots and DLLs in
|
||||
`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync`
|
||||
leaves delayed rows out of its backlog for the same reason.
|
||||
|
||||
The probe reads only descriptors that lie wholly inside the directory's
|
||||
declared size, and expects that size to hold the empty descriptor that ends the
|
||||
table. It reads descriptors whose `RvaBased` attribute is set, and requires each
|
||||
one's DLL name, import address table and import name table to be present and to
|
||||
start in section data. A table that breaks one of these rules, sets a reserved
|
||||
attribute bit, is truncated, or uses the earlier virtual-address descriptor form
|
||||
is reported in `delay_import_error` and in the Markdown report, together with
|
||||
the entries read before it.
|
||||
|
||||
The synthetic process registry supports the current-process pseudo handle and
|
||||
its process ID. The priority boost setter and getter record and query a guest
|
||||
|
||||
@@ -33,6 +33,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
|
||||
| `s_movk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged | `B0088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmovk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged | `B1088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_eq_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed) | `B1888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lg_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed) | `B2088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_gt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed) | `B2888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_ge_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed) | `B3088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed) | `B3888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_le_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed) | `B4088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_eq_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned) | `B4888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lg_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned) | `B5088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_gt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned) | `B5888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_ge_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned) | `B6088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned) | `B6888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_le_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned) | `B7088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_addk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow | `B7888000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mulk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged | `B8088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# SOPK scalar immediate forms
|
||||
|
||||
Xenora decodes and translates sixteen gfx1030 SOPK integer forms through the
|
||||
semantic registry (`crates/isa/semantics/rdna2/sopk.toml`, operand rules
|
||||
`sopk_sgpr` and `sopk_compare`). Each is one 32-bit word: SIMM16 in bits 0-15,
|
||||
SDST in bits 16-22, OP in bits 23-27, ENCODING `0b1011` in bits 28-31
|
||||
(guide 13.1.2). The word never takes a literal dword (guide 12.2), so a SIMM16
|
||||
whose low byte is `0xff` is an immediate, not a literal marker.
|
||||
|
||||
| Form | Opcode | Operation | SCC |
|
||||
| --- | ---: | --- | --- |
|
||||
| `s_movk_i32` | 0 | D = signext(SIMM16) | unchanged |
|
||||
| `s_cmovk_i32` | 2 | if SCC, D = signext(SIMM16); otherwise D keeps its value | read, unchanged |
|
||||
| `s_cmpk_{eq,lg,gt,ge,lt,le}_i32` | 3-8 | SCC = (D relation signext(SIMM16)), signed | the relation |
|
||||
| `s_cmpk_{eq,lg,gt,ge,lt,le}_u32` | 9-14 | SCC = (D relation SIMM16), SIMM16 zero-extended, unsigned | the relation |
|
||||
| `s_addk_i32` | 15 | D = D + signext(SIMM16) | signed overflow of the sum |
|
||||
| `s_mulk_i32` | 16 | D = low 32 bits of D * signext(SIMM16) | unchanged |
|
||||
|
||||
## Operands
|
||||
|
||||
SDST is `s0`-`s105`. `s0`-`s7` hold the resource descriptors of the fixture
|
||||
ABI, so they may be read (the compares) but are never written: the translator
|
||||
refuses a write there even when `s_cmovk_i32` would not take it. SDST 106-127
|
||||
(`vcc`, `ttmp`, `m0`, `null`, `exec`) is rejected at decode. The other SOPK
|
||||
opcodes stay unsupported, except the fixed store fence `s_waitcnt_vscnt null,
|
||||
0` (`0xbbfd0000`), which keeps its own decoding.
|
||||
|
||||
## How it runs
|
||||
|
||||
SGPR values are known while translating, so a SOPK instruction folds into the
|
||||
translator's scalar state exactly like the SOP2 and SOPC forms: no IR node is
|
||||
emitted. `s_cmpk_*` sets SCC; `s_addk_i32` writes D and SCC; `s_mulk_i32` writes
|
||||
D; `s_movk_i32` and a taken `s_cmovk_i32` write D. `s_addk_i32`, `s_mulk_i32`
|
||||
and the compares read D, so an SDST nothing has written is rejected.
|
||||
`s_cmovk_i32` reads SCC and is rejected when SCC is uninitialized; with SCC clear
|
||||
it neither reads nor writes D, so an unwritten SDST stays unwritten.
|
||||
|
||||
## Verification
|
||||
|
||||
`tests/validation/tests/sopk.rs` derives its expected values from the guide
|
||||
alone and runs 4,184 cases on both CPU interpreters and, through the translator,
|
||||
on native Metal (that test is `#[ignore]`d and runs under `scripts/test-gpu.sh`),
|
||||
plus 398 rejected programs. `fixtures/rdna2/scalar-immediate.s` (LLVM-assembled,
|
||||
expected input ^ 0x40008275) uses all sixteen forms, recording each compare's SCC
|
||||
through an `s_cbranch_scc0`; its IR and MSL are pinned under
|
||||
`fixtures/golden/scalar-immediate.*`. Agreement with a spec-derived reference is
|
||||
not agreement with hardware.
|
||||
@@ -27,7 +27,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
@@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
|
||||
| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 |
|
||||
| **Total** | 1465 | 120 | 107 | 124 | 120 | 120 | 18 | 18 | 65 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -47,6 +47,8 @@ The table counts distinct variant names per family across registry operand rules
|
||||
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
|
||||
@@ -13,7 +13,7 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. |
|
||||
| `crates/isa/semantics/rdna2/<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/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sopk.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
|
||||
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
|
||||
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
|
||||
@@ -109,7 +109,7 @@ error.
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` and `cmov` (SOPK only), `compare` and the SOP1 unaries |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
@@ -118,7 +118,7 @@ error.
|
||||
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
|
||||
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
@@ -150,6 +150,8 @@ fixes the `scc` value:
|
||||
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
|
||||
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
|
||||
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
|
||||
| `mov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | no |
|
||||
| `cmov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | required |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
|
||||
@@ -187,6 +189,19 @@ sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
|
||||
SOPK forms (guide 12.2) use two rules. `sopk_sgpr` (kind `immediate`, enum
|
||||
`ScalarImmediateOp`) has SDST `s0`-`s105` as the destination and SIMM16 as the one
|
||||
source; it takes `mov`, `cmov` (reads SCC, so `carry_in = "scc"`), `add` (`D = D +
|
||||
signext(SIMM16)`, `scc = "signed_overflow"`) and `mul` (`scc = "unchanged"`), all
|
||||
`signed`, and the `add` and `mul` forms read the old SDST. `sopk_compare` (kind
|
||||
`immediate_compare`, enum `ScalarImmediateCompareOp`) takes `compare` with SDST as
|
||||
the left operand and the SIMM16 as the right one: sign-extended for `signed`,
|
||||
zero-extended for `unsigned`. A SOPK compare's opcode must be 3 (`signed`) or 9
|
||||
(`unsigned`) plus the relation's index in `eq, lg, gt, ge, lt, le` (guide 13.1.2).
|
||||
The XML must give SIMM16 as 16-bit `FMT_NUM_I16` (`FMT_NUM_U16` for `unsigned`).
|
||||
The word never takes a literal dword. The details are in
|
||||
[scalar-immediate.md](scalar-immediate.md).
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
|
||||
@@ -279,6 +279,198 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_movk_i32"
|
||||
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged"
|
||||
representation = "`B0088000`"
|
||||
lowering = "resolved scalar state"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmovk_i32"
|
||||
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged"
|
||||
representation = "`B1088000`"
|
||||
lowering = "resolved scalar state"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_eq_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed)"
|
||||
representation = "`B1888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_lg_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed)"
|
||||
representation = "`B2088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_gt_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed)"
|
||||
representation = "`B2888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_ge_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed)"
|
||||
representation = "`B3088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_lt_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed)"
|
||||
representation = "`B3888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_le_i32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed)"
|
||||
representation = "`B4088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_eq_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned)"
|
||||
representation = "`B4888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_lg_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned)"
|
||||
representation = "`B5088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_gt_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned)"
|
||||
representation = "`B5888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_ge_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned)"
|
||||
representation = "`B6088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_lt_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned)"
|
||||
representation = "`B6888000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmpk_le_u32"
|
||||
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned)"
|
||||
representation = "`B7088000`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_addk_i32"
|
||||
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow"
|
||||
representation = "`B7888000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mulk_i32"
|
||||
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged"
|
||||
representation = "`B8088000`"
|
||||
lowering = "resolved scalar state"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0018: branch.uniform 0x0020 taken=false
|
||||
0024: branch.uniform 0x002c taken=true
|
||||
0030: branch.uniform 0x0038 taken=false
|
||||
003c: branch.uniform 0x0044 taken=true
|
||||
0048: branch.uniform 0x0050 taken=false
|
||||
0054: branch.uniform 0x005c taken=false
|
||||
0060: branch.uniform 0x0068 taken=false
|
||||
006c: branch.uniform 0x0078 taken=true
|
||||
007c: branch.uniform 0x0088 taken=false
|
||||
008c: branch.uniform 0x0098 taken=true
|
||||
009c: branch.uniform 0x00a8 taken=false
|
||||
00ac: branch.uniform 0x00b8 taken=false
|
||||
00c8: branch.uniform 0x00d4 taken=false
|
||||
00d8: branch.uniform 0x00e4 taken=false
|
||||
00e8: branch.uniform 0x00f4 taken=false
|
||||
00f8: branch.uniform 0x0104 taken=true
|
||||
0118: t17 = const.u32 0x00007d75
|
||||
011c: t18 = const.u32 0xc000ffff
|
||||
0120: t19 = xor.b32 t18, t17
|
||||
0124: t20 = const.u32 0x7fffffff
|
||||
0128: t21 = xor.b32 t20, t19
|
||||
012c: t22 = const.u32 0xffffff00
|
||||
0130: t23 = xor.b32 t22, t21
|
||||
0134: t24 = xor.b32 t0, t23
|
||||
0138: store.u32 output[index], t24
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t17 = 0x00007d75u;
|
||||
uint t18 = 0xc000ffffu;
|
||||
uint t19 = t18 ^ t17;
|
||||
uint t20 = 0x7fffffffu;
|
||||
uint t21 = t20 ^ t19;
|
||||
uint t22 = 0xffffff00u;
|
||||
uint t23 = t22 ^ t21;
|
||||
uint t24 = t0 ^ t23;
|
||||
output[index] = t24;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Generate the original PE32+ delay-load import fixture without an x86 toolchain.
|
||||
|
||||
The image has one ordinary import DLL and two delay-loaded DLLs, each with a
|
||||
named import and one of them with an import by ordinal. It follows Microsoft's
|
||||
PE format specification ("The .idata Section" and "Delay-Load Import Tables
|
||||
(Image Only)"). It is for static inspection: the entry point returns at once and
|
||||
nothing calls an import.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from struct import pack_into
|
||||
|
||||
BASE = 0x140000000
|
||||
TEXT, RDATA, DATA = 0x1000, 0x2000, 0x3000
|
||||
# File offset of each section's data, after the 0x400-byte headers.
|
||||
RAW = {TEXT: 0x400, RDATA: 0x600, DATA: 0xA00}
|
||||
ORDINAL = 1 << 63
|
||||
|
||||
# Ordinary imports, in .rdata.
|
||||
IMPORT_DIRECTORY = RDATA
|
||||
LOOKUP, IAT = RDATA + 0x30, RDATA + 0x50
|
||||
ORDINARY_DLL, ORDINARY_NAME = RDATA + 0x70, RDATA + 0x90
|
||||
|
||||
# Delay-load names and name tables, in .rdata before their directory so that a
|
||||
# file cut inside the directory still holds everything the first entry names.
|
||||
NAMES_A, NAMES_B = RDATA + 0x100, RDATA + 0x118
|
||||
DELAY_DLL_A, DELAY_DLL_B = RDATA + 0x130, RDATA + 0x150
|
||||
DELAY_NAME_A, DELAY_NAME_B = RDATA + 0x170, RDATA + 0x190
|
||||
DELAY_DIRECTORY = RDATA + 0x200
|
||||
|
||||
# Delay-load address tables and module handles, in writable .data.
|
||||
DELAY_IAT_A, DELAY_IAT_B = DATA, DATA + 0x20
|
||||
HANDLE_A, HANDLE_B = DATA + 0x40, DATA + 0x48
|
||||
|
||||
# Each delay-load address slot starts out pointing at its own stub.
|
||||
STUBS = (TEXT + 0x10, TEXT + 0x18, TEXT + 0x20)
|
||||
|
||||
|
||||
def fixture():
|
||||
data = bytearray(0xC00)
|
||||
|
||||
def offset(rva):
|
||||
section = rva & ~0xFFF
|
||||
return RAW[section] + rva - section
|
||||
|
||||
def put(rva, layout, *values):
|
||||
pack_into(layout, data, offset(rva), *values)
|
||||
|
||||
def text(rva, value):
|
||||
data[offset(rva):offset(rva) + len(value) + 1] = value + b"\0"
|
||||
|
||||
data[:2] = b"MZ"
|
||||
pack_into("<I", data, 0x3C, 0x80)
|
||||
data[0x80:0x84] = b"PE\0\0"
|
||||
# AMD64, three sections, 240-byte optional header; relocations stripped,
|
||||
# executable, large-address-aware.
|
||||
pack_into("<HHIIIHH", data, 0x84, 0x8664, 3, 0, 0, 0, 240, 0x23)
|
||||
opt = 0x98
|
||||
pack_into("<H", data, opt, 0x20B)
|
||||
pack_into("<III", data, opt + 4, 0x200, 0x600, 0)
|
||||
pack_into("<IIQII", data, opt + 16, TEXT, TEXT, BASE, 0x1000, 0x200)
|
||||
pack_into("<HHHHHH", data, opt + 40, 6, 0, 0, 0, 6, 0)
|
||||
pack_into("<II", data, opt + 56, 0x4000, 0x400)
|
||||
# Console subsystem; NX compatible at a fixed base.
|
||||
pack_into("<HH", data, opt + 68, 3, 0x100)
|
||||
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
|
||||
# Import table, import address table and delay import descriptor.
|
||||
for index, rva, size in (
|
||||
(1, IMPORT_DIRECTORY, 40),
|
||||
(12, IAT, 24),
|
||||
(13, DELAY_DIRECTORY, 96),
|
||||
):
|
||||
pack_into("<II", data, opt + 112 + index * 8, rva, size)
|
||||
|
||||
sections = (
|
||||
(b".text", TEXT, 0x200, 0x60000020),
|
||||
(b".rdata", RDATA, 0x400, 0x40000040),
|
||||
(b".data", DATA, 0x200, 0xC0000040),
|
||||
)
|
||||
for index, (name, rva, size, characteristics) in enumerate(sections):
|
||||
pack_into(
|
||||
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, size, rva,
|
||||
size, offset(rva), 0, 0, 0, 0, characteristics,
|
||||
)
|
||||
|
||||
# Entry returns. The stubs are INT3 because the fixture is never run.
|
||||
data[offset(TEXT)] = 0xC3
|
||||
for stub in STUBS:
|
||||
data[offset(stub)] = 0xCC
|
||||
|
||||
# One ordinary DLL: a named import and ordinal 3.
|
||||
put(IMPORT_DIRECTORY, "<IIIII", LOOKUP, 0, 0, ORDINARY_DLL, IAT)
|
||||
for table in (LOOKUP, IAT):
|
||||
put(table, "<QQQ", ORDINARY_NAME, ORDINAL | 3, 0)
|
||||
text(ORDINARY_DLL, b"fixture-ordinary.dll")
|
||||
text(ORDINARY_NAME + 2, b"OrdinaryByName")
|
||||
|
||||
# Two delay-loaded DLLs. Attributes bit 0 marks the fields as RVAs.
|
||||
put(DELAY_DIRECTORY, "<IIIIIIII",
|
||||
1, DELAY_DLL_A, HANDLE_A, DELAY_IAT_A, NAMES_A, 0, 0, 0)
|
||||
put(DELAY_DIRECTORY + 32, "<IIIIIIII",
|
||||
1, DELAY_DLL_B, HANDLE_B, DELAY_IAT_B, NAMES_B, 0, 0, 0)
|
||||
put(NAMES_A, "<QQQ", DELAY_NAME_A, ORDINAL | 7, 0)
|
||||
put(NAMES_B, "<QQ", DELAY_NAME_B, 0)
|
||||
text(DELAY_DLL_A, b"fixture-delay-a.dll")
|
||||
text(DELAY_DLL_B, b"fixture-delay-b.dll")
|
||||
text(DELAY_NAME_A + 2, b"DelayedAlpha")
|
||||
text(DELAY_NAME_B + 2, b"DelayedBeta")
|
||||
put(DELAY_IAT_A, "<QQQ", BASE + STUBS[0], BASE + STUBS[1], 0)
|
||||
put(DELAY_IAT_B, "<QQ", BASE + STUBS[2], 0)
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).with_suffix(".exe")
|
||||
if args.check:
|
||||
if path.read_bytes() != fixture():
|
||||
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(fixture())
|
||||
Binary file not shown.
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOPK vectors: the sixteen 16-bit-immediate integer forms. s8 =
|
||||
// 0xffff8000 (s_movk_i32 sign-extends 0x8000), so the twelve s_cmpk compares
|
||||
// split signed (sign-extended SIMM16) from unsigned (zero-extended); an
|
||||
// s_cbranch_scc0 skips setting that compare's bit in s20. s_addk_i32 sets SCC
|
||||
// on signed overflow, s_mulk_i32 leaves SCC alone, and s_cmovk_i32 moves only
|
||||
// while SCC is set. Bits worked out by hand below.
|
||||
// Expected: input ^ 0x40008275 (s20 ^ s9 ^ s10 ^ s11).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_movk_i32 s8, 0x8000 // s8 = 0xffff8000
|
||||
s_mov_b32 s20, 0
|
||||
s_cmpk_eq_i32 s8, 0x8000 // SCC = 1 (-32768 == -32768)
|
||||
s_cbranch_scc0 .Lskip0
|
||||
s_or_b32 s20, s20, 0x1
|
||||
.Lskip0:
|
||||
s_cmpk_eq_u32 s8, 0x8000 // 0xffff8000 == 0x00008000: SCC = 0
|
||||
s_cbranch_scc0 .Lskip1
|
||||
s_or_b32 s20, s20, 0x2
|
||||
.Lskip1:
|
||||
s_cmpk_lg_i32 s8, 0x7fff // -32768 != 32767: SCC = 1
|
||||
s_cbranch_scc0 .Lskip2
|
||||
s_or_b32 s20, s20, 0x4
|
||||
.Lskip2:
|
||||
s_cmpk_gt_i32 s8, 0xffff // -32768 > -1 (0xffff sign-extends): SCC = 0
|
||||
s_cbranch_scc0 .Lskip3
|
||||
s_or_b32 s20, s20, 0x8
|
||||
.Lskip3:
|
||||
s_cmpk_gt_u32 s8, 0xffff // 0xffff8000 > 0x0000ffff (zero-extends): SCC = 1
|
||||
s_cbranch_scc0 .Lskip4
|
||||
s_or_b32 s20, s20, 0x10
|
||||
.Lskip4:
|
||||
s_cmpk_ge_i32 s8, 0x8000 // -32768 >= -32768: SCC = 1
|
||||
s_cbranch_scc0 .Lskip5
|
||||
s_or_b32 s20, s20, 0x20
|
||||
.Lskip5:
|
||||
s_cmpk_lt_i32 s8, 0x1 // -32768 < 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip6
|
||||
s_or_b32 s20, s20, 0x40
|
||||
.Lskip6:
|
||||
s_cmpk_lt_u32 s8, 0x1 // 0xffff8000 < 1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip7
|
||||
s_or_b32 s20, s20, 0x80
|
||||
.Lskip7:
|
||||
s_cmpk_le_i32 s8, 0x8000 // -32768 <= -32768: SCC = 1
|
||||
s_cbranch_scc0 .Lskip8
|
||||
s_or_b32 s20, s20, 0x100
|
||||
.Lskip8:
|
||||
s_cmpk_le_u32 s8, 0x8000 // 0xffff8000 <= 0x8000: SCC = 0
|
||||
s_cbranch_scc0 .Lskip9
|
||||
s_or_b32 s20, s20, 0x200
|
||||
.Lskip9:
|
||||
s_cmpk_ge_u32 s8, 0x8000 // 0xffff8000 >= 0x8000: SCC = 1
|
||||
s_cbranch_scc0 .Lskip10
|
||||
s_or_b32 s20, s20, 0x400
|
||||
.Lskip10:
|
||||
s_cmpk_lg_u32 s8, 0x8000 // 0xffff8000 != 0x8000: SCC = 1
|
||||
s_cbranch_scc0 .Lskip11
|
||||
s_or_b32 s20, s20, 0x800
|
||||
.Lskip11:
|
||||
s_movk_i32 s9, 0x7fff // s9 = 32767
|
||||
s_mov_b32 s10, 0x7fffffff
|
||||
s_addk_i32 s10, 1 // 0x7fffffff + 1 overflows: s10 = 0x80000000, SCC = 1
|
||||
s_cbranch_scc0 .Lskip12
|
||||
s_or_b32 s20, s20, 0x1000
|
||||
.Lskip12:
|
||||
s_mulk_i32 s9, 0x8000 // 32767 * -32768: s9 = 0xc0008000, SCC stays 1
|
||||
s_cbranch_scc0 .Lskip13
|
||||
s_or_b32 s20, s20, 0x2000
|
||||
.Lskip13:
|
||||
s_addk_i32 s10, 0xffff // 0x80000000 + -1 overflows: s10 = 0x7fffffff, SCC = 1
|
||||
s_cbranch_scc0 .Lskip14
|
||||
s_or_b32 s20, s20, 0x4000
|
||||
.Lskip14:
|
||||
s_addk_i32 s9, 0x7fff // 0xc0008000 + 32767 = 0xc000ffff, no overflow: SCC = 0
|
||||
s_cbranch_scc0 .Lskip15
|
||||
s_or_b32 s20, s20, 0x8000
|
||||
.Lskip15:
|
||||
s_mov_b32 s11, 0x1111
|
||||
s_cmovk_i32 s11, 0xff00 // SCC = 0: s11 stays 0x1111
|
||||
s_cmpk_eq_u32 s11, 0x1111 // SCC = 1
|
||||
s_cmovk_i32 s11, 0xff00 // SCC = 1: s11 = 0xffffff00
|
||||
v_mov_b32_e32 v2, s20 // s20 = 0x00007d75
|
||||
v_mov_b32_e32 v3, s9 // s9 = 0xc000ffff
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_mov_b32_e32 v3, s10 // s10 = 0x7fffffff
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_mov_b32_e32 v3, s11 // s11 = 0xffffff00
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_xor_b32_e32 v2, v1, v2
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer vector-compare-ft; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
+4
-2
@@ -53,6 +53,8 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
|
||||
# and VOPC compares.
|
||||
cargo test --locked -p xenora-semantic-review --no-run
|
||||
# Oracles whose translator side has not landed are skipped by name until it does.
|
||||
# Oracles whose translator side has not landed are skipped by name until it does
|
||||
# (#215: the PR that translates the forms removes its skip).
|
||||
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
|
||||
--skip vopc_wide_match_the_guide_on_native_metal
|
||||
--skip vopc_wide_match_the_guide_on_native_metal \
|
||||
--skip vop1_integer_forms_match_the_guide_on_native_metal
|
||||
@@ -1429,5 +1429,71 @@ class CommandLine(unittest.TestCase):
|
||||
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
|
||||
|
||||
|
||||
class SopkForms(unittest.TestCase):
|
||||
"""SOPK immediate forms, checked against the real registry and XML snapshot."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.snapshot = gen.load_snapshot()
|
||||
|
||||
def registry(self):
|
||||
return gen.load_registry()
|
||||
|
||||
def rejects(self, reg, fragment):
|
||||
errors = gen.validate(reg, self.snapshot)
|
||||
self.assertTrue(
|
||||
any(fragment in error for error in errors),
|
||||
f"expected an error containing {fragment!r}, got {errors}",
|
||||
)
|
||||
|
||||
def test_the_registry_declares_the_sixteen_sopk_forms(self):
|
||||
names = {item["name"] for item in self.registry()["form"] if item["family"] == "SOPK"}
|
||||
self.assertEqual(len(names), 16)
|
||||
self.assertTrue({"S_MOVK_I32", "S_CMOVK_I32", "S_ADDK_I32", "S_MULK_I32"} <= names)
|
||||
|
||||
def test_rejects_a_compare_with_the_wrong_sopk_opcode(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_CMPK_GT_U32")["opcode"] = 10
|
||||
self.rejects(reg, "S_CMPK_GT_U32: relation gt/unsigned has SOPK opcode 11")
|
||||
|
||||
def test_rejects_an_unsigned_compare_declared_signed(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_CMPK_GT_U32")["signedness"] = "signed"
|
||||
self.rejects(reg, "SIMM16 is 16 bits FMT_NUM_U16")
|
||||
|
||||
def test_rejects_addk_without_the_overflow_flag(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_ADDK_I32")["scc"] = "unchanged"
|
||||
self.rejects(reg, "S_ADDK_I32: scc unchanged contradicts add/signed")
|
||||
|
||||
def test_rejects_cmovk_that_does_not_read_scc(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_CMOVK_I32")["carry_in"] = "none"
|
||||
self.rejects(reg, "S_CMOVK_I32: carry_in none contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_a_conditional_move_that_does_not_read_scc(self):
|
||||
# S_MOVK_I32 has no SCC input, so as a cmov it would see SCC = 0 and
|
||||
# never write D.
|
||||
reg = self.registry()
|
||||
form(reg, "S_MOVK_I32")["operation"] = "cmov"
|
||||
self.rejects(reg, "S_MOVK_I32: operation cmov reads SCC (requires carry_in scc)")
|
||||
|
||||
def test_rejects_a_two_source_operation_on_a_sopk_rule(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_MULK_I32")["operation"] = "and"
|
||||
form(reg, "S_MULK_I32")["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_MULK_I32: no primitive implements and/bitwise")
|
||||
|
||||
def test_rejects_a_move_on_the_compare_rule(self):
|
||||
reg = self.registry()
|
||||
form(reg, "S_MOVK_I32")["operands"] = "sopk_compare"
|
||||
self.rejects(reg, "S_MOVK_I32: operation mov does not fit rule sopk_compare")
|
||||
|
||||
def test_generated_compare_extends_signed_and_unsigned_immediates_differently(self):
|
||||
text = gen.render(self.registry(), self.snapshot)
|
||||
self.assertIn("Self::CmpkGtI32 => primitive::gt_i32(dst, primitive::sext_simm16(simm16)),", text)
|
||||
self.assertIn("Self::CmpkGtU32 => primitive::gt_u32(dst, simm16 as u32),", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -69,6 +69,8 @@ enum Insn {
|
||||
SAlu(u32, u8, Src, Src),
|
||||
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
|
||||
SCmp(u32, Src, Src),
|
||||
/// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16.
|
||||
SImm(u32, u8, u16),
|
||||
BranchScc0(usize),
|
||||
BranchMaskZero {
|
||||
target: usize,
|
||||
@@ -263,6 +265,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
None
|
||||
})
|
||||
}),
|
||||
Insn::SImm(opcode, dst, simm16) => {
|
||||
scalar_immediate(&mut sgpr, &mut scc, (opcode, dst, simm16), offset).map(|()| None)
|
||||
}
|
||||
Insn::SAlu(opcode, dst, a, b) => {
|
||||
scalar_alu(&mut sgpr, &mut scc, (opcode, dst, a, b), offset).map(|()| None)
|
||||
}
|
||||
@@ -320,6 +325,65 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string()))
|
||||
}
|
||||
|
||||
/// One SOPK instruction, per the operation text of guide 12.2. SDST names
|
||||
/// the destination and, for every form but the two moves, the first source.
|
||||
fn scalar_immediate(
|
||||
sgpr: &mut [Option<u32>; 128],
|
||||
scc: &mut Option<bool>,
|
||||
(opcode, dst, simm16): (u32, u8, u16),
|
||||
offset: usize,
|
||||
) -> Result<(), String> {
|
||||
let d = |sgpr: &[Option<u32>; 128]| {
|
||||
sgpr[dst as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{dst}"))
|
||||
};
|
||||
// signext(SIMM16[15:0]): copy bit 15 into bits 16-31.
|
||||
let sext = u32::from(simm16) | if simm16 >> 15 == 1 { 0xffff_0000 } else { 0 };
|
||||
// The unsigned compares use SIMM16[15:0] as is, zero-extended.
|
||||
let zext = u32::from(simm16);
|
||||
if (3..=14).contains(&opcode) {
|
||||
let s0 = d(sgpr)?;
|
||||
let (a, k) = (s0 as i32, sext as i32);
|
||||
*scc = Some(match opcode {
|
||||
3 => a == k,
|
||||
4 => a != k,
|
||||
5 => a > k,
|
||||
6 => a >= k,
|
||||
7 => a < k,
|
||||
8 => a <= k,
|
||||
9 => s0 == zext,
|
||||
10 => s0 != zext,
|
||||
11 => s0 > zext,
|
||||
12 => s0 >= zext,
|
||||
13 => s0 < zext,
|
||||
_ => s0 <= zext,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
if dst < 8 {
|
||||
return Err(format!("{offset:#x}: write to a resource SGPR"));
|
||||
}
|
||||
let value = match opcode {
|
||||
0 => sext,
|
||||
2 => {
|
||||
if !scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))? {
|
||||
return Ok(());
|
||||
}
|
||||
sext
|
||||
}
|
||||
15 => {
|
||||
let tmp = d(sgpr)?;
|
||||
let sum = tmp.wrapping_add(sext);
|
||||
// tmp[31] == SIMM16[15] && tmp[31] != D[31].
|
||||
*scc = Some(tmp >> 31 == u32::from(simm16 >> 15) && tmp >> 31 != sum >> 31);
|
||||
sum
|
||||
}
|
||||
// 16: the low 32 bits of the product, the same for both signednesses.
|
||||
_ => d(sgpr)?.wrapping_mul(sext),
|
||||
};
|
||||
sgpr[dst as usize] = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scalar_alu(
|
||||
sgpr: &mut [Option<u32>; 128],
|
||||
scc: &mut Option<bool>,
|
||||
@@ -1220,6 +1284,15 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
let (src, len) = scalar_source(code, offset, first as u8)?;
|
||||
return Ok((Insn::SMov(dst, src), len));
|
||||
}
|
||||
// SOPK: ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15
|
||||
// (guide 13.1.2). Guide 12.2: no literal dword may follow.
|
||||
if first >> 28 == 0b1011 && matches!((first >> 23) & 0x1f, 0 | 2..=16) {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOPK register"));
|
||||
}
|
||||
return Ok((Insn::SImm((first >> 23) & 0x1f, dst, first as u16), 4));
|
||||
}
|
||||
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
|
||||
if first >> 30 == 0b10
|
||||
&& matches!(
|
||||
|
||||
@@ -774,6 +774,10 @@ mod review {
|
||||
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
|
||||
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
|
||||
const SCALAR_IMMEDIATE_FIXTURE: &[u8] =
|
||||
include_bytes!("../../fixtures/rdna2/scalar-immediate.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-immediate.s from the guide's 12.2 pseudocode.
|
||||
const SCALAR_IMMEDIATE_KEY: u32 = 0x4000_8275;
|
||||
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
|
||||
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
|
||||
@@ -964,6 +968,18 @@ mod review {
|
||||
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_fixture_records_every_registry_sopk_form() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_IMMEDIATE_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input
|
||||
.iter()
|
||||
.map(|word| word ^ SCALAR_IMMEDIATE_KEY)
|
||||
.collect();
|
||||
verify(SCALAR_IMMEDIATE_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_IMMEDIATE_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_cmpk_le_u32 s8, 0x8000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_fixture_chains_registry_unary_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the sixteen SOPK integer forms of #215:
|
||||
//! `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`,
|
||||
//! `s_addk_i32` and `s_mulk_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.2 "SOPK Instructions" for
|
||||
//! each form's operation (and that no literal dword may follow), section
|
||||
//! 13.1.2 for the SOPK word and its SDST range, and Tables 11-14 of sections
|
||||
//! 5.4-5.7 for which forms set SCC. Nothing here comes from the ISA crate, the
|
||||
//! semantic registry, the decoder or the shader compiler. Every case runs on
|
||||
//! the reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
//!
|
||||
//! Supported subset: SDST s0-s105 (s0-s7 are readable but, as resource
|
||||
//! SGPRs, never written). Refused: SDST 106-127 (VCC, TTMP, M0, NULL, EXEC)
|
||||
//! and every other SOPK opcode (`s_version`, `s_getreg`, `s_setreg*`,
|
||||
//! `s_call_b64`, `s_waitcnt_*` other than the fixed `s_waitcnt_vscnt null, 0`
|
||||
//! store fence, and the subvector loops).
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, compile};
|
||||
|
||||
/// The sixteen forms with their ENC_SOPK opcodes (guide 13.1.2, Table 66).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Form {
|
||||
MovK = 0,
|
||||
CmovK = 2,
|
||||
CmpEqI32 = 3,
|
||||
CmpLgI32 = 4,
|
||||
CmpGtI32 = 5,
|
||||
CmpGeI32 = 6,
|
||||
CmpLtI32 = 7,
|
||||
CmpLeI32 = 8,
|
||||
CmpEqU32 = 9,
|
||||
CmpLgU32 = 10,
|
||||
CmpGtU32 = 11,
|
||||
CmpGeU32 = 12,
|
||||
CmpLtU32 = 13,
|
||||
CmpLeU32 = 14,
|
||||
AddK = 15,
|
||||
MulK = 16,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 16] = [
|
||||
(Form::MovK, "s_movk_i32"),
|
||||
(Form::CmovK, "s_cmovk_i32"),
|
||||
(Form::CmpEqI32, "s_cmpk_eq_i32"),
|
||||
(Form::CmpLgI32, "s_cmpk_lg_i32"),
|
||||
(Form::CmpGtI32, "s_cmpk_gt_i32"),
|
||||
(Form::CmpGeI32, "s_cmpk_ge_i32"),
|
||||
(Form::CmpLtI32, "s_cmpk_lt_i32"),
|
||||
(Form::CmpLeI32, "s_cmpk_le_i32"),
|
||||
(Form::CmpEqU32, "s_cmpk_eq_u32"),
|
||||
(Form::CmpLgU32, "s_cmpk_lg_u32"),
|
||||
(Form::CmpGtU32, "s_cmpk_gt_u32"),
|
||||
(Form::CmpGeU32, "s_cmpk_ge_u32"),
|
||||
(Form::CmpLtU32, "s_cmpk_lt_u32"),
|
||||
(Form::CmpLeU32, "s_cmpk_le_u32"),
|
||||
(Form::AddK, "s_addk_i32"),
|
||||
(Form::MulK, "s_mulk_i32"),
|
||||
];
|
||||
|
||||
fn is_compare(form: Form) -> bool {
|
||||
(Form::CmpEqI32 as u32..=Form::CmpLeU32 as u32).contains(&(form as u32))
|
||||
}
|
||||
|
||||
/// signext(SIMM16[15:0]) as a 32-bit word.
|
||||
fn sext(simm16: u16) -> u32 {
|
||||
i32::from(simm16 as i16) as u32
|
||||
}
|
||||
|
||||
/// The guide's (D after, SCC after) for `form` with D = `d` before, SCC =
|
||||
/// `scc` before and the immediate `k`.
|
||||
fn expect(form: Form, d: u32, scc: bool, k: u16) -> (u32, bool) {
|
||||
let (di, ki, ku) = (d as i32, sext(k) as i32, u32::from(k));
|
||||
match form {
|
||||
// 0 S_MOVK_I32: D.i32 = signext(SIMM16[15:0]); Table 14: no SCC.
|
||||
Form::MovK => (sext(k), scc),
|
||||
// 2 S_CMOVK_I32: if (SCC) D.i32 = signext(SIMM16[15:0]); Table 12: no SCC.
|
||||
Form::CmovK => (if scc { sext(k) } else { d }, scc),
|
||||
// 3-8: SCC = (S0.i32 <cond> signext(SIMM16[15:0])), S0 = D.
|
||||
Form::CmpEqI32 => (d, di == ki),
|
||||
Form::CmpLgI32 => (d, di != ki),
|
||||
Form::CmpGtI32 => (d, di > ki),
|
||||
Form::CmpGeI32 => (d, di >= ki),
|
||||
Form::CmpLtI32 => (d, di < ki),
|
||||
Form::CmpLeI32 => (d, di <= ki),
|
||||
// 9-14: SCC = (S0.u32 <cond> SIMM16[15:0]), zero-extended.
|
||||
Form::CmpEqU32 => (d, d == ku),
|
||||
Form::CmpLgU32 => (d, d != ku),
|
||||
Form::CmpGtU32 => (d, d > ku),
|
||||
Form::CmpGeU32 => (d, d >= ku),
|
||||
Form::CmpLtU32 => (d, d < ku),
|
||||
Form::CmpLeU32 => (d, d <= ku),
|
||||
// 15 S_ADDK_I32: D.i32 = D.i32 + signext(SIMM16), SCC = signed overflow.
|
||||
Form::AddK => match di.checked_add(ki) {
|
||||
Some(sum) => (sum as u32, false),
|
||||
None => (di.wrapping_add(ki) as u32, true),
|
||||
},
|
||||
// 16 S_MULK_I32: D.i32 = D.i32 * signext(SIMM16) (low 32 bits); Table 11: no SCC.
|
||||
Form::MulK => ((i64::from(di) * i64::from(ki)) as u32, scc),
|
||||
}
|
||||
}
|
||||
|
||||
/// SIMM16 values: zero, one, both sides of bit 15, all ones, an all-ones low
|
||||
/// byte (selector 255 as a register field would mean a literal) and two
|
||||
/// mixed patterns.
|
||||
const IMMEDIATES: [u16; 10] = [
|
||||
0, 1, 0x7fff, 0x8000, 0x8001, 0xfffe, 0xffff, 0x00ff, 0x1234, 0xedcb,
|
||||
];
|
||||
/// Signed and unsigned boundaries, and the words the sign- and zero-extended
|
||||
/// immediates produce.
|
||||
const VALUES: [u32; 15] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0x7fff,
|
||||
0x8000,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0xffff_8000,
|
||||
0xffff_7fff,
|
||||
0x8001,
|
||||
];
|
||||
/// The value s10 holds throughout.
|
||||
const MARKER: u32 = 0x0f0f_1234;
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 9] = [
|
||||
("sopk movk", 10 * 2),
|
||||
("sopk cmovk", 10 * 2 * 2),
|
||||
("sopk cmpk", 12 * 15 * 10 * 2),
|
||||
("sopk addk", 15 * 10),
|
||||
("sopk mulk", 15 * 10 * 2),
|
||||
("sopk no literal", 16 * 2),
|
||||
("sopk s105", 16),
|
||||
("sopk cmovk unwritten sdst", 10),
|
||||
("sopk no other write", 16),
|
||||
];
|
||||
/// Per form: SDST 106-127; per writing form: SDST s0-s7; per reading form: an
|
||||
/// uninitialized SDST.
|
||||
const REJECTIONS: usize = 16 * 22 + 4 * 8 + 14;
|
||||
|
||||
/// ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15 (guide
|
||||
/// 13.1.2).
|
||||
fn sopk(op: u32, sdst: u32, simm16: u16) -> u32 {
|
||||
0xb000_0000 | op << 23 | sdst << 16 | u32::from(simm16)
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
|
||||
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0),
|
||||
/// run `alu`, then v2 = s<result>, `s_cbranch_scc0` over
|
||||
/// `v_xor_b32 v2, v1, v2`, and store v2. With the lane input [0, !0] the
|
||||
/// output is [R, R] when SCC is clear and [R, !R] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init.iter().chain(&[(10, MARKER)]) {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn case(
|
||||
name: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
let (r, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
/// One form on s8 = `d` with SCC = `scc` before; the result is s8.
|
||||
fn single(form: Form, name: &'static str, family: &'static str, d: u32, scc: bool, k: u16) -> Case {
|
||||
let code = program(&[(8, d)], scc, &[sopk(form as u32, 8, k)], 8);
|
||||
let label = format!("s8 {d:#x}, simm16 {k:#06x}, scc before {scc}");
|
||||
case(name, family, label, code, expect(form, d, scc, k))
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for k in IMMEDIATES {
|
||||
match form {
|
||||
Form::MovK => {
|
||||
for scc in [false, true] {
|
||||
cases.push(single(form, name, "sopk movk", 0x5a5a_5a5a, scc, k));
|
||||
}
|
||||
}
|
||||
Form::CmovK => {
|
||||
for d in [0x5a5a_5a5a, sext(k)] {
|
||||
for scc in [false, true] {
|
||||
cases.push(single(form, name, "sopk cmovk", d, scc, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
// SCC before is the opposite of the result, so a missing
|
||||
// write shows.
|
||||
Form::AddK => {
|
||||
for d in VALUES {
|
||||
let scc = !expect(form, d, false, k).1;
|
||||
cases.push(single(form, name, "sopk addk", d, scc, k));
|
||||
}
|
||||
}
|
||||
Form::MulK => {
|
||||
for d in VALUES {
|
||||
for scc in [false, true] {
|
||||
cases.push(single(form, name, "sopk mulk", d, scc, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Both SCC values before, so neither a missing write nor a
|
||||
// flip of the old SCC passes.
|
||||
_ => {
|
||||
for d in VALUES {
|
||||
for scc in [false, true] {
|
||||
cases.push(single(form, name, "sopk cmpk", d, scc, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// An immediate whose low byte is 0xff (or both bytes) followed by
|
||||
// `s_movk_i32 s9, 0x42`: had the word taken a literal, the move would
|
||||
// be consumed and s9 never written.
|
||||
for k in [0x00ff, 0xffff] {
|
||||
let (d, scc) = (0x8000_0000, true);
|
||||
let code = program(&[(8, d)], scc, &[sopk(op, 8, k), sopk(0, 9, 0x42)], 9);
|
||||
let label = format!("simm16 {k:#06x}, then s_movk_i32 s9");
|
||||
let after = expect(form, d, scc, k).1;
|
||||
cases.push(case(name, "sopk no literal", label, code, (0x42, after)));
|
||||
}
|
||||
// s10 (the marker) and s9 keep their values: the form writes only
|
||||
// SDST s8. The result is s10.
|
||||
let code = program(
|
||||
&[(8, 0x8000_0000), (9, 0x9999)],
|
||||
true,
|
||||
&[sopk(op, 8, 0x8000)],
|
||||
10,
|
||||
);
|
||||
let after = expect(form, 0x8000_0000, true, 0x8000).1;
|
||||
let label = "s10 after the form on s8".to_string();
|
||||
cases.push(case(
|
||||
name,
|
||||
"sopk no other write",
|
||||
label,
|
||||
code,
|
||||
(MARKER, after),
|
||||
));
|
||||
if form == Form::CmovK {
|
||||
// A taken move initializes a never-written SDST: s20 is not read.
|
||||
for k in IMMEDIATES {
|
||||
let code = program(&[], true, &[sopk(op, 20, k)], 20);
|
||||
let label = format!("s20 unwritten, simm16 {k:#06x}");
|
||||
let family = "sopk cmovk unwritten sdst";
|
||||
cases.push(case(name, family, label, code, (sext(k), true)));
|
||||
}
|
||||
}
|
||||
// The top supported SGPR, s105, as SDST; the result is s105.
|
||||
let (d, k) = (0x7fff_fff0, 0x0020);
|
||||
let scc = if is_compare(form) || form == Form::AddK {
|
||||
!expect(form, d, false, k).1
|
||||
} else {
|
||||
true
|
||||
};
|
||||
let code = program(&[(105, d)], scc, &[sopk(op, 105, k)], 105);
|
||||
let label = format!("s105 {d:#x}, simm16 {k:#06x}");
|
||||
cases.push(case(
|
||||
name,
|
||||
"sopk s105",
|
||||
label,
|
||||
code,
|
||||
expect(form, d, scc, k),
|
||||
));
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOPK word's byte offset in `program` with `init` SGPR moves: three
|
||||
/// header words, one 8-byte move per init pair and the marker, and the AND.
|
||||
fn alu_offset(init: usize) -> usize {
|
||||
12 + 8 * (init + 1) + 4
|
||||
}
|
||||
|
||||
/// Both interpreters must refuse `code` at the SOPK word, not later.
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
|
||||
let offset = alu_offset(init);
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse at the SOPK word, with the number
|
||||
/// of init pairs before it.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// VCC_LO/HI, TTMP0-15, M0, NULL, EXEC_LO/HI: outside the subset.
|
||||
for sdst in 106..=127 {
|
||||
let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8);
|
||||
all.push((format!("{name} sdst {sdst}"), code, 1));
|
||||
}
|
||||
if is_compare(form) {
|
||||
// s20 is never written: the compare reads SDST.
|
||||
let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8);
|
||||
all.push((format!("{name} uninitialized s20"), code, 1));
|
||||
} else {
|
||||
for sdst in 0..8 {
|
||||
let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8);
|
||||
all.push((format!("{name} write to resource s{sdst}"), code, 1));
|
||||
}
|
||||
if matches!(form, Form::AddK | Form::MulK) {
|
||||
let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8);
|
||||
all.push((format!("{name} uninitialized s20"), code, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sopk_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, reference);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sopk: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sopk_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sopk: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sopk_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, init) in &rejections {
|
||||
assert_rejected_at_alu(label, code, *init);
|
||||
}
|
||||
eprintln!("sopk: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sopk_opcodes_stay_unsupported() {
|
||||
// Table 66: 1 s_version, 18-19 getreg and setreg, 21 setreg_imm32 (its
|
||||
// literal here would be the next word, refused all the same), 22 call,
|
||||
// 23-26 waitcnt and 27-28 subvector loops; 17 and 20 are unlisted. 29-31
|
||||
// are the SOP1, SOPC and SOPP encodings. With SDST s8, opcode 23 is not
|
||||
// the `null, 0` store fence either.
|
||||
for op in [1].into_iter().chain(17..=28) {
|
||||
let code = program(&[(8, 1)], true, &[sopk(op, 8, 0)], 8);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code, 1);
|
||||
}
|
||||
// `s_waitcnt_vscnt null, 1`: only the zero count is the supported fence.
|
||||
let code = program(&[(8, 1)], true, &[sopk(23, 125, 1)], 8);
|
||||
assert_rejected_at_alu("s_waitcnt_vscnt null, 1", &code, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmovk_without_scc_is_rejected() {
|
||||
// The header and the s10 marker move, then `s_cmovk_i32 s8, 1` with SCC
|
||||
// never written: both interpreters must refuse it at byte 20.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0xbe80_03ff | 10 << 16,
|
||||
MARKER,
|
||||
sopk(Form::CmovK as u32, 8, 1),
|
||||
0x7e04_0208,
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
match xenora_ref::execute(&code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted s_cmovk_i32 without SCC"),
|
||||
Err(error) => assert_eq!(error.offset, 20, "reference rejected it elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(&code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted s_cmovk_i32 without SCC"),
|
||||
Err(error) => assert!(error.starts_with("0x14:"), "independent: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sopk_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, _) in rejections() {
|
||||
assert!(
|
||||
compile(Architecture::Gfx1030, &code).is_err(),
|
||||
"compiler accepted {label}"
|
||||
);
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!("sopk: {} Metal cases in {programs} programs", cases.len());
|
||||
}
|
||||
Reference in new issue
Block a user