Merge remote-tracking branch 'origin/main' into task/215-sop2-b64

# Conflicts:
#	CHANGELOG.md
#	crates/decoder/src/lib.rs
#	crates/decoder/tests/gfx1030.rs
#	crates/isa/generate_semantics.py
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	crates/shader/tests/compiler.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	scripts/assemble-fixture.sh
This commit is contained in:
elforeign committed 2026-11-24 10:05:47 -06:00
commit a332ee60b4
37 files changed
+2516 -606

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ remains unsupported.
### Added
- Added eight gfx1030 SOP2 64-bit logical forms with even scalar register pairs, inline integers and one zero-extended literal. The compiler resolves both result words and sets SCC from the full result. Local CPU oracle and LLVM fixture checks passed. Native Metal readback and independent acceptance are pending (part of #215).
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
- 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.
+20 -2
View File
@@ -6,6 +6,7 @@ pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAlu64Op,
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource,
ScalarSource64, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource,
VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
@@ -14,8 +15,8 @@ use xenora_isa::{
};
use xenora_isa::meta::EncodingFamily;
pub use xenora_isa::semantics::VectorBinary;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
pub use xenora_isa::semantics::{VectorBinary, VectorUnary};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
@@ -316,6 +317,23 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
if let Some(op) = VectorUnaryOp::from_word(first) {
let dst = (first >> 17) as u8;
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((Instruction::VectorUnary { op, dst, src }, len));
}
if let Some(op) = VectorSwapOp::from_word(first) {
if first & 0x100 == 0 {
return Err(unsupported(
op.assembly_name(),
"expected a VGPR SRC0 for writeback",
));
}
let dst = (first >> 17) as u8;
let src = first as u8;
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
}
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
@@ -715,7 +733,7 @@ fn vector_compare(
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
+20 -3
View File
@@ -5,12 +5,12 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAlu64Op, ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarSource64, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorSource, decode, decode_at,
VectorAluOp, VectorAluVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
Source, VectorAlu, VectorInteger,
Source, VectorAlu, VectorInteger, VectorUnary,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
@@ -357,6 +357,22 @@ fn reference_op(instruction: Instruction) -> Op {
};
Op::ScalarLogicPair(kind, dst, pair(src0), pair(src1))
}
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
match op {
VectorUnaryOp::NotB32 => VectorUnary::Not,
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
},
dst,
match src {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
),
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
Instruction::ScalarAlu {
op,
dst,
@@ -596,12 +612,13 @@ fn compares_fixture_instructions_against_llvm() {
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 128, "forms compared: {forms:?}");
assert_eq!(forms.len(), 134, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
+88 -10
View File
@@ -61,7 +61,7 @@ OPERATIONS = {
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
"mov": "Move", "cmov": "ConditionalMove",
"mov": "Move", "cmov": "ConditionalMove", "swap": "Swap",
}
# Unary operations read one source; they need an operand rule of the unary kind.
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
@@ -97,7 +97,7 @@ COMPARE_PRIMITIVES = {
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap",
}
ARITHMETIC = {
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
@@ -140,10 +140,14 @@ MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
WAVE = {"any": "Any", "wave32": "Wave32"}
# Which wave declaration each operand-rule kind must make. The decoder has no
# wave-size input, so "wave32" is only true where the caller's ABI fixes the
# wave size: the lane-mask compares, whose one entry point is the Wave32
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
# kind must be "any".
WAVE_BY_KIND = {"vector_compare": "wave32"}
# wave size. Lane-mask compares, vector unary operations and vector swaps use
# the Wave32 compute fixture ABI. The default for other kinds is "any".
WAVE_BY_KIND = {
"alu64": "any",
"vector_compare": "wave32",
"vector_unary": "wave32",
"vector_swap": "wave32",
}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
@@ -262,7 +266,45 @@ UNSUPPORTED_COMBOS = {
# VOP3 rules also name source classes and encoding fields they refuse.
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS | {"dst_odd_pair", "src_odd_pair"}
VECTOR_UNARY_PRIMITIVES = {
("not", "bitwise"): "Not",
("brev", "bitwise"): "ReverseBits",
("flbit", "unsigned"): "FindHighUnsigned",
("ff1", "bitwise"): "FindLow",
("flbit", "signed"): "FindHighSigned",
}
OPERAND_RULES = {
"vop1_vgpr": {
"rust": "Vop1Vgpr",
"enum": "VectorUnaryOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vector_source"}],
"max_literals": 1,
},
"unsupported": {
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
"src_special",
},
"kind": "vector_unary",
},
"vop1_swap": {
"rust": "Vop1Swap",
"enum": "VectorSwapOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vgpr"}],
"max_literals": 0,
},
"unsupported": {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
},
"kind": "vector_swap",
},
"sop2_sgpr": {
"rust": "Sop2Sgpr",
"enum": "ScalarAluOp",
@@ -668,7 +710,10 @@ def _check_xml(form, rule, snapshot, errors):
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
# The XML marks both swap operands as outputs. Guide 12.8 also
# reads both old values before assigning either result.
direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source)
if (is_input, is_output) != direction:
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
@@ -843,10 +888,16 @@ def validate(registry, snapshot):
if form["carry_in"] != "none":
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
primitive = (scc, None, False)
elif _rule_kind(form) == "vector":
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
key = (form["operation"], form["signedness"])
table = {
"vector": VECTOR_PRIMITIVES,
"vector_unary": VECTOR_UNARY_PRIMITIVES,
"vector_swap": {("swap", "bitwise"): "Swap"},
}[_rule_kind(form)]
lowering = table.get(key)
primitive = None if lowering is None else ("unchanged", lowering, False)
elif _rule_kind(form) == "alu64":
if RELATION_KEY in form:
@@ -878,6 +929,8 @@ def validate(registry, snapshot):
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
if form["operation"] == "compare"
else "vector_swap" if form["operation"] == "swap"
else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY
else "unary" if form["operation"] in UNARY or (
form["operation"] == "mov" and form["family"] == "SOP1"
)
@@ -1069,7 +1122,7 @@ def render(registry, snapshot):
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, VectorBinary, Wave,",
" Signedness, SpecRef, VectorBinary, VectorUnary, Wave,",
"};",
"use crate::CompareRelation;",
"",
@@ -1316,6 +1369,31 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }]",
" }",
]
if kind in ("vector_unary", "vector_swap"):
out += [
"",
" /// Assembler name of the 32-bit VOP1 encoding.",
" pub const fn assembly_name(self) -> &'static str {",
" match self {",
]
suffix = "_e32" if kind == "vector_unary" else ""
out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms]
out += [" }", " }"]
if kind == "vector_swap":
return out + ["}"]
if kind == "vector_unary":
out += [
"",
" /// Per-lane integer operation selected by the registry.",
" pub const fn lowering(self) -> VectorUnary {",
" match self {",
]
out += [
f" Self::{form['variant']} => "
f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]},"
for form in forms
]
return out + [" }", " }", "}"]
if kind == "immediate":
out += [
"",
+2 -1
View File
@@ -21,6 +21,7 @@ include = [
"rdna2/sopc.toml",
"rdna2/sopk.toml",
"rdna2/sop1.toml",
"rdna2/vop1.toml",
"rdna2/vop2.toml",
"rdna2/vopc.toml",
"rdna2/vop3.toml",
@@ -47,7 +48,7 @@ file = "amdgpu_isa_rdna2.xml"
# width operand and result width in bits
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
# wave any | wave32 (wave32 for VOPC compares and VOP1 integer forms)
# operands a key of [operand_rules]
# spec references; at least one guide section with a page
# verify evidence required before the form counts as verified
+123
View File
@@ -0,0 +1,123 @@
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
[operand_rules.vop1_vgpr]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vector_source" }]
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
# Both operands are read and written by swap; SRC0 must select a VGPR.
[operand_rules.vop1_swap]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vgpr" }]
max_literals = 0
unsupported = [
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
]
[[form]]
name = "V_NOT_B32"
family = "VOP1"
opcode = 55
variant = "NotB32"
operation = "not"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_BFREV_B32"
family = "VOP1"
opcode = 56
variant = "BfrevB32"
operation = "brev"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_U32"
family = "VOP1"
opcode = 57
variant = "FfbhU32"
operation = "flbit"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBL_B32"
family = "VOP1"
opcode = 58
variant = "FfblB32"
operation = "ff1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_I32"
family = "VOP1"
opcode = 59
variant = "FfbhI32"
operation = "flbit"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 144 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SWAP_B32"
family = "VOP1"
opcode = 101
variant = "SwapB32"
operation = "swap"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_swap"
spec = [{ document = "guide", section = "12.8", page = 149 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+15 -2
View File
@@ -20,7 +20,7 @@ pub use rdna2::{
};
pub use semantics_gen::{
ScalarAlu64Op, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
@@ -176,6 +176,14 @@ pub enum Instruction {
WaitStore,
/// VOP1 unmodified 32-bit vector move.
MoveB32 { dst: u8, src: VectorSource },
/// VOP1 unary integer operation with a single VGPR result.
VectorUnary {
op: VectorUnaryOp,
dst: u8,
src: VectorSource,
},
/// VOP1 register swap. Both operands are inputs and outputs.
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
VectorAluVop3 {
@@ -307,6 +315,8 @@ impl Instruction {
Self::WaitLoad => "s_waitcnt",
Self::WaitStore => "s_waitcnt_vscnt",
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::VectorUnary { op, .. } => op.assembly_name(),
Self::VectorSwap { op, .. } => op.assembly_name(),
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu64 { op, .. } => op.mnemonic(),
@@ -359,7 +369,10 @@ impl fmt::Display for Instruction {
}
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
Self::WaitStore => formatter.write_str(" null, 0"),
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
write!(formatter, " v{dst}, {src}")
}
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
Self::VectorAluVop3 {
dst, src0, src1, ..
}
+21
View File
@@ -94,6 +94,23 @@ pub enum Operation {
Move,
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
ConditionalMove,
/// Swap the two old per-lane VGPR values (guide 12.8).
Swap,
}
/// Per-lane integer operation with one input and one result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnary {
/// Bitwise complement.
Not,
/// Reverse bit order.
ReverseBits,
/// Count leading zeros, or return all ones for zero.
FindHighUnsigned,
/// Count trailing zeros, or return all ones for zero.
FindLow,
/// Count leading sign bits, or return all ones if every bit matches.
FindHighSigned,
}
/// The per-lane integer operation a vector form lowers to. One reusable MSL
@@ -235,6 +252,10 @@ pub enum OperandRule {
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
Vop2Vgpr2,
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
Vop1Vgpr,
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
Vop1Swap,
}
/// Evidence a form needs before it counts as verified.
+813 -38
View File
@@ -5,7 +5,7 @@ use crate::meta::EncodingFamily;
use crate::primitive;
use crate::semantics::{
CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,
Signedness, SpecRef, VectorBinary, Wave,
Signedness, SpecRef, VectorBinary, VectorUnary, Wave,
};
use crate::CompareRelation;
@@ -1721,6 +1721,649 @@ impl ScalarImmediateOp {
}
}
/// VOP1 operations declared in the semantic registry (operand rule `vop1_swap`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorSwapOp {
/// `v_swap_b32` (VOP1 opcode 101): bitwise swap, SCC = unchanged.
SwapB32,
}
/// VectorSwapOp by VOP1 OP field value; `None` for undeclared opcodes.
const VECTOR_SWAP_OP_BY_OPCODE: [Option<VectorSwapOp>; 256] = [
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
Some(VectorSwapOp::SwapB32),
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
];
impl VectorSwapOp {
/// Every operation, in registry order.
pub const ALL: [Self; 1] = [
Self::SwapB32,
];
/// Selects the operation from a first instruction word: the VOP1 encoding
/// bits (mask 0xfe00_0000) and then the OP field (bits 9-16).
pub const fn from_word(word: u32) -> Option<Self> {
if word & 0xfe00_0000 != 0x7e00_0000 {
return None;
}
VECTOR_SWAP_OP_BY_OPCODE[((word >> 9) & 0xff) as usize]
}
/// Lower-case mnemonic.
pub const fn mnemonic(self) -> &'static str {
match self {
Self::SwapB32 => "v_swap_b32",
}
}
/// The validated registry row.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::SwapB32 => 86,
}]
}
/// Assembler name of the 32-bit VOP1 encoding.
pub const fn assembly_name(self) -> &'static str {
match self {
Self::SwapB32 => "v_swap_b32",
}
}
}
/// VOP1 operations declared in the semantic registry (operand rule `vop1_vgpr`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnaryOp {
/// `v_not_b32` (VOP1 opcode 55): bitwise not, SCC = unchanged.
NotB32,
/// `v_bfrev_b32` (VOP1 opcode 56): bitwise brev, SCC = unchanged.
BfrevB32,
/// `v_ffbh_u32` (VOP1 opcode 57): unsigned flbit, SCC = unchanged.
FfbhU32,
/// `v_ffbl_b32` (VOP1 opcode 58): bitwise ff1, SCC = unchanged.
FfblB32,
/// `v_ffbh_i32` (VOP1 opcode 59): signed flbit, SCC = unchanged.
FfbhI32,
}
/// VectorUnaryOp by VOP1 OP field value; `None` for undeclared opcodes.
const VECTOR_UNARY_OP_BY_OPCODE: [Option<VectorUnaryOp>; 256] = [
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
Some(VectorUnaryOp::NotB32),
Some(VectorUnaryOp::BfrevB32),
Some(VectorUnaryOp::FfbhU32),
Some(VectorUnaryOp::FfblB32),
Some(VectorUnaryOp::FfbhI32),
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
];
impl VectorUnaryOp {
/// Every operation, in registry order.
pub const ALL: [Self; 5] = [
Self::NotB32,
Self::BfrevB32,
Self::FfbhU32,
Self::FfblB32,
Self::FfbhI32,
];
/// Selects the operation from a first instruction word: the VOP1 encoding
/// bits (mask 0xfe00_0000) and then the OP field (bits 9-16).
pub const fn from_word(word: u32) -> Option<Self> {
if word & 0xfe00_0000 != 0x7e00_0000 {
return None;
}
VECTOR_UNARY_OP_BY_OPCODE[((word >> 9) & 0xff) as usize]
}
/// Lower-case mnemonic.
pub const fn mnemonic(self) -> &'static str {
match self {
Self::NotB32 => "v_not_b32",
Self::BfrevB32 => "v_bfrev_b32",
Self::FfbhU32 => "v_ffbh_u32",
Self::FfblB32 => "v_ffbl_b32",
Self::FfbhI32 => "v_ffbh_i32",
}
}
/// The validated registry row.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::NotB32 => 81,
Self::BfrevB32 => 82,
Self::FfbhU32 => 83,
Self::FfblB32 => 84,
Self::FfbhI32 => 85,
}]
}
/// Assembler name of the 32-bit VOP1 encoding.
pub const fn assembly_name(self) -> &'static str {
match self {
Self::NotB32 => "v_not_b32_e32",
Self::BfrevB32 => "v_bfrev_b32_e32",
Self::FfbhU32 => "v_ffbh_u32_e32",
Self::FfblB32 => "v_ffbl_b32_e32",
Self::FfbhI32 => "v_ffbh_i32_e32",
}
}
/// Per-lane integer operation selected by the registry.
pub const fn lowering(self) -> VectorUnary {
match self {
Self::NotB32 => VectorUnary::Not,
Self::BfrevB32 => VectorUnary::ReverseBits,
Self::FfbhU32 => VectorUnary::FindHighUnsigned,
Self::FfblB32 => VectorUnary::FindLow,
Self::FfbhI32 => VectorUnary::FindHighSigned,
}
}
}
/// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAluOp {
@@ -1889,24 +2532,24 @@ impl VectorAluOp {
/// The validated registry row.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::MulI32I24 => 81,
Self::MulHiI32I24 => 82,
Self::MulU32U24 => 83,
Self::MulHiU32U24 => 84,
Self::MinI32 => 85,
Self::MaxI32 => 86,
Self::MinU32 => 87,
Self::MaxU32 => 88,
Self::XnorB32 => 89,
Self::AddNcU32 => 90,
Self::SubNcU32 => 91,
Self::SubrevNcU32 => 92,
Self::LshrrevB32 => 93,
Self::AshrrevI32 => 94,
Self::LshlrevB32 => 95,
Self::AndB32 => 96,
Self::OrB32 => 97,
Self::XorB32 => 98,
Self::MulI32I24 => 87,
Self::MulHiI32I24 => 88,
Self::MulU32U24 => 89,
Self::MulHiU32U24 => 90,
Self::MinI32 => 91,
Self::MaxI32 => 92,
Self::MinU32 => 93,
Self::MaxU32 => 94,
Self::XnorB32 => 95,
Self::AddNcU32 => 96,
Self::SubNcU32 => 97,
Self::SubrevNcU32 => 98,
Self::LshrrevB32 => 99,
Self::AshrrevI32 => 100,
Self::LshlrevB32 => 101,
Self::AndB32 => 102,
Self::OrB32 => 103,
Self::XorB32 => 104,
}]
}
@@ -2359,22 +3002,22 @@ impl VectorCompareOp {
/// The validated registry row.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::CmpLtI32 => 99,
Self::CmpEqI32 => 100,
Self::CmpLeI32 => 101,
Self::CmpGtI32 => 102,
Self::CmpNeI32 => 103,
Self::CmpGeI32 => 104,
Self::CmpLtU32 => 105,
Self::CmpEqU32 => 106,
Self::CmpLeU32 => 107,
Self::CmpGtU32 => 108,
Self::CmpNeU32 => 109,
Self::CmpGeU32 => 110,
Self::CmpFI32 => 111,
Self::CmpTI32 => 112,
Self::CmpFU32 => 113,
Self::CmpTU32 => 114,
Self::CmpLtI32 => 105,
Self::CmpEqI32 => 106,
Self::CmpLeI32 => 107,
Self::CmpGtI32 => 108,
Self::CmpNeI32 => 109,
Self::CmpGeI32 => 110,
Self::CmpLtU32 => 111,
Self::CmpEqU32 => 112,
Self::CmpLeU32 => 113,
Self::CmpGtU32 => 114,
Self::CmpNeU32 => 115,
Self::CmpGeU32 => 116,
Self::CmpFI32 => 117,
Self::CmpTI32 => 118,
Self::CmpFU32 => 119,
Self::CmpTU32 => 120,
}]
}
@@ -2510,13 +3153,13 @@ impl VectorAluVop3Op {
/// The validated registry row of this encoding.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::AddNcU32 => 115,
Self::AddNcU32 => 121,
}]
}
}
/// Identity of every registry form and encoding variant, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 116] = [
pub const FORM_IDS: [(&str, EncodingFamily); 122] = [
("S_ADD_U32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_ADD_I32", EncodingFamily::Sop2),
@@ -2598,6 +3241,12 @@ pub const FORM_IDS: [(&str, EncodingFamily); 116] = [
("S_SEXT_I32_I8", EncodingFamily::Sop1),
("S_SEXT_I32_I16", EncodingFamily::Sop1),
("S_ABS_I32", EncodingFamily::Sop1),
("V_NOT_B32", EncodingFamily::Vop1),
("V_BFREV_B32", EncodingFamily::Vop1),
("V_FFBH_U32", EncodingFamily::Vop1),
("V_FFBL_B32", EncodingFamily::Vop1),
("V_FFBH_I32", EncodingFamily::Vop1),
("V_SWAP_B32", EncodingFamily::Vop1),
("V_MUL_I32_I24", EncodingFamily::Vop2),
("V_MUL_HI_I32_I24", EncodingFamily::Vop2),
("V_MUL_U32_U24", EncodingFamily::Vop2),
@@ -2636,7 +3285,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 116] = [
];
/// One validated row per registry form, in registry order.
pub static FORMS: [FormSemantics; 116] = [
pub static FORMS: [FormSemantics; 122] = [
FormSemantics {
name: "S_ADD_U32",
family: EncodingFamily::Sop2,
@@ -4338,6 +4987,132 @@ pub static FORMS: [FormSemantics; 116] = [
spec: &[SpecRef { document: Document::Guide, section: "12.3", page: 0 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_NOT_B32",
family: EncodingFamily::Vop1,
opcode: 55,
operation: Operation::Not,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop1Vgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_BFREV_B32",
family: EncodingFamily::Vop1,
opcode: 56,
operation: Operation::ReverseBits,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop1Vgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_FFBH_U32",
family: EncodingFamily::Vop1,
opcode: 57,
operation: Operation::FindLastBit,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop1Vgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_FFBL_B32",
family: EncodingFamily::Vop1,
opcode: 58,
operation: Operation::FindFirstOne,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop1Vgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 143 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_FFBH_I32",
family: EncodingFamily::Vop1,
opcode: 59,
operation: Operation::FindLastBit,
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::Wave32,
operands: OperandRule::Vop1Vgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 144 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_SWAP_B32",
family: EncodingFamily::Vop1,
opcode: 101,
operation: Operation::Swap,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop1Swap,
spec: &[SpecRef { document: Document::Guide, section: "12.8", page: 149 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MUL_I32_I24",
family: EncodingFamily::Vop2,
+10 -4
View File
@@ -7,8 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, and
flags declared both written and undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned"}
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -63,6 +64,8 @@ ENCS = {
"reg_xmm": ("RegXmm", True, {""}),
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
}
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
# Encodings whose ModRM operand is an XMM register or memory of the source width.
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
@@ -171,6 +174,8 @@ def load(text):
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
or form["enc"] == "xmm_gpr_imm"):
fail(f"{where}: XMM size does not match the encoding")
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
fail(f"{where}: LOCK needs a memory destination")
if form.get("unaligned") and form["src"] != "x":
fail(f"{where}: alignment applies only to 16-byte operands")
if form["prefix"] and form["map"] != "0f":
@@ -266,7 +271,8 @@ def generate(operations, forms):
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
out += ["];", ""]
groups = []
+20 -2
View File
@@ -50,6 +50,8 @@ pub struct Form {
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
/// The LOCK prefix is accepted when the ModRM operand is memory.
pub lockable: bool,
}
/// Opcode table entry.
@@ -167,6 +169,9 @@ pub struct Insn {
pub imm: u64,
/// Condition code for Jcc, CMOVcc and SETcc.
pub condition: u8,
/// Carries a LOCK prefix. Set only for a lockable form with a memory
/// destination.
pub lock: bool,
}
impl Insn {
@@ -231,8 +236,9 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
/// Forms the registry does not declare, LOCK, address-size overrides and an
/// ignored segment override after FS or GS are rejected rather than approximated.
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
/// with a memory destination, address-size overrides and an ignored segment
/// override after FS or GS are rejected rather than approximated.
pub fn decode<E>(
rip: u64,
fetch: impl FnMut(u64) -> Result<u8, E>,
@@ -246,6 +252,7 @@ pub fn decode<E>(
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
let mut lock = false;
let mut segment = None;
let mut byte = cursor.u8()?;
loop {
@@ -267,6 +274,11 @@ pub fn decode<E>(
byte = cursor.u8()?;
continue;
}
0xF0 => {
lock = true;
byte = cursor.u8()?;
continue;
}
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
// FS or GS their meaning is not relied on, so it is rejected.
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
@@ -413,6 +425,11 @@ pub fn decode<E>(
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
reg = register(opcode & 7, rex_b, size);
}
// LOCK is an invalid opcode unless the instruction is lockable and its
// destination is memory (Intel SDM Vol. 2, "LOCK").
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
return Err(DecodeError::Unsupported(0xF0));
}
let mut imm = match form.immediate {
Immediate::None => 0,
@@ -449,6 +466,7 @@ pub fn decode<E>(
reg,
imm,
condition: opcode & 0xF,
lock,
})
}
+29
View File
@@ -369,6 +369,35 @@ pub fn execute(
write_rm(cpu, memory, insn, b)?;
write_reg(cpu, insn.reg, size, a);
}
Op::Xadd => {
let (a, b) = operands(cpu, memory, insn)?;
let (value, flags) = add(a, b, false, size);
write_rm(cpu, memory, insn, value)?;
// The source is loaded before the destination is stored, so a
// register added to itself keeps the sum.
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
write_reg(cpu, insn.reg, size, a);
}
cpu.flags = flags;
}
Op::Cmpxchg => {
let (destination, source) = operands(cpu, memory, insn)?;
let expected = cpu.gpr[RAX] & mask(size);
let (_, flags) = sub(expected, destination, false, size);
// The destination is written whether or not the values match, so a
// mismatch on memory that cannot be written still faults.
let matched = expected == destination;
write_rm(
cpu,
memory,
insn,
if matched { source } else { destination },
)?;
if !matched {
write_reg(cpu, accumulator(RAX), size, destination);
}
cpu.flags = flags;
}
Op::Bswap => {
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
write_reg(cpu, insn.reg, size, value);
File diff suppressed because it is too large. Load diff
-14
View File
@@ -2672,15 +2672,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("cmpxchg16b_not_equal", 0),
("cmpxchg16b_unaligned_is_gp", 0),
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
("cmpxchg32_equal", 0),
("cmpxchg64_memory_equal_without_lock", 0),
("cmpxchg64_memory_not_equal", 0),
("cmpxchg64_memory_not_equal_without_lock", 0),
("cmpxchg8_not_equal_loads_al", 0),
("cmpxchg8b_equal", 0),
("cmpxchg8b_equal_without_lock", 0),
("cmpxchg8b_not_equal", 0),
("cmpxchg_mismatch_still_writes", 0),
("crc32c_byte_and_qword_forms_agree", 0),
("crc32c_check_string", 0),
("dpps_mask", 0),
@@ -2689,8 +2683,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("fs_addr32_truncates_before_adding_base", 0),
("fs_rep_movsb_overrides_source_only", 0),
("fs_rep_movsb_overrides_source_only_df_clear", 0),
("gs_lock_xadd", 0),
("gs_xadd_without_lock", 0),
("haddps_hsubpd_addsubps", 0),
("insertps_zero_mask", 0),
("jecxz_tests_low_32_bits", 1),
@@ -2783,12 +2775,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("shrd32_by8", 0),
("shrd64_by1_sign_change", 0),
("shrd64_cl64_is_count_zero", 0),
("xadd32_reg_reg", 0),
("xadd64_memory", 0),
("xadd64_memory_without_lock", 0),
("xadd64_same_register_doubles", 0),
("xadd8_al_ah", 0),
("xadd_readonly_page_keeps_register", 0),
("xchg_ax_r9w_preserves_both_uppers", 0),
("xchg_eax_ebx_clears_both_uppers", 0),
("xchg_rax_r8_is_not_nop", 0),
+16 -1
View File
@@ -84,6 +84,15 @@ def cases():
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
f"xchg {mem(bits)}, {reg(2, bits)}"]
for op in ("xadd", "cmpxchg"):
for bits in (8, 16, 32, 64):
# Destination RAX always matches the accumulator; a register with
# itself keeps the sum. LOCK is valid only with a memory destination.
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
@@ -163,7 +172,13 @@ def assemble(lines):
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
# One line per instruction: objdump never wraps its raw bytes.
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
rows, prefix = [], []
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
row = prefix + match.group(1).split()
# objdump lists a leading LOCK prefix on a row of its own.
prefix = row if match.group(2).strip() == "lock" else []
if not prefix:
rows.append(row)
if len(rows) != len(lines):
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
+62
View File
@@ -953,6 +953,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
49 87 d9 | xchg rbx, r9
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
0f c0 cb | xadd bl, cl
45 0f c0 e1 | xadd r9b, r12b
0f c0 d0 | xadd al, dl
0f c0 db | xadd bl, bl
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
66 0f c1 cb | xadd bx, cx
66 45 0f c1 e1 | xadd r9w, r12w
66 0f c1 d0 | xadd ax, dx
66 0f c1 db | xadd bx, bx
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
0f c1 cb | xadd ebx, ecx
45 0f c1 e1 | xadd r9d, r12d
0f c1 d0 | xadd eax, edx
0f c1 db | xadd ebx, ebx
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
48 0f c1 cb | xadd rbx, rcx
4d 0f c1 e1 | xadd r9, r12
48 0f c1 d0 | xadd rax, rdx
48 0f c1 db | xadd rbx, rbx
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
0f c0 dc | xadd ah, bl
0f c0 f1 | xadd cl, dh
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
0f b0 cb | cmpxchg bl, cl
45 0f b0 e1 | cmpxchg r9b, r12b
0f b0 d0 | cmpxchg al, dl
0f b0 db | cmpxchg bl, bl
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
66 0f b1 cb | cmpxchg bx, cx
66 45 0f b1 e1 | cmpxchg r9w, r12w
66 0f b1 d0 | cmpxchg ax, dx
66 0f b1 db | cmpxchg bx, bx
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
0f b1 cb | cmpxchg ebx, ecx
45 0f b1 e1 | cmpxchg r9d, r12d
0f b1 d0 | cmpxchg eax, edx
0f b1 db | cmpxchg ebx, ebx
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
48 0f b1 cb | cmpxchg rbx, rcx
4d 0f b1 e1 | cmpxchg r9, r12
48 0f b1 d0 | cmpxchg rax, rdx
48 0f b1 db | cmpxchg rbx, rbx
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
0f b0 dc | cmpxchg ah, bl
0f b0 f1 | cmpxchg cl, dh
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
88 dc | mov ah, bl
88 ea | mov dl, ch
b7 21 | mov bh, 0x21
+376
View File
@@ -0,0 +1,376 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
//!
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
//! Nothing was compared with x86 hardware.
//!
//! Both engines run one guest instruction at a time on one host thread, so
//! these tests establish the single-thread results that any later guest
//! scheduler has to preserve. They say nothing about concurrent execution.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
/// Two writable pages. Nothing is mapped after them unless a test says so.
const DATA: u64 = 0x4000;
const PAGE: u64 = 0x1000;
const END: u64 = DATA + 2 * PAGE;
const RAX: usize = 0;
const RCX: usize = 1;
const RDX: usize = 2;
const RBX: usize = 3;
const RSI: usize = 6;
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
}
fn data(memory: &GuestMemory) -> Vec<u8> {
let mut out = vec![0; 2 * PAGE as usize];
memory.read_bytes(DATA, &mut out).unwrap();
out
}
struct Run {
name: &'static str,
cpu: CpuState,
exit: ExitReason,
memory: GuestMemory,
/// Instructions the DBT ran on the shared semantics.
helpers: usize,
}
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
let mut interpreted = memory.clone();
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
let mut translated = memory.clone();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut state = cpu.clone();
let native = engine.run(&mut state, &mut translated, budget);
[
Run {
name: "interpreter",
cpu: result.final_state,
exit: result.exit_reason,
memory: interpreted,
helpers: 0,
},
Run {
name: "DBT",
cpu: native.final_state,
exit: native.exit_reason,
memory: translated,
helpers: engine.metrics.interpreter_fallbacks,
},
]
}
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
RFlags {
cf,
zf,
sf,
of,
pf,
af,
}
}
fn low(bits: u32) -> u64 {
u64::MAX >> (64 - bits)
}
#[test]
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
let accepted: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
];
for code in accepted {
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
let mut unlocked = code.to_vec();
unlocked.remove(lock);
let insn = decode(ENTRY, |at| {
code.get((at - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
// The accumulator matches the operand, so each exchange stores RCX.
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
cpu.gpr[RSI] = DATA + 0x40;
let mut memory = image(code);
memory
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
.unwrap();
let mut plain = image(&unlocked);
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
// LOCK changes no result here: only the instruction is a byte longer.
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
let mut shifted = wanted.cpu.clone();
shifted.rip += 1;
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
}
}
let rejected: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
&[0xF0, 0x90], // lock nop
];
for code in rejected {
let mut padded = code.to_vec();
padded.extend([0x90; 8]);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = DATA;
let memory = image(&padded);
for run in both(&cpu, &memory, 1) {
assert!(
matches!(run.exit, ExitReason::IllegalInstruction(_)),
"{code:02X?} on the {}: {:?}",
run.name,
run.exit
);
assert_eq!(run.cpu, cpu, "{code:02X?}");
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
}
}
}
#[test]
fn compare_and_exchange_takes_each_branch_at_every_width() {
// Destination [rsi] or RBX, source RCX, accumulator RAX.
let forms: &[(&[u8], u32, bool)] = &[
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
];
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
const ABOVE: u64 = 0x5555_6666_7777_8888;
for &(code, bits, in_memory) in forms {
let mask = low(bits);
for matches in [true, false] {
// The destination holds the accumulator's low bits, or differs in
// bit 0, under bits the operation must not read.
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = ACCUMULATOR;
cpu.gpr[RCX] = SOURCE;
cpu.gpr[RBX] = old;
cpu.gpr[RSI] = DATA + 0x80;
// accumulator - destination is 0, or -1 when the destination is
// one more. Start from the opposite flags so each must be written.
let after = if matches {
flags(false, true, false, false, true, false)
} else {
flags(true, false, true, false, true, true)
};
cpu.flags = flags(
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
);
let mut memory = image(code);
memory.write_u64(DATA + 0x80, old).unwrap();
// A match stores the source. A mismatch stores the old value back
// and loads it into the accumulator. An 8- or 16-bit register write
// keeps the bits above it, a 32-bit one clears them, and a memory
// write touches only its own bytes.
let stored = if matches { SOURCE & mask } else { old & mask };
let merged = |before: u64, value: u64| match bits {
32 => value,
_ => (before & !mask) | value,
};
let mut wanted = cpu.clone();
wanted.rip = ENTRY + code.len() as u64;
wanted.flags = after;
if !matches {
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
}
let wanted_memory = if in_memory {
(old & !mask) | stored
} else {
wanted.gpr[RBX] = merged(old, stored);
old
};
for run in both(&cpu, &memory, 1) {
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
assert_eq!(run.cpu, wanted, "{what}");
assert_eq!(
run.memory.read_u64(DATA + 0x80).unwrap(),
wanted_memory,
"{what}"
);
}
}
}
}
#[test]
fn locked_operands_may_be_unaligned_and_span_two_regions() {
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
// last address straddles the data and a second writable region after it.
let spanning = |code: &[u8]| {
let mut memory = image(code);
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
};
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
// lock xadd [rsi], rcx
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0000_0001_0000_0001,
"{at:#x}"
);
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
assert_eq!(
run.cpu.flags,
flags(true, false, false, false, false, true),
"{at:#x}"
);
}
// lock cmpxchg [rsi], rcx, with a matching accumulator
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0102_0304_0506_0708,
"{at:#x}"
);
}
}
}
#[test]
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
// The last three bytes of writable memory, then five bytes that are
// unmapped or read-only.
let at = END - 3;
for code in [xadd, cmpxchg] {
for read_only_tail in [false, true] {
// Accumulators that match and that do not match the operand's
// writable bytes: a failed compare needs the write access too.
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
let mut memory = image(code);
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
if read_only_tail {
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = accumulator;
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
cpu.gpr[RSI] = at;
cpu.flags = flags(true, false, true, false, true, false);
for run in both(&cpu, &memory, 1) {
let what = format!(
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
run.name
);
assert!(
matches!(run.exit, ExitReason::MemoryFault(_)),
"{what}: {:?}",
run.exit
);
assert_eq!(run.cpu, cpu, "{what}");
assert_eq!(data(&run.memory), data(&memory), "{what}");
}
}
}
}
}
#[test]
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
// retry: lea rcx, [rax + 1]
// lock cmpxchg [rsi], rcx
// jne retry
// mov edx, 5
// lock xadd [rsi], rdx
// hlt
let code = [
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
];
const COUNTER: u64 = DATA + 0x100;
let mut cpu = CpuState::new(ENTRY, 0);
// A stale expectation: the first exchange fails and reloads RAX, the
// second succeeds.
cpu.gpr[RAX] = 0xDEAD;
cpu.gpr[RSI] = COUNTER;
let mut memory = image(&code);
memory.write_u64(COUNTER, 41).unwrap();
for run in both(&cpu, &memory, 64) {
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
// XADD returns the value before its addition.
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
// Two exchanges and one addition, none lowered to ARM64 yet.
if run.name == "DBT" {
assert_eq!(run.helpers, 3);
}
}
}
+24
View File
@@ -305,6 +305,8 @@ enum Outcome {
}
fn reference(m: &mut Machine, text: &str) -> Outcome {
// LOCK changes no result on a machine that runs one instruction at a time.
let text = text.strip_prefix("lock ").unwrap_or(text);
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
Vec::new()
@@ -659,6 +661,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
write(m, places[1], a);
Outcome::Done(none)
}
"xadd" => {
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
let sum = arithmetic(m, a, b, false, false, bits);
write(m, places[1], a);
write(m, places[0], sum);
Outcome::Done(none)
}
"cmpxchg" => {
// The accumulator is compared with DEST as CMP would. On a match
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
let accumulator = read(m, rax(bits), bits);
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
arithmetic(m, accumulator, destination, true, false, bits);
if accumulator == destination {
write(m, places[0], source);
} else {
write(m, rax(bits), destination);
write(m, places[0], destination);
}
Outcome::Done(none)
}
"bswap" => {
let value = read(m, places[0], bits);
let bytes = bits / 8;
+37
View File
@@ -10,6 +10,9 @@
# decodable; a form counts as implemented only once its operation has semantics
# and independent tests. Forms not listed here are rejected.
#
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -48,6 +51,8 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
movsxd = { ref = "sdm MOVSX/MOVSXD" }
lea = { ref = "sdm LEA" }
xchg = { ref = "sdm XCHG" }
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
bswap = { ref = "sdm BSWAP" }
cwde = { ref = "sdm CBW/CWDE/CDQE" }
cdq = { ref = "sdm CWD/CDQ/CQO" }
@@ -674,6 +679,38 @@ enc = "rm_reg"
size = "v"
register_only = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB1
enc = "rm_reg"
size = "v"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC1
enc = "rm_reg"
size = "v"
lock = true
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
[[group]]
map = "0f"
+83 -23
View File
@@ -10,7 +10,7 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarSource64, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource,
VectorAluOp, VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, VectorUnary,
};
/// SGPR index of `vcc_lo`.
@@ -92,6 +92,7 @@ enum Op {
Load,
Constant(u32),
Binary(Binary, Value, Value),
Unary(VectorUnary, Value),
MergeLanes {
mask: u32,
active: Value,
@@ -129,6 +130,7 @@ impl Op {
match self {
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
Self::Binary(_, left, right) => vec![left, right],
Self::Unary(_, source) => vec![source],
Self::MergeLanes {
active, inactive, ..
} => vec![active, inactive],
@@ -149,6 +151,21 @@ impl Op {
match self {
Self::Load => format!("input[{index}]"),
Self::Constant(value) => format!("0x{value:08x}u"),
Self::Unary(op, source) => {
let src = name(source);
// AMD guide 12.8: all three scans return -1 if no bit matches.
match op {
VectorUnary::Not => format!("~{src}"),
VectorUnary::ReverseBits => format!("reverse_bits({src})"),
VectorUnary::FindHighUnsigned => {
format!("{src} == 0u ? 0xffffffffu : clz({src})")
}
VectorUnary::FindLow => format!("{src} == 0u ? 0xffffffffu : ctz({src})"),
VectorUnary::FindHighSigned => format!(
"({src} == 0u || {src} == 0xffffffffu) ? 0xffffffffu : clz({src} ^ (0u - ({src} >> 31u)))"
),
}
}
Self::Binary(operator, left, right) => {
let (left, right) = (name(left), name(right));
let (_, symbol) = operator.operator();
@@ -440,6 +457,19 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Unary(operator, source) => {
let mnemonic = match operator {
VectorUnary::Not => "not.b32",
VectorUnary::ReverseBits => "brev.b32",
VectorUnary::FindHighUnsigned => "ffbh.u32",
VectorUnary::FindLow => "ffbl.b32",
VectorUnary::FindHighSigned => "ffbh.i32",
};
(
format!("{dest} = {mnemonic} {source}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
)
}
Op::Binary(operator, left, right) => (
format!("{dest} = {} {left}, {right}", operator.operator().0),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
@@ -726,6 +756,25 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
};
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
Ok(match source {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(operations, facts, offset, bits),
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(operations, facts, offset, bits)
}
VectorSource::Immediate(bits) => constant(operations, facts, offset, bits),
})
};
// Scalar instructions and waits still execute when all lanes are inactive.
if exec == 0 {
match instruction.instruction {
@@ -733,7 +782,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
| Instruction::VectorAlu { .. }
| Instruction::VectorUnary { .. }
| Instruction::VectorSwap { .. } => continue,
_ => {}
}
}
@@ -1060,27 +1111,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
src0,
src1,
} => {
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, offset, bits)
}
VectorSource::Immediate(bits) => {
constant(&mut operations, &mut facts, offset, bits)
}
};
let src0 = read_vector(src0, &mut operations, &mut facts)?;
let src1 = read(src1)?;
let (left, right) = if op.swaps_sources() {
(src1, src0)
@@ -1092,6 +1123,35 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::VectorUnary { op, dst, src } => {
let source = read_vector(src, &mut operations, &mut facts)?;
(Some(dst), Op::Unary(op.lowering(), source))
}
Instruction::VectorSwap { dst, src, .. } => {
// Guide 12.8: capture both old values before updating either VGPR.
// read() also rejects v0 and registers with outstanding loads.
let old_dst = read(dst)?;
let old_src = read(src)?;
if dst != src {
registers[usize::from(dst)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_src,
Some(old_dst),
)?);
registers[usize::from(src)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_dst,
Some(old_src),
)?);
}
continue;
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
+14
View File
@@ -405,3 +405,17 @@ fn scalar_logic_b64_fixture_matches_goldens() {
include_str!("../../../fixtures/golden/scalar-logic-b64.metal")
);
}
#[test]
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vector-unary.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vector-unary.metal")
);
}
+1
View File
@@ -26,6 +26,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
- [SOP2 64-bit logic](shaders/scalar-logic-b64.md) — Register pairs, literal expansion, SCC and local verification.
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits.
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
+4 -4
View File
@@ -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: 128 of 128. Accepted Metal forms · Apple M5: 18 of 128. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 134 of 134. Accepted Metal forms · Apple M5: 18 of 134. 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">128 / 128</text>
<text x="510" y="58" font-size="13" text-anchor="end">134 / 134</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 / 128</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 134</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="68.91" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="65.82" 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

+15 -1
View File
@@ -45,6 +45,20 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
None of it has been compared with x86 hardware.
## Locked instructions
XADD and CMPXCHG exist for 8-, 16-, 32- and 64-bit register and memory destinations. The LOCK prefix (F0) is accepted on exactly the forms the registry marks `lock = true`, and only when the destination is memory. Today those are the memory forms of XADD and CMPXCHG. LOCK anywhere else is an illegal instruction, as the Intel SDM (Vol. 2, "LOCK") specifies for a register destination or an instruction that cannot be locked. LOCK on the other instructions the SDM allows (ADD, ADC, AND, BTC, BTR, BTS, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR and XCHG), CMPXCHG8B and CMPXCHG16B are not implemented and stay rejected.
These rules hold for both engines and are what a guest scheduler has to preserve:
- **Ordering.** Each engine runs one guest instruction at a time on one host thread, and an instruction either completes or changes nothing. A locked instruction is therefore indivisible and totally ordered with every other guest access, and LOCK changes no result: the locked and unlocked encodings leave identical state. A scheduler that switches guest threads only between instructions keeps this. One that runs guest threads on several host threads does not, and must first make each locked instruction atomic against every access to its operand, with x86's ordering rather than ARM64's weaker one. Nothing here provides or tests that.
- **Alignment.** A locked operand may have any alignment and may span two mapped regions.
- **Compare failure.** CMPXCHG compares the accumulator with the destination as CMP would and sets all six status flags from it. On a match it stores the source and leaves the accumulator alone. On a mismatch it loads the destination into the accumulator and stores the destination's old value back, so the destination is written either way and a mismatch on memory that cannot be written still faults. With a 32-bit register destination both stores clear the upper half of that register, following the SDM's operation text.
- **Faults.** If any byte of the operand cannot be read or written, the instruction faults before memory, registers or flags change.
- **Lowering.** The DBT runs these forms on the shared semantics. They are not lowered to ARM64 atomic instructions, which could only be judged against concurrent guest threads.
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
## Rejected on purpose
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
+6
View File
@@ -129,6 +129,12 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbl_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero | `7E0A7501` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_i32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match | `7E0C7702` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_swap_b32` | VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0 | `7E02CB02` | yes | yes | three-way passed | per-thread exchange of both register values with lane merges under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
+4 -2
View File
@@ -30,13 +30,13 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| 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 |
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
| **Total** | 1465 | 128 | 116 | 132 | 128 | 128 | 18 | 18 | 67 |
| **Total** | 1465 | 134 | 122 | 138 | 134 | 134 | 18 | 18 | 78 |
## Unsupported operand variants
@@ -51,6 +51,8 @@ The table counts distinct variant names per family across registry operand rules
| 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` |
| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| 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` |
+1 -1
View File
@@ -123,7 +123,7 @@ error.
| `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 and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `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` (explicit destinations are covered by the operand rule) |
| `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` |
| `wave` | Wave sizes the form is valid in | `wave32` for VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
+38
View File
@@ -0,0 +1,38 @@
# Wave32 vector unary integer operations and swap
Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute
ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8,
the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3.
| Form | Result in each active lane |
| --- | --- |
| `v_not_b32_e32` | Complement all 32 bits. |
| `v_bfrev_b32_e32` | Reverse the order of the 32 bits. |
| `v_ffbh_u32_e32` | Count leading zeros. Return all ones if the source is zero. |
| `v_ffbl_b32_e32` | Count trailing zeros. Return all ones if the source is zero. |
| `v_ffbh_i32_e32` | Count leading bits equal to the sign bit. Return all ones if all bits match. |
| `v_swap_b32` | Exchange the old values of two vector general-purpose registers (VGPRs). A register swapped with itself keeps its value. |
The unary forms accept a VGPR, scalar register `s0`–`s105`, `vcc_lo` (the low
half of the vector condition code), inline integer `-16`–`64`, or a literal
word as SRC0. Swap requires a VGPR as SRC0 because it writes both operands.
Both operands of swap must be initialized when EXEC is nonzero. The compute
ABI reserves `v0` for indexing and requires waiting for buffer loads before
using or overwriting their destination. Inactive lanes retain their old
values. The six forms leave EXEC, VCC and the scalar condition code (SCC)
unchanged.
The compiler emits per-thread Metal Shading Language for unary operations.
For swap it captures both old values in the intermediate representation before
updating either register binding. Under partial EXEC, each register receives
its own lane merge.
The [guide-derived oracle](../../tests/validation/tests/vop1_integer.rs) checks
the 752 accepted cases' outputs against its expected values on each CPU
interpreter and, through the translator, on native Metal (Apple M5, API and
shader validation on: 752 cases in 613 programs). A CPU test checks that the
compiler accepts every case and refuses each of the 610 rejected programs at
the same instruction offset as the interpreters. The
[LLVM-assembled fixture](../../fixtures/rdna2/vector-unary.s) exercises all
six forms with a partial EXEC swap. Independent acceptance of the
translator is pending. Xbox hardware agreement is unknown.
+72
View File
@@ -1430,6 +1430,78 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_not_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement"
representation = "`7E046F01`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_bfrev_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order"
representation = "`7E067101`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_u32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero"
representation = "`7E087302`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbl_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero"
representation = "`7E0A7501`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_i32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match"
representation = "`7E0C7702`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_swap_b32"
encoding = "VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0"
representation = "`7E02CB02`"
lowering = "per-thread exchange of both register values with lane merges under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
+12
View File
@@ -0,0 +1,12 @@
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0018: t2 = merge.lanes mask=0xaaaaaaaa, t1, t0
0018: t3 = merge.lanes mask=0xaaaaaaaa, t0, t1
0020: t4 = brev.b32 t2
0024: t5 = ffbh.u32 t3
0028: t6 = ffbl.b32 t2
002c: t7 = ffbh.i32 t3
0030: t8 = xor.b32 t4, t5
0034: t9 = xor.b32 t6, t8
0038: t10 = xor.b32 t7, t9
003c: store.u32 output[index], t10
+19
View File
@@ -0,0 +1,19 @@
#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 t1 = ~t0;
uint t2 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t1 : t0;
uint t3 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t0 : t1;
uint t4 = reverse_bits(t2);
uint t5 = t3 == 0u ? 0xffffffffu : clz(t3);
uint t6 = t2 == 0u ? 0xffffffffu : ctz(t2);
uint t7 = (t3 == 0u || t3 == 0xffffffffu) ? 0xffffffffu : clz(t3 ^ (0u - (t3 >> 31u)));
uint t8 = t4 ^ t5;
uint t9 = t6 ^ t8;
uint t10 = t7 ^ t9;
output[index] = t10;
}
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Wave32 VOP1 integer forms (AMD RDNA 2 ISA guide 12.8).
// Exchange the input and its complement in odd lanes, then use both values
// and all three bit scans to form the output.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
v_not_b32_e32 v2, v1
s_mov_b32 exec_lo, 0xaaaaaaaa
v_swap_b32 v1, v2
s_mov_b32 exec_lo, -1
v_bfrev_b32_e32 v3, v1
v_ffbh_u32_e32 v4, v2
v_ffbl_b32_e32 v5, v1
v_ffbh_i32_e32 v6, v2
v_xor_b32_e32 v7, v3, v4
v_xor_b32_e32 v7, v5, v7
v_xor_b32_e32 v7, v6, v7
buffer_store_dword v7, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1 -1
View File
@@ -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-logic-b64 scalar-compare scalar-unary scalar-arith scalar-immediate 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-logic-b64 scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-unary; 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"
+1 -2
View File
@@ -56,5 +56,4 @@ cargo test --locked -p xenora-semantic-review --no-run
# 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 vop1_integer_forms_match_the_guide_on_native_metal
--skip vopc_wide_match_the_guide_on_native_metal
+22 -4
View File
@@ -843,10 +843,20 @@ fn other_vop1_opcodes_stay_unsupported() {
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation, and the translator's VOP1 integer forms (skipped by scripts/test-gpu.sh until then)"]
fn vop1_integer_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"));
fn compiler_matches_the_vop1_integer_operand_domain() {
let cases = checked_cases();
for case in &cases {
compile(Architecture::Gfx1030, &case.code)
.unwrap_or_else(|error| panic!("compiler rejected {}: {error:?}", case.label));
}
check_compiler_rejections();
eprintln!(
"vop1_integer: {} compiler cases and {REJECTIONS} rejections",
cases.len()
);
}
fn check_compiler_rejections() {
for (label, code, offset) in rejections() {
// Refused at the same word as by the interpreters, so a later failure
// cannot stand in.
@@ -857,7 +867,15 @@ fn vop1_integer_forms_match_the_guide_on_native_metal() {
};
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop1_integer_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"));
let cases = checked_cases();
check_compiler_rejections();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
+12
View File
@@ -67,6 +67,18 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "movq"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"\nsrc = "q"\nunaligned = true'), "alignment applies")
self.rejects(self.form('op = "nop"\nprefix = "66"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "map 0f")
def test_lock_needs_a_memory_destination(self):
# Not a form without ModRM, not one whose ModRM operand is the source,
# and not one that takes only a register.
message = "LOCK needs a memory destination"
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nlock = true'), message)
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
def test_only_xadd_and_cmpxchg_are_lockable(self):
_, forms = generate_x86.load(REGISTRY)
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
def test_unknown_vocabulary_is_rejected(self):
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")