Compare commits

...
Author SHA1 Message Date
katherinebytes a7fa8b0d65 Retry the ARM64 CI run
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 20:47:35 +00:00
katherinebytes 9ddb708cdf Merge upstream main for the compute pipeline cache
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:15:39 +00:00
Zach Doxsee 5b7ffec90a Merge pull request #347 from Arths17/task/109-relocation-overhead
loader: avoid per-entry relocation histogram lookups
2026-11-24 20:15:11 +01:00
Zach Doxsee 48c5d20aa9 Merge pull request #335 from izdat-sl4w/fix/audit-utf8-locale
audit: read and write tracked files as UTF-8
2026-11-24 20:14:57 +01:00
izdat-sl4w 8049c36f51 audit: pin LF newlines in the generated status writes
Path.write_text opens with newline=None, so on Windows a regeneration
would translate the tracked LF files to CRLF and show a spurious diff.
Both write sites now pass newline="\n", which leaves the bytes
identical on macOS and Linux.

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:45 +01:00
izdat-sl4w c91036f879 Merge main into fix/audit-utf8-locale
Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:30 +01:00
katherinebytes 6f1ac2a906 Reuse Metal compute pipelines
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:12:15 +00:00
atharvranjan adf10db015 loader: build relocation type counts once per image
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 12:04:05 -06:00
elforeign 0fdb995892 isa, decoder, shader, ref: VOP3A encodings of eleven VOP2 integer forms and the sixteen integer compares (#215) (#311)
* isa, decoder: VOP3 encodings of the eleven registry VOP2 integer forms (#215)

Eleven [[encoding_variant]] entries re-encode the VOP2 integer forms as
VOP3A (_e64) under operand rule vop3_vgpr2: two VGPR sources, no
modifiers, SRC2 the unused inline zero. Opcodes from the pinned XML,
checked against llvm-mc. Decoder known words and per-bit rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, decoder, shader: LLVM-assembled fixture and goldens for the eleven VOP3 VOP2 variants (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* ref, validation: independent guide-derived oracle for VOP3 integer VOP2 forms and Wave32 VOP3 compares (#215)

crates/ref and tests/validation/independent_ref.rs decode and run the eleven
VOP3A (_e64) integer VOP2 forms and the sixteen V_CMP_*_{I32,U32}_e64 compares
writing a 32-bit lane mask to one SGPR (s0-s105) or vcc_lo, derived from the
AMD RDNA 2 guide only. New suites vop3_integer.rs and vop3_compare.rs, with
ignored native Metal parts.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: add VOP3A encodings for the sixteen integer compares (#215)

Sixteen gfx1030 Wave32 integer compares gain their VOP3A (_e64) encoding
as registry variants, with an explicit SGPR mask destination (guide 3.9,
13.3.3; pinned XML OPR_SREG), VCCZ branching through vcc_lo and
translation errors for reads of runtime-only SGPR results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, shader, validation: VOP3A compare fixture and native Metal runs (#215)

A fixture with all sixteen VOP3A integer compares (vcc_lo destination,
runtime s_cbranch_vccz) ties the new variants to fixture coverage, with
IR and MSL goldens. The VOP3 integer and compare Metal oracles now run in
the GPU gate: the translator they waited for is in this branch.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* changelog: VOP3A integer and compare encodings (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* shader, fixtures, docs: e64 compare names in the IR; status rows for the 27 VOP3A forms (#215)

The IR names a VOP3A compare by its _e64 mnemonic and prints its SGPR
destination; VOPC output is unchanged. The compare fixture now uses a
mid-range second source (so swapped unsigned opcodes change the golden)
and one plain SGPR destination. docs/status.toml and the rendered
instruction table list the 27 new forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* docs: use a recognized lowering phrase for the VOP3A integer rows (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: VOP3A variants exist only for the 32-bit VOPC compares (#215)

After main gained the 16-bit compares (#327), the dispatch test expected a
VOP3A encoding for every non-64-bit compare. Only the 32-bit ones have one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:38:44 -06:00
elforeign d7f7d586d3 gpu: bind a texture and sampler to guest draws through descriptor tables (#303) (#336)
* gpu: bind a texture and sampler to guest draws through descriptor tables (#303)

A guest command list had no way to bind a texture: GraphicsCommand stopped
at vertex and index buffers. This adds the smallest D3D12-shaped binding the
translated image_sample_lz pixel stage needs: shader-visible CBV_SRV_UAV and
sampler heaps, CreateShaderResourceView for one-level RGBA8 and BC1 2D
textures, a point/clamp CreateSampler, a root signature with one pixel-stage
SRV table and one sampler table, and SetDescriptorHeaps and
SetGraphicsRootDescriptorTable. Everything else fails explicitly before any
draw.

The native path hands the bound level to a textured backend.
NativeCompute::render_rgba8_sampled_bc1 binds a BC1 level natively to
fragment texture 0 and sampler 0. The software reference point-samples with
clamp addressing.

BC1 fixtures use only endpoint colours. Apple's hardware decoder gives
171/84 for the interpolated palette entries where the spec-exact decoder
gives 170/85.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* gpu: tighten guest texture binding after independent review (#303)

The independent review found binding rules that diverged from D3D12:
changing descriptor heaps kept tables bound in the old heaps, setting the
same root signature again cleared its tables, and unsupported draw shapes
were drawn as one triangle. Now heap changes and a different root signature
invalidate tables, while redundant sets keep them. Table bases are checked
against the bound heap of their type when bound. Textured draws other than
one instance of three vertices fail, and zero vertices or instances draw
nothing.

Descriptor handle offsets can no longer carry into another heap's ID. SRVs
of array or multi-level textures are rejected. A texture whose state
excludes pixel-shader reads is not sampled. Vertex buffer offsets are
overflow-checked. The tests now cover swapped root parameters, a second
sampler slot, off-centre and out-of-range coordinates, state transitions,
draw shapes and resource bounds.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* loader: format the guest texture test (#303)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* gpu: close the review's remaining texture-binding gaps (#303)

The re-review found three partial fixes. The public software reference
could overflow on a huge viewport. A texture in a combined write and read
state could be sampled. The sampler-slot test used two identical filled
slots. The viewport is now bounded to 4096 pixels. A sampled texture must be
COMMON or a read-only state that includes PIXEL_SHADER_RESOURCE. The sampler
heap now leaves its middle slot empty. The docs now state the start-instance
rule and when table bases are checked.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:21:03 -06:00
izdat-sl4w d01627b3de audit: read and write tracked files as UTF-8
The generated-status check and the claims audit called
Path.read_text()/write_text() without encoding=, so they used the process
locale encoding. Under an ASCII locale the status check raises
UnicodeDecodeError on docs/claims.toml, and under cp1252 it reports a
spurious xenora-progress.svg difference, so a current tree fails the
documented checkout command. Both scripts now pass encoding="utf-8", as
the rest of scripts/ does, and CI runs the two checks again under a
non-UTF-8 locale so the requirement stays enforced.

Closes #334

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 18:09:21 +01:00
Ranveer Soni 1d363c3c34 Merge pull request #328 from elforeign/task/215-vop2-vcc
isa, decoder, shader, ref: the four VOP2 VCC-reading integer forms through the semantic registry (#215)
2026-11-24 22:02:56 +05:30
elforeign e74ebbe30b Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/decoder/tests/gfx1030.rs
#	crates/isa/src/semantics_gen.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:27:02 -06:00
elforeign 26eba92b87 docs: record the VOP2 VCC-reading forms' Metal readback (#215)
scripts/test-gpu.sh now runs vop2_vcc_matches_guide_on_native_metal,
which passes under API and shader validation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:26:42 -06:00
Ranveer Soni 05143d6295 Merge pull request #327 from elforeign/task/215-vopc16-xlate
isa, decoder, shader: translate the twelve VOPC 16-bit integer compares (#215)
2026-11-24 21:54:09 +05:30
elforeign d6a65b2940 Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:24:07 -06:00
elforeign 1cc7f01fec Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	crates/isa/generate_semantics.py
#	crates/isa/src/semantics_gen.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
2026-11-24 10:23:59 -06:00
elforeign 34b16ca65c Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:17:48 -06:00
elforeign 7adb978683 Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/decoder/src/lib.rs
#	crates/decoder/tests/gfx1030.rs
#	crates/isa/generate_semantics.py
#	crates/isa/semantics/rdna2.toml
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	crates/shader/tests/compiler.rs
#	docs/README.md
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:13:25 -06:00
elforeign 8e9ec8b9d1 isa, decoder, shader, ref: the four VOP2 VCC-reading integer forms through the semantic registry (#215)
v_cndmask_b32, v_add_co_ci_u32, v_sub_co_ci_u32 and v_subrev_co_ci_u32
(VOP2 e32, Wave32) read VCC_LO as the per-lane select or carry-in; the
co_ci forms write the carry-out to VCC_LO. An independent guide-derived
oracle, tests/validation/tests/vop2_vcc.rs, checks both CPU interpreters;
its native Metal half is ignored until the lead runs it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:06:08 -06:00
56 changed files with 7544 additions and 379 deletions

No files matched your search

+3 -1
View File
@@ -41,6 +41,8 @@ jobs:
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
# The generated status check must not depend on the host locale encoding.
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
@@ -65,7 +67,7 @@ jobs:
cargo test --locked --workspace
cargo test --locked --manifest-path experiments/x1/Cargo.toml
scripts/audit/dependencies.sh
scripts/audit/claims.sh
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p xenora
+6
View File
@@ -10,13 +10,18 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
@@ -193,6 +198,7 @@ remains unsupported.
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
Generated
+1
View File
@@ -204,6 +204,7 @@ dependencies = [
"sha2",
"xenora-metal",
"xenora-shader",
"xenora-texture",
]
[[package]]
+46 -15
View File
@@ -5,8 +5,8 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp,
VectorUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
VectorSource, VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
@@ -15,7 +15,7 @@ use xenora_isa::{
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
pub use xenora_isa::semantics::{VectorBinary, VectorUnary};
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
@@ -330,6 +330,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
if let Some(op) = VectorCompareVop3Op::from_word(first) {
let second = word(bytes, 8)?;
let sdst = first as u8;
if sdst > VCC_LO {
return Err(unsupported(
op.assembly_name(),
"expected a destination of s0-s105 or vcc_lo",
));
}
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
return Ok((
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
},
8,
));
}
if let Some(op) = VectorAluVop3Op::from_word(first) {
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
@@ -419,7 +439,10 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
(VectorSource::Register(src0), 4)
}
_ => vector_src0(first, bytes, op.assembly_name())?,
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
vector_src0(first, bytes, op.assembly_name())?
}
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
};
return Ok((
Instruction::VectorAlu {
@@ -720,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
Ok((Instruction::MoveB32 { dst, src }, len))
}
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
/// the gfx1030 assembler's inline-zero operand encoding.
fn vop3_vgpr2(
op: VectorAluVop3Op,
first: u32,
second: u32,
) -> Result<Instruction, DecodeErrorKind> {
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0,
src1,
})
}
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
/// CLAMP, OMOD and NEG are clear.
fn vop3_vgpr2_sources(
mnemonic: &'static str,
first: u32,
second: u32,
) -> Result<(u8, u8), DecodeErrorKind> {
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(unsupported(
op.assembly_name(),
mnemonic,
"expected two VGPR sources and no modifiers",
));
}
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0: src0 as u8,
src1: src1 as u8,
})
Ok((src0 as u8, src1 as u8))
}
fn scalar_form(
+310 -36
View File
@@ -5,7 +5,7 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorSource, VectorUnaryOp, decode, decode_at,
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
@@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
assert_eq!(instructions, wanted);
}
#[test]
fn decodes_wave32_vop3_compares_from_llvm_words() {
use VectorCompareVop3Op::*;
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
(0xd481_0004, CmpLtI32, 4),
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
(0xd482_0004, CmpEqI32, 4),
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
(0xd483_0004, CmpLeI32, 4),
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
(0xd484_0004, CmpGtI32, 4),
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
(0xd485_0004, CmpNeI32, 4),
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
(0xd486_0004, CmpGeI32, 4),
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
(0xd4c1_0004, CmpLtU32, 4),
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0004, CmpEqU32, 4),
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
(0xd4c3_0004, CmpLeU32, 4),
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
(0xd4c4_0004, CmpGtU32, 4),
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
(0xd4c5_0004, CmpNeU32, 4),
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
(0xd4c6_0004, CmpGeU32, 4),
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
(0xd480_0004, CmpFI32, 4),
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
(0xd487_0004, CmpTI32, 4),
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
(0xd4c0_0004, CmpFU32, 4),
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
(0xd4c7_0004, CmpTU32, 4),
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0000, CmpEqU32, 0),
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0069, CmpEqU32, 105),
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_006a, CmpEqU32, 106),
];
for (first, op, sdst) in cases {
let code: Vec<_> = [first, 0x0202_0501]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
let dst = if sdst == 106 {
"vcc_lo".to_owned()
} else {
format!("s{sdst}")
};
assert_eq!(
decoded,
[DecodedInstruction {
offset: 0,
byte_len: 8,
instruction: Instruction::VectorCompareVop3 {
op,
sdst,
src0: 1,
src1: 2
},
}],
);
assert_eq!(
decoded[0].instruction.to_string(),
format!("{} {dst}, v1, v2", op.assembly_name())
);
}
}
#[test]
fn rejects_noncanonical_wave32_vop3_compare_operands() {
// v_cmp_eq_u32_e64 s4, v1, v2
let first = 0xd4c2_0004;
let second = 0x0202_0501;
let rejects = |first, second| {
let code: Vec<_> = [first, second]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
assert_eq!(error.offset, 0);
assert!(
matches!(
error.kind,
DecodeErrorKind::UnsupportedForm {
mnemonic: "v_cmp_eq_u32_e64",
..
}
),
"{first:#010x} {second:#010x}: {error}"
);
};
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
for sdst in 107..=255 {
rejects((first & !0xff) | sdst, second);
}
for bit in 8..=15 {
// ABS, OP_SEL and CLAMP.
rejects(first | (1 << bit), second);
}
for bit in 27..=31 {
// OMOD and NEG.
rejects(first, second | (1 << bit));
}
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
for shift in [0, 9] {
for selector in [4, 106, 128, 240, 255] {
// SGPR, VCC_LO, inline integer/float, literal.
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
}
}
}
#[test]
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
let lengths = [8, 4, 8, 8, 8, 4, 4];
@@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
}
}
fn reference_comparison(op: VectorCompareOp) -> Comparison {
Comparison {
offset: match op.relation() {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
CompareRelation::False => 0,
CompareRelation::True => 7,
},
signed: op.signed(),
}
}
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
match op {
VectorAluOp::CndmaskB32 => VectorInteger::Select,
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
}
}
fn reference_op(instruction: Instruction) -> Op {
match instruction {
Instruction::BufferLoadDword {
@@ -391,13 +550,23 @@ fn reference_op(instruction: Instruction) -> Op {
reference_scalar(src0),
reference_scalar(src1),
),
// The reference's VOP3 add; it is the only VOP3 variant so far.
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst,
src0,
src1,
} => Op::Add(dst, src0, src1),
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
reference_vector_integer(op.base()),
dst,
CompareSource::Vector(src0),
src1,
),
Instruction::ScalarUnary { op, dst, src } => {
let src = reference_scalar(src);
let unary = match op {
@@ -506,19 +675,7 @@ fn reference_op(instruction: Instruction) -> Op {
}
Instruction::VectorCompare { op, src0, src1 } => {
let comparison = Comparison {
offset: match op.relation() {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
CompareRelation::False => 0,
CompareRelation::True => 7,
},
signed: op.signed(),
};
let comparison = reference_comparison(op);
let src0 = match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
@@ -531,27 +688,24 @@ fn reference_op(instruction: Instruction) -> Op {
width => panic!("unexpected VOPC operand width {width}"),
}
}
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
} => Op::CompareVop3(
sdst,
reference_comparison(op.base()),
CompareSource::Vector(src0),
src1,
),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
match op {
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
},
reference_vector_integer(op),
dst,
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
@@ -587,16 +741,19 @@ fn compares_fixture_instructions_against_llvm() {
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 138, "forms compared: {forms:?}");
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -824,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
let outside_subset: &[&[u32]] = &[
&[0x7e04_026b], // VOP1 VCC_HI source
&[0x7da2_0501], // v_cmpx_eq_u32_e32
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
&[0x8788_0908], // s_and_b64
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
&[0x806c_0908], // SOP2 TTMP destination
@@ -893,7 +1050,7 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
let target = next_offset + displacement * 4;
format!("{mnemonic} -> 0x{target:04x}")
}
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
// VOPC and registry VOP2 forms print SRC0 as bits.
mnemonic
if mnemonic.starts_with("v_cmp_")
|| VectorAluOp::ALL
@@ -901,10 +1058,11 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
.any(|op| op.assembly_name() == mnemonic) =>
{
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
parts[1] = match literal_bits(&parts[1]) {
let src = if parts.len() == 5 { 2 } else { 1 };
parts[src] = match literal_bits(&parts[src]) {
Some(bits) => format!("0x{bits:x}"),
None => parts[1].parse::<i32>().map_or_else(
|_| parts[1].clone(),
None => parts[src].parse::<i32>().map_or_else(
|_| parts[src].clone(),
|value| format!("0x{:x}", value as u32),
),
};
@@ -1113,6 +1271,122 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
);
}
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MinI32, 0xd51100ff),
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MaxI32, 0xd51200ff),
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MinU32, 0xd51300ff),
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MaxU32, 0xd51400ff),
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
];
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
#[test]
fn decodes_registry_vop3_integer_encodings() {
for (op, first) in VOP3_INTEGER_ENCODINGS {
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].byte_len, 8);
assert_eq!(
decoded[0].instruction,
Instruction::VectorAluVop3 {
op,
dst: 255,
src0: 0,
src1: 127,
}
);
}
}
#[test]
fn decodes_vop3_integer_fixture() {
use VectorAluVop3Op::*;
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
let decoded = decode(Architecture::Gfx1030, code).unwrap();
let expected = [
(MulI32I24, 2, 1, 1),
(MulHiI32I24, 3, 2, 1),
(MulU32U24, 4, 2, 1),
(MulHiU32U24, 255, 4, 1),
(MinI32, 6, 1, 2),
(MaxI32, 7, 1, 4),
(MinU32, 8, 3, 1),
(MaxU32, 9, 255, 2),
(XnorB32, 10, 1, 255),
(SubNcU32, 11, 6, 10),
(SubrevNcU32, 1, 1, 9),
];
let actual: Vec<_> = decoded
.iter()
.filter_map(|decoded| match decoded.instruction {
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
_ => None,
})
.collect();
let expected: Vec<_> = expected
.into_iter()
.enumerate()
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
.collect();
assert_eq!(actual, expected);
}
#[test]
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
for (op, first) in VOP3_INTEGER_ENCODINGS {
let second = VOP3_INTEGER_SOURCE_WORD;
let reject = |first: u32, second: u32| {
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
let error = decode(Architecture::Gfx1030, &bytes)
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
assert_eq!(error.offset, 0);
assert!(matches!(
error.kind,
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
if mnemonic == op.assembly_name()
));
};
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
for bit in 8..=15 {
reject(first | (1 << bit), second);
}
// Second word: OMOD[28:27], NEG[31:29].
for bit in 27..=31 {
reject(first, second | (1 << bit));
}
reject(first, second & !0x1ff); // SRC0 = s0
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
reject(first, second | (1 << 18)); // SRC2 = inline one
}
}
#[test]
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
use xenora_decoder::ScalarImmediateCompareOp;
+112 -45
View File
@@ -44,7 +44,7 @@ TOP_KEYS = {
# An encoding variant is another encoding of a form already in the registry (for
# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base
# form, the encoding family, its opcode there and the operand rule of that
# encoding. It inherits the base form's operation, signedness and effects.
# encoding. The rule may redirect the base form's mask to an explicit destination.
VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
# The assembler suffix LLVM prints for a variant's encoding family.
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
@@ -140,7 +140,7 @@ SHIFT_AMOUNTS = {1, 2, 3, 4}
SOURCE_ORDER_KEY = "source_order"
SOURCE_ORDERS = {"reversed"}
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
CARRY_IN = {"none": "None", "scc": "Scc"}
CARRY_IN = {"none": "None", "scc": "Scc", "vcc": "Vcc"}
SCC = {
"unchanged": "Unchanged",
"carry_out": "CarryOut",
@@ -150,16 +150,19 @@ SCC = {
"relation": "Relation",
"selected_src0": "SelectedSrc0",
}
# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes
# such as v_cmpx have no contract yet, so exec must stay unchanged).
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST.
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"}
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".
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
WAVE_BY_KIND = {"control": "wave32", "vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
VCC_VECTOR_PRIMITIVES = {
("cselect", "bitwise"): "Select",
("add", "unsigned"): "AddCarry",
("sub", "unsigned"): "SubtractBorrow",
}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
@@ -273,7 +276,12 @@ UNSUPPORTED_COMBOS = {
# which SOP2 groups under src_vcc and src_special).
# 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
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS
VOP3_VGPR2_UNSUPPORTED = {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
}
VECTOR_UNARY_PRIMITIVES = {
("not", "bitwise"): "Not",
("brev", "bitwise"): "ReverseBits",
@@ -493,16 +501,34 @@ OPERAND_RULES = {
},
# Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and
# SRC2 the assembler's unused inline zero; the decoder rejects the rest.
"unsupported": {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
},
"unsupported": VOP3_VGPR2_UNSUPPORTED,
"kind": "vector_vop3",
# Only encoding variants of forms whose rule has this kind may use it.
"variant_of": "vector",
# The generated enum of this rule's variants; base() maps to "enum".
"variant_enum": "VectorAluVop3Op",
},
"vop3_cmp_vgpr2": {
"rust": "Vop3CmpVgpr2",
"enum": "VectorCompareOp",
"shape": {
"family": "VOP3",
"dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106},
"src": [
{"field": "SRC0", "class": "vgpr"},
{"field": "SRC1", "class": "vgpr"},
],
"max_literals": 0,
"variant_only": True,
},
"unsupported": VOP3_VGPR2_UNSUPPORTED | {
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
},
"kind": "vector_compare_vop3",
"variant_of": "vector_compare",
"variant_enum": "VectorCompareVop3Op",
"vcc_transition": ("lane_mask", "sdst_lane_mask"),
},
"vop2_vgpr": {
"rust": "Vop2Vgpr",
"enum": "VectorAluOp",
@@ -523,6 +549,24 @@ OPERAND_RULES = {
},
"kind": "vector",
},
"vop2_vcc": {
"rust": "Vop2Vcc",
"enum": "VectorAluOp",
"shape": {
"family": "VOP2",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [
{"field": "SRC0", "class": "vector_source"},
{"field": "VSRC1", "class": "vgpr"},
],
"max_literals": 1,
},
"unsupported": {
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
"src_special",
},
"kind": "vector",
},
"vop2_vgpr2": {
"rust": "Vop2Vgpr2",
"enum": "VectorAluOp",
@@ -712,7 +756,7 @@ def _check_xml(form, rule, snapshot, errors):
operands = {}
scc_in = scc_out = False
implicit = set()
vcc_writes = []
vcc_operands = []
control_mask = CONTROL_OPERATIONS.get(form["operation"], (None, None, None))[2]
mask_inputs = 0
for field, data_format, kind, size, is_input, is_output, is_implicit, encoded in variant["operands"]:
@@ -724,18 +768,21 @@ def _check_xml(form, rule, snapshot, errors):
):
mask_inputs += 1
elif field:
operands[field] = (data_format, size, is_input, is_output)
operands[field] = (data_format, kind, size, is_input, is_output)
elif kind == "OPR_VCC":
vcc_operands.append((data_format, size, is_input, is_output))
else:
implicit.add(kind)
if kind == "OPR_VCC":
vcc_writes.append((is_input, is_output))
# The vocabulary states SCC effects and a lane-mask VCC write; any other
# implicit XML operand (such as an EXEC write) is undeclared.
if form["carry_in"] == "vcc":
if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1:
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
if ("FMT_NUM_M64", 64, True, False) in vcc_operands:
vcc_operands.remove(("FMT_NUM_M64", 64, True, False))
if form["vcc"] == "lane_mask":
# Exactly one fieldless VCC operand, written and not read.
if vcc_writes != [(False, True)]:
if vcc_operands != [("FMT_NUM_M64", 64, False, True)]:
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
implicit.discard("OPR_VCC")
elif vcc_operands:
implicit.add("OPR_VCC")
if control_mask and mask_inputs != 1:
errors.append(f"{label}: expected one implicit {control_mask} input in the XML")
if implicit:
@@ -757,7 +804,7 @@ def _check_xml(form, rule, snapshot, errors):
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
data_format, kind, size, is_input, is_output = operands[field]
if field == "SIMM16" and _rule_kind(form) == "control":
expected_kind, expected_format = (
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
@@ -777,6 +824,11 @@ def _check_xml(form, rule, snapshot, errors):
continue
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if not is_source and form["vcc"] == "sdst_lane_mask":
# The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR.
expected = 64
if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"):
errors.append(f"{label}: {field} is not a scalar mask destination in the XML")
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
# The XML marks both swap operands as outputs. Guide 12.8 also
@@ -866,14 +918,18 @@ def validate(registry, snapshot):
errors.append(f"{label}: variant {form['variant']!r} is reserved")
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
errors.append(f"{label}: invalid opcode")
wave = WAVE_BY_KIND.get(_rule_kind(form), "any")
reads_vcc = form["operands"] == "vop2_vcc"
wave = "wave32" if reads_vcc else WAVE_BY_KIND.get(_rule_kind(form), "any")
if (form["carry_in"] == "vcc") != reads_vcc:
errors.append(f"{label}: implicit VCC input requires the vop2_vcc rule")
if form["wave"] in WAVE and form["wave"] != wave:
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
lane_mask = _rule_kind(form) == "vector_compare"
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
vcc = "lane_mask" if lane_mask else "unchanged"
if form["vcc"] in MASK and form["vcc"] != vcc:
errors.append(
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
f"(requires {vcc})"
)
if form["exec"] != "unchanged":
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
@@ -918,7 +974,7 @@ def validate(registry, snapshot):
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
elif _rule_kind(form) != "vector":
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
if not reads_vcc and form["operation"] in SCC_READERS and form["carry_in"] != "scc":
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
if form["operation"] == "sext":
bits = form.get(SOURCE_BITS_KEY)
@@ -971,7 +1027,7 @@ def validate(registry, snapshot):
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
key = (form["operation"], form["signedness"])
table = {
"vector": VECTOR_PRIMITIVES,
"vector": VCC_VECTOR_PRIMITIVES if reads_vcc else VECTOR_PRIMITIVES,
"vector_unary": VECTOR_UNARY_PRIMITIVES,
"vector_swap": {("swap", "bitwise"): "Swap"},
}[_rule_kind(form)]
@@ -1044,9 +1100,10 @@ def variant_row(registry, variant, base=None):
"""The base form re-encoded: its declaration with the variant's identity."""
if base is None:
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
_, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged"))
return dict(
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
spec=variant["spec"], verify=variant["verify"],
vcc=vcc, spec=variant["spec"], verify=variant["verify"],
)
@@ -1116,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
if FORM_KEYS - set(base):
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
continue
base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged"))
if base["vcc"] != base_vcc:
errors.append(
f"{label}: operand rule {variant['operands']} requires a base "
f"destination contract of {base_vcc}, got {base['vcc']}"
)
# The same base row as the completeness check above (with duplicate
# declarations, the dict keeps the last one).
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
# Every explicit operand, destination included, has the base encoding's
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
# Explicit destinations and sources keep the base encoding's data format
# in the same role. The implicit-to-explicit mask transition is checked
# above and in _check_xml for each encoding.
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
base_rule = rules.get(base.get("operands"))
if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule):
# Operands correspond by role, in rule order: the destination, then
# each source (VSRC1 of VOP2 is SRC1 of VOP3).
def roles(rule, record):
def roles(rule, record, explicit_dst):
by_field = {row[0]: row[1] for row in record["operands"] if row[0]}
fields = ([rule["dst"]["field"]] if "dst" in rule else [])
fields = [rule["dst"]["field"]] if explicit_dst else []
fields += [src["field"] for src in rule.get("src", [])]
return [(field, by_field.get(field)) for field in fields]
pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml)))
explicit_dst = "dst" in base_rule and "dst" in rule
pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst))
for (base_field, base_format), (field, data_format) in pairs:
if base_format != data_format:
errors.append(
@@ -1196,7 +1261,7 @@ def render(registry, snapshot):
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, VectorBinary, VectorUnary, Wave,",
" Signedness, SpecRef, VectorBinary, VectorLowering, VectorUnary, VectorVcc, Wave,",
"};",
"use crate::CompareRelation;",
"",
@@ -1386,7 +1451,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
f"pub enum {enum} {{",
]
for form in forms:
carry = " plus SCC" if form["carry_in"] == "scc" else ""
carry = {"scc": " plus SCC", "vcc": " with VCC input"}.get(form["carry_in"], "")
what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"]
effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}"
out += [
@@ -1646,14 +1711,16 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }",
"",
" /// The per-lane operation its MSL lowering uses.",
" pub const fn lowering(self) -> VectorBinary {",
" pub const fn lowering(self) -> VectorLowering {",
" match self {",
]
out += [
f" Self::{form['variant']} => "
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
for form in forms
]
for form in forms:
key = (form["operation"], form["signedness"])
if form["operands"] == "vop2_vcc":
lowering = f"Vcc(VectorVcc::{VCC_VECTOR_PRIMITIVES[key]})"
else:
lowering = f"Binary(VectorBinary::{VECTOR_PRIMITIVES[key]})"
out.append(f" Self::{form['variant']} => VectorLowering::{lowering},")
out += [
" }",
" }",
+4 -3
View File
@@ -45,11 +45,12 @@ file = "amdgpu_isa_rdna2.xml"
# variant Rust enum variant of the typed op
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
# carry_in none | scc | vcc (implicit scalar or per-lane condition or carry)
# 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 for VOPC compares and VOP1 integer forms)
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 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
+82
View File
@@ -348,3 +348,85 @@ wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[operand_rules.vop2_vcc]
family = "VOP2"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [
{ field = "SRC0", class = "vector_source" },
{ field = "VSRC1", class = "vgpr" },
]
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
[[form]]
name = "V_CNDMASK_B32"
family = "VOP2"
opcode = 1
variant = "CndmaskB32"
operation = "cselect"
signedness = "bitwise"
carry_in = "vcc"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop2_vcc"
spec = [{ document = "guide", section = "12.7", page = 131 }, { document = "guide", section = "3.9", page = 20 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_ADD_CO_CI_U32"
family = "VOP2"
opcode = 40
variant = "AddCoCiU32"
operation = "add"
signedness = "unsigned"
carry_in = "vcc"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vop2_vcc"
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SUB_CO_CI_U32"
family = "VOP2"
opcode = 41
variant = "SubCoCiU32"
operation = "sub"
signedness = "unsigned"
carry_in = "vcc"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vop2_vcc"
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SUBREV_CO_CI_U32"
family = "VOP2"
opcode = 42
variant = "SubrevCoCiU32"
operation = "sub"
signedness = "unsigned"
carry_in = "vcc"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vop2_vcc"
source_order = "reversed"
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+323
View File
@@ -1,6 +1,202 @@
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- Wave32 VOPC compares in VOP3A (#215) ----
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
[operand_rules.vop3_cmp_vgpr2]
family = "VOP3"
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
src = [
{ field = "SRC0", class = "vgpr" },
{ field = "SRC1", class = "vgpr" },
]
max_literals = 0
variant_only = true
unsupported = [
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
]
# Opcodes come from the pinned XML's default ENC_VOP3 records.
[[encoding_variant]]
of = "V_CMP_LT_I32"
family = "VOP3"
opcode = 129
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_EQ_I32"
family = "VOP3"
opcode = 130
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LE_I32"
family = "VOP3"
opcode = 131
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GT_I32"
family = "VOP3"
opcode = 132
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_NE_I32"
family = "VOP3"
opcode = 133
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GE_I32"
family = "VOP3"
opcode = 134
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LT_U32"
family = "VOP3"
opcode = 193
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_EQ_U32"
family = "VOP3"
opcode = 194
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LE_U32"
family = "VOP3"
opcode = 195
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GT_U32"
family = "VOP3"
opcode = 196
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_NE_U32"
family = "VOP3"
opcode = 197
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GE_U32"
family = "VOP3"
opcode = 198
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_F_I32"
family = "VOP3"
opcode = 128
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_T_I32"
family = "VOP3"
opcode = 135
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_F_U32"
family = "VOP3"
opcode = 192
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_T_U32"
family = "VOP3"
opcode = 199
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- VOP3 encoding variants of registry forms (#215) ----
# An [[encoding_variant]] re-encodes a form declared in another family file: it
# names the form (`of`), this family, the XML opcode here and the operand rule
@@ -37,3 +233,130 @@ spec = [
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
# applies to floating-point results (6.2.2). These integer forms use neither.
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
# (6.5), which these registry forms do not declare. SGPR, inline and literal
# sources remain outside this operand rule.
[[encoding_variant]]
of = "V_MUL_I32_I24"
family = "VOP3"
opcode = 265
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 131 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_HI_I32_I24"
family = "VOP3"
opcode = 266
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_U32_U24"
family = "VOP3"
opcode = 267
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_HI_U32_U24"
family = "VOP3"
opcode = 268
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MIN_I32"
family = "VOP3"
opcode = 273
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MAX_I32"
family = "VOP3"
opcode = 274
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MIN_U32"
family = "VOP3"
opcode = 275
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MAX_U32"
family = "VOP3"
opcode = 276
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_XNOR_B32"
family = "VOP3"
opcode = 286
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_SUB_NC_U32"
family = "VOP3"
opcode = 294
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_SUBREV_NC_U32"
family = "VOP3"
opcode = 295
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+39 -3
View File
@@ -20,9 +20,22 @@ pub use rdna2::{
};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
VectorSwapOp, VectorUnaryOp,
};
impl VectorAluOp {
/// Whether this encoding takes a per-lane VCC_LO bit.
pub fn reads_vcc(self) -> bool {
self.semantics().carry_in == semantics::CarryIn::Vcc
}
/// Whether this encoding replaces the Wave32 VCC_LO mask.
pub fn writes_vcc(self) -> bool {
self.semantics().vcc == semantics::MaskEffect::LaneMask
}
}
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
@@ -215,6 +228,14 @@ pub enum Instruction {
src0: VectorSource,
src1: u8,
},
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
/// Both sources are VGPR indices.
VectorCompareVop3 {
op: VectorCompareVop3Op,
sdst: u8,
src0: u8,
src1: u8,
},
/// VOP2 32-bit per-lane integer operation from the semantic registry.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
/// `src1` is a VGPR. Inactive lanes keep `dst`.
@@ -297,6 +318,7 @@ impl Instruction {
Self::ScalarImmediate { op, .. } => op.mnemonic(),
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.assembly_name(),
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
Self::VectorAlu { op, .. } => op.assembly_name(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
@@ -381,10 +403,24 @@ impl fmt::Display for Instruction {
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
Self::VectorCompareVop3 {
sdst, src0, src1, ..
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
Self::VectorAlu {
dst, src0, src1, ..
op,
dst,
src0,
src1,
} => {
write!(formatter, " v{dst}, {src0}, v{src1}")
write!(formatter, " v{dst}, ")?;
if op.writes_vcc() {
write!(formatter, "vcc_lo, ")?;
}
write!(formatter, "{src0}, v{src1}")?;
if op.reads_vcc() {
write!(formatter, ", vcc_lo")?;
}
Ok(())
}
Self::Branch { target }
| Self::BranchSccZero { target }
+34 -5
View File
@@ -47,7 +47,7 @@ pub enum Operation {
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
/// Compare S0 with S1 under the form's relation; writes only SCC.
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
Compare,
/// Bitwise complement of S0.
Not,
@@ -177,13 +177,35 @@ pub enum Signedness {
Bitwise,
}
/// Whether the operation reads SCC.
/// Per-lane VOP2 operation selected by the semantic registry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorLowering {
/// Two explicit operands, with no implicit lane input.
Binary(VectorBinary),
/// Two explicit operands and the lane's VCC bit.
Vcc(VectorVcc),
}
/// VOP2 primitives with an implicit per-lane VCC input.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorVcc {
/// Choose S1 when the VCC bit is set, otherwise S0.
Select,
/// Unsigned addition with carry-in and carry-out.
AddCarry,
/// Unsigned subtraction with borrow-in and borrow-out.
SubtractBorrow,
}
/// Implicit condition or carry input.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// SCC is not read.
/// No implicit condition or carry input.
None,
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
Scc,
/// Per-lane Wave32 VCC_LO bit.
Vcc,
}
/// What a form writes to SCC.
@@ -205,7 +227,7 @@ pub enum SccEffect {
SelectedSrc0,
}
/// What a form writes to VCC or EXEC.
/// Where a form writes its lane mask, if any.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MaskEffect {
/// Not written.
@@ -214,6 +236,8 @@ pub enum MaskEffect {
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
/// it (docs/shaders/vector-compare.md section 3).
LaneMask,
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
SdstLaneMask,
}
/// Wave-size restriction.
@@ -266,10 +290,15 @@ pub enum OperandRule {
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
/// rejected as unsupported.
Vop3Vgpr2,
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
/// VGPRs, SRC2 is unused and all modifiers are clear.
Vop3CmpVgpr2,
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
/// rejected as unsupported.
Vop2Vgpr,
/// VOP2 general SRC0 and VGPR VSRC1 with an implicit VCC_LO input.
Vop2Vcc,
/// 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,
@@ -341,7 +370,7 @@ pub struct FormSemantics {
pub relation: Option<CompareRelation>,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
/// Implicit VCC write or explicit scalar destination for a compare mask.
pub vcc: MaskEffect,
/// EXEC write.
pub exec: MaskEffect,
File diff suppressed because it is too large. Load diff
+40 -3
View File
@@ -2,11 +2,12 @@
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
Signedness, Wave,
};
use xenora_isa::{
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
};
#[test]
@@ -261,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
assert_eq!(row.swap_sources, base.swap_sources);
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
}
for base_op in VectorCompareOp::ALL {
let base = base_op.semantics();
let mut variants = VectorCompareVop3Op::ALL
.into_iter()
.filter(|op| op.base() == base_op);
if base.width != 32 {
assert_eq!(variants.next(), None, "{}", base.name);
continue;
}
let op = variants
.next()
.expect("32-bit VOPC form must have a VOP3A encoding");
assert_eq!(variants.next(), None);
let row = op.semantics();
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
assert_eq!(row.operation, base.operation);
assert_eq!(row.signedness, base.signedness);
assert_eq!(row.relation, base.relation);
assert_eq!(row.scc, SccEffect::Unchanged);
assert_eq!(row.exec, MaskEffect::Unchanged);
assert_eq!(row.wave, Wave::Wave32);
assert_eq!(row.width, 32);
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
}
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
let alu = VectorAluVop3Op::from_word(word);
let compare = VectorCompareVop3Op::from_word(word);
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
alu.map(|op| op.semantics().name)
.or_else(|| compare.map(|op| op.semantics().name))
});
// No first word of the other 64-bit families (VOP3B shares VOP3's
// encoding bits) selects a variant.
@@ -276,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
"{}",
meta.name
);
assert_eq!(
VectorCompareVop3Op::from_word(meta.bits as u32),
None,
"{}",
meta.name
);
}
}
+1
View File
@@ -16,6 +16,7 @@ gpu-tests = []
[dependencies]
libc = "0.2"
sha2 = "0.10"
xenora-texture = { path = "../texture" }
[dev-dependencies]
xenora-metal = { path = "../metal" }
File diff suppressed because it is too large. Load diff
+234 -1
View File
@@ -163,7 +163,6 @@ pub fn apply_relocations(
let reloc_type = (entry_val >> 12) as u8;
let offset_in_page = (entry_val & 0x0FFF) as u32;
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
report.total_entries += 1;
match reloc_type {
@@ -221,6 +220,17 @@ pub fn apply_relocations(
read_bytes += block_size as usize;
}
// Only these two types can reach a successful return. Build the public
// histogram once instead of searching its tree for every relocation.
for (kind, count) in [
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
] {
if count != 0 {
report.type_counts.insert(kind, count);
}
}
Ok(report)
}
@@ -274,3 +284,226 @@ fn find_reloc_directory(
Ok(Some((reloc_rva, reloc_size)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryPermissions;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const PREFERRED: u64 = 0x140000000;
const LOADED: u64 = PREFERRED + 0x200000;
const DATA_RVA: u32 = 0x1000;
const DIRECTORY_RVA: u32 = 0x10000000;
const DIRECTORY_OFFSET: usize = 0x200;
// Original synthetic directory, laid out from Microsoft's PE Format,
// .reloc section: eight-byte block headers and two-byte type/offset words.
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
// Header fields and metadata are supplied directly: PE parsing is not timed.
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
for (page, entries) in blocks {
bytes.extend_from_slice(&page.to_le_bytes());
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
for entry in entries {
bytes.extend_from_slice(&entry.to_le_bytes());
}
}
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
let pe = ParsedPe {
machine: 0x8664,
number_of_sections: 1,
time_date_stamp: 0,
image_base: PREFERRED,
section_alignment: 4096,
file_alignment: 512,
size_of_image: DIRECTORY_RVA + size.max(4096),
size_of_headers: 512,
entry_point_rva: 0,
sections: vec![PeSection {
name: ".reloc".into(),
virtual_address: DIRECTORY_RVA,
virtual_size: size,
raw_data_ptr: DIRECTORY_OFFSET as u32,
raw_data_size: size,
characteristics: 0x40000040,
permissions: MemoryPermissions::READ_ONLY,
}],
};
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
LOADED + u64::from(DATA_RVA),
data.len(),
MemoryPermissions::READ_ONLY,
data,
)
.unwrap();
(pe, bytes, memory)
}
#[test]
fn counts_padding_and_rebases_read_only_targets() {
for (preferred, initial, expected) in [
(PREFERRED, 0x140001234, 0x140201234),
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
(LOADED - 8, u64::MAX - 3, 4),
(LOADED + 8, 3, u64::MAX - 4),
] {
let (mut pe, bytes, mut memory) =
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
pe.image_base = preferred;
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
assert_eq!(report.total_entries, 2);
assert_eq!(report.applied_dir64, 1);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
}
}
#[test]
fn histogram_omits_types_that_did_not_occur() {
for (entries, counts) in [
(vec![], BTreeMap::new()),
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
] {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(report.type_counts, counts);
}
}
#[test]
fn preserves_duplicate_and_overlapping_entry_order() {
let (pe, bytes, mut memory) = fixture(
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
&[0; 16],
);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
// Two additions of 0x200000 at offset zero, then one at offset four.
let mut actual = [0; 16];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(
actual,
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
}
#[test]
fn overlapping_fields_observe_prior_carries_in_directory_order() {
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
for (entries, expected) in [
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
] {
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
pe.image_base = LOADED - 1;
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
let mut actual = [0; 12];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(actual, expected);
}
}
#[test]
fn preserves_prior_writes_and_rejects_unsupported_types() {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
assert_eq!(
apply_relocations(&pe, &bytes, LOADED, &mut memory),
Err(RelocationError::UnsupportedRelocationType(15))
);
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
}
#[test]
fn zero_delta_keeps_the_empty_report_without_parsing() {
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
pe.image_base = LOADED;
assert_eq!(
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
RelocationReport::default()
);
}
#[test]
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
fn relocation_profile() {
for pages in [1u32, 128] {
for padding_every in [0usize, 2, 1] {
let blocks: Vec<_> = (0..pages)
.map(|page| {
let entries = (0..512)
.map(|slot| {
let padding = padding_every != 0 && slot % padding_every == 0;
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
})
.collect();
(DATA_RVA + page * 4096, entries)
})
.collect();
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
let mut samples = Vec::new();
for run in 0..36 {
let mut memory = initial.clone();
let start = Instant::now();
let report = black_box(
apply_relocations(
black_box(&pe),
black_box(&bytes),
LOADED,
black_box(&mut memory),
)
.unwrap(),
);
let elapsed = start.elapsed().as_secs_f64() * 1e6;
assert_eq!(report.total_entries, pages as usize * 512);
let padding = match padding_every {
0 => 0,
2 => report.total_entries / 2,
_ => report.total_entries,
};
assert_eq!(report.skipped_absolute, padding);
assert_eq!(report.applied_dir64, report.total_entries - padding);
// Check every output against the fixture's independently specified pattern.
for slot in 0..pages as usize * 512 {
let expected = if padding_every != 0 && slot % padding_every == 0 {
0
} else {
0x200000
};
assert_eq!(
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
expected
);
}
if run >= 5 {
samples.push(elapsed);
}
}
samples.sort_by(f64::total_cmp);
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
let variance =
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
println!(
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
samples.len(),
samples[samples.len() / 2],
samples[0],
samples[samples.len() - 1]
);
}
}
}
}
File diff suppressed because it is too large. Load diff
+76 -27
View File
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, VecDeque};
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
@@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const MAX_IN_FLIGHT: usize = 16;
const MAX_CACHED_PIPELINES: usize = 16;
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
struct CachedPipeline {
source: Box<str>,
entry: Box<str>,
shader_validation: bool,
pipeline: ComputePipeline,
}
const BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -148,7 +158,9 @@ impl std::error::Error for MetalError {}
/// measure a single submission and are not a benchmark distribution.
#[derive(Debug, Clone)]
pub struct RunProfile {
/// Host library compilation time, or zero when reusing a compute pipeline.
pub library_seconds: f64,
/// Host pipeline creation time, or zero when reusing a compute pipeline.
pub pipeline_seconds: f64,
pub gpu_seconds: f64,
/// Host wall time from the start of setup until wait observes completion.
@@ -171,6 +183,8 @@ pub struct NativeCompute {
device: Retained<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
submissions: Mutex<SubmissionTable>,
// Least recently used first. In-flight submissions retain their own reference.
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
}
/// A submitted dispatch whose result can be collected by its issuing context.
@@ -247,7 +261,7 @@ struct SubmissionEntry {
/// Metal reports Completed or Error.
struct InFlightResources {
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_pipeline: ComputePipeline,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
@@ -348,6 +362,7 @@ impl NativeCompute {
device,
queue,
submissions: Mutex::default(),
compute_pipelines: Mutex::default(),
})
})
}
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
self.run_profiled_words(source, entry, input, Some(width))
}
/// Compile the kernel and report the smaller of the device and pipeline width limits.
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
@@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
validate_source(source, &[entry])?;
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(source, &options)?;
let function = find_function(&library, entry)?;
let pipeline = self.compute_pipeline(&function)?;
verify_shader_validation(&pipeline)?;
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
@@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
host_start: Instant,
) -> Result<Submission<'_>, MetalError> {
self.submissions().check_capacity()?;
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self.compute_pipeline(&function)?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let (pipeline, library_seconds, pipeline_seconds) =
self.prepare_compute_pipeline(source, entry)?;
let limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
@@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
fn prepare_compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
self.device
.newComputePipelineStateWithFunction_error(function)
source: &str,
entry: &str,
) -> Result<(ComputePipeline, f64, f64), MetalError> {
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
// Device identity is fixed by this context. All misses use the same
// compile options (safe math, precise functions, default language,
// no macros) and unspecialized functions. Any configurable options
// must become part of the key before they are used here.
let mut cache = self
.compute_pipelines
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(index) = cache.iter().position(|cached| {
cached.source.as_ref() == source
&& cached.entry.as_ref() == entry
&& cached.shader_validation == shader_validation
}) {
let cached = cache.remove(index).expect("position in the locked cache");
let pipeline = cached.pipeline.clone();
cache.push_back(cached);
return Ok((pipeline, 0.0, 0.0));
}
// Serialize cache misses in this context so concurrent requests for
// one key share the same build. The submission table is unlocked here.
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self
.device
.newComputePipelineStateWithFunction_error(&function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})
})?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
if shader_validation {
verify_shader_validation(&pipeline)?;
}
// Bound owned key text to 1 MiB. A valid oversized key can run
// uncached, so this budget does not alter source or entry validation.
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
if cache.len() == MAX_CACHED_PIPELINES {
cache.pop_front();
}
cache.push_back(CachedPipeline {
source: source.into(),
entry: entry.into(),
shader_validation,
pipeline: pipeline.clone(),
});
}
Ok((pipeline, library_seconds, pipeline_seconds))
}
fn pipeline_group_width_limit(
@@ -1232,10 +1285,6 @@ fn check_command_status(
fn verify_shader_validation(
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> Result<(), MetalError> {
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
return Ok(());
}
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
return Err(MetalError::new(
"shaderValidation",
+39 -3
View File
@@ -101,7 +101,43 @@ impl NativeCompute {
colors,
[width, height],
clear,
sampled,
sampled.map(|(texture, sampler)| (texture.raw(), sampler)),
)
.map(|(pixels, _)| pixels)
}
/// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound
/// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the
/// sampler to fragment sampler slot 0.
///
/// # Errors
///
/// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level.
#[allow(clippy::too_many_arguments)]
pub fn render_rgba8_sampled_bc1(
&self,
source: &str,
entries: [&str; 2],
vertices: &[[f32; 4]; 3],
colors: &[[f32; 4]; 3],
extent: [usize; 2],
clear: [u8; 4],
texture: &Bc1Upload<'_>,
sampler: &crate::sampler::MetalSampler,
) -> Result<Vec<u8>, MetalError> {
let level = texture
.subresource(0, 0)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.validate_bc_extent(level.width, level.height, "BC1")?;
let bc1 = self.new_bc1_texture(&level)?;
self.render_rgba8_internal(
source,
entries,
vertices,
colors,
extent,
clear,
Some((&bc1, sampler)),
)
.map(|(pixels, _)| pixels)
}
@@ -116,7 +152,7 @@ impl NativeCompute {
[width, height]: [usize; 2],
clear: [u8; 4],
sampled: Option<(
&crate::texture_pipeline::MetalRgba8Texture,
&ProtocolObject<dyn MTLTexture>,
&crate::sampler::MetalSampler,
)>,
) -> Result<(Vec<u8>, Option<f64>), MetalError> {
@@ -228,7 +264,7 @@ impl NativeCompute {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
if let Some((tex, samp)) = sampled {
encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0);
encoder.setFragmentTexture_atIndex(Some(tex), 0);
encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0);
}
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1};
use super::{context, native};
/// The translated `image_sample_lz` pixel stage samples a native BC1
/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's
/// four blocks selects only its two endpoints, which expand exactly to 0 or
/// 255, so the image is known without a decoder: selector 1 (the second
/// endpoint) where `x == 0 || y == 3` within a block, else selector 0.
#[test]
fn translated_image_sample_lz_reads_bound_bc1_texture() {
let blocks: [[u8; 8]; 4] = [
[0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue
[0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black
[0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta
[0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan
];
let endpoints: [[[u8; 4]; 2]; 4] = [
[[255, 0, 0, 255], [0, 0, 255, 255]],
[[0, 255, 0, 255], [0, 0, 0, 255]],
[[255, 255, 255, 255], [255, 0, 255, 255]],
[[255, 255, 0, 255], [0, 255, 255, 255]],
];
let mut expected = Vec::new();
for y in 0..8 {
for x in 0..8 {
let selector = usize::from(x % 4 == 0 || y % 4 == 3);
expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]);
}
}
for (index, block) in blocks.into_iter().enumerate() {
let (bx, by) = (index % 2 * 4, index / 2 * 4);
for (i, texel) in decode_bc1(block).iter().enumerate() {
let at = ((by + i / 4) * 8 + bx + i % 4) * 4;
assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}");
}
}
let ps: Vec<u8> = [
&[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x
&[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x
&[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y
&[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y
&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz
&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0
&[0x00, 0x00, 0x81, 0xbf], // s_endpgm
]
.concat();
let compiled = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"),
&ps,
)
.expect("compile translated image_sample_lz shader");
let gpu = context();
let upload = Bc1Upload::new(
blocks.as_flattened(),
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload");
let sampler = native(xenora_metal::sampler::MetalSampler::new(
gpu.device(),
SamplerDesc::nearest_clamp(),
));
// Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8).
let positions = [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
];
let uvs = [
[0.0, 1.0, 0.0, 1.0],
[2.0, 1.0, 0.0, 1.0],
[0.0, -1.0, 0.0, 1.0],
];
let pixels = native(gpu.render_rgba8_sampled_bc1(
&compiled.msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&positions,
&uvs,
[8, 8],
[19, 43, 93, 251],
&upload,
&sampler,
));
assert_eq!(pixels, expected);
}
+176
View File
@@ -26,6 +26,8 @@ mod texture_bc_alpha;
mod texture_bc_channel;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_bc1.rs"]
mod translated_bc1;
#[path = "native/translated_render.rs"]
mod translated_render;
@@ -354,6 +356,131 @@ fn multiple_submissions() {
assert_eq!(second, [5, 5, 1, 5]);
}
fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool {
profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0
}
#[test]
fn compute_pipeline_cache_distinguishes_source_entry_and_context() {
let context = context();
let source = fixture("output[id] = input[id] + 1u;");
let second_entry =
fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other(");
let source = format!("{source}\n{second_entry}");
let changed = source.replace("input[id] + 1u", "input[id] - 1u");
let input = [0, 11, u32::MAX];
for (msl, entry, expected) in [
(source.as_str(), "fixture", [1, 12, 0]),
(source.as_str(), "other", [0, 22, u32::MAX - 1]),
(changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]),
] {
let cold = native(context.run_words_profiled(msl, entry, &input));
let warm = native(context.run_words_profiled(msl, entry, &input));
assert!(!pipeline_was_reused(&cold), "{entry}");
assert!(pipeline_was_reused(&warm), "{entry}");
assert_eq!(cold.output, expected, "{entry}");
assert_eq!(warm.output, expected, "{entry}");
}
let separate = native(NativeCompute::new());
let fresh = native(separate.run_words_profiled(&source, "fixture", &input));
assert!(!pipeline_was_reused(&fresh));
assert_eq!(fresh.output, [1, 12, 0]);
for _ in 0..2 {
for (msl, entry, operation) in [
(source.as_str(), "missing", "newFunctionWithName"),
("not valid MSL", "fixture", "newLibraryWithSource"),
] {
let error = context
.run_words_profiled(msl, entry, &input)
.expect_err("invalid pipeline must still fail after warming the cache");
assert_eq!(error.operation, operation);
}
}
let error = context
.run_words_with_group_width(&source, "fixture", &input, 0)
.expect_err("cached pipeline must still check dispatch width");
assert_eq!(error.operation, "threadgroup width");
}
#[test]
fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() {
const SOURCE_LIMIT: usize = 64 * 1024;
let context = context();
let mut source = fixture("output[id] = input[id] ^ 1u;");
source.push_str("\n// ");
source.push_str(&" ".repeat(SOURCE_LIMIT - source.len()));
for _ in 0..2 {
let profile = native(context.run_words_profiled(&source, "fixture", &[8]));
assert_eq!(profile.output, [9]);
assert!(!pipeline_was_reused(&profile));
}
source.push(' ');
let error = context
.run_words_profiled(&source, "fixture", &[8])
.expect_err("source above 64 KiB must fail before pipeline lookup");
assert_eq!(error.operation, "source bounds");
}
#[test]
fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() {
let context = context();
// Seventeen entries in one source fit in Metal's input limit and exceed
// Xenora's 16-pipeline cache. Each kernel writes a distinct result.
let source: String = (0..=16)
.map(|id| {
fixture(&format!("output[id] = input[id] + {id}u;"))
.replace("void fixture(", &format!("void entry{id}("))
})
.collect::<Vec<_>>()
.join("\n");
native(context.max_group_width(&source, "entry0"));
let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7]));
for id in 2..16 {
native(context.max_group_width(&source, &format!("entry{id}")));
}
native(context.max_group_width(&source, "entry0"));
native(context.max_group_width(&source, "entry16"));
gate.open();
let finished = native(context.wait(pending));
assert_eq!(finished.output, [8]);
let recent = native(context.run_words_profiled(&source, "entry0", &[29]));
assert!(pipeline_was_reused(&recent));
assert_eq!(recent.output, [29]);
let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17]));
assert!(!pipeline_was_reused(&rebuilt));
assert_eq!(rebuilt.output, [18]);
}
#[test]
fn simultaneous_compute_submissions_share_one_pipeline_build() {
let context = context();
let source = fixture("output[id] = input[id] ^ 5u;");
let start = std::sync::Barrier::new(4);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..4)
.map(|input| {
let (context, source, start) = (&context, &source, &start);
scope.spawn(move || {
start.wait();
let token = native(context.submit_words(source, "fixture", &[input]));
let result = native(context.wait(token));
assert_eq!(result.output, [input ^ 5]);
usize::from(!pipeline_was_reused(&result))
})
})
.collect();
let builds: usize = workers
.into_iter()
.map(|worker| worker.join().unwrap())
.sum();
assert_eq!(builds, 1);
});
}
#[test]
fn errors_propagate() {
let context = context();
@@ -411,3 +538,52 @@ kernel void fixture(device const uint *input [[buffer(0)]],
}
}
}
#[test]
#[ignore = "manual GPU timing run"]
fn compute_pipeline_reuse_benchmark() {
const WARMUPS: usize = 10;
const SAMPLES: usize = 101;
let warm_context = context();
let device = warm_context.device_name();
let source = fixture("output[id] = input[id] * 7u + 3u;");
let input = mixing_input(131);
let expected: Vec<_> = input
.iter()
.map(|word| word.wrapping_mul(7).wrapping_add(3))
.collect();
let mut timings = [[[0.0; SAMPLES]; 4]; 2];
for round in 0..WARMUPS + SAMPLES {
let cold_context = context();
// Alternate order so neither measurement always follows the other.
let contexts = [&cold_context, &warm_context];
for index in [round % 2, (round + 1) % 2] {
let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input));
assert_eq!(profile.output, expected, "context={index} round={round}");
if round >= WARMUPS {
for (samples, seconds) in timings[index].iter_mut().zip([
profile.library_seconds,
profile.pipeline_seconds,
profile.host_seconds,
profile.gpu_seconds,
]) {
samples[round - WARMUPS] = seconds;
}
}
}
}
for (label, [mut library, mut pipeline, mut host, mut gpu]) in
["fresh context", "repeated context"]
.into_iter()
.zip(timings)
{
println!(
"device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]",
timing_summary(&mut library),
timing_summary(&mut pipeline),
timing_summary(&mut host),
timing_summary(&mut gpu),
);
}
}
+138 -14
View File
@@ -57,6 +57,8 @@ pub enum Op {
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// VOP3A integer compare writing a Wave32 mask to SDST.
CompareVop3(u8, Comparison, CompareSource, u8),
/// VOPC 16- or 64-bit integer compare writing the Wave32 mask to
/// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name
/// the low register of a pair.
@@ -76,7 +78,7 @@ pub enum Op {
},
Vector(VectorAlu, u8, u8, u8),
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
/// integer or literal) and VSRC1, with implicit VCC for select/carry forms.
VectorInteger(VectorInteger, u8, CompareSource, u8),
/// VOP1 32-bit integer or bit form: VDST and SRC0 (VGPR, SGPR, `vcc_lo`,
/// inline integer or literal). Writes neither VCC nor SCC.
@@ -187,6 +189,8 @@ pub enum BranchCondition {
SccZero,
/// Take the branch when the low half of VCC is clear.
VccZero,
/// Take the branch when the low half of VCC is nonzero.
VccNonzero,
/// Take the branch when the low half of EXEC is clear.
ExecZero,
}
@@ -317,6 +321,12 @@ pub enum VectorAlu {
/// section 12.7). None has a carry-in or carry-out.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorInteger {
/// 1: select S1 when the lane's VCC bit is set.
Select,
/// 40: unsigned add with carry input and output.
AddCarry,
/// 41 / 42: unsigned subtract with borrow input and output.
SubtractBorrow { reversed: bool },
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
/// bit 23 when `signed`.
Multiply24 { signed: bool },
@@ -340,6 +350,11 @@ impl VectorInteger {
/// Opcode bits 30-25 of the VOP2 word.
fn from_opcode(opcode: u8) -> Option<Self> {
Some(match opcode {
1 => Self::Select,
40 => Self::AddCarry,
41 | 42 => Self::SubtractBorrow {
reversed: opcode == 42,
},
9 => Self::Multiply24 { signed: true },
10 => Self::MultiplyHigh24 { signed: true },
11 => Self::Multiply24 { signed: false },
@@ -356,6 +371,34 @@ impl VectorInteger {
})
}
fn reads_vcc(self) -> bool {
matches!(
self,
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. }
)
}
fn writes_vcc(self) -> bool {
matches!(self, Self::AddCarry | Self::SubtractBorrow { .. })
}
// Guide 12.7: carry/borrow is determined from the exact mathematical result.
fn apply_vcc(self, a: u32, b: u32, bit: u32) -> (u32, bool) {
match self {
Self::Select => (if bit == 0 { a } else { b }, false),
Self::AddCarry => {
let exact = u64::from(a) + u64::from(b) + u64::from(bit);
(exact as u32, exact > u64::from(u32::MAX))
}
Self::SubtractBorrow { reversed } => {
let (minuend, subtrahend) = if reversed { (b, a) } else { (a, b) };
let exact = i64::from(minuend) - i64::from(subtrahend) - i64::from(bit);
(exact as u32, exact < 0)
}
_ => unreachable!("VOP2 operation does not read VCC"),
}
}
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
fn apply(self, a: u32, b: u32) -> u32 {
let field = |bits: u32, signed: bool| {
@@ -393,6 +436,9 @@ impl VectorInteger {
Self::Add => a.wrapping_add(b),
Self::Subtract => a.wrapping_sub(b),
Self::SubtractReverse => b.wrapping_sub(a),
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. } => {
unreachable!("VOP2 operation requires VCC")
}
}
}
}
@@ -677,7 +723,13 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
left_length.max(right_length),
)
}
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
[
lo,
hi,
opcode @ (0x82 | 0x84 | 0x86 | 0x87 | 0x88),
0xbf,
..,
] => {
let words = i16::from_le_bytes([*lo, *hi]);
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
(
@@ -686,6 +738,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
condition: match opcode {
0x84 => BranchCondition::SccZero,
0x86 => BranchCondition::VccZero,
0x87 => BranchCondition::VccNonzero,
0x88 => BranchCondition::ExecZero,
_ => BranchCondition::Always,
},
@@ -713,9 +766,50 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let src1 = (second >> 1) | ((third & 1) << 7);
(Op::Vector(kind, dst, *first, src1), 4)
}
[dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => {
// Guide §§12.7.1, 12.9.1, 12.12 and 13.3.4: VOP3A extends
// VOP2 by 0x100 and preserves the VOPC opcode. This subset
// fixes unused SRC2 to inline 0 and excludes FP ABS/NEG/OMOD,
// halfword OP_SEL, and CLAMP (integer saturation or FP compare
// exceptions, §6.5).
[
dst,
0,
op,
tag @ (0xd4 | 0xd5),
lo,
middle,
hi @ 2..=3,
0x02,
..,
] if middle & 1 != 0 => {
let src0 = CompareSource::Vector(*lo);
let src1 = (middle >> 1) | ((hi & 1) << 7);
(Op::Add(*dst, *lo, src1), 8)
match tag {
0xd4 if matches!(op, 128..=135 | 192..=199) && *dst <= 106 => (
Op::CompareVop3(
*dst,
Comparison {
offset: op & 7,
signed: *op < 192,
},
src0,
src1,
),
8,
),
0xd5 if *op == 37 => (Op::Add(*dst, *lo, src1), 8),
0xd5 => (
Op::VectorInteger(
VectorInteger::from_opcode(*op)
.ok_or_else(|| error(offset, "unsupported VOP3 opcode"))?,
*dst,
src0,
src1,
),
8,
),
_ => return Err(error(offset, "unsupported VOP3 opcode or destination")),
}
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
@@ -1087,13 +1181,33 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
check(src1)?;
}
let incoming = if exec != 0 && kind.reads_vcc() {
read_scalar(Source::Register(VCC_LO as u8))?
} else {
0
};
let mut outgoing = 0;
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let s0 = match src0 {
CompareSource::Vector(register) => read(lane, register)?,
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
CompareSource::Immediate(bits) => bits,
};
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
let s1 = read(lane, src1)?;
let value = if kind.reads_vcc() {
let (value, carry) = kind.apply_vcc(s0, s1, (incoming >> lane) & 1);
outgoing |= u32::from(carry) << lane;
value
} else {
kind.apply(s0, s1)
};
results[lane] = Some((dst, value));
}
// Guide 3.9: only executing lanes can contribute a carry.
if kind.writes_vcc() {
scalars[VCC_LO] = Some(outgoing);
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
}
}
Op::VectorUnary(kind, dst, src0) => {
@@ -1372,13 +1486,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(..) | Op::WideCompare(..) => {
let (comparison, width, src0, src1) = match op {
Op::Compare(..) | Op::WideCompare(..) | Op::CompareVop3(..) => {
let (dst, comparison, width, src0, src1) = match op {
Op::Compare(comparison, src0, src1) => {
(comparison, CompareWidth::Word, src0, src1)
(VCC_LO, comparison, CompareWidth::Word, src0, src1)
}
Op::CompareVop3(dst, comparison, src0, src1) => {
(usize::from(dst), comparison, CompareWidth::Word, src0, src1)
}
Op::WideCompare(comparison, width, src0, src1) => {
(comparison, width, src0, src1)
(VCC_LO, comparison, width, src0, src1)
}
_ => unreachable!(),
};
@@ -1439,18 +1556,24 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
}
scalars[VCC_LO] = Some(mask);
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
scalars[dst] = Some(mask);
if dst == VCC_LO {
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
}
}
Op::Branch {
target: destination,
condition,
} => {
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
let tests_vcc = matches!(
condition,
BranchCondition::VccZero | BranchCondition::VccNonzero
);
if tests_vcc && scalars[VCC_LO].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if condition == BranchCondition::VccZero && lane_derived_vcc {
if tests_vcc && lane_derived_vcc {
check_runtime_region(
&program[position + 1..],
destination,
@@ -1467,6 +1590,7 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
}
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
BranchCondition::VccNonzero => scalars[VCC_LO] != Some(0),
BranchCondition::ExecZero => exec == 0,
};
if take_branch {
+274 -71
View File
@@ -11,7 +11,8 @@ pub use xenora_decoder::Architecture;
use xenora_decoder::SoppControlOp;
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarUnaryOp, VectorAluOp,
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, VectorUnary,
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorLowering, VectorSource, VectorUnary,
VectorVcc,
};
/// SGPR index of `vcc_lo`.
@@ -100,6 +101,17 @@ enum Op {
inactive: Value,
},
Store(Value),
VccArithmetic {
primitive: VectorVcc,
left: Value,
right: Value,
mask: Value,
flag: bool,
},
CarryMask {
flag: Value,
exec: u32,
},
ScalarBranch {
target: usize,
taken: bool,
@@ -108,6 +120,10 @@ enum Op {
/// The value is wave-uniform; every thread computes it for its own wave.
LaneMask {
op: VectorCompareOp,
/// Assembly name of the decoded encoding (`_e32` or `_e64`).
name: &'static str,
/// The explicit SGPR destination of the VOP3A encoding (IR text only).
sdst: Option<usize>,
src0: Value,
src1: Value,
high: Option<(Value, Value)>,
@@ -147,6 +163,10 @@ impl Op {
operands
}
Self::RuntimeBranch { mask, .. } => vec![mask],
Self::VccArithmetic {
left, right, mask, ..
} => vec![left, right, mask],
Self::CarryMask { flag, .. } => vec![flag],
Self::JoinVccz {
mask,
fallthrough,
@@ -205,8 +225,32 @@ impl Op {
name(fallthrough),
name(taken)
),
Self::VccArithmetic {
primitive,
left,
right,
mask,
flag,
} => {
let (left, right) = (name(left), name(right));
let bit = format!("(({} >> {lane}) & 1u)", name(mask));
// Guide 12.7: widen the carry/borrow check before adding the input bit.
match (primitive, flag) {
(VectorVcc::Select, false) => format!("{bit} != 0u ? {right} : {left}"),
(VectorVcc::AddCarry, false) => format!("{left} + {right} + {bit}"),
(VectorVcc::AddCarry, true) => {
format!("uint((ulong({left}) + ulong({right}) + {bit}) >> 32u)")
}
(VectorVcc::SubtractBorrow, false) => format!("{left} - {right} - {bit}"),
(VectorVcc::SubtractBorrow, true) => {
format!("uint(ulong({right}) + {bit} > ulong({left}))")
}
_ => unreachable!("not a VCC arithmetic operation"),
}
}
Self::Store(_)
| Self::ScalarBranch { .. }
| Self::CarryMask { .. }
| Self::LaneMask { .. }
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
}
@@ -440,7 +484,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
let mut ir = String::new();
let has_mask = operations
.iter()
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. } | Op::CarryMask { .. }));
let grid = if has_mask {
",\n uint grid [[threads_per_grid]]"
} else {
@@ -462,8 +506,8 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
for (index, &(offset, operation)) in operations.iter().enumerate() {
let dest = Value(index);
uniform.push(match operation {
Op::Constant(_) | Op::LaneMask { .. } => true,
Op::Load | Op::MergeLanes { .. } => false,
Op::Constant(_) | Op::LaneMask { .. } | Op::CarryMask { .. } => true,
Op::Load | Op::MergeLanes { .. } | Op::VccArithmetic { .. } => false,
_ => operation.operands().iter().all(|value| uniform[value.0]),
});
let thread = |value: Value| value.to_string();
@@ -526,13 +570,52 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::VccArithmetic {
primitive,
left,
right,
mask,
flag,
} => (
format!(
"{dest} = vcc.{primitive:?}{suffix} {left}, {right}, {mask}",
suffix = if flag { ".flag" } else { "" }
),
format!(
"uint {dest} = {};",
operation.expression(&thread, "", "(index & 31u)")
),
),
Op::CarryMask { flag, exec } => {
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.carry {flag} exec=0x{exec:08x}"
);
emit_lane_mask(
&mut msl,
&operations,
&uniform,
index,
exec,
vec![flag],
|name| name(flag),
);
continue;
}
Op::LaneMask {
op,
name,
sdst,
src0,
src1,
high,
exec,
} => {
let target = match sdst {
None => String::new(),
Some(VCC_LO) => " -> vcc_lo".to_string(),
Some(register) => format!(" -> s{register}"),
};
let (left, right) = if let Some((hi0, hi1)) = high {
(format!("{src0}:{hi0}"), format!("{src1}:{hi1}"))
} else {
@@ -540,10 +623,35 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
};
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.mask {} {left}, {right} exec=0x{exec:08x}",
op.assembly_name()
"{offset:04x}: {dest} = wave.mask {name} {left}, {right}{target} exec=0x{exec:08x}"
);
let inputs = if matches!(
op.relation(),
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
) {
Vec::new()
} else {
operation.operands()
};
emit_lane_mask(
&mut msl,
&operations,
&uniform,
index,
exec,
inputs,
|name| {
let (left, right) = if let Some((hi0, hi1)) = high {
let pair = |lo, hi| {
format!("((ulong({}) << 32u) | ulong({}))", name(hi), name(lo))
};
(pair(src0, hi0), pair(src1, hi1))
} else {
(name(src0), name(src1))
};
format!("({}) ? 1u : 0u", compare_expression(op, &left, &right))
},
);
emit_lane_mask(&mut msl, &operations, &uniform, index, operation);
continue;
}
Op::Store(value) => (
@@ -563,7 +671,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
})
}
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
/// Emit a Wave32 predicate mask without any cross-thread operation: the thread
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
/// Absent lanes of a final partial wave contribute 0.
@@ -572,28 +680,11 @@ fn emit_lane_mask(
operations: &[(usize, Op)],
uniform: &[bool],
index: usize,
operation: Op,
exec: u32,
mut pending: Vec<Value>,
predicate: impl FnOnce(&dyn Fn(Value) -> String) -> String,
) {
let Op::LaneMask {
op,
src0,
src1,
high,
exec,
} = operation
else {
unreachable!("expected a lane mask")
};
let mut cone = vec![false; index];
// F and T do not depend on the operands, so their lanes compute none.
let mut pending = if matches!(
op.relation(),
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
) {
Vec::new()
} else {
operation.operands()
};
while let Some(value) = pending.pop() {
if uniform[value.0] || cone[value.0] {
continue;
@@ -623,16 +714,10 @@ fn emit_lane_mask(
);
}
}
let (left, right) = if let Some((hi0, hi1)) = high {
let pair = |lo, hi| format!("((ulong({}) << 32u) | ulong({}))", name(hi), name(lo));
(pair(src0, hi0), pair(src1, hi1))
} else {
(name(src0), name(src1))
};
let _ = writeln!(
msl,
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
compare_expression(op, &left, &right)
" uint pass = {};\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
predicate(&name)
);
}
@@ -646,6 +731,13 @@ fn decode_fixture(
xenora_decoder::decode(architecture, bytes).map_err(CompileError::Decode)
}
#[derive(Clone, Copy)]
enum ScalarValue {
Uninitialized,
Known(u32),
RuntimeMask,
}
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
let mut operations = Vec::new();
let mut registers = [None::<Value>; 256];
@@ -653,12 +745,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let mut pending_load = None;
let mut stored = false;
let mut store_pending = false;
let mut scalars = [None; 128];
let mut scalars = [ScalarValue::Uninitialized; 128];
let mut exec = u32::MAX; // The fixture starts with full Wave32 EXEC.
scalars[126] = Some(exec);
scalars[126] = ScalarValue::Known(exec);
let mut scc = None;
let mut skip_before = 0;
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
// VCC_LO can forward a lane-derived mask to its supported runtime consumers.
let mut lane_vcc: Option<Value> = None;
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
@@ -790,11 +882,15 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
}
let read_scalar = |source| match source {
ScalarSource::Immediate(value) => Ok(value),
ScalarSource::Register(register) => scalars
.get(usize::from(register))
.copied()
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
ScalarSource::Register(register) => match scalars.get(usize::from(register)) {
Some(ScalarValue::Known(value)) => Ok(*value),
Some(ScalarValue::RuntimeMask) => Err(error(
"scalar source reads a runtime-only SGPR compare mask",
)),
Some(ScalarValue::Uninitialized) | None => {
Err(error("scalar source has no known value"))
}
},
};
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
Ok(match source {
@@ -802,8 +898,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
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) => {
(None, ScalarValue::Known(bits)) => {
constant(operations, facts, offset, bits)
}
(None, _) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
@@ -818,6 +916,13 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
// Scalar instructions and waits still execute when all lanes are inactive.
if exec == 0 {
match instruction.instruction {
Instruction::VectorAlu { op, .. } if op.writes_vcc() => {
// Guide 3.9: inactive lanes contribute zero to carry-out.
lane_vcc = None;
scalars[VCC_LO] = ScalarValue::Known(0);
scalars[VCC_HI] = ScalarValue::Uninitialized;
continue;
}
Instruction::MoveB32 { .. }
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorAddF32 { .. }
@@ -836,6 +941,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
{
return Err(error("vector memory requires full Wave32 EXEC"));
}
if let Instruction::BufferLoadDword { resource, .. }
| Instruction::BufferStoreDword { resource, .. } = instruction.instruction
{
let start = usize::from(resource);
if scalars[start..start + 4]
.iter()
.any(|value| matches!(value, ScalarValue::RuntimeMask))
{
return Err(error(
"resource descriptor reads a runtime-only SGPR compare mask",
));
}
}
let next = Value(operations.len());
let (dest, operation) = match instruction.instruction {
Instruction::BufferLoadDword { data, .. } => {
@@ -928,10 +1046,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
} else {
(read(src0)?, read(src1)?)
};
(
Some(dst),
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
let VectorLowering::Binary(binary) = op.lowering() else {
return Err(error("VOP3 with a lane condition is unsupported"));
};
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
}
Instruction::ScalarUnary {
op: op @ ScalarUnaryOp::MovB32,
@@ -951,7 +1069,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
continue;
}
Instruction::ScalarUnary { op, dst, src } => {
@@ -963,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
if let Some(flag) = flag {
scc = Some(flag);
}
@@ -988,7 +1106,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
if let Some(flag) = flag {
scc = Some(flag);
}
@@ -1012,13 +1130,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
let old = if op.reads_dst() {
slot.ok_or_else(|| error("SOPK reads an uninitialized SGPR"))?
match *slot {
ScalarValue::Known(value) => value,
ScalarValue::RuntimeMask => {
return Err(error("SOPK reads a runtime-only SGPR compare mask"));
}
ScalarValue::Uninitialized => {
return Err(error("SOPK reads an uninitialized SGPR"));
}
}
} else {
0
};
let (value, flag) = op.evaluate(old, simm16, scc_in);
if let Some(value) = value {
*slot = Some(value);
*slot = ScalarValue::Known(value);
}
if let Some(flag) = flag {
scc = Some(flag);
@@ -1030,11 +1156,36 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
Instruction::VectorCompare { op, src0, src1 } => {
// Both encodings share the Wave32 lane mask implementation.
compare @ (Instruction::VectorCompare { .. }
| Instruction::VectorCompareVop3 { .. }) => {
let (op, name, explicit, sdst, src0, src1) = match compare {
Instruction::VectorCompare { op, src0, src1 } => {
(op, op.assembly_name(), false, VCC_LO, src0, src1)
}
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
} => (
op.base(),
op.assembly_name(),
true,
usize::from(sdst),
VectorSource::Register(src0),
src1,
),
_ => unreachable!("only vector compares reach this arm"),
};
if exec == 0 {
scalars[VCC_HI] = None;
scalars[VCC_LO] = Some(0);
lane_vcc = None;
if sdst == VCC_LO {
scalars[VCC_HI] = ScalarValue::Uninitialized;
scalars[VCC_LO] = ScalarValue::Known(0);
lane_vcc = None;
} else {
scalars[sdst] = ScalarValue::RuntimeMask;
}
continue;
}
let constant =
@@ -1066,8 +1217,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
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, bits),
(None, None) => {
(None, ScalarValue::Known(bits)) => {
constant(&mut operations, &mut facts, bits)
}
(None, _) => {
return Err(error("compare reads uninitialized VCC_LO"));
}
}
@@ -1084,6 +1237,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
offset,
Op::LaneMask {
op,
name,
sdst: explicit.then_some(sdst),
src0,
src1,
high,
@@ -1091,9 +1246,13 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
},
));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = None;
scalars[VCC_HI] = None;
lane_vcc = Some(mask);
if sdst == VCC_LO {
scalars[VCC_LO] = ScalarValue::Uninitialized;
scalars[VCC_HI] = ScalarValue::Uninitialized;
lane_vcc = Some(mask);
} else {
scalars[sdst] = ScalarValue::RuntimeMask;
}
continue;
}
Instruction::Branch { .. }
@@ -1140,9 +1299,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
error("conditional branch reads uninitialized SCC")
})?,
SoppControlOp::BranchVccZero => {
scalars[106].ok_or_else(|| {
error("conditional branch reads uninitialized VCC_LO")
})? == 0
let ScalarValue::Known(bits) = scalars[VCC_LO] else {
return Err(error(
"conditional branch reads uninitialized VCC_LO",
));
};
bits == 0
}
SoppControlOp::BranchExecZero => exec == 0,
SoppControlOp::WaitLoad | SoppControlOp::EndProgram => {
@@ -1170,10 +1332,51 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
} else {
(src0, src1)
};
(
Some(dst),
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
match op.lowering() {
VectorLowering::Binary(binary) => {
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
}
VectorLowering::Vcc(primitive) => {
let mask = match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, ScalarValue::Known(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, _) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
};
if op.writes_vcc() {
let flag = Value(operations.len());
operations.push((
offset,
Op::VccArithmetic {
primitive,
left,
right,
mask,
flag: true,
},
));
facts.push(KnownBits::UNKNOWN);
lane_vcc = Some(Value(operations.len()));
operations.push((offset, Op::CarryMask { flag, exec }));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = ScalarValue::Uninitialized;
scalars[VCC_HI] = ScalarValue::Uninitialized;
}
(
Some(dst),
Op::VccArithmetic {
primitive,
left,
right,
mask,
flag: false,
},
)
}
}
}
Instruction::VectorUnary { op, dst, src } => {
let source = read_vector(src, &mut operations, &mut facts)?;
+146
View File
@@ -14,6 +14,110 @@ fn compiles_original_fixture() {
);
}
#[test]
fn vop3_compare_to_vcc_lo_drives_a_runtime_vccz_branch() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xd4c2_006a, // v_cmp_eq_u32_e64 vcc_lo, v1, v2
0x0202_0501,
0xbf86_0001, // s_cbranch_vccz 1
0x7e02_0302, // v_mov_b32_e32 v1, v2
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert!(
shader
.disassembly
.contains("v_cmp_eq_u32_e64 vcc_lo, v1, v2")
);
assert!(shader.ir.contains("0008: t2 = wave.mask"));
assert!(shader.ir.contains("0010: branch.vccz t2 -> 0x0018"));
assert!(shader.ir.contains("join.vccz t2"));
assert!(shader.msl.contains("lane_index >= grid"));
}
#[test]
fn vop3_compare_to_s4_rejects_later_scalar_reads() {
for (setup, offset) in [
(&[0x7e02_0281u32, 0x7e04_0282][..], 16), // Initialize both VGPRs.
(&[0xbefe_0380][..], 12), // Empty EXEC. The VGPRs need not be initialized.
] {
let code: Vec<_> = setup
.iter()
.copied()
.chain([
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
0x0202_0501,
0xbf06_8004, // s_cmp_eq_u32 s4, 0
0xbefe_03c1, // s_mov_b32 exec_lo, -1
0x7e02_0281, // v_mov_b32_e32 v1, 1
])
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let error = compile(Architecture::Gfx1030, &code).unwrap_err();
assert!(
matches!(
error,
CompileError::Verify {
offset: actual,
reason: "scalar source reads a runtime-only SGPR compare mask",
} if actual == offset
),
"{error}"
);
}
}
#[test]
fn vop3_compare_mask_cannot_be_read_as_a_buffer_descriptor() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
0x0202_0501,
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify {
offset: 16,
reason: "resource descriptor reads a runtime-only SGPR compare mask",
})
));
}
#[test]
fn vop3_compare_to_normal_sgpr_preserves_vcc_and_can_be_overwritten() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xbeea_0381, // s_mov_b32 vcc_lo, 1
0xd4c2_0008, // v_cmp_eq_u32_e64 s8, v1, v2
0x0202_0501,
0xbf86_0001, // s_cbranch_vccz 1
0xbe88_0381, // s_mov_b32 s8, 1
0xbf06_8008, // s_cmp_eq_u32 s8, 0
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert!(
shader
.ir
.contains("0014: branch.uniform 0x001c taken=false")
);
}
#[test]
fn load_wait_is_required_before_using_loaded_data() {
let mut code = FIXTURE.to_vec();
@@ -364,6 +468,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() {
);
}
#[test]
fn vop3_integer_forms_lower_to_per_lane_templates() {
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vop3-integer.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vop3-integer.metal")
);
}
#[test]
fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin");
@@ -392,6 +510,34 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
);
}
#[test]
fn vop3_compare_forms_lower_to_wave_masks() {
let code = include_bytes!("../../../fixtures/rdna2/vop3-compare.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vop3-compare.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vop3-compare.metal")
);
}
#[test]
fn vector_vcc_fixture_matches_ir_and_msl_goldens() {
let code = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
let result = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
result.ir,
include_str!("../../../fixtures/golden/vector-vcc.ir")
);
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/vector-vcc.metal")
);
}
#[test]
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
+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.
- [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.
- [VOP2 select and carry](shaders/vector-vcc.md) — Wave32 lane selection, carry and borrow through the vector condition code.
- [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: 154 of 154. Accepted Metal forms · Apple M5: 18 of 154. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. 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">154 / 154</text>
<text x="510" y="58" font-size="13" text-anchor="end">185 / 185</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 / 154</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 185</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="57.27" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="47.68" 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

+44
View File
@@ -498,3 +498,47 @@ compare function. Colour and the stored depth are both read back.
These passes are checked on the GPU with Metal validation against expectations
derived independently from the public semantics; synthetic fixtures only.
### Guest texture binding (descriptor tables)
`GraphicsContext` lets a guest command list sample one texture in the pixel
stage through a D3D12-shaped binding. A draw samples only if a root signature
is bound. Draws without one keep the flat-colour path. The supported subset
is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the
object is created, or with an error at execution. A rejected draw never
reaches the backend. Draws recorded before it in the same list have already
run.
| Object | Supported |
| --- | --- |
| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. |
| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. |
| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. |
| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. |
| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. |
| `cmd_set_descriptor_heaps` | At most one heap of each type. |
| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. |
Descriptor handles follow D3D12 pointer arithmetic: the heap start plus
`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the
value). `offset` returns `None` rather than carry into the next heap. CPU and
GPU handles are separate spaces. A textured draw is a `DrawInstanced` of
one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or
instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes
`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position
at byte 0 and a float4 texture coordinate at byte 16, with a stride of at
least 32. Textured indexed draws are unsupported.
The native backend receives a `TexturedDraw` with the bound level and must
bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of
the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1`
binds a BC1 level natively for that purpose. The software reference has no
clipping or depth test. A pixel is covered when its centre lies inside or on
an edge of the triangle. The texture coordinate is interpolated affinely, so
`w = 1` is required, and point sampled with
`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the
spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two
interpolated palette entries differently (171/84 against 170/85, measured
on an M5 Pro), so the tests use endpoint colours only. Pipeline
state objects do not exist yet, so the backend, not the guest, chooses the
pixel shader. These entry points are not yet wired to guest imports.
+34 -3
View File
@@ -17,6 +17,33 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry) | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
| `v_mul_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_xnor_b32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_sub_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_subrev_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_gt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ne_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ge_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_f_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_gt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ne_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ge_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_f_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
| `s_endpgm` | SOPP, zero immediate (semantic registry) | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
@@ -167,16 +194,20 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_add_nc_u32_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 = S0 + S1, no carry | `4A160F06` | 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_sub_nc_u32_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 = S0 - S1, no carry | `4C181308` | 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_subrev_nc_u32_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 = S1 - S0, no carry | `4E1A170A` | 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_cndmask_b32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; select S1 when the VCC_LO lane bit is set, otherwise S0 | `020402C1` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_add_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned addition with carry input and output | `50040481` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_sub_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S0 minus S1 with borrow input and output | `52060480` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_subrev_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S1 minus S0 with borrow input and output | `540606C2` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
<!-- status:instructions:end -->
## Automated three-way comparison
LLVM 23.1.6, the production decoder and the independent reference decoder
matched 650 instructions across ten streams: the eight synthetic fixtures,
matched 1,088 instructions across 18 streams: 16 synthetic fixtures,
a high-register sequence and an operand matrix assembled by LLVM.
The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic
and operands, and the typed reference operation against the production
operation. It covers all 42 compute forms in this document.
operation. It covers 124 instruction forms.
The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and
SOP2, forced literals that could otherwise be inline, literal selection in
@@ -186,7 +217,7 @@ operands, and zero and nonzero forward branch displacements. The decoder
trace exposes MUBUF operands independently of the synthetic execution ABI,
which still requires the original index and resource bindings.
Five malformed LLVM probes produced diagnostics, and 25 valid encodings
Five malformed LLVM probes produced diagnostics, and 27 valid encodings
or disassemblable branch sequences were deliberately rejected by both Xenora
decoders. Both Xenora decoders also reject all 37 interior truncation offsets
in the add fixture and every case in the unsupported-encoding list.
+5 -3
View File
@@ -31,12 +31,12 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| SOPP | 36 | 6 | 6 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 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 |
| VOP2 | 47 | 24 | 22 | 24 | 24 | 24 | 7 | 7 | 11 |
| VOP3 | 416 | 28 | 28 | 28 | 28 | 28 | 1 | 1 | 17 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 28 | 44 | 44 | 44 | 44 | 0 | 0 | 9 |
| **Total** | 1465 | 138 | 148 | 158 | 154 | 154 | 18 | 18 | 78 |
| **Total** | 1465 | 169 | 179 | 189 | 185 | 185 | 18 | 18 | 83 |
## Unsupported operand variants
@@ -55,8 +55,10 @@ The table counts distinct variant names per family across registry operand rules
| SOPP | `sopp_wait` | None listed |
| 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_vcc` | `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_cmp_vgpr2` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc_hi`, `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOPC | `vopc_vcc_half` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
+30 -16
View File
@@ -48,20 +48,19 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields:
| `of` | The `name` of the declared base form |
| `family` | The encoding family of this variant; must differ from the form's |
| `opcode` | The XML opcode in that family |
| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) |
| `operands` | An operand rule of that family that can encode the base form (`vop3_vgpr2` for VOP2 vector forms, `vop3_cmp_vgpr2` for VOPC integer compares) |
| `spec`, `verify` | As for a form |
Everything else (operation, signedness, effects, source order) is inherited
from the base form, and the XML check runs on that inherited declaration with
the variant's family, opcode and operand rule, so the VOP3 operand widths and
formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for
`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding
The variant inherits the operation, signedness, source order and SCC and EXEC
effects. Its operand rule determines where the result is written. The XML
check uses the variant's family, opcode and operand rule to validate the
inherited declaration. The generator emits one enum per variant rule
(`VectorAluVop3Op` or `VectorCompareVop3Op`) with `from_word` (encoding
bits, then an explicit match on the OP field), `base()` (the inherited form),
`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the
forms. Because the enum has no undeclared members, an instruction cannot name a
VOP3 encoding that does not exist. Every explicit XML operand of the variant,
destination included, must have the data format of the base operand in the same
role (destination, then the sources in rule order). A variant-only rule says so
VOP3 encoding that does not exist. Corresponding explicit XML operands must
have the same data format by role. A variant-only rule says so
in the data (`variant_only = true`), so the RDNA2 planner does not count it as a
rule that can host new forms. A
variant-only rule (one marked `variant_of` in the generator) cannot be used by a
@@ -75,7 +74,15 @@ the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and
NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its
first variant; adding the VOP3 encoding of another VOP2 form under this rule is
one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline
sources, legal modifiers) come with the VOP3 batch.
sources, legal modifiers) need separate rules.
`vop3_cmp_vgpr2` uses the same VGPR source and modifier restrictions and
specifies a scalar destination. It requires a base form with a `lane_mask`
write to implicit VCC, and generates an `sdst_lane_mask` effect on the
variant row. The generator checks the base VCC output and the variant's
explicit scalar mask destination against the XML. An SDST of 106 selects
`vcc_lo`. See [the compare contract](vector-compare.md#11-vop3a-encoding-_e64)
for Wave32 lowering and allowed consumers.
## Fields
@@ -111,7 +118,7 @@ error.
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` (SOP1 and SOPK), `cmov` (SOPK only), `compare` and the SOP1 unaries |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
| `carry_in` | Implicit carry, borrow or select input | `none`, `scc` for unsigned scalar `add` and `sub` and required for scalar `cselect`, `vcc` for the Wave32 VOP2 select and carry forms |
| `width` | Operand and result width in bits (operand width for compares) | `32`, `16` with `vopc_vcc_half`, or `64` with `vopc_vcc_pair` |
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
@@ -119,8 +126,8 @@ error.
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC 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` for SOPP controls, VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms |
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `vcc` is `lane_mask` for [VOPC compares](vector-compare.md) and the three [VOP2 carry forms](vector-vcc.md). These write all of VCC_LO, zero inactive lane bits and leave VCC_HI unknown. Other forms declare `vcc` as `unchanged`. All forms declare `exec` as `unchanged`. Operand rules cover explicit destinations. |
| `wave` | Wave sizes the form is valid in | `wave32` for SOPP controls, VOPC compares, VOP1 integer forms and VCC-reading VOP2 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` |
@@ -162,11 +169,11 @@ and one literal dword. The move copies the source and leaves SCC unchanged.
The destination vocabulary preserves the original decoder subset of the
RDNA 2 guide sections 5.3 and 12.3.
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
Binary vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
which rule a form uses) use a separate table:
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
must be `unchanged` (these binary forms write no SCC, VCC or EXEC):
| `operation` / `signedness` | `VectorBinary` |
| --- | --- |
@@ -177,6 +184,12 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` |
| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` |
The [Wave32 VOP2 select and carry forms](vector-vcc.md) use `vop2_vcc` with
the general SRC0 domain and an implicit VCC input. The generator checks the
direction of each fieldless VCC operand in the pinned XML. The three arithmetic
forms also declare a lane-mask output and use the same reverse-source mechanism
as the no-carry subtraction.
`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder
accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`
and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them
@@ -193,7 +206,8 @@ integer as SRC0 and a VGPR pair as VSRC1. All three declare a `relation`,
`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit
64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness
still matters for `eq` and `lg`, because the MSL lowering casts signed operands.
`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported.
The VOP3A variants redirect the same Wave32 mask to SDST. EXEC-writing
compares (`v_cmpx_*`) and Wave64 stay unsupported.
A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
+38 -4
View File
@@ -122,7 +122,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
## 4. Rejected (controlled translation/reference error, never a silent no-op)
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
- VOP3A compares outside the integer subset in section 11.
- SDWA and DPP forms; float compares; v_cmp_class.
- 16-bit compares in the decoder and translator (the reference interpreters
accept the subset in 2a).
@@ -275,12 +275,11 @@ swapped signedness, without the EXEC mask, without the absent-lane bound
(shader validation aborts on the out-of-range read) or with an inverted join.
The 32-bit readback evidence is local agreement with a specification-derived
reference on Apple M5 Pro. The 16-bit compiler evidence is CPU-only.
There is no RDNA 2 or Xbox hardware evidence.
reference on Apple M5 Pro. There is no RDNA 2 or Xbox hardware evidence.
## 10. Limitations
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares.
- Wave32 only. No `v_cmpx`, SDWA, DPP or float compares. VOP3 encodings cover the 32-bit compares only.
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
is no divergent execution. That needs its own contract.
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
@@ -289,3 +288,38 @@ There is no RDNA 2 or Xbox hardware evidence.
- Each thread recomputes up to 32 lanes per compare. The cost grows with the
compare's dependency chain. That is fine for fixtures, and no performance is
claimed.
## 11. VOP3A encoding (`_e64`)
All sixteen 32-bit signed and unsigned compares in section 2 also have a 64-bit
VOP3A encoding. The pinned AMD XML supplies each opcode. Bits 7:0 of the first
word are the scalar destination selector (SDST), in the field named VDST.
Selectors 0–105 name scalar general-purpose registers (SGPRs), and 106 names
`vcc_lo`. All other destinations are rejected. Both SRC0 and SRC1 must name
vector general-purpose registers (VGPRs), and the unused SRC2 must be the
assembler's inline-zero selector (128). ABS, OP_SEL, CLAMP, OMOD and NEG must
be clear. The guide describes CLAMP on compares as enabling floating-point
exception signaling (§6.5, p. 48 and §12.9.1, p. 162).
The AMD guide's compare-specific text (§3.9, pp. 19–20 and §13.3.3, p. 252)
specifies an SGPR destination for this encoding. The generic VDST label in
§12.9.1 (p. 162) and §13.3.4 Table 82 (pp. 257–258) describes the VOP3A field
as a VGPR destination. The pinned XML identifies VDST for these compares as
`OPR_SREG`, with the Wave64 pair described by `FMT_NUM_M64`. The Wave32 write
occupies one 32-bit SGPR. The guide defines 32 work-items in §2.1 (pp. 7–8),
32-bit SGPRs in §3.1 Table 2 (p. 12) and one compare result bit per lane in
§12.9 (p. 150). Wave64 stays unsupported.
LLVM 23 `llvm-mc` for gfx1030 with `+wavefrontsize32` assembles
`v_cmp_eq_u32_e64 s4, v1, v2` as bytes `04 00 c2 d4 01 05 02 02`.
Selecting `vcc_lo` changes the first byte to `6a`. The decoder tests cover
the assembler's words for all sixteen forms. This is encoding evidence.
The compare replaces all 32 bits of SDST with the lane mask from section 3,
including zero bits for inactive and absent lanes. It leaves SCC and EXEC
unchanged. VCC is written only when SDST selects `vcc_lo`, which uses the
same lowering and consumers as the VOPC form, including `s_cbranch_vccz`.
Every other SDST is tracked as a runtime-only SGPR result, including under
empty EXEC. Translation rejects later reads of that result, including reads
through resource descriptors. The runtime branch region rules in section 6
also apply here.
+42
View File
@@ -0,0 +1,42 @@
# Wave32 vector select, carry and borrow
The gfx1030 compute fixture ABI supports four 32-bit vector two-operand
instruction (VOP2) forms that read the vector condition code (VCC).
In Wave32, bit `n` of `VCC_LO` supplies lane `n`'s input `c`.
The AMD RDNA 2 guide describes the operations in section 12.7, the VOP2 word
in section 13.3.1, and the execution and condition masks in sections 3.3 and 3.9.
| Instruction | Active lane destination | Active lane VCC output |
| --- | --- | --- |
| `v_cndmask_b32_e32` | S1 if c is set, S0 otherwise | Preserved |
| `v_add_co_ci_u32_e32` | Low 32 bits of S0 + S1 + c | Exact sum reaches 2³² |
| `v_sub_co_ci_u32_e32` | Low 32 bits of S0 − S1 − c | S1 + c exceeds S0 |
| `v_subrev_co_ci_u32_e32` | Low 32 bits of S1 − S0 − c | S0 + c exceeds S1 |
Section 12.7 prints a reverse-subtract flag expression that conflicts with its
prose and destination equation. Xenora uses unsigned borrow from the stated
reverse subtraction, consistent with section 12.12's `v_subrev_co_u32` when
the incoming borrow is zero.
Inactive lanes retain the old vector destination (VDST). Section 3.9
describes a fully written VCC mask and defines carry-out in terms of executing
lanes. Under that reading, inactive lanes contribute zero to a carry or borrow
output. Section 3.3 says scalar-register-writing vector ALU instructions
still execute under empty EXEC, so the carry output is a zero mask.
The synthetic ABI also zeros
absent lanes in a final short wave when it constructs a new mask.
The scalar condition code (SCC) and EXEC are preserved by these forms.
The general SRC0 subset includes vector general-purpose registers (VGPRs),
scalar registers s0–s105, `vcc_lo`, inline integers and one literal word.
VSRC1 and VDST are VGPRs. Translated scalar sources must be known or supplied
by a translated VCC result. The pinned XML lists the VCC input on all four
forms and an additional VCC output on the three arithmetic forms. VOP3
encodings with explicit scalar conditions and VOP3B carry-out-only forms
are outside this subset.
The Metal lowering reuses the compare mask's replay of the current wave's
input lanes to form carry and borrow masks. The original `vector-vcc.s`
fixture chains all four operations. LLVM checks encoding, and the guide-derived
oracle checks both CPU interpreters. `vop2_vcc_matches_guide_on_native_metal` passes on a local
Apple M5 under API and shader validation; independent acceptance is pending. The expectations are derived from the public AMD specification (class B).
+372
View File
@@ -87,6 +87,330 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_hi_i32_i24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_u32_u24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_hi_u32_u24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_min_i32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_max_i32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_min_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_max_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_xnor_b32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_sub_nc_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
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_subrev_nc_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_f_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_t_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_f_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_t_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
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 = "buffer_store_dword"
encoding = "MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags"
@@ -1886,6 +2210,54 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cndmask_b32_e32"
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; select S1 when the VCC_LO lane bit is set, otherwise S0"
representation = "`020402C1`"
lowering = "per-thread integer expression with EXEC masking"
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_add_co_ci_u32_e32"
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned addition with carry input and output"
representation = "`50040481`"
lowering = "per-thread integer expression with EXEC masking"
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_sub_co_ci_u32_e32"
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S0 minus S1 with borrow input and output"
representation = "`52060480`"
lowering = "per-thread integer expression with EXEC masking"
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_subrev_co_ci_u32_e32"
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S1 minus S0 with borrow input and output"
representation = "`540606C2`"
lowering = "per-thread integer expression with EXEC masking"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[guest_milestones]
X1 = "accepted"
X2 = "accepted"
+18
View File
@@ -0,0 +1,18 @@
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000000
000c: t2 = wave.mask v_cmp_eq_u32_e32 t1, t0 exec=0xffffffff
0010: t3 = const.u32 0xffffffff
0010: t4 = vcc.Select t3, t0, t2
0014: t5 = const.u32 0x00000001
0014: t6 = vcc.AddCarry.flag t5, t4, t2
0014: t7 = wave.carry t6 exec=0xffffffff
0014: t8 = vcc.AddCarry t5, t4, t2
0018: t9 = const.u32 0x00000000
0018: t10 = vcc.SubtractBorrow.flag t9, t8, t7
0018: t11 = wave.carry t10 exec=0xffffffff
0018: t12 = vcc.SubtractBorrow t9, t8, t7
001c: t13 = const.u32 0xfffffffe
001c: t14 = vcc.SubtractBorrow.flag t12, t13, t11
001c: t15 = wave.carry t14 exec=0xffffffff
001c: t16 = vcc.SubtractBorrow t12, t13, t11
0024: store.u32 output[index], t15
+63
View File
@@ -0,0 +1,63 @@
#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 grid [[threads_per_grid]]) {
uint t0 = input[index];
uint t1 = 0x00000000u;
uint t2 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t1 == l0) ? 1u : 0u;
t2 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t3 = 0xffffffffu;
uint t4 = ((t2 >> (index & 31u)) & 1u) != 0u ? t0 : t3;
uint t5 = 0x00000001u;
uint t6 = uint((ulong(t5) + ulong(t4) + ((t2 >> (index & 31u)) & 1u)) >> 32u);
uint t7 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
uint l6 = uint((ulong(t5) + ulong(l4) + ((t2 >> lane) & 1u)) >> 32u);
uint pass = l6;
t7 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t8 = t5 + t4 + ((t2 >> (index & 31u)) & 1u);
uint t9 = 0x00000000u;
uint t10 = uint(ulong(t8) + ((t7 >> (index & 31u)) & 1u) > ulong(t9));
uint t11 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
uint l10 = uint(ulong(l8) + ((t7 >> lane) & 1u) > ulong(t9));
uint pass = l10;
t11 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t12 = t9 - t8 - ((t7 >> (index & 31u)) & 1u);
uint t13 = 0xfffffffeu;
uint t14 = uint(ulong(t13) + ((t11 >> (index & 31u)) & 1u) > ulong(t12));
uint t15 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
uint l12 = t9 - l8 - ((t7 >> lane) & 1u);
uint l14 = uint(ulong(t13) + ((t11 >> lane) & 1u) > ulong(l12));
uint pass = l14;
t15 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t16 = t12 - t13 - ((t11 >> (index & 31u)) & 1u);
output[index] = t15;
}
+59
View File
@@ -0,0 +1,59 @@
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000000
0010: t2 = const.u32 0x00000001
0014: t3 = const.u32 0x40000001
001c: t4 = const.u32 0x00000001
0020: t5 = wave.mask v_cmp_f_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
002c: t6 = lshl.b32 t1, t2
0030: t7 = xor.b32 t6, t5
0034: t8 = wave.mask v_cmp_lt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0040: t9 = lshl.b32 t7, t2
0044: t10 = xor.b32 t9, t8
0048: t11 = wave.mask v_cmp_eq_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0054: t12 = lshl.b32 t10, t2
0058: t13 = xor.b32 t12, t11
005c: t14 = wave.mask v_cmp_le_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0068: t15 = lshl.b32 t13, t2
006c: t16 = xor.b32 t15, t14
0070: t17 = wave.mask v_cmp_gt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
007c: t18 = lshl.b32 t16, t2
0080: t19 = xor.b32 t18, t17
0084: t20 = wave.mask v_cmp_ne_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0090: t21 = lshl.b32 t19, t2
0094: t22 = xor.b32 t21, t20
0098: t23 = wave.mask v_cmp_ge_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00a4: t24 = lshl.b32 t22, t2
00a8: t25 = xor.b32 t24, t23
00ac: t26 = wave.mask v_cmp_t_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00b8: t27 = lshl.b32 t25, t2
00bc: t28 = xor.b32 t27, t26
00c0: t29 = wave.mask v_cmp_f_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00cc: t30 = lshl.b32 t28, t2
00d0: t31 = xor.b32 t30, t29
00d4: t32 = wave.mask v_cmp_lt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00e0: t33 = lshl.b32 t31, t2
00e4: t34 = xor.b32 t33, t32
00e8: t35 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00f4: t36 = lshl.b32 t34, t2
00f8: t37 = xor.b32 t36, t35
00fc: t38 = wave.mask v_cmp_le_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0108: t39 = lshl.b32 t37, t2
010c: t40 = xor.b32 t39, t38
0110: t41 = wave.mask v_cmp_gt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
011c: t42 = lshl.b32 t40, t2
0120: t43 = xor.b32 t42, t41
0124: t44 = wave.mask v_cmp_ne_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0130: t45 = lshl.b32 t43, t2
0134: t46 = xor.b32 t45, t44
0138: t47 = wave.mask v_cmp_ge_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0144: t48 = lshl.b32 t46, t2
0148: t49 = xor.b32 t48, t47
014c: t50 = wave.mask v_cmp_t_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0158: t51 = lshl.b32 t49, t2
015c: t52 = xor.b32 t51, t50
0160: t53 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> s8 exec=0xffffffff
0168: t54 = wave.mask v_cmp_gt_u32_e64 t3, t0 -> vcc_lo exec=0xffffffff
0170: branch.vccz t54 -> 0x0178
0174: t56 = xor.b32 t4, t52
0178: t57 = join.vccz t54, t56, t52
0178: store.u32 output[index], t57
+188
View File
@@ -0,0 +1,188 @@
#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 grid [[threads_per_grid]]) {
uint t0 = input[index];
uint t1 = 0x00000000u;
uint t2 = 0x00000001u;
uint t3 = 0x40000001u;
uint t4 = 0x00000001u;
uint t5 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (false) ? 1u : 0u;
t5 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t6 = t1 << (t2 & 31u);
uint t7 = t6 ^ t5;
uint t8 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) < as_type<int>(t3)) ? 1u : 0u;
t8 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t9 = t7 << (t2 & 31u);
uint t10 = t9 ^ t8;
uint t11 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) == as_type<int>(t3)) ? 1u : 0u;
t11 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t12 = t10 << (t2 & 31u);
uint t13 = t12 ^ t11;
uint t14 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) <= as_type<int>(t3)) ? 1u : 0u;
t14 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t15 = t13 << (t2 & 31u);
uint t16 = t15 ^ t14;
uint t17 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) > as_type<int>(t3)) ? 1u : 0u;
t17 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t18 = t16 << (t2 & 31u);
uint t19 = t18 ^ t17;
uint t20 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) != as_type<int>(t3)) ? 1u : 0u;
t20 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t21 = t19 << (t2 & 31u);
uint t22 = t21 ^ t20;
uint t23 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) >= as_type<int>(t3)) ? 1u : 0u;
t23 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t24 = t22 << (t2 & 31u);
uint t25 = t24 ^ t23;
uint t26 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (true) ? 1u : 0u;
t26 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t27 = t25 << (t2 & 31u);
uint t28 = t27 ^ t26;
uint t29 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (false) ? 1u : 0u;
t29 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t30 = t28 << (t2 & 31u);
uint t31 = t30 ^ t29;
uint t32 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 < t3) ? 1u : 0u;
t32 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t33 = t31 << (t2 & 31u);
uint t34 = t33 ^ t32;
uint t35 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 == t3) ? 1u : 0u;
t35 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t36 = t34 << (t2 & 31u);
uint t37 = t36 ^ t35;
uint t38 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 <= t3) ? 1u : 0u;
t38 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t39 = t37 << (t2 & 31u);
uint t40 = t39 ^ t38;
uint t41 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 > t3) ? 1u : 0u;
t41 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t42 = t40 << (t2 & 31u);
uint t43 = t42 ^ t41;
uint t44 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 != t3) ? 1u : 0u;
t44 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t45 = t43 << (t2 & 31u);
uint t46 = t45 ^ t44;
uint t47 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 >= t3) ? 1u : 0u;
t47 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t48 = t46 << (t2 & 31u);
uint t49 = t48 ^ t47;
uint t50 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (true) ? 1u : 0u;
t50 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t51 = t49 << (t2 & 31u);
uint t52 = t51 ^ t50;
uint t53 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 == t3) ? 1u : 0u;
t53 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t54 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t3 > l0) ? 1u : 0u;
t54 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t56 = t4 ^ t52;
uint t57 = t54 != 0u ? t56 : t52;
output[index] = t57;
}
+23
View File
@@ -0,0 +1,23 @@
0000: t0 = load.u32 input[index]
000c: t1 = mul24.i32 t0, t0
0014: t2 = mulhi24.i32 t1, t0
001c: t3 = mul24.u32 t1, t0
0024: t4 = mulhi24.u32 t3, t0
002c: t5 = min.i32 t0, t1
0034: t6 = max.i32 t0, t3
003c: t7 = min.u32 t2, t0
0044: t8 = max.u32 t4, t1
004c: t9 = xnor.b32 t0, t4
0054: t10 = sub.u32 t5, t9
005c: t11 = sub.u32 t8, t0
0064: t12 = xor.b32 t1, t2
0068: t13 = xor.b32 t3, t12
006c: t14 = xor.b32 t4, t13
0070: t15 = xor.b32 t5, t14
0074: t16 = xor.b32 t6, t15
0078: t17 = xor.b32 t7, t16
007c: t18 = xor.b32 t8, t17
0080: t19 = xor.b32 t9, t18
0084: t20 = xor.b32 t10, t19
0088: t21 = xor.b32 t11, t20
008c: store.u32 output[index], t21
+30
View File
@@ -0,0 +1,30 @@
#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 = as_type<uint>((as_type<int>(t0 << 8u) >> 8)) * as_type<uint>((as_type<int>(t0 << 8u) >> 8));
uint t2 = as_type<uint>(mulhi((as_type<int>(t1 << 8u) >> 8), (as_type<int>(t0 << 8u) >> 8)));
uint t3 = (t1 & 0x00ffffffu) * (t0 & 0x00ffffffu);
uint t4 = mulhi((t3 & 0x00ffffffu), (t0 & 0x00ffffffu));
uint t5 = as_type<uint>(min(as_type<int>(t0), as_type<int>(t1)));
uint t6 = as_type<uint>(max(as_type<int>(t0), as_type<int>(t3)));
uint t7 = min(t2, t0);
uint t8 = max(t4, t1);
uint t9 = ~(t0 ^ t4);
uint t10 = t5 - t9;
uint t11 = t8 - t0;
uint t12 = t1 ^ t2;
uint t13 = t3 ^ t12;
uint t14 = t4 ^ t13;
uint t15 = t5 ^ t14;
uint t16 = t6 ^ t15;
uint t17 = t7 ^ t16;
uint t18 = t8 ^ t17;
uint t19 = t9 ^ t18;
uint t20 = t10 ^ t19;
uint t21 = t11 ^ t20;
output[index] = t21;
}
Binary file not shown.
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original Wave32 example. The compare derives VCC from the input, then each
// carry/borrow feeds the next operation. Before reverse subtract, v3 is
// 0xfffffffe for a zero input and 0xffffffff otherwise, with borrow-in 1.
// Subtracting 0xfffffffe and the borrow-in sets the final VCC bit for zero inputs.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
v_cmp_eq_u32_e32 vcc_lo, 0, v1
v_cndmask_b32_e32 v2, -1, v1, vcc_lo
v_add_co_ci_u32_e32 v2, vcc_lo, 1, v2, vcc_lo
v_sub_co_ci_u32_e32 v3, vcc_lo, 0, v2, vcc_lo
v_subrev_co_ci_u32_e32 v3, vcc_lo, -2, v3, vcc_lo
v_mov_b32_e32 v4, vcc_lo
buffer_store_dword v4, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+85
View File
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original Wave32 VOP3A vectors for the sixteen integer compare encoding variants.
// Each compare writes vcc_lo through the explicit 64-bit destination field
// (one writes s8), and each wave folds the masks into v2 as
// v2 = (v2 << 1) ^ mask. Sources are VGPRs. This fixture is checked through
// its IR and MSL goldens; the per-lane expected values for these forms are in
// tests/validation/tests/vop3_compare.rs.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
s_waitcnt vmcnt(0) // Wait for the load.
v_mov_b32_e32 v2, 0 // Clear the accumulator.
v_mov_b32_e32 v5, 1 // Shift count for the fold.
v_mov_b32_e32 v3, 0x40000001 // Second source: inputs fall below, on and above it.
v_mov_b32_e32 v6, 1 // Low bit for the branch fold.
v_cmp_f_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_lt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_le_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_gt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ne_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ge_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_t_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_f_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_lt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_le_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_gt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ne_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ge_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_t_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_u32_e64 s8, v1, v3 // A mask into a plain SGPR, never read.
v_cmp_gt_u32_e64 vcc_lo, v3, v1 // Unsigned 0x40000001 > input.
s_cbranch_vccz 1 // Skip the next fold when no lane passed.
v_xor_b32_e32 v2, v6, v2 // Flip the low bit when some lane passed.
buffer_store_dword v2, v0, s[4:7], 0 idxen // Store the folded word.
s_waitcnt_vscnt null, 0 // Wait for the store.
s_endpgm // End the program.
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original VOP3A vectors for the eleven per-lane integer encoding variants.
// All arithmetic operands are vector general-purpose registers (VGPRs) and every result
// depends on the lane's own input word. XOR folds the results into one word.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
s_waitcnt vmcnt(0) // Wait for the load.
v_mul_i32_i24_e64 v2, v1, v1 // Multiply signed 24-bit inputs and keep the low word.
v_mul_hi_i32_i24_e64 v3, v2, v1 // Multiply signed 24-bit inputs and keep the high word.
v_mul_u32_u24_e64 v4, v2, v1 // Multiply unsigned 24-bit inputs and keep the low word.
v_mul_hi_u32_u24_e64 v255, v4, v1 // Multiply unsigned 24-bit inputs and keep the high word.
v_min_i32_e64 v6, v1, v2 // Select the signed minimum.
v_max_i32_e64 v7, v1, v4 // Select the signed maximum.
v_min_u32_e64 v8, v3, v1 // Select the unsigned minimum.
v_max_u32_e64 v9, v255, v2 // Select the unsigned maximum.
v_xnor_b32_e64 v10, v1, v255 // Complement the XOR.
v_sub_nc_u32_e64 v11, v6, v10 // Subtract the second source from the first.
v_subrev_nc_u32_e64 v1, v1, v9 // Subtract the first source from the second, overwriting the first.
v_xor_b32_e32 v13, v2, v3 // Start the XOR fold.
v_xor_b32_e32 v13, v4, v13 // Fold the unsigned product low word.
v_xor_b32_e32 v13, v255, v13 // Fold the unsigned product high word.
v_xor_b32_e32 v13, v6, v13 // Fold the signed minimum.
v_xor_b32_e32 v13, v7, v13 // Fold the signed maximum.
v_xor_b32_e32 v13, v8, v13 // Fold the unsigned minimum.
v_xor_b32_e32 v13, v9, v13 // Fold the unsigned maximum.
v_xor_b32_e32 v13, v10, v13 // Fold the XNOR result.
v_xor_b32_e32 v13, v11, v13 // Fold the subtraction result.
v_xor_b32_e32 v13, v1, v13 // Fold the reverse subtraction result.
buffer_store_dword v13, v0, s[4:7], 0 idxen // Store the folded word.
s_waitcnt_vscnt null, 0 // Wait for the store.
s_endpgm // End the program.
+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-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-unary vector-compare-64 vector-compare-16; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vop3-integer vop3-compare vector-unary vector-compare-64 vector-compare-16; 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"
+3 -3
View File
@@ -10,7 +10,7 @@ import sys
import tomllib
registry = Path("docs/claims.toml")
claims = tomllib.loads(registry.read_text())["claim"]
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
classes = {}
errors = []
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
for source in files:
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
continue
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
errors.append(f"{source}: unregistered {reference}")
status = tomllib.loads(Path("docs/status.toml").read_text())
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
for feature in status["feature"]:
verification = feature.get("hardware_verification", "")
if verification.casefold() != "verified":
+6 -6
View File
@@ -18,7 +18,7 @@ def table(headers, rows):
def replace_block(path, name, body, check):
original = path.read_text()
original = path.read_text(encoding="utf-8")
start = f"<!-- status:{name}:start -->\n"
stop = f"\n<!-- status:{name}:end -->"
head, _, tail = original.partition(start)
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
if check:
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(updated)
path.write_text(updated, encoding="utf-8", newline="\n")
return True
@@ -90,12 +90,12 @@ def render_progress(status):
def check_asset(path, svg, check):
if path.exists() and path.read_text() == svg:
if path.exists() and path.read_text(encoding="utf-8") == svg:
return True
if check:
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(svg)
path.write_text(svg, encoding="utf-8", newline="\n")
return True
@@ -105,8 +105,8 @@ def main():
check = parser.parse_args().check
root = Path(__file__).resolve().parents[2]
docs = root / "docs"
status = tomllib.loads((docs / "status.toml").read_text())
claims = tomllib.loads((docs / "claims.toml").read_text())
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
features = table(
+5
View File
@@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
--nocapture --test-threads=1
# Guest draws sample textures bound through descriptor tables (#303).
cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures --no-run
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures -- \
--nocapture --test-threads=1
# The native app interface runs the trusted fixture's guest draw on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
@@ -177,7 +177,7 @@ def snapshot():
["SRC2", [[50, 9]]], ["OMOD", [[59, 2]]], ["NEG", [[61, 3]]],
],
"identifier_mask": 0xFFFF0000,
"identifiers": [0xD4000000 | (op << 16) for op in (265, 273, 295)],
"identifiers": [0xD4000000 | (op << 16) for op in (129, 265, 273, 295)],
}
# Values copied from the AMD XML snapshot: VOP3 encodings of VOP2 forms.
for name, opcode, data_format in (
@@ -191,6 +191,14 @@ def snapshot():
["SRC1", data_format, "OPR_SRC_NOLDS", 32, True, False, False, True],
],
}
variants[("V_CMP_LT_I32", "ENC_VOP3")] = {
"instruction": "V_CMP_LT_I32", "encoding": "ENC_VOP3", "opcode": 129,
"operands": [
["VDST", "FMT_NUM_M64", "OPR_SREG", 64, False, True, False, True],
["SRC0", I32, "OPR_SRC", 32, True, False, False, True],
["SRC1", I32, "OPR_SRC_NOLDS", 32, True, False, False, True],
],
}
return {
"source": {"sha256": SHA},
"encodings": {
@@ -309,6 +317,18 @@ def _variant(of, opcode):
}
def compare_variants():
reg = vector_compares()
rule = gen.OPERAND_RULES["vop3_cmp_vgpr2"]
reg["operand_rules"]["vop3_cmp_vgpr2"] = dict(
copy.deepcopy(rule["shape"]), unsupported=sorted(rule["unsupported"])
)
reg["encoding_variant"] = [
dict(_variant("V_CMP_LT_I32", 129), operands="vop3_cmp_vgpr2")
]
return reg
def compares():
reg = registry()
reg["form"] += [
@@ -771,12 +791,21 @@ class Validate(unittest.TestCase):
text = gen.render(vectors(), snapshot())
self.assertIn("pub enum VectorAluOp {", text)
self.assertIn("if word & 0x8000_0000 != 0x0000_0000 {", text)
self.assertIn("Self::MulI32I24 => VectorBinary::Mul24Signed,", text)
self.assertIn("Self::SubrevNcU32 => VectorBinary::Sub,", text)
self.assertIn("Self::MulI32I24 => VectorLowering::Binary(VectorBinary::Mul24Signed),", text)
self.assertIn("Self::SubrevNcU32 => VectorLowering::Binary(VectorBinary::Sub),", text)
self.assertIn("Self::SubrevNcU32 => true,", text.split("fn swaps_sources", 1)[1])
self.assertIn('Self::AddU32 => "v_min_i32_e32",', text)
self.assertIn("swap_sources: true,", text)
def test_vop2_vcc_requires_the_xml_input_and_output(self):
reg = gen.load_registry()
snap = gen.load_snapshot()
operands = snap["variants"][("V_ADD_CO_CI_U32", "ENC_VOP2")]["operands"]
operands[:] = [op for op in operands if not (op[2] == "OPR_VCC" and op[4])]
self.rejects(reg, "V_ADD_CO_CI_U32: carry_in vcc requires one implicit XML VCC input", snap)
form(reg, "V_CNDMASK_B32")["vcc"] = "lane_mask"
self.rejects(reg, "V_CNDMASK_B32: vcc lane_mask contradicts rule vop2_vcc", snap)
def test_accepts_compares(self):
self.assertEqual(self.errors(compares()), [])
@@ -851,6 +880,25 @@ class Validate(unittest.TestCase):
def test_accepts_encoding_variants(self):
self.assertEqual(self.errors(variants()), [])
def test_compare_variant_routes_mask_to_sdst(self):
reg = compare_variants()
self.assertEqual(self.errors(reg), [])
row = gen.variant_row(reg, reg["encoding_variant"][0])
self.assertEqual((row["vcc"], row["width"], row["wave"]), ("sdst_lane_mask", 32, "wave32"))
def test_rejects_mismatched_compare_variant_destination(self):
reg = compare_variants()
form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged"
self.rejects(reg, "requires a base destination contract of lane_mask, got unchanged")
reg = compare_variants()
reg["operand_rules"]["vop3_cmp_vgpr2"]["dst"]["class"] = "vgpr"
self.rejects(reg, "operand rule vop3_cmp_vgpr2: declaration differs")
snap = snapshot()
snap["variants"][("V_CMP_LT_I32", "ENC_VOP3")]["operands"][0][2] = "OPR_VGPR"
self.rejects(compare_variants(), "VDST is not a scalar mask destination in the XML", snap)
def test_rejects_a_variant_of_an_undeclared_form(self):
reg = variants()
reg["encoding_variant"].append(_variant("V_MUL_HI_I32_I24", 266))
@@ -1140,7 +1188,7 @@ class Validate(unittest.TestCase):
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
for key, value in (
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
("signedness", "float"), ("carry_in", "exec"), ("exec", "written"), ("wave", "wave64"),
):
with self.subTest(key=key):
reg = registry()
+132 -18
View File
@@ -22,7 +22,7 @@
//! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32,
//! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a
//! shift-and-add multiplier and floor division for the high half, the ripple
//! adder for add and subtract), VOP3 add-no-carry, MUBUF
//! adder for add and subtract), VOP3A integer arithmetic and compares, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
//! error. The arithmetic shift is evaluated as a floor division by a power of
//! two rather than with a host signed shift, so the oracle does not share the
@@ -72,18 +72,20 @@ enum Insn {
/// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16.
SImm(u32, u8, u16),
BranchScc0(usize),
BranchMaskZero {
BranchMask {
target: usize,
register: usize,
nonzero: bool,
},
Branch(usize),
VMov(u8, Src),
VMovFromSgpr(u8, u8),
/// `v_mov_b32_e32 vD, vcc_lo`.
VMovFromVcc(u8),
/// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// Integer vector compare into `dst`: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// `bits` is 16, 32 or 64; 64-bit register operands name the low register of a pair.
VCmp {
dst: u8,
relation: u8,
signed: bool,
bits: u32,
@@ -99,6 +101,7 @@ enum Insn {
VXor(u8, u8, u8),
/// VOP2 integer opcode 9-12, 17-20, 30 or 37-39: VDST, SRC0, VSRC1.
VInt(u32, u8, CmpSrc, u8),
VIntVcc(u32, u8, CmpSrc, u8),
/// VOP1 integer opcode 55-59: VDST, SRC0.
VUnary(u32, u8, CmpSrc),
/// `v_swap_b32 vD, vS` (VOP1 opcode 101).
@@ -206,6 +209,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
return Ok(lanes.iter().map(|lane| lane.written.unwrap()).collect());
}
Insn::VCmp {
dst,
relation,
signed,
bits,
@@ -225,10 +229,32 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
offset,
)
.map(|mask| {
sgpr[106] = Some(mask);
// VCC_HI has no known value after a compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
sgpr[usize::from(dst)] = Some(mask);
if dst == 106 {
// VCC_HI has no known value after a VCC compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
}
None
})
}
Insn::VIntVcc(opcode, dst, src0, src1) => {
if let Some(error) = first_error(&lanes) {
return Err(error);
}
vector_vcc(
&mut lanes,
&sgpr,
execution_mask,
(opcode, dst, src0, src1),
offset,
)
.map(|mask| {
if opcode != 1 {
sgpr[106] = Some(mask);
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
}
None
})
}
@@ -280,12 +306,17 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
index_of(program, target, offset).map(Some)
}
}),
Insn::BranchMaskZero { target, register } => {
Insn::BranchMask {
target,
register,
nonzero,
} => {
let takes = |mask| (mask != 0) == nonzero;
if register == 106 && vcc_lane_derived {
let live = lanes.iter().find(|lane| lane.error.is_none()).unwrap();
check_runtime_region(program, pc, target, live, &sgpr, execution_mask, offset)
.and_then(|()| {
if sgpr[106] == Some(0) {
if takes(sgpr[106].unwrap()) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -295,7 +326,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
sgpr[register]
.ok_or_else(|| format!("{offset:#x}: uninitialized mask"))
.and_then(|mask| {
if mask == 0 {
if takes(mask) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -325,6 +356,60 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string()))
}
/// Guide 12.7 vector select and carry/borrow, with the Wave32 mask from 3.9.
fn vector_vcc(
lanes: &mut [Lane],
sgpr: &[Option<u32>; 128],
exec: u32,
(opcode, dst, src0, src1): (u32, u8, CmpSrc, u8),
offset: usize,
) -> Result<u32, String> {
if exec == 0 {
return Ok(0);
}
let incoming = sgpr[106].ok_or_else(|| format!("{offset:#x}: uninitialized vcc_lo"))?;
let mut mask = 0;
for (index, lane) in lanes.iter_mut().enumerate() {
if exec != u32::MAX && lane.vgpr[usize::from(dst)].is_none() {
return Err(format!("{offset:#x}: partial EXEC on uninitialized VGPR"));
}
let a = match src0 {
CmpSrc::Sgpr(reg) => sgpr[usize::from(reg)]
.ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))?,
CmpSrc::Vcc => incoming,
CmpSrc::Imm(value) => value,
CmpSrc::Vgpr(reg) => read_vgpr(lane, reg, offset)?,
};
let b = read_vgpr(lane, src1, offset)?;
let lane_bit = 2_u32.pow(index as u32);
if exec & lane_bit == 0 {
continue;
}
check_destination(dst, lane.pending_read, offset)?;
let bit = incoming / lane_bit % 2;
let (value, flag) = match opcode {
1 => (if bit == 1 { b } else { a }, false),
40 => {
let (sum, overflow) = a.overflowing_add(b);
let (value, carry) = sum.overflowing_add(bit);
(value, overflow || carry)
}
41 | 42 => {
let (lhs, rhs) = if opcode == 42 { (b, a) } else { (a, b) };
let (difference, underflow) = lhs.overflowing_sub(rhs);
let (value, borrow) = difference.overflowing_sub(bit);
(value, underflow || borrow)
}
_ => unreachable!("not a VCC-reading VOP2 opcode"),
};
lane.vgpr[usize::from(dst)] = Some(value);
if flag {
mask |= lane_bit;
}
}
Ok(mask)
}
/// One SOPK instruction, per the operation text of guide 12.2. SDST names
/// the destination and, for every form but the two moves, the first source.
fn scalar_immediate(
@@ -615,7 +700,7 @@ fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
lane.vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
}
/// Evaluate one VOPC compare for the whole wave and return the new VCC_LO.
/// Evaluate one integer vector compare for the whole wave and return its mask.
fn compare(
lanes: &[Lane],
sgpr: &[Option<u32>; 128],
@@ -1139,7 +1224,7 @@ fn decode(code: &[u8]) -> Result<Vec<(usize, Insn)>, String> {
offset += len;
}
for &(at, insn) in &program {
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMaskZero { target, .. } =
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMask { target, .. } =
insn
&& !program.iter().any(|(boundary, _)| *boundary == target)
{
@@ -1240,6 +1325,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Err(fail("unsupported VOPC operand"));
}
let insn = Insn::VCmp {
dst: 106,
relation: relation as u8,
signed,
bits,
@@ -1250,19 +1336,46 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
}
// VOP2 integer forms: bit 31 = 0, OP 30:25, VDST 24:17, VSRC1 16:9, SRC0 8:0.
let vop2_op = (first >> 25) & 0x3f;
if first >> 31 == 0 && matches!(vop2_op, 1 | 40..=42) {
let (src0, len) = vector_src0(code, offset, first, "VOP2")?;
return Ok((
Insn::VIntVcc(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8),
len,
));
}
if first >> 31 == 0 && matches!(vop2_op, 9..=12 | 17..=20 | 30 | 37..=39) {
let (src0, len) = vector_src0(code, offset, first, "VOP2")?;
let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8);
return Ok((insn, len));
}
if first & 0xffff_0000 == 0xd525_0000 {
let second = word(code, offset + 4)?;
if first >> 26 == 0b110101 {
let dst = first as u8;
let opcode = (first >> 16) & 0x3ff;
let second = word(code, offset + 4).map_err(|_| fail("truncated VOP3A"))?;
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(fail("bad VOP3 add form"));
return Err(fail("unsupported VOP3A modifiers or sources"));
}
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
// Guide §§3.9, 12.7.1 and 12.9.1: re-encoded VOP2 writes a VGPR,
// while VOPC uses the destination field for the scalar mask.
let (src0, src1) = (src0 as u8, src1 as u8);
let insn = match opcode {
128..=135 | 192..=199 if dst <= 106 => Insn::VCmp {
dst,
relation: (opcode % 8) as u8,
signed: opcode < 192,
bits: 32,
src0: CmpSrc::Vgpr(src0),
src1,
},
293 => Insn::VAddNc(dst, src0, src1),
265..=268 | 273..=276 | 286 | 294..=295 => {
Insn::VInt(opcode - 256, dst, CmpSrc::Vgpr(src0), src1)
}
_ => return Err(fail("unsupported VOP3A opcode or destination")),
};
return Ok((insn, 8));
}
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
let sop1_op = (first >> 8) & 0xff;
@@ -1347,15 +1460,16 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::BranchScc0(branch_target(first, offset)?), 4));
}
let tested_register = match first >> 16 {
0xbf86 => Some(106),
0xbf86 | 0xbf87 => Some(106),
0xbf88 => Some(126),
_ => None,
};
if let Some(register) = tested_register {
return Ok((
Insn::BranchMaskZero {
Insn::BranchMask {
target: branch_target(first, offset)?,
register,
nonzero: first >> 16 == 0xbf87,
},
4,
));
+21
View File
@@ -784,6 +784,27 @@ mod review {
const SCALAR_ARITH_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-arith.bin");
// Hand-derived in fixtures/rdna2/scalar-arith.s from the guide's 12.1 pseudocode.
const SCALAR_ARITH_KEY: u32 = 0x8115_7dfe;
#[test]
fn vector_vcc_chain_returns_the_zero_input_mask() {
let code = include_bytes!("../../fixtures/rdna2/vector-vcc.bin");
let input: Vec<_> = [0, 1, u32::MAX, 5, 0, 7]
.into_iter()
.cycle()
.take(67)
.collect();
let expected: Vec<_> = input
.chunks(32)
.flat_map(|wave| {
let mask = wave
.iter()
.enumerate()
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane));
std::iter::repeat_n(mask, wave.len())
})
.collect();
verify(code, &input, Some(&expected));
}
const VECTOR_INTEGER_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-integer.bin");
/// fixtures/rdna2/vector-integer.s for one lane input `x`, written from the
+2 -2
View File
@@ -745,9 +745,9 @@ fn unsupported_vop2_integer_encodings_are_rejected() {
fn other_vop2_opcodes_stay_unsupported() {
// Every VOP2 opcode (0-61; 62 and 63 are the VOPC and VOP1 encodings)
// except the forms supported before this set (V_ADD_F32 3, V_MUL_F32 8,
// the shifts 22, 24, 26 and AND, OR, XOR 27-29) and these twelve. VDST is
// the shifts 22, 24, 26 and AND, OR, XOR 27-29) and the registered integer forms. VDST is
// initialized, so a form that also reads it fails only on the opcode.
let earlier = [3, 8, 22, 24, 26, 27, 28, 29];
let earlier = [1, 3, 8, 22, 24, 26, 27, 28, 29, 40, 41, 42];
let supported: Vec<u32> = FORMS
.iter()
.map(|&(form, _)| form as u32)
+215
View File
@@ -0,0 +1,215 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP2 select and carry/borrow oracle from AMD RDNA 2 ISA guide
//! sections 3.3, 3.9, 12.7 and 13.3.1.
#[path = "../independent_ref.rs"]
mod independent_ref;
use xenora_shader::{Architecture, CompileError, compile};
const FORMS: [u32; 4] = [1, 40, 41, 42];
const EXEC_PATTERNS: [u32; 3] = [u32::MAX, 0xaaaa_aaab, 0];
const INITIAL_DST: u32 = 0x1234_5678;
const SCALAR_VCC: u32 = 0x8000_0005;
fn words(code: &[u32]) -> Vec<u8> {
code.iter().flat_map(|word| word.to_le_bytes()).collect()
}
fn vop2(op: u32, dst: u32, src0: u32, src1: u32) -> u32 {
op << 25 | dst << 17 | src1 << 9 | src0
}
fn program(body: &[u32], output: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
code.extend(body);
code.extend([
0xe070_2000,
0x8001_0000 | output << 8,
0xbbfd_0000,
0xbf81_0000,
]);
words(&code)
}
fn input() -> Vec<u32> {
[0, 1, 2, u32::MAX, u32::MAX - 1, 0x8000_0000, 0, 31]
.into_iter()
.cycle()
.take(67)
.collect()
}
/// Guide 12.7 gives the unbounded result and the 32-bit destination.
/// For SUBREV the prose and D equation reverse the operands. The printed
/// borrow formula repeats SUB's order, inconsistent with that subtraction.
fn expected(op: u32, a: u32, b: u32, bit: u32) -> (u32, bool) {
let (a, b, bit) = (i128::from(a), i128::from(b), i128::from(bit));
let exact = match op {
1 => return (if bit == 0 { a } else { b } as u32, false),
40 => a + b + bit,
41 => a - b - bit,
42 => b - a - bit,
_ => unreachable!(),
};
let modulus = 1_i128 << 32;
(
exact.rem_euclid(modulus) as u32,
!(0..modulus).contains(&exact),
)
}
fn cases() -> Vec<(Vec<u8>, Vec<u32>)> {
let input = input();
let mut cases = Vec::new();
for op in FORMS {
for exec in EXEC_PATTERNS {
for (selector, extension, src0) in [
(129, None, 1),
(193, None, u32::MAX),
(8, None, 0x8000_0000),
(255, Some(u32::MAX - 1), u32::MAX - 1),
(259, None, INITIAL_DST),
(106, None, 0),
] {
for from_compare in [false, true] {
let mut body = vec![0x7e06_02ff, INITIAL_DST, 0xbe88_03ff, 0x8000_0000];
if from_compare {
body.push(0x7d84_0280); // v_cmp_eq_u32_e32 vcc_lo, 0, v1
} else {
body.extend([0xbeea_03ff, SCALAR_VCC]); // s_mov_b32 vcc_lo, literal
}
body.extend([0xbefe_03ff, exec]);
body.push(vop2(op, 3, selector, 1));
body.extend(extension);
body.push(0xbefe_03c1); // restore full EXEC for the store
let mut values = Vec::new();
let mut masks = Vec::new();
for wave in input.chunks(32) {
let incoming = if from_compare {
wave.iter()
.enumerate()
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane))
} else {
SCALAR_VCC
};
let mut mask = if op == 1 { incoming } else { 0 };
for (lane, &x) in wave.iter().enumerate() {
if exec & (1 << lane) == 0 {
values.push(INITIAL_DST);
} else {
let a = if selector == 106 { incoming } else { src0 };
let (value, flag) = expected(op, a, x, (incoming >> lane) & 1);
values.push(value);
mask |= u32::from(flag) << lane;
}
}
masks.extend(std::iter::repeat_n(mask, wave.len()));
}
cases.push((program(&body, 3), values));
body.push(0x7e08_026a); // v_mov_b32_e32 v4, vcc_lo
cases.push((program(&body, 4), masks));
}
}
}
}
cases
}
#[test]
fn vop2_vcc_matches_guide_on_both_interpreters() {
let input = input();
for (index, (code, expected)) in cases().into_iter().enumerate() {
compile(Architecture::Gfx1030, &code).unwrap();
assert_eq!(
xenora_ref::execute(&code, &input).unwrap(),
expected,
"reference case {index}"
);
assert_eq!(
independent_ref::execute(&code, &input).unwrap(),
expected,
"independent case {index}"
);
}
}
#[test]
fn vop2_vcc_rejects_unsupported_operands_and_uninitialized_state() {
let mut cases = Vec::new();
for op in FORMS {
cases.push((program(&[vop2(op, 2, 129, 1)], 2), 12));
for selector in [107, 124, 126, 128 + 112, 249, 250] {
cases.push((program(&[vop2(op, 2, selector, 1), 0], 2), 12));
}
let fixture = words(&[vop2(op, 2, 255, 1)]);
assert!(matches!(
compile(Architecture::Gfx1030, &fixture),
Err(CompileError::Decode(_))
));
assert!(xenora_ref::execute(&fixture, &[1]).is_err());
assert!(independent_ref::execute(&fixture, &[1]).is_err());
cases.push((
program(&[0xbeea_03c1, 0xbefe_0381, vop2(op, 2, 129, 1)], 2),
20,
));
}
// LLVM-assembled e64 forms with an explicit scalar condition operand.
for first in [0xd501_0002, 0xd528_0902, 0xd529_0902, 0xd52a_0902] {
cases.push((program(&[first, 0x0022_0303], 2), 12));
}
for (code, offset) in cases {
let result = compile(Architecture::Gfx1030, &code);
let got = match result {
Err(CompileError::Decode(error)) => error.offset,
Err(CompileError::Verify { offset, .. }) => offset,
other => panic!("expected rejection at {offset:#x}: {other:?}"),
};
assert_eq!(got, offset);
assert_eq!(
xenora_ref::execute(&code, &[1, 2]).unwrap_err().offset,
offset
);
assert!(
independent_ref::execute(&code, &[1, 2])
.unwrap_err()
.starts_with(&format!("{offset:#x}:"))
);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop2_vcc_matches_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 metal = xenora_metal::NativeCompute::new().unwrap();
let input = input();
let fixture = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
let fixture_expected = input
.chunks(32)
.flat_map(|wave| {
let mask = wave
.iter()
.enumerate()
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane));
std::iter::repeat_n(mask, wave.len())
})
.collect();
for (index, (code, expected)) in cases()
.into_iter()
.chain([(fixture.to_vec(), fixture_expected)])
.enumerate()
{
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert_eq!(
metal
.run_words(&shader.msl, xenora_shader::ENTRY_POINT, &input)
.unwrap(),
expected,
"Metal case {index}",
);
}
}
+302
View File
@@ -0,0 +1,302 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer compares. Guide §3.9 permits an SGPR destination in
//! the 64-bit encoding and describes the fully rewritten per-lane mask.
//! A Wave32 mask has 32 bits (§2.1), so SDST consumes one 32-bit SGPR (§5.2).
//! The opcode relations are in §12.9, the re-encoding in §12.9.1, and the
//! VOP3A fields in §13.3.4. These are spec-derived expectations.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 16] = [
(128, "v_cmp_f_i32"),
(129, "v_cmp_lt_i32"),
(130, "v_cmp_eq_i32"),
(131, "v_cmp_le_i32"),
(132, "v_cmp_gt_i32"),
(133, "v_cmp_ne_i32"),
(134, "v_cmp_ge_i32"),
(135, "v_cmp_t_i32"),
(192, "v_cmp_f_u32"),
(193, "v_cmp_lt_u32"),
(194, "v_cmp_eq_u32"),
(195, "v_cmp_le_u32"),
(196, "v_cmp_gt_u32"),
(197, "v_cmp_ne_u32"),
(198, "v_cmp_ge_u32"),
(199, "v_cmp_t_u32"),
];
const VALUES: [u32; 10] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
0x00ff_ffff,
0x0080_0000,
0xff80_0000,
0x0100_0001,
0xff00_0003,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn passes(op: u32, a: u32, b: u32) -> bool {
let operand = |value: u32| {
if op < 192 {
i64::from(value as i32)
} else {
i64::from(value)
}
};
let (a, b) = (operand(a), operand(b));
match op & 7 {
// D[threadId] = 0.
0 => false,
// D[threadId] = (S0 < S1).
1 => a < b,
// D[threadId] = (S0 == S1).
2 => a == b,
// D[threadId] = (S0 <= S1).
3 => a <= b,
// D[threadId] = (S0 > S1).
4 => a > b,
// D[threadId] = (S0 <> S1).
5 => a != b,
// D[threadId] = (S0 >= S1).
6 => a >= b,
// D[threadId] = 1.
_ => true,
}
}
fn expected_mask(op: u32, exec: u32, wave: &[u32], bound: u32, reverse: bool) -> u32 {
// §3.9: VCC[n] = EXEC[n] & (test passed for thread[n]).
// §3.9 uses the same result for the alternate scalar destination.
wave.iter().enumerate().fold(0, |mask, (n, &x)| {
let (a, b) = if reverse { (bound, x) } else { (x, bound) };
mask | (exec & (u32::from(passes(op, a, b)) << n))
})
}
fn vop3(op: u32, dst: u32, reverse: bool) -> [u32; 2] {
let (a, b) = if reverse { (511, 257) } else { (257, 511) };
[0xd400_0000 | op << 16 | dst, a | b << 9 | 128 << 18]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(bound: u32, exec: u32) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend([0x7ffe_02ff, bound]); // v255 = literal
code.extend(smov(126, exec));
code
}
fn store(mut code: Vec<u32>) -> Vec<u8> {
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn mask_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for bound in VALUES {
for reverse in [false, true] {
for exec in MASKS {
for (lanes, dst) in [(7, 106), (32, 106), (45, 106), (45, 0), (45, 105)] {
let mut code = setup(bound, exec);
// Give the old VCC bits on both sides of EXEC.
code.extend(smov(106, 0xa5a5_5a5a));
code.extend(vop3(op, dst, reverse));
code.extend([0xbefe_03c1, 0x7e04_0200 | dst]);
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.chunks(32)
.flat_map(|wave| {
let mask = expected_mask(op, exec, wave, bound, reverse);
std::iter::repeat_n(mask, wave.len())
})
.collect();
cases.push(Case {
form: name,
family: if dst == 106 { "vcc_lo" } else { "sgpr" },
label: format!("{name} s{dst}, bound={bound:#x}, reverse={reverse}, EXEC={exec:#x}, {lanes} lanes"),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
fn branch_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for dst in [0, 105, 106] {
for exec in MASKS {
for old_vcc in [0, 0xa5a5_5a5a] {
for nonzero in [false, true] {
let scc = old_vcc != 0;
let mut code = setup(0, u32::MAX);
// Seed s1 to detect an accidental second SGPR write to s0:s1.
code.extend(vop3(199, 1, false));
code.extend(smov(106, old_vcc));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend([0x7e04_0280, 0x7e08_0280, 0x7e0c_0284]); // v2 = v4 = 0, v6 = 4
code.extend(smov(126, exec));
code.extend(vop3(op, dst, false));
code.extend([
0x7e08_0281, // v4 = 1 only where EXEC was set
0xbefe_03c1,
// Independent bits for the VCC edge, SCC, and EXEC.
if nonzero { 0xbf87_0001 } else { 0xbf86_0001 },
0x7e04_0282, // v2 = 2 on fallthrough
0xbf84_0001,
0x3a04_0d02, // v2 ^= 4 if SCC = 1
0x3a04_0902, // v2 ^= v4
0x7e06_0201,
0x3a04_0702, // v2 ^= s1
0x7e06_026a,
0x3a04_0702, // v2 ^= VCC_LO
]);
// The two waves give opposite results for several relations.
let input: Vec<_> = std::iter::repeat_n(1, 32)
.chain(std::iter::repeat_n(u32::MAX, 13))
.collect();
let mut expected = Vec::new();
for wave in input.chunks(32) {
let mask = expected_mask(op, exec, wave, 0, false);
let vcc = if dst == 106 { mask } else { old_vcc };
// §12.5: if (VCC == 0) / if (VCC != 0), PC = PC + signext(SIMM16 * 4) + 4.
let taken = (vcc != 0) == nonzero;
let s1 = u32::MAX >> (32 - wave.len());
let marker = (u32::from(scc) << 2) | (u32::from(!taken) << 1);
expected.extend(
wave.iter()
.enumerate()
.map(|(n, _)| marker ^ ((exec >> n) & 1) ^ s1 ^ vcc),
);
}
cases.push(Case {
form: name,
family: "vcc branch and flags",
label: format!(
"{name} s{dst}, EXEC={exec:#x}, VCC={old_vcc:#x}, NZ={nonzero}"
),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_compare_matches_the_guide() {
let masks = mask_cases();
let branches = branch_cases();
assert_eq!(masks.len(), 16 * 10 * 2 * 4 * 5);
assert_eq!(branches.len(), 16 * 3 * 4 * 2 * 2);
for case in masks.iter().chain(&branches) {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!(
"vop3_compare: {} mask and {} branch/flag cases per CPU interpreter",
masks.len(),
branches.len()
);
}
#[test]
fn vop3_compare_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 106, false);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
// A successful decode would read its mask here and complete.
code.push(0x7e04_026a);
store(code)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
for dst in 107..=255 {
check(&[(head & !255) | dst, tail]);
}
check(&[head]);
}
assert_eq!(count, 16 * (13 + 512 + 511 + 149 + 1));
eprintln!("vop3_compare: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop3_vcc_compare_matches_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: Vec<_> = mask_cases()
.into_iter()
.filter(|case| case.family == "vcc_lo")
.collect();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop3_compare: {} Metal cases in {programs} programs",
cases.len()
);
}
+246
View File
@@ -0,0 +1,246 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer ALU forms. AMD RDNA 2 ISA guide §§12.7, 12.7.1,
//! 12.12 and 13.3.4. The expectations use the guide's arithmetic per lane.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 11] = [
(265, "v_mul_i32_i24"),
(266, "v_mul_hi_i32_i24"),
(267, "v_mul_u32_u24"),
(268, "v_mul_hi_u32_u24"),
(273, "v_min_i32"),
(274, "v_max_i32"),
(275, "v_min_u32"),
(276, "v_max_u32"),
(286, "v_xnor_b32"),
(294, "v_sub_nc_u32"),
(295, "v_subrev_nc_u32"),
];
const VALUES: [u32; 12] = [
0,
1,
2,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
0x00ff_ffff,
0xff80_0000,
0xff00_0003,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn expected(op: u32, a: u32, b: u32) -> u32 {
// S.i24 is bits 23:0 sign-extended from bit 23; S.u24 is zero-extended.
let i24 = |x: u32| (i64::from(x & 0x7f_ffff)) - i64::from(x & 0x80_0000);
let u24 = |x: u32| i64::from(x & 0xff_ffff);
match op {
// D.i32 = S0.i24 * S1.i24.
265 => (i24(a) * i24(b)) as u32,
// D.i32 = (S0.i24 * S1.i24)>>32.
266 => (i24(a) * i24(b)).div_euclid(1 << 32) as u32,
// D.u32 = S0.u24 * S1.u24.
267 => (u24(a) * u24(b)) as u32,
// D.u32 = (S0.u24 * S1.u24)>>32.
268 => (u24(a) * u24(b)).div_euclid(1 << 32) as u32,
// D.i32 = (S0.i32 < S1.i32 ? S0.i32 : S1.i32).
273 => (a as i32).min(b as i32) as u32,
// D.i32 = (S0.i32 >= S1.i32 ? S0.i32 : S1.i32).
274 => (a as i32).max(b as i32) as u32,
// D.u32 = (S0.u32 < S1.u32 ? S0.u32 : S1.u32).
275 => a.min(b),
// D.u32 = (S0.u32 >= S1.u32 ? S0.u32 : S1.u32).
276 => a.max(b),
// D.u32 = ~(S0.u32 ^ S1.u32).
286 => !(a ^ b),
// D.u32 = S0.u32 - S1.u32.
294 => (i64::from(a) - i64::from(b)) as u32,
// D.u32 = S1.u32 - S0.u32.
295 => (i64::from(b) - i64::from(a)) as u32,
_ => unreachable!("test only uses the listed forms"),
}
}
/// VOP3A: OP 25:16, VDST 7:0, three 9-bit sources, inline zero at SRC2.
fn vop3(op: u32, dst: u32, a: u32, b: u32) -> [u32; 2] {
[
0xd400_0000 | op << 16 | dst,
(256 + a) | (256 + b) << 9 | 128 << 18,
]
}
fn vmov(dst: u32, value: u32) -> [u32; 2] {
[0x7e00_02ff | dst << 17, value]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(b: u32, exec: u32, scc: bool) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend(vmov(255, b));
code.extend(vmov(2, 0xabad_1dea));
code.extend(smov(106, 0x1357_9bdf));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(smov(126, exec));
code
}
fn finish(mut code: Vec<u32>, dst: u32) -> Vec<u8> {
// Restore EXEC, read D and VCC_LO, and XOR in v1 when SCC is set.
code.extend([
0xbefe_03c1,
0x7e04_0300 | dst,
0x7e0c_026a,
0x3a04_0506,
0xbf84_0001,
0x3a04_0501,
0xe070_2000,
0x8001_0200,
0xbbfd_0000,
0xbf81_0000,
]);
words(&code)
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for b in VALUES {
for (dst, src0, src1) in [
(2, 1, 255),
(2, 255, 1),
(1, 1, 255),
(255, 1, 255),
(255, 255, 255),
] {
for exec in MASKS {
for lanes in [7, 32, 45] {
let scc = dst == 255;
let mut code = setup(b, exec, scc);
code.extend(vop3(op, dst, src0, src1));
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.iter()
.enumerate()
.map(|(lane, &x)| {
let read = |reg| if reg == 1 { x } else { b };
// Guide §3.3: a disabled lane retains its previous VGPR.
let d = if exec & (1 << (lane % 32)) != 0 {
expected(op, read(src0), read(src1))
} else {
match dst {
1 => x,
255 => b,
_ => 0xabad_1dea,
}
};
d ^ 0x1357_9bdf ^ if scc { x } else { 0 }
})
.collect();
cases.push(Case {
form: name,
family: "vop3 integer",
label: format!("{name} v{dst}, v{src0}, v{src1} ({b:#x}), EXEC={exec:#x}, {lanes} lanes"),
code: finish(code, dst),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_integer_matches_the_guide() {
let cases = cases();
assert_eq!(cases.len(), 11 * 12 * 5 * 4 * 3);
for case in &cases {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!("vop3_integer: {} cases per CPU interpreter", cases.len());
}
#[test]
fn vop3_integer_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX, false);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 2, 1, 255);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
finish(code, 2)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
check(&[head]);
}
assert_eq!(count, 11 * (13 + 512 + 511 + 1));
eprintln!("vop3_integer: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop3_integer_matches_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 = cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop3_integer: {} Metal cases in {programs} programs",
cases.len()
);
}