Compare commits

..
Author SHA1 Message Date
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
elforeign de00cb2bfd Merge remote-tracking branch 'origin/main' into task/215-stage-c 2026-11-24 04:08:15 -06:00
elforeign d8f9669280 semantics: require exact XML number formats and a sane count width (#215)
Review follow-up: a shift count must be FMT_NUM_U32 and other sources
must have the format their signedness implies, so a float format no
longer passes; a negative shift_count_bits is a diagnostic instead of a
crash. The stage C rows cite the guide pages where the forms are listed,
and the scalar ALU page names which suite covers which forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:15 -06:00
elforeign 19b2e9b5d5 semantics: dispatch through a generated OP-indexed table (#215)
With 17 forms the generated match on the masked word cost about 0.4 ns
(4 %) more per decoded SOP2 instruction than main. The generator now
emits a fixed-bits test plus a static table indexed by the OP field,
both derived from the XML snapshot and checked to select exactly the
same words; decoding is back to main's speed (10.05 ns).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:07:17 -06:00
Ranveer Soni bb6bc52c95 Merge pull request #258 from Swastickc/task/80-pe-mapping-limits
loader: bound total mapped PE image size before allocation (#80)
2026-11-24 15:37:11 +05:30
Ranveer Soni ba6bbb2e4a Merge pull request #259 from Swastickc/task/77-teb-startup-bounds
loader: validate startup stack and TEB layout before mapping (#77)
2026-11-24 15:36:51 +05:30
elforeign d3c1150854 changelog: stage C SOP2 forms through the registry (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:22 -06:00
elforeign a81d62ffe3 decoder: map the stage C SOP2 operations onto the reference in the consistency test (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:00 -06:00
Swastick Chowdhury bb1372cd70 loader: validate startup stack and TEB layout before mapping (#77)
Replace the saturating TEB address with checked arithmetic and reject a
stack below address zero, an overflowing TEB range, or a TEB overlapping
the stack before the image is parsed. Name the Win64 TEB field offsets
and add unit tests for layout validation and field placement.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:33:38 +05:30
elforeign 8d53d82981 Merge branch 'task/215-stage-c-oracle' into task/215-stage-c 2026-11-24 04:03:01 -06:00
elforeign ba2cfc2a00 validation: close two blind spots in the stage C cases (#215)
Review found that one register operand per inline constant hides some wrong
inline values (ANDN2 with s8 = 0x80000f0f cannot tell 16 from 0), and that the
odd-opcode check used a misaligned SGPR pair. Each inline now runs against a
word and its complement, and the 64-bit neighbours read aligned pairs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:02:10 -06:00
elforeign b13ab327f2 ref, validation: evaluate the stage C SOP2 forms in both interpreters (#215)
The reference interpreter and the second, independent interpreter now run
s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and s_ashr_i32 per the RDNA 2
guide: shifts use only S1[4:0] and every form sets SCC = (D != 0). The two use
different arithmetic (host bit ops vs per-bit and power-of-two evaluation),
so they cannot share a mistake with each other or with the expectations.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:00:28 -06:00
Swastick Chowdhury e7cb8db14f loader: bound total mapped PE image size before allocation (#80)
Sum max(VirtualSize, SizeOfRawData) over all sections and reject images
above a 256 MiB loader budget with SectionMappingError(AllocationFailed)
before any host allocation. Adds pe_mapping_limits tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:29:34 +05:30
elforeign e7795d0e5a validation: guide-derived expectations for the stage C SOP2 forms (#215)
Expected D and SCC for s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and
s_ashr_i32 are written from the RDNA 2 ISA guide (12.1, 5.3) before either
interpreter implements them, so the implementation cannot shape the oracle.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:57:55 -06:00
Ranveer Soni 3ff9ddde24 Merge pull request #255 from Swastickc/task/82-memory-boundaries
loader: check guest memory accesses across region boundaries (#82)
2026-11-24 15:25:18 +05:30
elforeign ff191d89bd isa: declare eight more SOP2 logical and shift forms in the registry (#215 stage C, WIP)
Adds andn2, orn2, nand, nor, xnor, lshl, lshr and ashr as registry
primitives with a declared shift-count width that the generator applies
as a mask and checks against the XML's unsigned count operand. The forms
reach the decoder and translator through the generated dispatch with no
per-form Rust. The independent oracle side lands separately.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:55:00 -06:00
Ranveer Soni 4039be8ee2 Merge pull request #256 from elforeign/task/215-s1-operand-domains
test(validation): independent operand-domain verification for SOP2/VOPC (#215 stage E)
2026-11-24 15:24:48 +05:30
Ranveer Soni 898b79dc84 Merge pull request #253 from Swastickc/task/81-reloc-validation
loader: validate base relocation directory, blocks and targets (#81)
2026-11-24 15:24:29 +05:30
Ranveer Soni 30d20c8f33 Merge pull request #254 from Swastickc/task/79-clippy-as-chunks
loader: use as_chunks for PE section headers (Clippy fix, #79 follow-up)
2026-11-24 15:24:21 +05:30
Swastick Chowdhury 0687a8add6 loader: check guest memory accesses across region boundaries (#82)
Route reads, writes, instruction fetches and loader bypass writes through
one resolver. Accesses may span adjacent mapped regions when each grants
the required permission; the whole range is checked before any byte is
copied, so failed accesses change nothing; address wraparound returns
Overflow. Adds memory_validation tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:22:14 +05:30
elforeign 791b736b0e changelog: note the operand-domain verification harness (#215 stage E)
Contributors need to know the harness exists, what it covers and that
its expectations are spec-derived, not hardware results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:51:06 -06:00
elforeign fcda9c09bd Merge remote-tracking branch 'origin/main' into task/215-s1-operand-domains
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
elforeign ad5a6f9c53 validation: operand-domain harness for SOP2 and VOPC forms (part of #215, stage E)
The nine SOP2 forms and twelve VOPC integer compares had known answers
for a few chosen inputs only. This harness generates their operand
domains (boundary values, 64-bit carry and borrow chains observing both
words, aliased registers, every integer inline constant, literals, s105
and v255, partial and zero EXEC with VCC seeded to -1, VCCZ through
s_cbranch_vccz, 32 distinct lane inputs) and runs each case on the
reference interpreter and on native Metal against expectations written
out from the public RDNA 2 guide in oracle.rs, which imports no Xenora
crate. Rejections cover a missing literal word (as truncated) and
encodings outside Xenora's subset (two literal selectors, VCC/TTMP/M0/
EXEC destinations, float inline constants), at the expected offset.

4788 cases and 498 rejections. Failures are listed per family. The
Metal part compiles its 1777 distinct programs on four threads: 16 s
with a cold shader cache on an M5 Pro, against 47 s on one thread.

The oracle agrees with an independent guide-only table on 436 of 440
cases; the other 4 are s_subb_u32 with S1 = 0xffffffff and SCC set,
where the guide leaves the width of S1 + SCC open. The oracle reads it
at full width and keeps those cases in their own family.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
Ranveer Soni f856671b6d Merge pull request #252 from elforeign/feat/semantic-registry
isa, decoder: declarative semantic registry with generated SOP2 dispatch (#215 stages A+B)
2026-11-24 15:14:41 +05:30
Swastick Chowdhury e1317322e1 loader: use as_chunks for PE section headers (#79 follow-up)
Rust 1.100 Clippy rejects chunks_exact with a constant size
(chunks_exact_to_as_chunks), which fails the pinned
cargo clippy -D warnings gate on main since #250. No behavior change.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:14:00 +05:30
Swastick Chowdhury 92fd955a8d loader: validate base relocation directory, blocks and targets (#81)
Read the relocation directory only when NumberOfRvaAndSizes covers it,
reject odd block sizes and trailing partial block headers, keep DIR64
targets inside SizeOfImage, and check the directory end offset. Adds
relocation_validation tests for positive, negative and zero rebasing and
each malformed case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:13:12 +05:30
elforeign 0609012903 docs: bring the registry guide in line with the post-review rules (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:41:10 -06:00
elforeign dffa50cd9c semantics: run the generator unit tests in CI and fail clearly below Python 3.11 (#215)
Align the merged generator tests with the pinned documents and the
complete unsupported list, add tests for the rules added after review,
run them in the existing CI step next to the coverage tests, and give
the coverage script the same explicit Python 3.11 error as the
generator instead of a traceback.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:40:52 -06:00
elforeign b541dce0cc Merge branch 'feat/semantic-registry-s4' into feat/semantic-registry 2026-11-24 03:40:09 -06:00
elforeign 52ecece126 docs, tests: semantic registry contributor guide and generator unit tests (#215)
Contributors had no written path for adding a form through the registry,
and the generator's rejection rules had no direct tests: a disabled check
would only show up if the real registry happened to break it.

The new unit tests feed small in-memory registries and a hand-written
snapshot that each break one rule, check that the real registry passes,
that render is deterministic and independent of key order, and that the
CLI's validate, generate and --check modes exit as documented. Each of
44 deliberate generator mutations makes at least one test fail.

The guide covers the files, every field and its allowed values, what the
validator checks, what the generator does not do, the commands, and a
worked example on s_addc_u32.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:39:17 -06:00
elforeign 440856a997 semantics: pin cited documents and reject a boolean schema; reject duplicate generated rows in coverage (#215)
Follow-up to the independent review: a citation can no longer point at
another file, schema = true no longer passes as 1, the coverage reader
fails on a duplicated FORM_IDS row, and 'not yet' lowering is not
counted.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:38:49 -06:00
elforeign 1eeb614ea2 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:36:34 -06:00
elforeign afd936b20b semantics: close validation gaps found in review; check generated files in CI (#215)
The generator now rejects float widths, reserved variant names,
out-of-range pages and opcodes, Wave32 restrictions the decoder cannot
enforce yet, operand rules whose unsupported list differs from what the
decoder rejects, and undeclared or empty guide documents. The coverage
report reads decoder support from the compiled FORM_IDS table instead of
the registry, needs a decoding row before counting reference or Metal
evidence, and fails on unimplemented lowering. CI runs both --check
modes and the coverage unit tests so a stale generated file fails.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:36:18 -06:00
Ranveer Soni 6772205213 Merge pull request #251 from Swastickc/task/83-jit-capacity
loader: check JIT page size and capacity arithmetic (#83)
2026-11-24 15:04:40 +05:30
Ranveer Soni 4b5e2b690d Merge pull request #250 from Swastickc/task/79-pe-validation
loader: validate PE headers, section ranges and entry point (#79)
2026-11-24 15:04:31 +05:30
Ranveer Soni ee6c9ac067 fix(docs): synchronize generated status tables
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 15:03:22 +05:30
elforeign 1680e6b19c docs: describe the semantic registry and link the coverage report (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:32:41 -06:00
elforeign 3eef0ecfa8 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:32:10 -06:00
Swastick Chowdhury 999de9f2df loader: validate PE headers, section ranges and entry point (#79)
Fix two parser panics found by the pe_parse fuzz target: a truncated
PE32+ optional header and unchecked RVA range arithmetic. Also require
the 112-byte fixed optional header, check section table and raw data
bounds, reject overlapping sections and require the entry point to lie in
an executable section. Adds pe_validation regression tests built from
original synthetic images.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:02:00 +05:30
elforeign e616583c3f audit: add the semantic coverage report (#215 stage F slice)
Counts identified, encoding-validated, declared, decoder, IR/MSL,
reference and Metal evidence per encoding family, reading evidence only
from docs/status.toml so registry requirements never count as results.
Unrecognized inputs fail instead of being skipped. --check never writes.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:31:57 -06:00
Swastick Chowdhury 025f9dfd21 loader: check JIT page size and capacity arithmetic (#83)
Reject a failed, zero or non-power-of-two page size, and use checked
arithmetic for page rounding, emitted instruction length and code-cache
capacity. Adds unit tests for each overflow and boundary case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:01:50 +05:30
Ranveer Soni d8c02270ee stuff 2026-11-24 15:01:17 +05:30
Ranveer Soni 08c4451e68 docs: add draw, blend and depth contract sections to the interface contracts 2026-11-24 15:01:17 +05:30
Ranveer Soni 2ab189ddbe docs: refresh the engineering progress page for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni fa94b56ba3 docs: refresh the documentation index for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni 385e7a0729 readme: refresh the closing statement with the current research focus 2026-11-24 15:01:17 +05:30
Ranveer Soni 819699e8a7 readme: refresh the build, test and verification sections 2026-11-24 15:01:17 +05:30
Ranveer Soni 4404e3f4bb readme: refresh texture support and current limitations for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni d35cea8eff readme: refresh the architecture section for the current graphics passes 2026-11-24 15:01:17 +05:30
Ranveer Soni 8a69f80aa0 readme: add blend pass, indexed draws and depth pass as verified graphics work 2026-11-24 15:01:17 +05:30
Ranveer Soni c21d9ba92a readme: update milestone table statuses for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni e06242f2e0 readme: refresh the header and project summary for the current state 2026-11-24 15:01:17 +05:30
elforeign c9e3394eb3 isa, decoder: generate SOP2 dispatch from the semantic registry (#215 stage A+B)
generate_semantics.py validates the registry against its closed
vocabulary and the pinned XML snapshot (opcode, family, SCC input and
output, operand widths and signed formats) and emits static Rust tables.
The decoder now selects SOP2 operations through the generated from_word
match, and ScalarAluOp's mnemonic, SCC read and evaluation come from the
registry through shared primitives instead of hand-written per-opcode
code. The nine SOP2 opcode entries leave generate_rdna2.py.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:27:07 -06:00
Ranveer Soni 72d2ceb967 Merge pull request #249 from elforeign/task/156-cpu-decode-fuzz
fuzz: bounded CPU decoder fuzz target
2026-11-24 14:56:13 +05:30
elforeign 358ddc5eba isa: pin the semantic registry schema and Rust vocabulary (#215 stage A)
Freeze the registry format and typed vocabulary first so the parallel
slices (verification harness, coverage report, docs) can build against
them. The nine SOP2 forms are declared as data; the generator, validation
and decoder wiring follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:22:05 -06:00
elforeign 09cf27186c fuzz: add bounded cpu_decode target for the static probe decoder
Issue #156 asks for a bounded, non-executing fuzz target for the CPU
decoder. No public single-instruction decode API exists, so the target
wraps up to 4096 fuzz bytes as the code section of a fixed, original
PE32+ header and runs the public read-only probe_pe_bytes twice with a
bounded ProbeConfig. It asserts identical reports, the 15-byte x86
instruction limit, and that each record lies in and matches the input.
A startup self-check (nop; ret must decode to two records) stops a run
whose synthetic header no longer reaches the decoder.

A 600 s campaign found one decoder defect (unlimited segment prefixes
give instructions over 15 bytes), reported on #74 and not fixed here.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:19:21 -06:00
Ranveer Soni 9ac1343e34 Merge pull request #248 from elforeign/task/193-blending
gpu: native blend pass with per-draw blend state and write masks (#193)
2026-11-24 14:41:20 +05:30
elforeign 078afd4591 ref: bound the blend reference extent and parse rounding flags strictly (#193)
The second independent review found that an extent such as [usize::MAX, 1]
passed the overflow check and then panicked in the allocation, and that any
flag character other than 'e' silently granted the native tolerance. The
reference now accepts 1..=4096 pixels, the native limit, and the parser
rejects unknown flags.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:09:23 -06:00
elforeign 4741409de1 Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/src/compute.rs
#	crates/metal/src/lib.rs
#	crates/metal/src/render.rs
#	crates/ref/src/lib.rs
2026-11-24 03:06:27 -06:00
elforeign 6cbe976990 gpu: address independent review of the blend pass (#193)
The review found that the CPU blend reference multiplied an unchecked extent
before allocating, that only the second draw of each case varied its state,
and that the docs did not say Min/Max ignore the factors.

- The reference rejects empty or overflowing extents, with a unit test.
- New clean-room case first_draw_blended: a blended, masked first draw
  under a differently configured second draw (re-derived in a fresh
  session that reproduced the first 38 cases exactly).
- Doc and changelog wording now state the coverage scope precisely.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:06:03 -06:00
Ranveer Soni 857bec29e1 Merge pull request #247 from elforeign/task/192-indexed-draws
gpu: indexed draws with base vertex, native Metal and loader (#192)
2026-11-24 14:32:46 +05:30
elforeign 7b6c6fd92c Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 03:01:19 -06:00
elforeign 28846561ab gpu: native blend pass with per-draw blend state and write mask (#193)
Blending and colour write masks had no native path or check. Add
NativeCompute::render_blend: flat triangles drawn in order into an RGBA8
target, each with its own write mask and either blending disabled or
separate RGB and alpha factors and operations (one pipeline per draw,
since both are pipeline state in Metal).

xenora-ref gains an exact blend reference that also reports which
channels need rounding. Expected images were derived independently in a
clean room from the public Metal blend equations. The tolerance was fixed
before measuring: exact channels must match, rounded channels may differ
by 1.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:01:09 -06:00
elforeign 817a95b419 loader: test a vertex-buffer offset and zero-count backend calls; split recording and execution errors in the changelog (#192)
The second independent review asked for coverage of a nonzero vertex-buffer
offset and proof that zero-count draws never reach the backend, and for the
changelog to say which errors recording raises and which execution raises.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:58:29 -06:00
elforeign 33c025a785 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:55:08 -06:00
elforeign c0cbc2f787 gpu: tighten the indexed-draw contract after independent review (#192)
The review found that a raw primitive-restart index could pass the native
range check with a negative base vertex, that the loader ignored instance
parameters and could wrap a guest address, and that coverage missed flat
multi-triangle draws, an unadjusted textured draw and 32-bit indices above
16 bits.

- Native and CPU reference reject the raw restart value whatever the base.
- The loader rejects index counts other than 0 or 3 first, more than one
  instance and a nonzero start instance, and checks guest address
  arithmetic through the last byte read.
- Three clean-room cases added (re-derived in a fresh session, which also
  reproduced the first 13); native error checks now name each reason, and
  the loader error test proves no rejected draw reaches the backend.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:54:55 -06:00
Ranveer Soni e8b0a380e9 Merge pull request #246 from elforeign/task/157-pe-parse-fuzz
fuzz: bounded PE parser fuzz target
2026-11-24 14:24:24 +05:30
elforeign df3b9674a3 Merge remote-tracking branch 'origin/main' into task/157-pe-parse-fuzz
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:51:15 -06:00
elforeign db50deb9f7 fuzz: add bounded PE parser fuzz target
Add a pe_parse cargo-fuzz target that feeds malformed bytes to
ParsedPe::parse and rva_to_file_offset and, only when the summed
section mapping size and SizeOfImage are at most 64 MiB, to the checked
load_into_memory mapping step. No guest code is executed.

Refs #157

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:51:05 -06:00
elforeign 76679a9c05 changelog: keep the Added list without blank lines
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:47:59 -06:00
elforeign 6785cb04e3 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:47:49 -06:00
elforeign 99c8331576 gpu: indexed draws with base vertex, native Metal and loader (#192)
Indexed draws had no contract: the loader had no index buffer command and
the Metal backend only drew non-indexed triangles. Add a bounded one:

- NativeCompute::render_indexed issues real drawIndexedPrimitives calls on
  a 16- or 32-bit index buffer with a start index and signed base vertex,
  optionally sampling a natively uploaded BC1 texture.
- The loader gains SetIndexBuffer (DXGI R16_UINT/R32_UINT only) and
  DrawIndexedInstanced, which fetches one triangle through the index
  buffer and base vertex and feeds the existing one-triangle backend.
- Both reject bad formats, offsets and counts, indices past the buffer and
  any index + base vertex outside the vertex buffer before drawing.
- xenora-ref gains an index-fetch reference over the depth rasteriser.

Expected images and fetch lists were derived independently (clean room)
from public D3D12, Metal and BC1 documentation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:46:58 -06:00
Ranveer Soni 077a215d49 Merge pull request #243 from elforeign/task/138-threadgroup-sizing
metal: measure threadgroup sizing; keep the 64-thread default (#138)
2026-11-24 14:08:26 +05:30
Ranveer Soni 3c710b53ba Merge pull request #242 from atesahmet0/task/200-indirect-control
Verify indirect CALL and JMP target fetch, stack and retirement
2026-11-24 14:06:31 +05:30
Ranveer Soni 4886e9cd80 Merge pull request #241 from atesahmet0/task/86-precise-faults
Preserve precise guest fault state and retired instructions
2026-11-24 14:06:25 +05:30
elforeign 4dc10ae437 metal: check the requested group width directly; report all bench runs
The independent review noted that a 65-thread grid at width 1024 would also
pass if the width were clamped to the grid, so threads now also report
dispatch_threads_per_threadgroup. The changelog now gives all three benchmark
runs, including the slower first one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:34:06 -06:00
elforeign 16debc8fdb Merge remote-tracking branch 'origin/main' into task/138-threadgroup-sizing
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:31:44 -06:00
elforeign ee8347a39f metal: explicit threadgroup widths, measured against the default (#138)
Expose a bounded way to dispatch at a chosen width so every legal
configuration can be checked for identical known answers, including grids
that do not divide evenly, and timed against the default policy. On an
Apple M5 Pro widths 64-256 tie (median 58.8 us GPU), 512 is 6% slower and
1024 about 2x, so the default of 64 stays. run() keeps its signature; the
sized path is a separate private helper.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:31:33 -06:00
Ranveer Soni 6689761db3 Merge pull request #240 from elforeign/task/191-depth-attachment
metal: depth attachment known-answer rendering (#191)
2026-11-24 14:00:29 +05:30
ates 7aa8166cf2 Verify indirect CALL and JMP target fetch, stack and retirement
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
ates c107f3a43f Preserve precise guest fault state and retired instructions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
83 changed files with 11195 additions and 388 deletions

No files matched your search

+6
View File
@@ -38,6 +38,8 @@ jobs:
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
@@ -48,6 +50,10 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
+8
View File
@@ -11,6 +11,14 @@ remains unsupported.
### Added
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
Generated
+7
View File
@@ -179,6 +179,13 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+51 -14
View File
@@ -2,13 +2,17 @@
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
### At a glance
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
@@ -18,7 +22,7 @@ Xenora is still experimental. It currently executes independently authored synth
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
### Development milestones
@@ -33,14 +37,14 @@ The latest verified milestone includes **translated gfx1030 vertex and pixel sha
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subet |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
@@ -97,14 +101,35 @@ The current graphics subset supports:
- Offscreen RGBA8 render targets.
- Native GPU readback and pixel-by-pixel validation.
- Explicit rejection of unsupported shader forms.
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
### Blend pass
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
GPU verification (Metal API and shader validation enabled): 39 Metal-validated passes over two original overlapping triangles — a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
### Indexed draws
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
### Depth pass
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
### Verified Apple M5 results
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
Representative checks include:
@@ -115,6 +140,9 @@ Representative checks include:
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
| BC1 texture handling | 33 texels across selected mip levels and array layers |
| Guest rendering | PE32+ guest receives and checks the translated render output |
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
The expected results were calculated independently of the production shader translation path.
@@ -141,20 +169,20 @@ The resource system remains experimental. Native GPU work already in flight duri
## Texture support
Xenora includes an original BC1 texture-processing path.
Xenora includes original texture upload, readback and block-compression paths.
Implemented and tested functionality includes:
- Validated mip levels and array layers.
- Pitched texture uploads.
- Block-compressed texture handling.
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
- Native Metal texture readback.
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
@@ -209,6 +237,8 @@ flowchart TD
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
@@ -227,8 +257,8 @@ The following remain unsupported or incomplete:
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
| Graphics | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
@@ -272,6 +302,10 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
```
The format, lint and test trio is the standard check set. The native Metal
passes use Metal API and shader validation; `scripts/audit/status.py --check`
verifies the generated status tables.
### Run native Metal tests
These require a Metal-capable Apple Silicon Mac.
@@ -320,6 +354,9 @@ Testing distinguishes between:
Compiling a shader is not equivalent to proving its GPU output is correct.
### Where the work is heading
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
---
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Gate 1 shell: proves the app links the Rust runtime through the versioned C
// interface. It inspects the bundled trusted fixture and executes no guest code.
import CXenora
import Foundation
import SwiftUI
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
var body: some View {
Form {
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Guest execution and live display are not available in this build.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.frame(minWidth: 420, minHeight: 240)
}
}
struct XenoraApp: App {
var body: some Scene {
WindowGroup("Xenora") { ContentView() }
}
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+28 -29
View File
@@ -7,9 +7,8 @@ pub use xenora_isa::{
ScalarSource, VectorCompareOp, VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
@@ -17,19 +16,36 @@ use xenora_isa::{
};
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::FORM_IDS;
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination. Operand restrictions are listed in docs/status.toml;
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
/// operand combination: the hand-written forms below followed by every form of
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
/// restrictions are listed in docs/status.toml; every other form in
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
concat_forms();
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
let mut forms = [("", EncodingFamily::Sop2); N];
let mut index = 0;
while index < N {
forms[index] = if index < HANDWRITTEN_FORMS.len() {
HANDWRITTEN_FORMS[index]
} else {
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
};
index += 1;
}
forms
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_ADD_I32", EncodingFamily::Sop2),
("S_ADD_U32", EncodingFamily::Sop2),
("S_ADDC_U32", EncodingFamily::Sop2),
("S_AND_B32", EncodingFamily::Sop2),
("S_BRANCH", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
@@ -37,13 +53,8 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
("S_CMP_EQ_U32", EncodingFamily::Sopc),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_OR_B32", EncodingFamily::Sop2),
("S_SUB_I32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_SUBB_U32", EncodingFamily::Sop2),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("S_XOR_B32", EncodingFamily::Sop2),
("V_ADD_F32", EncodingFamily::Vop2),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
@@ -384,20 +395,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let target = branch_target(first, offset, "s_branch")?;
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
}
for (opcode, op) in [
(S_ADD_U32, ScalarAluOp::AddU32),
(S_SUB_U32, ScalarAluOp::SubU32),
(S_ADD_I32, ScalarAluOp::AddI32),
(S_SUB_I32, ScalarAluOp::SubI32),
(S_ADDC_U32, ScalarAluOp::AddcU32),
(S_SUBB_U32, ScalarAluOp::SubbU32),
(S_AND_B32, ScalarAluOp::AndB32),
(S_OR_B32, ScalarAluOp::OrB32),
(S_XOR_B32, ScalarAluOp::XorB32),
] {
if opcode.matches(first) {
return scalar_alu(op, first, bytes);
}
if let Some(op) = ScalarAluOp::from_word(first) {
return scalar_alu(op, first, bytes);
}
if S_CBRANCH_SCC0.matches(first) {
let target = branch_target(first, offset, "s_cbranch_scc0")?;
+10 -1
View File
@@ -340,6 +340,14 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
ScalarAluOp::NandB32 => ScalarAlu::Nand,
ScalarAluOp::NorB32 => ScalarAlu::Nor,
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
},
dst,
reference_scalar(src0),
@@ -434,13 +442,14 @@ fn compares_fixture_instructions_against_llvm() {
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
assert_eq!(forms.len(), 50, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[dependencies]
xenora-loader = { path = "../loader" }
+47
View File
@@ -0,0 +1,47 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
};
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
#endif
+264
View File
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
//!
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
//! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot.
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use xenora_loader::ParsedPe;
pub const XENORA_ABI_VERSION: u32 = 1;
pub const XENORA_OK: i32 = 0;
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
pub const XENORA_INVALID_HANDLE: i32 = 2;
pub const XENORA_VERSION_MISMATCH: i32 = 3;
pub const XENORA_INTERNAL_ERROR: i32 = 4;
pub const XENORA_PE_ERROR: i32 = 5;
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
/// Upper bound on simultaneously live sessions.
const MAX_SESSIONS: usize = 64;
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
struct Slot {
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
generation: u32,
}
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
fn guarded(f: impl FnOnce() -> i32) -> i32 {
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
}
fn split(handle: u64) -> (usize, u32) {
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
}
fn is_live(slots: &[Slot], handle: u64) -> bool {
let (index, generation) = split(handle);
slots
.get(index)
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_abi_version() -> u32 {
XENORA_ABI_VERSION
}
/// # Safety
/// `out_session` must be null or valid for one aligned `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
guarded(|| {
if out_session.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if abi_version != XENORA_ABI_VERSION {
return XENORA_VERSION_MISMATCH;
}
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
Some(index) => index,
None if slots.len() < MAX_SESSIONS => {
slots.push(Slot { generation: 0 });
slots.len() - 1
}
None => return XENORA_LIMIT_EXCEEDED,
};
let slot = &mut slots[index];
// ponytail: a slot retires after 2^31 reuses instead of wrapping its generation.
let Some(generation) = slot.generation.checked_add(1) else {
return XENORA_LIMIT_EXCEEDED;
};
slot.generation = generation;
// SAFETY: checked non-null above; the caller guarantees validity.
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
XENORA_OK
})
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
guarded(|| {
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
if !is_live(&slots, session) {
return XENORA_INVALID_HANDLE;
}
slots[split(session).0].generation += 1;
XENORA_OK
})
}
/// # Safety
/// Each output pointer must be null or valid for one aligned `u32` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
session: u64,
out_section_count: *mut u32,
out_entry_rva: *mut u32,
) -> i32 {
guarded(|| {
if out_section_count.is_null() || out_entry_rva.is_null() {
return XENORA_INVALID_ARGUMENT;
}
match SESSIONS.lock() {
Ok(slots) if is_live(&slots, session) => {}
Ok(_) => return XENORA_INVALID_HANDLE,
Err(_) => return XENORA_INTERNAL_ERROR,
}
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
return XENORA_PE_ERROR;
};
// SAFETY: both checked non-null above; the caller guarantees validity.
unsafe {
out_section_count.write(u32::from(pe.number_of_sections));
out_entry_rva.write(pe.entry_point_rva);
}
XENORA_OK
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ptr::null_mut;
/// The session table is process-global, so tests that fill or count it run one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn create() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
fn inspect(handle: u64) -> (i32, u32, u32) {
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
let status =
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
(status, sections, entry)
}
#[test]
fn header_and_rust_constants_agree() {
let header = include_str!("../include/xenora.h");
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
for (name, value) in [
("XENORA_OK", XENORA_OK),
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
("XENORA_PE_ERROR", XENORA_PE_ERROR),
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
] {
assert!(header.contains(&format!("{name} = {value},")), "{name}");
}
}
#[test]
fn session_inspects_the_trusted_fixture() {
let _serial = serial();
let handle = create();
// Independent expectation: read straight from the fixture's COFF and optional headers.
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
assert_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
#[test]
fn version_mismatch_and_null_outputs_are_rejected() {
let _serial = serial();
let mut handle = 7;
assert_eq!(
unsafe { xenora_session_create(2, &mut handle) },
XENORA_VERSION_MISMATCH
);
assert_eq!(handle, 7, "output untouched on failure");
assert_eq!(
unsafe { xenora_session_create(1, null_mut()) },
XENORA_INVALID_ARGUMENT
);
let live = create();
let mut x = 0;
assert_eq!(
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
XENORA_INVALID_ARGUMENT
);
xenora_session_destroy(live);
}
#[test]
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
let _serial = serial();
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
assert_eq!(
xenora_session_destroy(bogus),
XENORA_INVALID_HANDLE,
"{bogus:#x}"
);
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
}
let handle = create();
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
// Reusing the slot must not revive the old handle.
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
assert!(!reused.contains(&handle));
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
for h in reused {
xenora_session_destroy(h);
}
}
#[test]
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
let _serial = serial();
let threads: Vec<_> = (0..8)
.map(|_| {
std::thread::spawn(|| {
for _ in 0..500 {
let mut handle = 0;
let status = unsafe { xenora_session_create(1, &mut handle) };
assert_eq!(status, XENORA_OK);
assert_eq!(inspect(handle).0, XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
}
#[test]
fn panics_do_not_cross_the_boundary() {
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
}
}
-9
View File
@@ -18,15 +18,6 @@ VARIANTS = (
("S_ENDPGM", "ENC_SOPP"),
("S_MOV_B32", "ENC_SOP1"),
("S_CMP_EQ_U32", "ENC_SOPC"),
("S_ADD_U32", "ENC_SOP2"),
("S_SUB_U32", "ENC_SOP2"),
("S_ADD_I32", "ENC_SOP2"),
("S_SUB_I32", "ENC_SOP2"),
("S_ADDC_U32", "ENC_SOP2"),
("S_SUBB_U32", "ENC_SOP2"),
("S_AND_B32", "ENC_SOP2"),
("S_OR_B32", "ENC_SOP2"),
("S_XOR_B32", "ENC_SOP2"),
("S_CBRANCH_SCC0", "ENC_SOPP"),
("S_CBRANCH_EXECZ", "ENC_SOPP"),
("S_CBRANCH_VCCZ", "ENC_SOPP"),
+603
View File
@@ -0,0 +1,603 @@
#!/usr/bin/env python3
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
generate validate, then write crates/isa/src/semantics_gen.rs
--check validate and regenerate in memory; exit 1 if the committed file
differs. Never writes.
The registry is data only. Behaviour is chosen from a closed set of primitives
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
effect, never from a mnemonic. Only the Python standard library is used
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
"""
import argparse
import json
import re
import sys
from pathlib import Path
try:
import tomllib
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
ROOT = Path(__file__).resolve().parents[2]
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
SCHEMA = 1
ARCHITECTURE = "gfx1030"
FORM_KEYS = {
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
}
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
OPERATIONS = {
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
}
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor"}
ARITHMETIC = {"add", "sub"}
SHIFTS = {"lshl", "lshr", "ashr"}
# XML number formats a source may have for each declared signedness.
SOURCE_FORMATS = {
"signed": {"FMT_NUM_I32"},
"unsigned": {"FMT_NUM_U32"},
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
}
# Optional keys: required exactly when the condition holds.
SHIFT_KEY = "shift_count_bits"
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
CARRY_IN = {"none": "None", "scc": "Scc"}
SCC = {
"unchanged": "Unchanged",
"carry_out": "CarryOut",
"borrow": "Borrow",
"signed_overflow": "SignedOverflow",
"nonzero": "Nonzero",
}
MASK = {"unchanged": "Unchanged"}
WAVE = {"any": "Any", "wave32": "Wave32"}
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
# restriction could be declared but not enforced. Reject it until it can be.
ENFORCED_WAVES = {"any"}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
"metal": "Metal",
"llvm_encoding": "LlvmEncoding",
}
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
# The public documents spec references may cite, pinned so a citation cannot
# silently point at another file.
PINNED_DOCUMENTS = {
"guide": {
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
"file": "rdna2-shader-instruction-set-architecture.pdf",
"pages": 291,
},
"xml": {
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
"file": "amdgpu_isa_rdna2.xml",
},
}
WIDTHS = {32}
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
# A form whose declaration is not a row here has no primitive and is rejected.
PRIMITIVES = {
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
}
# Operand rules the decoder implements, each exactly once. A registry rule must
# match one of these shapes; anything else is an unimplemented rule.
UNSUPPORTED_COMBOS = {
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
}
OPERAND_RULES = {
"sop2_sgpr": {
"rust": "Sop2Sgpr",
"enum": "ScalarAluOp",
"shape": {
"family": "SOP2",
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
"src": [
{"field": "SSRC0", "class": "scalar_source"},
{"field": "SSRC1", "class": "scalar_source"},
],
"max_literals": 1,
},
# Every one of these is rejected by the decoder's SOP2 operand checks.
"unsupported": UNSUPPORTED_COMBOS,
},
}
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
RESERVED_VARIANTS = {"Self", "ALL"}
U16_MAX = 0xFFFF
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
def load_registry(path=REGISTRY):
"""Parse the TOML registry into a dict."""
with open(path, "rb") as handle:
return tomllib.load(handle)
def load_snapshot(path=SNAPSHOT):
"""Index the normalised XML snapshot: source line, encodings, default variants."""
source = None
encodings = {}
variants = {}
with open(path, encoding="utf-8") as handle:
for line in handle:
record = json.loads(line)
kind = record.get("kind")
if kind == "source":
source = record
elif kind == "encoding":
encodings[record["name"]] = record
elif kind == "variant" and record.get("condition") == "default":
variants[(record["instruction"], record["encoding"])] = record
return {"source": source or {}, "encodings": encodings, "variants": variants}
def _family_encoding(family):
return "ENC_" + family
def _rust_family(family):
return family[0] + family[1:].lower()
def _check_rule(name, rule, errors):
implemented = OPERAND_RULES.get(name)
if implemented is None:
errors.append(f"operand rule {name}: not implemented by the decoder")
return
unsupported = rule.get("unsupported", [])
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
if unknown:
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
if len(set(unsupported)) != len(unsupported):
errors.append(f"operand rule {name}: duplicate unsupported combos")
if set(unsupported) != implemented["unsupported"]:
errors.append(
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
)
declared = {key: value for key, value in rule.items() if key != "unsupported"}
if declared != implemented["shape"]:
errors.append(
f"operand rule {name}: declaration differs from the decoder's implemented rule"
)
def _check_xml(form, rule, snapshot, errors):
label = form["name"]
encoding_name = _family_encoding(form["family"])
encoding = snapshot["encodings"].get(encoding_name)
if encoding is None:
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
return
variant = snapshot["variants"].get((form["name"], encoding_name))
if variant is None:
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
return
if variant["opcode"] != form["opcode"]:
errors.append(
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
)
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
operands = {}
scc_in = scc_out = False
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
if kind == "OPR_SSRC_SPECIAL_SCC":
scc_in |= is_input
scc_out |= is_output
elif field:
operands[field] = (data_format, size, is_input, is_output)
if scc_in != (form["carry_in"] == "scc"):
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
if scc_out != (form["scc"] != "unchanged"):
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
if rule is None:
return
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
count_field = rule["src"][1]["field"] if form["operation"] in SHIFTS else None
for field, is_source in fields:
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
if size != form["width"]:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
if (is_input, is_output) != (is_source, not is_source):
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
errors.append(
f"{label}: shift count {field} has XML format {data_format}, not FMT_NUM_U32"
)
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
errors.append(
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
)
extra = sorted(set(operands) - {field for field, _ in fields})
if extra:
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
def _identifier(encoding, opcode):
fields = dict((name, ranges) for name, ranges in encoding["fields"])
(offset, size), = fields["OP"]
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
return base | (opcode << offset)
def validate(registry, snapshot):
"""Return every error in the registry; an empty list means it is valid."""
errors = []
unknown = sorted(set(registry) - TOP_KEYS)
if unknown:
errors.append(f"unknown top-level keys {unknown}")
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
if registry.get("architecture") != ARCHITECTURE:
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
errors.append("source_sha256 does not match the XML snapshot")
documents = registry.get("documents", {})
for name, document in documents.items():
if name not in DOCUMENTS:
errors.append(f"unknown document {name}")
elif document != PINNED_DOCUMENTS[name]:
errors.append(f"document {name}: differs from the pinned public document")
if "guide" not in documents:
errors.append("the guide document is not declared")
rules = registry.get("operand_rules", {})
for name, rule in rules.items():
_check_rule(name, rule, errors)
forms = registry.get("form", [])
if not forms:
errors.append("the registry declares no forms")
seen = {"name": set(), "opcode": set(), "variant": set()}
for index, form in enumerate(forms):
label = form.get("name", f"form #{index}")
missing = sorted(FORM_KEYS - set(form))
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY})
if missing:
errors.append(f"{label}: incomplete, missing {missing}")
if extra:
errors.append(f"{label}: unknown keys {extra}")
if missing:
continue
for key, vocabulary in (
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
):
if form[key] not in vocabulary:
errors.append(f"{label}: unknown {key} {form[key]!r}")
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
errors.append(f"{label}: invalid name")
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
errors.append(f"{label}: invalid variant {form['variant']!r}")
if form["variant"] in RESERVED_VARIANTS:
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")
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
if type(form["width"]) is not int or form["width"] not in WIDTHS:
errors.append(f"{label}: width {form['width']} is not supported")
for key, value in (
("name", form["name"]),
("opcode", (form["family"], form["opcode"])),
("variant", form["variant"]),
):
if value in seen[key]:
errors.append(f"{label}: duplicate {key} {value}")
seen[key].add(value)
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
):
errors.append(
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
)
if form["operation"] in SHIFTS:
bits = form.get(SHIFT_KEY)
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
errors.append(
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
)
elif SHIFT_KEY in form:
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
if primitive is None:
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
else:
scc, _, takes_carry = primitive
if form["scc"] != scc:
errors.append(
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
f"{form['signedness']} (requires {scc})"
)
if form["carry_in"] == "scc" and not takes_carry:
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
rule = rules.get(form["operands"])
if rule is None:
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
elif rule.get("family") != form["family"]:
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
_check_spec(label, form["spec"], documents, errors)
verify = form["verify"]
if not verify:
errors.append(f"{label}: no verification requirement")
if any(item not in EVIDENCE for item in verify):
errors.append(f"{label}: unknown verification requirement in {verify}")
if len(set(verify)) != len(verify):
errors.append(f"{label}: duplicate verification requirement")
_check_xml(form, rule, snapshot, errors)
return errors
def _check_spec(label, spec, documents, errors):
has_guide = False
for ref in spec:
if set(ref) != {"document", "section", "page"}:
errors.append(f"{label}: spec reference needs exactly document, section, page")
continue
if ref["document"] not in documents:
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
if not SECTION.match(str(ref["section"])):
errors.append(f"{label}: invalid spec section {ref['section']!r}")
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
errors.append(f"{label}: invalid spec page")
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
has_guide = True
if not has_guide:
errors.append(f"{label}: missing a guide section and page reference")
def render(registry, snapshot):
"""Return the complete generated Rust source. Requires a valid registry."""
forms = registry["form"]
rule_names = sorted({form["operands"] for form in forms})
positions = {form["name"]: position for position, form in enumerate(forms)}
out = [
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
"",
"use crate::meta::EncodingFamily;",
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, Wave,",
"};",
"",
"/// Registry schema of the generated tables.",
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
]
for rule_name in rule_names:
selected = [form for form in forms if form["operands"] == rule_name]
out += _render_enum(rule_name, selected, snapshot, positions)
out += [
"",
"/// Identity of every registry form, in registry order.",
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
]
for form in forms:
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
out += [
"];",
"",
"/// One validated row per registry form, in registry order.",
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
]
for form in forms:
spec = ", ".join(
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
f"section: \"{ref['section']}\", page: {ref['page']} }}"
for ref in form["spec"]
)
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
out += [
" FormSemantics {",
f" name: \"{form['name']}\",",
f" family: EncodingFamily::{_rust_family(form['family'])},",
f" opcode: {form['opcode']},",
f" operation: Operation::{OPERATIONS[form['operation']]},",
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
f" width: {form['width']},",
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
f" scc: SccEffect::{SCC[form['scc']]},",
f" vcc: MaskEffect::{MASK[form['vcc']]},",
f" exec: MaskEffect::{MASK[form['exec']]},",
f" wave: Wave::{WAVE[form['wave']]},",
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
f" spec: &[{spec}],",
f" verify: &[{verify}],",
" },",
]
out += ["];", ""]
return "\n".join(out)
def _render_enum(rule_name, forms, snapshot, positions):
enum = OPERAND_RULES[rule_name]["enum"]
family = forms[0]["family"]
encoding = snapshot["encodings"][_family_encoding(family)]
mask = encoding["identifier_mask"]
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
op_mask = ((1 << size) - 1) << offset
fixed_mask = mask & ~op_mask
fixed_bits = encoding["identifiers"][0] & fixed_mask
# Every identifier of the family must share the fixed bits, or the split
# into an encoding test plus an OP match would change which words match.
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
mask & op_mask != op_mask
):
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
out = [
"",
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
f"pub enum {enum} {{",
]
for form in forms:
carry = " plus SCC" if form["carry_in"] == "scc" else ""
out += [
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
f" {form['variant']},",
]
by_opcode = {form["opcode"]: form["variant"] for form in forms}
out += [
"}",
"",
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
f"const BY_OPCODE: [Option<{enum}>; {1 << size}] = [",
]
out += [
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
for opcode in range(1 << size)
]
out += [
"];",
"",
f"impl {enum} {{",
" /// Every operation, in registry order.",
f" pub const ALL: [Self; {len(forms)}] = [",
]
out += [f" Self::{form['variant']}," for form in forms]
out += [
" ];",
"",
f" /// Selects the operation from a first instruction word: the {family} encoding",
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
" pub const fn from_word(word: u32) -> Option<Self> {",
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
" return None;",
" }",
f" BY_OPCODE[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
" }",
"",
" /// Lower-case mnemonic.",
" pub const fn mnemonic(self) -> &'static str {",
" match self {",
]
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
out += [
" }",
" }",
"",
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The validated registry row.",
" pub fn semantics(self) -> &'static FormSemantics {",
" &FORMS[match self {",
]
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
out += [
" }]",
" }",
"",
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
" /// consume it (ignored by the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
" match self {",
]
for form in forms:
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
if takes_carry:
argument = "carry_in" if form["carry_in"] == "scc" else "false"
call = f"primitive::{function}(src0, src1, {argument})"
elif form["operation"] in SHIFTS:
mask = (1 << form[SHIFT_KEY]) - 1
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
else:
call = f"primitive::{function}(src0, src1)"
out.append(f" Self::{form['variant']} => {call},")
out += [" }", " }", "}"]
return out
def _display(path):
try:
return path.resolve().relative_to(ROOT)
except ValueError:
return path
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
parser.add_argument("--registry", type=Path, default=REGISTRY)
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
parser.add_argument("--output", type=Path, default=RUST)
arguments = parser.parse_args()
if bool(arguments.mode) == arguments.check:
parser.error("choose exactly one of generate, validate or --check")
registry = load_registry(arguments.registry)
snapshot = load_snapshot(arguments.snapshot)
errors = validate(registry, snapshot)
if errors:
for error in errors:
print(f"error: {error}", file=sys.stderr)
return 1
count = len(registry["form"])
if arguments.mode == "validate":
print(f"registry valid: {count} forms")
return 0
text = render(registry, snapshot)
if arguments.check:
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
if current != text:
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
return 1
print(f"registry valid and generated code current: {count} forms")
return 0
arguments.output.write_text(text, encoding="utf-8")
print(f"wrote {_display(arguments.output)}: {count} forms")
return 0
if __name__ == "__main__":
sys.exit(main())
+374
View File
@@ -0,0 +1,374 @@
# Declarative semantic registry for gfx1030 (AMD RDNA 2) instruction forms.
#
# Data only: no code strings, no expressions. Every value is a member of a closed
# vocabulary that crates/isa/generate_semantics.py validates and turns into static
# Rust tables (crates/isa/src/semantics_gen.rs). Identity, family, opcode and
# operand facts are cross-checked against the pinned AMD XML snapshot
# (crates/isa/data/rdna2.jsonl); behaviour comes from the public AMD guide cited
# per form, never from the mnemonic. See docs/shaders/semantic-registry.md.
#
# Independence: the reference interpreter (crates/ref) and the second
# interpreter (tests/validation/independent_ref.rs) never read this file.
schema = 1
architecture = "gfx1030"
# Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl.
source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
# Named public documents that spec references point at.
[documents.guide]
title = "AMD RDNA 2 Instruction Set Architecture Reference Guide"
file = "rdna2-shader-instruction-set-architecture.pdf"
pages = 291
[documents.xml]
title = "AMD RDNA 2 machine-readable ISA (pinned XML)"
file = "amdgpu_isa_rdna2.xml"
# Operand rules shared by a family. A rule names its destination and source
# classes; the decoder implements each rule once (rules are not per opcode).
[operand_rules.sop2_sgpr]
family = "SOP2"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
max_literals = 1
# Encodings this rule rejects, so they stay unsupported rather than guessed.
unsupported = [
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
"src_special", "two_literals",
]
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
# Field meanings:
# name XML instruction name (stable identity)
# family encoding family; must match the XML base encoding
# opcode XML opcode; must match
# variant Rust enum variant of the typed op
# operation primitive: add | sub | and | or | xor
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
# carry_in none | scc (scc only for unsigned add/sub)
# width operand and result width in bits
# scc carry_out | borrow | signed_overflow | nonzero
# vcc, exec unchanged (stated, not implied)
# wave any | wave32
# 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
[[form]]
name = "S_ADD_U32"
family = "SOP2"
opcode = 0
variant = "AddU32"
operation = "add"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_U32"
family = "SOP2"
opcode = 1
variant = "SubU32"
operation = "sub"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADD_I32"
family = "SOP2"
opcode = 2
variant = "AddI32"
operation = "add"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_I32"
family = "SOP2"
opcode = 3
variant = "SubI32"
operation = "sub"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADDC_U32"
family = "SOP2"
opcode = 4
variant = "AddcU32"
operation = "add"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUBB_U32"
family = "SOP2"
opcode = 5
variant = "SubbU32"
operation = "sub"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_AND_B32"
family = "SOP2"
opcode = 14
variant = "AndB32"
operation = "and"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_OR_B32"
family = "SOP2"
opcode = 16
variant = "OrB32"
operation = "or"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XOR_B32"
family = "SOP2"
opcode = 18
variant = "XorB32"
operation = "xor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
[[form]]
name = "S_ANDN2_B32"
family = "SOP2"
opcode = 20
variant = "Andn2B32"
operation = "andn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ORN2_B32"
family = "SOP2"
opcode = 22
variant = "Orn2B32"
operation = "orn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NAND_B32"
family = "SOP2"
opcode = 24
variant = "NandB32"
operation = "nand"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOR_B32"
family = "SOP2"
opcode = 26
variant = "NorB32"
operation = "nor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XNOR_B32"
family = "SOP2"
opcode = 28
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL_B32"
family = "SOP2"
opcode = 30
variant = "LshlB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHR_B32"
family = "SOP2"
opcode = 32
variant = "LshrB32"
operation = "lshr"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ASHR_I32"
family = "SOP2"
opcode = 34
variant = "AshrI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+7 -83
View File
@@ -3,18 +3,22 @@
use std::fmt;
pub mod meta;
pub mod primitive;
mod rdna2;
pub mod semantics;
#[rustfmt::skip]
mod rdna2_meta;
#[rustfmt::skip]
mod semantics_gen;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
pub use semantics_gen::ScalarAluOp;
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
@@ -164,86 +168,6 @@ impl VectorCompareOp {
}
}
/// SOP2 32-bit integer operations in the supported scalar subset.
///
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume
/// SCC as carry-in or borrow-in, signed forms store signed overflow (RDNA 2 ISA
/// guide 12.1), and bitwise operations set SCC iff the result is nonzero. See
/// docs/shaders/scalar-alu.md for the sources.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAluOp {
/// `s_add_u32`: D = S0 + S1, SCC = carry-out.
AddU32,
/// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0).
SubU32,
/// `s_add_i32`: D = S0 + S1, SCC = signed overflow.
AddI32,
/// `s_sub_i32`: D = S0 - S1, SCC = signed overflow.
SubI32,
/// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out.
AddcU32,
/// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow.
SubbU32,
/// `s_and_b32`: D = S0 & S1, SCC = D != 0.
AndB32,
/// `s_or_b32`: D = S0 | S1, SCC = D != 0.
OrB32,
/// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0.
XorB32,
}
impl ScalarAluOp {
/// Lower-case mnemonic.
pub fn mnemonic(self) -> &'static str {
match self {
Self::AddU32 => "s_add_u32",
Self::SubU32 => "s_sub_u32",
Self::AddI32 => "s_add_i32",
Self::SubI32 => "s_sub_i32",
Self::AddcU32 => "s_addc_u32",
Self::SubbU32 => "s_subb_u32",
Self::AndB32 => "s_and_b32",
Self::OrB32 => "s_or_b32",
Self::XorB32 => "s_xor_b32",
}
}
/// The 32-bit result and the new SCC, with `carry_in` the SCC read by
/// ADDC and SUBB (ignored by the other operations).
pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
let carry = u32::from(carry_in && self.reads_scc());
match self {
Self::AddU32 | Self::AddcU32 => {
let (partial, first) = src0.overflowing_add(src1);
let (value, second) = partial.overflowing_add(carry);
(value, first || second)
}
Self::SubU32 | Self::SubbU32 => {
let (partial, first) = src0.overflowing_sub(src1);
let (value, second) = partial.overflowing_sub(carry);
(value, first || second)
}
Self::AddI32 => {
let (value, overflow) = (src0 as i32).overflowing_add(src1 as i32);
(value as u32, overflow)
}
Self::SubI32 => {
let (value, overflow) = (src0 as i32).overflowing_sub(src1 as i32);
(value as u32, overflow)
}
Self::AndB32 => (src0 & src1, src0 & src1 != 0),
Self::OrB32 => (src0 | src1, src0 | src1 != 0),
Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0),
}
}
/// Whether the operation reads SCC as a carry-in or borrow-in.
pub fn reads_scc(self) -> bool {
matches!(self, Self::AddcU32 | Self::SubbU32)
}
}
/// Output targeted by a supported uncompressed four-component export.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExportTarget {
+100
View File
@@ -0,0 +1,100 @@
//! Reusable integer semantic primitives selected by the generated registry dispatch.
//!
//! Each function implements one closed [`crate::semantics::Operation`] at one
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
//! Forms share a primitive only when their declared operation, signedness and
//! SCC effect are identical; the generator never selects one by mnemonic.
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_add(b);
let (value, second) = partial.overflowing_add(carry_in as u32);
(value, first || second)
}
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_sub(b);
let (value, second) = partial.overflowing_sub(borrow_in as u32);
(value, first || second)
}
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_add(b as i32);
(value as u32, overflow)
}
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
(value as u32, overflow)
}
/// Bitwise AND and whether the result is nonzero.
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & b;
(value, value != 0)
}
/// Bitwise OR and whether the result is nonzero.
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | b;
(value, value != 0)
}
/// Bitwise XOR and whether the result is nonzero.
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a ^ b;
(value, value != 0)
}
/// Bitwise `a & !b` and whether the result is nonzero.
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & !b;
(value, value != 0)
}
/// Bitwise `a | !b` and whether the result is nonzero.
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | !b;
(value, value != 0)
}
/// Bitwise `!(a & b)` and whether the result is nonzero.
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a & b);
(value, value != 0)
}
/// Bitwise `!(a | b)` and whether the result is nonzero.
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a | b);
(value, value != 0)
}
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a ^ b);
(value, value != 0)
}
/// `a << count` and whether the result is nonzero. The caller masks the count
/// to the declared count width, so `count` is below 32.
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a << count;
(value, value != 0)
}
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a >> count;
(value, value != 0)
}
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
let value = ((a as i32) >> count) as u32;
(value, value != 0)
}
-45
View File
@@ -50,51 +50,6 @@ pub const S_CMP_EQ_U32: Opcode = Opcode {
bits: 0xbf060000,
bytes: 4,
};
pub const S_ADD_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x80000000,
bytes: 4,
};
pub const S_SUB_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x80800000,
bytes: 4,
};
pub const S_ADD_I32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x81000000,
bytes: 4,
};
pub const S_SUB_I32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x81800000,
bytes: 4,
};
pub const S_ADDC_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x82000000,
bytes: 4,
};
pub const S_SUBB_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x82800000,
bytes: 4,
};
pub const S_AND_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x87000000,
bytes: 4,
};
pub const S_OR_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x88000000,
bytes: 4,
};
pub const S_XOR_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x89000000,
bytes: 4,
};
pub const S_CBRANCH_SCC0: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf840000,
+176
View File
@@ -0,0 +1,176 @@
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
//!
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
//! time; the decoder and translator call the generated `const fn`s and `match`es.
//!
//! The reference interpreter (`crates/ref`) and the independent interpreter
//! (`tests/validation/independent_ref.rs`) must not use this module.
use crate::meta::EncodingFamily;
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
/// Version of the registry schema this crate was generated against.
pub const SCHEMA: u32 = 1;
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
/// any other name, and each primitive has one implementation in `primitive.rs`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operation {
/// Integer addition.
Add,
/// Integer subtraction.
Sub,
/// Bitwise AND.
And,
/// Bitwise OR.
Or,
/// Bitwise exclusive OR.
Xor,
/// Bitwise AND with the complement of S1.
AndNot,
/// Bitwise OR with the complement of S1.
OrNot,
/// Complement of bitwise AND.
Nand,
/// Complement of bitwise OR.
Nor,
/// Complement of bitwise exclusive OR.
Xnor,
/// Shift S0 left by the masked count in S1, filling with zeros.
ShiftLeft,
/// Shift S0 right by the masked count in S1, filling with zeros.
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Signedness {
/// Unsigned integers.
Unsigned,
/// Two's-complement integers.
Signed,
/// Untyped bits.
Bitwise,
}
/// Extra input consumed by the operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// No carry or borrow input.
None,
/// SCC as carry-in (add) or borrow-in (sub).
Scc,
}
/// What a form writes to SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SccEffect {
/// SCC is not written.
Unchanged,
/// Unsigned carry-out of the top bit.
CarryOut,
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
Borrow,
/// Two's-complement overflow of the exact result.
SignedOverflow,
/// The result is not zero.
Nonzero,
}
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MaskEffect {
/// Not written.
Unchanged,
}
/// Wave-size restriction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Wave {
/// Behaviour does not depend on the wave size.
Any,
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
Wave32,
}
/// Shared operand rule. The decoder implements each rule once.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperandRule {
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
/// or one literal word. Everything else is rejected as unsupported.
Sop2Sgpr,
}
/// Evidence a form needs before it counts as verified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Evidence {
/// `crates/ref` lockstep reference.
Reference,
/// `tests/validation/independent_ref.rs`.
Independent,
/// Native Metal known-answer runs.
Metal,
/// LLVM assembler/disassembler encoding agreement.
LlvmEncoding,
}
/// Public document a [`SpecRef`] points at.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Document {
/// AMD RDNA 2 ISA reference guide (PDF).
Guide,
/// Pinned AMD machine-readable XML.
Xml,
}
/// One public specification reference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SpecRef {
/// Source document.
pub document: Document,
/// Section number, for example `"12.1"`.
pub section: &'static str,
/// Page in the document, 0 when not paginated.
pub page: u16,
}
/// One validated registry row, emitted as a static table by the generator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormSemantics {
/// XML instruction name, the stable form identity.
pub name: &'static str,
/// Encoding family (matches [`crate::meta::FORMS`]).
pub family: EncodingFamily,
/// Opcode within the family.
pub opcode: u16,
/// Primitive.
pub operation: Operation,
/// Operand interpretation.
pub signedness: Signedness,
/// Carry or borrow input.
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
pub vcc: MaskEffect,
/// EXEC write.
pub exec: MaskEffect,
/// Wave-size restriction.
pub wave: Wave,
/// Operand rule.
pub operands: OperandRule,
/// Public references.
pub spec: &'static [SpecRef],
/// Required evidence.
pub verify: &'static [Evidence],
}
+622
View File
@@ -0,0 +1,622 @@
// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.
// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate
use crate::meta::EncodingFamily;
use crate::primitive;
use crate::semantics::{
CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,
Signedness, SpecRef, Wave,
};
/// Registry schema of the generated tables.
pub const GENERATED_SCHEMA: u32 = 1;
/// SOP2 operations declared in the semantic registry (operand rule `sop2_sgpr`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAluOp {
/// `s_add_u32` (SOP2 opcode 0): unsigned add, SCC = carry_out.
AddU32,
/// `s_sub_u32` (SOP2 opcode 1): unsigned sub, SCC = borrow.
SubU32,
/// `s_add_i32` (SOP2 opcode 2): signed add, SCC = signed_overflow.
AddI32,
/// `s_sub_i32` (SOP2 opcode 3): signed sub, SCC = signed_overflow.
SubI32,
/// `s_addc_u32` (SOP2 opcode 4): unsigned add plus SCC, SCC = carry_out.
AddcU32,
/// `s_subb_u32` (SOP2 opcode 5): unsigned sub plus SCC, SCC = borrow.
SubbU32,
/// `s_and_b32` (SOP2 opcode 14): bitwise and, SCC = nonzero.
AndB32,
/// `s_or_b32` (SOP2 opcode 16): bitwise or, SCC = nonzero.
OrB32,
/// `s_xor_b32` (SOP2 opcode 18): bitwise xor, SCC = nonzero.
XorB32,
/// `s_andn2_b32` (SOP2 opcode 20): bitwise andn2, SCC = nonzero.
Andn2B32,
/// `s_orn2_b32` (SOP2 opcode 22): bitwise orn2, SCC = nonzero.
Orn2B32,
/// `s_nand_b32` (SOP2 opcode 24): bitwise nand, SCC = nonzero.
NandB32,
/// `s_nor_b32` (SOP2 opcode 26): bitwise nor, SCC = nonzero.
NorB32,
/// `s_xnor_b32` (SOP2 opcode 28): bitwise xnor, SCC = nonzero.
XnorB32,
/// `s_lshl_b32` (SOP2 opcode 30): bitwise lshl, SCC = nonzero.
LshlB32,
/// `s_lshr_b32` (SOP2 opcode 32): unsigned lshr, SCC = nonzero.
LshrB32,
/// `s_ashr_i32` (SOP2 opcode 34): signed ashr, SCC = nonzero.
AshrI32,
}
/// ScalarAluOp by SOP2 OP field value; `None` for undeclared opcodes.
const BY_OPCODE: [Option<ScalarAluOp>; 128] = [
Some(ScalarAluOp::AddU32),
Some(ScalarAluOp::SubU32),
Some(ScalarAluOp::AddI32),
Some(ScalarAluOp::SubI32),
Some(ScalarAluOp::AddcU32),
Some(ScalarAluOp::SubbU32),
None,
None,
None,
None,
None,
None,
None,
None,
Some(ScalarAluOp::AndB32),
None,
Some(ScalarAluOp::OrB32),
None,
Some(ScalarAluOp::XorB32),
None,
Some(ScalarAluOp::Andn2B32),
None,
Some(ScalarAluOp::Orn2B32),
None,
Some(ScalarAluOp::NandB32),
None,
Some(ScalarAluOp::NorB32),
None,
Some(ScalarAluOp::XnorB32),
None,
Some(ScalarAluOp::LshlB32),
None,
Some(ScalarAluOp::LshrB32),
None,
Some(ScalarAluOp::AshrI32),
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
];
impl ScalarAluOp {
/// Every operation, in registry order.
pub const ALL: [Self; 17] = [
Self::AddU32,
Self::SubU32,
Self::AddI32,
Self::SubI32,
Self::AddcU32,
Self::SubbU32,
Self::AndB32,
Self::OrB32,
Self::XorB32,
Self::Andn2B32,
Self::Orn2B32,
Self::NandB32,
Self::NorB32,
Self::XnorB32,
Self::LshlB32,
Self::LshrB32,
Self::AshrI32,
];
/// Selects the operation from a first instruction word: the SOP2 encoding
/// bits (mask 0xc000_0000) and then the OP field (bits 23-29).
pub const fn from_word(word: u32) -> Option<Self> {
if word & 0xc000_0000 != 0x8000_0000 {
return None;
}
BY_OPCODE[((word >> 23) & 0x7f) as usize]
}
/// Lower-case mnemonic.
pub const fn mnemonic(self) -> &'static str {
match self {
Self::AddU32 => "s_add_u32",
Self::SubU32 => "s_sub_u32",
Self::AddI32 => "s_add_i32",
Self::SubI32 => "s_sub_i32",
Self::AddcU32 => "s_addc_u32",
Self::SubbU32 => "s_subb_u32",
Self::AndB32 => "s_and_b32",
Self::OrB32 => "s_or_b32",
Self::XorB32 => "s_xor_b32",
Self::Andn2B32 => "s_andn2_b32",
Self::Orn2B32 => "s_orn2_b32",
Self::NandB32 => "s_nand_b32",
Self::NorB32 => "s_nor_b32",
Self::XnorB32 => "s_xnor_b32",
Self::LshlB32 => "s_lshl_b32",
Self::LshrB32 => "s_lshr_b32",
Self::AshrI32 => "s_ashr_i32",
}
}
/// Whether the operation reads SCC as a carry-in or borrow-in.
pub const fn reads_scc(self) -> bool {
match self {
Self::AddU32 => false,
Self::SubU32 => false,
Self::AddI32 => false,
Self::SubI32 => false,
Self::AddcU32 => true,
Self::SubbU32 => true,
Self::AndB32 => false,
Self::OrB32 => false,
Self::XorB32 => false,
Self::Andn2B32 => false,
Self::Orn2B32 => false,
Self::NandB32 => false,
Self::NorB32 => false,
Self::XnorB32 => false,
Self::LshlB32 => false,
Self::LshrB32 => false,
Self::AshrI32 => false,
}
}
/// The validated registry row.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::AddU32 => 0,
Self::SubU32 => 1,
Self::AddI32 => 2,
Self::SubI32 => 3,
Self::AddcU32 => 4,
Self::SubbU32 => 5,
Self::AndB32 => 6,
Self::OrB32 => 7,
Self::XorB32 => 8,
Self::Andn2B32 => 9,
Self::Orn2B32 => 10,
Self::NandB32 => 11,
Self::NorB32 => 12,
Self::XnorB32 => 13,
Self::LshlB32 => 14,
Self::LshrB32 => 15,
Self::AshrI32 => 16,
}]
}
/// The result and the new SCC, with `carry_in` the SCC read by forms that
/// consume it (ignored by the others).
pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
match self {
Self::AddU32 => primitive::add_carry_u32(src0, src1, false),
Self::SubU32 => primitive::sub_borrow_u32(src0, src1, false),
Self::AddI32 => primitive::add_overflow_i32(src0, src1),
Self::SubI32 => primitive::sub_overflow_i32(src0, src1),
Self::AddcU32 => primitive::add_carry_u32(src0, src1, carry_in),
Self::SubbU32 => primitive::sub_borrow_u32(src0, src1, carry_in),
Self::AndB32 => primitive::and_nonzero_b32(src0, src1),
Self::OrB32 => primitive::or_nonzero_b32(src0, src1),
Self::XorB32 => primitive::xor_nonzero_b32(src0, src1),
Self::Andn2B32 => primitive::andn2_nonzero_b32(src0, src1),
Self::Orn2B32 => primitive::orn2_nonzero_b32(src0, src1),
Self::NandB32 => primitive::nand_nonzero_b32(src0, src1),
Self::NorB32 => primitive::nor_nonzero_b32(src0, src1),
Self::XnorB32 => primitive::xnor_nonzero_b32(src0, src1),
Self::LshlB32 => primitive::lshl_nonzero_b32(src0, src1 & 0x1f),
Self::LshrB32 => primitive::lshr_nonzero_b32(src0, src1 & 0x1f),
Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),
}
}
}
/// Identity of every registry form, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 17] = [
("S_ADD_U32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_ADD_I32", EncodingFamily::Sop2),
("S_SUB_I32", EncodingFamily::Sop2),
("S_ADDC_U32", EncodingFamily::Sop2),
("S_SUBB_U32", EncodingFamily::Sop2),
("S_AND_B32", EncodingFamily::Sop2),
("S_OR_B32", EncodingFamily::Sop2),
("S_XOR_B32", EncodingFamily::Sop2),
("S_ANDN2_B32", EncodingFamily::Sop2),
("S_ORN2_B32", EncodingFamily::Sop2),
("S_NAND_B32", EncodingFamily::Sop2),
("S_NOR_B32", EncodingFamily::Sop2),
("S_XNOR_B32", EncodingFamily::Sop2),
("S_LSHL_B32", EncodingFamily::Sop2),
("S_LSHR_B32", EncodingFamily::Sop2),
("S_ASHR_I32", EncodingFamily::Sop2),
];
/// One validated row per registry form, in registry order.
pub static FORMS: [FormSemantics; 17] = [
FormSemantics {
name: "S_ADD_U32",
family: EncodingFamily::Sop2,
opcode: 0,
operation: Operation::Add,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::CarryOut,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_SUB_U32",
family: EncodingFamily::Sop2,
opcode: 1,
operation: Operation::Sub,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Borrow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ADD_I32",
family: EncodingFamily::Sop2,
opcode: 2,
operation: Operation::Add,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::SignedOverflow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_SUB_I32",
family: EncodingFamily::Sop2,
opcode: 3,
operation: Operation::Sub,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::SignedOverflow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ADDC_U32",
family: EncodingFamily::Sop2,
opcode: 4,
operation: Operation::Add,
signedness: Signedness::Unsigned,
carry_in: CarryIn::Scc,
width: 32,
shift_count_bits: 0,
scc: SccEffect::CarryOut,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_SUBB_U32",
family: EncodingFamily::Sop2,
opcode: 5,
operation: Operation::Sub,
signedness: Signedness::Unsigned,
carry_in: CarryIn::Scc,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Borrow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_AND_B32",
family: EncodingFamily::Sop2,
opcode: 14,
operation: Operation::And,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_OR_B32",
family: EncodingFamily::Sop2,
opcode: 16,
operation: Operation::Or,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_XOR_B32",
family: EncodingFamily::Sop2,
opcode: 18,
operation: Operation::Xor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ANDN2_B32",
family: EncodingFamily::Sop2,
opcode: 20,
operation: Operation::AndNot,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ORN2_B32",
family: EncodingFamily::Sop2,
opcode: 22,
operation: Operation::OrNot,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_NAND_B32",
family: EncodingFamily::Sop2,
opcode: 24,
operation: Operation::Nand,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_NOR_B32",
family: EncodingFamily::Sop2,
opcode: 26,
operation: Operation::Nor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_XNOR_B32",
family: EncodingFamily::Sop2,
opcode: 28,
operation: Operation::Xnor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_LSHL_B32",
family: EncodingFamily::Sop2,
opcode: 30,
operation: Operation::ShiftLeft,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_LSHR_B32",
family: EncodingFamily::Sop2,
opcode: 32,
operation: Operation::LogicalShiftRight,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ASHR_I32",
family: EncodingFamily::Sop2,
opcode: 34,
operation: Operation::ArithmeticShiftRight,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
];
+60
View File
@@ -0,0 +1,60 @@
//! Ties the generated semantic registry tables to the independent XML metadata table.
use xenora_isa::ScalarAluOp;
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
#[test]
fn generated_tables_match_the_schema_and_the_metadata_forms() {
assert_eq!(GENERATED_SCHEMA, SCHEMA);
assert_eq!(FORM_IDS.len(), FORMS.len());
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
assert_eq!((row.name, row.family), (name, family));
let meta = META_FORMS
.iter()
.find(|form| form.name == row.name && form.family == row.family)
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
}
}
#[test]
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
for op in ScalarAluOp::ALL {
let row = op.semantics();
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
}
let mut selected = 0;
for meta in META_FORMS
.iter()
.filter(|form| form.family == EncodingFamily::Sop2)
{
let word = meta.bits as u32;
match ScalarAluOp::from_word(word) {
Some(op) => {
assert_eq!(op.semantics().name, meta.name);
selected += 1;
}
None => assert!(
FORMS.iter().all(|row| row.name != meta.name),
"{} is declared but not dispatched",
meta.name
),
}
}
assert_eq!(selected, FORMS.len());
// Other encodings never reach the SOP2 dispatch.
for meta in META_FORMS
.iter()
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
{
assert_eq!(
ScalarAluOp::from_word(meta.bits as u32),
None,
"{}",
meta.name
);
}
}
+9
View File
@@ -246,6 +246,15 @@ impl<'a> Interpreter<'a> {
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let start = self.cpu.rip;
let result = self.execute_instruction();
if result.is_err() {
self.cpu.rip = start;
}
result
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
+65 -1
View File
@@ -112,7 +112,19 @@ impl DbtEngine {
// Look up or translate block at cpu.rip
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
let block_fn_ptr = match self.get_or_compile_block(cpu.rip, memory, block_limit) {
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
// A decode failure can belong to a later instruction in the block.
// Execute the current instruction alone so earlier effects retire
// and an earlier data fault takes precedence over speculative fetch.
if block_limit > 1
&& matches!(
block,
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
)
{
block = self.get_or_compile_block(cpu.rip, memory, 1);
}
let block_fn_ptr = match block {
Ok(ptr) => ptr,
Err(reason) => {
return ExecutionResult {
@@ -1661,6 +1673,58 @@ mod tests {
assert_eq!(unsupported.instructions_executed, 0);
}
#[test]
fn completed_store_survives_the_next_fault_or_budget_boundary() {
for native in [false, true] {
for (tail, fault) in [
(&[0xcc][..], ExitReason::IllegalInstruction(0xcc)),
(
&[0xb8, 1][..],
ExitReason::MemoryFault(MemoryError::UnmappedAddress(ENTRY + 5)),
),
(
&[0x48, 0x8b, 0x02, 0xf4][..],
ExitReason::MemoryFault(MemoryError::UnmappedAddress(0x4000)),
),
] {
for budget in [0, 1, 16] {
// mov [rcx], rax; then an illegal, truncated or faulting instruction.
let code = [&[0x48, 0x89, 0x01][..], tail].concat();
let (mut engine, mut cpu, mut memory) = fixture(&code);
memory
.map_region(0x3000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
cpu.set(Register::Rax, 0x1234);
cpu.set(Register::Rcx, 0x3000);
cpu.set(Register::Rdx, 0x4000);
let mut expected = cpu.clone();
if budget > 0 {
expected.rip += 3;
}
let result = if native {
engine.run(&mut cpu, &mut memory, budget)
} else {
crate::cpu::Interpreter::new(cpu, &mut memory, budget).run()
};
assert_eq!(result.instructions_executed, budget.min(1));
assert_eq!(
result.exit_reason,
if budget <= 1 {
ExitReason::StepLimitExceeded
} else {
fault
}
);
assert_eq!(result.final_state, expected);
assert_eq!(
memory.read_u64(0x3000).unwrap(),
if budget == 0 { 0 } else { 0x1234 }
);
}
}
}
}
#[test]
fn hlt_preserves_first_memory_fault() {
let code = [
+241 -1
View File
@@ -117,6 +117,11 @@ pub enum GraphicsError {
DeviceCreationFailure(String),
BackendError(String),
NativeMetalRequired,
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
IndexOutOfRange,
}
impl std::fmt::Display for GraphicsError {
@@ -140,6 +145,10 @@ impl std::fmt::Display for GraphicsError {
f,
"native Metal backend required but not provided or failed"
),
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
}
}
}
@@ -173,6 +182,32 @@ pub struct GraphicsResource {
pub data: Vec<u8>,
}
/// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IndexFormat {
R16Uint,
R32Uint,
}
impl IndexFormat {
/// The format for a DXGI format code: `R16_UINT` (57) or `R32_UINT` (42).
pub const fn from_dxgi(format: u32) -> Option<Self> {
match format {
57 => Some(Self::R16Uint),
42 => Some(Self::R32Uint),
_ => None,
}
}
/// Bytes per index.
pub const fn size(self) -> usize {
match self {
Self::R16Uint => 2,
Self::R32Uint => 4,
}
}
}
/// Primitive Draw Command recorded in a Command List.
#[derive(Clone, Debug)]
pub enum GraphicsCommand {
@@ -200,6 +235,18 @@ pub enum GraphicsCommand {
start_vertex_location: u32,
start_instance_location: u32,
},
SetIndexBuffer {
resource: GraphicsHandle,
offset: usize,
format: IndexFormat,
},
DrawIndexedInstanced {
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
},
}
/// Command List in recording or closed state.
@@ -548,6 +595,72 @@ impl GraphicsContext {
Ok(())
}
/// Record set index buffer. `format` is a DXGI format code; only
/// `R16_UINT` (57) and `R32_UINT` (42) are index formats.
pub fn cmd_set_index_buffer(
&mut self,
list: GraphicsHandle,
resource: GraphicsHandle,
offset: usize,
format: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
let format =
IndexFormat::from_dxgi(format).ok_or(GraphicsError::InvalidIndexFormat(format))?;
let res = self
.resources
.get(&resource)
.ok_or(GraphicsError::InvalidResourceHandle)?;
if !offset.is_multiple_of(format.size()) || offset > res.data.len() {
return Err(GraphicsError::InvalidDescriptor);
}
cmd_list.commands.push(GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
});
Ok(())
}
/// Record draw indexed instanced. Each draw renders one triangle once: at
/// execution the index count must be 0 or 3, the instance count 0 or 1 and
/// the start instance 0, or the draw is rejected; a zero index or instance
/// count draws nothing. Index values are ordinary triangle-list indices
/// (no primitive restart), range checked after adding the base vertex.
pub fn cmd_draw_indexed_instanced(
&mut self,
list: GraphicsHandle,
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
cmd_list
.commands
.push(GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
});
Ok(())
}
/// Close command list.
pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> {
let cmd_list = self
@@ -649,6 +762,8 @@ impl GraphicsContext {
let mut target_handle: Option<GraphicsHandle> = None;
let mut vertex_resource: Option<GraphicsHandle> = None;
let mut vertex_offset = 0usize;
let mut vertex_stride = 0usize;
let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None;
let mut rendered_output: Option<Vec<u8>> = None;
let mut draw_count = 0usize;
@@ -679,10 +794,57 @@ impl GraphicsContext {
viewport = (*width, *height);
}
GraphicsCommand::SetVertexBuffer {
resource, offset, ..
resource,
offset,
stride,
} => {
vertex_resource = Some(*resource);
vertex_offset = *offset;
vertex_stride = *stride;
}
GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
} => index_buffer = Some((*resource, *offset, *format)),
GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
} => {
if !matches!(index_count_per_instance, 0 | 3)
|| *instance_count > 1
|| *start_instance_location != 0
{
return Err(GraphicsError::InvalidDescriptor);
}
if *index_count_per_instance == 0 || *instance_count == 0 {
continue;
}
let vertices = self.fetch_indexed_triangle(
memory,
index_buffer,
(vertex_resource, vertex_offset, vertex_stride),
*start_index_location,
*base_vertex_location,
)?;
draw_count += 1;
let pixels = if let Some(renderer) = backend_renderer {
renderer(&vertices, viewport, clear_color)?
} else if backend_id == GraphicsBackendId::MetalNative {
return Err(GraphicsError::NativeMetalRequired);
} else {
Self::execute_software_reference_draw(&vertices, viewport, clear_color)?
};
if let Some(th) = target_handle
&& let Some(target_res) = self.resources.get_mut(&th)
&& target_res.data.len() >= pixels.len()
{
target_res.data[..pixels.len()].copy_from_slice(&pixels);
}
rendered_output = Some(pixels);
}
GraphicsCommand::DrawInstanced {
vertex_count_per_instance,
@@ -761,6 +923,84 @@ impl GraphicsContext {
})
}
/// The three float4 positions one indexed triangle fetches: index `k` is
/// read at `offset + (start + k) * size` of the index buffer, and vertex
/// `index + base_vertex` at `offset + vertex * stride` of the vertex buffer.
fn fetch_indexed_triangle(
&self,
memory: &GuestMemory,
index_buffer: Option<(GraphicsHandle, usize, IndexFormat)>,
(vertex_resource, vertex_offset, vertex_stride): (Option<GraphicsHandle>, usize, usize),
start: u32,
base_vertex: i32,
) -> Result<[[f32; 4]; 3], GraphicsError> {
let resource = |handle: Option<GraphicsHandle>| {
handle
.and_then(|handle| self.resources.get(&handle))
.ok_or(GraphicsError::InvalidResourceHandle)
};
let (index_handle, index_offset, format) =
index_buffer.ok_or(GraphicsError::InvalidResourceHandle)?;
let index_res = resource(Some(index_handle))?;
let vertex_res = resource(vertex_resource)?;
if vertex_stride < 16 {
return Err(GraphicsError::InvalidDescriptor);
}
let size = format.size();
let mut raw_indices = [0u8; 12];
let raw_indices = &mut raw_indices[..3 * size];
let first = (start as usize)
.checked_mul(size)
.and_then(|bytes| bytes.checked_add(index_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
Self::read_resource(index_res, memory, first, raw_indices)?;
let mut vertices = [[0.0f32; 4]; 3];
for (row, index) in vertices.iter_mut().zip(raw_indices.chunks_exact(size)) {
let index = if size == 2 {
u32::from(u16::from_le_bytes([index[0], index[1]]))
} else {
u32::from_le_bytes(index.try_into().unwrap())
};
let vertex = usize::try_from(i64::from(index) + i64::from(base_vertex))
.map_err(|_| GraphicsError::IndexOutOfRange)?;
let at = vertex
.checked_mul(vertex_stride)
.and_then(|bytes| bytes.checked_add(vertex_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
let mut raw = [0u8; 16];
Self::read_resource(vertex_res, memory, at, &mut raw)?;
for (value, bytes) in row.iter_mut().zip(raw.as_chunks::<4>().0) {
*value = f32::from_le_bytes(*bytes);
}
}
Ok(vertices)
}
/// Read `out.len()` bytes at `offset` of a resource, from its guest backing
/// when it has one. The range must lie inside the resource's size.
fn read_resource(
res: &GraphicsResource,
memory: &GuestMemory,
offset: usize,
out: &mut [u8],
) -> Result<(), GraphicsError> {
let end = offset
.checked_add(out.len())
.filter(|&end| end <= res.data.len())
.ok_or(GraphicsError::IndexOutOfRange)?;
match res.guest_backing_addr {
Some(guest_addr) => {
let address = guest_addr
.checked_add(offset as u64)
.filter(|address| address.checked_add(out.len() as u64).is_some())
.ok_or(GraphicsError::IndexOutOfRange)?;
memory.read_bytes(address, out)?;
}
None => out.copy_from_slice(&res.data[offset..end]),
}
Ok(())
}
/// Software reference rasterizer for deterministic test verification when GPU tests are off.
pub fn execute_software_reference_draw(
vertices: &[[f32; 4]; 3],
+89 -6
View File
@@ -47,8 +47,8 @@ unsafe impl Sync for JitMemory {}
impl JitMemory {
/// Allocate a new JIT memory region using `MAP_JIT`.
pub fn new(capacity: usize) -> Result<Self, JitError> {
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
let aligned_capacity = aligned_capacity(capacity, page_size)?;
let ptr = unsafe {
libc::mmap(
@@ -98,10 +98,7 @@ impl JitMemory {
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
/// flushes data cache and invalidates instruction cache.
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
let bytes_len = instructions.len() * 4;
if self.used + bytes_len > self.capacity {
return Err(JitError::CapacityExceeded);
}
let bytes_len = emit_len(self.used, instructions.len(), self.capacity)?;
let emit_offset = self.used;
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
@@ -131,6 +128,27 @@ impl JitMemory {
}
}
/// Round `capacity` up to a whole number of pages, rejecting an invalid page size
/// (`sysconf` failure, zero or not a power of two) and arithmetic overflow.
fn aligned_capacity(capacity: usize, page_size: libc::c_long) -> Result<usize, JitError> {
let page_size = usize::try_from(page_size)
.ok()
.filter(|p| p.is_power_of_two())
.ok_or(JitError::AllocationFailed(libc::EINVAL))?;
capacity
.checked_add(page_size - 1)
.map(|c| c & !(page_size - 1))
.ok_or(JitError::CapacityExceeded)
}
/// Byte length of `count` 4-byte instructions, if they fit after `used` bytes.
fn emit_len(used: usize, count: usize, capacity: usize) -> Result<usize, JitError> {
count
.checked_mul(4)
.filter(|len| used.checked_add(*len).is_some_and(|end| end <= capacity))
.ok_or(JitError::CapacityExceeded)
}
impl Drop for JitMemory {
fn drop(&mut self) {
unsafe {
@@ -138,3 +156,68 @@ impl Drop for JitMemory {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capacity_rounds_up_to_whole_pages() {
assert_eq!(aligned_capacity(1, 16384), Ok(16384));
assert_eq!(aligned_capacity(16384, 16384), Ok(16384));
assert_eq!(aligned_capacity(16385, 16384), Ok(32768));
assert_eq!(aligned_capacity(0, 4096), Ok(0));
}
#[test]
fn invalid_page_size_is_rejected() {
for page in [-1, 0, 3, 12288] {
assert_eq!(
aligned_capacity(4096, page),
Err(JitError::AllocationFailed(libc::EINVAL)),
"page size {page}"
);
}
}
#[test]
fn capacity_rounding_overflow_is_rejected() {
assert_eq!(
aligned_capacity(usize::MAX, 16384),
Err(JitError::CapacityExceeded)
);
assert_eq!(
aligned_capacity(usize::MAX - 16382, 16384),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_length_is_checked() {
assert_eq!(emit_len(0, 4, 16), Ok(16));
assert_eq!(emit_len(4, 3, 16), Ok(12));
assert_eq!(emit_len(4, 4, 16), Err(JitError::CapacityExceeded));
// count * 4 overflows usize.
assert_eq!(
emit_len(0, usize::MAX / 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
// used + len overflows usize.
assert_eq!(
emit_len(usize::MAX - 3, 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_past_capacity_fails_and_leaves_usage_unchanged() {
let mut jit = JitMemory::new(1).expect("MAP_JIT allocation");
let words = jit.capacity() / 4;
assert!(jit.emit_block(&vec![0xD503_201F; words]).is_ok()); // NOP fills the page
assert_eq!(
jit.emit_block(&[0xD503_201F]),
Err(JitError::CapacityExceeded)
);
assert_eq!(jit.used(), jit.capacity());
}
}
+90 -66
View File
@@ -226,57 +226,102 @@ impl GuestMemory {
true
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
for region in &mut self.regions {
if region.contains(address, src.len()) {
if !region.permissions.write {
return Err(MemoryError::PermissionViolation {
address,
required: "write",
});
}
let offset = (address - region.base) as usize;
region.data[offset..offset + src.len()].copy_from_slice(src);
return Ok(());
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
///
/// An access may span adjacent regions, as it would span adjacent pages, but every
/// byte must be mapped and every region must grant `required` (`None` bypasses
/// permission checks for the loader). The whole range is checked before any byte
/// is copied, so a failed access never partially reads or writes.
fn resolve(
&self,
address: u64,
len: usize,
required: Option<&'static str>,
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
let end = address
.checked_add(len as u64)
.ok_or(MemoryError::Overflow)?;
if len == 0 {
return if self.regions.iter().any(|r| r.contains(address, 0)) {
Ok(Vec::new())
} else {
Err(MemoryError::UnmappedAddress(address))
};
}
let mut pieces = Vec::new();
let mut cursor = address;
for (index, region) in self.regions.iter().enumerate() {
let region_end = region.base + region.data.len() as u64;
if region_end <= cursor {
continue;
}
if region.base > cursor {
break;
}
let permitted = match required {
None => true,
Some("read") => region.permissions.read,
Some("write") => region.permissions.write,
Some(_) => region.permissions.execute,
};
if let (false, Some(required)) = (permitted, required) {
return Err(MemoryError::PermissionViolation { address, required });
}
let take = (end.min(region_end) - cursor) as usize;
pieces.push((index, (cursor - region.base) as usize, take));
cursor += take as u64;
if cursor == end {
return Ok(pieces);
}
}
Err(MemoryError::UnmappedAddress(address))
}
fn read_checked(
&self,
address: u64,
dst: &mut [u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
dst[done..done + take]
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
done += take;
}
Ok(())
}
fn write_checked(
&mut self,
address: u64,
src: &[u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
Ok(())
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
self.write_checked(address, src, Some("write"))
}
/// Read raw bytes from guest memory at the specified address, checking permissions.
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
for region in &self.regions {
if region.contains(address, dst.len()) {
if !region.permissions.read {
return Err(MemoryError::PermissionViolation {
address,
required: "read",
});
}
let offset = (address - region.base) as usize;
dst.copy_from_slice(&region.data[offset..offset + dst.len()]);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.read_checked(address, dst, Some("read"))
}
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
for region in &self.regions {
if region.contains(address, 1) {
if !region.permissions.execute {
return Err(MemoryError::PermissionViolation {
address,
required: "execute",
});
}
let offset = (address - region.base) as usize;
return Ok(region.data[offset]);
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 1];
self.read_checked(address, &mut buf, Some("execute"))?;
Ok(buf[0])
}
/// Read a 64-bit integer (little endian) from guest memory.
@@ -288,14 +333,9 @@ impl GuestMemory {
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
for region in &self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
return Ok(u64::from_le_bytes(buf));
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 8];
self.read_checked(address, &mut buf, None)?;
Ok(u64::from_le_bytes(buf))
}
/// Write a 64-bit integer (little endian) to guest memory.
@@ -305,15 +345,7 @@ impl GuestMemory {
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 8].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a 32-bit integer (little endian) from guest memory.
@@ -330,15 +362,7 @@ impl GuestMemory {
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 4) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 4].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a single byte from guest memory.
+108 -51
View File
@@ -91,6 +91,20 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
// Standard Constants
pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
fn read_u32(bytes: &[u8], at: usize) -> u32 {
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
}
impl ParsedPe {
/// Parse PE32+ headers from an in-memory byte slice.
@@ -105,80 +119,85 @@ impl ParsedPe {
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
if bytes.len() < e_lfanew + 24 {
let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?;
if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? {
return Err(PeError::TooSmall);
}
// 2. PE Signature
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
if &bytes[e_lfanew..coff_offset] != b"PE\0\0" {
return Err(PeError::InvalidPeSignature);
}
// 3. COFF File Header
let coff_offset = e_lfanew + 4;
let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap());
let machine = read_u16(bytes, coff_offset);
if machine != IMAGE_FILE_MACHINE_AMD64 {
return Err(PeError::UnsupportedMachine(machine));
}
let number_of_sections = read_u16(bytes, coff_offset + 2);
let time_date_stamp = read_u32(bytes, coff_offset + 4);
let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16));
let number_of_sections =
u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap());
let time_date_stamp =
u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap());
let size_of_optional_header = u16::from_le_bytes(
bytes[coff_offset + 16..coff_offset + 18]
.try_into()
.unwrap(),
) as usize;
// 4. Optional Header (PE32+ is required)
// 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at
// NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed.
let opt_offset = coff_offset + 20;
if bytes.len() < opt_offset + size_of_optional_header {
let section_table_offset = opt_offset + size_of_optional_header;
if bytes.len() < opt_offset + 2 {
return Err(PeError::TooSmall);
}
let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap());
let magic = read_u16(bytes, opt_offset);
if magic != PE32_PLUS_MAGIC {
return Err(PeError::InvalidMagic(magic));
}
if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER
|| bytes.len() < section_table_offset
{
return Err(PeError::TooSmall);
}
let entry_point_rva =
u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap());
let entry_point_rva = read_u32(bytes, opt_offset + 16);
let image_base =
u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap());
let section_alignment =
u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap());
let file_alignment =
u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap());
let size_of_image =
u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap());
let size_of_headers =
u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap());
let section_alignment = read_u32(bytes, opt_offset + 32);
let file_alignment = read_u32(bytes, opt_offset + 36);
let size_of_image = read_u32(bytes, opt_offset + 56);
let size_of_headers = read_u32(bytes, opt_offset + 60);
// 5. Section Headers
let mut sections = Vec::with_capacity(number_of_sections as usize);
let section_table_offset = opt_offset + size_of_optional_header;
let section_header_size = 40;
if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size)
{
let table_end = usize::from(number_of_sections)
.checked_mul(SECTION_HEADER_SIZE)
.and_then(|len| section_table_offset.checked_add(len))
.ok_or(PeError::InvalidSectionHeaders)?;
if bytes.len() < table_end {
return Err(PeError::InvalidSectionHeaders);
}
for i in 0..number_of_sections as usize {
let offset = section_table_offset + i * section_header_size;
let sec_bytes = &bytes[offset..offset + section_header_size];
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
for sec_bytes in bytes[section_table_offset..table_end]
.as_chunks::<SECTION_HEADER_SIZE>()
.0
{
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
let name_raw = &sec_bytes[0..8];
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned();
let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap());
let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap());
let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap());
let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap());
let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap());
let virtual_size = read_u32(sec_bytes, 8);
let virtual_address = read_u32(sec_bytes, 12);
let raw_data_size = read_u32(sec_bytes, 16);
let raw_data_ptr = read_u32(sec_bytes, 20);
let characteristics = read_u32(sec_bytes, 36);
// The mapped range must fit in the 32-bit RVA space, and raw data must be in the file.
virtual_address
.checked_add(virtual_size.max(raw_data_size))
.ok_or(PeError::InvalidSectionHeaders)?;
if raw_data_size > 0 {
let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size);
if raw_end > bytes.len() as u64 {
return Err(PeError::InvalidSectionHeaders);
}
}
let permissions = MemoryPermissions {
read: (characteristics & IMAGE_SCN_MEM_READ) != 0,
@@ -197,6 +216,32 @@ impl ParsedPe {
});
}
// Mapped section ranges must not overlap. Zero-sized sections map nothing.
let mut ranges: Vec<(u32, u32)> = sections
.iter()
.map(|s| {
(
s.virtual_address,
s.virtual_address + s.virtual_size.max(s.raw_data_size),
)
})
.filter(|(start, end)| start < end)
.collect();
ranges.sort_unstable();
if ranges.windows(2).any(|w| w[1].0 < w[0].1) {
return Err(PeError::InvalidSectionHeaders);
}
// The entry point must lie inside an executable section.
let entry_ok = sections.iter().any(|s| {
s.permissions.execute
&& entry_point_rva >= s.virtual_address
&& entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size)
});
if !entry_ok {
return Err(PeError::InvalidEntryPoint);
}
Ok(ParsedPe {
machine,
number_of_sections,
@@ -214,13 +259,12 @@ impl ParsedPe {
/// Translate a Relative Virtual Address (RVA) to a raw file offset.
pub fn rva_to_file_offset(&self, rva: u32) -> Option<usize> {
for sec in &self.sections {
let start = sec.virtual_address;
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= start && rva < start + size {
let diff = (rva - start) as usize;
if diff < sec.raw_data_size as usize {
return Some(sec.raw_data_ptr as usize + diff);
}
// Sections are public and may not come from `parse`, so stay checked here.
let Some(diff) = rva.checked_sub(sec.virtual_address) else {
continue;
};
if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size {
return (sec.raw_data_ptr as usize).checked_add(diff as usize);
}
}
None
@@ -232,6 +276,17 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
@@ -245,7 +300,9 @@ impl ParsedPe {
let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 {
let start = sec.raw_data_ptr as usize;
let end = start + sec.raw_data_size as usize;
let end = start
.checked_add(sec.raw_data_size as usize)
.ok_or(PeError::InvalidSectionHeaders)?;
bytes
.get(start..end)
.ok_or(PeError::InvalidSectionHeaders)?
+33 -5
View File
@@ -117,7 +117,10 @@ pub fn apply_relocations(
size: reloc_size,
})?;
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
if reloc_file_offset
.checked_add(reloc_size as usize)
.is_none_or(|end| end > bytes.len())
{
return Err(RelocationError::DirectoryOutOfBounds {
rva: reloc_rva,
size: reloc_size,
@@ -127,13 +130,20 @@ pub fn apply_relocations(
let mut read_bytes = 0usize;
let max_read = reloc_size as usize;
while read_bytes + 8 <= max_read {
while read_bytes < max_read {
// A partial block header after the last block is malformed, not padding.
if max_read - read_bytes < 8 {
return Err(RelocationError::MalformedBlockHeader {
offset: reloc_file_offset + read_bytes,
});
}
let block_start = reloc_file_offset + read_bytes;
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
let block_size =
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
if block_size < 8 {
// A block is an 8-byte header followed by whole 2-byte entries.
if block_size < 8 || block_size % 2 != 0 {
return Err(RelocationError::MalformedBlockHeader {
offset: block_start,
});
@@ -166,6 +176,15 @@ pub fn apply_relocations(
let target_rva = page_rva
.checked_add(offset_in_page)
.ok_or(RelocationError::ArithmeticOverflow)?;
// The 8-byte target must lie inside the image, not in other mapped memory.
if target_rva
.checked_add(8)
.is_none_or(|end| end > pe.size_of_image)
{
return Err(RelocationError::TargetOutOfBounds {
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
});
}
let target_va = loaded_base
.checked_add(target_rva as u64)
.ok_or(RelocationError::ArithmeticOverflow)?;
@@ -213,8 +232,8 @@ fn find_reloc_directory(
return Ok(None);
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
let opt_offset = e_lfanew + 24;
let coff_offset = e_lfanew + 4;
let opt_offset = coff_offset + 20;
if bytes.len() < coff_offset + 18 {
return Ok(None);
}
@@ -224,10 +243,19 @@ fn find_reloc_directory(
.unwrap(),
) as usize;
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
return Ok(None);
}
let number_of_rva_and_sizes = u32::from_le_bytes(
bytes[opt_offset + 108..opt_offset + 112]
.try_into()
.unwrap(),
);
if number_of_rva_and_sizes < 6 {
return Ok(None);
}
let reloc_rva = u32::from_le_bytes(
bytes[opt_offset + 152..opt_offset + 156]
+136 -16
View File
@@ -11,6 +11,14 @@ use crate::{
const STACK_SIZE: usize = 64 * 1024;
const JIT_CAPACITY: usize = 1024 * 1024;
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
const TEB_OFFSET: u64 = 0x10000;
const TEB_SIZE: usize = 0x2000;
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_SELF: u64 = 0x30;
const TEB_TLS_POINTER: u64 = 0x58;
/// Guest addresses reserved by the fixture harness.
pub struct StartupLayout {
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
)
.into());
}
// Reject an impossible layout before parsing or mapping anything.
let (stack_base, teb_base) = layout_regions(&layout)?;
let pe = ParsedPe::parse(bytes)?;
observe(StartupEvent::Parsed {
sections: pe.sections.len(),
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
)?;
}
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
// Allocate and initialize Win64 TEB (Thread Environment Block)
// Layout in TEB:
// +0x08: StackBase (highest address)
// +0x10: StackLimit (lowest address)
// +0x30: Self pointer (TEB linear address)
// +0x58: ThreadLocalStoragePointer
let teb_base = layout.tls_base.saturating_add(0x10000);
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
map_teb(memory, teb_base, &layout, stack_base)?;
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
engine.set_import_registry(imports);
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
dbt_metrics: engine.metrics,
})
}
/// Validate the harness layout and return `(stack_base, teb_base)`.
///
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
/// space and must not overlap each other.
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let teb_base = layout
.tls_base
.checked_add(TEB_OFFSET)
.ok_or(MemoryError::Overflow)?;
let teb_end = teb_base
.checked_add(TEB_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
if teb_base < layout.stack_top && stack_base < teb_end {
return Err(MemoryError::OverlappingRegion {
base: teb_base,
size: TEB_SIZE as u64,
});
}
Ok((stack_base, teb_base))
}
/// Map the Win64 TEB and write the fields the harness provides.
fn map_teb(
memory: &mut crate::GuestMemory,
teb_base: u64,
layout: &StartupLayout,
stack_base: u64,
) -> Result<(), MemoryError> {
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GuestMemory;
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
StartupLayout {
image_base: 0x1_4000_0000,
stack_top,
tls_base,
}
}
#[test]
fn valid_layout_places_stack_and_teb() {
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
}
#[test]
fn stack_below_zero_is_rejected() {
assert_eq!(
layout_regions(&layout(0x8000, 0x3_0000_0000)),
Err(MemoryError::Overflow)
);
}
#[test]
fn teb_address_overflow_is_rejected_not_saturated() {
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
assert_eq!(
layout_regions(&layout(0x2_0001_0000, tls_base)),
Err(MemoryError::Overflow),
"tls_base {tls_base:#x}"
);
}
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
// representable, and GuestMemory could not map that range either.
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
}
#[test]
fn teb_overlapping_stack_is_rejected() {
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
assert!(matches!(
layout_regions(&collide),
Err(MemoryError::OverlappingRegion { .. })
));
// Directly above the stack is fine.
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
}
#[test]
fn invalid_layout_fails_before_parsing() {
// Empty bytes would fail PE parsing; the layout error must come first.
let err = run_synthetic_startup(
&[],
layout(0x2_0001_0000, u64::MAX),
ImportRegistry::new(),
1,
)
.err()
.expect("startup must fail");
assert_eq!(
err.downcast_ref::<MemoryError>(),
Some(&MemoryError::Overflow)
);
}
#[test]
fn teb_fields_are_at_win64_offsets() {
let l = layout(0x2_0001_0000, 0x3_0000_0000);
let (stack_base, teb) = layout_regions(&l).unwrap();
let mut memory = GuestMemory::new();
map_teb(&mut memory, teb, &l, stack_base).unwrap();
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
}
}
+411
View File
@@ -590,3 +590,414 @@ fn test_guest_dbt_graphics_pipeline_metal_render_dual_inputs() {
let expected_clear = [10, 20, 30, 255];
assert_eq!(pixels2, expected_clear.repeat(12));
}
/// Guest addresses of the indexed-draw fixtures.
const INDEXED_VB: u64 = 0x7000_0000;
const INDEXED_IB: u64 = 0x7100_0000;
/// Vertex stride of the indexed fixtures: a float4 position and 16 unused bytes.
const INDEXED_STRIDE: usize = 32;
/// Triangle (4,3) (16,4) (6,16) of a 16x16 target in clip space; no pixel
/// centre lies on one of its edges.
const INDEXED_TRIANGLE: [[f32; 4]; 3] = [
[-0.5, 0.625, 0.5, 1.0],
[1.0, 0.5, 0.5, 1.0],
[-0.25, -1.0, 0.5, 1.0],
];
/// Ten vertices: the triangle at vertices 5, 7 and 2, and decoys elsewhere,
/// so a wrong fetch passes different positions.
fn indexed_vertices() -> Vec<u8> {
let mut bytes = Vec::new();
for vertex in 0..10 {
let position = match vertex {
5 => INDEXED_TRIANGLE[0],
7 => INDEXED_TRIANGLE[1],
2 => INDEXED_TRIANGLE[2],
other => [other as f32 * 0.125 - 0.75, -0.5, 0.5, 1.0],
};
for value in position {
bytes.extend(value.to_le_bytes());
}
bytes.extend([0xAB; 16]);
}
bytes
}
struct IndexedRig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vb: GraphicsHandle,
ib16: GraphicsHandle,
ib32: GraphicsHandle,
}
/// A context with guest-backed vertex and index buffers. The 16-bit buffer
/// holds 9, 9, 6, 8, 3, 5, 0 and the 32-bit buffer 9, 3, 5, 0, 7 and three
/// indices above 16 bits, 0x10003, 0x10005, 0x10000.
fn indexed_rig() -> IndexedRig {
use xenora_loader::memory::MemoryPermissions;
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
let buffer = |ctx: &mut GraphicsContext, bytes: usize, addr| {
let desc = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: bytes as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
ctx.create_committed_resource(device, desc, ResourceStates::COMMON, Some(addr))
.unwrap()
};
let vertices = indexed_vertices();
let ib16: Vec<u8> = [9u16, 9, 6, 8, 3, 5, 0]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let ib32: Vec<u8> = [9u32, 3, 5, 0, 7, 0x1_0003, 0x1_0005, 0x1_0000]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let vb = buffer(&mut ctx, vertices.len(), INDEXED_VB);
let ib16_handle = buffer(&mut ctx, ib16.len(), INDEXED_IB);
let ib32_handle = buffer(&mut ctx, ib32.len(), INDEXED_IB + 0x1000);
let mut memory = GuestMemory::new();
for (addr, bytes) in [
(INDEXED_VB, &vertices),
(INDEXED_IB, &ib16),
(INDEXED_IB + 0x1000, &ib32),
] {
memory
.map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes)
.unwrap();
}
IndexedRig {
ctx,
memory,
queue,
alloc,
list,
vb,
ib16: ib16_handle,
ib32: ib32_handle,
}
}
/// Record one indexed draw (16x16 viewport, the rig's vertex buffer) and run it.
fn run_indexed(
rig: &mut IndexedRig,
index_buffer: (GraphicsHandle, usize, u32),
draw: (u32, u32, u32, i32),
) -> Result<xenora_loader::graphics::ExecutionOutcome, GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_set_viewport(rig.list, 16, 16)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)?;
ctx.cmd_set_index_buffer(rig.list, index_buffer.0, index_buffer.1, index_buffer.2)?;
let (count, instances, start, base) = draw;
ctx.cmd_draw_indexed_instanced(rig.list, count, instances, start, base, 0)?;
ctx.close_command_list(rig.list)?;
ctx.execute_command_list(rig.queue, rig.list, &rig.memory)
}
const R16_UINT: u32 = 57;
const R32_UINT: u32 = 42;
/// Start index, signed base vertex, index size and buffer offset all select
/// vertices 5, 7, 2: the backend receives exactly the triangle's positions
/// (literal values), never a decoy.
#[test]
fn test_d3d12_indexed_draw_fetches_start_and_base_vertex() {
let mut rig = indexed_rig();
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let record = seen.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
record.lock().unwrap().push(*vtx);
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
for (name, buffer, draw) in [
// 16-bit indices 3, 5, 0 at index 4, base vertex +2.
("u16 positive base", (ib16, 0, R16_UINT), (3, 1, 4, 2)),
// 16-bit indices 6, 8, 3 at index 2, base vertex -1.
("u16 negative base", (ib16, 0, R16_UINT), (3, 1, 2, -1)),
// The same through a buffer offset of one index (2 bytes).
("u16 buffer offset", (ib16, 2, R16_UINT), (3, 1, 1, -1)),
// 32-bit indices 3, 5, 0 at index 1, base vertex +2.
("u32 positive base", (ib32, 0, R32_UINT), (3, 1, 1, 2)),
// 32-bit indices above 16 bits, base vertex -65534: all 32 bits count.
("u32 wide indices", (ib32, 0, R32_UINT), (3, 1, 5, -65534)),
] {
seen.lock().unwrap().clear();
let outcome = run_indexed(&mut rig, buffer, draw).expect(name);
assert_eq!(outcome.draw_count, 1, "{name}");
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE], "{name}");
assert_eq!(
outcome.pixels,
GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255]
)
.unwrap(),
"{name}"
);
}
// A vertex buffer offset of two vertices does the base vertex's work.
seen.lock().unwrap().clear();
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_viewport(rig.list, 16, 16).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 2 * INDEXED_STRIDE, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
let outcome = ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.expect("vertex buffer offset");
assert_eq!(outcome.draw_count, 1);
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE]);
// Zero indices or zero instances draw nothing and never call the backend.
seen.lock().unwrap().clear();
for draw in [(0, 1, 0, 0), (3, 0, 0, 0)] {
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), draw).unwrap();
assert_eq!(outcome.draw_count, 0);
}
assert!(seen.lock().unwrap().is_empty());
}
/// Index format, offset, count, range, negative fetch and unknown or missing
/// buffers each fail with a typed error, and nothing reaches the backend.
#[test]
fn test_d3d12_indexed_draw_errors() {
let mut rig = indexed_rig();
let calls = Arc::new(std::sync::Mutex::new(0usize));
let counter = calls.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
*counter.lock().unwrap() += 1;
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
let unknown = GraphicsHandle {
id: 999,
generation: 1,
};
for format in [0, 41, 56, 58, 28] {
assert_eq!(
run_indexed(&mut rig, (ib16, 0, format), (3, 1, 0, 0)).unwrap_err(),
GraphicsError::InvalidIndexFormat(format)
);
}
for (name, buffer, draw, error) in [
(
"misaligned offset",
(ib32, 2, R32_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"offset past buffer",
(ib16, 16, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"unknown buffer",
(unknown, 0, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidResourceHandle,
),
(
"count not one triangle",
(ib16, 0, R16_UINT),
(6, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"bad count with zero instances",
(ib16, 0, R16_UINT),
(6, 0, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"two instances",
(ib16, 0, R16_UINT),
(3, 2, 4, 2),
GraphicsError::InvalidDescriptor,
),
(
"indices past buffer",
(ib16, 0, R16_UINT),
(3, 1, 5, 0),
GraphicsError::IndexOutOfRange,
),
(
"start overflow",
(ib32, 0, R32_UINT),
(3, 1, u32::MAX, 0),
GraphicsError::IndexOutOfRange,
),
(
"negative vertex",
(ib16, 0, R16_UINT),
(3, 1, 4, -1),
GraphicsError::IndexOutOfRange,
),
(
"vertex past buffer",
(ib16, 0, R16_UINT),
(3, 1, 0, 1),
GraphicsError::IndexOutOfRange,
),
(
"base overflow",
(ib32, 0, R32_UINT),
(3, 1, 0, i32::MAX),
GraphicsError::IndexOutOfRange,
),
] {
let got = run_indexed(&mut rig, buffer, draw);
assert_eq!(got.unwrap_err(), error, "{name}");
}
// A draw without an index buffer is rejected at execution.
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidResourceHandle)
);
// A stride smaller than one float4 position is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, 12).unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// A nonzero start instance is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 1)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// An index buffer whose guest backing would wrap the address space is
// rejected, not read at a wrapped address.
let device = ctx.create_device().unwrap();
// The read's start wraps (start 8 at 2 bytes each), then only its end does.
for (guest_addr, start) in [(u64::MAX - 8, 8), (u64::MAX - 2, 0)] {
let wrapping = rig
.ctx
.create_committed_resource(
device,
ResourceDesc {
dimension: ResourceDimension::Buffer,
width: 64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
},
ResourceStates::COMMON,
Some(guest_addr),
)
.unwrap();
assert_eq!(
run_indexed(&mut rig, (wrapping, 0, R16_UINT), (3, 1, start, 0)).unwrap_err(),
GraphicsError::IndexOutOfRange,
"guest address {guest_addr:#x} start {start}"
);
}
// No rejected draw reached the backend.
assert_eq!(*calls.lock().unwrap(), 0);
}
/// The loader's indexed fetch feeds the native Metal renderer: the GPU image
/// of the fetched triangle equals the image of the literal triangle.
#[test]
#[cfg_attr(
not(feature = "gpu-tests"),
ignore = "needs native Metal device; run scripts/test-gpu.sh"
)]
fn test_d3d12_indexed_draw_native_metal() {
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
let msl = compile_graphics(Architecture::Gfx1030, vs_bytes, ps_bytes)
.expect("compile graphics RDNA2 shaders")
.msl;
let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device"));
let render = {
let gpu = gpu.clone();
let msl = msl.clone();
move |vtx: &[[f32; 4]; 3], vp: (usize, usize), cc: [u8; 4]| {
gpu.render_rgba8(
&msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
vtx,
&[[0.0; 4]; 3],
[vp.0, vp.1],
cc,
)
.map_err(|e| GraphicsError::BackendError(format!("Metal GPU error: {e:?}")))
}
};
let direct = render(&INDEXED_TRIANGLE, (16, 16), [0, 0, 0, 255]).expect("direct render");
let mut rig = indexed_rig();
rig.ctx.set_metal_backend(render);
let ib16 = rig.ib16;
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), (3, 1, 2, -1)).expect("indexed");
assert_eq!(outcome.backend, GraphicsBackendId::MetalNative);
assert_eq!(outcome.pixels, direct);
// The constant shader paints the covered pixels red; the CPU rasteriser
// agrees pixel for pixel, and the triangle covers some but not all pixels.
let reference = GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255],
)
.unwrap();
assert_eq!(outcome.pixels, reference);
let red = outcome
.pixels
.chunks(4)
.filter(|p| *p == [255, 0, 0, 255])
.count();
assert!((1..256).contains(&red), "{red} red pixels");
println!("indexed native Metal draw: {red} of 256 pixels covered");
}
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
#[test]
fn native_indirect_transfers_commit_before_target_fetch() {
const ENTRY: u64 = 0x2000;
const SLOT: u64 = 0x1800;
const TARGET: u64 = 0x3000;
const STACK: u64 = 0x4000;
const SENTINEL: u64 = 0xabcd_1234;
// R9 or [RIP - 0x806]. Both memory operands point back to SLOT.
for (branch, call) in [
(&[0x41, 0xff, 0xd1][..], true),
(&[0x41, 0xff, 0xe1][..], false),
(&[0xff, 0x15, 0xfa, 0xf7, 0xff, 0xff][..], true),
(&[0xff, 0x25, 0xfa, 0xf7, 0xff, 0xff][..], false),
] {
for target_permissions in [
Some(MemoryPermissions::READ_EXECUTE),
Some(MemoryPermissions::READ_WRITE),
None,
] {
let return_address = ENTRY + branch.len() as u64;
let mut code = branch.to_vec();
code.push(0xf4);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
memory
.map_region_with_data(
SLOT,
8,
MemoryPermissions::READ_WRITE,
&TARGET.to_le_bytes(),
)
.unwrap();
memory
.map_region_with_data(
STACK,
8,
MemoryPermissions::READ_WRITE,
&SENTINEL.to_le_bytes(),
)
.unwrap();
if let Some(permissions) = target_permissions {
let target_opcode = if call { 0xc3 } else { 0xf4 };
memory
.map_region_with_data(TARGET, 1, permissions, &[target_opcode])
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, STACK + 8);
cpu.set(Register::R9, TARGET);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let transfer = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(transfer.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(transfer.instructions_executed, 1);
assert_eq!(cpu.rip, TARGET);
let stack_after_transfer = if call { STACK } else { STACK + 8 };
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
assert_eq!(
memory.read_u64(STACK).unwrap(),
if call { return_address } else { SENTINEL }
);
let resumed = engine.run(&mut cpu, &mut memory, 3);
match target_permissions {
Some(MemoryPermissions::READ_EXECUTE) => {
assert_eq!(resumed.exit_reason, ExitReason::Halt);
assert_eq!(resumed.instructions_executed, if call { 2 } else { 1 });
assert_eq!(cpu.rip, if call { return_address + 1 } else { TARGET + 1 });
assert_eq!(cpu.get(Register::Rsp), STACK + 8);
}
permissions => {
let fault = if permissions.is_some() {
MemoryError::PermissionViolation {
address: TARGET,
required: "execute",
}
} else {
MemoryError::UnmappedAddress(TARGET)
};
assert_eq!(resumed.exit_reason, ExitReason::MemoryFault(fault));
assert_eq!(resumed.instructions_executed, 0);
assert_eq!(cpu.rip, TARGET);
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
}
}
}
}
}
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest memory boundary regression tests (#82).
//!
//! Expected behavior follows x86-64 data access rules: an access is valid when
//! every byte it touches is mapped with the required permission, whether or not
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
//! nothing.
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
const A: u64 = 0x10_0000;
fn two_regions(first: P, second: P) -> GuestMemory {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
.unwrap();
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
.unwrap();
m
}
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
m.read_u64_bypass(at).unwrap()
}
#[test]
fn permissions_are_enforced_per_access_kind() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
let violation = |address, required| MemoryError::PermissionViolation { address, required };
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
assert_eq!(
m.write_u8(A + 0x1000, 1),
Err(violation(A + 0x1000, "write"))
);
assert_eq!(
m.fetch_instruction_byte(A + 0x2000),
Err(violation(A + 0x2000, "execute"))
);
assert!(m.read_u8(A + 0x1000).is_ok());
assert!(m.write_u8(A + 0x2000, 1).is_ok());
}
#[test]
fn region_end_is_exclusive() {
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
assert!(m.read_u32(A + 0xFFC).is_ok());
assert!(matches!(
m.read_u32(A + 0xFFD),
Err(MemoryError::PermissionViolation { .. })
));
let mut lone = GuestMemory::new();
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
assert_eq!(
lone.read_u32(A + 0xFFD),
Err(MemoryError::UnmappedAddress(A + 0xFFD))
);
assert_eq!(
lone.read_u8(A - 1),
Err(MemoryError::UnmappedAddress(A - 1))
);
}
#[test]
fn unaligned_accesses_succeed_inside_a_region() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
}
#[test]
fn access_spanning_adjacent_permitted_regions_succeeds() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
}
#[test]
fn spanning_into_a_gap_fails_without_partial_write() {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
.unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::UnmappedAddress(A + 0xFFC))
);
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
}
#[test]
fn spanning_into_a_forbidden_region_fails_atomically() {
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::PermissionViolation {
address: A + 0xFFC,
required: "write"
})
);
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
assert!(m.read_u64(A + 0xFFC).is_ok());
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
}
#[test]
fn loader_bypass_ignores_permissions_but_not_mapping() {
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
.unwrap();
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
m.write_u32_bypass(A, 7).unwrap();
assert_eq!(m.read_u32(A), Ok(7));
assert_eq!(
m.write_u64_bypass(A + 0x1FFC, 0),
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
);
}
#[test]
fn address_overflow_is_reported() {
let mut m = GuestMemory::new();
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
.unwrap();
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
assert_eq!(
m.write_u64_bypass(u64::MAX - 3, 0),
Err(MemoryError::Overflow)
);
assert_eq!(
m.map_region(u64::MAX, 2, P::READ_WRITE),
Err(MemoryError::Overflow)
);
}
#[test]
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
Err(MemoryError::OverlappingRegion {
base: A + 0xFFF,
size: 0x10
})
);
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
}
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
+239
View File
@@ -0,0 +1,239 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Malformed-input regression tests for the PE32+ parser (#79).
//!
//! Every image here is built byte by byte from the Microsoft PE/COFF
//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the
//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the
//! data directories) and 40-byte section headers.
use xenora_loader::{ParsedPe, PeError, PeSection};
const RX: u32 = 0x6000_0020; // code | execute | read
const R: u32 = 0x4000_0040; // initialized data | read
struct Sec {
va: u32,
vsize: u32,
raw_ptr: u32,
raw_size: u32,
flags: u32,
}
/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400).
fn valid_sections() -> Vec<Sec> {
vec![
Sec {
va: 0x1000,
vsize: 0x100,
raw_ptr: 0x200,
raw_size: 0x200,
flags: RX,
},
Sec {
va: 0x2000,
vsize: 0x80,
raw_ptr: 0x400,
raw_size: 0x200,
flags: R,
},
]
}
fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(secs.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&entry.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
let table = opt + usize::from(opt_size);
for (i, s) in secs.iter().enumerate() {
let h = table + i * 40;
pe[h..h + 5].copy_from_slice(b".sect");
pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes());
}
pe
}
#[test]
fn valid_image_parses_maps_and_translates() {
let bytes = build(112, 0x1010, &valid_sections());
let pe = ParsedPe::parse(&bytes).expect("valid image");
assert_eq!(pe.entry_point_rva, 0x1010);
assert_eq!(pe.sections.len(), 2);
assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404));
assert_eq!(pe.rva_to_file_offset(0x3000), None);
let loaded = pe.load_into_memory(&bytes).expect("load");
assert_eq!(loaded.entry_point, 0x1_4000_1010);
}
#[test]
fn optional_header_with_data_directories_is_accepted() {
let bytes = build(240, 0x1000, &valid_sections());
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn repository_fixtures_still_parse_and_load() {
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");
for path in [
"fixtures/pe/trusted-runner.exe",
"experiments/x1/fixtures/x2.exe",
"experiments/x1/fixtures/x3.exe",
"experiments/x1/fixtures/x4-17.exe",
"experiments/x1/fixtures/x4-93.exe",
"experiments/x1/fixtures/x5.exe",
"experiments/x1/fixtures/x6.exe",
] {
let bytes = std::fs::read(format!("{root}/{path}")).expect(path);
let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}"));
pe.load_into_memory(&bytes)
.unwrap_or_else(|e| panic!("{path}: {e}"));
}
}
/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic.
#[test]
fn truncated_optional_header_is_rejected_not_panicking() {
let mut bytes = vec![0u8; 90];
bytes[0..2].copy_from_slice(b"MZ");
bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
bytes[0x40..0x44].copy_from_slice(b"PE\0\0");
bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes());
bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() {
for opt_size in [24u16, 64, 111] {
let bytes = build(opt_size, 0x1000, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::TooSmall,
"{opt_size}"
);
}
}
#[test]
fn e_lfanew_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn section_table_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn section_range_overflowing_rva_space_is_rejected() {
let mut secs = valid_sections();
secs[1].va = 0xFFFF_F000;
secs[1].vsize = 0x2000;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap.
#[test]
fn rva_lookup_with_overflowing_section_returns_none() {
let bytes = build(112, 0x1000, &valid_sections());
let mut pe = ParsedPe::parse(&bytes).unwrap();
pe.sections.insert(
0,
PeSection {
name: "wrap".into(),
virtual_address: 0xFFFF_FF00,
virtual_size: 0x200,
raw_data_ptr: 0x200,
raw_data_size: 0x200,
characteristics: R,
permissions: pe.sections[1].permissions,
},
);
// A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80.
assert_eq!(pe.rva_to_file_offset(0x80), None);
assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204));
}
#[test]
fn overlapping_sections_are_rejected() {
let mut secs = valid_sections();
secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins)
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn adjacent_sections_are_accepted() {
let mut secs = valid_sections();
secs[1].va = 0x1200;
let bytes = build(112, 0x1000, &secs);
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn truncated_section_data_is_rejected() {
let mut secs = valid_sections();
secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
secs[1].raw_size = 0x200;
secs[1].raw_ptr = u32::MAX;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn entry_point_outside_executable_section_is_rejected() {
// Past the end of .text's mapped range, in non-executable .rdata, and outside every section.
for entry in [0x1200, 0x2000, 0x0, u32::MAX] {
let bytes = build(112, entry, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidEntryPoint,
"entry {entry:#x}"
);
}
// Last byte of .text is still inside it.
assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok());
}
@@ -0,0 +1,271 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Base relocation regression tests (#81).
//!
//! Images are built byte by byte from the PE/COFF layout: data directory 5
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
const PREFERRED: u64 = 0x1_4000_0000;
const RELOC_FILE: usize = 0x400;
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
// .reloc fills the image up to SizeOfImage (0x3000).
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
];
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
let h = opt + 240 + i * 40;
pe[h..h + name.len()].copy_from_slice(name);
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
}
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
pe
}
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
let mut b = page_rva.to_le_bytes().to_vec();
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
for e in entries {
b.extend_from_slice(&e.to_le_bytes());
}
b
}
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
fn standard_table() -> Vec<u8> {
block(0x1000, &[0xA010, 0xA018, 0x0000])
}
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
let pe = ParsedPe::parse(bytes).expect("parse");
let mut memory = GuestMemory::new();
for s in &pe.sections {
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
memory
.map_region_with_data(
base + u64::from(s.virtual_address),
0x200,
s.permissions,
raw,
)
.expect("map");
}
(pe, memory)
}
fn relocate(
bytes: &[u8],
base: u64,
) -> (
Result<xenora_loader::RelocationReport, RelocationError>,
GuestMemory,
) {
let (pe, mut memory) = load(bytes, base);
let result = apply_relocations(&pe, bytes, base, &mut memory);
(result, memory)
}
#[test]
fn positive_rebase_adds_delta_to_each_dir64_target() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
let report = result.expect("relocate");
assert_eq!(report.delta, 0x1_0000_0000);
assert_eq!(report.applied_dir64, 2);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.total_entries, 3);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn negative_rebase_subtracts_delta() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = 0x1000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(
result.expect("relocate").delta,
base as i64 - PREFERRED as i64
);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn preferred_base_leaves_targets_unchanged() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let (result, memory) = relocate(&bytes, PREFERRED);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn directory_beyond_declared_count_is_ignored() {
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
let table = standard_table();
let bytes = build(5, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn unsupported_type_is_rejected() {
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::UnsupportedRelocationType(3)
);
}
#[test]
fn malformed_block_sizes_are_rejected() {
let base = PREFERRED + 0x1000;
for size in [0u32, 4, 7, 11] {
let mut table = 0x1000u32.to_le_bytes().to_vec();
table.extend_from_slice(&size.to_le_bytes());
table.extend_from_slice(&[0; 8]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, base);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
"block size {size}"
);
}
}
#[test]
fn block_larger_than_directory_is_rejected() {
let table = standard_table(); // 14 bytes
let bytes = build(16, &table, 12);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::BlockSizeOutOfBounds {
block_size: 14,
max_size: 12
}
);
}
#[test]
fn trailing_partial_block_header_is_rejected() {
let mut table = block(0x1000, &[0xA010, 0x0000]);
table.extend_from_slice(&[0; 4]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader {
offset: RELOC_FILE + 12
}
);
}
#[test]
fn directory_past_end_of_file_is_rejected() {
let table = standard_table();
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::DirectoryOutOfBounds {
rva: 0x2000,
size: 0x300
}
);
}
#[test]
fn target_outside_image_is_rejected_even_if_mapped() {
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
let table = block(0x3000, &[0xA000, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1000;
let (pe, mut memory) = load(&bytes, base);
let rw = pe.sections[1].permissions;
memory
.map_region(base + 0x3000, 0x1000, rw)
.expect("adjacent mapping");
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
let result = apply_relocations(&pe, &bytes, base, &mut memory);
assert_eq!(
result.unwrap_err(),
RelocationError::TargetOutOfBounds {
target_va: base + 0x3000
}
);
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
}
#[test]
fn target_rva_at_top_of_address_space_is_rejected() {
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert!(matches!(
result,
Err(RelocationError::TargetOutOfBounds { .. })
));
}
+1
View File
@@ -32,6 +32,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
+104 -15
View File
@@ -23,7 +23,11 @@ use xenora_texture::{
#[path = "render.rs"]
mod render;
pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState};
pub use render::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer, IndexedDraw,
IndexedPass,
};
const MAX_THREADS_PER_GROUP: usize = 64;
const MAX_GROUPS: usize = 64;
@@ -553,6 +557,56 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: &[u32],
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, None)
}
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
///
/// The grid still contains one invocation per input word. The requested width
/// is passed to Metal even when the grid is smaller or ends in a partial group.
/// The trusted-kernel requirements of [`Self::run_words`] apply.
///
/// # Errors
///
/// Returns the same errors as [`Self::run_words_profiled`], with dispatch
/// bounds evaluated using this width. Zero and widths above the device or
/// pipeline limit are rejected.
pub fn run_words_with_group_width(
&self,
source: &str,
entry: &str,
input: &[u32],
width: usize,
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, Some(width))
}
/// Compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
/// # Errors
///
/// Returns an error if source validation, compilation or pipeline setup fails.
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)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
fn run_profiled_words(
&self,
source: &str,
entry: &str,
input: &[u32],
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
@@ -561,7 +615,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
));
}
validate_source(source, &[entry])?;
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
}
fn run(
@@ -569,6 +623,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: ComputeInput<'_>,
) -> Result<RunProfile, MetalError> {
self.run_sized(source, entry, input, None)
}
/// [`Self::run`] with an optional explicit threadgroup width; `None` keeps
/// the default sizing.
fn run_sized(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let options = compile_options()?;
@@ -577,22 +643,21 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
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 = self.compute_pipeline(&function)?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let width = MAX_THREADS_PER_GROUP
.min(input.len())
.min(self.device.maxThreadsPerThreadgroup().width)
.min(pipeline.maxTotalThreadsPerThreadgroup());
let limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
Some(width) if (1..=limit).contains(&width) => width,
Some(width) => {
return Err(MetalError::new(
"threadgroup width",
format!("expected a nonzero width at most {limit}, got {width}"),
));
}
None => MAX_THREADS_PER_GROUP.min(input.len()).min(limit),
};
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
return Err(MetalError::new(
"dispatch bounds",
@@ -683,6 +748,30 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
self.device
.newComputePipelineStateWithFunction_error(function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})
}
fn pipeline_group_width_limit(
&self,
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> usize {
self.device
.maxThreadsPerThreadgroup()
.width
.min(pipeline.maxTotalThreadsPerThreadgroup())
}
fn new_buffer(
&self,
words: &[u32],
+3 -2
View File
@@ -14,8 +14,9 @@ pub mod texture_pipeline;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use compute::{
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer,
GuestBufferView, MetalError, NativeCompute, RunProfile,
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
+594 -6
View File
@@ -6,12 +6,12 @@ use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
use objc2_metal::{
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction,
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction,
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
MTLTextureUsage, MTLViewport,
MTLBlendFactor, MTLBlendOperation, MTLClearColor, MTLColorWriteMask, MTLCommandBuffer,
MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLDepthStencilDescriptor,
MTLDepthStencilState, MTLDevice, MTLFunction, MTLIndexType, MTLLoadAction, MTLOrigin,
MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLShaderValidation, MTLSize,
MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLViewport,
};
use xenora_texture::{Bc1Subresource, Bc1Upload};
@@ -717,6 +717,312 @@ impl NativeCompute {
}
}
const MAX_INDEXED_VERTICES: usize = 1024;
const MAX_INDICES: usize = 4096;
/// An index buffer of 16- or 32-bit unsigned indices.
#[derive(Clone, Copy, Debug)]
pub enum IndexBuffer<'a> {
U16(&'a [u16]),
U32(&'a [u32]),
}
impl IndexBuffer<'_> {
fn len(self) -> usize {
match self {
Self::U16(indices) => indices.len(),
Self::U32(indices) => indices.len(),
}
}
fn index(self, position: usize) -> u32 {
match self {
Self::U16(indices) => u32::from(indices[position]),
Self::U32(indices) => indices[position],
}
}
fn restart(self) -> u32 {
match self {
Self::U16(_) => u32::from(u16::MAX),
Self::U32(_) => u32::MAX,
}
}
fn size(self) -> usize {
match self {
Self::U16(_) => 2,
Self::U32(_) => 4,
}
}
/// The indices packed into little-endian words, the last one zero-padded.
fn words(self) -> Vec<u32> {
match self {
Self::U16(indices) => indices
.chunks(2)
.map(|pair| {
u32::from(pair[0]) | pair.get(1).map_or(0, |&high| u32::from(high) << 16)
})
.collect(),
Self::U32(indices) => indices.to_vec(),
}
}
}
/// One indexed triangle-list draw: `index_count` indices from `start_index`,
/// each fetching vertex `index + base_vertex`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IndexedDraw {
pub start_index: usize,
pub index_count: usize,
pub base_vertex: i32,
pub fill: DepthFill,
}
/// An offscreen pass of up to 16 indexed draws, in order, into a cleared
/// RGBA8Unorm target without depth attachment.
#[derive(Clone, Copy, Debug)]
pub struct IndexedPass<'a> {
pub extent: [usize; 2],
pub clear_color: [u8; 4],
/// Up to 1024 clip-space float4 positions.
pub vertices: &'a [[f32; 4]],
/// Up to 4096 indices shared by every draw.
pub indices: IndexBuffer<'a>,
pub draws: &'a [IndexedDraw],
/// As [`DepthPass::texture`], for [`DepthFill::Bc1Texture`] draws.
pub texture: Option<&'a Bc1Upload<'a>>,
}
impl NativeCompute {
/// Draw an indexed offscreen pass and read back its colour.
///
/// Each draw is one native `drawIndexedPrimitives` call on the pass's
/// index buffer with the draw's start offset and signed base vertex, so
/// Metal itself fetches the vertices. Every fetched vertex is checked
/// against the vertex buffer first: out-of-range fetches and raw
/// primitive-restart values are rejected, never left to the GPU. Base vertex needs no capability query: the
/// Apple family 7 that [`NativeCompute::new`] requires supports it.
///
/// # Errors
///
/// Returns an error for an invalid extent, too many draws, vertices or
/// indices, non-finite positions, an index count that is zero or not a
/// multiple of 3, an index range past the buffer, a primitive-restart
/// index, a fetched vertex outside the vertex buffer, a textured draw without texture, unavailable BC
/// compression (operation `supportsBCTextureCompression`), or Metal setup
/// or execution failure.
pub fn render_indexed(&self, pass: &IndexedPass<'_>) -> Result<Vec<u8>, MetalError> {
let [width, height] = pass.extent;
let pixels = width
.checked_mul(height)
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
validate_indexed_pass(pass)?;
let bc1 = pass
.texture
.map(|upload| {
let level = upload.subresource(0, 0).map_err(|error| {
MetalError::new("texture subresource", format!("{error:?}"))
})?;
self.validate_bc_extent(level.width, level.height, "BC1")?;
self.new_bc1_texture(&level)
})
.transpose()?;
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(DEPTH_SOURCE, &options)?;
let vertex = find_function(&library, "depth_vertex")?;
let flat = self.depth_pipeline(
&vertex,
&*find_function(&library, "depth_flat")?,
MTLPixelFormat::Invalid,
)?;
let textured = self.depth_pipeline(
&vertex,
&*find_function(&library, "depth_textured")?,
MTLPixelFormat::Invalid,
)?;
let color = self.new_target(
PIXEL_FORMAT,
width,
height,
MTLStorageMode::Shared,
MTLTextureUsage::RenderTarget,
)?;
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
// SAFETY: Slot zero is the only color attachment for this pass.
let attachment = unsafe {
pass_descriptor
.colorAttachments()
.objectAtIndexedSubscript(0)
};
attachment.setTexture(Some(&color));
attachment.setLoadAction(MTLLoadAction::Clear);
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
attachment.setClearColor(MTLClearColor {
red,
green,
blue,
alpha,
});
attachment.setStoreAction(MTLStoreAction::Store);
let positions: Vec<u32> = pass
.vertices
.as_flattened()
.iter()
.map(|value| value.to_bits())
.collect();
let positions = self.new_buffer(&positions)?;
let indices = self.new_buffer(&pass.indices.words())?;
let index_type = match pass.indices {
IndexBuffer::U16(_) => MTLIndexType::UInt16,
IndexBuffer::U32(_) => MTLIndexType::UInt32,
};
let command = self.queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "render command buffer creation failed")
})?;
let encoder = command
.renderCommandEncoderWithDescriptor(&pass_descriptor)
.ok_or_else(|| {
MetalError::new(
"renderCommandEncoderWithDescriptor",
"render encoder creation failed",
)
})?;
encoder.setViewport(MTLViewport {
originX: 0.0,
originY: 0.0,
width: width as f64,
height: height as f64,
znear: 0.0,
zfar: 1.0,
});
let extent = [width as f32, height as f32];
for draw in pass.draws {
// SAFETY: Validation proved that every index the draw reads lies
// inside the index buffer, that the offset is a multiple of the
// index size, and that every `index + base_vertex` names a float4
// of the position buffer, the only memory the vertex stage reads.
// Fragment constants are copied by Metal and match the declared
// types. The texture, when bound, is a live BC1 texture of this
// device; both buffers outlive the command.
unsafe {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
match draw.fill {
DepthFill::Flat(rgba) => {
encoder.setRenderPipelineState(&flat);
let rgba = rgba.map(|value| f32::from(value) / 255.0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&rgba).cast(),
size_of_val(&rgba),
0,
);
}
DepthFill::Bc1Texture => {
encoder.setRenderPipelineState(&textured);
encoder.setFragmentTexture_atIndex(bc1.as_deref(), 0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&extent).cast(),
size_of_val(&extent),
0,
);
}
}
encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance(
MTLPrimitiveType::Triangle,
draw.index_count,
index_type,
&indices,
draw.start_index * pass.indices.size(),
1,
draw.base_vertex as isize,
0,
);
}
}
encoder.endEncoding();
complete_command(&command)?;
let mut output = vec![0; pixels * 4];
// SAFETY: GPU writes have completed, and the initialized output
// allocation fits the entire shared texture with tightly packed rows.
unsafe {
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
NonNull::from(output.as_mut_slice()).cast(),
width * 4,
whole(width, height),
0,
);
}
Ok(output)
})
}
}
fn validate_indexed_pass(pass: &IndexedPass<'_>) -> Result<(), MetalError> {
let invalid = |reason: String| Err(MetalError::new("indexed pass", reason));
if pass.draws.len() > MAX_DEPTH_DRAWS {
return invalid("expected at most 16 draws".to_owned());
}
if !(1..=MAX_INDEXED_VERTICES).contains(&pass.vertices.len())
|| !(1..=MAX_INDICES).contains(&pass.indices.len())
{
return invalid("expected 1..=1024 vertices and 1..=4096 indices".to_owned());
}
if pass
.vertices
.as_flattened()
.iter()
.any(|value| !value.is_finite())
{
return Err(MetalError::new(
"render input",
"expected finite vertex data",
));
}
for (number, draw) in pass.draws.iter().enumerate() {
if draw.index_count == 0 || !draw.index_count.is_multiple_of(3) {
return invalid(format!(
"draw {number}: index count must be a nonzero multiple of 3"
));
}
let end = draw
.start_index
.checked_add(draw.index_count)
.filter(|&end| end <= pass.indices.len())
.ok_or_else(|| {
MetalError::new(
"indexed pass",
format!("draw {number}: index range past the index buffer"),
)
})?;
for position in draw.start_index..end {
let index = pass.indices.index(position);
// Metal documents 0xFFFF / 0xFFFFFFFF as the primitive-restart value
// of indexed draws without defining it for triangle lists, so the
// raw value is rejected whatever the base vertex.
if index == pass.indices.restart() {
return invalid(format!(
"draw {number}: index {position} is the primitive-restart value"
));
}
let vertex = i64::from(index) + i64::from(draw.base_vertex);
if !(0..pass.vertices.len() as i64).contains(&vertex) {
return invalid(format!(
"draw {number}: index {position} fetches vertex {vertex} outside the vertex buffer"
));
}
}
if draw.fill == DepthFill::Bc1Texture && pass.texture.is_none() {
return invalid("textured draw without texture".to_owned());
}
}
Ok(())
}
fn validate_depth_pass(pass: &DepthPass<'_>) -> Result<(), MetalError> {
if pass.draws.len() > MAX_DEPTH_DRAWS {
return Err(MetalError::new("depth pass", "expected at most 16 draws"));
@@ -775,3 +1081,285 @@ fn whole(width: usize, height: usize) -> MTLRegion {
},
}
}
/// A blend factor, as Metal defines it for the RGB and the alpha channel.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlendFactor {
Zero,
One,
SourceColor,
OneMinusSourceColor,
SourceAlpha,
OneMinusSourceAlpha,
DestinationColor,
OneMinusDestinationColor,
DestinationAlpha,
OneMinusDestinationAlpha,
}
impl BlendFactor {
fn metal(self) -> MTLBlendFactor {
match self {
Self::Zero => MTLBlendFactor::Zero,
Self::One => MTLBlendFactor::One,
Self::SourceColor => MTLBlendFactor::SourceColor,
Self::OneMinusSourceColor => MTLBlendFactor::OneMinusSourceColor,
Self::SourceAlpha => MTLBlendFactor::SourceAlpha,
Self::OneMinusSourceAlpha => MTLBlendFactor::OneMinusSourceAlpha,
Self::DestinationColor => MTLBlendFactor::DestinationColor,
Self::OneMinusDestinationColor => MTLBlendFactor::OneMinusDestinationColor,
Self::DestinationAlpha => MTLBlendFactor::DestinationAlpha,
Self::OneMinusDestinationAlpha => MTLBlendFactor::OneMinusDestinationAlpha,
}
}
}
/// A blend operation combining the weighted source and destination; `Min`
/// and `Max` take the unweighted values and ignore the factors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlendOperation {
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
impl BlendOperation {
fn metal(self) -> MTLBlendOperation {
match self {
Self::Add => MTLBlendOperation::Add,
Self::Subtract => MTLBlendOperation::Subtract,
Self::ReverseSubtract => MTLBlendOperation::ReverseSubtract,
Self::Min => MTLBlendOperation::Min,
Self::Max => MTLBlendOperation::Max,
}
}
}
/// Separate RGB and alpha blend equations of one draw.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BlendState {
pub source_rgb: BlendFactor,
pub destination_rgb: BlendFactor,
pub rgb_operation: BlendOperation,
pub source_alpha: BlendFactor,
pub destination_alpha: BlendFactor,
pub alpha_operation: BlendOperation,
}
/// The colour channels a draw writes; the others keep the stored value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ColorWriteMask {
pub red: bool,
pub green: bool,
pub blue: bool,
pub alpha: bool,
}
impl ColorWriteMask {
pub const ALL: Self = Self {
red: true,
green: true,
blue: true,
alpha: true,
};
fn metal(self) -> MTLColorWriteMask {
[
(self.red, MTLColorWriteMask::Red),
(self.green, MTLColorWriteMask::Green),
(self.blue, MTLColorWriteMask::Blue),
(self.alpha, MTLColorWriteMask::Alpha),
]
.into_iter()
.filter(|(on, _)| *on)
.fold(MTLColorWriteMask::None, |mask, (_, bit)| mask | bit)
}
}
/// One flat-coloured triangle of a blend pass.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlendDraw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
/// `None` disables blending: the source replaces the masked channels.
pub blend: Option<BlendState>,
pub write_mask: ColorWriteMask,
}
/// An offscreen pass of up to 16 triangles drawn in order into a cleared
/// RGBA8Unorm target without depth attachment.
#[derive(Clone, Copy, Debug)]
pub struct BlendPass<'a> {
pub extent: [usize; 2],
pub clear_color: [u8; 4],
pub draws: &'a [BlendDraw],
}
impl NativeCompute {
/// Draw a blended, write-masked offscreen pass and read back its colour.
///
/// Blend state and write mask are pipeline state in Metal, so each draw
/// gets its own pipeline built from exactly the draw's settings.
///
/// # Errors
///
/// Returns an error for an invalid extent, too many draws, non-finite
/// positions, or Metal setup or execution failure.
pub fn render_blend(&self, pass: &BlendPass<'_>) -> Result<Vec<u8>, MetalError> {
let [width, height] = pass.extent;
let pixels = width
.checked_mul(height)
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
if pass.draws.len() > MAX_DEPTH_DRAWS {
return Err(MetalError::new("blend pass", "expected at most 16 draws"));
}
if pass
.draws
.iter()
.flat_map(|draw| draw.positions.as_flattened())
.any(|value| !value.is_finite())
{
return Err(MetalError::new(
"render input",
"expected finite vertex data",
));
}
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(DEPTH_SOURCE, &options)?;
let vertex = find_function(&library, "depth_vertex")?;
let fragment = find_function(&library, "depth_flat")?;
let pipelines = pass
.draws
.iter()
.map(|draw| self.blend_pipeline(&vertex, &fragment, draw))
.collect::<Result<Vec<_>, _>>()?;
let color = self.new_target(
PIXEL_FORMAT,
width,
height,
MTLStorageMode::Shared,
MTLTextureUsage::RenderTarget,
)?;
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
// SAFETY: Slot zero is the only color attachment for this pass.
let attachment = unsafe {
pass_descriptor
.colorAttachments()
.objectAtIndexedSubscript(0)
};
attachment.setTexture(Some(&color));
attachment.setLoadAction(MTLLoadAction::Clear);
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
attachment.setClearColor(MTLClearColor {
red,
green,
blue,
alpha,
});
attachment.setStoreAction(MTLStoreAction::Store);
let words: Vec<u32> = pass
.draws
.iter()
.flat_map(|draw| draw.positions.as_flattened())
.map(|value| value.to_bits())
.collect();
let positions = (!words.is_empty())
.then(|| self.new_buffer(&words))
.transpose()?;
let command = self.queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "render command buffer creation failed")
})?;
let encoder = command
.renderCommandEncoderWithDescriptor(&pass_descriptor)
.ok_or_else(|| {
MetalError::new(
"renderCommandEncoderWithDescriptor",
"render encoder creation failed",
)
})?;
encoder.setViewport(MTLViewport {
originX: 0.0,
originY: 0.0,
width: width as f64,
height: height as f64,
znear: 0.0,
zfar: 1.0,
});
for (index, (draw, pipeline)) in pass.draws.iter().zip(&pipelines).enumerate() {
encoder.setRenderPipelineState(pipeline);
let rgba = draw.color.map(|value| f32::from(value) / 255.0);
// SAFETY: The position buffer holds three float4s per draw and
// the vertex stage reads only this draw's three. The fragment
// constant is copied by Metal and matches the declared float4.
unsafe {
encoder.setVertexBuffer_offset_atIndex(positions.as_deref(), index * 48, 0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&rgba).cast(),
size_of_val(&rgba),
0,
);
encoder.drawPrimitives_vertexStart_vertexCount(
MTLPrimitiveType::Triangle,
0,
3,
);
}
}
encoder.endEncoding();
complete_command(&command)?;
let mut output = vec![0; pixels * 4];
// SAFETY: GPU writes have completed, and the initialized output
// allocation fits the entire shared texture with tightly packed rows.
unsafe {
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
NonNull::from(output.as_mut_slice()).cast(),
width * 4,
whole(width, height),
0,
);
}
Ok(output)
})
}
fn blend_pipeline(
&self,
vertex: &ProtocolObject<dyn MTLFunction>,
fragment: &ProtocolObject<dyn MTLFunction>,
draw: &BlendDraw,
) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, MetalError> {
let descriptor = MTLRenderPipelineDescriptor::new();
descriptor.setVertexFunction(Some(vertex));
descriptor.setFragmentFunction(Some(fragment));
// SAFETY: Slot zero is the only color attachment for this pipeline.
let attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) };
attachment.setPixelFormat(PIXEL_FORMAT);
attachment.setWriteMask(draw.write_mask.metal());
attachment.setBlendingEnabled(draw.blend.is_some());
if let Some(blend) = draw.blend {
attachment.setSourceRGBBlendFactor(blend.source_rgb.metal());
attachment.setDestinationRGBBlendFactor(blend.destination_rgb.metal());
attachment.setRgbBlendOperation(blend.rgb_operation.metal());
attachment.setSourceAlphaBlendFactor(blend.source_alpha.metal());
attachment.setDestinationAlphaBlendFactor(blend.destination_alpha.metal());
attachment.setAlphaBlendOperation(blend.alpha_operation.metal());
}
let pipeline = self
.device
.newRenderPipelineStateWithDescriptor_error(&descriptor)
.map_err(|error| {
MetalError::new(
"newRenderPipelineStateWithDescriptor",
error.localizedDescription().to_string(),
)
})?;
verify_render_validation(&pipeline)?;
Ok(pipeline)
}
}
+36
View File
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the blend reference agrees with the independently derived
//! expectations for every blend case, colour and rounding flags alike. Runs
//! without a GPU.
#[path = "support/blend_cases.rs"]
mod blend_cases;
use blend_cases::{CLEAR, SIZE, cases, expected};
use xenora_ref::blend::{RefBlendDraw, render_blend};
#[test]
fn reference_matches_independent_expectations() {
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 39);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefBlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend,
mask: draw.mask,
})
.collect();
let pixels = render_blend([SIZE, SIZE], CLEAR, &draws).expect("reference render");
let color: Vec<_> = pixels.iter().map(|p| p.map(|c| c.value)).collect();
let exact: Vec<_> = pixels.iter().map(|p| p.map(|c| c.exact)).collect();
assert_eq!(color, want.color, "{} colour", case.name);
assert_eq!(exact, want.exact, "{} rounding flags", case.name);
}
}
+842
View File
@@ -0,0 +1,842 @@
case clear
palette A 32 64 96 128 eeee
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
end
case disabled
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 14 127 226 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 46 53 14 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 23 68 90 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 37 112 150 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 13 109 193 36 rrrr
palette D 52 135 150 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 38 113 151 60 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 22 67 89 36 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 153 29 3 100 rrrr
palette D 24 19 6 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 38 19 60 rrrr
palette D 12 24 36 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 62 31 100 rrrr
palette D 20 40 60 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 157 39 10 100 rrrr
palette D 4 16 36 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 43 61 40 60 rrrr
palette D 28 48 60 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 63 31 100 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 37 19 60 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Add
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 136 rrrr
palette D 43 108 150 116 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Subtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 5 59 0 erre
palette D 3 28 30 0 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_ReverseSubtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 102 0 0 64 reer
palette D 0 0 0 44 eeer
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Min
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Max
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case additive_clamp
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 255 255 255 255 eeee
palette D 92 244 255 224 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_alpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 96 rrre
palette D 43 108 150 96 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_R
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 160 eeee
palette D 60 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_G
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 50 160 eeee
palette D 32 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_B
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 240 160 eeee
palette D 32 64 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_A
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGB
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_none
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGBA
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RG_blended
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 50 160 rree
palette D 43 108 96 128 rree
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_operation
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 64 rrre
palette D 43 108 150 32 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case first_draw_blended
palette A 32 87 67 148 errr
palette B 32 64 96 128 eeee
palette C 60 180 67 148 eerr
palette D 60 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
+361
View File
@@ -0,0 +1,361 @@
case clear
palette 0 16 32 48 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
end
case u16_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u32_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u16_odd_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u32_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u16_base_positive
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u16_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u32_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case reversed_winding
fetch 2 1 0
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case two_triangles_textured
fetch 9 10 11 9 11 12
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 255 255 255 255
palette 5 255 255 0 255
palette 6 132 130 132 255
palette 7 8 8 8 255
palette 8 0 0 0 255
color 0011001122223333
color 0011001122223333
color 1100110033332222
color 1100110033332222
color 0000111133223344
color 0000111133223344
color 1111000044332233
color 1111000044332233
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888877666677
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888888888888
end
case textured_base_vertex
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
palette 2 0 0 255 255
palette 3 0 0 0 0
palette 4 0 255 0 255
palette 5 255 255 255 255
palette 6 132 130 132 255
palette 7 8 8 8 255
color 0122112233334444
color 0022112233334444
color 0001221144443333
color 0000221144443333
color 0000022244334455
color 0000002244334455
color 0000000155443344
color 0000000055443344
color 0000000006777766
color 0000000000777766
color 0000000000066677
color 0000000000006677
color 0000000000000766
color 0000000000000066
color 0000000000000007
color 0000000000000000
end
case painter_order
fetch 0 1 2
fetch 3 4 5
fetch 6 7 8
palette 0 255 0 0 255
palette 1 0 0 0 255
palette 2 0 255 0 255
palette 3 0 0 255 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000222222011111
color 0000222222222222
color 0000222222222221
color 0000022222222211
color 0000022222222111
color 3333333332221111
color 3333333322211111
color 3333333222211111
color 3333332222111111
color 3333122221111111
color 3331112211111111
color 3311112111111111
color 3111111111111111
end
case u32_mixed
fetch 9 10 11 9 11 12
fetch 9 10 11
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 255 0 255
palette 2 255 255 0 255
palette 3 132 130 132 255
palette 4 0 0 0 255
palette 5 8 8 8 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000000011111111
color 0000022231111111
color 0002222233111111
color 0044444455311111
color 0444444455331111
color 2222222233555111
color 2222222233555511
color 4444444455333351
color 4444444444444444
end
case flat_two_triangles
fetch 9 10 11 9 11 12
palette 0 0 255 0 255
palette 1 0 0 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000011111111
end
case textured_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 0 0 0 255
palette 5 255 255 0 255
color 0011001122223334
color 0011001122223344
color 1100110033332444
color 1100110033344444
color 0000111133444444
color 0000111134444444
color 1111000444444444
color 1111004444444444
color 5555544444444444
color 5554444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
end
case u32_high_indices
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
color 0111111111111111
color 0011111111111111
color 0001111111111111
color 0000111111111111
color 0000011111111111
color 0000001111111111
color 0000000111111111
color 0000000011111111
color 0000000001111111
color 0000000000111111
color 0000000000011111
color 0000000000001111
color 0000000000000111
color 0000000000000011
color 0000000000000001
color 0000000000000000
end
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the reference index fetch and rasteriser agree with the
//! independently derived expectations for every indexed case. Runs without a GPU.
#[path = "support/indexed_cases.rs"]
mod indexed_cases;
use indexed_cases::{BC1_BLOCKS, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices};
use xenora_ref::depth::{RefFill, RefTexture};
use xenora_ref::indexed::{RefIndexedDraw, RefIndices, fetch, render_indexed};
fn bc1_texels() -> Vec<[u8; 4]> {
let mut texels = vec![[0; 4]; 64];
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
for (index, texel) in xenora_texture::decode_bc1(*bytes).iter().enumerate() {
texels[((block / 2) * 4 + index / 4) * 8 + (block % 2) * 4 + index % 4] = *texel;
}
}
texels
}
#[test]
fn reference_matches_independent_expectations() {
let texels = bc1_texels();
let texture = RefTexture {
width: 8,
height: 8,
texels: &texels,
};
let wide = wide_indices();
let vertices = vertices();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 16);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let indices = if case.wide {
RefIndices::U32(&wide)
} else {
RefIndices::U16(&INDICES)
};
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefIndexedDraw {
start: draw.start,
count: draw.count,
base_vertex: draw.base_vertex,
fill: match draw.fill {
Fill::Flat(rgba) => RefFill::Flat(rgba),
Fill::Texture => RefFill::Texture,
},
})
.collect();
let fetched: Vec<_> = draws
.iter()
.enumerate()
.map(|(number, draw)| fetch(number, draw, indices, vertices.len()).expect("fetch"))
.collect();
assert_eq!(fetched, want.fetch, "{} fetch", case.name);
let color = render_indexed(
[SIZE, SIZE],
case.clear_color,
&vertices,
indices,
&draws,
Some(texture),
)
.expect("reference render");
assert_eq!(color, want.color, "{} colour", case.name);
}
}
+150
View File
@@ -0,0 +1,150 @@
use xenora_metal::{BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask};
use xenora_ref::blend::{RefBlend, RefBlendFactor, RefBlendOperation};
use super::blend_cases::{CLEAR, Case, SIZE, cases, expected};
use super::{context, native};
/// Tolerance, fixed before any native measurement: a channel whose exact
/// result is a whole unorm8 value must match exactly; a channel that needs
/// rounding may differ by at most this much, because Metal does not document
/// how it rounds blended unorm values.
const ROUNDING_TOLERANCE: u8 = 1;
fn factor(factor: RefBlendFactor) -> BlendFactor {
match factor {
RefBlendFactor::Zero => BlendFactor::Zero,
RefBlendFactor::One => BlendFactor::One,
RefBlendFactor::SourceColor => BlendFactor::SourceColor,
RefBlendFactor::OneMinusSourceColor => BlendFactor::OneMinusSourceColor,
RefBlendFactor::SourceAlpha => BlendFactor::SourceAlpha,
RefBlendFactor::OneMinusSourceAlpha => BlendFactor::OneMinusSourceAlpha,
RefBlendFactor::DestinationColor => BlendFactor::DestinationColor,
RefBlendFactor::OneMinusDestinationColor => BlendFactor::OneMinusDestinationColor,
RefBlendFactor::DestinationAlpha => BlendFactor::DestinationAlpha,
RefBlendFactor::OneMinusDestinationAlpha => BlendFactor::OneMinusDestinationAlpha,
}
}
fn operation(operation: RefBlendOperation) -> BlendOperation {
match operation {
RefBlendOperation::Add => BlendOperation::Add,
RefBlendOperation::Subtract => BlendOperation::Subtract,
RefBlendOperation::ReverseSubtract => BlendOperation::ReverseSubtract,
RefBlendOperation::Min => BlendOperation::Min,
RefBlendOperation::Max => BlendOperation::Max,
}
}
fn state(blend: RefBlend) -> BlendState {
BlendState {
source_rgb: factor(blend.source_rgb),
destination_rgb: factor(blend.destination_rgb),
rgb_operation: operation(blend.rgb_operation),
source_alpha: factor(blend.source_alpha),
destination_alpha: factor(blend.destination_alpha),
alpha_operation: operation(blend.alpha_operation),
}
}
fn metal_draws(case: &Case) -> Vec<BlendDraw> {
case.draws
.iter()
.map(|draw| BlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend.map(state),
write_mask: ColorWriteMask {
red: draw.mask[0],
green: draw.mask[1],
blue: draw.mask[2],
alpha: draw.mask[3],
},
})
.collect()
}
/// Each case's native colour must equal the independently derived image,
/// per channel: exactly where the exact result is a whole unorm8 value, and
/// within [`ROUNDING_TOLERANCE`] where it needs rounding.
#[test]
fn blend_known_answers() {
let gpu = context();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), expected.len());
let (mut rounded, mut off_by_one, mut largest) = (0usize, 0usize, 0u8);
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws = metal_draws(case);
let color = native(gpu.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &draws,
}));
assert_eq!(color.len(), SIZE * SIZE * 4);
for (index, ((pixel, wanted), exact)) in color
.as_chunks::<4>()
.0
.iter()
.zip(&want.color)
.zip(&want.exact)
.enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
for channel in 0..4 {
let difference = pixel[channel].abs_diff(wanted[channel]);
let allowed = if exact[channel] {
0
} else {
ROUNDING_TOLERANCE
};
assert!(
difference <= allowed,
"{} at ({x}, {y}) channel {channel}: {pixel:?} vs {wanted:?} (allowed {allowed})",
case.name
);
if !exact[channel] {
rounded += 1;
off_by_one += usize::from(difference == 1);
largest = largest.max(difference);
}
}
}
}
println!(
"checked {} blend passes; {rounded} rounded channels, {off_by_one} off by one, largest difference {largest}",
cases.len()
);
}
#[test]
fn too_many_blend_draws_are_rejected() {
let gpu = context();
let draw = BlendDraw {
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],
],
color: [255; 4],
blend: None,
write_mask: ColorWriteMask::ALL,
};
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[draw; 17],
})
.expect_err("17 draws must be rejected");
assert!(error.to_string().contains("at most 16 draws"), "{error}");
let mut bad = draw;
bad.positions[1][0] = f32::NAN;
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[bad],
})
.expect_err("non-finite positions must be rejected");
assert!(error.to_string().contains("finite"), "{error}");
}
+165
View File
@@ -0,0 +1,165 @@
use xenora_metal::{DepthFill, IndexBuffer, IndexedDraw, IndexedPass};
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
use super::indexed_cases::{
BC1_BLOCKS, Case, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices,
};
use super::{context, native};
fn metal_draws(case: &Case) -> Vec<IndexedDraw> {
case.draws
.iter()
.map(|draw| IndexedDraw {
start_index: draw.start,
index_count: draw.count,
base_vertex: draw.base_vertex,
fill: match draw.fill {
Fill::Flat(rgba) => DepthFill::Flat(rgba),
Fill::Texture => DepthFill::Bc1Texture,
},
})
.collect()
}
fn bc1_upload() -> Bc1Upload<'static> {
Bc1Upload::new(
&BC1_BLOCKS,
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload")
}
/// Each case's native colour must equal the independently derived image
/// (which the CPU reference also reproduces in `indexed_reference`), per pixel.
/// Metal fetches the vertices itself from the index buffer, start offset and
/// base vertex of each `drawIndexedPrimitives` call.
#[test]
fn indexed_draw_known_answers() {
let gpu = context();
let upload = bc1_upload();
let vertices = vertices();
let wide = wide_indices();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), expected.len());
let mut checked = 0;
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
// One independently derived fetch list per draw keeps the fixtures aligned.
assert_eq!(want.fetch.len(), case.draws.len(), "{}", case.name);
let draws = metal_draws(case);
let color = native(
gpu.render_indexed(&IndexedPass {
extent: [SIZE, SIZE],
clear_color: case.clear_color,
vertices: &vertices,
indices: if case.wide {
IndexBuffer::U32(&wide)
} else {
IndexBuffer::U16(&INDICES)
},
draws: &draws,
// Only textured cases need BC support, so a device without it fails
// those cases alone, as a capability error.
texture: case
.draws
.iter()
.any(|draw| draw.fill == Fill::Texture)
.then_some(&upload),
}),
);
assert_eq!(color.len(), SIZE * SIZE * 4);
for (index, (pixel, wanted)) in color.as_chunks::<4>().0.iter().zip(&want.color).enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name);
}
checked += 1;
}
println!("checked {checked} indexed passes of {} pixels", SIZE * SIZE);
}
/// Every malformed draw is rejected before encoding, with its own reason.
#[test]
fn invalid_indexed_draws_are_rejected() {
let gpu = context();
let vertices = vertices();
let restart = [0, 1, u16::MAX];
let flat = DepthFill::Flat([255; 4]);
let run = |indices, start_index, index_count, base_vertex, fill| {
gpu.render_indexed(&IndexedPass {
extent: [SIZE, SIZE],
clear_color: [0; 4],
vertices: &vertices,
indices,
draws: &[IndexedDraw {
start_index,
index_count,
base_vertex,
fill,
}],
texture: None,
})
.expect_err("invalid draw must be rejected")
.to_string()
};
let short = IndexBuffer::U16(&INDICES);
let count = "index count must be a nonzero multiple of 3";
let range = "index range past the index buffer";
let outside = "outside the vertex buffer";
let restart_value = "primitive-restart value";
for (reason, error, wanted) in [
// First: Metal itself would draw this one, so only the check rejects it.
(
"count not a multiple of 3",
run(short, 0, 4, 0, flat),
count,
),
("zero count", run(short, 0, 0, 0, flat), count),
("range past buffer", run(short, 19, 3, 0, flat), range),
("start overflow", run(short, usize::MAX, 3, 0, flat), range),
("negative vertex", run(short, 0, 3, -1, flat), outside),
("vertex past buffer", run(short, 9, 3, 2, flat), outside),
(
"32-bit index past buffer",
run(IndexBuffer::U32(&[0, 1, 13]), 0, 3, 0, flat),
outside,
),
(
"16-bit restart value",
run(IndexBuffer::U16(&restart), 0, 3, 0, flat),
restart_value,
),
// In range after the base vertex, but still the raw restart value.
(
"16-bit restart value with base vertex",
run(IndexBuffer::U16(&[65533, 65534, 65535]), 0, 3, -65533, flat),
restart_value,
),
(
"32-bit restart value",
run(IndexBuffer::U32(&[0, 1, u32::MAX]), 0, 3, 0, flat),
restart_value,
),
("base overflow", run(short, 0, 3, i32::MAX, flat), outside),
(
"texture missing",
run(short, 0, 3, 0, DepthFill::Bc1Texture),
"textured draw without texture",
),
] {
println!("{reason}: {error}");
assert!(
error.contains("indexed pass") && error.contains(wanted),
"{reason}: {error}"
);
}
}
+202
View File
@@ -1,11 +1,19 @@
use xenora_metal::NativeCompute;
#[path = "native/blend.rs"]
mod blend;
#[path = "support/blend_cases.rs"]
mod blend_cases;
#[path = "native/depth.rs"]
mod depth;
#[path = "support/depth_cases.rs"]
mod depth_cases;
#[path = "native/guest_buffer.rs"]
mod guest_buffer;
#[path = "native/indexed.rs"]
mod indexed;
#[path = "support/indexed_cases.rs"]
mod indexed_cases;
#[path = "native/offscreen.rs"]
mod offscreen;
#[path = "native/texture.rs"]
@@ -55,6 +63,165 @@ fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
assert_eq!(actual, expected);
}
const MAX_DISPATCH_GROUPS: usize = 64;
fn mixing_fixture(rounds: u32) -> String {
fixture(&format!(
"
uint value = input[id] ^ (id * 0x9e3779b9u);
for (uint round = 0u; round < {rounds}u; ++round) {{
value ^= value << 13u;
value ^= value >> 17u;
value ^= value << 5u;
value = value * 0x85ebca6bu + round;
}}
output[id] = value;
"
))
}
fn mixing_expectation(input: &[u32], rounds: u32) -> Vec<u32> {
(0_u32..)
.zip(input)
.map(|(id, &word)| {
let mut value = word ^ id.wrapping_mul(0x9e37_79b9);
for round in 0..rounds {
let left = value ^ (value << 13);
let right = left ^ (left >> 17);
let mixed = right ^ (right << 5);
value = mixed.wrapping_mul(0x85eb_ca6b).wrapping_add(round);
}
value
})
.collect()
}
fn mixing_input(words: u32) -> Vec<u32> {
(0..words)
.map(|id| id.wrapping_mul(0xc2b2_ae35) ^ 0xdead_beef)
.collect()
}
#[test]
fn threadgroup_widths_give_identical_known_answers() {
const WIDTHS: [usize; 16] = [
1, 2, 3, 7, 31, 32, 33, 63, 64, 65, 96, 128, 255, 256, 512, 1024,
];
const GRIDS: [u32; 7] = [1, 63, 64, 65, 1000, 4093, 4096];
const ROUNDS: u32 = 37;
let context = context();
let source = mixing_fixture(ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut checked = 0;
let mut skipped = 0;
for grid in GRIDS {
let input = mixing_input(grid);
let expected = mixing_expectation(&input, ROUNDS);
for width in WIDTHS {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
skipped += 1;
continue;
}
let groups = input.len().div_ceil(width);
if groups > MAX_DISPATCH_GROUPS {
println!(
"skipped grid={grid} width={width}: {groups} groups exceed {MAX_DISPATCH_GROUPS}"
);
skipped += 1;
continue;
}
let profile =
native(context.run_words_with_group_width(&source, "fixture", &input, width));
assert_eq!(profile.output, expected, "grid={grid} width={width}");
checked += 1;
}
}
assert!(checked > 0);
println!("checked {checked} configurations, skipped {skipped}");
}
#[test]
fn threadgroup_width_rejections() {
let context = context();
let source = fixture("output[id] = input[id];");
let limit = native(context.max_group_width(&source, "fixture"));
for width in [0, limit + 1] {
let error = context
.run_words_with_group_width(&source, "fixture", &[25], width)
.expect_err("invalid threadgroup width must fail");
assert_eq!(error.operation, "threadgroup width");
}
let error = context
.run_words_with_group_width(&source, "fixture", &[25; MAX_DISPATCH_GROUPS + 1], 1)
.expect_err("too many threadgroups must fail");
assert_eq!(error.operation, "dispatch bounds");
}
fn timing_summary(samples: &mut [f64]) -> String {
samples.sort_by(f64::total_cmp);
let count = samples.len();
let median = f64::midpoint(samples[(count - 1) / 2], samples[count / 2]);
let p95 = samples[(count * 95).div_ceil(100) - 1];
format!(
"median={:.3} min={:.3} max={:.3} p95={:.3}",
median * 1e6,
samples[0] * 1e6,
samples[count - 1] * 1e6,
p95 * 1e6,
)
}
#[test]
#[ignore = "manual GPU timing run"]
fn threadgroup_width_benchmark() {
const ROUNDS: u32 = 2000;
const WARMUPS: usize = 5;
const SAMPLES: usize = 30;
let context = context();
let device = context.device_name();
let source = mixing_fixture(ROUNDS);
let input = mixing_input(4096);
let expected = mixing_expectation(&input, ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut widths = vec![None];
for width in [32, 64, 128, 256, 512, 1024] {
if width > limit {
println!("device={device} skipped width={width}: device/pipeline limit is {limit}");
} else if input.len().div_ceil(width) > MAX_DISPATCH_GROUPS {
println!("device={device} skipped width={width}: exceeds {MAX_DISPATCH_GROUPS} groups");
} else {
widths.push(Some(width));
}
}
let mut timings = vec![([0.0; SAMPLES], [0.0; SAMPLES]); widths.len()];
for round in 0..WARMUPS + SAMPLES {
for (width, (gpu, host)) in widths.iter().zip(&mut timings) {
let profile = native(match width {
Some(width) => {
context.run_words_with_group_width(&source, "fixture", &input, *width)
}
None => context.run_words_profiled(&source, "fixture", &input),
});
assert_eq!(profile.output, expected, "width={width:?} round={round}");
if round >= WARMUPS {
gpu[round - WARMUPS] = profile.gpu_seconds;
host[round - WARMUPS] = profile.host_seconds;
}
}
}
for (width, (gpu, host)) in widths.into_iter().zip(&mut timings) {
let width = width.map_or_else(|| "default".to_owned(), |width| width.to_string());
println!(
"device={device} width={width} gpu_us[{}] host_us[{}]",
timing_summary(gpu),
timing_summary(host),
);
}
}
#[test]
fn integer_multiplication() {
let context = context();
@@ -207,3 +374,38 @@ fn errors_propagate() {
.expect_err("excessive dispatch must fail");
assert_eq!(error.operation, "dispatch bounds");
}
/// Identical outputs alone cannot show which width ran, so each thread also
/// reports the requested group width, its own group's size and its in-group
/// index (11, 11 and 10 bits).
#[test]
fn requested_threadgroup_width_is_dispatched() {
const SOURCE: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void fixture(device const uint *input [[buffer(0)]],
device uint *output [[buffer(1)]],
uint id [[thread_position_in_grid]],
uint local [[thread_index_in_threadgroup]],
uint group_size [[threads_per_threadgroup]],
uint requested [[dispatch_threads_per_threadgroup]]) {
output[id] = (requested << 21u) | (group_size << 10u) | local;
}
";
let context = context();
let limit = native(context.max_group_width(SOURCE, "fixture"));
for (grid, width) in [(1000_usize, 33_usize), (4093, 64), (4096, 256), (65, 1024)] {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
continue;
}
let profile =
native(context.run_words_with_group_width(SOURCE, "fixture", &vec![0; grid], width));
for (id, word) in profile.output.iter().enumerate() {
// dispatchThreads trims the last group to the grid's remainder.
let size = width.min(grid - id / width * width);
let expected = u32::try_from((width << 21) | (size << 10) | (id % width)).unwrap();
assert_eq!(*word, expected, "grid={grid} width={width} id={id}");
}
}
}
+212
View File
@@ -0,0 +1,212 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original blend-pass fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/blend_expected.txt`.
//!
//! The expectations record, per channel, whether the exact result needed
//! rounding; the native test's tolerance (`native/blend.rs`) depends on it.
use xenora_ref::blend::{RefBlend, RefBlendFactor, RefBlendOperation};
pub const SIZE: usize = 16;
pub const CLEAR: [u8; 4] = [32, 64, 96, 128];
const DST: [u8; 4] = [200, 100, 50, 160];
const SRC: [u8; 4] = [60, 180, 240, 96];
// Triangles in pixel coordinates; no pixel centre lies on any edge.
const A: [[f32; 2]; 3] = [[0.0, 0.0], [16.0, 0.0], [0.0, 12.0]];
const B: [[f32; 2]; 3] = [[4.0, 3.0], [16.0, 4.0], [6.0, 16.0]];
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
pub blend: Option<RefBlend>,
/// Written channels R, G, B, A.
pub mask: [bool; 4],
}
#[derive(Debug)]
pub struct Case {
pub name: String,
pub draws: Vec<Draw>,
}
fn clip(tri: [[f32; 2]; 3]) -> [[f32; 4]; 3] {
tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0])
}
fn same(
source: RefBlendFactor,
destination: RefBlendFactor,
operation: RefBlendOperation,
) -> RefBlend {
RefBlend {
source_rgb: source,
destination_rgb: destination,
rgb_operation: operation,
source_alpha: source,
destination_alpha: destination,
alpha_operation: operation,
}
}
/// Destination triangle A, then source triangle B with `blend` and `mask`.
fn case(name: String, blend: Option<RefBlend>, mask: [bool; 4]) -> Case {
Case {
name,
draws: vec![
Draw {
positions: clip(A),
color: DST,
blend: None,
mask: [true; 4],
},
Draw {
positions: clip(B),
color: SRC,
blend,
mask,
},
],
}
}
/// Every case, in fixture order.
pub fn cases() -> Vec<Case> {
use RefBlendFactor::{One, OneMinusSourceAlpha, SourceAlpha, Zero};
use RefBlendOperation::Add;
let all = [true; 4];
let mut cases = vec![
Case {
name: "clear".to_owned(),
draws: Vec::new(),
},
case("disabled".to_owned(), None, all),
];
for factor in RefBlendFactor::ALL {
cases.push(case(
format!("src_{factor:?}"),
Some(same(factor, Zero, Add)),
all,
));
}
for factor in RefBlendFactor::ALL {
cases.push(case(
format!("dst_{factor:?}"),
Some(same(Zero, factor, Add)),
all,
));
}
for operation in RefBlendOperation::ALL {
cases.push(case(
format!("op_{operation:?}"),
Some(same(SourceAlpha, OneMinusSourceAlpha, operation)),
all,
));
}
cases.push(case(
"additive_clamp".to_owned(),
Some(same(One, One, Add)),
all,
));
cases.push(case(
"separate_alpha".to_owned(),
Some(RefBlend {
source_alpha: One,
destination_alpha: Zero,
..same(SourceAlpha, OneMinusSourceAlpha, Add)
}),
all,
));
for (name, mask) in [
("R", [true, false, false, false]),
("G", [false, true, false, false]),
("B", [false, false, true, false]),
("A", [false, false, false, true]),
("RGB", [true, true, true, false]),
("none", [false; 4]),
("RGBA", all),
] {
cases.push(case(format!("mask_{name}"), None, mask));
}
cases.push(case(
"mask_RG_blended".to_owned(),
Some(same(SourceAlpha, OneMinusSourceAlpha, Add)),
[true, true, false, false],
));
let mut first = case(
"first_draw_blended".to_owned(),
None,
[true, true, false, false],
);
first.draws[0].blend = Some(same(SourceAlpha, OneMinusSourceAlpha, Add));
first.draws[0].mask = [false, true, true, true];
cases.push(case(
"separate_operation".to_owned(),
Some(RefBlend {
source_alpha: One,
destination_alpha: One,
alpha_operation: RefBlendOperation::ReverseSubtract,
..same(SourceAlpha, OneMinusSourceAlpha, Add)
}),
all,
));
cases.push(first);
cases
}
/// One case of `blend_expected.txt`: per pixel, the colour and whether each
/// channel needed rounding.
#[derive(Debug)]
pub struct Expected {
pub name: String,
pub color: Vec<[u8; 4]>,
pub exact: Vec<[bool; 4]>,
}
/// Parse the independently derived expectations.
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/blend_expected.txt");
let mut out = Vec::new();
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
while let Some(header) = lines.next() {
let name = header.strip_prefix("case ").expect("case line").to_owned();
let (mut palette, mut color, mut exact) = (Vec::new(), Vec::new(), Vec::new());
for line in lines.by_ref() {
let words: Vec<&str> = line.split_whitespace().collect();
match words[0] {
"palette" => {
let key = words[1].chars().next().unwrap();
let rgba: Vec<u8> = words[2..6].iter().map(|w| w.parse().unwrap()).collect();
let flags: Vec<bool> = words[6]
.chars()
.map(|c| match c {
'e' => true,
'r' => false,
other => panic!("unexpected rounding flag {other}"),
})
.collect();
palette.push((
key,
<[u8; 4]>::try_from(rgba).unwrap(),
<[bool; 4]>::try_from(flags).unwrap(),
));
}
"color" => {
for c in words[1].chars() {
let entry = palette.iter().find(|(k, ..)| *k == c).expect("palette key");
color.push(entry.1);
exact.push(entry.2);
}
}
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
out.push(Expected { name, color, exact });
}
out
}
+188
View File
@@ -0,0 +1,188 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original indexed-draw fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/indexed_expected.txt`.
pub const SIZE: usize = 16;
const RED: [u8; 4] = [255, 0, 0, 255];
const GREEN: [u8; 4] = [0, 255, 0, 255];
const BLUE: [u8; 4] = [0, 0, 255, 255];
const BLACK: [u8; 4] = [0, 0, 0, 255];
/// The four original BC1 blocks of the depth fixtures (8x8 texels), using
/// only endpoint and transparent selectors so every decoded texel is exact.
pub const BC1_BLOCKS: [u8; 32] = [
0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour
0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour
0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black
0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black
];
/// Vertex buffer in pixel coordinates; no pixel centre lies on any edge of
/// a triangle the cases draw.
const VERTICES: [[f32; 2]; 13] = [
[0.0, 0.0],
[16.0, 0.0],
[0.0, 12.0],
[4.0, 3.0],
[16.0, 4.0],
[6.0, 16.0],
[0.0, 8.0],
[10.0, 8.0],
[0.0, 16.0],
[0.0, 0.0],
[16.0, 0.0],
[16.0, 15.0],
[0.0, 16.0],
];
/// The index buffer of the 16-bit cases.
pub const INDICES: [u16; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 11, 12, 2, 1, 0, 10, 11, 12,
];
/// The index buffer of the 32-bit cases: [`INDICES`] and three indices that
/// need more than 16 bits.
pub fn wide_indices() -> Vec<u32> {
INDICES
.iter()
.map(|&index| u32::from(index))
.chain([65545, 65546, 65547])
.collect()
}
/// Clip-space positions of [`VERTICES`] at depth 0.5.
pub fn vertices() -> Vec<[f32; 4]> {
VERTICES
.iter()
.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0])
.collect()
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Fill {
Flat([u8; 4]),
Texture,
}
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub start: usize,
pub count: usize,
pub base_vertex: i32,
pub fill: Fill,
}
#[derive(Debug)]
pub struct Case {
pub name: &'static str,
pub wide: bool,
pub clear_color: [u8; 4],
pub draws: Vec<Draw>,
}
/// Every case, in fixture order.
pub fn cases() -> Vec<Case> {
let draw = |start, count, base_vertex, fill| Draw {
start,
count,
base_vertex,
fill,
};
let (red, green, blue, texture) = (
Fill::Flat(RED),
Fill::Flat(GREEN),
Fill::Flat(BLUE),
Fill::Texture,
);
let case = |name, wide, draws| Case {
name,
wide,
clear_color: BLACK,
draws,
};
vec![
Case {
clear_color: [16, 32, 48, 255],
..case("clear", false, Vec::new())
},
case("u16_first", false, vec![draw(0, 3, 0, red)]),
case("u32_first", true, vec![draw(0, 3, 0, red)]),
case("u16_odd_start", false, vec![draw(3, 3, 0, green)]),
case("u32_start", true, vec![draw(3, 3, 0, green)]),
case("u16_base_positive", false, vec![draw(0, 3, 6, blue)]),
case("u16_base_negative", false, vec![draw(18, 3, -4, blue)]),
case("u32_base_negative", true, vec![draw(18, 3, -4, blue)]),
case("reversed_winding", false, vec![draw(15, 3, 0, red)]),
case(
"two_triangles_textured",
false,
vec![draw(9, 6, 0, texture)],
),
case("textured_base_vertex", false, vec![draw(0, 3, 9, texture)]),
case(
"painter_order",
false,
vec![
draw(0, 3, 0, red),
draw(3, 3, 0, green),
draw(0, 3, 6, blue),
],
),
case(
"u32_mixed",
true,
vec![
draw(9, 6, 0, texture),
draw(18, 3, -1, green),
draw(6, 3, -6, red),
],
),
case("flat_two_triangles", false, vec![draw(9, 6, 0, green)]),
case("textured_first", false, vec![draw(0, 3, 0, texture)]),
case("u32_high_indices", true, vec![draw(21, 3, -65536, red)]),
]
}
/// One case of `indexed_expected.txt`: fetched vertices per draw and colours.
#[derive(Debug)]
pub struct Expected {
pub name: String,
pub fetch: Vec<Vec<usize>>,
pub color: Vec<[u8; 4]>,
}
/// Parse the independently derived expectations.
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/indexed_expected.txt");
let mut out = Vec::new();
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
while let Some(header) = lines.next() {
let name = header.strip_prefix("case ").expect("case line").to_owned();
let (mut fetch, mut palette, mut color) = (Vec::new(), Vec::new(), Vec::new());
for line in lines.by_ref() {
let mut words = line.split_whitespace();
match words.next().expect("keyword") {
"fetch" => fetch.push(words.map(|word| word.parse().unwrap()).collect()),
"palette" => {
let key = words.next().unwrap().chars().next().unwrap();
let rgba: Vec<u8> = words.map(|word| word.parse().unwrap()).collect();
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
}
"color" => color.extend(words.next().unwrap().chars().map(|c| {
palette
.iter()
.find(|(key, _)| *key == c)
.expect("palette key")
.1
})),
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
out.push(Expected { name, fetch, color });
}
out
}
+310
View File
@@ -0,0 +1,310 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for blended, write-masked triangle draws into an
//! RGBA8 unorm target.
//!
//! Every value is kept exact: a unorm8 value `v` means `v / 255`, so a
//! weighted term `value * factor` is an integer count of `1 / 255²`. The
//! result is clamped to 0..=1 and rounded to the nearest unorm8 value. The
//! reference also reports, per channel, whether that rounding was needed, so
//! a native comparison can hold exact results to exact equality. Coverage
//! comes from [`crate::depth::render_depth`].
use std::fmt;
use crate::depth::{CompareFunction, DepthRefError, RefDraw, RefFill, render_depth};
/// A blend factor; the colour factors use the alpha channel's own value for alpha.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefBlendFactor {
Zero,
One,
SourceColor,
OneMinusSourceColor,
SourceAlpha,
OneMinusSourceAlpha,
DestinationColor,
OneMinusDestinationColor,
DestinationAlpha,
OneMinusDestinationAlpha,
}
impl RefBlendFactor {
pub const ALL: [Self; 10] = [
Self::Zero,
Self::One,
Self::SourceColor,
Self::OneMinusSourceColor,
Self::SourceAlpha,
Self::OneMinusSourceAlpha,
Self::DestinationColor,
Self::OneMinusDestinationColor,
Self::DestinationAlpha,
Self::OneMinusDestinationAlpha,
];
/// The factor for `channel` in units of 1/255.
fn value(self, source: [u8; 4], destination: [u8; 4], channel: usize) -> i64 {
let (s, d) = (i64::from(source[channel]), i64::from(destination[channel]));
let (sa, da) = (i64::from(source[3]), i64::from(destination[3]));
match self {
Self::Zero => 0,
Self::One => 255,
Self::SourceColor => s,
Self::OneMinusSourceColor => 255 - s,
Self::SourceAlpha => sa,
Self::OneMinusSourceAlpha => 255 - sa,
Self::DestinationColor => d,
Self::OneMinusDestinationColor => 255 - d,
Self::DestinationAlpha => da,
Self::OneMinusDestinationAlpha => 255 - da,
}
}
}
/// A blend operation; `Min` and `Max` ignore the factors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefBlendOperation {
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
impl RefBlendOperation {
pub const ALL: [Self; 5] = [
Self::Add,
Self::Subtract,
Self::ReverseSubtract,
Self::Min,
Self::Max,
];
}
/// Separate RGB and alpha blend equations.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RefBlend {
pub source_rgb: RefBlendFactor,
pub destination_rgb: RefBlendFactor,
pub rgb_operation: RefBlendOperation,
pub source_alpha: RefBlendFactor,
pub destination_alpha: RefBlendFactor,
pub alpha_operation: RefBlendOperation,
}
/// One flat-coloured triangle; `mask` lists the written channels R, G, B, A.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefBlendDraw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
pub blend: Option<RefBlend>,
pub mask: [bool; 4],
}
/// A blended channel value and whether rounding was needed to reach it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RefChannel {
pub value: u8,
pub exact: bool,
}
/// Blend one channel (0 to 3: R, G, B, A) of `source` over `destination`.
///
/// # Panics
///
/// Panics when `channel` is above 3.
pub fn blend_channel(
blend: RefBlend,
source: [u8; 4],
destination: [u8; 4],
channel: usize,
) -> RefChannel {
let (factors, operation) = if channel == 3 {
(
(blend.source_alpha, blend.destination_alpha),
blend.alpha_operation,
)
} else {
(
(blend.source_rgb, blend.destination_rgb),
blend.rgb_operation,
)
};
let (s, d) = (i64::from(source[channel]), i64::from(destination[channel]));
let weighted_s = s * factors.0.value(source, destination, channel);
let weighted_d = d * factors.1.value(source, destination, channel);
// In units of 1/255².
let result = match operation {
RefBlendOperation::Add => weighted_s + weighted_d,
RefBlendOperation::Subtract => weighted_s - weighted_d,
RefBlendOperation::ReverseSubtract => weighted_d - weighted_s,
RefBlendOperation::Min => s.min(d) * 255,
RefBlendOperation::Max => s.max(d) * 255,
}
.clamp(0, 255 * 255);
RefChannel {
// Round half up: floor(result / 255 + 1/2).
value: u8::try_from((2 * result + 255) / 510).expect("clamped to 0..=255"),
exact: result % 255 == 0,
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum BlendRefError {
/// The extent is empty or holds more than 4096 pixels, the native limit.
Extent,
/// The triangle coverage could not be computed.
Raster(DepthRefError),
}
impl fmt::Display for BlendRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for BlendRefError {}
/// Render `draws` in order over a target cleared to `clear_color`, returning
/// each pixel's channels and whether each needed rounding (a cleared or
/// replaced channel is exact).
///
/// # Errors
///
/// Returns an error for an extent that is empty or above 4096 pixels, or when a triangle's
/// coverage cannot be computed (see [`render_depth`]).
pub fn render_blend(
extent: [usize; 2],
clear_color: [u8; 4],
draws: &[RefBlendDraw],
) -> Result<Vec<[RefChannel; 4]>, BlendRefError> {
let exact = |value| RefChannel { value, exact: true };
let pixels = extent[0]
.checked_mul(extent[1])
.filter(|&n| (1..=4096).contains(&n))
.ok_or(BlendRefError::Extent)?;
let mut target = vec![clear_color.map(exact); pixels];
for draw in draws {
// Coverage: a white triangle over black, without depth attachment.
let (coverage, _) = render_depth(
extent,
[0; 4],
None,
&[RefDraw {
positions: draw.positions,
fill: RefFill::Flat([255; 4]),
compare: CompareFunction::Always,
write: false,
}],
None,
)
.map_err(BlendRefError::Raster)?;
for (pixel, covered) in target.iter_mut().zip(coverage) {
if covered != [255; 4] {
continue;
}
let destination = pixel.map(|channel| channel.value);
for (channel, slot) in pixel.iter_mut().enumerate() {
if !draw.mask[channel] {
continue;
}
*slot = match draw.blend {
None => exact(draw.color[channel]),
Some(blend) => blend_channel(blend, draw.color, destination, channel),
};
}
}
}
Ok(target)
}
#[cfg(test)]
mod tests {
use super::*;
use RefBlendFactor::{One, OneMinusSourceAlpha, SourceAlpha, Zero};
use RefBlendOperation::{Add, Max, Min, ReverseSubtract, Subtract};
fn blend(
source: RefBlendFactor,
destination: RefBlendFactor,
operation: RefBlendOperation,
) -> RefBlend {
RefBlend {
source_rgb: source,
destination_rgb: destination,
rgb_operation: operation,
source_alpha: source,
destination_alpha: destination,
alpha_operation: operation,
}
}
#[test]
fn bad_extents_are_rejected() {
for extent in [[0, 4], [4, 0], [usize::MAX, 2], [usize::MAX, 1], [65, 64]] {
assert_eq!(
render_blend(extent, [0; 4], &[]),
Err(BlendRefError::Extent)
);
}
}
#[test]
fn channels_follow_the_blend_equation() {
let (s, d) = ([60, 180, 240, 96], [200, 100, 50, 160]);
let channel = |state, c| blend_channel(state, s, d, c);
// 60 * 96 / 255 + 200 * 159 / 255 = 147.29...
assert_eq!(
channel(blend(SourceAlpha, OneMinusSourceAlpha, Add), 0),
RefChannel {
value: 147,
exact: false
}
);
assert_eq!(
channel(blend(One, Zero, Add), 1),
RefChannel {
value: 180,
exact: true
}
);
// 240 + 50 clamps to 255; 60 - 200 clamps to 0.
assert_eq!(
channel(blend(One, One, Add), 2),
RefChannel {
value: 255,
exact: true
}
);
assert_eq!(
channel(blend(One, One, Subtract), 0),
RefChannel {
value: 0,
exact: true
}
);
assert_eq!(
channel(blend(One, One, ReverseSubtract), 0),
RefChannel {
value: 140,
exact: true
}
);
// Min and Max ignore the factors.
assert_eq!(
channel(blend(Zero, Zero, Min), 1),
RefChannel {
value: 100,
exact: true
}
);
assert_eq!(
channel(blend(Zero, Zero, Max), 3),
RefChannel {
value: 160,
exact: true
}
);
}
}
+202
View File
@@ -0,0 +1,202 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for indexed triangle-list draws.
//!
//! A draw reads `count` indices starting at index `start` and fetches vertex
//! `index + base_vertex` for each, as `DrawIndexedInstanced` and Metal's
//! `drawIndexedPrimitives` describe. Every fetched vertex must lie inside the
//! vertex buffer, and no index may be the primitive-restart value (all bits
//! set); the reference rejects the draw instead of defining either behaviour. The triangles are then rasterised by
//! [`crate::depth::render_depth`] without a depth attachment.
use std::fmt;
use crate::depth::{CompareFunction, RefDraw, RefFill, RefTexture, render_depth};
/// An index buffer of 16- or 32-bit unsigned indices.
#[derive(Clone, Copy, Debug)]
pub enum RefIndices<'a> {
U16(&'a [u16]),
U32(&'a [u32]),
}
impl RefIndices<'_> {
fn len(self) -> usize {
match self {
Self::U16(indices) => indices.len(),
Self::U32(indices) => indices.len(),
}
}
fn restart(self) -> u32 {
match self {
Self::U16(_) => u32::from(u16::MAX),
Self::U32(_) => u32::MAX,
}
}
fn get(self, position: usize) -> Option<u32> {
match self {
Self::U16(indices) => indices.get(position).map(|&index| u32::from(index)),
Self::U32(indices) => indices.get(position).copied(),
}
}
}
/// One indexed draw: a range of the index buffer, a signed base vertex and a fill.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefIndexedDraw {
pub start: usize,
pub count: usize,
pub base_vertex: i32,
pub fill: RefFill,
}
#[derive(Debug, Eq, PartialEq)]
pub enum IndexedRefError {
/// The index count of the draw is zero or not a multiple of 3: (draw).
Count(usize),
/// The index range of the draw ends past the index buffer: (draw).
IndexRange(usize),
/// `index + base_vertex` lies outside the vertex buffer: (draw, index position).
VertexRange(usize, usize),
/// The index is the primitive-restart value: (draw, index position).
Restart(usize, usize),
/// The resolved triangles could not be rasterised.
Raster(crate::depth::DepthRefError),
}
impl fmt::Display for IndexedRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for IndexedRefError {}
/// The vertex numbers draw `draw` of a pass fetches, in index order.
///
/// # Errors
///
/// Returns an error for a count that is zero or not a multiple of 3, an index
/// range past the buffer, a primitive-restart index, or a fetched vertex
/// outside `0..vertex_count`.
pub fn fetch(
draw_number: usize,
draw: &RefIndexedDraw,
indices: RefIndices<'_>,
vertex_count: usize,
) -> Result<Vec<usize>, IndexedRefError> {
if draw.count == 0 || !draw.count.is_multiple_of(3) {
return Err(IndexedRefError::Count(draw_number));
}
let end = draw
.start
.checked_add(draw.count)
.filter(|&end| end <= indices.len())
.ok_or(IndexedRefError::IndexRange(draw_number))?;
(draw.start..end)
.map(|position| {
let index = indices.get(position).expect("position checked above");
if index == indices.restart() {
return Err(IndexedRefError::Restart(draw_number, position));
}
usize::try_from(i64::from(index) + i64::from(draw.base_vertex))
.ok()
.filter(|&vertex| vertex < vertex_count)
.ok_or(IndexedRefError::VertexRange(draw_number, position))
})
.collect()
}
/// Render indexed draws in order over a target cleared to `clear_color`.
///
/// # Errors
///
/// Returns an error when [`fetch`] rejects a draw or the resolved triangles
/// cannot be rasterised (see [`render_depth`]).
pub fn render_indexed(
extent: [usize; 2],
clear_color: [u8; 4],
vertices: &[[f32; 4]],
indices: RefIndices<'_>,
draws: &[RefIndexedDraw],
texture: Option<RefTexture<'_>>,
) -> Result<Vec<[u8; 4]>, IndexedRefError> {
let mut triangles = Vec::new();
for (number, draw) in draws.iter().enumerate() {
let fetched = fetch(number, draw, indices, vertices.len())?;
triangles.extend(fetched.as_chunks::<3>().0.iter().map(|triangle| RefDraw {
positions: triangle.map(|vertex| vertices[vertex]),
fill: draw.fill,
compare: CompareFunction::Always,
write: false,
}));
}
render_depth(extent, clear_color, None, &triangles, texture)
.map(|(color, _)| color)
.map_err(IndexedRefError::Raster)
}
#[cfg(test)]
mod tests {
use super::*;
fn draw(start: usize, count: usize, base_vertex: i32) -> RefIndexedDraw {
RefIndexedDraw {
start,
count,
base_vertex,
fill: RefFill::Flat([255; 4]),
}
}
#[test]
fn fetch_applies_start_and_signed_base_vertex() {
let indices = RefIndices::U16(&[7, 0, 1, 2, 5]);
assert_eq!(fetch(0, &draw(1, 3, 2), indices, 5), Ok(vec![2, 3, 4]));
assert_eq!(fetch(0, &draw(2, 3, -1), indices, 5), Ok(vec![0, 1, 4]));
}
#[test]
fn fetch_rejects_bad_counts_ranges_and_vertices() {
let indices = RefIndices::U32(&[0, 1, 2, u32::MAX]);
assert_eq!(
fetch(3, &draw(0, 0, 0), indices, 3),
Err(IndexedRefError::Count(3))
);
assert_eq!(
fetch(0, &draw(0, 2, 0), indices, 3),
Err(IndexedRefError::Count(0))
);
assert_eq!(
fetch(0, &draw(2, 3, 0), indices, 3),
Err(IndexedRefError::IndexRange(0))
);
assert_eq!(
fetch(0, &draw(usize::MAX, 3, 0), indices, 3),
Err(IndexedRefError::IndexRange(0))
);
assert_eq!(
fetch(0, &draw(0, 3, -1), indices, 3),
Err(IndexedRefError::VertexRange(0, 0))
);
assert_eq!(
fetch(0, &draw(0, 3, 1), indices, 3),
Err(IndexedRefError::VertexRange(0, 2))
);
assert_eq!(
fetch(0, &draw(1, 3, 0), indices, 3),
Err(IndexedRefError::Restart(0, 3))
);
// The raw restart value is rejected even when the base vertex would
// bring it into range.
let high = RefIndices::U16(&[65533, 65534, 65535]);
assert_eq!(
fetch(0, &draw(0, 3, -65533), high, 3),
Err(IndexedRefError::Restart(0, 2))
);
let high = RefIndices::U16(&[65532, 65533, 65534]);
assert_eq!(fetch(0, &draw(0, 3, -65532), high, 3), Ok(vec![0, 1, 2]));
}
}
+46 -4
View File
@@ -1,8 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling and depth-tested rendering.
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling, and host-side references for depth-tested rendering, indexed draws and blending.
pub mod blend;
pub mod depth;
pub mod indexed;
pub mod texture_sampling;
use std::fmt;
@@ -127,7 +129,7 @@ pub enum BranchCondition {
///
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
/// operations set SCC iff the result is nonzero.
/// operations and shifts set SCC iff the result is nonzero.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAlu {
Add,
@@ -140,6 +142,22 @@ pub enum ScalarAlu {
And,
Or,
Xor,
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
AndNot,
/// D = S0 | ~S1, SCC = (D != 0).
OrNot,
/// D = ~(S0 & S1), SCC = (D != 0).
Nand,
/// D = ~(S0 | S1), SCC = (D != 0).
Nor,
/// D = ~(S0 ^ S1), SCC = (D != 0).
Xnor,
/// D = S0 << S1[4:0], SCC = (D != 0).
ShiftLeft,
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
ShiftRight,
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
ArithmeticShiftRight,
}
/// VOP2 operations decoded by the reference interpreter.
@@ -285,7 +303,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
left,
right,
low,
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
high @ (0x80..=0x82 | 0x87..=0x91),
tail @ ..,
] if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
@@ -300,7 +318,16 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
(0x82, _) => ScalarAlu::SubtractWithBorrow,
(0x87, _) => ScalarAlu::And,
(0x88, _) => ScalarAlu::Or,
_ => ScalarAlu::Xor,
(0x89, _) => ScalarAlu::Xor,
// Even opcodes 20-34 (bit 23 clear, checked above).
(0x8a, _) => ScalarAlu::AndNot,
(0x8b, _) => ScalarAlu::OrNot,
(0x8c, _) => ScalarAlu::Nand,
(0x8d, _) => ScalarAlu::Nor,
(0x8e, _) => ScalarAlu::Xnor,
(0x8f, _) => ScalarAlu::ShiftLeft,
(0x90, _) => ScalarAlu::ShiftRight,
_ => ScalarAlu::ArithmeticShiftRight,
};
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
@@ -692,6 +719,21 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
};
(bits, bits != 0)
}
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
_ => {
let (a, b) = (lhs as u32, rhs as u32);
let bits = match kind {
ScalarAlu::AndNot => a & !b,
ScalarAlu::OrNot => a | !b,
ScalarAlu::Nand => !(a & b),
ScalarAlu::Nor => !(a | b),
ScalarAlu::Xnor => !(a ^ b),
ScalarAlu::ShiftLeft => a << (b & 0x1f),
ScalarAlu::ShiftRight => a >> (b & 0x1f),
_ => ((a as i32) >> (b & 0x1f)) as u32,
};
(i64::from(bits), bits != 0)
}
};
let value = exact.rem_euclid(1 << 32) as u32;
scalars[usize::from(dst)] = Some(value);
+14
View File
@@ -280,6 +280,20 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
);
}
#[test]
fn scalar_logic_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-logic.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-logic.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
+9 -7
View File
@@ -10,21 +10,24 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
## Architecture and technical design
- [Interface contracts](interfaces.md) — Shader inputs, guest services, native command submission, and synthetic textures.
- [Interface contracts](interfaces.md) — Translated shader stages, guest services, native command submission, and synthetic textures.
- [Fixture memory model](adr/0003-demo-memory-model.md) and [CPU boundary](adr/0004-cpu-boundary.md) — Buffer bindings, guest address translation, and dependency direction.
## Native Metal graphics
- [Translated offscreen stages](interfaces.md#translated-offscreen-stages) — Translated vertex and pixel stages for the bounded gfx1030 subset.
- [Blend and depth passes](interfaces.md) — Native blend and depth graphics passes with per-draw state.
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
## RDNA 2 decoding and shader translation
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
- [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.
- [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.
## Native Metal backend
- [Compute interface](interfaces.md#gfx1030-compute-fixtures) — Resource limits, dispatch, completion, and profiling.
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
## Guest CPU and runtime experiments
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
@@ -36,7 +39,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
+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: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 50 of 50. Accepted Metal forms · Apple M5: 18 of 50. 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">42 / 42</text>
<text x="510" y="58" font-size="13" text-anchor="end">50 / 50</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 / 42</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 50</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="176.40" 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

+21
View File
@@ -186,3 +186,24 @@ multiply forms. The graphics ABI also supports register and finite
literal moves. Unsupported stage instructions or export combinations
fail explicitly. The Xbox graphics ABI, hardware-specific floating-point
modes, image instructions, and additional varyings remain unsupported.
## Graphics draw and blend contracts
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call
per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a
signed base vertex, into an offscreen RGBA8 target. A draw can sample an
original BC1 texture uploaded natively. Before encoding anything it rejects
malformed draws; execution checks each draw in turn.
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order
into an offscreen RGBA8 target. Each draw has its own colour write mask and
either blending disabled or separate RGB and alpha blend factors and
operations. Colours are compared per channel against expectations derived
independently from the public Metal blend equations.
`NativeCompute::render_depth` draws up to 16 triangles in order with an
optional `Depth32Float` attachment, a chosen clear depth and a per-draw depth
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.
+9 -15
View File
@@ -1,12 +1,16 @@
# Engineering progress
**NOT RELEASE-READY.** The three-fixture demo checkpoint was pushed at `96cff7c66e55f1e4693ace19577c207795258d5c` and its [Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/runs/45001680455) passed. See the [current assurance report](testing/phase01-assurance.md) for candidate evidence and the [historical engineering report](testing/phase01-checkpoint.md) for the initial checkpoint.
Xenora is an experimental research project. Verified work is restricted to
independently authored synthetic programs and shaders; commercial game
execution and authentic Xbox startup are unsupported. Progress is measured by
reproducible tests, not by estimated game compatibility percentages.
## Reading the progress graphic
- **Decoded forms** counts rows marked decoded in the [status registry](status.toml), out of all rows in that reviewed gfx1030 instruction inventory.
- **Accepted Metal forms** counts rows with accepted native fixture readback, over the same inventory. See the [form-by-form results](shaders/instruction-coverage.md) and [implementation checkpoint](testing/phase-02-baseline.md#implementation-checkpoint) for class A evidence from Apple M5. Arithmetic shift has its own [fixture record](../fixtures/rdna2/ashr.md); its CPU path now has explicit checkpoints, a positive-value control and independent-oracle coverage, while its native readback remains local evidence with independent acceptance open.
- **Accepted guest milestones** counts the recorded fixture demonstrations for native guest instruction execution (X1), executable loading (X2), guest-to-GPU command submission (X3), and guest-driven Metal rendering (X4), out of those four milestones. See the [guest acceptance record](testing/phase-02-baseline.md#track-b--guest-execution).
- **Accepted Metal forms** counts rows with accepted native fixture readback, over the same inventory. See the [form-by-form results](shaders/instruction-coverage.md) and [implementation checkpoint](testing/phase-02-baseline.md#implementation-checkpoint) for class A evidence from Apple M5.
## Feature status
<!-- status:features:start -->
| Feature | Target | Implementation | Correctness | Hardware | Evidence | Limits |
@@ -35,18 +39,8 @@ scripts/audit/claims.sh
scripts/audit/dependencies.sh
```
The independent CPU validation tests are part of the workspace. The native suite and optional LLVM oracle run separately so CPU-only CI can report them accurately. Final local logs are under ignored `artifacts/phase01/`. Keep the historical lab and candidate logs separate.
## Dual-track execution
The [dual-track baseline](testing/phase-02-baseline.md) records Phase 02
GPU prerequisites and the separate guest execution milestones.
The independent CPU validation tests are part of the workspace. The native suite and optional LLVM oracle run separately so CPU-only CI can report them accurately. Final local logs are under ignored `artifacts/`. Keep the historical lab and candidate logs separate.
## Remaining work
See the [assurance checkpoint](testing/phase01-assurance.md) for the original gate ledger and commands, and the [independent review](testing/review-log.md#phase-01-evidence-recheck-at-4b9a4ce) for later findings.
1. The independent reference (G5), LLVM decoder comparison (G6), and mutation testing (G7) passed at the Phase 01 candidate. The [integrated review](testing/mutation.md#integrated-source-campaign-at-4b9a4ce) confirmed 359 of 361 non-equivalent source mutants killed, all 44 independent-oracle kills and all 12 native semantic kills. The form-by-form validation report is in the [validation inventory](../tests/validation/README.md).
2. Parser fuzzing (G9) passed for the Phase 01 candidate. Native decoder and reference runs at `4b9a4ce` exited 0 after 123,522,954 and 240,077,291 executions respectively, each in 601 seconds. The fixture run at `aff46b0` exited 0 after 244,422,168 executions in 601 seconds. The fuzz source, dependencies, script and fixture inputs are identical between these commits. Logs and executable hashes are under `artifacts/g9/4b9a4ce-20261123T041525Z/`. Phase 02 source changes require their own assurance.
3. Finish benchmark corpus and protocol coverage before rerunning on AC and an idle system. Preserve the [exploratory battery and AC records](testing/benchmarks.md).
4. Close independent claims, status, history and review findings against the integrated candidate. Verify the [runtime redistribution blockers](licenses.md#runtime-redistribution-review) before closing the redistribution gate (G11).
See the [current limitations](../README.md#current-limitations) for the outstanding items. The active research steps are: finish the remaining RDNA2 wave execution and mesh stages, translated texture sampling, broader resource binding and synchronization. Close independent claims, status, history and review findings against the current candidates, and verify the [runtime redistribution blockers](licenses.md#runtime-redistribution-review) before closing the redistribution gate (G11).
+8
View File
@@ -31,6 +31,14 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
+34 -2
View File
@@ -1,6 +1,6 @@
# SOP2 scalar ALU subset
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
Xenora decodes and executes seventeen gfx1030 SOP2 forms. Each takes 32-bit
operands, writes a normal SGPR (s0-s105) and sets SCC.
| Form | D | SCC |
@@ -14,8 +14,33 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
| `s_and_b32` | S0 & S1 | D != 0 |
| `s_or_b32` | S0 \| S1 | D != 0 |
| `s_xor_b32` | S0 ^ S1 | D != 0 |
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
The last eight were added through the semantic registry alone: one TOML entry
each, with no hand-written Rust per form. Shifts use only the low five bits of
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
ignored.
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
These forms are declared as data in the semantic registry,
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
checks each declaration against the pinned AMD XML snapshot and rejects
contradictions (for example a carry-in on a bitwise form, or a signed form whose
SCC is a carry). It then generates `crates/isa/src/semantics_gen.rs`, which holds
the decoder's opcode dispatch and `ScalarAluOp`'s mnemonic, SCC read and
evaluation through the shared primitives in `crates/isa/src/primitive.rs`. Run
`python3 crates/isa/generate_semantics.py validate`, `generate` or `--check`
(Python 3.11 or newer). The reference and independent interpreters do not use
the registry.
`v_mov_b32_e32` may read a normal SGPR, so the results can reach vector code.
## Sources
@@ -73,7 +98,7 @@ literal operands, bitwise results that set and clear SCC, and an
Its expected output, input ^ 0x0000000e,
was derived by hand.
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
operands squared, with SCC clear and set. That is 1,800 programs. The same file
covers aliasing, inline and literal operands, and rejected forms. Expected
values come from exact integer definitions in the test. Three implementations
@@ -82,6 +107,13 @@ must agree with them:
- the reference interpreter (exact integers, reduced modulo 2^32);
- the independent interpreter (a bit-serial ripple-carry adder).
The eight logical and shift forms added through the registry have their own
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
values were derived from the guide separately from the registry, checked on
both CPU interpreters and, through the translator, on native Metal. The
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
runs on all three and on native Metal.
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
and the aliasing and immediate cases on native Metal with API and shader
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
+47
View File
@@ -0,0 +1,47 @@
# gfx1030 semantic coverage
<!-- Generated by scripts/audit/semantic_coverage.py. -->
Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms
come from the semantic registry. Decoder support is the decoder's hand-written
list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.
The status inventory records LLVM three-way encoding checks, intermediate
representation (IR) and Metal Shading Language (MSL) lowering, and fixture
verification. IR and MSL share the inventory's lowering field. Reference
verification requires an implemented reference and verified CPU fixture.
Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending
acceptance remain outside the verified count. All results concern synthetic fixtures.
| Family | Identified | Encoding-validated | Declared | Decoder-supported | IR | MSL | Reference-verified | Metal-verified | Unsupported operand variants |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| DS | 123 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| EXP | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
| FLAT | 54 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| GLOBAL | 57 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| MIMG | 130 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
| MTBUF | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
| **Total** | 1465 | 50 | 17 | 54 | 50 | 50 | 18 | 18 | 12 |
## Unsupported operand variants
The table counts distinct variant names per family across registry operand rules.
| Family | Operand rule | Unsupported variants |
| --- | --- | --- |
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
+218
View File
@@ -0,0 +1,218 @@
# Adding an instruction through the semantic registry
The semantic registry is a data file that declares what each supported gfx1030
instruction form does. A generator checks it and turns it into Rust tables that
the decoder uses. This page explains where entries live, what each field means,
how to check and regenerate the tables, and what the generator does not do for
you.
The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.md).
## Files
| File | Role |
| --- | --- |
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
| `crates/isa/src/semantics.rs` | The Rust types the generated tables use (`FormSemantics`, `Operation`, `SccEffect` and so on). |
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
| `tests/semantics_generator/` | Unit tests for the generator. |
## Fields
The top of the file holds:
- `schema`: must be `1`.
- `architecture`: must be `"gfx1030"`.
- `source_sha256`: must equal the `sha256` on the `source` line of
`crates/isa/data/rdna2.jsonl`, so the registry is always checked against the
snapshot it was written for.
- `[documents.<name>]`: the public documents that spec references cite. Only
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
machine-readable ISA) are allowed, and each must match the title and file
pinned in the generator, so a citation cannot point at another file.
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
decoder implements each rule once, and the generator only accepts a rule
whose declaration matches the decoder's implementation exactly. Today there
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
literal. Its `unsupported` list names the encodings the rule rejects, which
stay unsupported instead of being guessed. The list must name exactly the
encodings the decoder rejects.
Each `[[form]]` entry has exactly these fields. A missing or unknown field is an
error.
| Field | Meaning | Allowed values |
| --- | --- | --- |
| `name` | XML instruction name, the form's stable identity | upper-case, e.g. `S_ADD_U32` |
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, never for `add` and `sub`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
| `width` | Operand and result width in bits | `32` |
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
| `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` |
The `operation` and `signedness` pair picks one primitive, and that primitive
fixes the `scc` value:
| `operation` / `signedness` | Required `scc` | Primitive | Reads carry-in |
| --- | --- | --- | --- |
| `add` / `unsigned` | `carry_out` | `add_carry_u32` | allowed |
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
Behaviour is chosen only from these declared fields, never from the mnemonic.
## What the validator checks
`validate` reports every error it finds, not only the first (a form with a missing field is not checked further). Besides the
vocabularies above, it rejects:
- contradictions: a declared `scc` or `carry_in` that the primitive does not
have, `bitwise` on an arithmetic operation or the reverse;
- duplicates: the same `name`, the same `(family, opcode)` or the same
`variant` declared twice;
- XML disagreements: a family with no XML encoding, a form with no default XML
variant, a different opcode, an SCC input or output the XML does not show (or
that the declaration omits), an operand width other than `width`, a signed
declaration on unsigned XML formats or the reverse, an operand direction that
differs, and XML operands the operand rule does not cover;
- references: a spec citing an undeclared document, a bad section or page, or
no guide page at all;
- operand rules the decoder does not implement, or whose declaration differs
from the implemented one;
- wrong types: a float width, a boolean schema, an opcode or page outside
0-65535, or a reserved variant name such as `Self`.
CI runs `generate_semantics.py --check`, `scripts/audit/semantic_coverage.py
--check` and both Python test suites next to the existing
`generate_rdna2_meta.py --check`. Both scripts stop with a clear message on
Python older than 3.11.
## What the generator does not do
- **The XML gives identity and encodings only.** The snapshot confirms the
name, family, opcode, operand fields, widths, number formats and whether SCC
is read or written. It says nothing about the arithmetic. Behaviour comes from
the AMD guide, cited in `spec`, through the closed primitive table.
- **It does not invent behaviour.** A form whose operation, signedness or
operand rule is not already implemented is rejected. Adding a new operation
means hand-writing a primitive in `primitive.rs`, a variant in
`semantics.rs` and a row in the generator's vocabulary tables, reviewed like
any other code.
- **Undeclared forms stay unsupported.** The generated `from_word` returns
`None` for every opcode not in the registry, and the decoder reports
`UnsupportedOpcode`. Nothing falls back to a guess or a no-op.
- **It does not write tests or reference semantics.** The reference
interpreter (`crates/ref`) and the independent interpreter
(`tests/validation/independent_ref.rs`) never read the registry or the
generated code, and their known-answer tests are written by hand from the
guide. That independence is what lets them catch a wrong registry entry; keep
it when you add a form. Agreement with these references is agreement with a
reading of the public AMD guide, not with Xbox hardware.
## Commands
Run these from the repository root. `python3` must be 3.11 or newer.
```sh
# Check the registry only.
python3 crates/isa/generate_semantics.py validate
# Validate, then rewrite crates/isa/src/semantics_gen.rs.
python3 crates/isa/generate_semantics.py generate
# Validate and regenerate in memory; exit 1 if the committed file is stale. Never writes.
python3 crates/isa/generate_semantics.py --check
# Generator unit tests.
python3 -m unittest discover -s tests/semantics_generator
# The XML metadata tables the registry is cross-checked against are still current.
python3 crates/isa/generate_rdna2_meta.py --check
# Rust tests of the generated tables and the decoder that uses them.
cargo test --locked -p xenora-isa -p xenora-decoder
# Independent CPU validation.
cargo test --locked -p xenora-semantic-review
# Native GPU correctness on Apple silicon.
scripts/test-gpu.sh
```
The LLVM encoding corpus check needs an LLVM build with the AMDGPU target:
```sh
python3 crates/isa/tests/llvm/corpus.py --llvm-bin /path/to/llvm/bin --check
```
## Worked example: `s_addc_u32`
`s_addc_u32` adds two 32-bit sources plus SCC and writes the carry-out of
bit 31 to SCC (guide section 12.1, page 102; SCC rules in section 5.3, page 33).
Its registry entry is:
```toml
[[form]]
name = "S_ADDC_U32"
family = "SOP2"
opcode = 4
variant = "AddcU32"
operation = "add"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
```
How each field is checked:
1. The XML snapshot has a default `ENC_SOP2` variant named `S_ADDC_U32` with
opcode 4, so `name`, `family` and `opcode` agree.
2. That XML variant reads and writes SCC, which matches `carry_in = "scc"` and
an `scc` other than `unchanged`.
3. `add` / `unsigned` selects `add_carry_u32`, which requires
`scc = "carry_out"` and accepts a carry-in.
4. The XML `SDST`, `SSRC0` and `SSRC1` operands are 32-bit `FMT_NUM_U32`
fields, which matches `width = 32`, `unsigned` and the `sop2_sgpr` rule.
From this entry the generator emits, in `semantics_gen.rs`, the `AddcU32`
variant of `ScalarAluOp`, its `from_word` arm (`0x8200_0000`), the mnemonic
`s_addc_u32`, `reads_scc() == true`, an `evaluate` arm that calls
`primitive::add_carry_u32(src0, src1, carry_in)`, and a `FormSemantics` row.
To add a form the same way:
1. Confirm its behaviour in the AMD guide and note the section and page.
2. Check that an existing primitive and operand rule cover it. If not, the
form needs hand-written code first (see above).
3. Add a `[[form]]` entry and run `validate` until it reports no errors.
4. Run `generate` and commit the registry and `semantics_gen.rs` together.
5. Add known-answer tests to the reference and independent interpreters by
hand, then run every command in [Commands](#commands).
+96
View File
@@ -255,6 +255,102 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_andn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
representation = "`8A09FF08 FF00FF00`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_orn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
representation = "`8B0AC109`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_nand_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
representation = "`8C0B0808`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_nor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
representation = "`8D0C090B`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_xnor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
representation = "`8E0D080C`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshl_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
representation = "`8F0EA40D`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshr_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
representation = "`900FFF0E FFFFFFE1`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_ashr_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
representation = "`91109F0E`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
+13
View File
@@ -0,0 +1,13 @@
0000: t0 = load.u32 input[index]
0040: branch.uniform 0x004c taken=true
004c: t2 = const.u32 0xff0fffff
0050: t3 = const.u32 0x787ffff8
0054: t4 = xor.b32 t2, t3
0058: t5 = const.u32 0xffffffff
005c: t6 = xor.b32 t4, t5
0060: t7 = const.u32 0x00f00000
0064: t8 = xor.b32 t6, t7
0068: t9 = const.u32 0xf000ff00
006c: t10 = xor.b32 t8, t9
0070: t11 = xor.b32 t0, t10
0074: store.u32 output[index], t11
+19
View File
@@ -0,0 +1,19 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t2 = 0xff0fffffu;
uint t3 = 0x787ffff8u;
uint t4 = t2 ^ t3;
uint t5 = 0xffffffffu;
uint t6 = t4 ^ t5;
uint t7 = 0x00f00000u;
uint t8 = t6 ^ t7;
uint t9 = 0xf000ff00u;
uint t10 = t8 ^ t9;
uint t11 = t0 ^ t10;
output[index] = t11;
}
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors for the registry-declared logical and shift forms:
// ANDN2/ORN2 with a literal and an inline -1, NAND with aliased sources,
// NOR/XNOR chains, shift counts that use only S1[4:0] (36 -> 4, a literal
// 0xffffffe1 -> 1, 31), an arithmetic shift of a negative and a positive value,
// and an SCC branch on a zero shift result. SGPR results are moved into VGPRs.
// Expected: input ^ 0x887f00f8 (worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xf0f0ff00
s_andn2_b32 s9, s8, 0xff00ff00 // s9 = 0x00f00000, SCC = 1
s_orn2_b32 s10, s9, -1 // s10 = 0x00f00000, SCC = 1
s_nand_b32 s11, s8, s8 // s11 = 0x0f0f00ff, SCC = 1
s_nor_b32 s12, s11, s9 // s12 = 0xf000ff00, SCC = 1
s_xnor_b32 s13, s12, s8 // s13 = 0xff0fffff, SCC = 1
s_lshl_b32 s14, s13, 36 // s14 = 0xf0fffff0 (count 4), SCC = 1
s_lshr_b32 s15, s14, 0xffffffe1 // s15 = 0x787ffff8 (count 1), SCC = 1
s_ashr_i32 s16, s14, 31 // s16 = 0xffffffff, SCC = 1
s_ashr_i32 s17, s15, 31 // s17 = 0, SCC = 0
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s13
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v4, s16
v_xor_b32_e32 v2, v2, v4
v_mov_b32_e32 v5, s10
v_xor_b32_e32 v2, v2, v5
v_mov_b32_e32 v6, s12
v_xor_b32_e32 v2, v2, v6 // 0xff0fffff ^ 0x787ffff8 ^ 0xffffffff ^ 0x00f00000 ^ 0xf000ff00
v_xor_b32_e32 v2, v1, v2
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+80
View File
@@ -8,6 +8,15 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cc"
version = "1.11.3"
@@ -26,12 +35,51 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -75,12 +123,35 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "xenora-decoder"
version = "0.1.0"
@@ -94,6 +165,7 @@ version = "0.0.0"
dependencies = [
"libfuzzer-sys",
"xenora-decoder",
"xenora-loader",
"xenora-ref",
"xenora-shader",
]
@@ -102,6 +174,14 @@ dependencies = [
name = "xenora-isa"
version = "0.1.0"
[[package]]
name = "xenora-loader"
version = "0.1.0"
dependencies = [
"libc",
"sha2",
]
[[package]]
name = "xenora-ref"
version = "0.1.0"
+13
View File
@@ -11,11 +11,18 @@ cargo-fuzz = true
[dependencies]
libfuzzer-sys = "=0.4.13"
xenora-decoder = { path = "../crates/decoder" }
xenora-loader = { path = "../crates/loader" }
xenora-ref = { path = "../crates/ref" }
xenora-shader = { path = "../crates/shader" }
[workspace]
[[bin]]
name = "cpu_decode"
path = "fuzz_targets/cpu_decode.rs"
test = false
doc = false
[[bin]]
name = "instruction_stream"
path = "fuzz_targets/instruction_stream.rs"
@@ -28,6 +35,12 @@ path = "fuzz_targets/fixture.rs"
test = false
doc = false
[[bin]]
name = "pe_parse"
path = "fuzz_targets/pe_parse.rs"
test = false
doc = false
[[bin]]
name = "reference"
path = "fuzz_targets/reference.rs"
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![no_main]
use libfuzzer_sys::fuzz_target;
use std::collections::BTreeSet;
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
const MAX_CODE_BYTES: usize = 4096;
const CONFIG: ProbeConfig = ProbeConfig {
max_disasm_bytes: MAX_CODE_BYTES,
max_instructions: 2048,
max_worklist_entries: 1024,
};
const PE_OFFSET: usize = 0x40;
const COFF: usize = PE_OFFSET + 4;
const OPTIONAL: usize = COFF + 20;
const OPTIONAL_LEN: u16 = 0xf0;
const TEXT: usize = OPTIONAL + OPTIONAL_LEN as usize;
const HEADER_LEN: usize = 0x200;
const TEXT_RVA: u32 = 0x1000;
const SECTION_ALIGNMENT: u32 = 0x1000;
const HEADER: [u8; HEADER_LEN] = {
let mut header = [0; HEADER_LEN];
write_field(&mut header, 0, b"MZ");
write_field(&mut header, 0x3c, &(PE_OFFSET as u32).to_le_bytes());
write_field(&mut header, PE_OFFSET, b"PE\0\0");
write_field(&mut header, COFF, &0x8664u16.to_le_bytes()); // Machine
write_field(&mut header, COFF + 2, &1u16.to_le_bytes()); // NumberOfSections
write_field(&mut header, COFF + 16, &OPTIONAL_LEN.to_le_bytes());
write_field(&mut header, OPTIONAL, &0x20bu16.to_le_bytes()); // Magic
write_field(&mut header, OPTIONAL + 16, &TEXT_RVA.to_le_bytes()); // AddressOfEntryPoint
write_field(&mut header, OPTIONAL + 20, &TEXT_RVA.to_le_bytes()); // BaseOfCode
write_field(&mut header, OPTIONAL + 24, &0x1_4000_0000u64.to_le_bytes()); // ImageBase
write_field(&mut header, OPTIONAL + 32, &SECTION_ALIGNMENT.to_le_bytes());
write_field(&mut header, OPTIONAL + 36, &0x200u32.to_le_bytes()); // FileAlignment
write_field(
&mut header,
OPTIONAL + 60,
&(HEADER_LEN as u32).to_le_bytes(),
); // SizeOfHeaders
write_field(&mut header, OPTIONAL + 108, &16u32.to_le_bytes()); // NumberOfRvaAndSizes
write_field(&mut header, TEXT, b".text");
write_field(&mut header, TEXT + 12, &TEXT_RVA.to_le_bytes()); // VirtualAddress
write_field(&mut header, TEXT + 20, &(HEADER_LEN as u32).to_le_bytes()); // PointerToRawData
write_field(&mut header, TEXT + 36, &0x6000_0020u32.to_le_bytes()); // CODE | EXECUTE | READ
header
};
const fn write_field(header: &mut [u8], offset: usize, bytes: &[u8]) {
let (_, tail) = header.split_at_mut(offset);
let (field, _) = tail.split_at_mut(bytes.len());
field.copy_from_slice(bytes);
}
fn build_image(payload: &[u8]) -> Vec<u8> {
let mut header = HEADER;
let code_size = payload.len() as u32;
let image_size = TEXT_RVA + code_size.next_multiple_of(SECTION_ALIGNMENT);
write_field(&mut header, OPTIONAL + 4, &code_size.to_le_bytes()); // SizeOfCode
write_field(&mut header, OPTIONAL + 56, &image_size.to_le_bytes()); // SizeOfImage
write_field(&mut header, TEXT + 8, &code_size.to_le_bytes()); // VirtualSize
write_field(&mut header, TEXT + 16, &code_size.to_le_bytes()); // SizeOfRawData
// The probe decodes up to EOF, so leave the payload unpadded.
let mut image = Vec::with_capacity(HEADER_LEN + payload.len());
image.extend_from_slice(&header);
image.extend_from_slice(payload);
image
}
fuzz_target!(init: {
let image = build_image(&[0x90, 0xc3]);
let report = probe_pe_bytes(&image, &CONFIG).expect("startup PE probe succeeds");
let records = report.instruction_records;
assert!(records.len() == 2, "startup decodes two instructions");
assert!(records[0].rva == TEXT_RVA, "startup decodes entry RVA");
assert!(records[1].rva == TEXT_RVA + 1, "startup decodes next RVA");
}, |data: &[u8]| {
let payload = &data[..data.len().min(MAX_CODE_BYTES)];
let image = build_image(payload);
let a = probe_pe_bytes(&image, &CONFIG);
let b = probe_pe_bytes(&image, &CONFIG);
assert!(format!("{a:?}") == format!("{b:?}"), "probe is deterministic");
if let Ok(report) = a {
let records = report.instruction_records;
assert!(records.len() <= CONFIG.max_instructions, "instruction budget");
let code_range = TEXT_RVA..TEXT_RVA + payload.len() as u32;
let mut rvas = BTreeSet::new();
for record in records {
let len = record.bytes.len();
assert!((1..=15).contains(&len), "x86 instruction length");
assert!(code_range.contains(&record.rva), "RVA within payload");
assert!(rvas.insert(record.rva), "RVA is unique");
let start = (record.rva - TEXT_RVA) as usize;
let end = start + len;
assert!(end <= payload.len(), "instruction ends within payload");
assert!(record.bytes == payload[start..end], "instruction bytes match payload");
}
}
});
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![no_main]
use libfuzzer_sys::fuzz_target;
const MAX_MAPPED_BYTES: u64 = 64 * 1024 * 1024;
fuzz_target!(|data: &[u8]| {
let Ok(pe) = xenora_loader::ParsedPe::parse(data) else {
return;
};
let _ = pe.rva_to_file_offset(pe.entry_point_rva);
let mut mapped_bytes = 0u64;
for section in &pe.sections {
let _ = pe.rva_to_file_offset(section.virtual_address);
// The loader allocates each section separately, independent of size_of_image.
let section_size = u64::from(section.virtual_size.max(section.raw_data_size));
mapped_bytes = mapped_bytes.saturating_add(section_size);
}
if mapped_bytes <= MAX_MAPPED_BYTES && u64::from(pe.size_of_image) <= MAX_MAPPED_BYTES {
let _ = pe.load_into_memory(data);
}
});
+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; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic; 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"
+326
View File
@@ -0,0 +1,326 @@
"""Generate the gfx1030 semantic coverage report from the checked-in inventories."""
import argparse
from collections import Counter, defaultdict
import difflib
import json
from pathlib import Path
import re
import runpy
import sys
try:
import tomllib
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
sys.exit("semantic_coverage.py needs Python 3.11 or newer (tomllib)")
ROOT = Path(__file__).resolve().parents[2]
SNAPSHOT = Path("crates/isa/data/rdna2.jsonl")
REGISTRY = Path("crates/isa/semantics/rdna2.toml")
DECODER = Path("crates/decoder/src/lib.rs")
GENERATED = Path("crates/isa/src/semantics_gen.rs")
STATUS = Path("docs/status.toml")
REPORT = Path("docs/shaders/semantic-coverage.md")
DECODER_HEADER = re.compile(
r'const HANDWRITTEN_FORMS: \[\(&str, EncodingFamily\); (\d+)\] = \['
)
# The decoder's full list is its hand-written forms plus every registry form.
DECODER_TOTAL = re.compile(
r'pub const SEMANTIC_FORMS: \[\(&str, EncodingFamily\); '
r'HANDWRITTEN_FORMS\.len\(\) \+ FORM_IDS\.len\(\)\] ='
)
DECODER_ENTRY = re.compile(r'\("([A-Z0-9_]+)", EncodingFamily::([A-Za-z0-9]+)\),')
STATUS_ALIASES = {
"s_waitcnt vmcnt(0)": ("SOPP", "S_WAITCNT"),
"s_waitcnt_vscnt null, 0": ("SOPK", "S_WAITCNT_VSCNT"),
}
COLUMNS = (
"Identified", "Encoding-validated", "Declared", "Decoder-supported",
"IR", "MSL", "Reference-verified", "Metal-verified", "Unsupported operand variants",
)
def load_snapshot(root):
# Reuse the metadata generator's base-form rules, including literal-only
# forms and the relative moves whose base condition is not "default".
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
encodings = metadata["BASE_ENCODINGS"] | metadata["EXTENSIONS"]
snapshot = (root / SNAPSHOT).read_text(encoding="utf-8")
variants = []
for number, line in enumerate(snapshot.splitlines(), 1):
location = f"{SNAPSHOT}:{number}"
try:
row = json.loads(line)
except ValueError as error:
raise ValueError(f"{location}: {error}") from error
if not isinstance(row, dict):
raise ValueError(f"{location}: expected an object")
kind = row.get("kind")
if kind == "variant":
if (
not isinstance(row.get("encoding"), str) or row["encoding"] not in encodings
or any(not isinstance(row.get(key), str) or not row[key]
for key in ("instruction", "condition"))
or type(row.get("opcode")) is not int
):
raise ValueError(f"{location}: invalid variant {row!r}")
variants.append((location, row))
elif kind not in ("source", "encoding", "operand_type", "data_format"):
raise ValueError(f"{location}: unknown row kind {kind!r}")
try:
_, _, forms = metadata["forms_from_snapshot"](snapshot)
except (SystemExit, ValueError, KeyError, IndexError, TypeError) as error:
raise ValueError(f"{SNAPSHOT}: {error}") from error
identified = {(form["encoding"].upper(), form["name"]): form["opcode"] for form in forms}
if not identified or len(identified) != len(forms):
raise ValueError(f"{SNAPSHOT}: expected unique, nonempty base forms")
for location, row in variants:
encoding = row["encoding"]
base, _ = metadata["EXTENSIONS"].get(encoding, (encoding, None))
key = (metadata["BASE_ENCODINGS"][base].upper(), row["instruction"])
if key not in identified:
raise ValueError(f"{location}: cannot map {encoding} variant to base form {key}")
return identified
def parse_decoder(source):
lines = source.splitlines()
if sum(bool(DECODER_TOTAL.fullmatch(line.strip())) for line in lines) != 1:
raise ValueError(f"{DECODER}: expected SEMANTIC_FORMS = hand-written + registry forms")
starts = [i for i, line in enumerate(lines)
if re.match(r"\s*const HANDWRITTEN_FORMS\b", line)]
if len(starts) != 1:
raise ValueError(f"{DECODER}: expected one HANDWRITTEN_FORMS declaration")
start = starts[0]
header = DECODER_HEADER.fullmatch(lines[start].strip())
if not header:
raise ValueError(f"{DECODER}:{start + 1}: unrecognized SEMANTIC_FORMS declaration")
forms = set()
for number, line in enumerate(lines[start + 1:], start + 2):
line = line.partition("//")[0].strip()
if line == "];":
if len(forms) != int(header[1]):
raise ValueError(f"{DECODER}:{number}: SEMANTIC_FORMS length mismatch")
return forms
if not line:
continue
entry = DECODER_ENTRY.fullmatch(line)
if not entry:
raise ValueError(f"{DECODER}:{number}: unrecognized SEMANTIC_FORMS entry {line!r}")
key = (entry[2].upper(), entry[1])
if key in forms:
raise ValueError(f"{DECODER}:{number}: duplicate form {key}")
forms.add(key)
raise ValueError(f"{DECODER}: unterminated SEMANTIC_FORMS")
GENERATED_HEADER = re.compile(r"pub const FORM_IDS: \[\(&str, EncodingFamily\); (\d+)\] = \[")
def parse_generated(source):
"""Registry forms compiled into the decoder, read from the generated FORM_IDS table."""
lines = source.splitlines()
starts = [i for i, line in enumerate(lines) if GENERATED_HEADER.fullmatch(line.strip())]
if len(starts) != 1:
raise ValueError(f"{GENERATED}: expected one FORM_IDS declaration")
forms = set()
rows = 0
for number, line in enumerate(lines[starts[0] + 1:], starts[0] + 2):
line = line.strip()
if line == "];":
if rows != len(forms):
raise ValueError(f"{GENERATED}:{number}: duplicate FORM_IDS entry")
if len(forms) != int(GENERATED_HEADER.fullmatch(lines[starts[0]].strip())[1]):
raise ValueError(f"{GENERATED}:{number}: FORM_IDS length mismatch")
return forms
entry = DECODER_ENTRY.fullmatch(line)
if not entry:
raise ValueError(f"{GENERATED}:{number}: unrecognized FORM_IDS entry {line!r}")
forms.add((entry[2].upper(), entry[1]))
rows += 1
raise ValueError(f"{GENERATED}: unterminated FORM_IDS")
def read_declarations(registry, identified):
if type(registry.get("schema")) is not int or registry["schema"] != 1:
raise ValueError(f"{REGISTRY}: expected schema 1")
families = {family for family, _ in identified}
rules = {}
for name, rule in registry["operand_rules"].items():
location = f"{REGISTRY}: operand_rules.{name}"
family = rule["family"]
unsupported = rule["unsupported"]
if family not in families:
raise ValueError(f"{location}: unknown family {family!r}")
if not isinstance(unsupported, list) or any(
not isinstance(variant, str) or not re.fullmatch(r"[a-zA-Z0-9_]+", variant)
for variant in unsupported
):
raise ValueError(f"{location}: invalid unsupported list")
rules[name] = (family, set(unsupported))
declared = set()
for form in registry["form"]:
key = (form["family"], form["name"])
if key not in identified:
raise ValueError(f"{REGISTRY}: unknown form {key}")
if type(form["opcode"]) is not int or form["opcode"] != identified[key]:
raise ValueError(f"{REGISTRY}: opcode mismatch for {key}")
if key in declared:
raise ValueError(f"{REGISTRY}: duplicate form {key}")
rule = form["operands"]
if rule not in rules or rules[rule][0] != key[0]:
raise ValueError(f"{REGISTRY}: invalid operand rule {rule!r} for {key}")
declared.add(key)
return declared, rules
def status_form(row, identified):
name = row["form"]
if not isinstance(name, str) or not isinstance(row["encoding"], str):
raise ValueError(f"{STATUS}: invalid form or encoding in {row!r}")
families = {family for family, _ in identified}
family_hint = row["encoding"].split(",", 1)[0].strip().upper()
if name in STATUS_ALIASES:
candidates = [STATUS_ALIASES[name]]
else:
mnemonic = name.upper()
eligible = families
if mnemonic.endswith("_E32"):
mnemonic = mnemonic.removesuffix("_E32")
eligible = families & {"VOP1", "VOP2", "VOPC"}
elif mnemonic.endswith("_E64"):
mnemonic = mnemonic.removesuffix("_E64")
eligible = families & {"VOP3", "VOP3SDST"}
candidates = sorted((family, mnemonic) for family in eligible
if (family, mnemonic) in identified)
if family_hint in families:
candidates = [key for key in candidates if key[0] == family_hint]
if len(candidates) != 1 or candidates[0] not in identified:
raise ValueError(f"{STATUS}: cannot uniquely map {name!r} ({candidates})")
return candidates[0]
def collect_coverage(identified, registry, decoder, status):
declared, rules = read_declarations(registry, identified)
unknown = decoder.difference(identified)
if unknown:
raise ValueError(f"{DECODER}: unknown forms {sorted(unknown)}")
encoded, lowered, reference, metal = set(), set(), set(), set()
seen = set()
for row in status["instruction"]:
key = status_form(row, identified)
if key in seen:
raise ValueError(f"{STATUS}: duplicate evidence for {key}")
seen.add(key)
for field in ("llvm", "lowering", "reference", "cpu", "gpu"):
if field in row and not isinstance(row[field], str):
raise ValueError(f"{STATUS}: {key} has invalid {field} evidence")
if row.get("llvm") == "three-way passed":
encoded.add(key)
lowering = row.get("lowering", "").strip().lower()
# This status schema uses one field for the IR-to-MSL path. A
# compile-time resolution also implements that path for the form.
if (
lowering.startswith(("msl ", "resolved ", "verified ", "constant or ", "per-thread "))
and not re.search(r"\b(?:stub|placeholder|planned|unsupported|pending|todo|unimplemented|not implemented|not yet)\b", lowering)
):
lowered.add(key)
elif lowering:
raise ValueError(f"{STATUS}: {key} has unrecognized lowering {row['lowering']!r}")
# Verified evidence also requires the status row to say the form decodes.
decodes = row.get("decoded") is True
if decodes and row.get("reference") == "implemented" and row.get("cpu") == "fixture verified":
reference.add(key)
if decodes and row.get("gpu") in {"fixture verified", "fixture verified on Apple M5"}:
metal.add(key)
counts = [Counter(family for family, _ in forms) for forms in (
identified, encoded, declared, decoder, lowered, lowered, reference, metal,
)]
unsupported = defaultdict(set)
for family, variants in rules.values():
unsupported[family].update(variants)
return {
family: (*[count[family] for count in counts], len(unsupported[family]))
for family in sorted(counts[0])
}, rules
def render_report(counts, rules):
lines = [
"# gfx1030 semantic coverage",
"",
"<!-- Generated by scripts/audit/semantic_coverage.py. -->",
"",
"Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms",
"come from the semantic registry. Decoder support is the decoder's hand-written",
"list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.",
"",
"The status inventory records LLVM three-way encoding checks, intermediate",
"representation (IR) and Metal Shading Language (MSL) lowering, and fixture",
"verification. IR and MSL share the inventory's lowering field. Reference",
"verification requires an implemented reference and verified CPU fixture.",
"Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending",
"acceptance remain outside the verified count. All results concern synthetic fixtures.",
"",
"| Family | " + " | ".join(COLUMNS) + " |",
"| --- |" + " ---: |" * len(COLUMNS),
]
for family, values in counts.items():
lines.append(f"| {family} | " + " | ".join(map(str, values)) + " |")
lines.append("| **Total** | " + " | ".join(map(str, map(sum, zip(*counts.values())))) + " |")
lines.extend([
"",
"## Unsupported operand variants",
"",
"The table counts distinct variant names per family across registry operand rules.",
"",
"| Family | Operand rule | Unsupported variants |",
"| --- | --- | --- |",
])
for family, name, variants in sorted((family, name, variants)
for name, (family, variants) in rules.items()):
names = ", ".join(f"`{variant}`" for variant in sorted(variants))
lines.append(f"| {family} | `{name}` | {names or 'None listed'} |")
return "\n".join(lines) + "\n"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="compare without writing")
args = parser.parse_args()
try:
identified = load_snapshot(ROOT)
registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8"))
decoder = parse_decoder((ROOT / DECODER).read_text(encoding="utf-8")) | parse_generated(
(ROOT / GENERATED).read_text(encoding="utf-8"))
status = tomllib.loads((ROOT / STATUS).read_text(encoding="utf-8"))
report = render_report(*collect_coverage(identified, registry, decoder, status)).encode()
path = ROOT / REPORT
if not args.check:
path.write_bytes(report)
print(f"Wrote {REPORT}")
return 0
committed = path.read_bytes() if path.exists() else b""
if committed == report:
print(f"{REPORT} is up to date")
return 0
before = committed.decode("utf-8", errors="replace").splitlines(keepends=True)
after = report.decode().splitlines(keepends=True)
diff = list(difflib.unified_diff(before, after, fromfile=str(REPORT),
tofile="regenerated", n=0))
print(f"{REPORT} differs from the regenerated report", file=sys.stderr)
for line in diff[:12]:
print(line.rstrip("\n"), file=sys.stderr)
if len(diff) > 12:
print("…", file=sys.stderr)
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
print(f"semantic_coverage: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
fail() { echo "build-app: $*" >&2; exit 1; }
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
target=aarch64-apple-darwin
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
swift build --package-path app -c release --arch arm64 \
-Xlinker -L -Xlinker "$root/target/$target/release"
bundle="$root/build/Xenora.app"
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key><string>Xenora</string>
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
<key>CFBundleName</key><string>Xenora</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
# Ad-hoc signature for local development only. No entitlements are requested:
# this build executes no guest code, so it needs no JIT entitlement.
codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/Xenora"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
"$binary" --smoke
echo "build-app: built $bundle"
@@ -0,0 +1,117 @@
import unittest
from audit import semantic_coverage as coverage
class SemanticCoverageTests(unittest.TestCase):
def setUp(self):
self.identified = {("SOP2", "S_ADD_U32"): 0, ("SOP2", "S_SUB_U32"): 1}
self.registry = {
"schema": 1,
"form": [{
"family": "SOP2", "name": "S_ADD_U32", "opcode": 0,
"operands": "scalar", "verify": ["metal", "reference", "llvm_encoding"],
}],
"operand_rules": {
"scalar": {"family": "SOP2", "unsupported": ["two_literals"]},
},
}
def counts(self, *rows):
counts, _ = coverage.collect_coverage(
self.identified, self.registry, {("SOP2", "S_SUB_U32")},
{"instruction": list(rows)},
)
return dict(zip(coverage.COLUMNS, counts["SOP2"]))
def test_declared_without_metal_evidence_is_not_metal_verified(self):
counts = self.counts()
self.assertEqual(counts["Declared"], 1)
self.assertEqual(counts["Metal-verified"], 0)
self.assertEqual(counts["Reference-verified"], 0)
self.assertEqual(counts["Encoding-validated"], 0)
def test_status_evidence_counts_for_handwritten_form(self):
counts = self.counts({
"form": "s_sub_u32", "encoding": "SOP2, scalar operands",
"llvm": "three-way passed", "lowering": "resolved scalar state and SCC",
"reference": "implemented", "cpu": "fixture verified",
"gpu": "fixture verified on Apple M5", "decoded": True,
})
self.assertEqual(counts, {
"Identified": 2, "Encoding-validated": 1, "Declared": 1,
"Decoder-supported": 1, "IR": 1, "MSL": 1, "Reference-verified": 1,
"Metal-verified": 1, "Unsupported operand variants": 1,
})
def test_pending_readback_does_not_count(self):
counts = self.counts({
"form": "s_add_u32", "encoding": "SOP2", "lowering": "resolved scalar state and SCC",
"reference": "implemented", "cpu": "local known-answer test passed",
"gpu": "local Apple M5 readback passed; acceptance pending",
})
self.assertEqual(counts["Metal-verified"], 0)
self.assertEqual(counts["Reference-verified"], 0)
self.assertEqual(counts["IR"], 1)
def test_verified_evidence_needs_a_decoding_row(self):
counts = self.counts({
"form": "s_sub_u32", "encoding": "SOP2", "reference": "implemented",
"cpu": "fixture verified", "gpu": "fixture verified", "decoded": False,
})
self.assertEqual(counts["Reference-verified"], 0)
self.assertEqual(counts["Metal-verified"], 0)
def test_declared_but_not_compiled_is_not_decoder_supported(self):
# S_ADD_U32 is declared in the registry but absent from the compiled tables.
self.assertEqual(self.counts()["Decoder-supported"], 1)
def test_generated_table_parser(self):
source = (
"pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n"
' ("S_ADD_U32", EncodingFamily::Sop2),\n];'
)
self.assertEqual(coverage.parse_generated(source), {("SOP2", "S_ADD_U32")})
with self.assertRaisesRegex(ValueError, "length mismatch"):
coverage.parse_generated(source.replace("; 1]", "; 2]"))
duplicated = source.replace("; 1]", "; 2]").replace(
' ("S_ADD_U32", EncodingFamily::Sop2),\n',
' ("S_ADD_U32", EncodingFamily::Sop2),\n' * 2,
)
with self.assertRaisesRegex(ValueError, "duplicate FORM_IDS entry"):
coverage.parse_generated(duplicated)
def test_stub_or_unrecognized_lowering_fails(self):
for lowering in ("stub", "MSL placeholder add", "MSL unimplemented", "something new"):
with self.assertRaisesRegex(ValueError, "unrecognized lowering"):
self.counts({"form": "s_add_u32", "encoding": "SOP2", "lowering": lowering})
def test_status_suffix_disambiguates_encoding(self):
forms = {("VOP2", "V_AND_B32"): 1, ("VOP3", "V_AND_B32"): 2}
self.assertEqual(coverage.status_form(
{"form": "v_and_b32_e32", "encoding": "Two VGPR sources"}, forms,
), ("VOP2", "V_AND_B32"))
with self.assertRaisesRegex(ValueError, "cannot uniquely map"):
coverage.status_form(
{"form": "v_and_b32", "encoding": "Two VGPR sources"}, forms,
)
def test_unknown_status_form_fails(self):
with self.assertRaisesRegex(ValueError, "cannot uniquely map.*s_typo"):
self.counts({"form": "s_typo", "encoding": "SOP2"})
def test_decoder_parser_rejects_unrecognized_entry(self):
header = (
"pub const SEMANTIC_FORMS: [(&str, EncodingFamily); "
"HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =\n"
"const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 1] = ["
)
self.assertEqual(coverage.parse_decoder(
f'{header}\n ("S_ADD_U32", EncodingFamily::Sop2),\n];',
), {("SOP2", "S_ADD_U32")})
with self.assertRaisesRegex(ValueError, "unrecognized SEMANTIC_FORMS entry"):
coverage.parse_decoder(f"{header}\n unknown!(),\n];")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,556 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Unit tests for crates/isa/generate_semantics.py.
Each rejection rule is fed a small in-memory registry that breaks exactly that
rule, checked against a tiny hand-written XML snapshot. The real registry and
snapshot are only read, never edited. Run from the repository root:
python3 -m unittest discover -s tests/semantics_generator
"""
import copy
import importlib.util
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "crates/isa/generate_semantics.py"
_spec = importlib.util.spec_from_file_location("generate_semantics", SCRIPT)
gen = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(gen)
SHA = "0" * 64
# Minimal stand-in for crates/isa/data/rdna2.jsonl: the SOP2 encoding and the
# default variants of the four forms the fixture declares (values copied from
# the AMD XML snapshot).
U32 = "FMT_NUM_U32"
I32 = "FMT_NUM_I32"
def _operands(data_format, scc_in=False, src1_format=None):
rows = [
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["SSRC1", src1_format or data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
]
if scc_in:
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
return rows
def snapshot():
sop2_base = 0x80000000
encoding = {
"name": "ENC_SOP2",
"bits": 32,
"fields": [
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["SDST", [[16, 7]]],
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
],
"identifier_mask": 0xFF800000,
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14, 34)],
}
variants = {}
for name, opcode, operands in (
("S_ADD_U32", 0, _operands(U32)),
("S_ADD_I32", 2, _operands(I32)),
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
("S_AND_B32", 14, _operands(U32)),
# The XML gives S_ASHR_I32 a signed S0 and an unsigned shift count.
("S_ASHR_I32", 34, _operands(I32, src1_format=U32)),
):
variants[(name, "ENC_SOP2")] = {
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
}
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
return {
"name": name, "family": "SOP2", "opcode": opcode, "variant": variant,
"operation": operation, "signedness": signedness, "carry_in": carry_in,
"width": 32, "scc": scc, "vcc": "unchanged", "exec": "unchanged", "wave": "any",
"operands": "sop2_sgpr",
"spec": [{"document": "guide", "section": "12.1", "page": 101}],
"verify": ["reference", "independent"],
}
def registry():
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
return {
"schema": 1,
"architecture": "gfx1030",
"source_sha256": SHA,
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
"operand_rules": {"sop2_sgpr": rule},
"form": [
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
dict(
_form("S_ASHR_I32", 34, "AshrI32", "ashr", "signed", "nonzero"),
shift_count_bits=5,
),
],
}
def form(reg, name):
return next(item for item in reg["form"] if item["name"] == name)
class Validate(unittest.TestCase):
def errors(self, reg, snap=None):
return gen.validate(reg, snap if snap is not None else snapshot())
def rejects(self, reg, fragment, snap=None):
errors = self.errors(reg, snap)
self.assertTrue(
any(fragment in error for error in errors),
f"expected an error containing {fragment!r}, got {errors}",
)
# ---- acceptance ----
def test_accepts_the_fixture(self):
self.assertEqual(self.errors(registry()), [])
def test_accepts_the_real_registry(self):
self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), [])
# ---- top level ----
def test_rejects_wrong_schema(self):
reg = registry()
reg["schema"] = 2
self.rejects(reg, "schema 2 is not 1")
def test_rejects_source_sha256_mismatch(self):
reg = registry()
reg["source_sha256"] = "f" * 64
self.rejects(reg, "source_sha256 does not match")
def test_rejects_unknown_top_level_key(self):
reg = registry()
reg["notes"] = "x"
self.rejects(reg, "unknown top-level keys ['notes']")
def test_rejects_empty_registry(self):
reg = registry()
reg["form"] = []
self.rejects(reg, "declares no forms")
# ---- incomplete or unknown fields ----
def test_rejects_missing_required_field(self):
reg = registry()
del form(reg, "S_ADD_U32")["scc"]
self.rejects(reg, "S_ADD_U32: incomplete, missing ['scc']")
def test_rejects_unknown_form_key(self):
reg = registry()
form(reg, "S_ADD_U32")["expression"] = "a + b"
self.rejects(reg, "S_ADD_U32: unknown keys ['expression']")
# ---- closed vocabularies ----
def test_rejects_unknown_operation(self):
reg = registry()
form(reg, "S_ADD_U32")["operation"] = "mul"
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
def test_rejects_unknown_scc_effect(self):
reg = registry()
form(reg, "S_ADD_U32")["scc"] = "overflow"
self.rejects(reg, "S_ADD_U32: unknown scc 'overflow'")
def test_rejects_unknown_mask_effect(self):
reg = registry()
form(reg, "S_ADD_U32")["vcc"] = "written"
self.rejects(reg, "S_ADD_U32: unknown vcc 'written'")
def test_rejects_unsupported_width(self):
reg = registry()
form(reg, "S_ADD_U32")["width"] = 64
self.rejects(reg, "S_ADD_U32: width 64 is not supported")
def test_rejects_unknown_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = ["reference", "hardware"]
self.rejects(reg, "S_ADD_U32: unknown verification requirement")
def test_rejects_empty_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = []
self.rejects(reg, "S_ADD_U32: no verification requirement")
# ---- contradictions ----
def test_rejects_bitwise_operation_declared_signed(self):
reg = registry()
form(reg, "S_AND_B32")["signedness"] = "signed"
self.rejects(reg, "S_AND_B32: signedness signed contradicts operation and")
def test_rejects_carry_in_on_logical_operation(self):
reg = registry()
form(reg, "S_AND_B32")["carry_in"] = "scc"
self.rejects(reg, "S_AND_B32: carry_in scc contradicts and/bitwise")
def test_rejects_carry_out_on_signed_form(self):
reg = registry()
form(reg, "S_ADD_I32")["scc"] = "carry_out"
self.rejects(reg, "S_ADD_I32: scc carry_out contradicts add/signed")
def test_rejects_scc_unchanged_on_a_form_that_writes_it(self):
# Declared as preserving SCC while the primitive and the XML both write it.
reg = registry()
form(reg, "S_ADD_U32")["scc"] = "unchanged"
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts add/unsigned")
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts the XML SCC output")
def test_rejects_carry_in_the_xml_does_not_read(self):
reg = registry()
form(reg, "S_ADD_U32")["carry_in"] = "scc"
self.rejects(reg, "S_ADD_U32: carry_in scc contradicts the XML SCC input")
def test_rejects_signedness_contradicting_xml_format(self):
reg = registry()
f = form(reg, "S_ADD_I32")
f["signedness"], f["scc"] = "unsigned", "carry_out"
self.rejects(reg, "S_ADD_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
# ---- identity against the XML snapshot ----
def test_rejects_opcode_mismatch(self):
reg = registry()
form(reg, "S_ADD_U32")["opcode"] = 1
self.rejects(reg, "S_ADD_U32: opcode 1 disagrees with the XML opcode 0")
def test_rejects_family_mismatch(self):
reg = registry()
form(reg, "S_ADD_U32")["family"] = "SOPC"
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
def test_rejects_form_absent_from_the_xml(self):
reg = registry()
reg["form"].append(_form("S_MUL_I32", 38, "MulI32", "add", "signed", "signed_overflow"))
self.rejects(reg, "S_MUL_I32: no default ENC_SOP2 variant in the XML snapshot")
# ---- duplicates ----
def test_rejects_duplicate_name(self):
reg = registry()
reg["form"].append(copy.deepcopy(form(reg, "S_ADD_U32")))
self.rejects(reg, "S_ADD_U32: duplicate name S_ADD_U32")
def test_rejects_same_encoding_claimed_twice(self):
reg = registry()
twin = copy.deepcopy(form(reg, "S_ADD_U32"))
twin["name"], twin["variant"] = "S_ADD_U32_COPY", "AddU32Copy"
reg["form"].append(twin)
self.rejects(reg, "S_ADD_U32_COPY: duplicate opcode ('SOP2', 0)")
def test_rejects_duplicate_variant(self):
reg = registry()
form(reg, "S_ADD_I32")["variant"] = "AddU32"
self.rejects(reg, "S_ADD_I32: duplicate variant AddU32")
# ---- references ----
def test_rejects_missing_guide_reference(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"] = [{"document": "xml", "section": "1", "page": 0}]
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
def test_rejects_undeclared_document(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"].append({"document": "blog", "section": "1", "page": 1})
self.rejects(reg, "S_ADD_U32: spec cites undeclared document 'blog'")
# ---- operand rules ----
def test_rejects_unknown_operand_rule_on_a_form(self):
reg = registry()
form(reg, "S_ADD_U32")["operands"] = "vop2_vgpr"
self.rejects(reg, "S_ADD_U32: unknown operand rule 'vop2_vgpr'")
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
reg = registry()
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
def test_rejects_a_shift_without_a_count_width(self):
reg = registry()
del reg["form"][-1]["shift_count_bits"]
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got None")
def test_rejects_a_wrong_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = 6
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got 6")
def test_rejects_a_count_width_on_a_non_shift(self):
reg = registry()
reg["form"][0]["shift_count_bits"] = 5
self.rejects(reg, "S_ADD_U32: shift_count_bits on a non-shift operation")
def test_rejects_a_signed_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(I32)
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_I32", snap)
def test_rejects_a_float_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(
I32, src1_format="FMT_NUM_F32"
)
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_F32", snap)
def test_rejects_a_float_source_format(self):
snap = snapshot()
snap["variants"][("S_AND_B32", "ENC_SOP2")]["operands"] = _operands("FMT_NUM_F32")
self.rejects(registry(), "S_AND_B32: signedness bitwise contradicts XML format FMT_NUM_F32", snap)
def test_rejects_a_negative_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = -1
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got -1")
def test_rejects_an_unsigned_arithmetic_shift(self):
reg = registry()
reg["form"][-1]["signedness"] = "unsigned"
self.rejects(reg, "S_ASHR_I32: no primitive implements ashr/unsigned")
def test_renders_the_declared_count_mask(self):
self.assertIn(
"Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),",
gen.render(registry(), snapshot()),
)
def test_rejects_an_incomplete_unsupported_list(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
self.rejects(
reg, "operand rule sop2_sgpr: unsupported combos differ from those the decoder rejects"
)
def test_rejects_a_citation_to_another_file(self):
reg = registry()
reg["documents"]["guide"]["file"] = "missing.pdf"
self.rejects(reg, "document guide: differs from the pinned public document")
def test_rejects_an_unenforced_wave_restriction(self):
reg = registry()
reg["form"][0]["wave"] = "wave32"
self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet")
def test_rejects_a_reserved_variant(self):
reg = registry()
reg["form"][0]["variant"] = "Self"
self.rejects(reg, "S_ADD_U32: variant 'Self' is reserved")
def test_rejects_a_boolean_schema(self):
reg = registry()
reg["schema"] = True
self.rejects(reg, "schema True is not 1")
def test_rejects_unknown_unsupported_combo(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_lds")
self.rejects(reg, "operand rule sop2_sgpr: unknown unsupported combos ['dst_lds']")
def test_rejects_duplicate_unsupported_combo(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_vcc")
self.rejects(reg, "operand rule sop2_sgpr: duplicate unsupported combos")
# ---- remaining vocabulary, identity and reference rules ----
def test_rejects_wrong_architecture(self):
reg = registry()
reg["architecture"] = "gfx1100"
self.rejects(reg, "architecture 'gfx1100' is not gfx1030")
def test_rejects_unknown_document(self):
reg = registry()
reg["documents"]["blog"] = {"title": "blog"}
self.rejects(reg, "unknown document blog")
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
for key, value in (
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
):
with self.subTest(key=key):
reg = registry()
form(reg, "S_ADD_U32")[key] = value
self.rejects(reg, f"S_ADD_U32: unknown {key} {value!r}")
def test_rejects_invalid_name_variant_and_opcode(self):
for key, value, fragment in (
("name", "s_add_u32", "s_add_u32: invalid name"),
("variant", "add_u32", "S_ADD_U32: invalid variant 'add_u32'"),
("opcode", -1, "S_ADD_U32: invalid opcode"),
("opcode", True, "S_ADD_U32: invalid opcode"),
):
with self.subTest(key=key, value=value):
reg = registry()
form(reg, "S_ADD_U32")[key] = value
self.rejects(reg, fragment)
def test_rejects_declaration_no_primitive_implements(self):
reg = registry()
form(reg, "S_AND_B32")["operation"] = "sub"
self.rejects(reg, "S_AND_B32: no primitive implements sub/bitwise")
def test_rejects_duplicate_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = ["reference", "reference"]
self.rejects(reg, "S_ADD_U32: duplicate verification requirement")
def test_rejects_malformed_spec_references(self):
for ref, fragment in (
({"document": "guide", "section": "12.1"}, "spec reference needs exactly document, section, page"),
({"document": "guide", "section": "12.x", "page": 101}, "invalid spec section '12.x'"),
({"document": "guide", "section": "12.1", "page": -1}, "invalid spec page"),
):
with self.subTest(ref=ref):
reg = registry()
form(reg, "S_ADD_U32")["spec"].append(ref)
self.rejects(reg, f"S_ADD_U32: {fragment}")
def test_rejects_guide_reference_without_a_page(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"] = [{"document": "guide", "section": "12.1", "page": 0}]
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
def test_rejects_opcode_outside_the_encoding_identifiers(self):
snap = snapshot()
snap["encodings"]["ENC_SOP2"]["identifiers"].remove(0x80000000 | (14 << 23))
self.rejects(registry(), "S_AND_B32: opcode 14 is not an identifier of ENC_SOP2", snap)
def test_rejects_xml_operand_disagreements(self):
cases = (
("missing", lambda ops: ops.pop(2), "S_ADD_U32: XML has no operand SSRC1"),
("width", lambda ops: ops[1].__setitem__(3, 64), "S_ADD_U32: SSRC0 is 64 bits in the XML"),
("direction", lambda ops: ops[0].__setitem__(4, True),
"S_ADD_U32: SDST direction disagrees with the XML"),
("extra", lambda ops: ops.append(["SIMM16", U32, "OPR_SIMM16", 16, True, False, False, True]),
"S_ADD_U32: XML operands ['SIMM16'] are not covered by rule sop2_sgpr"),
)
for label, change, fragment in cases:
with self.subTest(case=label):
snap = snapshot()
change(snap["variants"][("S_ADD_U32", "ENC_SOP2")]["operands"])
self.rejects(registry(), fragment, snap)
def _reorder(value):
"""Reverse the key order of every mapping, keeping list order."""
if isinstance(value, dict):
return {key: _reorder(value[key]) for key in reversed(list(value))}
if isinstance(value, list):
return [_reorder(item) for item in value]
return value
class Render(unittest.TestCase):
def test_two_renders_are_identical(self):
self.assertEqual(gen.render(registry(), snapshot()), gen.render(registry(), snapshot()))
def test_render_ignores_mapping_key_order(self):
reg = registry()
reordered = _reorder(reg)
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
def test_dispatch_table_is_indexed_by_opcode(self):
reg = registry()
reg["form"].reverse()
text = gen.render(reg, snapshot())
body = text.split("const BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
rows = [line.strip() for line in body.splitlines() if line.strip()]
self.assertEqual(len(rows), 128)
declared = {index: row for index, row in enumerate(rows) if row != "None,"}
self.assertEqual(sorted(declared), [0, 2, 4, 14, 34])
self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),")
self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text)
self.assertIn("BY_OPCODE[((word >> 23) & 0x7f) as usize]", text)
def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self):
snap = snapshot()
snap["encodings"]["ENC_SOP2"]["identifiers"].append(0x40000000)
with self.assertRaisesRegex(ValueError, "do not split into fixed bits and OP"):
gen.render(registry(), snap)
def test_real_registry_renders_the_committed_file(self):
text = gen.render(gen.load_registry(), gen.load_snapshot())
self.assertEqual(text, gen.RUST.read_text(encoding="utf-8"))
class CommandLine(unittest.TestCase):
def run_cli(self, *arguments):
return subprocess.run(
[sys.executable, str(SCRIPT), *map(str, arguments)],
capture_output=True, text=True, check=False,
)
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def test_check_passes_on_the_committed_file(self):
result = self.run_cli("--check")
self.assertEqual(result.returncode, 0, result.stderr)
def test_check_passes_on_a_fresh_file_and_fails_on_a_stale_one(self):
output = self.dir / "semantics_gen.rs"
result = self.run_cli("generate", "--output", output)
self.assertEqual(result.returncode, 0, result.stderr)
fresh = output.read_text(encoding="utf-8")
self.assertEqual(self.run_cli("--check", "--output", output).returncode, 0)
output.write_text(fresh.replace("pub const GENERATED_SCHEMA: u32 = 1;", "pub const GENERATED_SCHEMA: u32 = 2;"))
stale = self.run_cli("--check", "--output", output)
self.assertEqual(stale.returncode, 1)
self.assertIn("is stale", stale.stderr)
# --check never writes.
self.assertNotEqual(output.read_text(encoding="utf-8"), fresh)
def test_check_fails_when_the_generated_file_is_missing(self):
self.assertEqual(self.run_cli("--check", "--output", self.dir / "absent.rs").returncode, 1)
def test_invalid_registry_fails_every_mode_without_writing(self):
bad = self.dir / "rdna2.toml"
text = gen.REGISTRY.read_text(encoding="utf-8")
bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8")
output = self.dir / "out.rs"
for mode in (("validate",), ("generate",), ("--check",)):
result = self.run_cli(*mode, "--registry", bad, "--output", output)
self.assertEqual(result.returncode, 1, mode)
self.assertIn("error: schema 2 is not 1", result.stderr)
self.assertFalse(output.exists())
def test_validate_reports_the_form_count(self):
result = self.run_cli("validate")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
if __name__ == "__main__":
unittest.main()
+27 -4
View File
@@ -10,7 +10,8 @@
//!
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
//! and XOR, VOP1 move
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
//! ASHR (32-bit), VOP1 move
//! (including from an SGPR),
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
@@ -50,7 +51,7 @@ enum CmpSrc {
#[derive(Clone, Copy, Debug)]
enum Insn {
SMov(u8, Src),
/// SOP2 opcode 0-5, 14, 16 or 18.
/// SOP2 opcode 0-5, 14, 16, 18 or an even opcode 20-34.
SAlu(u32, u8, Src, Src),
SCmpEq(Src, Src),
BranchScc0(usize),
@@ -320,6 +321,18 @@ fn scalar_alu(
let (value, carry) = ripple(a, !b, !borrow);
(value, !carry)
}
// RDNA 2 ISA guide 12.1: the shifts use only S1[4:0], taken here as
// the remainder modulo 32, and scale by a power of two in exact
// arithmetic; ASHR is floor division of the signed S0. SCC = D != 0.
30 | 32 | 34 => {
let scale = 1_i64 << (b % 32);
let value = match opcode {
30 => (i64::from(a) * scale).rem_euclid(1 << 32),
32 => i64::from(a) / scale,
_ => i64::from(a as i32).div_euclid(scale).rem_euclid(1 << 32),
} as u32;
(value, value != 0)
}
_ => {
let mut value = 0;
for bit in 0..32 {
@@ -327,7 +340,12 @@ fn scalar_alu(
let set = match opcode {
14 => x && y,
16 => x || y,
_ => x != y,
18 => x != y,
20 => x && !y,
22 => x || !y,
24 => !(x && y),
26 => !(x || y),
_ => x == y,
};
value |= u32::from(set) << bit;
}
@@ -795,7 +813,12 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::SMov(dst, src), len));
}
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0..=5 | 14 | 16 | 18) {
if first >> 30 == 0b10
&& matches!(
(first >> 23) & 0x7f,
0..=5 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
)
{
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(fail("unsupported SOP2 destination"));
+24 -1
View File
@@ -768,6 +768,9 @@ mod review {
}
const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin");
const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin");
// Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode.
const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8;
// SOP2 opcodes of the supported subset (RDNA 2 XML opcode table).
const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18];
const SCALAR_VALUES: [u32; 10] = [
@@ -869,6 +872,24 @@ mod review {
verify(&nonzero, &input, Some(&[0; 5]));
}
#[test]
fn scalar_logic_fixture_chains_registry_logical_and_shift_forms() {
let input = [0, 1, u32::MAX, SCALAR_LOGIC_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
verify(SCALAR_LOGIC_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_LOGIC_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_ashr_i32 s17, s15, 31"));
// The SCC-zero edge is observable: with a shift count of 30 instead of
// 31, s17 = 0x787ffff8 >> 30 = 1, SCC = 1, and v2 = 0.
let mut nonzero = SCALAR_LOGIC_FIXTURE.to_vec();
let at = nonzero
.windows(4)
.position(|word| word == [0x0f, 0x9f, 0x11, 0x91])
.unwrap();
nonzero[at + 1] = 0x9e;
verify(&nonzero, &input, Some(&[0; 5]));
}
/// The translator's own folding: v2 = D as a constant, and the SCC-zero edge
/// is taken exactly when SCC is clear.
fn assert_translated(code: &[u8], expected: &[u32; 2]) {
@@ -1089,6 +1110,8 @@ mod review {
let input: Vec<u32> = (0..64).map(|lane| lane * 0x0101_0101).collect();
let expected: Vec<_> = input.iter().map(|word| word ^ 0x0000_000e).collect();
assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected);
let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic);
let mut vectors = sop2_vectors();
vectors.extend(sop2_operand_cases());
vectors.extend(signed_immediate_overflows());
@@ -1097,7 +1120,7 @@ mod review {
}
eprintln!(
"{} SOP2 programs matched on native Metal",
vectors.len() + 1
vectors.len() + 2
);
}
+65
View File
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Operand-domain verification for the supported SOP2 and VOPC forms (part of
//! #215, stage E).
//!
//! Every case runs three ways: the expected value written out below from the
//! public AMD "RDNA 2" Instruction Set Architecture Reference Guide, the
//! reference interpreter `xenora_ref`, and the translated MSL on native Metal.
//! The expected values come only from `oracle`, which imports nothing from the
//! ISA crate, the decoder, the shader compiler or the semantic registry, so a
//! mistake there cannot also produce the expectation.
#[path = "operand_domains/harness.rs"]
mod harness;
#[path = "operand_domains/oracle.rs"]
mod oracle;
#[path = "operand_domains/sop2.rs"]
mod sop2;
#[path = "operand_domains/vopc.rs"]
mod vopc;
use harness::{Case, Rejection};
fn cases() -> Vec<Case> {
let mut all = sop2::cases();
all.extend(vopc::cases());
all
}
fn rejections() -> Vec<Rejection> {
let mut all = sop2::rejections();
all.extend(vopc::rejections());
all
}
#[test]
fn operand_domains_match_the_guide_on_the_reference() {
let cases = cases();
harness::assert_counts(&cases, sop2::COUNTS.iter().chain(vopc::COUNTS));
harness::check_reference(&cases).assert_none("reference disagrees with the guide");
eprintln!("operand_domains: {} reference cases", cases.len());
harness::print_counts(&cases);
}
#[test]
fn unsupported_and_truncated_operands_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), sop2::REJECTIONS + vopc::REJECTIONS);
harness::check_rejected(&rejections).assert_none("not rejected as the guide requires");
eprintln!("operand_domains: {} rejections", rejections.len());
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn operand_domains_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"operand_domains: {} native Metal cases ({programs} distinct programs)",
cases.len()
);
}
@@ -0,0 +1,203 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Running a case on the reference and on Metal. The helpers mirror the ones in
//! `known_answers.rs` (copied, not shared, so that file stays untouched).
use std::collections::{BTreeMap, BTreeSet, HashMap};
use xenora_shader::{Architecture, CompileError, ENTRY_POINT, compile};
/// One program, its lane input and the guide's expected lane output.
pub struct Case {
pub form: &'static str,
pub family: &'static str,
pub label: String,
pub code: Vec<u8>,
pub input: Vec<u32>,
pub expected: Vec<u32>,
}
/// A program every implementation must refuse, at byte `offset`: as truncated
/// when `truncated`, else as outside the supported subset.
pub struct Rejection {
pub family: &'static str,
pub truncated: bool,
pub label: String,
pub code: Vec<u8>,
pub offset: usize,
}
pub fn words(code: &[u32]) -> Vec<u8> {
code.iter().copied().flat_map(u32::to_le_bytes).collect()
}
/// The cases that failed, grouped by family: the count and the first message.
#[derive(Default)]
pub struct Failures(BTreeMap<&'static str, (usize, String)>);
impl Failures {
fn record(&mut self, family: &'static str, message: String) {
let entry = self.0.entry(family).or_insert((0, message));
entry.0 += 1;
}
/// Panics with one line per failing family.
pub fn assert_none(&self, what: &str) {
let lines: Vec<String> = self
.0
.iter()
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
.collect();
assert!(lines.is_empty(), "{what}:\n{}", lines.join("\n"));
}
}
pub fn check_reference(cases: &[Case]) -> Failures {
let mut failures = Failures::default();
for case in cases {
let compiled = compile(Architecture::Gfx1030, &case.code);
let reference = xenora_ref::execute(&case.code, &case.input);
if compiled.is_err() {
failures.record(case.family, format!("{}: {compiled:?}", case.label));
} else if reference.as_deref().ok() != Some(case.expected.as_slice()) {
let expected = &case.expected;
let message = format!("{}: {reference:?}, expected {expected:?}", case.label);
failures.record(case.family, message);
}
}
failures
}
pub fn check_rejected(rejections: &[Rejection]) -> Failures {
let mut failures = Failures::default();
for rejection in rejections {
if let Err(message) = rejected_at(rejection) {
failures.record(rejection.family, format!("{}: {message}", rejection.label));
}
}
failures
}
fn rejected_at(rejection: &Rejection) -> Result<(), String> {
let (compiler, compiler_truncated) = match compile(Architecture::Gfx1030, &rejection.code) {
Ok(_) => return Err("the compiler accepted it".into()),
Err(CompileError::Verify { offset, .. }) => (offset, false),
// The decoder crate is not a dependency of this package, so its
// `DecodeErrorKind::Truncated` variant is recognised by name.
Err(CompileError::Decode(decode)) => (
decode.offset,
format!("{:?}", decode.kind).starts_with("Truncated "),
),
Err(other) => return Err(format!("{other:?}")),
};
let reference = match xenora_ref::execute(&rejection.code, &[0, 1]) {
Ok(_) => return Err("the reference accepted it".into()),
Err(error) => error,
};
// The reference names a missing word "truncated ..."; its fall-through
// "unsupported or truncated ..." does not say which, and counts as unsupported.
let reference_truncated = reference.detail.starts_with("truncated");
if compiler != rejection.offset || reference.offset != rejection.offset {
return Err(format!(
"compiler at {compiler:#x}, reference at {:#x}, expected {:#x}",
reference.offset, rejection.offset
));
}
if compiler_truncated != rejection.truncated || reference_truncated != rejection.truncated {
return Err(format!(
"truncated: compiler {compiler_truncated}, reference {reference_truncated} ({}), \
expected {}",
reference.detail, rejection.truncated
));
}
Ok(())
}
/// Runs every case on Metal. Cases whose translated MSL and input are identical
/// are one program, so each distinct program runs once and its output is
/// compared with every case that shares it. The programs are spread over
/// `THREADS` threads, each with its own device queue, because pipeline
/// compilation dominates the run time. Returns the failures and the number of
/// programs.
pub fn check_metal(cases: &[Case]) -> (Failures, usize) {
const THREADS: usize = 4;
let mut programs = BTreeSet::new();
let mut failures = Failures::default();
let mut keys = Vec::with_capacity(cases.len());
for case in cases {
match compile(Architecture::Gfx1030, &case.code) {
Ok(compiled) => {
let key = (compiled.msl, case.input.clone());
programs.insert(key.clone());
keys.push(Some(key));
}
Err(error) => {
failures.record(case.family, format!("{}: {error:?}", case.label));
keys.push(None);
}
}
}
let work: Vec<&(String, Vec<u32>)> = programs.iter().collect();
let chunk = work.len().div_ceil(THREADS).max(1);
let outputs: HashMap<(String, Vec<u32>), Result<Vec<u32>, String>> = std::thread::scope(|s| {
let handles: Vec<_> = work
.chunks(chunk)
.map(|part| {
s.spawn(move || {
let metal = xenora_metal::NativeCompute::new().unwrap();
part.iter()
.map(|&key| {
let output = metal
.run_words(&key.0, ENTRY_POINT, &key.1)
.map_err(|error| error.to_string());
(key.clone(), output)
})
.collect::<Vec<_>>()
})
})
.collect();
handles
.into_iter()
.flat_map(|handle| handle.join().unwrap())
.collect()
});
for (case, key) in cases.iter().zip(keys) {
let Some(key) = key else { continue };
match &outputs[&key] {
Ok(output) if *output == case.expected => {}
Ok(output) => {
let expected = &case.expected;
let message = format!("{}: {output:?}, expected {expected:?}", case.label);
failures.record(case.family, message);
}
Err(error) => failures.record(case.family, format!("{}: {error}", case.label)),
}
}
(failures, outputs.len())
}
/// The number of cases in each family, which `expected` lists in full.
pub fn assert_counts<'a>(
cases: &[Case],
expected: impl Iterator<Item = &'a (&'static str, usize)>,
) {
let expected: BTreeMap<_, _> = expected.map(|&(family, n)| (family, n)).collect();
assert_eq!(tally(cases, |case| case.family), expected);
}
pub fn print_counts(cases: &[Case]) {
for (name, n) in tally(cases, |case| case.form) {
eprintln!(" form {name}: {n}");
}
for (name, n) in tally(cases, |case| case.family) {
eprintln!(" family {name}: {n}");
}
}
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
let mut counts = BTreeMap::new();
for case in cases {
*counts.entry(key(case)).or_default() += 1;
}
counts
}
@@ -0,0 +1,174 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Expected results transcribed from the AMD "RDNA 2" Instruction Set
//! Architecture Reference Guide (30 November 2020). Section numbers refer to
//! that guide. Nothing here comes from Xenora's own decoder, ISA tables,
//! compiler or semantic registry.
/// The SOP2 forms under test with their opcode numbers (guide 12.1).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Sop2 {
AddU32 = 0,
SubU32 = 1,
AddI32 = 2,
SubI32 = 3,
AddcU32 = 4,
SubbU32 = 5,
AndB32 = 14,
OrB32 = 16,
XorB32 = 18,
}
pub const SOP2_FORMS: [(Sop2, &str); 9] = [
(Sop2::AddU32, "s_add_u32"),
(Sop2::SubU32, "s_sub_u32"),
(Sop2::AddI32, "s_add_i32"),
(Sop2::SubI32, "s_sub_i32"),
(Sop2::AddcU32, "s_addc_u32"),
(Sop2::SubbU32, "s_subb_u32"),
(Sop2::AndB32, "s_and_b32"),
(Sop2::OrB32, "s_or_b32"),
(Sop2::XorB32, "s_xor_b32"),
];
fn bit31(value: u32) -> bool {
value >> 31 == 1
}
/// D and SCC as guide 12.1 writes them; `scc` is the SCC value before the
/// instruction. The `>= 0x100000000ULL` tests are evaluated in 64 bits, as the
/// ULL constant says.
pub fn sop2(op: Sop2, s0: u32, s1: u32, scc: bool) -> (u32, bool) {
let (a, b, c) = (u64::from(s0), u64::from(s1), u64::from(scc));
match op {
// D.u32 = S0.u32 + S1.u32; SCC = S0.u32 + S1.u32 >= 0x100000000ULL.
Sop2::AddU32 => (s0.wrapping_add(s1), a + b >= 0x1_0000_0000),
// D.u = S0.u - S1.u; SCC = (S1.u > S0.u).
Sop2::SubU32 => (s0.wrapping_sub(s1), s1 > s0),
// D.i = S0.i + S1.i; SCC = (S0.u[31] == S1.u[31] && S0.u[31] != D.u[31]).
Sop2::AddI32 => {
let d = s0.wrapping_add(s1);
(d, bit31(s0) == bit31(s1) && bit31(s0) != bit31(d))
}
// D.i = S0.i - S1.i; SCC = (S0.u[31] != S1.u[31] && S0.u[31] != D.u[31]).
Sop2::SubI32 => {
let d = s0.wrapping_sub(s1);
(d, bit31(s0) != bit31(s1) && bit31(s0) != bit31(d))
}
// D.u32 = S0.u32 + S1.u32 + SCC; SCC = S0.u32 + S1.u32 + SCC >= 0x100000000ULL.
Sop2::AddcU32 => (
s0.wrapping_add(s1).wrapping_add(u32::from(scc)),
a + b + c >= 0x1_0000_0000,
),
// D.u = S0.u - S1.u - SCC; SCC = (S1.u + SCC > S0.u), "unsigned overflow".
// The guide does not say whether S1.u + SCC wraps at 32 bits. It is read
// here at full width: only then does SCC report the borrow out of the
// subtraction, which the comment names. This decides only S1 = 0xffffffff
// with SCC set; `sop2::cases` keeps those in their own family.
Sop2::SubbU32 => (s0.wrapping_sub(s1).wrapping_sub(u32::from(scc)), b + c > a),
// D = S0 & S1, S0 | S1, S0 ^ S1; SCC = (D != 0).
Sop2::AndB32 => (s0 & s1, s0 & s1 != 0),
Sop2::OrB32 => (s0 | s1, s0 | s1 != 0),
Sop2::XorB32 => (s0 ^ s1, s0 ^ s1 != 0),
}
}
/// Integer inline constants (guide 5.2, scalar source operand table): codes
/// 128-192 are 0..=64 and codes 193-208 are -1..=-16.
pub fn inline_integer(code: u32) -> Option<u32> {
match code {
128..=192 => Some(code - 128),
193..=208 => Some((192_i32 - code as i32) as u32),
_ => None,
}
}
/// Literal constant code: one 32-bit word follows the instruction (guide 5.2).
pub const LITERAL: u32 = 255;
/// The VOPC integer compares (guide 12.9): V_CMP_{LT,EQ,LE,GT,NE,GE}_I32 are
/// opcodes 129-134 and the _U32 forms 193-198.
#[derive(Clone, Copy, Debug)]
pub struct Compare {
pub opcode: u32,
pub name: &'static str,
}
pub const COMPARES: [Compare; 12] = [
Compare {
opcode: 129,
name: "v_cmp_lt_i32",
},
Compare {
opcode: 130,
name: "v_cmp_eq_i32",
},
Compare {
opcode: 131,
name: "v_cmp_le_i32",
},
Compare {
opcode: 132,
name: "v_cmp_gt_i32",
},
Compare {
opcode: 133,
name: "v_cmp_ne_i32",
},
Compare {
opcode: 134,
name: "v_cmp_ge_i32",
},
Compare {
opcode: 193,
name: "v_cmp_lt_u32",
},
Compare {
opcode: 194,
name: "v_cmp_eq_u32",
},
Compare {
opcode: 195,
name: "v_cmp_le_u32",
},
Compare {
opcode: 196,
name: "v_cmp_gt_u32",
},
Compare {
opcode: 197,
name: "v_cmp_ne_u32",
},
Compare {
opcode: 198,
name: "v_cmp_ge_u32",
},
];
/// "D[threadId] = (S0 < S1)" and so on (guide 12.9), with I32 operands read as
/// two's complement and U32 operands as unsigned (chapter 12 suffix rules).
pub fn compare(form: Compare, s0: u32, s1: u32) -> bool {
let signed = form.name.ends_with("_i32");
let order = if signed {
(s0 as i32).cmp(&(s1 as i32))
} else {
s0.cmp(&s1)
};
match &form.name[6..8] {
"lt" => order.is_lt(),
"eq" => order.is_eq(),
"le" => order.is_le(),
"gt" => order.is_gt(),
"ne" => order.is_ne(),
"ge" => order.is_ge(),
other => unreachable!("{other}"),
}
}
/// VCC for one Wave32 wave (guide 3.9): "VCC[n] = EXEC[n] & (test passed for
/// thread[n])", and "VCC is fully written", so inactive lanes read 0.
pub fn vcc(exec: u32, passed: impl Fn(usize) -> bool) -> u32 {
(0..32)
.filter(|&lane| exec >> lane & 1 == 1 && passed(lane))
.fold(0, |mask, lane| mask | 1 << lane)
}
@@ -0,0 +1,302 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! SOP2 programs: the operands start in SGPRs (or as inline or literal
//! sources), SCC is set or cleared first, and the result reaches the output as
//! v2 = D, XORed with the lane input only when SCC is set afterwards. With the
//! lane input [0, 0xffffffff] the output is [D, D] or [D, !D].
use super::harness::{Case, Rejection, words};
use super::oracle::{self, LITERAL, SOP2_FORMS, Sop2, sop2 as expect};
/// Boundary operands: zero, one, signed max/min and min + 1, unsigned max and
/// max - 1, and an ordinary pattern.
const VALUES: [u32; 8] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
u32::MAX,
0x1234_5678,
];
const LITERALS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1234_5678];
/// 64-bit operands for add/addc and sub/subb chains.
const WIDE: [u64; 6] = [
0,
1,
0xffff_ffff,
0x1_0000_0000,
0x8000_0000_0000_0000,
u64::MAX,
];
const INPUT: [u32; 2] = [0, u32::MAX];
pub const COUNTS: &[(&str, usize)] = &[
("sop2 domain", 9 * 8 * 8 * 2 - 8),
("sop2 subb full-width borrow", 8),
("sop2 carry chain", 2 * 6 * 6 * 2 * 2),
("sop2 aliasing", 9 * 5 * 2),
("sop2 inline integer", 9 * 81 * 2),
("sop2 literal", 9 * 6 * 2 * 2),
("sop2 max register", 9 * 4),
];
/// Two literals, 21 special destinations, 9 float inline codes in two slots,
/// and a missing literal word in two slots, for each of the 9 forms.
pub const REJECTIONS: usize = 9 * (1 + 21 + 9 * 2 + 2);
/// The SOP2 word's offset: load 8, wait 4, two literal moves 8 each, s_cmp 4.
const ALU_OFFSET: usize = 0x20;
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
/// (guide 13.1.1).
pub fn sop2(op: Sop2, dst: u32, src0: u32, src1: u32) -> u32 {
0x8000_0000 | (op as u32) << 23 | dst << 16 | src1 << 8 | src0
}
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
fn mov(reg: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | reg << 16, value]
}
/// The program around `alu`: `init` sets SGPRs, SCC = `scc`, then `alu`, then
/// v2 = s<result>, XORed with v1 when SCC is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend(mov(reg, value));
}
// s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it.
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn lanes((d, scc): (u32, bool)) -> Vec<u32> {
vec![d, if scc { !d } else { d }]
}
fn case(
form: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
Case {
form,
family,
label: format!("{form} {label}"),
code,
input: INPUT.to_vec(),
expected: lanes(out),
}
}
pub fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in SOP2_FORMS {
let alu = [sop2(op, 10, 8, 9)];
for a in VALUES {
for b in VALUES {
for scc in [false, true] {
let family = if op == Sop2::SubbU32 && b == u32::MAX && scc {
"sop2 subb full-width borrow"
} else {
"sop2 domain"
};
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
cases.push(case(
name,
family,
format!("{a:#x}, {b:#x}, scc {scc}"),
code,
expect(op, a, b, scc),
));
}
}
}
// dst/src aliasing, SCC set: (dst, src0, src1) with s8 = a, s9 = b.
for (a, b) in [(0xffff_fff0, 0x11), (0x8000_0000, 0x8000_0000)] {
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
let pick = |reg| if reg == 8 { a } else { b };
let code = program(&[(8, a), (9, b)], true, &[sop2(op, dst, src0, src1)], dst);
let out = expect(op, pick(src0), pick(src1), true);
cases.push(case(
name,
"sop2 aliasing",
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})"),
code,
out,
));
}
}
// Every integer inline constant in each source slot, s8 = 0xfffffff0, SCC set.
let a = 0xffff_fff0;
for code_point in (128..=208).filter_map(|c| oracle::inline_integer(c).map(|v| (c, v))) {
let (selector, value) = code_point;
for slot in 0..2 {
let (alu, out) = if slot == 0 {
(sop2(op, 10, selector, 8), expect(op, value, a, true))
} else {
(sop2(op, 10, 8, selector), expect(op, a, value, true))
};
let code = program(&[(8, a), (9, 0)], true, &[alu], 10);
cases.push(case(
name,
"sop2 inline integer",
format!("inline {selector} ({value:#x}) slot {slot}"),
code,
out,
));
}
}
// A literal word in each source slot, with SCC clear.
for a in [1, 0x8000_0000] {
for literal in LITERALS {
for slot in 0..2 {
let (alu, out) = if slot == 0 {
(sop2(op, 10, LITERAL, 8), expect(op, literal, a, false))
} else {
(sop2(op, 10, 8, LITERAL), expect(op, a, literal, false))
};
let code = program(&[(8, a), (9, 0)], false, &[alu, literal], 10);
cases.push(case(
name,
"sop2 literal",
format!("literal {literal:#x} slot {slot}, s8 {a:#x}"),
code,
out,
));
}
}
}
// s105, the highest SGPR a SOP2 operand may name (guide 5.2), as
// destination and source; s105 = a, s8 = s9 = b, SCC set.
let (a, b) = (0x8000_0001, u32::MAX);
for (dst, src0, src1) in [(105, 105, 9), (105, 8, 105), (105, 105, 105), (8, 105, 9)] {
let pick = |reg| if reg == 105 { a } else { b };
let code = program(
&[(105, a), (8, b), (9, b)],
true,
&[sop2(op, dst, src0, src1)],
dst,
);
let out = expect(op, pick(src0), pick(src1), true);
cases.push(case(
name,
"sop2 max register",
format!("s{dst} = s{src0}, s{src1}"),
code,
out,
));
}
}
cases.extend(chains());
cases
}
/// 64-bit add and subtract built from the u32 forms: low word with
/// s_add_u32/s_sub_u32, high word with s_addc_u32/s_subb_u32 consuming its
/// SCC. SCC is preset both ways first to show the low form overwrites it. Each
/// chain runs twice, outputting the low word and then the high word, both with
/// the final SCC. The expected words and SCC follow the guide; they are also
/// checked against 64-bit arithmetic here.
fn chains() -> Vec<Case> {
let mut cases = Vec::new();
for (low, high, name) in [
(Sop2::AddU32, Sop2::AddcU32, "s_addc_u32"),
(Sop2::SubU32, Sop2::SubbU32, "s_subb_u32"),
] {
for x in WIDE {
for y in WIDE {
for preset in [false, true] {
let (xl, xh, yl, yh) = (x as u32, (x >> 32) as u32, y as u32, (y >> 32) as u32);
let (d_low, carry) = expect(low, xl, yl, preset);
let (d_high, scc) = expect(high, xh, yh, carry);
let exact = if low == Sop2::AddU32 {
(x.wrapping_add(y), x.checked_add(y).is_none())
} else {
(x.wrapping_sub(y), y > x)
};
let joined = u64::from(d_high) << 32 | u64::from(d_low);
assert_eq!((joined, scc), exact, "{x:#x} {y:#x}");
let alu = [sop2(low, 12, 8, 9), sop2(high, 13, 10, 11)];
let init = [(8, xl), (9, yl), (10, xh), (11, yh)];
for (word, d) in [("low", d_low), ("high", d_high)] {
let result = if word == "low" { 12 } else { 13 };
cases.push(case(
name,
"sop2 carry chain",
format!("{x:#x}, {y:#x}, preset {preset}, {word} word"),
program(&init, preset, &alu, result),
(d, scc),
));
}
}
}
}
}
cases
}
pub fn rejections() -> Vec<Rejection> {
let mut rejections = Vec::new();
let reject = |family, label: String, alu: &[u32]| Rejection {
family,
truncated: false,
label,
code: program(&[(8, 1), (9, 2)], false, alu, 10),
offset: ALU_OFFSET,
};
for (op, name) in SOP2_FORMS {
// Both sources select the literal. The guide allows at most one literal
// constant per instruction; whether two selectors may share one word is
// not stated, and Xenora's subset rejects it.
rejections.push(reject(
"sop2 two literals",
format!("{name} two literals"),
&[sop2(op, 10, LITERAL, LITERAL), 3, 3],
));
// VCC_LO, VCC_HI, TTMP0-15, M0, EXEC_LO, EXEC_HI as destination. The
// guide lists these as scalar destinations; Xenora's SOP2 subset writes
// only s0-s105, so these are rejections of the subset, not of the guide.
for dst in (106..=123).chain([124, 126, 127]) {
rejections.push(reject(
"sop2 special destination",
format!("{name} dst {dst}"),
&[sop2(op, dst, 8, 9)],
));
}
// Float inline constants 0.5 .. -4.0 and 1/(2*pi) (codes 240-248). The
// guide defines them for every source; Xenora's subset rejects them for
// these integer forms.
for selector in 240..=248 {
rejections.push(reject(
"sop2 float inline",
format!("{name} float inline {selector} src0"),
&[sop2(op, 10, selector, 8)],
));
rejections.push(reject(
"sop2 float inline",
format!("{name} float inline {selector} src1"),
&[sop2(op, 10, 8, selector)],
));
}
// The stream ends where the literal word should be.
for (slot, alu) in [(0, sop2(op, 10, LITERAL, 8)), (1, sop2(op, 10, 8, LITERAL))] {
let mut code = program(&[(8, 1), (9, 2)], false, &[], 10);
code.truncate(ALU_OFFSET);
code.extend(alu.to_le_bytes());
rejections.push(Rejection {
family: "sop2 missing literal",
truncated: true,
label: format!("{name} missing literal slot {slot}"),
code,
offset: ALU_OFFSET,
});
}
}
rejections
}
@@ -0,0 +1,280 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! VOPC programs on one Wave32 wave: v1 = lane input, v3 (or v255) = a literal
//! `b`, an optional EXEC mask around the compare, then every lane outputs
//! VCC_LO. The 32 lane inputs are distinct, so a mask bit landing in the wrong
//! lane changes the output.
//!
//! Not covered: whether a compare also writes EXEC. The supported subset has
//! no instruction that reads EXEC back, so the EXEC cases restore it before
//! the output move.
use super::harness::{Case, Rejection, words};
use super::oracle::{COMPARES, Compare, LITERAL, compare, inline_integer, vcc};
/// Boundary operands, also the first ten lane inputs: zero, one, signed max - 1
/// and max, signed min and min + 1, -16, unsigned max - 1 and max, and a
/// pattern.
const VALUES: [u32; 10] = [
0,
1,
0x7fff_fffe,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fff0,
0xffff_fffe,
u32::MAX,
0x0f0f_0f0f,
];
/// The other 22 lane inputs: more values near the boundaries and patterns.
const MORE_LANES: [u32; 22] = [
2,
3,
15,
16,
63,
64,
65,
0x7fff_fffd,
0x8000_0002,
0xffff_fffd,
0xffff_ffef,
0xffff_fff1,
0x4000_0000,
0xc000_0000,
0x0000_ffff,
0xffff_0000,
0x1234_5678,
0x8765_4321,
0x00ff_00ff,
0xff00_ff00,
0x5555_5555,
0xaaaa_aaaa,
];
const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX];
const EXEC_MASKS: [u32; 5] = [0, 0x5555_5555, 0xaaaa_aaaa, 0x8000_0001, 0x0000_ffff];
pub const COUNTS: &[(&str, usize)] = &[
("vopc domain", 12 * 10 * 2),
("vopc aliasing", 12),
("vopc inline integer", 12 * 81),
("vopc literal", 12 * 5),
("vopc sgpr source", 12 * 2 * 2),
("vopc max register", 12 * 2),
("vopc exec mask", 12 * 5),
("vopc vccz", 12 * 11),
];
/// A missing literal word and 9 float inline codes (defined by the guide, outside
/// Xenora's subset for integer compares), for each of the 12 forms.
pub const REJECTIONS: usize = 12 * (1 + 9);
/// The compare's offset: load 8, wait 4, v_mov with literal 8.
const COMPARE_OFFSET: usize = 0x14;
/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8
/// (guide 13.3.3); SRC0 256 + n is VGPR n.
fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 {
0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0
}
const fn vgpr(n: u32) -> u32 {
256 + n
}
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
fn vmov(reg: u32, value: u32) -> [u32; 2] {
[0x7e00_02ff | reg << 17, value]
}
/// `s_mov_b32 vcc_lo, 0xffffffff`, so a compare that leaves bits untouched
/// shows up.
const SEED_VCC: [u32; 2] = [0xbeea_03ff, u32::MAX];
/// `s_mov_b32 exec_lo, literal` and `s_mov_b32 exec_lo, -1`.
const SET_EXEC: u32 = 0xbefe_03ff;
const FULL_EXEC: u32 = 0xbefe_03c1;
/// After v2 = VCC_LO: `s_cbranch_vccz` over `v_xor_b32 v2, v1, v2`.
const VCCZ_TAIL: [u32; 2] = [0xbf86_0001, 0x3a04_0501];
/// Load v1, v<breg> = b, then `before`, the compare words, `after`, and every
/// lane outputs VCC_LO.
fn program(breg: u32, b: u32, before: &[u32], compare: &[u32], after: &[u32]) -> Vec<u8> {
program_with_tail(breg, b, before, compare, after, &[])
}
/// As `program`, with `tail` between the output move and the store.
fn program_with_tail(
breg: u32,
b: u32,
before: &[u32],
compare: &[u32],
after: &[u32],
tail: &[u32],
) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
code.extend(vmov(breg, b));
code.extend(before);
code.extend(compare);
code.extend(after);
code.push(0x7e04_026a);
code.extend(tail);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn lanes() -> Vec<u32> {
VALUES.iter().chain(&MORE_LANES).copied().collect()
}
fn case(form: Compare, family: &'static str, label: String, code: Vec<u8>, mask: u32) -> Case {
Case {
form: form.name,
family,
label: format!("{} {label}", form.name),
code,
input: lanes(),
expected: vec![mask; 32],
}
}
pub fn cases() -> Vec<Case> {
let input = lanes();
let all = u32::MAX;
let mut cases = Vec::new();
for form in COMPARES {
let op = form.opcode;
for b in VALUES {
let code = program(3, b, &[], &[vopc(op, vgpr(1), 3)], &[]);
let mask = vcc(all, |n| compare(form, input[n], b));
cases.push(case(form, "vopc domain", format!("v1, {b:#x}"), code, mask));
let code = program(3, b, &[], &[vopc(op, vgpr(3), 1)], &[]);
let mask = vcc(all, |n| compare(form, b, input[n]));
cases.push(case(form, "vopc domain", format!("{b:#x}, v1"), code, mask));
}
let code = program(3, 0, &[], &[vopc(op, vgpr(1), 1)], &[]);
let mask = vcc(all, |n| compare(form, input[n], input[n]));
cases.push(case(form, "vopc aliasing", "v1, v1".into(), code, mask));
for selector in 128..=208 {
let value = inline_integer(selector).unwrap();
let code = program(3, 0, &[], &[vopc(op, selector, 1)], &[]);
let mask = vcc(all, |n| compare(form, value, input[n]));
cases.push(case(
form,
"vopc inline integer",
format!("inline {selector} ({value:#x})"),
code,
mask,
));
}
for literal in LITERALS {
let code = program(3, 0, &[], &[vopc(op, LITERAL, 1), literal], &[]);
let mask = vcc(all, |n| compare(form, literal, input[n]));
cases.push(case(
form,
"vopc literal",
format!("literal {literal:#x}"),
code,
mask,
));
}
// SGPR source s8 and s105, the highest SGPR (guide 5.2).
for reg in [8, 105] {
for value in [0x8000_0000, 0xffff_fff0] {
let set = [0xbe80_03ff | reg << 16, value];
let code = program(3, 0, &set, &[vopc(op, reg, 1)], &[]);
let mask = vcc(all, |n| compare(form, value, input[n]));
cases.push(case(
form,
"vopc sgpr source",
format!("s{reg} = {value:#x}"),
code,
mask,
));
}
}
// v255, the highest VGPR, in each slot.
let b = 0x8000_0001;
let code = program(255, b, &[], &[vopc(op, vgpr(1), 255)], &[]);
let mask = vcc(all, |n| compare(form, input[n], b));
cases.push(case(
form,
"vopc max register",
"v1, v255".into(),
code,
mask,
));
let code = program(255, b, &[], &[vopc(op, vgpr(255), 1)], &[]);
let mask = vcc(all, |n| compare(form, b, input[n]));
cases.push(case(
form,
"vopc max register",
"v255, v1".into(),
code,
mask,
));
// Partial and empty EXEC around the compare, with VCC_LO = -1 before
// it, so inactive lanes must be cleared ("VCC is fully written");
// EXEC_LO = -1 again before the output move so every lane stores VCC_LO.
let b = 0x8000_0000;
for exec in EXEC_MASKS {
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, exec];
let code = program(3, b, &before, &[vopc(op, vgpr(1), 3)], &[FULL_EXEC]);
let mask = vcc(exec, |n| compare(form, input[n], b));
cases.push(case(
form,
"vopc exec mask",
format!("exec {exec:#x}"),
code,
mask,
));
}
// VCCZ after the compare (guide 3.9: VCCZ is VCC == 0), read with
// s_cbranch_vccz: lanes output VCC_LO when it is zero, else input ^ VCC_LO.
let vccz = |mask: u32| -> Vec<u32> {
if mask == 0 {
vec![0; 32]
} else {
input.iter().map(|lane| lane ^ mask).collect()
}
};
for b in VALUES {
let code = program_with_tail(3, b, &[], &[vopc(op, vgpr(1), 3)], &[], &VCCZ_TAIL);
let mask = vcc(all, |n| compare(form, input[n], b));
let mut case = case(form, "vopc vccz", format!("v1, {b:#x}"), code, mask);
case.expected = vccz(mask);
cases.push(case);
}
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, 0];
let compare_words = [vopc(op, vgpr(1), 3)];
let code = program_with_tail(3, 0, &before, &compare_words, &[FULL_EXEC], &VCCZ_TAIL);
let mut case = case(form, "vopc vccz", "exec 0".into(), code, 0);
case.expected = vccz(0);
cases.push(case);
}
cases
}
pub fn rejections() -> Vec<Rejection> {
let mut rejections = Vec::new();
for form in COMPARES {
let mut code = program(3, 0, &[], &[], &[]);
code.truncate(COMPARE_OFFSET);
code.extend(vopc(form.opcode, LITERAL, 1).to_le_bytes());
rejections.push(Rejection {
family: "vopc missing literal",
truncated: true,
label: format!("{} missing literal", form.name),
code,
offset: COMPARE_OFFSET,
});
for selector in 240..=248 {
rejections.push(Rejection {
family: "vopc float inline",
truncated: false,
label: format!("{} float inline {selector}", form.name),
code: program(3, 0, &[], &[vopc(form.opcode, selector, 1)], &[]),
offset: COMPARE_OFFSET,
});
}
}
rejections
}
+328
View File
@@ -0,0 +1,328 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for the eight SOP2 forms added in #215 stage C:
//! `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`,
//! `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions" for
//! D and SCC of each form, section 5.3 for the SCC rule of bit/logical
//! operations, and the scalar operand table (section 3) for inline integer
//! constants. Nothing here comes from the ISA crate, the semantic registry, the
//! decoder or the shader compiler. Every case runs on the reference interpreter
//! `xenora_ref` and on the second interpreter `independent_ref`; the ignored
//! test also runs the translated MSL on native Metal.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use std::collections::BTreeMap;
use harness::{Case, words};
/// The eight stage C forms with their ENC_SOP2 opcodes (guide 12.1).
#[derive(Clone, Copy, Debug)]
enum Form {
Andn2 = 20,
Orn2 = 22,
Nand = 24,
Nor = 26,
Xnor = 28,
Lshl = 30,
Lshr = 32,
Ashr = 34,
}
const FORMS: [(Form, &str); 8] = [
(Form::Andn2, "s_andn2_b32"),
(Form::Orn2, "s_orn2_b32"),
(Form::Nand, "s_nand_b32"),
(Form::Nor, "s_nor_b32"),
(Form::Xnor, "s_xnor_b32"),
(Form::Lshl, "s_lshl_b32"),
(Form::Lshr, "s_lshr_b32"),
(Form::Ashr, "s_ashr_i32"),
];
/// The guide's D and SCC for `form` with S0 = `s0` and S1 = `s1`. None of
/// these forms reads SCC, so the value of SCC before the instruction is not an
/// input.
fn expect(form: Form, s0: u32, s1: u32) -> (u32, bool) {
let d = match form {
// 20 S_ANDN2_B32: D = S0 & ~S1; SCC = (D != 0).
Form::Andn2 => s0 & !s1,
// 22 S_ORN2_B32: D = S0 | ~S1; SCC = (D != 0).
Form::Orn2 => s0 | !s1,
// 24 S_NAND_B32: D = ~(S0 & S1); SCC = (D != 0).
Form::Nand => !(s0 & s1),
// 26 S_NOR_B32: D = ~(S0 | S1); SCC = (D != 0).
Form::Nor => !(s0 | s1),
// 28 S_XNOR_B32: D = ~(S0 ^ S1); SCC = (D != 0).
Form::Xnor => !(s0 ^ s1),
// 30 S_LSHL_B32: D.u = S0.u << S1.u[4:0]; SCC = (D.u != 0).
Form::Lshl => s0 << (s1 & 0x1f),
// 32 S_LSHR_B32: D.u = S0.u >> S1.u[4:0]; SCC = (D.u != 0).
Form::Lshr => s0 >> (s1 & 0x1f),
// 34 S_ASHR_I32: D.i = signext(S0.i) >> S1.u[4:0]; SCC = (D.i != 0).
// S1 is read as unsigned and only its low five bits count, so its
// sign never matters; the shift replicates S0's sign bit.
Form::Ashr => ((s0 as i32) >> (s1 & 0x1f)) as u32,
};
// Section 5.3: bit/logical operations set SCC = 1 iff the result is not zero.
(d, d != 0)
}
/// Guide section 3 scalar operand table: 128 is 0, 129-192 are 1 to 64 and
/// 193-208 are -1 to -16, as 32-bit words.
fn inline_integer(selector: u32) -> u32 {
match selector {
128..=192 => selector - 128,
193..=208 => (-((selector - 192) as i32)) as u32,
_ => unreachable!("not an integer inline constant"),
}
}
const LITERAL: u32 = 255;
/// Boundary operands and alternating bit patterns.
const VALUES: [u32; 8] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
0xffff_ffff,
0xaaaa_aaaa,
0x5555_5555,
0x1234_5678,
];
/// Shift counts around the five-bit field, and one whose low bits are 1.
const SHIFTS: [u32; 7] = [0, 1, 31, 32, 33, 63, 0xffff_ffe1];
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 5] = [
("stage c domain", 8 * 8 * 8 * 2),
("stage c shift count", 3 * 8 * 7 * 2),
("stage c aliasing", 8 * 2 * 5 * 2),
("stage c inline integer", 8 * 81 * 2 * 2 * 2),
("stage c literal", 8 * 6 * 2 * 2),
];
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7.
fn sop2(form: Form, dst: u32, src0: u32, src1: u32) -> u32 {
0x8000_0000 | (form as u32) << 23 | dst << 16 | src1 << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
/// `scc` with `s_cmp_eq_u32`, run `alu`, then v2 = s<result>, XORed with v1
/// when SCC is set afterwards, and store v2. With the lane input [0, !0] the
/// output is [D, D] when SCC is clear and [D, !D] when it is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend([0xbe80_03ff | reg << 16, value]);
}
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
let (d, scc) = out;
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input: INPUT.to_vec(),
expected: vec![d, if scc { !d } else { d }],
}
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let shift = matches!(form, Form::Lshl | Form::Lshr | Form::Ashr);
for scc in [false, true] {
let alu = [sop2(form, 10, 8, 9)];
let pairs = VALUES
.iter()
.flat_map(|&a| VALUES.map(|b| (a, b, "stage c domain")));
let counts = VALUES
.iter()
.flat_map(|&a| SHIFTS.map(|b| (a, b, "stage c shift count")));
let counts: Vec<_> = if shift { counts.collect() } else { Vec::new() };
for (a, b, family) in pairs.chain(counts) {
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
cases.push(case(name, family, label, code, expect(form, a, b)));
}
// dst/src aliasing with s8 = a, s9 = b.
for (a, b) in [(0xffff_fff0, 0x21), (0x8000_0001, 0x8000_0001)] {
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
let pick = |reg| if reg == 8 { a } else { b };
let code = program(&[(8, a), (9, b)], scc, &[sop2(form, dst, src0, src1)], dst);
let label =
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x}), scc before {scc}");
let out = expect(form, pick(src0), pick(src1));
cases.push(case(name, "stage c aliasing", label, code, out));
}
}
// Every integer inline constant (-16..64) in each source slot. The
// register operand s8 takes a word and its complement, so a wrong
// inline value changes D for at least one of them (as a shift
// count it is 0x40 and 0x21, i.e. counts 0 and 1).
for selector in 128..=208 {
let value = inline_integer(selector);
for (slot, other) in [0, 1].into_iter().flat_map(|slot| {
let others = if slot == 0 && shift {
[0x40, 0x21]
} else {
[0x8000_0f0f, 0x7fff_f0f0]
};
others.map(|other| (slot, other))
}) {
let (alu, out) = if slot == 0 {
(sop2(form, 10, selector, 8), expect(form, value, other))
} else {
(sop2(form, 10, 8, selector), expect(form, other, value))
};
let code = program(&[(8, other)], scc, &[alu], 10);
let label =
format!("inline {value:#x} in src{slot}, s8 {other:#x}, scc before {scc}");
cases.push(case(name, "stage c inline integer", label, code, out));
}
}
// A 32-bit literal dword after the SOP2 word in each source slot.
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0xffff_ffe1] {
for slot in 0..2 {
let other = 0xc000_0003;
let (alu, out) = if slot == 0 {
(
[sop2(form, 10, LITERAL, 8), value],
expect(form, value, other),
)
} else {
(
[sop2(form, 10, 8, LITERAL), value],
expect(form, other, value),
)
};
let code = program(&[(8, other)], scc, &alu, 10);
let label = format!("literal {value:#x} in src{slot}, scc before {scc}");
cases.push(case(name, "stage c literal", label, code, out));
}
}
}
}
cases
}
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
let mut counts = BTreeMap::new();
for case in cases {
*counts.entry(key(case)).or_default() += 1;
}
counts
}
/// Runs `execute` on every case and returns one line per failing family: the
/// number of failures and the first one.
fn failures(
cases: &[Case],
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
) -> Vec<String> {
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
for case in cases {
let output = execute(&case.code, &case.input);
if output.as_deref().ok() != Some(case.expected.as_slice()) {
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
failed.entry(case.family).or_insert((0, first)).0 += 1;
}
}
failed
.into_iter()
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
.collect()
}
fn checked_cases() -> Vec<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn stage_c_forms_match_the_guide_on_the_reference() {
let cases = checked_cases();
let failed = failures(&cases, |code, input| {
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
});
assert!(
failed.is_empty(),
"reference disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("sop2_stage_c: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn stage_c_forms_match_the_guide_on_the_independent_interpreter() {
let cases = checked_cases();
let failed = failures(&cases, independent_ref::execute);
assert!(
failed.is_empty(),
"independent interpreter disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!(
"sop2_stage_c: {} independent-interpreter cases",
cases.len()
);
}
#[test]
fn odd_opcodes_beside_the_stage_c_forms_stay_unsupported() {
// The 64-bit neighbours (opcodes 21-35 odd) read aligned SGPR pairs
// (s[10:11] = s[8:9] op s[12:13], all initialized); neither interpreter
// supports them, so each must refuse the SOP2 word.
for op in (21..=35).step_by(2) {
let alu = [0x8000_0000 | op << 23 | 10 << 16 | 12 << 8 | 8];
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
let code = program(&init, false, &alu, 10);
assert!(
xenora_ref::execute(&code, &INPUT).is_err(),
"reference accepted opcode {op}"
);
assert!(
independent_ref::execute(&code, &INPUT).is_err(),
"independent accepted opcode {op}"
);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn stage_c_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"sop2_stage_c: {} Metal cases in {programs} programs",
cases.len()
);
}